werift 0.26.0 → 0.28.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 (552) hide show
  1. package/README.md +182 -8
  2. package/THIRD_PARTY_LICENSES_LIBWEBRTC.txt +58 -0
  3. package/lib/common/src/binary.d.ts +1 -3
  4. package/lib/common/src/binary.js +8 -6
  5. package/lib/common/src/binary.js.map +1 -1
  6. package/lib/common/src/binaryData.js +2 -1
  7. package/lib/common/src/binaryData.js.map +1 -1
  8. package/lib/common/src/event.d.ts +26 -0
  9. package/lib/common/src/event.js +87 -2
  10. package/lib/common/src/event.js.map +1 -1
  11. package/lib/common/src/log.js +5 -7
  12. package/lib/common/src/log.js.map +1 -1
  13. package/lib/common/src/network.d.ts +6 -1
  14. package/lib/common/src/network.js +8 -2
  15. package/lib/common/src/network.js.map +1 -1
  16. package/lib/common/src/transport.d.ts +12 -5
  17. package/lib/common/src/transport.js +13 -7
  18. package/lib/common/src/transport.js.map +1 -1
  19. package/lib/dtls/src/alert.d.ts +49 -0
  20. package/lib/dtls/src/alert.js +103 -0
  21. package/lib/dtls/src/alert.js.map +1 -0
  22. package/lib/dtls/src/client.js +15 -1
  23. package/lib/dtls/src/client.js.map +1 -1
  24. package/lib/dtls/src/context/cipher.d.ts +1 -1
  25. package/lib/dtls/src/context/cipher.js +6 -3
  26. package/lib/dtls/src/context/cipher.js.map +1 -1
  27. package/lib/dtls/src/context/dtls.d.ts +2 -0
  28. package/lib/dtls/src/context/dtls.js +11 -2
  29. package/lib/dtls/src/context/dtls.js.map +1 -1
  30. package/lib/dtls/src/context/transport.d.ts +17 -1
  31. package/lib/dtls/src/context/transport.js +40 -3
  32. package/lib/dtls/src/context/transport.js.map +1 -1
  33. package/lib/dtls/src/flight/client/flight1.js +2 -1
  34. package/lib/dtls/src/flight/client/flight1.js.map +1 -1
  35. package/lib/dtls/src/flight/client/flight5.js +8 -3
  36. package/lib/dtls/src/flight/client/flight5.js.map +1 -1
  37. package/lib/dtls/src/flight/flight.d.ts +6 -1
  38. package/lib/dtls/src/flight/flight.js +18 -5
  39. package/lib/dtls/src/flight/flight.js.map +1 -1
  40. package/lib/dtls/src/flight/server/flight4.js +4 -2
  41. package/lib/dtls/src/flight/server/flight4.js.map +1 -1
  42. package/lib/dtls/src/flight/server/flight6.js +6 -2
  43. package/lib/dtls/src/flight/server/flight6.js.map +1 -1
  44. package/lib/dtls/src/handshake/const.d.ts +17 -13
  45. package/lib/dtls/src/handshake/const.js +16 -14
  46. package/lib/dtls/src/handshake/const.js.map +1 -1
  47. package/lib/dtls/src/handshake/message/alert.js +4 -2
  48. package/lib/dtls/src/handshake/message/alert.js.map +1 -1
  49. package/lib/dtls/src/handshake/message/certificate.js +2 -1
  50. package/lib/dtls/src/handshake/message/certificate.js.map +1 -1
  51. package/lib/dtls/src/handshake/message/changeCipherSpec.js +2 -1
  52. package/lib/dtls/src/handshake/message/changeCipherSpec.js.map +1 -1
  53. package/lib/dtls/src/handshake/message/client/certificateVerify.js +4 -2
  54. package/lib/dtls/src/handshake/message/client/certificateVerify.js.map +1 -1
  55. package/lib/dtls/src/handshake/message/client/hello.js +14 -7
  56. package/lib/dtls/src/handshake/message/client/hello.js.map +1 -1
  57. package/lib/dtls/src/handshake/message/client/keyExchange.js +2 -1
  58. package/lib/dtls/src/handshake/message/client/keyExchange.js.map +1 -1
  59. package/lib/dtls/src/handshake/message/finished.js +2 -1
  60. package/lib/dtls/src/handshake/message/finished.js.map +1 -1
  61. package/lib/dtls/src/handshake/message/server/certificateRequest.js +6 -3
  62. package/lib/dtls/src/handshake/message/server/certificateRequest.js.map +1 -1
  63. package/lib/dtls/src/handshake/message/server/hello.js +12 -6
  64. package/lib/dtls/src/handshake/message/server/hello.js.map +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 +4 -2
  67. package/lib/dtls/src/handshake/message/server/helloVerifyRequest.js.map +1 -1
  68. package/lib/dtls/src/handshake/message/server/keyExchange.js +16 -8
  69. package/lib/dtls/src/handshake/message/server/keyExchange.js.map +1 -1
  70. package/lib/dtls/src/handshake/random.d.ts +2 -2
  71. package/lib/dtls/src/handshake/random.js +5 -2
  72. package/lib/dtls/src/handshake/random.js.map +1 -1
  73. package/lib/dtls/src/index.d.ts +3 -1
  74. package/lib/dtls/src/index.js +10 -1
  75. package/lib/dtls/src/index.js.map +1 -1
  76. package/lib/dtls/src/record/const.d.ts +52 -33
  77. package/lib/dtls/src/record/const.js +51 -36
  78. package/lib/dtls/src/record/const.js.map +1 -1
  79. package/lib/dtls/src/record/message/fragment.js +12 -6
  80. package/lib/dtls/src/record/message/fragment.js.map +1 -1
  81. package/lib/dtls/src/record/message/header.js +10 -5
  82. package/lib/dtls/src/record/message/header.js.map +1 -1
  83. package/lib/dtls/src/record/message/plaintext.js +4 -2
  84. package/lib/dtls/src/record/message/plaintext.js.map +1 -1
  85. package/lib/dtls/src/record/receive.d.ts +6 -0
  86. package/lib/dtls/src/record/receive.js +50 -19
  87. package/lib/dtls/src/record/receive.js.map +1 -1
  88. package/lib/dtls/src/server.js +19 -1
  89. package/lib/dtls/src/server.js.map +1 -1
  90. package/lib/dtls/src/socket.d.ts +134 -2
  91. package/lib/dtls/src/socket.js +326 -8
  92. package/lib/dtls/src/socket.js.map +1 -1
  93. package/lib/ice/src/candidate.d.ts +1 -1
  94. package/lib/ice/src/candidate.js +24 -12
  95. package/lib/ice/src/candidate.js.map +1 -1
  96. package/lib/ice/src/candidateError.d.ts +155 -0
  97. package/lib/ice/src/candidateError.js +246 -0
  98. package/lib/ice/src/candidateError.js.map +1 -0
  99. package/lib/ice/src/candidateGatherer.d.ts +127 -0
  100. package/lib/ice/src/candidateGatherer.js +745 -0
  101. package/lib/ice/src/candidateGatherer.js.map +1 -0
  102. package/lib/ice/src/consent.d.ts +49 -0
  103. package/lib/ice/src/consent.js +258 -0
  104. package/lib/ice/src/consent.js.map +1 -0
  105. package/lib/ice/src/dns/lookup.d.ts +10 -1
  106. package/lib/ice/src/dns/lookup.js +42 -7
  107. package/lib/ice/src/dns/lookup.js.map +1 -1
  108. package/lib/ice/src/exceptions.d.ts +21 -5
  109. package/lib/ice/src/exceptions.js +58 -13
  110. package/lib/ice/src/exceptions.js.map +1 -1
  111. package/lib/ice/src/ice.d.ts +254 -58
  112. package/lib/ice/src/ice.js +979 -945
  113. package/lib/ice/src/ice.js.map +1 -1
  114. package/lib/ice/src/iceBase.d.ts +328 -14
  115. package/lib/ice/src/iceBase.js +254 -38
  116. package/lib/ice/src/iceBase.js.map +1 -1
  117. package/lib/ice/src/index.d.ts +1 -0
  118. package/lib/ice/src/index.js +1 -0
  119. package/lib/ice/src/index.js.map +1 -1
  120. package/lib/ice/src/internal/checkMessages.d.ts +41 -0
  121. package/lib/ice/src/internal/checkMessages.js +63 -0
  122. package/lib/ice/src/internal/checkMessages.js.map +1 -0
  123. package/lib/ice/src/internal/defaultRoute.d.ts +20 -0
  124. package/lib/ice/src/internal/defaultRoute.js +134 -0
  125. package/lib/ice/src/internal/defaultRoute.js.map +1 -0
  126. package/lib/ice/src/internal/hostInterfaces.d.ts +17 -0
  127. package/lib/ice/src/internal/hostInterfaces.js +77 -0
  128. package/lib/ice/src/internal/hostInterfaces.js.map +1 -0
  129. package/lib/ice/src/internal/hostPreference.d.ts +24 -0
  130. package/lib/ice/src/internal/hostPreference.js +38 -0
  131. package/lib/ice/src/internal/hostPreference.js.map +1 -0
  132. package/lib/ice/src/internal/resolveHostAddresses.d.ts +56 -8
  133. package/lib/ice/src/internal/resolveHostAddresses.js +127 -24
  134. package/lib/ice/src/internal/resolveHostAddresses.js.map +1 -1
  135. package/lib/ice/src/internal/selectAddresses.d.ts +27 -0
  136. package/lib/ice/src/internal/selectAddresses.js +37 -18
  137. package/lib/ice/src/internal/selectAddresses.js.map +1 -1
  138. package/lib/ice/src/nomination/regularNomination.d.ts +200 -0
  139. package/lib/ice/src/nomination/regularNomination.js +311 -0
  140. package/lib/ice/src/nomination/regularNomination.js.map +1 -0
  141. package/lib/ice/src/nomination/selectionReplacement.d.ts +138 -0
  142. package/lib/ice/src/nomination/selectionReplacement.js +371 -0
  143. package/lib/ice/src/nomination/selectionReplacement.js.map +1 -0
  144. package/lib/ice/src/provisional.d.ts +139 -0
  145. package/lib/ice/src/provisional.js +468 -0
  146. package/lib/ice/src/provisional.js.map +1 -0
  147. package/lib/ice/src/stun/protocol.d.ts +9 -2
  148. package/lib/ice/src/stun/protocol.js +16 -17
  149. package/lib/ice/src/stun/protocol.js.map +1 -1
  150. package/lib/ice/src/stun/tcpProtocol.d.ts +1 -1
  151. package/lib/ice/src/stun/tcpProtocol.js +7 -7
  152. package/lib/ice/src/stun/tcpProtocol.js.map +1 -1
  153. package/lib/ice/src/stun/transaction.d.ts +30 -1
  154. package/lib/ice/src/stun/transaction.js +90 -19
  155. package/lib/ice/src/stun/transaction.js.map +1 -1
  156. package/lib/ice/src/turn/credential.d.ts +49 -0
  157. package/lib/ice/src/turn/credential.js +78 -0
  158. package/lib/ice/src/turn/credential.js.map +1 -0
  159. package/lib/ice/src/turn/protocol.d.ts +31 -10
  160. package/lib/ice/src/turn/protocol.js +127 -51
  161. package/lib/ice/src/turn/protocol.js.map +1 -1
  162. package/lib/ice/src/types/model.d.ts +16 -5
  163. package/lib/ice/src/types/model.js.map +1 -1
  164. package/lib/ice-server/src/stun/attributes.d.ts +2 -0
  165. package/lib/ice-server/src/stun/attributes.js +11 -1
  166. package/lib/ice-server/src/stun/attributes.js.map +1 -1
  167. package/lib/ice-server/src/stun/const.d.ts +44 -17
  168. package/lib/ice-server/src/stun/const.js +31 -19
  169. package/lib/ice-server/src/stun/const.js.map +1 -1
  170. package/lib/ice-server/src/stun/message.d.ts +29 -4
  171. package/lib/ice-server/src/stun/message.js +115 -24
  172. package/lib/ice-server/src/stun/message.js.map +1 -1
  173. package/lib/index.mjs +35121 -22337
  174. package/lib/nonstandard/index.mjs +3169 -1399
  175. package/lib/polyfill/dom.mjs +24650 -12365
  176. package/lib/polyfill/index.mjs +24650 -12365
  177. package/lib/rtp/src/codec/assertPayload.d.ts +4 -0
  178. package/lib/rtp/src/codec/assertPayload.js +12 -0
  179. package/lib/rtp/src/codec/assertPayload.js.map +1 -0
  180. package/lib/rtp/src/codec/av1.js +2 -0
  181. package/lib/rtp/src/codec/av1.js.map +1 -1
  182. package/lib/rtp/src/codec/h264.js +35 -43
  183. package/lib/rtp/src/codec/h264.js.map +1 -1
  184. package/lib/rtp/src/codec/vp8.js +11 -5
  185. package/lib/rtp/src/codec/vp8.js.map +1 -1
  186. package/lib/rtp/src/codec/vp9.js +12 -0
  187. package/lib/rtp/src/codec/vp9.js.map +1 -1
  188. package/lib/rtp/src/extra/container/mp4/container.js +2 -1
  189. package/lib/rtp/src/extra/container/mp4/container.js.map +1 -1
  190. package/lib/rtp/src/extra/container/mp4/exp-golomb.js +2 -1
  191. package/lib/rtp/src/extra/container/mp4/exp-golomb.js.map +1 -1
  192. package/lib/rtp/src/extra/container/mp4/h264.d.ts +21 -17
  193. package/lib/rtp/src/extra/container/mp4/h264.js +26 -24
  194. package/lib/rtp/src/extra/container/mp4/h264.js.map +1 -1
  195. package/lib/rtp/src/extra/container/ogg/index.d.ts +1 -0
  196. package/lib/rtp/src/extra/container/ogg/index.js +1 -0
  197. package/lib/rtp/src/extra/container/ogg/index.js.map +1 -1
  198. package/lib/rtp/src/extra/container/ogg/writer.d.ts +90 -0
  199. package/lib/rtp/src/extra/container/ogg/writer.js +300 -0
  200. package/lib/rtp/src/extra/container/ogg/writer.js.map +1 -0
  201. package/lib/rtp/src/extra/container/webm/ebml/ebml.js +6 -3
  202. package/lib/rtp/src/extra/container/webm/ebml/ebml.js.map +1 -1
  203. package/lib/rtp/src/extra/processor/depacketizer.d.ts +5 -0
  204. package/lib/rtp/src/extra/processor/depacketizer.js +28 -2
  205. package/lib/rtp/src/extra/processor/depacketizer.js.map +1 -1
  206. package/lib/rtp/src/extra/processor/dtx.js +4 -2
  207. package/lib/rtp/src/extra/processor/dtx.js.map +1 -1
  208. package/lib/rtp/src/extra/processor/index.d.ts +2 -0
  209. package/lib/rtp/src/extra/processor/index.js +2 -0
  210. package/lib/rtp/src/extra/processor/index.js.map +1 -1
  211. package/lib/rtp/src/extra/processor/jitterBuffer.d.ts +29 -6
  212. package/lib/rtp/src/extra/processor/jitterBuffer.js +101 -111
  213. package/lib/rtp/src/extra/processor/jitterBuffer.js.map +1 -1
  214. package/lib/rtp/src/extra/processor/jitterBufferTransformer.js +2 -1
  215. package/lib/rtp/src/extra/processor/jitterBufferTransformer.js.map +1 -1
  216. package/lib/rtp/src/extra/processor/lipsync.d.ts +63 -0
  217. package/lib/rtp/src/extra/processor/lipsync.js +202 -51
  218. package/lib/rtp/src/extra/processor/lipsync.js.map +1 -1
  219. package/lib/rtp/src/extra/processor/mp4.d.ts +0 -6
  220. package/lib/rtp/src/extra/processor/mp4.js +6 -3
  221. package/lib/rtp/src/extra/processor/mp4.js.map +1 -1
  222. package/lib/rtp/src/extra/processor/mute.js +4 -2
  223. package/lib/rtp/src/extra/processor/mute.js.map +1 -1
  224. package/lib/rtp/src/extra/processor/nack.js +4 -2
  225. package/lib/rtp/src/extra/processor/nack.js.map +1 -1
  226. package/lib/rtp/src/extra/processor/ntpTime.js +4 -6
  227. package/lib/rtp/src/extra/processor/ntpTime.js.map +1 -1
  228. package/lib/rtp/src/extra/processor/ogg.d.ts +72 -0
  229. package/lib/rtp/src/extra/processor/ogg.js +221 -0
  230. package/lib/rtp/src/extra/processor/ogg.js.map +1 -0
  231. package/lib/rtp/src/extra/processor/oggCallback.d.ts +21 -0
  232. package/lib/rtp/src/extra/processor/oggCallback.js +97 -0
  233. package/lib/rtp/src/extra/processor/oggCallback.js.map +1 -0
  234. package/lib/rtp/src/extra/processor/rtpCallback.js +2 -1
  235. package/lib/rtp/src/extra/processor/rtpCallback.js.map +1 -1
  236. package/lib/rtp/src/extra/processor/rtpStream.js +2 -1
  237. package/lib/rtp/src/extra/processor/rtpStream.js.map +1 -1
  238. package/lib/rtp/src/extra/processor/rtpTime.js +2 -1
  239. package/lib/rtp/src/extra/processor/rtpTime.js.map +1 -1
  240. package/lib/rtp/src/extra/processor/webm.js +14 -7
  241. package/lib/rtp/src/extra/processor/webm.js.map +1 -1
  242. package/lib/rtp/src/extra/processor/webmCallback.js.map +1 -1
  243. package/lib/rtp/src/index.d.ts +8 -0
  244. package/lib/rtp/src/index.js +8 -0
  245. package/lib/rtp/src/index.js.map +1 -1
  246. package/lib/rtp/src/rtcp/psfb/fullIntraRequest.d.ts +4 -0
  247. package/lib/rtp/src/rtcp/psfb/fullIntraRequest.js +4 -0
  248. package/lib/rtp/src/rtcp/psfb/fullIntraRequest.js.map +1 -1
  249. package/lib/rtp/src/rtcp/rtcp.js +8 -4
  250. package/lib/rtp/src/rtcp/rtcp.js.map +1 -1
  251. package/lib/rtp/src/rtcp/rtpfb/transportWideSequence.d.ts +58 -0
  252. package/lib/rtp/src/rtcp/rtpfb/transportWideSequence.js +143 -0
  253. package/lib/rtp/src/rtcp/rtpfb/transportWideSequence.js.map +1 -0
  254. package/lib/rtp/src/rtcp/rtpfb/twcc.d.ts +35 -13
  255. package/lib/rtp/src/rtcp/rtpfb/twcc.js +132 -54
  256. package/lib/rtp/src/rtcp/rtpfb/twcc.js.map +1 -1
  257. package/lib/rtp/src/rtcp/rtpfb/twccReceiveTiming.d.ts +13 -0
  258. package/lib/rtp/src/rtcp/rtpfb/twccReceiveTiming.js +29 -0
  259. package/lib/rtp/src/rtcp/rtpfb/twccReceiveTiming.js.map +1 -0
  260. package/lib/rtp/src/rtcp/rtpfb/twccReferenceTime.d.ts +41 -0
  261. package/lib/rtp/src/rtcp/rtpfb/twccReferenceTime.js +89 -0
  262. package/lib/rtp/src/rtcp/rtpfb/twccReferenceTime.js.map +1 -0
  263. package/lib/rtp/src/rtcp/sr.js +1 -0
  264. package/lib/rtp/src/rtcp/sr.js.map +1 -1
  265. package/lib/rtp/src/rtp/continuity.d.ts +49 -0
  266. package/lib/rtp/src/rtp/continuity.js +120 -0
  267. package/lib/rtp/src/rtp/continuity.js.map +1 -0
  268. package/lib/rtp/src/rtp/headerExtension.js +41 -21
  269. package/lib/rtp/src/rtp/headerExtension.js.map +1 -1
  270. package/lib/rtp/src/rtp/padding.d.ts +17 -0
  271. package/lib/rtp/src/rtp/padding.js +37 -0
  272. package/lib/rtp/src/rtp/padding.js.map +1 -0
  273. package/lib/rtp/src/rtp/red/encoder.d.ts +10 -0
  274. package/lib/rtp/src/rtp/red/encoder.js +14 -1
  275. package/lib/rtp/src/rtp/red/encoder.js.map +1 -1
  276. package/lib/rtp/src/rtp/red/packet.js +24 -8
  277. package/lib/rtp/src/rtp/red/packet.js.map +1 -1
  278. package/lib/rtp/src/rtp/rtp.d.ts +24 -1
  279. package/lib/rtp/src/rtp/rtp.js +70 -29
  280. package/lib/rtp/src/rtp/rtp.js.map +1 -1
  281. package/lib/rtp/src/rtp/rtx.js +3 -0
  282. package/lib/rtp/src/rtp/rtx.js.map +1 -1
  283. package/lib/rtp/src/rtp/sendHeaderExtensions.d.ts +36 -0
  284. package/lib/rtp/src/rtp/sendHeaderExtensions.js +85 -0
  285. package/lib/rtp/src/rtp/sendHeaderExtensions.js.map +1 -0
  286. package/lib/rtp/src/rtp/timelineRewriter.d.ts +178 -0
  287. package/lib/rtp/src/rtp/timelineRewriter.js +417 -0
  288. package/lib/rtp/src/rtp/timelineRewriter.js.map +1 -0
  289. package/lib/rtp/src/srtp/cipher/ctr.js +4 -2
  290. package/lib/rtp/src/srtp/cipher/ctr.js.map +1 -1
  291. package/lib/rtp/src/srtp/cipher/index.js +8 -4
  292. package/lib/rtp/src/srtp/cipher/index.js.map +1 -1
  293. package/lib/rtp/src/srtp/context/context.js +6 -3
  294. package/lib/rtp/src/srtp/context/context.js.map +1 -1
  295. package/lib/rtp/src/srtp/context/srtcp.d.ts +1 -1
  296. package/lib/rtp/src/srtp/context/srtcp.js +33 -0
  297. package/lib/rtp/src/srtp/context/srtcp.js.map +1 -1
  298. package/lib/rtp/src/srtp/context/srtp.d.ts +1 -1
  299. package/lib/rtp/src/srtp/context/srtp.js +34 -10
  300. package/lib/rtp/src/srtp/context/srtp.js.map +1 -1
  301. package/lib/rtp/src/srtp/error.d.ts +8 -0
  302. package/lib/rtp/src/srtp/error.js +13 -1
  303. package/lib/rtp/src/srtp/error.js.map +1 -1
  304. package/lib/rtp/src/srtp/packet.js +4 -1
  305. package/lib/rtp/src/srtp/packet.js.map +1 -1
  306. package/lib/rtp/src/srtp/replay.d.ts +24 -0
  307. package/lib/rtp/src/srtp/replay.js +75 -0
  308. package/lib/rtp/src/srtp/replay.js.map +1 -0
  309. package/lib/rtp/src/srtp/session.js +2 -1
  310. package/lib/rtp/src/srtp/session.js.map +1 -1
  311. package/lib/rtp/src/srtp/srtcp.js +2 -1
  312. package/lib/rtp/src/srtp/srtcp.js.map +1 -1
  313. package/lib/rtp/src/srtp/srtp.js +2 -1
  314. package/lib/rtp/src/srtp/srtp.js.map +1 -1
  315. package/lib/rtp/src/util.js +2 -1
  316. package/lib/rtp/src/util.js.map +1 -1
  317. package/lib/sctp/src/chunk.d.ts +5 -0
  318. package/lib/sctp/src/chunk.js +31 -8
  319. package/lib/sctp/src/chunk.js.map +1 -1
  320. package/lib/sctp/src/const.d.ts +25 -17
  321. package/lib/sctp/src/const.js +23 -19
  322. package/lib/sctp/src/const.js.map +1 -1
  323. package/lib/sctp/src/param.d.ts +6 -2
  324. package/lib/sctp/src/param.js +22 -8
  325. package/lib/sctp/src/param.js.map +1 -1
  326. package/lib/sctp/src/sctp.d.ts +85 -0
  327. package/lib/sctp/src/sctp.js +707 -126
  328. package/lib/sctp/src/sctp.js.map +1 -1
  329. package/lib/sctp/src/transport.js +4 -2
  330. package/lib/sctp/src/transport.js.map +1 -1
  331. package/lib/webrtc/src/api/compatibilityOptions.d.ts +33 -0
  332. package/lib/webrtc/src/api/compatibilityOptions.js +33 -0
  333. package/lib/webrtc/src/api/compatibilityOptions.js.map +1 -0
  334. package/lib/webrtc/src/api/peerConfig.d.ts +385 -28
  335. package/lib/webrtc/src/api/peerConfig.js +121 -14
  336. package/lib/webrtc/src/api/peerConfig.js.map +1 -1
  337. package/lib/webrtc/src/api/peerConnectionEvents.d.ts +77 -1
  338. package/lib/webrtc/src/api/peerConnectionEvents.js +105 -1
  339. package/lib/webrtc/src/api/peerConnectionEvents.js.map +1 -1
  340. package/lib/webrtc/src/dataChannel.d.ts +10 -0
  341. package/lib/webrtc/src/dataChannel.js +24 -4
  342. package/lib/webrtc/src/dataChannel.js.map +1 -1
  343. package/lib/webrtc/src/helper.d.ts +8 -0
  344. package/lib/webrtc/src/helper.js +40 -4
  345. package/lib/webrtc/src/helper.js.map +1 -1
  346. package/lib/webrtc/src/media/codecCompatibility.d.ts +87 -1
  347. package/lib/webrtc/src/media/codecCompatibility.js +338 -12
  348. package/lib/webrtc/src/media/codecCompatibility.js.map +1 -1
  349. package/lib/webrtc/src/media/index.d.ts +10 -0
  350. package/lib/webrtc/src/media/index.js +70 -0
  351. package/lib/webrtc/src/media/index.js.map +1 -1
  352. package/lib/webrtc/src/media/receiver/nack.d.ts +43 -10
  353. package/lib/webrtc/src/media/receiver/nack.js +246 -88
  354. package/lib/webrtc/src/media/receiver/nack.js.map +1 -1
  355. package/lib/webrtc/src/media/receiver/receiverTwcc.d.ts +61 -1
  356. package/lib/webrtc/src/media/receiver/receiverTwcc.js +218 -63
  357. package/lib/webrtc/src/media/receiver/receiverTwcc.js.map +1 -1
  358. package/lib/webrtc/src/media/router.d.ts +241 -40
  359. package/lib/webrtc/src/media/router.js +676 -205
  360. package/lib/webrtc/src/media/router.js.map +1 -1
  361. package/lib/webrtc/src/media/routing/pendingRoutes.d.ts +26 -0
  362. package/lib/webrtc/src/media/routing/pendingRoutes.js +48 -0
  363. package/lib/webrtc/src/media/routing/pendingRoutes.js.map +1 -0
  364. package/lib/webrtc/src/media/routing/ridRouting.d.ts +37 -0
  365. package/lib/webrtc/src/media/routing/ridRouting.js +74 -0
  366. package/lib/webrtc/src/media/routing/ridRouting.js.map +1 -0
  367. package/lib/webrtc/src/media/routing/routeTable.d.ts +60 -0
  368. package/lib/webrtc/src/media/routing/routeTable.js +95 -0
  369. package/lib/webrtc/src/media/routing/routeTable.js.map +1 -0
  370. package/lib/webrtc/src/media/routing/rtcpRouting.d.ts +34 -0
  371. package/lib/webrtc/src/media/routing/rtcpRouting.js +165 -0
  372. package/lib/webrtc/src/media/routing/rtcpRouting.js.map +1 -0
  373. package/lib/webrtc/src/media/routing/unknownSsrc.d.ts +55 -0
  374. package/lib/webrtc/src/media/routing/unknownSsrc.js +117 -0
  375. package/lib/webrtc/src/media/routing/unknownSsrc.js.map +1 -0
  376. package/lib/webrtc/src/media/rtpReceiver.d.ts +252 -2
  377. package/lib/webrtc/src/media/rtpReceiver.js +833 -44
  378. package/lib/webrtc/src/media/rtpReceiver.js.map +1 -1
  379. package/lib/webrtc/src/media/rtpSender.d.ts +191 -70
  380. package/lib/webrtc/src/media/rtpSender.js +631 -448
  381. package/lib/webrtc/src/media/rtpSender.js.map +1 -1
  382. package/lib/webrtc/src/media/rtpTransceiver.d.ts +19 -3
  383. package/lib/webrtc/src/media/rtpTransceiver.js +74 -9
  384. package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
  385. package/lib/webrtc/src/media/sender/bandwidthEstimator.d.ts +249 -0
  386. package/lib/webrtc/src/media/sender/bandwidthEstimator.js +144 -0
  387. package/lib/webrtc/src/media/sender/bandwidthEstimator.js.map +1 -0
  388. package/lib/webrtc/src/media/sender/createBandwidthEstimator.d.ts +20 -0
  389. package/lib/webrtc/src/media/sender/createBandwidthEstimator.js +26 -0
  390. package/lib/webrtc/src/media/sender/createBandwidthEstimator.js.map +1 -0
  391. package/lib/webrtc/src/media/sender/estimatorBinding.d.ts +70 -0
  392. package/lib/webrtc/src/media/sender/estimatorBinding.js +175 -0
  393. package/lib/webrtc/src/media/sender/estimatorBinding.js.map +1 -0
  394. package/lib/webrtc/src/media/sender/estimators/disabledBwe.d.ts +18 -0
  395. package/lib/webrtc/src/media/sender/estimators/disabledBwe.js +44 -0
  396. package/lib/webrtc/src/media/sender/estimators/disabledBwe.js.map +1 -0
  397. package/lib/webrtc/src/media/sender/estimators/gcc/acknowledgedBitrateEstimator.d.ts +79 -0
  398. package/lib/webrtc/src/media/sender/estimators/gcc/acknowledgedBitrateEstimator.js +289 -0
  399. package/lib/webrtc/src/media/sender/estimators/gcc/acknowledgedBitrateEstimator.js.map +1 -0
  400. package/lib/webrtc/src/media/sender/estimators/gcc/aimdRateControl.d.ts +87 -0
  401. package/lib/webrtc/src/media/sender/estimators/gcc/aimdRateControl.js +429 -0
  402. package/lib/webrtc/src/media/sender/estimators/gcc/aimdRateControl.js.map +1 -0
  403. package/lib/webrtc/src/media/sender/estimators/gcc/alrDetector.d.ts +21 -0
  404. package/lib/webrtc/src/media/sender/estimators/gcc/alrDetector.js +84 -0
  405. package/lib/webrtc/src/media/sender/estimators/gcc/alrDetector.js.map +1 -0
  406. package/lib/webrtc/src/media/sender/estimators/gcc/bandwidthLimitedCause.d.ts +37 -0
  407. package/lib/webrtc/src/media/sender/estimators/gcc/bandwidthLimitedCause.js +74 -0
  408. package/lib/webrtc/src/media/sender/estimators/gcc/bandwidthLimitedCause.js.map +1 -0
  409. package/lib/webrtc/src/media/sender/estimators/gcc/constants.d.ts +383 -0
  410. package/lib/webrtc/src/media/sender/estimators/gcc/constants.js +408 -0
  411. package/lib/webrtc/src/media/sender/estimators/gcc/constants.js.map +1 -0
  412. package/lib/webrtc/src/media/sender/estimators/gcc/gccBwe.d.ts +406 -0
  413. package/lib/webrtc/src/media/sender/estimators/gcc/gccBwe.js +1391 -0
  414. package/lib/webrtc/src/media/sender/estimators/gcc/gccBwe.js.map +1 -0
  415. package/lib/webrtc/src/media/sender/estimators/gcc/index.d.ts +19 -0
  416. package/lib/webrtc/src/media/sender/estimators/gcc/index.js +75 -0
  417. package/lib/webrtc/src/media/sender/estimators/gcc/index.js.map +1 -0
  418. package/lib/webrtc/src/media/sender/estimators/gcc/interArrivalDelta.d.ts +68 -0
  419. package/lib/webrtc/src/media/sender/estimators/gcc/interArrivalDelta.js +201 -0
  420. package/lib/webrtc/src/media/sender/estimators/gcc/interArrivalDelta.js.map +1 -0
  421. package/lib/webrtc/src/media/sender/estimators/gcc/intervalBudget.d.ts +26 -0
  422. package/lib/webrtc/src/media/sender/estimators/gcc/intervalBudget.js +72 -0
  423. package/lib/webrtc/src/media/sender/estimators/gcc/intervalBudget.js.map +1 -0
  424. package/lib/webrtc/src/media/sender/estimators/gcc/linkCapacityEstimator.d.ts +41 -0
  425. package/lib/webrtc/src/media/sender/estimators/gcc/linkCapacityEstimator.js +99 -0
  426. package/lib/webrtc/src/media/sender/estimators/gcc/linkCapacityEstimator.js.map +1 -0
  427. package/lib/webrtc/src/media/sender/estimators/gcc/lossBasedBwe.d.ts +247 -0
  428. package/lib/webrtc/src/media/sender/estimators/gcc/lossBasedBwe.js +1042 -0
  429. package/lib/webrtc/src/media/sender/estimators/gcc/lossBasedBwe.js.map +1 -0
  430. package/lib/webrtc/src/media/sender/estimators/gcc/overuseDetector.d.ts +26 -0
  431. package/lib/webrtc/src/media/sender/estimators/gcc/overuseDetector.js +132 -0
  432. package/lib/webrtc/src/media/sender/estimators/gcc/overuseDetector.js.map +1 -0
  433. package/lib/webrtc/src/media/sender/estimators/gcc/probeController.d.ts +305 -0
  434. package/lib/webrtc/src/media/sender/estimators/gcc/probeController.js +1073 -0
  435. package/lib/webrtc/src/media/sender/estimators/gcc/probeController.js.map +1 -0
  436. package/lib/webrtc/src/media/sender/estimators/gcc/rttBasedBackoff.d.ts +60 -0
  437. package/lib/webrtc/src/media/sender/estimators/gcc/rttBasedBackoff.js +151 -0
  438. package/lib/webrtc/src/media/sender/estimators/gcc/rttBasedBackoff.js.map +1 -0
  439. package/lib/webrtc/src/media/sender/estimators/gcc/trendlineEstimator.d.ts +44 -0
  440. package/lib/webrtc/src/media/sender/estimators/gcc/trendlineEstimator.js +246 -0
  441. package/lib/webrtc/src/media/sender/estimators/gcc/trendlineEstimator.js.map +1 -0
  442. package/lib/webrtc/src/media/sender/estimators/index.d.ts +7 -0
  443. package/lib/webrtc/src/media/sender/estimators/index.js +19 -0
  444. package/lib/webrtc/src/media/sender/estimators/index.js.map +1 -0
  445. package/lib/webrtc/src/media/sender/estimators/lightweightBwe.d.ts +64 -0
  446. package/lib/webrtc/src/media/sender/estimators/lightweightBwe.js +216 -0
  447. package/lib/webrtc/src/media/sender/estimators/lightweightBwe.js.map +1 -0
  448. package/lib/webrtc/src/media/sender/estimators/twccFeedbackAdapter.d.ts +117 -0
  449. package/lib/webrtc/src/media/sender/estimators/twccFeedbackAdapter.js +250 -0
  450. package/lib/webrtc/src/media/sender/estimators/twccFeedbackAdapter.js.map +1 -0
  451. package/lib/webrtc/src/media/sender/outgoingQueue.d.ts +40 -0
  452. package/lib/webrtc/src/media/sender/outgoingQueue.js +153 -0
  453. package/lib/webrtc/src/media/sender/outgoingQueue.js.map +1 -0
  454. package/lib/webrtc/src/media/sender/padding.d.ts +45 -0
  455. package/lib/webrtc/src/media/sender/padding.js +134 -0
  456. package/lib/webrtc/src/media/sender/padding.js.map +1 -0
  457. package/lib/webrtc/src/media/sender/pendingRtp.d.ts +35 -0
  458. package/lib/webrtc/src/media/sender/pendingRtp.js +120 -0
  459. package/lib/webrtc/src/media/sender/pendingRtp.js.map +1 -0
  460. package/lib/webrtc/src/media/sender/rtpWire.d.ts +13 -0
  461. package/lib/webrtc/src/media/sender/rtpWire.js +38 -0
  462. package/lib/webrtc/src/media/sender/rtpWire.js.map +1 -0
  463. package/lib/webrtc/src/media/sender/sendPacer.d.ts +27 -0
  464. package/lib/webrtc/src/media/sender/sendPacer.js +110 -0
  465. package/lib/webrtc/src/media/sender/sendPacer.js.map +1 -0
  466. package/lib/webrtc/src/media/sender/senderBWE.d.ts +8 -33
  467. package/lib/webrtc/src/media/sender/senderBWE.js +5 -154
  468. package/lib/webrtc/src/media/sender/senderBWE.js.map +1 -1
  469. package/lib/webrtc/src/media/sender/senderReportHistory.d.ts +51 -0
  470. package/lib/webrtc/src/media/sender/senderReportHistory.js +111 -0
  471. package/lib/webrtc/src/media/sender/senderReportHistory.js.map +1 -0
  472. package/lib/webrtc/src/media/sender/senderStats.d.ts +101 -0
  473. package/lib/webrtc/src/media/sender/senderStats.js +317 -0
  474. package/lib/webrtc/src/media/sender/senderStats.js.map +1 -0
  475. package/lib/webrtc/src/media/track.d.ts +29 -2
  476. package/lib/webrtc/src/media/track.js +32 -5
  477. package/lib/webrtc/src/media/track.js.map +1 -1
  478. package/lib/webrtc/src/negotiation/bundleTopology.d.ts +1 -5
  479. package/lib/webrtc/src/negotiation/bundleTopology.js +15 -11
  480. package/lib/webrtc/src/negotiation/bundleTopology.js.map +1 -1
  481. package/lib/webrtc/src/negotiation/descriptionValidation.js +12 -6
  482. package/lib/webrtc/src/negotiation/descriptionValidation.js.map +1 -1
  483. package/lib/webrtc/src/negotiation/negotiationNeeded.js +2 -1
  484. package/lib/webrtc/src/negotiation/negotiationNeeded.js.map +1 -1
  485. package/lib/webrtc/src/negotiation/remoteCandidates.js +10 -5
  486. package/lib/webrtc/src/negotiation/remoteCandidates.js.map +1 -1
  487. package/lib/webrtc/src/negotiation/remoteMediaApplication.d.ts +24 -7
  488. package/lib/webrtc/src/negotiation/remoteMediaApplication.js +67 -27
  489. package/lib/webrtc/src/negotiation/remoteMediaApplication.js.map +1 -1
  490. package/lib/webrtc/src/negotiation/transceiverPairing.d.ts +1 -0
  491. package/lib/webrtc/src/negotiation/transceiverPairing.js +62 -0
  492. package/lib/webrtc/src/negotiation/transceiverPairing.js.map +1 -0
  493. package/lib/webrtc/src/negotiation/transportActivation.d.ts +8 -1
  494. package/lib/webrtc/src/negotiation/transportActivation.js +40 -8
  495. package/lib/webrtc/src/negotiation/transportActivation.js.map +1 -1
  496. package/lib/webrtc/src/negotiationTransaction.d.ts +43 -5
  497. package/lib/webrtc/src/negotiationTransaction.js +129 -13
  498. package/lib/webrtc/src/negotiationTransaction.js.map +1 -1
  499. package/lib/webrtc/src/nonstandard/dummyMedia.js +2 -1
  500. package/lib/webrtc/src/nonstandard/dummyMedia.js.map +1 -1
  501. package/lib/webrtc/src/nonstandard/navigator.js +4 -3
  502. package/lib/webrtc/src/nonstandard/navigator.js.map +1 -1
  503. package/lib/webrtc/src/nonstandard/recorder/index.d.ts +32 -8
  504. package/lib/webrtc/src/nonstandard/recorder/index.js +81 -20
  505. package/lib/webrtc/src/nonstandard/recorder/index.js.map +1 -1
  506. package/lib/webrtc/src/nonstandard/recorder/writer/index.d.ts +9 -7
  507. package/lib/webrtc/src/nonstandard/recorder/writer/index.js +2 -1
  508. package/lib/webrtc/src/nonstandard/recorder/writer/index.js.map +1 -1
  509. package/lib/webrtc/src/nonstandard/recorder/writer/ogg.d.ts +32 -0
  510. package/lib/webrtc/src/nonstandard/recorder/writer/ogg.js +185 -0
  511. package/lib/webrtc/src/nonstandard/recorder/writer/ogg.js.map +1 -0
  512. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js +8 -1
  513. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js.map +1 -1
  514. package/lib/webrtc/src/nonstandard/userMedia.js +2 -1
  515. package/lib/webrtc/src/nonstandard/userMedia.js.map +1 -1
  516. package/lib/webrtc/src/peerConnection.d.ts +108 -6
  517. package/lib/webrtc/src/peerConnection.js +357 -36
  518. package/lib/webrtc/src/peerConnection.js.map +1 -1
  519. package/lib/webrtc/src/polyfill/globals.d.ts +2 -1
  520. package/lib/webrtc/src/polyfill/globals.js.map +1 -1
  521. package/lib/webrtc/src/polyfill/install.js +2 -0
  522. package/lib/webrtc/src/polyfill/install.js.map +1 -1
  523. package/lib/webrtc/src/polyfill/mediaDevices.js +2 -1
  524. package/lib/webrtc/src/polyfill/mediaDevices.js.map +1 -1
  525. package/lib/webrtc/src/sctpManager.d.ts +46 -14
  526. package/lib/webrtc/src/sctpManager.js +92 -25
  527. package/lib/webrtc/src/sctpManager.js.map +1 -1
  528. package/lib/webrtc/src/sdp.d.ts +69 -0
  529. package/lib/webrtc/src/sdp.js +151 -20
  530. package/lib/webrtc/src/sdp.js.map +1 -1
  531. package/lib/webrtc/src/sdpManager.d.ts +85 -4
  532. package/lib/webrtc/src/sdpManager.js +214 -14
  533. package/lib/webrtc/src/sdpManager.js.map +1 -1
  534. package/lib/webrtc/src/secureTransportManager.d.ts +89 -4
  535. package/lib/webrtc/src/secureTransportManager.js +184 -26
  536. package/lib/webrtc/src/secureTransportManager.js.map +1 -1
  537. package/lib/webrtc/src/transceiverManager.d.ts +82 -4
  538. package/lib/webrtc/src/transceiverManager.js +239 -41
  539. package/lib/webrtc/src/transceiverManager.js.map +1 -1
  540. package/lib/webrtc/src/transport/dtls.d.ts +147 -1
  541. package/lib/webrtc/src/transport/dtls.js +446 -50
  542. package/lib/webrtc/src/transport/dtls.js.map +1 -1
  543. package/lib/webrtc/src/transport/ice.d.ts +71 -90
  544. package/lib/webrtc/src/transport/ice.js +250 -42
  545. package/lib/webrtc/src/transport/ice.js.map +1 -1
  546. package/lib/webrtc/src/transport/sctp.d.ts +25 -0
  547. package/lib/webrtc/src/transport/sctp.js +153 -22
  548. package/lib/webrtc/src/transport/sctp.js.map +1 -1
  549. package/lib/webrtc/src/utils.d.ts +69 -3
  550. package/lib/webrtc/src/utils.js +105 -16
  551. package/lib/webrtc/src/utils.js.map +1 -1
  552. package/package.json +9 -6
@@ -33,33 +33,57 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.Connection = void 0;
36
+ exports.Connection = exports.DEFAULT_STUN_SERVER_URL = void 0;
37
37
  const timers = __importStar(require("node:timers/promises"));
38
38
  const crypto_1 = require("crypto");
39
- const net_1 = require("net");
40
- const common_1 = require("./imports/common");
41
39
  const candidate_1 = require("./candidate");
40
+ const candidateGatherer_1 = require("./candidateGatherer");
41
+ const consent_1 = require("./consent");
42
42
  const lookup_1 = require("./dns/lookup");
43
43
  const exceptions_1 = require("./exceptions");
44
44
  const helper_1 = require("./helper");
45
45
  const iceBase_1 = require("./iceBase");
46
+ const common_1 = require("./imports/common");
47
+ const checkMessages_1 = require("./internal/checkMessages");
48
+ const defaultRoute_1 = require("./internal/defaultRoute");
49
+ const hostInterfaces_1 = require("./internal/hostInterfaces");
46
50
  const resolveHostAddresses_1 = require("./internal/resolveHostAddresses");
51
+ const regularNomination_1 = require("./nomination/regularNomination");
52
+ const selectionReplacement_1 = require("./nomination/selectionReplacement");
53
+ const provisional_1 = require("./provisional");
47
54
  const const_1 = require("./stun/const");
48
55
  const message_1 = require("./stun/message");
49
56
  const protocol_1 = require("./stun/protocol");
50
- const tcpProtocol_1 = require("./stun/tcpProtocol");
51
- const protocol_2 = require("./turn/protocol");
52
- const utils_1 = require("./utils");
53
57
  const log = (0, common_1.debug)("werift-ice : packages/ice/src/ice.ts : log");
54
58
  /** Fallback STUN server when none is configured (constructor / setIceServers). */
55
59
  const DEFAULT_STUN_SERVER = ["stun.l.google.com", 19302];
60
+ /**
61
+ * The URL `onIceCandidateError` names the built-in default STUN server by:
62
+ * it is in no configuration, so werift synthesizes one.
63
+ */
64
+ exports.DEFAULT_STUN_SERVER_URL = "stun:stun.l.google.com:19302";
65
+ // The ICE agent. This file keeps the public API, the lifecycle (restart,
66
+ // close, state), the protocol event wiring and the live checklist
67
+ // (connect / checkStart / checkComplete / checkIncoming). Its parts live in
68
+ // collaborators the agent supplies through a host object:
69
+ // - candidateGatherer.ts: host / server-reflexive / relay gathering
70
+ // - consent.ts: RFC 7675 consent freshness of the selected pair
71
+ // - provisional.ts: the checklist of an ICE restart negotiated with a pranswer
72
+ // - nomination/regularNomination.ts: RFC 8445 regular nomination
73
+ // - nomination/selectionReplacement.ts: semi-aggressive nomination /
74
+ // renomination replacing the selection
75
+ // - internal/checkMessages.ts: building and reading connectivity checks
56
76
  class Connection {
77
+ /** The staged ICE restart generation (`ProvisionalChecklist`). */
78
+ get provisional() {
79
+ return this.provisionalChecklist.generation;
80
+ }
57
81
  constructor(_iceControlling, options) {
58
82
  Object.defineProperty(this, "_iceControlling", {
59
83
  enumerable: true,
60
84
  configurable: true,
61
85
  writable: true,
62
- value: _iceControlling
86
+ value: void 0
63
87
  });
64
88
  Object.defineProperty(this, "localUsername", {
65
89
  enumerable: true,
@@ -79,6 +103,19 @@ class Connection {
79
103
  writable: true,
80
104
  value: false
81
105
  });
106
+ /** The peer advertised `a=ice-options:renomination` (see `IceOptions.renomination`). */
107
+ Object.defineProperty(this, "remoteRenomination", {
108
+ enumerable: true,
109
+ configurable: true,
110
+ writable: true,
111
+ value: false
112
+ });
113
+ Object.defineProperty(this, "remoteIceOptions", {
114
+ enumerable: true,
115
+ configurable: true,
116
+ writable: true,
117
+ value: []
118
+ });
82
119
  Object.defineProperty(this, "remotePassword", {
83
120
  enumerable: true,
84
121
  configurable: true,
@@ -103,17 +140,30 @@ class Connection {
103
140
  writable: true,
104
141
  value: []
105
142
  });
106
- Object.defineProperty(this, "stunServer", {
143
+ /**
144
+ * STUN servers gathering queries: the configured ones (see
145
+ * normalizeIceServerOptions), or the built-in default when none is
146
+ * configured and useDefaultStunServer is not false.
147
+ */
148
+ Object.defineProperty(this, "stunServers", {
107
149
  enumerable: true,
108
150
  configurable: true,
109
151
  writable: true,
110
- value: void 0
152
+ value: []
111
153
  });
112
- Object.defineProperty(this, "turnServer", {
154
+ /** Whether stunServers is the built-in default (none configured). */
155
+ Object.defineProperty(this, "usesDefaultStunServer", {
113
156
  enumerable: true,
114
157
  configurable: true,
115
158
  writable: true,
116
- value: void 0
159
+ value: false
160
+ });
161
+ /** TURN servers gathering allocates on, one allocation each. */
162
+ Object.defineProperty(this, "turnServers", {
163
+ enumerable: true,
164
+ configurable: true,
165
+ writable: true,
166
+ value: []
117
167
  });
118
168
  Object.defineProperty(this, "options", {
119
169
  enumerable: true,
@@ -138,7 +188,11 @@ class Connection {
138
188
  writable: true,
139
189
  value: false
140
190
  });
141
- /** mDNS resolutions of remote candidates that arrived before end-of-candidates. */
191
+ /**
192
+ * mDNS resolutions of remote candidates that arrived before
193
+ * end-of-candidates. close() (and restart()) closes `lookup`, which rejects
194
+ * them at once.
195
+ */
142
196
  Object.defineProperty(this, "remoteResolutions", {
143
197
  enumerable: true,
144
198
  configurable: true,
@@ -158,6 +212,13 @@ class Connection {
158
212
  writable: true,
159
213
  value: false
160
214
  });
215
+ /** connect() stopped scheduling checks (a later pair must start its own). */
216
+ Object.defineProperty(this, "schedulingStopped", {
217
+ enumerable: true,
218
+ configurable: true,
219
+ writable: true,
220
+ value: false
221
+ });
161
222
  Object.defineProperty(this, "generation", {
162
223
  enumerable: true,
163
224
  configurable: true,
@@ -206,6 +267,14 @@ class Connection {
206
267
  writable: true,
207
268
  value: "new"
208
269
  });
270
+ /** close() ran; unlike `state`, a restart does not reset it. */
271
+ Object.defineProperty(this, "closed", {
272
+ enumerable: true,
273
+ configurable: true,
274
+ writable: true,
275
+ value: false
276
+ });
277
+ /** Resolves remote mDNS candidates; closed (pending lookups cancelled) by restart() and close(). */
209
278
  Object.defineProperty(this, "lookup", {
210
279
  enumerable: true,
211
280
  configurable: true,
@@ -225,12 +294,61 @@ class Connection {
225
294
  writable: true,
226
295
  value: void 0
227
296
  });
228
- Object.defineProperty(this, "nominating", {
297
+ /** The ICE-lite nomination (first valid pair, in `checkStart`) is in flight. */
298
+ Object.defineProperty(this, "liteNominating", {
229
299
  enumerable: true,
230
300
  configurable: true,
231
301
  writable: true,
232
302
  value: false
233
303
  });
304
+ /** Regular nomination (RFC 8445 §8.1.1) of the live checklist. */
305
+ Object.defineProperty(this, "nomination", {
306
+ enumerable: true,
307
+ configurable: true,
308
+ writable: true,
309
+ value: new regularNomination_1.RegularNomination(this.liveNominationHost())
310
+ });
311
+ /** Semi-aggressive nomination and renomination: replacing the selection. */
312
+ Object.defineProperty(this, "selection", {
313
+ enumerable: true,
314
+ configurable: true,
315
+ writable: true,
316
+ value: new selectionReplacement_1.SelectionReplacement({
317
+ checkList: () => this.checkList,
318
+ selected: () => this.nominated,
319
+ controlling: () => this.iceControlling,
320
+ closed: () => this.state === "closed",
321
+ remoteGeneration: () => this.remoteGeneration,
322
+ usesRenomination: () => this.usesRenomination(),
323
+ usesSemiAggressiveNomination: () => this.usesSemiAggressiveNomination(),
324
+ replacesSelection: () => this.replacesSelection(),
325
+ replacesWith: (pair) => this.replacesWith(pair),
326
+ outranks: (pair, other) => this.outranks(pair, other),
327
+ bestValidPair: (pairs) => this.bestValidPair(pairs),
328
+ isTcpPair: (pair) => this.isTcpPair(pair),
329
+ check: (pair) => {
330
+ pair.handle = this.checkStart(pair);
331
+ },
332
+ complete: (pair) => this.checkComplete(pair),
333
+ sendNomination: (pair, signal, value) => this.sendNomination(pair, signal, value),
334
+ isStaleNomination: (pair, generation) => this.isStaleNomination(pair, generation),
335
+ roleConflict: () => this.switchRole(false),
336
+ })
337
+ });
338
+ /** See `NominationHint`; set by the restart that ends a provisional checklist. */
339
+ Object.defineProperty(this, "nominationHint", {
340
+ enumerable: true,
341
+ configurable: true,
342
+ writable: true,
343
+ value: void 0
344
+ });
345
+ /** USE-CANDIDATE re-sent for a pair selected before the agent became controlling (`confirmSelections`). */
346
+ Object.defineProperty(this, "selectionConfirmations", {
347
+ enumerable: true,
348
+ configurable: true,
349
+ writable: true,
350
+ value: new Set()
351
+ });
234
352
  /**
235
353
  * Aborted when the remote generation ends (restart, restartRemote, close):
236
354
  * every check and nomination transaction of that generation stops with it.
@@ -243,16 +361,21 @@ class Connection {
243
361
  * - `retryCheck` (487 role conflict / 401 retry): the handle of the check
244
362
  * it replaces and this signal (the retry is a `checkStart`).
245
363
  * - 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`.
364
+ * check's signal; `isStaleNomination` guards `liteNominating`, the pair
365
+ * state and `checkComplete`.
366
+ * - `RegularNomination` (live: `sendNomination`): this signal and the
367
+ * attempt's own, which `reset()` (restart, restartRemote,
368
+ * resetNominatedPair, close) and `invalidate()` (role change) abort; a
369
+ * result of a replaced attempt is ignored. Its delay timer is cleared by
370
+ * `reset()`.
371
+ * - `ProvisionalChecklist` checks and nominations: `generation.checks`
372
+ * (`end()`, a replacement pranswer, close); `belongs()`, and
373
+ * the provisional `RegularNomination` as above.
374
+ * - consent checks (`ConsentFreshness`): a per-request `AbortController`
375
+ * and `consent.stop()`; its session id.
253
376
  * - `serverReflexiveCandidate` (gathering): `protocol.close()`; otherwise
254
377
  * it ends by its retransmission timeout, and `stale()` drops the
255
- * candidate of an ended gather.
378
+ * candidate (or the failure) of an ended gather.
256
379
  * - TURN client requests: the `closing` signal and `TurnProtocol.close()`.
257
380
  * Regression tests: `tests/ice/check-cancel.test.ts`.
258
381
  */
@@ -325,238 +448,147 @@ class Connection {
325
448
  writable: true,
326
449
  value: []
327
450
  });
328
- Object.defineProperty(this, "queryConsentHandle", {
329
- enumerable: true,
330
- configurable: true,
331
- writable: true,
332
- value: void 0
333
- });
334
- /** RFC 7675 consent-to-send: application data may use the selected pair. */
335
- Object.defineProperty(this, "consentFresh", {
336
- enumerable: true,
337
- configurable: true,
338
- writable: true,
339
- value: false
340
- });
341
- /** Invalidates in-flight consent callbacks on restart / close / replace / expire. */
342
- Object.defineProperty(this, "consentSessionId", {
451
+ /** RFC 7675 consent freshness of the selected pair. */
452
+ Object.defineProperty(this, "consent", {
343
453
  enumerable: true,
344
454
  configurable: true,
345
455
  writable: true,
346
- value: 0
456
+ value: new consent_1.ConsentFreshness({
457
+ selected: () => this.nominated,
458
+ state: () => this.state,
459
+ setState: (state) => this.setState(state),
460
+ remoteGeneration: () => this.remoteGeneration,
461
+ remotePassword: () => this.remotePassword,
462
+ iceLite: () => this.iceLite,
463
+ integrityAlgorithm: () => this.options.messageIntegrity,
464
+ buildRequest: (pair) => this.buildRequest({
465
+ nominate: this.shouldNominateConsentRequest(pair),
466
+ nomination: this.consentNomination(pair),
467
+ localUsername: this.localUsername,
468
+ remoteUsername: this.remoteUsername,
469
+ iceControlling: this.iceControlling,
470
+ localCandidate: pair.localCandidate,
471
+ }),
472
+ })
347
473
  });
348
- Object.defineProperty(this, "consentExpiryTimer", {
474
+ /** Host, server-reflexive and relay gathering (`CandidateGatherer`). */
475
+ Object.defineProperty(this, "gatherer", {
349
476
  enumerable: true,
350
477
  configurable: true,
351
478
  writable: true,
352
- value: void 0
479
+ value: new candidateGatherer_1.CandidateGatherer({
480
+ options: () => this.options,
481
+ iceLite: () => this.iceLite,
482
+ generation: () => this.generation,
483
+ localUsername: () => this.localUsername,
484
+ protocols: () => this.protocols,
485
+ stunServers: () => this.stunServers,
486
+ turnServers: () => this.turnServers,
487
+ defaultStunServer: () => this.usesDefaultStunServer
488
+ ? { address: DEFAULT_STUN_SERVER, url: exports.DEFAULT_STUN_SERVER_URL }
489
+ : undefined,
490
+ isGathering: (generation) => this.isGathering(generation),
491
+ closing: () => this.closing.signal,
492
+ ensureProtocol: (protocol) => this.ensureProtocol(protocol),
493
+ pairLocalProtocol: (protocol) => this.pairLocalProtocol(protocol),
494
+ appendLocalCandidate: (candidate) => this.appendLocalCandidate(candidate),
495
+ emitCandidateError: (stale, generation, server, failure, local) => this.emitCandidateError(stale, generation, server, failure, local),
496
+ emitServerReached: (stale, generation, server) => this.emitServerReached(stale, generation, server),
497
+ })
353
498
  });
354
- Object.defineProperty(this, "consentRequestAbort", {
499
+ /**
500
+ * Settles when the background server-reflexive queries of the current
501
+ * generation end (see {@link Connection.waitForLocalCandidatesEnd}).
502
+ */
503
+ Object.defineProperty(this, "localCandidatesEndPromise", {
355
504
  enumerable: true,
356
505
  configurable: true,
357
506
  writable: true,
358
507
  value: void 0
359
508
  });
360
509
  /** ICE restart generation checked beside the selected current pair. */
361
- Object.defineProperty(this, "provisional", {
510
+ Object.defineProperty(this, "provisionalChecklist", {
362
511
  enumerable: true,
363
512
  configurable: true,
364
513
  writable: true,
365
- value: void 0
514
+ value: new provisional_1.ProvisionalChecklist({
515
+ closed: () => this.closed,
516
+ iceLite: () => this.iceLite,
517
+ iceControlling: () => this.iceControlling,
518
+ remoteIsLite: () => this.remoteIsLite,
519
+ localCandidatesEnd: () => this.localCandidatesEnd,
520
+ options: () => this.options,
521
+ protocols: () => this.protocols,
522
+ mdnsLookup: () => {
523
+ this.lookup ?? (this.lookup = new lookup_1.MdnsLookup());
524
+ return this.lookup;
525
+ },
526
+ isUncheckedPair: (pair) => this.isUncheckedPair(pair),
527
+ isWildcardProtocol: (protocol) => this.gatherer.isWildcardProtocol(protocol),
528
+ wildcardPathUncovered: (remoteCandidate) => this.gatherer.wildcardPathUncovered(remoteCandidate),
529
+ nominatesFullPeer: () => this.nominatesFullPeer(),
530
+ usesRegularNomination: () => this.usesRegularNomination(),
531
+ replacesWith: (pair) => this.replacesWith(pair),
532
+ regularNominationPairs: (pairs) => this.regularNominationPairs(pairs),
533
+ bestValidPair: (pairs) => this.bestValidPair(pairs),
534
+ outranks: (pair, other) => this.outranks(pair, other),
535
+ nominationDelayMs: () => this.nominationDelayMs,
536
+ buildRequest: (params) => this.buildRequest(params),
537
+ switchRole: (iceControlling) => this.switchRole(iceControlling),
538
+ })
366
539
  });
367
- /** Last server-reflexive candidate each UDP socket advertised. */
368
- Object.defineProperty(this, "reflexiveBySocket", {
540
+ Object.defineProperty(this, "onData", {
369
541
  enumerable: true,
370
542
  configurable: true,
371
543
  writable: true,
372
- value: new WeakMap()
544
+ value: new common_1.Event()
373
545
  });
374
- Object.defineProperty(this, "onData", {
546
+ Object.defineProperty(this, "stateChanged", {
375
547
  enumerable: true,
376
548
  configurable: true,
377
549
  writable: true,
378
550
  value: new common_1.Event()
379
551
  });
380
- Object.defineProperty(this, "stateChanged", {
552
+ Object.defineProperty(this, "onIceCandidate", {
381
553
  enumerable: true,
382
554
  configurable: true,
383
555
  writable: true,
384
556
  value: new common_1.Event()
385
557
  });
386
- Object.defineProperty(this, "onIceCandidate", {
558
+ /**
559
+ * A STUN server query or TURN allocation of the current generation's
560
+ * gathering failed (W3C `icecandidateerror`), synchronously and without
561
+ * changing the gathering: other servers and sockets go on, and gathering
562
+ * still completes. A server answering with an error gives its ERROR-CODE,
563
+ * once per local socket and generation. One that is not reached (timeout,
564
+ * `stunGatherTimeout`, DNS, connect or socket error) gives 701, once per
565
+ * server and generation and only when no local socket reached it (a STUN
566
+ * server is reported when the last socket's query ended). A TURN server's UDP attempt and its TCP fallback are
567
+ * one failure, reported when both failed (a server's error code wins over
568
+ * 701). A credential retry (401 / 438) that succeeds is not a failure.
569
+ * Nothing is fired for a replaced generation or after close (the event
570
+ * completes then). A STUN failure carries the host address of a socket
571
+ * that asked; a TURN one carries none. The built-in default STUN server (none
572
+ * configured, `useDefaultStunServer` not false) is named by the
573
+ * synthesized URL {@link DEFAULT_STUN_SERVER_URL} in `server.urls`.
574
+ */
575
+ Object.defineProperty(this, "onIceCandidateError", {
387
576
  enumerable: true,
388
577
  configurable: true,
389
578
  writable: true,
390
579
  value: new common_1.Event()
391
580
  });
392
- // RFC 7675 consent freshness
393
- Object.defineProperty(this, "queryConsent", {
581
+ /**
582
+ * A STUN or TURN server of the current generation's gathering answered:
583
+ * a STUN query or TURN allocation gave a candidate, or the server sent an
584
+ * error response (see {@link IceServerReachedInfo}). Synchronous; nothing
585
+ * is fired for a replaced generation or after close.
586
+ */
587
+ Object.defineProperty(this, "onIceServerReached", {
394
588
  enumerable: true,
395
589
  configurable: true,
396
590
  writable: true,
397
- value: () => {
398
- if (this.iceLite) {
399
- return;
400
- }
401
- // Invalidate any previous consent session before starting a new one.
402
- this.stopConsentLifecycle();
403
- const sessionId = this.consentSessionId;
404
- this.consentFresh = true;
405
- const handle = (0, helper_1.cancelable)(async (_, __, onCancel) => {
406
- let canceled = false;
407
- const cancelEvent = new AbortController();
408
- const clearConsentExpiry = () => {
409
- if (this.consentExpiryTimer === undefined) {
410
- return;
411
- }
412
- clearTimeout(this.consentExpiryTimer);
413
- this.consentExpiryTimer = undefined;
414
- };
415
- const refreshConsentExpiry = () => {
416
- // Only the active session may refresh the shared expiry timer.
417
- if (canceled || sessionId !== this.consentSessionId) {
418
- return;
419
- }
420
- clearConsentExpiry();
421
- this.consentExpiryTimer = setTimeout(() => {
422
- this.consentExpiryTimer = undefined;
423
- if (canceled || sessionId !== this.consentSessionId) {
424
- return;
425
- }
426
- if (this.state === "closed" || this.state === "failed") {
427
- return;
428
- }
429
- log("Consent to send expired");
430
- // Expire independently of request cadence / failure count (RFC 7675).
431
- this.consentFresh = false;
432
- this.consentSessionId++;
433
- this.consentRequestAbort?.abort();
434
- this.consentRequestAbort = undefined;
435
- if (this.queryConsentHandle === handle) {
436
- this.queryConsentHandle = undefined;
437
- }
438
- canceled = true;
439
- cancelEvent.abort();
440
- // Transport stays available for ICE restart; explicit close() uses "closed".
441
- this.setState("failed");
442
- }, iceBase_1.CONSENT_TIMEOUT * 1000);
443
- };
444
- onCancel.once(() => {
445
- canceled = true;
446
- // Avoid clearing a replacement session's timer/handle.
447
- if (sessionId === this.consentSessionId) {
448
- clearConsentExpiry();
449
- this.consentRequestAbort?.abort();
450
- this.consentRequestAbort = undefined;
451
- }
452
- cancelEvent.abort();
453
- if (this.queryConsentHandle === handle) {
454
- this.queryConsentHandle = undefined;
455
- }
456
- });
457
- // Initial ICE check success is the first valid consent response.
458
- refreshConsentExpiry();
459
- const randomizedConsentInterval = () => iceBase_1.CONSENT_INTERVAL * (0.8 + 0.4 * Math.random()) * 1000;
460
- // Cadence is measured between request *starts*, not response completions.
461
- let nextConsentAt = Date.now() + randomizedConsentInterval();
462
- const isTerminalState = () => this.state === "closed" || this.state === "failed";
463
- try {
464
- while (!isTerminalState() &&
465
- !canceled &&
466
- sessionId === this.consentSessionId) {
467
- await this.abortableDelay(Math.max(0, nextConsentAt - Date.now()), cancelEvent.signal);
468
- if (canceled ||
469
- isTerminalState() ||
470
- sessionId !== this.consentSessionId) {
471
- break;
472
- }
473
- // Fix next start time before awaiting any response (independent timers).
474
- nextConsentAt = Date.now() + randomizedConsentInterval();
475
- const nominated = this.nominated;
476
- if (!nominated) {
477
- break;
478
- }
479
- const pairId = nominated.id;
480
- const generation = this.remoteGeneration;
481
- const remotePassword = this.remotePassword;
482
- const { localUsername, remoteUsername, iceControlling } = this;
483
- const request = this.buildRequest({
484
- nominate: this.shouldNominateConsentRequest(nominated),
485
- localUsername,
486
- remoteUsername,
487
- iceControlling,
488
- localCandidate: nominated.localCandidate,
489
- });
490
- this.consentRequestAbort?.abort();
491
- const requestAbort = new AbortController();
492
- this.consentRequestAbort = requestAbort;
493
- nominated.consentRequestsSent++;
494
- nominated.requestsSent++;
495
- // RTT-aware wait (floor 500ms); independent of retransmissions: 0.
496
- const responseTimeout = (0, iceBase_1.consentResponseTimeoutMs)(nominated.rtt);
497
- const requestStartedAt = performance.now();
498
- // Do not await here: response wait must not stretch the 4–6s cadence.
499
- nominated.protocol
500
- .request(request, nominated.remoteAddr, Buffer.from(remotePassword, "utf8"), {
501
- retransmissions: 0,
502
- responseTimeout,
503
- signal: requestAbort.signal,
504
- onRequestSent: (attempt) => {
505
- if (attempt > 0) {
506
- nominated.retransmissionsSent++;
507
- }
508
- },
509
- })
510
- .then(() => {
511
- // Accept only responses for the current pair / generation / session.
512
- // Address / MESSAGE-INTEGRITY / response class are enforced in Transaction + protocol.
513
- if (sessionId !== this.consentSessionId || canceled) {
514
- return;
515
- }
516
- const state = this.state;
517
- if (state === "closed" || state === "failed") {
518
- return;
519
- }
520
- if (this.nominated?.id !== pairId) {
521
- return;
522
- }
523
- if (this.remoteGeneration !== generation) {
524
- return;
525
- }
526
- if (this.remotePassword !== remotePassword) {
527
- return;
528
- }
529
- const rtt = (performance.now() - requestStartedAt) / 1000; // seconds
530
- nominated.rtt = rtt;
531
- nominated.totalRoundTripTime += rtt;
532
- nominated.roundTripTimeMeasurements++;
533
- nominated.responsesReceived++;
534
- this.consentFresh = true;
535
- refreshConsentExpiry();
536
- if (state === "disconnected") {
537
- this.setState("connected");
538
- }
539
- })
540
- .catch((error) => {
541
- // Individual request loss is expected; keep monitoring (RFC 7675).
542
- if (sessionId === this.consentSessionId &&
543
- this.nominated?.id === pairId) {
544
- log("no stun response", error);
545
- }
546
- });
547
- }
548
- }
549
- catch (error) {
550
- // Abort during delay is normal on cancel / expire.
551
- }
552
- finally {
553
- if (sessionId === this.consentSessionId) {
554
- clearConsentExpiry();
555
- }
556
- }
557
- });
558
- this.queryConsentHandle = handle;
559
- }
591
+ value: new common_1.Event()
560
592
  });
561
593
  Object.defineProperty(this, "send", {
562
594
  enumerable: true,
@@ -595,8 +627,13 @@ class Connection {
595
627
  const result = {};
596
628
  const { remotePassword, remoteUsername, generation } = this;
597
629
  const localUsername = pair.localCandidate.ufrag ?? this.localUsername;
598
- // TCP pairs use regular nomination (see nominateTcpPairIfReady).
599
- const nominate = this.iceControlling && !this.remoteIsLite && !this.isTcpPair(pair);
630
+ // Semi-aggressive nomination: USE-CANDIDATE while nothing is selected
631
+ // and for a pair that outranks the selected one. Regular nomination
632
+ // (RegularNomination) and renomination (`SelectionReplacement.evaluate`) nominate
633
+ // with a separate check; an ordinary check carries nothing.
634
+ const nominate = this.usesSemiAggressiveNomination() &&
635
+ this.replacesWith(pair) &&
636
+ (!this.nominated || this.outranks(pair, this.nominated));
600
637
  const request = this.buildRequest({
601
638
  nominate,
602
639
  localUsername,
@@ -631,6 +668,7 @@ class Connection {
631
668
  // A cancelled check (its handle resolved, or the agent closed and
632
669
  // cancelled its transactions) changes nothing.
633
670
  if (signal.aborted || error instanceof exceptions_1.TransactionCancelled) {
671
+ this.checkCancelled(pair, remoteGeneration);
634
672
  r();
635
673
  return;
636
674
  }
@@ -677,16 +715,19 @@ class Connection {
677
715
  return;
678
716
  }
679
717
  // # success
680
- if (nominate || pair.remoteNominated) {
681
- // # nominated by agressive nomination or the remote party
718
+ // The peer's USE-CANDIDATE selects the pair only while this agent is
719
+ // controlled: one received before a role switch made it controlling is
720
+ // not a nomination any more (the peer is controlled now and waits for
721
+ // this agent's USE-CANDIDATE), so it nominates by itself below.
722
+ if (pair.remoteNominated && !this.iceControlling) {
723
+ // # nominated by the remote party
682
724
  pair.nominated = true;
683
725
  }
684
- else if (this.usesTcpRegularNomination(pair)) {
685
- // # nominated later by nominateTcpPairIfReady (from checkComplete)
686
- }
687
- else if (this.iceControlling && !this.nominating) {
688
- // # perform regular nomination
689
- this.nominating = true;
726
+ else if (this.iceControlling &&
727
+ this.remoteIsLite &&
728
+ !this.liteNominating) {
729
+ // # ICE-lite peer: nominate the first pair that succeeds
730
+ this.liteNominating = true;
690
731
  const request = this.buildRequest({
691
732
  nominate: true,
692
733
  localUsername,
@@ -708,7 +749,7 @@ class Connection {
708
749
  r();
709
750
  return;
710
751
  }
711
- this.nominating = false;
752
+ this.liteNominating = false;
712
753
  pair.updateState(iceBase_1.CandidatePairState.FAILED);
713
754
  this.checkComplete(pair);
714
755
  r();
@@ -720,6 +761,12 @@ class Connection {
720
761
  }
721
762
  pair.nominated = true;
722
763
  }
764
+ else if (nominate &&
765
+ this.iceControlling &&
766
+ this.remoteGeneration === remoteGeneration) {
767
+ // # semi-aggressive: the check that succeeded carried USE-CANDIDATE
768
+ pair.nominated = true;
769
+ }
723
770
  pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
724
771
  this.checkComplete(pair);
725
772
  r();
@@ -735,6 +782,7 @@ class Connection {
735
782
  }
736
783
  }
737
784
  });
785
+ this._iceControlling = _iceControlling;
738
786
  this.closedSignal = new Promise((resolve) => {
739
787
  this.signalClosed = resolve;
740
788
  });
@@ -759,40 +807,51 @@ class Connection {
759
807
  * Link headers) and must take effect before the next gather pass.
760
808
  */
761
809
  setIceServers(options) {
762
- // Explicitly assign server fields even when undefined so a STUN-only
763
- // update cannot leave a previous TURN host/credential in options.
764
- this.options = {
765
- ...this.options,
766
- stunServer: options.stunServer,
767
- turnServer: options.turnServer,
768
- turnUsername: options.turnUsername,
769
- turnPassword: options.turnPassword,
770
- turnTransport: options.turnTransport,
771
- };
772
- if (options.forceTurn !== undefined) {
773
- this.options.forceTurn = options.forceTurn;
774
- }
775
- if (options.useTcp !== undefined) {
776
- this.options.useTcp = options.useTcp;
777
- }
778
- if (options.turnTlsOptions !== undefined) {
779
- this.options.turnTlsOptions = options.turnTlsOptions;
780
- }
781
- if (options.turnUdpFamily !== undefined) {
782
- this.options.turnUdpFamily = options.turnUdpFamily;
783
- }
810
+ // Server fields are assigned even when undefined, so a STUN-only update
811
+ // or an unset TLS / address-family option leaves nothing behind.
812
+ this.options = (0, iceBase_1.mergeIceServerOptions)(this.options, options);
784
813
  this.applyStunTurnServersFromOptions();
785
814
  log("Connection ice servers updated", this.options);
786
815
  }
787
816
  /**
788
- * Derive Connection.stunServer / turnServer from this.options.
817
+ * Derive Connection.stunServers / turnServers from this.options.
789
818
  * Shared by the constructor and setIceServers so both paths validate and
790
819
  * default identically.
791
820
  */
792
821
  applyStunTurnServersFromOptions() {
793
- this.stunServer =
794
- (0, iceBase_1.validateAddress)(this.options.stunServer) ?? DEFAULT_STUN_SERVER;
795
- this.turnServer = (0, iceBase_1.validateAddress)(this.options.turnServer);
822
+ const { stunServers, turnServers } = (0, iceBase_1.normalizeIceServerOptions)(this.options);
823
+ this.usesDefaultStunServer = !(stunServers.length > 0 || this.options.useDefaultStunServer === false);
824
+ this.stunServers = this.usesDefaultStunServer
825
+ ? [DEFAULT_STUN_SERVER]
826
+ : stunServers;
827
+ this.turnServers = turnServers;
828
+ }
829
+ /** @deprecated The first of {@link Connection.stunServers}. */
830
+ get stunServer() {
831
+ return this.stunServers[0];
832
+ }
833
+ /** @deprecated Replaces {@link Connection.stunServers} with this one server (none for undefined). */
834
+ set stunServer(server) {
835
+ this.stunServers = server ? [server] : [];
836
+ }
837
+ /** @deprecated The address of the first of {@link Connection.turnServers}. */
838
+ get turnServer() {
839
+ return this.turnServers[0]?.address;
840
+ }
841
+ /**
842
+ * @deprecated Replaces {@link Connection.turnServers} with this one server
843
+ * and the deprecated turnUsername / turnPassword / turnTransport options
844
+ * (none for undefined).
845
+ */
846
+ set turnServer(server) {
847
+ this.turnServers = server
848
+ ? (0, iceBase_1.normalizeIceServerOptions)({
849
+ turnServer: server,
850
+ turnUsername: this.options.turnUsername,
851
+ turnPassword: this.options.turnPassword,
852
+ turnTransport: this.options.turnTransport,
853
+ }).turnServers
854
+ : [];
796
855
  }
797
856
  get iceControlling() {
798
857
  return this._iceControlling;
@@ -842,12 +901,19 @@ class Connection {
842
901
  this.remoteCandidatesEndRequested = false;
843
902
  this.remoteResolutions.clear();
844
903
  this.localCandidatesEnd = false;
904
+ this.localCandidatesEndPromise = undefined;
845
905
  this.checksBegun = false;
906
+ this.schedulingStopped = false;
846
907
  this.state = "new";
847
908
  this.lookup?.close?.();
848
909
  this.lookup = undefined;
849
910
  this.nominated = undefined;
850
- this.nominating = false;
911
+ this.liteNominating = false;
912
+ // Taken before `provisionalChecklist.end()` drops the provisional checklist.
913
+ const hint = this.provisionalNominationHint();
914
+ this.nomination.reset();
915
+ this.selection.abort();
916
+ this.nominationHint = hint;
851
917
  this.cancelChecks();
852
918
  this.checkList = [];
853
919
  this.checkListDone = false;
@@ -864,8 +930,8 @@ class Connection {
864
930
  }
865
931
  }
866
932
  // Tear down consent timers/transactions; new credentials require a new session.
867
- this.stopConsentLifecycle();
868
- this.endProvisional();
933
+ this.consent.stop();
934
+ this.provisionalChecklist.end();
869
935
  }
870
936
  /**
871
937
  * Only the remote side restarted (new remote credentials in an answer to an
@@ -883,15 +949,18 @@ class Connection {
883
949
  this.checksBegun = false;
884
950
  this.state = "new";
885
951
  this.nominated = undefined;
886
- this.nominating = false;
952
+ this.liteNominating = false;
953
+ this.nomination.reset();
954
+ this.selection.abort();
955
+ this.nominationHint = undefined;
887
956
  this.cancelChecks();
888
957
  this.checkList = [];
889
958
  this.checkListDone = false;
890
959
  this.checkListState = new helper_1.PQueue();
891
960
  this.earlyChecks = [];
892
961
  this.earlyChecksDone = false;
893
- this.stopConsentLifecycle();
894
- this.endProvisional();
962
+ this.consent.stop();
963
+ this.provisionalChecklist.end();
895
964
  }
896
965
  /**
897
966
  * Stop the checks and nominations in flight for the checklist a restart
@@ -902,35 +971,16 @@ class Connection {
902
971
  this.remoteChecks = new AbortController();
903
972
  for (const pair of this.checkList)
904
973
  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;
974
+ this.selection.clearRetries();
913
975
  }
914
976
  /** Accept provisional checks without changing the selected current pair. */
915
- stageLocalCredentials(usernameFragment, password) {
977
+ stageLocalCredentials(usernameFragment, password, gatherOptions) {
916
978
  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
- };
979
+ this.provisionalChecklist.stage(usernameFragment, password, gatherOptions);
930
980
  }
931
981
  discardStagedLocalCredentials(usernameFragment) {
932
982
  if (this.provisional?.localUsername === usernameFragment) {
933
- this.endProvisional();
983
+ this.provisionalChecklist.end();
934
984
  }
935
985
  if (usernameFragment !== this.localUsername) {
936
986
  delete this.userHistory[usernameFragment];
@@ -938,269 +988,17 @@ class Connection {
938
988
  }
939
989
  /** Remote credentials of the provisional generation (pranswer). */
940
990
  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;
991
+ this.provisionalChecklist.setRemoteParams({ usernameFragment, password });
962
992
  }
963
993
  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
- }
994
+ await this.provisionalChecklist.addRemoteCandidate(remoteCandidate);
1026
995
  }
1027
996
  /** Start checks for the provisional generation; the selected pair is kept. */
1028
997
  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
- }
998
+ this.provisionalChecklist.start();
1041
999
  }
1042
1000
  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
- }
1001
+ return this.provisionalChecklist.nominated;
1204
1002
  }
1205
1003
  /** Called after restart, before re-gathering the chosen generation. */
1206
1004
  commitLocalCredentials(usernameFragment, password) {
@@ -1230,13 +1028,25 @@ class Connection {
1230
1028
  pair.handle?.resolve?.();
1231
1029
  }
1232
1030
  this.checkList = this.checkList.filter((pair) => !stale(pair.remoteCandidate));
1031
+ this.nomination.evaluate();
1233
1032
  }
1234
1033
  resetNominatedPair() {
1235
1034
  log("resetNominatedPair");
1236
1035
  this.nominated = undefined;
1237
- this.nominating = false;
1036
+ this.liteNominating = false;
1037
+ this.nomination.reset();
1038
+ this.selection.abort();
1039
+ this.nominationHint = undefined;
1238
1040
  // Drop old pair's consent timers/transactions; restarted when a new pair is nominated.
1239
- this.stopConsentLifecycle();
1041
+ this.consent.stop();
1042
+ }
1043
+ get remoteIce2() {
1044
+ return this.remoteIceOptions.includes("ice2");
1045
+ }
1046
+ setRemoteIceOptions(options) {
1047
+ log("setRemoteIceOptions", options);
1048
+ this.remoteIceOptions = [...options];
1049
+ this.remoteRenomination = options.includes("renomination");
1240
1050
  }
1241
1051
  setRemoteParams({ iceLite, usernameFragment, password, }) {
1242
1052
  log("setRemoteParams", { iceLite, usernameFragment, password });
@@ -1261,17 +1071,34 @@ class Connection {
1261
1071
  // An ICE restart allocates TURN afresh, which is how a restart recovers
1262
1072
  // from an allocation that died: the previous one leaves the generation.
1263
1073
  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()));
1074
+ // The generation keeps only the sockets a fresh gathering with the
1075
+ // current options would open: a relay-only policy or useTcp turned off
1076
+ // since the previous generation closes the kept host (UDP / TCP)
1077
+ // sockets, so they are neither advertised, paired nor reachable.
1078
+ const excluded = this.protocols.filter((protocol) => !previousTurn.includes(protocol) &&
1079
+ !!protocol.localCandidate &&
1080
+ !(0, iceBase_1.isCandidateAllowedByGatherOptions)(protocol.localCandidate, this.options));
1081
+ this.protocols = this.protocols.filter((protocol) => !previousTurn.includes(protocol) && !excluded.includes(protocol));
1082
+ void Promise.allSettled([...previousTurn, ...excluded].map((protocol) => protocol.close()));
1266
1083
  // ICE restart keeps transport protocols; re-advertise their host candidates
1267
1084
  // with the new generation / ufrag before gathering additional addresses.
1085
+ for (const [family, wildcard] of this.gatherer.wildcardProtocols) {
1086
+ if (!this.protocols.includes(wildcard)) {
1087
+ // Closed with the excluded sockets, or still opening for the
1088
+ // replaced generation: a fresh one is opened if needed.
1089
+ this.gatherer.wildcardProtocols.delete(family);
1090
+ }
1091
+ }
1268
1092
  for (const protocol of this.protocols) {
1269
1093
  if (protocol.localCandidate) {
1270
1094
  protocol.localCandidate.generation = this.generation;
1271
1095
  protocol.localCandidate.ufrag = this.localUsername;
1272
- this.appendLocalCandidate(protocol.localCandidate);
1273
- const reflexive = this.reflexiveBySocket.get(protocol);
1274
- if (reflexive) {
1096
+ // A wildcard socket's local candidate is one of its
1097
+ // server-reflexive candidates, re-advertised below.
1098
+ if (!this.gatherer.isWildcardProtocol(protocol)) {
1099
+ this.appendLocalCandidate(protocol.localCandidate);
1100
+ }
1101
+ for (const reflexive of this.gatherer.reflexiveBySocket.get(protocol) ?? []) {
1275
1102
  this.appendLocalCandidate(this.withGeneration(reflexive));
1276
1103
  }
1277
1104
  }
@@ -1279,27 +1106,54 @@ class Connection {
1279
1106
  // A family bound to an explicit interface address gathers only that
1280
1107
  // address, so the advertised host candidate is the socket's address.
1281
1108
  const address = (0, resolveHostAddresses_1.resolveHostAddresses)({
1282
- enumerated: (0, utils_1.getHostAddresses)(this.options.useIpv4, this.options.useIpv6, {
1109
+ enumerated: (0, hostInterfaces_1.getHostInterfaceAddresses)(this.options.useIpv4, this.options.useIpv6, {
1283
1110
  useLinkLocalAddress: this.options.useLinkLocalAddress,
1284
1111
  }),
1112
+ assigned: (0, hostInterfaces_1.getAssignedInterfaceAddresses)(),
1285
1113
  interfaceAddresses: this.options.interfaceAddresses,
1286
1114
  additionalHostAddresses: this.options.additionalHostAddresses,
1287
1115
  useIpv4: this.options.useIpv4,
1288
1116
  useIpv6: this.options.useIpv6,
1289
1117
  log,
1290
1118
  });
1291
- const candidatePromises = this.getCandidatePromises(address, this.options.stunGatherTimeout, generation);
1119
+ // The default-route address of each family: the source address of the
1120
+ // route to the configured STUN / TURN servers (none without one: no
1121
+ // other address is probed). Its host candidate gets the highest local preference, and its
1122
+ // socket is a representative of the family's server-reflexive queries.
1123
+ // Probed while the sockets bind: no server work waits for it.
1124
+ const defaultRoutes = Promise.race([
1125
+ (0, defaultRoute_1.getDefaultRouteAddresses)(this.options.useIpv4, this.options.useIpv6, [
1126
+ ...this.stunServers.map(([host]) => host),
1127
+ ...this.turnServers.map(({ address: [host] }) => host),
1128
+ ]),
1129
+ this.closedSignal.then(() => []),
1130
+ ]);
1131
+ const { primary, background } = this.gatherer.candidatePromises(address, this.options.stunGatherTimeout, generation, defaultRoutes);
1292
1132
  // close() ends the gathering at once: the continuations above close
1293
1133
  // whatever a server query still opens for a closed agent.
1294
- await Promise.race([
1295
- Promise.allSettled(candidatePromises),
1296
- this.closedSignal,
1297
- ]);
1134
+ await Promise.race([Promise.allSettled(primary), this.closedSignal]);
1298
1135
  // A later ICE restart (or close) owns the agent now: this gathering
1299
1136
  // neither completes that generation nor touches its state.
1300
1137
  if (!this.isGathering(generation))
1301
1138
  return;
1302
- this.localCandidatesEnd = true;
1139
+ const pending = background.filter(({ settled }) => !settled);
1140
+ if (pending.length === 0) {
1141
+ this.localCandidatesEnd = true;
1142
+ }
1143
+ else {
1144
+ // The other host sockets' server-reflexive candidates trickle in;
1145
+ // end-of-candidates follows the last of them.
1146
+ this.localCandidatesEndPromise = Promise.race([
1147
+ Promise.allSettled(pending.map(({ query }) => query)),
1148
+ this.closedSignal,
1149
+ ]).then(() => {
1150
+ if (!this.isGathering(generation))
1151
+ return;
1152
+ this.localCandidatesEnd = true;
1153
+ if (this.checksBegun)
1154
+ this.concludeCheckListIfExhausted();
1155
+ });
1156
+ }
1303
1157
  }
1304
1158
  // Gathering that finishes after connectivity checks began (an ICE restart
1305
1159
  // keeps gathering from its servers) must not overwrite their state: the
@@ -1307,6 +1161,17 @@ class Connection {
1307
1161
  if (this.state === "new" && !this.checksBegun)
1308
1162
  this.setState("completed");
1309
1163
  }
1164
+ /**
1165
+ * Resolves when the current generation's gathering has ended
1166
+ * (`localCandidatesEnd`): {@link Connection.gatherCandidates} returns once
1167
+ * the host sockets, the TURN allocations and the representative socket's
1168
+ * server-reflexive query are done, while the other host sockets' queries
1169
+ * continue and trickle through `onIceCandidate`. Also resolves when the
1170
+ * agent closes or restarts (the generation ends without its end).
1171
+ */
1172
+ async waitForLocalCandidatesEnd() {
1173
+ await this.localCandidatesEndPromise;
1174
+ }
1310
1175
  /**
1311
1176
  * Whether gathering started for `generation` still belongs to the agent:
1312
1177
  * no ICE restart replaced the generation and the agent is not closed.
@@ -1320,22 +1185,76 @@ class Connection {
1320
1185
  }
1321
1186
  /** Whether gathering contacts a STUN or TURN server (more than re-advertising sockets). */
1322
1187
  get gathersFromServers() {
1323
- return !!this.stunServer || !!this.turnServer;
1188
+ return this.stunServers.length > 0 || this.turnServers.length > 0;
1324
1189
  }
1325
1190
  appendLocalCandidate(candidate) {
1326
1191
  this.localCandidates.push(candidate);
1327
1192
  this.onIceCandidate.execute(candidate);
1328
1193
  }
1194
+ /**
1195
+ * Report a failed STUN query / TURN allocation of the gathering whose
1196
+ * `stale` is given (see onIceCandidateError). A failure that is not
1197
+ * reported (cancelled), belongs to a replaced generation or arrives after
1198
+ * close is dropped. A listener that throws does not stop the gathering.
1199
+ */
1200
+ emitCandidateError(stale, generation, server, failure, local) {
1201
+ if (!failure || stale() || this.closing.signal.aborted)
1202
+ return;
1203
+ const info = {
1204
+ server,
1205
+ ...(local ? { address: local.address, port: local.port } : {}),
1206
+ errorCode: failure.errorCode,
1207
+ errorText: failure.errorText,
1208
+ generation,
1209
+ };
1210
+ log("ice candidate error", {
1211
+ server: { ...server, urls: undefined },
1212
+ errorCode: info.errorCode,
1213
+ errorText: info.errorText,
1214
+ });
1215
+ try {
1216
+ this.onIceCandidateError.execute(info);
1217
+ }
1218
+ catch (error) {
1219
+ log("onIceCandidateError listener threw", error);
1220
+ }
1221
+ }
1222
+ /** Report that `server` answered the gathering whose `stale` is given. */
1223
+ emitServerReached(stale, generation, server) {
1224
+ if (stale() || this.closing.signal.aborted)
1225
+ return;
1226
+ try {
1227
+ this.onIceServerReached.execute({ server, generation });
1228
+ }
1229
+ catch (error) {
1230
+ log("onIceServerReached listener threw", error);
1231
+ }
1232
+ }
1329
1233
  ensureProtocol(protocol) {
1330
1234
  protocol.onRequestReceived.subscribe((msg, addr, data) => {
1331
1235
  if (msg.messageMethod !== const_1.methods.BINDING) {
1332
1236
  this.respondError(msg, addr, protocol, [400, "Bad Request"]);
1333
1237
  return;
1334
1238
  }
1239
+ // The MESSAGE-INTEGRITY / MESSAGE-INTEGRITY-SHA256 of an incoming check
1240
+ // is not verified here (parseMessage(data, localPassword) would do it):
1241
+ // rejecting unverifiable checks with 401 (RFC 8445 §7.3, RFC 8489
1242
+ // §9.1.3) changes established behavior and is tracked separately.
1335
1243
  const txUsername = msg.getAttributeValue("USERNAME");
1336
1244
  // 相手にとってのremoteは自分にとってのlocal
1337
- const { remoteUsername: localUsername } = decodeTxUsername(txUsername);
1245
+ const { remoteUsername: localUsername } = (0, checkMessages_1.decodeTxUsername)(txUsername);
1338
1246
  const localPassword = this.userHistory[localUsername] ?? this.localPassword;
1247
+ // A check for the staged generation on a socket it drops at the commit
1248
+ // (a host socket under a relay-only policy, a TURN allocation whose
1249
+ // server was removed or replaced) is not answered: the socket is not
1250
+ // part of that generation.
1251
+ const staged = this.provisional;
1252
+ if (staged &&
1253
+ localUsername === staged.localUsername &&
1254
+ localUsername !== this.localUsername &&
1255
+ !this.provisionalChecklist.allows(staged, protocol)) {
1256
+ return;
1257
+ }
1339
1258
  const { iceControlling } = this;
1340
1259
  // 7.2.1.1. Detecting and Repairing Role Conflicts
1341
1260
  if (iceControlling && msg.attributesKeys.includes("ICE-CONTROLLING")) {
@@ -1367,7 +1286,7 @@ class Connection {
1367
1286
  const response = new message_1.Message(const_1.methods.BINDING, const_1.classes.RESPONSE, msg.transactionId);
1368
1287
  response
1369
1288
  .setAttribute("XOR-MAPPED-ADDRESS", addr)
1370
- .addMessageIntegrity(Buffer.from(localPassword, "utf8"))
1289
+ .addIntegrity(Buffer.from(localPassword, "utf8"), (0, checkMessages_1.responseIntegrityMode)(msg))
1371
1290
  .addFingerprint();
1372
1291
  protocol.sendStun(response, addr).catch((e) => {
1373
1292
  log("sendStun error", e);
@@ -1376,7 +1295,7 @@ class Connection {
1376
1295
  if (provisional &&
1377
1296
  localUsername === provisional.localUsername &&
1378
1297
  localUsername !== this.localUsername) {
1379
- this.checkIncomingProvisional(provisional, msg, addr, protocol);
1298
+ this.provisionalChecklist.checkIncoming(provisional, msg, addr, protocol);
1380
1299
  return;
1381
1300
  }
1382
1301
  if (this.checkList.length === 0 && !this.earlyChecksDone) {
@@ -1386,7 +1305,7 @@ class Connection {
1386
1305
  this.checkIncoming(msg, addr, protocol);
1387
1306
  }
1388
1307
  });
1389
- protocol.onDataReceived.subscribe((data) => {
1308
+ protocol.onDataReceived.subscribe((data, addr) => {
1390
1309
  try {
1391
1310
  // Update statistics for the nominated pair
1392
1311
  const activePair = this.nominated;
@@ -1394,6 +1313,9 @@ class Connection {
1394
1313
  activePair.packetsReceived++;
1395
1314
  activePair.bytesReceived += data.length;
1396
1315
  }
1316
+ if (!this.iceControlling && addr) {
1317
+ this.selection.controlledDataReceived(protocol, addr);
1318
+ }
1397
1319
  this.onData.execute(data);
1398
1320
  }
1399
1321
  catch (error) {
@@ -1421,248 +1343,9 @@ class Connection {
1421
1343
  return;
1422
1344
  }
1423
1345
  log("selected tcp connection closed", nominated.toJSON());
1424
- this.stopConsentLifecycle();
1346
+ this.consent.stop();
1425
1347
  this.setState("failed");
1426
1348
  }
1427
- getCandidatePromises(addresses, timeout = 5, generation = this.generation) {
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);
1433
- const { stunServer, turnServer } = this;
1434
- const { turnUsername, turnPassword, interfaceAddresses } = this.options;
1435
- const gatherIceLite = this.iceLite;
1436
- const gatherRelayOnly = !gatherIceLite &&
1437
- this.options.forceTurn &&
1438
- turnServer &&
1439
- turnUsername &&
1440
- turnPassword;
1441
- addresses = addresses.filter((address) => {
1442
- // ice restartで同じアドレスが追加されるのを防ぐ
1443
- if (this.protocols.find((protocol) => protocol.localIp === address)) {
1444
- return false;
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
- }
1455
- return true;
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");
1463
- const localStunPromises = gatherRelayOnly
1464
- ? []
1465
- : addresses.map(async (address) => {
1466
- // # create transport
1467
- const protocol = new protocol_1.StunProtocol();
1468
- this.ensureProtocol(protocol);
1469
- const boundInterface = (0, common_1.interfaceAddress)(socketTypeOf(address), interfaceAddresses);
1470
- try {
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;
1490
- this.protocols.push(protocol);
1491
- log("protocol", protocol.localIp);
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);
1493
- this.pairLocalProtocol(protocol);
1494
- this.appendLocalCandidate(protocol.localCandidate);
1495
- return protocol;
1496
- }
1497
- catch (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
- }
1506
- }
1507
- });
1508
- if (!gatherRelayOnly) {
1509
- candidatePromises.push(...localStunPromises.map((localPromise) => localPromise.then((protocol) => protocol?.localCandidate)));
1510
- }
1511
- if (!gatherRelayOnly && this.options.useTcp) {
1512
- const tcpCandidatePromises = addresses.map(async (address) => {
1513
- // Passive candidates open a listening TCP server; skip them when the
1514
- // agent only makes outbound connections (tcpPassive === false). Active
1515
- // candidates below still dial out, so direct TCP egress is unaffected.
1516
- if (this.options.tcpPassive !== false) {
1517
- const passiveProtocol = new tcpProtocol_1.TcpPassiveProtocol();
1518
- this.ensureProtocol(passiveProtocol);
1519
- await passiveProtocol.connectionMade(address, this.options.portRange);
1520
- if (stale()) {
1521
- await passiveProtocol.close();
1522
- return;
1523
- }
1524
- passiveProtocol.localIp = address;
1525
- passiveProtocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("host", "tcp", address), 1, "tcp", (0, candidate_1.candidatePriority)("host", {
1526
- transport: "tcp",
1527
- tcptype: "passive",
1528
- }), address, passiveProtocol.listeningPort, "host", undefined, undefined, "passive", this.generation, this.localUsername);
1529
- this.protocols.push(passiveProtocol);
1530
- this.appendLocalCandidate(passiveProtocol.localCandidate);
1531
- }
1532
- if (!gatherIceLite) {
1533
- const activeProtocol = new tcpProtocol_1.TcpActiveProtocol();
1534
- this.ensureProtocol(activeProtocol);
1535
- await activeProtocol.connectionMade(address);
1536
- if (stale()) {
1537
- await activeProtocol.close();
1538
- return;
1539
- }
1540
- activeProtocol.localIp = address;
1541
- activeProtocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("host", "tcp", address), 1, "tcp", (0, candidate_1.candidatePriority)("host", {
1542
- transport: "tcp",
1543
- tcptype: "active",
1544
- }), address, 9, "host", undefined, undefined, "active", this.generation, this.localUsername);
1545
- this.protocols.push(activeProtocol);
1546
- this.pairLocalProtocol(activeProtocol);
1547
- this.appendLocalCandidate(activeProtocol.localCandidate);
1548
- }
1549
- });
1550
- candidatePromises.push(...tcpCandidatePromises);
1551
- }
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);
1578
- const stunCandidatePromises = localStunPromises.map(async (protocolPromise) => {
1579
- const protocol = await protocolPromise;
1580
- if (!protocol)
1581
- return;
1582
- const stunCandidatePromise = new Promise(async (r, f) => {
1583
- const timer = setTimeout(f, timeout * 1000);
1584
- if (protocol.localCandidate?.host &&
1585
- (0, net_1.isIPv4)(protocol.localCandidate?.host)) {
1586
- const candidate = await (0, iceBase_1.serverReflexiveCandidate)(protocol, stunServer).catch((error) => {
1587
- log("error", error);
1588
- });
1589
- if (candidate && !stale()) {
1590
- this.reflexiveBySocket.set(protocol, candidate);
1591
- this.appendLocalCandidate(candidate);
1592
- }
1593
- clearTimeout(timer);
1594
- r(candidate);
1595
- }
1596
- else {
1597
- clearTimeout(timer);
1598
- r();
1599
- }
1600
- }).catch((error) => {
1601
- log("query STUN server", error);
1602
- });
1603
- return stunCandidatePromise;
1604
- });
1605
- candidatePromises.push(...stunCandidatePromises);
1606
- }
1607
- if (!gatherIceLite && turnServer && turnUsername && turnPassword) {
1608
- const turnCandidatePromise = (async () => {
1609
- const turnTransport = this.options.turnTransport ?? "udp";
1610
- const protocol = await (0, protocol_2.createStunOverTurnClient)({
1611
- address: turnServer,
1612
- username: turnUsername,
1613
- password: turnPassword,
1614
- }, {
1615
- portRange: this.options.portRange,
1616
- interfaceAddresses: this.options.interfaceAddresses,
1617
- transport: turnTransport,
1618
- tlsOptions: this.options.turnTlsOptions,
1619
- connectTimeoutMs: (this.options.turnConnectTimeout ?? 8) * 1000,
1620
- udpFamily: this.options.turnUdpFamily,
1621
- signal: this.closing.signal,
1622
- }).catch(async (e) => {
1623
- // close() cancelled the allocation: no TCP fallback.
1624
- if (turnTransport === "udp" && !this.closing.signal.aborted) {
1625
- return await (0, protocol_2.createStunOverTurnClient)({
1626
- address: turnServer,
1627
- username: turnUsername,
1628
- password: turnPassword,
1629
- }, {
1630
- portRange: this.options.portRange,
1631
- interfaceAddresses: this.options.interfaceAddresses,
1632
- transport: "tcp",
1633
- connectTimeoutMs: (this.options.turnConnectTimeout ?? 8) * 1000,
1634
- signal: this.closing.signal,
1635
- });
1636
- }
1637
- else {
1638
- throw e;
1639
- }
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
- }
1647
- this.ensureProtocol(protocol);
1648
- this.protocols.push(protocol);
1649
- const candidateAddress = protocol.turn.relayedAddress;
1650
- const relatedAddress = protocol.turn.mappedAddress;
1651
- log("turn candidateAddress", candidateAddress);
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);
1657
- this.appendLocalCandidate(protocol.localCandidate);
1658
- return protocol.localCandidate;
1659
- })().catch((error) => {
1660
- log("query TURN server", error);
1661
- });
1662
- candidatePromises.push(turnCandidatePromise);
1663
- }
1664
- return candidatePromises;
1665
- }
1666
1349
  async connect() {
1667
1350
  // """
1668
1351
  // Perform ICE handshake.
@@ -1695,6 +1378,8 @@ class Connection {
1695
1378
  }
1696
1379
  this.earlyChecks = [];
1697
1380
  this.earlyChecksDone = true;
1381
+ // Arms the wait for a preferred pair even while the checklist is empty.
1382
+ this.nomination.evaluate();
1698
1383
  if (this.iceLite) {
1699
1384
  if (!this.nominated) {
1700
1385
  let res = iceBase_1.ICE_FAILED;
@@ -1717,25 +1402,42 @@ class Connection {
1717
1402
  for (;;) {
1718
1403
  if (this.state === "closed")
1719
1404
  break;
1405
+ // A selection that may still be replaced: the checks of the pairs that
1406
+ // outrank it go on in `SelectionReplacement.checkOutrankingPairs`.
1407
+ if (this.nominated && this.iceControlling && this.replacesSelection()) {
1408
+ break;
1409
+ }
1720
1410
  if (!this.schedulingChecks())
1721
1411
  break;
1722
1412
  await timers.setTimeout(20);
1723
1413
  }
1414
+ this.schedulingStopped = true;
1724
1415
  // # wait for completion
1725
1416
  let res = iceBase_1.ICE_FAILED;
1726
- while (this.checkList.length > 0 && res === iceBase_1.ICE_FAILED) {
1417
+ // The nomination may still wait for a pair an incoming check forms
1418
+ // (`NominationHint`), even with an empty checklist.
1419
+ while ((this.checkList.length > 0 || this.nomination.waiting) &&
1420
+ res === iceBase_1.ICE_FAILED) {
1727
1421
  res = await this.checkListState.get();
1728
1422
  log("checkListState", res);
1729
1423
  }
1730
1424
  // # cancel remaining checks
1425
+ // (but those of pairs that may still replace the selection)
1426
+ const selected = this.nominated;
1427
+ const keepsChecking = !!selected && this.iceControlling && this.replacesSelection();
1731
1428
  for (const check of this.checkList) {
1429
+ if (keepsChecking &&
1430
+ this.replacesWith(check) &&
1431
+ this.outranks(check, selected)) {
1432
+ continue;
1433
+ }
1732
1434
  check.handle?.resolve?.();
1733
1435
  }
1734
1436
  if (res !== iceBase_1.ICE_COMPLETED) {
1735
1437
  throw new Error("ICE negotiation failed");
1736
1438
  }
1737
1439
  // # start consent freshness tests
1738
- this.queryConsent();
1440
+ this.consent.start();
1739
1441
  this.setState("connected");
1740
1442
  }
1741
1443
  unfreezeInitial() {
@@ -1764,7 +1466,7 @@ class Connection {
1764
1466
  // # find the highest-priority pair that is in the waiting state
1765
1467
  const pair = this.checkList
1766
1468
  .filter((pair) => {
1767
- if (this.options.forceTurn &&
1469
+ if ((0, iceBase_1.isRelayOnlyGathering)(this.options) &&
1768
1470
  pair.protocol.type === protocol_1.StunProtocol.type)
1769
1471
  return false;
1770
1472
  return true;
@@ -1792,30 +1494,30 @@ class Connection {
1792
1494
  return false;
1793
1495
  }
1794
1496
  /**
1795
- * Stop consent request cadence, expiry timer, and outstanding transactions.
1796
- * Does not change ICE state by itself.
1497
+ * Mirror libwebrtc semi-aggressive nomination (not required by RFC 7675):
1498
+ * attach USE-CANDIDATE to consent checks of the selected pair when we are
1499
+ * controlling and the remote is ICE-lite, or we nominate semi-aggressively
1500
+ * (a peer that became controlled after a role conflict, or lost the
1501
+ * nominating response, learns the selection from them).
1797
1502
  */
1798
- stopConsentLifecycle() {
1799
- this.consentSessionId++;
1800
- this.consentFresh = false;
1801
- if (this.consentExpiryTimer !== undefined) {
1802
- clearTimeout(this.consentExpiryTimer);
1803
- this.consentExpiryTimer = undefined;
1804
- }
1805
- this.consentRequestAbort?.abort();
1806
- this.consentRequestAbort = undefined;
1807
- const handle = this.queryConsentHandle;
1808
- this.queryConsentHandle = undefined;
1809
- // Resolve after clearing the field so a stale onCancel cannot wipe a replacement.
1810
- handle?.resolve?.();
1503
+ shouldNominateConsentRequest(pair) {
1504
+ return (this.iceControlling &&
1505
+ this.nominated?.id === pair.id &&
1506
+ (this.remoteIsLite || this.usesSemiAggressiveNomination()));
1811
1507
  }
1812
1508
  /**
1813
- * ICE-lite interop only (not required by RFC 7675): mirror libwebrtc
1814
- * semi-aggressive nomination — attach USE-CANDIDATE when we are controlling,
1815
- * the remote is ICE-lite, and the target is the current selected pair.
1509
+ * Renomination: the NOMINATION value consent checks of the selected pair
1510
+ * carry, so the peer keeps (or learns) the selection. A pair selected
1511
+ * without a renomination of this agent (the peer nominated it while this
1512
+ * agent was controlled) takes the next value.
1816
1513
  */
1817
- shouldNominateConsentRequest(pair) {
1818
- return (this.iceControlling && this.remoteIsLite && this.nominated?.id === pair.id);
1514
+ consentNomination(pair) {
1515
+ if (!this.usesRenomination() || this.nominated?.id !== pair.id) {
1516
+ return undefined;
1517
+ }
1518
+ if (pair.nomination === 0)
1519
+ pair.nomination = this.selection.nextNominationValue();
1520
+ return pair.nomination;
1819
1521
  }
1820
1522
  canSendApplicationData() {
1821
1523
  if (!this.nominated) {
@@ -1828,36 +1530,27 @@ class Connection {
1828
1530
  if (this.iceLite) {
1829
1531
  return true;
1830
1532
  }
1831
- return this.consentFresh;
1832
- }
1833
- abortableDelay(ms, signal) {
1834
- return new Promise((resolve, reject) => {
1835
- if (signal.aborted) {
1836
- reject(new DOMException("The operation was aborted", "AbortError"));
1837
- return;
1838
- }
1839
- const timer = setTimeout(() => {
1840
- signal.removeEventListener("abort", onAbort);
1841
- resolve();
1842
- }, ms);
1843
- const onAbort = () => {
1844
- clearTimeout(timer);
1845
- reject(new DOMException("The operation was aborted", "AbortError"));
1846
- };
1847
- signal.addEventListener("abort", onAbort, { once: true });
1848
- });
1533
+ return this.consent.fresh;
1849
1534
  }
1850
1535
  async close() {
1851
1536
  // """
1852
1537
  // Close the connection.
1853
1538
  // """
1539
+ this.closed = true;
1854
1540
  this.setState("closed");
1541
+ this.onIceCandidateError.complete();
1542
+ this.onIceServerReached.complete();
1855
1543
  this.signalClosed();
1856
1544
  this.closing.abort();
1857
1545
  this.cancelChecks();
1858
- this.endProvisional();
1546
+ this.provisionalChecklist.end();
1547
+ // Before the first await: a pending mDNS lookup is cancelled here, so no
1548
+ // response arriving while the protocols close adds a remote candidate.
1549
+ this.lookup?.close?.();
1550
+ this.lookup = undefined;
1551
+ this.remoteResolutions.clear();
1859
1552
  // # stop consent freshness tests
1860
- this.stopConsentLifecycle();
1553
+ this.consent.stop();
1861
1554
  // # stop check list
1862
1555
  if (this.checkList && !this.checkListDone) {
1863
1556
  this.checkListState.put(new Promise((r) => {
@@ -1865,15 +1558,21 @@ class Connection {
1865
1558
  }));
1866
1559
  }
1867
1560
  this.nominated = undefined;
1868
- for (const protocol of this.protocols) {
1561
+ this.liteNominating = false;
1562
+ this.nomination.reset();
1563
+ this.selection.abort();
1564
+ this.nominationHint = undefined;
1565
+ const pendingWildcards = [
1566
+ ...this.gatherer.wildcardProtocols.values(),
1567
+ ].filter((protocol) => !this.protocols.includes(protocol));
1568
+ this.gatherer.wildcardProtocols.clear();
1569
+ for (const protocol of [...this.protocols, ...pendingWildcards]) {
1869
1570
  if (protocol.close) {
1870
1571
  await protocol.close();
1871
1572
  }
1872
1573
  }
1873
1574
  this.protocols = [];
1874
1575
  this.localCandidates = [];
1875
- this.lookup?.close?.();
1876
- this.lookup = undefined;
1877
1576
  }
1878
1577
  setState(state) {
1879
1578
  this.state = state;
@@ -1893,6 +1592,9 @@ class Connection {
1893
1592
  // To signal end-of-candidates, pass `None`.
1894
1593
  // :param remote_candidate: A :class:`Candidate` instance or `None`.
1895
1594
  // """
1595
+ // A closed agent takes no candidate (and opens no mDNS socket).
1596
+ if (this.closed)
1597
+ return;
1896
1598
  if (!remoteCandidate) {
1897
1599
  if (this.remoteCandidatesEnd || this.remoteCandidatesEndRequested) {
1898
1600
  return;
@@ -1902,10 +1604,11 @@ class Connection {
1902
1604
  if (this.remoteResolutions.size > 0) {
1903
1605
  const generation = this.remoteGeneration;
1904
1606
  await Promise.allSettled([...this.remoteResolutions]);
1905
- if (this.remoteGeneration !== generation)
1607
+ if (this.remoteGeneration !== generation || this.closed)
1906
1608
  return;
1907
1609
  }
1908
1610
  this.remoteCandidatesEnd = true;
1611
+ this.nomination.evaluate();
1909
1612
  return;
1910
1613
  }
1911
1614
  // RFC 8838: a completed generation takes no further candidates.
@@ -1930,8 +1633,10 @@ class Connection {
1930
1633
  catch (error) {
1931
1634
  return;
1932
1635
  }
1933
- // An ICE restart or completion while resolving ends this candidate's generation.
1934
- if (this.remoteGeneration !== generation || this.remoteCandidatesEnd)
1636
+ // An ICE restart, completion or close while resolving ends this candidate's generation.
1637
+ if (this.remoteGeneration !== generation ||
1638
+ this.remoteCandidatesEnd ||
1639
+ this.closed)
1935
1640
  return;
1936
1641
  }
1937
1642
  try {
@@ -1980,10 +1685,92 @@ class Connection {
1980
1685
  return pair;
1981
1686
  }
1982
1687
  applyIceControlling(iceControlling) {
1688
+ const becameControlling = !this._iceControlling && iceControlling;
1689
+ if (this._iceControlling !== iceControlling) {
1690
+ this.invalidateNominations();
1691
+ this.selection.clearRetries();
1692
+ // USE-CANDIDATE received while controlled came from a peer that was
1693
+ // controlling then; as the controlling agent this one nominates itself.
1694
+ if (iceControlling) {
1695
+ for (const pair of [
1696
+ ...this.checkList,
1697
+ ...(this.provisional?.pairs ?? []),
1698
+ ]) {
1699
+ pair.remoteNominated = false;
1700
+ pair.remoteNomination = 0;
1701
+ }
1702
+ }
1703
+ }
1983
1704
  this._iceControlling = iceControlling;
1984
1705
  for (const pair of this.checkList) {
1985
1706
  pair.iceControlling = iceControlling;
1986
1707
  }
1708
+ if (becameControlling)
1709
+ this.confirmSelections();
1710
+ }
1711
+ /**
1712
+ * The agent became controlling with a pair already selected (live or
1713
+ * provisional), e.g. one the peer nominated while this agent was
1714
+ * controlled. The selection stays (RFC 8445 §8.1.1 allows no other pair),
1715
+ * but the peer, controlled now, may still wait for a nomination: send
1716
+ * USE-CANDIDATE for that pair, repeated on timeouts as a nomination is.
1717
+ * A peer that selected the pair already keeps it.
1718
+ */
1719
+ confirmSelections() {
1720
+ if (!this.nominatesFullPeer())
1721
+ return;
1722
+ const live = this.nominated;
1723
+ if (live && this.state !== "closed" && this.checkList.includes(live)) {
1724
+ void this.confirmSelection((signal) => this.sendNomination(live, signal, this.consentNomination(live)), () => this.nominated === live && this.state !== "closed");
1725
+ }
1726
+ const generation = this.provisional;
1727
+ const provisional = generation?.nominated;
1728
+ if (generation && provisional && generation.pairs.includes(provisional)) {
1729
+ void this.confirmSelection((signal) => this.provisionalChecklist.nominate(generation, provisional, AbortSignal.any([generation.checks.signal, signal])), () => this.provisional === generation &&
1730
+ generation.nominated === provisional);
1731
+ }
1732
+ }
1733
+ async confirmSelection(send, selected) {
1734
+ const abort = new AbortController();
1735
+ this.selectionConfirmations.add(abort);
1736
+ try {
1737
+ for (let attempt = 1; attempt <= regularNomination_1.NOMINATION_ATTEMPTS; attempt++) {
1738
+ const outcome = await send(abort.signal);
1739
+ if (abort.signal.aborted || !selected() || !this.iceControlling) {
1740
+ return;
1741
+ }
1742
+ if (outcome === "unanswered")
1743
+ continue;
1744
+ // 487: the peer is controlling and wins; it nominates.
1745
+ if (outcome === "role-conflict")
1746
+ this.switchRole(false);
1747
+ return;
1748
+ }
1749
+ }
1750
+ catch (error) {
1751
+ log("confirm selection failed", error);
1752
+ }
1753
+ finally {
1754
+ this.selectionConfirmations.delete(abort);
1755
+ }
1756
+ }
1757
+ /**
1758
+ * The role changed: a nomination in flight (live or provisional) was sent
1759
+ * as the controlling agent and must not select a pair, fail one, or fail
1760
+ * the agent under the new role. Its transaction stops; a controlling agent
1761
+ * later nominates afresh.
1762
+ */
1763
+ invalidateNominations() {
1764
+ this.liteNominating = false;
1765
+ this.nomination.invalidate();
1766
+ this.selection.abort();
1767
+ for (const abort of this.selectionConfirmations)
1768
+ abort.abort();
1769
+ this.selectionConfirmations.clear();
1770
+ if (this.provisional) {
1771
+ this.provisional.liteNominating = false;
1772
+ this.provisional.nomination.invalidate();
1773
+ }
1987
1774
  }
1988
1775
  switchRole(iceControlling) {
1989
1776
  log("switch role", iceControlling);
@@ -1994,10 +1781,15 @@ class Connection {
1994
1781
  }
1995
1782
  this.applyIceControlling(iceControlling);
1996
1783
  this.sortCheckList();
1784
+ // Only a controlling agent nominates: start (or stop) waiting for it.
1785
+ this.nomination.evaluate();
1786
+ this.provisional?.nomination.evaluate();
1787
+ this.selection.evaluate();
1997
1788
  }
1998
1789
  checkComplete(pair) {
1999
1790
  pair.handle = undefined;
2000
1791
  if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
1792
+ this.selection.forgetRetry(pair);
2001
1793
  // Updating the Nominated Flag
2002
1794
  // https://www.rfc-editor.org/rfc/rfc8445#section-7.3.1.5,
2003
1795
  // Once the nominated flag is set for a component of a data stream, it
@@ -2014,28 +1806,41 @@ class Connection {
2014
1806
  this.checkList.includes(pair) &&
2015
1807
  (pair.remoteCandidate.ufrag == undefined ||
2016
1808
  pair.remoteCandidate.ufrag === this.remoteUsername) &&
2017
- this.nominated == undefined) {
2018
- log("nominated", pair.toJSON());
1809
+ // One selection, except that semi-aggressive nomination and
1810
+ // renomination replace it with a better nominated pair
1811
+ // (`SelectionReplacement.replaces`).
1812
+ (this.nominated == undefined || this.selection.replaces(pair))) {
1813
+ const previous = this.nominated;
1814
+ log(previous ? "selected pair replaced" : "nominated", pair.toJSON(), {
1815
+ previous: previous?.toJSON(),
1816
+ });
2019
1817
  this.nominated = pair;
2020
- this.nominating = false;
1818
+ this.liteNominating = false;
1819
+ this.nomination.stop();
2021
1820
  // RFC 7675 section 5.1: the successful connectivity check that
2022
1821
  // selected the pair is its initial consent, so data may flow at once
2023
1822
  // instead of waiting for the consent lifecycle to start.
2024
- this.consentFresh = true;
1823
+ this.consent.fresh = true;
2025
1824
  this.pruneTcpConnections(pair);
2026
1825
  // After resetNominatedPair / renomination while already connected,
2027
1826
  // restart consent freshness on the new selected pair.
2028
1827
  if (!this.iceLite &&
2029
1828
  (this.state === "connected" || this.state === "completed")) {
2030
- this.queryConsent();
1829
+ this.consent.start();
2031
1830
  }
2032
1831
  // 8.1.2. Updating States
2033
1832
  // The agent MUST remove all Waiting and Frozen pairs in the check
2034
1833
  // list and triggered check queue for the same component as the
2035
- // nominated pairs for that media stream.
1834
+ // nominated pairs for that media stream. A controlling agent that
1835
+ // may replace the selection keeps the pairs that outrank it.
1836
+ const keepsChecking = this.iceControlling && this.replacesSelection();
2036
1837
  for (const p of this.checkList) {
2037
1838
  if (p.component === pair.component &&
2038
- [iceBase_1.CandidatePairState.WAITING, iceBase_1.CandidatePairState.FROZEN].includes(p.state)) {
1839
+ [
1840
+ iceBase_1.CandidatePairState.WAITING,
1841
+ iceBase_1.CandidatePairState.FROZEN,
1842
+ ].includes(p.state) &&
1843
+ !(keepsChecking && this.replacesWith(p) && this.outranks(p, pair))) {
2039
1844
  p.updateState(iceBase_1.CandidatePairState.FAILED);
2040
1845
  }
2041
1846
  }
@@ -2049,6 +1854,11 @@ class Connection {
2049
1854
  this.checkListState.put(new Promise((r) => r(iceBase_1.ICE_COMPLETED)));
2050
1855
  this.checkListDone = true;
2051
1856
  }
1857
+ if (this.iceControlling && this.replacesSelection()) {
1858
+ this.selection.evaluate();
1859
+ void this.selection.checkOutrankingPairs();
1860
+ this.selection.scheduleRetries();
1861
+ }
2052
1862
  return;
2053
1863
  }
2054
1864
  log("not completed", pair.toJSON());
@@ -2060,13 +1870,28 @@ class Connection {
2060
1870
  }
2061
1871
  }
2062
1872
  }
2063
- this.nominateTcpPairIfReady();
2064
- // A nomination request is still in flight; its result decides the outcome.
2065
- if (this.nominating) {
1873
+ this.nomination.evaluate();
1874
+ this.selection.evaluate();
1875
+ this.selection.scheduleRetries();
1876
+ this.concludeCheckListIfExhausted();
1877
+ }
1878
+ /**
1879
+ * Fail the check list once no pair can succeed and no nomination can still
1880
+ * select one. Background gathering and remote trickle both delay this.
1881
+ */
1882
+ concludeCheckListIfExhausted() {
1883
+ if (this.nominated ||
1884
+ this.liteNominating ||
1885
+ this.selection.nominating ||
1886
+ this.nomination.inFlight ||
1887
+ this.nomination.waiting) {
2066
1888
  return;
2067
1889
  }
2068
1890
  {
2069
- const list = [iceBase_1.CandidatePairState.SUCCEEDED, iceBase_1.CandidatePairState.FAILED];
1891
+ const list = [
1892
+ iceBase_1.CandidatePairState.SUCCEEDED,
1893
+ iceBase_1.CandidatePairState.FAILED,
1894
+ ];
2070
1895
  if (this.checkList.find(({ state }) => !list.includes(state))) {
2071
1896
  return;
2072
1897
  }
@@ -2089,6 +1914,28 @@ class Connection {
2089
1914
  }));
2090
1915
  }
2091
1916
  }
1917
+ /**
1918
+ * A check of the live checklist cancelled before its outcome (the
1919
+ * checklist completed, `connect` cancels the remaining checks) leaves the
1920
+ * pair Waiting instead of In-Progress, so the peer's checks on it still
1921
+ * trigger one (7.2.1.4): a controlled agent that selected a lower pair can
1922
+ * then follow a later nomination of this one. A nomination already received
1923
+ * for it is checked at once (its triggering check came while the cancelled
1924
+ * one was still in flight). A generation that ended or a closed agent
1925
+ * changes nothing.
1926
+ */
1927
+ checkCancelled(pair, remoteGeneration) {
1928
+ if (pair.state !== iceBase_1.CandidatePairState.IN_PROGRESS ||
1929
+ this.state === "closed" ||
1930
+ this.remoteGeneration !== remoteGeneration ||
1931
+ !this.checkList.includes(pair)) {
1932
+ return;
1933
+ }
1934
+ pair.updateState(iceBase_1.CandidatePairState.WAITING);
1935
+ if (pair.remoteNominated && !this.iceControlling) {
1936
+ pair.handle = this.checkStart(pair);
1937
+ }
1938
+ }
2092
1939
  /**
2093
1940
  * 487 / 401 retry of a check: the retry is cancelled with the check it
2094
1941
  * replaces (its handle) and, through checkStart, with the generation.
@@ -2101,97 +1948,256 @@ class Connection {
2101
1948
  isTcpPair(pair) {
2102
1949
  return pair.localCandidate.transport.toLowerCase() === "tcp";
2103
1950
  }
2104
- /**
2105
- * Aggressive nomination lets each side settle on whichever TCP connection
2106
- * finished first; the two sides can then pick different connections and
2107
- * pruning destroys the peer's choice. For TCP the controlling agent instead
2108
- * nominates exactly one valid pair (RFC 8445 §8.1.1 regular nomination).
2109
- */
2110
- usesTcpRegularNomination(pair) {
2111
- return this.iceControlling && !this.remoteIsLite && this.isTcpPair(pair);
2112
- }
2113
1951
  checkRequestOptions(pair) {
2114
1952
  const onRequestSent = (attempt) => {
2115
1953
  if (attempt > 0) {
2116
1954
  pair.retransmissionsSent++;
2117
1955
  }
2118
1956
  };
1957
+ const integrityAlgorithm = this.options.messageIntegrity;
2119
1958
  if (this.isTcpPair(pair)) {
2120
1959
  // RFC 5389 §7.2.2: no retransmissions over a reliable transport.
2121
1960
  return {
2122
1961
  retransmissions: 0,
2123
1962
  responseTimeout: const_1.TCP_CHECK_RESPONSE_TIMEOUT_MS,
2124
1963
  onRequestSent,
1964
+ integrityAlgorithm,
2125
1965
  };
2126
1966
  }
2127
- return { retransmissions: 4, onRequestSent };
1967
+ return { retransmissions: 4, onRequestSent, integrityAlgorithm };
1968
+ }
1969
+ /** The agent is controlling and both agents are full ICE. */
1970
+ nominatesFullPeer() {
1971
+ return this.iceControlling && !this.remoteIsLite && !this.iceLite;
2128
1972
  }
2129
1973
  /**
2130
- * Controlling side: nominate the highest-priority TCP pair once every
2131
- * higher-priority TCP pair has finished its check, so the choice does not
2132
- * depend on which connection happened to complete first.
1974
+ * Both agents advertised renomination (`IceOptions.renomination`): the
1975
+ * controlling agent nominates with NOMINATION values instead of
1976
+ * USE-CANDIDATE, whatever `IceOptions.nomination` says.
2133
1977
  */
2134
- nominateTcpPairIfReady() {
2135
- if (!this.iceControlling ||
2136
- this.remoteIsLite ||
2137
- this.nominated ||
2138
- this.nominating) {
2139
- return;
2140
- }
2141
- for (const pair of this.checkList) {
2142
- if (!this.isTcpPair(pair)) {
2143
- continue;
2144
- }
2145
- if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
2146
- this.nominateTcpPair(pair);
2147
- return;
2148
- }
2149
- if (pair.state !== iceBase_1.CandidatePairState.FAILED) {
2150
- // A higher-priority pair may still succeed.
2151
- return;
1978
+ usesRenomination() {
1979
+ return (this.nominatesFullPeer() &&
1980
+ !!this.options.renomination &&
1981
+ this.remoteRenomination);
1982
+ }
1983
+ /**
1984
+ * `nomination: "regular"`: RFC 8445 §8.1.1 regular nomination for every
1985
+ * transport. A check that succeeds only makes its pair valid;
1986
+ * `RegularNomination` later picks one valid pair and nominates it once
1987
+ * with a separate USE-CANDIDATE check.
1988
+ */
1989
+ usesRegularNomination() {
1990
+ return (this.nominatesFullPeer() &&
1991
+ this.options.nomination === "regular" &&
1992
+ !this.usesRenomination());
1993
+ }
1994
+ /**
1995
+ * The default, as libwebrtc: checks carry USE-CANDIDATE until a pair is
1996
+ * selected and afterwards for pairs that outrank the selected one, so the
1997
+ * first pair that succeeds is selected at once and a higher-priority pair
1998
+ * that succeeds later (a TURN/UDP candidate trickled after a TURN/TCP one
1999
+ * connected) replaces it. A first-success-wins nomination would keep the
2000
+ * lower-priority pair for the whole session.
2001
+ */
2002
+ usesSemiAggressiveNomination() {
2003
+ return (this.nominatesFullPeer() &&
2004
+ this.options.nomination !== "regular" &&
2005
+ !this.usesRenomination());
2006
+ }
2007
+ /**
2008
+ * The controlling agent may move the selection to a higher-priority pair
2009
+ * (semi-aggressive nomination, renomination): checks of pairs that outrank
2010
+ * the selected one go on after the first selection.
2011
+ */
2012
+ replacesSelection() {
2013
+ return this.usesSemiAggressiveNomination() || this.usesRenomination();
2014
+ }
2015
+ /**
2016
+ * A pair semi-aggressive nomination and renomination may select: not an
2017
+ * ICE-TCP pair (each TCP pair is its own connection, and nominating more
2018
+ * than one could leave the agents on different connections after pruning;
2019
+ * TCP pairs keep regular nomination, see `regularNominationPairs`), nor
2020
+ * one the agent never checks (forceTurn).
2021
+ */
2022
+ replacesWith(pair) {
2023
+ return !this.isTcpPair(pair) && !this.isUncheckedPair(pair);
2024
+ }
2025
+ /**
2026
+ * The pairs `RegularNomination` nominates from: every pair with
2027
+ * `nomination: "regular"`, otherwise the ICE-TCP pairs (as before
2028
+ * semi-aggressive nomination, #721).
2029
+ */
2030
+ regularNominationPairs(pairs) {
2031
+ return this.usesRegularNomination()
2032
+ ? pairs
2033
+ : pairs.filter((pair) => this.isTcpPair(pair));
2034
+ }
2035
+ /** `IceOptions.nominationDelayMs`, or its default when unset or invalid. */
2036
+ get nominationDelayMs() {
2037
+ const delay = this.options.nominationDelayMs;
2038
+ return delay !== undefined && Number.isFinite(delay) && delay >= 0
2039
+ ? delay
2040
+ : regularNomination_1.DEFAULT_NOMINATION_DELAY_MS;
2041
+ }
2042
+ /** A pair the agent never checks itself (forceTurn keeps it from the schedule). */
2043
+ isUncheckedPair(pair) {
2044
+ return !!this.options.forceTurn && pair.protocol.type === protocol_1.StunProtocol.type;
2045
+ }
2046
+ /** The highest-priority valid pair of `pairs`. */
2047
+ bestValidPair(pairs) {
2048
+ let best;
2049
+ for (const pair of pairs) {
2050
+ if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED &&
2051
+ (!best || this.outranks(pair, best))) {
2052
+ best = pair;
2152
2053
  }
2153
2054
  }
2055
+ return best;
2056
+ }
2057
+ outranks(pair, other) {
2058
+ return ((0, iceBase_1.compareCandidatePairPriority)(pair.localCandidate, pair.remoteCandidate, other.localCandidate, other.remoteCandidate, this.iceControlling) > 0);
2059
+ }
2060
+ /**
2061
+ * The live checklist's side of regular nomination (`RegularNomination`):
2062
+ * the controlling agent nominates the best valid pair once the checklist
2063
+ * is quiet (see `decideNomination`).
2064
+ */
2065
+ liveNominationHost() {
2066
+ return {
2067
+ active: () => this.nominatesFullPeer() && !this.nominated && this.state !== "closed",
2068
+ checking: () => this.checksBegun,
2069
+ pairs: () => this.regularNominationPairs(this.checkList),
2070
+ remoteCandidatesEnd: () => this.remoteCandidatesEnd,
2071
+ localCandidatesEnd: () => this.localCandidatesEnd,
2072
+ delayMs: () => this.nominationDelayMs,
2073
+ unchecked: (pair) => this.isUncheckedPair(pair),
2074
+ outranks: (pair, other) => this.outranks(pair, other),
2075
+ preferred: () => {
2076
+ const hint = this.nominationHint;
2077
+ if (!hint ||
2078
+ // Semi-aggressive nomination and renomination may replace the
2079
+ // selection; the hint belongs to regular nomination.
2080
+ !this.usesRegularNomination() ||
2081
+ hint.localUsername !== this.localUsername ||
2082
+ hint.remoteUsername !== this.remoteUsername ||
2083
+ hint.remotePassword !== this.remotePassword ||
2084
+ // The commit closed the pair's socket (a TURN allocation an ICE
2085
+ // restart replaces, an excluded host socket): the path is gone for
2086
+ // the peer too, so the usual rules choose.
2087
+ !this.protocols.includes(hint.protocol)) {
2088
+ return undefined;
2089
+ }
2090
+ return (pair) => (0, regularNomination_1.pairKey)(pair) === hint.key;
2091
+ },
2092
+ owns: (pair) => this.state !== "closed" && this.checkList.includes(pair),
2093
+ send: (pair, signal) => this.sendNomination(pair, signal),
2094
+ nominated: (pair) => {
2095
+ pair.nominated = true;
2096
+ this.checkComplete(pair);
2097
+ },
2098
+ rejected: (pair) => {
2099
+ // The peer did not select this pair: only it fails, and
2100
+ // checkComplete nominates the next one.
2101
+ pair.updateState(iceBase_1.CandidatePairState.FAILED);
2102
+ this.checkComplete(pair);
2103
+ },
2104
+ // RFC 8445 §7.2.5.1: the peer is controlling too and wins; the
2105
+ // nomination was not accepted. Become controlled: the pair stays
2106
+ // valid and the peer nominates.
2107
+ roleConflict: () => this.switchRole(false),
2108
+ abandoned: (pair) => this.nominationAbandoned(pair),
2109
+ // The valid pair it waited for may be gone (another remote generation
2110
+ // dropped): the checklist may have failed meanwhile.
2111
+ deadlinePassed: () => this.concludeCheckListIfExhausted(),
2112
+ };
2154
2113
  }
2155
- nominateTcpPair(pair) {
2156
- this.nominating = true;
2157
- const generation = this.remoteGeneration;
2114
+ /**
2115
+ * Send the USE-CANDIDATE check for a live `pair` (see `NominationOutcome`),
2116
+ * or with `nomination` the renomination check that carries that
2117
+ * NOMINATION value instead.
2118
+ */
2119
+ async sendNomination(pair, signal, nomination) {
2158
2120
  const request = this.buildRequest({
2159
- nominate: true,
2121
+ nominate: nomination === undefined,
2122
+ nomination,
2160
2123
  localUsername: pair.localCandidate.ufrag ?? this.localUsername,
2161
2124
  remoteUsername: this.remoteUsername,
2162
2125
  iceControlling: this.iceControlling,
2163
2126
  localCandidate: pair.localCandidate,
2164
2127
  });
2165
2128
  pair.requestsSent++;
2166
- pair.protocol
2167
- .request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), { ...this.checkRequestOptions(pair), signal: this.remoteChecks.signal })
2168
- .then(() => {
2169
- if (this.isStaleNomination(pair, generation)) {
2170
- return;
2171
- }
2129
+ try {
2130
+ await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), {
2131
+ ...this.checkRequestOptions(pair),
2132
+ signal: AbortSignal.any([this.remoteChecks.signal, signal]),
2133
+ });
2172
2134
  pair.responsesReceived++;
2173
- pair.nominated = true;
2174
- this.nominating = false;
2175
- this.checkComplete(pair);
2176
- }, (error) => {
2177
- if (this.isStaleNomination(pair, generation)) {
2178
- return;
2179
- }
2180
- log("tcp nomination failed", pair.toJSON(), error);
2181
- this.nominating = false;
2182
- pair.updateState(iceBase_1.CandidatePairState.FAILED);
2183
- this.checkComplete(pair);
2184
- });
2135
+ return "nominated";
2136
+ }
2137
+ catch (error) {
2138
+ log("nomination failed", pair.toJSON(), error);
2139
+ if ((0, checkMessages_1.isRoleConflict)(error))
2140
+ return "role-conflict";
2141
+ return error instanceof exceptions_1.TransactionTimeout ? "unanswered" : "rejected";
2142
+ }
2185
2143
  }
2186
- /** The agent was closed or restarted while the nomination was in flight. */
2144
+ /**
2145
+ * No attempt of a USE-CANDIDATE check was answered, or the pair a
2146
+ * provisional nomination may have selected (`NominationHint`) failed or
2147
+ * never appeared. A request may still have reached the peer, and a
2148
+ * controlled agent keeps the first pair
2149
+ * nominated to it (RFC 8445 §8.1.1): nominating another pair could leave
2150
+ * the two agents on different pairs. The agent nominates nothing else,
2151
+ * connect() rejects and the agent fails (an ICE restart starts over), as a
2152
+ * consent expiry does.
2153
+ */
2154
+ nominationAbandoned(pair) {
2155
+ pair?.updateState(iceBase_1.CandidatePairState.FAILED);
2156
+ if (!this.checkListDone) {
2157
+ this.checkListDone = true;
2158
+ this.checkListState.put(new Promise((r) => r(regularNomination_1.ICE_NOMINATION_ABANDONED)));
2159
+ }
2160
+ this.setState("failed");
2161
+ }
2162
+ /**
2163
+ * At the restart that ends the provisional checklist (a final answer): the
2164
+ * pair it nominated, or sent a USE-CANDIDATE to that the peer did not
2165
+ * refuse (see `NominationHint`).
2166
+ */
2167
+ provisionalNominationHint() {
2168
+ const generation = this.provisional;
2169
+ const pair = generation?.nominated ?? generation?.nomination.maybeSelected;
2170
+ if (!generation?.remoteUsername || !generation.remotePassword || !pair) {
2171
+ return undefined;
2172
+ }
2173
+ return {
2174
+ localUsername: generation.localUsername,
2175
+ remoteUsername: generation.remoteUsername,
2176
+ remotePassword: generation.remotePassword,
2177
+ key: (0, regularNomination_1.pairKey)(pair),
2178
+ protocol: pair.protocol,
2179
+ };
2180
+ }
2181
+ /** The agent was closed or restarted while the ICE-lite nomination was in flight. */
2187
2182
  isStaleNomination(pair, generation) {
2188
2183
  return (this.state === "closed" ||
2189
2184
  this.remoteGeneration !== generation ||
2190
2185
  !this.checkList.includes(pair));
2191
2186
  }
2192
2187
  addPair(pair) {
2188
+ const best = this.bestValidPair(this.checkList);
2193
2189
  this.checkList.push(pair);
2194
2190
  this.sortCheckList();
2191
+ this.nomination.pairAdded(pair, best);
2192
+ // A pair that may replace the selection is checked after it too.
2193
+ const selected = this.nominated;
2194
+ if (selected &&
2195
+ this.iceControlling &&
2196
+ this.replacesSelection() &&
2197
+ this.replacesWith(pair) &&
2198
+ this.outranks(pair, selected)) {
2199
+ void this.selection.checkOutrankingPairs();
2200
+ }
2195
2201
  }
2196
2202
  // 7.2. STUN Server Procedures
2197
2203
  // 7.2.1.3、7.2.1.4、および7.2.1.5
@@ -2200,7 +2206,7 @@ class Connection {
2200
2206
  // Handle a successful incoming check.
2201
2207
  // """
2202
2208
  const txUsername = message.getAttributeValue("USERNAME");
2203
- const { remoteUsername: localUsername } = decodeTxUsername(txUsername);
2209
+ const { remoteUsername: localUsername } = (0, checkMessages_1.decodeTxUsername)(txUsername);
2204
2210
  // find remote candidate
2205
2211
  let remoteCandidate;
2206
2212
  const [host, port] = addr;
@@ -2238,9 +2244,13 @@ class Connection {
2238
2244
  remotePassword: this.remotePassword,
2239
2245
  generation: this.generation,
2240
2246
  });
2247
+ const nomination = (0, checkMessages_1.receivedNomination)(message);
2248
+ if (nomination > 0 && !this.iceControlling) {
2249
+ // We don't un-nominate a pair: keep the larger nomination.
2250
+ pair.remoteNomination = Math.max(pair.remoteNomination, nomination);
2251
+ }
2241
2252
  if (this.iceLite) {
2242
- if (message.attributesKeys.includes("USE-CANDIDATE") &&
2243
- !this.iceControlling) {
2253
+ if (nomination > 0 && !this.iceControlling) {
2244
2254
  pair.remoteNominated = true;
2245
2255
  pair.nominated = true;
2246
2256
  pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
@@ -2249,12 +2259,16 @@ class Connection {
2249
2259
  return;
2250
2260
  }
2251
2261
  // 7.2.1.4. Triggered Checks
2252
- if ([iceBase_1.CandidatePairState.WAITING, iceBase_1.CandidatePairState.FAILED].includes(pair.state)) {
2262
+ if ([
2263
+ iceBase_1.CandidatePairState.WAITING,
2264
+ iceBase_1.CandidatePairState.FAILED,
2265
+ ].includes(pair.state)) {
2253
2266
  pair.handle = this.checkStart(pair);
2254
2267
  }
2255
2268
  // 7.2.1.5. Updating the Nominated Flag
2256
- if (message.attributesKeys.includes("USE-CANDIDATE") &&
2257
- !this.iceControlling) {
2269
+ // (USE-CANDIDATE, or a NOMINATION value with renomination; a pair
2270
+ // already selected may be replaced, see `SelectionReplacement.replaces`)
2271
+ if (nomination > 0 && !this.iceControlling) {
2258
2272
  pair.remoteNominated = true;
2259
2273
  if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
2260
2274
  pair.nominated = true;
@@ -2262,7 +2276,35 @@ class Connection {
2262
2276
  }
2263
2277
  }
2264
2278
  }
2265
- tryPair(protocol, remoteCandidate) {
2279
+ /**
2280
+ * @param admit after a selection that may still be replaced, only pairs
2281
+ * that could replace it join the checklist.
2282
+ */
2283
+ tryPair(protocol, remoteCandidate, admit = this.admitsPair(), routeChecked = false) {
2284
+ if (!routeChecked && this.gatherer.isWildcardProtocol(protocol)) {
2285
+ void this.gatherer
2286
+ .wildcardPathUncovered(remoteCandidate)
2287
+ .then((uncovered) => {
2288
+ // As pairLocalProtocol: once a pair is selected (which also ends
2289
+ // the checklist) only a selection that may still be replaced
2290
+ // takes more pairs.
2291
+ const replaceable = !!this.nominated && this.iceControlling && this.replacesSelection();
2292
+ if (uncovered &&
2293
+ ((!this.nominated && !this.checkListDone) || replaceable) &&
2294
+ this.state !== "closed" &&
2295
+ this.protocols.includes(protocol) &&
2296
+ this.remoteCandidates.includes(remoteCandidate)) {
2297
+ this.tryPair(protocol, remoteCandidate, this.admitsPair(), true);
2298
+ this.sortCheckList();
2299
+ const pair = this.findPair(protocol, remoteCandidate);
2300
+ if (this.schedulingStopped &&
2301
+ pair?.state === iceBase_1.CandidatePairState.WAITING) {
2302
+ pair.handle = this.checkStart(pair);
2303
+ }
2304
+ }
2305
+ });
2306
+ return;
2307
+ }
2266
2308
  if (protocol.localCandidate?.canPairWith(remoteCandidate) &&
2267
2309
  !(protocol.localCandidate.transport.toLowerCase() === "tcp" &&
2268
2310
  protocol.localCandidate.tcptype === "passive" &&
@@ -2273,41 +2315,43 @@ class Connection {
2273
2315
  !this.options.filterCandidatePair(pair)) {
2274
2316
  return;
2275
2317
  }
2318
+ if (admit && !admit(pair))
2319
+ return;
2276
2320
  pair.updateState(iceBase_1.CandidatePairState.WAITING);
2277
2321
  this.addPair(pair);
2278
2322
  }
2279
2323
  }
2324
+ /** See `tryPair`: undefined admits every pair. */
2325
+ admitsPair() {
2326
+ const selected = this.nominated;
2327
+ if (!selected || !this.iceControlling || !this.replacesSelection()) {
2328
+ return undefined;
2329
+ }
2330
+ return (pair) => this.replacesWith(pair) && this.outranks(pair, selected);
2331
+ }
2280
2332
  /**
2281
2333
  * Pair a local candidate gathered after remote candidates arrived (a late
2282
2334
  * TURN allocation, a slow host socket) with them.
2283
2335
  */
2284
2336
  pairLocalProtocol(protocol) {
2285
2337
  // 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") {
2338
+ // Waiting pairs, so a candidate gathered later starts no check. A
2339
+ // selection that may still be replaced (semi-aggressive nomination,
2340
+ // renomination) takes them: a late TURN/UDP allocation may outrank a
2341
+ // TURN/TCP pair selected before it.
2342
+ if (this.state === "closed")
2343
+ return;
2344
+ const replaceable = !!this.nominated && this.iceControlling && this.replacesSelection();
2345
+ if ((this.nominated || this.checkListDone) && !replaceable) {
2288
2346
  return;
2289
2347
  }
2290
2348
  for (const remoteCandidate of this.remoteCandidates) {
2291
2349
  this.tryPair(protocol, remoteCandidate);
2292
2350
  }
2293
2351
  }
2294
- buildRequest({ nominate, remoteUsername, localUsername, iceControlling, localCandidate, }) {
2295
- const txUsername = encodeTxUsername({ remoteUsername, localUsername });
2296
- const request = new message_1.Message(const_1.methods.BINDING, const_1.classes.REQUEST);
2297
- request.setAttribute("USERNAME", txUsername).setAttribute("PRIORITY", (0, candidate_1.candidatePriority)("prflx", {
2298
- transport: localCandidate?.transport,
2299
- tcptype: localCandidate?.tcptype,
2300
- }));
2301
- if (iceControlling) {
2302
- request.setAttribute("ICE-CONTROLLING", this.tieBreaker);
2303
- if (nominate) {
2304
- request.setAttribute("USE-CANDIDATE", null);
2305
- }
2306
- }
2307
- else {
2308
- request.setAttribute("ICE-CONTROLLED", this.tieBreaker);
2309
- }
2310
- return request;
2352
+ /** A connectivity check from this agent (`buildCheckRequest`). */
2353
+ buildRequest(params) {
2354
+ return (0, checkMessages_1.buildCheckRequest)({ ...params, tieBreaker: this.tieBreaker });
2311
2355
  }
2312
2356
  pruneTcpConnections(selectedPair) {
2313
2357
  for (const protocol of this.protocols) {
@@ -2331,7 +2375,7 @@ class Connection {
2331
2375
  const response = new message_1.Message(request.messageMethod, const_1.classes.ERROR, request.transactionId);
2332
2376
  response
2333
2377
  .setAttribute("ERROR-CODE", errorCode)
2334
- .addMessageIntegrity(Buffer.from(localPassword, "utf8"))
2378
+ .addIntegrity(Buffer.from(localPassword, "utf8"), (0, checkMessages_1.responseIntegrityMode)(request))
2335
2379
  .addFingerprint();
2336
2380
  protocol.sendStun(response, addr).catch((e) => {
2337
2381
  log("sendStun error", e);
@@ -2339,14 +2383,4 @@ class Connection {
2339
2383
  }
2340
2384
  }
2341
2385
  exports.Connection = Connection;
2342
- const encodeTxUsername = ({ remoteUsername, localUsername, }) => {
2343
- return `${remoteUsername}:${localUsername}`;
2344
- };
2345
- const decodeTxUsername = (txUsername) => {
2346
- const [remoteUsername, localUsername] = txUsername.split(":");
2347
- return { remoteUsername, localUsername };
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];
2352
2386
  //# sourceMappingURL=ice.js.map