werift 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (492) hide show
  1. package/README.md +182 -2
  2. package/lib/common/src/transport.d.ts +39 -5
  3. package/lib/common/src/transport.js +32 -7
  4. package/lib/common/src/transport.js.map +1 -1
  5. package/lib/dtls/src/carrier/direct.d.ts +67 -0
  6. package/lib/dtls/src/carrier/direct.js +226 -0
  7. package/lib/dtls/src/carrier/direct.js.map +1 -0
  8. package/lib/dtls/src/carrier/types.d.ts +81 -0
  9. package/lib/dtls/src/carrier/types.js +7 -0
  10. package/lib/dtls/src/carrier/types.js.map +1 -0
  11. package/lib/dtls/src/cipher/const.d.ts +6 -0
  12. package/lib/dtls/src/cipher/const.js +13 -2
  13. package/lib/dtls/src/cipher/const.js.map +1 -1
  14. package/lib/dtls/src/cipher/prf.js +11 -2
  15. package/lib/dtls/src/cipher/prf.js.map +1 -1
  16. package/lib/dtls/src/cipher/tls13/aead.d.ts +41 -0
  17. package/lib/dtls/src/cipher/tls13/aead.js +128 -0
  18. package/lib/dtls/src/cipher/tls13/aead.js.map +1 -0
  19. package/lib/dtls/src/cipher/tls13/hkdf.d.ts +30 -0
  20. package/lib/dtls/src/cipher/tls13/hkdf.js +76 -0
  21. package/lib/dtls/src/cipher/tls13/hkdf.js.map +1 -0
  22. package/lib/dtls/src/cipher/tls13/keySchedule.d.ts +70 -0
  23. package/lib/dtls/src/cipher/tls13/keySchedule.js +114 -0
  24. package/lib/dtls/src/cipher/tls13/keySchedule.js.map +1 -0
  25. package/lib/dtls/src/cipher/tls13/signature.d.ts +30 -0
  26. package/lib/dtls/src/cipher/tls13/signature.js +149 -0
  27. package/lib/dtls/src/cipher/tls13/signature.js.map +1 -0
  28. package/lib/dtls/src/client.d.ts +253 -0
  29. package/lib/dtls/src/client.js +1257 -16
  30. package/lib/dtls/src/client.js.map +1 -1
  31. package/lib/dtls/src/context/dtls.d.ts +45 -0
  32. package/lib/dtls/src/context/dtls.js +114 -0
  33. package/lib/dtls/src/context/dtls.js.map +1 -1
  34. package/lib/dtls/src/context/transport.d.ts +13 -0
  35. package/lib/dtls/src/context/transport.js +29 -1
  36. package/lib/dtls/src/context/transport.js.map +1 -1
  37. package/lib/dtls/src/engine/v1_3/connection-base.d.ts +520 -0
  38. package/lib/dtls/src/engine/v1_3/connection-base.js +1644 -0
  39. package/lib/dtls/src/engine/v1_3/connection-base.js.map +1 -0
  40. package/lib/dtls/src/engine/v1_3/connection.d.ts +181 -0
  41. package/lib/dtls/src/engine/v1_3/connection.js +680 -0
  42. package/lib/dtls/src/engine/v1_3/connection.js.map +1 -0
  43. package/lib/dtls/src/engine/v1_3/early-data-buffer.d.ts +38 -0
  44. package/lib/dtls/src/engine/v1_3/early-data-buffer.js +166 -0
  45. package/lib/dtls/src/engine/v1_3/early-data-buffer.js.map +1 -0
  46. package/lib/dtls/src/engine/v1_3/flight/certificate.d.ts +4 -0
  47. package/lib/dtls/src/engine/v1_3/flight/certificate.js +62 -0
  48. package/lib/dtls/src/engine/v1_3/flight/certificate.js.map +1 -0
  49. package/lib/dtls/src/engine/v1_3/flight/client/flight1.d.ts +8 -0
  50. package/lib/dtls/src/engine/v1_3/flight/client/flight1.js +119 -0
  51. package/lib/dtls/src/engine/v1_3/flight/client/flight1.js.map +1 -0
  52. package/lib/dtls/src/engine/v1_3/flight/client/flight4.d.ts +8 -0
  53. package/lib/dtls/src/engine/v1_3/flight/client/flight4.js +251 -0
  54. package/lib/dtls/src/engine/v1_3/flight/client/flight4.js.map +1 -0
  55. package/lib/dtls/src/engine/v1_3/flight/client/flight5.d.ts +5 -0
  56. package/lib/dtls/src/engine/v1_3/flight/client/flight5.js +99 -0
  57. package/lib/dtls/src/engine/v1_3/flight/client/flight5.js.map +1 -0
  58. package/lib/dtls/src/engine/v1_3/flight/dispatch.d.ts +12 -0
  59. package/lib/dtls/src/engine/v1_3/flight/dispatch.js +138 -0
  60. package/lib/dtls/src/engine/v1_3/flight/dispatch.js.map +1 -0
  61. package/lib/dtls/src/engine/v1_3/flight/extensions.d.ts +13 -0
  62. package/lib/dtls/src/engine/v1_3/flight/extensions.js +46 -0
  63. package/lib/dtls/src/engine/v1_3/flight/extensions.js.map +1 -0
  64. package/lib/dtls/src/engine/v1_3/flight/finished.d.ts +6 -0
  65. package/lib/dtls/src/engine/v1_3/flight/finished.js +16 -0
  66. package/lib/dtls/src/engine/v1_3/flight/finished.js.map +1 -0
  67. package/lib/dtls/src/engine/v1_3/flight/post-hs.d.ts +12 -0
  68. package/lib/dtls/src/engine/v1_3/flight/post-hs.js +94 -0
  69. package/lib/dtls/src/engine/v1_3/flight/post-hs.js.map +1 -0
  70. package/lib/dtls/src/engine/v1_3/flight/server/flight2.d.ts +21 -0
  71. package/lib/dtls/src/engine/v1_3/flight/server/flight2.js +227 -0
  72. package/lib/dtls/src/engine/v1_3/flight/server/flight2.js.map +1 -0
  73. package/lib/dtls/src/engine/v1_3/flight/server/flight4.d.ts +6 -0
  74. package/lib/dtls/src/engine/v1_3/flight/server/flight4.js +455 -0
  75. package/lib/dtls/src/engine/v1_3/flight/server/flight4.js.map +1 -0
  76. package/lib/dtls/src/engine/v1_3/flight/server/flight5.d.ts +5 -0
  77. package/lib/dtls/src/engine/v1_3/flight/server/flight5.js +48 -0
  78. package/lib/dtls/src/engine/v1_3/flight/server/flight5.js.map +1 -0
  79. package/lib/dtls/src/engine/v1_3/flight-tx.d.ts +119 -0
  80. package/lib/dtls/src/engine/v1_3/flight-tx.js +782 -0
  81. package/lib/dtls/src/engine/v1_3/flight-tx.js.map +1 -0
  82. package/lib/dtls/src/engine/v1_3/host.d.ts +86 -0
  83. package/lib/dtls/src/engine/v1_3/host.js +11 -0
  84. package/lib/dtls/src/engine/v1_3/host.js.map +1 -0
  85. package/lib/dtls/src/engine/v1_3/record-rx.d.ts +77 -0
  86. package/lib/dtls/src/engine/v1_3/record-rx.js +818 -0
  87. package/lib/dtls/src/engine/v1_3/record-rx.js.map +1 -0
  88. package/lib/dtls/src/engine/v1_3/transcript.d.ts +22 -0
  89. package/lib/dtls/src/engine/v1_3/transcript.js +65 -0
  90. package/lib/dtls/src/engine/v1_3/transcript.js.map +1 -0
  91. package/lib/dtls/src/engine/v1_3/types.d.ts +169 -0
  92. package/lib/dtls/src/engine/v1_3/types.js +113 -0
  93. package/lib/dtls/src/engine/v1_3/types.js.map +1 -0
  94. package/lib/dtls/src/flight/client/flight1.d.ts +7 -1
  95. package/lib/dtls/src/flight/client/flight1.js +9 -3
  96. package/lib/dtls/src/flight/client/flight1.js.map +1 -1
  97. package/lib/dtls/src/flight/client/flight3.d.ts +8 -0
  98. package/lib/dtls/src/flight/client/flight3.js +24 -4
  99. package/lib/dtls/src/flight/client/flight3.js.map +1 -1
  100. package/lib/dtls/src/flight/client/flight5.js +13 -1
  101. package/lib/dtls/src/flight/client/flight5.js.map +1 -1
  102. package/lib/dtls/src/flight/flight.d.ts +16 -0
  103. package/lib/dtls/src/flight/flight.js +109 -8
  104. package/lib/dtls/src/flight/flight.js.map +1 -1
  105. package/lib/dtls/src/flight/server/commitClientHello.d.ts +35 -0
  106. package/lib/dtls/src/flight/server/commitClientHello.js +149 -0
  107. package/lib/dtls/src/flight/server/commitClientHello.js.map +1 -0
  108. package/lib/dtls/src/flight/server/flight2.d.ts +12 -3
  109. package/lib/dtls/src/flight/server/flight2.js +29 -105
  110. package/lib/dtls/src/flight/server/flight2.js.map +1 -1
  111. package/lib/dtls/src/flight/server/flight4.js +14 -2
  112. package/lib/dtls/src/flight/server/flight4.js.map +1 -1
  113. package/lib/dtls/src/flight/server/flight6.js +8 -0
  114. package/lib/dtls/src/flight/server/flight6.js.map +1 -1
  115. package/lib/dtls/src/handshake/const.d.ts +10 -0
  116. package/lib/dtls/src/handshake/const.js +10 -0
  117. package/lib/dtls/src/handshake/const.js.map +1 -1
  118. package/lib/dtls/src/handshake/extensions/cookie.d.ts +113 -0
  119. package/lib/dtls/src/handshake/extensions/cookie.js +326 -0
  120. package/lib/dtls/src/handshake/extensions/cookie.js.map +1 -0
  121. package/lib/dtls/src/handshake/extensions/ids.d.ts +7 -0
  122. package/lib/dtls/src/handshake/extensions/ids.js +11 -0
  123. package/lib/dtls/src/handshake/extensions/ids.js.map +1 -0
  124. package/lib/dtls/src/handshake/extensions/keyShare.d.ts +28 -0
  125. package/lib/dtls/src/handshake/extensions/keyShare.js +156 -0
  126. package/lib/dtls/src/handshake/extensions/keyShare.js.map +1 -0
  127. package/lib/dtls/src/handshake/extensions/signatureAlgorithms.d.ts +27 -0
  128. package/lib/dtls/src/handshake/extensions/signatureAlgorithms.js +67 -0
  129. package/lib/dtls/src/handshake/extensions/signatureAlgorithms.js.map +1 -0
  130. package/lib/dtls/src/handshake/extensions/supportedVersions.d.ts +20 -0
  131. package/lib/dtls/src/handshake/extensions/supportedVersions.js +90 -0
  132. package/lib/dtls/src/handshake/extensions/supportedVersions.js.map +1 -0
  133. package/lib/dtls/src/handshake/extensions/unique.d.ts +7 -0
  134. package/lib/dtls/src/handshake/extensions/unique.js +19 -0
  135. package/lib/dtls/src/handshake/extensions/unique.js.map +1 -0
  136. package/lib/dtls/src/handshake/extensions/useSrtp.d.ts +26 -3
  137. package/lib/dtls/src/handshake/extensions/useSrtp.js +68 -12
  138. package/lib/dtls/src/handshake/extensions/useSrtp.js.map +1 -1
  139. package/lib/dtls/src/handshake/message/tls13/ack.d.ts +50 -0
  140. package/lib/dtls/src/handshake/message/tls13/ack.js +107 -0
  141. package/lib/dtls/src/handshake/message/tls13/ack.js.map +1 -0
  142. package/lib/dtls/src/handshake/message/tls13/certificate.d.ts +17 -0
  143. package/lib/dtls/src/handshake/message/tls13/certificate.js +112 -0
  144. package/lib/dtls/src/handshake/message/tls13/certificate.js.map +1 -0
  145. package/lib/dtls/src/handshake/message/tls13/certificateRequest.d.ts +17 -0
  146. package/lib/dtls/src/handshake/message/tls13/certificateRequest.js +99 -0
  147. package/lib/dtls/src/handshake/message/tls13/certificateRequest.js.map +1 -0
  148. package/lib/dtls/src/handshake/message/tls13/certificateVerify.d.ts +21 -0
  149. package/lib/dtls/src/handshake/message/tls13/certificateVerify.js +77 -0
  150. package/lib/dtls/src/handshake/message/tls13/certificateVerify.js.map +1 -0
  151. package/lib/dtls/src/handshake/message/tls13/encryptedExtensions.d.ts +19 -0
  152. package/lib/dtls/src/handshake/message/tls13/encryptedExtensions.js +56 -0
  153. package/lib/dtls/src/handshake/message/tls13/encryptedExtensions.js.map +1 -0
  154. package/lib/dtls/src/handshake/message/tls13/keyUpdate.d.ts +13 -0
  155. package/lib/dtls/src/handshake/message/tls13/keyUpdate.js +54 -0
  156. package/lib/dtls/src/handshake/message/tls13/keyUpdate.js.map +1 -0
  157. package/lib/dtls/src/handshake/message/tls13/newSessionTicket.d.ts +33 -0
  158. package/lib/dtls/src/handshake/message/tls13/newSessionTicket.js +158 -0
  159. package/lib/dtls/src/handshake/message/tls13/newSessionTicket.js.map +1 -0
  160. package/lib/dtls/src/handshake/random.d.ts +14 -0
  161. package/lib/dtls/src/handshake/random.js +24 -0
  162. package/lib/dtls/src/handshake/random.js.map +1 -1
  163. package/lib/dtls/src/handshake/validation.d.ts +26 -0
  164. package/lib/dtls/src/handshake/validation.js +32 -0
  165. package/lib/dtls/src/handshake/validation.js.map +1 -0
  166. package/lib/dtls/src/index.d.ts +6 -1
  167. package/lib/dtls/src/index.js +116 -44
  168. package/lib/dtls/src/index.js.map +1 -1
  169. package/lib/dtls/src/internal.d.ts +7 -0
  170. package/lib/dtls/src/internal.js +57 -0
  171. package/lib/dtls/src/internal.js.map +1 -0
  172. package/lib/dtls/src/peer.d.ts +49 -0
  173. package/lib/dtls/src/peer.js +54 -0
  174. package/lib/dtls/src/peer.js.map +1 -0
  175. package/lib/dtls/src/record/antiReplayWindow.d.ts +33 -0
  176. package/lib/dtls/src/record/antiReplayWindow.js +119 -0
  177. package/lib/dtls/src/record/antiReplayWindow.js.map +1 -0
  178. package/lib/dtls/src/record/const.d.ts +6 -0
  179. package/lib/dtls/src/record/const.js +6 -0
  180. package/lib/dtls/src/record/const.js.map +1 -1
  181. package/lib/dtls/src/record/message/fragment.d.ts +0 -2
  182. package/lib/dtls/src/record/message/fragment.js +36 -17
  183. package/lib/dtls/src/record/message/fragment.js.map +1 -1
  184. package/lib/dtls/src/record/message/reassembler.d.ts +62 -0
  185. package/lib/dtls/src/record/message/reassembler.js +249 -0
  186. package/lib/dtls/src/record/message/reassembler.js.map +1 -0
  187. package/lib/dtls/src/record/receive.js +24 -16
  188. package/lib/dtls/src/record/receive.js.map +1 -1
  189. package/lib/dtls/src/record/v1_3/header.d.ts +34 -0
  190. package/lib/dtls/src/record/v1_3/header.js +95 -0
  191. package/lib/dtls/src/record/v1_3/header.js.map +1 -0
  192. package/lib/dtls/src/record/v1_3/record.d.ts +133 -0
  193. package/lib/dtls/src/record/v1_3/record.js +370 -0
  194. package/lib/dtls/src/record/v1_3/record.js.map +1 -0
  195. package/lib/dtls/src/retransmission.d.ts +26 -0
  196. package/lib/dtls/src/retransmission.js +39 -0
  197. package/lib/dtls/src/retransmission.js.map +1 -0
  198. package/lib/dtls/src/server.d.ts +38 -0
  199. package/lib/dtls/src/server.js +367 -20
  200. package/lib/dtls/src/server.js.map +1 -1
  201. package/lib/dtls/src/socket.d.ts +379 -35
  202. package/lib/dtls/src/socket.js +1105 -132
  203. package/lib/dtls/src/socket.js.map +1 -1
  204. package/lib/dtls/src/version.d.ts +89 -0
  205. package/lib/dtls/src/version.js +204 -0
  206. package/lib/dtls/src/version.js.map +1 -0
  207. package/lib/ice/src/consent.d.ts +78 -1
  208. package/lib/ice/src/consent.js +236 -24
  209. package/lib/ice/src/consent.js.map +1 -1
  210. package/lib/ice/src/dns/lookup.d.ts +10 -0
  211. package/lib/ice/src/dns/lookup.js +130 -3
  212. package/lib/ice/src/dns/lookup.js.map +1 -1
  213. package/lib/ice/src/exceptions.d.ts +9 -0
  214. package/lib/ice/src/exceptions.js +14 -1
  215. package/lib/ice/src/exceptions.js.map +1 -1
  216. package/lib/ice/src/failover.d.ts +270 -0
  217. package/lib/ice/src/failover.js +674 -0
  218. package/lib/ice/src/failover.js.map +1 -0
  219. package/lib/ice/src/gatheringError.d.ts +28 -0
  220. package/lib/ice/src/gatheringError.js +17 -0
  221. package/lib/ice/src/gatheringError.js.map +1 -0
  222. package/lib/ice/src/ice.d.ts +265 -9
  223. package/lib/ice/src/ice.js +1624 -236
  224. package/lib/ice/src/ice.js.map +1 -1
  225. package/lib/ice/src/iceBase.d.ts +197 -6
  226. package/lib/ice/src/iceBase.js +157 -7
  227. package/lib/ice/src/iceBase.js.map +1 -1
  228. package/lib/ice/src/index.d.ts +2 -0
  229. package/lib/ice/src/index.js +4 -1
  230. package/lib/ice/src/index.js.map +1 -1
  231. package/lib/ice/src/internal/datagram.d.ts +37 -0
  232. package/lib/ice/src/internal/datagram.js +45 -0
  233. package/lib/ice/src/internal/datagram.js.map +1 -0
  234. package/lib/ice/src/internal/hostInterfaces.d.ts +13 -2
  235. package/lib/ice/src/internal/hostInterfaces.js +16 -4
  236. package/lib/ice/src/internal/hostInterfaces.js.map +1 -1
  237. package/lib/ice/src/internal/sped-bind.d.ts +44 -0
  238. package/lib/ice/src/internal/sped-bind.js +53 -0
  239. package/lib/ice/src/internal/sped-bind.js.map +1 -0
  240. package/lib/ice/src/internal/sped-binding-cache.d.ts +27 -0
  241. package/lib/ice/src/internal/sped-binding-cache.js +102 -0
  242. package/lib/ice/src/internal/sped-binding-cache.js.map +1 -0
  243. package/lib/ice/src/internal/sped.d.ts +15 -0
  244. package/lib/ice/src/internal/sped.js +62 -0
  245. package/lib/ice/src/internal/sped.js.map +1 -0
  246. package/lib/ice/src/nomination/selectionController.d.ts +111 -0
  247. package/lib/ice/src/nomination/selectionController.js +172 -0
  248. package/lib/ice/src/nomination/selectionController.js.map +1 -0
  249. package/lib/ice/src/nomination/selectionReplacement.d.ts +40 -0
  250. package/lib/ice/src/nomination/selectionReplacement.js +65 -7
  251. package/lib/ice/src/nomination/selectionReplacement.js.map +1 -1
  252. package/lib/ice/src/sped/draft00/codec.d.ts +20 -0
  253. package/lib/ice/src/sped/draft00/codec.js +59 -0
  254. package/lib/ice/src/sped/draft00/codec.js.map +1 -0
  255. package/lib/ice/src/sped/draft00/constants.d.ts +14 -0
  256. package/lib/ice/src/sped/draft00/constants.js +18 -0
  257. package/lib/ice/src/sped/draft00/constants.js.map +1 -0
  258. package/lib/ice/src/sped/draft00/index.d.ts +6 -0
  259. package/lib/ice/src/sped/draft00/index.js +26 -0
  260. package/lib/ice/src/sped/draft00/index.js.map +1 -0
  261. package/lib/ice/src/sped/draft00/mtu.d.ts +38 -0
  262. package/lib/ice/src/sped/draft00/mtu.js +96 -0
  263. package/lib/ice/src/sped/draft00/mtu.js.map +1 -0
  264. package/lib/ice/src/sped/draft00/session.d.ts +86 -0
  265. package/lib/ice/src/sped/draft00/session.js +353 -0
  266. package/lib/ice/src/sped/draft00/session.js.map +1 -0
  267. package/lib/ice/src/sped/draft00/types.d.ts +16 -0
  268. package/lib/ice/src/sped/draft00/types.js +3 -0
  269. package/lib/ice/src/sped/draft00/types.js.map +1 -0
  270. package/lib/ice/src/sped/runtime.d.ts +188 -0
  271. package/lib/ice/src/sped/runtime.js +643 -0
  272. package/lib/ice/src/sped/runtime.js.map +1 -0
  273. package/lib/ice/src/stun/protocol.d.ts +29 -0
  274. package/lib/ice/src/stun/protocol.js +91 -4
  275. package/lib/ice/src/stun/protocol.js.map +1 -1
  276. package/lib/ice/src/stun/rawAttributeValue.d.ts +1 -0
  277. package/lib/ice/src/stun/rawAttributeValue.js +6 -0
  278. package/lib/ice/src/stun/rawAttributeValue.js.map +1 -0
  279. package/lib/ice/src/stun/tcpProtocol.d.ts +1 -0
  280. package/lib/ice/src/stun/tcpProtocol.js +14 -2
  281. package/lib/ice/src/stun/tcpProtocol.js.map +1 -1
  282. package/lib/ice/src/stun/transaction.d.ts +4 -0
  283. package/lib/ice/src/stun/transaction.js +23 -0
  284. package/lib/ice/src/stun/transaction.js.map +1 -1
  285. package/lib/ice/src/turn/protocol.d.ts +21 -2
  286. package/lib/ice/src/turn/protocol.js +93 -8
  287. package/lib/ice/src/turn/protocol.js.map +1 -1
  288. package/lib/ice/src/types/model.d.ts +9 -0
  289. package/lib/ice/src/types/model.js.map +1 -1
  290. package/lib/ice/src/utils.d.ts +13 -0
  291. package/lib/ice/src/utils.js +13 -0
  292. package/lib/ice/src/utils.js.map +1 -1
  293. package/lib/ice-server/src/stun/message.d.ts +15 -2
  294. package/lib/ice-server/src/stun/message.js +156 -25
  295. package/lib/ice-server/src/stun/message.js.map +1 -1
  296. package/lib/ice-server/src/stun/rawAttributeValue.d.ts +6 -0
  297. package/lib/ice-server/src/stun/rawAttributeValue.js +12 -0
  298. package/lib/ice-server/src/stun/rawAttributeValue.js.map +1 -0
  299. package/lib/index.mjs +19568 -3106
  300. package/lib/nonstandard/index.mjs +2539 -1175
  301. package/lib/polyfill/dom.mjs +33210 -16872
  302. package/lib/polyfill/index.mjs +33345 -17013
  303. package/lib/rtp/src/extra/processor/fsRetry.d.ts +20 -0
  304. package/lib/rtp/src/extra/processor/fsRetry.js +73 -0
  305. package/lib/rtp/src/extra/processor/fsRetry.js.map +1 -0
  306. package/lib/rtp/src/extra/processor/webm.d.ts +6 -0
  307. package/lib/rtp/src/extra/processor/webm.js +6 -2
  308. package/lib/rtp/src/extra/processor/webm.js.map +1 -1
  309. package/lib/rtp/src/extra/processor/webmCallback.d.ts +11 -0
  310. package/lib/rtp/src/extra/processor/webmCallback.js +23 -31
  311. package/lib/rtp/src/extra/processor/webmCallback.js.map +1 -1
  312. package/lib/rtp/src/extra/processor/webmFileWriter.d.ts +24 -0
  313. package/lib/rtp/src/extra/processor/webmFileWriter.js +94 -0
  314. package/lib/rtp/src/extra/processor/webmFileWriter.js.map +1 -0
  315. package/lib/sctp/src/chunk.d.ts +5 -0
  316. package/lib/sctp/src/chunk.js +10 -0
  317. package/lib/sctp/src/chunk.js.map +1 -1
  318. package/lib/sctp/src/index.d.ts +1 -1
  319. package/lib/sctp/src/index.js +4 -1
  320. package/lib/sctp/src/index.js.map +1 -1
  321. package/lib/sctp/src/sctp.d.ts +81 -5
  322. package/lib/sctp/src/sctp.js +273 -28
  323. package/lib/sctp/src/sctp.js.map +1 -1
  324. package/lib/webrtc/src/api/compatibilityOptions.d.ts +11 -1
  325. package/lib/webrtc/src/api/compatibilityOptions.js +11 -1
  326. package/lib/webrtc/src/api/compatibilityOptions.js.map +1 -1
  327. package/lib/webrtc/src/api/peerConfig.d.ts +210 -13
  328. package/lib/webrtc/src/api/peerConfig.js +100 -5
  329. package/lib/webrtc/src/api/peerConfig.js.map +1 -1
  330. package/lib/webrtc/src/api/peerConnectionEvents.d.ts +10 -1
  331. package/lib/webrtc/src/api/peerConnectionEvents.js.map +1 -1
  332. package/lib/webrtc/src/dataChannel.d.ts +122 -10
  333. package/lib/webrtc/src/dataChannel.js +214 -20
  334. package/lib/webrtc/src/dataChannel.js.map +1 -1
  335. package/lib/webrtc/src/media/domEventTarget.d.ts +55 -0
  336. package/lib/webrtc/src/media/domEventTarget.js +216 -0
  337. package/lib/webrtc/src/media/domEventTarget.js.map +1 -0
  338. package/lib/webrtc/src/media/index.d.ts +2 -0
  339. package/lib/webrtc/src/media/index.js +1 -0
  340. package/lib/webrtc/src/media/index.js.map +1 -1
  341. package/lib/webrtc/src/media/parameters.d.ts +5 -0
  342. package/lib/webrtc/src/media/parameters.js +10 -0
  343. package/lib/webrtc/src/media/parameters.js.map +1 -1
  344. package/lib/webrtc/src/media/receiver/receiverTwcc.d.ts +10 -0
  345. package/lib/webrtc/src/media/receiver/receiverTwcc.js +4 -10
  346. package/lib/webrtc/src/media/receiver/receiverTwcc.js.map +1 -1
  347. package/lib/webrtc/src/media/router.d.ts +6 -0
  348. package/lib/webrtc/src/media/router.js +39 -1
  349. package/lib/webrtc/src/media/router.js.map +1 -1
  350. package/lib/webrtc/src/media/rtpReceiver.d.ts +56 -6
  351. package/lib/webrtc/src/media/rtpReceiver.js +165 -15
  352. package/lib/webrtc/src/media/rtpReceiver.js.map +1 -1
  353. package/lib/webrtc/src/media/rtpSender.d.ts +1 -1
  354. package/lib/webrtc/src/media/rtpSender.js +4 -3
  355. package/lib/webrtc/src/media/rtpSender.js.map +1 -1
  356. package/lib/webrtc/src/media/rtpTransceiver.d.ts +29 -11
  357. package/lib/webrtc/src/media/rtpTransceiver.js +31 -9
  358. package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
  359. package/lib/webrtc/src/media/stats.d.ts +13 -0
  360. package/lib/webrtc/src/media/stats.js.map +1 -1
  361. package/lib/webrtc/src/media/track.d.ts +103 -11
  362. package/lib/webrtc/src/media/track.js +241 -19
  363. package/lib/webrtc/src/media/track.js.map +1 -1
  364. package/lib/webrtc/src/media/trackConstraints.d.ts +80 -0
  365. package/lib/webrtc/src/media/trackConstraints.js +141 -0
  366. package/lib/webrtc/src/media/trackConstraints.js.map +1 -0
  367. package/lib/webrtc/src/negotiation/internalState.d.ts +0 -4
  368. package/lib/webrtc/src/negotiation/internalState.js +0 -11
  369. package/lib/webrtc/src/negotiation/internalState.js.map +1 -1
  370. package/lib/webrtc/src/negotiation/remoteCandidates.d.ts +20 -1
  371. package/lib/webrtc/src/negotiation/remoteCandidates.js +29 -1
  372. package/lib/webrtc/src/negotiation/remoteCandidates.js.map +1 -1
  373. package/lib/webrtc/src/negotiation/transportActivation.d.ts +4 -0
  374. package/lib/webrtc/src/negotiation/transportActivation.js +112 -11
  375. package/lib/webrtc/src/negotiation/transportActivation.js.map +1 -1
  376. package/lib/webrtc/src/negotiationTransaction.d.ts +25 -4
  377. package/lib/webrtc/src/negotiationTransaction.js +27 -6
  378. package/lib/webrtc/src/negotiationTransaction.js.map +1 -1
  379. package/lib/webrtc/src/nonstandard/dummyMedia.d.ts +6 -0
  380. package/lib/webrtc/src/nonstandard/dummyMedia.js +14 -19
  381. package/lib/webrtc/src/nonstandard/dummyMedia.js.map +1 -1
  382. package/lib/webrtc/src/nonstandard/navigator.d.ts +1 -1
  383. package/lib/webrtc/src/nonstandard/recorder/index.js +5 -1
  384. package/lib/webrtc/src/nonstandard/recorder/index.js.map +1 -1
  385. package/lib/webrtc/src/nonstandard/recorder/writer/webm.d.ts +6 -1
  386. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js +31 -2
  387. package/lib/webrtc/src/nonstandard/recorder/writer/webm.js.map +1 -1
  388. package/lib/webrtc/src/nonstandard/userMedia/packetizer.d.ts +16 -0
  389. package/lib/webrtc/src/nonstandard/userMedia/packetizer.js +25 -0
  390. package/lib/webrtc/src/nonstandard/userMedia/packetizer.js.map +1 -1
  391. package/lib/webrtc/src/nonstandard/userMedia.js +6 -13
  392. package/lib/webrtc/src/nonstandard/userMedia.js.map +1 -1
  393. package/lib/webrtc/src/peerConnection.d.ts +44 -8
  394. package/lib/webrtc/src/peerConnection.js +88 -9
  395. package/lib/webrtc/src/peerConnection.js.map +1 -1
  396. package/lib/webrtc/src/polyfill/api.d.ts +2 -1
  397. package/lib/webrtc/src/polyfill/api.js +3 -3
  398. package/lib/webrtc/src/polyfill/api.js.map +1 -1
  399. package/lib/webrtc/src/polyfill/dom.d.ts +21 -7
  400. package/lib/webrtc/src/polyfill/dom.js +15 -0
  401. package/lib/webrtc/src/polyfill/dom.js.map +1 -1
  402. package/lib/webrtc/src/polyfill/globals.d.ts +6 -2
  403. package/lib/webrtc/src/polyfill/globals.js.map +1 -1
  404. package/lib/webrtc/src/polyfill/index.d.ts +1 -1
  405. package/lib/webrtc/src/polyfill/index.js +1 -1
  406. package/lib/webrtc/src/polyfill/index.js.map +1 -1
  407. package/lib/webrtc/src/polyfill/install.d.ts +5 -1
  408. package/lib/webrtc/src/polyfill/install.js +2 -2
  409. package/lib/webrtc/src/polyfill/install.js.map +1 -1
  410. package/lib/webrtc/src/polyfill/mediaDevices.js +28 -4
  411. package/lib/webrtc/src/polyfill/mediaDevices.js.map +1 -1
  412. package/lib/webrtc/src/polyfill/peerConnectionConfig.d.ts +6 -0
  413. package/lib/webrtc/src/polyfill/peerConnectionConfig.js +15 -4
  414. package/lib/webrtc/src/polyfill/peerConnectionConfig.js.map +1 -1
  415. package/lib/webrtc/src/polyfill/selectSettings.d.ts +4 -14
  416. package/lib/webrtc/src/polyfill/selectSettings.js +10 -106
  417. package/lib/webrtc/src/polyfill/selectSettings.js.map +1 -1
  418. package/lib/webrtc/src/polyfill/sourceIo.d.ts +1 -2
  419. package/lib/webrtc/src/polyfill/sourceIo.js +6 -6
  420. package/lib/webrtc/src/polyfill/sourceIo.js.map +1 -1
  421. package/lib/webrtc/src/sctpManager.d.ts +31 -18
  422. package/lib/webrtc/src/sctpManager.js +158 -38
  423. package/lib/webrtc/src/sctpManager.js.map +1 -1
  424. package/lib/webrtc/src/sdp.d.ts +38 -2
  425. package/lib/webrtc/src/sdp.js +84 -3
  426. package/lib/webrtc/src/sdp.js.map +1 -1
  427. package/lib/webrtc/src/sdpManager.d.ts +19 -9
  428. package/lib/webrtc/src/sdpManager.js +26 -4
  429. package/lib/webrtc/src/sdpManager.js.map +1 -1
  430. package/lib/webrtc/src/secureTransportManager.d.ts +11 -2
  431. package/lib/webrtc/src/secureTransportManager.js +84 -5
  432. package/lib/webrtc/src/secureTransportManager.js.map +1 -1
  433. package/lib/webrtc/src/transceiverManager.d.ts +5 -2
  434. package/lib/webrtc/src/transceiverManager.js +42 -14
  435. package/lib/webrtc/src/transceiverManager.js.map +1 -1
  436. package/lib/webrtc/src/transport/dtls-application-gate.d.ts +1 -0
  437. package/lib/webrtc/src/transport/dtls-application-gate.js +143 -0
  438. package/lib/webrtc/src/transport/dtls-application-gate.js.map +1 -0
  439. package/lib/webrtc/src/transport/dtls-attempt.d.ts +1 -0
  440. package/lib/webrtc/src/transport/dtls-attempt.js +79 -0
  441. package/lib/webrtc/src/transport/dtls-attempt.js.map +1 -0
  442. package/lib/webrtc/src/transport/dtls-certificate.d.ts +24 -0
  443. package/lib/webrtc/src/transport/dtls-certificate.js +98 -0
  444. package/lib/webrtc/src/transport/dtls-certificate.js.map +1 -0
  445. package/lib/webrtc/src/transport/dtls-fingerprint.d.ts +7 -0
  446. package/lib/webrtc/src/transport/dtls-fingerprint.js +66 -0
  447. package/lib/webrtc/src/transport/dtls-fingerprint.js.map +1 -0
  448. package/lib/webrtc/src/transport/dtls-ice-transport.d.ts +1 -0
  449. package/lib/webrtc/src/transport/dtls-ice-transport.js +123 -0
  450. package/lib/webrtc/src/transport/dtls-ice-transport.js.map +1 -0
  451. package/lib/webrtc/src/transport/dtls-media-queue.d.ts +1 -0
  452. package/lib/webrtc/src/transport/dtls-media-queue.js +95 -0
  453. package/lib/webrtc/src/transport/dtls-media-queue.js.map +1 -0
  454. package/lib/webrtc/src/transport/dtls-readiness.d.ts +1 -0
  455. package/lib/webrtc/src/transport/dtls-readiness.js +173 -0
  456. package/lib/webrtc/src/transport/dtls-readiness.js.map +1 -0
  457. package/lib/webrtc/src/transport/dtls-sped-handshake.d.ts +1 -0
  458. package/lib/webrtc/src/transport/dtls-sped-handshake.js +146 -0
  459. package/lib/webrtc/src/transport/dtls-sped-handshake.js.map +1 -0
  460. package/lib/webrtc/src/transport/dtls-srtp.d.ts +1 -0
  461. package/lib/webrtc/src/transport/dtls-srtp.js +133 -0
  462. package/lib/webrtc/src/transport/dtls-srtp.js.map +1 -0
  463. package/lib/webrtc/src/transport/dtls-stats.d.ts +1 -0
  464. package/lib/webrtc/src/transport/dtls-stats.js +134 -0
  465. package/lib/webrtc/src/transport/dtls-stats.js.map +1 -0
  466. package/lib/webrtc/src/transport/dtls-types.d.ts +23 -0
  467. package/lib/webrtc/src/transport/dtls-types.js +11 -0
  468. package/lib/webrtc/src/transport/dtls-types.js.map +1 -0
  469. package/lib/webrtc/src/transport/dtls.d.ts +150 -55
  470. package/lib/webrtc/src/transport/dtls.js +1017 -556
  471. package/lib/webrtc/src/transport/dtls.js.map +1 -1
  472. package/lib/webrtc/src/transport/ice.d.ts +35 -2
  473. package/lib/webrtc/src/transport/ice.js +147 -14
  474. package/lib/webrtc/src/transport/ice.js.map +1 -1
  475. package/lib/webrtc/src/transport/iceCandidateAttribute.d.ts +4 -2
  476. package/lib/webrtc/src/transport/iceCandidateAttribute.js.map +1 -1
  477. package/lib/webrtc/src/transport/sctp.d.ts +126 -2
  478. package/lib/webrtc/src/transport/sctp.js +747 -134
  479. package/lib/webrtc/src/transport/sctp.js.map +1 -1
  480. package/lib/webrtc/src/transport/sped.d.ts +139 -0
  481. package/lib/webrtc/src/transport/sped.js +757 -0
  482. package/lib/webrtc/src/transport/sped.js.map +1 -0
  483. package/lib/webrtc/src/types/util.d.ts +6 -0
  484. package/lib/webrtc/src/types/util.js.map +1 -1
  485. package/lib/webrtc/src/utils.d.ts +1 -1
  486. package/lib/webrtc/src/webidl.d.ts +15 -0
  487. package/lib/webrtc/src/webidl.js +34 -0
  488. package/lib/webrtc/src/webidl.js.map +1 -0
  489. package/package.json +7 -3
  490. package/lib/webrtc/src/polyfill/rtcSessionDescription.d.ts +0 -18
  491. package/lib/webrtc/src/polyfill/rtcSessionDescription.js +0 -36
  492. package/lib/webrtc/src/polyfill/rtcSessionDescription.js.map +0 -1
@@ -869,9 +869,9 @@ var Event2 = class {
869
869
  if (timeout) clearTimeout(timeout);
870
870
  resolve([]);
871
871
  },
872
- (err5) => {
872
+ (err6) => {
873
873
  if (timeout) clearTimeout(timeout);
874
- reject(err5);
874
+ reject(err6);
875
875
  }
876
876
  );
877
877
  });
@@ -1067,11 +1067,11 @@ async function findPort(min, max, protocol = "udp4", interfaceAddresses, bindAdd
1067
1067
  address
1068
1068
  })
1069
1069
  );
1070
- const err5 = await new Promise((r) => {
1070
+ const err6 = await new Promise((r) => {
1071
1071
  socket.once("error", (e) => r(e));
1072
1072
  socket.once("listening", () => r());
1073
1073
  });
1074
- if (err5) {
1074
+ if (err6) {
1075
1075
  await new Promise((r) => socket.close(() => r()));
1076
1076
  continue;
1077
1077
  }
@@ -1366,12 +1366,13 @@ var UdpTransport = class _UdpTransport {
1366
1366
  }
1367
1367
  });
1368
1368
  }
1369
- send = async (data, addr) => {
1370
- if (addr && !net.isIP(addr[0])) {
1369
+ send = async (data, addr, options) => {
1370
+ if (addr && !net.isIP(addr[0]) || options?.confirm) {
1371
+ const target = addr ?? [this.rinfo?.address, this.rinfo?.port];
1371
1372
  return new Promise((r, f) => {
1372
- this.socket.send(data, addr[1], addr[0], (error) => {
1373
+ this.socket.send(data, target[1], target[0], (error) => {
1373
1374
  if (error) {
1374
- log("send error", addr, data);
1375
+ log("send error", target, data);
1375
1376
  f(error);
1376
1377
  } else {
1377
1378
  r();
@@ -1448,13 +1449,16 @@ var TcpTransport = class _TcpTransport {
1448
1449
  get closed() {
1449
1450
  return this.stream.closed;
1450
1451
  }
1452
+ get onClosed() {
1453
+ return this.stream.onClosed;
1454
+ }
1451
1455
  get onData() {
1452
1456
  return this.stream.onData;
1453
1457
  }
1454
1458
  set onData(handler) {
1455
1459
  this.stream.onData = handler;
1456
1460
  }
1457
- send = async (data, addr) => {
1461
+ send = async (data, addr, _options) => {
1458
1462
  await this.stream.send(data, addr);
1459
1463
  };
1460
1464
  close = async () => {
@@ -1498,13 +1502,16 @@ var TlsTransport = class _TlsTransport {
1498
1502
  get closed() {
1499
1503
  return this.stream.closed;
1500
1504
  }
1505
+ get onClosed() {
1506
+ return this.stream.onClosed;
1507
+ }
1501
1508
  get onData() {
1502
1509
  return this.stream.onData;
1503
1510
  }
1504
1511
  set onData(handler) {
1505
1512
  this.stream.onData = handler;
1506
1513
  }
1507
- send = async (data, addr) => {
1514
+ send = async (data, addr, _options) => {
1508
1515
  await this.stream.send(data, addr);
1509
1516
  };
1510
1517
  close = async () => {
@@ -1521,6 +1528,8 @@ var StreamTransport = class {
1521
1528
  onData = () => {
1522
1529
  };
1523
1530
  closed = false;
1531
+ /** See `Transport.onClosed`. */
1532
+ onClosed = new Event2();
1524
1533
  rejectConnecting;
1525
1534
  constructor(type, createClient, connectEvent = type === "tls" ? "secureConnect" : "connect", connectTimeoutMs = DEFAULT_CONNECT_TIMEOUT_MS) {
1526
1535
  this.createClient = createClient;
@@ -1576,6 +1585,12 @@ var StreamTransport = class {
1576
1585
  client.on("error", (error) => {
1577
1586
  log(`${this.type} transport error`, error);
1578
1587
  });
1588
+ client.once("close", () => {
1589
+ if (this.closed || this.client !== client) return;
1590
+ this.closed = true;
1591
+ log(`${this.type} transport closed by the peer`);
1592
+ this.onClosed.execute();
1593
+ });
1579
1594
  }
1580
1595
  async waitForConnect() {
1581
1596
  await this.connecting;
@@ -1595,9 +1610,9 @@ var StreamTransport = class {
1595
1610
  void addr;
1596
1611
  await this.connecting;
1597
1612
  await new Promise((resolve, reject) => {
1598
- this.client.write(data, (err5) => {
1599
- if (err5) {
1600
- reject(err5);
1613
+ this.client.write(data, (err6) => {
1614
+ if (err6) {
1615
+ reject(err6);
1601
1616
  return;
1602
1617
  }
1603
1618
  resolve();
@@ -1608,6 +1623,7 @@ var StreamTransport = class {
1608
1623
  this.closed = true;
1609
1624
  this.rejectConnecting?.(new Error(`${this.type} transport closed`));
1610
1625
  this.client?.destroy();
1626
+ this.onClosed.complete();
1611
1627
  };
1612
1628
  };
1613
1629
  function stripZoneId(address) {
@@ -11432,7 +11448,7 @@ var WebmBase = class {
11432
11448
  this.builder.ebmlHeader,
11433
11449
  this.builder.createSegment(this.options.duration)
11434
11450
  ]);
11435
- this.output({ saveToFile: staticPart, kind: "initial" });
11451
+ this.output({ saveToFile: staticPart, kind: "initial", position: 0 });
11436
11452
  this.position += staticPart.length;
11437
11453
  const video = this.tracks.find((t) => t.kind === "video");
11438
11454
  if (video) {
@@ -11497,7 +11513,8 @@ var WebmBase = class {
11497
11513
  this.output({
11498
11514
  saveToFile: Buffer.from(cluster),
11499
11515
  kind: "cluster",
11500
- previousDuration: duration
11516
+ previousDuration: duration,
11517
+ position: this.position
11501
11518
  });
11502
11519
  this.position += cluster.length;
11503
11520
  this.elapsed = void 0;
@@ -11538,7 +11555,7 @@ var WebmBase = class {
11538
11555
  elapsed
11539
11556
  );
11540
11557
  this.internalStats["createSimpleBlock_trackNumber" + trackNumber] = (/* @__PURE__ */ new Date()).toISOString();
11541
- this.output({ saveToFile: block, kind: "block" });
11558
+ this.output({ saveToFile: block, kind: "block", position: this.position });
11542
11559
  this.position += block.length;
11543
11560
  const [cuePoint] = this.cuePoints.slice(-1);
11544
11561
  if (cuePoint) {
@@ -11567,15 +11584,18 @@ var WebmBase = class {
11567
11584
  this.output({
11568
11585
  saveToFile: Buffer.from(cues),
11569
11586
  kind: "cuePoints",
11570
- previousDuration: duration
11587
+ previousDuration: duration,
11588
+ position: this.position
11571
11589
  });
11590
+ this.position += cues.length;
11572
11591
  const durationElement = this.builder.createDuration(duration);
11573
11592
  const header = Buffer.concat([
11574
11593
  this.builder.ebmlHeader,
11575
11594
  this.builder.createSegment(duration)
11576
11595
  ]);
11577
11596
  this.output({
11578
- eol: { duration, durationElement, header, clusters: this.clusters }
11597
+ eol: { duration, durationElement, header, clusters: this.clusters },
11598
+ position: this.position
11579
11599
  });
11580
11600
  this.timestamps = {};
11581
11601
  this.clusters = [];
@@ -11688,18 +11708,156 @@ var RtpTimeBase = class {
11688
11708
  var RtpTimeCallback = class extends SimpleProcessorCallbackBase(RtpTimeBase) {
11689
11709
  };
11690
11710
 
11711
+ // ../rtp/src/extra/processor/webmFileWriter.ts
11712
+ import { constants as fsConstants, open as fsOpen } from "fs/promises";
11713
+
11714
+ // ../rtp/src/extra/processor/fsRetry.ts
11715
+ var TransientFsErrorCodes = Object.freeze(["EBUSY"]);
11716
+ var MaxAttempts = 8;
11717
+ var MaxTotalDelayMs = 1e3;
11718
+ var BaseDelayMs = 20;
11719
+ function isTransientFsError(error) {
11720
+ const code = error?.code;
11721
+ return typeof code === "string" && TransientFsErrorCodes.includes(code);
11722
+ }
11723
+ var sleepFor = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
11724
+ async function retryTransientFsError(op, options = {}) {
11725
+ const isTransient = options.isTransient ?? isTransientFsError;
11726
+ const sleep = options.sleep ?? sleepFor;
11727
+ let waited = 0;
11728
+ for (let attempt = 1; ; attempt++) {
11729
+ try {
11730
+ return await op();
11731
+ } catch (error) {
11732
+ const delay = BaseDelayMs * attempt;
11733
+ if (!isTransient(error) || attempt >= MaxAttempts || waited + delay > MaxTotalDelayMs) {
11734
+ throw error;
11735
+ }
11736
+ waited += delay;
11737
+ await sleep(delay);
11738
+ }
11739
+ }
11740
+ }
11741
+ async function withFileHandle(open, body) {
11742
+ const handle = await open();
11743
+ let result;
11744
+ try {
11745
+ result = await body(handle);
11746
+ } catch (error) {
11747
+ await handle.close().catch(() => void 0);
11748
+ throw error;
11749
+ }
11750
+ await handle.close();
11751
+ return result;
11752
+ }
11753
+
11754
+ // ../rtp/src/extra/processor/webmFileWriter.ts
11755
+ var OpenExistingOrCreate = fsConstants.O_RDWR | fsConstants.O_CREAT;
11756
+ function createWebmFileWriter(path2, options = {}) {
11757
+ const open = options.open ?? ((p, flags) => fsOpen(p, flags));
11758
+ const queue = new PromiseQueue();
11759
+ let written = 0;
11760
+ let failure;
11761
+ const writeAll = async (handle, buf, position) => {
11762
+ for (let done = 0; done < buf.length; ) {
11763
+ const { bytesWritten } = await handle.write(
11764
+ buf,
11765
+ done,
11766
+ buf.length - done,
11767
+ position + done
11768
+ );
11769
+ if (bytesWritten <= 0) {
11770
+ throw new Error(`webm write made no progress at ${position + done}`);
11771
+ }
11772
+ done += bytesWritten;
11773
+ }
11774
+ };
11775
+ const saveChunk = async (value, chunk) => {
11776
+ const known = value.position ?? (written > 0 || value.kind === "initial" ? written : void 0);
11777
+ let offset = known;
11778
+ await retryTransientFsError(
11779
+ () => withFileHandle(
11780
+ () => open(
11781
+ path2,
11782
+ offset === 0 ? "w" : offset === void 0 ? OpenExistingOrCreate : "r+"
11783
+ ),
11784
+ async (handle) => {
11785
+ if (offset === void 0) {
11786
+ offset = (await handle.stat()).size;
11787
+ }
11788
+ await writeAll(handle, chunk, offset);
11789
+ }
11790
+ ),
11791
+ options
11792
+ );
11793
+ written = offset + chunk.length;
11794
+ };
11795
+ const saveEol = async (value, eol) => {
11796
+ const { durationElement, clusters } = eol;
11797
+ const known = value.position ?? (written > 0 ? written : void 0);
11798
+ await retryTransientFsError(
11799
+ () => withFileHandle(
11800
+ () => open(path2, "r+"),
11801
+ async (handle) => {
11802
+ const total = known ?? (await handle.stat()).size;
11803
+ await handle.truncate(total);
11804
+ await writeAll(
11805
+ handle,
11806
+ Buffer.from(durationElement),
11807
+ DurationPosition
11808
+ );
11809
+ for (const { position, size } of clusters) {
11810
+ await writeAll(
11811
+ handle,
11812
+ replaceClusterSize(size),
11813
+ position + ClusterSizeOffset
11814
+ );
11815
+ }
11816
+ await writeAll(
11817
+ handle,
11818
+ replaceSegmentSize(total),
11819
+ SegmentSizePosition
11820
+ );
11821
+ }
11822
+ ),
11823
+ options
11824
+ );
11825
+ };
11826
+ return (value) => queue.push(async () => {
11827
+ if (failure !== void 0) {
11828
+ throw failure;
11829
+ }
11830
+ try {
11831
+ if (value.saveToFile) {
11832
+ await saveChunk(value, value.saveToFile);
11833
+ return false;
11834
+ } else if (value.eol) {
11835
+ await saveEol(value, value.eol);
11836
+ return true;
11837
+ }
11838
+ return false;
11839
+ } catch (error) {
11840
+ failure = error;
11841
+ throw error;
11842
+ }
11843
+ });
11844
+ }
11845
+
11691
11846
  // ../rtp/src/extra/processor/webmCallback.ts
11692
- import { appendFile as appendFile3, open, stat } from "fs/promises";
11693
11847
  var WebmCallback = class extends WebmBase {
11694
11848
  cb;
11695
11849
  queue = new PromiseQueue();
11850
+ /** a failed output callback (e.g. file write error) is reported here instead of an unhandled rejection */
11851
+ onError = new Event2();
11696
11852
  constructor(tracks, options = {}) {
11697
11853
  super(
11698
11854
  tracks,
11699
11855
  async (output) => {
11700
11856
  const cb = this.cb;
11701
11857
  if (cb) {
11702
- await this.queue.push(() => cb(output));
11858
+ await this.queue.push(() => cb(output)).catch((error) => {
11859
+ this.onError.execute(error);
11860
+ });
11703
11861
  }
11704
11862
  },
11705
11863
  options
@@ -11720,41 +11878,7 @@ var WebmCallback = class extends WebmBase {
11720
11878
  this.queue.cancel();
11721
11879
  };
11722
11880
  };
11723
- var saveToFileSystem = (path2) => {
11724
- const queue = new PromiseQueue();
11725
- return async (value) => {
11726
- return await queue.push(async () => {
11727
- if (value.saveToFile) {
11728
- await appendFile3(path2, value.saveToFile);
11729
- return false;
11730
- } else if (value.eol) {
11731
- const { durationElement, clusters } = value.eol;
11732
- const handler = await open(path2, "r+");
11733
- await handler.write(
11734
- durationElement,
11735
- 0,
11736
- durationElement.length,
11737
- DurationPosition
11738
- );
11739
- for (const { position, size } of clusters) {
11740
- const resize2 = replaceClusterSize(size);
11741
- await handler.write(
11742
- resize2,
11743
- 0,
11744
- resize2.length,
11745
- position + ClusterSizeOffset
11746
- );
11747
- }
11748
- const meta = await stat(path2);
11749
- const resize = replaceSegmentSize(meta.size);
11750
- await handler.write(resize, 0, resize.length, SegmentSizePosition);
11751
- await handler.close();
11752
- return true;
11753
- }
11754
- return false;
11755
- });
11756
- };
11757
- };
11881
+ var saveToFileSystem = (path2) => createWebmFileWriter(path2);
11758
11882
 
11759
11883
  // ../rtp/src/extra/processor/webmStream.ts
11760
11884
  import { ReadableStream as ReadableStream2, WritableStream } from "stream/web";
@@ -11799,6 +11923,16 @@ var WebmStream = class extends WebmBase {
11799
11923
  // src/nonstandard/navigator.ts
11800
11924
  import { createSocket as createSocket3 } from "dgram";
11801
11925
 
11926
+ // src/errors.ts
11927
+ var OverconstrainedError = class extends DOMException {
11928
+ constraint;
11929
+ constructor(constraint, message = "") {
11930
+ super(message, "OverconstrainedError");
11931
+ Object.setPrototypeOf(this, new.target.prototype);
11932
+ this.constraint = constraint;
11933
+ }
11934
+ };
11935
+
11802
11936
  // src/helper.ts
11803
11937
  import { EventEmitter } from "node:events";
11804
11938
  var EventTarget2 = class extends EventEmitter {
@@ -11859,6 +11993,12 @@ var EventTarget2 = class extends EventEmitter {
11859
11993
 
11860
11994
  // src/dataChannel.ts
11861
11995
  var log11 = debug("werift:packages/webrtc/src/dataChannel.ts");
11996
+ var RTCDataChannelBinaryType = {
11997
+ nodebuffer: "nodebuffer",
11998
+ arraybuffer: "arraybuffer",
11999
+ blob: "blob"
12000
+ };
12001
+ var RTCDataChannelBinaryTypes = Object.values(RTCDataChannelBinaryType);
11862
12002
 
11863
12003
  // ../common/src/asn1.ts
11864
12004
  var Asn1Tag = {
@@ -12099,10 +12239,18 @@ var HashAlgorithm = {
12099
12239
  var CipherSuite = {
12100
12240
  TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195: 49195,
12101
12241
  //49195,
12102
- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199: 49199
12242
+ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199: 49199,
12103
12243
  //49199
12244
+ /** TLS 1.3 AES-128-GCM-SHA256 */
12245
+ TLS_AES_128_GCM_SHA256_0x1301: 4865
12104
12246
  };
12105
- var CipherSuiteList = Object.values(CipherSuite);
12247
+ var CipherSuiteList = [
12248
+ CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195,
12249
+ CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199
12250
+ ];
12251
+ var TLS13_CIPHER_SUITES = [
12252
+ CipherSuite.TLS_AES_128_GCM_SHA256_0x1301
12253
+ ];
12106
12254
  var NamedCurveAlgorithm = {
12107
12255
  x25519_29: 29,
12108
12256
  secp256r1_23: 23
@@ -12114,6 +12262,56 @@ var signatures = [
12114
12262
  { hash: HashAlgorithm.sha256_4, signature: SignatureAlgorithm.ecdsa_3 }
12115
12263
  ];
12116
12264
 
12265
+ // ../dtls/src/cipher/namedCurve.ts
12266
+ import { generateKeyPairSync } from "node:crypto";
12267
+
12268
+ // ../dtls/src/cipher/ec.ts
12269
+ import { createECDH } from "node:crypto";
12270
+ var p256Keypair = () => {
12271
+ const ecdh = createECDH("prime256v1");
12272
+ ecdh.generateKeys();
12273
+ const privateKey = ecdh.getPrivateKey();
12274
+ const publicKey = ecdh.getPublicKey();
12275
+ return {
12276
+ privateKey,
12277
+ publicKey
12278
+ };
12279
+ };
12280
+ var p256PreMasterSecret = ({
12281
+ publicKey,
12282
+ privateKey
12283
+ }) => {
12284
+ const ecdh = createECDH("prime256v1");
12285
+ ecdh.setPrivateKey(privateKey);
12286
+ return ecdh.computeSecret(publicKey);
12287
+ };
12288
+
12289
+ // ../dtls/src/cipher/namedCurve.ts
12290
+ function generateKeyPair(namedCurve) {
12291
+ switch (namedCurve) {
12292
+ case NamedCurveAlgorithm.secp256r1_23: {
12293
+ const { privateKey, publicKey } = p256Keypair();
12294
+ return {
12295
+ curve: namedCurve,
12296
+ privateKey,
12297
+ publicKey
12298
+ };
12299
+ }
12300
+ case NamedCurveAlgorithm.x25519_29: {
12301
+ const keys = generateKeyPairSync("x25519");
12302
+ const privateJwk = keys.privateKey.export({ format: "jwk" });
12303
+ const publicJwk = keys.publicKey.export({ format: "jwk" });
12304
+ return {
12305
+ curve: namedCurve,
12306
+ privateKey: Buffer.from(privateJwk.d, "base64url"),
12307
+ publicKey: Buffer.from(publicJwk.x, "base64url")
12308
+ };
12309
+ }
12310
+ default:
12311
+ throw new Error();
12312
+ }
12313
+ }
12314
+
12117
12315
  // ../dtls/src/cipher/suites/abstract.ts
12118
12316
  var SessionType = {
12119
12317
  CLIENT: 1,
@@ -12155,6 +12353,31 @@ var AbstractCipher = class {
12155
12353
  }
12156
12354
  };
12157
12355
 
12356
+ // ../dtls/src/handshake/const.ts
12357
+ var HandshakeType = {
12358
+ hello_request_0: 0,
12359
+ client_hello_1: 1,
12360
+ server_hello_2: 2,
12361
+ hello_verify_request_3: 3,
12362
+ /** TLS 1.3 NewSessionTicket */
12363
+ new_session_ticket_4: 4,
12364
+ /** TLS 1.3 EndOfEarlyData */
12365
+ end_of_early_data_5: 5,
12366
+ /** TLS 1.3 EncryptedExtensions */
12367
+ encrypted_extensions_8: 8,
12368
+ certificate_11: 11,
12369
+ server_key_exchange_12: 12,
12370
+ certificate_request_13: 13,
12371
+ server_hello_done_14: 14,
12372
+ certificate_verify_15: 15,
12373
+ client_key_exchange_16: 16,
12374
+ finished_20: 20,
12375
+ /** TLS 1.3 KeyUpdate */
12376
+ key_update_24: 24,
12377
+ /** TLS 1.3 MessageHash (HRR transcript) */
12378
+ message_hash_254: 254
12379
+ };
12380
+
12158
12381
  // ../dtls/src/record/message/fragment.ts
12159
12382
  var { decode: decode4, encode: encode4, types: types5 } = binaryData_exports;
12160
12383
  var FragmentedHandshake = class _FragmentedHandshake {
@@ -12247,10 +12470,39 @@ var FragmentedHandshake = class _FragmentedHandshake {
12247
12470
  if (!messages?.length) {
12248
12471
  throw new Error("cannot reassemble handshake from empty array");
12249
12472
  }
12473
+ const total = messages[0].length;
12474
+ if (total < 0 || total > 16777216) {
12475
+ throw new Error("invalid handshake message length");
12476
+ }
12250
12477
  messages = messages.sort((a, b) => a.fragment_offset - b.fragment_offset);
12251
- const combined = Buffer.alloc(messages[0].length);
12478
+ const combined = Buffer.alloc(total);
12479
+ const covered = new Uint8Array(total);
12252
12480
  for (const msg of messages) {
12253
- msg.fragment.copy(combined, msg.fragment_offset);
12481
+ if (msg.length !== total) {
12482
+ throw new Error("fragment total length mismatch");
12483
+ }
12484
+ if (msg.fragment_length !== msg.fragment.length) {
12485
+ throw new Error("fragment_length does not match buffer");
12486
+ }
12487
+ if (msg.fragment_offset < 0 || msg.fragment_length < 0 || msg.fragment_offset + msg.fragment_length > total) {
12488
+ throw new Error("fragment range exceeds message length");
12489
+ }
12490
+ for (let i = 0; i < msg.fragment_length; i++) {
12491
+ const idx = msg.fragment_offset + i;
12492
+ if (covered[idx]) {
12493
+ if (combined[idx] !== msg.fragment[i]) {
12494
+ throw new Error("overlapping fragment conflict");
12495
+ }
12496
+ } else {
12497
+ covered[idx] = 1;
12498
+ combined[idx] = msg.fragment[i];
12499
+ }
12500
+ }
12501
+ }
12502
+ for (let i = 0; i < total; i++) {
12503
+ if (!covered[i]) {
12504
+ throw new Error("incomplete reassembly");
12505
+ }
12254
12506
  }
12255
12507
  return new _FragmentedHandshake(
12256
12508
  messages[0].msg_type,
@@ -12261,33 +12513,16 @@ var FragmentedHandshake = class _FragmentedHandshake {
12261
12513
  combined
12262
12514
  );
12263
12515
  }
12264
- static findAllFragments(fragments, type) {
12265
- const reference = fragments.find((v) => v.msg_type === type);
12266
- if (!reference) return [];
12267
- if (!fragments?.length) return [];
12268
- return fragments.filter((f) => {
12269
- return f.msg_type === reference.msg_type && f.message_seq === reference.message_seq && f.length === reference.length;
12270
- });
12271
- }
12272
- };
12273
-
12274
- // ../dtls/src/handshake/const.ts
12275
- var HandshakeType = {
12276
- hello_request_0: 0,
12277
- client_hello_1: 1,
12278
- server_hello_2: 2,
12279
- hello_verify_request_3: 3,
12280
- certificate_11: 11,
12281
- server_key_exchange_12: 12,
12282
- certificate_request_13: 13,
12283
- server_hello_done_14: 14,
12284
- certificate_verify_15: 15,
12285
- client_key_exchange_16: 16,
12286
- finished_20: 20
12287
12516
  };
12288
12517
 
12289
12518
  // ../dtls/src/handshake/random.ts
12290
12519
  import { randomBytes as randomBytes3 } from "crypto";
12520
+
12521
+ // ../dtls/src/version.ts
12522
+ var DOWNGRADE_TLS12_SENTINEL = Buffer.from("444F574E47524401", "hex");
12523
+ var DOWNGRADE_TLS11_SENTINEL = Buffer.from("444F574E47524400", "hex");
12524
+
12525
+ // ../dtls/src/handshake/random.ts
12291
12526
  var { decode: decode5, encode: encode5, types: types6 } = binaryData_exports;
12292
12527
  var DtlsRandom = class _DtlsRandom {
12293
12528
  gmt_unix_time;
@@ -12311,6 +12546,34 @@ var DtlsRandom = class _DtlsRandom {
12311
12546
  serialize() {
12312
12547
  return encode5(this, _DtlsRandom.spec);
12313
12548
  }
12549
+ /** Full 32-byte Random (gmt_unix_time || random_bytes). */
12550
+ static bytes32(random) {
12551
+ const b = Buffer.alloc(32);
12552
+ b.writeUInt32BE(random.gmt_unix_time >>> 0, 0);
12553
+ random.random_bytes.copy(b, 4);
12554
+ return b;
12555
+ }
12556
+ /** Full 32-byte Random (gmt_unix_time || random_bytes). */
12557
+ toBuffer32() {
12558
+ return _DtlsRandom.bytes32(this);
12559
+ }
12560
+ /**
12561
+ * RFC 8446 §4.1.3 / RFC 9147: TLS 1.3-capable server negotiating TLS 1.2
12562
+ * MUST set the last 8 bytes of ServerHello.Random to DOWNGRD\\x01.
12563
+ * Mutates `random_bytes` in place (must run before ServerHello is sent and
12564
+ * before the same Random is used in the PRF).
12565
+ */
12566
+ applyTls12DowngradeSentinel() {
12567
+ if (this.random_bytes.length < 8) {
12568
+ throw new Error(
12569
+ "DtlsRandom.random_bytes too short for downgrade sentinel"
12570
+ );
12571
+ }
12572
+ DOWNGRADE_TLS12_SENTINEL.copy(
12573
+ this.random_bytes,
12574
+ this.random_bytes.length - 8
12575
+ );
12576
+ }
12314
12577
  };
12315
12578
 
12316
12579
  // ../dtls/src/handshake/message/client/hello.ts
@@ -12375,120 +12638,288 @@ var ClientHello = class _ClientHello {
12375
12638
  }
12376
12639
  };
12377
12640
 
12378
- // ../dtls/src/flight/flight.ts
12379
- var warn = debug("werift-dtls : packages/dtls/src/flight/flight.ts : warn");
12380
- var err = debug("werift-dtls : packages/dtls/src/flight/flight.ts : err");
12381
-
12382
- // ../dtls/src/flight/client/flight3.ts
12383
- var log12 = debug(
12384
- "werift-dtls : packages/dtls/src/flight/client/flight3.ts : log"
12385
- );
12641
+ // ../dtls/src/handshake/extensions/ids.ts
12642
+ var EXT_PADDING = 21;
12643
+ var EXT_EARLY_DATA = 42;
12386
12644
 
12387
- // ../dtls/src/cipher/key-exchange.ts
12388
- var signTypes = {
12389
- NULL: 0,
12390
- ECDHE: 1
12391
- };
12392
- var keyTypes = {
12393
- NULL: 0,
12394
- RSA: 1,
12395
- ECDSA: 2,
12396
- PSK: 3
12397
- };
12398
- var kxTypes = {
12399
- NULL: 0,
12400
- RSA: 1,
12401
- ECDHE_RSA: 2,
12402
- ECDHE_ECDSA: 3,
12403
- PSK: 4,
12404
- ECDHE_PSK: 5
12405
- };
12406
- var KeyExchange = class {
12407
- id = 0;
12408
- name;
12409
- signType;
12410
- keyType;
12411
- /**
12412
- * @returns {string}
12413
- */
12414
- toString() {
12415
- return this.name;
12645
+ // ../dtls/src/handshake/extensions/cookie.ts
12646
+ var COOKIE_EXTENSION_TYPE = 44;
12647
+ var ADDRESS_COOKIE_LENGTH = 1 + 16 + 32 + 32 + 1 + 2 + 4 + 16;
12648
+ var CookieExtension = class _CookieExtension {
12649
+ static type = COOKIE_EXTENSION_TYPE;
12650
+ cookie;
12651
+ constructor(cookie) {
12652
+ this.cookie = cookie;
12653
+ }
12654
+ static fromData(data) {
12655
+ if (data.length < 2) throw new Error("cookie extension: truncated");
12656
+ const len = data.readUInt16BE(0);
12657
+ if (len < 1) throw new Error("cookie extension: empty cookie not allowed");
12658
+ if (data.length !== 2 + len) {
12659
+ throw new Error(
12660
+ `cookie extension: length mismatch (declared ${len}, total ${data.length - 2})`
12661
+ );
12662
+ }
12663
+ return new _CookieExtension(Buffer.from(data.subarray(2, 2 + len)));
12664
+ }
12665
+ serializeData() {
12666
+ const out = Buffer.alloc(2 + this.cookie.length);
12667
+ out.writeUInt16BE(this.cookie.length, 0);
12668
+ this.cookie.copy(out, 2);
12669
+ return out;
12670
+ }
12671
+ get extension() {
12672
+ return { type: _CookieExtension.type, data: this.serializeData() };
12416
12673
  }
12417
12674
  };
12418
- function createRSAKeyExchange() {
12419
- const exchange = new KeyExchange();
12420
- exchange.id = kxTypes.RSA;
12421
- exchange.name = "RSA";
12422
- exchange.keyType = keyTypes.RSA;
12423
- return exchange;
12675
+
12676
+ // ../dtls/src/record/v1_3/record.ts
12677
+ var DTLS13_MAX_PLAINTEXT_LENGTH = 1 << 14;
12678
+ var DTLS13_MAX_CIPHERTEXT_LENGTH = DTLS13_MAX_PLAINTEXT_LENGTH + 256;
12679
+
12680
+ // ../dtls/src/carrier/direct.ts
12681
+ import { AsyncLocalStorage } from "node:async_hooks";
12682
+ var inboundInjectEpochAls = new AsyncLocalStorage();
12683
+
12684
+ // ../dtls/src/cipher/tls13/hkdf.ts
12685
+ import { createHash, createHmac as createHmac3 } from "crypto";
12686
+ var DTLS13_LABEL_PREFIX = "dtls13";
12687
+ function hashSha256(data) {
12688
+ return createHash("sha256").update(data).digest();
12424
12689
  }
12425
- function createECDHERSAKeyExchange() {
12426
- const exchange = new KeyExchange();
12427
- exchange.id = kxTypes.ECDHE_RSA;
12428
- exchange.name = "ECDHE_RSA";
12429
- exchange.signType = signTypes.ECDHE;
12430
- exchange.keyType = keyTypes.RSA;
12431
- return exchange;
12690
+ function hmacSha256(key, data) {
12691
+ return createHmac3("sha256", key).update(data).digest();
12432
12692
  }
12433
- function createECDHEECDSAKeyExchange() {
12434
- const exchange = new KeyExchange();
12435
- exchange.id = kxTypes.ECDHE_ECDSA;
12436
- exchange.name = "ECDHE_ECDSA";
12437
- exchange.signType = signTypes.ECDHE;
12438
- exchange.keyType = keyTypes.ECDSA;
12439
- return exchange;
12693
+ function hkdfExtract(salt, ikm) {
12694
+ return hmacSha256(salt.length === 0 ? Buffer.alloc(32) : salt, ikm);
12440
12695
  }
12441
- function createPSKKeyExchange() {
12442
- const exchange = new KeyExchange();
12443
- exchange.id = kxTypes.PSK;
12444
- exchange.name = "PSK";
12445
- exchange.signType = signTypes.NULL;
12446
- exchange.keyType = keyTypes.PSK;
12447
- return exchange;
12696
+ function hkdfExpand(prk, info, length) {
12697
+ const hashLen = 32;
12698
+ const n = Math.ceil(length / hashLen);
12699
+ const okm = [];
12700
+ let prev = Buffer.alloc(0);
12701
+ for (let i = 1; i <= n; i++) {
12702
+ prev = Buffer.from(
12703
+ hmacSha256(prk, Buffer.concat([prev, info, Buffer.from([i])]))
12704
+ );
12705
+ okm.push(prev);
12706
+ }
12707
+ return Buffer.concat(okm).subarray(0, length);
12448
12708
  }
12449
- function createECDHEPSKKeyExchange() {
12450
- const exchange = new KeyExchange();
12451
- exchange.id = kxTypes.ECDHE_PSK;
12452
- exchange.name = "ECDHE_PSK";
12453
- exchange.signType = signTypes.ECDHE;
12454
- exchange.keyType = keyTypes.PSK;
12455
- return exchange;
12709
+ function hkdfExpandLabel(secret, label, context, length, labelPrefix = DTLS13_LABEL_PREFIX) {
12710
+ const fullLabel = Buffer.from(labelPrefix + label, "ascii");
12711
+ const hkdfLabel = Buffer.alloc(2 + 1 + fullLabel.length + 1 + context.length);
12712
+ hkdfLabel.writeUInt16BE(length, 0);
12713
+ hkdfLabel.writeUInt8(fullLabel.length, 2);
12714
+ fullLabel.copy(hkdfLabel, 3);
12715
+ hkdfLabel.writeUInt8(context.length, 3 + fullLabel.length);
12716
+ context.copy(hkdfLabel, 4 + fullLabel.length);
12717
+ return hkdfExpand(secret, hkdfLabel, length);
12718
+ }
12719
+ function deriveSecret(secret, label, messages, labelPrefix = DTLS13_LABEL_PREFIX) {
12720
+ const transcriptHash = hashSha256(messages);
12721
+ return hkdfExpandLabel(secret, label, transcriptHash, 32, labelPrefix);
12722
+ }
12723
+ function emptyHashSha256() {
12724
+ return hashSha256(Buffer.alloc(0));
12456
12725
  }
12457
12726
 
12458
- // ../dtls/src/cipher/suites/aead.ts
12459
- import { createCipheriv as createCipheriv5, createDecipheriv as createDecipheriv3 } from "crypto";
12727
+ // ../dtls/src/cipher/tls13/keySchedule.ts
12728
+ var HASH_LEN = 32;
12729
+ var KEY_LEN = 16;
12730
+ var IV_LEN = 12;
12731
+ var Dtls13KeySchedule = class {
12732
+ labelPrefix;
12733
+ constructor(labelPrefix = DTLS13_LABEL_PREFIX) {
12734
+ this.labelPrefix = labelPrefix;
12735
+ }
12736
+ earlySecret(psk = Buffer.alloc(0)) {
12737
+ const ikm = psk.length === 0 ? Buffer.alloc(HASH_LEN) : psk;
12738
+ return hkdfExtract(Buffer.alloc(HASH_LEN), ikm);
12739
+ }
12740
+ deriveHandshakeSecrets(sharedSecret, helloTranscript) {
12741
+ const earlySecret = this.earlySecret();
12742
+ const derived = deriveSecret(
12743
+ earlySecret,
12744
+ "derived",
12745
+ Buffer.alloc(0),
12746
+ this.labelPrefix
12747
+ );
12748
+ const derivedSecret = hkdfExpandLabel(
12749
+ earlySecret,
12750
+ "derived",
12751
+ emptyHashSha256(),
12752
+ HASH_LEN,
12753
+ this.labelPrefix
12754
+ );
12755
+ const handshakeSecret = hkdfExtract(derivedSecret, sharedSecret);
12756
+ const clientHandshakeTrafficSecret = deriveSecret(
12757
+ handshakeSecret,
12758
+ "c hs traffic",
12759
+ helloTranscript,
12760
+ this.labelPrefix
12761
+ );
12762
+ const serverHandshakeTrafficSecret = deriveSecret(
12763
+ handshakeSecret,
12764
+ "s hs traffic",
12765
+ helloTranscript,
12766
+ this.labelPrefix
12767
+ );
12768
+ return {
12769
+ earlySecret,
12770
+ handshakeSecret,
12771
+ clientHandshakeTrafficSecret,
12772
+ serverHandshakeTrafficSecret
12773
+ };
12774
+ }
12775
+ deriveApplicationSecrets(handshakeSecret, handshakeTranscript) {
12776
+ const derivedSecret = hkdfExpandLabel(
12777
+ handshakeSecret,
12778
+ "derived",
12779
+ emptyHashSha256(),
12780
+ HASH_LEN,
12781
+ this.labelPrefix
12782
+ );
12783
+ const masterSecret = hkdfExtract(derivedSecret, Buffer.alloc(HASH_LEN));
12784
+ const clientApplicationTrafficSecret = deriveSecret(
12785
+ masterSecret,
12786
+ "c ap traffic",
12787
+ handshakeTranscript,
12788
+ this.labelPrefix
12789
+ );
12790
+ const serverApplicationTrafficSecret = deriveSecret(
12791
+ masterSecret,
12792
+ "s ap traffic",
12793
+ handshakeTranscript,
12794
+ this.labelPrefix
12795
+ );
12796
+ const exporterMasterSecret = deriveSecret(
12797
+ masterSecret,
12798
+ "exp master",
12799
+ handshakeTranscript,
12800
+ this.labelPrefix
12801
+ );
12802
+ return {
12803
+ masterSecret,
12804
+ clientApplicationTrafficSecret,
12805
+ serverApplicationTrafficSecret,
12806
+ exporterMasterSecret
12807
+ };
12808
+ }
12809
+ trafficKeys(trafficSecret) {
12810
+ return {
12811
+ key: hkdfExpandLabel(
12812
+ trafficSecret,
12813
+ "key",
12814
+ Buffer.alloc(0),
12815
+ KEY_LEN,
12816
+ this.labelPrefix
12817
+ ),
12818
+ iv: hkdfExpandLabel(
12819
+ trafficSecret,
12820
+ "iv",
12821
+ Buffer.alloc(0),
12822
+ IV_LEN,
12823
+ this.labelPrefix
12824
+ ),
12825
+ /** Record number encryption key (RFC 9147 §4.2.3) */
12826
+ snKey: hkdfExpandLabel(
12827
+ trafficSecret,
12828
+ "sn",
12829
+ Buffer.alloc(0),
12830
+ KEY_LEN,
12831
+ this.labelPrefix
12832
+ )
12833
+ };
12834
+ }
12835
+ finishedKey(baseKey) {
12836
+ return hkdfExpandLabel(
12837
+ baseKey,
12838
+ "finished",
12839
+ Buffer.alloc(0),
12840
+ HASH_LEN,
12841
+ this.labelPrefix
12842
+ );
12843
+ }
12844
+ /**
12845
+ * TLS 1.3 binder_key (RFC 8446 §7.1).
12846
+ * Derive-Secret(Early Secret, "ext binder" | "res binder", "")
12847
+ * Used for PSK binder computation; Epic 1 exposes derivation for vectors /
12848
+ * future 0-RTT (handshake path remains PSK-less).
12849
+ */
12850
+ binderKey(earlySecret, resumption = false) {
12851
+ const label = resumption ? "res binder" : "ext binder";
12852
+ return deriveSecret(earlySecret, label, Buffer.alloc(0), this.labelPrefix);
12853
+ }
12854
+ /**
12855
+ * Finished verify_data = HMAC(finished_key, Hash(Handshake Context))
12856
+ * (RFC 8446 §4.4.4). Same construction for PSK binders with binder_key.
12857
+ */
12858
+ verifyData(baseKey, transcript) {
12859
+ const finishedKey = this.finishedKey(baseKey);
12860
+ return hmacSha256(finishedKey, hashSha256(transcript));
12861
+ }
12862
+ /**
12863
+ * PSK binder HMAC (RFC 8446 §4.2.11.2):
12864
+ * HMAC(finished_key(binder_key), Hash(transcript up to Binder))
12865
+ * Same primitive as Finished verify_data with binder_key as base.
12866
+ */
12867
+ binderVerifyData(binderKey, transcript) {
12868
+ return this.verifyData(binderKey, transcript);
12869
+ }
12870
+ /**
12871
+ * Traffic secret update for KeyUpdate (RFC 8446 §7.2).
12872
+ * application_traffic_secret_N+1 =
12873
+ * HKDF-Expand-Label(..., "traffic upd", "", Hash.length)
12874
+ */
12875
+ updateTrafficSecret(secret) {
12876
+ return hkdfExpandLabel(
12877
+ secret,
12878
+ "traffic upd",
12879
+ Buffer.alloc(0),
12880
+ HASH_LEN,
12881
+ this.labelPrefix
12882
+ );
12883
+ }
12884
+ /**
12885
+ * TLS 1.3 exporter (RFC 8446 §7.5).
12886
+ * Used for DTLS-SRTP EXTRACTOR-dtls_srtp on 1.3 connections.
12887
+ */
12888
+ exportKeyingMaterial(exporterMasterSecret, label, context, length) {
12889
+ const derived = deriveSecret(
12890
+ exporterMasterSecret,
12891
+ label,
12892
+ Buffer.alloc(0),
12893
+ this.labelPrefix
12894
+ );
12895
+ return hkdfExpandLabel(
12896
+ derived,
12897
+ "exporter",
12898
+ hashSha256(context),
12899
+ length,
12900
+ this.labelPrefix
12901
+ );
12902
+ }
12903
+ };
12904
+ var defaultKeySchedule = new Dtls13KeySchedule(DTLS13_LABEL_PREFIX);
12905
+
12906
+ // ../dtls/src/context/cipher.ts
12907
+ import {
12908
+ createPrivateKey as createPrivateKey2,
12909
+ createSign,
12910
+ generateKeyPair as generateKeyPair2,
12911
+ X509Certificate
12912
+ } from "node:crypto";
12913
+ import { promisify } from "node:util";
12460
12914
 
12461
12915
  // ../dtls/src/cipher/prf.ts
12462
12916
  import {
12463
- createHash,
12464
- createHmac as createHmac3,
12917
+ createHash as createHash2,
12918
+ createHmac as createHmac4,
12465
12919
  createPrivateKey,
12466
12920
  createPublicKey,
12467
12921
  diffieHellman
12468
12922
  } from "node:crypto";
12469
-
12470
- // ../dtls/src/cipher/ec.ts
12471
- import { createECDH } from "node:crypto";
12472
- var p256Keypair = () => {
12473
- const ecdh = createECDH("prime256v1");
12474
- ecdh.generateKeys();
12475
- const privateKey = ecdh.getPrivateKey();
12476
- const publicKey = ecdh.getPublicKey();
12477
- return {
12478
- privateKey,
12479
- publicKey
12480
- };
12481
- };
12482
- var p256PreMasterSecret = ({
12483
- publicKey,
12484
- privateKey
12485
- }) => {
12486
- const ecdh = createECDH("prime256v1");
12487
- ecdh.setPrivateKey(privateKey);
12488
- return ecdh.computeSecret(publicKey);
12489
- };
12490
-
12491
- // ../dtls/src/cipher/prf.ts
12492
12923
  var x25519Oid = "1.3.101.110";
12493
12924
  var x25519RawKeyLength = 32;
12494
12925
  var x25519AlgorithmIdentifier = encodeDerSequence(encodeDerOid(x25519Oid));
@@ -12506,7 +12937,7 @@ function prfPreMasterSecret(publicKey, privateKey, curve) {
12506
12937
  switch (curve) {
12507
12938
  case NamedCurveAlgorithm.secp256r1_23:
12508
12939
  return p256PreMasterSecret({ publicKey, privateKey });
12509
- case NamedCurveAlgorithm.x25519_29:
12940
+ case NamedCurveAlgorithm.x25519_29: {
12510
12941
  if (privateKey.length !== x25519RawKeyLength) {
12511
12942
  throw new Error(
12512
12943
  `invalid X25519 private key length: ${privateKey.length}`
@@ -12517,7 +12948,10 @@ function prfPreMasterSecret(publicKey, privateKey, curve) {
12517
12948
  `invalid X25519 public key length: ${publicKey.length}`
12518
12949
  );
12519
12950
  }
12520
- return diffieHellman({
12951
+ if (publicKey.every((b) => b === 0)) {
12952
+ throw new Error("X25519 peer public key is all-zero (low-order point)");
12953
+ }
12954
+ const shared = diffieHellman({
12521
12955
  privateKey: createPrivateKey({
12522
12956
  key: Buffer.concat([x25519PrivateKeyPrefix, privateKey]),
12523
12957
  format: "der",
@@ -12529,12 +12963,17 @@ function prfPreMasterSecret(publicKey, privateKey, curve) {
12529
12963
  type: "spki"
12530
12964
  })
12531
12965
  });
12966
+ if (shared.every((b) => b === 0)) {
12967
+ throw new Error("X25519 shared secret is all-zero (low-order point)");
12968
+ }
12969
+ return shared;
12970
+ }
12532
12971
  default:
12533
12972
  throw new Error();
12534
12973
  }
12535
12974
  }
12536
12975
  function hmac(algorithm, secret, data) {
12537
- const hash2 = createHmac3(algorithm, secret);
12976
+ const hash2 = createHmac4(algorithm, secret);
12538
12977
  hash2.update(data);
12539
12978
  return hash2.digest();
12540
12979
  }
@@ -12568,7 +13007,7 @@ function prfExtendedMasterSecret(preMasterSecret, handshakes) {
12568
13007
  );
12569
13008
  }
12570
13009
  function hash(algorithm, data) {
12571
- return createHash(algorithm).update(data).digest();
13010
+ return createHash2(algorithm).update(data).digest();
12572
13011
  }
12573
13012
  function prfVerifyData(masterSecret, handshakes, label, size = 12) {
12574
13013
  const bytes2 = hash("sha256", handshakes);
@@ -12606,330 +13045,448 @@ function prfEncryptionKeys(masterSecret, clientRandom, serverRandom, prfKeyLen,
12606
13045
  return { clientWriteKey, serverWriteKey, clientNonce, serverNonce };
12607
13046
  }
12608
13047
 
12609
- // ../dtls/src/cipher/suites/aead.ts
12610
- var err2 = debug(
12611
- "werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err"
12612
- );
12613
- var AEADCipher = class extends AbstractCipher {
12614
- keyLength = 0;
12615
- nonceLength = 0;
12616
- ivLength = 0;
12617
- authTagLength = 0;
12618
- nonceImplicitLength = 0;
12619
- nonceExplicitLength = 0;
12620
- clientWriteKey;
12621
- serverWriteKey;
12622
- clientNonce;
12623
- serverNonce;
12624
- constructor() {
12625
- super();
12626
- }
12627
- get summary() {
12628
- return getObjectSummary(this);
13048
+ // ../dtls/src/context/certificate.ts
13049
+ import { randomBytes as randomBytes4, sign } from "node:crypto";
13050
+ var signatureAlgorithms = {
13051
+ // ecdsa-with-SHA256 (RFC 5758): parameters MUST be absent
13052
+ "ecdsa-sha256": {
13053
+ identifier: encodeDerSequence(encodeDerOid("1.2.840.10045.4.3.2")),
13054
+ hash: "sha256"
13055
+ },
13056
+ // sha256WithRSAEncryption (RFC 4055): parameters MUST be NULL
13057
+ "rsa-sha256": {
13058
+ identifier: encodeDerSequence(
13059
+ encodeDerOid("1.2.840.113549.1.1.11"),
13060
+ encodeDerNull()
13061
+ ),
13062
+ hash: "sha256"
12629
13063
  }
12630
- init(masterSecret, serverRandom, clientRandom) {
12631
- const keys = prfEncryptionKeys(
12632
- masterSecret,
12633
- clientRandom,
12634
- serverRandom,
12635
- this.keyLength,
12636
- this.ivLength,
12637
- this.nonceLength,
12638
- this.hashAlgorithm
12639
- );
12640
- this.clientWriteKey = keys.clientWriteKey;
12641
- this.serverWriteKey = keys.serverWriteKey;
12642
- this.clientNonce = keys.clientNonce;
12643
- this.serverNonce = keys.serverNonce;
13064
+ };
13065
+ var attributeTypes = {
13066
+ C: "2.5.4.6",
13067
+ ST: "2.5.4.8",
13068
+ L: "2.5.4.7",
13069
+ O: "2.5.4.10",
13070
+ OU: "2.5.4.11",
13071
+ CN: "2.5.4.3"
13072
+ };
13073
+ function encodeCertificateName(attributes) {
13074
+ return encodeDerSequence(
13075
+ ...attributes.map(
13076
+ ([type, value]) => encodeDerSet(
13077
+ encodeDerSequence(
13078
+ encodeDerOid(attributeTypes[type]),
13079
+ type === "C" ? encodeDerPrintableString(value) : encodeDerUtf8String(value)
13080
+ )
13081
+ )
13082
+ )
13083
+ );
13084
+ }
13085
+ function createSelfSignedCertificatePem({
13086
+ publicKey,
13087
+ privateKey,
13088
+ signatureAlgorithm,
13089
+ name,
13090
+ notBefore,
13091
+ notAfter,
13092
+ serialNumber = randomBytes4(8)
13093
+ }) {
13094
+ const { identifier, hash: hash2 } = signatureAlgorithms[signatureAlgorithm];
13095
+ const encodedName = encodeCertificateName(name);
13096
+ const tbsCertificate = encodeDerSequence(
13097
+ // version: v3
13098
+ encodeDerExplicit(0, encodeDerInteger(2)),
13099
+ encodeDerInteger(serialNumber),
13100
+ identifier,
13101
+ // issuer = subject for a self-signed certificate
13102
+ encodedName,
13103
+ encodeDerSequence(encodeDerTime(notBefore), encodeDerTime(notAfter)),
13104
+ encodedName,
13105
+ publicKey.export({ type: "spki", format: "der" })
13106
+ );
13107
+ const signature = sign(hash2, tbsCertificate, privateKey);
13108
+ const certificate = encodeDerSequence(
13109
+ tbsCertificate,
13110
+ identifier,
13111
+ encodeDerBitString(signature)
13112
+ );
13113
+ return encodePem("CERTIFICATE", certificate);
13114
+ }
13115
+
13116
+ // ../dtls/src/context/cipher.ts
13117
+ var { encode: encode7, types: types8 } = binaryData_exports;
13118
+ var generateKeyPairAsync = promisify(generateKeyPair2);
13119
+ var CipherContext = class {
13120
+ sessionType;
13121
+ certPem;
13122
+ keyPem;
13123
+ localRandom;
13124
+ remoteRandom;
13125
+ cipherSuite;
13126
+ remoteCertificate;
13127
+ remoteKeyPair;
13128
+ localKeyPair;
13129
+ masterSecret;
13130
+ cipher;
13131
+ namedCurve;
13132
+ signatureHashAlgorithm;
13133
+ localCert;
13134
+ localPrivateKey;
13135
+ constructor(sessionType, certPem, keyPem, signatureHashAlgorithm) {
13136
+ this.sessionType = sessionType;
13137
+ this.certPem = certPem;
13138
+ this.keyPem = keyPem;
13139
+ if (certPem && keyPem && signatureHashAlgorithm) {
13140
+ this.parseX509(certPem, keyPem, signatureHashAlgorithm);
13141
+ }
12644
13142
  }
12645
13143
  /**
12646
- * Encrypt message.
13144
+ *
13145
+ * @param signatureHash
13146
+ * @param namedCurveAlgorithm kept for compatibility. ECDSA certificates always use P-256 (X25519 cannot sign).
12647
13147
  */
12648
- encrypt(type, data, header) {
12649
- const isClient = type === SessionType.CLIENT;
12650
- const iv = isClient ? this.clientNonce : this.serverNonce;
12651
- const writeKey = isClient ? this.clientWriteKey : this.serverWriteKey;
12652
- if (!iv || !writeKey) throw new Error();
12653
- iv.writeUInt16BE(header.epoch, this.nonceImplicitLength);
12654
- iv.writeUIntBE(header.sequenceNumber, this.nonceImplicitLength + 2, 6);
12655
- const explicitNonce = iv.slice(this.nonceImplicitLength);
12656
- const additionalBuffer = this.encodeAdditionalBuffer(header, data.length);
12657
- const cipher = createCipheriv5(this.blockAlgorithm, writeKey, iv, {
12658
- authTagLength: this.authTagLength
12659
- });
12660
- cipher.setAAD(additionalBuffer, {
12661
- plaintextLength: data.length
12662
- });
12663
- const headPart = cipher.update(data);
12664
- const finalPart = cipher.final();
12665
- const authTag = cipher.getAuthTag();
12666
- return Buffer.concat([explicitNonce, headPart, finalPart, authTag]);
12667
- }
12668
- encodeAdditionalBuffer(header, dataLength) {
12669
- const additionalBuffer = Buffer.alloc(13);
12670
- additionalBuffer.writeUInt16BE(header.epoch, 0);
12671
- additionalBuffer.writeUintBE(header.sequenceNumber, 2, 6);
12672
- additionalBuffer.writeUInt8(header.type, 8);
12673
- additionalBuffer.writeUInt16BE(header.version, 9);
12674
- additionalBuffer.writeUInt16BE(dataLength, 11);
12675
- return additionalBuffer;
13148
+ static createSelfSignedCertificateWithKey = async (signatureHash, namedCurveAlgorithm) => {
13149
+ if (signatureHash.hash !== HashAlgorithm.sha256_4) {
13150
+ throw new Error(`unsupported hash algorithm: ${signatureHash.hash}`);
13151
+ }
13152
+ const { publicKey, privateKey } = await (() => {
13153
+ switch (signatureHash.signature) {
13154
+ case SignatureAlgorithm.rsa_1:
13155
+ return generateKeyPairAsync("rsa", {
13156
+ modulusLength: 2048,
13157
+ publicExponent: 65537
13158
+ });
13159
+ case SignatureAlgorithm.ecdsa_3:
13160
+ return generateKeyPairAsync("ec", { namedCurve: "P-256" });
13161
+ default:
13162
+ throw new Error(
13163
+ `unsupported signature algorithm: ${signatureHash.signature}`
13164
+ );
13165
+ }
13166
+ })();
13167
+ const notBefore = /* @__PURE__ */ new Date();
13168
+ const certPem = createSelfSignedCertificatePem({
13169
+ publicKey,
13170
+ privateKey,
13171
+ signatureAlgorithm: signatureHash.signature === SignatureAlgorithm.ecdsa_3 ? "ecdsa-sha256" : "rsa-sha256",
13172
+ name: [
13173
+ ["C", "AU"],
13174
+ ["ST", "Some-State"],
13175
+ ["O", "Internet Widgits Pty Ltd"]
13176
+ ],
13177
+ notBefore,
13178
+ notAfter: new Date(notBefore.getTime() + 10 * 365 * 24 * 60 * 60 * 1e3)
13179
+ });
13180
+ const keyPem = privateKey.export({
13181
+ type: "pkcs8",
13182
+ format: "pem"
13183
+ });
13184
+ return { certPem, keyPem, signatureHash };
13185
+ };
13186
+ encryptPacket(pkt) {
13187
+ const header = pkt.recordLayerHeader;
13188
+ const version = header.protocolVersion.major << 8 | header.protocolVersion.minor;
13189
+ const enc = this.cipher.encrypt(this.sessionType, pkt.fragment, {
13190
+ type: header.contentType,
13191
+ version,
13192
+ epoch: header.epoch,
13193
+ sequenceNumber: header.sequenceNumber
13194
+ });
13195
+ pkt.fragment = enc;
13196
+ pkt.recordLayerHeader.contentLen = enc.length;
13197
+ return pkt;
12676
13198
  }
12677
- /**
12678
- * Decrypt message.
12679
- */
12680
- decrypt(type, data, header) {
12681
- const isClient = type === SessionType.CLIENT;
12682
- const iv = isClient ? this.serverNonce : this.clientNonce;
12683
- const writeKey = isClient ? this.serverWriteKey : this.clientWriteKey;
12684
- if (!iv || !writeKey) throw new Error();
12685
- const explicitNonce = data.subarray(0, this.nonceExplicitLength);
12686
- explicitNonce.copy(iv, this.nonceImplicitLength);
12687
- const encrypted = data.subarray(
12688
- this.nonceExplicitLength,
12689
- data.length - this.authTagLength
13199
+ decryptPacket(pkt) {
13200
+ const header = pkt.recordLayerHeader;
13201
+ const version = header.protocolVersion.major << 8 | header.protocolVersion.minor;
13202
+ const dec = this.cipher.decrypt(this.sessionType, pkt.fragment, {
13203
+ type: header.contentType,
13204
+ version,
13205
+ epoch: header.epoch,
13206
+ sequenceNumber: header.sequenceNumber
13207
+ });
13208
+ return dec;
13209
+ }
13210
+ verifyData(buf) {
13211
+ if (this.sessionType === SessionType.CLIENT)
13212
+ return prfVerifyDataClient(this.masterSecret, buf);
13213
+ else return prfVerifyDataServer(this.masterSecret, buf);
13214
+ }
13215
+ signatureData(data, hash2) {
13216
+ return createSign(hash2).update(data).sign(this.localPrivateKey);
13217
+ }
13218
+ generateKeySignature(hashAlgorithm) {
13219
+ const clientRandom = this.sessionType === SessionType.CLIENT ? this.localRandom : this.remoteRandom;
13220
+ const serverRandom = this.sessionType === SessionType.SERVER ? this.localRandom : this.remoteRandom;
13221
+ const sig = this.valueKeySignature(
13222
+ clientRandom.serialize(),
13223
+ serverRandom.serialize(),
13224
+ this.localKeyPair.publicKey,
13225
+ this.namedCurve
12690
13226
  );
12691
- const authTag = data.subarray(data.length - this.authTagLength);
12692
- const additionalBuffer = this.encodeAdditionalBuffer(
12693
- header,
12694
- encrypted.length
13227
+ return createSign(hashAlgorithm).update(sig).sign(this.localPrivateKey);
13228
+ }
13229
+ parseX509(certPem, keyPem, signatureHash) {
13230
+ this.localCert = new X509Certificate(normalizePem(certPem)).raw;
13231
+ this.localPrivateKey = createPrivateKey2(normalizePem(keyPem));
13232
+ this.signatureHashAlgorithm = signatureHash;
13233
+ }
13234
+ valueKeySignature(clientRandom, serverRandom, publicKey, namedCurve) {
13235
+ const serverParams = encode7(
13236
+ {
13237
+ type: CurveType.named_curve_3,
13238
+ curve: namedCurve,
13239
+ len: publicKey.length
13240
+ },
13241
+ { type: types8.uint8, curve: types8.uint16be, len: types8.uint8 }
12695
13242
  );
12696
- const decipher = createDecipheriv3(this.blockAlgorithm, writeKey, iv, {
12697
- authTagLength: this.authTagLength
12698
- });
12699
- decipher.setAuthTag(authTag);
12700
- decipher.setAAD(additionalBuffer, {
12701
- plaintextLength: encrypted.length
12702
- });
12703
- const headPart = decipher.update(encrypted);
12704
- try {
12705
- const finalPart = decipher.final();
12706
- return finalPart.length > 0 ? Buffer.concat([headPart, finalPart]) : headPart;
12707
- } catch (error) {
12708
- err2(
12709
- "decrypt failed",
12710
- error,
12711
- type,
12712
- dumpBuffer2(data),
12713
- header,
12714
- this.summary
13243
+ return Buffer.concat([clientRandom, serverRandom, serverParams, publicKey]);
13244
+ }
13245
+ };
13246
+ function normalizePem(pem) {
13247
+ return `${pem.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0).join("\n")}
13248
+ `;
13249
+ }
13250
+
13251
+ // ../dtls/src/handshake/extensions/signatureAlgorithms.ts
13252
+ var SIGNATURE_ALGORITHMS_TYPE = 13;
13253
+ var SignatureScheme13 = {
13254
+ /** @deprecated Not used for TLS 1.3 CertificateVerify (kept for wire decode only). */
13255
+ rsa_pkcs1_sha256: 1025,
13256
+ rsa_pss_rsae_sha256: 2052,
13257
+ ecdsa_secp256r1_sha256: 1027,
13258
+ ed25519: 2055
13259
+ };
13260
+ var DEFAULT_SIGNATURE_SCHEMES = [
13261
+ SignatureScheme13.ecdsa_secp256r1_sha256,
13262
+ SignatureScheme13.rsa_pss_rsae_sha256
13263
+ ];
13264
+ var SignatureAlgorithms = class _SignatureAlgorithms {
13265
+ static type = SIGNATURE_ALGORITHMS_TYPE;
13266
+ schemes;
13267
+ constructor(schemes) {
13268
+ this.schemes = schemes;
13269
+ }
13270
+ static create(schemes = DEFAULT_SIGNATURE_SCHEMES) {
13271
+ return new _SignatureAlgorithms(schemes);
13272
+ }
13273
+ static fromData(data) {
13274
+ if (data.length < 2) throw new Error("signature_algorithms: truncated");
13275
+ const len = data.readUInt16BE(0);
13276
+ if (data.length !== 2 + len || len % 2 !== 0 || len < 2) {
13277
+ throw new Error(
13278
+ `signature_algorithms: invalid length (declared ${len}, total ${data.length})`
12715
13279
  );
12716
- throw error;
12717
13280
  }
13281
+ const schemes = [];
13282
+ for (let i = 0; i < len; i += 2) {
13283
+ schemes.push(data.readUInt16BE(2 + i));
13284
+ }
13285
+ return new _SignatureAlgorithms(schemes);
13286
+ }
13287
+ serializeData() {
13288
+ const buf = Buffer.alloc(2 + this.schemes.length * 2);
13289
+ buf.writeUInt16BE(this.schemes.length * 2, 0);
13290
+ this.schemes.forEach((s, i) => buf.writeUInt16BE(s, 2 + i * 2));
13291
+ return buf;
13292
+ }
13293
+ get extension() {
13294
+ return { type: _SignatureAlgorithms.type, data: this.serializeData() };
12718
13295
  }
12719
13296
  };
12720
13297
 
12721
- // ../dtls/src/cipher/create.ts
12722
- var cipherSuites = {
12723
- TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: 49195,
12724
- TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: 49196,
12725
- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: 49199,
12726
- TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: 49200,
12727
- TLS_RSA_WITH_AES_128_GCM_SHA256: 156,
12728
- TLS_RSA_WITH_AES_256_GCM_SHA384: 157,
12729
- TLS_PSK_WITH_AES_128_GCM_SHA256: 168,
12730
- TLS_PSK_WITH_AES_256_GCM_SHA384: 169,
12731
- TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256: 53249,
12732
- TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384: 53250,
12733
- TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256: 52396,
12734
- TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: 52393,
12735
- TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: 52392,
12736
- TLS_PSK_WITH_CHACHA20_POLY1305_SHA256: 52395
13298
+ // ../dtls/src/engine/v1_3/types.ts
13299
+ var MAX_HS_MESSAGE_BYTES = 64 * 1024;
13300
+ var MAX_FRAGMENT_BUFFER_BYTES = 128 * 1024;
13301
+ var ACK_ENCRYPTED_OVERHEAD = 5 + 1 + 2 + 16;
13302
+ var ACK_PLAINTEXT_OVERHEAD = 13 + 2;
13303
+ var MAX_EARLY_APP_DATA_RECORDS = 256;
13304
+ var MAX_EARLY_APP_DATA_BYTES = 256 * 1024;
13305
+ var EARLY_APP_DATA_RETENTION_MS = 2e3;
13306
+ var EARLY_DATA_LIMITS = Object.freeze({
13307
+ maxRecords: MAX_EARLY_APP_DATA_RECORDS,
13308
+ maxBytes: MAX_EARLY_APP_DATA_BYTES,
13309
+ retentionMs: EARLY_APP_DATA_RETENTION_MS
13310
+ });
13311
+ var EARLY_APP_DATA_UNLIMITED = Number.POSITIVE_INFINITY;
13312
+ var log12 = debug("werift-dtls : packages/dtls/src/engine/v1_3");
13313
+ var HRR_RANDOM = Buffer.from(
13314
+ "CF21AD74E59A6111BE1D8C021E65B891C2A211167ABB8C5E079E09E2C8A8339C",
13315
+ "hex"
13316
+ );
13317
+
13318
+ // ../dtls/src/handshake/extensions/ellipticCurves.ts
13319
+ var { decode: decode7, encode: encode8, types: types9 } = binaryData_exports;
13320
+ var EllipticCurves = class _EllipticCurves {
13321
+ static type = 10;
13322
+ static spec = {
13323
+ type: types9.uint16be,
13324
+ data: types9.array(types9.uint16be, types9.uint16be, "bytes")
13325
+ };
13326
+ type = _EllipticCurves.type;
13327
+ data = [];
13328
+ constructor(props = {}) {
13329
+ Object.assign(this, props);
13330
+ }
13331
+ static createEmpty() {
13332
+ return new _EllipticCurves();
13333
+ }
13334
+ static fromData(buf) {
13335
+ return new _EllipticCurves({
13336
+ type: _EllipticCurves.type,
13337
+ data: decode7(buf, _EllipticCurves.spec.data)
13338
+ });
13339
+ }
13340
+ static deSerialize(buf) {
13341
+ return new _EllipticCurves(decode7(buf, _EllipticCurves.spec));
13342
+ }
13343
+ serialize() {
13344
+ return encode8(this, _EllipticCurves.spec);
13345
+ }
13346
+ get extension() {
13347
+ return {
13348
+ type: this.type,
13349
+ data: this.serialize().slice(2)
13350
+ };
13351
+ }
12737
13352
  };
12738
- var AEAD_AES_128_GCM = {
12739
- K_LEN: 16,
12740
- // Length of a key.
12741
- N_MIN: 12,
12742
- // Min nonce length.
12743
- N_MAX: 12,
12744
- // Max nonce length.
12745
- P_MAX: 2 ** 36 - 31,
12746
- // Max length of a plaintext.
12747
- // Max safe int in js is 2 ** 53. So, use this value
12748
- // instead of 2 ** 61 as described in rfc5116.
12749
- A_MAX: 2 ** 53 - 1,
12750
- // Max length of an additional data.
12751
- C_MAX: 2 ** 36 - 15
12752
- // Cipher text length.
13353
+
13354
+ // ../dtls/src/handshake/extensions/extendedMasterSecret.ts
13355
+ var ExtendedMasterSecret = class {
13356
+ static type = 23;
12753
13357
  };
12754
- var AEAD_AES_256_GCM = {
12755
- K_LEN: 32,
12756
- // Length of a key.
12757
- N_MIN: 12,
12758
- // Min nonce length.
12759
- N_MAX: 12,
12760
- // Max nonce length.
12761
- P_MAX: 2 ** 36 - 31,
12762
- // Max length of a plaintext.
12763
- // Note: see above.
12764
- A_MAX: 2 ** 53 - 1,
12765
- // Max length of an additional data.
12766
- C_MAX: 2 ** 36 - 15
12767
- // Cipher text length.
12768
- };
12769
- var RSA_KEY_EXCHANGE = createRSAKeyExchange();
12770
- var ECDHE_RSA_KEY_EXCHANGE = createECDHERSAKeyExchange();
12771
- var ECDHE_ECDSA_KEY_EXCHANGE = createECDHEECDSAKeyExchange();
12772
- var PSK_KEY_EXCHANGE = createPSKKeyExchange();
12773
- var ECDHE_PSK_KEY_EXCHANGE = createECDHEPSKKeyExchange();
12774
- function createCipher(cipher) {
12775
- switch (cipher) {
12776
- case cipherSuites.TLS_RSA_WITH_AES_128_GCM_SHA256:
12777
- return createAEADCipher(
12778
- cipherSuites.TLS_RSA_WITH_AES_128_GCM_SHA256,
12779
- "TLS_RSA_WITH_AES_128_GCM_SHA256",
12780
- "aes-128-gcm",
12781
- RSA_KEY_EXCHANGE,
12782
- AEAD_AES_128_GCM
12783
- );
12784
- case cipherSuites.TLS_RSA_WITH_AES_256_GCM_SHA384:
12785
- return createAEADCipher(
12786
- cipherSuites.TLS_RSA_WITH_AES_256_GCM_SHA384,
12787
- "TLS_RSA_WITH_AES_256_GCM_SHA384",
12788
- "aes-256-gcm",
12789
- RSA_KEY_EXCHANGE,
12790
- AEAD_AES_256_GCM,
12791
- "sha384"
12792
- );
12793
- case cipherSuites.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
12794
- return createAEADCipher(
12795
- cipherSuites.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
12796
- "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
12797
- "aes-128-gcm",
12798
- ECDHE_RSA_KEY_EXCHANGE,
12799
- AEAD_AES_128_GCM
12800
- );
12801
- case cipherSuites.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
12802
- return createAEADCipher(
12803
- cipherSuites.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
12804
- "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
12805
- "aes-256-gcm",
12806
- ECDHE_RSA_KEY_EXCHANGE,
12807
- AEAD_AES_256_GCM,
12808
- "sha384"
12809
- );
12810
- case cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
12811
- return createAEADCipher(
12812
- cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
12813
- "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
12814
- "aes-128-gcm",
12815
- ECDHE_ECDSA_KEY_EXCHANGE,
12816
- AEAD_AES_128_GCM
12817
- );
12818
- case cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
12819
- return createAEADCipher(
12820
- cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
12821
- "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
12822
- "aes-256-gcm",
12823
- ECDHE_ECDSA_KEY_EXCHANGE,
12824
- AEAD_AES_256_GCM,
12825
- "sha384"
12826
- );
12827
- case cipherSuites.TLS_PSK_WITH_AES_128_GCM_SHA256:
12828
- return createAEADCipher(
12829
- cipherSuites.TLS_PSK_WITH_AES_128_GCM_SHA256,
12830
- "TLS_PSK_WITH_AES_128_GCM_SHA256",
12831
- "aes-128-gcm",
12832
- PSK_KEY_EXCHANGE,
12833
- AEAD_AES_128_GCM,
12834
- "sha256"
12835
- );
12836
- case cipherSuites.TLS_PSK_WITH_AES_256_GCM_SHA384:
12837
- return createAEADCipher(
12838
- cipherSuites.TLS_PSK_WITH_AES_256_GCM_SHA384,
12839
- "TLS_PSK_WITH_AES_256_GCM_SHA384",
12840
- "aes-256-gcm",
12841
- PSK_KEY_EXCHANGE,
12842
- AEAD_AES_256_GCM,
12843
- "sha384"
12844
- );
12845
- case cipherSuites.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:
12846
- return createAEADCipher(
12847
- cipherSuites.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,
12848
- "TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256",
12849
- "aes-128-gcm",
12850
- ECDHE_PSK_KEY_EXCHANGE,
12851
- AEAD_AES_128_GCM,
12852
- "sha256"
12853
- );
12854
- case cipherSuites.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:
12855
- return createAEADCipher(
12856
- cipherSuites.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,
12857
- "TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384",
12858
- "aes-256-gcm",
12859
- ECDHE_PSK_KEY_EXCHANGE,
12860
- AEAD_AES_256_GCM,
12861
- "sha384"
12862
- );
12863
- default:
12864
- break;
12865
- }
12866
- return null;
12867
- }
12868
- function createAEADCipher(id, name, block, kx, constants, hash2 = "sha256") {
12869
- const cipher = new AEADCipher();
12870
- cipher.id = id;
12871
- cipher.name = name;
12872
- cipher.blockAlgorithm = block;
12873
- cipher.kx = kx;
12874
- cipher.hashAlgorithm = hash2;
12875
- cipher.keyLength = constants.K_LEN;
12876
- cipher.nonceLength = constants.N_MAX;
12877
- cipher.nonceImplicitLength = 4;
12878
- cipher.nonceExplicitLength = 8;
12879
- cipher.ivLength = cipher.nonceImplicitLength;
12880
- cipher.authTagLength = 16;
12881
- return cipher;
12882
- }
12883
-
12884
- // ../dtls/src/cipher/namedCurve.ts
12885
- import { generateKeyPairSync } from "node:crypto";
12886
- function generateKeyPair(namedCurve) {
12887
- switch (namedCurve) {
12888
- case NamedCurveAlgorithm.secp256r1_23: {
12889
- const { privateKey, publicKey } = p256Keypair();
12890
- return {
12891
- curve: namedCurve,
12892
- privateKey,
12893
- publicKey
12894
- };
12895
- }
12896
- case NamedCurveAlgorithm.x25519_29: {
12897
- const keys = generateKeyPairSync("x25519");
12898
- const privateJwk = keys.privateKey.export({ format: "jwk" });
12899
- const publicJwk = keys.publicKey.export({ format: "jwk" });
12900
- return {
12901
- curve: namedCurve,
12902
- privateKey: Buffer.from(privateJwk.d, "base64url"),
12903
- publicKey: Buffer.from(publicJwk.x, "base64url")
12904
- };
12905
- }
12906
- default:
12907
- throw new Error();
12908
- }
12909
- }
12910
-
12911
- // ../dtls/src/context/srtp.ts
12912
- var SrtpContext2 = class {
12913
- srtpProfile;
12914
- static findMatchingSRTPProfile(remote, local) {
12915
- for (const v of local) {
12916
- if (remote.includes(v)) return v;
12917
- }
12918
- }
12919
- };
12920
-
12921
- // ../dtls/src/handshake/extensions/extendedMasterSecret.ts
12922
- var ExtendedMasterSecret = class {
12923
- static type = 23;
13358
+
13359
+ // ../dtls/src/handshake/extensions/keyShare.ts
13360
+ var KEY_SHARE_TYPE = 51;
13361
+ function expectedKeyExchangeLength(group) {
13362
+ switch (group) {
13363
+ case NamedCurveAlgorithm.x25519_29:
13364
+ return 32;
13365
+ case NamedCurveAlgorithm.secp256r1_23:
13366
+ return 65;
13367
+ // uncompressed point 0x04 || X || Y
13368
+ default:
13369
+ return void 0;
13370
+ }
13371
+ }
13372
+ function assertKeyExchangeEncoding(group, ke) {
13373
+ const expected = expectedKeyExchangeLength(group);
13374
+ if (expected !== void 0 && ke.length !== expected) {
13375
+ throw new Error(
13376
+ `key_share: illegal_parameter key_exchange length ${ke.length} for group 0x${group.toString(16)} (expected ${expected})`
13377
+ );
13378
+ }
13379
+ if (group === NamedCurveAlgorithm.secp256r1_23 && ke[0] !== 4) {
13380
+ throw new Error(
13381
+ "key_share: illegal_parameter P-256 key_exchange must be uncompressed (0x04\u2026)"
13382
+ );
13383
+ }
13384
+ }
13385
+ var KeyShare = class _KeyShare {
13386
+ static type = KEY_SHARE_TYPE;
13387
+ clientShares;
13388
+ serverShare;
13389
+ selectedGroup;
13390
+ constructor(clientShares, serverShare, selectedGroup) {
13391
+ this.clientShares = clientShares;
13392
+ this.serverShare = serverShare;
13393
+ this.selectedGroup = selectedGroup;
13394
+ }
13395
+ static forClient(shares) {
13396
+ return new _KeyShare(shares);
13397
+ }
13398
+ static forServer(share) {
13399
+ return new _KeyShare(void 0, share);
13400
+ }
13401
+ static forHelloRetryRequest(group) {
13402
+ return new _KeyShare(void 0, void 0, group);
13403
+ }
13404
+ static fromClientData(data) {
13405
+ if (data.length < 2) throw new Error("key_share client: truncated");
13406
+ const listLen = data.readUInt16BE(0);
13407
+ let offset = 2;
13408
+ const end = 2 + listLen;
13409
+ if (data.length !== end) {
13410
+ throw new Error(
13411
+ `key_share client: length mismatch (declared ${listLen}, total ${data.length - 2})`
13412
+ );
13413
+ }
13414
+ const shares = [];
13415
+ while (offset < end) {
13416
+ if (end - offset < 4)
13417
+ throw new Error("key_share client: entry truncated");
13418
+ const group = data.readUInt16BE(offset);
13419
+ const keLen = data.readUInt16BE(offset + 2);
13420
+ offset += 4;
13421
+ if (end - offset < keLen)
13422
+ throw new Error("key_share client: ke truncated");
13423
+ const keyExchange = Buffer.from(data.subarray(offset, offset + keLen));
13424
+ offset += keLen;
13425
+ assertKeyExchangeEncoding(group, keyExchange);
13426
+ shares.push({ group, keyExchange });
13427
+ }
13428
+ return _KeyShare.forClient(shares);
13429
+ }
13430
+ static fromServerData(data) {
13431
+ if (data.length === 2) {
13432
+ return _KeyShare.forHelloRetryRequest(data.readUInt16BE(0));
13433
+ }
13434
+ if (data.length < 4) throw new Error("key_share server: truncated");
13435
+ const group = data.readUInt16BE(0);
13436
+ const keLen = data.readUInt16BE(2);
13437
+ if (data.length !== 4 + keLen) {
13438
+ throw new Error(
13439
+ `key_share server: length mismatch (declared ke ${keLen}, total ${data.length - 4})`
13440
+ );
13441
+ }
13442
+ const keyExchange = Buffer.from(data.subarray(4, 4 + keLen));
13443
+ assertKeyExchangeEncoding(group, keyExchange);
13444
+ return _KeyShare.forServer({ group, keyExchange });
13445
+ }
13446
+ serializeClientData() {
13447
+ const shares = this.clientShares ?? [];
13448
+ const parts = shares.map((s) => {
13449
+ const buf = Buffer.alloc(4 + s.keyExchange.length);
13450
+ buf.writeUInt16BE(s.group, 0);
13451
+ buf.writeUInt16BE(s.keyExchange.length, 2);
13452
+ s.keyExchange.copy(buf, 4);
13453
+ return buf;
13454
+ });
13455
+ const body = Buffer.concat(parts);
13456
+ const out = Buffer.alloc(2 + body.length);
13457
+ out.writeUInt16BE(body.length, 0);
13458
+ body.copy(out, 2);
13459
+ return out;
13460
+ }
13461
+ serializeServerData() {
13462
+ if (this.selectedGroup !== void 0 && !this.serverShare) {
13463
+ const buf2 = Buffer.alloc(2);
13464
+ buf2.writeUInt16BE(this.selectedGroup, 0);
13465
+ return buf2;
13466
+ }
13467
+ if (!this.serverShare) throw new Error("key_share: no server share");
13468
+ const s = this.serverShare;
13469
+ const buf = Buffer.alloc(4 + s.keyExchange.length);
13470
+ buf.writeUInt16BE(s.group, 0);
13471
+ buf.writeUInt16BE(s.keyExchange.length, 2);
13472
+ s.keyExchange.copy(buf, 4);
13473
+ return buf;
13474
+ }
13475
+ get clientExtension() {
13476
+ return { type: _KeyShare.type, data: this.serializeClientData() };
13477
+ }
13478
+ get serverExtension() {
13479
+ return { type: _KeyShare.type, data: this.serializeServerData() };
13480
+ }
12924
13481
  };
12925
13482
 
12926
13483
  // ../dtls/src/handshake/extensions/renegotiationIndication.ts
12927
- var { decode: decode7, encode: encode7, types: types8 } = binaryData_exports;
13484
+ var { decode: decode8, encode: encode9, types: types10 } = binaryData_exports;
12928
13485
  var RenegotiationIndication = class _RenegotiationIndication {
12929
13486
  static type = 65281;
12930
13487
  static spec = {
12931
- type: types8.uint16be,
12932
- data: types8.uint8
13488
+ type: types10.uint16be,
13489
+ data: types10.uint8
12933
13490
  };
12934
13491
  type = _RenegotiationIndication.type;
12935
13492
  data = 0;
@@ -12942,11 +13499,11 @@ var RenegotiationIndication = class _RenegotiationIndication {
12942
13499
  }
12943
13500
  static deSerialize(buf) {
12944
13501
  return new _RenegotiationIndication(
12945
- decode7(buf, _RenegotiationIndication.spec)
13502
+ decode8(buf, _RenegotiationIndication.spec)
12946
13503
  );
12947
13504
  }
12948
13505
  serialize() {
12949
- return encode7(this, _RenegotiationIndication.spec);
13506
+ return encode9(this, _RenegotiationIndication.spec);
12950
13507
  }
12951
13508
  get extension() {
12952
13509
  return {
@@ -12956,43 +13513,167 @@ var RenegotiationIndication = class _RenegotiationIndication {
12956
13513
  }
12957
13514
  };
12958
13515
 
13516
+ // ../dtls/src/handshake/extensions/supportedVersions.ts
13517
+ var SUPPORTED_VERSIONS_TYPE = 43;
13518
+ var SupportedVersions = class _SupportedVersions {
13519
+ static type = SUPPORTED_VERSIONS_TYPE;
13520
+ versions;
13521
+ selected;
13522
+ constructor(versions, selected) {
13523
+ this.versions = versions;
13524
+ this.selected = selected;
13525
+ }
13526
+ static forClient(versions) {
13527
+ return new _SupportedVersions(versions);
13528
+ }
13529
+ static forServer(selected) {
13530
+ return new _SupportedVersions([], selected);
13531
+ }
13532
+ static fromData(data, isServerHello) {
13533
+ if (isServerHello) {
13534
+ if (data.length !== 2) {
13535
+ throw new Error(
13536
+ `supported_versions: ServerHello/HRR must be exactly 2 bytes (got ${data.length})`
13537
+ );
13538
+ }
13539
+ return _SupportedVersions.forServer(data.readUInt16BE(0));
13540
+ }
13541
+ if (data.length < 1) {
13542
+ throw new Error("supported_versions: truncated client");
13543
+ }
13544
+ const len = data.readUInt8(0);
13545
+ if (len % 2 !== 0) {
13546
+ throw new Error(
13547
+ "supported_versions: client versions length must be even"
13548
+ );
13549
+ }
13550
+ if (len < 2) {
13551
+ throw new Error(
13552
+ "supported_versions: client versions list must be at least 2 bytes"
13553
+ );
13554
+ }
13555
+ if (data.length !== 1 + len) {
13556
+ throw new Error(
13557
+ `supported_versions: client list length mismatch (declared ${len}, total ${data.length})`
13558
+ );
13559
+ }
13560
+ const versions = [];
13561
+ for (let i = 0; i < len; i += 2) {
13562
+ versions.push(data.readUInt16BE(1 + i));
13563
+ }
13564
+ return _SupportedVersions.forClient(versions);
13565
+ }
13566
+ serializeClientData() {
13567
+ const buf = Buffer.alloc(1 + this.versions.length * 2);
13568
+ buf.writeUInt8(this.versions.length * 2, 0);
13569
+ this.versions.forEach((v, i) => buf.writeUInt16BE(v, 1 + i * 2));
13570
+ return buf;
13571
+ }
13572
+ serializeServerData() {
13573
+ if (this.selected === void 0) {
13574
+ throw new Error("supported_versions: no selected version");
13575
+ }
13576
+ const buf = Buffer.alloc(2);
13577
+ buf.writeUInt16BE(this.selected, 0);
13578
+ return buf;
13579
+ }
13580
+ get clientExtension() {
13581
+ return { type: _SupportedVersions.type, data: this.serializeClientData() };
13582
+ }
13583
+ get serverExtension() {
13584
+ return { type: _SupportedVersions.type, data: this.serializeServerData() };
13585
+ }
13586
+ };
13587
+
12959
13588
  // ../dtls/src/handshake/extensions/useSrtp.ts
12960
- var { decode: decode8, encode: encode8, types: types9 } = binaryData_exports;
13589
+ var { decode: decode9, encode: encode10, types: types11 } = binaryData_exports;
12961
13590
  var UseSRTP = class _UseSRTP {
12962
13591
  static type = 14;
12963
13592
  // 9. IANA Considerations
12964
13593
  static spec = {
12965
- type: types9.uint16be,
12966
- data: types9.buffer(types9.uint16be)
13594
+ type: types11.uint16be,
13595
+ data: types11.buffer(types11.uint16be)
12967
13596
  };
12968
13597
  type = _UseSRTP.type;
12969
13598
  data = Buffer.from([]);
12970
13599
  profiles = [];
12971
- mki = Buffer.from([0]);
13600
+ /** MKI payload only (not including the length byte). */
13601
+ mki = Buffer.alloc(0);
12972
13602
  constructor(props = {}) {
12973
13603
  Object.assign(this, props);
12974
13604
  }
12975
- static create(profiles, mki) {
13605
+ static create(profiles, mki = Buffer.alloc(0)) {
12976
13606
  const v = new _UseSRTP({
12977
13607
  profiles,
12978
- mki
13608
+ mki: Buffer.from(mki)
12979
13609
  });
12980
13610
  return v;
12981
13611
  }
12982
- static deSerialize(buf) {
12983
- const useSrtp = new _UseSRTP(decode8(buf, _UseSRTP.spec));
12984
- const profileLength = useSrtp.data.readUInt16BE();
12985
- const profiles = new Array(profileLength / 2);
12986
- for (let i = 0; i < profiles.length; i++) {
12987
- profiles[i] = useSrtp.data.readUInt16BE(i * 2 + 2);
13612
+ static deSerialize(buf, options = {}) {
13613
+ const useSrtp = new _UseSRTP(decode9(buf, _UseSRTP.spec));
13614
+ if (options.lenient) {
13615
+ _UseSRTP.parseProfilesAndMkiLenient(useSrtp);
13616
+ } else {
13617
+ _UseSRTP.parseProfilesAndMki(useSrtp);
12988
13618
  }
12989
- useSrtp.profiles = profiles;
12990
- useSrtp.mki = useSrtp.data.slice(profileLength + 2);
12991
13619
  return useSrtp;
12992
13620
  }
13621
+ /**
13622
+ * Parse without length checks (`handshakeValidation: "lenient"`, the DTLS
13623
+ * 1.2 behavior before the strict checks): the declared profile list is
13624
+ * read as far as the data reaches and the rest after the MKI length byte
13625
+ * is the MKI.
13626
+ */
13627
+ static parseProfilesAndMkiLenient(useSrtp) {
13628
+ const data = useSrtp.data;
13629
+ const profileLength = data.length >= 2 ? data.readUInt16BE(0) : 0;
13630
+ const profiles = [];
13631
+ for (let i = 0; i + 1 < profileLength && 2 + i + 2 <= data.length; i += 2) {
13632
+ profiles.push(data.readUInt16BE(2 + i));
13633
+ }
13634
+ useSrtp.profiles = profiles;
13635
+ useSrtp.mki = Buffer.from(data.subarray(2 + profileLength + 1));
13636
+ }
13637
+ /**
13638
+ * Parse extension data (profiles + MKI) into profiles[] and mki payload.
13639
+ * Strict length checks (RFC 5764).
13640
+ */
13641
+ static parseProfilesAndMki(useSrtp) {
13642
+ const data = useSrtp.data;
13643
+ if (data.length < 2) {
13644
+ throw new Error("use_srtp: truncated profiles length");
13645
+ }
13646
+ const profileLength = data.readUInt16BE(0);
13647
+ if (profileLength % 2 !== 0) {
13648
+ throw new Error("use_srtp: profiles length must be even");
13649
+ }
13650
+ if (data.length < 2 + profileLength + 1) {
13651
+ throw new Error("use_srtp: truncated after profiles");
13652
+ }
13653
+ const profiles = [];
13654
+ for (let i = 0; i < profileLength; i += 2) {
13655
+ profiles.push(data.readUInt16BE(2 + i));
13656
+ }
13657
+ const mkiOffset = 2 + profileLength;
13658
+ const mkiLen = data.readUInt8(mkiOffset);
13659
+ if (data.length !== mkiOffset + 1 + mkiLen) {
13660
+ throw new Error(
13661
+ `use_srtp: MKI length mismatch (declared ${mkiLen}, remaining ${data.length - mkiOffset - 1})`
13662
+ );
13663
+ }
13664
+ useSrtp.profiles = profiles;
13665
+ useSrtp.mki = Buffer.from(
13666
+ data.subarray(mkiOffset + 1, mkiOffset + 1 + mkiLen)
13667
+ );
13668
+ }
12993
13669
  serialize() {
13670
+ if (this.mki.length > 255) {
13671
+ throw new Error("use_srtp: MKI longer than 255 bytes");
13672
+ }
12994
13673
  const profileLength = Buffer.alloc(2);
12995
13674
  profileLength.writeUInt16BE(this.profiles.length * 2);
13675
+ const mkiLen = Buffer.alloc(1);
13676
+ mkiLen.writeUInt8(this.mki.length, 0);
12996
13677
  const data = Buffer.concat([
12997
13678
  profileLength,
12998
13679
  ...this.profiles.map((profile) => {
@@ -13000,16 +13681,17 @@ var UseSRTP = class _UseSRTP {
13000
13681
  buf.writeUInt16BE(profile);
13001
13682
  return buf;
13002
13683
  }),
13684
+ mkiLen,
13003
13685
  this.mki
13004
13686
  ]);
13005
13687
  this.data = data;
13006
- return encode8(this, _UseSRTP.spec);
13688
+ return encode10(this, _UseSRTP.spec);
13007
13689
  }
13008
- static fromData(buf) {
13690
+ static fromData(buf, options = {}) {
13009
13691
  const head = Buffer.alloc(4);
13010
13692
  head.writeUInt16BE(_UseSRTP.type);
13011
13693
  head.writeUInt16BE(buf.length, 2);
13012
- return _UseSRTP.deSerialize(Buffer.concat([head, buf]));
13694
+ return _UseSRTP.deSerialize(Buffer.concat([head, buf]), options);
13013
13695
  }
13014
13696
  get extension() {
13015
13697
  return {
@@ -13019,28 +13701,62 @@ var UseSRTP = class _UseSRTP {
13019
13701
  }
13020
13702
  };
13021
13703
 
13022
- // ../dtls/src/handshake/message/certificate.ts
13023
- var { decode: decode9, encode: encode9, types: types10 } = binaryData_exports;
13024
- var Certificate = class _Certificate {
13025
- certificateList;
13026
- msgType = HandshakeType.certificate_11;
13704
+ // ../dtls/src/handshake/message/server/hello.ts
13705
+ var { decode: decode10, encode: encode11, types: types12 } = binaryData_exports;
13706
+ var ServerHello = class _ServerHello {
13707
+ serverVersion;
13708
+ random;
13709
+ sessionId;
13710
+ cipherSuite;
13711
+ compressionMethod;
13712
+ extensions;
13713
+ msgType = HandshakeType.server_hello_2;
13027
13714
  messageSeq;
13028
13715
  static spec = {
13029
- certificateList: types10.array(ASN11Cert, types10.uint24be, "bytes")
13716
+ serverVersion: ProtocolVersion,
13717
+ random: DtlsRandom.spec,
13718
+ sessionId: types12.buffer(types12.uint8),
13719
+ cipherSuite: types12.uint16be,
13720
+ compressionMethod: types12.uint8
13030
13721
  };
13031
- constructor(certificateList) {
13032
- this.certificateList = certificateList;
13722
+ constructor(serverVersion, random, sessionId, cipherSuite, compressionMethod, extensions) {
13723
+ this.serverVersion = serverVersion;
13724
+ this.random = random;
13725
+ this.sessionId = sessionId;
13726
+ this.cipherSuite = cipherSuite;
13727
+ this.compressionMethod = compressionMethod;
13728
+ this.extensions = extensions;
13033
13729
  }
13034
13730
  static createEmpty() {
13035
- return new _Certificate(void 0);
13731
+ return new _ServerHello(
13732
+ void 0,
13733
+ void 0,
13734
+ void 0,
13735
+ void 0,
13736
+ void 0,
13737
+ void 0
13738
+ );
13036
13739
  }
13037
13740
  static deSerialize(buf) {
13038
- return new _Certificate(
13039
- ...Object.values(decode9(buf, _Certificate.spec))
13741
+ const res = decode10(buf, _ServerHello.spec);
13742
+ const cls = new _ServerHello(
13743
+ ...Object.values(res)
13040
13744
  );
13745
+ const expect = cls.serialize();
13746
+ if (expect.length < buf.length) {
13747
+ return new _ServerHello(
13748
+ ...Object.values(
13749
+ decode10(buf, { ..._ServerHello.spec, extensions: ExtensionList })
13750
+ )
13751
+ );
13752
+ }
13753
+ return cls;
13041
13754
  }
13042
13755
  serialize() {
13043
- return encode9(this, _Certificate.spec);
13756
+ return this.extensions === void 0 ? encode11(this, _ServerHello.spec) : encode11(this, {
13757
+ ..._ServerHello.spec,
13758
+ extensions: ExtensionList
13759
+ });
13044
13760
  }
13045
13761
  toFragment() {
13046
13762
  const body = this.serialize();
@@ -13055,54 +13771,75 @@ var Certificate = class _Certificate {
13055
13771
  }
13056
13772
  };
13057
13773
 
13058
- // ../dtls/src/handshake/message/changeCipherSpec.ts
13059
- var { decode: decode10, encode: encode10, types: types11 } = binaryData_exports;
13060
- var ChangeCipherSpec = class _ChangeCipherSpec {
13061
- type;
13062
- static spec = {
13063
- type: types11.uint8
13064
- };
13065
- constructor(type = 1) {
13066
- this.type = type;
13067
- }
13068
- static createEmpty() {
13069
- return new _ChangeCipherSpec();
13070
- }
13071
- static deSerialize(buf) {
13072
- const { type } = decode10(buf, _ChangeCipherSpec.spec);
13073
- return new _ChangeCipherSpec(type);
13074
- }
13075
- serialize() {
13076
- return encode10(this, _ChangeCipherSpec.spec);
13077
- }
13078
- };
13774
+ // ../dtls/src/handshake/message/tls13/encryptedExtensions.ts
13775
+ var { decode: decode11, encode: encode12 } = binaryData_exports;
13079
13776
 
13080
- // ../dtls/src/handshake/message/client/certificateVerify.ts
13081
- var { decode: decode11, encode: encode11, types: types12 } = binaryData_exports;
13082
- var CertificateVerify = class _CertificateVerify {
13083
- algorithm;
13084
- signature;
13085
- msgType = HandshakeType.certificate_verify_15;
13777
+ // ../dtls/src/engine/v1_3/flight/extensions.ts
13778
+ var SERVER_HELLO_ALLOWED_EXTS = /* @__PURE__ */ new Set([
13779
+ SupportedVersions.type,
13780
+ KeyShare.type
13781
+ ]);
13782
+ var HRR_ALLOWED_EXTS = /* @__PURE__ */ new Set([
13783
+ SupportedVersions.type,
13784
+ KeyShare.type,
13785
+ CookieExtension.type
13786
+ ]);
13787
+ var EE_KNOWN_ALLOWED_EXTS = /* @__PURE__ */ new Set([
13788
+ EllipticCurves.type,
13789
+ // 10 supported_groups (CH, EE)
13790
+ UseSRTP.type
13791
+ // 14 use_srtp (CH, EE)
13792
+ ]);
13793
+ var KNOWN_EXTENSION_TYPES = /* @__PURE__ */ new Set([
13794
+ EllipticCurves.type,
13795
+ // 10 supported_groups
13796
+ SignatureAlgorithms.type,
13797
+ // 13
13798
+ UseSRTP.type,
13799
+ // 14
13800
+ EXT_PADDING,
13801
+ // 21
13802
+ SupportedVersions.type,
13803
+ // 43
13804
+ CookieExtension.type,
13805
+ // 44
13806
+ KeyShare.type,
13807
+ // 51
13808
+ EXT_EARLY_DATA
13809
+ // 42
13810
+ ]);
13811
+
13812
+ // ../dtls/src/handshake/message/server/helloVerifyRequest.ts
13813
+ var { decode: decode12, encode: encode13, types: types13 } = binaryData_exports;
13814
+ var ServerHelloVerifyRequest = class _ServerHelloVerifyRequest {
13815
+ serverVersion;
13816
+ cookie;
13817
+ msgType = HandshakeType.hello_verify_request_3;
13086
13818
  messageSeq;
13087
13819
  static spec = {
13088
- algorithm: types12.uint16be,
13089
- signature: types12.buffer(types12.uint16be)
13820
+ serverVersion: ProtocolVersion,
13821
+ cookie: types13.buffer(types13.uint8)
13090
13822
  };
13091
- constructor(algorithm, signature) {
13092
- this.algorithm = algorithm;
13093
- this.signature = signature;
13823
+ constructor(serverVersion, cookie) {
13824
+ this.serverVersion = serverVersion;
13825
+ this.cookie = cookie;
13094
13826
  }
13095
13827
  static createEmpty() {
13096
- return new _CertificateVerify(void 0, void 0);
13828
+ return new _ServerHelloVerifyRequest(void 0, void 0);
13097
13829
  }
13098
13830
  static deSerialize(buf) {
13099
- const res = decode11(buf, _CertificateVerify.spec);
13100
- return new _CertificateVerify(
13101
- ...Object.values(res)
13831
+ return new _ServerHelloVerifyRequest(
13832
+ ...Object.values(decode12(buf, _ServerHelloVerifyRequest.spec))
13102
13833
  );
13103
13834
  }
13104
13835
  serialize() {
13105
- return encode11(this, _CertificateVerify.spec);
13836
+ return encode13(this, _ServerHelloVerifyRequest.spec);
13837
+ }
13838
+ get version() {
13839
+ return {
13840
+ major: 255 - this.serverVersion.major,
13841
+ minor: 255 - this.serverVersion.minor
13842
+ };
13106
13843
  }
13107
13844
  toFragment() {
13108
13845
  const body = this.serialize();
@@ -13117,592 +13854,706 @@ var CertificateVerify = class _CertificateVerify {
13117
13854
  }
13118
13855
  };
13119
13856
 
13120
- // ../dtls/src/handshake/message/client/keyExchange.ts
13121
- var { decode: decode12, encode: encode12, types: types13 } = binaryData_exports;
13122
- var ClientKeyExchange = class _ClientKeyExchange {
13123
- publicKey;
13124
- msgType = HandshakeType.client_key_exchange_16;
13125
- messageSeq;
13126
- static spec = {
13127
- publicKey: types13.buffer(types13.uint8)
13128
- };
13129
- constructor(publicKey) {
13130
- this.publicKey = publicKey;
13131
- }
13132
- static createEmpty() {
13133
- return new _ClientKeyExchange(void 0);
13134
- }
13135
- static deSerialize(buf) {
13136
- const res = decode12(buf, _ClientKeyExchange.spec);
13137
- return new _ClientKeyExchange(
13138
- ...Object.values(res)
13139
- );
13140
- }
13141
- serialize() {
13142
- return encode12(this, _ClientKeyExchange.spec);
13857
+ // ../dtls/src/context/srtp.ts
13858
+ var SrtpContext2 = class {
13859
+ srtpProfile;
13860
+ static findMatchingSRTPProfile(remote, local) {
13861
+ for (const v of local) {
13862
+ if (remote.includes(v)) return v;
13863
+ }
13143
13864
  }
13144
- toFragment() {
13145
- const body = this.serialize();
13146
- return new FragmentedHandshake(
13147
- this.msgType,
13148
- body.length,
13149
- this.messageSeq,
13150
- 0,
13151
- body.length,
13152
- body
13153
- );
13865
+ };
13866
+
13867
+ // ../dtls/src/flight/flight.ts
13868
+ var warn = debug("werift-dtls : packages/dtls/src/flight/flight.ts : warn");
13869
+ var err = debug("werift-dtls : packages/dtls/src/flight/flight.ts : err");
13870
+
13871
+ // ../dtls/src/flight/client/flight3.ts
13872
+ var log13 = debug(
13873
+ "werift-dtls : packages/dtls/src/flight/client/flight3.ts : log"
13874
+ );
13875
+
13876
+ // ../dtls/src/cipher/key-exchange.ts
13877
+ var signTypes = {
13878
+ NULL: 0,
13879
+ ECDHE: 1
13880
+ };
13881
+ var keyTypes = {
13882
+ NULL: 0,
13883
+ RSA: 1,
13884
+ ECDSA: 2,
13885
+ PSK: 3
13886
+ };
13887
+ var kxTypes = {
13888
+ NULL: 0,
13889
+ RSA: 1,
13890
+ ECDHE_RSA: 2,
13891
+ ECDHE_ECDSA: 3,
13892
+ PSK: 4,
13893
+ ECDHE_PSK: 5
13894
+ };
13895
+ var KeyExchange = class {
13896
+ id = 0;
13897
+ name;
13898
+ signType;
13899
+ keyType;
13900
+ /**
13901
+ * @returns {string}
13902
+ */
13903
+ toString() {
13904
+ return this.name;
13154
13905
  }
13155
13906
  };
13907
+ function createRSAKeyExchange() {
13908
+ const exchange = new KeyExchange();
13909
+ exchange.id = kxTypes.RSA;
13910
+ exchange.name = "RSA";
13911
+ exchange.keyType = keyTypes.RSA;
13912
+ return exchange;
13913
+ }
13914
+ function createECDHERSAKeyExchange() {
13915
+ const exchange = new KeyExchange();
13916
+ exchange.id = kxTypes.ECDHE_RSA;
13917
+ exchange.name = "ECDHE_RSA";
13918
+ exchange.signType = signTypes.ECDHE;
13919
+ exchange.keyType = keyTypes.RSA;
13920
+ return exchange;
13921
+ }
13922
+ function createECDHEECDSAKeyExchange() {
13923
+ const exchange = new KeyExchange();
13924
+ exchange.id = kxTypes.ECDHE_ECDSA;
13925
+ exchange.name = "ECDHE_ECDSA";
13926
+ exchange.signType = signTypes.ECDHE;
13927
+ exchange.keyType = keyTypes.ECDSA;
13928
+ return exchange;
13929
+ }
13930
+ function createPSKKeyExchange() {
13931
+ const exchange = new KeyExchange();
13932
+ exchange.id = kxTypes.PSK;
13933
+ exchange.name = "PSK";
13934
+ exchange.signType = signTypes.NULL;
13935
+ exchange.keyType = keyTypes.PSK;
13936
+ return exchange;
13937
+ }
13938
+ function createECDHEPSKKeyExchange() {
13939
+ const exchange = new KeyExchange();
13940
+ exchange.id = kxTypes.ECDHE_PSK;
13941
+ exchange.name = "ECDHE_PSK";
13942
+ exchange.signType = signTypes.ECDHE;
13943
+ exchange.keyType = keyTypes.PSK;
13944
+ return exchange;
13945
+ }
13156
13946
 
13157
- // ../dtls/src/handshake/message/server/certificateRequest.ts
13158
- var { decode: decode13, encode: encode13, types: types14 } = binaryData_exports;
13159
- var ServerCertificateRequest = class _ServerCertificateRequest {
13160
- certificateTypes;
13161
- signatures;
13162
- authorities;
13163
- msgType = HandshakeType.certificate_request_13;
13164
- messageSeq;
13165
- static spec = {
13166
- certificateTypes: types14.array(ClientCertificateType, types14.uint8, "bytes"),
13167
- signatures: types14.array(SignatureHashAlgorithm, types14.uint16be, "bytes"),
13168
- authorities: types14.array(DistinguishedName, types14.uint16be, "bytes")
13169
- };
13170
- constructor(certificateTypes2, signatures2, authorities) {
13171
- this.certificateTypes = certificateTypes2;
13172
- this.signatures = signatures2;
13173
- this.authorities = authorities;
13947
+ // ../dtls/src/cipher/suites/aead.ts
13948
+ import { createCipheriv as createCipheriv5, createDecipheriv as createDecipheriv3 } from "crypto";
13949
+ var err2 = debug(
13950
+ "werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err"
13951
+ );
13952
+ var AEADCipher = class extends AbstractCipher {
13953
+ keyLength = 0;
13954
+ nonceLength = 0;
13955
+ ivLength = 0;
13956
+ authTagLength = 0;
13957
+ nonceImplicitLength = 0;
13958
+ nonceExplicitLength = 0;
13959
+ clientWriteKey;
13960
+ serverWriteKey;
13961
+ clientNonce;
13962
+ serverNonce;
13963
+ constructor() {
13964
+ super();
13174
13965
  }
13175
- static createEmpty() {
13176
- return new _ServerCertificateRequest(
13177
- void 0,
13178
- void 0,
13179
- void 0
13180
- );
13966
+ get summary() {
13967
+ return getObjectSummary(this);
13181
13968
  }
13182
- static deSerialize(buf) {
13183
- return new _ServerCertificateRequest(
13184
- ...Object.values(decode13(buf, _ServerCertificateRequest.spec))
13969
+ init(masterSecret, serverRandom, clientRandom) {
13970
+ const keys = prfEncryptionKeys(
13971
+ masterSecret,
13972
+ clientRandom,
13973
+ serverRandom,
13974
+ this.keyLength,
13975
+ this.ivLength,
13976
+ this.nonceLength,
13977
+ this.hashAlgorithm
13185
13978
  );
13979
+ this.clientWriteKey = keys.clientWriteKey;
13980
+ this.serverWriteKey = keys.serverWriteKey;
13981
+ this.clientNonce = keys.clientNonce;
13982
+ this.serverNonce = keys.serverNonce;
13186
13983
  }
13187
- serialize() {
13188
- return encode13(this, _ServerCertificateRequest.spec);
13984
+ /**
13985
+ * Encrypt message.
13986
+ */
13987
+ encrypt(type, data, header) {
13988
+ const isClient = type === SessionType.CLIENT;
13989
+ const iv = isClient ? this.clientNonce : this.serverNonce;
13990
+ const writeKey = isClient ? this.clientWriteKey : this.serverWriteKey;
13991
+ if (!iv || !writeKey) throw new Error();
13992
+ iv.writeUInt16BE(header.epoch, this.nonceImplicitLength);
13993
+ iv.writeUIntBE(header.sequenceNumber, this.nonceImplicitLength + 2, 6);
13994
+ const explicitNonce = iv.slice(this.nonceImplicitLength);
13995
+ const additionalBuffer = this.encodeAdditionalBuffer(header, data.length);
13996
+ const cipher = createCipheriv5(this.blockAlgorithm, writeKey, iv, {
13997
+ authTagLength: this.authTagLength
13998
+ });
13999
+ cipher.setAAD(additionalBuffer, {
14000
+ plaintextLength: data.length
14001
+ });
14002
+ const headPart = cipher.update(data);
14003
+ const finalPart = cipher.final();
14004
+ const authTag = cipher.getAuthTag();
14005
+ return Buffer.concat([explicitNonce, headPart, finalPart, authTag]);
13189
14006
  }
13190
- toFragment() {
13191
- const body = this.serialize();
13192
- return new FragmentedHandshake(
13193
- this.msgType,
13194
- body.length,
13195
- this.messageSeq,
13196
- 0,
13197
- body.length,
13198
- body
13199
- );
14007
+ encodeAdditionalBuffer(header, dataLength) {
14008
+ const additionalBuffer = Buffer.alloc(13);
14009
+ additionalBuffer.writeUInt16BE(header.epoch, 0);
14010
+ additionalBuffer.writeUintBE(header.sequenceNumber, 2, 6);
14011
+ additionalBuffer.writeUInt8(header.type, 8);
14012
+ additionalBuffer.writeUInt16BE(header.version, 9);
14013
+ additionalBuffer.writeUInt16BE(dataLength, 11);
14014
+ return additionalBuffer;
13200
14015
  }
13201
- };
13202
-
13203
- // ../dtls/src/handshake/message/server/hello.ts
13204
- var { decode: decode14, encode: encode14, types: types15 } = binaryData_exports;
13205
- var ServerHello = class _ServerHello {
13206
- serverVersion;
13207
- random;
13208
- sessionId;
13209
- cipherSuite;
13210
- compressionMethod;
13211
- extensions;
13212
- msgType = HandshakeType.server_hello_2;
13213
- messageSeq;
13214
- static spec = {
13215
- serverVersion: ProtocolVersion,
13216
- random: DtlsRandom.spec,
13217
- sessionId: types15.buffer(types15.uint8),
13218
- cipherSuite: types15.uint16be,
13219
- compressionMethod: types15.uint8
13220
- };
13221
- constructor(serverVersion, random, sessionId, cipherSuite, compressionMethod, extensions) {
13222
- this.serverVersion = serverVersion;
13223
- this.random = random;
13224
- this.sessionId = sessionId;
13225
- this.cipherSuite = cipherSuite;
13226
- this.compressionMethod = compressionMethod;
13227
- this.extensions = extensions;
13228
- }
13229
- static createEmpty() {
13230
- return new _ServerHello(
13231
- void 0,
13232
- void 0,
13233
- void 0,
13234
- void 0,
13235
- void 0,
13236
- void 0
14016
+ /**
14017
+ * Decrypt message.
14018
+ */
14019
+ decrypt(type, data, header) {
14020
+ const isClient = type === SessionType.CLIENT;
14021
+ const iv = isClient ? this.serverNonce : this.clientNonce;
14022
+ const writeKey = isClient ? this.serverWriteKey : this.clientWriteKey;
14023
+ if (!iv || !writeKey) throw new Error();
14024
+ const explicitNonce = data.subarray(0, this.nonceExplicitLength);
14025
+ explicitNonce.copy(iv, this.nonceImplicitLength);
14026
+ const encrypted = data.subarray(
14027
+ this.nonceExplicitLength,
14028
+ data.length - this.authTagLength
13237
14029
  );
13238
- }
13239
- static deSerialize(buf) {
13240
- const res = decode14(buf, _ServerHello.spec);
13241
- const cls = new _ServerHello(
13242
- ...Object.values(res)
14030
+ const authTag = data.subarray(data.length - this.authTagLength);
14031
+ const additionalBuffer = this.encodeAdditionalBuffer(
14032
+ header,
14033
+ encrypted.length
13243
14034
  );
13244
- const expect = cls.serialize();
13245
- if (expect.length < buf.length) {
13246
- return new _ServerHello(
13247
- ...Object.values(
13248
- decode14(buf, { ..._ServerHello.spec, extensions: ExtensionList })
13249
- )
14035
+ const decipher = createDecipheriv3(this.blockAlgorithm, writeKey, iv, {
14036
+ authTagLength: this.authTagLength
14037
+ });
14038
+ decipher.setAuthTag(authTag);
14039
+ decipher.setAAD(additionalBuffer, {
14040
+ plaintextLength: encrypted.length
14041
+ });
14042
+ const headPart = decipher.update(encrypted);
14043
+ try {
14044
+ const finalPart = decipher.final();
14045
+ return finalPart.length > 0 ? Buffer.concat([headPart, finalPart]) : headPart;
14046
+ } catch (error) {
14047
+ err2(
14048
+ "decrypt failed",
14049
+ error,
14050
+ type,
14051
+ dumpBuffer2(data),
14052
+ header,
14053
+ this.summary
13250
14054
  );
14055
+ throw error;
13251
14056
  }
13252
- return cls;
13253
- }
13254
- serialize() {
13255
- return this.extensions === void 0 ? encode14(this, _ServerHello.spec) : encode14(this, {
13256
- ..._ServerHello.spec,
13257
- extensions: ExtensionList
13258
- });
13259
- }
13260
- toFragment() {
13261
- const body = this.serialize();
13262
- return new FragmentedHandshake(
13263
- this.msgType,
13264
- body.length,
13265
- this.messageSeq,
13266
- 0,
13267
- body.length,
13268
- body
13269
- );
13270
- }
13271
- };
13272
-
13273
- // ../dtls/src/handshake/message/server/helloDone.ts
13274
- var { decode: decode15, encode: encode15 } = binaryData_exports;
13275
-
13276
- // ../dtls/src/util/binary.ts
13277
- var { encode: encode16 } = binaryData_exports;
13278
- function encodeBuffer(obj, spec) {
13279
- return encode16(obj, spec);
13280
- }
13281
-
13282
- // ../dtls/src/handshake/message/server/keyExchange.ts
13283
- var { decode: decode16, types: types16 } = binaryData_exports;
13284
- var ServerKeyExchange = class _ServerKeyExchange {
13285
- ellipticCurveType;
13286
- namedCurve;
13287
- publicKeyLength;
13288
- publicKey;
13289
- hashAlgorithm;
13290
- signatureAlgorithm;
13291
- signatureLength;
13292
- signature;
13293
- msgType = HandshakeType.server_key_exchange_12;
13294
- messageSeq;
13295
- static spec = {
13296
- ellipticCurveType: types16.uint8,
13297
- namedCurve: types16.uint16be,
13298
- publicKeyLength: types16.uint8,
13299
- publicKey: types16.buffer((ctx) => ctx.current.publicKeyLength),
13300
- hashAlgorithm: types16.uint8,
13301
- signatureAlgorithm: types16.uint8,
13302
- signatureLength: types16.uint16be,
13303
- signature: types16.buffer((ctx) => ctx.current.signatureLength)
13304
- };
13305
- constructor(ellipticCurveType, namedCurve, publicKeyLength, publicKey, hashAlgorithm, signatureAlgorithm, signatureLength, signature) {
13306
- this.ellipticCurveType = ellipticCurveType;
13307
- this.namedCurve = namedCurve;
13308
- this.publicKeyLength = publicKeyLength;
13309
- this.publicKey = publicKey;
13310
- this.hashAlgorithm = hashAlgorithm;
13311
- this.signatureAlgorithm = signatureAlgorithm;
13312
- this.signatureLength = signatureLength;
13313
- this.signature = signature;
13314
- }
13315
- static createEmpty() {
13316
- return new _ServerKeyExchange(
13317
- void 0,
13318
- void 0,
13319
- void 0,
13320
- void 0,
13321
- void 0,
13322
- void 0,
13323
- void 0,
13324
- void 0
13325
- );
13326
- }
13327
- static deSerialize(buf) {
13328
- const res = decode16(buf, _ServerKeyExchange.spec);
13329
- return new _ServerKeyExchange(
13330
- ...Object.values(res)
13331
- );
13332
- }
13333
- serialize() {
13334
- const res = encodeBuffer(this, _ServerKeyExchange.spec);
13335
- return res;
13336
- }
13337
- toFragment() {
13338
- const body = this.serialize();
13339
- return new FragmentedHandshake(
13340
- this.msgType,
13341
- body.length,
13342
- this.messageSeq,
13343
- 0,
13344
- body.length,
13345
- body
13346
- );
13347
14057
  }
13348
14058
  };
13349
14059
 
13350
- // ../dtls/src/flight/client/flight5.ts
13351
- var log13 = debug(
13352
- "werift-dtls : packages/dtls/src/flight/client/flight5.ts : log"
13353
- );
13354
- var handlers = {};
13355
- handlers[HandshakeType.server_hello_2] = ({ cipher, srtp, dtls }) => (message) => {
13356
- log13(dtls.sessionId, "serverHello", message.cipherSuite);
13357
- cipher.remoteRandom = DtlsRandom.from(message.random);
13358
- cipher.cipherSuite = message.cipherSuite;
13359
- log13(dtls.sessionId, "selected cipherSuite", cipher.cipherSuite);
13360
- if (message.extensions) {
13361
- message.extensions.forEach((extension) => {
13362
- switch (extension.type) {
13363
- case UseSRTP.type:
13364
- {
13365
- const useSrtp = UseSRTP.fromData(extension.data);
13366
- const profile = SrtpContext2.findMatchingSRTPProfile(
13367
- useSrtp.profiles,
13368
- dtls.options.srtpProfiles || []
13369
- );
13370
- log13(dtls.sessionId, "selected srtp profile", profile);
13371
- if (profile == void 0) return;
13372
- srtp.srtpProfile = profile;
13373
- }
13374
- break;
13375
- case ExtendedMasterSecret.type:
13376
- dtls.remoteExtendedMasterSecret = true;
13377
- break;
13378
- case RenegotiationIndication.type:
13379
- log13(dtls.sessionId, "RenegotiationIndication");
13380
- break;
13381
- }
13382
- });
13383
- }
13384
- };
13385
- handlers[HandshakeType.certificate_11] = ({ cipher, dtls }) => (message) => {
13386
- log13(dtls.sessionId, "handshake certificate", message);
13387
- cipher.remoteCertificate = message.certificateList[0];
13388
- };
13389
- handlers[HandshakeType.server_key_exchange_12] = ({ cipher, dtls }) => (message) => {
13390
- if (!cipher.localRandom || !cipher.remoteRandom) throw new Error();
13391
- log13(dtls.sessionId, "ServerKeyExchange", message);
13392
- log13(dtls.sessionId, "selected curve", message.namedCurve);
13393
- cipher.remoteKeyPair = {
13394
- curve: message.namedCurve,
13395
- publicKey: message.publicKey
13396
- };
13397
- cipher.localKeyPair = generateKeyPair(message.namedCurve);
14060
+ // ../dtls/src/cipher/create.ts
14061
+ var cipherSuites = {
14062
+ TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: 49195,
14063
+ TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: 49196,
14064
+ TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: 49199,
14065
+ TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: 49200,
14066
+ TLS_RSA_WITH_AES_128_GCM_SHA256: 156,
14067
+ TLS_RSA_WITH_AES_256_GCM_SHA384: 157,
14068
+ TLS_PSK_WITH_AES_128_GCM_SHA256: 168,
14069
+ TLS_PSK_WITH_AES_256_GCM_SHA384: 169,
14070
+ TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256: 53249,
14071
+ TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384: 53250,
14072
+ TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256: 52396,
14073
+ TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: 52393,
14074
+ TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: 52392,
14075
+ TLS_PSK_WITH_CHACHA20_POLY1305_SHA256: 52395
13398
14076
  };
13399
- handlers[HandshakeType.certificate_request_13] = ({ dtls }) => (message) => {
13400
- log13(dtls.sessionId, "certificate_request", message);
13401
- dtls.requestedCertificateTypes = message.certificateTypes;
13402
- dtls.requestedSignatureAlgorithms = message.signatures;
14077
+ var AEAD_AES_128_GCM = {
14078
+ K_LEN: 16,
14079
+ // Length of a key.
14080
+ N_MIN: 12,
14081
+ // Min nonce length.
14082
+ N_MAX: 12,
14083
+ // Max nonce length.
14084
+ P_MAX: 2 ** 36 - 31,
14085
+ // Max length of a plaintext.
14086
+ // Max safe int in js is 2 ** 53. So, use this value
14087
+ // instead of 2 ** 61 as described in rfc5116.
14088
+ A_MAX: 2 ** 53 - 1,
14089
+ // Max length of an additional data.
14090
+ C_MAX: 2 ** 36 - 15
14091
+ // Cipher text length.
13403
14092
  };
13404
- handlers[HandshakeType.server_hello_done_14] = ({ dtls }) => (msg) => {
13405
- log13(dtls.sessionId, "server_hello_done", msg);
14093
+ var AEAD_AES_256_GCM = {
14094
+ K_LEN: 32,
14095
+ // Length of a key.
14096
+ N_MIN: 12,
14097
+ // Min nonce length.
14098
+ N_MAX: 12,
14099
+ // Max nonce length.
14100
+ P_MAX: 2 ** 36 - 31,
14101
+ // Max length of a plaintext.
14102
+ // Note: see above.
14103
+ A_MAX: 2 ** 53 - 1,
14104
+ // Max length of an additional data.
14105
+ C_MAX: 2 ** 36 - 15
14106
+ // Cipher text length.
13406
14107
  };
13407
-
13408
- // ../dtls/src/handshake/message/server/helloVerifyRequest.ts
13409
- var { decode: decode17, encode: encode17, types: types17 } = binaryData_exports;
13410
- var ServerHelloVerifyRequest = class _ServerHelloVerifyRequest {
13411
- serverVersion;
13412
- cookie;
13413
- msgType = HandshakeType.hello_verify_request_3;
13414
- messageSeq;
13415
- static spec = {
13416
- serverVersion: ProtocolVersion,
13417
- cookie: types17.buffer(types17.uint8)
13418
- };
13419
- constructor(serverVersion, cookie) {
13420
- this.serverVersion = serverVersion;
13421
- this.cookie = cookie;
13422
- }
13423
- static createEmpty() {
13424
- return new _ServerHelloVerifyRequest(void 0, void 0);
13425
- }
13426
- static deSerialize(buf) {
13427
- return new _ServerHelloVerifyRequest(
13428
- ...Object.values(decode17(buf, _ServerHelloVerifyRequest.spec))
13429
- );
13430
- }
13431
- serialize() {
13432
- return encode17(this, _ServerHelloVerifyRequest.spec);
13433
- }
13434
- get version() {
13435
- return {
13436
- major: 255 - this.serverVersion.major,
13437
- minor: 255 - this.serverVersion.minor
13438
- };
13439
- }
13440
- toFragment() {
13441
- const body = this.serialize();
13442
- return new FragmentedHandshake(
13443
- this.msgType,
13444
- body.length,
13445
- this.messageSeq,
13446
- 0,
13447
- body.length,
13448
- body
13449
- );
13450
- }
13451
- };
13452
-
13453
- // ../dtls/src/context/cipher.ts
13454
- import {
13455
- createPrivateKey as createPrivateKey2,
13456
- createSign,
13457
- generateKeyPair as generateKeyPair2,
13458
- X509Certificate
13459
- } from "node:crypto";
13460
- import { promisify } from "node:util";
13461
-
13462
- // ../dtls/src/context/certificate.ts
13463
- import { randomBytes as randomBytes4, sign } from "node:crypto";
13464
- var signatureAlgorithms = {
13465
- // ecdsa-with-SHA256 (RFC 5758): parameters MUST be absent
13466
- "ecdsa-sha256": {
13467
- identifier: encodeDerSequence(encodeDerOid("1.2.840.10045.4.3.2")),
13468
- hash: "sha256"
13469
- },
13470
- // sha256WithRSAEncryption (RFC 4055): parameters MUST be NULL
13471
- "rsa-sha256": {
13472
- identifier: encodeDerSequence(
13473
- encodeDerOid("1.2.840.113549.1.1.11"),
13474
- encodeDerNull()
13475
- ),
13476
- hash: "sha256"
14108
+ var RSA_KEY_EXCHANGE = createRSAKeyExchange();
14109
+ var ECDHE_RSA_KEY_EXCHANGE = createECDHERSAKeyExchange();
14110
+ var ECDHE_ECDSA_KEY_EXCHANGE = createECDHEECDSAKeyExchange();
14111
+ var PSK_KEY_EXCHANGE = createPSKKeyExchange();
14112
+ var ECDHE_PSK_KEY_EXCHANGE = createECDHEPSKKeyExchange();
14113
+ function createCipher(cipher) {
14114
+ switch (cipher) {
14115
+ case cipherSuites.TLS_RSA_WITH_AES_128_GCM_SHA256:
14116
+ return createAEADCipher(
14117
+ cipherSuites.TLS_RSA_WITH_AES_128_GCM_SHA256,
14118
+ "TLS_RSA_WITH_AES_128_GCM_SHA256",
14119
+ "aes-128-gcm",
14120
+ RSA_KEY_EXCHANGE,
14121
+ AEAD_AES_128_GCM
14122
+ );
14123
+ case cipherSuites.TLS_RSA_WITH_AES_256_GCM_SHA384:
14124
+ return createAEADCipher(
14125
+ cipherSuites.TLS_RSA_WITH_AES_256_GCM_SHA384,
14126
+ "TLS_RSA_WITH_AES_256_GCM_SHA384",
14127
+ "aes-256-gcm",
14128
+ RSA_KEY_EXCHANGE,
14129
+ AEAD_AES_256_GCM,
14130
+ "sha384"
14131
+ );
14132
+ case cipherSuites.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
14133
+ return createAEADCipher(
14134
+ cipherSuites.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
14135
+ "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
14136
+ "aes-128-gcm",
14137
+ ECDHE_RSA_KEY_EXCHANGE,
14138
+ AEAD_AES_128_GCM
14139
+ );
14140
+ case cipherSuites.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
14141
+ return createAEADCipher(
14142
+ cipherSuites.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
14143
+ "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
14144
+ "aes-256-gcm",
14145
+ ECDHE_RSA_KEY_EXCHANGE,
14146
+ AEAD_AES_256_GCM,
14147
+ "sha384"
14148
+ );
14149
+ case cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
14150
+ return createAEADCipher(
14151
+ cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
14152
+ "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
14153
+ "aes-128-gcm",
14154
+ ECDHE_ECDSA_KEY_EXCHANGE,
14155
+ AEAD_AES_128_GCM
14156
+ );
14157
+ case cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
14158
+ return createAEADCipher(
14159
+ cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
14160
+ "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
14161
+ "aes-256-gcm",
14162
+ ECDHE_ECDSA_KEY_EXCHANGE,
14163
+ AEAD_AES_256_GCM,
14164
+ "sha384"
14165
+ );
14166
+ case cipherSuites.TLS_PSK_WITH_AES_128_GCM_SHA256:
14167
+ return createAEADCipher(
14168
+ cipherSuites.TLS_PSK_WITH_AES_128_GCM_SHA256,
14169
+ "TLS_PSK_WITH_AES_128_GCM_SHA256",
14170
+ "aes-128-gcm",
14171
+ PSK_KEY_EXCHANGE,
14172
+ AEAD_AES_128_GCM,
14173
+ "sha256"
14174
+ );
14175
+ case cipherSuites.TLS_PSK_WITH_AES_256_GCM_SHA384:
14176
+ return createAEADCipher(
14177
+ cipherSuites.TLS_PSK_WITH_AES_256_GCM_SHA384,
14178
+ "TLS_PSK_WITH_AES_256_GCM_SHA384",
14179
+ "aes-256-gcm",
14180
+ PSK_KEY_EXCHANGE,
14181
+ AEAD_AES_256_GCM,
14182
+ "sha384"
14183
+ );
14184
+ case cipherSuites.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256:
14185
+ return createAEADCipher(
14186
+ cipherSuites.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,
14187
+ "TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256",
14188
+ "aes-128-gcm",
14189
+ ECDHE_PSK_KEY_EXCHANGE,
14190
+ AEAD_AES_128_GCM,
14191
+ "sha256"
14192
+ );
14193
+ case cipherSuites.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384:
14194
+ return createAEADCipher(
14195
+ cipherSuites.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,
14196
+ "TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384",
14197
+ "aes-256-gcm",
14198
+ ECDHE_PSK_KEY_EXCHANGE,
14199
+ AEAD_AES_256_GCM,
14200
+ "sha384"
14201
+ );
14202
+ default:
14203
+ break;
13477
14204
  }
13478
- };
13479
- var attributeTypes = {
13480
- C: "2.5.4.6",
13481
- ST: "2.5.4.8",
13482
- L: "2.5.4.7",
13483
- O: "2.5.4.10",
13484
- OU: "2.5.4.11",
13485
- CN: "2.5.4.3"
13486
- };
13487
- function encodeCertificateName(attributes) {
13488
- return encodeDerSequence(
13489
- ...attributes.map(
13490
- ([type, value]) => encodeDerSet(
13491
- encodeDerSequence(
13492
- encodeDerOid(attributeTypes[type]),
13493
- type === "C" ? encodeDerPrintableString(value) : encodeDerUtf8String(value)
13494
- )
13495
- )
13496
- )
13497
- );
13498
- }
13499
- function createSelfSignedCertificatePem({
13500
- publicKey,
13501
- privateKey,
13502
- signatureAlgorithm,
13503
- name,
13504
- notBefore,
13505
- notAfter,
13506
- serialNumber = randomBytes4(8)
13507
- }) {
13508
- const { identifier, hash: hash2 } = signatureAlgorithms[signatureAlgorithm];
13509
- const encodedName = encodeCertificateName(name);
13510
- const tbsCertificate = encodeDerSequence(
13511
- // version: v3
13512
- encodeDerExplicit(0, encodeDerInteger(2)),
13513
- encodeDerInteger(serialNumber),
13514
- identifier,
13515
- // issuer = subject for a self-signed certificate
13516
- encodedName,
13517
- encodeDerSequence(encodeDerTime(notBefore), encodeDerTime(notAfter)),
13518
- encodedName,
13519
- publicKey.export({ type: "spki", format: "der" })
13520
- );
13521
- const signature = sign(hash2, tbsCertificate, privateKey);
13522
- const certificate = encodeDerSequence(
13523
- tbsCertificate,
13524
- identifier,
13525
- encodeDerBitString(signature)
13526
- );
13527
- return encodePem("CERTIFICATE", certificate);
14205
+ return null;
13528
14206
  }
13529
-
13530
- // ../dtls/src/context/cipher.ts
13531
- var { encode: encode18, types: types18 } = binaryData_exports;
13532
- var generateKeyPairAsync = promisify(generateKeyPair2);
13533
- var CipherContext = class {
13534
- sessionType;
13535
- certPem;
13536
- keyPem;
13537
- localRandom;
13538
- remoteRandom;
13539
- cipherSuite;
13540
- remoteCertificate;
13541
- remoteKeyPair;
13542
- localKeyPair;
13543
- masterSecret;
13544
- cipher;
13545
- namedCurve;
13546
- signatureHashAlgorithm;
13547
- localCert;
13548
- localPrivateKey;
13549
- constructor(sessionType, certPem, keyPem, signatureHashAlgorithm) {
13550
- this.sessionType = sessionType;
13551
- this.certPem = certPem;
13552
- this.keyPem = keyPem;
13553
- if (certPem && keyPem && signatureHashAlgorithm) {
13554
- this.parseX509(certPem, keyPem, signatureHashAlgorithm);
13555
- }
13556
- }
13557
- /**
13558
- *
13559
- * @param signatureHash
13560
- * @param namedCurveAlgorithm kept for compatibility. ECDSA certificates always use P-256 (X25519 cannot sign).
13561
- */
13562
- static createSelfSignedCertificateWithKey = async (signatureHash, namedCurveAlgorithm) => {
13563
- if (signatureHash.hash !== HashAlgorithm.sha256_4) {
13564
- throw new Error(`unsupported hash algorithm: ${signatureHash.hash}`);
13565
- }
13566
- const { publicKey, privateKey } = await (() => {
13567
- switch (signatureHash.signature) {
13568
- case SignatureAlgorithm.rsa_1:
13569
- return generateKeyPairAsync("rsa", {
13570
- modulusLength: 2048,
13571
- publicExponent: 65537
13572
- });
13573
- case SignatureAlgorithm.ecdsa_3:
13574
- return generateKeyPairAsync("ec", { namedCurve: "P-256" });
13575
- default:
13576
- throw new Error(
13577
- `unsupported signature algorithm: ${signatureHash.signature}`
13578
- );
13579
- }
13580
- })();
13581
- const notBefore = /* @__PURE__ */ new Date();
13582
- const certPem = createSelfSignedCertificatePem({
13583
- publicKey,
13584
- privateKey,
13585
- signatureAlgorithm: signatureHash.signature === SignatureAlgorithm.ecdsa_3 ? "ecdsa-sha256" : "rsa-sha256",
13586
- name: [
13587
- ["C", "AU"],
13588
- ["ST", "Some-State"],
13589
- ["O", "Internet Widgits Pty Ltd"]
13590
- ],
13591
- notBefore,
13592
- notAfter: new Date(notBefore.getTime() + 10 * 365 * 24 * 60 * 60 * 1e3)
13593
- });
13594
- const keyPem = privateKey.export({
13595
- type: "pkcs8",
13596
- format: "pem"
13597
- });
13598
- return { certPem, keyPem, signatureHash };
14207
+ function createAEADCipher(id, name, block, kx, constants, hash2 = "sha256") {
14208
+ const cipher = new AEADCipher();
14209
+ cipher.id = id;
14210
+ cipher.name = name;
14211
+ cipher.blockAlgorithm = block;
14212
+ cipher.kx = kx;
14213
+ cipher.hashAlgorithm = hash2;
14214
+ cipher.keyLength = constants.K_LEN;
14215
+ cipher.nonceLength = constants.N_MAX;
14216
+ cipher.nonceImplicitLength = 4;
14217
+ cipher.nonceExplicitLength = 8;
14218
+ cipher.ivLength = cipher.nonceImplicitLength;
14219
+ cipher.authTagLength = 16;
14220
+ return cipher;
14221
+ }
14222
+
14223
+ // ../dtls/src/handshake/message/certificate.ts
14224
+ var { decode: decode13, encode: encode14, types: types14 } = binaryData_exports;
14225
+ var Certificate = class _Certificate {
14226
+ certificateList;
14227
+ msgType = HandshakeType.certificate_11;
14228
+ messageSeq;
14229
+ static spec = {
14230
+ certificateList: types14.array(ASN11Cert, types14.uint24be, "bytes")
13599
14231
  };
13600
- encryptPacket(pkt) {
13601
- const header = pkt.recordLayerHeader;
13602
- const version = header.protocolVersion.major << 8 | header.protocolVersion.minor;
13603
- const enc = this.cipher.encrypt(this.sessionType, pkt.fragment, {
13604
- type: header.contentType,
13605
- version,
13606
- epoch: header.epoch,
13607
- sequenceNumber: header.sequenceNumber
13608
- });
13609
- pkt.fragment = enc;
13610
- pkt.recordLayerHeader.contentLen = enc.length;
13611
- return pkt;
14232
+ constructor(certificateList) {
14233
+ this.certificateList = certificateList;
13612
14234
  }
13613
- decryptPacket(pkt) {
13614
- const header = pkt.recordLayerHeader;
13615
- const version = header.protocolVersion.major << 8 | header.protocolVersion.minor;
13616
- const dec = this.cipher.decrypt(this.sessionType, pkt.fragment, {
13617
- type: header.contentType,
13618
- version,
13619
- epoch: header.epoch,
13620
- sequenceNumber: header.sequenceNumber
13621
- });
13622
- return dec;
14235
+ static createEmpty() {
14236
+ return new _Certificate(void 0);
13623
14237
  }
13624
- verifyData(buf) {
13625
- if (this.sessionType === SessionType.CLIENT)
13626
- return prfVerifyDataClient(this.masterSecret, buf);
13627
- else return prfVerifyDataServer(this.masterSecret, buf);
14238
+ static deSerialize(buf) {
14239
+ return new _Certificate(
14240
+ ...Object.values(decode13(buf, _Certificate.spec))
14241
+ );
13628
14242
  }
13629
- signatureData(data, hash2) {
13630
- return createSign(hash2).update(data).sign(this.localPrivateKey);
14243
+ serialize() {
14244
+ return encode14(this, _Certificate.spec);
13631
14245
  }
13632
- generateKeySignature(hashAlgorithm) {
13633
- const clientRandom = this.sessionType === SessionType.CLIENT ? this.localRandom : this.remoteRandom;
13634
- const serverRandom = this.sessionType === SessionType.SERVER ? this.localRandom : this.remoteRandom;
13635
- const sig = this.valueKeySignature(
13636
- clientRandom.serialize(),
13637
- serverRandom.serialize(),
13638
- this.localKeyPair.publicKey,
13639
- this.namedCurve
14246
+ toFragment() {
14247
+ const body = this.serialize();
14248
+ return new FragmentedHandshake(
14249
+ this.msgType,
14250
+ body.length,
14251
+ this.messageSeq,
14252
+ 0,
14253
+ body.length,
14254
+ body
13640
14255
  );
13641
- return createSign(hashAlgorithm).update(sig).sign(this.localPrivateKey);
13642
14256
  }
13643
- parseX509(certPem, keyPem, signatureHash) {
13644
- this.localCert = new X509Certificate(normalizePem(certPem)).raw;
13645
- this.localPrivateKey = createPrivateKey2(normalizePem(keyPem));
13646
- this.signatureHashAlgorithm = signatureHash;
14257
+ };
14258
+
14259
+ // ../dtls/src/handshake/message/changeCipherSpec.ts
14260
+ var { decode: decode14, encode: encode15, types: types15 } = binaryData_exports;
14261
+ var ChangeCipherSpec = class _ChangeCipherSpec {
14262
+ type;
14263
+ static spec = {
14264
+ type: types15.uint8
14265
+ };
14266
+ constructor(type = 1) {
14267
+ this.type = type;
13647
14268
  }
13648
- valueKeySignature(clientRandom, serverRandom, publicKey, namedCurve) {
13649
- const serverParams = encode18(
13650
- {
13651
- type: CurveType.named_curve_3,
13652
- curve: namedCurve,
13653
- len: publicKey.length
13654
- },
13655
- { type: types18.uint8, curve: types18.uint16be, len: types18.uint8 }
14269
+ static createEmpty() {
14270
+ return new _ChangeCipherSpec();
14271
+ }
14272
+ static deSerialize(buf) {
14273
+ const { type } = decode14(buf, _ChangeCipherSpec.spec);
14274
+ return new _ChangeCipherSpec(type);
14275
+ }
14276
+ serialize() {
14277
+ return encode15(this, _ChangeCipherSpec.spec);
14278
+ }
14279
+ };
14280
+
14281
+ // ../dtls/src/handshake/message/client/certificateVerify.ts
14282
+ var { decode: decode15, encode: encode16, types: types16 } = binaryData_exports;
14283
+ var CertificateVerify = class _CertificateVerify {
14284
+ algorithm;
14285
+ signature;
14286
+ msgType = HandshakeType.certificate_verify_15;
14287
+ messageSeq;
14288
+ static spec = {
14289
+ algorithm: types16.uint16be,
14290
+ signature: types16.buffer(types16.uint16be)
14291
+ };
14292
+ constructor(algorithm, signature) {
14293
+ this.algorithm = algorithm;
14294
+ this.signature = signature;
14295
+ }
14296
+ static createEmpty() {
14297
+ return new _CertificateVerify(void 0, void 0);
14298
+ }
14299
+ static deSerialize(buf) {
14300
+ const res = decode15(buf, _CertificateVerify.spec);
14301
+ return new _CertificateVerify(
14302
+ ...Object.values(res)
14303
+ );
14304
+ }
14305
+ serialize() {
14306
+ return encode16(this, _CertificateVerify.spec);
14307
+ }
14308
+ toFragment() {
14309
+ const body = this.serialize();
14310
+ return new FragmentedHandshake(
14311
+ this.msgType,
14312
+ body.length,
14313
+ this.messageSeq,
14314
+ 0,
14315
+ body.length,
14316
+ body
13656
14317
  );
13657
- return Buffer.concat([clientRandom, serverRandom, serverParams, publicKey]);
13658
14318
  }
13659
14319
  };
13660
- function normalizePem(pem) {
13661
- return `${pem.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0).join("\n")}
13662
- `;
13663
- }
13664
14320
 
13665
- // ../dtls/src/context/dtls.ts
13666
- var log14 = debug("werift-dtls : packages/dtls/src/context/dtls.ts : log");
14321
+ // ../dtls/src/handshake/message/client/keyExchange.ts
14322
+ var { decode: decode16, encode: encode17, types: types17 } = binaryData_exports;
14323
+ var ClientKeyExchange = class _ClientKeyExchange {
14324
+ publicKey;
14325
+ msgType = HandshakeType.client_key_exchange_16;
14326
+ messageSeq;
14327
+ static spec = {
14328
+ publicKey: types17.buffer(types17.uint8)
14329
+ };
14330
+ constructor(publicKey) {
14331
+ this.publicKey = publicKey;
14332
+ }
14333
+ static createEmpty() {
14334
+ return new _ClientKeyExchange(void 0);
14335
+ }
14336
+ static deSerialize(buf) {
14337
+ const res = decode16(buf, _ClientKeyExchange.spec);
14338
+ return new _ClientKeyExchange(
14339
+ ...Object.values(res)
14340
+ );
14341
+ }
14342
+ serialize() {
14343
+ return encode17(this, _ClientKeyExchange.spec);
14344
+ }
14345
+ toFragment() {
14346
+ const body = this.serialize();
14347
+ return new FragmentedHandshake(
14348
+ this.msgType,
14349
+ body.length,
14350
+ this.messageSeq,
14351
+ 0,
14352
+ body.length,
14353
+ body
14354
+ );
14355
+ }
14356
+ };
13667
14357
 
13668
- // ../dtls/src/handshake/extensions/ellipticCurves.ts
13669
- var { decode: decode18, encode: encode19, types: types19 } = binaryData_exports;
13670
- var EllipticCurves = class _EllipticCurves {
13671
- static type = 10;
14358
+ // ../dtls/src/handshake/message/server/certificateRequest.ts
14359
+ var { decode: decode17, encode: encode18, types: types18 } = binaryData_exports;
14360
+ var ServerCertificateRequest = class _ServerCertificateRequest {
14361
+ certificateTypes;
14362
+ signatures;
14363
+ authorities;
14364
+ msgType = HandshakeType.certificate_request_13;
14365
+ messageSeq;
13672
14366
  static spec = {
13673
- type: types19.uint16be,
13674
- data: types19.array(types19.uint16be, types19.uint16be, "bytes")
14367
+ certificateTypes: types18.array(ClientCertificateType, types18.uint8, "bytes"),
14368
+ signatures: types18.array(SignatureHashAlgorithm, types18.uint16be, "bytes"),
14369
+ authorities: types18.array(DistinguishedName, types18.uint16be, "bytes")
13675
14370
  };
13676
- type = _EllipticCurves.type;
13677
- data = [];
13678
- constructor(props = {}) {
13679
- Object.assign(this, props);
14371
+ constructor(certificateTypes2, signatures2, authorities) {
14372
+ this.certificateTypes = certificateTypes2;
14373
+ this.signatures = signatures2;
14374
+ this.authorities = authorities;
13680
14375
  }
13681
14376
  static createEmpty() {
13682
- return new _EllipticCurves();
14377
+ return new _ServerCertificateRequest(
14378
+ void 0,
14379
+ void 0,
14380
+ void 0
14381
+ );
13683
14382
  }
13684
- static fromData(buf) {
13685
- return new _EllipticCurves({
13686
- type: _EllipticCurves.type,
13687
- data: decode18(buf, _EllipticCurves.spec.data)
13688
- });
14383
+ static deSerialize(buf) {
14384
+ return new _ServerCertificateRequest(
14385
+ ...Object.values(decode17(buf, _ServerCertificateRequest.spec))
14386
+ );
14387
+ }
14388
+ serialize() {
14389
+ return encode18(this, _ServerCertificateRequest.spec);
14390
+ }
14391
+ toFragment() {
14392
+ const body = this.serialize();
14393
+ return new FragmentedHandshake(
14394
+ this.msgType,
14395
+ body.length,
14396
+ this.messageSeq,
14397
+ 0,
14398
+ body.length,
14399
+ body
14400
+ );
14401
+ }
14402
+ };
14403
+
14404
+ // ../dtls/src/handshake/message/server/helloDone.ts
14405
+ var { decode: decode18, encode: encode19 } = binaryData_exports;
14406
+
14407
+ // ../dtls/src/util/binary.ts
14408
+ var { encode: encode20 } = binaryData_exports;
14409
+ function encodeBuffer(obj, spec) {
14410
+ return encode20(obj, spec);
14411
+ }
14412
+
14413
+ // ../dtls/src/handshake/message/server/keyExchange.ts
14414
+ var { decode: decode19, types: types19 } = binaryData_exports;
14415
+ var ServerKeyExchange = class _ServerKeyExchange {
14416
+ ellipticCurveType;
14417
+ namedCurve;
14418
+ publicKeyLength;
14419
+ publicKey;
14420
+ hashAlgorithm;
14421
+ signatureAlgorithm;
14422
+ signatureLength;
14423
+ signature;
14424
+ msgType = HandshakeType.server_key_exchange_12;
14425
+ messageSeq;
14426
+ static spec = {
14427
+ ellipticCurveType: types19.uint8,
14428
+ namedCurve: types19.uint16be,
14429
+ publicKeyLength: types19.uint8,
14430
+ publicKey: types19.buffer((ctx) => ctx.current.publicKeyLength),
14431
+ hashAlgorithm: types19.uint8,
14432
+ signatureAlgorithm: types19.uint8,
14433
+ signatureLength: types19.uint16be,
14434
+ signature: types19.buffer((ctx) => ctx.current.signatureLength)
14435
+ };
14436
+ constructor(ellipticCurveType, namedCurve, publicKeyLength, publicKey, hashAlgorithm, signatureAlgorithm, signatureLength, signature) {
14437
+ this.ellipticCurveType = ellipticCurveType;
14438
+ this.namedCurve = namedCurve;
14439
+ this.publicKeyLength = publicKeyLength;
14440
+ this.publicKey = publicKey;
14441
+ this.hashAlgorithm = hashAlgorithm;
14442
+ this.signatureAlgorithm = signatureAlgorithm;
14443
+ this.signatureLength = signatureLength;
14444
+ this.signature = signature;
14445
+ }
14446
+ static createEmpty() {
14447
+ return new _ServerKeyExchange(
14448
+ void 0,
14449
+ void 0,
14450
+ void 0,
14451
+ void 0,
14452
+ void 0,
14453
+ void 0,
14454
+ void 0,
14455
+ void 0
14456
+ );
13689
14457
  }
13690
14458
  static deSerialize(buf) {
13691
- return new _EllipticCurves(decode18(buf, _EllipticCurves.spec));
14459
+ const res = decode19(buf, _ServerKeyExchange.spec);
14460
+ return new _ServerKeyExchange(
14461
+ ...Object.values(res)
14462
+ );
14463
+ }
14464
+ serialize() {
14465
+ const res = encodeBuffer(this, _ServerKeyExchange.spec);
14466
+ return res;
13692
14467
  }
13693
- serialize() {
13694
- return encode19(this, _EllipticCurves.spec);
14468
+ toFragment() {
14469
+ const body = this.serialize();
14470
+ return new FragmentedHandshake(
14471
+ this.msgType,
14472
+ body.length,
14473
+ this.messageSeq,
14474
+ 0,
14475
+ body.length,
14476
+ body
14477
+ );
13695
14478
  }
13696
- get extension() {
13697
- return {
13698
- type: this.type,
13699
- data: this.serialize().slice(2)
13700
- };
14479
+ };
14480
+
14481
+ // ../dtls/src/handshake/validation.ts
14482
+ var HandshakeValidation = {
14483
+ standard: "standard",
14484
+ lenient: "lenient"
14485
+ };
14486
+ function isStandardHandshakeValidation(validation) {
14487
+ return validation === HandshakeValidation.standard;
14488
+ }
14489
+
14490
+ // ../dtls/src/flight/client/flight5.ts
14491
+ var log14 = debug(
14492
+ "werift-dtls : packages/dtls/src/flight/client/flight5.ts : log"
14493
+ );
14494
+ var handlers = {};
14495
+ handlers[HandshakeType.server_hello_2] = ({ cipher, srtp, dtls }) => (message) => {
14496
+ log14(dtls.sessionId, "serverHello", message.cipherSuite);
14497
+ cipher.remoteRandom = DtlsRandom.from(message.random);
14498
+ cipher.cipherSuite = message.cipherSuite;
14499
+ log14(dtls.sessionId, "selected cipherSuite", cipher.cipherSuite);
14500
+ if (message.extensions) {
14501
+ message.extensions.forEach((extension) => {
14502
+ switch (extension.type) {
14503
+ case UseSRTP.type:
14504
+ {
14505
+ const useSrtp = UseSRTP.fromData(extension.data, {
14506
+ lenient: !isStandardHandshakeValidation(
14507
+ dtls.options.handshakeValidation
14508
+ )
14509
+ });
14510
+ const profile = SrtpContext2.findMatchingSRTPProfile(
14511
+ useSrtp.profiles,
14512
+ dtls.options.srtpProfiles || []
14513
+ );
14514
+ log14(dtls.sessionId, "selected srtp profile", profile);
14515
+ if (profile == void 0) return;
14516
+ srtp.srtpProfile = profile;
14517
+ }
14518
+ break;
14519
+ case ExtendedMasterSecret.type:
14520
+ dtls.remoteExtendedMasterSecret = true;
14521
+ break;
14522
+ case RenegotiationIndication.type:
14523
+ log14(dtls.sessionId, "RenegotiationIndication");
14524
+ break;
14525
+ }
14526
+ });
13701
14527
  }
13702
14528
  };
14529
+ handlers[HandshakeType.certificate_11] = ({ cipher, dtls }) => (message) => {
14530
+ log14(dtls.sessionId, "handshake certificate", message);
14531
+ cipher.remoteCertificate = message.certificateList[0];
14532
+ };
14533
+ handlers[HandshakeType.server_key_exchange_12] = ({ cipher, dtls }) => (message) => {
14534
+ if (!cipher.localRandom || !cipher.remoteRandom) throw new Error();
14535
+ log14(dtls.sessionId, "ServerKeyExchange", message);
14536
+ log14(dtls.sessionId, "selected curve", message.namedCurve);
14537
+ cipher.remoteKeyPair = {
14538
+ curve: message.namedCurve,
14539
+ publicKey: message.publicKey
14540
+ };
14541
+ cipher.localKeyPair = generateKeyPair(message.namedCurve);
14542
+ };
14543
+ handlers[HandshakeType.certificate_request_13] = ({ dtls }) => (message) => {
14544
+ log14(dtls.sessionId, "certificate_request", message);
14545
+ dtls.requestedCertificateTypes = message.certificateTypes;
14546
+ dtls.requestedSignatureAlgorithms = message.signatures;
14547
+ };
14548
+ handlers[HandshakeType.server_hello_done_14] = ({ dtls }) => (msg) => {
14549
+ log14(dtls.sessionId, "server_hello_done", msg);
14550
+ };
14551
+
14552
+ // ../dtls/src/context/dtls.ts
14553
+ var log15 = debug("werift-dtls : packages/dtls/src/context/dtls.ts : log");
13703
14554
 
13704
14555
  // ../dtls/src/handshake/extensions/signature.ts
13705
- var { decode: decode19, encode: encode20, types: types20 } = binaryData_exports;
14556
+ var { decode: decode20, encode: encode21, types: types20 } = binaryData_exports;
13706
14557
  var Signature = class _Signature {
13707
14558
  static type = 13;
13708
14559
  static spec = {
@@ -13723,10 +14574,10 @@ var Signature = class _Signature {
13723
14574
  return v;
13724
14575
  }
13725
14576
  static deSerialize(buf) {
13726
- return new _Signature(decode19(buf, _Signature.spec));
14577
+ return new _Signature(decode20(buf, _Signature.spec));
13727
14578
  }
13728
14579
  serialize() {
13729
- return encode20(this, _Signature.spec);
14580
+ return encode21(this, _Signature.spec);
13730
14581
  }
13731
14582
  static fromData(buf) {
13732
14583
  const type = Buffer.alloc(2);
@@ -13741,26 +14592,36 @@ var Signature = class _Signature {
13741
14592
  }
13742
14593
  };
13743
14594
 
14595
+ // ../dtls/src/record/message/reassembler.ts
14596
+ var err3 = debug(
14597
+ "werift-dtls : packages/dtls/src/record/message/reassembler.ts : err"
14598
+ );
14599
+
13744
14600
  // ../dtls/src/record/receive.ts
13745
- var log15 = debug("werift-dtls : packages/dtls/record/receive.ts : log");
13746
- var err3 = debug("werift-dtls : packages/dtls/record/receive.ts : err");
14601
+ var log16 = debug("werift-dtls : packages/dtls/record/receive.ts : log");
14602
+ var err4 = debug("werift-dtls : packages/dtls/record/receive.ts : err");
13747
14603
 
13748
14604
  // ../dtls/src/socket.ts
13749
- var { decode: decode20, types: types21 } = binaryData_exports;
13750
- var log16 = debug("werift-dtls : packages/dtls/src/socket.ts : log");
13751
- var err4 = debug("werift-dtls : packages/dtls/src/socket.ts : err");
14605
+ var { decode: decode21, types: types21 } = binaryData_exports;
14606
+ var log17 = debug("werift-dtls : packages/dtls/src/socket.ts : log");
14607
+ var err5 = debug("werift-dtls : packages/dtls/src/socket.ts : err");
13752
14608
 
13753
14609
  // ../dtls/src/client.ts
13754
- var log17 = debug("werift-dtls : packages/dtls/src/client.ts : log");
14610
+ var log18 = debug("werift-dtls : packages/dtls/src/client.ts : log");
14611
+
14612
+ // ../dtls/src/flight/server/commitClientHello.ts
14613
+ var log19 = debug(
14614
+ "werift-dtls : packages/dtls/flight/server/commitClientHello.ts : log"
14615
+ );
13755
14616
 
13756
14617
  // ../dtls/src/flight/server/flight2.ts
13757
- var log18 = debug("werift-dtls : packages/dtls/flight/server/flight2.ts : log");
14618
+ var log20 = debug("werift-dtls : packages/dtls/flight/server/flight2.ts : log");
13758
14619
 
13759
14620
  // ../dtls/src/flight/server/flight4.ts
13760
- var log19 = debug("werift-dtls : packages/dtls/flight/server/flight4.ts : log");
14621
+ var log21 = debug("werift-dtls : packages/dtls/flight/server/flight4.ts : log");
13761
14622
 
13762
14623
  // ../dtls/src/flight/server/flight6.ts
13763
- var log20 = debug("werift-dtls : packages/dtls/flight/server/flight6.ts");
14624
+ var log22 = debug("werift-dtls : packages/dtls/flight/server/flight6.ts");
13764
14625
  var handlers2 = {};
13765
14626
  handlers2[HandshakeType.client_key_exchange_16] = ({ cipher, dtls }) => (message) => {
13766
14627
  cipher.remoteKeyPair = {
@@ -13774,7 +14635,7 @@ handlers2[HandshakeType.client_key_exchange_16] = ({ cipher, dtls }) => (message
13774
14635
  cipher.localKeyPair.privateKey,
13775
14636
  cipher.localKeyPair.curve
13776
14637
  );
13777
- log20(
14638
+ log22(
13778
14639
  dtls.sessionId,
13779
14640
  "extendedMasterSecret",
13780
14641
  dtls.options.extendedMasterSecret,
@@ -13794,24 +14655,24 @@ handlers2[HandshakeType.client_key_exchange_16] = ({ cipher, dtls }) => (message
13794
14655
  cipher.localRandom.serialize(),
13795
14656
  cipher.remoteRandom.serialize()
13796
14657
  );
13797
- log20(dtls.sessionId, "setup cipher", cipher.cipher.summary);
14658
+ log22(dtls.sessionId, "setup cipher", cipher.cipher.summary);
13798
14659
  };
13799
14660
  handlers2[HandshakeType.certificate_11] = ({ cipher, dtls }) => (message) => {
13800
- log20(dtls.sessionId, "handshake certificate", message);
14661
+ log22(dtls.sessionId, "handshake certificate", message);
13801
14662
  cipher.remoteCertificate = message.certificateList[0];
13802
14663
  };
13803
14664
  handlers2[HandshakeType.certificate_verify_15] = ({ cipher, dtls }) => (message) => {
13804
14665
  if (!cipher.remoteCertificate) {
13805
14666
  throw new Error("client certificate missing before certificate verify");
13806
14667
  }
13807
- log20(dtls.sessionId, "certificate_verify", message.algorithm);
14668
+ log22(dtls.sessionId, "certificate_verify", message.algorithm);
13808
14669
  };
13809
14670
  handlers2[HandshakeType.finished_20] = ({ dtls }) => (message) => {
13810
- log20(dtls.sessionId, "finished", message);
14671
+ log22(dtls.sessionId, "finished", message);
13811
14672
  };
13812
14673
 
13813
14674
  // ../dtls/src/server.ts
13814
- var log21 = debug("werift-dtls : packages/dtls/src/server.ts : log");
14675
+ var log23 = debug("werift-dtls : packages/dtls/src/server.ts : log");
13815
14676
 
13816
14677
  // ../ice-server/src/stun/const.ts
13817
14678
  var COOKIE = 554869826;
@@ -14068,25 +14929,43 @@ var ATTRIBUTES_BY_NAME = ATTRIBUTES.reduce(
14068
14929
  var INTEGRITY_SHA1_VALUE_LENGTH = INTEGRITY_LENGTH - 4;
14069
14930
 
14070
14931
  // ../ice/src/iceBase.ts
14071
- var log22 = debug("werift-ice : packages/ice/src/ice.ts : log");
14932
+ var log24 = debug("werift-ice : packages/ice/src/ice.ts : log");
14933
+ var CONSENT_TIMEOUT = 30;
14934
+ var WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL = 900;
14935
+ var CONNECTION_WRITE_CONNECT_FAILURES = 5;
14936
+ var CONNECTION_WRITE_CONNECT_TIMEOUT = 5e3;
14937
+ var WEAK_CONNECTION_RECEIVE_TIMEOUT = 2500;
14938
+ var RECEIVING_SWITCHING_DELAY = 1e3;
14939
+ var DEAD_CONNECTION_RECEIVE_TIMEOUT = CONSENT_TIMEOUT * 1e3;
14072
14940
 
14073
14941
  // ../ice/src/stun/transaction.ts
14074
- var log23 = debug("werift-ice:packages/ice/src/stun/transaction.ts");
14942
+ var log25 = debug("werift-ice:packages/ice/src/stun/transaction.ts");
14075
14943
 
14076
14944
  // ../ice/src/stun/protocol.ts
14077
- var log24 = debug("werift-ice : packages/ice/src/stun/protocol.ts");
14945
+ var log26 = debug("werift-ice : packages/ice/src/stun/protocol.ts");
14078
14946
 
14079
14947
  // ../ice/src/stun/tcpProtocol.ts
14080
- var log25 = debug("werift-ice:packages/ice/src/stun/tcpProtocol.ts");
14948
+ var log27 = debug("werift-ice:packages/ice/src/stun/tcpProtocol.ts");
14081
14949
 
14082
14950
  // ../ice/src/turn/protocol.ts
14083
- var log26 = debug("werift-ice:packages/ice/src/turn/protocol.ts");
14951
+ var log28 = debug("werift-ice:packages/ice/src/turn/protocol.ts");
14084
14952
 
14085
14953
  // ../ice/src/candidateGatherer.ts
14086
- var log27 = debug("werift-ice : packages/ice/src/candidateGatherer.ts : log");
14954
+ var log29 = debug("werift-ice : packages/ice/src/candidateGatherer.ts : log");
14955
+
14956
+ // ../ice/src/failover.ts
14957
+ var DEFAULT_FAILOVER_THRESHOLDS = Object.freeze({
14958
+ unwritableMinChecks: CONNECTION_WRITE_CONNECT_FAILURES,
14959
+ unwritableTimeout: CONNECTION_WRITE_CONNECT_TIMEOUT,
14960
+ receivingTimeout: WEAK_CONNECTION_RECEIVE_TIMEOUT,
14961
+ receivingSwitchingDelay: RECEIVING_SWITCHING_DELAY
14962
+ });
14087
14963
 
14088
14964
  // ../ice/src/consent.ts
14089
- var log28 = debug("werift-ice : packages/ice/src/consent.ts : log");
14965
+ var log30 = debug("werift-ice : packages/ice/src/consent.ts : log");
14966
+ var CONSENT_MAX_OUTSTANDING_REQUESTS = Math.ceil(
14967
+ CONSENT_TIMEOUT * 1e3 / WEAK_OR_STABILIZING_WRITABLE_CONNECTION_PING_INTERVAL
14968
+ ) + 1;
14090
14969
 
14091
14970
  // ../ice/src/dns/lookup.ts
14092
14971
  import mdns from "multicast-dns";
@@ -14094,21 +14973,29 @@ import mdns from "multicast-dns";
14094
14973
  // ../ice/src/utils.ts
14095
14974
  var logger = debug("werift-ice : packages/ice/src/utils.ts");
14096
14975
 
14976
+ // ../ice/src/dns/lookup.ts
14977
+ var log31 = debug("werift-ice : packages/ice/src/dns/lookup.ts : log");
14978
+
14097
14979
  // ../ice/src/nomination/regularNomination.ts
14098
- var log29 = debug(
14980
+ var log32 = debug(
14099
14981
  "werift-ice : packages/ice/src/nomination/regularNomination.ts : log"
14100
14982
  );
14101
14983
 
14984
+ // ../ice/src/nomination/selectionController.ts
14985
+ var log33 = debug(
14986
+ "werift-ice : packages/ice/src/nomination/selectionController.ts : log"
14987
+ );
14988
+
14102
14989
  // ../ice/src/nomination/selectionReplacement.ts
14103
- var log30 = debug(
14990
+ var log34 = debug(
14104
14991
  "werift-ice : packages/ice/src/nomination/selectionReplacement.ts : log"
14105
14992
  );
14106
14993
 
14107
14994
  // ../ice/src/provisional.ts
14108
- var log31 = debug("werift-ice : packages/ice/src/provisional.ts : log");
14995
+ var log35 = debug("werift-ice : packages/ice/src/provisional.ts : log");
14109
14996
 
14110
14997
  // ../ice/src/ice.ts
14111
- var log32 = debug("werift-ice : packages/ice/src/ice.ts : log");
14998
+ var log36 = debug("werift-ice : packages/ice/src/ice.ts : log");
14112
14999
 
14113
15000
  // ../sctp/src/chunk.ts
14114
15001
  var SCTP_PADDING_MULTIPLE = 4;
@@ -14251,6 +15138,11 @@ var DataChunk = class _DataChunk extends Chunk {
14251
15138
  /** Gap-acked before, then dropped by the peer (reneged) and not resent yet. */
14252
15139
  reneged = false;
14253
15140
  misses = 0;
15141
+ /**
15142
+ * Fast-retransmitted since it was last sent by the T3-rtx timer (or first
15143
+ * sent): it is not struck or fast-retransmitted again (RFC 9260 §7.2.4).
15144
+ */
15145
+ fastRetransmitted = false;
14254
15146
  retransmit = false;
14255
15147
  sentCount = 0;
14256
15148
  bookSize = 0;
@@ -14515,7 +15407,7 @@ function decodeParams(body) {
14515
15407
  }
14516
15408
 
14517
15409
  // ../sctp/src/sctp.ts
14518
- var log33 = debug("werift/sctp/sctp");
15410
+ var log37 = debug("werift/sctp/sctp");
14519
15411
  var DEFAULT_SCTP_MTU = 1191;
14520
15412
  var SCTP_RTO_ALPHA = 1 / 8;
14521
15413
  var SCTP_RTO_BETA = 1 / 4;
@@ -14645,26 +15537,284 @@ var SRTP_PROFILE = {
14645
15537
 
14646
15538
  // src/media/track.ts
14647
15539
  import { randomUUID as randomUUID5 } from "crypto";
15540
+
15541
+ // src/media/domEventTarget.ts
15542
+ var log38 = debug("werift:packages/webrtc/src/media/domEventTarget.ts");
15543
+ function captureOf(options) {
15544
+ return typeof options === "boolean" ? options : !!options?.capture;
15545
+ }
15546
+ var DomEventTarget = class extends EventTarget2 {
15547
+ domListeners = [];
15548
+ handlerAttributes = /* @__PURE__ */ new Map();
15549
+ addEventListener = (type, callback, options) => {
15550
+ if (callback == void 0) {
15551
+ return;
15552
+ }
15553
+ const flags = typeof options === "object" ? options : {};
15554
+ if (flags.signal?.aborted) {
15555
+ return;
15556
+ }
15557
+ const capture = captureOf(options);
15558
+ if (this.findListener(type, callback, capture)) {
15559
+ return;
15560
+ }
15561
+ const listener = this.register(type, callback, {
15562
+ capture,
15563
+ once: !!flags.once,
15564
+ passive: !!flags.passive
15565
+ });
15566
+ flags.signal?.addEventListener("abort", () => this.unregister(listener), {
15567
+ once: true
15568
+ });
15569
+ };
15570
+ removeEventListener = (type, callback, options) => {
15571
+ if (callback == void 0) {
15572
+ return;
15573
+ }
15574
+ const listener = this.findListener(type, callback, captureOf(options));
15575
+ if (listener) {
15576
+ this.unregister(listener);
15577
+ }
15578
+ };
15579
+ /** DOM `dispatchEvent()`: `false` only when a cancelable event was canceled. */
15580
+ dispatchEvent = (event) => {
15581
+ this.emitIsolated(
15582
+ (error) => log38(`${event.type} listener failed`, error),
15583
+ event.type,
15584
+ event
15585
+ );
15586
+ return !event.defaultPrevented;
15587
+ };
15588
+ /** The value of the `on<type>` handler attribute. */
15589
+ getEventHandler(type) {
15590
+ return this.handlerAttributes.get(type)?.handler ?? null;
15591
+ }
15592
+ /** Set the `on<type>` handler attribute (a non-function value clears it, as the DOM does). */
15593
+ setEventHandler(type, handler) {
15594
+ const current = this.handlerAttributes.get(type);
15595
+ if (typeof handler !== "function") {
15596
+ if (current) {
15597
+ this.handlerAttributes.delete(type);
15598
+ this.unregister(current.listener);
15599
+ }
15600
+ return;
15601
+ }
15602
+ if (current) {
15603
+ current.handler = handler;
15604
+ return;
15605
+ }
15606
+ const entry = {
15607
+ handler,
15608
+ listener: void 0
15609
+ };
15610
+ const callback = (event) => {
15611
+ const result = entry.handler.call(this, event);
15612
+ if (result === false) {
15613
+ event.preventDefault();
15614
+ }
15615
+ };
15616
+ entry.listener = this.register(type, callback, {
15617
+ capture: false,
15618
+ once: false,
15619
+ passive: false
15620
+ });
15621
+ this.handlerAttributes.set(type, entry);
15622
+ }
15623
+ findListener(type, callback, capture) {
15624
+ return this.domListeners.find(
15625
+ (listener) => listener.type === type && listener.callback === callback && listener.capture === capture
15626
+ );
15627
+ }
15628
+ register(type, callback, flags) {
15629
+ const listener = {
15630
+ type,
15631
+ callback,
15632
+ ...flags,
15633
+ removed: false,
15634
+ wrapper: (event) => this.invoke(listener, event)
15635
+ };
15636
+ this.domListeners.push(listener);
15637
+ this.on(type, listener.wrapper);
15638
+ return listener;
15639
+ }
15640
+ unregister(listener) {
15641
+ if (listener.removed) {
15642
+ return;
15643
+ }
15644
+ listener.removed = true;
15645
+ const index = this.domListeners.indexOf(listener);
15646
+ if (index >= 0) {
15647
+ this.domListeners.splice(index, 1);
15648
+ }
15649
+ this.removeListener(listener.type, listener.wrapper);
15650
+ }
15651
+ invoke(listener, event) {
15652
+ if (listener.removed) {
15653
+ return;
15654
+ }
15655
+ if (listener.once) {
15656
+ this.unregister(listener);
15657
+ }
15658
+ const restore = listener.passive ? suppressPreventDefault(event) : noop;
15659
+ try {
15660
+ const { callback } = listener;
15661
+ if (typeof callback === "function") {
15662
+ callback.call(this, event);
15663
+ } else {
15664
+ callback.handleEvent(event);
15665
+ }
15666
+ } catch (error) {
15667
+ log38(`${listener.type} listener failed`, error);
15668
+ } finally {
15669
+ restore();
15670
+ }
15671
+ }
15672
+ };
15673
+ function noop() {
15674
+ }
15675
+ function suppressPreventDefault(event) {
15676
+ if (typeof event?.preventDefault !== "function") {
15677
+ return noop;
15678
+ }
15679
+ const own = Object.getOwnPropertyDescriptor(event, "preventDefault");
15680
+ try {
15681
+ Object.defineProperty(event, "preventDefault", {
15682
+ configurable: true,
15683
+ value: noop
15684
+ });
15685
+ } catch {
15686
+ return noop;
15687
+ }
15688
+ return () => {
15689
+ if (own) {
15690
+ Object.defineProperty(event, "preventDefault", own);
15691
+ } else {
15692
+ delete event.preventDefault;
15693
+ }
15694
+ };
15695
+ }
15696
+
15697
+ // src/media/trackConstraints.ts
15698
+ var weriftConstraintNames = [
15699
+ "deviceId",
15700
+ "groupId",
15701
+ "mimeType"
15702
+ ];
15703
+ function stripUnsupportedConstraints(constraints) {
15704
+ const next = { ...pickSupported(constraints) };
15705
+ const advanced = constraints?.advanced;
15706
+ if (Array.isArray(advanced)) {
15707
+ next.advanced = advanced.map((entry) => pickSupported(entry));
15708
+ }
15709
+ return next;
15710
+ }
15711
+ function pickSupported(constraintSet) {
15712
+ const next = {};
15713
+ for (const name of weriftConstraintNames) {
15714
+ const value = constraintSet?.[name];
15715
+ if (value != void 0) {
15716
+ next[name] = structuredClone(value);
15717
+ }
15718
+ }
15719
+ return next;
15720
+ }
15721
+ function findUnsupportedRequiredConstraint(constraints) {
15722
+ for (const [name, value] of Object.entries(constraints ?? {})) {
15723
+ if (name === "advanced" || weriftConstraintNames.includes(name) || typeof value !== "object" || value == null || Array.isArray(value)) {
15724
+ continue;
15725
+ }
15726
+ const { exact, min, max } = value;
15727
+ if (exact != void 0 || min != void 0 || max != void 0) {
15728
+ return name;
15729
+ }
15730
+ }
15731
+ return void 0;
15732
+ }
15733
+ function constraintFitnessDistance(settings, constraintSet, bareMode) {
15734
+ let distance = 0;
15735
+ for (const name of weriftConstraintNames) {
15736
+ const constraint = constraintSet[name];
15737
+ if (constraint == void 0) {
15738
+ continue;
15739
+ }
15740
+ const next = constrainDomStringDistance(
15741
+ settings[name],
15742
+ constraint,
15743
+ bareMode
15744
+ );
15745
+ if (next === Number.POSITIVE_INFINITY) {
15746
+ return Number.POSITIVE_INFINITY;
15747
+ }
15748
+ distance += next;
15749
+ }
15750
+ return distance;
15751
+ }
15752
+ function findFailedRequiredConstraint(candidates, basic) {
15753
+ for (const name of weriftConstraintNames) {
15754
+ const constraint = basic[name];
15755
+ if (!isRequired(constraint)) {
15756
+ continue;
15757
+ }
15758
+ const anyFinite = candidates.some(
15759
+ (candidate) => constraintFitnessDistance(candidate, { [name]: constraint }, "ideal") < Number.POSITIVE_INFINITY
15760
+ );
15761
+ if (!anyFinite) {
15762
+ return name;
15763
+ }
15764
+ }
15765
+ return void 0;
15766
+ }
15767
+ function constrainDomStringDistance(actual, constraint, bareMode) {
15768
+ const { exact, ideal } = normalizeConstrainDomString(constraint, bareMode);
15769
+ if (exact && !matchesDomString(actual, exact)) {
15770
+ return Number.POSITIVE_INFINITY;
15771
+ }
15772
+ if (!ideal) {
15773
+ return 0;
15774
+ }
15775
+ return matchesDomString(actual, ideal) ? 0 : 1;
15776
+ }
15777
+ function normalizeConstrainDomString(constraint, bareMode) {
15778
+ if (typeof constraint === "string" || Array.isArray(constraint)) {
15779
+ const values = toStringList(constraint);
15780
+ return bareMode === "exact" ? { exact: values } : { ideal: values };
15781
+ }
15782
+ return {
15783
+ exact: constraint.exact ? toStringList(constraint.exact) : void 0,
15784
+ ideal: constraint.ideal ? toStringList(constraint.ideal) : void 0
15785
+ };
15786
+ }
15787
+ function toStringList(value) {
15788
+ return Array.isArray(value) ? value : [value];
15789
+ }
15790
+ function matchesDomString(actual, expected) {
15791
+ return actual != void 0 && expected.includes(actual);
15792
+ }
15793
+ function isRequired(constraint) {
15794
+ if (constraint == void 0) {
15795
+ return false;
15796
+ }
15797
+ if (typeof constraint === "string" || Array.isArray(constraint)) {
15798
+ return false;
15799
+ }
15800
+ return constraint.exact != void 0;
15801
+ }
15802
+
15803
+ // src/media/track.ts
14648
15804
  var RtpReceivePacketType = {
14649
15805
  media: "media",
14650
15806
  padding: "padding",
14651
15807
  retransmission: "retransmission"
14652
15808
  };
14653
- var sourceCodecsByTrack = /* @__PURE__ */ new WeakMap();
14654
- var sourceCodecsCapturedByTrack = /* @__PURE__ */ new WeakSet();
14655
15809
  function setTrackSourceCodecs(track, codecs) {
14656
- sourceCodecsCapturedByTrack.add(track);
14657
- if (codecs == void 0) sourceCodecsByTrack.delete(track);
14658
- else sourceCodecsByTrack.set(track, codecs);
14659
- }
14660
- function getTrackSourceCodecs(track) {
14661
- return track == void 0 ? void 0 : sourceCodecsByTrack.get(track);
15810
+ track.sourceCodecsCaptured = true;
15811
+ track.sourceCodecs = codecs;
14662
15812
  }
14663
15813
  function captureTrackSourceCodecs(track) {
14664
- if (sourceCodecsCapturedByTrack.has(track)) return;
14665
- sourceCodecsCapturedByTrack.add(track);
15814
+ if (track.sourceCodecsCaptured) return;
15815
+ track.sourceCodecsCaptured = true;
14666
15816
  if (track.codec != void 0) {
14667
- sourceCodecsByTrack.set(track, [track.codec]);
15817
+ track.sourceCodecs = [track.codec];
14668
15818
  }
14669
15819
  }
14670
15820
  var TrackBroadcastSource = class {
@@ -14711,18 +15861,27 @@ var TrackBroadcastSource = class {
14711
15861
  }
14712
15862
  }
14713
15863
  stopAllTracks() {
15864
+ let failed;
14714
15865
  for (const track of [...this.tracks]) {
14715
- track.stop();
15866
+ try {
15867
+ track.stop();
15868
+ } catch (error) {
15869
+ failed ??= { error };
15870
+ }
15871
+ }
15872
+ if (failed) {
15873
+ throw failed.error;
14716
15874
  }
14717
15875
  }
14718
15876
  };
14719
- var MediaStreamTrack = class _MediaStreamTrack extends EventTarget2 {
15877
+ var MediaStreamTrack = class _MediaStreamTrack extends DomEventTarget {
14720
15878
  uuid = randomUUID5().toString();
14721
15879
  /**MediaStream ID*/
14722
15880
  streamId;
14723
15881
  remote = false;
14724
15882
  label;
14725
15883
  kind;
15884
+ /** Track ID. Defaults to {@link uuid} when not given to the constructor. */
14726
15885
  id;
14727
15886
  /**mediaSsrc */
14728
15887
  ssrc;
@@ -14731,11 +15890,62 @@ var MediaStreamTrack = class _MediaStreamTrack extends EventTarget2 {
14731
15890
  codec;
14732
15891
  /**todo impl */
14733
15892
  enabled = true;
15893
+ /** DOM `contentHint`. Stored only; werift does not change encoding by it. */
15894
+ contentHint = "";
15895
+ /**
15896
+ * DOM `onended`, a listener of `"ended"` at the position where it was first
15897
+ * set (see {@link DomEventTarget}). Unlike the DOM, werift also dispatches
15898
+ * `"ended"` when {@link stop} is called, once per track.
15899
+ */
15900
+ get onended() {
15901
+ return this.getEventHandler("ended");
15902
+ }
15903
+ set onended(handler) {
15904
+ this.setEventHandler("ended", handler);
15905
+ }
15906
+ /**
15907
+ * DOM `onmute`. werift does not detect a muted source and never dispatches
15908
+ * `"mute"` itself; the handler runs for a `"mute"` event passed to
15909
+ * `dispatchEvent`.
15910
+ */
15911
+ get onmute() {
15912
+ return this.getEventHandler("mute");
15913
+ }
15914
+ set onmute(handler) {
15915
+ this.setEventHandler("mute", handler);
15916
+ }
15917
+ /**
15918
+ * DOM `onunmute`. werift changes {@link muted} on the first received media
15919
+ * packet without dispatching `"unmute"`; the handler runs for an `"unmute"`
15920
+ * event passed to `dispatchEvent`.
15921
+ */
15922
+ get onunmute() {
15923
+ return this.getEventHandler("unmute");
15924
+ }
15925
+ set onunmute(handler) {
15926
+ this.setEventHandler("unmute", handler);
15927
+ }
14734
15928
  onReceiveRtp = new Event2();
14735
15929
  onReceiveRtcp = new Event2();
14736
15930
  onSourceChanged = new Event2();
14737
15931
  stopped = false;
14738
15932
  muted = true;
15933
+ /**
15934
+ * @internal The codecs the source produces, set by
15935
+ * {@link setTrackSourceCodecs} or captured from `codec` when the track is
15936
+ * first attached to a sender ({@link captureTrackSourceCodecs}).
15937
+ */
15938
+ sourceCodecs;
15939
+ /** @internal Whether {@link sourceCodecs} is already decided. */
15940
+ sourceCodecsCaptured = false;
15941
+ /**
15942
+ * @internal The settings the media source reported
15943
+ * ({@link setTrackMediaSettings}); `undefined` for a track werift created
15944
+ * without a media source.
15945
+ */
15946
+ sourceSettings;
15947
+ /** @internal The constraints most recently applied to this track. */
15948
+ appliedConstraints = {};
14739
15949
  broadcastSource;
14740
15950
  constructor(props) {
14741
15951
  super();
@@ -14764,9 +15974,99 @@ var MediaStreamTrack = class _MediaStreamTrack extends EventTarget2 {
14764
15974
  this.stopped = true;
14765
15975
  this.muted = true;
14766
15976
  this.onReceiveRtp.complete();
14767
- this.emit("ended");
15977
+ this.dispatchEvent(new globalThis.Event("ended"));
14768
15978
  this.broadcastSource.detach(this);
14769
15979
  };
15980
+ /**
15981
+ * DOM `getSettings()`. A track from the polyfill's `getUserMedia` reports
15982
+ * the `deviceId` / `groupId` / `mimeType` its media register was selected
15983
+ * by; another track reports what its {@link codec} tells (`mimeType`, and
15984
+ * `sampleRate` / `channelCount` for audio). An ended track reports only the
15985
+ * inherent `deviceId` / `groupId`, as the DOM does.
15986
+ */
15987
+ getSettings() {
15988
+ const settings = this.currentSettings();
15989
+ if (!this.stopped) {
15990
+ return settings;
15991
+ }
15992
+ const inherent = {};
15993
+ if (settings.deviceId != void 0) {
15994
+ inherent.deviceId = settings.deviceId;
15995
+ }
15996
+ if (settings.groupId != void 0) {
15997
+ inherent.groupId = settings.groupId;
15998
+ }
15999
+ return inherent;
16000
+ }
16001
+ currentSettings() {
16002
+ if (this.sourceSettings) {
16003
+ return { ...this.sourceSettings };
16004
+ }
16005
+ const settings = {};
16006
+ if (this.codec) {
16007
+ settings.mimeType = this.codec.mimeType;
16008
+ if (this.kind === "audio") {
16009
+ settings.sampleRate = this.codec.clockRate;
16010
+ if (this.codec.channels != void 0) {
16011
+ settings.channelCount = this.codec.channels;
16012
+ }
16013
+ }
16014
+ }
16015
+ return settings;
16016
+ }
16017
+ /**
16018
+ * DOM `getConstraints()`: the constraints most recently applied by
16019
+ * `getUserMedia` (limited to the constraints werift understands: `deviceId`,
16020
+ * `groupId`, `mimeType`) or {@link applyConstraints} (kept as given).
16021
+ */
16022
+ getConstraints() {
16023
+ return structuredClone(this.appliedConstraints);
16024
+ }
16025
+ /**
16026
+ * DOM `getCapabilities()`. werift cannot reconfigure a source, so the only
16027
+ * capabilities are the `deviceId` / `groupId` it was selected by.
16028
+ */
16029
+ getCapabilities() {
16030
+ const capabilities = {};
16031
+ const { deviceId, groupId } = this.getSettings();
16032
+ if (deviceId != void 0) {
16033
+ capabilities.deviceId = deviceId;
16034
+ }
16035
+ if (groupId != void 0) {
16036
+ capabilities.groupId = groupId;
16037
+ }
16038
+ return capabilities;
16039
+ }
16040
+ /**
16041
+ * DOM `applyConstraints()`. werift cannot reconfigure a source, so the
16042
+ * current settings are the only possible settings: a required (`exact`)
16043
+ * constraint they do not satisfy rejects with `OverconstrainedError` and
16044
+ * keeps the previous constraints (so does a required constraint on a name werift cannot honor, such as `width`); otherwise the constraints, including such ideal ones, are stored
16045
+ * (see {@link getConstraints}) and the settings stay the same. An ended
16046
+ * track is checked against its ended settings ({@link getSettings}).
16047
+ */
16048
+ async applyConstraints(constraints = {}) {
16049
+ const unsupported = findUnsupportedRequiredConstraint(
16050
+ constraints
16051
+ );
16052
+ if (unsupported != void 0) {
16053
+ throw new OverconstrainedError(
16054
+ unsupported,
16055
+ "Cannot satisfy required constraints"
16056
+ );
16057
+ }
16058
+ const { advanced: _advanced, ...basic } = stripUnsupportedConstraints(
16059
+ constraints
16060
+ );
16061
+ const settings = this.getSettings();
16062
+ if (constraintFitnessDistance(settings, basic, "ideal") === Number.POSITIVE_INFINITY) {
16063
+ throw new OverconstrainedError(
16064
+ findFailedRequiredConstraint([settings], basic) ?? "",
16065
+ "Cannot satisfy required constraints"
16066
+ );
16067
+ }
16068
+ this.appliedConstraints = structuredClone(constraints);
16069
+ }
14770
16070
  writeRtp = (rtp) => {
14771
16071
  if (this.remote) {
14772
16072
  throw new Error("this is remoteTrack");
@@ -14813,20 +16113,44 @@ var MediaStreamTrack = class _MediaStreamTrack extends EventTarget2 {
14813
16113
  ssrc: this.ssrc,
14814
16114
  rid: this.rid,
14815
16115
  header: this.header,
16116
+ contentHint: this.contentHint,
14816
16117
  broadcastSource: this.broadcastSource
14817
16118
  });
14818
- if (sourceCodecsCapturedByTrack.has(this)) {
14819
- setTrackSourceCodecs(cloned, getTrackSourceCodecs(this));
16119
+ if (this.sourceSettings) {
16120
+ cloned.sourceSettings = { ...this.sourceSettings };
16121
+ }
16122
+ cloned.appliedConstraints = structuredClone(this.appliedConstraints);
16123
+ if (this.sourceCodecsCaptured) {
16124
+ setTrackSourceCodecs(cloned, this.sourceCodecs);
14820
16125
  } else {
14821
16126
  captureTrackSourceCodecs(cloned);
14822
16127
  }
14823
16128
  return cloned;
14824
16129
  }
14825
16130
  };
14826
- var MediaStream = class _MediaStream {
16131
+ var MediaStream = class _MediaStream extends DomEventTarget {
14827
16132
  id;
14828
16133
  tracks = [];
16134
+ /**
16135
+ * DOM `onaddtrack`. The DOM fires `"addtrack"` only when the user agent adds
16136
+ * a track; werift never does, and {@link addTrack} does not fire it either.
16137
+ * The handler runs for an `"addtrack"` event passed to `dispatchEvent`.
16138
+ */
16139
+ get onaddtrack() {
16140
+ return this.getEventHandler("addtrack");
16141
+ }
16142
+ set onaddtrack(handler) {
16143
+ this.setEventHandler("addtrack", handler);
16144
+ }
16145
+ /** DOM `onremovetrack`. werift never dispatches `"removetrack"`, as {@link onaddtrack}. */
16146
+ get onremovetrack() {
16147
+ return this.getEventHandler("removetrack");
16148
+ }
16149
+ set onremovetrack(handler) {
16150
+ this.setEventHandler("removetrack", handler);
16151
+ }
14829
16152
  constructor(props = {}) {
16153
+ super();
14830
16154
  if (Array.isArray(props)) {
14831
16155
  this.tracks = props;
14832
16156
  } else {
@@ -14848,13 +16172,17 @@ var MediaStream = class _MediaStream {
14848
16172
  return this.tracks;
14849
16173
  }
14850
16174
  getAudioTracks() {
14851
- return this.tracks.filter((track) => track.kind === "audio");
16175
+ return this.tracks.filter(
16176
+ (track) => track.kind === "audio"
16177
+ );
14852
16178
  }
14853
16179
  getVideoTracks() {
14854
- return this.tracks.filter((track) => track.kind === "video");
16180
+ return this.tracks.filter(
16181
+ (track) => track.kind === "video"
16182
+ );
14855
16183
  }
14856
16184
  getTrackById(id) {
14857
- return this.tracks.find((track) => track.id === id);
16185
+ return this.tracks.find((track) => track.id === id) ?? null;
14858
16186
  }
14859
16187
  get active() {
14860
16188
  return this.tracks.some((track) => !track.stopped);
@@ -14869,14 +16197,21 @@ var MediaStream = class _MediaStream {
14869
16197
  };
14870
16198
 
14871
16199
  // src/utils.ts
14872
- var log34 = debug("werift:packages/webrtc/src/utils.ts");
16200
+ var log39 = debug("werift:packages/webrtc/src/utils.ts");
14873
16201
  var milliTime = Date.now;
14874
16202
  var startupTimestampInMicroseconds = BigInt(Date.now()) * 1000n - process.hrtime.bigint() / 1000n;
14875
16203
  var NTP_FRACTION_SCALE = 2 ** 32;
14876
16204
  var createSelfSignedCertificate = CipherContext.createSelfSignedCertificateWithKey;
14877
16205
 
16206
+ // src/transport/sped.ts
16207
+ var log40 = debug("werift:packages/webrtc/src/transport/sped.ts");
16208
+ var EARLY_SEND_MAX_BYTES = 256 * 1024;
16209
+
16210
+ // src/transport/dtls-srtp.ts
16211
+ var log41 = debug("werift:packages/webrtc/src/transport/dtls-srtp.ts");
16212
+
14878
16213
  // src/transport/dtls.ts
14879
- var log35 = debug("werift:packages/webrtc/src/transport/dtls.ts");
16214
+ var log42 = debug("werift:packages/webrtc/src/transport/dtls.ts");
14880
16215
 
14881
16216
  // src/transport/iceCandidateAttribute.ts
14882
16217
  var emptyCandidateFields = Object.freeze({
@@ -14897,10 +16232,10 @@ var fqdn = new RegExp(
14897
16232
  );
14898
16233
 
14899
16234
  // src/transport/ice.ts
14900
- var log36 = debug("werift:packages/webrtc/src/transport/ice.ts");
16235
+ var log43 = debug("werift:packages/webrtc/src/transport/ice.ts");
14901
16236
 
14902
16237
  // src/transport/sctp.ts
14903
- var log37 = debug("werift:packages/webrtc/src/transport/sctp.ts");
16238
+ var log44 = debug("werift:packages/webrtc/src/transport/sctp.ts");
14904
16239
  var DEFAULT_MAX_MESSAGE_SIZE = 65536;
14905
16240
 
14906
16241
  // src/api/compatibilityOptions.ts
@@ -14908,13 +16243,17 @@ var CompatibilityOptionValues = {
14908
16243
  certificateScope: ["standard", "process"],
14909
16244
  mLineReuse: ["standard", "aggressive"],
14910
16245
  transceiverPairing: ["standard", "byKind"],
14911
- keyFrameRequestRouting: ["standard", "fallback"]
16246
+ keyFrameRequestRouting: ["standard", "fallback"],
16247
+ dtlsHandshakeValidation: ["standard", "lenient"],
16248
+ dataChannelBinaryType: ["standard", "nodebuffer", "arraybuffer", "blob"]
14912
16249
  };
14913
16250
 
14914
16251
  // src/api/peerConfig.ts
14915
16252
  var CertificateScopeModes = CompatibilityOptionValues.certificateScope;
14916
16253
  var MLineReuseModes = CompatibilityOptionValues.mLineReuse;
14917
16254
  var TransceiverPairingModes = CompatibilityOptionValues.transceiverPairing;
16255
+ var DtlsHandshakeValidationModes = CompatibilityOptionValues.dtlsHandshakeValidation;
16256
+ var DataChannelBinaryTypeModes = CompatibilityOptionValues.dataChannelBinaryType;
14918
16257
  var COMPATIBILITY_OPTIONS = Object.keys(
14919
16258
  CompatibilityOptionValues
14920
16259
  );
@@ -14938,9 +16277,11 @@ function generateDefaultPeerConfig() {
14938
16277
  iceTcpPassive: true,
14939
16278
  iceStunGatherTimeout: void 0,
14940
16279
  iceTurnConnectTimeout: void 0,
16280
+ iceIncomingCheckTimeout: void 0,
14941
16281
  iceNominationDelayMs: void 0,
14942
16282
  iceNomination: void 0,
14943
16283
  iceRenomination: false,
16284
+ iceFailover: void 0,
14944
16285
  turnTransport: void 0,
14945
16286
  turnTlsOptions: void 0,
14946
16287
  turnUdpFamily: void 0,
@@ -14951,6 +16292,12 @@ function generateDefaultPeerConfig() {
14951
16292
  icePasswordPrefix: void 0,
14952
16293
  iceUseLinkLocalAddress: void 0,
14953
16294
  dtls: {},
16295
+ sped: false,
16296
+ warp: {
16297
+ allowEarlyServerData: false,
16298
+ earlyMediaPolicy: "drop",
16299
+ sendBeforeNomination: false
16300
+ },
14954
16301
  bundlePolicy: "max-compat",
14955
16302
  rtcpMuxPolicy: "require",
14956
16303
  iceCandidatePoolSize: 0,
@@ -14960,6 +16307,7 @@ function generateDefaultPeerConfig() {
14960
16307
  midSuffix: false,
14961
16308
  forceTurnTCP: false,
14962
16309
  maxMessageSize: DEFAULT_MAX_MESSAGE_SIZE,
16310
+ dataChannelBinaryType: "nodebuffer",
14963
16311
  filterProbePaddingOnReceiveRtp: false,
14964
16312
  bandwidthEstimator: "lightweight",
14965
16313
  sctp: { mtu: DEFAULT_SCTP_MTU },
@@ -14967,6 +16315,7 @@ function generateDefaultPeerConfig() {
14967
16315
  mLineReuse: "standard",
14968
16316
  transceiverPairing: "byKind",
14969
16317
  keyFrameRequestRouting: "fallback",
16318
+ dtlsHandshakeValidation: "lenient",
14970
16319
  bundleCandidates: "legacy",
14971
16320
  compatibility: void 0
14972
16321
  };
@@ -14977,44 +16326,44 @@ var defaultPeerConfig = generateDefaultPeerConfig();
14977
16326
  var kNetworkStateEstimateProbingIntervalMs = Number.POSITIVE_INFINITY;
14978
16327
 
14979
16328
  // src/transceiverManager.ts
14980
- var log38 = debug("werift:packages/webrtc/src/media/rtpTransceiverManager.ts");
16329
+ var log45 = debug("werift:packages/webrtc/src/media/rtpTransceiverManager.ts");
14981
16330
 
14982
16331
  // src/media/receiver/nack.ts
14983
- var log39 = debug("werift:packages/webrtc/src/media/receiver/nack.ts");
16332
+ var log46 = debug("werift:packages/webrtc/src/media/receiver/nack.ts");
14984
16333
  var LOST_SIZE2 = 30 * 5;
14985
16334
 
14986
16335
  // src/media/receiver/receiverTwcc.ts
14987
- var log40 = debug("werift:packages/webrtc/media/receiver/receiverTwcc");
16336
+ var log47 = debug("werift:packages/webrtc/media/receiver/receiverTwcc");
14988
16337
 
14989
16338
  // src/media/rtpReceiver.ts
14990
- var log41 = debug("werift:packages/webrtc/src/media/rtpReceiver.ts");
16339
+ var log48 = debug("werift:packages/webrtc/src/media/rtpReceiver.ts");
14991
16340
 
14992
16341
  // src/media/routing/ridRouting.ts
14993
- var log42 = debug("werift:packages/webrtc/src/media/routing/ridRouting.ts");
16342
+ var log49 = debug("werift:packages/webrtc/src/media/routing/ridRouting.ts");
14994
16343
 
14995
16344
  // src/media/routing/rtcpRouting.ts
14996
16345
  var KeyFrameRequestRoutingModes = CompatibilityOptionValues.keyFrameRequestRouting;
14997
16346
 
14998
16347
  // src/media/router.ts
14999
- var log43 = debug("werift:packages/webrtc/src/media/router.ts");
16348
+ var log50 = debug("werift:packages/webrtc/src/media/router.ts");
15000
16349
 
15001
16350
  // src/media/sender/outgoingQueue.ts
15002
16351
  var kOutgoingQueueMaxBytesVideo = 512 * 1024;
15003
16352
  var kOutgoingQueueMaxBytesAudio = 64 * 1024;
15004
16353
 
15005
16354
  // src/media/rtpSender.ts
15006
- var log44 = debug("werift:packages/webrtc/src/media/rtpSender.ts");
16355
+ var log51 = debug("werift:packages/webrtc/src/media/rtpSender.ts");
15007
16356
 
15008
16357
  // src/negotiation/transportActivation.ts
15009
- var log45 = debug(
16358
+ var log52 = debug(
15010
16359
  "werift:packages/webrtc/src/negotiation/transportActivation.ts"
15011
16360
  );
15012
16361
 
15013
16362
  // src/sctpManager.ts
15014
- var log46 = debug("werift:packages/webrtc/src/transport/sctpManager.ts");
16363
+ var log53 = debug("werift:packages/webrtc/src/transport/sctpManager.ts");
15015
16364
 
15016
16365
  // src/secureTransportManager.ts
15017
- var log47 = debug(
16366
+ var log54 = debug(
15018
16367
  "werift:packages/webrtc/src/transport/secureTransportManager.ts"
15019
16368
  );
15020
16369
  var srtpProfiles = [
@@ -15024,20 +16373,15 @@ var srtpProfiles = [
15024
16373
  ];
15025
16374
 
15026
16375
  // src/peerConnection.ts
15027
- var log48 = debug("werift:packages/webrtc/src/peerConnection.ts");
16376
+ var log55 = debug("werift:packages/webrtc/src/peerConnection.ts");
15028
16377
 
15029
16378
  // src/nonstandard/dummyMedia.ts
16379
+ import { randomInt } from "node:crypto";
15030
16380
  var AUDIO_PACKET_MS = 20;
15031
16381
  var AUDIO_TIMESTAMP_STEP = 960;
15032
16382
  var AUDIO_PAYLOAD = Buffer.from([248, 255, 254]);
15033
16383
  var DEFAULT_VIDEO_FPS = 30;
15034
16384
  var VIDEO_TIMESTAMP_STEP = 3e3;
15035
- var DUMMY_SSRC_BASE = 439041024;
15036
- var DUMMY_SEQUENCE_BASE = 16384;
15037
- var DUMMY_SEQUENCE_STEP = 256;
15038
- var DUMMY_PICTURE_ID_BASE = 256;
15039
- var DUMMY_PICTURE_ID_STEP = 256;
15040
- var nextDummySourceId = 0;
15041
16385
  var VP8_KEYFRAME = Buffer.from(
15042
16386
  "7002009d012a10001000390500011c240c2c2c442c2440100000606ac0feffab5080",
15043
16387
  "hex"
@@ -15072,12 +16416,13 @@ function createDummyVideoTrack(options = {}) {
15072
16416
  const keyframeIntervalFrames = options.keyframeIntervalFrames ?? fps;
15073
16417
  const intervalMs = 1e3 / fps;
15074
16418
  const track = new MediaStreamTrack({ kind: "video" });
16419
+ const pictureIdBase = randomInt(32768);
15075
16420
  const source = new ScheduledRtpSource({
15076
16421
  track,
15077
16422
  intervalMs,
15078
- buildPacket: ({ sequenceNumber, timestamp, ssrc, iteration, sourceId }) => {
16423
+ buildPacket: ({ sequenceNumber, timestamp, ssrc, iteration }) => {
15079
16424
  const isKeyframe = iteration % keyframeIntervalFrames === 0;
15080
- const pictureId = DUMMY_PICTURE_ID_BASE + sourceId * DUMMY_PICTURE_ID_STEP + iteration & 32767;
16425
+ const pictureId = pictureIdBase + iteration & 32767;
15081
16426
  return new RtpPacket(
15082
16427
  new RtpHeader({
15083
16428
  version: 2,
@@ -15101,9 +16446,8 @@ function createDummyVideoTrack(options = {}) {
15101
16446
  }
15102
16447
  var ScheduledRtpSource = class {
15103
16448
  props;
15104
- sourceId = nextDummySourceId++;
15105
- ssrc = DUMMY_SSRC_BASE + this.sourceId >>> 0;
15106
- sequenceNumber = DUMMY_SEQUENCE_BASE + this.sourceId * DUMMY_SEQUENCE_STEP & 65535;
16449
+ ssrc = random32();
16450
+ sequenceNumber = random16();
15107
16451
  timestamp = 0;
15108
16452
  iteration = 0;
15109
16453
  nextTickAt;
@@ -15139,8 +16483,7 @@ var ScheduledRtpSource = class {
15139
16483
  sequenceNumber: this.sequenceNumber,
15140
16484
  timestamp: this.timestamp,
15141
16485
  ssrc: this.ssrc,
15142
- iteration: this.iteration,
15143
- sourceId: this.sourceId
16486
+ iteration: this.iteration
15144
16487
  });
15145
16488
  this.props.track.writeRtp(packet);
15146
16489
  this.sequenceNumber = this.sequenceNumber + 1 & 65535;
@@ -15432,6 +16775,10 @@ var WebmFactory = class extends MediaWriter {
15432
16775
  rtpSources = [];
15433
16776
  onEol = new Event2();
15434
16777
  ended = false;
16778
+ /** RTP sources are stopped once: a second eol would break LipsyncCallback */
16779
+ sourcesStopped;
16780
+ /** a write failure stops the recording and is reported here */
16781
+ onError = new Event2();
15435
16782
  unSubscribers = new EventDisposer();
15436
16783
  async start(tracks) {
15437
16784
  if (this.props.path) {
@@ -15486,6 +16833,14 @@ var WebmFactory = class extends MediaWriter {
15486
16833
  const webm = new WebmCallback(inputTracks, {
15487
16834
  duration: this.props.defaultDuration ?? 1e3 * 60 * 60 * 24
15488
16835
  });
16836
+ webm.onError.once((error) => {
16837
+ this.ended = true;
16838
+ webm.destroy();
16839
+ this.unSubscribers.dispose();
16840
+ this.stopSources();
16841
+ this.onEol.execute();
16842
+ this.onError.execute(error);
16843
+ });
15489
16844
  const lipsync = new LipsyncCallback({
15490
16845
  ...this.props.lipsync,
15491
16846
  // wait only for the kinds being recorded, so a video-only recording
@@ -15535,8 +16890,9 @@ var WebmFactory = class extends MediaWriter {
15535
16890
  return rtpSource;
15536
16891
  });
15537
16892
  if (this.props.path) {
16893
+ const save = saveToFileSystem(this.props.path);
15538
16894
  webm.pipe(async (o) => {
15539
- const eol = await saveToFileSystem(this.props.path)(o);
16895
+ const eol = await save(o);
15540
16896
  if (this.props.stream) {
15541
16897
  this.props.stream.execute(o);
15542
16898
  }
@@ -15551,8 +16907,12 @@ var WebmFactory = class extends MediaWriter {
15551
16907
  });
15552
16908
  }
15553
16909
  }
16910
+ stopSources() {
16911
+ this.sourcesStopped ??= Promise.all(this.rtpSources.map((r) => r.stop()));
16912
+ return this.sourcesStopped;
16913
+ }
15554
16914
  async stop() {
15555
- await Promise.all(this.rtpSources.map((r) => r.stop()));
16915
+ await this.stopSources();
15556
16916
  if (!this.ended) {
15557
16917
  await this.onEol.asPromise(5e3).catch((e) => e);
15558
16918
  }
@@ -15587,7 +16947,11 @@ var MediaRecorder = class {
15587
16947
  const writerProps = { ...props, path: path2, stream };
15588
16948
  switch (this.format) {
15589
16949
  case "webm":
15590
- this.writer = new WebmFactory(writerProps);
16950
+ {
16951
+ const writer = new WebmFactory(writerProps);
16952
+ writer.onError.subscribe((error) => this.onError.execute(error));
16953
+ this.writer = writer;
16954
+ }
15591
16955
  break;
15592
16956
  case "ogg":
15593
16957
  if (props.numOfTracks !== void 0) {