werift 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/README.md +119 -8
  2. package/lib/common/src/event.d.ts +26 -0
  3. package/lib/common/src/event.js +87 -2
  4. package/lib/common/src/event.js.map +1 -1
  5. package/lib/common/src/network.d.ts +6 -1
  6. package/lib/common/src/network.js +8 -2
  7. package/lib/common/src/network.js.map +1 -1
  8. package/lib/common/src/transport.d.ts +12 -5
  9. package/lib/common/src/transport.js +3 -2
  10. package/lib/common/src/transport.js.map +1 -1
  11. package/lib/dtls/src/alert.d.ts +49 -0
  12. package/lib/dtls/src/alert.js +103 -0
  13. package/lib/dtls/src/alert.js.map +1 -0
  14. package/lib/dtls/src/client.js +15 -1
  15. package/lib/dtls/src/client.js.map +1 -1
  16. package/lib/dtls/src/context/dtls.d.ts +2 -0
  17. package/lib/dtls/src/context/dtls.js +7 -0
  18. package/lib/dtls/src/context/dtls.js.map +1 -1
  19. package/lib/dtls/src/context/transport.d.ts +17 -1
  20. package/lib/dtls/src/context/transport.js +38 -2
  21. package/lib/dtls/src/context/transport.js.map +1 -1
  22. package/lib/dtls/src/flight/client/flight5.js +4 -1
  23. package/lib/dtls/src/flight/client/flight5.js.map +1 -1
  24. package/lib/dtls/src/flight/flight.d.ts +5 -0
  25. package/lib/dtls/src/flight/flight.js +10 -1
  26. package/lib/dtls/src/flight/flight.js.map +1 -1
  27. package/lib/dtls/src/flight/server/flight6.js +4 -1
  28. package/lib/dtls/src/flight/server/flight6.js.map +1 -1
  29. package/lib/dtls/src/index.d.ts +3 -1
  30. package/lib/dtls/src/index.js +10 -1
  31. package/lib/dtls/src/index.js.map +1 -1
  32. package/lib/dtls/src/record/const.d.ts +9 -0
  33. package/lib/dtls/src/record/const.js +9 -1
  34. package/lib/dtls/src/record/const.js.map +1 -1
  35. package/lib/dtls/src/record/receive.d.ts +6 -0
  36. package/lib/dtls/src/record/receive.js +50 -19
  37. package/lib/dtls/src/record/receive.js.map +1 -1
  38. package/lib/dtls/src/server.js +19 -1
  39. package/lib/dtls/src/server.js.map +1 -1
  40. package/lib/dtls/src/socket.d.ts +134 -2
  41. package/lib/dtls/src/socket.js +322 -6
  42. package/lib/dtls/src/socket.js.map +1 -1
  43. package/lib/ice/src/candidateError.d.ts +155 -0
  44. package/lib/ice/src/candidateError.js +246 -0
  45. package/lib/ice/src/candidateError.js.map +1 -0
  46. package/lib/ice/src/candidateGatherer.d.ts +127 -0
  47. package/lib/ice/src/candidateGatherer.js +745 -0
  48. package/lib/ice/src/candidateGatherer.js.map +1 -0
  49. package/lib/ice/src/consent.d.ts +49 -0
  50. package/lib/ice/src/consent.js +258 -0
  51. package/lib/ice/src/consent.js.map +1 -0
  52. package/lib/ice/src/ice.d.ts +223 -71
  53. package/lib/ice/src/ice.js +873 -975
  54. package/lib/ice/src/ice.js.map +1 -1
  55. package/lib/ice/src/iceBase.d.ts +207 -8
  56. package/lib/ice/src/iceBase.js +94 -31
  57. package/lib/ice/src/iceBase.js.map +1 -1
  58. package/lib/ice/src/index.d.ts +1 -0
  59. package/lib/ice/src/index.js +1 -0
  60. package/lib/ice/src/index.js.map +1 -1
  61. package/lib/ice/src/internal/checkMessages.d.ts +41 -0
  62. package/lib/ice/src/internal/checkMessages.js +63 -0
  63. package/lib/ice/src/internal/checkMessages.js.map +1 -0
  64. package/lib/ice/src/internal/defaultRoute.d.ts +20 -0
  65. package/lib/ice/src/internal/defaultRoute.js +134 -0
  66. package/lib/ice/src/internal/defaultRoute.js.map +1 -0
  67. package/lib/ice/src/internal/hostInterfaces.d.ts +17 -0
  68. package/lib/ice/src/internal/hostInterfaces.js +77 -0
  69. package/lib/ice/src/internal/hostInterfaces.js.map +1 -0
  70. package/lib/ice/src/internal/hostPreference.d.ts +24 -0
  71. package/lib/ice/src/internal/hostPreference.js +38 -0
  72. package/lib/ice/src/internal/hostPreference.js.map +1 -0
  73. package/lib/ice/src/internal/resolveHostAddresses.d.ts +56 -8
  74. package/lib/ice/src/internal/resolveHostAddresses.js +127 -24
  75. package/lib/ice/src/internal/resolveHostAddresses.js.map +1 -1
  76. package/lib/ice/src/internal/selectAddresses.d.ts +27 -0
  77. package/lib/ice/src/internal/selectAddresses.js +37 -18
  78. package/lib/ice/src/internal/selectAddresses.js.map +1 -1
  79. package/lib/ice/src/nomination/regularNomination.d.ts +200 -0
  80. package/lib/ice/src/nomination/regularNomination.js +311 -0
  81. package/lib/ice/src/nomination/regularNomination.js.map +1 -0
  82. package/lib/ice/src/nomination/selectionReplacement.d.ts +138 -0
  83. package/lib/ice/src/nomination/selectionReplacement.js +371 -0
  84. package/lib/ice/src/nomination/selectionReplacement.js.map +1 -0
  85. package/lib/ice/src/provisional.d.ts +139 -0
  86. package/lib/ice/src/provisional.js +468 -0
  87. package/lib/ice/src/provisional.js.map +1 -0
  88. package/lib/ice/src/stun/protocol.d.ts +9 -2
  89. package/lib/ice/src/stun/protocol.js +16 -17
  90. package/lib/ice/src/stun/protocol.js.map +1 -1
  91. package/lib/ice/src/stun/tcpProtocol.d.ts +1 -1
  92. package/lib/ice/src/stun/tcpProtocol.js +7 -7
  93. package/lib/ice/src/stun/tcpProtocol.js.map +1 -1
  94. package/lib/ice/src/stun/transaction.js +4 -2
  95. package/lib/ice/src/stun/transaction.js.map +1 -1
  96. package/lib/ice/src/turn/protocol.d.ts +2 -2
  97. package/lib/ice/src/turn/protocol.js +6 -3
  98. package/lib/ice/src/turn/protocol.js.map +1 -1
  99. package/lib/ice/src/types/model.d.ts +16 -5
  100. package/lib/ice/src/types/model.js.map +1 -1
  101. package/lib/ice-server/src/stun/attributes.js +4 -0
  102. package/lib/ice-server/src/stun/attributes.js.map +1 -1
  103. package/lib/ice-server/src/stun/const.d.ts +20 -1
  104. package/lib/ice-server/src/stun/const.js +9 -1
  105. package/lib/ice-server/src/stun/const.js.map +1 -1
  106. package/lib/ice-server/src/stun/message.d.ts +28 -1
  107. package/lib/ice-server/src/stun/message.js +102 -15
  108. package/lib/ice-server/src/stun/message.js.map +1 -1
  109. package/lib/index.mjs +13394 -7732
  110. package/lib/nonstandard/index.mjs +680 -286
  111. package/lib/polyfill/dom.mjs +19605 -14243
  112. package/lib/polyfill/index.mjs +19605 -14243
  113. package/lib/rtp/src/index.d.ts +1 -0
  114. package/lib/rtp/src/index.js +1 -0
  115. package/lib/rtp/src/index.js.map +1 -1
  116. package/lib/rtp/src/rtp/continuity.d.ts +14 -1
  117. package/lib/rtp/src/rtp/continuity.js +24 -4
  118. package/lib/rtp/src/rtp/continuity.js.map +1 -1
  119. package/lib/rtp/src/rtp/timelineRewriter.d.ts +178 -0
  120. package/lib/rtp/src/rtp/timelineRewriter.js +417 -0
  121. package/lib/rtp/src/rtp/timelineRewriter.js.map +1 -0
  122. package/lib/sctp/src/sctp.d.ts +5 -0
  123. package/lib/sctp/src/sctp.js +81 -47
  124. package/lib/sctp/src/sctp.js.map +1 -1
  125. package/lib/webrtc/src/api/compatibilityOptions.d.ts +33 -0
  126. package/lib/webrtc/src/api/compatibilityOptions.js +33 -0
  127. package/lib/webrtc/src/api/compatibilityOptions.js.map +1 -0
  128. package/lib/webrtc/src/api/peerConfig.d.ts +348 -34
  129. package/lib/webrtc/src/api/peerConfig.js +90 -24
  130. package/lib/webrtc/src/api/peerConfig.js.map +1 -1
  131. package/lib/webrtc/src/api/peerConnectionEvents.d.ts +77 -1
  132. package/lib/webrtc/src/api/peerConnectionEvents.js +105 -1
  133. package/lib/webrtc/src/api/peerConnectionEvents.js.map +1 -1
  134. package/lib/webrtc/src/helper.d.ts +8 -0
  135. package/lib/webrtc/src/helper.js +40 -4
  136. package/lib/webrtc/src/helper.js.map +1 -1
  137. package/lib/webrtc/src/media/codecCompatibility.d.ts +87 -1
  138. package/lib/webrtc/src/media/codecCompatibility.js +338 -12
  139. package/lib/webrtc/src/media/codecCompatibility.js.map +1 -1
  140. package/lib/webrtc/src/media/receiver/nack.d.ts +43 -10
  141. package/lib/webrtc/src/media/receiver/nack.js +245 -88
  142. package/lib/webrtc/src/media/receiver/nack.js.map +1 -1
  143. package/lib/webrtc/src/media/router.d.ts +239 -51
  144. package/lib/webrtc/src/media/router.js +664 -237
  145. package/lib/webrtc/src/media/router.js.map +1 -1
  146. package/lib/webrtc/src/media/routing/pendingRoutes.d.ts +26 -0
  147. package/lib/webrtc/src/media/routing/pendingRoutes.js +48 -0
  148. package/lib/webrtc/src/media/routing/pendingRoutes.js.map +1 -0
  149. package/lib/webrtc/src/media/routing/ridRouting.d.ts +37 -0
  150. package/lib/webrtc/src/media/routing/ridRouting.js +74 -0
  151. package/lib/webrtc/src/media/routing/ridRouting.js.map +1 -0
  152. package/lib/webrtc/src/media/routing/routeTable.d.ts +60 -0
  153. package/lib/webrtc/src/media/routing/routeTable.js +95 -0
  154. package/lib/webrtc/src/media/routing/routeTable.js.map +1 -0
  155. package/lib/webrtc/src/media/routing/rtcpRouting.d.ts +34 -0
  156. package/lib/webrtc/src/media/routing/rtcpRouting.js +165 -0
  157. package/lib/webrtc/src/media/routing/rtcpRouting.js.map +1 -0
  158. package/lib/webrtc/src/media/routing/unknownSsrc.d.ts +55 -0
  159. package/lib/webrtc/src/media/routing/unknownSsrc.js +117 -0
  160. package/lib/webrtc/src/media/routing/unknownSsrc.js.map +1 -0
  161. package/lib/webrtc/src/media/rtpReceiver.d.ts +222 -0
  162. package/lib/webrtc/src/media/rtpReceiver.js +668 -28
  163. package/lib/webrtc/src/media/rtpReceiver.js.map +1 -1
  164. package/lib/webrtc/src/media/rtpSender.d.ts +7 -0
  165. package/lib/webrtc/src/media/rtpSender.js +9 -3
  166. package/lib/webrtc/src/media/rtpSender.js.map +1 -1
  167. package/lib/webrtc/src/media/rtpTransceiver.d.ts +18 -0
  168. package/lib/webrtc/src/media/rtpTransceiver.js +64 -2
  169. package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
  170. package/lib/webrtc/src/media/sender/senderReportHistory.d.ts +51 -0
  171. package/lib/webrtc/src/media/sender/senderReportHistory.js +111 -0
  172. package/lib/webrtc/src/media/sender/senderReportHistory.js.map +1 -0
  173. package/lib/webrtc/src/media/sender/senderStats.d.ts +6 -5
  174. package/lib/webrtc/src/media/sender/senderStats.js +14 -19
  175. package/lib/webrtc/src/media/sender/senderStats.js.map +1 -1
  176. package/lib/webrtc/src/media/track.d.ts +9 -0
  177. package/lib/webrtc/src/media/track.js +9 -0
  178. package/lib/webrtc/src/media/track.js.map +1 -1
  179. package/lib/webrtc/src/negotiation/remoteMediaApplication.d.ts +23 -6
  180. package/lib/webrtc/src/negotiation/remoteMediaApplication.js +46 -22
  181. package/lib/webrtc/src/negotiation/remoteMediaApplication.js.map +1 -1
  182. package/lib/webrtc/src/negotiation/transceiverPairing.d.ts +1 -0
  183. package/lib/webrtc/src/negotiation/transceiverPairing.js +62 -0
  184. package/lib/webrtc/src/negotiation/transceiverPairing.js.map +1 -0
  185. package/lib/webrtc/src/negotiation/transportActivation.d.ts +8 -1
  186. package/lib/webrtc/src/negotiation/transportActivation.js +21 -0
  187. package/lib/webrtc/src/negotiation/transportActivation.js.map +1 -1
  188. package/lib/webrtc/src/negotiationTransaction.d.ts +35 -4
  189. package/lib/webrtc/src/negotiationTransaction.js +111 -8
  190. package/lib/webrtc/src/negotiationTransaction.js.map +1 -1
  191. package/lib/webrtc/src/peerConnection.d.ts +65 -6
  192. package/lib/webrtc/src/peerConnection.js +283 -28
  193. package/lib/webrtc/src/peerConnection.js.map +1 -1
  194. package/lib/webrtc/src/polyfill/globals.d.ts +2 -1
  195. package/lib/webrtc/src/polyfill/globals.js.map +1 -1
  196. package/lib/webrtc/src/polyfill/install.js +2 -0
  197. package/lib/webrtc/src/polyfill/install.js.map +1 -1
  198. package/lib/webrtc/src/sctpManager.js +4 -0
  199. package/lib/webrtc/src/sctpManager.js.map +1 -1
  200. package/lib/webrtc/src/sdp.d.ts +69 -0
  201. package/lib/webrtc/src/sdp.js +139 -14
  202. package/lib/webrtc/src/sdp.js.map +1 -1
  203. package/lib/webrtc/src/sdpManager.d.ts +85 -4
  204. package/lib/webrtc/src/sdpManager.js +214 -14
  205. package/lib/webrtc/src/sdpManager.js.map +1 -1
  206. package/lib/webrtc/src/secureTransportManager.d.ts +38 -1
  207. package/lib/webrtc/src/secureTransportManager.js +82 -7
  208. package/lib/webrtc/src/secureTransportManager.js.map +1 -1
  209. package/lib/webrtc/src/transceiverManager.d.ts +82 -4
  210. package/lib/webrtc/src/transceiverManager.js +231 -38
  211. package/lib/webrtc/src/transceiverManager.js.map +1 -1
  212. package/lib/webrtc/src/transport/dtls.d.ts +95 -1
  213. package/lib/webrtc/src/transport/dtls.js +324 -28
  214. package/lib/webrtc/src/transport/dtls.js.map +1 -1
  215. package/lib/webrtc/src/transport/ice.d.ts +61 -4
  216. package/lib/webrtc/src/transport/ice.js +180 -11
  217. package/lib/webrtc/src/transport/ice.js.map +1 -1
  218. package/lib/webrtc/src/transport/sctp.d.ts +23 -0
  219. package/lib/webrtc/src/transport/sctp.js +87 -2
  220. package/lib/webrtc/src/transport/sctp.js.map +1 -1
  221. package/lib/webrtc/src/utils.d.ts +33 -0
  222. package/lib/webrtc/src/utils.js +52 -3
  223. package/lib/webrtc/src/utils.js.map +1 -1
  224. package/package.json +2 -1
@@ -33,27 +33,51 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.Connection = void 0;
36
+ exports.Connection = exports.DEFAULT_STUN_SERVER_URL = void 0;
37
37
  const timers = __importStar(require("node:timers/promises"));
38
38
  const crypto_1 = require("crypto");
39
- const net_1 = require("net");
40
39
  const candidate_1 = require("./candidate");
40
+ const candidateGatherer_1 = require("./candidateGatherer");
41
+ const consent_1 = require("./consent");
41
42
  const lookup_1 = require("./dns/lookup");
42
43
  const exceptions_1 = require("./exceptions");
43
44
  const helper_1 = require("./helper");
44
45
  const iceBase_1 = require("./iceBase");
45
46
  const common_1 = require("./imports/common");
47
+ const checkMessages_1 = require("./internal/checkMessages");
48
+ const defaultRoute_1 = require("./internal/defaultRoute");
49
+ const hostInterfaces_1 = require("./internal/hostInterfaces");
46
50
  const resolveHostAddresses_1 = require("./internal/resolveHostAddresses");
51
+ const regularNomination_1 = require("./nomination/regularNomination");
52
+ const selectionReplacement_1 = require("./nomination/selectionReplacement");
53
+ const provisional_1 = require("./provisional");
47
54
  const const_1 = require("./stun/const");
48
55
  const message_1 = require("./stun/message");
49
56
  const protocol_1 = require("./stun/protocol");
50
- const tcpProtocol_1 = require("./stun/tcpProtocol");
51
- const protocol_2 = require("./turn/protocol");
52
- const utils_1 = require("./utils");
53
57
  const log = (0, common_1.debug)("werift-ice : packages/ice/src/ice.ts : log");
54
58
  /** Fallback STUN server when none is configured (constructor / setIceServers). */
55
59
  const DEFAULT_STUN_SERVER = ["stun.l.google.com", 19302];
60
+ /**
61
+ * The URL `onIceCandidateError` names the built-in default STUN server by:
62
+ * it is in no configuration, so werift synthesizes one.
63
+ */
64
+ exports.DEFAULT_STUN_SERVER_URL = "stun:stun.l.google.com:19302";
65
+ // The ICE agent. This file keeps the public API, the lifecycle (restart,
66
+ // close, state), the protocol event wiring and the live checklist
67
+ // (connect / checkStart / checkComplete / checkIncoming). Its parts live in
68
+ // collaborators the agent supplies through a host object:
69
+ // - candidateGatherer.ts: host / server-reflexive / relay gathering
70
+ // - consent.ts: RFC 7675 consent freshness of the selected pair
71
+ // - provisional.ts: the checklist of an ICE restart negotiated with a pranswer
72
+ // - nomination/regularNomination.ts: RFC 8445 regular nomination
73
+ // - nomination/selectionReplacement.ts: semi-aggressive nomination /
74
+ // renomination replacing the selection
75
+ // - internal/checkMessages.ts: building and reading connectivity checks
56
76
  class Connection {
77
+ /** The staged ICE restart generation (`ProvisionalChecklist`). */
78
+ get provisional() {
79
+ return this.provisionalChecklist.generation;
80
+ }
57
81
  constructor(_iceControlling, options) {
58
82
  Object.defineProperty(this, "_iceControlling", {
59
83
  enumerable: true,
@@ -79,6 +103,19 @@ class Connection {
79
103
  writable: true,
80
104
  value: false
81
105
  });
106
+ /** The peer advertised `a=ice-options:renomination` (see `IceOptions.renomination`). */
107
+ Object.defineProperty(this, "remoteRenomination", {
108
+ enumerable: true,
109
+ configurable: true,
110
+ writable: true,
111
+ value: false
112
+ });
113
+ Object.defineProperty(this, "remoteIceOptions", {
114
+ enumerable: true,
115
+ configurable: true,
116
+ writable: true,
117
+ value: []
118
+ });
82
119
  Object.defineProperty(this, "remotePassword", {
83
120
  enumerable: true,
84
121
  configurable: true,
@@ -114,6 +151,13 @@ class Connection {
114
151
  writable: true,
115
152
  value: []
116
153
  });
154
+ /** Whether stunServers is the built-in default (none configured). */
155
+ Object.defineProperty(this, "usesDefaultStunServer", {
156
+ enumerable: true,
157
+ configurable: true,
158
+ writable: true,
159
+ value: false
160
+ });
117
161
  /** TURN servers gathering allocates on, one allocation each. */
118
162
  Object.defineProperty(this, "turnServers", {
119
163
  enumerable: true,
@@ -168,6 +212,13 @@ class Connection {
168
212
  writable: true,
169
213
  value: false
170
214
  });
215
+ /** connect() stopped scheduling checks (a later pair must start its own). */
216
+ Object.defineProperty(this, "schedulingStopped", {
217
+ enumerable: true,
218
+ configurable: true,
219
+ writable: true,
220
+ value: false
221
+ });
171
222
  Object.defineProperty(this, "generation", {
172
223
  enumerable: true,
173
224
  configurable: true,
@@ -243,12 +294,61 @@ class Connection {
243
294
  writable: true,
244
295
  value: void 0
245
296
  });
246
- Object.defineProperty(this, "nominating", {
297
+ /** The ICE-lite nomination (first valid pair, in `checkStart`) is in flight. */
298
+ Object.defineProperty(this, "liteNominating", {
247
299
  enumerable: true,
248
300
  configurable: true,
249
301
  writable: true,
250
302
  value: false
251
303
  });
304
+ /** Regular nomination (RFC 8445 §8.1.1) of the live checklist. */
305
+ Object.defineProperty(this, "nomination", {
306
+ enumerable: true,
307
+ configurable: true,
308
+ writable: true,
309
+ value: new regularNomination_1.RegularNomination(this.liveNominationHost())
310
+ });
311
+ /** Semi-aggressive nomination and renomination: replacing the selection. */
312
+ Object.defineProperty(this, "selection", {
313
+ enumerable: true,
314
+ configurable: true,
315
+ writable: true,
316
+ value: new selectionReplacement_1.SelectionReplacement({
317
+ checkList: () => this.checkList,
318
+ selected: () => this.nominated,
319
+ controlling: () => this.iceControlling,
320
+ closed: () => this.state === "closed",
321
+ remoteGeneration: () => this.remoteGeneration,
322
+ usesRenomination: () => this.usesRenomination(),
323
+ usesSemiAggressiveNomination: () => this.usesSemiAggressiveNomination(),
324
+ replacesSelection: () => this.replacesSelection(),
325
+ replacesWith: (pair) => this.replacesWith(pair),
326
+ outranks: (pair, other) => this.outranks(pair, other),
327
+ bestValidPair: (pairs) => this.bestValidPair(pairs),
328
+ isTcpPair: (pair) => this.isTcpPair(pair),
329
+ check: (pair) => {
330
+ pair.handle = this.checkStart(pair);
331
+ },
332
+ complete: (pair) => this.checkComplete(pair),
333
+ sendNomination: (pair, signal, value) => this.sendNomination(pair, signal, value),
334
+ isStaleNomination: (pair, generation) => this.isStaleNomination(pair, generation),
335
+ roleConflict: () => this.switchRole(false),
336
+ })
337
+ });
338
+ /** See `NominationHint`; set by the restart that ends a provisional checklist. */
339
+ Object.defineProperty(this, "nominationHint", {
340
+ enumerable: true,
341
+ configurable: true,
342
+ writable: true,
343
+ value: void 0
344
+ });
345
+ /** USE-CANDIDATE re-sent for a pair selected before the agent became controlling (`confirmSelections`). */
346
+ Object.defineProperty(this, "selectionConfirmations", {
347
+ enumerable: true,
348
+ configurable: true,
349
+ writable: true,
350
+ value: new Set()
351
+ });
252
352
  /**
253
353
  * Aborted when the remote generation ends (restart, restartRemote, close):
254
354
  * every check and nomination transaction of that generation stops with it.
@@ -261,16 +361,21 @@ class Connection {
261
361
  * - `retryCheck` (487 role conflict / 401 retry): the handle of the check
262
362
  * it replaces and this signal (the retry is a `checkStart`).
263
363
  * - regular nomination in `checkStart` (toward an ICE-lite peer): the
264
- * check's signal; `isStaleNomination` guards `nominating`, the pair state
265
- * and `checkComplete`.
266
- * - `nominateTcpPair`: this signal; `isStaleNomination`.
267
- * - `checkProvisional` / `nominateProvisional`: `generation.checks`
268
- * (`endProvisional()`, a replacement pranswer, close); `belongs()`.
269
- * - `queryConsent`: a per-request `AbortController` and
270
- * `stopConsentLifecycle()`; `consentSessionId`.
364
+ * check's signal; `isStaleNomination` guards `liteNominating`, the pair
365
+ * state and `checkComplete`.
366
+ * - `RegularNomination` (live: `sendNomination`): this signal and the
367
+ * attempt's own, which `reset()` (restart, restartRemote,
368
+ * resetNominatedPair, close) and `invalidate()` (role change) abort; a
369
+ * result of a replaced attempt is ignored. Its delay timer is cleared by
370
+ * `reset()`.
371
+ * - `ProvisionalChecklist` checks and nominations: `generation.checks`
372
+ * (`end()`, a replacement pranswer, close); `belongs()`, and
373
+ * the provisional `RegularNomination` as above.
374
+ * - consent checks (`ConsentFreshness`): a per-request `AbortController`
375
+ * and `consent.stop()`; its session id.
271
376
  * - `serverReflexiveCandidate` (gathering): `protocol.close()`; otherwise
272
377
  * it ends by its retransmission timeout, and `stale()` drops the
273
- * candidate of an ended gather.
378
+ * candidate (or the failure) of an ended gather.
274
379
  * - TURN client requests: the `closing` signal and `TurnProtocol.close()`.
275
380
  * Regression tests: `tests/ice/check-cancel.test.ts`.
276
381
  */
@@ -343,241 +448,147 @@ class Connection {
343
448
  writable: true,
344
449
  value: []
345
450
  });
346
- Object.defineProperty(this, "queryConsentHandle", {
347
- enumerable: true,
348
- configurable: true,
349
- writable: true,
350
- value: void 0
351
- });
352
- /** RFC 7675 consent-to-send: application data may use the selected pair. */
353
- Object.defineProperty(this, "consentFresh", {
354
- enumerable: true,
355
- configurable: true,
356
- writable: true,
357
- value: false
358
- });
359
- /** Invalidates in-flight consent callbacks on restart / close / replace / expire. */
360
- Object.defineProperty(this, "consentSessionId", {
451
+ /** RFC 7675 consent freshness of the selected pair. */
452
+ Object.defineProperty(this, "consent", {
361
453
  enumerable: true,
362
454
  configurable: true,
363
455
  writable: true,
364
- value: 0
456
+ value: new consent_1.ConsentFreshness({
457
+ selected: () => this.nominated,
458
+ state: () => this.state,
459
+ setState: (state) => this.setState(state),
460
+ remoteGeneration: () => this.remoteGeneration,
461
+ remotePassword: () => this.remotePassword,
462
+ iceLite: () => this.iceLite,
463
+ integrityAlgorithm: () => this.options.messageIntegrity,
464
+ buildRequest: (pair) => this.buildRequest({
465
+ nominate: this.shouldNominateConsentRequest(pair),
466
+ nomination: this.consentNomination(pair),
467
+ localUsername: this.localUsername,
468
+ remoteUsername: this.remoteUsername,
469
+ iceControlling: this.iceControlling,
470
+ localCandidate: pair.localCandidate,
471
+ }),
472
+ })
365
473
  });
366
- Object.defineProperty(this, "consentExpiryTimer", {
474
+ /** Host, server-reflexive and relay gathering (`CandidateGatherer`). */
475
+ Object.defineProperty(this, "gatherer", {
367
476
  enumerable: true,
368
477
  configurable: true,
369
478
  writable: true,
370
- value: void 0
479
+ value: new candidateGatherer_1.CandidateGatherer({
480
+ options: () => this.options,
481
+ iceLite: () => this.iceLite,
482
+ generation: () => this.generation,
483
+ localUsername: () => this.localUsername,
484
+ protocols: () => this.protocols,
485
+ stunServers: () => this.stunServers,
486
+ turnServers: () => this.turnServers,
487
+ defaultStunServer: () => this.usesDefaultStunServer
488
+ ? { address: DEFAULT_STUN_SERVER, url: exports.DEFAULT_STUN_SERVER_URL }
489
+ : undefined,
490
+ isGathering: (generation) => this.isGathering(generation),
491
+ closing: () => this.closing.signal,
492
+ ensureProtocol: (protocol) => this.ensureProtocol(protocol),
493
+ pairLocalProtocol: (protocol) => this.pairLocalProtocol(protocol),
494
+ appendLocalCandidate: (candidate) => this.appendLocalCandidate(candidate),
495
+ emitCandidateError: (stale, generation, server, failure, local) => this.emitCandidateError(stale, generation, server, failure, local),
496
+ emitServerReached: (stale, generation, server) => this.emitServerReached(stale, generation, server),
497
+ })
371
498
  });
372
- Object.defineProperty(this, "consentRequestAbort", {
499
+ /**
500
+ * Settles when the background server-reflexive queries of the current
501
+ * generation end (see {@link Connection.waitForLocalCandidatesEnd}).
502
+ */
503
+ Object.defineProperty(this, "localCandidatesEndPromise", {
373
504
  enumerable: true,
374
505
  configurable: true,
375
506
  writable: true,
376
507
  value: void 0
377
508
  });
378
509
  /** ICE restart generation checked beside the selected current pair. */
379
- Object.defineProperty(this, "provisional", {
510
+ Object.defineProperty(this, "provisionalChecklist", {
380
511
  enumerable: true,
381
512
  configurable: true,
382
513
  writable: true,
383
- value: void 0
514
+ value: new provisional_1.ProvisionalChecklist({
515
+ closed: () => this.closed,
516
+ iceLite: () => this.iceLite,
517
+ iceControlling: () => this.iceControlling,
518
+ remoteIsLite: () => this.remoteIsLite,
519
+ localCandidatesEnd: () => this.localCandidatesEnd,
520
+ options: () => this.options,
521
+ protocols: () => this.protocols,
522
+ mdnsLookup: () => {
523
+ this.lookup ?? (this.lookup = new lookup_1.MdnsLookup());
524
+ return this.lookup;
525
+ },
526
+ isUncheckedPair: (pair) => this.isUncheckedPair(pair),
527
+ isWildcardProtocol: (protocol) => this.gatherer.isWildcardProtocol(protocol),
528
+ wildcardPathUncovered: (remoteCandidate) => this.gatherer.wildcardPathUncovered(remoteCandidate),
529
+ nominatesFullPeer: () => this.nominatesFullPeer(),
530
+ usesRegularNomination: () => this.usesRegularNomination(),
531
+ replacesWith: (pair) => this.replacesWith(pair),
532
+ regularNominationPairs: (pairs) => this.regularNominationPairs(pairs),
533
+ bestValidPair: (pairs) => this.bestValidPair(pairs),
534
+ outranks: (pair, other) => this.outranks(pair, other),
535
+ nominationDelayMs: () => this.nominationDelayMs,
536
+ buildRequest: (params) => this.buildRequest(params),
537
+ switchRole: (iceControlling) => this.switchRole(iceControlling),
538
+ })
384
539
  });
385
- /**
386
- * Server-reflexive candidates each UDP socket advertised in its last
387
- * gathering (one per distinct mapping its STUN servers returned).
388
- */
389
- Object.defineProperty(this, "reflexiveBySocket", {
540
+ Object.defineProperty(this, "onData", {
390
541
  enumerable: true,
391
542
  configurable: true,
392
543
  writable: true,
393
- value: new WeakMap()
544
+ value: new common_1.Event()
394
545
  });
395
- Object.defineProperty(this, "onData", {
546
+ Object.defineProperty(this, "stateChanged", {
396
547
  enumerable: true,
397
548
  configurable: true,
398
549
  writable: true,
399
550
  value: new common_1.Event()
400
551
  });
401
- Object.defineProperty(this, "stateChanged", {
552
+ Object.defineProperty(this, "onIceCandidate", {
402
553
  enumerable: true,
403
554
  configurable: true,
404
555
  writable: true,
405
556
  value: new common_1.Event()
406
557
  });
407
- Object.defineProperty(this, "onIceCandidate", {
558
+ /**
559
+ * A STUN server query or TURN allocation of the current generation's
560
+ * gathering failed (W3C `icecandidateerror`), synchronously and without
561
+ * changing the gathering: other servers and sockets go on, and gathering
562
+ * still completes. A server answering with an error gives its ERROR-CODE,
563
+ * once per local socket and generation. One that is not reached (timeout,
564
+ * `stunGatherTimeout`, DNS, connect or socket error) gives 701, once per
565
+ * server and generation and only when no local socket reached it (a STUN
566
+ * server is reported when the last socket's query ended). A TURN server's UDP attempt and its TCP fallback are
567
+ * one failure, reported when both failed (a server's error code wins over
568
+ * 701). A credential retry (401 / 438) that succeeds is not a failure.
569
+ * Nothing is fired for a replaced generation or after close (the event
570
+ * completes then). A STUN failure carries the host address of a socket
571
+ * that asked; a TURN one carries none. The built-in default STUN server (none
572
+ * configured, `useDefaultStunServer` not false) is named by the
573
+ * synthesized URL {@link DEFAULT_STUN_SERVER_URL} in `server.urls`.
574
+ */
575
+ Object.defineProperty(this, "onIceCandidateError", {
408
576
  enumerable: true,
409
577
  configurable: true,
410
578
  writable: true,
411
579
  value: new common_1.Event()
412
580
  });
413
- // RFC 7675 consent freshness
414
- Object.defineProperty(this, "queryConsent", {
581
+ /**
582
+ * A STUN or TURN server of the current generation's gathering answered:
583
+ * a STUN query or TURN allocation gave a candidate, or the server sent an
584
+ * error response (see {@link IceServerReachedInfo}). Synchronous; nothing
585
+ * is fired for a replaced generation or after close.
586
+ */
587
+ Object.defineProperty(this, "onIceServerReached", {
415
588
  enumerable: true,
416
589
  configurable: true,
417
590
  writable: true,
418
- value: () => {
419
- if (this.iceLite) {
420
- return;
421
- }
422
- // Invalidate any previous consent session before starting a new one.
423
- this.stopConsentLifecycle();
424
- const sessionId = this.consentSessionId;
425
- this.consentFresh = true;
426
- const handle = (0, helper_1.cancelable)(async (_, __, onCancel) => {
427
- let canceled = false;
428
- const cancelEvent = new AbortController();
429
- const clearConsentExpiry = () => {
430
- if (this.consentExpiryTimer === undefined) {
431
- return;
432
- }
433
- clearTimeout(this.consentExpiryTimer);
434
- this.consentExpiryTimer = undefined;
435
- };
436
- const refreshConsentExpiry = () => {
437
- // Only the active session may refresh the shared expiry timer.
438
- if (canceled || sessionId !== this.consentSessionId) {
439
- return;
440
- }
441
- clearConsentExpiry();
442
- this.consentExpiryTimer = setTimeout(() => {
443
- this.consentExpiryTimer = undefined;
444
- if (canceled || sessionId !== this.consentSessionId) {
445
- return;
446
- }
447
- if (this.state === "closed" || this.state === "failed") {
448
- return;
449
- }
450
- log("Consent to send expired");
451
- // Expire independently of request cadence / failure count (RFC 7675).
452
- this.consentFresh = false;
453
- this.consentSessionId++;
454
- this.consentRequestAbort?.abort();
455
- this.consentRequestAbort = undefined;
456
- if (this.queryConsentHandle === handle) {
457
- this.queryConsentHandle = undefined;
458
- }
459
- canceled = true;
460
- cancelEvent.abort();
461
- // Transport stays available for ICE restart; explicit close() uses "closed".
462
- this.setState("failed");
463
- }, iceBase_1.CONSENT_TIMEOUT * 1000);
464
- };
465
- onCancel.once(() => {
466
- canceled = true;
467
- // Avoid clearing a replacement session's timer/handle.
468
- if (sessionId === this.consentSessionId) {
469
- clearConsentExpiry();
470
- this.consentRequestAbort?.abort();
471
- this.consentRequestAbort = undefined;
472
- }
473
- cancelEvent.abort();
474
- if (this.queryConsentHandle === handle) {
475
- this.queryConsentHandle = undefined;
476
- }
477
- });
478
- // Initial ICE check success is the first valid consent response.
479
- refreshConsentExpiry();
480
- const randomizedConsentInterval = () => iceBase_1.CONSENT_INTERVAL * (0.8 + 0.4 * Math.random()) * 1000;
481
- // Cadence is measured between request *starts*, not response completions.
482
- let nextConsentAt = Date.now() + randomizedConsentInterval();
483
- const isTerminalState = () => this.state === "closed" || this.state === "failed";
484
- try {
485
- while (!isTerminalState() &&
486
- !canceled &&
487
- sessionId === this.consentSessionId) {
488
- await this.abortableDelay(Math.max(0, nextConsentAt - Date.now()), cancelEvent.signal);
489
- if (canceled ||
490
- isTerminalState() ||
491
- sessionId !== this.consentSessionId) {
492
- break;
493
- }
494
- // Fix next start time before awaiting any response (independent timers).
495
- nextConsentAt = Date.now() + randomizedConsentInterval();
496
- const nominated = this.nominated;
497
- if (!nominated) {
498
- break;
499
- }
500
- const pairId = nominated.id;
501
- const generation = this.remoteGeneration;
502
- const remotePassword = this.remotePassword;
503
- const { localUsername, remoteUsername, iceControlling } = this;
504
- const request = this.buildRequest({
505
- nominate: this.shouldNominateConsentRequest(nominated),
506
- localUsername,
507
- remoteUsername,
508
- iceControlling,
509
- localCandidate: nominated.localCandidate,
510
- });
511
- this.consentRequestAbort?.abort();
512
- const requestAbort = new AbortController();
513
- this.consentRequestAbort = requestAbort;
514
- nominated.consentRequestsSent++;
515
- nominated.requestsSent++;
516
- // RTT-aware wait (floor 500ms); independent of retransmissions: 0.
517
- const responseTimeout = (0, iceBase_1.consentResponseTimeoutMs)(nominated.rtt);
518
- const requestStartedAt = performance.now();
519
- // Do not await here: response wait must not stretch the 4–6s cadence.
520
- nominated.protocol
521
- .request(request, nominated.remoteAddr, Buffer.from(remotePassword, "utf8"), {
522
- retransmissions: 0,
523
- responseTimeout,
524
- signal: requestAbort.signal,
525
- onRequestSent: (attempt) => {
526
- if (attempt > 0) {
527
- nominated.retransmissionsSent++;
528
- }
529
- },
530
- })
531
- .then(() => {
532
- // Accept only responses for the current pair / generation / session.
533
- // Address / MESSAGE-INTEGRITY / response class are enforced in Transaction + protocol.
534
- if (sessionId !== this.consentSessionId || canceled) {
535
- return;
536
- }
537
- const state = this.state;
538
- if (state === "closed" || state === "failed") {
539
- return;
540
- }
541
- if (this.nominated?.id !== pairId) {
542
- return;
543
- }
544
- if (this.remoteGeneration !== generation) {
545
- return;
546
- }
547
- if (this.remotePassword !== remotePassword) {
548
- return;
549
- }
550
- const rtt = (performance.now() - requestStartedAt) / 1000; // seconds
551
- nominated.rtt = rtt;
552
- nominated.totalRoundTripTime += rtt;
553
- nominated.roundTripTimeMeasurements++;
554
- nominated.responsesReceived++;
555
- this.consentFresh = true;
556
- refreshConsentExpiry();
557
- if (state === "disconnected") {
558
- this.setState("connected");
559
- }
560
- })
561
- .catch((error) => {
562
- // Individual request loss is expected; keep monitoring (RFC 7675).
563
- if (sessionId === this.consentSessionId &&
564
- this.nominated?.id === pairId) {
565
- log("no stun response", error);
566
- }
567
- });
568
- }
569
- }
570
- catch (error) {
571
- // Abort during delay is normal on cancel / expire.
572
- }
573
- finally {
574
- if (sessionId === this.consentSessionId) {
575
- clearConsentExpiry();
576
- }
577
- }
578
- });
579
- this.queryConsentHandle = handle;
580
- }
591
+ value: new common_1.Event()
581
592
  });
582
593
  Object.defineProperty(this, "send", {
583
594
  enumerable: true,
@@ -616,8 +627,13 @@ class Connection {
616
627
  const result = {};
617
628
  const { remotePassword, remoteUsername, generation } = this;
618
629
  const localUsername = pair.localCandidate.ufrag ?? this.localUsername;
619
- // TCP pairs use regular nomination (see nominateTcpPairIfReady).
620
- const nominate = this.iceControlling && !this.remoteIsLite && !this.isTcpPair(pair);
630
+ // Semi-aggressive nomination: USE-CANDIDATE while nothing is selected
631
+ // and for a pair that outranks the selected one. Regular nomination
632
+ // (RegularNomination) and renomination (`SelectionReplacement.evaluate`) nominate
633
+ // with a separate check; an ordinary check carries nothing.
634
+ const nominate = this.usesSemiAggressiveNomination() &&
635
+ this.replacesWith(pair) &&
636
+ (!this.nominated || this.outranks(pair, this.nominated));
621
637
  const request = this.buildRequest({
622
638
  nominate,
623
639
  localUsername,
@@ -652,6 +668,7 @@ class Connection {
652
668
  // A cancelled check (its handle resolved, or the agent closed and
653
669
  // cancelled its transactions) changes nothing.
654
670
  if (signal.aborted || error instanceof exceptions_1.TransactionCancelled) {
671
+ this.checkCancelled(pair, remoteGeneration);
655
672
  r();
656
673
  return;
657
674
  }
@@ -698,16 +715,19 @@ class Connection {
698
715
  return;
699
716
  }
700
717
  // # success
701
- if (nominate || pair.remoteNominated) {
702
- // # nominated by agressive nomination or the remote party
718
+ // The peer's USE-CANDIDATE selects the pair only while this agent is
719
+ // controlled: one received before a role switch made it controlling is
720
+ // not a nomination any more (the peer is controlled now and waits for
721
+ // this agent's USE-CANDIDATE), so it nominates by itself below.
722
+ if (pair.remoteNominated && !this.iceControlling) {
723
+ // # nominated by the remote party
703
724
  pair.nominated = true;
704
725
  }
705
- else if (this.usesTcpRegularNomination(pair)) {
706
- // # nominated later by nominateTcpPairIfReady (from checkComplete)
707
- }
708
- else if (this.iceControlling && !this.nominating) {
709
- // # perform regular nomination
710
- this.nominating = true;
726
+ else if (this.iceControlling &&
727
+ this.remoteIsLite &&
728
+ !this.liteNominating) {
729
+ // # ICE-lite peer: nominate the first pair that succeeds
730
+ this.liteNominating = true;
711
731
  const request = this.buildRequest({
712
732
  nominate: true,
713
733
  localUsername,
@@ -729,7 +749,7 @@ class Connection {
729
749
  r();
730
750
  return;
731
751
  }
732
- this.nominating = false;
752
+ this.liteNominating = false;
733
753
  pair.updateState(iceBase_1.CandidatePairState.FAILED);
734
754
  this.checkComplete(pair);
735
755
  r();
@@ -741,6 +761,12 @@ class Connection {
741
761
  }
742
762
  pair.nominated = true;
743
763
  }
764
+ else if (nominate &&
765
+ this.iceControlling &&
766
+ this.remoteGeneration === remoteGeneration) {
767
+ // # semi-aggressive: the check that succeeded carried USE-CANDIDATE
768
+ pair.nominated = true;
769
+ }
744
770
  pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
745
771
  this.checkComplete(pair);
746
772
  r();
@@ -794,10 +820,10 @@ class Connection {
794
820
  */
795
821
  applyStunTurnServersFromOptions() {
796
822
  const { stunServers, turnServers } = (0, iceBase_1.normalizeIceServerOptions)(this.options);
797
- this.stunServers =
798
- stunServers.length > 0 || this.options.useDefaultStunServer === false
799
- ? stunServers
800
- : [DEFAULT_STUN_SERVER];
823
+ this.usesDefaultStunServer = !(stunServers.length > 0 || this.options.useDefaultStunServer === false);
824
+ this.stunServers = this.usesDefaultStunServer
825
+ ? [DEFAULT_STUN_SERVER]
826
+ : stunServers;
801
827
  this.turnServers = turnServers;
802
828
  }
803
829
  /** @deprecated The first of {@link Connection.stunServers}. */
@@ -875,12 +901,19 @@ class Connection {
875
901
  this.remoteCandidatesEndRequested = false;
876
902
  this.remoteResolutions.clear();
877
903
  this.localCandidatesEnd = false;
904
+ this.localCandidatesEndPromise = undefined;
878
905
  this.checksBegun = false;
906
+ this.schedulingStopped = false;
879
907
  this.state = "new";
880
908
  this.lookup?.close?.();
881
909
  this.lookup = undefined;
882
910
  this.nominated = undefined;
883
- this.nominating = false;
911
+ this.liteNominating = false;
912
+ // Taken before `provisionalChecklist.end()` drops the provisional checklist.
913
+ const hint = this.provisionalNominationHint();
914
+ this.nomination.reset();
915
+ this.selection.abort();
916
+ this.nominationHint = hint;
884
917
  this.cancelChecks();
885
918
  this.checkList = [];
886
919
  this.checkListDone = false;
@@ -897,8 +930,8 @@ class Connection {
897
930
  }
898
931
  }
899
932
  // Tear down consent timers/transactions; new credentials require a new session.
900
- this.stopConsentLifecycle();
901
- this.endProvisional();
933
+ this.consent.stop();
934
+ this.provisionalChecklist.end();
902
935
  }
903
936
  /**
904
937
  * Only the remote side restarted (new remote credentials in an answer to an
@@ -916,15 +949,18 @@ class Connection {
916
949
  this.checksBegun = false;
917
950
  this.state = "new";
918
951
  this.nominated = undefined;
919
- this.nominating = false;
952
+ this.liteNominating = false;
953
+ this.nomination.reset();
954
+ this.selection.abort();
955
+ this.nominationHint = undefined;
920
956
  this.cancelChecks();
921
957
  this.checkList = [];
922
958
  this.checkListDone = false;
923
959
  this.checkListState = new helper_1.PQueue();
924
960
  this.earlyChecks = [];
925
961
  this.earlyChecksDone = false;
926
- this.stopConsentLifecycle();
927
- this.endProvisional();
962
+ this.consent.stop();
963
+ this.provisionalChecklist.end();
928
964
  }
929
965
  /**
930
966
  * Stop the checks and nominations in flight for the checklist a restart
@@ -935,36 +971,16 @@ class Connection {
935
971
  this.remoteChecks = new AbortController();
936
972
  for (const pair of this.checkList)
937
973
  pair.handle?.resolve?.();
938
- }
939
- /**
940
- * Drop the provisional generation and stop the checks still in flight for
941
- * it (their retransmissions would outlive it).
942
- */
943
- endProvisional() {
944
- this.provisional?.checks.abort();
945
- this.provisional = undefined;
974
+ this.selection.clearRetries();
946
975
  }
947
976
  /** Accept provisional checks without changing the selected current pair. */
948
977
  stageLocalCredentials(usernameFragment, password, gatherOptions) {
949
978
  this.userHistory[usernameFragment] = password;
950
- this.endProvisional();
951
- this.provisional = {
952
- localUsername: usernameFragment,
953
- localPassword: password,
954
- gatherOptions,
955
- remoteCandidates: [],
956
- remoteCandidatesEnd: false,
957
- remoteCandidatesEndRequested: false,
958
- resolutions: new Set(),
959
- revision: 0,
960
- pairs: [],
961
- started: false,
962
- checks: new AbortController(),
963
- };
979
+ this.provisionalChecklist.stage(usernameFragment, password, gatherOptions);
964
980
  }
965
981
  discardStagedLocalCredentials(usernameFragment) {
966
982
  if (this.provisional?.localUsername === usernameFragment) {
967
- this.endProvisional();
983
+ this.provisionalChecklist.end();
968
984
  }
969
985
  if (usernameFragment !== this.localUsername) {
970
986
  delete this.userHistory[usernameFragment];
@@ -972,281 +988,17 @@ class Connection {
972
988
  }
973
989
  /** Remote credentials of the provisional generation (pranswer). */
974
990
  setProvisionalRemoteParams({ usernameFragment, password, }) {
975
- const generation = this.provisional;
976
- if (!generation)
977
- return;
978
- if (generation.remoteUsername === usernameFragment &&
979
- generation.remotePassword === password) {
980
- return;
981
- }
982
- // A replacement pranswer starts a new provisional checklist; candidates
983
- // still resolving for the replaced one are dropped by `revision`.
984
- generation.remoteUsername = usernameFragment;
985
- generation.remotePassword = password;
986
- generation.remoteCandidates = [];
987
- generation.remoteCandidatesEnd = false;
988
- generation.remoteCandidatesEndRequested = false;
989
- generation.resolutions.clear();
990
- generation.revision++;
991
- generation.checks.abort();
992
- generation.checks = new AbortController();
993
- generation.pairs = [];
994
- generation.nominated = undefined;
995
- generation.nominating = false;
991
+ this.provisionalChecklist.setRemoteParams({ usernameFragment, password });
996
992
  }
997
993
  async addProvisionalRemoteCandidate(remoteCandidate) {
998
- const generation = this.provisional;
999
- if (!generation || this.closed)
1000
- return;
1001
- const revision = generation.revision;
1002
- const current = () => !this.closed &&
1003
- this.provisional === generation &&
1004
- generation.revision === revision;
1005
- if (!remoteCandidate) {
1006
- if (generation.remoteCandidatesEnd ||
1007
- generation.remoteCandidatesEndRequested) {
1008
- return;
1009
- }
1010
- // Candidates that arrived before end-of-candidates finish first.
1011
- generation.remoteCandidatesEndRequested = true;
1012
- if (generation.resolutions.size > 0) {
1013
- await Promise.allSettled([...generation.resolutions]);
1014
- if (!current())
1015
- return;
1016
- }
1017
- generation.remoteCandidatesEnd = true;
1018
- return;
1019
- }
1020
- // RFC 8838: a completed generation takes no further candidates.
1021
- if (generation.remoteCandidatesEnd ||
1022
- generation.remoteCandidatesEndRequested) {
1023
- return;
1024
- }
1025
- if (remoteCandidate.host.includes(".local")) {
1026
- try {
1027
- if (!this.lookup) {
1028
- this.lookup = new lookup_1.MdnsLookup();
1029
- }
1030
- const resolution = this.lookup.lookup(remoteCandidate.host);
1031
- generation.resolutions.add(resolution);
1032
- try {
1033
- remoteCandidate.host = await resolution;
1034
- }
1035
- finally {
1036
- generation.resolutions.delete(resolution);
1037
- }
1038
- }
1039
- catch (error) {
1040
- return;
1041
- }
1042
- // The generation may have been replaced or completed while resolving.
1043
- if (!current() || generation.remoteCandidatesEnd)
1044
- return;
1045
- }
1046
- try {
1047
- (0, iceBase_1.validateRemoteCandidate)(remoteCandidate);
1048
- }
1049
- catch (error) {
1050
- return;
1051
- }
1052
- if (!current() ||
1053
- generation.remoteCandidates.some((c) => c.host === remoteCandidate.host &&
1054
- c.port === remoteCandidate.port &&
1055
- c.transport.toLowerCase() === remoteCandidate.transport.toLowerCase())) {
1056
- return;
1057
- }
1058
- generation.remoteCandidates.push(remoteCandidate);
1059
- for (const protocol of this.protocols) {
1060
- this.tryProvisionalPair(generation, protocol, remoteCandidate);
1061
- }
994
+ await this.provisionalChecklist.addRemoteCandidate(remoteCandidate);
1062
995
  }
1063
996
  /** Start checks for the provisional generation; the selected pair is kept. */
1064
997
  startProvisionalChecks() {
1065
- const generation = this.provisional;
1066
- if (!generation || generation.started)
1067
- return;
1068
- generation.started = true;
1069
- for (const remoteCandidate of generation.remoteCandidates) {
1070
- for (const protocol of this.protocols) {
1071
- this.tryProvisionalPair(generation, protocol, remoteCandidate);
1072
- }
1073
- }
1074
- for (const pair of generation.pairs) {
1075
- void this.checkProvisional(generation, pair);
1076
- }
998
+ this.provisionalChecklist.start();
1077
999
  }
1078
1000
  get provisionalNominated() {
1079
- return this.provisional?.nominated;
1080
- }
1081
- tryProvisionalPair(generation, protocol, remoteCandidate) {
1082
- if (!protocol.localCandidate?.canPairWith(remoteCandidate) ||
1083
- !this.allowsProvisional(generation, protocol) ||
1084
- (protocol.localCandidate.transport.toLowerCase() === "tcp" &&
1085
- protocol.localCandidate.tcptype === "passive" &&
1086
- remoteCandidate.type !== "prflx") ||
1087
- generation.pairs.some((pair) => pair.protocol === protocol &&
1088
- pair.remoteCandidate === remoteCandidate)) {
1089
- return;
1090
- }
1091
- const pair = new iceBase_1.CandidatePair(protocol, remoteCandidate, this.iceControlling);
1092
- // The provisional checklist admits the same pairs as the live one.
1093
- if (this.options.filterCandidatePair &&
1094
- !this.options.filterCandidatePair(pair)) {
1095
- return;
1096
- }
1097
- pair.updateState(iceBase_1.CandidatePairState.WAITING);
1098
- generation.pairs.push(pair);
1099
- if (generation.started)
1100
- void this.checkProvisional(generation, pair);
1101
- }
1102
- async checkProvisional(generation, pair, retry = true) {
1103
- const revision = generation.revision;
1104
- // A check belongs to one checklist: a replacement pranswer (new revision)
1105
- // or a replaced generation makes its outcome meaningless.
1106
- const belongs = () => this.provisional === generation &&
1107
- generation.revision === revision &&
1108
- generation.pairs.includes(pair);
1109
- if (
1110
- // An ICE-lite agent only answers checks (RFC 8445 §2.5), in the
1111
- // provisional generation as in the live one.
1112
- this.iceLite ||
1113
- !belongs() ||
1114
- !generation.started ||
1115
- !generation.remoteUsername ||
1116
- !generation.remotePassword ||
1117
- [
1118
- iceBase_1.CandidatePairState.IN_PROGRESS,
1119
- iceBase_1.CandidatePairState.SUCCEEDED,
1120
- ].includes(pair.state)) {
1121
- return;
1122
- }
1123
- pair.updateState(iceBase_1.CandidatePairState.IN_PROGRESS);
1124
- const nominate = this.iceControlling && !this.remoteIsLite;
1125
- const request = this.buildRequest({
1126
- nominate,
1127
- localUsername: generation.localUsername,
1128
- remoteUsername: generation.remoteUsername,
1129
- iceControlling: this.iceControlling,
1130
- localCandidate: pair.localCandidate,
1131
- });
1132
- try {
1133
- pair.requestsSent++;
1134
- const [, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(generation.remotePassword, "utf8"), {
1135
- retransmissions: pair.localCandidate.transport.toLowerCase() === "tcp" ? 0 : 4,
1136
- signal: generation.checks.signal,
1137
- });
1138
- pair.responsesReceived++;
1139
- if (!belongs())
1140
- return;
1141
- if (addr[0] !== pair.remoteAddr[0] || addr[1] !== pair.remoteAddr[1]) {
1142
- pair.updateState(iceBase_1.CandidatePairState.FAILED);
1143
- return;
1144
- }
1145
- }
1146
- catch (error) {
1147
- if (!belongs())
1148
- return;
1149
- const code = error.response?.getAttributeValue("ERROR-CODE")?.[0];
1150
- pair.updateState(iceBase_1.CandidatePairState.FAILED);
1151
- if (code === 487 && retry) {
1152
- this.switchRole(request.attributesKeys.includes("ICE-CONTROLLED"));
1153
- pair.updateState(iceBase_1.CandidatePairState.WAITING);
1154
- return this.checkProvisional(generation, pair, false);
1155
- }
1156
- return;
1157
- }
1158
- if (nominate || pair.remoteNominated)
1159
- pair.nominated = true;
1160
- pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
1161
- if (!pair.nominated &&
1162
- this.iceControlling &&
1163
- !generation.nominated &&
1164
- !generation.nominating) {
1165
- // Regular nomination (the peer is ICE-lite, so the checks carried no
1166
- // USE-CANDIDATE), as the live checklist does: nominate the first pair
1167
- // that succeeded with a check that carries it.
1168
- await this.nominateProvisional(generation, pair, belongs);
1169
- }
1170
- if (pair.nominated && !generation.nominated) {
1171
- log("provisional nominated", pair.toJSON());
1172
- generation.nominated = pair;
1173
- }
1174
- }
1175
- async nominateProvisional(generation, pair, belongs) {
1176
- generation.nominating = true;
1177
- const request = this.buildRequest({
1178
- nominate: true,
1179
- localUsername: generation.localUsername,
1180
- remoteUsername: generation.remoteUsername,
1181
- iceControlling: this.iceControlling,
1182
- localCandidate: pair.localCandidate,
1183
- });
1184
- try {
1185
- pair.requestsSent++;
1186
- await pair.protocol.request(request, pair.remoteAddr, Buffer.from(generation.remotePassword, "utf8"), {
1187
- retransmissions: pair.localCandidate.transport.toLowerCase() === "tcp" ? 0 : 4,
1188
- // endProvisional / a replacement pranswer stops it with the checks.
1189
- signal: generation.checks.signal,
1190
- });
1191
- pair.responsesReceived++;
1192
- if (belongs())
1193
- pair.nominated = true;
1194
- }
1195
- catch (error) {
1196
- log("provisional regular nomination failed", error);
1197
- }
1198
- finally {
1199
- if (belongs())
1200
- generation.nominating = false;
1201
- }
1202
- }
1203
- /** Incoming check for the provisional ufrag; never touches the current checklist. */
1204
- checkIncomingProvisional(generation, message, addr, protocol) {
1205
- // A socket the staged generation drops at the commit takes no pair.
1206
- if (!this.allowsProvisional(generation, protocol))
1207
- return;
1208
- // Only checks from the remote credentials of the current checklist count
1209
- // (a replacement pranswer replaced any earlier ones).
1210
- const txUsername = message.getAttributeValue("USERNAME");
1211
- const sender = typeof txUsername === "string"
1212
- ? decodeTxUsername(txUsername).localUsername
1213
- : undefined;
1214
- if (generation.remoteUsername && sender !== generation.remoteUsername) {
1215
- return;
1216
- }
1217
- const [host, port] = addr;
1218
- let remoteCandidate = generation.remoteCandidates.find((c) => c.host === host && c.port === port);
1219
- if (!remoteCandidate) {
1220
- remoteCandidate = new candidate_1.Candidate((0, helper_1.randomString)(10), 1, protocol.localCandidate?.transport ?? "udp", message.getAttributeValue("PRIORITY"), host, port, "prflx", undefined, undefined, protocol.localCandidate?.transport === "tcp"
1221
- ? (0, candidate_1.remoteTcpTypeForIncoming)(protocol.localCandidate.tcptype)
1222
- : undefined, undefined, undefined);
1223
- generation.remoteCandidates.push(remoteCandidate);
1224
- }
1225
- let pair = generation.pairs.find((p) => p.protocol === protocol && p.remoteCandidate === remoteCandidate);
1226
- if (!pair) {
1227
- pair = new iceBase_1.CandidatePair(protocol, remoteCandidate, this.iceControlling);
1228
- pair.updateState(iceBase_1.CandidatePairState.WAITING);
1229
- generation.pairs.push(pair);
1230
- }
1231
- pair.noteIncomingRequest(message.transactionIdHex);
1232
- pair.requestsReceived++;
1233
- pair.responsesSent++;
1234
- if (message.attributesKeys.includes("USE-CANDIDATE") &&
1235
- !this.iceControlling) {
1236
- pair.remoteNominated = true;
1237
- if (this.iceLite || pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
1238
- pair.nominated = true;
1239
- pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
1240
- generation.nominated ?? (generation.nominated = pair);
1241
- }
1242
- }
1243
- if (!this.iceLite &&
1244
- [
1245
- iceBase_1.CandidatePairState.WAITING,
1246
- iceBase_1.CandidatePairState.FAILED,
1247
- ].includes(pair.state)) {
1248
- void this.checkProvisional(generation, pair);
1249
- }
1001
+ return this.provisionalChecklist.nominated;
1250
1002
  }
1251
1003
  /** Called after restart, before re-gathering the chosen generation. */
1252
1004
  commitLocalCredentials(usernameFragment, password) {
@@ -1276,13 +1028,25 @@ class Connection {
1276
1028
  pair.handle?.resolve?.();
1277
1029
  }
1278
1030
  this.checkList = this.checkList.filter((pair) => !stale(pair.remoteCandidate));
1031
+ this.nomination.evaluate();
1279
1032
  }
1280
1033
  resetNominatedPair() {
1281
1034
  log("resetNominatedPair");
1282
1035
  this.nominated = undefined;
1283
- this.nominating = false;
1036
+ this.liteNominating = false;
1037
+ this.nomination.reset();
1038
+ this.selection.abort();
1039
+ this.nominationHint = undefined;
1284
1040
  // Drop old pair's consent timers/transactions; restarted when a new pair is nominated.
1285
- this.stopConsentLifecycle();
1041
+ this.consent.stop();
1042
+ }
1043
+ get remoteIce2() {
1044
+ return this.remoteIceOptions.includes("ice2");
1045
+ }
1046
+ setRemoteIceOptions(options) {
1047
+ log("setRemoteIceOptions", options);
1048
+ this.remoteIceOptions = [...options];
1049
+ this.remoteRenomination = options.includes("renomination");
1286
1050
  }
1287
1051
  setRemoteParams({ iceLite, usernameFragment, password, }) {
1288
1052
  log("setRemoteParams", { iceLite, usernameFragment, password });
@@ -1318,12 +1082,23 @@ class Connection {
1318
1082
  void Promise.allSettled([...previousTurn, ...excluded].map((protocol) => protocol.close()));
1319
1083
  // ICE restart keeps transport protocols; re-advertise their host candidates
1320
1084
  // with the new generation / ufrag before gathering additional addresses.
1085
+ for (const [family, wildcard] of this.gatherer.wildcardProtocols) {
1086
+ if (!this.protocols.includes(wildcard)) {
1087
+ // Closed with the excluded sockets, or still opening for the
1088
+ // replaced generation: a fresh one is opened if needed.
1089
+ this.gatherer.wildcardProtocols.delete(family);
1090
+ }
1091
+ }
1321
1092
  for (const protocol of this.protocols) {
1322
1093
  if (protocol.localCandidate) {
1323
1094
  protocol.localCandidate.generation = this.generation;
1324
1095
  protocol.localCandidate.ufrag = this.localUsername;
1325
- this.appendLocalCandidate(protocol.localCandidate);
1326
- for (const reflexive of this.reflexiveBySocket.get(protocol) ?? []) {
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) ?? []) {
1327
1102
  this.appendLocalCandidate(this.withGeneration(reflexive));
1328
1103
  }
1329
1104
  }
@@ -1331,27 +1106,54 @@ class Connection {
1331
1106
  // A family bound to an explicit interface address gathers only that
1332
1107
  // address, so the advertised host candidate is the socket's address.
1333
1108
  const address = (0, resolveHostAddresses_1.resolveHostAddresses)({
1334
- enumerated: (0, utils_1.getHostAddresses)(this.options.useIpv4, this.options.useIpv6, {
1109
+ enumerated: (0, hostInterfaces_1.getHostInterfaceAddresses)(this.options.useIpv4, this.options.useIpv6, {
1335
1110
  useLinkLocalAddress: this.options.useLinkLocalAddress,
1336
1111
  }),
1112
+ assigned: (0, hostInterfaces_1.getAssignedInterfaceAddresses)(),
1337
1113
  interfaceAddresses: this.options.interfaceAddresses,
1338
1114
  additionalHostAddresses: this.options.additionalHostAddresses,
1339
1115
  useIpv4: this.options.useIpv4,
1340
1116
  useIpv6: this.options.useIpv6,
1341
1117
  log,
1342
1118
  });
1343
- const candidatePromises = this.getCandidatePromises(address, this.options.stunGatherTimeout, generation);
1119
+ // The default-route address of each family: the source address of the
1120
+ // route to the configured STUN / TURN servers (none without one: no
1121
+ // other address is probed). Its host candidate gets the highest local preference, and its
1122
+ // socket is a representative of the family's server-reflexive queries.
1123
+ // Probed while the sockets bind: no server work waits for it.
1124
+ const defaultRoutes = Promise.race([
1125
+ (0, defaultRoute_1.getDefaultRouteAddresses)(this.options.useIpv4, this.options.useIpv6, [
1126
+ ...this.stunServers.map(([host]) => host),
1127
+ ...this.turnServers.map(({ address: [host] }) => host),
1128
+ ]),
1129
+ this.closedSignal.then(() => []),
1130
+ ]);
1131
+ const { primary, background } = this.gatherer.candidatePromises(address, this.options.stunGatherTimeout, generation, defaultRoutes);
1344
1132
  // close() ends the gathering at once: the continuations above close
1345
1133
  // whatever a server query still opens for a closed agent.
1346
- await Promise.race([
1347
- Promise.allSettled(candidatePromises),
1348
- this.closedSignal,
1349
- ]);
1134
+ await Promise.race([Promise.allSettled(primary), this.closedSignal]);
1350
1135
  // A later ICE restart (or close) owns the agent now: this gathering
1351
1136
  // neither completes that generation nor touches its state.
1352
1137
  if (!this.isGathering(generation))
1353
1138
  return;
1354
- this.localCandidatesEnd = true;
1139
+ const pending = background.filter(({ settled }) => !settled);
1140
+ if (pending.length === 0) {
1141
+ this.localCandidatesEnd = true;
1142
+ }
1143
+ else {
1144
+ // The other host sockets' server-reflexive candidates trickle in;
1145
+ // end-of-candidates follows the last of them.
1146
+ this.localCandidatesEndPromise = Promise.race([
1147
+ Promise.allSettled(pending.map(({ query }) => query)),
1148
+ this.closedSignal,
1149
+ ]).then(() => {
1150
+ if (!this.isGathering(generation))
1151
+ return;
1152
+ this.localCandidatesEnd = true;
1153
+ if (this.checksBegun)
1154
+ this.concludeCheckListIfExhausted();
1155
+ });
1156
+ }
1355
1157
  }
1356
1158
  // Gathering that finishes after connectivity checks began (an ICE restart
1357
1159
  // keeps gathering from its servers) must not overwrite their state: the
@@ -1359,6 +1161,17 @@ class Connection {
1359
1161
  if (this.state === "new" && !this.checksBegun)
1360
1162
  this.setState("completed");
1361
1163
  }
1164
+ /**
1165
+ * Resolves when the current generation's gathering has ended
1166
+ * (`localCandidatesEnd`): {@link Connection.gatherCandidates} returns once
1167
+ * the host sockets, the TURN allocations and the representative socket's
1168
+ * server-reflexive query are done, while the other host sockets' queries
1169
+ * continue and trickle through `onIceCandidate`. Also resolves when the
1170
+ * agent closes or restarts (the generation ends without its end).
1171
+ */
1172
+ async waitForLocalCandidatesEnd() {
1173
+ await this.localCandidatesEndPromise;
1174
+ }
1362
1175
  /**
1363
1176
  * Whether gathering started for `generation` still belongs to the agent:
1364
1177
  * no ICE restart replaced the generation and the agent is not closed.
@@ -1366,30 +1179,6 @@ class Connection {
1366
1179
  isGathering(generation) {
1367
1180
  return this.generation === generation && this.state !== "closed";
1368
1181
  }
1369
- /**
1370
- * Whether the provisional generation may use `protocol`: the staged
1371
- * generation drops the sockets its gather options exclude at the commit,
1372
- * so its checks never use them. A kept TURN allocation serves it only when
1373
- * the generation still uses that TURN server, credential and transport (any of its
1374
- * TURN servers): one whose server was removed or replaced (a credential
1375
- * rotation) is not part of it.
1376
- */
1377
- allowsProvisional(generation, protocol) {
1378
- const options = generation.gatherOptions ?? this.options;
1379
- if (!protocol.localCandidate ||
1380
- !(0, iceBase_1.isCandidateAllowedByGatherOptions)(protocol.localCandidate, options)) {
1381
- return false;
1382
- }
1383
- if (protocol instanceof protocol_2.StunOverTurnProtocol) {
1384
- const { configuredServer, username, password } = protocol.turn;
1385
- return (0, iceBase_1.normalizeIceServerOptions)(options).turnServers.some((server) => configuredServer[0] === server.address[0] &&
1386
- configuredServer[1] === server.address[1] &&
1387
- username === server.username &&
1388
- password === server.password &&
1389
- protocol.configuredTransport === server.transport);
1390
- }
1391
- return true;
1392
- }
1393
1182
  /** A copy of `candidate` labelled with the current generation and ufrag. */
1394
1183
  withGeneration(candidate) {
1395
1184
  return new candidate_1.Candidate(candidate.foundation, candidate.component, candidate.transport, candidate.priority, candidate.host, candidate.port, candidate.type, candidate.relatedAddress, candidate.relatedPort, candidate.tcptype, this.generation, this.localUsername);
@@ -1402,15 +1191,58 @@ class Connection {
1402
1191
  this.localCandidates.push(candidate);
1403
1192
  this.onIceCandidate.execute(candidate);
1404
1193
  }
1194
+ /**
1195
+ * Report a failed STUN query / TURN allocation of the gathering whose
1196
+ * `stale` is given (see onIceCandidateError). A failure that is not
1197
+ * reported (cancelled), belongs to a replaced generation or arrives after
1198
+ * close is dropped. A listener that throws does not stop the gathering.
1199
+ */
1200
+ emitCandidateError(stale, generation, server, failure, local) {
1201
+ if (!failure || stale() || this.closing.signal.aborted)
1202
+ return;
1203
+ const info = {
1204
+ server,
1205
+ ...(local ? { address: local.address, port: local.port } : {}),
1206
+ errorCode: failure.errorCode,
1207
+ errorText: failure.errorText,
1208
+ generation,
1209
+ };
1210
+ log("ice candidate error", {
1211
+ server: { ...server, urls: undefined },
1212
+ errorCode: info.errorCode,
1213
+ errorText: info.errorText,
1214
+ });
1215
+ try {
1216
+ this.onIceCandidateError.execute(info);
1217
+ }
1218
+ catch (error) {
1219
+ log("onIceCandidateError listener threw", error);
1220
+ }
1221
+ }
1222
+ /** Report that `server` answered the gathering whose `stale` is given. */
1223
+ emitServerReached(stale, generation, server) {
1224
+ if (stale() || this.closing.signal.aborted)
1225
+ return;
1226
+ try {
1227
+ this.onIceServerReached.execute({ server, generation });
1228
+ }
1229
+ catch (error) {
1230
+ log("onIceServerReached listener threw", error);
1231
+ }
1232
+ }
1405
1233
  ensureProtocol(protocol) {
1406
1234
  protocol.onRequestReceived.subscribe((msg, addr, data) => {
1407
1235
  if (msg.messageMethod !== const_1.methods.BINDING) {
1408
1236
  this.respondError(msg, addr, protocol, [400, "Bad Request"]);
1409
1237
  return;
1410
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.
1411
1243
  const txUsername = msg.getAttributeValue("USERNAME");
1412
1244
  // 相手にとってのremoteは自分にとってのlocal
1413
- const { remoteUsername: localUsername } = decodeTxUsername(txUsername);
1245
+ const { remoteUsername: localUsername } = (0, checkMessages_1.decodeTxUsername)(txUsername);
1414
1246
  const localPassword = this.userHistory[localUsername] ?? this.localPassword;
1415
1247
  // A check for the staged generation on a socket it drops at the commit
1416
1248
  // (a host socket under a relay-only policy, a TURN allocation whose
@@ -1420,7 +1252,7 @@ class Connection {
1420
1252
  if (staged &&
1421
1253
  localUsername === staged.localUsername &&
1422
1254
  localUsername !== this.localUsername &&
1423
- !this.allowsProvisional(staged, protocol)) {
1255
+ !this.provisionalChecklist.allows(staged, protocol)) {
1424
1256
  return;
1425
1257
  }
1426
1258
  const { iceControlling } = this;
@@ -1454,7 +1286,7 @@ class Connection {
1454
1286
  const response = new message_1.Message(const_1.methods.BINDING, const_1.classes.RESPONSE, msg.transactionId);
1455
1287
  response
1456
1288
  .setAttribute("XOR-MAPPED-ADDRESS", addr)
1457
- .addMessageIntegrity(Buffer.from(localPassword, "utf8"))
1289
+ .addIntegrity(Buffer.from(localPassword, "utf8"), (0, checkMessages_1.responseIntegrityMode)(msg))
1458
1290
  .addFingerprint();
1459
1291
  protocol.sendStun(response, addr).catch((e) => {
1460
1292
  log("sendStun error", e);
@@ -1463,7 +1295,7 @@ class Connection {
1463
1295
  if (provisional &&
1464
1296
  localUsername === provisional.localUsername &&
1465
1297
  localUsername !== this.localUsername) {
1466
- this.checkIncomingProvisional(provisional, msg, addr, protocol);
1298
+ this.provisionalChecklist.checkIncoming(provisional, msg, addr, protocol);
1467
1299
  return;
1468
1300
  }
1469
1301
  if (this.checkList.length === 0 && !this.earlyChecksDone) {
@@ -1473,7 +1305,7 @@ class Connection {
1473
1305
  this.checkIncoming(msg, addr, protocol);
1474
1306
  }
1475
1307
  });
1476
- protocol.onDataReceived.subscribe((data) => {
1308
+ protocol.onDataReceived.subscribe((data, addr) => {
1477
1309
  try {
1478
1310
  // Update statistics for the nominated pair
1479
1311
  const activePair = this.nominated;
@@ -1481,6 +1313,9 @@ class Connection {
1481
1313
  activePair.packetsReceived++;
1482
1314
  activePair.bytesReceived += data.length;
1483
1315
  }
1316
+ if (!this.iceControlling && addr) {
1317
+ this.selection.controlledDataReceived(protocol, addr);
1318
+ }
1484
1319
  this.onData.execute(data);
1485
1320
  }
1486
1321
  catch (error) {
@@ -1508,279 +1343,9 @@ class Connection {
1508
1343
  return;
1509
1344
  }
1510
1345
  log("selected tcp connection closed", nominated.toJSON());
1511
- this.stopConsentLifecycle();
1346
+ this.consent.stop();
1512
1347
  this.setState("failed");
1513
1348
  }
1514
- getCandidatePromises(addresses, timeout = 5, generation = this.generation) {
1515
- const candidatePromises = [];
1516
- // Each continuation below runs after an await: a socket or allocation it
1517
- // opened for a replaced generation (or a closed agent) is closed, and
1518
- // nothing is added to the current one.
1519
- const stale = () => !this.isGathering(generation);
1520
- const { stunServers, turnServers } = this;
1521
- const { interfaceAddresses } = this.options;
1522
- const gatherIceLite = this.iceLite;
1523
- const gatherRelayOnly = (0, iceBase_1.isRelayOnlyGathering)(this.options);
1524
- // TCP host candidates are kept per address like the UDP ones, but on
1525
- // their own: a restart that turned useTcp on gathers them for addresses
1526
- // whose UDP sockets were kept.
1527
- const tcpAddresses = addresses.filter((address) => !this.protocols.some((protocol) => protocol.localCandidate?.transport.toLowerCase() === "tcp" &&
1528
- protocol.localIp === address));
1529
- addresses = addresses.filter((address) => {
1530
- // ice restartで同じアドレスが追加されるのを防ぐ
1531
- if (this.protocols.find((protocol) => protocol.localIp === address)) {
1532
- return false;
1533
- }
1534
- // A family bound to an interface address has one UDP host socket; its
1535
- // localIp is the bound address, whose notation may differ (IPv6).
1536
- if ((0, common_1.interfaceAddress)(socketTypeOf(address), interfaceAddresses) ===
1537
- address &&
1538
- this.protocols.some((protocol) => protocol instanceof protocol_1.StunProtocol &&
1539
- protocol.localCandidate?.type === "host" &&
1540
- (0, net_1.isIPv4)(protocol.localCandidate.host) === (0, net_1.isIPv4)(address))) {
1541
- return false;
1542
- }
1543
- return true;
1544
- });
1545
- // An ICE restart keeps its UDP sockets. They are not re-created above, but
1546
- // their server-reflexive address is part of the new generation too, so
1547
- // the STUN query below runs for them as well.
1548
- const reusedStunProtocols = this.protocols.filter((protocol) => protocol instanceof protocol_1.StunProtocol &&
1549
- protocol.localCandidate?.type === "host" &&
1550
- protocol.localCandidate.transport === "udp");
1551
- const localStunPromises = gatherRelayOnly
1552
- ? []
1553
- : addresses.map(async (address) => {
1554
- // # create transport
1555
- const protocol = new protocol_1.StunProtocol();
1556
- this.ensureProtocol(protocol);
1557
- const boundInterface = (0, common_1.interfaceAddress)(socketTypeOf(address), interfaceAddresses);
1558
- try {
1559
- await protocol.connectionMade((0, net_1.isIPv4)(address), this.options.portRange, interfaceAddresses);
1560
- if (stale()) {
1561
- await protocol.close();
1562
- return;
1563
- }
1564
- // # add host candidate
1565
- // A socket bound to an interface address advertises that address:
1566
- // the peer sends its checks there. A wildcard socket advertises
1567
- // the gathered address (never 0.0.0.0 / ::).
1568
- const [boundHost, boundPort] = protocol.getExtraInfo();
1569
- let candidateHost = address;
1570
- if (boundInterface) {
1571
- candidateHost = stripZoneId(boundHost);
1572
- if (candidateHost !== address) {
1573
- log("host address differs from the bound interface address; advertise the bound one", address, candidateHost);
1574
- }
1575
- }
1576
- const candidateAddress = [candidateHost, boundPort];
1577
- protocol.localIp = candidateHost;
1578
- this.protocols.push(protocol);
1579
- log("protocol", protocol.localIp);
1580
- protocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("host", "udp", candidateAddress[0]), 1, "udp", (0, candidate_1.candidatePriority)("host", { transport: "udp" }), candidateAddress[0], candidateAddress[1], "host", undefined, undefined, undefined, this.generation, this.localUsername);
1581
- this.pairLocalProtocol(protocol);
1582
- this.appendLocalCandidate(protocol.localCandidate);
1583
- return protocol;
1584
- }
1585
- catch (error) {
1586
- if (boundInterface) {
1587
- // No host candidate for this family: advertising another
1588
- // address than the socket's would mislead the peer.
1589
- log("failed to bind UDP socket to interface address", boundInterface, error);
1590
- }
1591
- else {
1592
- log("error protocol STUN", error);
1593
- }
1594
- }
1595
- });
1596
- if (!gatherRelayOnly) {
1597
- candidatePromises.push(...localStunPromises.map((localPromise) => localPromise.then((protocol) => protocol?.localCandidate)));
1598
- }
1599
- if (!gatherRelayOnly && this.options.useTcp) {
1600
- const tcpCandidatePromises = tcpAddresses.map(async (address) => {
1601
- // Passive candidates open a listening TCP server; skip them when the
1602
- // agent only makes outbound connections (tcpPassive === false). Active
1603
- // candidates below still dial out, so direct TCP egress is unaffected.
1604
- if (this.options.tcpPassive !== false) {
1605
- const passiveProtocol = new tcpProtocol_1.TcpPassiveProtocol();
1606
- this.ensureProtocol(passiveProtocol);
1607
- await passiveProtocol.connectionMade(address, this.options.portRange);
1608
- if (stale()) {
1609
- await passiveProtocol.close();
1610
- return;
1611
- }
1612
- passiveProtocol.localIp = address;
1613
- passiveProtocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("host", "tcp", address), 1, "tcp", (0, candidate_1.candidatePriority)("host", {
1614
- transport: "tcp",
1615
- tcptype: "passive",
1616
- }), address, passiveProtocol.listeningPort, "host", undefined, undefined, "passive", this.generation, this.localUsername);
1617
- this.protocols.push(passiveProtocol);
1618
- this.appendLocalCandidate(passiveProtocol.localCandidate);
1619
- }
1620
- if (!gatherIceLite) {
1621
- const activeProtocol = new tcpProtocol_1.TcpActiveProtocol();
1622
- this.ensureProtocol(activeProtocol);
1623
- await activeProtocol.connectionMade(address);
1624
- if (stale()) {
1625
- await activeProtocol.close();
1626
- return;
1627
- }
1628
- activeProtocol.localIp = address;
1629
- activeProtocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("host", "tcp", address), 1, "tcp", (0, candidate_1.candidatePriority)("host", {
1630
- transport: "tcp",
1631
- tcptype: "active",
1632
- }), address, 9, "host", undefined, undefined, "active", this.generation, this.localUsername);
1633
- this.protocols.push(activeProtocol);
1634
- this.pairLocalProtocol(activeProtocol);
1635
- this.appendLocalCandidate(activeProtocol.localCandidate);
1636
- }
1637
- });
1638
- candidatePromises.push(...tcpCandidatePromises);
1639
- }
1640
- // A server-reflexive query of one socket to one STUN server, bounded by
1641
- // the STUN gather timeout; an unanswered one yields nothing.
1642
- const queryReflexive = async (protocol, server) => {
1643
- let timer;
1644
- const candidate = await Promise.race([
1645
- (0, iceBase_1.serverReflexiveCandidate)(protocol, server).catch((error) => {
1646
- log("query STUN server", server, error);
1647
- return undefined;
1648
- }),
1649
- new Promise((resolve) => {
1650
- timer = setTimeout(() => resolve(undefined), timeout * 1000);
1651
- }),
1652
- ]);
1653
- clearTimeout(timer);
1654
- return candidate;
1655
- };
1656
- // RFC 8445 §5.1.3: a mapping equal to one the socket already advertised
1657
- // (same base, same transport address) is redundant.
1658
- const sameMapping = (a, b) => a.host === b.host && a.port === b.port;
1659
- if (!gatherIceLite && !gatherRelayOnly && stunServers.length > 0) {
1660
- // Sockets kept across an ICE restart query every STUN server again.
1661
- // The mappings they already advertised are in the new generation from
1662
- // the start; a different fresh mapping (the NAT rebound) is added to
1663
- // it, and the fresh mappings replace the kept ones for the next restart.
1664
- const reusedReflexivePromises = reusedStunProtocols
1665
- .filter((protocol) => (0, net_1.isIPv4)(protocol.localCandidate.host))
1666
- .map(async (protocol) => {
1667
- const previous = this.reflexiveBySocket.get(protocol) ?? [];
1668
- const advertised = [...previous];
1669
- const fresh = [];
1670
- await Promise.all(stunServers.map(async (server) => {
1671
- const candidate = await queryReflexive(protocol, server);
1672
- if (!candidate || stale())
1673
- return;
1674
- if (!fresh.some((known) => sameMapping(known, candidate))) {
1675
- fresh.push(candidate);
1676
- }
1677
- if (advertised.some((known) => sameMapping(known, candidate))) {
1678
- return;
1679
- }
1680
- advertised.push(candidate);
1681
- this.appendLocalCandidate(candidate);
1682
- }));
1683
- if (stale())
1684
- return;
1685
- if (fresh.length > 0)
1686
- this.reflexiveBySocket.set(protocol, fresh);
1687
- return fresh.length > 0 ? fresh : previous;
1688
- })
1689
- .map((promise) => promise.catch((error) => {
1690
- log("query STUN server", error);
1691
- }));
1692
- candidatePromises.push(...reusedReflexivePromises);
1693
- // Every new IPv4 socket queries every STUN server in parallel.
1694
- const stunCandidatePromises = localStunPromises.map(async (protocolPromise) => {
1695
- const protocol = await protocolPromise;
1696
- if (!protocol?.localCandidate ||
1697
- !(0, net_1.isIPv4)(protocol.localCandidate.host))
1698
- return;
1699
- const advertised = [];
1700
- await Promise.all(stunServers.map(async (server) => {
1701
- const candidate = await queryReflexive(protocol, server);
1702
- if (!candidate || stale())
1703
- return;
1704
- if (advertised.some((known) => sameMapping(known, candidate))) {
1705
- return;
1706
- }
1707
- advertised.push(candidate);
1708
- this.reflexiveBySocket.set(protocol, advertised);
1709
- this.appendLocalCandidate(candidate);
1710
- })).catch((error) => {
1711
- log("query STUN server", error);
1712
- });
1713
- return advertised;
1714
- });
1715
- candidatePromises.push(...stunCandidatePromises);
1716
- }
1717
- if (!gatherIceLite) {
1718
- // Every TURN server gets its own allocation, made with its own
1719
- // credential and transport; one that fails does not stop the others.
1720
- const turnCandidatePromises = turnServers.map((server) => this.gatherRelayCandidate(server, gatherRelayOnly, stale).catch((error) => {
1721
- log("query TURN server", server.address, error);
1722
- }));
1723
- candidatePromises.push(...turnCandidatePromises);
1724
- }
1725
- return candidatePromises;
1726
- }
1727
- /**
1728
- * Allocate on one TURN server and add its relay candidate. A UDP
1729
- * allocation that fails falls back to TCP on the same server. An
1730
- * allocation that completes for a replaced generation (or a closed agent)
1731
- * is released.
1732
- */
1733
- async gatherRelayCandidate(server, relayOnly, stale) {
1734
- const { address, username, password, transport } = server;
1735
- const protocol = await (0, protocol_2.createStunOverTurnClient)({ address, username, password }, {
1736
- portRange: this.options.portRange,
1737
- interfaceAddresses: this.options.interfaceAddresses,
1738
- transport,
1739
- tlsOptions: this.options.turnTlsOptions,
1740
- connectTimeoutMs: (this.options.turnConnectTimeout ?? 8) * 1000,
1741
- udpFamily: this.options.turnUdpFamily,
1742
- signal: this.closing.signal,
1743
- }).catch(async (e) => {
1744
- // close() cancelled the allocation: no TCP fallback.
1745
- if (transport === "udp" && !this.closing.signal.aborted) {
1746
- return await (0, protocol_2.createStunOverTurnClient)({ address, username, password }, {
1747
- portRange: this.options.portRange,
1748
- interfaceAddresses: this.options.interfaceAddresses,
1749
- transport: "tcp",
1750
- connectTimeoutMs: (this.options.turnConnectTimeout ?? 8) * 1000,
1751
- signal: this.closing.signal,
1752
- });
1753
- }
1754
- else {
1755
- throw e;
1756
- }
1757
- });
1758
- if (stale()) {
1759
- // The allocation never joins a generation: release it (and its
1760
- // refresh timer) instead of keeping a second one alive.
1761
- await protocol.close();
1762
- return;
1763
- }
1764
- protocol.configuredTransport = transport;
1765
- this.ensureProtocol(protocol);
1766
- this.protocols.push(protocol);
1767
- const candidateAddress = protocol.turn.relayedAddress;
1768
- // The related address of a relay candidate is the address the TURN
1769
- // server saw the agent at. A relay-only policy hides the agent's
1770
- // addresses from the peer, so it advertises the unspecified address
1771
- // and port 9 instead (RFC 8839 §5.1), in SDP and trickle alike.
1772
- const relatedAddress = relayOnly
1773
- ? [(0, net_1.isIPv4)(candidateAddress[0]) ? "0.0.0.0" : "::", 9]
1774
- : protocol.turn.mappedAddress;
1775
- log("turn candidateAddress", candidateAddress);
1776
- protocol.localCandidate = new candidate_1.Candidate((0, candidate_1.candidateFoundation)("relay", "udp", candidateAddress[0]), 1, "udp", (0, candidate_1.candidatePriority)("relay"), candidateAddress[0], candidateAddress[1], "relay", relatedAddress[0], relatedAddress[1], undefined, this.generation, this.localUsername);
1777
- // An allocation that completes after the remote candidates arrived
1778
- // (early signaling, or an ICE restart that allocates afresh) pairs
1779
- // with them; a connect() already running schedules the new pairs.
1780
- this.pairLocalProtocol(protocol);
1781
- this.appendLocalCandidate(protocol.localCandidate);
1782
- return protocol.localCandidate;
1783
- }
1784
1349
  async connect() {
1785
1350
  // """
1786
1351
  // Perform ICE handshake.
@@ -1813,6 +1378,8 @@ class Connection {
1813
1378
  }
1814
1379
  this.earlyChecks = [];
1815
1380
  this.earlyChecksDone = true;
1381
+ // Arms the wait for a preferred pair even while the checklist is empty.
1382
+ this.nomination.evaluate();
1816
1383
  if (this.iceLite) {
1817
1384
  if (!this.nominated) {
1818
1385
  let res = iceBase_1.ICE_FAILED;
@@ -1835,25 +1402,42 @@ class Connection {
1835
1402
  for (;;) {
1836
1403
  if (this.state === "closed")
1837
1404
  break;
1405
+ // A selection that may still be replaced: the checks of the pairs that
1406
+ // outrank it go on in `SelectionReplacement.checkOutrankingPairs`.
1407
+ if (this.nominated && this.iceControlling && this.replacesSelection()) {
1408
+ break;
1409
+ }
1838
1410
  if (!this.schedulingChecks())
1839
1411
  break;
1840
1412
  await timers.setTimeout(20);
1841
1413
  }
1414
+ this.schedulingStopped = true;
1842
1415
  // # wait for completion
1843
1416
  let res = iceBase_1.ICE_FAILED;
1844
- while (this.checkList.length > 0 && res === iceBase_1.ICE_FAILED) {
1417
+ // The nomination may still wait for a pair an incoming check forms
1418
+ // (`NominationHint`), even with an empty checklist.
1419
+ while ((this.checkList.length > 0 || this.nomination.waiting) &&
1420
+ res === iceBase_1.ICE_FAILED) {
1845
1421
  res = await this.checkListState.get();
1846
1422
  log("checkListState", res);
1847
1423
  }
1848
1424
  // # cancel remaining checks
1425
+ // (but those of pairs that may still replace the selection)
1426
+ const selected = this.nominated;
1427
+ const keepsChecking = !!selected && this.iceControlling && this.replacesSelection();
1849
1428
  for (const check of this.checkList) {
1429
+ if (keepsChecking &&
1430
+ this.replacesWith(check) &&
1431
+ this.outranks(check, selected)) {
1432
+ continue;
1433
+ }
1850
1434
  check.handle?.resolve?.();
1851
1435
  }
1852
1436
  if (res !== iceBase_1.ICE_COMPLETED) {
1853
1437
  throw new Error("ICE negotiation failed");
1854
1438
  }
1855
1439
  // # start consent freshness tests
1856
- this.queryConsent();
1440
+ this.consent.start();
1857
1441
  this.setState("connected");
1858
1442
  }
1859
1443
  unfreezeInitial() {
@@ -1910,30 +1494,30 @@ class Connection {
1910
1494
  return false;
1911
1495
  }
1912
1496
  /**
1913
- * Stop consent request cadence, expiry timer, and outstanding transactions.
1914
- * Does not change ICE state by itself.
1497
+ * Mirror libwebrtc semi-aggressive nomination (not required by RFC 7675):
1498
+ * attach USE-CANDIDATE to consent checks of the selected pair when we are
1499
+ * controlling and the remote is ICE-lite, or we nominate semi-aggressively
1500
+ * (a peer that became controlled after a role conflict, or lost the
1501
+ * nominating response, learns the selection from them).
1915
1502
  */
1916
- stopConsentLifecycle() {
1917
- this.consentSessionId++;
1918
- this.consentFresh = false;
1919
- if (this.consentExpiryTimer !== undefined) {
1920
- clearTimeout(this.consentExpiryTimer);
1921
- this.consentExpiryTimer = undefined;
1922
- }
1923
- this.consentRequestAbort?.abort();
1924
- this.consentRequestAbort = undefined;
1925
- const handle = this.queryConsentHandle;
1926
- this.queryConsentHandle = undefined;
1927
- // Resolve after clearing the field so a stale onCancel cannot wipe a replacement.
1928
- handle?.resolve?.();
1503
+ shouldNominateConsentRequest(pair) {
1504
+ return (this.iceControlling &&
1505
+ this.nominated?.id === pair.id &&
1506
+ (this.remoteIsLite || this.usesSemiAggressiveNomination()));
1929
1507
  }
1930
1508
  /**
1931
- * ICE-lite interop only (not required by RFC 7675): mirror libwebrtc
1932
- * semi-aggressive nomination — attach USE-CANDIDATE when we are controlling,
1933
- * the remote is ICE-lite, and the target is the current selected pair.
1509
+ * Renomination: the NOMINATION value consent checks of the selected pair
1510
+ * carry, so the peer keeps (or learns) the selection. A pair selected
1511
+ * without a renomination of this agent (the peer nominated it while this
1512
+ * agent was controlled) takes the next value.
1934
1513
  */
1935
- shouldNominateConsentRequest(pair) {
1936
- return (this.iceControlling && this.remoteIsLite && this.nominated?.id === pair.id);
1514
+ consentNomination(pair) {
1515
+ if (!this.usesRenomination() || this.nominated?.id !== pair.id) {
1516
+ return undefined;
1517
+ }
1518
+ if (pair.nomination === 0)
1519
+ pair.nomination = this.selection.nextNominationValue();
1520
+ return pair.nomination;
1937
1521
  }
1938
1522
  canSendApplicationData() {
1939
1523
  if (!this.nominated) {
@@ -1946,24 +1530,7 @@ class Connection {
1946
1530
  if (this.iceLite) {
1947
1531
  return true;
1948
1532
  }
1949
- return this.consentFresh;
1950
- }
1951
- abortableDelay(ms, signal) {
1952
- return new Promise((resolve, reject) => {
1953
- if (signal.aborted) {
1954
- reject(new DOMException("The operation was aborted", "AbortError"));
1955
- return;
1956
- }
1957
- const timer = setTimeout(() => {
1958
- signal.removeEventListener("abort", onAbort);
1959
- resolve();
1960
- }, ms);
1961
- const onAbort = () => {
1962
- clearTimeout(timer);
1963
- reject(new DOMException("The operation was aborted", "AbortError"));
1964
- };
1965
- signal.addEventListener("abort", onAbort, { once: true });
1966
- });
1533
+ return this.consent.fresh;
1967
1534
  }
1968
1535
  async close() {
1969
1536
  // """
@@ -1971,17 +1538,19 @@ class Connection {
1971
1538
  // """
1972
1539
  this.closed = true;
1973
1540
  this.setState("closed");
1541
+ this.onIceCandidateError.complete();
1542
+ this.onIceServerReached.complete();
1974
1543
  this.signalClosed();
1975
1544
  this.closing.abort();
1976
1545
  this.cancelChecks();
1977
- this.endProvisional();
1546
+ this.provisionalChecklist.end();
1978
1547
  // Before the first await: a pending mDNS lookup is cancelled here, so no
1979
1548
  // response arriving while the protocols close adds a remote candidate.
1980
1549
  this.lookup?.close?.();
1981
1550
  this.lookup = undefined;
1982
1551
  this.remoteResolutions.clear();
1983
1552
  // # stop consent freshness tests
1984
- this.stopConsentLifecycle();
1553
+ this.consent.stop();
1985
1554
  // # stop check list
1986
1555
  if (this.checkList && !this.checkListDone) {
1987
1556
  this.checkListState.put(new Promise((r) => {
@@ -1989,7 +1558,15 @@ class Connection {
1989
1558
  }));
1990
1559
  }
1991
1560
  this.nominated = undefined;
1992
- for (const protocol of this.protocols) {
1561
+ this.liteNominating = false;
1562
+ this.nomination.reset();
1563
+ this.selection.abort();
1564
+ this.nominationHint = undefined;
1565
+ const pendingWildcards = [
1566
+ ...this.gatherer.wildcardProtocols.values(),
1567
+ ].filter((protocol) => !this.protocols.includes(protocol));
1568
+ this.gatherer.wildcardProtocols.clear();
1569
+ for (const protocol of [...this.protocols, ...pendingWildcards]) {
1993
1570
  if (protocol.close) {
1994
1571
  await protocol.close();
1995
1572
  }
@@ -2031,6 +1608,7 @@ class Connection {
2031
1608
  return;
2032
1609
  }
2033
1610
  this.remoteCandidatesEnd = true;
1611
+ this.nomination.evaluate();
2034
1612
  return;
2035
1613
  }
2036
1614
  // RFC 8838: a completed generation takes no further candidates.
@@ -2107,10 +1685,92 @@ class Connection {
2107
1685
  return pair;
2108
1686
  }
2109
1687
  applyIceControlling(iceControlling) {
1688
+ const becameControlling = !this._iceControlling && iceControlling;
1689
+ if (this._iceControlling !== iceControlling) {
1690
+ this.invalidateNominations();
1691
+ this.selection.clearRetries();
1692
+ // USE-CANDIDATE received while controlled came from a peer that was
1693
+ // controlling then; as the controlling agent this one nominates itself.
1694
+ if (iceControlling) {
1695
+ for (const pair of [
1696
+ ...this.checkList,
1697
+ ...(this.provisional?.pairs ?? []),
1698
+ ]) {
1699
+ pair.remoteNominated = false;
1700
+ pair.remoteNomination = 0;
1701
+ }
1702
+ }
1703
+ }
2110
1704
  this._iceControlling = iceControlling;
2111
1705
  for (const pair of this.checkList) {
2112
1706
  pair.iceControlling = iceControlling;
2113
1707
  }
1708
+ if (becameControlling)
1709
+ this.confirmSelections();
1710
+ }
1711
+ /**
1712
+ * The agent became controlling with a pair already selected (live or
1713
+ * provisional), e.g. one the peer nominated while this agent was
1714
+ * controlled. The selection stays (RFC 8445 §8.1.1 allows no other pair),
1715
+ * but the peer, controlled now, may still wait for a nomination: send
1716
+ * USE-CANDIDATE for that pair, repeated on timeouts as a nomination is.
1717
+ * A peer that selected the pair already keeps it.
1718
+ */
1719
+ confirmSelections() {
1720
+ if (!this.nominatesFullPeer())
1721
+ return;
1722
+ const live = this.nominated;
1723
+ if (live && this.state !== "closed" && this.checkList.includes(live)) {
1724
+ void this.confirmSelection((signal) => this.sendNomination(live, signal, this.consentNomination(live)), () => this.nominated === live && this.state !== "closed");
1725
+ }
1726
+ const generation = this.provisional;
1727
+ const provisional = generation?.nominated;
1728
+ if (generation && provisional && generation.pairs.includes(provisional)) {
1729
+ void this.confirmSelection((signal) => this.provisionalChecklist.nominate(generation, provisional, AbortSignal.any([generation.checks.signal, signal])), () => this.provisional === generation &&
1730
+ generation.nominated === provisional);
1731
+ }
1732
+ }
1733
+ async confirmSelection(send, selected) {
1734
+ const abort = new AbortController();
1735
+ this.selectionConfirmations.add(abort);
1736
+ try {
1737
+ for (let attempt = 1; attempt <= regularNomination_1.NOMINATION_ATTEMPTS; attempt++) {
1738
+ const outcome = await send(abort.signal);
1739
+ if (abort.signal.aborted || !selected() || !this.iceControlling) {
1740
+ return;
1741
+ }
1742
+ if (outcome === "unanswered")
1743
+ continue;
1744
+ // 487: the peer is controlling and wins; it nominates.
1745
+ if (outcome === "role-conflict")
1746
+ this.switchRole(false);
1747
+ return;
1748
+ }
1749
+ }
1750
+ catch (error) {
1751
+ log("confirm selection failed", error);
1752
+ }
1753
+ finally {
1754
+ this.selectionConfirmations.delete(abort);
1755
+ }
1756
+ }
1757
+ /**
1758
+ * The role changed: a nomination in flight (live or provisional) was sent
1759
+ * as the controlling agent and must not select a pair, fail one, or fail
1760
+ * the agent under the new role. Its transaction stops; a controlling agent
1761
+ * later nominates afresh.
1762
+ */
1763
+ invalidateNominations() {
1764
+ this.liteNominating = false;
1765
+ this.nomination.invalidate();
1766
+ this.selection.abort();
1767
+ for (const abort of this.selectionConfirmations)
1768
+ abort.abort();
1769
+ this.selectionConfirmations.clear();
1770
+ if (this.provisional) {
1771
+ this.provisional.liteNominating = false;
1772
+ this.provisional.nomination.invalidate();
1773
+ }
2114
1774
  }
2115
1775
  switchRole(iceControlling) {
2116
1776
  log("switch role", iceControlling);
@@ -2121,10 +1781,15 @@ class Connection {
2121
1781
  }
2122
1782
  this.applyIceControlling(iceControlling);
2123
1783
  this.sortCheckList();
1784
+ // Only a controlling agent nominates: start (or stop) waiting for it.
1785
+ this.nomination.evaluate();
1786
+ this.provisional?.nomination.evaluate();
1787
+ this.selection.evaluate();
2124
1788
  }
2125
1789
  checkComplete(pair) {
2126
1790
  pair.handle = undefined;
2127
1791
  if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
1792
+ this.selection.forgetRetry(pair);
2128
1793
  // Updating the Nominated Flag
2129
1794
  // https://www.rfc-editor.org/rfc/rfc8445#section-7.3.1.5,
2130
1795
  // Once the nominated flag is set for a component of a data stream, it
@@ -2141,31 +1806,41 @@ class Connection {
2141
1806
  this.checkList.includes(pair) &&
2142
1807
  (pair.remoteCandidate.ufrag == undefined ||
2143
1808
  pair.remoteCandidate.ufrag === this.remoteUsername) &&
2144
- this.nominated == undefined) {
2145
- log("nominated", pair.toJSON());
1809
+ // One selection, except that semi-aggressive nomination and
1810
+ // renomination replace it with a better nominated pair
1811
+ // (`SelectionReplacement.replaces`).
1812
+ (this.nominated == undefined || this.selection.replaces(pair))) {
1813
+ const previous = this.nominated;
1814
+ log(previous ? "selected pair replaced" : "nominated", pair.toJSON(), {
1815
+ previous: previous?.toJSON(),
1816
+ });
2146
1817
  this.nominated = pair;
2147
- this.nominating = false;
1818
+ this.liteNominating = false;
1819
+ this.nomination.stop();
2148
1820
  // RFC 7675 section 5.1: the successful connectivity check that
2149
1821
  // selected the pair is its initial consent, so data may flow at once
2150
1822
  // instead of waiting for the consent lifecycle to start.
2151
- this.consentFresh = true;
1823
+ this.consent.fresh = true;
2152
1824
  this.pruneTcpConnections(pair);
2153
1825
  // After resetNominatedPair / renomination while already connected,
2154
1826
  // restart consent freshness on the new selected pair.
2155
1827
  if (!this.iceLite &&
2156
1828
  (this.state === "connected" || this.state === "completed")) {
2157
- this.queryConsent();
1829
+ this.consent.start();
2158
1830
  }
2159
1831
  // 8.1.2. Updating States
2160
1832
  // The agent MUST remove all Waiting and Frozen pairs in the check
2161
1833
  // list and triggered check queue for the same component as the
2162
- // nominated pairs for that media stream.
1834
+ // nominated pairs for that media stream. A controlling agent that
1835
+ // may replace the selection keeps the pairs that outrank it.
1836
+ const keepsChecking = this.iceControlling && this.replacesSelection();
2163
1837
  for (const p of this.checkList) {
2164
1838
  if (p.component === pair.component &&
2165
1839
  [
2166
1840
  iceBase_1.CandidatePairState.WAITING,
2167
1841
  iceBase_1.CandidatePairState.FROZEN,
2168
- ].includes(p.state)) {
1842
+ ].includes(p.state) &&
1843
+ !(keepsChecking && this.replacesWith(p) && this.outranks(p, pair))) {
2169
1844
  p.updateState(iceBase_1.CandidatePairState.FAILED);
2170
1845
  }
2171
1846
  }
@@ -2179,6 +1854,11 @@ class Connection {
2179
1854
  this.checkListState.put(new Promise((r) => r(iceBase_1.ICE_COMPLETED)));
2180
1855
  this.checkListDone = true;
2181
1856
  }
1857
+ if (this.iceControlling && this.replacesSelection()) {
1858
+ this.selection.evaluate();
1859
+ void this.selection.checkOutrankingPairs();
1860
+ this.selection.scheduleRetries();
1861
+ }
2182
1862
  return;
2183
1863
  }
2184
1864
  log("not completed", pair.toJSON());
@@ -2190,9 +1870,21 @@ class Connection {
2190
1870
  }
2191
1871
  }
2192
1872
  }
2193
- this.nominateTcpPairIfReady();
2194
- // A nomination request is still in flight; its result decides the outcome.
2195
- if (this.nominating) {
1873
+ this.nomination.evaluate();
1874
+ this.selection.evaluate();
1875
+ this.selection.scheduleRetries();
1876
+ this.concludeCheckListIfExhausted();
1877
+ }
1878
+ /**
1879
+ * Fail the check list once no pair can succeed and no nomination can still
1880
+ * select one. Background gathering and remote trickle both delay this.
1881
+ */
1882
+ concludeCheckListIfExhausted() {
1883
+ if (this.nominated ||
1884
+ this.liteNominating ||
1885
+ this.selection.nominating ||
1886
+ this.nomination.inFlight ||
1887
+ this.nomination.waiting) {
2196
1888
  return;
2197
1889
  }
2198
1890
  {
@@ -2222,6 +1914,28 @@ class Connection {
2222
1914
  }));
2223
1915
  }
2224
1916
  }
1917
+ /**
1918
+ * A check of the live checklist cancelled before its outcome (the
1919
+ * checklist completed, `connect` cancels the remaining checks) leaves the
1920
+ * pair Waiting instead of In-Progress, so the peer's checks on it still
1921
+ * trigger one (7.2.1.4): a controlled agent that selected a lower pair can
1922
+ * then follow a later nomination of this one. A nomination already received
1923
+ * for it is checked at once (its triggering check came while the cancelled
1924
+ * one was still in flight). A generation that ended or a closed agent
1925
+ * changes nothing.
1926
+ */
1927
+ checkCancelled(pair, remoteGeneration) {
1928
+ if (pair.state !== iceBase_1.CandidatePairState.IN_PROGRESS ||
1929
+ this.state === "closed" ||
1930
+ this.remoteGeneration !== remoteGeneration ||
1931
+ !this.checkList.includes(pair)) {
1932
+ return;
1933
+ }
1934
+ pair.updateState(iceBase_1.CandidatePairState.WAITING);
1935
+ if (pair.remoteNominated && !this.iceControlling) {
1936
+ pair.handle = this.checkStart(pair);
1937
+ }
1938
+ }
2225
1939
  /**
2226
1940
  * 487 / 401 retry of a check: the retry is cancelled with the check it
2227
1941
  * replaces (its handle) and, through checkStart, with the generation.
@@ -2234,97 +1948,256 @@ class Connection {
2234
1948
  isTcpPair(pair) {
2235
1949
  return pair.localCandidate.transport.toLowerCase() === "tcp";
2236
1950
  }
2237
- /**
2238
- * Aggressive nomination lets each side settle on whichever TCP connection
2239
- * finished first; the two sides can then pick different connections and
2240
- * pruning destroys the peer's choice. For TCP the controlling agent instead
2241
- * nominates exactly one valid pair (RFC 8445 §8.1.1 regular nomination).
2242
- */
2243
- usesTcpRegularNomination(pair) {
2244
- return this.iceControlling && !this.remoteIsLite && this.isTcpPair(pair);
2245
- }
2246
1951
  checkRequestOptions(pair) {
2247
1952
  const onRequestSent = (attempt) => {
2248
1953
  if (attempt > 0) {
2249
1954
  pair.retransmissionsSent++;
2250
1955
  }
2251
1956
  };
1957
+ const integrityAlgorithm = this.options.messageIntegrity;
2252
1958
  if (this.isTcpPair(pair)) {
2253
1959
  // RFC 5389 §7.2.2: no retransmissions over a reliable transport.
2254
1960
  return {
2255
1961
  retransmissions: 0,
2256
1962
  responseTimeout: const_1.TCP_CHECK_RESPONSE_TIMEOUT_MS,
2257
1963
  onRequestSent,
1964
+ integrityAlgorithm,
2258
1965
  };
2259
1966
  }
2260
- return { retransmissions: 4, onRequestSent };
1967
+ return { retransmissions: 4, onRequestSent, integrityAlgorithm };
1968
+ }
1969
+ /** The agent is controlling and both agents are full ICE. */
1970
+ nominatesFullPeer() {
1971
+ return this.iceControlling && !this.remoteIsLite && !this.iceLite;
2261
1972
  }
2262
1973
  /**
2263
- * Controlling side: nominate the highest-priority TCP pair once every
2264
- * higher-priority TCP pair has finished its check, so the choice does not
2265
- * depend on which connection happened to complete first.
1974
+ * Both agents advertised renomination (`IceOptions.renomination`): the
1975
+ * controlling agent nominates with NOMINATION values instead of
1976
+ * USE-CANDIDATE, whatever `IceOptions.nomination` says.
2266
1977
  */
2267
- nominateTcpPairIfReady() {
2268
- if (!this.iceControlling ||
2269
- this.remoteIsLite ||
2270
- this.nominated ||
2271
- this.nominating) {
2272
- return;
2273
- }
2274
- for (const pair of this.checkList) {
2275
- if (!this.isTcpPair(pair)) {
2276
- continue;
2277
- }
2278
- if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
2279
- this.nominateTcpPair(pair);
2280
- return;
2281
- }
2282
- if (pair.state !== iceBase_1.CandidatePairState.FAILED) {
2283
- // A higher-priority pair may still succeed.
2284
- return;
1978
+ usesRenomination() {
1979
+ return (this.nominatesFullPeer() &&
1980
+ !!this.options.renomination &&
1981
+ this.remoteRenomination);
1982
+ }
1983
+ /**
1984
+ * `nomination: "regular"`: RFC 8445 §8.1.1 regular nomination for every
1985
+ * transport. A check that succeeds only makes its pair valid;
1986
+ * `RegularNomination` later picks one valid pair and nominates it once
1987
+ * with a separate USE-CANDIDATE check.
1988
+ */
1989
+ usesRegularNomination() {
1990
+ return (this.nominatesFullPeer() &&
1991
+ this.options.nomination === "regular" &&
1992
+ !this.usesRenomination());
1993
+ }
1994
+ /**
1995
+ * The default, as libwebrtc: checks carry USE-CANDIDATE until a pair is
1996
+ * selected and afterwards for pairs that outrank the selected one, so the
1997
+ * first pair that succeeds is selected at once and a higher-priority pair
1998
+ * that succeeds later (a TURN/UDP candidate trickled after a TURN/TCP one
1999
+ * connected) replaces it. A first-success-wins nomination would keep the
2000
+ * lower-priority pair for the whole session.
2001
+ */
2002
+ usesSemiAggressiveNomination() {
2003
+ return (this.nominatesFullPeer() &&
2004
+ this.options.nomination !== "regular" &&
2005
+ !this.usesRenomination());
2006
+ }
2007
+ /**
2008
+ * The controlling agent may move the selection to a higher-priority pair
2009
+ * (semi-aggressive nomination, renomination): checks of pairs that outrank
2010
+ * the selected one go on after the first selection.
2011
+ */
2012
+ replacesSelection() {
2013
+ return this.usesSemiAggressiveNomination() || this.usesRenomination();
2014
+ }
2015
+ /**
2016
+ * A pair semi-aggressive nomination and renomination may select: not an
2017
+ * ICE-TCP pair (each TCP pair is its own connection, and nominating more
2018
+ * than one could leave the agents on different connections after pruning;
2019
+ * TCP pairs keep regular nomination, see `regularNominationPairs`), nor
2020
+ * one the agent never checks (forceTurn).
2021
+ */
2022
+ replacesWith(pair) {
2023
+ return !this.isTcpPair(pair) && !this.isUncheckedPair(pair);
2024
+ }
2025
+ /**
2026
+ * The pairs `RegularNomination` nominates from: every pair with
2027
+ * `nomination: "regular"`, otherwise the ICE-TCP pairs (as before
2028
+ * semi-aggressive nomination, #721).
2029
+ */
2030
+ regularNominationPairs(pairs) {
2031
+ return this.usesRegularNomination()
2032
+ ? pairs
2033
+ : pairs.filter((pair) => this.isTcpPair(pair));
2034
+ }
2035
+ /** `IceOptions.nominationDelayMs`, or its default when unset or invalid. */
2036
+ get nominationDelayMs() {
2037
+ const delay = this.options.nominationDelayMs;
2038
+ return delay !== undefined && Number.isFinite(delay) && delay >= 0
2039
+ ? delay
2040
+ : regularNomination_1.DEFAULT_NOMINATION_DELAY_MS;
2041
+ }
2042
+ /** A pair the agent never checks itself (forceTurn keeps it from the schedule). */
2043
+ isUncheckedPair(pair) {
2044
+ return !!this.options.forceTurn && pair.protocol.type === protocol_1.StunProtocol.type;
2045
+ }
2046
+ /** The highest-priority valid pair of `pairs`. */
2047
+ bestValidPair(pairs) {
2048
+ let best;
2049
+ for (const pair of pairs) {
2050
+ if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED &&
2051
+ (!best || this.outranks(pair, best))) {
2052
+ best = pair;
2285
2053
  }
2286
2054
  }
2055
+ return best;
2056
+ }
2057
+ outranks(pair, other) {
2058
+ return ((0, iceBase_1.compareCandidatePairPriority)(pair.localCandidate, pair.remoteCandidate, other.localCandidate, other.remoteCandidate, this.iceControlling) > 0);
2059
+ }
2060
+ /**
2061
+ * The live checklist's side of regular nomination (`RegularNomination`):
2062
+ * the controlling agent nominates the best valid pair once the checklist
2063
+ * is quiet (see `decideNomination`).
2064
+ */
2065
+ liveNominationHost() {
2066
+ return {
2067
+ active: () => this.nominatesFullPeer() && !this.nominated && this.state !== "closed",
2068
+ checking: () => this.checksBegun,
2069
+ pairs: () => this.regularNominationPairs(this.checkList),
2070
+ remoteCandidatesEnd: () => this.remoteCandidatesEnd,
2071
+ localCandidatesEnd: () => this.localCandidatesEnd,
2072
+ delayMs: () => this.nominationDelayMs,
2073
+ unchecked: (pair) => this.isUncheckedPair(pair),
2074
+ outranks: (pair, other) => this.outranks(pair, other),
2075
+ preferred: () => {
2076
+ const hint = this.nominationHint;
2077
+ if (!hint ||
2078
+ // Semi-aggressive nomination and renomination may replace the
2079
+ // selection; the hint belongs to regular nomination.
2080
+ !this.usesRegularNomination() ||
2081
+ hint.localUsername !== this.localUsername ||
2082
+ hint.remoteUsername !== this.remoteUsername ||
2083
+ hint.remotePassword !== this.remotePassword ||
2084
+ // The commit closed the pair's socket (a TURN allocation an ICE
2085
+ // restart replaces, an excluded host socket): the path is gone for
2086
+ // the peer too, so the usual rules choose.
2087
+ !this.protocols.includes(hint.protocol)) {
2088
+ return undefined;
2089
+ }
2090
+ return (pair) => (0, regularNomination_1.pairKey)(pair) === hint.key;
2091
+ },
2092
+ owns: (pair) => this.state !== "closed" && this.checkList.includes(pair),
2093
+ send: (pair, signal) => this.sendNomination(pair, signal),
2094
+ nominated: (pair) => {
2095
+ pair.nominated = true;
2096
+ this.checkComplete(pair);
2097
+ },
2098
+ rejected: (pair) => {
2099
+ // The peer did not select this pair: only it fails, and
2100
+ // checkComplete nominates the next one.
2101
+ pair.updateState(iceBase_1.CandidatePairState.FAILED);
2102
+ this.checkComplete(pair);
2103
+ },
2104
+ // RFC 8445 §7.2.5.1: the peer is controlling too and wins; the
2105
+ // nomination was not accepted. Become controlled: the pair stays
2106
+ // valid and the peer nominates.
2107
+ roleConflict: () => this.switchRole(false),
2108
+ abandoned: (pair) => this.nominationAbandoned(pair),
2109
+ // The valid pair it waited for may be gone (another remote generation
2110
+ // dropped): the checklist may have failed meanwhile.
2111
+ deadlinePassed: () => this.concludeCheckListIfExhausted(),
2112
+ };
2287
2113
  }
2288
- nominateTcpPair(pair) {
2289
- this.nominating = true;
2290
- const generation = this.remoteGeneration;
2114
+ /**
2115
+ * Send the USE-CANDIDATE check for a live `pair` (see `NominationOutcome`),
2116
+ * or with `nomination` the renomination check that carries that
2117
+ * NOMINATION value instead.
2118
+ */
2119
+ async sendNomination(pair, signal, nomination) {
2291
2120
  const request = this.buildRequest({
2292
- nominate: true,
2121
+ nominate: nomination === undefined,
2122
+ nomination,
2293
2123
  localUsername: pair.localCandidate.ufrag ?? this.localUsername,
2294
2124
  remoteUsername: this.remoteUsername,
2295
2125
  iceControlling: this.iceControlling,
2296
2126
  localCandidate: pair.localCandidate,
2297
2127
  });
2298
2128
  pair.requestsSent++;
2299
- pair.protocol
2300
- .request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), { ...this.checkRequestOptions(pair), signal: this.remoteChecks.signal })
2301
- .then(() => {
2302
- if (this.isStaleNomination(pair, generation)) {
2303
- return;
2304
- }
2129
+ try {
2130
+ await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), {
2131
+ ...this.checkRequestOptions(pair),
2132
+ signal: AbortSignal.any([this.remoteChecks.signal, signal]),
2133
+ });
2305
2134
  pair.responsesReceived++;
2306
- pair.nominated = true;
2307
- this.nominating = false;
2308
- this.checkComplete(pair);
2309
- }, (error) => {
2310
- if (this.isStaleNomination(pair, generation)) {
2311
- return;
2312
- }
2313
- log("tcp nomination failed", pair.toJSON(), error);
2314
- this.nominating = false;
2315
- pair.updateState(iceBase_1.CandidatePairState.FAILED);
2316
- this.checkComplete(pair);
2317
- });
2135
+ return "nominated";
2136
+ }
2137
+ catch (error) {
2138
+ log("nomination failed", pair.toJSON(), error);
2139
+ if ((0, checkMessages_1.isRoleConflict)(error))
2140
+ return "role-conflict";
2141
+ return error instanceof exceptions_1.TransactionTimeout ? "unanswered" : "rejected";
2142
+ }
2143
+ }
2144
+ /**
2145
+ * No attempt of a USE-CANDIDATE check was answered, or the pair a
2146
+ * provisional nomination may have selected (`NominationHint`) failed or
2147
+ * never appeared. A request may still have reached the peer, and a
2148
+ * controlled agent keeps the first pair
2149
+ * nominated to it (RFC 8445 §8.1.1): nominating another pair could leave
2150
+ * the two agents on different pairs. The agent nominates nothing else,
2151
+ * connect() rejects and the agent fails (an ICE restart starts over), as a
2152
+ * consent expiry does.
2153
+ */
2154
+ nominationAbandoned(pair) {
2155
+ pair?.updateState(iceBase_1.CandidatePairState.FAILED);
2156
+ if (!this.checkListDone) {
2157
+ this.checkListDone = true;
2158
+ this.checkListState.put(new Promise((r) => r(regularNomination_1.ICE_NOMINATION_ABANDONED)));
2159
+ }
2160
+ this.setState("failed");
2161
+ }
2162
+ /**
2163
+ * At the restart that ends the provisional checklist (a final answer): the
2164
+ * pair it nominated, or sent a USE-CANDIDATE to that the peer did not
2165
+ * refuse (see `NominationHint`).
2166
+ */
2167
+ provisionalNominationHint() {
2168
+ const generation = this.provisional;
2169
+ const pair = generation?.nominated ?? generation?.nomination.maybeSelected;
2170
+ if (!generation?.remoteUsername || !generation.remotePassword || !pair) {
2171
+ return undefined;
2172
+ }
2173
+ return {
2174
+ localUsername: generation.localUsername,
2175
+ remoteUsername: generation.remoteUsername,
2176
+ remotePassword: generation.remotePassword,
2177
+ key: (0, regularNomination_1.pairKey)(pair),
2178
+ protocol: pair.protocol,
2179
+ };
2318
2180
  }
2319
- /** The agent was closed or restarted while the nomination was in flight. */
2181
+ /** The agent was closed or restarted while the ICE-lite nomination was in flight. */
2320
2182
  isStaleNomination(pair, generation) {
2321
2183
  return (this.state === "closed" ||
2322
2184
  this.remoteGeneration !== generation ||
2323
2185
  !this.checkList.includes(pair));
2324
2186
  }
2325
2187
  addPair(pair) {
2188
+ const best = this.bestValidPair(this.checkList);
2326
2189
  this.checkList.push(pair);
2327
2190
  this.sortCheckList();
2191
+ this.nomination.pairAdded(pair, best);
2192
+ // A pair that may replace the selection is checked after it too.
2193
+ const selected = this.nominated;
2194
+ if (selected &&
2195
+ this.iceControlling &&
2196
+ this.replacesSelection() &&
2197
+ this.replacesWith(pair) &&
2198
+ this.outranks(pair, selected)) {
2199
+ void this.selection.checkOutrankingPairs();
2200
+ }
2328
2201
  }
2329
2202
  // 7.2. STUN Server Procedures
2330
2203
  // 7.2.1.3、7.2.1.4、および7.2.1.5
@@ -2333,7 +2206,7 @@ class Connection {
2333
2206
  // Handle a successful incoming check.
2334
2207
  // """
2335
2208
  const txUsername = message.getAttributeValue("USERNAME");
2336
- const { remoteUsername: localUsername } = decodeTxUsername(txUsername);
2209
+ const { remoteUsername: localUsername } = (0, checkMessages_1.decodeTxUsername)(txUsername);
2337
2210
  // find remote candidate
2338
2211
  let remoteCandidate;
2339
2212
  const [host, port] = addr;
@@ -2371,9 +2244,13 @@ class Connection {
2371
2244
  remotePassword: this.remotePassword,
2372
2245
  generation: this.generation,
2373
2246
  });
2247
+ const nomination = (0, checkMessages_1.receivedNomination)(message);
2248
+ if (nomination > 0 && !this.iceControlling) {
2249
+ // We don't un-nominate a pair: keep the larger nomination.
2250
+ pair.remoteNomination = Math.max(pair.remoteNomination, nomination);
2251
+ }
2374
2252
  if (this.iceLite) {
2375
- if (message.attributesKeys.includes("USE-CANDIDATE") &&
2376
- !this.iceControlling) {
2253
+ if (nomination > 0 && !this.iceControlling) {
2377
2254
  pair.remoteNominated = true;
2378
2255
  pair.nominated = true;
2379
2256
  pair.updateState(iceBase_1.CandidatePairState.SUCCEEDED);
@@ -2389,8 +2266,9 @@ class Connection {
2389
2266
  pair.handle = this.checkStart(pair);
2390
2267
  }
2391
2268
  // 7.2.1.5. Updating the Nominated Flag
2392
- if (message.attributesKeys.includes("USE-CANDIDATE") &&
2393
- !this.iceControlling) {
2269
+ // (USE-CANDIDATE, or a NOMINATION value with renomination; a pair
2270
+ // already selected may be replaced, see `SelectionReplacement.replaces`)
2271
+ if (nomination > 0 && !this.iceControlling) {
2394
2272
  pair.remoteNominated = true;
2395
2273
  if (pair.state === iceBase_1.CandidatePairState.SUCCEEDED) {
2396
2274
  pair.nominated = true;
@@ -2398,7 +2276,35 @@ class Connection {
2398
2276
  }
2399
2277
  }
2400
2278
  }
2401
- tryPair(protocol, remoteCandidate) {
2279
+ /**
2280
+ * @param admit after a selection that may still be replaced, only pairs
2281
+ * that could replace it join the checklist.
2282
+ */
2283
+ tryPair(protocol, remoteCandidate, admit = this.admitsPair(), routeChecked = false) {
2284
+ if (!routeChecked && this.gatherer.isWildcardProtocol(protocol)) {
2285
+ void this.gatherer
2286
+ .wildcardPathUncovered(remoteCandidate)
2287
+ .then((uncovered) => {
2288
+ // As pairLocalProtocol: once a pair is selected (which also ends
2289
+ // the checklist) only a selection that may still be replaced
2290
+ // takes more pairs.
2291
+ const replaceable = !!this.nominated && this.iceControlling && this.replacesSelection();
2292
+ if (uncovered &&
2293
+ ((!this.nominated && !this.checkListDone) || replaceable) &&
2294
+ this.state !== "closed" &&
2295
+ this.protocols.includes(protocol) &&
2296
+ this.remoteCandidates.includes(remoteCandidate)) {
2297
+ this.tryPair(protocol, remoteCandidate, this.admitsPair(), true);
2298
+ this.sortCheckList();
2299
+ const pair = this.findPair(protocol, remoteCandidate);
2300
+ if (this.schedulingStopped &&
2301
+ pair?.state === iceBase_1.CandidatePairState.WAITING) {
2302
+ pair.handle = this.checkStart(pair);
2303
+ }
2304
+ }
2305
+ });
2306
+ return;
2307
+ }
2402
2308
  if (protocol.localCandidate?.canPairWith(remoteCandidate) &&
2403
2309
  !(protocol.localCandidate.transport.toLowerCase() === "tcp" &&
2404
2310
  protocol.localCandidate.tcptype === "passive" &&
@@ -2409,41 +2315,43 @@ class Connection {
2409
2315
  !this.options.filterCandidatePair(pair)) {
2410
2316
  return;
2411
2317
  }
2318
+ if (admit && !admit(pair))
2319
+ return;
2412
2320
  pair.updateState(iceBase_1.CandidatePairState.WAITING);
2413
2321
  this.addPair(pair);
2414
2322
  }
2415
2323
  }
2324
+ /** See `tryPair`: undefined admits every pair. */
2325
+ admitsPair() {
2326
+ const selected = this.nominated;
2327
+ if (!selected || !this.iceControlling || !this.replacesSelection()) {
2328
+ return undefined;
2329
+ }
2330
+ return (pair) => this.replacesWith(pair) && this.outranks(pair, selected);
2331
+ }
2416
2332
  /**
2417
2333
  * Pair a local candidate gathered after remote candidates arrived (a late
2418
2334
  * TURN allocation, a slow host socket) with them.
2419
2335
  */
2420
2336
  pairLocalProtocol(protocol) {
2421
2337
  // RFC 8445 §8.1.2: once a pair is selected, the check list takes no more
2422
- // Waiting pairs, so a candidate gathered later starts no check.
2423
- if (this.nominated || this.checkListDone || this.state === "closed") {
2338
+ // Waiting pairs, so a candidate gathered later starts no check. A
2339
+ // selection that may still be replaced (semi-aggressive nomination,
2340
+ // renomination) takes them: a late TURN/UDP allocation may outrank a
2341
+ // TURN/TCP pair selected before it.
2342
+ if (this.state === "closed")
2343
+ return;
2344
+ const replaceable = !!this.nominated && this.iceControlling && this.replacesSelection();
2345
+ if ((this.nominated || this.checkListDone) && !replaceable) {
2424
2346
  return;
2425
2347
  }
2426
2348
  for (const remoteCandidate of this.remoteCandidates) {
2427
2349
  this.tryPair(protocol, remoteCandidate);
2428
2350
  }
2429
2351
  }
2430
- buildRequest({ nominate, remoteUsername, localUsername, iceControlling, localCandidate, }) {
2431
- const txUsername = encodeTxUsername({ remoteUsername, localUsername });
2432
- const request = new message_1.Message(const_1.methods.BINDING, const_1.classes.REQUEST);
2433
- request.setAttribute("USERNAME", txUsername).setAttribute("PRIORITY", (0, candidate_1.candidatePriority)("prflx", {
2434
- transport: localCandidate?.transport,
2435
- tcptype: localCandidate?.tcptype,
2436
- }));
2437
- if (iceControlling) {
2438
- request.setAttribute("ICE-CONTROLLING", this.tieBreaker);
2439
- if (nominate) {
2440
- request.setAttribute("USE-CANDIDATE", null);
2441
- }
2442
- }
2443
- else {
2444
- request.setAttribute("ICE-CONTROLLED", this.tieBreaker);
2445
- }
2446
- return request;
2352
+ /** A connectivity check from this agent (`buildCheckRequest`). */
2353
+ buildRequest(params) {
2354
+ return (0, checkMessages_1.buildCheckRequest)({ ...params, tieBreaker: this.tieBreaker });
2447
2355
  }
2448
2356
  pruneTcpConnections(selectedPair) {
2449
2357
  for (const protocol of this.protocols) {
@@ -2467,7 +2375,7 @@ class Connection {
2467
2375
  const response = new message_1.Message(request.messageMethod, const_1.classes.ERROR, request.transactionId);
2468
2376
  response
2469
2377
  .setAttribute("ERROR-CODE", errorCode)
2470
- .addMessageIntegrity(Buffer.from(localPassword, "utf8"))
2378
+ .addIntegrity(Buffer.from(localPassword, "utf8"), (0, checkMessages_1.responseIntegrityMode)(request))
2471
2379
  .addFingerprint();
2472
2380
  protocol.sendStun(response, addr).catch((e) => {
2473
2381
  log("sendStun error", e);
@@ -2475,14 +2383,4 @@ class Connection {
2475
2383
  }
2476
2384
  }
2477
2385
  exports.Connection = Connection;
2478
- const encodeTxUsername = ({ remoteUsername, localUsername, }) => {
2479
- return `${remoteUsername}:${localUsername}`;
2480
- };
2481
- const decodeTxUsername = (txUsername) => {
2482
- const [remoteUsername, localUsername] = txUsername.split(":");
2483
- return { remoteUsername, localUsername };
2484
- };
2485
- const socketTypeOf = (address) => ((0, net_1.isIPv4)(address) ? "udp4" : "udp6");
2486
- /** Candidates carry no IPv6 zone id (e.g. `fe80::1%eth0`). */
2487
- const stripZoneId = (address) => address.split("%")[0];
2488
2386
  //# sourceMappingURL=ice.js.map