werift 0.27.0 → 0.29.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 (582) hide show
  1. package/README.md +299 -8
  2. package/lib/common/src/event.d.ts +26 -0
  3. package/lib/common/src/event.js +87 -2
  4. package/lib/common/src/event.js.map +1 -1
  5. package/lib/common/src/network.d.ts +6 -1
  6. package/lib/common/src/network.js +8 -2
  7. package/lib/common/src/network.js.map +1 -1
  8. package/lib/common/src/transport.d.ts +51 -10
  9. package/lib/common/src/transport.js +35 -9
  10. package/lib/common/src/transport.js.map +1 -1
  11. package/lib/dtls/src/alert.d.ts +49 -0
  12. package/lib/dtls/src/alert.js +103 -0
  13. package/lib/dtls/src/alert.js.map +1 -0
  14. package/lib/dtls/src/carrier/direct.d.ts +67 -0
  15. package/lib/dtls/src/carrier/direct.js +226 -0
  16. package/lib/dtls/src/carrier/direct.js.map +1 -0
  17. package/lib/dtls/src/carrier/types.d.ts +81 -0
  18. package/lib/dtls/src/carrier/types.js +7 -0
  19. package/lib/dtls/src/carrier/types.js.map +1 -0
  20. package/lib/dtls/src/cipher/const.d.ts +6 -0
  21. package/lib/dtls/src/cipher/const.js +13 -2
  22. package/lib/dtls/src/cipher/const.js.map +1 -1
  23. package/lib/dtls/src/cipher/prf.js +11 -2
  24. package/lib/dtls/src/cipher/prf.js.map +1 -1
  25. package/lib/dtls/src/cipher/tls13/aead.d.ts +41 -0
  26. package/lib/dtls/src/cipher/tls13/aead.js +128 -0
  27. package/lib/dtls/src/cipher/tls13/aead.js.map +1 -0
  28. package/lib/dtls/src/cipher/tls13/hkdf.d.ts +30 -0
  29. package/lib/dtls/src/cipher/tls13/hkdf.js +76 -0
  30. package/lib/dtls/src/cipher/tls13/hkdf.js.map +1 -0
  31. package/lib/dtls/src/cipher/tls13/keySchedule.d.ts +70 -0
  32. package/lib/dtls/src/cipher/tls13/keySchedule.js +114 -0
  33. package/lib/dtls/src/cipher/tls13/keySchedule.js.map +1 -0
  34. package/lib/dtls/src/cipher/tls13/signature.d.ts +30 -0
  35. package/lib/dtls/src/cipher/tls13/signature.js +149 -0
  36. package/lib/dtls/src/cipher/tls13/signature.js.map +1 -0
  37. package/lib/dtls/src/client.d.ts +253 -0
  38. package/lib/dtls/src/client.js +1269 -14
  39. package/lib/dtls/src/client.js.map +1 -1
  40. package/lib/dtls/src/context/dtls.d.ts +47 -0
  41. package/lib/dtls/src/context/dtls.js +121 -0
  42. package/lib/dtls/src/context/dtls.js.map +1 -1
  43. package/lib/dtls/src/context/transport.d.ts +30 -1
  44. package/lib/dtls/src/context/transport.js +67 -3
  45. package/lib/dtls/src/context/transport.js.map +1 -1
  46. package/lib/dtls/src/engine/v1_3/connection-base.d.ts +520 -0
  47. package/lib/dtls/src/engine/v1_3/connection-base.js +1644 -0
  48. package/lib/dtls/src/engine/v1_3/connection-base.js.map +1 -0
  49. package/lib/dtls/src/engine/v1_3/connection.d.ts +181 -0
  50. package/lib/dtls/src/engine/v1_3/connection.js +680 -0
  51. package/lib/dtls/src/engine/v1_3/connection.js.map +1 -0
  52. package/lib/dtls/src/engine/v1_3/early-data-buffer.d.ts +38 -0
  53. package/lib/dtls/src/engine/v1_3/early-data-buffer.js +166 -0
  54. package/lib/dtls/src/engine/v1_3/early-data-buffer.js.map +1 -0
  55. package/lib/dtls/src/engine/v1_3/flight/certificate.d.ts +4 -0
  56. package/lib/dtls/src/engine/v1_3/flight/certificate.js +62 -0
  57. package/lib/dtls/src/engine/v1_3/flight/certificate.js.map +1 -0
  58. package/lib/dtls/src/engine/v1_3/flight/client/flight1.d.ts +8 -0
  59. package/lib/dtls/src/engine/v1_3/flight/client/flight1.js +119 -0
  60. package/lib/dtls/src/engine/v1_3/flight/client/flight1.js.map +1 -0
  61. package/lib/dtls/src/engine/v1_3/flight/client/flight4.d.ts +8 -0
  62. package/lib/dtls/src/engine/v1_3/flight/client/flight4.js +251 -0
  63. package/lib/dtls/src/engine/v1_3/flight/client/flight4.js.map +1 -0
  64. package/lib/dtls/src/engine/v1_3/flight/client/flight5.d.ts +5 -0
  65. package/lib/dtls/src/engine/v1_3/flight/client/flight5.js +99 -0
  66. package/lib/dtls/src/engine/v1_3/flight/client/flight5.js.map +1 -0
  67. package/lib/dtls/src/engine/v1_3/flight/dispatch.d.ts +12 -0
  68. package/lib/dtls/src/engine/v1_3/flight/dispatch.js +138 -0
  69. package/lib/dtls/src/engine/v1_3/flight/dispatch.js.map +1 -0
  70. package/lib/dtls/src/engine/v1_3/flight/extensions.d.ts +13 -0
  71. package/lib/dtls/src/engine/v1_3/flight/extensions.js +46 -0
  72. package/lib/dtls/src/engine/v1_3/flight/extensions.js.map +1 -0
  73. package/lib/dtls/src/engine/v1_3/flight/finished.d.ts +6 -0
  74. package/lib/dtls/src/engine/v1_3/flight/finished.js +16 -0
  75. package/lib/dtls/src/engine/v1_3/flight/finished.js.map +1 -0
  76. package/lib/dtls/src/engine/v1_3/flight/post-hs.d.ts +12 -0
  77. package/lib/dtls/src/engine/v1_3/flight/post-hs.js +94 -0
  78. package/lib/dtls/src/engine/v1_3/flight/post-hs.js.map +1 -0
  79. package/lib/dtls/src/engine/v1_3/flight/server/flight2.d.ts +21 -0
  80. package/lib/dtls/src/engine/v1_3/flight/server/flight2.js +227 -0
  81. package/lib/dtls/src/engine/v1_3/flight/server/flight2.js.map +1 -0
  82. package/lib/dtls/src/engine/v1_3/flight/server/flight4.d.ts +6 -0
  83. package/lib/dtls/src/engine/v1_3/flight/server/flight4.js +455 -0
  84. package/lib/dtls/src/engine/v1_3/flight/server/flight4.js.map +1 -0
  85. package/lib/dtls/src/engine/v1_3/flight/server/flight5.d.ts +5 -0
  86. package/lib/dtls/src/engine/v1_3/flight/server/flight5.js +48 -0
  87. package/lib/dtls/src/engine/v1_3/flight/server/flight5.js.map +1 -0
  88. package/lib/dtls/src/engine/v1_3/flight-tx.d.ts +119 -0
  89. package/lib/dtls/src/engine/v1_3/flight-tx.js +782 -0
  90. package/lib/dtls/src/engine/v1_3/flight-tx.js.map +1 -0
  91. package/lib/dtls/src/engine/v1_3/host.d.ts +86 -0
  92. package/lib/dtls/src/engine/v1_3/host.js +11 -0
  93. package/lib/dtls/src/engine/v1_3/host.js.map +1 -0
  94. package/lib/dtls/src/engine/v1_3/record-rx.d.ts +77 -0
  95. package/lib/dtls/src/engine/v1_3/record-rx.js +818 -0
  96. package/lib/dtls/src/engine/v1_3/record-rx.js.map +1 -0
  97. package/lib/dtls/src/engine/v1_3/transcript.d.ts +22 -0
  98. package/lib/dtls/src/engine/v1_3/transcript.js +65 -0
  99. package/lib/dtls/src/engine/v1_3/transcript.js.map +1 -0
  100. package/lib/dtls/src/engine/v1_3/types.d.ts +169 -0
  101. package/lib/dtls/src/engine/v1_3/types.js +113 -0
  102. package/lib/dtls/src/engine/v1_3/types.js.map +1 -0
  103. package/lib/dtls/src/flight/client/flight1.d.ts +7 -1
  104. package/lib/dtls/src/flight/client/flight1.js +9 -3
  105. package/lib/dtls/src/flight/client/flight1.js.map +1 -1
  106. package/lib/dtls/src/flight/client/flight3.d.ts +8 -0
  107. package/lib/dtls/src/flight/client/flight3.js +24 -4
  108. package/lib/dtls/src/flight/client/flight3.js.map +1 -1
  109. package/lib/dtls/src/flight/client/flight5.js +17 -2
  110. package/lib/dtls/src/flight/client/flight5.js.map +1 -1
  111. package/lib/dtls/src/flight/flight.d.ts +21 -0
  112. package/lib/dtls/src/flight/flight.js +119 -9
  113. package/lib/dtls/src/flight/flight.js.map +1 -1
  114. package/lib/dtls/src/flight/server/commitClientHello.d.ts +35 -0
  115. package/lib/dtls/src/flight/server/commitClientHello.js +149 -0
  116. package/lib/dtls/src/flight/server/commitClientHello.js.map +1 -0
  117. package/lib/dtls/src/flight/server/flight2.d.ts +12 -3
  118. package/lib/dtls/src/flight/server/flight2.js +29 -105
  119. package/lib/dtls/src/flight/server/flight2.js.map +1 -1
  120. package/lib/dtls/src/flight/server/flight4.js +14 -2
  121. package/lib/dtls/src/flight/server/flight4.js.map +1 -1
  122. package/lib/dtls/src/flight/server/flight6.js +12 -1
  123. package/lib/dtls/src/flight/server/flight6.js.map +1 -1
  124. package/lib/dtls/src/handshake/const.d.ts +10 -0
  125. package/lib/dtls/src/handshake/const.js +10 -0
  126. package/lib/dtls/src/handshake/const.js.map +1 -1
  127. package/lib/dtls/src/handshake/extensions/cookie.d.ts +113 -0
  128. package/lib/dtls/src/handshake/extensions/cookie.js +326 -0
  129. package/lib/dtls/src/handshake/extensions/cookie.js.map +1 -0
  130. package/lib/dtls/src/handshake/extensions/ids.d.ts +7 -0
  131. package/lib/dtls/src/handshake/extensions/ids.js +11 -0
  132. package/lib/dtls/src/handshake/extensions/ids.js.map +1 -0
  133. package/lib/dtls/src/handshake/extensions/keyShare.d.ts +28 -0
  134. package/lib/dtls/src/handshake/extensions/keyShare.js +156 -0
  135. package/lib/dtls/src/handshake/extensions/keyShare.js.map +1 -0
  136. package/lib/dtls/src/handshake/extensions/signatureAlgorithms.d.ts +27 -0
  137. package/lib/dtls/src/handshake/extensions/signatureAlgorithms.js +67 -0
  138. package/lib/dtls/src/handshake/extensions/signatureAlgorithms.js.map +1 -0
  139. package/lib/dtls/src/handshake/extensions/supportedVersions.d.ts +20 -0
  140. package/lib/dtls/src/handshake/extensions/supportedVersions.js +90 -0
  141. package/lib/dtls/src/handshake/extensions/supportedVersions.js.map +1 -0
  142. package/lib/dtls/src/handshake/extensions/unique.d.ts +7 -0
  143. package/lib/dtls/src/handshake/extensions/unique.js +19 -0
  144. package/lib/dtls/src/handshake/extensions/unique.js.map +1 -0
  145. package/lib/dtls/src/handshake/extensions/useSrtp.d.ts +26 -3
  146. package/lib/dtls/src/handshake/extensions/useSrtp.js +68 -12
  147. package/lib/dtls/src/handshake/extensions/useSrtp.js.map +1 -1
  148. package/lib/dtls/src/handshake/message/tls13/ack.d.ts +50 -0
  149. package/lib/dtls/src/handshake/message/tls13/ack.js +107 -0
  150. package/lib/dtls/src/handshake/message/tls13/ack.js.map +1 -0
  151. package/lib/dtls/src/handshake/message/tls13/certificate.d.ts +17 -0
  152. package/lib/dtls/src/handshake/message/tls13/certificate.js +112 -0
  153. package/lib/dtls/src/handshake/message/tls13/certificate.js.map +1 -0
  154. package/lib/dtls/src/handshake/message/tls13/certificateRequest.d.ts +17 -0
  155. package/lib/dtls/src/handshake/message/tls13/certificateRequest.js +99 -0
  156. package/lib/dtls/src/handshake/message/tls13/certificateRequest.js.map +1 -0
  157. package/lib/dtls/src/handshake/message/tls13/certificateVerify.d.ts +21 -0
  158. package/lib/dtls/src/handshake/message/tls13/certificateVerify.js +77 -0
  159. package/lib/dtls/src/handshake/message/tls13/certificateVerify.js.map +1 -0
  160. package/lib/dtls/src/handshake/message/tls13/encryptedExtensions.d.ts +19 -0
  161. package/lib/dtls/src/handshake/message/tls13/encryptedExtensions.js +56 -0
  162. package/lib/dtls/src/handshake/message/tls13/encryptedExtensions.js.map +1 -0
  163. package/lib/dtls/src/handshake/message/tls13/keyUpdate.d.ts +13 -0
  164. package/lib/dtls/src/handshake/message/tls13/keyUpdate.js +54 -0
  165. package/lib/dtls/src/handshake/message/tls13/keyUpdate.js.map +1 -0
  166. package/lib/dtls/src/handshake/message/tls13/newSessionTicket.d.ts +33 -0
  167. package/lib/dtls/src/handshake/message/tls13/newSessionTicket.js +158 -0
  168. package/lib/dtls/src/handshake/message/tls13/newSessionTicket.js.map +1 -0
  169. package/lib/dtls/src/handshake/random.d.ts +14 -0
  170. package/lib/dtls/src/handshake/random.js +24 -0
  171. package/lib/dtls/src/handshake/random.js.map +1 -1
  172. package/lib/dtls/src/handshake/validation.d.ts +26 -0
  173. package/lib/dtls/src/handshake/validation.js +32 -0
  174. package/lib/dtls/src/handshake/validation.js.map +1 -0
  175. package/lib/dtls/src/index.d.ts +8 -1
  176. package/lib/dtls/src/index.js +125 -44
  177. package/lib/dtls/src/index.js.map +1 -1
  178. package/lib/dtls/src/internal.d.ts +7 -0
  179. package/lib/dtls/src/internal.js +57 -0
  180. package/lib/dtls/src/internal.js.map +1 -0
  181. package/lib/dtls/src/peer.d.ts +49 -0
  182. package/lib/dtls/src/peer.js +54 -0
  183. package/lib/dtls/src/peer.js.map +1 -0
  184. package/lib/dtls/src/record/antiReplayWindow.d.ts +33 -0
  185. package/lib/dtls/src/record/antiReplayWindow.js +119 -0
  186. package/lib/dtls/src/record/antiReplayWindow.js.map +1 -0
  187. package/lib/dtls/src/record/const.d.ts +15 -0
  188. package/lib/dtls/src/record/const.js +15 -1
  189. package/lib/dtls/src/record/const.js.map +1 -1
  190. package/lib/dtls/src/record/message/fragment.d.ts +0 -2
  191. package/lib/dtls/src/record/message/fragment.js +36 -17
  192. package/lib/dtls/src/record/message/fragment.js.map +1 -1
  193. package/lib/dtls/src/record/message/reassembler.d.ts +62 -0
  194. package/lib/dtls/src/record/message/reassembler.js +249 -0
  195. package/lib/dtls/src/record/message/reassembler.js.map +1 -0
  196. package/lib/dtls/src/record/receive.d.ts +6 -0
  197. package/lib/dtls/src/record/receive.js +58 -19
  198. package/lib/dtls/src/record/receive.js.map +1 -1
  199. package/lib/dtls/src/record/v1_3/header.d.ts +34 -0
  200. package/lib/dtls/src/record/v1_3/header.js +95 -0
  201. package/lib/dtls/src/record/v1_3/header.js.map +1 -0
  202. package/lib/dtls/src/record/v1_3/record.d.ts +133 -0
  203. package/lib/dtls/src/record/v1_3/record.js +370 -0
  204. package/lib/dtls/src/record/v1_3/record.js.map +1 -0
  205. package/lib/dtls/src/retransmission.d.ts +26 -0
  206. package/lib/dtls/src/retransmission.js +39 -0
  207. package/lib/dtls/src/retransmission.js.map +1 -0
  208. package/lib/dtls/src/server.d.ts +38 -0
  209. package/lib/dtls/src/server.js +382 -17
  210. package/lib/dtls/src/server.js.map +1 -1
  211. package/lib/dtls/src/socket.d.ts +487 -11
  212. package/lib/dtls/src/socket.js +1359 -70
  213. package/lib/dtls/src/socket.js.map +1 -1
  214. package/lib/dtls/src/version.d.ts +89 -0
  215. package/lib/dtls/src/version.js +204 -0
  216. package/lib/dtls/src/version.js.map +1 -0
  217. package/lib/ice/src/candidateError.d.ts +155 -0
  218. package/lib/ice/src/candidateError.js +246 -0
  219. package/lib/ice/src/candidateError.js.map +1 -0
  220. package/lib/ice/src/candidateGatherer.d.ts +127 -0
  221. package/lib/ice/src/candidateGatherer.js +745 -0
  222. package/lib/ice/src/candidateGatherer.js.map +1 -0
  223. package/lib/ice/src/consent.d.ts +126 -0
  224. package/lib/ice/src/consent.js +470 -0
  225. package/lib/ice/src/consent.js.map +1 -0
  226. package/lib/ice/src/dns/lookup.d.ts +10 -0
  227. package/lib/ice/src/dns/lookup.js +130 -3
  228. package/lib/ice/src/dns/lookup.js.map +1 -1
  229. package/lib/ice/src/exceptions.d.ts +9 -0
  230. package/lib/ice/src/exceptions.js +14 -1
  231. package/lib/ice/src/exceptions.js.map +1 -1
  232. package/lib/ice/src/failover.d.ts +270 -0
  233. package/lib/ice/src/failover.js +674 -0
  234. package/lib/ice/src/failover.js.map +1 -0
  235. package/lib/ice/src/gatheringError.d.ts +28 -0
  236. package/lib/ice/src/gatheringError.js +17 -0
  237. package/lib/ice/src/gatheringError.js.map +1 -0
  238. package/lib/ice/src/ice.d.ts +486 -78
  239. package/lib/ice/src/ice.js +2415 -1129
  240. package/lib/ice/src/ice.js.map +1 -1
  241. package/lib/ice/src/iceBase.d.ts +404 -14
  242. package/lib/ice/src/iceBase.js +251 -38
  243. package/lib/ice/src/iceBase.js.map +1 -1
  244. package/lib/ice/src/index.d.ts +3 -0
  245. package/lib/ice/src/index.js +5 -1
  246. package/lib/ice/src/index.js.map +1 -1
  247. package/lib/ice/src/internal/checkMessages.d.ts +41 -0
  248. package/lib/ice/src/internal/checkMessages.js +63 -0
  249. package/lib/ice/src/internal/checkMessages.js.map +1 -0
  250. package/lib/ice/src/internal/datagram.d.ts +37 -0
  251. package/lib/ice/src/internal/datagram.js +45 -0
  252. package/lib/ice/src/internal/datagram.js.map +1 -0
  253. package/lib/ice/src/internal/defaultRoute.d.ts +20 -0
  254. package/lib/ice/src/internal/defaultRoute.js +134 -0
  255. package/lib/ice/src/internal/defaultRoute.js.map +1 -0
  256. package/lib/ice/src/internal/hostInterfaces.d.ts +28 -0
  257. package/lib/ice/src/internal/hostInterfaces.js +89 -0
  258. package/lib/ice/src/internal/hostInterfaces.js.map +1 -0
  259. package/lib/ice/src/internal/hostPreference.d.ts +24 -0
  260. package/lib/ice/src/internal/hostPreference.js +38 -0
  261. package/lib/ice/src/internal/hostPreference.js.map +1 -0
  262. package/lib/ice/src/internal/resolveHostAddresses.d.ts +56 -8
  263. package/lib/ice/src/internal/resolveHostAddresses.js +127 -24
  264. package/lib/ice/src/internal/resolveHostAddresses.js.map +1 -1
  265. package/lib/ice/src/internal/selectAddresses.d.ts +27 -0
  266. package/lib/ice/src/internal/selectAddresses.js +37 -18
  267. package/lib/ice/src/internal/selectAddresses.js.map +1 -1
  268. package/lib/ice/src/internal/sped-bind.d.ts +44 -0
  269. package/lib/ice/src/internal/sped-bind.js +53 -0
  270. package/lib/ice/src/internal/sped-bind.js.map +1 -0
  271. package/lib/ice/src/internal/sped-binding-cache.d.ts +27 -0
  272. package/lib/ice/src/internal/sped-binding-cache.js +102 -0
  273. package/lib/ice/src/internal/sped-binding-cache.js.map +1 -0
  274. package/lib/ice/src/internal/sped.d.ts +15 -0
  275. package/lib/ice/src/internal/sped.js +62 -0
  276. package/lib/ice/src/internal/sped.js.map +1 -0
  277. package/lib/ice/src/nomination/regularNomination.d.ts +200 -0
  278. package/lib/ice/src/nomination/regularNomination.js +311 -0
  279. package/lib/ice/src/nomination/regularNomination.js.map +1 -0
  280. package/lib/ice/src/nomination/selectionController.d.ts +111 -0
  281. package/lib/ice/src/nomination/selectionController.js +172 -0
  282. package/lib/ice/src/nomination/selectionController.js.map +1 -0
  283. package/lib/ice/src/nomination/selectionReplacement.d.ts +178 -0
  284. package/lib/ice/src/nomination/selectionReplacement.js +429 -0
  285. package/lib/ice/src/nomination/selectionReplacement.js.map +1 -0
  286. package/lib/ice/src/provisional.d.ts +139 -0
  287. package/lib/ice/src/provisional.js +468 -0
  288. package/lib/ice/src/provisional.js.map +1 -0
  289. package/lib/ice/src/sped/draft00/codec.d.ts +20 -0
  290. package/lib/ice/src/sped/draft00/codec.js +59 -0
  291. package/lib/ice/src/sped/draft00/codec.js.map +1 -0
  292. package/lib/ice/src/sped/draft00/constants.d.ts +14 -0
  293. package/lib/ice/src/sped/draft00/constants.js +18 -0
  294. package/lib/ice/src/sped/draft00/constants.js.map +1 -0
  295. package/lib/ice/src/sped/draft00/index.d.ts +6 -0
  296. package/lib/ice/src/sped/draft00/index.js +26 -0
  297. package/lib/ice/src/sped/draft00/index.js.map +1 -0
  298. package/lib/ice/src/sped/draft00/mtu.d.ts +38 -0
  299. package/lib/ice/src/sped/draft00/mtu.js +96 -0
  300. package/lib/ice/src/sped/draft00/mtu.js.map +1 -0
  301. package/lib/ice/src/sped/draft00/session.d.ts +86 -0
  302. package/lib/ice/src/sped/draft00/session.js +353 -0
  303. package/lib/ice/src/sped/draft00/session.js.map +1 -0
  304. package/lib/ice/src/sped/draft00/types.d.ts +16 -0
  305. package/lib/ice/src/sped/draft00/types.js +3 -0
  306. package/lib/ice/src/sped/draft00/types.js.map +1 -0
  307. package/lib/ice/src/sped/runtime.d.ts +188 -0
  308. package/lib/ice/src/sped/runtime.js +643 -0
  309. package/lib/ice/src/sped/runtime.js.map +1 -0
  310. package/lib/ice/src/stun/protocol.d.ts +38 -2
  311. package/lib/ice/src/stun/protocol.js +107 -21
  312. package/lib/ice/src/stun/protocol.js.map +1 -1
  313. package/lib/ice/src/stun/rawAttributeValue.d.ts +1 -0
  314. package/lib/ice/src/stun/rawAttributeValue.js +6 -0
  315. package/lib/ice/src/stun/rawAttributeValue.js.map +1 -0
  316. package/lib/ice/src/stun/tcpProtocol.d.ts +2 -1
  317. package/lib/ice/src/stun/tcpProtocol.js +21 -9
  318. package/lib/ice/src/stun/tcpProtocol.js.map +1 -1
  319. package/lib/ice/src/stun/transaction.d.ts +4 -0
  320. package/lib/ice/src/stun/transaction.js +27 -2
  321. package/lib/ice/src/stun/transaction.js.map +1 -1
  322. package/lib/ice/src/turn/protocol.d.ts +23 -4
  323. package/lib/ice/src/turn/protocol.js +99 -11
  324. package/lib/ice/src/turn/protocol.js.map +1 -1
  325. package/lib/ice/src/types/model.d.ts +25 -5
  326. package/lib/ice/src/types/model.js.map +1 -1
  327. package/lib/ice/src/utils.d.ts +13 -0
  328. package/lib/ice/src/utils.js +13 -0
  329. package/lib/ice/src/utils.js.map +1 -1
  330. package/lib/ice-server/src/stun/attributes.js +4 -0
  331. package/lib/ice-server/src/stun/attributes.js.map +1 -1
  332. package/lib/ice-server/src/stun/const.d.ts +20 -1
  333. package/lib/ice-server/src/stun/const.js +9 -1
  334. package/lib/ice-server/src/stun/const.js.map +1 -1
  335. package/lib/ice-server/src/stun/message.d.ts +43 -3
  336. package/lib/ice-server/src/stun/message.js +258 -40
  337. package/lib/ice-server/src/stun/message.js.map +1 -1
  338. package/lib/ice-server/src/stun/rawAttributeValue.d.ts +6 -0
  339. package/lib/ice-server/src/stun/rawAttributeValue.js +12 -0
  340. package/lib/ice-server/src/stun/rawAttributeValue.js.map +1 -0
  341. package/lib/index.mjs +47427 -25303
  342. package/lib/nonstandard/index.mjs +3076 -1318
  343. package/lib/polyfill/dom.mjs +40430 -18730
  344. package/lib/polyfill/index.mjs +40333 -18639
  345. package/lib/rtp/src/extra/processor/fsRetry.d.ts +20 -0
  346. package/lib/rtp/src/extra/processor/fsRetry.js +73 -0
  347. package/lib/rtp/src/extra/processor/fsRetry.js.map +1 -0
  348. package/lib/rtp/src/extra/processor/webm.d.ts +6 -0
  349. package/lib/rtp/src/extra/processor/webm.js +6 -2
  350. package/lib/rtp/src/extra/processor/webm.js.map +1 -1
  351. package/lib/rtp/src/extra/processor/webmCallback.d.ts +11 -0
  352. package/lib/rtp/src/extra/processor/webmCallback.js +23 -31
  353. package/lib/rtp/src/extra/processor/webmCallback.js.map +1 -1
  354. package/lib/rtp/src/extra/processor/webmFileWriter.d.ts +24 -0
  355. package/lib/rtp/src/extra/processor/webmFileWriter.js +94 -0
  356. package/lib/rtp/src/extra/processor/webmFileWriter.js.map +1 -0
  357. package/lib/rtp/src/index.d.ts +1 -0
  358. package/lib/rtp/src/index.js +1 -0
  359. package/lib/rtp/src/index.js.map +1 -1
  360. package/lib/rtp/src/rtp/continuity.d.ts +14 -1
  361. package/lib/rtp/src/rtp/continuity.js +24 -4
  362. package/lib/rtp/src/rtp/continuity.js.map +1 -1
  363. package/lib/rtp/src/rtp/timelineRewriter.d.ts +178 -0
  364. package/lib/rtp/src/rtp/timelineRewriter.js +417 -0
  365. package/lib/rtp/src/rtp/timelineRewriter.js.map +1 -0
  366. package/lib/sctp/src/chunk.d.ts +5 -0
  367. package/lib/sctp/src/chunk.js +10 -0
  368. package/lib/sctp/src/chunk.js.map +1 -1
  369. package/lib/sctp/src/index.d.ts +1 -1
  370. package/lib/sctp/src/index.js +4 -1
  371. package/lib/sctp/src/index.js.map +1 -1
  372. package/lib/sctp/src/sctp.d.ts +86 -5
  373. package/lib/sctp/src/sctp.js +354 -75
  374. package/lib/sctp/src/sctp.js.map +1 -1
  375. package/lib/webrtc/src/api/compatibilityOptions.d.ts +43 -0
  376. package/lib/webrtc/src/api/compatibilityOptions.js +43 -0
  377. package/lib/webrtc/src/api/compatibilityOptions.js.map +1 -0
  378. package/lib/webrtc/src/api/peerConfig.d.ts +547 -36
  379. package/lib/webrtc/src/api/peerConfig.js +187 -26
  380. package/lib/webrtc/src/api/peerConfig.js.map +1 -1
  381. package/lib/webrtc/src/api/peerConnectionEvents.d.ts +87 -2
  382. package/lib/webrtc/src/api/peerConnectionEvents.js +105 -1
  383. package/lib/webrtc/src/api/peerConnectionEvents.js.map +1 -1
  384. package/lib/webrtc/src/dataChannel.d.ts +122 -10
  385. package/lib/webrtc/src/dataChannel.js +214 -20
  386. package/lib/webrtc/src/dataChannel.js.map +1 -1
  387. package/lib/webrtc/src/helper.d.ts +8 -0
  388. package/lib/webrtc/src/helper.js +40 -4
  389. package/lib/webrtc/src/helper.js.map +1 -1
  390. package/lib/webrtc/src/media/codecCompatibility.d.ts +87 -1
  391. package/lib/webrtc/src/media/codecCompatibility.js +338 -12
  392. package/lib/webrtc/src/media/codecCompatibility.js.map +1 -1
  393. package/lib/webrtc/src/media/domEventTarget.d.ts +55 -0
  394. package/lib/webrtc/src/media/domEventTarget.js +216 -0
  395. package/lib/webrtc/src/media/domEventTarget.js.map +1 -0
  396. package/lib/webrtc/src/media/index.d.ts +2 -0
  397. package/lib/webrtc/src/media/index.js +1 -0
  398. package/lib/webrtc/src/media/index.js.map +1 -1
  399. package/lib/webrtc/src/media/parameters.d.ts +5 -0
  400. package/lib/webrtc/src/media/parameters.js +10 -0
  401. package/lib/webrtc/src/media/parameters.js.map +1 -1
  402. package/lib/webrtc/src/media/receiver/nack.d.ts +43 -10
  403. package/lib/webrtc/src/media/receiver/nack.js +245 -88
  404. package/lib/webrtc/src/media/receiver/nack.js.map +1 -1
  405. package/lib/webrtc/src/media/receiver/receiverTwcc.d.ts +10 -0
  406. package/lib/webrtc/src/media/receiver/receiverTwcc.js +4 -10
  407. package/lib/webrtc/src/media/receiver/receiverTwcc.js.map +1 -1
  408. package/lib/webrtc/src/media/router.d.ts +245 -51
  409. package/lib/webrtc/src/media/router.js +702 -237
  410. package/lib/webrtc/src/media/router.js.map +1 -1
  411. package/lib/webrtc/src/media/routing/pendingRoutes.d.ts +26 -0
  412. package/lib/webrtc/src/media/routing/pendingRoutes.js +48 -0
  413. package/lib/webrtc/src/media/routing/pendingRoutes.js.map +1 -0
  414. package/lib/webrtc/src/media/routing/ridRouting.d.ts +37 -0
  415. package/lib/webrtc/src/media/routing/ridRouting.js +74 -0
  416. package/lib/webrtc/src/media/routing/ridRouting.js.map +1 -0
  417. package/lib/webrtc/src/media/routing/routeTable.d.ts +60 -0
  418. package/lib/webrtc/src/media/routing/routeTable.js +95 -0
  419. package/lib/webrtc/src/media/routing/routeTable.js.map +1 -0
  420. package/lib/webrtc/src/media/routing/rtcpRouting.d.ts +34 -0
  421. package/lib/webrtc/src/media/routing/rtcpRouting.js +165 -0
  422. package/lib/webrtc/src/media/routing/rtcpRouting.js.map +1 -0
  423. package/lib/webrtc/src/media/routing/unknownSsrc.d.ts +55 -0
  424. package/lib/webrtc/src/media/routing/unknownSsrc.js +117 -0
  425. package/lib/webrtc/src/media/routing/unknownSsrc.js.map +1 -0
  426. package/lib/webrtc/src/media/rtpReceiver.d.ts +277 -5
  427. package/lib/webrtc/src/media/rtpReceiver.js +826 -36
  428. package/lib/webrtc/src/media/rtpReceiver.js.map +1 -1
  429. package/lib/webrtc/src/media/rtpSender.d.ts +8 -1
  430. package/lib/webrtc/src/media/rtpSender.js +13 -6
  431. package/lib/webrtc/src/media/rtpSender.js.map +1 -1
  432. package/lib/webrtc/src/media/rtpTransceiver.d.ts +47 -11
  433. package/lib/webrtc/src/media/rtpTransceiver.js +95 -11
  434. package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
  435. package/lib/webrtc/src/media/sender/senderReportHistory.d.ts +51 -0
  436. package/lib/webrtc/src/media/sender/senderReportHistory.js +111 -0
  437. package/lib/webrtc/src/media/sender/senderReportHistory.js.map +1 -0
  438. package/lib/webrtc/src/media/sender/senderStats.d.ts +6 -5
  439. package/lib/webrtc/src/media/sender/senderStats.js +14 -19
  440. package/lib/webrtc/src/media/sender/senderStats.js.map +1 -1
  441. package/lib/webrtc/src/media/stats.d.ts +13 -0
  442. package/lib/webrtc/src/media/stats.js.map +1 -1
  443. package/lib/webrtc/src/media/track.d.ts +112 -11
  444. package/lib/webrtc/src/media/track.js +250 -19
  445. package/lib/webrtc/src/media/track.js.map +1 -1
  446. package/lib/webrtc/src/media/trackConstraints.d.ts +80 -0
  447. package/lib/webrtc/src/media/trackConstraints.js +141 -0
  448. package/lib/webrtc/src/media/trackConstraints.js.map +1 -0
  449. package/lib/webrtc/src/negotiation/internalState.d.ts +0 -4
  450. package/lib/webrtc/src/negotiation/internalState.js +0 -11
  451. package/lib/webrtc/src/negotiation/internalState.js.map +1 -1
  452. package/lib/webrtc/src/negotiation/remoteCandidates.d.ts +20 -1
  453. package/lib/webrtc/src/negotiation/remoteCandidates.js +29 -1
  454. package/lib/webrtc/src/negotiation/remoteCandidates.js.map +1 -1
  455. package/lib/webrtc/src/negotiation/remoteMediaApplication.d.ts +23 -6
  456. package/lib/webrtc/src/negotiation/remoteMediaApplication.js +46 -22
  457. package/lib/webrtc/src/negotiation/remoteMediaApplication.js.map +1 -1
  458. package/lib/webrtc/src/negotiation/transceiverPairing.d.ts +1 -0
  459. package/lib/webrtc/src/negotiation/transceiverPairing.js +62 -0
  460. package/lib/webrtc/src/negotiation/transceiverPairing.js.map +1 -0
  461. package/lib/webrtc/src/negotiation/transportActivation.d.ts +12 -1
  462. package/lib/webrtc/src/negotiation/transportActivation.js +133 -11
  463. package/lib/webrtc/src/negotiation/transportActivation.js.map +1 -1
  464. package/lib/webrtc/src/negotiationTransaction.d.ts +57 -5
  465. package/lib/webrtc/src/negotiationTransaction.js +134 -10
  466. package/lib/webrtc/src/negotiationTransaction.js.map +1 -1
  467. package/lib/webrtc/src/nonstandard/dummyMedia.d.ts +6 -0
  468. package/lib/webrtc/src/nonstandard/dummyMedia.js +14 -19
  469. package/lib/webrtc/src/nonstandard/dummyMedia.js.map +1 -1
  470. package/lib/webrtc/src/nonstandard/navigator.d.ts +1 -1
  471. package/lib/webrtc/src/nonstandard/recorder/index.js +5 -1
  472. package/lib/webrtc/src/nonstandard/recorder/index.js.map +1 -1
  473. package/lib/webrtc/src/nonstandard/recorder/writer/webm.d.ts +6 -1
  474. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js +31 -2
  475. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js.map +1 -1
  476. package/lib/webrtc/src/nonstandard/userMedia/packetizer.d.ts +16 -0
  477. package/lib/webrtc/src/nonstandard/userMedia/packetizer.js +25 -0
  478. package/lib/webrtc/src/nonstandard/userMedia/packetizer.js.map +1 -1
  479. package/lib/webrtc/src/nonstandard/userMedia.js +6 -13
  480. package/lib/webrtc/src/nonstandard/userMedia.js.map +1 -1
  481. package/lib/webrtc/src/peerConnection.d.ts +106 -11
  482. package/lib/webrtc/src/peerConnection.js +370 -36
  483. package/lib/webrtc/src/peerConnection.js.map +1 -1
  484. package/lib/webrtc/src/polyfill/api.d.ts +2 -1
  485. package/lib/webrtc/src/polyfill/api.js +3 -3
  486. package/lib/webrtc/src/polyfill/api.js.map +1 -1
  487. package/lib/webrtc/src/polyfill/dom.d.ts +21 -7
  488. package/lib/webrtc/src/polyfill/dom.js +15 -0
  489. package/lib/webrtc/src/polyfill/dom.js.map +1 -1
  490. package/lib/webrtc/src/polyfill/globals.d.ts +8 -3
  491. package/lib/webrtc/src/polyfill/globals.js.map +1 -1
  492. package/lib/webrtc/src/polyfill/index.d.ts +1 -1
  493. package/lib/webrtc/src/polyfill/index.js +1 -1
  494. package/lib/webrtc/src/polyfill/index.js.map +1 -1
  495. package/lib/webrtc/src/polyfill/install.d.ts +5 -1
  496. package/lib/webrtc/src/polyfill/install.js +4 -2
  497. package/lib/webrtc/src/polyfill/install.js.map +1 -1
  498. package/lib/webrtc/src/polyfill/mediaDevices.js +28 -4
  499. package/lib/webrtc/src/polyfill/mediaDevices.js.map +1 -1
  500. package/lib/webrtc/src/polyfill/peerConnectionConfig.d.ts +6 -0
  501. package/lib/webrtc/src/polyfill/peerConnectionConfig.js +15 -4
  502. package/lib/webrtc/src/polyfill/peerConnectionConfig.js.map +1 -1
  503. package/lib/webrtc/src/polyfill/selectSettings.d.ts +4 -14
  504. package/lib/webrtc/src/polyfill/selectSettings.js +10 -106
  505. package/lib/webrtc/src/polyfill/selectSettings.js.map +1 -1
  506. package/lib/webrtc/src/polyfill/sourceIo.d.ts +1 -2
  507. package/lib/webrtc/src/polyfill/sourceIo.js +6 -6
  508. package/lib/webrtc/src/polyfill/sourceIo.js.map +1 -1
  509. package/lib/webrtc/src/sctpManager.d.ts +31 -18
  510. package/lib/webrtc/src/sctpManager.js +162 -38
  511. package/lib/webrtc/src/sctpManager.js.map +1 -1
  512. package/lib/webrtc/src/sdp.d.ts +107 -2
  513. package/lib/webrtc/src/sdp.js +223 -17
  514. package/lib/webrtc/src/sdp.js.map +1 -1
  515. package/lib/webrtc/src/sdpManager.d.ts +101 -10
  516. package/lib/webrtc/src/sdpManager.js +236 -14
  517. package/lib/webrtc/src/sdpManager.js.map +1 -1
  518. package/lib/webrtc/src/secureTransportManager.d.ts +49 -3
  519. package/lib/webrtc/src/secureTransportManager.js +166 -12
  520. package/lib/webrtc/src/secureTransportManager.js.map +1 -1
  521. package/lib/webrtc/src/transceiverManager.d.ts +87 -6
  522. package/lib/webrtc/src/transceiverManager.js +272 -51
  523. package/lib/webrtc/src/transceiverManager.js.map +1 -1
  524. package/lib/webrtc/src/transport/dtls-application-gate.d.ts +1 -0
  525. package/lib/webrtc/src/transport/dtls-application-gate.js +143 -0
  526. package/lib/webrtc/src/transport/dtls-application-gate.js.map +1 -0
  527. package/lib/webrtc/src/transport/dtls-attempt.d.ts +1 -0
  528. package/lib/webrtc/src/transport/dtls-attempt.js +79 -0
  529. package/lib/webrtc/src/transport/dtls-attempt.js.map +1 -0
  530. package/lib/webrtc/src/transport/dtls-certificate.d.ts +24 -0
  531. package/lib/webrtc/src/transport/dtls-certificate.js +98 -0
  532. package/lib/webrtc/src/transport/dtls-certificate.js.map +1 -0
  533. package/lib/webrtc/src/transport/dtls-fingerprint.d.ts +7 -0
  534. package/lib/webrtc/src/transport/dtls-fingerprint.js +66 -0
  535. package/lib/webrtc/src/transport/dtls-fingerprint.js.map +1 -0
  536. package/lib/webrtc/src/transport/dtls-ice-transport.d.ts +1 -0
  537. package/lib/webrtc/src/transport/dtls-ice-transport.js +123 -0
  538. package/lib/webrtc/src/transport/dtls-ice-transport.js.map +1 -0
  539. package/lib/webrtc/src/transport/dtls-media-queue.d.ts +1 -0
  540. package/lib/webrtc/src/transport/dtls-media-queue.js +95 -0
  541. package/lib/webrtc/src/transport/dtls-media-queue.js.map +1 -0
  542. package/lib/webrtc/src/transport/dtls-readiness.d.ts +1 -0
  543. package/lib/webrtc/src/transport/dtls-readiness.js +173 -0
  544. package/lib/webrtc/src/transport/dtls-readiness.js.map +1 -0
  545. package/lib/webrtc/src/transport/dtls-sped-handshake.d.ts +1 -0
  546. package/lib/webrtc/src/transport/dtls-sped-handshake.js +146 -0
  547. package/lib/webrtc/src/transport/dtls-sped-handshake.js.map +1 -0
  548. package/lib/webrtc/src/transport/dtls-srtp.d.ts +1 -0
  549. package/lib/webrtc/src/transport/dtls-srtp.js +133 -0
  550. package/lib/webrtc/src/transport/dtls-srtp.js.map +1 -0
  551. package/lib/webrtc/src/transport/dtls-stats.d.ts +1 -0
  552. package/lib/webrtc/src/transport/dtls-stats.js +134 -0
  553. package/lib/webrtc/src/transport/dtls-stats.js.map +1 -0
  554. package/lib/webrtc/src/transport/dtls-types.d.ts +23 -0
  555. package/lib/webrtc/src/transport/dtls-types.js +11 -0
  556. package/lib/webrtc/src/transport/dtls-types.js.map +1 -0
  557. package/lib/webrtc/src/transport/dtls.d.ts +236 -47
  558. package/lib/webrtc/src/transport/dtls.js +1198 -441
  559. package/lib/webrtc/src/transport/dtls.js.map +1 -1
  560. package/lib/webrtc/src/transport/ice.d.ts +95 -5
  561. package/lib/webrtc/src/transport/ice.js +323 -21
  562. package/lib/webrtc/src/transport/ice.js.map +1 -1
  563. package/lib/webrtc/src/transport/iceCandidateAttribute.d.ts +4 -2
  564. package/lib/webrtc/src/transport/iceCandidateAttribute.js.map +1 -1
  565. package/lib/webrtc/src/transport/sctp.d.ts +149 -2
  566. package/lib/webrtc/src/transport/sctp.js +826 -128
  567. package/lib/webrtc/src/transport/sctp.js.map +1 -1
  568. package/lib/webrtc/src/transport/sped.d.ts +139 -0
  569. package/lib/webrtc/src/transport/sped.js +757 -0
  570. package/lib/webrtc/src/transport/sped.js.map +1 -0
  571. package/lib/webrtc/src/types/util.d.ts +6 -0
  572. package/lib/webrtc/src/types/util.js.map +1 -1
  573. package/lib/webrtc/src/utils.d.ts +34 -1
  574. package/lib/webrtc/src/utils.js +52 -3
  575. package/lib/webrtc/src/utils.js.map +1 -1
  576. package/lib/webrtc/src/webidl.d.ts +15 -0
  577. package/lib/webrtc/src/webidl.js +34 -0
  578. package/lib/webrtc/src/webidl.js.map +1 -0
  579. package/package.json +8 -3
  580. package/lib/webrtc/src/polyfill/rtcSessionDescription.d.ts +0 -18
  581. package/lib/webrtc/src/polyfill/rtcSessionDescription.js +0 -36
  582. package/lib/webrtc/src/polyfill/rtcSessionDescription.js.map +0 -1
@@ -33,27 +33,76 @@ 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
39
  const candidate_1 = require("./candidate");
40
+ const candidateGatherer_1 = require("./candidateGatherer");
41
+ const consent_1 = require("./consent");
41
42
  const lookup_1 = require("./dns/lookup");
42
43
  const exceptions_1 = require("./exceptions");
44
+ const failover_1 = require("./failover");
45
+ const gatheringError_1 = require("./gatheringError");
43
46
  const helper_1 = require("./helper");
44
47
  const iceBase_1 = require("./iceBase");
45
48
  const common_1 = require("./imports/common");
49
+ const checkMessages_1 = require("./internal/checkMessages");
50
+ const datagram_1 = require("./internal/datagram");
51
+ const defaultRoute_1 = require("./internal/defaultRoute");
52
+ const hostInterfaces_1 = require("./internal/hostInterfaces");
46
53
  const resolveHostAddresses_1 = require("./internal/resolveHostAddresses");
54
+ const sped_bind_1 = require("./internal/sped-bind");
55
+ const sped_binding_cache_1 = require("./internal/sped-binding-cache");
56
+ const regularNomination_1 = require("./nomination/regularNomination");
57
+ const selectionController_1 = require("./nomination/selectionController");
58
+ const selectionReplacement_1 = require("./nomination/selectionReplacement");
59
+ const provisional_1 = require("./provisional");
60
+ const runtime_1 = require("./sped/runtime");
47
61
  const const_1 = require("./stun/const");
48
62
  const message_1 = require("./stun/message");
49
63
  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
64
  const log = (0, common_1.debug)("werift-ice : packages/ice/src/ice.ts : log");
65
+ /**
66
+ * One STUN connectivity-check transaction: initial send plus RETRY_MAX
67
+ * retransmissions with doubling RTO. The SPED Binding Response replay cache
68
+ * keeps an entry for this long (STUN retransmissions of the same request).
69
+ */
70
+ function stunTransactionLifetimeMs() {
71
+ const tries = 1 + const_1.RETRY_MAX;
72
+ return const_1.RETRY_RTO * (2 ** tries - 1);
73
+ }
54
74
  /** Fallback STUN server when none is configured (constructor / setIceServers). */
55
75
  const DEFAULT_STUN_SERVER = ["stun.l.google.com", 19302];
76
+ /** @see packages/ice/tests/ice/interface-enumeration.test.ts「without servers or explicit addresses: ends with interface-enumeration-failed then no-candidates」(errorText) */
77
+ const errorMessage = (error) => error instanceof Error ? error.message : String(error);
78
+ /**
79
+ * The URL `onIceCandidateError` names the built-in default STUN server by:
80
+ * it is in no configuration, so werift synthesizes one.
81
+ */
82
+ exports.DEFAULT_STUN_SERVER_URL = "stun:stun.l.google.com:19302";
83
+ // The ICE agent. This file keeps the public API, the lifecycle (restart,
84
+ // close, state), the protocol event wiring and the live checklist
85
+ // (connect / checkStart / checkComplete / checkIncoming) and candidate
86
+ // gathering (gatherCandidates / getCandidatePromises). Its other parts live in
87
+ // collaborators the agent supplies through a host object:
88
+ // - consent.ts: RFC 7675 consent freshness of the selected pair
89
+ // - provisional.ts: the checklist of an ICE restart negotiated with a pranswer
90
+ // - nomination/regularNomination.ts: RFC 8445 regular nomination
91
+ // - nomination/selectionReplacement.ts: semi-aggressive nomination /
92
+ // renomination replacing the selection
93
+ // - internal/checkMessages.ts: building and reading connectivity checks
56
94
  class Connection {
95
+ /** The staged ICE restart generation (`ProvisionalChecklist`). */
96
+ get provisional() {
97
+ return this.provisionalChecklist.generation;
98
+ }
99
+ /** @internal SPED controller; unset unless PeerConfig.sped (or tests) attach it. */
100
+ get spedRuntime() {
101
+ return (0, sped_bind_1.getConnectionSpedRuntime)(this);
102
+ }
103
+ set spedRuntime(runtime) {
104
+ (0, sped_bind_1.setConnectionSpedRuntime)(this, runtime);
105
+ }
57
106
  constructor(_iceControlling, options) {
58
107
  Object.defineProperty(this, "_iceControlling", {
59
108
  enumerable: true,
@@ -61,6 +110,20 @@ class Connection {
61
110
  writable: true,
62
111
  value: void 0
63
112
  });
113
+ /** @internal SPED wiring (see internal/sped-bind.ts); PeerConfig.sped only. */
114
+ Object.defineProperty(this, "internalSped", {
115
+ enumerable: true,
116
+ configurable: true,
117
+ writable: true,
118
+ value: { enabled: false }
119
+ });
120
+ /** @internal Source/generation-aware datagram event (see internal/datagram.ts). */
121
+ Object.defineProperty(this, "internalDatagramEvent", {
122
+ enumerable: true,
123
+ configurable: true,
124
+ writable: true,
125
+ value: void 0
126
+ });
64
127
  Object.defineProperty(this, "localUsername", {
65
128
  enumerable: true,
66
129
  configurable: true,
@@ -79,6 +142,19 @@ class Connection {
79
142
  writable: true,
80
143
  value: false
81
144
  });
145
+ /** The peer advertised `a=ice-options:renomination` (see `IceOptions.renomination`). */
146
+ Object.defineProperty(this, "remoteRenomination", {
147
+ enumerable: true,
148
+ configurable: true,
149
+ writable: true,
150
+ value: false
151
+ });
152
+ Object.defineProperty(this, "remoteIceOptions", {
153
+ enumerable: true,
154
+ configurable: true,
155
+ writable: true,
156
+ value: []
157
+ });
82
158
  Object.defineProperty(this, "remotePassword", {
83
159
  enumerable: true,
84
160
  configurable: true,
@@ -91,6 +167,17 @@ class Connection {
91
167
  writable: true,
92
168
  value: ""
93
169
  });
170
+ /**
171
+ * Remote ufrags of replaced generations (bounded). A late check one of them
172
+ * sends is still answered but never adds a candidate or pair to the new
173
+ * generation's checklist.
174
+ */
175
+ Object.defineProperty(this, "retiredRemoteUsernames", {
176
+ enumerable: true,
177
+ configurable: true,
178
+ writable: true,
179
+ value: []
180
+ });
94
181
  Object.defineProperty(this, "checkList", {
95
182
  enumerable: true,
96
183
  configurable: true,
@@ -114,6 +201,13 @@ class Connection {
114
201
  writable: true,
115
202
  value: []
116
203
  });
204
+ /** Whether stunServers is the built-in default (none configured). */
205
+ Object.defineProperty(this, "usesDefaultStunServer", {
206
+ enumerable: true,
207
+ configurable: true,
208
+ writable: true,
209
+ value: false
210
+ });
117
211
  /** TURN servers gathering allocates on, one allocation each. */
118
212
  Object.defineProperty(this, "turnServers", {
119
213
  enumerable: true,
@@ -168,6 +262,24 @@ class Connection {
168
262
  writable: true,
169
263
  value: false
170
264
  });
265
+ /** connect() stopped scheduling checks (a later pair must start its own). */
266
+ Object.defineProperty(this, "schedulingStopped", {
267
+ enumerable: true,
268
+ configurable: true,
269
+ writable: true,
270
+ value: false
271
+ });
272
+ /**
273
+ * The waits of connect() (one per concurrent call) for the peer's first
274
+ * check on an empty check list; woken when a pair is added or the local
275
+ * gathering ends (waitForIncomingCheck).
276
+ */
277
+ Object.defineProperty(this, "incomingCheckWaits", {
278
+ enumerable: true,
279
+ configurable: true,
280
+ writable: true,
281
+ value: new Set()
282
+ });
171
283
  Object.defineProperty(this, "generation", {
172
284
  enumerable: true,
173
285
  configurable: true,
@@ -243,12 +355,91 @@ class Connection {
243
355
  writable: true,
244
356
  value: void 0
245
357
  });
246
- Object.defineProperty(this, "nominating", {
358
+ /** Authenticated pair the remote peer last sent application data on. */
359
+ Object.defineProperty(this, "lastDataPair", {
360
+ enumerable: true,
361
+ configurable: true,
362
+ writable: true,
363
+ value: void 0
364
+ });
365
+ /**
366
+ * Selected pairs of the previous generation (ours and the one the peer was
367
+ * sending on; nomination can be asymmetric). RFC 8445 §9: media continues
368
+ * over the previously selected pair until the restart selects a new one.
369
+ * The peer may keep using it after we nominate, so these are released once
370
+ * the peer sends on an authenticated current-generation pair.
371
+ */
372
+ Object.defineProperty(this, "previousSelectedPairs", {
373
+ enumerable: true,
374
+ configurable: true,
375
+ writable: true,
376
+ value: []
377
+ });
378
+ /** The ICE-lite nomination (first valid pair, in `checkStart`) is in flight. */
379
+ Object.defineProperty(this, "liteNominating", {
247
380
  enumerable: true,
248
381
  configurable: true,
249
382
  writable: true,
250
383
  value: false
251
384
  });
385
+ /** Regular nomination (RFC 8445 §8.1.1) of the live checklist. */
386
+ Object.defineProperty(this, "nomination", {
387
+ enumerable: true,
388
+ configurable: true,
389
+ writable: true,
390
+ value: new regularNomination_1.RegularNomination(this.liveNominationHost())
391
+ });
392
+ /** Semi-aggressive nomination and renomination: replacing the selection. */
393
+ Object.defineProperty(this, "selection", {
394
+ enumerable: true,
395
+ configurable: true,
396
+ writable: true,
397
+ value: new selectionReplacement_1.SelectionReplacement({
398
+ checkList: () => this.checkList,
399
+ selected: () => this.nominated,
400
+ controlling: () => this.iceControlling,
401
+ closed: () => this.state === "closed",
402
+ remoteGeneration: () => this.remoteGeneration,
403
+ usesRenomination: () => this.usesRenomination(),
404
+ usesSemiAggressiveNomination: () => this.usesSemiAggressiveNomination(),
405
+ replacesSelection: () => this.replacesSelection(),
406
+ replacesWith: (pair) => this.replacesWith(pair),
407
+ outranks: (pair, other) => this.outranks(pair, other),
408
+ bestValidPair: (pairs) => this.bestValidPair(pairs),
409
+ isTcpPair: (pair) => this.isTcpPair(pair),
410
+ check: (pair) => {
411
+ pair.handle = this.checkStart(pair);
412
+ },
413
+ complete: (pair) => this.checkComplete(pair),
414
+ sendNomination: (pair, signal, value) => this.sendNomination(pair, signal, value),
415
+ isStaleNomination: (pair, generation) => this.isStaleNomination(pair, generation),
416
+ roleConflict: () => this.switchRole(false),
417
+ allows: (pair) => this.failoverAllows(pair),
418
+ failoverReplaces: (pair) => this.switchNomination?.pair === pair ||
419
+ (this.selectionFailing() && this.failover.writable(pair)),
420
+ nominationEnded: (pair) => {
421
+ if (this.switchNomination?.pair === pair) {
422
+ this.switchNomination = undefined;
423
+ }
424
+ },
425
+ retriesForever: () => this.failoverEnabled(),
426
+ selectionDown: () => this.selectionFailing(),
427
+ })
428
+ });
429
+ /** See `NominationHint`; set by the restart that ends a provisional checklist. */
430
+ Object.defineProperty(this, "nominationHint", {
431
+ enumerable: true,
432
+ configurable: true,
433
+ writable: true,
434
+ value: void 0
435
+ });
436
+ /** USE-CANDIDATE re-sent for a pair selected before the agent became controlling (`confirmSelections`). */
437
+ Object.defineProperty(this, "selectionConfirmations", {
438
+ enumerable: true,
439
+ configurable: true,
440
+ writable: true,
441
+ value: new Set()
442
+ });
252
443
  /**
253
444
  * Aborted when the remote generation ends (restart, restartRemote, close):
254
445
  * every check and nomination transaction of that generation stops with it.
@@ -261,16 +452,21 @@ class Connection {
261
452
  * - `retryCheck` (487 role conflict / 401 retry): the handle of the check
262
453
  * it replaces and this signal (the retry is a `checkStart`).
263
454
  * - regular nomination in `checkStart` (toward an ICE-lite peer): the
264
- * check's signal; `isStaleNomination` guards `nominating`, the pair state
265
- * and `checkComplete`.
266
- * - `nominateTcpPair`: this signal; `isStaleNomination`.
267
- * - `checkProvisional` / `nominateProvisional`: `generation.checks`
268
- * (`endProvisional()`, a replacement pranswer, close); `belongs()`.
269
- * - `queryConsent`: a per-request `AbortController` and
270
- * `stopConsentLifecycle()`; `consentSessionId`.
455
+ * check's signal; `isStaleNomination` guards `liteNominating`, the pair
456
+ * state and `checkComplete`.
457
+ * - `RegularNomination` (live: `sendNomination`): this signal and the
458
+ * attempt's own, which `reset()` (restart, restartRemote,
459
+ * resetNominatedPair, close) and `invalidate()` (role change) abort; a
460
+ * result of a replaced attempt is ignored. Its delay timer is cleared by
461
+ * `reset()`.
462
+ * - `ProvisionalChecklist` checks and nominations: `generation.checks`
463
+ * (`end()`, a replacement pranswer, close); `belongs()`, and
464
+ * the provisional `RegularNomination` as above.
465
+ * - consent checks (`ConsentFreshness`): a per-request `AbortController`
466
+ * and `consent.stop()`; its session id.
271
467
  * - `serverReflexiveCandidate` (gathering): `protocol.close()`; otherwise
272
468
  * it ends by its retransmission timeout, and `stale()` drops the
273
- * candidate of an ended gather.
469
+ * candidate (or the failure) of an ended gather.
274
470
  * - TURN client requests: the `closing` signal and `TurnProtocol.close()`.
275
471
  * Regression tests: `tests/ice/check-cancel.test.ts`.
276
472
  */
@@ -286,19 +482,6 @@ class Connection {
286
482
  writable: true,
287
483
  value: false
288
484
  });
289
- /** Resolves when the agent closes: work that awaits the network stops waiting. */
290
- Object.defineProperty(this, "closedSignal", {
291
- enumerable: true,
292
- configurable: true,
293
- writable: true,
294
- value: void 0
295
- });
296
- Object.defineProperty(this, "signalClosed", {
297
- enumerable: true,
298
- configurable: true,
299
- writable: true,
300
- value: void 0
301
- });
302
485
  /** Aborted by close(): a TURN allocation still running is released. */
303
486
  Object.defineProperty(this, "closing", {
304
487
  enumerable: true,
@@ -307,11 +490,9 @@ class Connection {
307
490
  value: new AbortController()
308
491
  });
309
492
  /**
310
- * Results for connect(). Known constraint (as in develop): a restart
311
- * replaces the queue, so a connect() still waiting on the old one never
312
- * settles (the agent is still collected). It cannot simply return, since
313
- * the caller (webrtc's `TransactionActivation`) treats a returned start as
314
- * a connected ICE transport.
493
+ * Results for connect() of the current generation. A restart replaces the
494
+ * queue; a connect() of the replaced generation keeps the old one and
495
+ * stops on that generation's `remoteChecks` signal instead (connectError).
315
496
  */
316
497
  Object.defineProperty(this, "checkListState", {
317
498
  enumerable: true,
@@ -343,54 +524,208 @@ class Connection {
343
524
  writable: true,
344
525
  value: []
345
526
  });
346
- Object.defineProperty(this, "queryConsentHandle", {
527
+ /** RFC 7675 consent freshness of the selected pair. */
528
+ Object.defineProperty(this, "consent", {
347
529
  enumerable: true,
348
530
  configurable: true,
349
531
  writable: true,
350
- value: void 0
532
+ value: new consent_1.ConsentFreshness({
533
+ selected: () => this.nominated,
534
+ state: () => this.state,
535
+ setState: (state) => this.setState(state),
536
+ remoteGeneration: () => this.remoteGeneration,
537
+ remotePassword: () => this.remotePassword,
538
+ iceLite: () => this.iceLite,
539
+ integrityAlgorithm: () => this.options.messageIntegrity,
540
+ buildRequest: (pair) => this.buildRequest({
541
+ nominate: this.shouldNominateConsentRequest(pair),
542
+ nomination: this.consentNomination(pair),
543
+ localUsername: this.localUsername,
544
+ remoteUsername: this.remoteUsername,
545
+ iceControlling: this.iceControlling,
546
+ localCandidate: pair.localCandidate,
547
+ }),
548
+ generation: () => this.generation,
549
+ decorateRequest: (request, pair) => this.decorateSpedRequest(request, pair),
550
+ onResponse: (response, addr, pair, generation) => this.consumeSpedStun(response, addr, pair.protocol, pair, generation),
551
+ failover: {
552
+ enabled: () => this.failoverEnabled(),
553
+ liveness: (pair) => this.failover.livenessOf(pair),
554
+ thresholds: () => this.failoverThresholds,
555
+ responded: (pair) => {
556
+ this.failover.responded(pair);
557
+ this.onLinkChanged();
558
+ },
559
+ unanswered: (pair) => {
560
+ this.failover.unanswered(pair);
561
+ this.onLinkChanged();
562
+ },
563
+ expired: () => {
564
+ // No data may be sent any more, but a writable backup may still
565
+ // take over (the controlling agent nominates it, a controlled one
566
+ // waits for the peer to). The agent is `disconnected` meanwhile and
567
+ // fails unless the selection moves within
568
+ // FAILOVER_CONSENT_EXPIRED_GRACE (or once no writable backup is
569
+ // left, updateLinkState). The expired pair is not checked any more:
570
+ // it is used again only if selected anew.
571
+ if (!this.failover.hasWritableBackup()) {
572
+ this.failover.reset();
573
+ this.switching.stop();
574
+ return false;
575
+ }
576
+ this.startConsentExpiredGrace();
577
+ this.onLinkChanged();
578
+ return true;
579
+ },
580
+ },
581
+ })
582
+ });
583
+ /**
584
+ * Failover of the selected pair without an ICE restart (see
585
+ * `failoverEnabled`): the backup pairs it monitors and the liveness of
586
+ * the selected one.
587
+ */
588
+ Object.defineProperty(this, "failover", {
589
+ enumerable: true,
590
+ configurable: true,
591
+ writable: true,
592
+ value: new failover_1.FailoverMonitor(this.failoverHost())
351
593
  });
352
- /** RFC 7675 consent-to-send: application data may use the selected pair. */
353
- Object.defineProperty(this, "consentFresh", {
594
+ /**
595
+ * The pair a nomination that moves the selection off a pair that still
596
+ * outranks (or equals) it is sent for, until its outcome, and why
597
+ * (`failover`: `evaluateFailover`; `receiving`, `rtt`:
598
+ * `SelectionController`). When it succeeds the selection moves to it even
599
+ * if the old pair answered again meanwhile (the peer may already have taken
600
+ * the nomination). After `failover` and `receiving` the old pair's socket
601
+ * is demoted (D4).
602
+ * @see tests/ice/selection-controller.test.ts "receiving: a selection that recovers within RECEIVING_SWITCHING_DELAY stays; one that does not moves after it"
603
+ * @see tests/ice/selection-controller.test.ts "an RTT switch within the hold is not a failover: the old pair is not demoted"
604
+ */
605
+ Object.defineProperty(this, "switchNomination", {
354
606
  enumerable: true,
355
607
  configurable: true,
356
608
  writable: true,
357
- value: false
609
+ value: void 0
358
610
  });
359
- /** Invalidates in-flight consent callbacks on restart / close / replace / expire. */
360
- Object.defineProperty(this, "consentSessionId", {
611
+ /**
612
+ * The controlling agent's choice among the selection and the monitored
613
+ * backups by receiving state and RTT (libwebrtc's ICE controller).
614
+ */
615
+ Object.defineProperty(this, "switching", {
361
616
  enumerable: true,
362
617
  configurable: true,
363
618
  writable: true,
364
- value: 0
619
+ value: new selectionController_1.SelectionController({
620
+ active: () => this.iceControlling &&
621
+ this.replacesSelection() &&
622
+ this.failoverEnabled() &&
623
+ !this.selection.nominating &&
624
+ (this.state === "connected" || this.state === "completed") &&
625
+ !this.selectionDown(),
626
+ selected: () => this.nominated,
627
+ candidates: () => this.failover.backupPairs,
628
+ liveness: (pair) => this.failover.livenessOf(pair),
629
+ thresholds: () => this.failoverThresholds,
630
+ writable: (pair, now) => this.failover.writable(pair, now),
631
+ allows: (pair) => this.replacesWith(pair) && this.failoverAllows(pair),
632
+ comparePriority: (pair, other) => (0, iceBase_1.compareCandidatePairPriority)(pair.localCandidate, pair.remoteCandidate, other.localCandidate, other.remoteCandidate, this.iceControlling),
633
+ switchTo: (pair, reason) => {
634
+ this.switchNomination = { pair, reason };
635
+ this.selection.nominate(pair);
636
+ },
637
+ })
365
638
  });
366
- Object.defineProperty(this, "consentExpiryTimer", {
639
+ /** See `failoverThresholds`. */
640
+ Object.defineProperty(this, "failoverThresholdsCache", {
367
641
  enumerable: true,
368
642
  configurable: true,
369
643
  writable: true,
370
644
  value: void 0
371
645
  });
372
- Object.defineProperty(this, "consentRequestAbort", {
646
+ /**
647
+ * The selected pair's consent expired while a backup was writable: the
648
+ * agent fails when this fires unless the selection moved first
649
+ * (FAILOVER_CONSENT_EXPIRED_GRACE).
650
+ */
651
+ Object.defineProperty(this, "consentExpiredGrace", {
373
652
  enumerable: true,
374
653
  configurable: true,
375
654
  writable: true,
376
655
  value: void 0
377
656
  });
378
- /** ICE restart generation checked beside the selected current pair. */
379
- Object.defineProperty(this, "provisional", {
657
+ /** The state `disconnected` replaced, restored when the selection works again. */
658
+ Object.defineProperty(this, "stateBeforeDisconnect", {
380
659
  enumerable: true,
381
660
  configurable: true,
382
661
  writable: true,
383
662
  value: void 0
384
663
  });
664
+ /** Host, server-reflexive and relay gathering (`CandidateGatherer`). */
665
+ Object.defineProperty(this, "gatherer", {
666
+ enumerable: true,
667
+ configurable: true,
668
+ writable: true,
669
+ value: new candidateGatherer_1.CandidateGatherer({
670
+ options: () => this.options,
671
+ iceLite: () => this.iceLite,
672
+ generation: () => this.generation,
673
+ localUsername: () => this.localUsername,
674
+ protocols: () => this.protocols,
675
+ stunServers: () => this.stunServers,
676
+ turnServers: () => this.turnServers,
677
+ defaultStunServer: () => this.usesDefaultStunServer
678
+ ? { address: DEFAULT_STUN_SERVER, url: exports.DEFAULT_STUN_SERVER_URL }
679
+ : undefined,
680
+ isGathering: (generation) => this.isGathering(generation),
681
+ closing: () => this.closing.signal,
682
+ ensureProtocol: (protocol) => this.ensureProtocol(protocol),
683
+ pairLocalProtocol: (protocol) => this.pairLocalProtocol(protocol),
684
+ appendLocalCandidate: (candidate) => this.appendLocalCandidate(candidate),
685
+ emitCandidateError: (stale, generation, server, failure, local) => this.emitCandidateError(stale, generation, server, failure, local),
686
+ emitServerReached: (stale, generation, server) => this.emitServerReached(stale, generation, server),
687
+ })
688
+ });
385
689
  /**
386
- * Server-reflexive candidates each UDP socket advertised in its last
387
- * gathering (one per distinct mapping its STUN servers returned).
690
+ * Settles when the background server-reflexive queries of the current
691
+ * generation end (see {@link Connection.waitForLocalCandidatesEnd}).
388
692
  */
389
- Object.defineProperty(this, "reflexiveBySocket", {
693
+ Object.defineProperty(this, "localCandidatesEndPromise", {
694
+ enumerable: true,
695
+ configurable: true,
696
+ writable: true,
697
+ value: void 0
698
+ });
699
+ /** ICE restart generation checked beside the selected current pair. */
700
+ Object.defineProperty(this, "provisionalChecklist", {
390
701
  enumerable: true,
391
702
  configurable: true,
392
703
  writable: true,
393
- value: new WeakMap()
704
+ value: new provisional_1.ProvisionalChecklist({
705
+ closed: () => this.closed,
706
+ iceLite: () => this.iceLite,
707
+ iceControlling: () => this.iceControlling,
708
+ remoteIsLite: () => this.remoteIsLite,
709
+ localCandidatesEnd: () => this.localCandidatesEnd,
710
+ options: () => this.options,
711
+ protocols: () => this.protocols,
712
+ mdnsLookup: () => {
713
+ this.lookup ?? (this.lookup = new lookup_1.MdnsLookup());
714
+ return this.lookup;
715
+ },
716
+ isUncheckedPair: (pair) => this.isUncheckedPair(pair),
717
+ isWildcardProtocol: (protocol) => this.gatherer.isWildcardProtocol(protocol),
718
+ wildcardPathUncovered: (remoteCandidate) => this.gatherer.wildcardPathUncovered(remoteCandidate),
719
+ nominatesFullPeer: () => this.nominatesFullPeer(),
720
+ usesRegularNomination: () => this.usesRegularNomination(),
721
+ replacesWith: (pair) => this.replacesWith(pair),
722
+ regularNominationPairs: (pairs) => this.regularNominationPairs(pairs),
723
+ bestValidPair: (pairs) => this.bestValidPair(pairs),
724
+ outranks: (pair, other) => this.outranks(pair, other),
725
+ nominationDelayMs: () => this.nominationDelayMs,
726
+ buildRequest: (params) => this.buildRequest(params),
727
+ switchRole: (iceControlling) => this.switchRole(iceControlling),
728
+ })
394
729
  });
395
730
  Object.defineProperty(this, "onData", {
396
731
  enumerable: true,
@@ -410,174 +745,70 @@ class Connection {
410
745
  writable: true,
411
746
  value: new common_1.Event()
412
747
  });
413
- // RFC 7675 consent freshness
414
- Object.defineProperty(this, "queryConsent", {
748
+ /**
749
+ * A STUN server query or TURN allocation of the current generation's
750
+ * gathering failed (W3C `icecandidateerror`), synchronously and without
751
+ * changing the gathering: other servers and sockets go on, and gathering
752
+ * still completes. A server answering with an error gives its ERROR-CODE,
753
+ * once per local socket and generation. One that is not reached (timeout,
754
+ * `stunGatherTimeout`, DNS, connect or socket error) gives 701, once per
755
+ * server and generation and only when no local socket reached it (a STUN
756
+ * server is reported when the last socket's query ended). A TURN server's UDP attempt and its TCP fallback are
757
+ * one failure, reported when both failed (a server's error code wins over
758
+ * 701). A credential retry (401 / 438) that succeeds is not a failure.
759
+ * Nothing is fired for a replaced generation or after close (the event
760
+ * completes then). A STUN failure carries the host address of a socket
761
+ * that asked; a TURN one carries none. The built-in default STUN server (none
762
+ * configured, `useDefaultStunServer` not false) is named by the
763
+ * synthesized URL {@link DEFAULT_STUN_SERVER_URL} in `server.urls`.
764
+ */
765
+ Object.defineProperty(this, "onIceCandidateError", {
415
766
  enumerable: true,
416
767
  configurable: true,
417
768
  writable: true,
418
- value: () => {
419
- if (this.iceLite) {
420
- return;
421
- }
422
- // Invalidate any previous consent session before starting a new one.
423
- this.stopConsentLifecycle();
424
- const sessionId = this.consentSessionId;
425
- this.consentFresh = true;
426
- const handle = (0, helper_1.cancelable)(async (_, __, onCancel) => {
427
- let canceled = false;
428
- const cancelEvent = new AbortController();
429
- const clearConsentExpiry = () => {
430
- if (this.consentExpiryTimer === undefined) {
431
- return;
432
- }
433
- clearTimeout(this.consentExpiryTimer);
434
- this.consentExpiryTimer = undefined;
435
- };
436
- const refreshConsentExpiry = () => {
437
- // Only the active session may refresh the shared expiry timer.
438
- if (canceled || sessionId !== this.consentSessionId) {
439
- return;
440
- }
441
- clearConsentExpiry();
442
- this.consentExpiryTimer = setTimeout(() => {
443
- this.consentExpiryTimer = undefined;
444
- if (canceled || sessionId !== this.consentSessionId) {
445
- return;
446
- }
447
- if (this.state === "closed" || this.state === "failed") {
448
- return;
449
- }
450
- log("Consent to send expired");
451
- // Expire independently of request cadence / failure count (RFC 7675).
452
- this.consentFresh = false;
453
- this.consentSessionId++;
454
- this.consentRequestAbort?.abort();
455
- this.consentRequestAbort = undefined;
456
- if (this.queryConsentHandle === handle) {
457
- this.queryConsentHandle = undefined;
458
- }
459
- canceled = true;
460
- cancelEvent.abort();
461
- // Transport stays available for ICE restart; explicit close() uses "closed".
462
- this.setState("failed");
463
- }, iceBase_1.CONSENT_TIMEOUT * 1000);
464
- };
465
- onCancel.once(() => {
466
- canceled = true;
467
- // Avoid clearing a replacement session's timer/handle.
468
- if (sessionId === this.consentSessionId) {
469
- clearConsentExpiry();
470
- this.consentRequestAbort?.abort();
471
- this.consentRequestAbort = undefined;
472
- }
473
- cancelEvent.abort();
474
- if (this.queryConsentHandle === handle) {
475
- this.queryConsentHandle = undefined;
476
- }
477
- });
478
- // Initial ICE check success is the first valid consent response.
479
- refreshConsentExpiry();
480
- const randomizedConsentInterval = () => iceBase_1.CONSENT_INTERVAL * (0.8 + 0.4 * Math.random()) * 1000;
481
- // Cadence is measured between request *starts*, not response completions.
482
- let nextConsentAt = Date.now() + randomizedConsentInterval();
483
- const isTerminalState = () => this.state === "closed" || this.state === "failed";
484
- try {
485
- while (!isTerminalState() &&
486
- !canceled &&
487
- sessionId === this.consentSessionId) {
488
- await this.abortableDelay(Math.max(0, nextConsentAt - Date.now()), cancelEvent.signal);
489
- if (canceled ||
490
- isTerminalState() ||
491
- sessionId !== this.consentSessionId) {
492
- break;
493
- }
494
- // Fix next start time before awaiting any response (independent timers).
495
- nextConsentAt = Date.now() + randomizedConsentInterval();
496
- const nominated = this.nominated;
497
- if (!nominated) {
498
- break;
499
- }
500
- const pairId = nominated.id;
501
- const generation = this.remoteGeneration;
502
- const remotePassword = this.remotePassword;
503
- const { localUsername, remoteUsername, iceControlling } = this;
504
- const request = this.buildRequest({
505
- nominate: this.shouldNominateConsentRequest(nominated),
506
- localUsername,
507
- remoteUsername,
508
- iceControlling,
509
- localCandidate: nominated.localCandidate,
510
- });
511
- this.consentRequestAbort?.abort();
512
- const requestAbort = new AbortController();
513
- this.consentRequestAbort = requestAbort;
514
- nominated.consentRequestsSent++;
515
- nominated.requestsSent++;
516
- // RTT-aware wait (floor 500ms); independent of retransmissions: 0.
517
- const responseTimeout = (0, iceBase_1.consentResponseTimeoutMs)(nominated.rtt);
518
- const requestStartedAt = performance.now();
519
- // Do not await here: response wait must not stretch the 4–6s cadence.
520
- nominated.protocol
521
- .request(request, nominated.remoteAddr, Buffer.from(remotePassword, "utf8"), {
522
- retransmissions: 0,
523
- responseTimeout,
524
- signal: requestAbort.signal,
525
- onRequestSent: (attempt) => {
526
- if (attempt > 0) {
527
- nominated.retransmissionsSent++;
528
- }
529
- },
530
- })
531
- .then(() => {
532
- // Accept only responses for the current pair / generation / session.
533
- // Address / MESSAGE-INTEGRITY / response class are enforced in Transaction + protocol.
534
- if (sessionId !== this.consentSessionId || canceled) {
535
- return;
536
- }
537
- const state = this.state;
538
- if (state === "closed" || state === "failed") {
539
- return;
540
- }
541
- if (this.nominated?.id !== pairId) {
542
- return;
543
- }
544
- if (this.remoteGeneration !== generation) {
545
- return;
546
- }
547
- if (this.remotePassword !== remotePassword) {
548
- return;
549
- }
550
- const rtt = (performance.now() - requestStartedAt) / 1000; // seconds
551
- nominated.rtt = rtt;
552
- nominated.totalRoundTripTime += rtt;
553
- nominated.roundTripTimeMeasurements++;
554
- nominated.responsesReceived++;
555
- this.consentFresh = true;
556
- refreshConsentExpiry();
557
- if (state === "disconnected") {
558
- this.setState("connected");
559
- }
560
- })
561
- .catch((error) => {
562
- // Individual request loss is expected; keep monitoring (RFC 7675).
563
- if (sessionId === this.consentSessionId &&
564
- this.nominated?.id === pairId) {
565
- log("no stun response", error);
566
- }
567
- });
568
- }
569
- }
570
- catch (error) {
571
- // Abort during delay is normal on cancel / expire.
572
- }
573
- finally {
574
- if (sessionId === this.consentSessionId) {
575
- clearConsentExpiry();
576
- }
577
- }
578
- });
579
- this.queryConsentHandle = handle;
580
- }
769
+ value: new common_1.Event()
770
+ });
771
+ /**
772
+ * The current generation's gathering reported an error (werift extension,
773
+ * see {@link IceGatheringErrorInfo}). New reasons may be added: handle
774
+ * unknown values.
775
+ * @see packages/ice/tests/ice/interface-enumeration.test.ts「without servers or explicit addresses: ends with interface-enumeration-failed then no-candidates」
776
+ * @see packages/ice/tests/ice/interface-enumeration.test.ts「a STUN server still gives a server-reflexive candidate」
777
+ * @see packages/ice/tests/ice/interface-enumeration.test.ts「an unexpected exception reports gathering-failed, ends the generation and rejects」
778
+ * @see packages/ice/tests/ice/interface-enumeration.test.ts「restarting from the no-candidates listener leaves the new generation ungathered」
779
+ * @see packages/ice/tests/ice/interface-enumeration.test.ts「nothing is reported after close」
780
+ * @see packages/ice/tests/ice/interface-enumeration.test.ts「nothing is reported for a generation an ICE restart replaced」
781
+ * @see packages/ice/tests/ice/interface-enumeration.test.ts「a listener that throws does not stop the gathering or the later listeners」
782
+ */
783
+ Object.defineProperty(this, "onGatheringError", {
784
+ enumerable: true,
785
+ configurable: true,
786
+ writable: true,
787
+ value: new common_1.Event({
788
+ onListenerError: (error) => log("onGatheringError listener threw", error),
789
+ })
790
+ });
791
+ /**
792
+ * A STUN or TURN server of the current generation's gathering answered:
793
+ * a STUN query or TURN allocation gave a candidate, or the server sent an
794
+ * error response (see {@link IceServerReachedInfo}). Synchronous; nothing
795
+ * is fired for a replaced generation or after close.
796
+ */
797
+ Object.defineProperty(this, "onIceServerReached", {
798
+ enumerable: true,
799
+ configurable: true,
800
+ writable: true,
801
+ value: new common_1.Event()
802
+ });
803
+ /**
804
+ * Exact SPED Binding Response bytes keyed by STUN transaction id.
805
+ * Handshake only: TTL = STUN transaction lifetime, LRU-capped.
806
+ */
807
+ Object.defineProperty(this, "spedBindingCache", {
808
+ enumerable: true,
809
+ configurable: true,
810
+ writable: true,
811
+ value: new sped_binding_cache_1.SpedBindingResponseCache()
581
812
  });
582
813
  Object.defineProperty(this, "send", {
583
814
  enumerable: true,
@@ -588,7 +819,10 @@ class Connection {
588
819
  if (!this.canSendApplicationData()) {
589
820
  return;
590
821
  }
591
- const activePair = this.nominated;
822
+ const activePair = this.applicationDataPair();
823
+ if (!activePair) {
824
+ return;
825
+ }
592
826
  await activePair.protocol.sendData(data, activePair.remoteAddr);
593
827
  // Update statistics
594
828
  activePair.packetsSent++;
@@ -613,11 +847,23 @@ class Connection {
613
847
  const signal = AbortSignal.any([checks.signal, this.remoteChecks.signal]);
614
848
  const remoteGeneration = this.remoteGeneration;
615
849
  pair.updateState(iceBase_1.CandidatePairState.IN_PROGRESS);
616
- const result = {};
617
850
  const { remotePassword, remoteUsername, generation } = this;
618
851
  const localUsername = pair.localCandidate.ufrag ?? this.localUsername;
619
- // TCP pairs use regular nomination (see nominateTcpPairIfReady).
620
- const nominate = this.iceControlling && !this.remoteIsLite && !this.isTcpPair(pair);
852
+ const stopIfStale = () => {
853
+ if (!this.isStaleConnectivityCheck(pair, generation)) {
854
+ return false;
855
+ }
856
+ r();
857
+ return true;
858
+ };
859
+ // Semi-aggressive nomination: USE-CANDIDATE while nothing is selected
860
+ // and for a pair that outranks the selected one. Regular nomination
861
+ // (RegularNomination) and renomination (`SelectionReplacement.evaluate`) nominate
862
+ // with a separate check; an ordinary check carries nothing.
863
+ const nominate = this.usesSemiAggressiveNomination() &&
864
+ this.replacesWith(pair) &&
865
+ (!this.nominated ||
866
+ (this.outranks(pair, this.nominated) && this.failoverAllows(pair)));
621
867
  const request = this.buildRequest({
622
868
  nominate,
623
869
  localUsername,
@@ -625,19 +871,35 @@ class Connection {
625
871
  iceControlling: this.iceControlling,
626
872
  localCandidate: pair.localCandidate,
627
873
  });
874
+ if (!this.decorateSpedRequest(request, pair)) {
875
+ if (stopIfStale()) {
876
+ return;
877
+ }
878
+ pair.updateState(iceBase_1.CandidatePairState.FAILED);
879
+ this.checkComplete(pair);
880
+ r();
881
+ return;
882
+ }
628
883
  // Record start time for RTT calculation
629
884
  const startTime = performance.now();
630
885
  try {
631
886
  pair.requestsSent++;
632
887
  const [response, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(remotePassword, "utf8"), { ...this.checkRequestOptions(pair), signal });
888
+ if (stopIfStale()) {
889
+ return;
890
+ }
891
+ if (!this.bindingResponseSourceMatches(addr, pair)) {
892
+ pair.updateState(iceBase_1.CandidatePairState.FAILED);
893
+ this.checkComplete(pair);
894
+ r();
895
+ return;
896
+ }
633
897
  pair.responsesReceived++;
898
+ this.failover.responded(pair);
634
899
  // Calculate RTT
635
900
  const endTime = performance.now();
636
- const rtt = (endTime - startTime) / 1000; // Convert to seconds
637
- // Update RTT statistics
638
- pair.rtt = rtt;
639
- pair.totalRoundTripTime += rtt;
640
- pair.roundTripTimeMeasurements++;
901
+ const rtt = (endTime - startTime) / 1000;
902
+ pair.recordRoundTrip(rtt);
641
903
  log("response received", request.toJSON(), response.toJSON(), addr, {
642
904
  localUsername,
643
905
  remoteUsername,
@@ -645,16 +907,23 @@ class Connection {
645
907
  generation,
646
908
  rtt,
647
909
  });
648
- result.response = response;
649
- result.addr = addr;
910
+ this.spedRuntime?.tryMarkDirectHandshakeReady(pair, generation);
911
+ await this.consumeSpedStun(response, addr, pair.protocol, pair, generation);
912
+ if (stopIfStale()) {
913
+ return;
914
+ }
650
915
  }
651
916
  catch (error) {
652
917
  // A cancelled check (its handle resolved, or the agent closed and
653
918
  // cancelled its transactions) changes nothing.
654
919
  if (signal.aborted || error instanceof exceptions_1.TransactionCancelled) {
920
+ this.checkCancelled(pair, remoteGeneration);
655
921
  r();
656
922
  return;
657
923
  }
924
+ if (stopIfStale()) {
925
+ return;
926
+ }
658
927
  const exc = error;
659
928
  // 7.1.3.1. Failure Cases
660
929
  log("failure case", request.toJSON(), exc.response ? JSON.stringify(exc.response.toJSON(), null, 2) : error, {
@@ -689,25 +958,23 @@ class Connection {
689
958
  return;
690
959
  }
691
960
  }
692
- // # check remote address matches
693
- if (result.addr[0] !== pair.remoteAddr[0] ||
694
- result.addr[1] !== pair.remoteAddr[1]) {
695
- pair.updateState(iceBase_1.CandidatePairState.FAILED);
696
- this.checkComplete(pair);
697
- r();
961
+ if (stopIfStale()) {
698
962
  return;
699
963
  }
700
964
  // # success
701
- if (nominate || pair.remoteNominated) {
702
- // # nominated by agressive nomination or the remote party
965
+ // The peer's USE-CANDIDATE selects the pair only while this agent is
966
+ // controlled: one received before a role switch made it controlling is
967
+ // not a nomination any more (the peer is controlled now and waits for
968
+ // this agent's USE-CANDIDATE), so it nominates by itself below.
969
+ if (pair.remoteNominated && !this.iceControlling) {
970
+ // # nominated by the remote party
703
971
  pair.nominated = true;
704
972
  }
705
- else if (this.usesTcpRegularNomination(pair)) {
706
- // # nominated later by nominateTcpPairIfReady (from checkComplete)
707
- }
708
- else if (this.iceControlling && !this.nominating) {
709
- // # perform regular nomination
710
- this.nominating = true;
973
+ else if (this.iceControlling &&
974
+ this.remoteIsLite &&
975
+ !this.liteNominating) {
976
+ // # ICE-lite peer: nominate the first pair that succeeds
977
+ this.liteNominating = true;
711
978
  const request = this.buildRequest({
712
979
  nominate: true,
713
980
  localUsername,
@@ -715,10 +982,33 @@ class Connection {
715
982
  iceControlling: this.iceControlling,
716
983
  localCandidate: pair.localCandidate,
717
984
  });
985
+ if (!this.decorateSpedRequest(request, pair)) {
986
+ if (stopIfStale()) {
987
+ return;
988
+ }
989
+ pair.updateState(iceBase_1.CandidatePairState.FAILED);
990
+ this.checkComplete(pair);
991
+ r();
992
+ return;
993
+ }
718
994
  try {
719
995
  pair.requestsSent++;
720
- await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), { ...this.checkRequestOptions(pair), signal });
996
+ const [nomResponse, nomAddr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), { ...this.checkRequestOptions(pair), signal });
997
+ if (stopIfStale()) {
998
+ return;
999
+ }
1000
+ if (!this.bindingResponseSourceMatches(nomAddr, pair)) {
1001
+ pair.updateState(iceBase_1.CandidatePairState.FAILED);
1002
+ this.checkComplete(pair);
1003
+ r();
1004
+ return;
1005
+ }
721
1006
  pair.responsesReceived++;
1007
+ this.spedRuntime?.tryMarkDirectHandshakeReady(pair, generation);
1008
+ await this.consumeSpedStun(nomResponse, nomAddr, pair.protocol, pair, generation);
1009
+ if (stopIfStale()) {
1010
+ return;
1011
+ }
722
1012
  }
723
1013
  catch (error) {
724
1014
  // A nomination of a generation that ended (or a cancelled check)
@@ -729,7 +1019,10 @@ class Connection {
729
1019
  r();
730
1020
  return;
731
1021
  }
732
- this.nominating = false;
1022
+ this.liteNominating = false;
1023
+ if (stopIfStale()) {
1024
+ return;
1025
+ }
733
1026
  pair.updateState(iceBase_1.CandidatePairState.FAILED);
734
1027
  this.checkComplete(pair);
735
1028
  r();
@@ -739,6 +1032,15 @@ class Connection {
739
1032
  r();
740
1033
  return;
741
1034
  }
1035
+ if (stopIfStale()) {
1036
+ return;
1037
+ }
1038
+ pair.nominated = true;
1039
+ }
1040
+ else if (nominate &&
1041
+ this.iceControlling &&
1042
+ this.remoteGeneration === remoteGeneration) {
1043
+ // # semi-aggressive: the check that succeeded carried USE-CANDIDATE
742
1044
  pair.nominated = true;
743
1045
  }
744
1046
  pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
@@ -757,9 +1059,6 @@ class Connection {
757
1059
  }
758
1060
  });
759
1061
  this._iceControlling = _iceControlling;
760
- this.closedSignal = new Promise((resolve) => {
761
- this.signalClosed = resolve;
762
- });
763
1062
  this.options = {
764
1063
  ...iceBase_1.defaultOptions,
765
1064
  ...options,
@@ -794,10 +1093,10 @@ class Connection {
794
1093
  */
795
1094
  applyStunTurnServersFromOptions() {
796
1095
  const { stunServers, turnServers } = (0, iceBase_1.normalizeIceServerOptions)(this.options);
797
- this.stunServers =
798
- stunServers.length > 0 || this.options.useDefaultStunServer === false
799
- ? stunServers
800
- : [DEFAULT_STUN_SERVER];
1096
+ this.usesDefaultStunServer = !(stunServers.length > 0 || this.options.useDefaultStunServer === false);
1097
+ this.stunServers = this.usesDefaultStunServer
1098
+ ? [DEFAULT_STUN_SERVER]
1099
+ : stunServers;
801
1100
  this.turnServers = turnServers;
802
1101
  }
803
1102
  /** @deprecated The first of {@link Connection.stunServers}. */
@@ -834,10 +1133,9 @@ class Connection {
834
1133
  if (this.iceLite) {
835
1134
  value = false;
836
1135
  }
837
- // While a pair is selected, keep the negotiated role. ICE restart clears
838
- // `nominated`, so offer/answer role and RFC 8445 role-conflict repair can
839
- // reassign controlling/controlled for the new generation.
840
- if (this.nominated) {
1136
+ // RFC 8445 §6.1.1. tests/ice/ice.test.ts "an offer/answer without an ICE restart keeps the roles of the checks in progress (RFC 8445 §6.1.1)"
1137
+ // tests/ice/ice.test.ts "once the checks began only a role conflict changes the role; restartRemote() lets offer/answer assign it again"
1138
+ if (this.nominated || this.checksBegun) {
841
1139
  return;
842
1140
  }
843
1141
  this.applyIceControlling(value);
@@ -845,8 +1143,22 @@ class Connection {
845
1143
  get iceLite() {
846
1144
  return this.options.iceLite;
847
1145
  }
1146
+ /**
1147
+ * Keep the selected path of the generation a restart replaces: the peer
1148
+ * keeps sending media on it until it moves to the new selected pair
1149
+ * (RFC 8445 §9). Its datagrams stay deliverable as media only.
1150
+ */
1151
+ retainSelectedPairs() {
1152
+ const selected = [this.nominated, this.lastDataPair].filter((pair) => pair !== undefined && (0, datagram_1.isAuthenticatedHandshakePair)(pair));
1153
+ if (selected.length > 0) {
1154
+ this.previousSelectedPairs = [...new Set(selected)];
1155
+ }
1156
+ this.lastDataPair = undefined;
1157
+ }
848
1158
  async restart() {
1159
+ this.retainSelectedPairs();
849
1160
  this.generation++;
1161
+ this.abandonInFlightStunTransactions();
850
1162
  this.remoteGeneration++;
851
1163
  const previous = this.restarted
852
1164
  ? { [this.localUsername]: this.localPassword }
@@ -867,6 +1179,7 @@ class Connection {
867
1179
  [this.localUsername]: this.localPassword,
868
1180
  };
869
1181
  this.restarted = true;
1182
+ this.retireRemoteUsername();
870
1183
  this.remoteUsername = "";
871
1184
  this.remotePassword = "";
872
1185
  this.localCandidates = [];
@@ -875,12 +1188,19 @@ class Connection {
875
1188
  this.remoteCandidatesEndRequested = false;
876
1189
  this.remoteResolutions.clear();
877
1190
  this.localCandidatesEnd = false;
1191
+ this.localCandidatesEndPromise = undefined;
878
1192
  this.checksBegun = false;
1193
+ this.schedulingStopped = false;
879
1194
  this.state = "new";
880
1195
  this.lookup?.close?.();
881
1196
  this.lookup = undefined;
882
1197
  this.nominated = undefined;
883
- this.nominating = false;
1198
+ this.liteNominating = false;
1199
+ // Taken before `provisionalChecklist.end()` drops the provisional checklist.
1200
+ const hint = this.provisionalNominationHint();
1201
+ this.nomination.reset();
1202
+ this.selection.abort();
1203
+ this.nominationHint = hint;
884
1204
  this.cancelChecks();
885
1205
  this.checkList = [];
886
1206
  this.checkListDone = false;
@@ -897,8 +1217,94 @@ class Connection {
897
1217
  }
898
1218
  }
899
1219
  // Tear down consent timers/transactions; new credentials require a new session.
900
- this.stopConsentLifecycle();
901
- this.endProvisional();
1220
+ this.consent.stop();
1221
+ this.spedBindingCache.clear();
1222
+ this.spedRuntime?.reset(this.generation);
1223
+ this.provisionalChecklist.end();
1224
+ }
1225
+ /** DTLS handshake datagram on an authenticated current-generation pair. */
1226
+ async sendHandshakeOnAuthenticatedPair(pair, bytes, generation) {
1227
+ if (generation !== this.generation) {
1228
+ return;
1229
+ }
1230
+ if (!(0, datagram_1.isAuthenticatedHandshakePair)(pair)) {
1231
+ return;
1232
+ }
1233
+ this.spedRuntime?.pinHandshakePath(pair);
1234
+ await pair.protocol.sendData(bytes, pair.remoteAddr);
1235
+ }
1236
+ /**
1237
+ * Direct fallback only on a current-generation authenticated CandidatePair.
1238
+ * No pair (e.g. earlyChecks) means no wire send.
1239
+ */
1240
+ async maybeSendSpedFallback(protocol, addr, generation) {
1241
+ const runtime = this.spedRuntime;
1242
+ if (!runtime || generation !== this.generation) {
1243
+ return;
1244
+ }
1245
+ if (runtime.fallbackStarted || runtime.session.state !== "fallback") {
1246
+ return;
1247
+ }
1248
+ const pair = runtime.lastPath ?? this.findPairByAddr(protocol, addr);
1249
+ if (!pair || !(0, datagram_1.isAuthenticatedHandshakePair)(pair)) {
1250
+ return;
1251
+ }
1252
+ if (runtime.lastPath && !(0, runtime_1.sameCandidatePair)(runtime.lastPath, pair)) {
1253
+ return;
1254
+ }
1255
+ runtime.pinHandshakePath(pair);
1256
+ const packets = runtime.beginFallback();
1257
+ const sendDirect = await runtime.hooks.onFallbackFlight(packets);
1258
+ if (sendDirect === false) {
1259
+ return;
1260
+ }
1261
+ for (const packet of packets) {
1262
+ await this.sendHandshakeOnAuthenticatedPair(pair, packet, generation);
1263
+ }
1264
+ }
1265
+ /**
1266
+ * UDP prflx with a pending C070-less Binding: lock unsupported once
1267
+ * trickle proves host/srflx, or end-of-candidates / nomination leaves a
1268
+ * lasting prflx. Nomination is enough: RFC 8838 allows ICE to complete
1269
+ * before end-of-candidates, and a nominated pair must not gain new
1270
+ * trickle candidates.
1271
+ * @returns the pair that locked unsupported, if any.
1272
+ */
1273
+ settleSpedUnconfirmed(pair) {
1274
+ const runtime = this.spedRuntime;
1275
+ if (!runtime || runtime.session.peerSupport !== "unknown") {
1276
+ return undefined;
1277
+ }
1278
+ const pairs = pair ? [pair] : this.checkList;
1279
+ let locked;
1280
+ for (const candidate of pairs) {
1281
+ if (runtime.settleUnconfirmedPair(candidate, {
1282
+ endOfCandidates: this.remoteCandidatesEnd,
1283
+ authenticated: (0, datagram_1.isAuthenticatedHandshakePair)(candidate),
1284
+ nominated: candidate.nominated || this.nominated === candidate,
1285
+ })) {
1286
+ locked = candidate;
1287
+ }
1288
+ }
1289
+ return locked;
1290
+ }
1291
+ /**
1292
+ * Send the original L1 snapshot on the pair that locked fallback.
1293
+ * Prefer `preferredPair` so nomination settlement cannot race
1294
+ * `this.nominated` and land on an earlier authenticated checklist entry.
1295
+ */
1296
+ async flushSpedUnconfirmedFallback(preferredPair) {
1297
+ const runtime = this.spedRuntime;
1298
+ if (!runtime || runtime.session.state !== "fallback") {
1299
+ return;
1300
+ }
1301
+ const pair = preferredPair ??
1302
+ this.nominated ??
1303
+ this.checkList.find((candidate) => (0, datagram_1.isAuthenticatedHandshakePair)(candidate));
1304
+ if (!pair) {
1305
+ return;
1306
+ }
1307
+ await this.maybeSendSpedFallback(pair.protocol, pair.remoteAddr, this.generation);
902
1308
  }
903
1309
  /**
904
1310
  * Only the remote side restarted (new remote credentials in an answer to an
@@ -906,7 +1312,9 @@ class Connection {
906
1312
  * the selected pair start over; local credentials and candidates stay.
907
1313
  */
908
1314
  restartRemote() {
1315
+ this.retainSelectedPairs();
909
1316
  this.remoteGeneration++;
1317
+ this.retireRemoteUsername();
910
1318
  this.remoteUsername = "";
911
1319
  this.remotePassword = "";
912
1320
  this._remoteCandidates = [];
@@ -916,15 +1324,18 @@ class Connection {
916
1324
  this.checksBegun = false;
917
1325
  this.state = "new";
918
1326
  this.nominated = undefined;
919
- this.nominating = false;
1327
+ this.liteNominating = false;
1328
+ this.nomination.reset();
1329
+ this.selection.abort();
1330
+ this.nominationHint = undefined;
920
1331
  this.cancelChecks();
921
1332
  this.checkList = [];
922
1333
  this.checkListDone = false;
923
1334
  this.checkListState = new helper_1.PQueue();
924
1335
  this.earlyChecks = [];
925
1336
  this.earlyChecksDone = false;
926
- this.stopConsentLifecycle();
927
- this.endProvisional();
1337
+ this.consent.stop();
1338
+ this.provisionalChecklist.end();
928
1339
  }
929
1340
  /**
930
1341
  * Stop the checks and nominations in flight for the checklist a restart
@@ -935,36 +1346,19 @@ class Connection {
935
1346
  this.remoteChecks = new AbortController();
936
1347
  for (const pair of this.checkList)
937
1348
  pair.handle?.resolve?.();
938
- }
939
- /**
940
- * Drop the provisional generation and stop the checks still in flight for
941
- * it (their retransmissions would outlive it).
942
- */
943
- endProvisional() {
944
- this.provisional?.checks.abort();
945
- this.provisional = undefined;
1349
+ this.selection.clearRetries();
1350
+ this.failover.reset();
1351
+ this.switching.stop();
1352
+ this.clearConsentExpiredGrace();
946
1353
  }
947
1354
  /** Accept provisional checks without changing the selected current pair. */
948
1355
  stageLocalCredentials(usernameFragment, password, gatherOptions) {
949
1356
  this.userHistory[usernameFragment] = password;
950
- this.endProvisional();
951
- this.provisional = {
952
- localUsername: usernameFragment,
953
- localPassword: password,
954
- gatherOptions,
955
- remoteCandidates: [],
956
- remoteCandidatesEnd: false,
957
- remoteCandidatesEndRequested: false,
958
- resolutions: new Set(),
959
- revision: 0,
960
- pairs: [],
961
- started: false,
962
- checks: new AbortController(),
963
- };
1357
+ this.provisionalChecklist.stage(usernameFragment, password, gatherOptions);
964
1358
  }
965
1359
  discardStagedLocalCredentials(usernameFragment) {
966
1360
  if (this.provisional?.localUsername === usernameFragment) {
967
- this.endProvisional();
1361
+ this.provisionalChecklist.end();
968
1362
  }
969
1363
  if (usernameFragment !== this.localUsername) {
970
1364
  delete this.userHistory[usernameFragment];
@@ -972,281 +1366,17 @@ class Connection {
972
1366
  }
973
1367
  /** Remote credentials of the provisional generation (pranswer). */
974
1368
  setProvisionalRemoteParams({ usernameFragment, password, }) {
975
- const generation = this.provisional;
976
- if (!generation)
977
- return;
978
- if (generation.remoteUsername === usernameFragment &&
979
- generation.remotePassword === password) {
980
- return;
981
- }
982
- // A replacement pranswer starts a new provisional checklist; candidates
983
- // still resolving for the replaced one are dropped by `revision`.
984
- generation.remoteUsername = usernameFragment;
985
- generation.remotePassword = password;
986
- generation.remoteCandidates = [];
987
- generation.remoteCandidatesEnd = false;
988
- generation.remoteCandidatesEndRequested = false;
989
- generation.resolutions.clear();
990
- generation.revision++;
991
- generation.checks.abort();
992
- generation.checks = new AbortController();
993
- generation.pairs = [];
994
- generation.nominated = undefined;
995
- generation.nominating = false;
1369
+ this.provisionalChecklist.setRemoteParams({ usernameFragment, password });
996
1370
  }
997
1371
  async addProvisionalRemoteCandidate(remoteCandidate) {
998
- const generation = this.provisional;
999
- if (!generation || this.closed)
1000
- return;
1001
- const revision = generation.revision;
1002
- const current = () => !this.closed &&
1003
- this.provisional === generation &&
1004
- generation.revision === revision;
1005
- if (!remoteCandidate) {
1006
- if (generation.remoteCandidatesEnd ||
1007
- generation.remoteCandidatesEndRequested) {
1008
- return;
1009
- }
1010
- // Candidates that arrived before end-of-candidates finish first.
1011
- generation.remoteCandidatesEndRequested = true;
1012
- if (generation.resolutions.size > 0) {
1013
- await Promise.allSettled([...generation.resolutions]);
1014
- if (!current())
1015
- return;
1016
- }
1017
- generation.remoteCandidatesEnd = true;
1018
- return;
1019
- }
1020
- // RFC 8838: a completed generation takes no further candidates.
1021
- if (generation.remoteCandidatesEnd ||
1022
- generation.remoteCandidatesEndRequested) {
1023
- return;
1024
- }
1025
- if (remoteCandidate.host.includes(".local")) {
1026
- try {
1027
- if (!this.lookup) {
1028
- this.lookup = new lookup_1.MdnsLookup();
1029
- }
1030
- const resolution = this.lookup.lookup(remoteCandidate.host);
1031
- generation.resolutions.add(resolution);
1032
- try {
1033
- remoteCandidate.host = await resolution;
1034
- }
1035
- finally {
1036
- generation.resolutions.delete(resolution);
1037
- }
1038
- }
1039
- catch (error) {
1040
- return;
1041
- }
1042
- // The generation may have been replaced or completed while resolving.
1043
- if (!current() || generation.remoteCandidatesEnd)
1044
- return;
1045
- }
1046
- try {
1047
- (0, iceBase_1.validateRemoteCandidate)(remoteCandidate);
1048
- }
1049
- catch (error) {
1050
- return;
1051
- }
1052
- if (!current() ||
1053
- generation.remoteCandidates.some((c) => c.host === remoteCandidate.host &&
1054
- c.port === remoteCandidate.port &&
1055
- c.transport.toLowerCase() === remoteCandidate.transport.toLowerCase())) {
1056
- return;
1057
- }
1058
- generation.remoteCandidates.push(remoteCandidate);
1059
- for (const protocol of this.protocols) {
1060
- this.tryProvisionalPair(generation, protocol, remoteCandidate);
1061
- }
1372
+ await this.provisionalChecklist.addRemoteCandidate(remoteCandidate);
1062
1373
  }
1063
1374
  /** Start checks for the provisional generation; the selected pair is kept. */
1064
1375
  startProvisionalChecks() {
1065
- const generation = this.provisional;
1066
- if (!generation || generation.started)
1067
- return;
1068
- generation.started = true;
1069
- for (const remoteCandidate of generation.remoteCandidates) {
1070
- for (const protocol of this.protocols) {
1071
- this.tryProvisionalPair(generation, protocol, remoteCandidate);
1072
- }
1073
- }
1074
- for (const pair of generation.pairs) {
1075
- void this.checkProvisional(generation, pair);
1076
- }
1376
+ this.provisionalChecklist.start();
1077
1377
  }
1078
1378
  get provisionalNominated() {
1079
- return this.provisional?.nominated;
1080
- }
1081
- tryProvisionalPair(generation, protocol, remoteCandidate) {
1082
- if (!protocol.localCandidate?.canPairWith(remoteCandidate) ||
1083
- !this.allowsProvisional(generation, protocol) ||
1084
- (protocol.localCandidate.transport.toLowerCase() === "tcp" &&
1085
- protocol.localCandidate.tcptype === "passive" &&
1086
- remoteCandidate.type !== "prflx") ||
1087
- generation.pairs.some((pair) => pair.protocol === protocol &&
1088
- pair.remoteCandidate === remoteCandidate)) {
1089
- return;
1090
- }
1091
- const pair = new iceBase_1.CandidatePair(protocol, remoteCandidate, this.iceControlling);
1092
- // The provisional checklist admits the same pairs as the live one.
1093
- if (this.options.filterCandidatePair &&
1094
- !this.options.filterCandidatePair(pair)) {
1095
- return;
1096
- }
1097
- pair.updateState(iceBase_1.CandidatePairState.WAITING);
1098
- generation.pairs.push(pair);
1099
- if (generation.started)
1100
- void this.checkProvisional(generation, pair);
1101
- }
1102
- async checkProvisional(generation, pair, retry = true) {
1103
- const revision = generation.revision;
1104
- // A check belongs to one checklist: a replacement pranswer (new revision)
1105
- // or a replaced generation makes its outcome meaningless.
1106
- const belongs = () => this.provisional === generation &&
1107
- generation.revision === revision &&
1108
- generation.pairs.includes(pair);
1109
- if (
1110
- // An ICE-lite agent only answers checks (RFC 8445 §2.5), in the
1111
- // provisional generation as in the live one.
1112
- this.iceLite ||
1113
- !belongs() ||
1114
- !generation.started ||
1115
- !generation.remoteUsername ||
1116
- !generation.remotePassword ||
1117
- [
1118
- iceBase_1.CandidatePairState.IN_PROGRESS,
1119
- iceBase_1.CandidatePairState.SUCCEEDED,
1120
- ].includes(pair.state)) {
1121
- return;
1122
- }
1123
- pair.updateState(iceBase_1.CandidatePairState.IN_PROGRESS);
1124
- const nominate = this.iceControlling && !this.remoteIsLite;
1125
- const request = this.buildRequest({
1126
- nominate,
1127
- localUsername: generation.localUsername,
1128
- remoteUsername: generation.remoteUsername,
1129
- iceControlling: this.iceControlling,
1130
- localCandidate: pair.localCandidate,
1131
- });
1132
- try {
1133
- pair.requestsSent++;
1134
- const [, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(generation.remotePassword, "utf8"), {
1135
- retransmissions: pair.localCandidate.transport.toLowerCase() === "tcp" ? 0 : 4,
1136
- signal: generation.checks.signal,
1137
- });
1138
- pair.responsesReceived++;
1139
- if (!belongs())
1140
- return;
1141
- if (addr[0] !== pair.remoteAddr[0] || addr[1] !== pair.remoteAddr[1]) {
1142
- pair.updateState(iceBase_1.CandidatePairState.FAILED);
1143
- return;
1144
- }
1145
- }
1146
- catch (error) {
1147
- if (!belongs())
1148
- return;
1149
- const code = error.response?.getAttributeValue("ERROR-CODE")?.[0];
1150
- pair.updateState(iceBase_1.CandidatePairState.FAILED);
1151
- if (code === 487 && retry) {
1152
- this.switchRole(request.attributesKeys.includes("ICE-CONTROLLED"));
1153
- pair.updateState(iceBase_1.CandidatePairState.WAITING);
1154
- return this.checkProvisional(generation, pair, false);
1155
- }
1156
- return;
1157
- }
1158
- if (nominate || pair.remoteNominated)
1159
- pair.nominated = true;
1160
- pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
1161
- if (!pair.nominated &&
1162
- this.iceControlling &&
1163
- !generation.nominated &&
1164
- !generation.nominating) {
1165
- // Regular nomination (the peer is ICE-lite, so the checks carried no
1166
- // USE-CANDIDATE), as the live checklist does: nominate the first pair
1167
- // that succeeded with a check that carries it.
1168
- await this.nominateProvisional(generation, pair, belongs);
1169
- }
1170
- if (pair.nominated && !generation.nominated) {
1171
- log("provisional nominated", pair.toJSON());
1172
- generation.nominated = pair;
1173
- }
1174
- }
1175
- async nominateProvisional(generation, pair, belongs) {
1176
- generation.nominating = true;
1177
- const request = this.buildRequest({
1178
- nominate: true,
1179
- localUsername: generation.localUsername,
1180
- remoteUsername: generation.remoteUsername,
1181
- iceControlling: this.iceControlling,
1182
- localCandidate: pair.localCandidate,
1183
- });
1184
- try {
1185
- pair.requestsSent++;
1186
- await pair.protocol.request(request, pair.remoteAddr, Buffer.from(generation.remotePassword, "utf8"), {
1187
- retransmissions: pair.localCandidate.transport.toLowerCase() === "tcp" ? 0 : 4,
1188
- // endProvisional / a replacement pranswer stops it with the checks.
1189
- signal: generation.checks.signal,
1190
- });
1191
- pair.responsesReceived++;
1192
- if (belongs())
1193
- pair.nominated = true;
1194
- }
1195
- catch (error) {
1196
- log("provisional regular nomination failed", error);
1197
- }
1198
- finally {
1199
- if (belongs())
1200
- generation.nominating = false;
1201
- }
1202
- }
1203
- /** Incoming check for the provisional ufrag; never touches the current checklist. */
1204
- checkIncomingProvisional(generation, message, addr, protocol) {
1205
- // A socket the staged generation drops at the commit takes no pair.
1206
- if (!this.allowsProvisional(generation, protocol))
1207
- return;
1208
- // Only checks from the remote credentials of the current checklist count
1209
- // (a replacement pranswer replaced any earlier ones).
1210
- const txUsername = message.getAttributeValue("USERNAME");
1211
- const sender = typeof txUsername === "string"
1212
- ? decodeTxUsername(txUsername).localUsername
1213
- : undefined;
1214
- if (generation.remoteUsername && sender !== generation.remoteUsername) {
1215
- return;
1216
- }
1217
- const [host, port] = addr;
1218
- let remoteCandidate = generation.remoteCandidates.find((c) => c.host === host && c.port === port);
1219
- if (!remoteCandidate) {
1220
- 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"
1221
- ? (0, candidate_1.remoteTcpTypeForIncoming)(protocol.localCandidate.tcptype)
1222
- : undefined, undefined, undefined);
1223
- generation.remoteCandidates.push(remoteCandidate);
1224
- }
1225
- let pair = generation.pairs.find((p) => p.protocol === protocol && p.remoteCandidate === remoteCandidate);
1226
- if (!pair) {
1227
- pair = new iceBase_1.CandidatePair(protocol, remoteCandidate, this.iceControlling);
1228
- pair.updateState(iceBase_1.CandidatePairState.WAITING);
1229
- generation.pairs.push(pair);
1230
- }
1231
- pair.noteIncomingRequest(message.transactionIdHex);
1232
- pair.requestsReceived++;
1233
- pair.responsesSent++;
1234
- if (message.attributesKeys.includes("USE-CANDIDATE") &&
1235
- !this.iceControlling) {
1236
- pair.remoteNominated = true;
1237
- if (this.iceLite || pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
1238
- pair.nominated = true;
1239
- pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
1240
- generation.nominated ?? (generation.nominated = pair);
1241
- }
1242
- }
1243
- if (!this.iceLite &&
1244
- [
1245
- iceBase_1.CandidatePairState.WAITING,
1246
- iceBase_1.CandidatePairState.FAILED,
1247
- ].includes(pair.state)) {
1248
- void this.checkProvisional(generation, pair);
1249
- }
1379
+ return this.provisionalChecklist.nominated;
1250
1380
  }
1251
1381
  /** Called after restart, before re-gathering the chosen generation. */
1252
1382
  commitLocalCredentials(usernameFragment, password) {
@@ -1276,19 +1406,55 @@ class Connection {
1276
1406
  pair.handle?.resolve?.();
1277
1407
  }
1278
1408
  this.checkList = this.checkList.filter((pair) => !stale(pair.remoteCandidate));
1409
+ this.nomination.evaluate();
1279
1410
  }
1280
1411
  resetNominatedPair() {
1281
1412
  log("resetNominatedPair");
1282
1413
  this.nominated = undefined;
1283
- this.nominating = false;
1414
+ this.liteNominating = false;
1415
+ this.nomination.reset();
1416
+ this.selection.abort();
1417
+ this.nominationHint = undefined;
1418
+ this.failover.reset();
1419
+ this.switching.stop();
1420
+ this.clearConsentExpiredGrace();
1284
1421
  // Drop old pair's consent timers/transactions; restarted when a new pair is nominated.
1285
- this.stopConsentLifecycle();
1422
+ this.consent.stop();
1423
+ }
1424
+ get remoteIce2() {
1425
+ return this.remoteIceOptions.includes("ice2");
1426
+ }
1427
+ setRemoteIceOptions(options) {
1428
+ log("setRemoteIceOptions", options);
1429
+ this.remoteIceOptions = [...options];
1430
+ this.remoteRenomination = options.includes("renomination");
1286
1431
  }
1287
1432
  setRemoteParams({ iceLite, usernameFragment, password, }) {
1288
1433
  log("setRemoteParams", { iceLite, usernameFragment, password });
1289
1434
  this.remoteIsLite = iceLite;
1435
+ if (usernameFragment !== this.remoteUsername)
1436
+ this.retireRemoteUsername();
1437
+ this.retiredRemoteUsernames = this.retiredRemoteUsernames.filter((retired) => retired !== usernameFragment);
1290
1438
  this.remoteUsername = usernameFragment;
1291
1439
  this.remotePassword = password;
1440
+ this.spedRuntime?.syncPathMtuFromConnection(this);
1441
+ }
1442
+ retireRemoteUsername() {
1443
+ if (!this.remoteUsername)
1444
+ return;
1445
+ this.retiredRemoteUsernames = [
1446
+ ...this.retiredRemoteUsernames.filter((u) => u !== this.remoteUsername),
1447
+ this.remoteUsername,
1448
+ ].slice(-RETIRED_REMOTE_USERNAMES_MAX);
1449
+ }
1450
+ /** A check sent by a remote generation that was replaced. */
1451
+ isRetiredRemoteCheck(message) {
1452
+ const txUsername = message.getAttributeValue("USERNAME");
1453
+ if (typeof txUsername !== "string")
1454
+ return false;
1455
+ const sender = (0, checkMessages_1.decodeTxUsername)(txUsername).localUsername;
1456
+ return (sender !== this.remoteUsername &&
1457
+ this.retiredRemoteUsernames.includes(sender));
1292
1458
  }
1293
1459
  // 4.1.1 Gathering Candidates
1294
1460
  /**
@@ -1301,63 +1467,180 @@ class Connection {
1301
1467
  * allocation), so a caller may let it finish in the background.
1302
1468
  */
1303
1469
  async gatherCandidates() {
1470
+ const generation = this.generation;
1304
1471
  if (!this.localCandidatesStart) {
1305
1472
  this.localCandidatesStart = true;
1306
- const generation = this.generation;
1307
- // An ICE restart allocates TURN afresh, which is how a restart recovers
1308
- // from an allocation that died: the previous one leaves the generation.
1309
- const previousTurn = this.protocols.filter((protocol) => protocol.localCandidate?.type === "relay");
1310
- // The generation keeps only the sockets a fresh gathering with the
1311
- // current options would open: a relay-only policy or useTcp turned off
1312
- // since the previous generation closes the kept host (UDP / TCP)
1313
- // sockets, so they are neither advertised, paired nor reachable.
1314
- const excluded = this.protocols.filter((protocol) => !previousTurn.includes(protocol) &&
1315
- !!protocol.localCandidate &&
1316
- !(0, iceBase_1.isCandidateAllowedByGatherOptions)(protocol.localCandidate, this.options));
1317
- this.protocols = this.protocols.filter((protocol) => !previousTurn.includes(protocol) && !excluded.includes(protocol));
1318
- void Promise.allSettled([...previousTurn, ...excluded].map((protocol) => protocol.close()));
1319
- // ICE restart keeps transport protocols; re-advertise their host candidates
1320
- // with the new generation / ufrag before gathering additional addresses.
1321
- for (const protocol of this.protocols) {
1322
- if (protocol.localCandidate) {
1323
- protocol.localCandidate.generation = this.generation;
1324
- protocol.localCandidate.ufrag = this.localUsername;
1325
- this.appendLocalCandidate(protocol.localCandidate);
1326
- for (const reflexive of this.reflexiveBySocket.get(protocol) ?? []) {
1327
- this.appendLocalCandidate(this.withGeneration(reflexive));
1328
- }
1473
+ try {
1474
+ await this.gatherGeneration(generation);
1475
+ }
1476
+ catch (error) {
1477
+ // テスト: interface-enumeration.test.ts「an unexpected exception reports gathering-failed, ends the generation and rejects」「a second gatherCandidates() reports nothing more and the generation stays ended」
1478
+ log("gatherCandidates failed", error);
1479
+ this.emitGatheringError(generation, gatheringError_1.IceGatheringErrorReason.gatheringFailed, `gathering failed: ${errorMessage(error)}`, error);
1480
+ if (this.isGathering(generation) && !this.localCandidatesEnd) {
1481
+ this.endLocalCandidates(generation);
1329
1482
  }
1483
+ throw error;
1330
1484
  }
1331
- // A family bound to an explicit interface address gathers only that
1332
- // address, so the advertised host candidate is the socket's address.
1333
- const address = (0, resolveHostAddresses_1.resolveHostAddresses)({
1334
- enumerated: (0, utils_1.getHostAddresses)(this.options.useIpv4, this.options.useIpv6, {
1335
- useLinkLocalAddress: this.options.useLinkLocalAddress,
1336
- }),
1337
- interfaceAddresses: this.options.interfaceAddresses,
1338
- additionalHostAddresses: this.options.additionalHostAddresses,
1339
- useIpv4: this.options.useIpv4,
1340
- useIpv6: this.options.useIpv6,
1341
- log,
1342
- });
1343
- const candidatePromises = this.getCandidatePromises(address, this.options.stunGatherTimeout, generation);
1344
- // close() ends the gathering at once: the continuations above close
1345
- // whatever a server query still opens for a closed agent.
1346
- await Promise.race([
1347
- Promise.allSettled(candidatePromises),
1348
- this.closedSignal,
1349
- ]);
1350
- // A later ICE restart (or close) owns the agent now: this gathering
1351
- // neither completes that generation nor touches its state.
1352
- if (!this.isGathering(generation))
1353
- return;
1354
- this.localCandidatesEnd = true;
1355
1485
  }
1356
1486
  // Gathering that finishes after connectivity checks began (an ICE restart
1357
1487
  // keeps gathering from its servers) must not overwrite their state: the
1358
1488
  // agent stays "new" while checking, and only the checks' outcome moves it.
1359
- if (this.state === "new" && !this.checksBegun)
1489
+ if (this.generation === generation &&
1490
+ this.state === "new" &&
1491
+ !this.checksBegun) {
1360
1492
  this.setState("completed");
1493
+ }
1494
+ }
1495
+ /** @see packages/ice/tests/ice/interface-enumeration.test.ts「an unexpected exception reports gathering-failed, ends the generation and rejects」 */
1496
+ async gatherGeneration(generation) {
1497
+ // An ICE restart allocates TURN afresh, which is how a restart recovers
1498
+ // from an allocation that died: the previous one leaves the generation.
1499
+ const previousTurn = this.protocols.filter((protocol) => protocol.localCandidate?.type === "relay");
1500
+ // The generation keeps only the sockets a fresh gathering with the
1501
+ // current options would open: a relay-only policy or useTcp turned off
1502
+ // since the previous generation closes the kept host (UDP / TCP)
1503
+ // sockets, so they are neither advertised, paired nor reachable.
1504
+ const excluded = this.protocols.filter((protocol) => !previousTurn.includes(protocol) &&
1505
+ !!protocol.localCandidate &&
1506
+ !(0, iceBase_1.isCandidateAllowedByGatherOptions)(protocol.localCandidate, this.options));
1507
+ this.protocols = this.protocols.filter((protocol) => !previousTurn.includes(protocol) && !excluded.includes(protocol));
1508
+ void Promise.allSettled([...previousTurn, ...excluded].map((protocol) => protocol.close()));
1509
+ // ICE restart keeps transport protocols; re-advertise their host candidates
1510
+ // with the new generation / ufrag before gathering additional addresses.
1511
+ for (const [family, wildcard] of this.gatherer.wildcardProtocols) {
1512
+ if (!this.protocols.includes(wildcard)) {
1513
+ // Closed with the excluded sockets, or still opening for the
1514
+ // replaced generation: a fresh one is opened if needed.
1515
+ this.gatherer.wildcardProtocols.delete(family);
1516
+ }
1517
+ }
1518
+ for (const protocol of this.protocols) {
1519
+ if (protocol.localCandidate) {
1520
+ protocol.localCandidate.generation = this.generation;
1521
+ protocol.localCandidate.ufrag = this.localUsername;
1522
+ // A wildcard socket's local candidate is one of its
1523
+ // server-reflexive candidates, re-advertised below.
1524
+ if (!this.gatherer.isWildcardProtocol(protocol)) {
1525
+ this.appendLocalCandidate(protocol.localCandidate);
1526
+ }
1527
+ for (const reflexive of this.gatherer.reflexiveBySocket.get(protocol) ??
1528
+ []) {
1529
+ this.appendLocalCandidate(this.withGeneration(reflexive));
1530
+ }
1531
+ }
1532
+ }
1533
+ // テスト: interface-enumeration.test.ts「without servers or explicit addresses: ends with interface-enumeration-failed then no-candidates」「an explicit interfaceAddresses.udp4 still gives its host candidate」「additionalHostAddresses are gathered on a wildcard socket」「a STUN server still gives a server-reflexive candidate」「a TURN server still gives a relay candidate」
1534
+ const enumeration = (0, hostInterfaces_1.readNetworkInterfaces)();
1535
+ if (enumeration.error !== undefined) {
1536
+ log("network interface enumeration failed", enumeration.error);
1537
+ this.emitGatheringError(generation, gatheringError_1.IceGatheringErrorReason.interfaceEnumerationFailed, `network interface enumeration failed: ${errorMessage(enumeration.error)}`, enumeration.error);
1538
+ }
1539
+ // A family bound to an explicit interface address gathers only that
1540
+ // address, so the advertised host candidate is the socket's address.
1541
+ const address = (0, resolveHostAddresses_1.resolveHostAddresses)({
1542
+ enumerated: (0, hostInterfaces_1.getHostInterfaceAddresses)(this.options.useIpv4, this.options.useIpv6, {
1543
+ useLinkLocalAddress: this.options.useLinkLocalAddress,
1544
+ }, enumeration.interfaces),
1545
+ assigned: (0, hostInterfaces_1.getAssignedInterfaceAddresses)(enumeration.interfaces),
1546
+ interfaceAddresses: this.options.interfaceAddresses,
1547
+ additionalHostAddresses: this.options.additionalHostAddresses,
1548
+ useIpv4: this.options.useIpv4,
1549
+ useIpv6: this.options.useIpv6,
1550
+ log,
1551
+ });
1552
+ // The default-route address of each family: the source address of the
1553
+ // route to the configured STUN / TURN servers (none without one: no
1554
+ // other address is probed). Its host candidate gets the highest local preference, and its
1555
+ // socket is a representative of the family's server-reflexive queries.
1556
+ // Probed while the sockets bind: no server work waits for it.
1557
+ const defaultRoutes = this.untilSettledOrClosed((0, defaultRoute_1.getDefaultRouteAddresses)(this.options.useIpv4, this.options.useIpv6, [
1558
+ ...this.stunServers.map(([host]) => host),
1559
+ ...this.turnServers.map(({ address: [host] }) => host),
1560
+ ]), []);
1561
+ const { primary, background } = this.gatherer.candidatePromises(address, this.options.stunGatherTimeout, generation, defaultRoutes);
1562
+ // close() ends the gathering at once: the continuations above close
1563
+ // whatever a server query still opens for a closed agent.
1564
+ await this.untilSettledOrClosed(Promise.allSettled(primary), undefined);
1565
+ // A later ICE restart (or close) owns the agent now: this gathering
1566
+ // neither completes that generation nor touches its state.
1567
+ if (!this.isGathering(generation))
1568
+ return;
1569
+ const pending = background.filter(({ settled }) => !settled);
1570
+ if (pending.length === 0) {
1571
+ this.endLocalCandidates(generation);
1572
+ }
1573
+ else {
1574
+ // The other host sockets' server-reflexive candidates trickle in;
1575
+ // end-of-candidates follows the last of them.
1576
+ this.localCandidatesEndPromise = this.untilSettledOrClosed(Promise.allSettled(pending.map(({ query }) => query)), undefined).then(() => {
1577
+ if (!this.isGathering(generation))
1578
+ return;
1579
+ this.endLocalCandidates(generation);
1580
+ if (this.checksBegun)
1581
+ this.concludeCheckListIfExhausted();
1582
+ });
1583
+ }
1584
+ }
1585
+ /** @see packages/ice/tests/ice/interface-enumeration.test.ts「without servers or explicit addresses: ends with interface-enumeration-failed then no-candidates」 */
1586
+ endLocalCandidates(generation) {
1587
+ if (this.localCandidates.length === 0) {
1588
+ this.emitGatheringError(generation, gatheringError_1.IceGatheringErrorReason.noCandidates, "gathering ended without any local candidate");
1589
+ }
1590
+ // テスト: interface-enumeration.test.ts「restarting from the no-candidates listener」
1591
+ if (!this.isGathering(generation))
1592
+ return;
1593
+ this.localCandidatesEnd = true;
1594
+ this.wakeIncomingCheckWaits();
1595
+ }
1596
+ /** @see packages/ice/tests/ice/interface-enumeration.test.ts「nothing is reported after close」 */
1597
+ emitGatheringError(generation, reason, errorText, cause) {
1598
+ if (!this.isGathering(generation) || this.closing.signal.aborted)
1599
+ return;
1600
+ const info = {
1601
+ reason,
1602
+ errorText,
1603
+ ...(cause !== undefined ? { cause } : {}),
1604
+ generation,
1605
+ };
1606
+ log("ice gathering error", { reason, errorText });
1607
+ // テスト: interface-enumeration.test.ts「a listener that throws does not stop」
1608
+ this.onGatheringError.execute(info);
1609
+ }
1610
+ /**
1611
+ * Wait for `work` or close(), whichever comes first. Unlike racing a
1612
+ * promise that stays pending for the agent's lifetime, the close listener
1613
+ * goes away with this wait, so a settled gathering (and the candidates its
1614
+ * result holds) is not kept alive by every later restart.
1615
+ */
1616
+ untilSettledOrClosed(work, closedValue) {
1617
+ const signal = this.closing.signal;
1618
+ if (signal.aborted)
1619
+ return Promise.resolve(closedValue);
1620
+ return new Promise((resolve) => {
1621
+ let settled = false;
1622
+ const done = (value) => {
1623
+ if (settled)
1624
+ return;
1625
+ settled = true;
1626
+ signal.removeEventListener("abort", onClose);
1627
+ resolve(value);
1628
+ };
1629
+ const onClose = () => done(closedValue);
1630
+ signal.addEventListener("abort", onClose, { once: true });
1631
+ work.then((value) => done(value), () => done(closedValue));
1632
+ });
1633
+ }
1634
+ /**
1635
+ * Resolves when the current generation's gathering has ended
1636
+ * (`localCandidatesEnd`): {@link Connection.gatherCandidates} returns once
1637
+ * the host sockets, the TURN allocations and the representative socket's
1638
+ * server-reflexive query are done, while the other host sockets' queries
1639
+ * continue and trickle through `onIceCandidate`. Also resolves when the
1640
+ * agent closes or restarts (the generation ends without its end).
1641
+ */
1642
+ async waitForLocalCandidatesEnd() {
1643
+ await this.localCandidatesEndPromise;
1361
1644
  }
1362
1645
  /**
1363
1646
  * Whether gathering started for `generation` still belongs to the agent:
@@ -1366,30 +1649,6 @@ class Connection {
1366
1649
  isGathering(generation) {
1367
1650
  return this.generation === generation && this.state !== "closed";
1368
1651
  }
1369
- /**
1370
- * Whether the provisional generation may use `protocol`: the staged
1371
- * generation drops the sockets its gather options exclude at the commit,
1372
- * so its checks never use them. A kept TURN allocation serves it only when
1373
- * the generation still uses that TURN server, credential and transport (any of its
1374
- * TURN servers): one whose server was removed or replaced (a credential
1375
- * rotation) is not part of it.
1376
- */
1377
- allowsProvisional(generation, protocol) {
1378
- const options = generation.gatherOptions ?? this.options;
1379
- if (!protocol.localCandidate ||
1380
- !(0, iceBase_1.isCandidateAllowedByGatherOptions)(protocol.localCandidate, options)) {
1381
- return false;
1382
- }
1383
- if (protocol instanceof protocol_2.StunOverTurnProtocol) {
1384
- const { configuredServer, username, password } = protocol.turn;
1385
- return (0, iceBase_1.normalizeIceServerOptions)(options).turnServers.some((server) => configuredServer[0] === server.address[0] &&
1386
- configuredServer[1] === server.address[1] &&
1387
- username === server.username &&
1388
- password === server.password &&
1389
- protocol.configuredTransport === server.transport);
1390
- }
1391
- return true;
1392
- }
1393
1652
  /** A copy of `candidate` labelled with the current generation and ufrag. */
1394
1653
  withGeneration(candidate) {
1395
1654
  return new candidate_1.Candidate(candidate.foundation, candidate.component, candidate.transport, candidate.priority, candidate.host, candidate.port, candidate.type, candidate.relatedAddress, candidate.relatedPort, candidate.tcptype, this.generation, this.localUsername);
@@ -1402,56 +1661,232 @@ class Connection {
1402
1661
  this.localCandidates.push(candidate);
1403
1662
  this.onIceCandidate.execute(candidate);
1404
1663
  }
1664
+ /**
1665
+ * Report a failed STUN query / TURN allocation of the gathering whose
1666
+ * `stale` is given (see onIceCandidateError). A failure that is not
1667
+ * reported (cancelled), belongs to a replaced generation or arrives after
1668
+ * close is dropped. A listener that throws does not stop the gathering.
1669
+ */
1670
+ emitCandidateError(stale, generation, server, failure, local) {
1671
+ if (!failure || stale() || this.closing.signal.aborted)
1672
+ return;
1673
+ const info = {
1674
+ server,
1675
+ ...(local ? { address: local.address, port: local.port } : {}),
1676
+ errorCode: failure.errorCode,
1677
+ errorText: failure.errorText,
1678
+ generation,
1679
+ };
1680
+ log("ice candidate error", {
1681
+ server: { ...server, urls: undefined },
1682
+ errorCode: info.errorCode,
1683
+ errorText: info.errorText,
1684
+ });
1685
+ try {
1686
+ this.onIceCandidateError.execute(info);
1687
+ }
1688
+ catch (error) {
1689
+ log("onIceCandidateError listener threw", error);
1690
+ }
1691
+ }
1692
+ /** Report that `server` answered the gathering whose `stale` is given. */
1693
+ emitServerReached(stale, generation, server) {
1694
+ if (stale() || this.closing.signal.aborted)
1695
+ return;
1696
+ try {
1697
+ this.onIceServerReached.execute({ server, generation });
1698
+ }
1699
+ catch (error) {
1700
+ log("onIceServerReached listener threw", error);
1701
+ }
1702
+ }
1405
1703
  ensureProtocol(protocol) {
1406
1704
  protocol.onRequestReceived.subscribe((msg, addr, data) => {
1407
- if (msg.messageMethod !== const_1.methods.BINDING) {
1408
- this.respondError(msg, addr, protocol, [400, "Bad Request"]);
1409
- return;
1410
- }
1411
- const txUsername = msg.getAttributeValue("USERNAME");
1412
- // 相手にとってのremoteは自分にとってのlocal
1413
- const { remoteUsername: localUsername } = decodeTxUsername(txUsername);
1414
- const localPassword = this.userHistory[localUsername] ?? this.localPassword;
1415
- // A check for the staged generation on a socket it drops at the commit
1416
- // (a host socket under a relay-only policy, a TURN allocation whose
1417
- // server was removed or replaced) is not answered: the socket is not
1418
- // part of that generation.
1419
- const staged = this.provisional;
1420
- if (staged &&
1421
- localUsername === staged.localUsername &&
1422
- localUsername !== this.localUsername &&
1423
- !this.allowsProvisional(staged, protocol)) {
1424
- return;
1425
- }
1426
- const { iceControlling } = this;
1427
- // 7.2.1.1. Detecting and Repairing Role Conflicts
1428
- if (iceControlling && msg.attributesKeys.includes("ICE-CONTROLLING")) {
1429
- if (this.tieBreaker >= msg.getAttributeValue("ICE-CONTROLLING")) {
1430
- this.respondError(msg, addr, protocol, [487, "Role Conflict"], localPassword);
1431
- return;
1705
+ // Asynchronous (SPED awaits the DTLS inject before answering): a
1706
+ // failure, e.g. thrown by a filterStunResponse callback, is logged as
1707
+ // it was when the request was handled synchronously, never left as an
1708
+ // unhandled rejection.
1709
+ this.handleBindingRequest(protocol, msg, addr, data).catch((error) => {
1710
+ log("handleBindingRequest", error);
1711
+ });
1712
+ });
1713
+ protocol.onDataReceived.subscribe((data, addr) => {
1714
+ try {
1715
+ // The source-aware datagram event has internal subscribers only
1716
+ // (SPED, the WebRTC DTLS transport): without one, a datagram (RTP /
1717
+ // SRTP included) skips the pair lookup. The authenticated path it
1718
+ // tracks (restart retention) is read only through this event.
1719
+ if (this.internalDatagramEvent) {
1720
+ const pair = this.resolveDatagramPair(protocol, addr);
1721
+ const authenticated = addr !== undefined &&
1722
+ pair !== undefined &&
1723
+ (0, datagram_1.isAuthenticatedHandshakePair)(pair);
1724
+ if (authenticated) {
1725
+ this.lastDataPair = pair;
1726
+ this.previousSelectedPairs = [];
1727
+ }
1728
+ (0, datagram_1.connectionDatagramEvent)(this).execute({
1729
+ bytes: data,
1730
+ // Never copy pair.remoteAddr into source: a missing addr must not
1731
+ // look like an authenticated 5-tuple match.
1732
+ source: addr ?? ["0.0.0.0", 0],
1733
+ protocol,
1734
+ pair,
1735
+ generation: this.generation,
1736
+ authenticated,
1737
+ // A new-generation pair for the same 5-tuple may already exist
1738
+ // (WAITING/IN_PROGRESS) before it is authenticated; that must not
1739
+ // hide the retained previous selected path.
1740
+ fromPreviousSelectedPair: !authenticated && this.isPreviousSelectedPair(protocol, addr),
1741
+ });
1432
1742
  }
1433
- else {
1434
- this.switchRole(false);
1743
+ // Update statistics for the nominated pair
1744
+ const activePair = this.nominated;
1745
+ if (activePair && activePair.protocol === protocol) {
1746
+ activePair.packetsReceived++;
1747
+ activePair.bytesReceived += data.length;
1435
1748
  }
1436
- }
1437
- else if (!iceControlling &&
1438
- msg.attributesKeys.includes("ICE-CONTROLLED")) {
1439
- if (this.iceLite ||
1440
- this.tieBreaker < msg.getAttributeValue("ICE-CONTROLLED")) {
1441
- this.respondError(msg, addr, protocol, [487, "Role Conflict"], localPassword);
1442
- return;
1749
+ if (addr && this.failoverEnabled()) {
1750
+ this.failoverDataReceived(protocol, addr);
1443
1751
  }
1444
- else {
1445
- this.switchRole(true);
1446
- return;
1752
+ if (!this.iceControlling && addr) {
1753
+ this.selection.controlledDataReceived(protocol, addr);
1447
1754
  }
1755
+ this.onData.execute(data);
1448
1756
  }
1757
+ catch (error) {
1758
+ log("dataReceived", error);
1759
+ }
1760
+ });
1761
+ protocol.onConnectionClosed?.subscribe((remoteAddr) => {
1762
+ this.handleConnectionClosed(protocol, remoteAddr);
1763
+ });
1764
+ protocol.onPathBroken?.subscribe((remoteAddr, error) => {
1765
+ this.failoverPathBroken(protocol, remoteAddr, error);
1766
+ });
1767
+ }
1768
+ async handleBindingRequest(protocol, msg, addr, data) {
1769
+ if (msg.messageMethod !== const_1.methods.BINDING) {
1770
+ this.respondError(msg, addr, protocol, [400, "Bad Request"]);
1771
+ return;
1772
+ }
1773
+ // SPED (PeerConfig.sped) carries DTLS on the check exchange, so its
1774
+ // requests are HMAC-verified (RFC 8445 §7.3) and an older generation's
1775
+ // check never reaches the current state. Without SPED the agent keeps its
1776
+ // default handling: the MESSAGE-INTEGRITY of an incoming check is not
1777
+ // verified here (rejecting unverifiable checks with 401, RFC 8489 §9.1.3,
1778
+ // changes established behavior and is tracked separately), and a
1779
+ // USERNAME without ":" is read as the local ufrag as before.
1780
+ const spedBoundary = (0, sped_bind_1.isConnectionSpedEnabled)(this);
1781
+ const txUsername = msg.getAttributeValue("USERNAME");
1782
+ if (typeof txUsername !== "string") {
1783
+ return;
1784
+ }
1785
+ if (spedBoundary && !txUsername.includes(":")) {
1786
+ return;
1787
+ }
1788
+ const { remoteUsername: localUsername } = (0, checkMessages_1.decodeTxUsername)(txUsername);
1789
+ const localPassword = this.userHistory[localUsername] ?? this.localPassword;
1790
+ let verified = msg;
1791
+ if (spedBoundary) {
1792
+ verified = (0, message_1.parseMessage)(data, Buffer.from(localPassword, "utf8"));
1793
+ if (!verified) {
1794
+ log("drop unauthenticated Binding Request");
1795
+ return;
1796
+ }
1797
+ }
1798
+ const isCurrentGeneration = localUsername === this.localUsername;
1799
+ if (!isCurrentGeneration) {
1800
+ const provisional = this.provisional;
1801
+ const isProvisional = !!provisional && localUsername === provisional.localUsername;
1802
+ if (isProvisional &&
1803
+ provisional &&
1804
+ !this.provisionalChecklist.allows(provisional, protocol)) {
1805
+ return;
1806
+ }
1807
+ if ((isProvisional || !spedBoundary) &&
1808
+ this.resolveRoleConflict(verified, addr, protocol, localPassword, this.iceControlling)) {
1809
+ return;
1810
+ }
1811
+ // The application filter applies to every generation's check, as for
1812
+ // the current generation (options.filterStunResponse).
1449
1813
  if (this.options.filterStunResponse &&
1450
- !this.options.filterStunResponse(msg, addr, protocol)) {
1814
+ !this.options.filterStunResponse(verified, addr, protocol)) {
1451
1815
  return;
1452
1816
  }
1453
- // # send binding response
1454
- const response = new message_1.Message(const_1.methods.BINDING, const_1.classes.RESPONSE, msg.transactionId);
1817
+ const response = new message_1.Message(const_1.methods.BINDING, const_1.classes.RESPONSE, verified.transactionId);
1818
+ response
1819
+ .setAttribute("XOR-MAPPED-ADDRESS", addr)
1820
+ .addIntegrity(Buffer.from(localPassword, "utf8"), this.spedRuntime?.session.embedding
1821
+ ? "sha1"
1822
+ : (0, checkMessages_1.responseIntegrityMode)(verified))
1823
+ .addFingerprint();
1824
+ protocol.sendStun(response, addr).catch((e) => {
1825
+ log("sendStun error", e);
1826
+ });
1827
+ if (provisional && isProvisional) {
1828
+ this.provisionalChecklist.checkIncoming(provisional, verified, addr, protocol);
1829
+ }
1830
+ else if (!spedBoundary) {
1831
+ // Without SPED an older generation's check is handled as before.
1832
+ this.queueOrCheckIncoming(verified, addr, protocol);
1833
+ }
1834
+ return;
1835
+ }
1836
+ const { iceControlling } = this;
1837
+ await this.handleCurrentGenerationBinding(protocol, verified, addr, localPassword, iceControlling, spedBoundary);
1838
+ }
1839
+ /** Queue a check until connect() while the checklist is empty, else handle it. */
1840
+ queueOrCheckIncoming(message, addr, protocol) {
1841
+ if (this.checkList.length === 0 && !this.earlyChecksDone) {
1842
+ this.earlyChecks.push([message, addr, protocol]);
1843
+ }
1844
+ else {
1845
+ this.checkIncoming(message, addr, protocol);
1846
+ }
1847
+ }
1848
+ /**
1849
+ * @returns true when the request is fully handled (an error response was
1850
+ * sent, or the role switched and the peer retries).
1851
+ */
1852
+ resolveRoleConflict(verified, addr, protocol, localPassword, iceControlling) {
1853
+ // 7.2.1.1. Detecting and Repairing Role Conflicts
1854
+ if (iceControlling && verified.attributesKeys.includes("ICE-CONTROLLING")) {
1855
+ if (this.tieBreaker >= verified.getAttributeValue("ICE-CONTROLLING")) {
1856
+ this.respondError(verified, addr, protocol, [487, "Role Conflict"], localPassword);
1857
+ return true;
1858
+ }
1859
+ else {
1860
+ this.switchRole(false);
1861
+ }
1862
+ }
1863
+ else if (!iceControlling &&
1864
+ verified.attributesKeys.includes("ICE-CONTROLLED")) {
1865
+ if (this.iceLite ||
1866
+ this.tieBreaker < verified.getAttributeValue("ICE-CONTROLLED")) {
1867
+ this.respondError(verified, addr, protocol, [487, "Role Conflict"], localPassword);
1868
+ return true;
1869
+ }
1870
+ else {
1871
+ this.switchRole(true);
1872
+ return true;
1873
+ }
1874
+ }
1875
+ return false;
1876
+ }
1877
+ async handleCurrentGenerationBinding(protocol, verified, addr, localPassword, iceControlling, spedBoundary) {
1878
+ if (this.resolveRoleConflict(verified, addr, protocol, localPassword, iceControlling)) {
1879
+ return;
1880
+ }
1881
+ if (this.options.filterStunResponse &&
1882
+ !this.options.filterStunResponse(verified, addr, protocol)) {
1883
+ return;
1884
+ }
1885
+ // A late check of the peer's replaced generation keeps its old path's
1886
+ // consent (RFC 8445 §9) but must not add a peer-reflexive candidate or a
1887
+ // pair to the new generation.
1888
+ if (this.isRetiredRemoteCheck(verified)) {
1889
+ const response = new message_1.Message(const_1.methods.BINDING, const_1.classes.RESPONSE, verified.transactionId);
1455
1890
  response
1456
1891
  .setAttribute("XOR-MAPPED-ADDRESS", addr)
1457
1892
  .addMessageIntegrity(Buffer.from(localPassword, "utf8"))
@@ -1459,37 +1894,145 @@ class Connection {
1459
1894
  protocol.sendStun(response, addr).catch((e) => {
1460
1895
  log("sendStun error", e);
1461
1896
  });
1462
- const provisional = this.provisional;
1463
- if (provisional &&
1464
- localUsername === provisional.localUsername &&
1465
- localUsername !== this.localUsername) {
1466
- this.checkIncomingProvisional(provisional, msg, addr, protocol);
1467
- return;
1897
+ return;
1898
+ }
1899
+ const generation = this.generation;
1900
+ // SPED needs the pair (and its prflx candidate) before the response so
1901
+ // the response can carry DTLS, and holds every check until connect().
1902
+ // Without SPED a check is queued only while the checklist is still empty
1903
+ // and the pair is formed by checkIncoming() after the response.
1904
+ const deferIncoming = spedBoundary
1905
+ ? !this.earlyChecksDone
1906
+ : this.checkList.length === 0 && !this.earlyChecksDone;
1907
+ let pair = this.findPairByAddr(protocol, addr);
1908
+ if (!pair && spedBoundary) {
1909
+ pair = this.ensureIncomingPair(verified, addr, protocol);
1910
+ }
1911
+ const txHex = verified.transactionIdHex;
1912
+ const replayCached = async (bytes) => {
1913
+ if (this.spedRuntime &&
1914
+ pair &&
1915
+ this.spedRuntime.isLiveGeneration(generation)) {
1916
+ await this.spedRuntime.handleAuthenticatedStun(verified, addr, generation, pair);
1468
1917
  }
1469
- if (this.checkList.length === 0 && !this.earlyChecksDone) {
1470
- this.earlyChecks.push([msg, addr, protocol]);
1918
+ const replay = new message_1.Message(const_1.methods.BINDING, const_1.classes.RESPONSE, verified.transactionId);
1919
+ Object.defineProperty(replay, "bytes", {
1920
+ configurable: true,
1921
+ enumerable: false,
1922
+ get: () => bytes,
1923
+ });
1924
+ protocol.sendStun(replay, addr).catch((e) => {
1925
+ log("sendStun error", e);
1926
+ });
1927
+ if (deferIncoming) {
1928
+ this.earlyChecks.push([verified, addr, protocol]);
1471
1929
  }
1472
1930
  else {
1473
- this.checkIncoming(msg, addr, protocol);
1931
+ this.checkIncoming(verified, addr, protocol);
1474
1932
  }
1475
- });
1476
- protocol.onDataReceived.subscribe((data) => {
1477
- try {
1478
- // Update statistics for the nominated pair
1479
- const activePair = this.nominated;
1480
- if (activePair && activePair.protocol === protocol) {
1481
- activePair.packetsReceived++;
1482
- activePair.bytesReceived += data.length;
1933
+ if (this.spedRuntime && generation === this.generation) {
1934
+ this.settleSpedUnconfirmed(pair);
1935
+ await this.maybeSendSpedFallback(protocol, addr, generation);
1936
+ }
1937
+ };
1938
+ // The Binding Response replay cache is SPED state: without SPED a
1939
+ // request is answered as before, keeping nothing per transaction.
1940
+ if (spedBoundary) {
1941
+ const cachedResponse = this.cachedSpedBindingResponse(txHex);
1942
+ if (cachedResponse) {
1943
+ await replayCached(cachedResponse);
1944
+ return;
1945
+ }
1946
+ const inFlight = this.spedBindingCache.getInFlight(txHex);
1947
+ if (inFlight) {
1948
+ const ready = await inFlight;
1949
+ if (ready && this.generation === generation) {
1950
+ await replayCached(ready);
1483
1951
  }
1484
- this.onData.execute(data);
1952
+ return;
1485
1953
  }
1486
- catch (error) {
1487
- log("dataReceived", error);
1954
+ }
1955
+ const finish = spedBoundary
1956
+ ? this.spedBindingCache.begin(txHex).finish
1957
+ : () => { };
1958
+ let result;
1959
+ try {
1960
+ if (this.spedRuntime &&
1961
+ pair &&
1962
+ this.spedRuntime.isLiveGeneration(generation)) {
1963
+ await this.spedRuntime.handleAuthenticatedStun(verified, addr, generation, pair);
1964
+ if (generation !== this.generation) {
1965
+ return;
1966
+ }
1967
+ const raced = this.cachedSpedBindingResponse(txHex);
1968
+ if (raced) {
1969
+ result = raced;
1970
+ await replayCached(raced);
1971
+ return;
1972
+ }
1488
1973
  }
1489
- });
1490
- protocol.onConnectionClosed?.subscribe((remoteAddr) => {
1491
- this.handleConnectionClosed(protocol, remoteAddr);
1492
- });
1974
+ const response = new message_1.Message(const_1.methods.BINDING, const_1.classes.RESPONSE, verified.transactionId);
1975
+ response.setAttribute("XOR-MAPPED-ADDRESS", addr);
1976
+ if (pair) {
1977
+ const decorated = this.spedRuntime
1978
+ ? this.spedRuntime.decorateOutgoing(response, pair)
1979
+ : (0, sped_bind_1.decoratePendingSped)(this, response, pair);
1980
+ if (!decorated) {
1981
+ return;
1982
+ }
1983
+ }
1984
+ response
1985
+ .addIntegrity(Buffer.from(localPassword, "utf8"), this.spedRuntime?.session.embedding
1986
+ ? "sha1"
1987
+ : (0, checkMessages_1.responseIntegrityMode)(verified))
1988
+ .addFingerprint();
1989
+ if (spedBoundary) {
1990
+ const wire = Buffer.from(response.bytes);
1991
+ this.storeSpedBindingResponse(txHex, wire);
1992
+ result = wire;
1993
+ }
1994
+ protocol.sendStun(response, addr).catch((e) => {
1995
+ log("sendStun error", e);
1996
+ });
1997
+ if (deferIncoming) {
1998
+ this.earlyChecks.push([verified, addr, protocol]);
1999
+ }
2000
+ else {
2001
+ this.checkIncoming(verified, addr, protocol);
2002
+ }
2003
+ if (this.spedRuntime && generation === this.generation) {
2004
+ this.settleSpedUnconfirmed(pair);
2005
+ await this.maybeSendSpedFallback(protocol, addr, generation);
2006
+ }
2007
+ }
2008
+ finally {
2009
+ finish(result);
2010
+ }
2011
+ }
2012
+ shouldCacheSpedBindingResponse() {
2013
+ return this.spedRuntime?.session.embedding === true;
2014
+ }
2015
+ cachedSpedBindingResponse(txHex) {
2016
+ if (!this.shouldCacheSpedBindingResponse()) {
2017
+ this.spedBindingCache.clearEntries();
2018
+ return undefined;
2019
+ }
2020
+ return this.spedBindingCache.get(txHex);
2021
+ }
2022
+ storeSpedBindingResponse(txHex, bytes) {
2023
+ if (!this.shouldCacheSpedBindingResponse()) {
2024
+ this.spedBindingCache.clearEntries();
2025
+ return;
2026
+ }
2027
+ this.spedBindingCache.set(txHex, bytes, stunTransactionLifetimeMs());
2028
+ }
2029
+ /**
2030
+ * @internal
2031
+ * Handshake complete: drop Binding Response replay entries immediately
2032
+ * instead of waiting for the next Binding or TTL.
2033
+ */
2034
+ forgetSpedBindingResponseCache() {
2035
+ this.spedBindingCache.clearEntries();
1493
2036
  }
1494
2037
  /**
1495
2038
  * RFC 6544: the selected TCP connection is the only path for this component;
@@ -1508,279 +2051,9 @@ class Connection {
1508
2051
  return;
1509
2052
  }
1510
2053
  log("selected tcp connection closed", nominated.toJSON());
1511
- this.stopConsentLifecycle();
2054
+ this.consent.stop();
1512
2055
  this.setState("failed");
1513
2056
  }
1514
- getCandidatePromises(addresses, timeout = 5, generation = this.generation) {
1515
- const candidatePromises = [];
1516
- // Each continuation below runs after an await: a socket or allocation it
1517
- // opened for a replaced generation (or a closed agent) is closed, and
1518
- // nothing is added to the current one.
1519
- const stale = () => !this.isGathering(generation);
1520
- const { stunServers, turnServers } = this;
1521
- const { interfaceAddresses } = this.options;
1522
- const gatherIceLite = this.iceLite;
1523
- const gatherRelayOnly = (0, iceBase_1.isRelayOnlyGathering)(this.options);
1524
- // TCP host candidates are kept per address like the UDP ones, but on
1525
- // their own: a restart that turned useTcp on gathers them for addresses
1526
- // whose UDP sockets were kept.
1527
- const tcpAddresses = addresses.filter((address) => !this.protocols.some((protocol) => protocol.localCandidate?.transport.toLowerCase() === "tcp" &&
1528
- protocol.localIp === address));
1529
- addresses = addresses.filter((address) => {
1530
- // ice restartで同じアドレスが追加されるのを防ぐ
1531
- if (this.protocols.find((protocol) => protocol.localIp === address)) {
1532
- return false;
1533
- }
1534
- // A family bound to an interface address has one UDP host socket; its
1535
- // localIp is the bound address, whose notation may differ (IPv6).
1536
- if ((0, common_1.interfaceAddress)(socketTypeOf(address), interfaceAddresses) ===
1537
- address &&
1538
- this.protocols.some((protocol) => protocol instanceof protocol_1.StunProtocol &&
1539
- protocol.localCandidate?.type === "host" &&
1540
- (0, net_1.isIPv4)(protocol.localCandidate.host) === (0, net_1.isIPv4)(address))) {
1541
- return false;
1542
- }
1543
- return true;
1544
- });
1545
- // An ICE restart keeps its UDP sockets. They are not re-created above, but
1546
- // their server-reflexive address is part of the new generation too, so
1547
- // the STUN query below runs for them as well.
1548
- const reusedStunProtocols = this.protocols.filter((protocol) => protocol instanceof protocol_1.StunProtocol &&
1549
- protocol.localCandidate?.type === "host" &&
1550
- protocol.localCandidate.transport === "udp");
1551
- const localStunPromises = gatherRelayOnly
1552
- ? []
1553
- : addresses.map(async (address) => {
1554
- // # create transport
1555
- const protocol = new protocol_1.StunProtocol();
1556
- this.ensureProtocol(protocol);
1557
- const boundInterface = (0, common_1.interfaceAddress)(socketTypeOf(address), interfaceAddresses);
1558
- try {
1559
- await protocol.connectionMade((0, net_1.isIPv4)(address), this.options.portRange, interfaceAddresses);
1560
- if (stale()) {
1561
- await protocol.close();
1562
- return;
1563
- }
1564
- // # add host candidate
1565
- // A socket bound to an interface address advertises that address:
1566
- // the peer sends its checks there. A wildcard socket advertises
1567
- // the gathered address (never 0.0.0.0 / ::).
1568
- const [boundHost, boundPort] = protocol.getExtraInfo();
1569
- let candidateHost = address;
1570
- if (boundInterface) {
1571
- candidateHost = stripZoneId(boundHost);
1572
- if (candidateHost !== address) {
1573
- log("host address differs from the bound interface address; advertise the bound one", address, candidateHost);
1574
- }
1575
- }
1576
- const candidateAddress = [candidateHost, boundPort];
1577
- protocol.localIp = candidateHost;
1578
- this.protocols.push(protocol);
1579
- log("protocol", protocol.localIp);
1580
- 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);
1581
- this.pairLocalProtocol(protocol);
1582
- this.appendLocalCandidate(protocol.localCandidate);
1583
- return protocol;
1584
- }
1585
- catch (error) {
1586
- if (boundInterface) {
1587
- // No host candidate for this family: advertising another
1588
- // address than the socket's would mislead the peer.
1589
- log("failed to bind UDP socket to interface address", boundInterface, error);
1590
- }
1591
- else {
1592
- log("error protocol STUN", error);
1593
- }
1594
- }
1595
- });
1596
- if (!gatherRelayOnly) {
1597
- candidatePromises.push(...localStunPromises.map((localPromise) => localPromise.then((protocol) => protocol?.localCandidate)));
1598
- }
1599
- if (!gatherRelayOnly && this.options.useTcp) {
1600
- const tcpCandidatePromises = tcpAddresses.map(async (address) => {
1601
- // Passive candidates open a listening TCP server; skip them when the
1602
- // agent only makes outbound connections (tcpPassive === false). Active
1603
- // candidates below still dial out, so direct TCP egress is unaffected.
1604
- if (this.options.tcpPassive !== false) {
1605
- const passiveProtocol = new tcpProtocol_1.TcpPassiveProtocol();
1606
- this.ensureProtocol(passiveProtocol);
1607
- await passiveProtocol.connectionMade(address, this.options.portRange);
1608
- if (stale()) {
1609
- await passiveProtocol.close();
1610
- return;
1611
- }
1612
- passiveProtocol.localIp = address;
1613
- passiveProtocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("host", "tcp", address), 1, "tcp", (0, candidate_1.candidatePriority)("host", {
1614
- transport: "tcp",
1615
- tcptype: "passive",
1616
- }), address, passiveProtocol.listeningPort, "host", undefined, undefined, "passive", this.generation, this.localUsername);
1617
- this.protocols.push(passiveProtocol);
1618
- this.appendLocalCandidate(passiveProtocol.localCandidate);
1619
- }
1620
- if (!gatherIceLite) {
1621
- const activeProtocol = new tcpProtocol_1.TcpActiveProtocol();
1622
- this.ensureProtocol(activeProtocol);
1623
- await activeProtocol.connectionMade(address);
1624
- if (stale()) {
1625
- await activeProtocol.close();
1626
- return;
1627
- }
1628
- activeProtocol.localIp = address;
1629
- activeProtocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("host", "tcp", address), 1, "tcp", (0, candidate_1.candidatePriority)("host", {
1630
- transport: "tcp",
1631
- tcptype: "active",
1632
- }), address, 9, "host", undefined, undefined, "active", this.generation, this.localUsername);
1633
- this.protocols.push(activeProtocol);
1634
- this.pairLocalProtocol(activeProtocol);
1635
- this.appendLocalCandidate(activeProtocol.localCandidate);
1636
- }
1637
- });
1638
- candidatePromises.push(...tcpCandidatePromises);
1639
- }
1640
- // A server-reflexive query of one socket to one STUN server, bounded by
1641
- // the STUN gather timeout; an unanswered one yields nothing.
1642
- const queryReflexive = async (protocol, server) => {
1643
- let timer;
1644
- const candidate = await Promise.race([
1645
- (0, iceBase_1.serverReflexiveCandidate)(protocol, server).catch((error) => {
1646
- log("query STUN server", server, error);
1647
- return undefined;
1648
- }),
1649
- new Promise((resolve) => {
1650
- timer = setTimeout(() => resolve(undefined), timeout * 1000);
1651
- }),
1652
- ]);
1653
- clearTimeout(timer);
1654
- return candidate;
1655
- };
1656
- // RFC 8445 §5.1.3: a mapping equal to one the socket already advertised
1657
- // (same base, same transport address) is redundant.
1658
- const sameMapping = (a, b) => a.host === b.host && a.port === b.port;
1659
- if (!gatherIceLite && !gatherRelayOnly && stunServers.length > 0) {
1660
- // Sockets kept across an ICE restart query every STUN server again.
1661
- // The mappings they already advertised are in the new generation from
1662
- // the start; a different fresh mapping (the NAT rebound) is added to
1663
- // it, and the fresh mappings replace the kept ones for the next restart.
1664
- const reusedReflexivePromises = reusedStunProtocols
1665
- .filter((protocol) => (0, net_1.isIPv4)(protocol.localCandidate.host))
1666
- .map(async (protocol) => {
1667
- const previous = this.reflexiveBySocket.get(protocol) ?? [];
1668
- const advertised = [...previous];
1669
- const fresh = [];
1670
- await Promise.all(stunServers.map(async (server) => {
1671
- const candidate = await queryReflexive(protocol, server);
1672
- if (!candidate || stale())
1673
- return;
1674
- if (!fresh.some((known) => sameMapping(known, candidate))) {
1675
- fresh.push(candidate);
1676
- }
1677
- if (advertised.some((known) => sameMapping(known, candidate))) {
1678
- return;
1679
- }
1680
- advertised.push(candidate);
1681
- this.appendLocalCandidate(candidate);
1682
- }));
1683
- if (stale())
1684
- return;
1685
- if (fresh.length > 0)
1686
- this.reflexiveBySocket.set(protocol, fresh);
1687
- return fresh.length > 0 ? fresh : previous;
1688
- })
1689
- .map((promise) => promise.catch((error) => {
1690
- log("query STUN server", error);
1691
- }));
1692
- candidatePromises.push(...reusedReflexivePromises);
1693
- // Every new IPv4 socket queries every STUN server in parallel.
1694
- const stunCandidatePromises = localStunPromises.map(async (protocolPromise) => {
1695
- const protocol = await protocolPromise;
1696
- if (!protocol?.localCandidate ||
1697
- !(0, net_1.isIPv4)(protocol.localCandidate.host))
1698
- return;
1699
- const advertised = [];
1700
- await Promise.all(stunServers.map(async (server) => {
1701
- const candidate = await queryReflexive(protocol, server);
1702
- if (!candidate || stale())
1703
- return;
1704
- if (advertised.some((known) => sameMapping(known, candidate))) {
1705
- return;
1706
- }
1707
- advertised.push(candidate);
1708
- this.reflexiveBySocket.set(protocol, advertised);
1709
- this.appendLocalCandidate(candidate);
1710
- })).catch((error) => {
1711
- log("query STUN server", error);
1712
- });
1713
- return advertised;
1714
- });
1715
- candidatePromises.push(...stunCandidatePromises);
1716
- }
1717
- if (!gatherIceLite) {
1718
- // Every TURN server gets its own allocation, made with its own
1719
- // credential and transport; one that fails does not stop the others.
1720
- const turnCandidatePromises = turnServers.map((server) => this.gatherRelayCandidate(server, gatherRelayOnly, stale).catch((error) => {
1721
- log("query TURN server", server.address, error);
1722
- }));
1723
- candidatePromises.push(...turnCandidatePromises);
1724
- }
1725
- return candidatePromises;
1726
- }
1727
- /**
1728
- * Allocate on one TURN server and add its relay candidate. A UDP
1729
- * allocation that fails falls back to TCP on the same server. An
1730
- * allocation that completes for a replaced generation (or a closed agent)
1731
- * is released.
1732
- */
1733
- async gatherRelayCandidate(server, relayOnly, stale) {
1734
- const { address, username, password, transport } = server;
1735
- const protocol = await (0, protocol_2.createStunOverTurnClient)({ address, username, password }, {
1736
- portRange: this.options.portRange,
1737
- interfaceAddresses: this.options.interfaceAddresses,
1738
- transport,
1739
- tlsOptions: this.options.turnTlsOptions,
1740
- connectTimeoutMs: (this.options.turnConnectTimeout ?? 8) * 1000,
1741
- udpFamily: this.options.turnUdpFamily,
1742
- signal: this.closing.signal,
1743
- }).catch(async (e) => {
1744
- // close() cancelled the allocation: no TCP fallback.
1745
- if (transport === "udp" && !this.closing.signal.aborted) {
1746
- return await (0, protocol_2.createStunOverTurnClient)({ address, username, password }, {
1747
- portRange: this.options.portRange,
1748
- interfaceAddresses: this.options.interfaceAddresses,
1749
- transport: "tcp",
1750
- connectTimeoutMs: (this.options.turnConnectTimeout ?? 8) * 1000,
1751
- signal: this.closing.signal,
1752
- });
1753
- }
1754
- else {
1755
- throw e;
1756
- }
1757
- });
1758
- if (stale()) {
1759
- // The allocation never joins a generation: release it (and its
1760
- // refresh timer) instead of keeping a second one alive.
1761
- await protocol.close();
1762
- return;
1763
- }
1764
- protocol.configuredTransport = transport;
1765
- this.ensureProtocol(protocol);
1766
- this.protocols.push(protocol);
1767
- const candidateAddress = protocol.turn.relayedAddress;
1768
- // The related address of a relay candidate is the address the TURN
1769
- // server saw the agent at. A relay-only policy hides the agent's
1770
- // addresses from the peer, so it advertises the unspecified address
1771
- // and port 9 instead (RFC 8839 §5.1), in SDP and trickle alike.
1772
- const relatedAddress = relayOnly
1773
- ? [(0, net_1.isIPv4)(candidateAddress[0]) ? "0.0.0.0" : "::", 9]
1774
- : protocol.turn.mappedAddress;
1775
- log("turn candidateAddress", candidateAddress);
1776
- 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);
1777
- // An allocation that completes after the remote candidates arrived
1778
- // (early signaling, or an ICE restart that allocates afresh) pairs
1779
- // with them; a connect() already running schedules the new pairs.
1780
- this.pairLocalProtocol(protocol);
1781
- this.appendLocalCandidate(protocol.localCandidate);
1782
- return protocol.localCandidate;
1783
- }
1784
2057
  async connect() {
1785
2058
  // """
1786
2059
  // Perform ICE handshake.
@@ -1798,6 +2071,14 @@ class Connection {
1798
2071
  throw new Error("Remote username or password is missing");
1799
2072
  }
1800
2073
  this.checksBegun = true;
2074
+ // The generation this connect() checks ends with restart(),
2075
+ // restartRemote() or close() (they abort `remoteChecks`). Every wait
2076
+ // below stops on `ended` and settles at once (connectError), and nothing
2077
+ // after it touches the state, check list or results (`checkListState`)
2078
+ // of the generation that replaced this one.
2079
+ const ended = this.remoteChecks.signal;
2080
+ const queue = this.checkListState;
2081
+ const untilEnded = this.untilEnded(ended);
1801
2082
  // # 5.7.1. Forming Candidate Pairs
1802
2083
  for (const c of this.remoteCandidates) {
1803
2084
  this.pairRemoteCandidate(c);
@@ -1810,20 +2091,43 @@ class Connection {
1810
2091
  // # handle early checks
1811
2092
  for (const earlyCheck of this.earlyChecks) {
1812
2093
  this.checkIncoming(...earlyCheck);
2094
+ const [, addr, protocol] = earlyCheck;
2095
+ this.settleSpedUnconfirmed(this.findPairByAddr(protocol, addr));
2096
+ await this.maybeSendSpedFallback(protocol, addr, this.generation);
1813
2097
  }
1814
2098
  this.earlyChecks = [];
1815
2099
  this.earlyChecksDone = true;
2100
+ // Arms the wait for a preferred pair even while the checklist is empty.
2101
+ this.nomination.evaluate();
1816
2102
  if (this.iceLite) {
2103
+ // An ICE-lite agent sends no checks: with no pair yet, only a check
2104
+ // from the peer (or a trickled candidate) can add one, and like a full
2105
+ // agent it waits `incomingCheckTimeout` for it.
2106
+ if (!this.nominated &&
2107
+ this.checkList.length === 0 &&
2108
+ !(await this.waitForIncomingCheck(ended))) {
2109
+ if (ended.aborted)
2110
+ throw this.connectError();
2111
+ if (!this.nominated)
2112
+ throw new Error("ICE negotiation failed");
2113
+ }
2114
+ if (ended.aborted)
2115
+ throw this.connectError();
1817
2116
  if (!this.nominated) {
1818
2117
  let res = iceBase_1.ICE_FAILED;
1819
- while (!this.checkListDone && this.state !== "closed") {
1820
- res = await this.checkListState.get();
2118
+ while (!this.checkListDone) {
2119
+ res = await Promise.race([queue.get(), untilEnded]);
2120
+ if (ended.aborted)
2121
+ throw this.connectError();
1821
2122
  log("checkListState", res);
1822
2123
  if (res === iceBase_1.ICE_COMPLETED) {
1823
2124
  break;
1824
2125
  }
1825
2126
  }
1826
2127
  if (res !== iceBase_1.ICE_COMPLETED && !this.nominated) {
2128
+ if (this.state !== "closed") {
2129
+ this.setState("failed");
2130
+ }
1827
2131
  throw new Error("ICE negotiation failed");
1828
2132
  }
1829
2133
  }
@@ -1832,30 +2136,147 @@ class Connection {
1832
2136
  }
1833
2137
  // # perform checks
1834
2138
  // 5.8. Scheduling Checks
1835
- for (;;) {
1836
- if (this.state === "closed")
1837
- break;
1838
- if (!this.schedulingChecks())
2139
+ scheduling: for (;;) {
2140
+ for (;;) {
2141
+ // A restart resets `remoteCandidatesEnd`, so schedulingChecks()
2142
+ // would keep returning true and checking the new generation's pairs.
2143
+ if (ended.aborted)
2144
+ throw this.connectError();
2145
+ if (this.state === "closed")
2146
+ break scheduling;
2147
+ // A selection that may still be replaced: the checks of the pairs
2148
+ // that outrank it go on in `SelectionReplacement.checkOutrankingPairs`.
2149
+ if (this.nominated && this.iceControlling && this.replacesSelection()) {
2150
+ break scheduling;
2151
+ }
2152
+ if (!this.schedulingChecks())
2153
+ break;
2154
+ await timers.setTimeout(20);
2155
+ }
2156
+ // No pair to check (the peer offered only active TCP candidates, or
2157
+ // none this agent can reach): a check from the peer can still add a
2158
+ // peer-reflexive pair, so the empty check list does not fail at once.
2159
+ const pairAdded = await this.waitForIncomingCheck(ended);
2160
+ if (ended.aborted)
2161
+ throw this.connectError();
2162
+ if (!pairAdded)
1839
2163
  break;
1840
- await timers.setTimeout(20);
1841
2164
  }
2165
+ this.schedulingStopped = true;
1842
2166
  // # wait for completion
1843
2167
  let res = iceBase_1.ICE_FAILED;
1844
- while (this.checkList.length > 0 && res === iceBase_1.ICE_FAILED) {
1845
- res = await this.checkListState.get();
2168
+ // The nomination may still wait for a pair an incoming check forms
2169
+ // (`NominationHint`), even with an empty checklist.
2170
+ while ((this.checkList.length > 0 || this.nomination.waiting) &&
2171
+ res === iceBase_1.ICE_FAILED) {
2172
+ res = await Promise.race([queue.get(), untilEnded]);
2173
+ // Before cancelling "remaining checks": after a restart `checkList`
2174
+ // is the new generation's.
2175
+ if (ended.aborted)
2176
+ throw this.connectError();
1846
2177
  log("checkListState", res);
1847
2178
  }
1848
2179
  // # cancel remaining checks
2180
+ // (but those of pairs that may still replace the selection)
2181
+ const selected = this.nominated;
2182
+ const keepsChecking = !!selected && this.iceControlling && this.replacesSelection();
1849
2183
  for (const check of this.checkList) {
2184
+ if (keepsChecking &&
2185
+ this.replacesWith(check) &&
2186
+ this.outranks(check, selected)) {
2187
+ continue;
2188
+ }
1850
2189
  check.handle?.resolve?.();
1851
2190
  }
1852
- if (res !== iceBase_1.ICE_COMPLETED) {
2191
+ if (res !== iceBase_1.ICE_COMPLETED && !this.nominated) {
2192
+ if (this.state !== "closed") {
2193
+ this.setState("failed");
2194
+ }
1853
2195
  throw new Error("ICE negotiation failed");
1854
2196
  }
1855
2197
  // # start consent freshness tests
1856
2198
  this.queryConsent();
1857
2199
  this.setState("connected");
1858
2200
  }
2201
+ /**
2202
+ * The error connect() ends with when its generation ended: close() fails
2203
+ * it as before (`ICE negotiation failed`); a restart (local or
2204
+ * remote-only) cancels it with `IceRestartedError`, which says nothing
2205
+ * about the generation that replaced it.
2206
+ */
2207
+ connectError() {
2208
+ if (this.closed)
2209
+ return new Error("ICE negotiation failed");
2210
+ log("connect of a replaced generation cancelled by an ICE restart");
2211
+ return new exceptions_1.IceRestartedError();
2212
+ }
2213
+ /**
2214
+ * Resolves (with ICE_FAILED, which no caller acts on: each checks
2215
+ * `ended` first) once `ended` aborts, so a wait raced against it stops.
2216
+ */
2217
+ untilEnded(ended) {
2218
+ return new Promise((resolve) => {
2219
+ if (ended.aborted)
2220
+ return resolve(iceBase_1.ICE_FAILED);
2221
+ ended.addEventListener("abort", () => resolve(iceBase_1.ICE_FAILED), {
2222
+ once: true,
2223
+ });
2224
+ });
2225
+ }
2226
+ /**
2227
+ * With an empty check list, wait for a pair (a check from the peer taught a
2228
+ * peer-reflexive candidate, RFC 8445 section 7.3.1.3, the only way to
2229
+ * connect to a peer whose TCP candidates are all active, RFC 6544; or a
2230
+ * trickled candidate). Resolves true when a pair was added, so that the
2231
+ * scheduling loop runs again; false when:
2232
+ * - the local gathering ended without a socket that could receive a check
2233
+ * (at once, also when it ends during the wait: an ICE-lite agent may
2234
+ * connect while it still gathers),
2235
+ * - `incomingCheckTimeout` ran out (a deadline fixed when the wait began;
2236
+ * being woken does not extend it), or
2237
+ * - the generation ended (`ended`; the caller settles with connectError).
2238
+ * Every concurrent caller wakes on its own.
2239
+ */
2240
+ async waitForIncomingCheck(ended) {
2241
+ const seconds = this.options.incomingCheckTimeout ?? iceBase_1.DEFAULT_INCOMING_CHECK_TIMEOUT;
2242
+ if (this.checkList.length > 0 || ended.aborted || !(seconds > 0)) {
2243
+ return false;
2244
+ }
2245
+ log("empty check list, waiting for an incoming check", seconds);
2246
+ const deadline = Date.now() + seconds * 1000;
2247
+ for (;;) {
2248
+ // Nothing local can receive a check, and gathering will not add one.
2249
+ if (this.protocols.length === 0 && this.localCandidatesEnd)
2250
+ return false;
2251
+ const remaining = deadline - Date.now();
2252
+ if (remaining <= 0)
2253
+ return false;
2254
+ const wake = new AbortController();
2255
+ this.incomingCheckWaits.add(wake);
2256
+ try {
2257
+ await timers.setTimeout(remaining, undefined, {
2258
+ signal: AbortSignal.any([wake.signal, ended]),
2259
+ });
2260
+ return false;
2261
+ }
2262
+ catch {
2263
+ // Woken: a pair was added, the gathering ended, or the generation ended.
2264
+ }
2265
+ finally {
2266
+ this.incomingCheckWaits.delete(wake);
2267
+ }
2268
+ if (ended.aborted || this.closed)
2269
+ return false;
2270
+ if (this.checkList.length > 0)
2271
+ return true;
2272
+ // The gathering ended without a pair: check its sockets again.
2273
+ }
2274
+ }
2275
+ /** Wake every wait of connect() for an incoming check (waitForIncomingCheck). */
2276
+ wakeIncomingCheckWaits() {
2277
+ for (const wait of this.incomingCheckWaits)
2278
+ wait.abort();
2279
+ }
1859
2280
  unfreezeInitial() {
1860
2281
  // # unfreeze first pair for the first component
1861
2282
  const [firstPair] = this.checkList;
@@ -1910,33 +2331,40 @@ class Connection {
1910
2331
  return false;
1911
2332
  }
1912
2333
  /**
1913
- * Stop consent request cadence, expiry timer, and outstanding transactions.
1914
- * Does not change ICE state by itself.
2334
+ * Mirror libwebrtc semi-aggressive nomination (not required by RFC 7675):
2335
+ * attach USE-CANDIDATE to consent checks of the selected pair when we are
2336
+ * controlling and the remote is ICE-lite, or we nominate semi-aggressively
2337
+ * (a peer that became controlled after a role conflict, or lost the
2338
+ * nominating response, learns the selection from them).
1915
2339
  */
1916
- stopConsentLifecycle() {
1917
- this.consentSessionId++;
1918
- this.consentFresh = false;
1919
- if (this.consentExpiryTimer !== undefined) {
1920
- clearTimeout(this.consentExpiryTimer);
1921
- this.consentExpiryTimer = undefined;
1922
- }
1923
- this.consentRequestAbort?.abort();
1924
- this.consentRequestAbort = undefined;
1925
- const handle = this.queryConsentHandle;
1926
- this.queryConsentHandle = undefined;
1927
- // Resolve after clearing the field so a stale onCancel cannot wipe a replacement.
1928
- handle?.resolve?.();
2340
+ shouldNominateConsentRequest(pair) {
2341
+ return (this.iceControlling &&
2342
+ this.nominated?.id === pair.id &&
2343
+ (this.remoteIsLite || this.usesSemiAggressiveNomination()));
1929
2344
  }
1930
2345
  /**
1931
- * ICE-lite interop only (not required by RFC 7675): mirror libwebrtc
1932
- * semi-aggressive nomination — attach USE-CANDIDATE when we are controlling,
1933
- * the remote is ICE-lite, and the target is the current selected pair.
2346
+ * Renomination: the NOMINATION value consent checks of the selected pair
2347
+ * carry, so the peer keeps (or learns) the selection. A pair selected
2348
+ * without a renomination of this agent (the peer nominated it while this
2349
+ * agent was controlled) takes the next value.
1934
2350
  */
1935
- shouldNominateConsentRequest(pair) {
1936
- return (this.iceControlling && this.remoteIsLite && this.nominated?.id === pair.id);
2351
+ consentNomination(pair) {
2352
+ if (!this.usesRenomination() || this.nominated?.id !== pair.id) {
2353
+ return undefined;
2354
+ }
2355
+ if (pair.nomination === 0)
2356
+ pair.nomination = this.selection.nextNominationValue();
2357
+ return pair.nomination;
1937
2358
  }
2359
+ /**
2360
+ * @internal
2361
+ * Return whether application data can be delivered on the selected pair.
2362
+ * This is kept separate from {@link send} so transports that buffer data
2363
+ * can distinguish an unavailable path from a successful no-op.
2364
+ */
1938
2365
  canSendApplicationData() {
1939
- if (!this.nominated) {
2366
+ const activePair = this.applicationDataPair();
2367
+ if (!activePair) {
1940
2368
  return false;
1941
2369
  }
1942
2370
  if (this.state === "closed" || this.state === "failed") {
@@ -1946,24 +2374,23 @@ class Connection {
1946
2374
  if (this.iceLite) {
1947
2375
  return true;
1948
2376
  }
1949
- return this.consentFresh;
2377
+ // Full ICE requires consent from a successful Binding response. A remote
2378
+ // USE-CANDIDATE only records nomination; it does not prove that this peer
2379
+ // can receive application data on the pair.
2380
+ return this.consent.fresh;
1950
2381
  }
1951
- abortableDelay(ms, signal) {
1952
- return new Promise((resolve, reject) => {
1953
- if (signal.aborted) {
1954
- reject(new DOMException("The operation was aborted", "AbortError"));
1955
- return;
1956
- }
1957
- const timer = setTimeout(() => {
1958
- signal.removeEventListener("abort", onAbort);
1959
- resolve();
1960
- }, ms);
1961
- const onAbort = () => {
1962
- clearTimeout(timer);
1963
- reject(new DOMException("The operation was aborted", "AbortError"));
1964
- };
1965
- signal.addEventListener("abort", onAbort, { once: true });
1966
- });
2382
+ applicationDataPair() {
2383
+ if (this.nominated &&
2384
+ this.nominated.state === iceBase_1.CandidatePairState.SUCCEEDED) {
2385
+ return this.nominated;
2386
+ }
2387
+ return this.checkList.find((pair) => pair.state === iceBase_1.CandidatePairState.SUCCEEDED &&
2388
+ (0, datagram_1.isAuthenticatedHandshakePair)(pair) &&
2389
+ (pair.nominated || (this.iceLite && pair.remoteNominated)));
2390
+ }
2391
+ /** Start RFC 7675 consent freshness for the selected pair. */
2392
+ queryConsent() {
2393
+ this.consent.start();
1967
2394
  }
1968
2395
  async close() {
1969
2396
  // """
@@ -1971,17 +2398,19 @@ class Connection {
1971
2398
  // """
1972
2399
  this.closed = true;
1973
2400
  this.setState("closed");
1974
- this.signalClosed();
2401
+ this.onIceCandidateError.complete();
2402
+ this.onGatheringError.complete();
2403
+ this.onIceServerReached.complete();
1975
2404
  this.closing.abort();
1976
2405
  this.cancelChecks();
1977
- this.endProvisional();
2406
+ this.provisionalChecklist.end();
1978
2407
  // Before the first await: a pending mDNS lookup is cancelled here, so no
1979
2408
  // response arriving while the protocols close adds a remote candidate.
1980
2409
  this.lookup?.close?.();
1981
2410
  this.lookup = undefined;
1982
2411
  this.remoteResolutions.clear();
1983
2412
  // # stop consent freshness tests
1984
- this.stopConsentLifecycle();
2413
+ this.consent.stop();
1985
2414
  // # stop check list
1986
2415
  if (this.checkList && !this.checkListDone) {
1987
2416
  this.checkListState.put(new Promise((r) => {
@@ -1989,17 +2418,33 @@ class Connection {
1989
2418
  }));
1990
2419
  }
1991
2420
  this.nominated = undefined;
1992
- for (const protocol of this.protocols) {
2421
+ this.lastDataPair = undefined;
2422
+ this.previousSelectedPairs = [];
2423
+ this.liteNominating = false;
2424
+ this.nomination.reset();
2425
+ this.selection.abort();
2426
+ this.nominationHint = undefined;
2427
+ const pendingWildcards = [
2428
+ ...this.gatherer.wildcardProtocols.values(),
2429
+ ].filter((protocol) => !this.protocols.includes(protocol));
2430
+ this.gatherer.wildcardProtocols.clear();
2431
+ for (const protocol of [...this.protocols, ...pendingWildcards]) {
1993
2432
  if (protocol.close) {
1994
2433
  await protocol.close();
1995
2434
  }
1996
2435
  }
1997
2436
  this.protocols = [];
1998
2437
  this.localCandidates = [];
2438
+ this.spedBindingCache.clear();
2439
+ this.spedRuntime?.abort();
2440
+ this.spedRuntime = undefined;
1999
2441
  }
2000
2442
  setState(state) {
2001
2443
  this.state = state;
2002
2444
  this.stateChanged.execute(state);
2445
+ if (state === "failed" || state === "closed") {
2446
+ this.spedRuntime?.abort();
2447
+ }
2003
2448
  }
2004
2449
  /**
2005
2450
  * Known constraint (as in develop): candidates are not deduplicated. A
@@ -2031,6 +2476,9 @@ class Connection {
2031
2476
  return;
2032
2477
  }
2033
2478
  this.remoteCandidatesEnd = true;
2479
+ this.nomination.evaluate();
2480
+ const settled = this.settleSpedUnconfirmed();
2481
+ await this.flushSpedUnconfirmedFallback(settled);
2034
2482
  return;
2035
2483
  }
2036
2484
  // RFC 8838: a completed generation takes no further candidates.
@@ -2068,10 +2516,38 @@ class Connection {
2068
2516
  return;
2069
2517
  }
2070
2518
  log("addRemoteCandidate", remoteCandidate);
2519
+ const adopted = this.adoptExistingPrflx(remoteCandidate);
2520
+ if (adopted) {
2521
+ this.pairRemoteCandidate(adopted);
2522
+ this.sortCheckList();
2523
+ const settled = this.settleSpedUnconfirmed();
2524
+ await this.flushSpedUnconfirmedFallback(settled);
2525
+ return;
2526
+ }
2071
2527
  this._remoteCandidates.push(remoteCandidate);
2072
2528
  this.pairRemoteCandidate(remoteCandidate);
2073
2529
  this.sortCheckList();
2074
2530
  }
2531
+ /**
2532
+ * Trickle may signal host/srflx/relay after the address was learned as
2533
+ * prflx. Reuse that Candidate so SPED eligibility follows the signaled type.
2534
+ */
2535
+ adoptExistingPrflx(signaled) {
2536
+ const existing = this._remoteCandidates.find((candidate) => candidate.type === "prflx" &&
2537
+ candidate.host === signaled.host &&
2538
+ candidate.port === signaled.port &&
2539
+ candidate.transport.toLowerCase() === signaled.transport.toLowerCase());
2540
+ if (!existing) {
2541
+ return undefined;
2542
+ }
2543
+ existing.type = signaled.type;
2544
+ existing.foundation = signaled.foundation;
2545
+ existing.priority = signaled.priority;
2546
+ existing.relatedAddress = signaled.relatedAddress;
2547
+ existing.relatedPort = signaled.relatedPort;
2548
+ existing.tcptype = signaled.tcptype;
2549
+ return existing;
2550
+ }
2075
2551
  getDefaultCandidate() {
2076
2552
  const candidates = this.localCandidates.sort((a, b) => a.priority - b.priority);
2077
2553
  const [candidate] = candidates;
@@ -2089,28 +2565,218 @@ class Connection {
2089
2565
  catch (error) {
2090
2566
  continue;
2091
2567
  }
2092
- this._remoteCandidates.push(remoteCandidate);
2568
+ this._remoteCandidates.push(remoteCandidate);
2569
+ }
2570
+ this.remoteCandidatesEnd = true;
2571
+ }
2572
+ get remoteCandidates() {
2573
+ return this._remoteCandidates;
2574
+ }
2575
+ get candidatePairs() {
2576
+ return this.checkList;
2577
+ }
2578
+ sortCheckList() {
2579
+ (0, iceBase_1.sortCandidatePairs)(this.checkList, this.iceControlling);
2580
+ }
2581
+ findPair(protocol, remoteCandidate) {
2582
+ const pair = this.checkList.find((pair) => pair.protocol === protocol && pair.remoteCandidate === remoteCandidate);
2583
+ return pair;
2584
+ }
2585
+ /**
2586
+ * Several remote candidates can share one transport address (a srflx equal
2587
+ * to its host base), so one 5-tuple may have several pairs. Checks are
2588
+ * accounted on one of them only; prefer the authenticated pair so the
2589
+ * 5-tuple is not judged by a FROZEN/FAILED duplicate.
2590
+ */
2591
+ findPairByAddr(protocol, addr) {
2592
+ let first;
2593
+ for (const pair of this.checkList) {
2594
+ if (pair.protocol !== protocol ||
2595
+ pair.remoteAddr[0] !== addr[0] ||
2596
+ pair.remoteAddr[1] !== addr[1]) {
2597
+ continue;
2598
+ }
2599
+ if ((0, datagram_1.isAuthenticatedHandshakePair)(pair))
2600
+ return pair;
2601
+ first ?? (first = pair);
2602
+ }
2603
+ return first;
2604
+ }
2605
+ /**
2606
+ * Datagrams map to a pair by protocol and remote 5-tuple.
2607
+ * Nominated is preferred only when the source matches that pair.
2608
+ */
2609
+ resolveDatagramPair(protocol, addr) {
2610
+ if (addr) {
2611
+ if (this.nominated?.protocol === protocol &&
2612
+ this.nominated.remoteAddr[0] === addr[0] &&
2613
+ this.nominated.remoteAddr[1] === addr[1]) {
2614
+ return this.nominated;
2615
+ }
2616
+ return this.findPairByAddr(protocol, addr);
2093
2617
  }
2094
- this.remoteCandidatesEnd = true;
2618
+ if (this.nominated?.protocol === protocol) {
2619
+ return this.nominated;
2620
+ }
2621
+ return this.checkList.find((candidate) => candidate.protocol === protocol);
2095
2622
  }
2096
- get remoteCandidates() {
2097
- return this._remoteCandidates;
2623
+ isPreviousSelectedPair(protocol, addr) {
2624
+ if (addr === undefined) {
2625
+ return false;
2626
+ }
2627
+ return this.previousSelectedPairs.some((previous) => previous.protocol === protocol &&
2628
+ previous.remoteAddr[0] === addr[0] &&
2629
+ previous.remoteAddr[1] === addr[1]);
2098
2630
  }
2099
- get candidatePairs() {
2100
- return this.checkList;
2631
+ decorateSpedRequest(request, pair) {
2632
+ const runtime = this.spedRuntime;
2633
+ return runtime
2634
+ ? runtime.decorateOutgoing(request, pair)
2635
+ : (0, sped_bind_1.decoratePendingSped)(this, request, pair);
2101
2636
  }
2102
- sortCheckList() {
2103
- (0, iceBase_1.sortCandidatePairs)(this.checkList, this.iceControlling);
2637
+ bindingResponseSourceMatches(addr, pair) {
2638
+ return (addr != null &&
2639
+ addr[0] === pair.remoteAddr[0] &&
2640
+ addr[1] === pair.remoteAddr[1]);
2104
2641
  }
2105
- findPair(protocol, remoteCandidate) {
2106
- const pair = this.checkList.find((pair) => pair.protocol === protocol && pair.remoteCandidate === remoteCandidate);
2107
- return pair;
2642
+ isStaleConnectivityCheck(pair, generation) {
2643
+ if (generation !== this.generation) {
2644
+ return true;
2645
+ }
2646
+ // Restart clears the list. Unlisted pair in an empty list is a unit-test
2647
+ // checkStart, not a stale generation.
2648
+ if (this.checkList.length === 0) {
2649
+ return false;
2650
+ }
2651
+ return !this.checkList.includes(pair);
2652
+ }
2653
+ abandonInFlightStunTransactions() {
2654
+ for (const protocol of this.protocols) {
2655
+ const transactions = protocol.transactions;
2656
+ if (!transactions) {
2657
+ continue;
2658
+ }
2659
+ for (const transaction of Object.values(transactions)) {
2660
+ transaction.abandon?.();
2661
+ }
2662
+ }
2663
+ }
2664
+ async consumeSpedStun(message, addr, protocol, pair, generation) {
2665
+ const runtime = this.spedRuntime;
2666
+ if (generation !== this.generation) {
2667
+ return;
2668
+ }
2669
+ if (!pair || !runtime || !runtime.isLiveGeneration(generation)) {
2670
+ return;
2671
+ }
2672
+ await runtime.handleAuthenticatedStun(message, addr, generation, pair);
2673
+ if (generation !== this.generation ||
2674
+ !runtime.isLiveGeneration(generation)) {
2675
+ return;
2676
+ }
2677
+ if (pair) {
2678
+ runtime.syncRtt(pair);
2679
+ }
2680
+ this.settleSpedUnconfirmed(pair);
2681
+ await this.maybeSendSpedFallback(protocol, addr, generation);
2108
2682
  }
2109
2683
  applyIceControlling(iceControlling) {
2684
+ const becameControlling = !this._iceControlling && iceControlling;
2685
+ const roleChanged = this._iceControlling !== iceControlling;
2686
+ if (roleChanged) {
2687
+ this.invalidateNominations();
2688
+ this.selection.clearRetries();
2689
+ // Checks in flight carry the old role: the backups' stop (monitoring
2690
+ // starts again under the new role below), and so do the selected
2691
+ // pair's consent requests (not counted as unanswered; the next one
2692
+ // carries the new role).
2693
+ this.failover.halt();
2694
+ this.switching.stop();
2695
+ this.consent.cancelRequests();
2696
+ // USE-CANDIDATE received while controlled came from a peer that was
2697
+ // controlling then; as the controlling agent this one nominates itself.
2698
+ if (iceControlling) {
2699
+ for (const pair of [
2700
+ ...this.checkList,
2701
+ ...(this.provisional?.pairs ?? []),
2702
+ ]) {
2703
+ pair.remoteNominated = false;
2704
+ pair.remoteNomination = 0;
2705
+ }
2706
+ }
2707
+ }
2110
2708
  this._iceControlling = iceControlling;
2111
2709
  for (const pair of this.checkList) {
2112
2710
  pair.iceControlling = iceControlling;
2113
2711
  }
2712
+ if (roleChanged)
2713
+ this.failover.refresh();
2714
+ if (becameControlling)
2715
+ this.confirmSelections();
2716
+ }
2717
+ /**
2718
+ * The agent became controlling with a pair already selected (live or
2719
+ * provisional), e.g. one the peer nominated while this agent was
2720
+ * controlled. The selection stays (RFC 8445 §8.1.1 allows no other pair),
2721
+ * but the peer, controlled now, may still wait for a nomination: send
2722
+ * USE-CANDIDATE for that pair, repeated on timeouts as a nomination is.
2723
+ * A peer that selected the pair already keeps it.
2724
+ */
2725
+ confirmSelections() {
2726
+ if (!this.nominatesFullPeer())
2727
+ return;
2728
+ const live = this.nominated;
2729
+ if (live && this.state !== "closed" && this.checkList.includes(live)) {
2730
+ void this.confirmSelection((signal) => this.sendNomination(live, signal, this.consentNomination(live)), () => this.nominated === live && this.state !== "closed");
2731
+ }
2732
+ const generation = this.provisional;
2733
+ const provisional = generation?.nominated;
2734
+ if (generation && provisional && generation.pairs.includes(provisional)) {
2735
+ void this.confirmSelection((signal) => this.provisionalChecklist.nominate(generation, provisional, AbortSignal.any([generation.checks.signal, signal])), () => this.provisional === generation &&
2736
+ generation.nominated === provisional);
2737
+ }
2738
+ }
2739
+ async confirmSelection(send, selected) {
2740
+ const abort = new AbortController();
2741
+ this.selectionConfirmations.add(abort);
2742
+ try {
2743
+ for (let attempt = 1; attempt <= regularNomination_1.NOMINATION_ATTEMPTS; attempt++) {
2744
+ const outcome = await send(abort.signal);
2745
+ if (abort.signal.aborted || !selected() || !this.iceControlling) {
2746
+ return;
2747
+ }
2748
+ if (outcome === "unanswered")
2749
+ continue;
2750
+ // 487: the peer is controlling and wins; it nominates.
2751
+ if (outcome === "role-conflict")
2752
+ this.switchRole(false);
2753
+ return;
2754
+ }
2755
+ }
2756
+ catch (error) {
2757
+ log("confirm selection failed", error);
2758
+ }
2759
+ finally {
2760
+ this.selectionConfirmations.delete(abort);
2761
+ }
2762
+ }
2763
+ /**
2764
+ * The role changed: a nomination in flight (live or provisional) was sent
2765
+ * as the controlling agent and must not select a pair, fail one, or fail
2766
+ * the agent under the new role. Its transaction stops; a controlling agent
2767
+ * later nominates afresh.
2768
+ */
2769
+ invalidateNominations() {
2770
+ this.liteNominating = false;
2771
+ this.nomination.invalidate();
2772
+ this.selection.abort();
2773
+ for (const abort of this.selectionConfirmations)
2774
+ abort.abort();
2775
+ this.selectionConfirmations.clear();
2776
+ if (this.provisional) {
2777
+ this.provisional.liteNominating = false;
2778
+ this.provisional.nomination.invalidate();
2779
+ }
2114
2780
  }
2115
2781
  switchRole(iceControlling) {
2116
2782
  log("switch role", iceControlling);
@@ -2121,10 +2787,17 @@ class Connection {
2121
2787
  }
2122
2788
  this.applyIceControlling(iceControlling);
2123
2789
  this.sortCheckList();
2790
+ // Only a controlling agent nominates: start (or stop) waiting for it.
2791
+ this.nomination.evaluate();
2792
+ this.provisional?.nomination.evaluate();
2793
+ this.selection.evaluate();
2124
2794
  }
2125
2795
  checkComplete(pair) {
2126
2796
  pair.handle = undefined;
2127
2797
  if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
2798
+ const settled = this.settleSpedUnconfirmed(pair);
2799
+ void this.flushSpedUnconfirmedFallback(settled ?? pair);
2800
+ this.selection.forgetRetry(pair);
2128
2801
  // Updating the Nominated Flag
2129
2802
  // https://www.rfc-editor.org/rfc/rfc8445#section-7.3.1.5,
2130
2803
  // Once the nominated flag is set for a component of a data stream, it
@@ -2141,44 +2814,104 @@ class Connection {
2141
2814
  this.checkList.includes(pair) &&
2142
2815
  (pair.remoteCandidate.ufrag == undefined ||
2143
2816
  pair.remoteCandidate.ufrag === this.remoteUsername) &&
2144
- this.nominated == undefined) {
2145
- log("nominated", pair.toJSON());
2817
+ // One selection, except that semi-aggressive nomination and
2818
+ // renomination replace it with a better nominated pair
2819
+ // (`SelectionReplacement.replaces`).
2820
+ (this.nominated == undefined || this.selection.replaces(pair))) {
2821
+ const previous = this.nominated;
2822
+ const switching = this.switchNomination?.pair === pair
2823
+ ? this.switchNomination.reason
2824
+ : undefined;
2825
+ if (switching)
2826
+ this.switchNomination = undefined;
2827
+ // Failover: the selection moves off a pair that stopped answering
2828
+ // (or stopped receiving), or a failover nomination sent while it did
2829
+ // not answer succeeded.
2830
+ const failingOver = !!previous &&
2831
+ (this.selectionFailing() ||
2832
+ switching === "failover" ||
2833
+ switching === "receiving");
2834
+ log(failingOver
2835
+ ? "selected pair failed over"
2836
+ : previous
2837
+ ? "selected pair replaced"
2838
+ : "nominated", pair.toJSON(), { previous: previous?.toJSON(), reason: switching });
2146
2839
  this.nominated = pair;
2147
- this.nominating = false;
2840
+ this.liteNominating = false;
2841
+ this.nomination.stop();
2842
+ if (failingOver) {
2843
+ // The old pair is a backup of its socket now: the selection moves
2844
+ // back only once that socket answers again (FailoverMonitor.allows),
2845
+ // with a new nomination.
2846
+ previous.nominated = false;
2847
+ this.failover.demote(previous);
2848
+ }
2849
+ else if (previous && switching === "rtt") {
2850
+ // Test: tests/ice/selection-controller.test.ts "equal priority: the selection moves to the pair whose RTT is 11 ms lower, nominating it"
2851
+ previous.nominated = false;
2852
+ }
2148
2853
  // RFC 7675 section 5.1: the successful connectivity check that
2149
2854
  // selected the pair is its initial consent, so data may flow at once
2150
2855
  // instead of waiting for the consent lifecycle to start.
2151
- this.consentFresh = true;
2856
+ this.consent.fresh = true;
2857
+ this.clearConsentExpiredGrace();
2152
2858
  this.pruneTcpConnections(pair);
2859
+ this.failover.selected(pair);
2153
2860
  // After resetNominatedPair / renomination while already connected,
2154
2861
  // restart consent freshness on the new selected pair.
2155
2862
  if (!this.iceLite &&
2156
- (this.state === "connected" || this.state === "completed")) {
2863
+ (this.state === "connected" ||
2864
+ this.state === "completed" ||
2865
+ this.state === "disconnected")) {
2157
2866
  this.queryConsent();
2158
2867
  }
2159
2868
  // 8.1.2. Updating States
2160
2869
  // The agent MUST remove all Waiting and Frozen pairs in the check
2161
2870
  // list and triggered check queue for the same component as the
2162
- // nominated pairs for that media stream.
2871
+ // nominated pairs for that media stream. A controlling agent that
2872
+ // may replace the selection keeps the pairs that outrank it, and
2873
+ // failover keeps the backup of each other socket.
2874
+ const keepsChecking = this.iceControlling && this.replacesSelection();
2875
+ const backups = this.failover.keeps();
2163
2876
  for (const p of this.checkList) {
2164
2877
  if (p.component === pair.component &&
2165
2878
  [
2166
2879
  iceBase_1.CandidatePairState.WAITING,
2167
2880
  iceBase_1.CandidatePairState.FROZEN,
2168
- ].includes(p.state)) {
2881
+ ].includes(p.state) &&
2882
+ !(keepsChecking &&
2883
+ this.replacesWith(p) &&
2884
+ this.outranks(p, pair)) &&
2885
+ !backups.has(p)) {
2169
2886
  p.updateState(iceBase_1.CandidatePairState.FAILED);
2887
+ if (this.failoverEnabled())
2888
+ this.failover.prunedWithoutCheck(p);
2170
2889
  }
2171
2890
  }
2891
+ this.updateLinkState();
2892
+ // SPED cannot ride a relay / TURN selection: with support undecided
2893
+ // nothing would carry the handshake, so send it directly.
2894
+ if (this.spedRuntime?.settleIneligibleSelectedPair(pair)) {
2895
+ void this.flushSpedUnconfirmedFallback(pair);
2896
+ }
2172
2897
  }
2173
2898
  // Once there is at least one nominated pair in the valid list for
2174
2899
  // every component of at least one media stream and the state of the
2175
2900
  // check list is Running:
2176
2901
  if (this.nominated) {
2902
+ this.failover.refresh();
2177
2903
  if (!this.checkListDone) {
2178
2904
  log("ICE completed");
2179
2905
  this.checkListState.put(new Promise((r) => r(iceBase_1.ICE_COMPLETED)));
2180
2906
  this.checkListDone = true;
2181
2907
  }
2908
+ if (this.iceControlling && this.replacesSelection()) {
2909
+ this.selection.evaluate();
2910
+ void this.selection.checkOutrankingPairs();
2911
+ this.selection.scheduleRetries();
2912
+ // Test: tests/ice/selection-controller.test.ts "equal priority: the selection moves to the pair whose RTT is 11 ms lower, nominating it"
2913
+ this.switching.evaluate();
2914
+ }
2182
2915
  return;
2183
2916
  }
2184
2917
  log("not completed", pair.toJSON());
@@ -2190,9 +2923,24 @@ class Connection {
2190
2923
  }
2191
2924
  }
2192
2925
  }
2193
- this.nominateTcpPairIfReady();
2194
- // A nomination request is still in flight; its result decides the outcome.
2195
- if (this.nominating) {
2926
+ this.nomination.evaluate();
2927
+ this.selection.evaluate();
2928
+ this.selection.scheduleRetries();
2929
+ // A backup (or a failover target) that failed is replaced.
2930
+ if (this.nominated)
2931
+ this.failover.refresh();
2932
+ this.concludeCheckListIfExhausted();
2933
+ }
2934
+ /**
2935
+ * Fail the check list once no pair can succeed and no nomination can still
2936
+ * select one. Background gathering and remote trickle both delay this.
2937
+ */
2938
+ concludeCheckListIfExhausted() {
2939
+ if (this.nominated ||
2940
+ this.liteNominating ||
2941
+ this.selection.nominating ||
2942
+ this.nomination.inFlight ||
2943
+ this.nomination.waiting) {
2196
2944
  return;
2197
2945
  }
2198
2946
  {
@@ -2222,6 +2970,28 @@ class Connection {
2222
2970
  }));
2223
2971
  }
2224
2972
  }
2973
+ /**
2974
+ * A check of the live checklist cancelled before its outcome (the
2975
+ * checklist completed, `connect` cancels the remaining checks) leaves the
2976
+ * pair Waiting instead of In-Progress, so the peer's checks on it still
2977
+ * trigger one (7.2.1.4): a controlled agent that selected a lower pair can
2978
+ * then follow a later nomination of this one. A nomination already received
2979
+ * for it is checked at once (its triggering check came while the cancelled
2980
+ * one was still in flight). A generation that ended or a closed agent
2981
+ * changes nothing.
2982
+ */
2983
+ checkCancelled(pair, remoteGeneration) {
2984
+ if (pair.state !== iceBase_1.CandidatePairState.IN_PROGRESS ||
2985
+ this.state === "closed" ||
2986
+ this.remoteGeneration !== remoteGeneration ||
2987
+ !this.checkList.includes(pair)) {
2988
+ return;
2989
+ }
2990
+ pair.updateState(iceBase_1.CandidatePairState.WAITING);
2991
+ if (pair.remoteNominated && !this.iceControlling) {
2992
+ pair.handle = this.checkStart(pair);
2993
+ }
2994
+ }
2225
2995
  /**
2226
2996
  * 487 / 401 retry of a check: the retry is cancelled with the check it
2227
2997
  * replaces (its handle) and, through checkStart, with the generation.
@@ -2234,107 +3004,271 @@ class Connection {
2234
3004
  isTcpPair(pair) {
2235
3005
  return pair.localCandidate.transport.toLowerCase() === "tcp";
2236
3006
  }
2237
- /**
2238
- * Aggressive nomination lets each side settle on whichever TCP connection
2239
- * finished first; the two sides can then pick different connections and
2240
- * pruning destroys the peer's choice. For TCP the controlling agent instead
2241
- * nominates exactly one valid pair (RFC 8445 §8.1.1 regular nomination).
2242
- */
2243
- usesTcpRegularNomination(pair) {
2244
- return this.iceControlling && !this.remoteIsLite && this.isTcpPair(pair);
2245
- }
2246
3007
  checkRequestOptions(pair) {
2247
3008
  const onRequestSent = (attempt) => {
2248
3009
  if (attempt > 0) {
2249
3010
  pair.retransmissionsSent++;
2250
3011
  }
2251
3012
  };
3013
+ const integrityAlgorithm = this.options.messageIntegrity;
2252
3014
  if (this.isTcpPair(pair)) {
2253
3015
  // RFC 5389 §7.2.2: no retransmissions over a reliable transport.
2254
3016
  return {
2255
3017
  retransmissions: 0,
2256
3018
  responseTimeout: const_1.TCP_CHECK_RESPONSE_TIMEOUT_MS,
2257
3019
  onRequestSent,
3020
+ integrityAlgorithm,
2258
3021
  };
2259
3022
  }
2260
- return { retransmissions: 4, onRequestSent };
3023
+ return { retransmissions: 4, onRequestSent, integrityAlgorithm };
3024
+ }
3025
+ /** The agent is controlling and both agents are full ICE. */
3026
+ nominatesFullPeer() {
3027
+ return this.iceControlling && !this.remoteIsLite && !this.iceLite;
2261
3028
  }
2262
3029
  /**
2263
- * Controlling side: nominate the highest-priority TCP pair once every
2264
- * higher-priority TCP pair has finished its check, so the choice does not
2265
- * depend on which connection happened to complete first.
3030
+ * Both agents advertised renomination (`IceOptions.renomination`): the
3031
+ * controlling agent nominates with NOMINATION values instead of
3032
+ * USE-CANDIDATE, whatever `IceOptions.nomination` says.
2266
3033
  */
2267
- nominateTcpPairIfReady() {
2268
- if (!this.iceControlling ||
2269
- this.remoteIsLite ||
2270
- this.nominated ||
2271
- this.nominating) {
2272
- return;
2273
- }
2274
- for (const pair of this.checkList) {
2275
- if (!this.isTcpPair(pair)) {
2276
- continue;
2277
- }
2278
- if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
2279
- this.nominateTcpPair(pair);
2280
- return;
2281
- }
2282
- if (pair.state !== iceBase_1.CandidatePairState.FAILED) {
2283
- // A higher-priority pair may still succeed.
2284
- return;
3034
+ usesRenomination() {
3035
+ return (this.nominatesFullPeer() &&
3036
+ !!this.options.renomination &&
3037
+ this.remoteRenomination);
3038
+ }
3039
+ /**
3040
+ * `nomination: "regular"`: RFC 8445 §8.1.1 regular nomination for every
3041
+ * transport. A check that succeeds only makes its pair valid;
3042
+ * `RegularNomination` later picks one valid pair and nominates it once
3043
+ * with a separate USE-CANDIDATE check.
3044
+ */
3045
+ usesRegularNomination() {
3046
+ return (this.nominatesFullPeer() &&
3047
+ this.options.nomination === "regular" &&
3048
+ !this.usesRenomination());
3049
+ }
3050
+ /**
3051
+ * The default, as libwebrtc: checks carry USE-CANDIDATE until a pair is
3052
+ * selected and afterwards for pairs that outrank the selected one, so the
3053
+ * first pair that succeeds is selected at once and a higher-priority pair
3054
+ * that succeeds later (a TURN/UDP candidate trickled after a TURN/TCP one
3055
+ * connected) replaces it. A first-success-wins nomination would keep the
3056
+ * lower-priority pair for the whole session.
3057
+ */
3058
+ usesSemiAggressiveNomination() {
3059
+ return (this.nominatesFullPeer() &&
3060
+ this.options.nomination !== "regular" &&
3061
+ !this.usesRenomination());
3062
+ }
3063
+ /**
3064
+ * The controlling agent may move the selection to a higher-priority pair
3065
+ * (semi-aggressive nomination, renomination): checks of pairs that outrank
3066
+ * the selected one go on after the first selection.
3067
+ */
3068
+ replacesSelection() {
3069
+ return this.usesSemiAggressiveNomination() || this.usesRenomination();
3070
+ }
3071
+ /**
3072
+ * A pair semi-aggressive nomination and renomination may select: not an
3073
+ * ICE-TCP pair (each TCP pair is its own connection, and nominating more
3074
+ * than one could leave the agents on different connections after pruning;
3075
+ * TCP pairs keep regular nomination, see `regularNominationPairs`), nor
3076
+ * one the agent never checks (forceTurn).
3077
+ */
3078
+ replacesWith(pair) {
3079
+ return !this.isTcpPair(pair) && !this.isUncheckedPair(pair);
3080
+ }
3081
+ /**
3082
+ * The pairs `RegularNomination` nominates from: every pair with
3083
+ * `nomination: "regular"`, otherwise the ICE-TCP pairs (as before
3084
+ * semi-aggressive nomination, #721).
3085
+ */
3086
+ regularNominationPairs(pairs) {
3087
+ return this.usesRegularNomination()
3088
+ ? pairs
3089
+ : pairs.filter((pair) => this.isTcpPair(pair));
3090
+ }
3091
+ /** `IceOptions.nominationDelayMs`, or its default when unset or invalid. */
3092
+ get nominationDelayMs() {
3093
+ const delay = this.options.nominationDelayMs;
3094
+ return delay !== undefined && Number.isFinite(delay) && delay >= 0
3095
+ ? delay
3096
+ : regularNomination_1.DEFAULT_NOMINATION_DELAY_MS;
3097
+ }
3098
+ /** A pair the agent never checks itself (forceTurn keeps it from the schedule). */
3099
+ isUncheckedPair(pair) {
3100
+ return !!this.options.forceTurn && pair.protocol.type === protocol_1.StunProtocol.type;
3101
+ }
3102
+ /** The highest-priority valid pair of `pairs`. */
3103
+ bestValidPair(pairs) {
3104
+ let best;
3105
+ for (const pair of pairs) {
3106
+ if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED &&
3107
+ (!best || this.outranks(pair, best))) {
3108
+ best = pair;
2285
3109
  }
2286
3110
  }
3111
+ return best;
3112
+ }
3113
+ outranks(pair, other) {
3114
+ return ((0, iceBase_1.compareCandidatePairPriority)(pair.localCandidate, pair.remoteCandidate, other.localCandidate, other.remoteCandidate, this.iceControlling) > 0);
3115
+ }
3116
+ /**
3117
+ * The live checklist's side of regular nomination (`RegularNomination`):
3118
+ * the controlling agent nominates the best valid pair once the checklist
3119
+ * is quiet (see `decideNomination`).
3120
+ */
3121
+ liveNominationHost() {
3122
+ return {
3123
+ active: () => this.nominatesFullPeer() && !this.nominated && this.state !== "closed",
3124
+ checking: () => this.checksBegun,
3125
+ pairs: () => this.regularNominationPairs(this.checkList),
3126
+ remoteCandidatesEnd: () => this.remoteCandidatesEnd,
3127
+ localCandidatesEnd: () => this.localCandidatesEnd,
3128
+ delayMs: () => this.nominationDelayMs,
3129
+ unchecked: (pair) => this.isUncheckedPair(pair),
3130
+ outranks: (pair, other) => this.outranks(pair, other),
3131
+ preferred: () => {
3132
+ const hint = this.nominationHint;
3133
+ if (!hint ||
3134
+ // Semi-aggressive nomination and renomination may replace the
3135
+ // selection; the hint belongs to regular nomination.
3136
+ !this.usesRegularNomination() ||
3137
+ hint.localUsername !== this.localUsername ||
3138
+ hint.remoteUsername !== this.remoteUsername ||
3139
+ hint.remotePassword !== this.remotePassword ||
3140
+ // The commit closed the pair's socket (a TURN allocation an ICE
3141
+ // restart replaces, an excluded host socket): the path is gone for
3142
+ // the peer too, so the usual rules choose.
3143
+ !this.protocols.includes(hint.protocol)) {
3144
+ return undefined;
3145
+ }
3146
+ return (pair) => (0, regularNomination_1.pairKey)(pair) === hint.key;
3147
+ },
3148
+ owns: (pair) => this.state !== "closed" && this.checkList.includes(pair),
3149
+ send: (pair, signal) => this.sendNomination(pair, signal),
3150
+ nominated: (pair) => {
3151
+ pair.nominated = true;
3152
+ this.checkComplete(pair);
3153
+ },
3154
+ rejected: (pair) => {
3155
+ // The peer did not select this pair: only it fails, and
3156
+ // checkComplete nominates the next one.
3157
+ pair.updateState(iceBase_1.CandidatePairState.FAILED);
3158
+ this.checkComplete(pair);
3159
+ },
3160
+ // RFC 8445 §7.2.5.1: the peer is controlling too and wins; the
3161
+ // nomination was not accepted. Become controlled: the pair stays
3162
+ // valid and the peer nominates.
3163
+ roleConflict: () => this.switchRole(false),
3164
+ abandoned: (pair) => this.nominationAbandoned(pair),
3165
+ // The valid pair it waited for may be gone (another remote generation
3166
+ // dropped): the checklist may have failed meanwhile.
3167
+ deadlinePassed: () => this.concludeCheckListIfExhausted(),
3168
+ };
2287
3169
  }
2288
- nominateTcpPair(pair) {
2289
- this.nominating = true;
2290
- const generation = this.remoteGeneration;
3170
+ /**
3171
+ * Send the USE-CANDIDATE check for a live `pair` (see `NominationOutcome`),
3172
+ * or with `nomination` the renomination check that carries that
3173
+ * NOMINATION value instead.
3174
+ */
3175
+ async sendNomination(pair, signal, nomination) {
2291
3176
  const request = this.buildRequest({
2292
- nominate: true,
3177
+ nominate: nomination === undefined,
3178
+ nomination,
2293
3179
  localUsername: pair.localCandidate.ufrag ?? this.localUsername,
2294
3180
  remoteUsername: this.remoteUsername,
2295
3181
  iceControlling: this.iceControlling,
2296
3182
  localCandidate: pair.localCandidate,
2297
3183
  });
3184
+ if (!this.decorateSpedRequest(request, pair)) {
3185
+ return "rejected";
3186
+ }
3187
+ const generation = this.generation;
2298
3188
  pair.requestsSent++;
2299
- pair.protocol
2300
- .request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), { ...this.checkRequestOptions(pair), signal: this.remoteChecks.signal })
2301
- .then(() => {
2302
- if (this.isStaleNomination(pair, generation)) {
2303
- return;
2304
- }
3189
+ try {
3190
+ const [response, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), {
3191
+ ...this.checkRequestOptions(pair),
3192
+ signal: AbortSignal.any([this.remoteChecks.signal, signal]),
3193
+ });
2305
3194
  pair.responsesReceived++;
2306
- pair.nominated = true;
2307
- this.nominating = false;
2308
- this.checkComplete(pair);
2309
- }, (error) => {
2310
- if (this.isStaleNomination(pair, generation)) {
2311
- return;
2312
- }
2313
- log("tcp nomination failed", pair.toJSON(), error);
2314
- this.nominating = false;
2315
- pair.updateState(iceBase_1.CandidatePairState.FAILED);
2316
- this.checkComplete(pair);
2317
- });
3195
+ this.spedRuntime?.tryMarkDirectHandshakeReady(pair, generation);
3196
+ await this.consumeSpedStun(response, addr, pair.protocol, pair, generation);
3197
+ return "nominated";
3198
+ }
3199
+ catch (error) {
3200
+ log("nomination failed", pair.toJSON(), error);
3201
+ if ((0, checkMessages_1.isRoleConflict)(error))
3202
+ return "role-conflict";
3203
+ return error instanceof exceptions_1.TransactionTimeout ? "unanswered" : "rejected";
3204
+ }
3205
+ }
3206
+ /**
3207
+ * No attempt of a USE-CANDIDATE check was answered, or the pair a
3208
+ * provisional nomination may have selected (`NominationHint`) failed or
3209
+ * never appeared. A request may still have reached the peer, and a
3210
+ * controlled agent keeps the first pair
3211
+ * nominated to it (RFC 8445 §8.1.1): nominating another pair could leave
3212
+ * the two agents on different pairs. The agent nominates nothing else,
3213
+ * connect() rejects and the agent fails (an ICE restart starts over), as a
3214
+ * consent expiry does.
3215
+ */
3216
+ nominationAbandoned(pair) {
3217
+ pair?.updateState(iceBase_1.CandidatePairState.FAILED);
3218
+ if (!this.checkListDone) {
3219
+ this.checkListDone = true;
3220
+ this.checkListState.put(new Promise((r) => r(regularNomination_1.ICE_NOMINATION_ABANDONED)));
3221
+ }
3222
+ this.setState("failed");
3223
+ }
3224
+ /**
3225
+ * At the restart that ends the provisional checklist (a final answer): the
3226
+ * pair it nominated, or sent a USE-CANDIDATE to that the peer did not
3227
+ * refuse (see `NominationHint`).
3228
+ */
3229
+ provisionalNominationHint() {
3230
+ const generation = this.provisional;
3231
+ const pair = generation?.nominated ?? generation?.nomination.maybeSelected;
3232
+ if (!generation?.remoteUsername || !generation.remotePassword || !pair) {
3233
+ return undefined;
3234
+ }
3235
+ return {
3236
+ localUsername: generation.localUsername,
3237
+ remoteUsername: generation.remoteUsername,
3238
+ remotePassword: generation.remotePassword,
3239
+ key: (0, regularNomination_1.pairKey)(pair),
3240
+ protocol: pair.protocol,
3241
+ };
2318
3242
  }
2319
- /** The agent was closed or restarted while the nomination was in flight. */
3243
+ /** The agent was closed or restarted while the ICE-lite nomination was in flight. */
2320
3244
  isStaleNomination(pair, generation) {
2321
3245
  return (this.state === "closed" ||
2322
3246
  this.remoteGeneration !== generation ||
2323
3247
  !this.checkList.includes(pair));
2324
3248
  }
2325
3249
  addPair(pair) {
3250
+ const best = this.bestValidPair(this.checkList);
2326
3251
  this.checkList.push(pair);
2327
3252
  this.sortCheckList();
3253
+ this.wakeIncomingCheckWaits();
3254
+ this.nomination.pairAdded(pair, best);
3255
+ // A pair that may replace the selection is checked after it too.
3256
+ const selected = this.nominated;
3257
+ if (selected &&
3258
+ this.iceControlling &&
3259
+ this.replacesSelection() &&
3260
+ this.replacesWith(pair) &&
3261
+ this.outranks(pair, selected) &&
3262
+ this.failoverAllows(pair)) {
3263
+ void this.selection.checkOutrankingPairs();
3264
+ }
3265
+ // A pair of another socket may become its backup.
3266
+ if (selected)
3267
+ this.failover.refresh();
2328
3268
  }
2329
- // 7.2. STUN Server Procedures
2330
- // 7.2.1.3、7.2.1.4、および7.2.1.5
2331
- checkIncoming(message, addr, protocol) {
2332
- // """
2333
- // Handle a successful incoming check.
2334
- // """
3269
+ ensureIncomingPair(message, addr, protocol) {
2335
3270
  const txUsername = message.getAttributeValue("USERNAME");
2336
- const { remoteUsername: localUsername } = decodeTxUsername(txUsername);
2337
- // find remote candidate
3271
+ const { remoteUsername: localUsername } = (0, checkMessages_1.decodeTxUsername)(txUsername);
2338
3272
  let remoteCandidate;
2339
3273
  const [host, port] = addr;
2340
3274
  for (const c of this.remoteCandidates) {
@@ -2343,23 +3277,41 @@ class Connection {
2343
3277
  break;
2344
3278
  }
2345
3279
  }
3280
+ if (!remoteCandidate && (0, sped_bind_1.isConnectionSpedEnabled)(this)) {
3281
+ // SPED: a pair of this protocol and remote address exists already (its
3282
+ // candidate is no longer listed). The check belongs to it: a second
3283
+ // pair of the same 5-tuple would split the authenticated path SPED
3284
+ // pins. Without SPED a new peer-reflexive pair is formed as before.
3285
+ const existing = this.findPairByAddr(protocol, addr);
3286
+ if (existing) {
3287
+ return existing;
3288
+ }
3289
+ }
2346
3290
  if (!remoteCandidate) {
2347
- // 7.2.1.3. Learning Peer Reflexive Candidates
2348
3291
  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"
2349
3292
  ? (0, candidate_1.remoteTcpTypeForIncoming)(protocol.localCandidate.tcptype)
2350
3293
  : undefined, undefined, undefined);
2351
3294
  this._remoteCandidates.push(remoteCandidate);
2352
3295
  }
2353
- // find pair
2354
3296
  let pair = this.findPair(protocol, remoteCandidate);
2355
3297
  if (!pair) {
2356
3298
  pair = new iceBase_1.CandidatePair(protocol, remoteCandidate, this.iceControlling);
2357
3299
  pair.updateState(iceBase_1.CandidatePairState.WAITING);
2358
3300
  this.addPair(pair);
2359
3301
  }
3302
+ return pair;
3303
+ }
3304
+ // 7.2. STUN Server Procedures
3305
+ // 7.2.1.3、7.2.1.4、および7.2.1.5
3306
+ checkIncoming(message, addr, protocol) {
3307
+ // """
3308
+ // Handle a successful incoming check.
3309
+ // """
3310
+ const pair = this.ensureIncomingPair(message, addr, protocol);
2360
3311
  pair.noteIncomingRequest(message.transactionIdHex);
2361
3312
  pair.requestsReceived++;
2362
3313
  pair.responsesSent++;
3314
+ this.failover.received(pair);
2363
3315
  // The pair's local candidate is the protocol's shared candidate of the
2364
3316
  // current generation. A late check addressed to an earlier ufrag (consent
2365
3317
  // on the old pair during an ICE restart) must not relabel it, or the next
@@ -2371,13 +3323,18 @@ class Connection {
2371
3323
  remotePassword: this.remotePassword,
2372
3324
  generation: this.generation,
2373
3325
  });
3326
+ const nomination = (0, checkMessages_1.receivedNomination)(message);
3327
+ if (nomination > 0 && !this.iceControlling) {
3328
+ // We don't un-nominate a pair: keep the larger nomination.
3329
+ pair.remoteNomination = Math.max(pair.remoteNomination, nomination);
3330
+ }
2374
3331
  if (this.iceLite) {
2375
- if (message.attributesKeys.includes("USE-CANDIDATE") &&
2376
- !this.iceControlling) {
3332
+ if (nomination > 0 && !this.iceControlling) {
2377
3333
  pair.remoteNominated = true;
2378
3334
  pair.nominated = true;
2379
3335
  pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
2380
3336
  this.checkComplete(pair);
3337
+ this.spedRuntime?.tryMarkDirectHandshakeReady(pair, this.generation);
2381
3338
  }
2382
3339
  return;
2383
3340
  }
@@ -2389,8 +3346,9 @@ class Connection {
2389
3346
  pair.handle = this.checkStart(pair);
2390
3347
  }
2391
3348
  // 7.2.1.5. Updating the Nominated Flag
2392
- if (message.attributesKeys.includes("USE-CANDIDATE") &&
2393
- !this.iceControlling) {
3349
+ // (USE-CANDIDATE, or a NOMINATION value with renomination; a pair
3350
+ // already selected may be replaced, see `SelectionReplacement.replaces`)
3351
+ if (nomination > 0 && !this.iceControlling) {
2394
3352
  pair.remoteNominated = true;
2395
3353
  if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
2396
3354
  pair.nominated = true;
@@ -2398,7 +3356,35 @@ class Connection {
2398
3356
  }
2399
3357
  }
2400
3358
  }
2401
- tryPair(protocol, remoteCandidate) {
3359
+ /**
3360
+ * @param admit after a selection that may still be replaced, only pairs
3361
+ * that could replace it join the checklist.
3362
+ */
3363
+ tryPair(protocol, remoteCandidate, admit = this.admitsPair(), routeChecked = false) {
3364
+ if (!routeChecked && this.gatherer.isWildcardProtocol(protocol)) {
3365
+ void this.gatherer
3366
+ .wildcardPathUncovered(remoteCandidate)
3367
+ .then((uncovered) => {
3368
+ // As pairLocalProtocol: once a pair is selected (which also ends
3369
+ // the checklist) only a selection that may still be replaced
3370
+ // takes more pairs.
3371
+ const replaceable = !!this.nominated && this.iceControlling && this.replacesSelection();
3372
+ if (uncovered &&
3373
+ ((!this.nominated && !this.checkListDone) || replaceable) &&
3374
+ this.state !== "closed" &&
3375
+ this.protocols.includes(protocol) &&
3376
+ this.remoteCandidates.includes(remoteCandidate)) {
3377
+ this.tryPair(protocol, remoteCandidate, this.admitsPair(), true);
3378
+ this.sortCheckList();
3379
+ const pair = this.findPair(protocol, remoteCandidate);
3380
+ if (this.schedulingStopped &&
3381
+ pair?.state === iceBase_1.CandidatePairState.WAITING) {
3382
+ pair.handle = this.checkStart(pair);
3383
+ }
3384
+ }
3385
+ });
3386
+ return;
3387
+ }
2402
3388
  if (protocol.localCandidate?.canPairWith(remoteCandidate) &&
2403
3389
  !(protocol.localCandidate.transport.toLowerCase() === "tcp" &&
2404
3390
  protocol.localCandidate.tcptype === "passive" &&
@@ -2409,41 +3395,349 @@ class Connection {
2409
3395
  !this.options.filterCandidatePair(pair)) {
2410
3396
  return;
2411
3397
  }
3398
+ if (admit && !admit(pair))
3399
+ return;
2412
3400
  pair.updateState(iceBase_1.CandidatePairState.WAITING);
2413
3401
  this.addPair(pair);
2414
3402
  }
2415
3403
  }
3404
+ /** See `tryPair`: undefined admits every pair. */
3405
+ admitsPair() {
3406
+ const selected = this.nominated;
3407
+ if (!selected || !this.iceControlling || !this.replacesSelection()) {
3408
+ return undefined;
3409
+ }
3410
+ // Failover: a pair of another socket, or of the selected pair's socket
3411
+ // to another remote address, may become a backup.
3412
+ const failover = this.failoverEnabled();
3413
+ return (pair) => this.replacesWith(pair) &&
3414
+ (this.outranks(pair, selected) ||
3415
+ (failover &&
3416
+ (pair.protocol !== selected.protocol ||
3417
+ pair.remoteAddr[0] !== selected.remoteAddr[0] ||
3418
+ pair.remoteAddr[1] !== selected.remoteAddr[1])));
3419
+ }
3420
+ /**
3421
+ * Failover of the selected pair without an ICE restart (libwebrtc
3422
+ * compatible) applies to the agent's mode: both agents are full ICE and the
3423
+ * agent uses semi-aggressive nomination or renomination (the modes in which
3424
+ * a controlling agent may replace the selection, `replacesSelection`; a
3425
+ * controlled agent follows the peer's nominations). Regular nomination
3426
+ * (RFC 8445 §8.1.1 allows no other pair without an ICE restart) and ICE-lite
3427
+ * keep the selection until consent expires.
3428
+ */
3429
+ failoverScope() {
3430
+ if (this.iceLite || this.remoteIsLite || this.state === "closed") {
3431
+ return false;
3432
+ }
3433
+ if (this.options.renomination && this.remoteRenomination)
3434
+ return true;
3435
+ return this.options.nomination !== "regular";
3436
+ }
3437
+ /** {@link failoverScope}, and the selected pair is not ICE-TCP (its closed connection fails the agent). */
3438
+ failoverEnabled() {
3439
+ const transport = this.nominated?.protocol?.localCandidate?.transport;
3440
+ return (transport !== undefined &&
3441
+ transport.toLowerCase() !== "tcp" &&
3442
+ this.failoverScope());
3443
+ }
3444
+ /** `IceOptions.failover` with its defaults (resolved again when the options change). */
3445
+ get failoverThresholds() {
3446
+ const source = this.options.failover;
3447
+ let cache = this.failoverThresholdsCache;
3448
+ if (!cache || cache.source !== source) {
3449
+ cache = { source, value: (0, failover_1.resolveFailoverThresholds)(source) };
3450
+ this.failoverThresholdsCache = cache;
3451
+ }
3452
+ return cache.value;
3453
+ }
3454
+ /**
3455
+ * Failover: the selected pair stopped receiving (`isNotReceiving`) while
3456
+ * its consent is still fresh and it is not unwritable yet.
3457
+ * `SelectionController` makes that switch; this lets its nomination
3458
+ * replace the selection.
3459
+ * @see tests/ice/failover.test.ts "the selected pair stops answering and receiving: once it has not been receiving for 1 s (from the later of 2.5 s of silence and an unanswered check), the agent moves to the backup that receives, before the pair is unwritable (§15 A)"
3460
+ */
3461
+ selectionNotReceiving() {
3462
+ const selected = this.nominated;
3463
+ return (!!selected &&
3464
+ this.failoverEnabled() &&
3465
+ this.consent.fresh &&
3466
+ this.failover.notReceiving(selected));
3467
+ }
3468
+ /** Failover: the selection may move to a backup ({@link selectionDown} or {@link selectionNotReceiving}). */
3469
+ selectionFailing() {
3470
+ return this.selectionDown() || this.selectionNotReceiving();
3471
+ }
3472
+ /** Failover: the selected pair stopped answering (unwritable) or its consent expired. */
3473
+ selectionDown() {
3474
+ const selected = this.nominated;
3475
+ return (!!selected &&
3476
+ this.failoverEnabled() &&
3477
+ (!this.consent.fresh || this.failover.knownUnwritable(selected)));
3478
+ }
3479
+ /** Whether `pair` may be nominated to move the selection up (see `FailoverMonitor.allows`). */
3480
+ failoverAllows(pair) {
3481
+ return !this.failoverEnabled() || this.failover.allows(pair);
3482
+ }
3483
+ failoverHost() {
3484
+ return {
3485
+ enabled: () => this.failoverEnabled(),
3486
+ selected: () => this.nominated,
3487
+ pairs: () => this.checkList,
3488
+ eligible: (pair) => this.replacesWith(pair),
3489
+ iceControlling: () => this.iceControlling,
3490
+ thresholds: () => this.failoverThresholds,
3491
+ movesSelectionUp: () => this.iceControlling && this.replacesSelection(),
3492
+ ping: (pair, signal) => this.pingBackup(pair, signal),
3493
+ validated: (pair) => {
3494
+ pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
3495
+ if (pair.remoteNominated && !this.iceControlling)
3496
+ pair.nominated = true;
3497
+ this.checkComplete(pair);
3498
+ },
3499
+ dropped: (pair) => {
3500
+ if (pair !== this.nominated) {
3501
+ pair.updateState(iceBase_1.CandidatePairState.FAILED);
3502
+ }
3503
+ },
3504
+ changed: () => this.onLinkChanged(),
3505
+ recovered: () => this.selection.evaluate(),
3506
+ };
3507
+ }
3508
+ /** The writability of a monitored pair may have changed. */
3509
+ onLinkChanged() {
3510
+ this.evaluateFailover();
3511
+ this.updateLinkState();
3512
+ // Test: tests/ice/selection-controller.test.ts "receiving: a selection that recovers within RECEIVING_SWITCHING_DELAY stays; one that does not moves after it"
3513
+ this.switching.evaluate();
3514
+ }
3515
+ /**
3516
+ * Failover (controlling): the selected pair stopped answering, so nominate
3517
+ * the best writable backup (`FailoverMonitor.target`), with USE-CANDIDATE
3518
+ * (semi-aggressive) or the next NOMINATION value (renomination). Its
3519
+ * success moves the selection (`replacesSelectedPair`). A controlled agent
3520
+ * only follows the peer's nominations.
3521
+ *
3522
+ * A selected pair that only stopped receiving is `SelectionController`'s.
3523
+ * @see tests/ice/failover.test.ts "the selected pair stops answering and receiving: once it has not been receiving for 1 s (from the later of 2.5 s of silence and an unanswered check), the agent moves to the backup that receives, before the pair is unwritable (§15 A)"
3524
+ */
3525
+ evaluateFailover() {
3526
+ if (!this.iceControlling ||
3527
+ !this.replacesSelection() ||
3528
+ this.selection.nominating ||
3529
+ this.state === "closed" ||
3530
+ this.state === "failed") {
3531
+ return;
3532
+ }
3533
+ if (!this.selectionDown())
3534
+ return;
3535
+ const target = this.failover.target();
3536
+ if (!target) {
3537
+ // Nothing to fail over to: check the failed pairs that outrank the
3538
+ // selection now (a path that came back may be one of them).
3539
+ this.selection.checkFailedOutranking();
3540
+ return;
3541
+ }
3542
+ log("failover", target.toJSON(), {
3543
+ selected: this.nominated?.toJSON(),
3544
+ reason: "unwritable",
3545
+ });
3546
+ this.switchNomination = { pair: target, reason: "failover" };
3547
+ this.selection.nominate(target);
3548
+ }
3549
+ /**
3550
+ * Failover: the agent's state from the selected pair and the backups.
3551
+ * `disconnected` while the selected pair is unwritable and no backup is
3552
+ * writable; back to the state it replaced only once the selected pair is
3553
+ * writable again (it recovered, or the selection moved to a backup); a
3554
+ * backup that answers before the selection moved to it keeps the agent
3555
+ * `disconnected`. `failed` once the selected pair's consent expired with no
3556
+ * writable backup left.
3557
+ */
3558
+ updateLinkState() {
3559
+ if (!this.failoverEnabled())
3560
+ return;
3561
+ const state = this.state;
3562
+ if (state !== "connected" &&
3563
+ state !== "completed" &&
3564
+ state !== "disconnected") {
3565
+ return;
3566
+ }
3567
+ const selected = this.nominated;
3568
+ const selectedUp = this.consent.fresh && !this.failover.knownUnwritable(selected);
3569
+ if (selectedUp) {
3570
+ // The selected pair answers again, or the selection moved to a
3571
+ // backup that answers (a replacement is selected with a fresh
3572
+ // response).
3573
+ if (state === "disconnected") {
3574
+ this.setState(this.stateBeforeDisconnect ?? "connected");
3575
+ }
3576
+ return;
3577
+ }
3578
+ if (!this.consent.fresh) {
3579
+ // Consent expired: nothing can be sent. Disconnected while a writable
3580
+ // backup may still take over within the grace period, else failed.
3581
+ if (this.consentExpiredGrace !== undefined &&
3582
+ this.failover.hasWritableBackup()) {
3583
+ if (state !== "disconnected") {
3584
+ this.stateBeforeDisconnect = state;
3585
+ this.setState("disconnected");
3586
+ }
3587
+ return;
3588
+ }
3589
+ log("consent expired without a writable backup");
3590
+ this.failConsentExpired();
3591
+ return;
3592
+ }
3593
+ // A writable backup the selection may still move to (the controlling
3594
+ // agent's nomination, the controlled agent's peer): not disconnected
3595
+ // yet, but not recovered either until the selection moved.
3596
+ if (this.failover.hasWritableBackup())
3597
+ return;
3598
+ if (state !== "disconnected") {
3599
+ this.stateBeforeDisconnect = state;
3600
+ this.setState("disconnected");
3601
+ }
3602
+ }
3603
+ /** See `consentExpiredGrace`. */
3604
+ startConsentExpiredGrace() {
3605
+ if (this.consentExpiredGrace !== undefined)
3606
+ return;
3607
+ this.consentExpiredGrace = setTimeout(() => {
3608
+ this.consentExpiredGrace = undefined;
3609
+ if (this.consent.fresh)
3610
+ return;
3611
+ const state = this.state;
3612
+ if (state === "closed" || state === "failed")
3613
+ return;
3614
+ log("consent expired and the selection did not move to a backup");
3615
+ this.failConsentExpired();
3616
+ }, iceBase_1.FAILOVER_CONSENT_EXPIRED_GRACE);
3617
+ }
3618
+ clearConsentExpiredGrace() {
3619
+ if (this.consentExpiredGrace === undefined)
3620
+ return;
3621
+ clearTimeout(this.consentExpiredGrace);
3622
+ this.consentExpiredGrace = undefined;
3623
+ }
3624
+ /** The selected pair's consent expired and no backup took over: the agent fails (an ICE restart recovers). */
3625
+ failConsentExpired() {
3626
+ this.clearConsentExpiredGrace();
3627
+ this.consent.stop();
3628
+ this.failover.reset();
3629
+ this.switching.stop();
3630
+ this.setState("failed");
3631
+ }
3632
+ /**
3633
+ * Failover: sending on `protocol` (to `remoteAddr`, or on every path of it
3634
+ * when undefined: its TURN allocation is lost) failed in a way that says
3635
+ * the path is gone (`Protocol.onPathBroken`). The monitored pairs on it are
3636
+ * unwritable at once, so the selection fails over without waiting for
3637
+ * unanswered checks (libwebrtc drops the connections of a port that is
3638
+ * gone).
3639
+ */
3640
+ failoverPathBroken(protocol, remoteAddr, error) {
3641
+ if (!this.failoverEnabled())
3642
+ return;
3643
+ if (this.state === "closed" || this.state === "failed")
3644
+ return;
3645
+ if (!this.failover.broken(protocol, remoteAddr))
3646
+ return;
3647
+ log("failover path broken", remoteAddr, error);
3648
+ // The selected pair's next check comes at the weak interval, so a path
3649
+ // that comes back is seen soon.
3650
+ this.consent.recheck();
3651
+ this.onLinkChanged();
3652
+ }
3653
+ /** Failover: application data arrived on `protocol` from `addr`. */
3654
+ failoverDataReceived(protocol, addr) {
3655
+ const sameAddress = (pair) => pair.protocol === protocol &&
3656
+ pair.remoteAddr[0] === addr[0] &&
3657
+ pair.remoteAddr[1] === addr[1];
3658
+ const selected = this.nominated;
3659
+ const pair = selected && sameAddress(selected)
3660
+ ? selected
3661
+ : this.failover.backupPairs.find(sameAddress);
3662
+ if (pair)
3663
+ this.failover.received(pair);
3664
+ }
3665
+ /**
3666
+ * Failover: one check of a backup pair, as libwebrtc pings its
3667
+ * connections: no nomination (USE-CANDIDATE / NOMINATION only when the
3668
+ * selection moves to it), a single transmission with the consent response
3669
+ * timeout. Resolves true when it was answered from the pair's address.
3670
+ */
3671
+ async pingBackup(pair, signal) {
3672
+ const { iceControlling } = this;
3673
+ const request = this.buildRequest({
3674
+ nominate: false,
3675
+ localUsername: pair.localCandidate.ufrag ?? this.localUsername,
3676
+ remoteUsername: this.remoteUsername,
3677
+ iceControlling,
3678
+ localCandidate: pair.localCandidate,
3679
+ });
3680
+ pair.requestsSent++;
3681
+ const startedAt = performance.now();
3682
+ try {
3683
+ const [, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), {
3684
+ retransmissions: 0,
3685
+ responseTimeout: pair.rtt === undefined
3686
+ ? iceBase_1.BACKUP_UNKNOWN_RTT_RESPONSE_TIMEOUT
3687
+ : (0, iceBase_1.consentResponseTimeoutMs)(pair.rtt),
3688
+ signal: AbortSignal.any([this.remoteChecks.signal, signal]),
3689
+ integrityAlgorithm: this.options.messageIntegrity,
3690
+ });
3691
+ if (signal.aborted ||
3692
+ addr[0] !== pair.remoteAddr[0] ||
3693
+ addr[1] !== pair.remoteAddr[1]) {
3694
+ return false;
3695
+ }
3696
+ pair.responsesReceived++;
3697
+ const rtt = (performance.now() - startedAt) / 1000;
3698
+ pair.recordRoundTrip(rtt);
3699
+ return true;
3700
+ }
3701
+ catch (error) {
3702
+ // 487: repair the role conflict as a check does (RFC 8445 §7.2.5.1).
3703
+ if (!signal.aborted &&
3704
+ (0, checkMessages_1.isRoleConflict)(error) &&
3705
+ this.iceControlling === iceControlling) {
3706
+ this.switchRole(!iceControlling);
3707
+ }
3708
+ return false;
3709
+ }
3710
+ }
2416
3711
  /**
2417
3712
  * Pair a local candidate gathered after remote candidates arrived (a late
2418
3713
  * TURN allocation, a slow host socket) with them.
2419
3714
  */
2420
3715
  pairLocalProtocol(protocol) {
2421
3716
  // RFC 8445 §8.1.2: once a pair is selected, the check list takes no more
2422
- // Waiting pairs, so a candidate gathered later starts no check.
2423
- if (this.nominated || this.checkListDone || this.state === "closed") {
3717
+ // Waiting pairs, so a candidate gathered later starts no check. A
3718
+ // selection that may still be replaced (semi-aggressive nomination,
3719
+ // renomination) takes them: a late TURN/UDP allocation may outrank a
3720
+ // TURN/TCP pair selected before it.
3721
+ if (this.state === "closed")
3722
+ return;
3723
+ const replaceable = !!this.nominated && this.iceControlling && this.replacesSelection();
3724
+ if ((this.nominated || this.checkListDone) && !replaceable) {
3725
+ // Failover (a controlled agent): the new socket may keep a backup.
3726
+ const selected = this.nominated;
3727
+ if (!selected || !this.failoverEnabled())
3728
+ return;
3729
+ for (const remoteCandidate of this.remoteCandidates) {
3730
+ this.tryPair(protocol, remoteCandidate, (pair) => this.replacesWith(pair) && pair.protocol !== selected.protocol);
3731
+ }
2424
3732
  return;
2425
3733
  }
2426
3734
  for (const remoteCandidate of this.remoteCandidates) {
2427
3735
  this.tryPair(protocol, remoteCandidate);
2428
3736
  }
2429
3737
  }
2430
- buildRequest({ nominate, remoteUsername, localUsername, iceControlling, localCandidate, }) {
2431
- const txUsername = encodeTxUsername({ remoteUsername, localUsername });
2432
- const request = new message_1.Message(const_1.methods.BINDING, const_1.classes.REQUEST);
2433
- request.setAttribute("USERNAME", txUsername).setAttribute("PRIORITY", (0, candidate_1.candidatePriority)("prflx", {
2434
- transport: localCandidate?.transport,
2435
- tcptype: localCandidate?.tcptype,
2436
- }));
2437
- if (iceControlling) {
2438
- request.setAttribute("ICE-CONTROLLING", this.tieBreaker);
2439
- if (nominate) {
2440
- request.setAttribute("USE-CANDIDATE", null);
2441
- }
2442
- }
2443
- else {
2444
- request.setAttribute("ICE-CONTROLLED", this.tieBreaker);
2445
- }
2446
- return request;
3738
+ /** A connectivity check from this agent (`buildCheckRequest`). */
3739
+ buildRequest(params) {
3740
+ return (0, checkMessages_1.buildCheckRequest)({ ...params, tieBreaker: this.tieBreaker });
2447
3741
  }
2448
3742
  pruneTcpConnections(selectedPair) {
2449
3743
  for (const protocol of this.protocols) {
@@ -2467,7 +3761,7 @@ class Connection {
2467
3761
  const response = new message_1.Message(request.messageMethod, const_1.classes.ERROR, request.transactionId);
2468
3762
  response
2469
3763
  .setAttribute("ERROR-CODE", errorCode)
2470
- .addMessageIntegrity(Buffer.from(localPassword, "utf8"))
3764
+ .addIntegrity(Buffer.from(localPassword, "utf8"), (0, checkMessages_1.responseIntegrityMode)(request))
2471
3765
  .addFingerprint();
2472
3766
  protocol.sendStun(response, addr).catch((e) => {
2473
3767
  log("sendStun error", e);
@@ -2475,14 +3769,6 @@ class Connection {
2475
3769
  }
2476
3770
  }
2477
3771
  exports.Connection = Connection;
2478
- const encodeTxUsername = ({ remoteUsername, localUsername, }) => {
2479
- return `${remoteUsername}:${localUsername}`;
2480
- };
2481
- const decodeTxUsername = (txUsername) => {
2482
- const [remoteUsername, localUsername] = txUsername.split(":");
2483
- return { remoteUsername, localUsername };
2484
- };
2485
- const socketTypeOf = (address) => ((0, net_1.isIPv4)(address) ? "udp4" : "udp6");
2486
- /** Candidates carry no IPv6 zone id (e.g. `fe80::1%eth0`). */
2487
- const stripZoneId = (address) => address.split("%")[0];
3772
+ /** Replaced remote ufrags remembered to recognise their late checks. */
3773
+ const RETIRED_REMOTE_USERNAMES_MAX = 4;
2488
3774
  //# sourceMappingURL=ice.js.map