werift 0.28.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 (492) hide show
  1. package/README.md +182 -2
  2. package/lib/common/src/transport.d.ts +39 -5
  3. package/lib/common/src/transport.js +32 -7
  4. package/lib/common/src/transport.js.map +1 -1
  5. package/lib/dtls/src/carrier/direct.d.ts +67 -0
  6. package/lib/dtls/src/carrier/direct.js +226 -0
  7. package/lib/dtls/src/carrier/direct.js.map +1 -0
  8. package/lib/dtls/src/carrier/types.d.ts +81 -0
  9. package/lib/dtls/src/carrier/types.js +7 -0
  10. package/lib/dtls/src/carrier/types.js.map +1 -0
  11. package/lib/dtls/src/cipher/const.d.ts +6 -0
  12. package/lib/dtls/src/cipher/const.js +13 -2
  13. package/lib/dtls/src/cipher/const.js.map +1 -1
  14. package/lib/dtls/src/cipher/prf.js +11 -2
  15. package/lib/dtls/src/cipher/prf.js.map +1 -1
  16. package/lib/dtls/src/cipher/tls13/aead.d.ts +41 -0
  17. package/lib/dtls/src/cipher/tls13/aead.js +128 -0
  18. package/lib/dtls/src/cipher/tls13/aead.js.map +1 -0
  19. package/lib/dtls/src/cipher/tls13/hkdf.d.ts +30 -0
  20. package/lib/dtls/src/cipher/tls13/hkdf.js +76 -0
  21. package/lib/dtls/src/cipher/tls13/hkdf.js.map +1 -0
  22. package/lib/dtls/src/cipher/tls13/keySchedule.d.ts +70 -0
  23. package/lib/dtls/src/cipher/tls13/keySchedule.js +114 -0
  24. package/lib/dtls/src/cipher/tls13/keySchedule.js.map +1 -0
  25. package/lib/dtls/src/cipher/tls13/signature.d.ts +30 -0
  26. package/lib/dtls/src/cipher/tls13/signature.js +149 -0
  27. package/lib/dtls/src/cipher/tls13/signature.js.map +1 -0
  28. package/lib/dtls/src/client.d.ts +253 -0
  29. package/lib/dtls/src/client.js +1257 -16
  30. package/lib/dtls/src/client.js.map +1 -1
  31. package/lib/dtls/src/context/dtls.d.ts +45 -0
  32. package/lib/dtls/src/context/dtls.js +114 -0
  33. package/lib/dtls/src/context/dtls.js.map +1 -1
  34. package/lib/dtls/src/context/transport.d.ts +13 -0
  35. package/lib/dtls/src/context/transport.js +29 -1
  36. package/lib/dtls/src/context/transport.js.map +1 -1
  37. package/lib/dtls/src/engine/v1_3/connection-base.d.ts +520 -0
  38. package/lib/dtls/src/engine/v1_3/connection-base.js +1644 -0
  39. package/lib/dtls/src/engine/v1_3/connection-base.js.map +1 -0
  40. package/lib/dtls/src/engine/v1_3/connection.d.ts +181 -0
  41. package/lib/dtls/src/engine/v1_3/connection.js +680 -0
  42. package/lib/dtls/src/engine/v1_3/connection.js.map +1 -0
  43. package/lib/dtls/src/engine/v1_3/early-data-buffer.d.ts +38 -0
  44. package/lib/dtls/src/engine/v1_3/early-data-buffer.js +166 -0
  45. package/lib/dtls/src/engine/v1_3/early-data-buffer.js.map +1 -0
  46. package/lib/dtls/src/engine/v1_3/flight/certificate.d.ts +4 -0
  47. package/lib/dtls/src/engine/v1_3/flight/certificate.js +62 -0
  48. package/lib/dtls/src/engine/v1_3/flight/certificate.js.map +1 -0
  49. package/lib/dtls/src/engine/v1_3/flight/client/flight1.d.ts +8 -0
  50. package/lib/dtls/src/engine/v1_3/flight/client/flight1.js +119 -0
  51. package/lib/dtls/src/engine/v1_3/flight/client/flight1.js.map +1 -0
  52. package/lib/dtls/src/engine/v1_3/flight/client/flight4.d.ts +8 -0
  53. package/lib/dtls/src/engine/v1_3/flight/client/flight4.js +251 -0
  54. package/lib/dtls/src/engine/v1_3/flight/client/flight4.js.map +1 -0
  55. package/lib/dtls/src/engine/v1_3/flight/client/flight5.d.ts +5 -0
  56. package/lib/dtls/src/engine/v1_3/flight/client/flight5.js +99 -0
  57. package/lib/dtls/src/engine/v1_3/flight/client/flight5.js.map +1 -0
  58. package/lib/dtls/src/engine/v1_3/flight/dispatch.d.ts +12 -0
  59. package/lib/dtls/src/engine/v1_3/flight/dispatch.js +138 -0
  60. package/lib/dtls/src/engine/v1_3/flight/dispatch.js.map +1 -0
  61. package/lib/dtls/src/engine/v1_3/flight/extensions.d.ts +13 -0
  62. package/lib/dtls/src/engine/v1_3/flight/extensions.js +46 -0
  63. package/lib/dtls/src/engine/v1_3/flight/extensions.js.map +1 -0
  64. package/lib/dtls/src/engine/v1_3/flight/finished.d.ts +6 -0
  65. package/lib/dtls/src/engine/v1_3/flight/finished.js +16 -0
  66. package/lib/dtls/src/engine/v1_3/flight/finished.js.map +1 -0
  67. package/lib/dtls/src/engine/v1_3/flight/post-hs.d.ts +12 -0
  68. package/lib/dtls/src/engine/v1_3/flight/post-hs.js +94 -0
  69. package/lib/dtls/src/engine/v1_3/flight/post-hs.js.map +1 -0
  70. package/lib/dtls/src/engine/v1_3/flight/server/flight2.d.ts +21 -0
  71. package/lib/dtls/src/engine/v1_3/flight/server/flight2.js +227 -0
  72. package/lib/dtls/src/engine/v1_3/flight/server/flight2.js.map +1 -0
  73. package/lib/dtls/src/engine/v1_3/flight/server/flight4.d.ts +6 -0
  74. package/lib/dtls/src/engine/v1_3/flight/server/flight4.js +455 -0
  75. package/lib/dtls/src/engine/v1_3/flight/server/flight4.js.map +1 -0
  76. package/lib/dtls/src/engine/v1_3/flight/server/flight5.d.ts +5 -0
  77. package/lib/dtls/src/engine/v1_3/flight/server/flight5.js +48 -0
  78. package/lib/dtls/src/engine/v1_3/flight/server/flight5.js.map +1 -0
  79. package/lib/dtls/src/engine/v1_3/flight-tx.d.ts +119 -0
  80. package/lib/dtls/src/engine/v1_3/flight-tx.js +782 -0
  81. package/lib/dtls/src/engine/v1_3/flight-tx.js.map +1 -0
  82. package/lib/dtls/src/engine/v1_3/host.d.ts +86 -0
  83. package/lib/dtls/src/engine/v1_3/host.js +11 -0
  84. package/lib/dtls/src/engine/v1_3/host.js.map +1 -0
  85. package/lib/dtls/src/engine/v1_3/record-rx.d.ts +77 -0
  86. package/lib/dtls/src/engine/v1_3/record-rx.js +818 -0
  87. package/lib/dtls/src/engine/v1_3/record-rx.js.map +1 -0
  88. package/lib/dtls/src/engine/v1_3/transcript.d.ts +22 -0
  89. package/lib/dtls/src/engine/v1_3/transcript.js +65 -0
  90. package/lib/dtls/src/engine/v1_3/transcript.js.map +1 -0
  91. package/lib/dtls/src/engine/v1_3/types.d.ts +169 -0
  92. package/lib/dtls/src/engine/v1_3/types.js +113 -0
  93. package/lib/dtls/src/engine/v1_3/types.js.map +1 -0
  94. package/lib/dtls/src/flight/client/flight1.d.ts +7 -1
  95. package/lib/dtls/src/flight/client/flight1.js +9 -3
  96. package/lib/dtls/src/flight/client/flight1.js.map +1 -1
  97. package/lib/dtls/src/flight/client/flight3.d.ts +8 -0
  98. package/lib/dtls/src/flight/client/flight3.js +24 -4
  99. package/lib/dtls/src/flight/client/flight3.js.map +1 -1
  100. package/lib/dtls/src/flight/client/flight5.js +13 -1
  101. package/lib/dtls/src/flight/client/flight5.js.map +1 -1
  102. package/lib/dtls/src/flight/flight.d.ts +16 -0
  103. package/lib/dtls/src/flight/flight.js +109 -8
  104. package/lib/dtls/src/flight/flight.js.map +1 -1
  105. package/lib/dtls/src/flight/server/commitClientHello.d.ts +35 -0
  106. package/lib/dtls/src/flight/server/commitClientHello.js +149 -0
  107. package/lib/dtls/src/flight/server/commitClientHello.js.map +1 -0
  108. package/lib/dtls/src/flight/server/flight2.d.ts +12 -3
  109. package/lib/dtls/src/flight/server/flight2.js +29 -105
  110. package/lib/dtls/src/flight/server/flight2.js.map +1 -1
  111. package/lib/dtls/src/flight/server/flight4.js +14 -2
  112. package/lib/dtls/src/flight/server/flight4.js.map +1 -1
  113. package/lib/dtls/src/flight/server/flight6.js +8 -0
  114. package/lib/dtls/src/flight/server/flight6.js.map +1 -1
  115. package/lib/dtls/src/handshake/const.d.ts +10 -0
  116. package/lib/dtls/src/handshake/const.js +10 -0
  117. package/lib/dtls/src/handshake/const.js.map +1 -1
  118. package/lib/dtls/src/handshake/extensions/cookie.d.ts +113 -0
  119. package/lib/dtls/src/handshake/extensions/cookie.js +326 -0
  120. package/lib/dtls/src/handshake/extensions/cookie.js.map +1 -0
  121. package/lib/dtls/src/handshake/extensions/ids.d.ts +7 -0
  122. package/lib/dtls/src/handshake/extensions/ids.js +11 -0
  123. package/lib/dtls/src/handshake/extensions/ids.js.map +1 -0
  124. package/lib/dtls/src/handshake/extensions/keyShare.d.ts +28 -0
  125. package/lib/dtls/src/handshake/extensions/keyShare.js +156 -0
  126. package/lib/dtls/src/handshake/extensions/keyShare.js.map +1 -0
  127. package/lib/dtls/src/handshake/extensions/signatureAlgorithms.d.ts +27 -0
  128. package/lib/dtls/src/handshake/extensions/signatureAlgorithms.js +67 -0
  129. package/lib/dtls/src/handshake/extensions/signatureAlgorithms.js.map +1 -0
  130. package/lib/dtls/src/handshake/extensions/supportedVersions.d.ts +20 -0
  131. package/lib/dtls/src/handshake/extensions/supportedVersions.js +90 -0
  132. package/lib/dtls/src/handshake/extensions/supportedVersions.js.map +1 -0
  133. package/lib/dtls/src/handshake/extensions/unique.d.ts +7 -0
  134. package/lib/dtls/src/handshake/extensions/unique.js +19 -0
  135. package/lib/dtls/src/handshake/extensions/unique.js.map +1 -0
  136. package/lib/dtls/src/handshake/extensions/useSrtp.d.ts +26 -3
  137. package/lib/dtls/src/handshake/extensions/useSrtp.js +68 -12
  138. package/lib/dtls/src/handshake/extensions/useSrtp.js.map +1 -1
  139. package/lib/dtls/src/handshake/message/tls13/ack.d.ts +50 -0
  140. package/lib/dtls/src/handshake/message/tls13/ack.js +107 -0
  141. package/lib/dtls/src/handshake/message/tls13/ack.js.map +1 -0
  142. package/lib/dtls/src/handshake/message/tls13/certificate.d.ts +17 -0
  143. package/lib/dtls/src/handshake/message/tls13/certificate.js +112 -0
  144. package/lib/dtls/src/handshake/message/tls13/certificate.js.map +1 -0
  145. package/lib/dtls/src/handshake/message/tls13/certificateRequest.d.ts +17 -0
  146. package/lib/dtls/src/handshake/message/tls13/certificateRequest.js +99 -0
  147. package/lib/dtls/src/handshake/message/tls13/certificateRequest.js.map +1 -0
  148. package/lib/dtls/src/handshake/message/tls13/certificateVerify.d.ts +21 -0
  149. package/lib/dtls/src/handshake/message/tls13/certificateVerify.js +77 -0
  150. package/lib/dtls/src/handshake/message/tls13/certificateVerify.js.map +1 -0
  151. package/lib/dtls/src/handshake/message/tls13/encryptedExtensions.d.ts +19 -0
  152. package/lib/dtls/src/handshake/message/tls13/encryptedExtensions.js +56 -0
  153. package/lib/dtls/src/handshake/message/tls13/encryptedExtensions.js.map +1 -0
  154. package/lib/dtls/src/handshake/message/tls13/keyUpdate.d.ts +13 -0
  155. package/lib/dtls/src/handshake/message/tls13/keyUpdate.js +54 -0
  156. package/lib/dtls/src/handshake/message/tls13/keyUpdate.js.map +1 -0
  157. package/lib/dtls/src/handshake/message/tls13/newSessionTicket.d.ts +33 -0
  158. package/lib/dtls/src/handshake/message/tls13/newSessionTicket.js +158 -0
  159. package/lib/dtls/src/handshake/message/tls13/newSessionTicket.js.map +1 -0
  160. package/lib/dtls/src/handshake/random.d.ts +14 -0
  161. package/lib/dtls/src/handshake/random.js +24 -0
  162. package/lib/dtls/src/handshake/random.js.map +1 -1
  163. package/lib/dtls/src/handshake/validation.d.ts +26 -0
  164. package/lib/dtls/src/handshake/validation.js +32 -0
  165. package/lib/dtls/src/handshake/validation.js.map +1 -0
  166. package/lib/dtls/src/index.d.ts +6 -1
  167. package/lib/dtls/src/index.js +116 -44
  168. package/lib/dtls/src/index.js.map +1 -1
  169. package/lib/dtls/src/internal.d.ts +7 -0
  170. package/lib/dtls/src/internal.js +57 -0
  171. package/lib/dtls/src/internal.js.map +1 -0
  172. package/lib/dtls/src/peer.d.ts +49 -0
  173. package/lib/dtls/src/peer.js +54 -0
  174. package/lib/dtls/src/peer.js.map +1 -0
  175. package/lib/dtls/src/record/antiReplayWindow.d.ts +33 -0
  176. package/lib/dtls/src/record/antiReplayWindow.js +119 -0
  177. package/lib/dtls/src/record/antiReplayWindow.js.map +1 -0
  178. package/lib/dtls/src/record/const.d.ts +6 -0
  179. package/lib/dtls/src/record/const.js +6 -0
  180. package/lib/dtls/src/record/const.js.map +1 -1
  181. package/lib/dtls/src/record/message/fragment.d.ts +0 -2
  182. package/lib/dtls/src/record/message/fragment.js +36 -17
  183. package/lib/dtls/src/record/message/fragment.js.map +1 -1
  184. package/lib/dtls/src/record/message/reassembler.d.ts +62 -0
  185. package/lib/dtls/src/record/message/reassembler.js +249 -0
  186. package/lib/dtls/src/record/message/reassembler.js.map +1 -0
  187. package/lib/dtls/src/record/receive.js +24 -16
  188. package/lib/dtls/src/record/receive.js.map +1 -1
  189. package/lib/dtls/src/record/v1_3/header.d.ts +34 -0
  190. package/lib/dtls/src/record/v1_3/header.js +95 -0
  191. package/lib/dtls/src/record/v1_3/header.js.map +1 -0
  192. package/lib/dtls/src/record/v1_3/record.d.ts +133 -0
  193. package/lib/dtls/src/record/v1_3/record.js +370 -0
  194. package/lib/dtls/src/record/v1_3/record.js.map +1 -0
  195. package/lib/dtls/src/retransmission.d.ts +26 -0
  196. package/lib/dtls/src/retransmission.js +39 -0
  197. package/lib/dtls/src/retransmission.js.map +1 -0
  198. package/lib/dtls/src/server.d.ts +38 -0
  199. package/lib/dtls/src/server.js +367 -20
  200. package/lib/dtls/src/server.js.map +1 -1
  201. package/lib/dtls/src/socket.d.ts +379 -35
  202. package/lib/dtls/src/socket.js +1105 -132
  203. package/lib/dtls/src/socket.js.map +1 -1
  204. package/lib/dtls/src/version.d.ts +89 -0
  205. package/lib/dtls/src/version.js +204 -0
  206. package/lib/dtls/src/version.js.map +1 -0
  207. package/lib/ice/src/consent.d.ts +78 -1
  208. package/lib/ice/src/consent.js +236 -24
  209. package/lib/ice/src/consent.js.map +1 -1
  210. package/lib/ice/src/dns/lookup.d.ts +10 -0
  211. package/lib/ice/src/dns/lookup.js +130 -3
  212. package/lib/ice/src/dns/lookup.js.map +1 -1
  213. package/lib/ice/src/exceptions.d.ts +9 -0
  214. package/lib/ice/src/exceptions.js +14 -1
  215. package/lib/ice/src/exceptions.js.map +1 -1
  216. package/lib/ice/src/failover.d.ts +270 -0
  217. package/lib/ice/src/failover.js +674 -0
  218. package/lib/ice/src/failover.js.map +1 -0
  219. package/lib/ice/src/gatheringError.d.ts +28 -0
  220. package/lib/ice/src/gatheringError.js +17 -0
  221. package/lib/ice/src/gatheringError.js.map +1 -0
  222. package/lib/ice/src/ice.d.ts +265 -9
  223. package/lib/ice/src/ice.js +1624 -236
  224. package/lib/ice/src/ice.js.map +1 -1
  225. package/lib/ice/src/iceBase.d.ts +197 -6
  226. package/lib/ice/src/iceBase.js +157 -7
  227. package/lib/ice/src/iceBase.js.map +1 -1
  228. package/lib/ice/src/index.d.ts +2 -0
  229. package/lib/ice/src/index.js +4 -1
  230. package/lib/ice/src/index.js.map +1 -1
  231. package/lib/ice/src/internal/datagram.d.ts +37 -0
  232. package/lib/ice/src/internal/datagram.js +45 -0
  233. package/lib/ice/src/internal/datagram.js.map +1 -0
  234. package/lib/ice/src/internal/hostInterfaces.d.ts +13 -2
  235. package/lib/ice/src/internal/hostInterfaces.js +16 -4
  236. package/lib/ice/src/internal/hostInterfaces.js.map +1 -1
  237. package/lib/ice/src/internal/sped-bind.d.ts +44 -0
  238. package/lib/ice/src/internal/sped-bind.js +53 -0
  239. package/lib/ice/src/internal/sped-bind.js.map +1 -0
  240. package/lib/ice/src/internal/sped-binding-cache.d.ts +27 -0
  241. package/lib/ice/src/internal/sped-binding-cache.js +102 -0
  242. package/lib/ice/src/internal/sped-binding-cache.js.map +1 -0
  243. package/lib/ice/src/internal/sped.d.ts +15 -0
  244. package/lib/ice/src/internal/sped.js +62 -0
  245. package/lib/ice/src/internal/sped.js.map +1 -0
  246. package/lib/ice/src/nomination/selectionController.d.ts +111 -0
  247. package/lib/ice/src/nomination/selectionController.js +172 -0
  248. package/lib/ice/src/nomination/selectionController.js.map +1 -0
  249. package/lib/ice/src/nomination/selectionReplacement.d.ts +40 -0
  250. package/lib/ice/src/nomination/selectionReplacement.js +65 -7
  251. package/lib/ice/src/nomination/selectionReplacement.js.map +1 -1
  252. package/lib/ice/src/sped/draft00/codec.d.ts +20 -0
  253. package/lib/ice/src/sped/draft00/codec.js +59 -0
  254. package/lib/ice/src/sped/draft00/codec.js.map +1 -0
  255. package/lib/ice/src/sped/draft00/constants.d.ts +14 -0
  256. package/lib/ice/src/sped/draft00/constants.js +18 -0
  257. package/lib/ice/src/sped/draft00/constants.js.map +1 -0
  258. package/lib/ice/src/sped/draft00/index.d.ts +6 -0
  259. package/lib/ice/src/sped/draft00/index.js +26 -0
  260. package/lib/ice/src/sped/draft00/index.js.map +1 -0
  261. package/lib/ice/src/sped/draft00/mtu.d.ts +38 -0
  262. package/lib/ice/src/sped/draft00/mtu.js +96 -0
  263. package/lib/ice/src/sped/draft00/mtu.js.map +1 -0
  264. package/lib/ice/src/sped/draft00/session.d.ts +86 -0
  265. package/lib/ice/src/sped/draft00/session.js +353 -0
  266. package/lib/ice/src/sped/draft00/session.js.map +1 -0
  267. package/lib/ice/src/sped/draft00/types.d.ts +16 -0
  268. package/lib/ice/src/sped/draft00/types.js +3 -0
  269. package/lib/ice/src/sped/draft00/types.js.map +1 -0
  270. package/lib/ice/src/sped/runtime.d.ts +188 -0
  271. package/lib/ice/src/sped/runtime.js +643 -0
  272. package/lib/ice/src/sped/runtime.js.map +1 -0
  273. package/lib/ice/src/stun/protocol.d.ts +29 -0
  274. package/lib/ice/src/stun/protocol.js +91 -4
  275. package/lib/ice/src/stun/protocol.js.map +1 -1
  276. package/lib/ice/src/stun/rawAttributeValue.d.ts +1 -0
  277. package/lib/ice/src/stun/rawAttributeValue.js +6 -0
  278. package/lib/ice/src/stun/rawAttributeValue.js.map +1 -0
  279. package/lib/ice/src/stun/tcpProtocol.d.ts +1 -0
  280. package/lib/ice/src/stun/tcpProtocol.js +14 -2
  281. package/lib/ice/src/stun/tcpProtocol.js.map +1 -1
  282. package/lib/ice/src/stun/transaction.d.ts +4 -0
  283. package/lib/ice/src/stun/transaction.js +23 -0
  284. package/lib/ice/src/stun/transaction.js.map +1 -1
  285. package/lib/ice/src/turn/protocol.d.ts +21 -2
  286. package/lib/ice/src/turn/protocol.js +93 -8
  287. package/lib/ice/src/turn/protocol.js.map +1 -1
  288. package/lib/ice/src/types/model.d.ts +9 -0
  289. package/lib/ice/src/types/model.js.map +1 -1
  290. package/lib/ice/src/utils.d.ts +13 -0
  291. package/lib/ice/src/utils.js +13 -0
  292. package/lib/ice/src/utils.js.map +1 -1
  293. package/lib/ice-server/src/stun/message.d.ts +15 -2
  294. package/lib/ice-server/src/stun/message.js +156 -25
  295. package/lib/ice-server/src/stun/message.js.map +1 -1
  296. package/lib/ice-server/src/stun/rawAttributeValue.d.ts +6 -0
  297. package/lib/ice-server/src/stun/rawAttributeValue.js +12 -0
  298. package/lib/ice-server/src/stun/rawAttributeValue.js.map +1 -0
  299. package/lib/index.mjs +19568 -3106
  300. package/lib/nonstandard/index.mjs +2539 -1175
  301. package/lib/polyfill/dom.mjs +33210 -16872
  302. package/lib/polyfill/index.mjs +33345 -17013
  303. package/lib/rtp/src/extra/processor/fsRetry.d.ts +20 -0
  304. package/lib/rtp/src/extra/processor/fsRetry.js +73 -0
  305. package/lib/rtp/src/extra/processor/fsRetry.js.map +1 -0
  306. package/lib/rtp/src/extra/processor/webm.d.ts +6 -0
  307. package/lib/rtp/src/extra/processor/webm.js +6 -2
  308. package/lib/rtp/src/extra/processor/webm.js.map +1 -1
  309. package/lib/rtp/src/extra/processor/webmCallback.d.ts +11 -0
  310. package/lib/rtp/src/extra/processor/webmCallback.js +23 -31
  311. package/lib/rtp/src/extra/processor/webmCallback.js.map +1 -1
  312. package/lib/rtp/src/extra/processor/webmFileWriter.d.ts +24 -0
  313. package/lib/rtp/src/extra/processor/webmFileWriter.js +94 -0
  314. package/lib/rtp/src/extra/processor/webmFileWriter.js.map +1 -0
  315. package/lib/sctp/src/chunk.d.ts +5 -0
  316. package/lib/sctp/src/chunk.js +10 -0
  317. package/lib/sctp/src/chunk.js.map +1 -1
  318. package/lib/sctp/src/index.d.ts +1 -1
  319. package/lib/sctp/src/index.js +4 -1
  320. package/lib/sctp/src/index.js.map +1 -1
  321. package/lib/sctp/src/sctp.d.ts +81 -5
  322. package/lib/sctp/src/sctp.js +273 -28
  323. package/lib/sctp/src/sctp.js.map +1 -1
  324. package/lib/webrtc/src/api/compatibilityOptions.d.ts +11 -1
  325. package/lib/webrtc/src/api/compatibilityOptions.js +11 -1
  326. package/lib/webrtc/src/api/compatibilityOptions.js.map +1 -1
  327. package/lib/webrtc/src/api/peerConfig.d.ts +210 -13
  328. package/lib/webrtc/src/api/peerConfig.js +100 -5
  329. package/lib/webrtc/src/api/peerConfig.js.map +1 -1
  330. package/lib/webrtc/src/api/peerConnectionEvents.d.ts +10 -1
  331. package/lib/webrtc/src/api/peerConnectionEvents.js.map +1 -1
  332. package/lib/webrtc/src/dataChannel.d.ts +122 -10
  333. package/lib/webrtc/src/dataChannel.js +214 -20
  334. package/lib/webrtc/src/dataChannel.js.map +1 -1
  335. package/lib/webrtc/src/media/domEventTarget.d.ts +55 -0
  336. package/lib/webrtc/src/media/domEventTarget.js +216 -0
  337. package/lib/webrtc/src/media/domEventTarget.js.map +1 -0
  338. package/lib/webrtc/src/media/index.d.ts +2 -0
  339. package/lib/webrtc/src/media/index.js +1 -0
  340. package/lib/webrtc/src/media/index.js.map +1 -1
  341. package/lib/webrtc/src/media/parameters.d.ts +5 -0
  342. package/lib/webrtc/src/media/parameters.js +10 -0
  343. package/lib/webrtc/src/media/parameters.js.map +1 -1
  344. package/lib/webrtc/src/media/receiver/receiverTwcc.d.ts +10 -0
  345. package/lib/webrtc/src/media/receiver/receiverTwcc.js +4 -10
  346. package/lib/webrtc/src/media/receiver/receiverTwcc.js.map +1 -1
  347. package/lib/webrtc/src/media/router.d.ts +6 -0
  348. package/lib/webrtc/src/media/router.js +39 -1
  349. package/lib/webrtc/src/media/router.js.map +1 -1
  350. package/lib/webrtc/src/media/rtpReceiver.d.ts +56 -6
  351. package/lib/webrtc/src/media/rtpReceiver.js +165 -15
  352. package/lib/webrtc/src/media/rtpReceiver.js.map +1 -1
  353. package/lib/webrtc/src/media/rtpSender.d.ts +1 -1
  354. package/lib/webrtc/src/media/rtpSender.js +4 -3
  355. package/lib/webrtc/src/media/rtpSender.js.map +1 -1
  356. package/lib/webrtc/src/media/rtpTransceiver.d.ts +29 -11
  357. package/lib/webrtc/src/media/rtpTransceiver.js +31 -9
  358. package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
  359. package/lib/webrtc/src/media/stats.d.ts +13 -0
  360. package/lib/webrtc/src/media/stats.js.map +1 -1
  361. package/lib/webrtc/src/media/track.d.ts +103 -11
  362. package/lib/webrtc/src/media/track.js +241 -19
  363. package/lib/webrtc/src/media/track.js.map +1 -1
  364. package/lib/webrtc/src/media/trackConstraints.d.ts +80 -0
  365. package/lib/webrtc/src/media/trackConstraints.js +141 -0
  366. package/lib/webrtc/src/media/trackConstraints.js.map +1 -0
  367. package/lib/webrtc/src/negotiation/internalState.d.ts +0 -4
  368. package/lib/webrtc/src/negotiation/internalState.js +0 -11
  369. package/lib/webrtc/src/negotiation/internalState.js.map +1 -1
  370. package/lib/webrtc/src/negotiation/remoteCandidates.d.ts +20 -1
  371. package/lib/webrtc/src/negotiation/remoteCandidates.js +29 -1
  372. package/lib/webrtc/src/negotiation/remoteCandidates.js.map +1 -1
  373. package/lib/webrtc/src/negotiation/transportActivation.d.ts +4 -0
  374. package/lib/webrtc/src/negotiation/transportActivation.js +112 -11
  375. package/lib/webrtc/src/negotiation/transportActivation.js.map +1 -1
  376. package/lib/webrtc/src/negotiationTransaction.d.ts +25 -4
  377. package/lib/webrtc/src/negotiationTransaction.js +27 -6
  378. package/lib/webrtc/src/negotiationTransaction.js.map +1 -1
  379. package/lib/webrtc/src/nonstandard/dummyMedia.d.ts +6 -0
  380. package/lib/webrtc/src/nonstandard/dummyMedia.js +14 -19
  381. package/lib/webrtc/src/nonstandard/dummyMedia.js.map +1 -1
  382. package/lib/webrtc/src/nonstandard/navigator.d.ts +1 -1
  383. package/lib/webrtc/src/nonstandard/recorder/index.js +5 -1
  384. package/lib/webrtc/src/nonstandard/recorder/index.js.map +1 -1
  385. package/lib/webrtc/src/nonstandard/recorder/writer/webm.d.ts +6 -1
  386. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js +31 -2
  387. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js.map +1 -1
  388. package/lib/webrtc/src/nonstandard/userMedia/packetizer.d.ts +16 -0
  389. package/lib/webrtc/src/nonstandard/userMedia/packetizer.js +25 -0
  390. package/lib/webrtc/src/nonstandard/userMedia/packetizer.js.map +1 -1
  391. package/lib/webrtc/src/nonstandard/userMedia.js +6 -13
  392. package/lib/webrtc/src/nonstandard/userMedia.js.map +1 -1
  393. package/lib/webrtc/src/peerConnection.d.ts +44 -8
  394. package/lib/webrtc/src/peerConnection.js +88 -9
  395. package/lib/webrtc/src/peerConnection.js.map +1 -1
  396. package/lib/webrtc/src/polyfill/api.d.ts +2 -1
  397. package/lib/webrtc/src/polyfill/api.js +3 -3
  398. package/lib/webrtc/src/polyfill/api.js.map +1 -1
  399. package/lib/webrtc/src/polyfill/dom.d.ts +21 -7
  400. package/lib/webrtc/src/polyfill/dom.js +15 -0
  401. package/lib/webrtc/src/polyfill/dom.js.map +1 -1
  402. package/lib/webrtc/src/polyfill/globals.d.ts +6 -2
  403. package/lib/webrtc/src/polyfill/globals.js.map +1 -1
  404. package/lib/webrtc/src/polyfill/index.d.ts +1 -1
  405. package/lib/webrtc/src/polyfill/index.js +1 -1
  406. package/lib/webrtc/src/polyfill/index.js.map +1 -1
  407. package/lib/webrtc/src/polyfill/install.d.ts +5 -1
  408. package/lib/webrtc/src/polyfill/install.js +2 -2
  409. package/lib/webrtc/src/polyfill/install.js.map +1 -1
  410. package/lib/webrtc/src/polyfill/mediaDevices.js +28 -4
  411. package/lib/webrtc/src/polyfill/mediaDevices.js.map +1 -1
  412. package/lib/webrtc/src/polyfill/peerConnectionConfig.d.ts +6 -0
  413. package/lib/webrtc/src/polyfill/peerConnectionConfig.js +15 -4
  414. package/lib/webrtc/src/polyfill/peerConnectionConfig.js.map +1 -1
  415. package/lib/webrtc/src/polyfill/selectSettings.d.ts +4 -14
  416. package/lib/webrtc/src/polyfill/selectSettings.js +10 -106
  417. package/lib/webrtc/src/polyfill/selectSettings.js.map +1 -1
  418. package/lib/webrtc/src/polyfill/sourceIo.d.ts +1 -2
  419. package/lib/webrtc/src/polyfill/sourceIo.js +6 -6
  420. package/lib/webrtc/src/polyfill/sourceIo.js.map +1 -1
  421. package/lib/webrtc/src/sctpManager.d.ts +31 -18
  422. package/lib/webrtc/src/sctpManager.js +158 -38
  423. package/lib/webrtc/src/sctpManager.js.map +1 -1
  424. package/lib/webrtc/src/sdp.d.ts +38 -2
  425. package/lib/webrtc/src/sdp.js +84 -3
  426. package/lib/webrtc/src/sdp.js.map +1 -1
  427. package/lib/webrtc/src/sdpManager.d.ts +19 -9
  428. package/lib/webrtc/src/sdpManager.js +26 -4
  429. package/lib/webrtc/src/sdpManager.js.map +1 -1
  430. package/lib/webrtc/src/secureTransportManager.d.ts +11 -2
  431. package/lib/webrtc/src/secureTransportManager.js +84 -5
  432. package/lib/webrtc/src/secureTransportManager.js.map +1 -1
  433. package/lib/webrtc/src/transceiverManager.d.ts +5 -2
  434. package/lib/webrtc/src/transceiverManager.js +42 -14
  435. package/lib/webrtc/src/transceiverManager.js.map +1 -1
  436. package/lib/webrtc/src/transport/dtls-application-gate.d.ts +1 -0
  437. package/lib/webrtc/src/transport/dtls-application-gate.js +143 -0
  438. package/lib/webrtc/src/transport/dtls-application-gate.js.map +1 -0
  439. package/lib/webrtc/src/transport/dtls-attempt.d.ts +1 -0
  440. package/lib/webrtc/src/transport/dtls-attempt.js +79 -0
  441. package/lib/webrtc/src/transport/dtls-attempt.js.map +1 -0
  442. package/lib/webrtc/src/transport/dtls-certificate.d.ts +24 -0
  443. package/lib/webrtc/src/transport/dtls-certificate.js +98 -0
  444. package/lib/webrtc/src/transport/dtls-certificate.js.map +1 -0
  445. package/lib/webrtc/src/transport/dtls-fingerprint.d.ts +7 -0
  446. package/lib/webrtc/src/transport/dtls-fingerprint.js +66 -0
  447. package/lib/webrtc/src/transport/dtls-fingerprint.js.map +1 -0
  448. package/lib/webrtc/src/transport/dtls-ice-transport.d.ts +1 -0
  449. package/lib/webrtc/src/transport/dtls-ice-transport.js +123 -0
  450. package/lib/webrtc/src/transport/dtls-ice-transport.js.map +1 -0
  451. package/lib/webrtc/src/transport/dtls-media-queue.d.ts +1 -0
  452. package/lib/webrtc/src/transport/dtls-media-queue.js +95 -0
  453. package/lib/webrtc/src/transport/dtls-media-queue.js.map +1 -0
  454. package/lib/webrtc/src/transport/dtls-readiness.d.ts +1 -0
  455. package/lib/webrtc/src/transport/dtls-readiness.js +173 -0
  456. package/lib/webrtc/src/transport/dtls-readiness.js.map +1 -0
  457. package/lib/webrtc/src/transport/dtls-sped-handshake.d.ts +1 -0
  458. package/lib/webrtc/src/transport/dtls-sped-handshake.js +146 -0
  459. package/lib/webrtc/src/transport/dtls-sped-handshake.js.map +1 -0
  460. package/lib/webrtc/src/transport/dtls-srtp.d.ts +1 -0
  461. package/lib/webrtc/src/transport/dtls-srtp.js +133 -0
  462. package/lib/webrtc/src/transport/dtls-srtp.js.map +1 -0
  463. package/lib/webrtc/src/transport/dtls-stats.d.ts +1 -0
  464. package/lib/webrtc/src/transport/dtls-stats.js +134 -0
  465. package/lib/webrtc/src/transport/dtls-stats.js.map +1 -0
  466. package/lib/webrtc/src/transport/dtls-types.d.ts +23 -0
  467. package/lib/webrtc/src/transport/dtls-types.js +11 -0
  468. package/lib/webrtc/src/transport/dtls-types.js.map +1 -0
  469. package/lib/webrtc/src/transport/dtls.d.ts +150 -55
  470. package/lib/webrtc/src/transport/dtls.js +1017 -556
  471. package/lib/webrtc/src/transport/dtls.js.map +1 -1
  472. package/lib/webrtc/src/transport/ice.d.ts +35 -2
  473. package/lib/webrtc/src/transport/ice.js +147 -14
  474. package/lib/webrtc/src/transport/ice.js.map +1 -1
  475. package/lib/webrtc/src/transport/iceCandidateAttribute.d.ts +4 -2
  476. package/lib/webrtc/src/transport/iceCandidateAttribute.js.map +1 -1
  477. package/lib/webrtc/src/transport/sctp.d.ts +126 -2
  478. package/lib/webrtc/src/transport/sctp.js +747 -134
  479. package/lib/webrtc/src/transport/sctp.js.map +1 -1
  480. package/lib/webrtc/src/transport/sped.d.ts +139 -0
  481. package/lib/webrtc/src/transport/sped.js +757 -0
  482. package/lib/webrtc/src/transport/sped.js.map +1 -0
  483. package/lib/webrtc/src/types/util.d.ts +6 -0
  484. package/lib/webrtc/src/types/util.js.map +1 -1
  485. package/lib/webrtc/src/utils.d.ts +1 -1
  486. package/lib/webrtc/src/webidl.d.ts +15 -0
  487. package/lib/webrtc/src/webidl.js +34 -0
  488. package/lib/webrtc/src/webidl.js.map +1 -0
  489. package/package.json +7 -3
  490. package/lib/webrtc/src/polyfill/rtcSessionDescription.d.ts +0 -18
  491. package/lib/webrtc/src/polyfill/rtcSessionDescription.js +0 -36
  492. package/lib/webrtc/src/polyfill/rtcSessionDescription.js.map +0 -1
@@ -41,22 +41,40 @@ const candidateGatherer_1 = require("./candidateGatherer");
41
41
  const consent_1 = require("./consent");
42
42
  const lookup_1 = require("./dns/lookup");
43
43
  const exceptions_1 = require("./exceptions");
44
+ const failover_1 = require("./failover");
45
+ const gatheringError_1 = require("./gatheringError");
44
46
  const helper_1 = require("./helper");
45
47
  const iceBase_1 = require("./iceBase");
46
48
  const common_1 = require("./imports/common");
47
49
  const checkMessages_1 = require("./internal/checkMessages");
50
+ const datagram_1 = require("./internal/datagram");
48
51
  const defaultRoute_1 = require("./internal/defaultRoute");
49
52
  const hostInterfaces_1 = require("./internal/hostInterfaces");
50
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");
51
56
  const regularNomination_1 = require("./nomination/regularNomination");
57
+ const selectionController_1 = require("./nomination/selectionController");
52
58
  const selectionReplacement_1 = require("./nomination/selectionReplacement");
53
59
  const provisional_1 = require("./provisional");
60
+ const runtime_1 = require("./sped/runtime");
54
61
  const const_1 = require("./stun/const");
55
62
  const message_1 = require("./stun/message");
56
63
  const protocol_1 = require("./stun/protocol");
57
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
+ }
58
74
  /** Fallback STUN server when none is configured (constructor / setIceServers). */
59
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);
60
78
  /**
61
79
  * The URL `onIceCandidateError` names the built-in default STUN server by:
62
80
  * it is in no configuration, so werift synthesizes one.
@@ -64,9 +82,9 @@ const DEFAULT_STUN_SERVER = ["stun.l.google.com", 19302];
64
82
  exports.DEFAULT_STUN_SERVER_URL = "stun:stun.l.google.com:19302";
65
83
  // The ICE agent. This file keeps the public API, the lifecycle (restart,
66
84
  // close, state), the protocol event wiring and the live checklist
67
- // (connect / checkStart / checkComplete / checkIncoming). Its parts live in
85
+ // (connect / checkStart / checkComplete / checkIncoming) and candidate
86
+ // gathering (gatherCandidates / getCandidatePromises). Its other parts live in
68
87
  // collaborators the agent supplies through a host object:
69
- // - candidateGatherer.ts: host / server-reflexive / relay gathering
70
88
  // - consent.ts: RFC 7675 consent freshness of the selected pair
71
89
  // - provisional.ts: the checklist of an ICE restart negotiated with a pranswer
72
90
  // - nomination/regularNomination.ts: RFC 8445 regular nomination
@@ -78,6 +96,13 @@ class Connection {
78
96
  get provisional() {
79
97
  return this.provisionalChecklist.generation;
80
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
+ }
81
106
  constructor(_iceControlling, options) {
82
107
  Object.defineProperty(this, "_iceControlling", {
83
108
  enumerable: true,
@@ -85,6 +110,20 @@ class Connection {
85
110
  writable: true,
86
111
  value: void 0
87
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
+ });
88
127
  Object.defineProperty(this, "localUsername", {
89
128
  enumerable: true,
90
129
  configurable: true,
@@ -128,6 +167,17 @@ class Connection {
128
167
  writable: true,
129
168
  value: ""
130
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
+ });
131
181
  Object.defineProperty(this, "checkList", {
132
182
  enumerable: true,
133
183
  configurable: true,
@@ -219,6 +269,17 @@ class Connection {
219
269
  writable: true,
220
270
  value: false
221
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
+ });
222
283
  Object.defineProperty(this, "generation", {
223
284
  enumerable: true,
224
285
  configurable: true,
@@ -294,6 +355,26 @@ class Connection {
294
355
  writable: true,
295
356
  value: void 0
296
357
  });
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
+ });
297
378
  /** The ICE-lite nomination (first valid pair, in `checkStart`) is in flight. */
298
379
  Object.defineProperty(this, "liteNominating", {
299
380
  enumerable: true,
@@ -333,6 +414,16 @@ class Connection {
333
414
  sendNomination: (pair, signal, value) => this.sendNomination(pair, signal, value),
334
415
  isStaleNomination: (pair, generation) => this.isStaleNomination(pair, generation),
335
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(),
336
427
  })
337
428
  });
338
429
  /** See `NominationHint`; set by the restart that ends a provisional checklist. */
@@ -391,19 +482,6 @@ class Connection {
391
482
  writable: true,
392
483
  value: false
393
484
  });
394
- /** Resolves when the agent closes: work that awaits the network stops waiting. */
395
- Object.defineProperty(this, "closedSignal", {
396
- enumerable: true,
397
- configurable: true,
398
- writable: true,
399
- value: void 0
400
- });
401
- Object.defineProperty(this, "signalClosed", {
402
- enumerable: true,
403
- configurable: true,
404
- writable: true,
405
- value: void 0
406
- });
407
485
  /** Aborted by close(): a TURN allocation still running is released. */
408
486
  Object.defineProperty(this, "closing", {
409
487
  enumerable: true,
@@ -412,11 +490,9 @@ class Connection {
412
490
  value: new AbortController()
413
491
  });
414
492
  /**
415
- * Results for connect(). Known constraint (as in develop): a restart
416
- * replaces the queue, so a connect() still waiting on the old one never
417
- * settles (the agent is still collected). It cannot simply return, since
418
- * the caller (webrtc's `TransactionActivation`) treats a returned start as
419
- * 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).
420
496
  */
421
497
  Object.defineProperty(this, "checkListState", {
422
498
  enumerable: true,
@@ -469,8 +545,122 @@ class Connection {
469
545
  iceControlling: this.iceControlling,
470
546
  localCandidate: pair.localCandidate,
471
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())
593
+ });
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", {
606
+ enumerable: true,
607
+ configurable: true,
608
+ writable: true,
609
+ value: void 0
610
+ });
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", {
616
+ enumerable: true,
617
+ configurable: true,
618
+ writable: true,
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
+ },
472
637
  })
473
638
  });
639
+ /** See `failoverThresholds`. */
640
+ Object.defineProperty(this, "failoverThresholdsCache", {
641
+ enumerable: true,
642
+ configurable: true,
643
+ writable: true,
644
+ value: void 0
645
+ });
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", {
652
+ enumerable: true,
653
+ configurable: true,
654
+ writable: true,
655
+ value: void 0
656
+ });
657
+ /** The state `disconnected` replaced, restored when the selection works again. */
658
+ Object.defineProperty(this, "stateBeforeDisconnect", {
659
+ enumerable: true,
660
+ configurable: true,
661
+ writable: true,
662
+ value: void 0
663
+ });
474
664
  /** Host, server-reflexive and relay gathering (`CandidateGatherer`). */
475
665
  Object.defineProperty(this, "gatherer", {
476
666
  enumerable: true,
@@ -578,6 +768,26 @@ class Connection {
578
768
  writable: true,
579
769
  value: new common_1.Event()
580
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
+ });
581
791
  /**
582
792
  * A STUN or TURN server of the current generation's gathering answered:
583
793
  * a STUN query or TURN allocation gave a candidate, or the server sent an
@@ -590,6 +800,16 @@ class Connection {
590
800
  writable: true,
591
801
  value: new common_1.Event()
592
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()
812
+ });
593
813
  Object.defineProperty(this, "send", {
594
814
  enumerable: true,
595
815
  configurable: true,
@@ -599,7 +819,10 @@ class Connection {
599
819
  if (!this.canSendApplicationData()) {
600
820
  return;
601
821
  }
602
- const activePair = this.nominated;
822
+ const activePair = this.applicationDataPair();
823
+ if (!activePair) {
824
+ return;
825
+ }
603
826
  await activePair.protocol.sendData(data, activePair.remoteAddr);
604
827
  // Update statistics
605
828
  activePair.packetsSent++;
@@ -624,16 +847,23 @@ class Connection {
624
847
  const signal = AbortSignal.any([checks.signal, this.remoteChecks.signal]);
625
848
  const remoteGeneration = this.remoteGeneration;
626
849
  pair.updateState(iceBase_1.CandidatePairState.IN_PROGRESS);
627
- const result = {};
628
850
  const { remotePassword, remoteUsername, generation } = this;
629
851
  const localUsername = pair.localCandidate.ufrag ?? this.localUsername;
852
+ const stopIfStale = () => {
853
+ if (!this.isStaleConnectivityCheck(pair, generation)) {
854
+ return false;
855
+ }
856
+ r();
857
+ return true;
858
+ };
630
859
  // Semi-aggressive nomination: USE-CANDIDATE while nothing is selected
631
860
  // and for a pair that outranks the selected one. Regular nomination
632
861
  // (RegularNomination) and renomination (`SelectionReplacement.evaluate`) nominate
633
862
  // with a separate check; an ordinary check carries nothing.
634
863
  const nominate = this.usesSemiAggressiveNomination() &&
635
864
  this.replacesWith(pair) &&
636
- (!this.nominated || this.outranks(pair, this.nominated));
865
+ (!this.nominated ||
866
+ (this.outranks(pair, this.nominated) && this.failoverAllows(pair)));
637
867
  const request = this.buildRequest({
638
868
  nominate,
639
869
  localUsername,
@@ -641,19 +871,35 @@ class Connection {
641
871
  iceControlling: this.iceControlling,
642
872
  localCandidate: pair.localCandidate,
643
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
+ }
644
883
  // Record start time for RTT calculation
645
884
  const startTime = performance.now();
646
885
  try {
647
886
  pair.requestsSent++;
648
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
+ }
649
897
  pair.responsesReceived++;
898
+ this.failover.responded(pair);
650
899
  // Calculate RTT
651
900
  const endTime = performance.now();
652
- const rtt = (endTime - startTime) / 1000; // Convert to seconds
653
- // Update RTT statistics
654
- pair.rtt = rtt;
655
- pair.totalRoundTripTime += rtt;
656
- pair.roundTripTimeMeasurements++;
901
+ const rtt = (endTime - startTime) / 1000;
902
+ pair.recordRoundTrip(rtt);
657
903
  log("response received", request.toJSON(), response.toJSON(), addr, {
658
904
  localUsername,
659
905
  remoteUsername,
@@ -661,8 +907,11 @@ class Connection {
661
907
  generation,
662
908
  rtt,
663
909
  });
664
- result.response = response;
665
- 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
+ }
666
915
  }
667
916
  catch (error) {
668
917
  // A cancelled check (its handle resolved, or the agent closed and
@@ -672,6 +921,9 @@ class Connection {
672
921
  r();
673
922
  return;
674
923
  }
924
+ if (stopIfStale()) {
925
+ return;
926
+ }
675
927
  const exc = error;
676
928
  // 7.1.3.1. Failure Cases
677
929
  log("failure case", request.toJSON(), exc.response ? JSON.stringify(exc.response.toJSON(), null, 2) : error, {
@@ -706,12 +958,7 @@ class Connection {
706
958
  return;
707
959
  }
708
960
  }
709
- // # check remote address matches
710
- if (result.addr[0] !== pair.remoteAddr[0] ||
711
- result.addr[1] !== pair.remoteAddr[1]) {
712
- pair.updateState(iceBase_1.CandidatePairState.FAILED);
713
- this.checkComplete(pair);
714
- r();
961
+ if (stopIfStale()) {
715
962
  return;
716
963
  }
717
964
  // # success
@@ -735,10 +982,33 @@ class Connection {
735
982
  iceControlling: this.iceControlling,
736
983
  localCandidate: pair.localCandidate,
737
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
+ }
738
994
  try {
739
995
  pair.requestsSent++;
740
- 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
+ }
741
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
+ }
742
1012
  }
743
1013
  catch (error) {
744
1014
  // A nomination of a generation that ended (or a cancelled check)
@@ -750,6 +1020,9 @@ class Connection {
750
1020
  return;
751
1021
  }
752
1022
  this.liteNominating = false;
1023
+ if (stopIfStale()) {
1024
+ return;
1025
+ }
753
1026
  pair.updateState(iceBase_1.CandidatePairState.FAILED);
754
1027
  this.checkComplete(pair);
755
1028
  r();
@@ -759,6 +1032,9 @@ class Connection {
759
1032
  r();
760
1033
  return;
761
1034
  }
1035
+ if (stopIfStale()) {
1036
+ return;
1037
+ }
762
1038
  pair.nominated = true;
763
1039
  }
764
1040
  else if (nominate &&
@@ -783,9 +1059,6 @@ class Connection {
783
1059
  }
784
1060
  });
785
1061
  this._iceControlling = _iceControlling;
786
- this.closedSignal = new Promise((resolve) => {
787
- this.signalClosed = resolve;
788
- });
789
1062
  this.options = {
790
1063
  ...iceBase_1.defaultOptions,
791
1064
  ...options,
@@ -860,10 +1133,9 @@ class Connection {
860
1133
  if (this.iceLite) {
861
1134
  value = false;
862
1135
  }
863
- // While a pair is selected, keep the negotiated role. ICE restart clears
864
- // `nominated`, so offer/answer role and RFC 8445 role-conflict repair can
865
- // reassign controlling/controlled for the new generation.
866
- 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) {
867
1139
  return;
868
1140
  }
869
1141
  this.applyIceControlling(value);
@@ -871,8 +1143,22 @@ class Connection {
871
1143
  get iceLite() {
872
1144
  return this.options.iceLite;
873
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
+ }
874
1158
  async restart() {
1159
+ this.retainSelectedPairs();
875
1160
  this.generation++;
1161
+ this.abandonInFlightStunTransactions();
876
1162
  this.remoteGeneration++;
877
1163
  const previous = this.restarted
878
1164
  ? { [this.localUsername]: this.localPassword }
@@ -893,6 +1179,7 @@ class Connection {
893
1179
  [this.localUsername]: this.localPassword,
894
1180
  };
895
1181
  this.restarted = true;
1182
+ this.retireRemoteUsername();
896
1183
  this.remoteUsername = "";
897
1184
  this.remotePassword = "";
898
1185
  this.localCandidates = [];
@@ -931,15 +1218,103 @@ class Connection {
931
1218
  }
932
1219
  // Tear down consent timers/transactions; new credentials require a new session.
933
1220
  this.consent.stop();
1221
+ this.spedBindingCache.clear();
1222
+ this.spedRuntime?.reset(this.generation);
934
1223
  this.provisionalChecklist.end();
935
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);
1308
+ }
936
1309
  /**
937
1310
  * Only the remote side restarted (new remote credentials in an answer to an
938
1311
  * offer that kept the local ones): the remote generation, its checks and
939
1312
  * the selected pair start over; local credentials and candidates stay.
940
1313
  */
941
1314
  restartRemote() {
1315
+ this.retainSelectedPairs();
942
1316
  this.remoteGeneration++;
1317
+ this.retireRemoteUsername();
943
1318
  this.remoteUsername = "";
944
1319
  this.remotePassword = "";
945
1320
  this._remoteCandidates = [];
@@ -972,6 +1347,9 @@ class Connection {
972
1347
  for (const pair of this.checkList)
973
1348
  pair.handle?.resolve?.();
974
1349
  this.selection.clearRetries();
1350
+ this.failover.reset();
1351
+ this.switching.stop();
1352
+ this.clearConsentExpiredGrace();
975
1353
  }
976
1354
  /** Accept provisional checks without changing the selected current pair. */
977
1355
  stageLocalCredentials(usernameFragment, password, gatherOptions) {
@@ -1037,6 +1415,9 @@ class Connection {
1037
1415
  this.nomination.reset();
1038
1416
  this.selection.abort();
1039
1417
  this.nominationHint = undefined;
1418
+ this.failover.reset();
1419
+ this.switching.stop();
1420
+ this.clearConsentExpiredGrace();
1040
1421
  // Drop old pair's consent timers/transactions; restarted when a new pair is nominated.
1041
1422
  this.consent.stop();
1042
1423
  }
@@ -1051,8 +1432,29 @@ class Connection {
1051
1432
  setRemoteParams({ iceLite, usernameFragment, password, }) {
1052
1433
  log("setRemoteParams", { iceLite, usernameFragment, password });
1053
1434
  this.remoteIsLite = iceLite;
1435
+ if (usernameFragment !== this.remoteUsername)
1436
+ this.retireRemoteUsername();
1437
+ this.retiredRemoteUsernames = this.retiredRemoteUsernames.filter((retired) => retired !== usernameFragment);
1054
1438
  this.remoteUsername = usernameFragment;
1055
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));
1056
1458
  }
1057
1459
  // 4.1.1 Gathering Candidates
1058
1460
  /**
@@ -1065,101 +1467,169 @@ class Connection {
1065
1467
  * allocation), so a caller may let it finish in the background.
1066
1468
  */
1067
1469
  async gatherCandidates() {
1470
+ const generation = this.generation;
1068
1471
  if (!this.localCandidatesStart) {
1069
1472
  this.localCandidatesStart = true;
1070
- const generation = this.generation;
1071
- // An ICE restart allocates TURN afresh, which is how a restart recovers
1072
- // from an allocation that died: the previous one leaves the generation.
1073
- const previousTurn = this.protocols.filter((protocol) => protocol.localCandidate?.type === "relay");
1074
- // The generation keeps only the sockets a fresh gathering with the
1075
- // current options would open: a relay-only policy or useTcp turned off
1076
- // since the previous generation closes the kept host (UDP / TCP)
1077
- // sockets, so they are neither advertised, paired nor reachable.
1078
- const excluded = this.protocols.filter((protocol) => !previousTurn.includes(protocol) &&
1079
- !!protocol.localCandidate &&
1080
- !(0, iceBase_1.isCandidateAllowedByGatherOptions)(protocol.localCandidate, this.options));
1081
- this.protocols = this.protocols.filter((protocol) => !previousTurn.includes(protocol) && !excluded.includes(protocol));
1082
- void Promise.allSettled([...previousTurn, ...excluded].map((protocol) => protocol.close()));
1083
- // ICE restart keeps transport protocols; re-advertise their host candidates
1084
- // with the new generation / ufrag before gathering additional addresses.
1085
- for (const [family, wildcard] of this.gatherer.wildcardProtocols) {
1086
- if (!this.protocols.includes(wildcard)) {
1087
- // Closed with the excluded sockets, or still opening for the
1088
- // replaced generation: a fresh one is opened if needed.
1089
- this.gatherer.wildcardProtocols.delete(family);
1090
- }
1473
+ try {
1474
+ await this.gatherGeneration(generation);
1091
1475
  }
1092
- for (const protocol of this.protocols) {
1093
- if (protocol.localCandidate) {
1094
- protocol.localCandidate.generation = this.generation;
1095
- protocol.localCandidate.ufrag = this.localUsername;
1096
- // A wildcard socket's local candidate is one of its
1097
- // server-reflexive candidates, re-advertised below.
1098
- if (!this.gatherer.isWildcardProtocol(protocol)) {
1099
- this.appendLocalCandidate(protocol.localCandidate);
1100
- }
1101
- for (const reflexive of this.gatherer.reflexiveBySocket.get(protocol) ?? []) {
1102
- this.appendLocalCandidate(this.withGeneration(reflexive));
1103
- }
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);
1104
1482
  }
1105
- }
1106
- // A family bound to an explicit interface address gathers only that
1107
- // address, so the advertised host candidate is the socket's address.
1108
- const address = (0, resolveHostAddresses_1.resolveHostAddresses)({
1109
- enumerated: (0, hostInterfaces_1.getHostInterfaceAddresses)(this.options.useIpv4, this.options.useIpv6, {
1110
- useLinkLocalAddress: this.options.useLinkLocalAddress,
1111
- }),
1112
- assigned: (0, hostInterfaces_1.getAssignedInterfaceAddresses)(),
1113
- interfaceAddresses: this.options.interfaceAddresses,
1114
- additionalHostAddresses: this.options.additionalHostAddresses,
1115
- useIpv4: this.options.useIpv4,
1116
- useIpv6: this.options.useIpv6,
1117
- log,
1118
- });
1119
- // The default-route address of each family: the source address of the
1120
- // route to the configured STUN / TURN servers (none without one: no
1121
- // other address is probed). Its host candidate gets the highest local preference, and its
1122
- // socket is a representative of the family's server-reflexive queries.
1123
- // Probed while the sockets bind: no server work waits for it.
1124
- const defaultRoutes = Promise.race([
1125
- (0, defaultRoute_1.getDefaultRouteAddresses)(this.options.useIpv4, this.options.useIpv6, [
1126
- ...this.stunServers.map(([host]) => host),
1127
- ...this.turnServers.map(({ address: [host] }) => host),
1128
- ]),
1129
- this.closedSignal.then(() => []),
1130
- ]);
1131
- const { primary, background } = this.gatherer.candidatePromises(address, this.options.stunGatherTimeout, generation, defaultRoutes);
1132
- // close() ends the gathering at once: the continuations above close
1133
- // whatever a server query still opens for a closed agent.
1134
- await Promise.race([Promise.allSettled(primary), this.closedSignal]);
1135
- // A later ICE restart (or close) owns the agent now: this gathering
1136
- // neither completes that generation nor touches its state.
1137
- if (!this.isGathering(generation))
1138
- return;
1139
- const pending = background.filter(({ settled }) => !settled);
1140
- if (pending.length === 0) {
1141
- this.localCandidatesEnd = true;
1142
- }
1143
- else {
1144
- // The other host sockets' server-reflexive candidates trickle in;
1145
- // end-of-candidates follows the last of them.
1146
- this.localCandidatesEndPromise = Promise.race([
1147
- Promise.allSettled(pending.map(({ query }) => query)),
1148
- this.closedSignal,
1149
- ]).then(() => {
1150
- if (!this.isGathering(generation))
1151
- return;
1152
- this.localCandidatesEnd = true;
1153
- if (this.checksBegun)
1154
- this.concludeCheckListIfExhausted();
1155
- });
1483
+ throw error;
1156
1484
  }
1157
1485
  }
1158
1486
  // Gathering that finishes after connectivity checks began (an ICE restart
1159
1487
  // keeps gathering from its servers) must not overwrite their state: the
1160
1488
  // agent stays "new" while checking, and only the checks' outcome moves it.
1161
- if (this.state === "new" && !this.checksBegun)
1489
+ if (this.generation === generation &&
1490
+ this.state === "new" &&
1491
+ !this.checksBegun) {
1162
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
+ });
1163
1633
  }
1164
1634
  /**
1165
1635
  * Resolves when the current generation's gathering has ended
@@ -1232,99 +1702,337 @@ class Connection {
1232
1702
  }
1233
1703
  ensureProtocol(protocol) {
1234
1704
  protocol.onRequestReceived.subscribe((msg, addr, data) => {
1235
- if (msg.messageMethod !== const_1.methods.BINDING) {
1236
- this.respondError(msg, addr, protocol, [400, "Bad Request"]);
1237
- return;
1238
- }
1239
- // The MESSAGE-INTEGRITY / MESSAGE-INTEGRITY-SHA256 of an incoming check
1240
- // is not verified here (parseMessage(data, localPassword) would do it):
1241
- // rejecting unverifiable checks with 401 (RFC 8445 §7.3, RFC 8489
1242
- // §9.1.3) changes established behavior and is tracked separately.
1243
- const txUsername = msg.getAttributeValue("USERNAME");
1244
- // 相手にとってのremoteは自分にとってのlocal
1245
- const { remoteUsername: localUsername } = (0, checkMessages_1.decodeTxUsername)(txUsername);
1246
- const localPassword = this.userHistory[localUsername] ?? this.localPassword;
1247
- // A check for the staged generation on a socket it drops at the commit
1248
- // (a host socket under a relay-only policy, a TURN allocation whose
1249
- // server was removed or replaced) is not answered: the socket is not
1250
- // part of that generation.
1251
- const staged = this.provisional;
1252
- if (staged &&
1253
- localUsername === staged.localUsername &&
1254
- localUsername !== this.localUsername &&
1255
- !this.provisionalChecklist.allows(staged, protocol)) {
1256
- return;
1257
- }
1258
- const { iceControlling } = this;
1259
- // 7.2.1.1. Detecting and Repairing Role Conflicts
1260
- if (iceControlling && msg.attributesKeys.includes("ICE-CONTROLLING")) {
1261
- if (this.tieBreaker >= msg.getAttributeValue("ICE-CONTROLLING")) {
1262
- this.respondError(msg, addr, protocol, [487, "Role Conflict"], localPassword);
1263
- 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
+ });
1264
1742
  }
1265
- else {
1266
- 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;
1267
1748
  }
1268
- }
1269
- else if (!iceControlling &&
1270
- msg.attributesKeys.includes("ICE-CONTROLLED")) {
1271
- if (this.iceLite ||
1272
- this.tieBreaker < msg.getAttributeValue("ICE-CONTROLLED")) {
1273
- this.respondError(msg, addr, protocol, [487, "Role Conflict"], localPassword);
1274
- return;
1749
+ if (addr && this.failoverEnabled()) {
1750
+ this.failoverDataReceived(protocol, addr);
1275
1751
  }
1276
- else {
1277
- this.switchRole(true);
1278
- return;
1752
+ if (!this.iceControlling && addr) {
1753
+ this.selection.controlledDataReceived(protocol, addr);
1279
1754
  }
1755
+ this.onData.execute(data);
1280
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).
1281
1813
  if (this.options.filterStunResponse &&
1282
- !this.options.filterStunResponse(msg, addr, protocol)) {
1814
+ !this.options.filterStunResponse(verified, addr, protocol)) {
1283
1815
  return;
1284
1816
  }
1285
- // # send binding response
1286
- 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);
1287
1818
  response
1288
1819
  .setAttribute("XOR-MAPPED-ADDRESS", addr)
1289
- .addIntegrity(Buffer.from(localPassword, "utf8"), (0, checkMessages_1.responseIntegrityMode)(msg))
1820
+ .addIntegrity(Buffer.from(localPassword, "utf8"), this.spedRuntime?.session.embedding
1821
+ ? "sha1"
1822
+ : (0, checkMessages_1.responseIntegrityMode)(verified))
1290
1823
  .addFingerprint();
1291
1824
  protocol.sendStun(response, addr).catch((e) => {
1292
1825
  log("sendStun error", e);
1293
1826
  });
1294
- const provisional = this.provisional;
1295
- if (provisional &&
1296
- localUsername === provisional.localUsername &&
1297
- localUsername !== this.localUsername) {
1298
- this.provisionalChecklist.checkIncoming(provisional, msg, addr, protocol);
1299
- return;
1827
+ if (provisional && isProvisional) {
1828
+ this.provisionalChecklist.checkIncoming(provisional, verified, addr, protocol);
1300
1829
  }
1301
- if (this.checkList.length === 0 && !this.earlyChecksDone) {
1302
- this.earlyChecks.push([msg, addr, protocol]);
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;
1303
1858
  }
1304
1859
  else {
1305
- this.checkIncoming(msg, addr, protocol);
1860
+ this.switchRole(false);
1306
1861
  }
1307
- });
1308
- protocol.onDataReceived.subscribe((data, addr) => {
1309
- try {
1310
- // Update statistics for the nominated pair
1311
- const activePair = this.nominated;
1312
- if (activePair && activePair.protocol === protocol) {
1313
- activePair.packetsReceived++;
1314
- activePair.bytesReceived += data.length;
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);
1890
+ response
1891
+ .setAttribute("XOR-MAPPED-ADDRESS", addr)
1892
+ .addMessageIntegrity(Buffer.from(localPassword, "utf8"))
1893
+ .addFingerprint();
1894
+ protocol.sendStun(response, addr).catch((e) => {
1895
+ log("sendStun error", e);
1896
+ });
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);
1917
+ }
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]);
1929
+ }
1930
+ else {
1931
+ this.checkIncoming(verified, addr, protocol);
1932
+ }
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);
1315
1951
  }
1316
- if (!this.iceControlling && addr) {
1317
- this.selection.controlledDataReceived(protocol, addr);
1952
+ return;
1953
+ }
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;
1318
1972
  }
1319
- this.onData.execute(data);
1320
1973
  }
1321
- catch (error) {
1322
- log("dataReceived", error);
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
+ }
1323
1983
  }
1324
- });
1325
- protocol.onConnectionClosed?.subscribe((remoteAddr) => {
1326
- this.handleConnectionClosed(protocol, remoteAddr);
1327
- });
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();
1328
2036
  }
1329
2037
  /**
1330
2038
  * RFC 6544: the selected TCP connection is the only path for this component;
@@ -1363,6 +2071,14 @@ class Connection {
1363
2071
  throw new Error("Remote username or password is missing");
1364
2072
  }
1365
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);
1366
2082
  // # 5.7.1. Forming Candidate Pairs
1367
2083
  for (const c of this.remoteCandidates) {
1368
2084
  this.pairRemoteCandidate(c);
@@ -1375,22 +2091,43 @@ class Connection {
1375
2091
  // # handle early checks
1376
2092
  for (const earlyCheck of this.earlyChecks) {
1377
2093
  this.checkIncoming(...earlyCheck);
2094
+ const [, addr, protocol] = earlyCheck;
2095
+ this.settleSpedUnconfirmed(this.findPairByAddr(protocol, addr));
2096
+ await this.maybeSendSpedFallback(protocol, addr, this.generation);
1378
2097
  }
1379
2098
  this.earlyChecks = [];
1380
2099
  this.earlyChecksDone = true;
1381
2100
  // Arms the wait for a preferred pair even while the checklist is empty.
1382
2101
  this.nomination.evaluate();
1383
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();
1384
2116
  if (!this.nominated) {
1385
2117
  let res = iceBase_1.ICE_FAILED;
1386
- while (!this.checkListDone && this.state !== "closed") {
1387
- 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();
1388
2122
  log("checkListState", res);
1389
2123
  if (res === iceBase_1.ICE_COMPLETED) {
1390
2124
  break;
1391
2125
  }
1392
2126
  }
1393
2127
  if (res !== iceBase_1.ICE_COMPLETED && !this.nominated) {
2128
+ if (this.state !== "closed") {
2129
+ this.setState("failed");
2130
+ }
1394
2131
  throw new Error("ICE negotiation failed");
1395
2132
  }
1396
2133
  }
@@ -1399,17 +2136,31 @@ class Connection {
1399
2136
  }
1400
2137
  // # perform checks
1401
2138
  // 5.8. Scheduling Checks
1402
- for (;;) {
1403
- if (this.state === "closed")
1404
- break;
1405
- // A selection that may still be replaced: the checks of the pairs that
1406
- // outrank it go on in `SelectionReplacement.checkOutrankingPairs`.
1407
- if (this.nominated && this.iceControlling && this.replacesSelection()) {
1408
- break;
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);
1409
2155
  }
1410
- if (!this.schedulingChecks())
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)
1411
2163
  break;
1412
- await timers.setTimeout(20);
1413
2164
  }
1414
2165
  this.schedulingStopped = true;
1415
2166
  // # wait for completion
@@ -1418,7 +2169,11 @@ class Connection {
1418
2169
  // (`NominationHint`), even with an empty checklist.
1419
2170
  while ((this.checkList.length > 0 || this.nomination.waiting) &&
1420
2171
  res === iceBase_1.ICE_FAILED) {
1421
- res = await this.checkListState.get();
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();
1422
2177
  log("checkListState", res);
1423
2178
  }
1424
2179
  // # cancel remaining checks
@@ -1433,13 +2188,95 @@ class Connection {
1433
2188
  }
1434
2189
  check.handle?.resolve?.();
1435
2190
  }
1436
- 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
+ }
1437
2195
  throw new Error("ICE negotiation failed");
1438
2196
  }
1439
2197
  // # start consent freshness tests
1440
- this.consent.start();
2198
+ this.queryConsent();
1441
2199
  this.setState("connected");
1442
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
+ }
1443
2280
  unfreezeInitial() {
1444
2281
  // # unfreeze first pair for the first component
1445
2282
  const [firstPair] = this.checkList;
@@ -1519,8 +2356,15 @@ class Connection {
1519
2356
  pair.nomination = this.selection.nextNominationValue();
1520
2357
  return pair.nomination;
1521
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
+ */
1522
2365
  canSendApplicationData() {
1523
- if (!this.nominated) {
2366
+ const activePair = this.applicationDataPair();
2367
+ if (!activePair) {
1524
2368
  return false;
1525
2369
  }
1526
2370
  if (this.state === "closed" || this.state === "failed") {
@@ -1530,8 +2374,24 @@ class Connection {
1530
2374
  if (this.iceLite) {
1531
2375
  return true;
1532
2376
  }
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.
1533
2380
  return this.consent.fresh;
1534
2381
  }
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();
2394
+ }
1535
2395
  async close() {
1536
2396
  // """
1537
2397
  // Close the connection.
@@ -1539,8 +2399,8 @@ class Connection {
1539
2399
  this.closed = true;
1540
2400
  this.setState("closed");
1541
2401
  this.onIceCandidateError.complete();
2402
+ this.onGatheringError.complete();
1542
2403
  this.onIceServerReached.complete();
1543
- this.signalClosed();
1544
2404
  this.closing.abort();
1545
2405
  this.cancelChecks();
1546
2406
  this.provisionalChecklist.end();
@@ -1558,6 +2418,8 @@ class Connection {
1558
2418
  }));
1559
2419
  }
1560
2420
  this.nominated = undefined;
2421
+ this.lastDataPair = undefined;
2422
+ this.previousSelectedPairs = [];
1561
2423
  this.liteNominating = false;
1562
2424
  this.nomination.reset();
1563
2425
  this.selection.abort();
@@ -1573,10 +2435,16 @@ class Connection {
1573
2435
  }
1574
2436
  this.protocols = [];
1575
2437
  this.localCandidates = [];
2438
+ this.spedBindingCache.clear();
2439
+ this.spedRuntime?.abort();
2440
+ this.spedRuntime = undefined;
1576
2441
  }
1577
2442
  setState(state) {
1578
2443
  this.state = state;
1579
2444
  this.stateChanged.execute(state);
2445
+ if (state === "failed" || state === "closed") {
2446
+ this.spedRuntime?.abort();
2447
+ }
1580
2448
  }
1581
2449
  /**
1582
2450
  * Known constraint (as in develop): candidates are not deduplicated. A
@@ -1609,6 +2477,8 @@ class Connection {
1609
2477
  }
1610
2478
  this.remoteCandidatesEnd = true;
1611
2479
  this.nomination.evaluate();
2480
+ const settled = this.settleSpedUnconfirmed();
2481
+ await this.flushSpedUnconfirmedFallback(settled);
1612
2482
  return;
1613
2483
  }
1614
2484
  // RFC 8838: a completed generation takes no further candidates.
@@ -1646,10 +2516,38 @@ class Connection {
1646
2516
  return;
1647
2517
  }
1648
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
+ }
1649
2527
  this._remoteCandidates.push(remoteCandidate);
1650
2528
  this.pairRemoteCandidate(remoteCandidate);
1651
2529
  this.sortCheckList();
1652
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
+ }
1653
2551
  getDefaultCandidate() {
1654
2552
  const candidates = this.localCandidates.sort((a, b) => a.priority - b.priority);
1655
2553
  const [candidate] = candidates;
@@ -1684,11 +2582,117 @@ class Connection {
1684
2582
  const pair = this.checkList.find((pair) => pair.protocol === protocol && pair.remoteCandidate === remoteCandidate);
1685
2583
  return pair;
1686
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);
2617
+ }
2618
+ if (this.nominated?.protocol === protocol) {
2619
+ return this.nominated;
2620
+ }
2621
+ return this.checkList.find((candidate) => candidate.protocol === protocol);
2622
+ }
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]);
2630
+ }
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);
2636
+ }
2637
+ bindingResponseSourceMatches(addr, pair) {
2638
+ return (addr != null &&
2639
+ addr[0] === pair.remoteAddr[0] &&
2640
+ addr[1] === pair.remoteAddr[1]);
2641
+ }
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);
2682
+ }
1687
2683
  applyIceControlling(iceControlling) {
1688
2684
  const becameControlling = !this._iceControlling && iceControlling;
1689
- if (this._iceControlling !== iceControlling) {
2685
+ const roleChanged = this._iceControlling !== iceControlling;
2686
+ if (roleChanged) {
1690
2687
  this.invalidateNominations();
1691
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();
1692
2696
  // USE-CANDIDATE received while controlled came from a peer that was
1693
2697
  // controlling then; as the controlling agent this one nominates itself.
1694
2698
  if (iceControlling) {
@@ -1705,6 +2709,8 @@ class Connection {
1705
2709
  for (const pair of this.checkList) {
1706
2710
  pair.iceControlling = iceControlling;
1707
2711
  }
2712
+ if (roleChanged)
2713
+ this.failover.refresh();
1708
2714
  if (becameControlling)
1709
2715
  this.confirmSelections();
1710
2716
  }
@@ -1789,6 +2795,8 @@ class Connection {
1789
2795
  checkComplete(pair) {
1790
2796
  pair.handle = undefined;
1791
2797
  if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
2798
+ const settled = this.settleSpedUnconfirmed(pair);
2799
+ void this.flushSpedUnconfirmedFallback(settled ?? pair);
1792
2800
  this.selection.forgetRetry(pair);
1793
2801
  // Updating the Nominated Flag
1794
2802
  // https://www.rfc-editor.org/rfc/rfc8445#section-7.3.1.5,
@@ -1811,44 +2819,87 @@ class Connection {
1811
2819
  // (`SelectionReplacement.replaces`).
1812
2820
  (this.nominated == undefined || this.selection.replaces(pair))) {
1813
2821
  const previous = this.nominated;
1814
- log(previous ? "selected pair replaced" : "nominated", pair.toJSON(), {
1815
- previous: previous?.toJSON(),
1816
- });
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 });
1817
2839
  this.nominated = pair;
1818
2840
  this.liteNominating = false;
1819
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
+ }
1820
2853
  // RFC 7675 section 5.1: the successful connectivity check that
1821
2854
  // selected the pair is its initial consent, so data may flow at once
1822
2855
  // instead of waiting for the consent lifecycle to start.
1823
2856
  this.consent.fresh = true;
2857
+ this.clearConsentExpiredGrace();
1824
2858
  this.pruneTcpConnections(pair);
2859
+ this.failover.selected(pair);
1825
2860
  // After resetNominatedPair / renomination while already connected,
1826
2861
  // restart consent freshness on the new selected pair.
1827
2862
  if (!this.iceLite &&
1828
- (this.state === "connected" || this.state === "completed")) {
1829
- this.consent.start();
2863
+ (this.state === "connected" ||
2864
+ this.state === "completed" ||
2865
+ this.state === "disconnected")) {
2866
+ this.queryConsent();
1830
2867
  }
1831
2868
  // 8.1.2. Updating States
1832
2869
  // The agent MUST remove all Waiting and Frozen pairs in the check
1833
2870
  // list and triggered check queue for the same component as the
1834
2871
  // nominated pairs for that media stream. A controlling agent that
1835
- // may replace the selection keeps the pairs that outrank it.
2872
+ // may replace the selection keeps the pairs that outrank it, and
2873
+ // failover keeps the backup of each other socket.
1836
2874
  const keepsChecking = this.iceControlling && this.replacesSelection();
2875
+ const backups = this.failover.keeps();
1837
2876
  for (const p of this.checkList) {
1838
2877
  if (p.component === pair.component &&
1839
2878
  [
1840
2879
  iceBase_1.CandidatePairState.WAITING,
1841
2880
  iceBase_1.CandidatePairState.FROZEN,
1842
2881
  ].includes(p.state) &&
1843
- !(keepsChecking && this.replacesWith(p) && this.outranks(p, pair))) {
2882
+ !(keepsChecking &&
2883
+ this.replacesWith(p) &&
2884
+ this.outranks(p, pair)) &&
2885
+ !backups.has(p)) {
1844
2886
  p.updateState(iceBase_1.CandidatePairState.FAILED);
2887
+ if (this.failoverEnabled())
2888
+ this.failover.prunedWithoutCheck(p);
1845
2889
  }
1846
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
+ }
1847
2897
  }
1848
2898
  // Once there is at least one nominated pair in the valid list for
1849
2899
  // every component of at least one media stream and the state of the
1850
2900
  // check list is Running:
1851
2901
  if (this.nominated) {
2902
+ this.failover.refresh();
1852
2903
  if (!this.checkListDone) {
1853
2904
  log("ICE completed");
1854
2905
  this.checkListState.put(new Promise((r) => r(iceBase_1.ICE_COMPLETED)));
@@ -1858,6 +2909,8 @@ class Connection {
1858
2909
  this.selection.evaluate();
1859
2910
  void this.selection.checkOutrankingPairs();
1860
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();
1861
2914
  }
1862
2915
  return;
1863
2916
  }
@@ -1873,6 +2926,9 @@ class Connection {
1873
2926
  this.nomination.evaluate();
1874
2927
  this.selection.evaluate();
1875
2928
  this.selection.scheduleRetries();
2929
+ // A backup (or a failover target) that failed is replaced.
2930
+ if (this.nominated)
2931
+ this.failover.refresh();
1876
2932
  this.concludeCheckListIfExhausted();
1877
2933
  }
1878
2934
  /**
@@ -2125,13 +3181,19 @@ class Connection {
2125
3181
  iceControlling: this.iceControlling,
2126
3182
  localCandidate: pair.localCandidate,
2127
3183
  });
3184
+ if (!this.decorateSpedRequest(request, pair)) {
3185
+ return "rejected";
3186
+ }
3187
+ const generation = this.generation;
2128
3188
  pair.requestsSent++;
2129
3189
  try {
2130
- await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), {
3190
+ const [response, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), {
2131
3191
  ...this.checkRequestOptions(pair),
2132
3192
  signal: AbortSignal.any([this.remoteChecks.signal, signal]),
2133
3193
  });
2134
3194
  pair.responsesReceived++;
3195
+ this.spedRuntime?.tryMarkDirectHandshakeReady(pair, generation);
3196
+ await this.consumeSpedStun(response, addr, pair.protocol, pair, generation);
2135
3197
  return "nominated";
2136
3198
  }
2137
3199
  catch (error) {
@@ -2188,6 +3250,7 @@ class Connection {
2188
3250
  const best = this.bestValidPair(this.checkList);
2189
3251
  this.checkList.push(pair);
2190
3252
  this.sortCheckList();
3253
+ this.wakeIncomingCheckWaits();
2191
3254
  this.nomination.pairAdded(pair, best);
2192
3255
  // A pair that may replace the selection is checked after it too.
2193
3256
  const selected = this.nominated;
@@ -2195,19 +3258,17 @@ class Connection {
2195
3258
  this.iceControlling &&
2196
3259
  this.replacesSelection() &&
2197
3260
  this.replacesWith(pair) &&
2198
- this.outranks(pair, selected)) {
3261
+ this.outranks(pair, selected) &&
3262
+ this.failoverAllows(pair)) {
2199
3263
  void this.selection.checkOutrankingPairs();
2200
3264
  }
3265
+ // A pair of another socket may become its backup.
3266
+ if (selected)
3267
+ this.failover.refresh();
2201
3268
  }
2202
- // 7.2. STUN Server Procedures
2203
- // 7.2.1.3、7.2.1.4、および7.2.1.5
2204
- checkIncoming(message, addr, protocol) {
2205
- // """
2206
- // Handle a successful incoming check.
2207
- // """
3269
+ ensureIncomingPair(message, addr, protocol) {
2208
3270
  const txUsername = message.getAttributeValue("USERNAME");
2209
3271
  const { remoteUsername: localUsername } = (0, checkMessages_1.decodeTxUsername)(txUsername);
2210
- // find remote candidate
2211
3272
  let remoteCandidate;
2212
3273
  const [host, port] = addr;
2213
3274
  for (const c of this.remoteCandidates) {
@@ -2216,23 +3277,41 @@ class Connection {
2216
3277
  break;
2217
3278
  }
2218
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
+ }
2219
3290
  if (!remoteCandidate) {
2220
- // 7.2.1.3. Learning Peer Reflexive Candidates
2221
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"
2222
3292
  ? (0, candidate_1.remoteTcpTypeForIncoming)(protocol.localCandidate.tcptype)
2223
3293
  : undefined, undefined, undefined);
2224
3294
  this._remoteCandidates.push(remoteCandidate);
2225
3295
  }
2226
- // find pair
2227
3296
  let pair = this.findPair(protocol, remoteCandidate);
2228
3297
  if (!pair) {
2229
3298
  pair = new iceBase_1.CandidatePair(protocol, remoteCandidate, this.iceControlling);
2230
3299
  pair.updateState(iceBase_1.CandidatePairState.WAITING);
2231
3300
  this.addPair(pair);
2232
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);
2233
3311
  pair.noteIncomingRequest(message.transactionIdHex);
2234
3312
  pair.requestsReceived++;
2235
3313
  pair.responsesSent++;
3314
+ this.failover.received(pair);
2236
3315
  // The pair's local candidate is the protocol's shared candidate of the
2237
3316
  // current generation. A late check addressed to an earlier ufrag (consent
2238
3317
  // on the old pair during an ICE restart) must not relabel it, or the next
@@ -2255,6 +3334,7 @@ class Connection {
2255
3334
  pair.nominated = true;
2256
3335
  pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
2257
3336
  this.checkComplete(pair);
3337
+ this.spedRuntime?.tryMarkDirectHandshakeReady(pair, this.generation);
2258
3338
  }
2259
3339
  return;
2260
3340
  }
@@ -2327,7 +3407,306 @@ class Connection {
2327
3407
  if (!selected || !this.iceControlling || !this.replacesSelection()) {
2328
3408
  return undefined;
2329
3409
  }
2330
- return (pair) => this.replacesWith(pair) && this.outranks(pair, selected);
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
+ }
2331
3710
  }
2332
3711
  /**
2333
3712
  * Pair a local candidate gathered after remote candidates arrived (a late
@@ -2343,6 +3722,13 @@ class Connection {
2343
3722
  return;
2344
3723
  const replaceable = !!this.nominated && this.iceControlling && this.replacesSelection();
2345
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
+ }
2346
3732
  return;
2347
3733
  }
2348
3734
  for (const remoteCandidate of this.remoteCandidates) {
@@ -2383,4 +3769,6 @@ class Connection {
2383
3769
  }
2384
3770
  }
2385
3771
  exports.Connection = Connection;
3772
+ /** Replaced remote ufrags remembered to recognise their late checks. */
3773
+ const RETIRED_REMOTE_USERNAMES_MAX = 4;
2386
3774
  //# sourceMappingURL=ice.js.map