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
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RTCDtlsParameters = exports.RTCDtlsFingerprint = exports.RTCCertificate = exports.DtlsStates = exports.RTCDtlsTransport = void 0;
3
+ exports.RTCDtlsParameters = exports.RTCDtlsFingerprint = exports.RTCCertificate = exports.DtlsStates = exports.RTCDtlsTransport = exports.RTCError = exports.DTLS_ALERT_SEND_TIMEOUT_MS = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
5
  const promises_1 = require("timers/promises");
6
6
  const helper_1 = require("../helper");
@@ -9,7 +9,76 @@ const dtls_1 = require("../imports/dtls");
9
9
  const rtp_1 = require("../imports/rtp");
10
10
  const stats_1 = require("../media/stats");
11
11
  const utils_1 = require("../utils");
12
+ /**
13
+ * Upper bound (ms) for waiting until close_notify / a fatal alert has been
14
+ * handed to ICE in {@link RTCDtlsTransport.stop}; it adds directly to the
15
+ * time `RTCPeerConnection.close()` takes.
16
+ */
17
+ exports.DTLS_ALERT_SEND_TIMEOUT_MS = 100;
18
+ /**
19
+ * Minimal `RTCError` (W3C webrtc-pc §10.1) for the DTLS failures that
20
+ * {@link RTCDtlsTransport} reports with its `error` event.
21
+ *
22
+ * - `"fingerprint-failure"`: the remote certificate matched none of the
23
+ * fingerprints of the remote description. `receivedAlert` / `sentAlert` are
24
+ * null, as the spec defines them only for `"dtls-failure"`, although werift
25
+ * still sends a fatal `bad_certificate` (42) to the peer, which in turn
26
+ * reports `"dtls-failure"` with `receivedAlert: 42`.
27
+ * - `"dtls-failure"`: any other DTLS failure, e.g. a fatal alert received
28
+ * (`receivedAlert`) or sent (`sentAlert`).
29
+ */
30
+ class RTCError extends Error {
31
+ constructor(init, message) {
32
+ super(message);
33
+ Object.defineProperty(this, "errorDetail", {
34
+ enumerable: true,
35
+ configurable: true,
36
+ writable: true,
37
+ value: void 0
38
+ });
39
+ /**
40
+ * `"dtls-failure"` only: the fatal alert description received from the
41
+ * peer, otherwise null.
42
+ */
43
+ Object.defineProperty(this, "receivedAlert", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: void 0
48
+ });
49
+ /**
50
+ * `"dtls-failure"` only: the fatal alert description sent to the peer,
51
+ * otherwise null.
52
+ */
53
+ Object.defineProperty(this, "sentAlert", {
54
+ enumerable: true,
55
+ configurable: true,
56
+ writable: true,
57
+ value: void 0
58
+ });
59
+ this.name = "OperationError";
60
+ this.errorDetail = init.errorDetail;
61
+ this.receivedAlert = init.receivedAlert ?? null;
62
+ this.sentAlert = init.sentAlert ?? null;
63
+ }
64
+ }
65
+ exports.RTCError = RTCError;
12
66
  const log = (0, rtp_1.debug)("werift:packages/webrtc/src/transport/dtls.ts");
67
+ /**
68
+ * Internal: the remote certificate matched none of the remote fingerprints
69
+ * (reported as `errorDetail: "fingerprint-failure"`). Other verification
70
+ * errors (no certificate, no usable fingerprint) stay `"dtls-failure"`.
71
+ */
72
+ class FingerprintMismatchError extends Error {
73
+ constructor() {
74
+ super("remote certificate fingerprint mismatch");
75
+ this.name = "FingerprintMismatchError";
76
+ }
77
+ }
78
+ /** The RTCError for a failed check of the remote certificate. */
79
+ const certificateVerificationError = (reason) => reason instanceof FingerprintMismatchError
80
+ ? new RTCError({ errorDetail: "fingerprint-failure" }, reason.message)
81
+ : new RTCError({ errorDetail: "dtls-failure", sentAlert: dtls_1.AlertDesc.BadCertificate }, String(reason));
13
82
  function formatDtlsVersion(version) {
14
83
  if (!version) {
15
84
  return;
@@ -201,6 +270,25 @@ class RTCDtlsTransport {
201
270
  writable: true,
202
271
  value: void 0
203
272
  });
273
+ /**
274
+ * Fires once when the transport becomes `failed`:
275
+ * - the remote certificate matched none of the remote fingerprints:
276
+ * `errorDetail: "fingerprint-failure"` (`receivedAlert` / `sentAlert`
277
+ * null; a fatal `bad_certificate` is still sent to the peer);
278
+ * - a fatal alert received from the peer, or sent by this side (e.g.
279
+ * `bad_certificate` for a certificate it could not verify for another
280
+ * reason), and other DTLS errors: `errorDetail: "dtls-failure"` with
281
+ * `receivedAlert` / `sentAlert`.
282
+ *
283
+ * A close_notify (`closed`) does not fire it. Also delivered as
284
+ * `addEventListener("error", ...)`.
285
+ */
286
+ Object.defineProperty(this, "onerror", {
287
+ enumerable: true,
288
+ configurable: true,
289
+ writable: true,
290
+ value: void 0
291
+ });
204
292
  Object.defineProperty(this, "remoteParameters", {
205
293
  enumerable: true,
206
294
  configurable: true,
@@ -229,6 +317,13 @@ class RTCDtlsTransport {
229
317
  writable: true,
230
318
  value: (event) => this.events.dispatchEvent(event)
231
319
  });
320
+ /** Settles a pending start() (set while the handshake is awaited). */
321
+ Object.defineProperty(this, "settleStart", {
322
+ enumerable: true,
323
+ configurable: true,
324
+ writable: true,
325
+ value: void 0
326
+ });
232
327
  Object.defineProperty(this, "sendData", {
233
328
  enumerable: true,
234
329
  configurable: true,
@@ -261,7 +356,7 @@ class RTCDtlsTransport {
261
356
  }
262
357
  /**
263
358
  * Generates a new self-signed certificate (ECDSA P-256 / SHA-256) on every call.
264
- * Used by an RTCPeerConnection created with `certificateScope: "peerConnection"`
359
+ * Used by an RTCPeerConnection created with `certificateScope: "standard"`
265
360
  * when `RTCConfiguration.certificates` is not given.
266
361
  */
267
362
  static async generateCertificate() {
@@ -314,7 +409,23 @@ class RTCDtlsTransport {
314
409
  }
315
410
  }
316
411
  this.setState("connecting");
412
+ // A connecting listener may have stopped the transport synchronously
413
+ // (stop() ran before any socket existed): start() then ends here,
414
+ // without creating a socket nobody would close, and closed stays.
415
+ // (Narrowed by the check above, the state may have changed meanwhile.)
416
+ if (this.isFinalState) {
417
+ log("stopped while notifying connecting", this.state);
418
+ return;
419
+ }
420
+ // The certificate is checked during the handshake, so that a mismatch is
421
+ // reported to the peer with a fatal bad_certificate alert before either
422
+ // side considers the connection established.
423
+ const verifyRemoteCertificate = (certificate) => {
424
+ this.verifyRemoteCertificateFingerprint(certificate);
425
+ return true;
426
+ };
317
427
  await new Promise(async (r, f) => {
428
+ this.settleStart = r;
318
429
  if (this.role === "server") {
319
430
  this.dtls = new dtls_1.DtlsServer({
320
431
  cert: this.localCertificate?.certPem,
@@ -324,6 +435,7 @@ class RTCDtlsTransport {
324
435
  srtpProfiles: this.srtpProfiles,
325
436
  extendedMasterSecret: true,
326
437
  certificateRequest: true,
438
+ verifyRemoteCertificate,
327
439
  });
328
440
  }
329
441
  else {
@@ -334,6 +446,7 @@ class RTCDtlsTransport {
334
446
  transport: createIceTransport(this.iceTransport.connection),
335
447
  srtpProfiles: this.srtpProfiles,
336
448
  extendedMasterSecret: true,
449
+ verifyRemoteCertificate,
337
450
  });
338
451
  }
339
452
  this.dtls.onData.subscribe((buf) => {
@@ -343,32 +456,77 @@ class RTCDtlsTransport {
343
456
  }
344
457
  this.dataReceiver(buf);
345
458
  });
459
+ // close_notify from the peer, also during the handshake: closed (with
460
+ // statechange, the peer caused it; W3C RTCDtlsTransportState "closed").
461
+ // close_notify is not a fatal alert, so neither failed nor an error
462
+ // event. closed / failed are final.
346
463
  this.dtls.onClose.subscribe(() => {
347
- if (this.state !== "failed") {
464
+ if (this.isFinalState)
465
+ return;
466
+ log("dtls closed by the peer");
467
+ try {
348
468
  this.setState("closed");
349
469
  }
470
+ finally {
471
+ // Settle start() even if a statechange listener threw: it returns
472
+ // with closed (transport activation then ends a connection attempt
473
+ // that never connected as failed).
474
+ r();
475
+ }
350
476
  });
351
477
  this.dtls.onConnect.once(r);
352
- this.dtls.onError.once((error) => {
353
- this.setState("failed");
478
+ // A handshake error, or a fatal alert received or sent while
479
+ // connecting or after the connection was established.
480
+ this.dtls.onError.subscribe((error) => {
354
481
  log("dtls failed", error);
355
- f(error);
482
+ try {
483
+ this.fail(error);
484
+ }
485
+ finally {
486
+ // Settle start() even if a statechange listener threw. A local
487
+ // certificate rejection rejects with the verifier's error (e.g.
488
+ // "remote certificate fingerprint mismatch").
489
+ f(error instanceof dtls_1.DtlsAlertError &&
490
+ error.source === "local" &&
491
+ error.reason instanceof Error
492
+ ? error.reason
493
+ : error);
494
+ }
356
495
  });
357
496
  if (this.dtls instanceof dtls_1.DtlsClient) {
358
497
  await (0, promises_1.setTimeout)(100);
498
+ if (this.isFinalState) {
499
+ // stop() / a failure during the wait: settle start().
500
+ r();
501
+ return;
502
+ }
359
503
  this.dtls.connect().catch((error) => {
360
- this.setState("failed");
504
+ this.fail(error);
361
505
  log("dtls connect failed", error);
362
506
  f(error);
363
507
  });
364
508
  }
365
509
  });
510
+ // A fatal alert raced with the end of the handshake.
511
+ // (Narrowed by the checks above, the state may have changed meanwhile.)
512
+ const state = this.state;
513
+ if (state === "failed")
514
+ throw new Error("dtls transport failed");
515
+ // stop() raced with the end of the handshake: closed stays.
516
+ if (state === "closed")
517
+ return;
366
518
  try {
367
- this.verifyRemoteCertificateFingerprint();
519
+ // Fallback: a certificate the in-handshake check did not see.
520
+ this.verifyRemoteCertificateFingerprint(this.dtls?.remoteCertificate);
368
521
  }
369
522
  catch (error) {
370
- this.setState("failed");
371
- this.dtls?.close();
523
+ const dtls = this.dtls;
524
+ this.fail(certificateVerificationError(error));
525
+ // Tell the peer (whose handshake already completed); a fatal alert
526
+ // closes the DTLS transport once it has been sent.
527
+ void dtls?.sendAlert(dtls_1.AlertLevel.fatal, dtls_1.AlertDesc.BadCertificate, {
528
+ timeoutMs: exports.DTLS_ALERT_SEND_TIMEOUT_MS,
529
+ });
372
530
  throw error;
373
531
  }
374
532
  if (this.srtpProfiles.length > 0) {
@@ -377,12 +535,47 @@ class RTCDtlsTransport {
377
535
  this.setState("connected");
378
536
  log("dtls connected");
379
537
  }
380
- verifyRemoteCertificateFingerprint() {
538
+ /** closed / failed: no later DTLS event changes the state any more. */
539
+ get isFinalState() {
540
+ return this.state === "closed" || this.state === "failed";
541
+ }
542
+ /**
543
+ * Move to failed (once; closed / failed are final) and fire the `error`
544
+ * event with the DTLS alert that caused it.
545
+ */
546
+ fail(error) {
547
+ if (this.isFinalState)
548
+ return;
549
+ this.setState("failed");
550
+ const rtcError = error instanceof RTCError
551
+ ? error
552
+ : error instanceof dtls_1.DtlsAlertError &&
553
+ error.source === "local" &&
554
+ error.reason instanceof FingerprintMismatchError
555
+ ? // This side rejected the peer certificate during the handshake
556
+ // (bad_certificate was sent).
557
+ certificateVerificationError(error.reason)
558
+ : error instanceof dtls_1.DtlsAlertError
559
+ ? new RTCError({
560
+ errorDetail: "dtls-failure",
561
+ ...(error.source === "remote"
562
+ ? { receivedAlert: error.description }
563
+ : { sentAlert: error.description }),
564
+ }, error.message)
565
+ : new RTCError({ errorDetail: "dtls-failure" }, String(error));
566
+ const event = {
567
+ type: "error",
568
+ error: rtcError,
569
+ };
570
+ this.notifySafely("onerror", () => this.onerror?.(event));
571
+ // Per listener (and no throw when nobody listens to "error").
572
+ this.events.emitIsolated((error) => log("error listener failed", error), "error", event);
573
+ }
574
+ verifyRemoteCertificateFingerprint(remoteCertificate) {
381
575
  if (!this.remoteParameters ||
382
576
  this.remoteParameters.fingerprints.length === 0) {
383
577
  throw new Error("remote fingerprint not exist");
384
578
  }
385
- const remoteCertificate = this.dtls?.remoteCertificate;
386
579
  if (!remoteCertificate) {
387
580
  throw new Error("remote certificate not available");
388
581
  }
@@ -410,7 +603,7 @@ class RTCDtlsTransport {
410
603
  }, new Map());
411
604
  const matched = expectedFingerprints.some(({ normalizedAlgorithm, normalizedValue }) => actualFingerprints.get(normalizedAlgorithm) === normalizedValue);
412
605
  if (!matched) {
413
- throw new Error("remote certificate fingerprint mismatch");
606
+ throw new FingerprintMismatchError();
414
607
  }
415
608
  }
416
609
  updateSrtpSession() {
@@ -446,6 +639,9 @@ class RTCDtlsTransport {
446
639
  }
447
640
  if (!(0, rtp_1.isMedia)(data))
448
641
  return;
642
+ // Nothing is processed after close_notify / a fatal alert.
643
+ if (this.isFinalState)
644
+ return;
449
645
  // Track received data statistics
450
646
  this.bytesReceived += data.length;
451
647
  this.packetsReceived++;
@@ -537,8 +733,16 @@ class RTCDtlsTransport {
537
733
  /**
538
734
  * Encrypt RTP and enqueue on ICE, capturing the clock immediately before
539
735
  * the ICE write (RFC 8888). Prefer {@link sendRtp} unless send time is needed.
736
+ *
737
+ * Nothing is sent once the transport is `closed` / `failed` (close_notify
738
+ * or a fatal alert, `stop()`): ICE may still be up, but the DTLS
739
+ * association that keyed SRTP has ended. The size is then 0.
540
740
  */
541
741
  async sendRtpWithMeta(payload, header) {
742
+ if (this.isFinalState) {
743
+ log("drop RTP on a", this.state, "transport");
744
+ return { size: 0, sendingAtMs: (0, utils_1.milliTime)() };
745
+ }
542
746
  try {
543
747
  const enc = this.srtp.encrypt(payload, header);
544
748
  if (this.config.debug?.outboundPacketLoss &&
@@ -557,7 +761,16 @@ class RTCDtlsTransport {
557
761
  return { size: 0, sendingAtMs: (0, utils_1.milliTime)() };
558
762
  }
559
763
  }
764
+ /**
765
+ * Encrypt RTCP and enqueue on ICE. Like RTP, nothing is sent once the
766
+ * transport is `closed` / `failed` (periodic sender / receiver reports,
767
+ * NACK, PLI, TWCC feedback included).
768
+ */
560
769
  async sendRtcp(packets) {
770
+ if (this.isFinalState) {
771
+ log("drop RTCP on a", this.state, "transport");
772
+ return;
773
+ }
561
774
  const payload = Buffer.concat(packets.map((packet) => packet.serialize()));
562
775
  const enc = this.srtcp.encrypt(payload);
563
776
  if (this.config.debug?.outboundPacketLoss &&
@@ -569,16 +782,39 @@ class RTCDtlsTransport {
569
782
  this.packetsSent++;
570
783
  await this.iceTransport.connection.send(enc).catch(() => { });
571
784
  }
785
+ /**
786
+ * Change the state and notify. Each notification is isolated: an
787
+ * exception thrown by a listener is logged and never interrupts the
788
+ * caller (stop() cleanup, settling start(), failing the transport).
789
+ */
572
790
  setState(state, emitEvent = true) {
573
791
  if (state != this.state) {
574
792
  this.state = state;
575
- this.onStateChange.execute(state);
793
+ // Per subscriber: an application subscriber registered before the
794
+ // internal ones (SCTP closing its association, connectionState) must
795
+ // not stop them by throwing.
796
+ this.onStateChange.executeIsolated((error) => log("onStateChange listener failed", error), state);
576
797
  if (emitEvent) {
577
- this.onstatechange?.();
578
- this.events.emit("statechange");
798
+ this.notifySafely("onstatechange", () => this.onstatechange?.());
799
+ this.events.emitIsolated((error) => log("statechange listener failed", error), "statechange");
579
800
  }
580
801
  }
581
802
  }
803
+ notifySafely(name, notify) {
804
+ (0, helper_1.notifySafely)(log, name, notify);
805
+ }
806
+ /**
807
+ * @internal
808
+ * The synchronous part of {@link RTCDtlsTransport.stop}: `closed` without
809
+ * statechange (W3C webrtc-pc `close()`), and a start() still waiting for
810
+ * the handshake settles. `RTCPeerConnection.close()` calls it before its
811
+ * first await; the alert and the ICE / socket teardown follow in stop().
812
+ */
813
+ markClosed() {
814
+ this.setState("closed", false);
815
+ // A start() still waiting for the handshake ends here (closed stays).
816
+ this.settleStart?.();
817
+ }
582
818
  /** Resolves once ICE has stopped; concurrent callers share one stop. */
583
819
  stop() {
584
820
  if (this.stopPromise)
@@ -592,18 +828,64 @@ class RTCDtlsTransport {
592
828
  settle(this.runStop());
593
829
  return this.stopPromise;
594
830
  }
831
+ /**
832
+ * 1. closed, synchronously and without statechange (W3C webrtc-pc
833
+ * `close()`).
834
+ * 2. close_notify to the peer (RFC 5246 §7.2.1), encrypted once the
835
+ * handshake reached epoch 1, plaintext while it is still at epoch 0. It
836
+ * is awaited for at most {@link DTLS_ALERT_SEND_TIMEOUT_MS}, so a dead
837
+ * ICE path cannot hold the close. Nothing is sent after a fatal alert,
838
+ * a received close_notify, or when ICE is already closed / failed.
839
+ * 3. ICE stops (the alert must reach ICE before it closes).
840
+ * 4. The DTLS socket closes, so a handshake still in flight stops
841
+ * retransmitting.
842
+ *
843
+ * Steps 3 and 4 and `onStopped` always run, even if an earlier step or a
844
+ * listener threw, so the underlying transports never outlive stop().
845
+ */
595
846
  async runStop() {
847
+ const dtls = this.dtls;
848
+ try {
849
+ this.markClosed();
850
+ if (dtls &&
851
+ !dtls.terminated &&
852
+ !["closed", "failed"].includes(this.iceTransport.state)) {
853
+ log("send close_notify", this.iceTransport.state);
854
+ await dtls.sendAlert(dtls_1.AlertLevel.warning, dtls_1.AlertDesc.CloseNotify, {
855
+ timeoutMs: exports.DTLS_ALERT_SEND_TIMEOUT_MS,
856
+ });
857
+ }
858
+ else if (dtls?.terminated) {
859
+ // The peer's close_notify is being answered: let that reply reach ICE
860
+ // before ICE stops.
861
+ await dtls.alertFlushed();
862
+ }
863
+ else {
864
+ log("skip close_notify", {
865
+ dtls: !!dtls,
866
+ terminated: dtls?.terminated,
867
+ ice: this.iceTransport.state,
868
+ });
869
+ }
870
+ }
871
+ catch (error) {
872
+ log("stop: close_notify step failed", error);
873
+ }
596
874
  try {
597
- this.setState("closed", false);
598
- // todo impl send alert
599
875
  await this.iceTransport.stop();
600
- // A handshake still in flight stops retransmitting its flight.
601
- this.dtls?.close();
602
876
  }
603
- finally {
604
- this.onStopped.execute();
605
- this.onStopped.complete();
877
+ catch (error) {
878
+ log("stop: ice stop failed", error);
879
+ }
880
+ try {
881
+ await dtls?.close();
606
882
  }
883
+ catch (error) {
884
+ log("stop: dtls close failed", error);
885
+ }
886
+ // Per subscriber: the owner releasing this transport must run.
887
+ this.onStopped.executeIsolated((error) => log("onStopped listener failed", error));
888
+ this.notifySafely("onStopped", () => this.onStopped.complete());
607
889
  }
608
890
  async getStats(timestamp = (0, stats_1.getStatsTimestamp)()) {
609
891
  const stats = [];
@@ -784,6 +1066,13 @@ const preferredFingerprintAlgorithms = [
784
1066
  const selectPreferredFingerprintAlgorithm = (fingerprints) => {
785
1067
  return (preferredFingerprintAlgorithms.find((algorithm) => fingerprints.some(({ normalizedAlgorithm }) => normalizedAlgorithm === algorithm)) ?? fingerprints[0].normalizedAlgorithm);
786
1068
  };
1069
+ /**
1070
+ * The DTLS socket's view of the ICE connection. The ICE connection belongs to
1071
+ * {@link RTCIceTransport} (shared with SRTP, stopped by
1072
+ * {@link RTCDtlsTransport.stop}): when the DTLS socket closes its transport
1073
+ * (after a received close_notify or fatal alert, or close()), this only
1074
+ * detaches DTLS from ICE; it never closes the ICE agent.
1075
+ */
787
1076
  class IceTransport {
788
1077
  constructor(ice) {
789
1078
  Object.defineProperty(this, "ice", {
@@ -792,6 +1081,12 @@ class IceTransport {
792
1081
  writable: true,
793
1082
  value: void 0
794
1083
  });
1084
+ Object.defineProperty(this, "unSubscribe", {
1085
+ enumerable: true,
1086
+ configurable: true,
1087
+ writable: true,
1088
+ value: void 0
1089
+ });
795
1090
  Object.defineProperty(this, "closed", {
796
1091
  enumerable: true,
797
1092
  configurable: true,
@@ -815,28 +1110,29 @@ class IceTransport {
815
1110
  configurable: true,
816
1111
  writable: true,
817
1112
  value: (data) => {
1113
+ if (this.closed)
1114
+ return Promise.resolve();
818
1115
  return this.ice.send(data);
819
1116
  }
820
1117
  });
821
1118
  this.ice = ice;
822
- ice.onData.subscribe((buf) => {
1119
+ this.unSubscribe = ice.onData.subscribe((buf) => {
823
1120
  if ((0, utils_1.isDtls)(buf)) {
824
1121
  if (this.onData) {
825
1122
  this.onData(buf);
826
1123
  }
827
1124
  }
828
- });
1125
+ }).unSubscribe;
829
1126
  }
830
1127
  get address() {
831
1128
  return {};
832
1129
  }
1130
+ /** Detach DTLS from ICE: no more DTLS records in either direction. */
833
1131
  async close() {
834
1132
  if (this.closed)
835
1133
  return;
836
1134
  this.closed = true;
837
- // RTCIceTransport.stop() may have closed the agent already.
838
- if (this.ice.state !== "closed")
839
- this.ice.close();
1135
+ this.unSubscribe();
840
1136
  }
841
1137
  }
842
1138
  const createIceTransport = (ice) => new IceTransport(ice);