werift 0.27.0 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -8
- package/lib/common/src/event.d.ts +26 -0
- package/lib/common/src/event.js +87 -2
- package/lib/common/src/event.js.map +1 -1
- package/lib/common/src/network.d.ts +6 -1
- package/lib/common/src/network.js +8 -2
- package/lib/common/src/network.js.map +1 -1
- package/lib/common/src/transport.d.ts +12 -5
- package/lib/common/src/transport.js +3 -2
- package/lib/common/src/transport.js.map +1 -1
- package/lib/dtls/src/alert.d.ts +49 -0
- package/lib/dtls/src/alert.js +103 -0
- package/lib/dtls/src/alert.js.map +1 -0
- package/lib/dtls/src/client.js +15 -1
- package/lib/dtls/src/client.js.map +1 -1
- package/lib/dtls/src/context/dtls.d.ts +2 -0
- package/lib/dtls/src/context/dtls.js +7 -0
- package/lib/dtls/src/context/dtls.js.map +1 -1
- package/lib/dtls/src/context/transport.d.ts +17 -1
- package/lib/dtls/src/context/transport.js +38 -2
- package/lib/dtls/src/context/transport.js.map +1 -1
- package/lib/dtls/src/flight/client/flight5.js +4 -1
- package/lib/dtls/src/flight/client/flight5.js.map +1 -1
- package/lib/dtls/src/flight/flight.d.ts +5 -0
- package/lib/dtls/src/flight/flight.js +10 -1
- package/lib/dtls/src/flight/flight.js.map +1 -1
- package/lib/dtls/src/flight/server/flight6.js +4 -1
- package/lib/dtls/src/flight/server/flight6.js.map +1 -1
- package/lib/dtls/src/index.d.ts +3 -1
- package/lib/dtls/src/index.js +10 -1
- package/lib/dtls/src/index.js.map +1 -1
- package/lib/dtls/src/record/const.d.ts +9 -0
- package/lib/dtls/src/record/const.js +9 -1
- package/lib/dtls/src/record/const.js.map +1 -1
- package/lib/dtls/src/record/receive.d.ts +6 -0
- package/lib/dtls/src/record/receive.js +50 -19
- package/lib/dtls/src/record/receive.js.map +1 -1
- package/lib/dtls/src/server.js +19 -1
- package/lib/dtls/src/server.js.map +1 -1
- package/lib/dtls/src/socket.d.ts +134 -2
- package/lib/dtls/src/socket.js +322 -6
- package/lib/dtls/src/socket.js.map +1 -1
- package/lib/ice/src/candidateError.d.ts +155 -0
- package/lib/ice/src/candidateError.js +246 -0
- package/lib/ice/src/candidateError.js.map +1 -0
- package/lib/ice/src/candidateGatherer.d.ts +127 -0
- package/lib/ice/src/candidateGatherer.js +745 -0
- package/lib/ice/src/candidateGatherer.js.map +1 -0
- package/lib/ice/src/consent.d.ts +49 -0
- package/lib/ice/src/consent.js +258 -0
- package/lib/ice/src/consent.js.map +1 -0
- package/lib/ice/src/ice.d.ts +223 -71
- package/lib/ice/src/ice.js +873 -975
- package/lib/ice/src/ice.js.map +1 -1
- package/lib/ice/src/iceBase.d.ts +207 -8
- package/lib/ice/src/iceBase.js +94 -31
- package/lib/ice/src/iceBase.js.map +1 -1
- package/lib/ice/src/index.d.ts +1 -0
- package/lib/ice/src/index.js +1 -0
- package/lib/ice/src/index.js.map +1 -1
- package/lib/ice/src/internal/checkMessages.d.ts +41 -0
- package/lib/ice/src/internal/checkMessages.js +63 -0
- package/lib/ice/src/internal/checkMessages.js.map +1 -0
- package/lib/ice/src/internal/defaultRoute.d.ts +20 -0
- package/lib/ice/src/internal/defaultRoute.js +134 -0
- package/lib/ice/src/internal/defaultRoute.js.map +1 -0
- package/lib/ice/src/internal/hostInterfaces.d.ts +17 -0
- package/lib/ice/src/internal/hostInterfaces.js +77 -0
- package/lib/ice/src/internal/hostInterfaces.js.map +1 -0
- package/lib/ice/src/internal/hostPreference.d.ts +24 -0
- package/lib/ice/src/internal/hostPreference.js +38 -0
- package/lib/ice/src/internal/hostPreference.js.map +1 -0
- package/lib/ice/src/internal/resolveHostAddresses.d.ts +56 -8
- package/lib/ice/src/internal/resolveHostAddresses.js +127 -24
- package/lib/ice/src/internal/resolveHostAddresses.js.map +1 -1
- package/lib/ice/src/internal/selectAddresses.d.ts +27 -0
- package/lib/ice/src/internal/selectAddresses.js +37 -18
- package/lib/ice/src/internal/selectAddresses.js.map +1 -1
- package/lib/ice/src/nomination/regularNomination.d.ts +200 -0
- package/lib/ice/src/nomination/regularNomination.js +311 -0
- package/lib/ice/src/nomination/regularNomination.js.map +1 -0
- package/lib/ice/src/nomination/selectionReplacement.d.ts +138 -0
- package/lib/ice/src/nomination/selectionReplacement.js +371 -0
- package/lib/ice/src/nomination/selectionReplacement.js.map +1 -0
- package/lib/ice/src/provisional.d.ts +139 -0
- package/lib/ice/src/provisional.js +468 -0
- package/lib/ice/src/provisional.js.map +1 -0
- package/lib/ice/src/stun/protocol.d.ts +9 -2
- package/lib/ice/src/stun/protocol.js +16 -17
- package/lib/ice/src/stun/protocol.js.map +1 -1
- package/lib/ice/src/stun/tcpProtocol.d.ts +1 -1
- package/lib/ice/src/stun/tcpProtocol.js +7 -7
- package/lib/ice/src/stun/tcpProtocol.js.map +1 -1
- package/lib/ice/src/stun/transaction.js +4 -2
- package/lib/ice/src/stun/transaction.js.map +1 -1
- package/lib/ice/src/turn/protocol.d.ts +2 -2
- package/lib/ice/src/turn/protocol.js +6 -3
- package/lib/ice/src/turn/protocol.js.map +1 -1
- package/lib/ice/src/types/model.d.ts +16 -5
- package/lib/ice/src/types/model.js.map +1 -1
- package/lib/ice-server/src/stun/attributes.js +4 -0
- package/lib/ice-server/src/stun/attributes.js.map +1 -1
- package/lib/ice-server/src/stun/const.d.ts +20 -1
- package/lib/ice-server/src/stun/const.js +9 -1
- package/lib/ice-server/src/stun/const.js.map +1 -1
- package/lib/ice-server/src/stun/message.d.ts +28 -1
- package/lib/ice-server/src/stun/message.js +102 -15
- package/lib/ice-server/src/stun/message.js.map +1 -1
- package/lib/index.mjs +13394 -7732
- package/lib/nonstandard/index.mjs +680 -286
- package/lib/polyfill/dom.mjs +19605 -14243
- package/lib/polyfill/index.mjs +19605 -14243
- package/lib/rtp/src/index.d.ts +1 -0
- package/lib/rtp/src/index.js +1 -0
- package/lib/rtp/src/index.js.map +1 -1
- package/lib/rtp/src/rtp/continuity.d.ts +14 -1
- package/lib/rtp/src/rtp/continuity.js +24 -4
- package/lib/rtp/src/rtp/continuity.js.map +1 -1
- package/lib/rtp/src/rtp/timelineRewriter.d.ts +178 -0
- package/lib/rtp/src/rtp/timelineRewriter.js +417 -0
- package/lib/rtp/src/rtp/timelineRewriter.js.map +1 -0
- package/lib/sctp/src/sctp.d.ts +5 -0
- package/lib/sctp/src/sctp.js +81 -47
- package/lib/sctp/src/sctp.js.map +1 -1
- package/lib/webrtc/src/api/compatibilityOptions.d.ts +33 -0
- package/lib/webrtc/src/api/compatibilityOptions.js +33 -0
- package/lib/webrtc/src/api/compatibilityOptions.js.map +1 -0
- package/lib/webrtc/src/api/peerConfig.d.ts +348 -34
- package/lib/webrtc/src/api/peerConfig.js +90 -24
- package/lib/webrtc/src/api/peerConfig.js.map +1 -1
- package/lib/webrtc/src/api/peerConnectionEvents.d.ts +77 -1
- package/lib/webrtc/src/api/peerConnectionEvents.js +105 -1
- package/lib/webrtc/src/api/peerConnectionEvents.js.map +1 -1
- package/lib/webrtc/src/helper.d.ts +8 -0
- package/lib/webrtc/src/helper.js +40 -4
- package/lib/webrtc/src/helper.js.map +1 -1
- package/lib/webrtc/src/media/codecCompatibility.d.ts +87 -1
- package/lib/webrtc/src/media/codecCompatibility.js +338 -12
- package/lib/webrtc/src/media/codecCompatibility.js.map +1 -1
- package/lib/webrtc/src/media/receiver/nack.d.ts +43 -10
- package/lib/webrtc/src/media/receiver/nack.js +245 -88
- package/lib/webrtc/src/media/receiver/nack.js.map +1 -1
- package/lib/webrtc/src/media/router.d.ts +239 -51
- package/lib/webrtc/src/media/router.js +664 -237
- package/lib/webrtc/src/media/router.js.map +1 -1
- package/lib/webrtc/src/media/routing/pendingRoutes.d.ts +26 -0
- package/lib/webrtc/src/media/routing/pendingRoutes.js +48 -0
- package/lib/webrtc/src/media/routing/pendingRoutes.js.map +1 -0
- package/lib/webrtc/src/media/routing/ridRouting.d.ts +37 -0
- package/lib/webrtc/src/media/routing/ridRouting.js +74 -0
- package/lib/webrtc/src/media/routing/ridRouting.js.map +1 -0
- package/lib/webrtc/src/media/routing/routeTable.d.ts +60 -0
- package/lib/webrtc/src/media/routing/routeTable.js +95 -0
- package/lib/webrtc/src/media/routing/routeTable.js.map +1 -0
- package/lib/webrtc/src/media/routing/rtcpRouting.d.ts +34 -0
- package/lib/webrtc/src/media/routing/rtcpRouting.js +165 -0
- package/lib/webrtc/src/media/routing/rtcpRouting.js.map +1 -0
- package/lib/webrtc/src/media/routing/unknownSsrc.d.ts +55 -0
- package/lib/webrtc/src/media/routing/unknownSsrc.js +117 -0
- package/lib/webrtc/src/media/routing/unknownSsrc.js.map +1 -0
- package/lib/webrtc/src/media/rtpReceiver.d.ts +222 -0
- package/lib/webrtc/src/media/rtpReceiver.js +668 -28
- package/lib/webrtc/src/media/rtpReceiver.js.map +1 -1
- package/lib/webrtc/src/media/rtpSender.d.ts +7 -0
- package/lib/webrtc/src/media/rtpSender.js +9 -3
- package/lib/webrtc/src/media/rtpSender.js.map +1 -1
- package/lib/webrtc/src/media/rtpTransceiver.d.ts +18 -0
- package/lib/webrtc/src/media/rtpTransceiver.js +64 -2
- package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
- package/lib/webrtc/src/media/sender/senderReportHistory.d.ts +51 -0
- package/lib/webrtc/src/media/sender/senderReportHistory.js +111 -0
- package/lib/webrtc/src/media/sender/senderReportHistory.js.map +1 -0
- package/lib/webrtc/src/media/sender/senderStats.d.ts +6 -5
- package/lib/webrtc/src/media/sender/senderStats.js +14 -19
- package/lib/webrtc/src/media/sender/senderStats.js.map +1 -1
- package/lib/webrtc/src/media/track.d.ts +9 -0
- package/lib/webrtc/src/media/track.js +9 -0
- package/lib/webrtc/src/media/track.js.map +1 -1
- package/lib/webrtc/src/negotiation/remoteMediaApplication.d.ts +23 -6
- package/lib/webrtc/src/negotiation/remoteMediaApplication.js +46 -22
- package/lib/webrtc/src/negotiation/remoteMediaApplication.js.map +1 -1
- package/lib/webrtc/src/negotiation/transceiverPairing.d.ts +1 -0
- package/lib/webrtc/src/negotiation/transceiverPairing.js +62 -0
- package/lib/webrtc/src/negotiation/transceiverPairing.js.map +1 -0
- package/lib/webrtc/src/negotiation/transportActivation.d.ts +8 -1
- package/lib/webrtc/src/negotiation/transportActivation.js +21 -0
- package/lib/webrtc/src/negotiation/transportActivation.js.map +1 -1
- package/lib/webrtc/src/negotiationTransaction.d.ts +35 -4
- package/lib/webrtc/src/negotiationTransaction.js +111 -8
- package/lib/webrtc/src/negotiationTransaction.js.map +1 -1
- package/lib/webrtc/src/peerConnection.d.ts +65 -6
- package/lib/webrtc/src/peerConnection.js +283 -28
- package/lib/webrtc/src/peerConnection.js.map +1 -1
- package/lib/webrtc/src/polyfill/globals.d.ts +2 -1
- package/lib/webrtc/src/polyfill/globals.js.map +1 -1
- package/lib/webrtc/src/polyfill/install.js +2 -0
- package/lib/webrtc/src/polyfill/install.js.map +1 -1
- package/lib/webrtc/src/sctpManager.js +4 -0
- package/lib/webrtc/src/sctpManager.js.map +1 -1
- package/lib/webrtc/src/sdp.d.ts +69 -0
- package/lib/webrtc/src/sdp.js +139 -14
- package/lib/webrtc/src/sdp.js.map +1 -1
- package/lib/webrtc/src/sdpManager.d.ts +85 -4
- package/lib/webrtc/src/sdpManager.js +214 -14
- package/lib/webrtc/src/sdpManager.js.map +1 -1
- package/lib/webrtc/src/secureTransportManager.d.ts +38 -1
- package/lib/webrtc/src/secureTransportManager.js +82 -7
- package/lib/webrtc/src/secureTransportManager.js.map +1 -1
- package/lib/webrtc/src/transceiverManager.d.ts +82 -4
- package/lib/webrtc/src/transceiverManager.js +231 -38
- package/lib/webrtc/src/transceiverManager.js.map +1 -1
- package/lib/webrtc/src/transport/dtls.d.ts +95 -1
- package/lib/webrtc/src/transport/dtls.js +324 -28
- package/lib/webrtc/src/transport/dtls.js.map +1 -1
- package/lib/webrtc/src/transport/ice.d.ts +61 -4
- package/lib/webrtc/src/transport/ice.js +180 -11
- package/lib/webrtc/src/transport/ice.js.map +1 -1
- package/lib/webrtc/src/transport/sctp.d.ts +23 -0
- package/lib/webrtc/src/transport/sctp.js +87 -2
- package/lib/webrtc/src/transport/sctp.js.map +1 -1
- package/lib/webrtc/src/utils.d.ts +33 -0
- package/lib/webrtc/src/utils.js +52 -3
- package/lib/webrtc/src/utils.js.map +1 -1
- package/package.json +2 -1
package/lib/dtls/src/socket.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.DtlsSocket = void 0;
|
|
4
4
|
const promises_1 = require("timers/promises");
|
|
5
|
+
const alert_1 = require("./alert");
|
|
5
6
|
const const_1 = require("./cipher/const");
|
|
6
7
|
const prf_1 = require("./cipher/prf");
|
|
7
8
|
const abstract_1 = require("./cipher/suites/abstract");
|
|
@@ -48,18 +49,31 @@ class DtlsSocket {
|
|
|
48
49
|
writable: true,
|
|
49
50
|
value: new common_1.Event()
|
|
50
51
|
});
|
|
52
|
+
/**
|
|
53
|
+
* Fires with a {@link DtlsAlertError} when the connection ends with a fatal
|
|
54
|
+
* alert (received from the peer, or sent by this side when it rejected the
|
|
55
|
+
* peer certificate), and with other errors raised by the handshake.
|
|
56
|
+
*/
|
|
51
57
|
Object.defineProperty(this, "onError", {
|
|
52
58
|
enumerable: true,
|
|
53
59
|
configurable: true,
|
|
54
60
|
writable: true,
|
|
55
61
|
value: new common_1.Event()
|
|
56
62
|
});
|
|
63
|
+
/** Fires once when the peer closed the connection with close_notify. */
|
|
57
64
|
Object.defineProperty(this, "onClose", {
|
|
58
65
|
enumerable: true,
|
|
59
66
|
configurable: true,
|
|
60
67
|
writable: true,
|
|
61
68
|
value: new common_1.Event()
|
|
62
69
|
});
|
|
70
|
+
/** Fires for every alert received from the peer (before onClose / onError). */
|
|
71
|
+
Object.defineProperty(this, "onAlert", {
|
|
72
|
+
enumerable: true,
|
|
73
|
+
configurable: true,
|
|
74
|
+
writable: true,
|
|
75
|
+
value: new common_1.Event()
|
|
76
|
+
});
|
|
63
77
|
Object.defineProperty(this, "transport", {
|
|
64
78
|
enumerable: true,
|
|
65
79
|
configurable: true,
|
|
@@ -108,19 +122,65 @@ class DtlsSocket {
|
|
|
108
122
|
writable: true,
|
|
109
123
|
value: []
|
|
110
124
|
});
|
|
125
|
+
/** close_notify or a fatal alert was sent: no record is sent any more. */
|
|
126
|
+
Object.defineProperty(this, "alertSent", {
|
|
127
|
+
enumerable: true,
|
|
128
|
+
configurable: true,
|
|
129
|
+
writable: true,
|
|
130
|
+
value: false
|
|
131
|
+
});
|
|
132
|
+
/** The alert that is being sent (shared with concurrent close calls). */
|
|
133
|
+
Object.defineProperty(this, "alertSending", {
|
|
134
|
+
enumerable: true,
|
|
135
|
+
configurable: true,
|
|
136
|
+
writable: true,
|
|
137
|
+
value: void 0
|
|
138
|
+
});
|
|
139
|
+
/**
|
|
140
|
+
* The connection ended (close_notify / fatal alert sent or received, or
|
|
141
|
+
* close()): received records are no longer processed.
|
|
142
|
+
*/
|
|
143
|
+
Object.defineProperty(this, "ended", {
|
|
144
|
+
enumerable: true,
|
|
145
|
+
configurable: true,
|
|
146
|
+
writable: true,
|
|
147
|
+
value: false
|
|
148
|
+
});
|
|
111
149
|
Object.defineProperty(this, "udpOnMessage", {
|
|
112
150
|
enumerable: true,
|
|
113
151
|
configurable: true,
|
|
114
152
|
writable: true,
|
|
115
153
|
value: (data) => {
|
|
154
|
+
if (this.ended)
|
|
155
|
+
return;
|
|
116
156
|
const packets = (0, receive_1.parsePacket)(data);
|
|
117
157
|
for (const packet of packets) {
|
|
158
|
+
// An alert earlier in this datagram may have ended the connection.
|
|
159
|
+
if (this.ended)
|
|
160
|
+
return;
|
|
118
161
|
try {
|
|
119
162
|
const messages = (0, receive_1.parsePlainText)(this.dtls, this.cipher)(packet);
|
|
120
163
|
for (const message of messages) {
|
|
164
|
+
// An alert earlier in this record (e.g. close_notify followed by a
|
|
165
|
+
// fatal alert) may have ended the connection: the rest is ignored.
|
|
166
|
+
if (this.ended)
|
|
167
|
+
return;
|
|
121
168
|
switch (message.type) {
|
|
122
169
|
case const_2.ContentType.handshake:
|
|
123
170
|
{
|
|
171
|
+
// Once the handshake completed, a handshake record of an
|
|
172
|
+
// epoch older than the peer's authenticated one (a plaintext
|
|
173
|
+
// epoch-0 Certificate, ClientHello, ...) is unauthenticated:
|
|
174
|
+
// anyone on the path can inject it, so it must not change
|
|
175
|
+
// the session (overwrite the peer certificate and fail its
|
|
176
|
+
// check, or reset the session through renegotiation()). It
|
|
177
|
+
// is dropped. A legitimate retransmission of the peer's last
|
|
178
|
+
// flight still carries its Finished at the current epoch.
|
|
179
|
+
if (this.connected &&
|
|
180
|
+
packet.recordLayerHeader.epoch < this.dtls.remoteEpoch) {
|
|
181
|
+
log(this.dtls.sessionId, "drop a stale-epoch handshake record after the handshake", packet.recordLayerHeader.epoch);
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
124
184
|
const handshake = message.data;
|
|
125
185
|
const handshakes = this.handleFragmentHandshake([handshake]);
|
|
126
186
|
const assembled = Object.values(handshakes.reduce((acc, cur) => {
|
|
@@ -133,22 +193,24 @@ class DtlsSocket {
|
|
|
133
193
|
.sort((a, b) => a.msg_type - b.msg_type);
|
|
134
194
|
this.onHandleHandshakes(assembled).catch((error) => {
|
|
135
195
|
err(this.dtls.sessionId, "onHandleHandshakes error", error);
|
|
136
|
-
this.onError
|
|
196
|
+
this.notify(this.onError, error);
|
|
137
197
|
});
|
|
138
198
|
}
|
|
139
199
|
break;
|
|
140
200
|
case const_2.ContentType.applicationData:
|
|
141
201
|
{
|
|
142
|
-
this.onData
|
|
202
|
+
this.notify(this.onData, message.data);
|
|
143
203
|
}
|
|
144
204
|
break;
|
|
145
205
|
case const_2.ContentType.alert:
|
|
146
|
-
this.
|
|
206
|
+
this.handleAlert(message.data);
|
|
147
207
|
break;
|
|
148
208
|
}
|
|
149
209
|
}
|
|
150
210
|
}
|
|
151
211
|
catch (error) {
|
|
212
|
+
// An invalid record (e.g. failed to decrypt) is discarded
|
|
213
|
+
// (RFC 6347 §4.1.2.1).
|
|
152
214
|
err(this.dtls.sessionId, "catch udpOnMessage error", error);
|
|
153
215
|
}
|
|
154
216
|
}
|
|
@@ -171,12 +233,19 @@ class DtlsSocket {
|
|
|
171
233
|
f("waitForReady timeout");
|
|
172
234
|
})
|
|
173
235
|
});
|
|
174
|
-
/**
|
|
236
|
+
/**
|
|
237
|
+
* send application data. Nothing is sent once close_notify or a fatal
|
|
238
|
+
* alert has been sent or received.
|
|
239
|
+
*/
|
|
175
240
|
Object.defineProperty(this, "send", {
|
|
176
241
|
enumerable: true,
|
|
177
242
|
configurable: true,
|
|
178
243
|
writable: true,
|
|
179
244
|
value: async (buf, addr) => {
|
|
245
|
+
if (this.alertSent || this.ended) {
|
|
246
|
+
log(this.dtls.sessionId, "drop application data after alert");
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
180
249
|
const pkt = (0, builder_1.createPlaintext)(this.dtls)([{ type: const_2.ContentType.applicationData, fragment: buf }], ++this.dtls.recordSequenceNumber)[0];
|
|
181
250
|
await this.transport.send(this.cipher.encryptPacket(pkt).serialize(), addr);
|
|
182
251
|
}
|
|
@@ -198,6 +267,213 @@ class DtlsSocket {
|
|
|
198
267
|
this.extensions = [];
|
|
199
268
|
this.bufferFragmentedHandshakes = [];
|
|
200
269
|
}
|
|
270
|
+
/**
|
|
271
|
+
* Resolves once the alert being sent (e.g. the close_notify answering the
|
|
272
|
+
* peer's) has been handed to the transport or timed out. Resolves
|
|
273
|
+
* immediately when none is in flight. Never rejects.
|
|
274
|
+
*/
|
|
275
|
+
alertFlushed() {
|
|
276
|
+
return this.alertSending ?? Promise.resolve();
|
|
277
|
+
}
|
|
278
|
+
/** Whether the connection ended (alert, or close()). */
|
|
279
|
+
get terminated() {
|
|
280
|
+
return this.ended;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Whether the handshake must not go on: the connection ended, or this side
|
|
284
|
+
* sent close_notify (RFC 5246 §7.2.1: nothing is sent after it, so a
|
|
285
|
+
* handshake that would answer or complete stops; records received after it
|
|
286
|
+
* are still processed, to receive the peer's close_notify).
|
|
287
|
+
*/
|
|
288
|
+
get handshakeStopped() {
|
|
289
|
+
return this.ended || this.alertSent;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Run the listeners of an event this socket reports, each isolated
|
|
293
|
+
* (`Event.executeIsolated`): a listener's exception is logged, so an
|
|
294
|
+
* application listener can never interrupt the socket's own processing
|
|
295
|
+
* (ending the connection, closing the transport, the receive loop) nor
|
|
296
|
+
* skip a listener registered after it.
|
|
297
|
+
*/
|
|
298
|
+
notify(event, ...args) {
|
|
299
|
+
// Per listener: one that throws neither skips the later listeners (e.g.
|
|
300
|
+
// werift's own, if the application subscribed first) nor this socket.
|
|
301
|
+
event.executeIsolated((error) => err(this.dtls.sessionId, "event listener failed", error), ...args);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* RFC 5246 §7.2: react to an alert received from the peer. The connection
|
|
305
|
+
* is ended (flights stopped, close_notify answered or the transport
|
|
306
|
+
* closed) before any listener runs, and each notification is isolated, so
|
|
307
|
+
* a throwing listener does not leave the socket ended but unreported.
|
|
308
|
+
*/
|
|
309
|
+
handleAlert(alert) {
|
|
310
|
+
const action = (0, alert_1.classifyAlert)(alert);
|
|
311
|
+
if (action === "ignore") {
|
|
312
|
+
log(this.dtls.sessionId, "ignore warning alert", alert);
|
|
313
|
+
this.notify(this.onAlert, alert);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
this.ended = true;
|
|
317
|
+
// Retransmitting a handshake flight makes no sense any more.
|
|
318
|
+
this.transport.stopFlights();
|
|
319
|
+
if (action === "close") {
|
|
320
|
+
log(this.dtls.sessionId, "received close_notify");
|
|
321
|
+
// RFC 5246 §7.2.1: respond with close_notify; nothing is sent after it.
|
|
322
|
+
void this.sendAlert(const_2.AlertLevel.warning, const_2.AlertDesc.CloseNotify);
|
|
323
|
+
// The connection is over: the socket closes its transport once the
|
|
324
|
+
// reply has been sent or timed out, like after a fatal alert (the
|
|
325
|
+
// application does not need to call close()).
|
|
326
|
+
void this.alertFlushed().then(() => this.closeTransport());
|
|
327
|
+
this.notify(this.onAlert, alert);
|
|
328
|
+
this.notify(this.onClose);
|
|
329
|
+
}
|
|
330
|
+
else {
|
|
331
|
+
err(this.dtls.sessionId, "received fatal alert", alert);
|
|
332
|
+
// A fatal alert is not answered (RFC 5246 §7.2.2).
|
|
333
|
+
this.alertSent = true;
|
|
334
|
+
this.closeTransport();
|
|
335
|
+
this.notify(this.onAlert, alert);
|
|
336
|
+
this.notify(this.onError, new alert_1.DtlsAlertError(alert, "remote"));
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Send an alert to the peer, protected with the current epoch (plaintext
|
|
341
|
+
* before ChangeCipherSpec, encrypted after it).
|
|
342
|
+
*
|
|
343
|
+
* Resolves once the transport has sent the record, or after `timeoutMs`
|
|
344
|
+
* (default {@link DtlsSocket.AlertSendTimeoutMs}). It never rejects: a
|
|
345
|
+
* failed send is only logged. Nothing is sent once close_notify or a fatal
|
|
346
|
+
* alert has been sent or the transport is closed. Sending close_notify or a
|
|
347
|
+
* fatal alert also stops the handshake flights (no retransmission). The
|
|
348
|
+
* record is handed to the transport synchronously, so closing the socket
|
|
349
|
+
* right after calling this does not drop it.
|
|
350
|
+
*
|
|
351
|
+
* A fatal alert ends the connection like a fatal error this side detected
|
|
352
|
+
* itself: `onError` fires synchronously with a local {@link DtlsAlertError},
|
|
353
|
+
* and the transport is closed once the alert has been sent (the returned
|
|
354
|
+
* promise resolves after that).
|
|
355
|
+
*/
|
|
356
|
+
sendAlert(level, description, options = {}) {
|
|
357
|
+
if (level === const_2.AlertLevel.fatal) {
|
|
358
|
+
return this.endWithFatalAlert(description, undefined, options);
|
|
359
|
+
}
|
|
360
|
+
return this.transmitAlert(level, description, options);
|
|
361
|
+
}
|
|
362
|
+
/** Encode, protect and send one alert record (see {@link sendAlert}). */
|
|
363
|
+
transmitAlert(level, description, options) {
|
|
364
|
+
if (this.alertSent || this.transport.closed) {
|
|
365
|
+
// A concurrent caller waits for the alert that is still being sent.
|
|
366
|
+
return this.alertSending ?? Promise.resolve();
|
|
367
|
+
}
|
|
368
|
+
if (level === const_2.AlertLevel.fatal || description === const_2.AlertDesc.CloseNotify) {
|
|
369
|
+
this.alertSent = true;
|
|
370
|
+
// A terminating alert ends the handshake too: no handshake flight is
|
|
371
|
+
// sent or retransmitted after it.
|
|
372
|
+
this.transport.stopFlights();
|
|
373
|
+
}
|
|
374
|
+
if (level === const_2.AlertLevel.fatal) {
|
|
375
|
+
this.ended = true;
|
|
376
|
+
}
|
|
377
|
+
let sending;
|
|
378
|
+
try {
|
|
379
|
+
const record = (0, alert_1.createAlertRecord)(this.dtls, this.cipher, {
|
|
380
|
+
level,
|
|
381
|
+
description,
|
|
382
|
+
});
|
|
383
|
+
log(this.dtls.sessionId, "send alert", {
|
|
384
|
+
level,
|
|
385
|
+
description,
|
|
386
|
+
epoch: this.dtls.epoch,
|
|
387
|
+
sequenceNumber: this.dtls.recordSequenceNumber,
|
|
388
|
+
});
|
|
389
|
+
sending = this.transport.send(record);
|
|
390
|
+
}
|
|
391
|
+
catch (error) {
|
|
392
|
+
err(this.dtls.sessionId, "failed to send alert", error);
|
|
393
|
+
return Promise.resolve();
|
|
394
|
+
}
|
|
395
|
+
const timeoutMs = options.timeoutMs ?? DtlsSocket.AlertSendTimeoutMs;
|
|
396
|
+
const timer = new AbortController();
|
|
397
|
+
const done = Promise.race([
|
|
398
|
+
sending,
|
|
399
|
+
(0, promises_1.setTimeout)(timeoutMs, undefined, { signal: timer.signal }).then(() => {
|
|
400
|
+
log(this.dtls.sessionId, "alert send timeout", timeoutMs);
|
|
401
|
+
}),
|
|
402
|
+
])
|
|
403
|
+
.catch((error) => {
|
|
404
|
+
if (timer.signal.aborted)
|
|
405
|
+
return;
|
|
406
|
+
err(this.dtls.sessionId, "failed to send alert", error);
|
|
407
|
+
})
|
|
408
|
+
.finally(() => timer.abort())
|
|
409
|
+
// A UDP transport hands the datagram to the socket on a later tick
|
|
410
|
+
// (dgram resolves the address asynchronously): closing the socket
|
|
411
|
+
// right after send() resolved would drop the alert.
|
|
412
|
+
.then(() => (0, promises_1.setImmediate)());
|
|
413
|
+
this.alertSending = done;
|
|
414
|
+
return done;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Abort the handshake (or the connection) because this side detected a
|
|
418
|
+
* fatal error: see {@link endWithFatalAlert}.
|
|
419
|
+
*/
|
|
420
|
+
abortWithFatalAlert(description, reason) {
|
|
421
|
+
void this.endWithFatalAlert(description, reason);
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* The single ending path for a fatal alert sent by this side (the public
|
|
425
|
+
* {@link sendAlert} and an internal abort): send the alert, stop the
|
|
426
|
+
* flights, report a local {@link DtlsAlertError} on onError (once), and
|
|
427
|
+
* close the transport once the alert has been sent or timed out. Does
|
|
428
|
+
* nothing more once the connection already ended.
|
|
429
|
+
*/
|
|
430
|
+
endWithFatalAlert(description, reason, options = {}) {
|
|
431
|
+
if (this.ended || this.alertSent || this.transport.closed) {
|
|
432
|
+
return this.alertSending ?? Promise.resolve();
|
|
433
|
+
}
|
|
434
|
+
const sending = this.transmitAlert(const_2.AlertLevel.fatal, description, options);
|
|
435
|
+
this.ended = true;
|
|
436
|
+
this.transport.stopFlights();
|
|
437
|
+
// The transport closes once the alert was sent, whatever a listener does.
|
|
438
|
+
const done = sending.then(() => this.closeTransport());
|
|
439
|
+
this.alertSending = done;
|
|
440
|
+
this.notify(this.onError, new alert_1.DtlsAlertError({ level: const_2.AlertLevel.fatal, description }, "local", reason));
|
|
441
|
+
return done;
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Call `options.verifyRemoteCertificate` with the received peer
|
|
445
|
+
* certificate. When it returns false or throws, the handshake is aborted
|
|
446
|
+
* with a fatal bad_certificate alert and false is returned.
|
|
447
|
+
*/
|
|
448
|
+
verifyRemoteCertificate() {
|
|
449
|
+
const verify = this.options.verifyRemoteCertificate;
|
|
450
|
+
if (!verify)
|
|
451
|
+
return true;
|
|
452
|
+
const certificate = this.cipher.remoteCertificate;
|
|
453
|
+
let reason;
|
|
454
|
+
try {
|
|
455
|
+
if (certificate && verify(Buffer.from(certificate))) {
|
|
456
|
+
return true;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
catch (error) {
|
|
460
|
+
reason = error;
|
|
461
|
+
}
|
|
462
|
+
err(this.dtls.sessionId, "remote certificate rejected", reason);
|
|
463
|
+
this.abortWithFatalAlert(const_2.AlertDesc.BadCertificate, reason);
|
|
464
|
+
return false;
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Close the transport (once; concurrent callers share the same close) and
|
|
468
|
+
* resolve when it has closed. A failure (a rejection or a synchronous
|
|
469
|
+
* throw of the transport's close()) is only logged: it never interrupts
|
|
470
|
+
* the caller, e.g. the onError notification of a received fatal alert.
|
|
471
|
+
*/
|
|
472
|
+
closeTransport() {
|
|
473
|
+
return this.transport.close().catch((error) => {
|
|
474
|
+
err(this.dtls.sessionId, "failed to close transport", error);
|
|
475
|
+
});
|
|
476
|
+
}
|
|
201
477
|
setupExtensions() {
|
|
202
478
|
log(this.dtls.sessionId, "support srtpProfiles", this.options.srtpProfiles);
|
|
203
479
|
if (this.options.srtpProfiles && this.options.srtpProfiles.length > 0) {
|
|
@@ -244,8 +520,41 @@ class DtlsSocket {
|
|
|
244
520
|
}
|
|
245
521
|
return handshakes; // return un fragmented handshakes
|
|
246
522
|
}
|
|
247
|
-
|
|
248
|
-
|
|
523
|
+
/**
|
|
524
|
+
* Close the socket: received records are no longer processed and a
|
|
525
|
+
* handshake flight stops retransmitting.
|
|
526
|
+
*
|
|
527
|
+
* - `close()`: sends no alert of its own and closes the transport right
|
|
528
|
+
* away, except that an alert already being sent (`sendAlert()`, the
|
|
529
|
+
* close_notify answering the peer's) is let through first: the transport
|
|
530
|
+
* closes once it has been sent or timed out.
|
|
531
|
+
* - `close({ notify: true })`: sends close_notify first and closes the
|
|
532
|
+
* transport once it has been sent, or after `timeoutMs`
|
|
533
|
+
* (default {@link DtlsSocket.AlertSendTimeoutMs}).
|
|
534
|
+
*
|
|
535
|
+
* The returned promise resolves once the transport is closed (also when
|
|
536
|
+
* the close was already started, e.g. after a fatal alert: it waits for
|
|
537
|
+
* that close) and never rejects; a failing transport close() (a rejection
|
|
538
|
+
* or a synchronous throw) is only logged.
|
|
539
|
+
*/
|
|
540
|
+
async close(options = {}) {
|
|
541
|
+
if (options.notify) {
|
|
542
|
+
const sending = this.sendAlert(const_2.AlertLevel.warning, const_2.AlertDesc.CloseNotify, {
|
|
543
|
+
...(options.timeoutMs !== undefined && {
|
|
544
|
+
timeoutMs: options.timeoutMs,
|
|
545
|
+
}),
|
|
546
|
+
});
|
|
547
|
+
this.ended = true;
|
|
548
|
+
this.transport.stopFlights();
|
|
549
|
+
await sending;
|
|
550
|
+
}
|
|
551
|
+
this.ended = true;
|
|
552
|
+
this.transport.stopFlights();
|
|
553
|
+
// Closing the transport now would drop an alert handed to it but not
|
|
554
|
+
// yet written (a UDP datagram goes out on a later tick).
|
|
555
|
+
await this.alertFlushed();
|
|
556
|
+
// Waits for a close already in progress (e.g. after a fatal alert).
|
|
557
|
+
await this.closeTransport();
|
|
249
558
|
}
|
|
250
559
|
extractSessionKeys(keyLength, saltLength) {
|
|
251
560
|
const keyingMaterial = this.exportKeyingMaterial("EXTRACTOR-dtls_srtp", keyLength * 2 + saltLength * 2);
|
|
@@ -280,4 +589,11 @@ class DtlsSocket {
|
|
|
280
589
|
}
|
|
281
590
|
}
|
|
282
591
|
exports.DtlsSocket = DtlsSocket;
|
|
592
|
+
/** Default upper bound (ms) for waiting until an alert has been sent. */
|
|
593
|
+
Object.defineProperty(DtlsSocket, "AlertSendTimeoutMs", {
|
|
594
|
+
enumerable: true,
|
|
595
|
+
configurable: true,
|
|
596
|
+
writable: true,
|
|
597
|
+
value: 200
|
|
598
|
+
});
|
|
283
599
|
//# sourceMappingURL=socket.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"socket.js","sourceRoot":"","sources":["../../../../dtls/src/socket.ts"],"names":[],"mappings":";;;AAAA,8CAA6C;AAC7C,0CAIwB;AACxB,sCAAoD;AACpD,uDAA0E;AAC1E,6CAAiD;AACjD,yCAA6C;AAC7C,yCAA6C;AAC7C,mDAAuD;AACvD,0EAAuE;AACvE,sFAAmF;AACnF,4FAAyF;AACzF,gEAA6D;AAC7D,4DAAyD;AAEzD,6CAA4D;AAE5D,8CAAmD;AACnD,0CAA6C;AAC7C,wDAAgE;AAChE,8CAA+D;AAG/D,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,mBAAU,CAAC;AAErC,MAAM,GAAG,GAAG,IAAA,cAAK,EAAC,iDAAiD,CAAC,CAAC;AACrE,MAAM,GAAG,GAAG,IAAA,cAAK,EAAC,iDAAiD,CAAC,CAAC;AAErE,MAAa,UAAU;IAmBrB,YAAY,OAAgB,EAAE,WAAyB;QAlBhD;;;;;WAAiB;QACjB;;;;;WAA0B;QAExB;;;;mBAAY,IAAI,cAAK,EAAE;WAAC;QACxB;;;;mBAAS,IAAI,cAAK,EAAY;WAAC;QAC/B;;;;mBAAU,IAAI,cAAK,EAAW;WAAC;QAC/B;;;;mBAAU,IAAI,cAAK,EAAE;WAAC;QACtB;;;;;WAA4B;QACrC;;;;;WAAsB;QACtB;;;;;WAAkB;QAClB;;;;mBAAoB,IAAI,kBAAW,EAAE;WAAC;QAEtC;;;;mBAAY,KAAK;WAAC;QAClB;;;;mBAA0B,EAAE;WAAC;QAC7B;;;;;WAAyE;QAEjE;;;;mBAAoD,EAAE;WAAC;QAgCvD;;;;mBAAe,CAAC,IAAY,EAAE,EAAE;gBACtC,MAAM,OAAO,GAAG,IAAA,qBAAW,EAAC,IAAI,CAAC,CAAC;gBAElC,KAAK,M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AE,UAAU,EAAE,UAAU,EAAE,GAAG,MAAM,CAC7D,cAAc,EACd;YACE,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC;YAClC,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAAS,CAAC;YAClC,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC;YACpC,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC;SACrC,CACF,CAAC;QAEF,IAAI,IAAI,CAAC,WAAW,KAAK,sBAAW,CAAC,MAAM,EAAE,CAAC;YAC5C,OAAO;gBACL,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,UAAU;gBACrB,SAAS,EAAE,SAAS;gBACpB,UAAU,EAAE,UAAU;aACvB,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,OAAO;gBACL,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,UAAU;gBACrB,SAAS,EAAE,SAAS;gBACpB,UAAU,EAAE,UAAU;aACvB,CAAC;QACJ,CAAC;IACH,CAAC;IAED,oBAAoB,CAAC,KAAa,EAAE,MAAc;QAChD,OAAO,IAAA,0BAAoB,EACzB,KAAK,EACL,MAAM,EACN,IAAI,CAAC,MAAM,CAAC,YAAY,EACxB,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,SAAS,EAAE,EACnC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,SAAS,EAAE,EACpC,IAAI,CAAC,WAAW,KAAK,sBAAW,CAAC,MAAM,CACxC,CAAC;IACJ,CAAC;IAED,IAAI,iBAAiB;QACnB,OAAO,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAAC;IACvC,CAAC;CACF;AAhOD,gCAgOC","sourcesContent":["import { setTimeout } from \"timers/promises\";\nimport {\n NamedCurveAlgorithmList,\n type SignatureHash,\n signatures,\n} from \"./cipher/const\";\nimport { exportKeyingMaterial } from \"./cipher/prf\";\nimport { SessionType, type SessionTypes } from \"./cipher/suites/abstract\";\nimport { CipherContext } from \"./context/cipher\";\nimport { DtlsContext } from \"./context/dtls\";\nimport { SrtpContext } from \"./context/srtp\";\nimport { TransportContext } from \"./context/transport\";\nimport { EllipticCurves } from \"./handshake/extensions/ellipticCurves\";\nimport { ExtendedMasterSecret } from \"./handshake/extensions/extendedMasterSecret\";\nimport { RenegotiationIndication } from \"./handshake/extensions/renegotiationIndication\";\nimport { Signature } from \"./handshake/extensions/signature\";\nimport { UseSRTP } from \"./handshake/extensions/useSrtp\";\nimport type { Address, Transport } from \"./imports/common\";\nimport { binaryData, debug, Event } from \"./imports/common\";\nimport type { SrtpProfile } from \"./imports/rtp\";\nimport { createPlaintext } from \"./record/builder\";\nimport { ContentType } from \"./record/const\";\nimport { FragmentedHandshake } from \"./record/message/fragment\";\nimport { parsePacket, parsePlainText } from \"./record/receive\";\nimport type { Extension } from \"./typings/domain\";\n\nconst { decode, types } = binaryData;\n\nconst log = debug(\"werift-dtls : packages/dtls/src/socket.ts : log\");\nconst err = debug(\"werift-dtls : packages/dtls/src/socket.ts : err\");\n\nexport class DtlsSocket {\n public options: Options;\n public sessionType: SessionTypes;\n\n readonly onConnect = new Event();\n readonly onData = new Event<[Buffer]>();\n readonly onError = new Event<[Error]>();\n readonly onClose = new Event();\n readonly transport: TransportContext;\n cipher: CipherContext;\n dtls: DtlsContext;\n srtp: SrtpContext = new SrtpContext();\n\n connected = false;\n extensions: Extension[] = [];\n onHandleHandshakes!: (assembled: FragmentedHandshake[]) => Promise<void>;\n\n private bufferFragmentedHandshakes: FragmentedHandshake[] = [];\n\n constructor(options: Options, sessionType: SessionTypes) {\n this.options = options;\n this.sessionType = sessionType;\n this.dtls = new DtlsContext(this.options, this.sessionType);\n this.cipher = new CipherContext(\n this.sessionType,\n this.options.cert,\n this.options.key,\n this.options.signatureHash,\n );\n this.transport = new TransportContext(this.options.transport);\n this.setupExtensions();\n this.transport.socket.onData = this.udpOnMessage;\n }\n\n renegotiation() {\n log(\"renegotiation\", this.sessionType);\n this.connected = false;\n this.cipher = new CipherContext(\n this.sessionType,\n this.options.cert,\n this.options.key,\n this.options.signatureHash,\n );\n this.dtls = new DtlsContext(this.options, this.sessionType);\n this.srtp = new SrtpContext();\n this.extensions = [];\n this.bufferFragmentedHandshakes = [];\n }\n\n private udpOnMessage = (data: Buffer) => {\n const packets = parsePacket(data);\n\n for (const packet of packets) {\n try {\n const messages = parsePlainText(this.dtls, this.cipher)(packet);\n for (const message of messages) {\n switch (message.type) {\n case ContentType.handshake:\n {\n const handshake = message.data as FragmentedHandshake;\n const handshakes = this.handleFragmentHandshake([handshake]);\n const assembled = Object.values(\n handshakes.reduce(\n (acc: { [type: string]: FragmentedHandshake[] }, cur) => {\n if (!acc[cur.msg_type]) acc[cur.msg_type] = [];\n acc[cur.msg_type].push(cur);\n return acc;\n },\n {},\n ),\n )\n .map((v) => FragmentedHandshake.assemble(v))\n .sort((a, b) => a.msg_type - b.msg_type);\n\n this.onHandleHandshakes(assembled).catch((error) => {\n err(this.dtls.sessionId, \"onHandleHandshakes error\", error);\n this.onError.execute(error);\n });\n }\n break;\n case ContentType.applicationData:\n {\n this.onData.execute(message.data as Buffer);\n }\n break;\n case ContentType.alert:\n this.onClose.execute();\n break;\n }\n }\n } catch (error) {\n err(this.dtls.sessionId, \"catch udpOnMessage error\", error);\n }\n }\n };\n\n private setupExtensions() {\n log(this.dtls.sessionId, \"support srtpProfiles\", this.options.srtpProfiles);\n if (this.options.srtpProfiles && this.options.srtpProfiles.length > 0) {\n const useSrtp = UseSRTP.create(\n this.options.srtpProfiles,\n Buffer.from([0x00]),\n );\n this.extensions.push(useSrtp.extension);\n }\n\n {\n const curve = EllipticCurves.createEmpty();\n curve.data = NamedCurveAlgorithmList;\n this.extensions.push(curve.extension);\n }\n\n {\n const signature = Signature.createEmpty();\n // libwebrtc/OpenSSL require 4=1 , 4=3 signatureHash\n signature.data = signatures;\n this.extensions.push(signature.extension);\n }\n if (this.options.extendedMasterSecret) {\n this.extensions.push({\n type: ExtendedMasterSecret.type,\n data: Buffer.alloc(0),\n });\n }\n\n {\n const renegotiationIndication = RenegotiationIndication.createEmpty();\n this.extensions.push(renegotiationIndication.extension);\n }\n }\n\n protected waitForReady = (condition: () => boolean) =>\n new Promise<void>(async (r, f) => {\n for (let i = 0; i < 10; i++) {\n if (condition()) {\n r();\n break;\n } else {\n await setTimeout(100 * i);\n }\n }\n f(\"waitForReady timeout\");\n });\n\n handleFragmentHandshake(messages: FragmentedHandshake[]) {\n let handshakes = messages.filter((v) => {\n // find fragmented\n if (v.fragment_length !== v.length) {\n this.bufferFragmentedHandshakes.push(v);\n return false;\n }\n return true;\n });\n\n if (this.bufferFragmentedHandshakes.length > 1) {\n const [last] = this.bufferFragmentedHandshakes.slice(-1);\n if (last.fragment_offset + last.fragment_length === last.length) {\n handshakes = [...this.bufferFragmentedHandshakes, ...handshakes];\n this.bufferFragmentedHandshakes = [];\n }\n }\n return handshakes; // return un fragmented handshakes\n }\n\n /**send application data */\n send = async (buf: Buffer, addr?: Address) => {\n const pkt = createPlaintext(this.dtls)(\n [{ type: ContentType.applicationData, fragment: buf }],\n ++this.dtls.recordSequenceNumber,\n )[0];\n await this.transport.send(this.cipher.encryptPacket(pkt).serialize(), addr);\n };\n\n close() {\n this.transport.close();\n }\n\n extractSessionKeys(keyLength: number, saltLength: number) {\n const keyingMaterial = this.exportKeyingMaterial(\n \"EXTRACTOR-dtls_srtp\",\n keyLength * 2 + saltLength * 2,\n );\n\n const { clientKey, serverKey, clientSalt, serverSalt } = decode(\n keyingMaterial,\n {\n clientKey: types.buffer(keyLength),\n serverKey: types.buffer(keyLength),\n clientSalt: types.buffer(saltLength),\n serverSalt: types.buffer(saltLength),\n },\n );\n\n if (this.sessionType === SessionType.CLIENT) {\n return {\n localKey: clientKey,\n localSalt: clientSalt,\n remoteKey: serverKey,\n remoteSalt: serverSalt,\n };\n } else {\n return {\n localKey: serverKey,\n localSalt: serverSalt,\n remoteKey: clientKey,\n remoteSalt: clientSalt,\n };\n }\n }\n\n exportKeyingMaterial(label: string, length: number) {\n return exportKeyingMaterial(\n label,\n length,\n this.cipher.masterSecret,\n this.cipher.localRandom.serialize(),\n this.cipher.remoteRandom.serialize(),\n this.sessionType === SessionType.CLIENT,\n );\n }\n\n get remoteCertificate() {\n return this.cipher.remoteCertificate;\n }\n}\n\nexport interface Options {\n transport: Transport;\n srtpProfiles?: SrtpProfile[];\n cert?: string;\n key?: string;\n signatureHash?: SignatureHash;\n certificateRequest?: boolean;\n extendedMasterSecret?: boolean;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"socket.js","sourceRoot":"","sources":["../../../../dtls/src/socket.ts"],"names":[],"mappings":";;;AAAA,8CAA2D;AAC3D,mCAKiB;AACjB,0CAIwB;AACxB,sCAAoD;AACpD,uDAA0E;AAC1E,6CAAiD;AACjD,yCAA6C;AAC7C,yCAA6C;AAC7C,mDAAuD;AACvD,0EAAuE;AACvE,sFAAmF;AACnF,4FAAyF;AACzF,gEAA6D;AAC7D,4DAAyD;AAEzD,6CAA4D;AAE5D,8CAAmD;AACnD,0CAAoE;AACpE,wDAAgE;AAChE,8CAA+D;AAG/D,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,mBAAU,CAAC;AAErC,MAAM,GAAG,GAAG,IAAA,cAAK,EAAC,iDAAiD,CAAC,CAAC;AACrE,MAAM,GAAG,GAAG,IAAA,cAAK,EAAC,iDAAiD,CAAC,CAAC;AAErE,MAAa,UAAU;IAuCrB,YAAY,OAAgB,EAAE,WAAyB;QAnChD;;;;;WAAiB;QACjB;;;;;WAA0B;QAExB;;;;mBAAY,IAAI,cAAK,EAAE;WAAC;QACxB;;;;mBAAS,IAAI,cAAK,EAAY;WAAC;QACxC;;;;WAIG;QACM;;;;mBAAU,IAAI,cAAK,EAAW;WAAC;QACxC,wEAAwE;QAC/D;;;;mBAAU,IAAI,cAAK,EAAE;WAAC;QAC/B,+EAA+E;QACtE;;;;mBAAU,IAAI,cAAK,EAAe;WAAC;QACnC;;;;;WAA4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UAAU,EAAE,UAAU;aACvB,CAAC;QACJ,CAAC;IACH,CAAC;IAED,oBAAoB,CAAC,KAAa,EAAE,MAAc;QAChD,OAAO,IAAA,0BAAoB,EACzB,KAAK,EACL,MAAM,EACN,IAAI,CAAC,MAAM,CAAC,YAAY,EACxB,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,SAAS,EAAE,EACnC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,SAAS,EAAE,EACpC,IAAI,CAAC,WAAW,KAAK,sBAAW,CAAC,MAAM,CACxC,CAAC;IACJ,CAAC;IAED,IAAI,iBAAiB;QACnB,OAAO,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAAC;IACvC,CAAC;;AAziBH,gCA0iBC;AAziBC,yEAAyE;AAClE;;;;WAAqB,GAAG;EAAN,CAAO","sourcesContent":["import { setImmediate, setTimeout } from \"timers/promises\";\nimport {\n classifyAlert,\n createAlertRecord,\n type DtlsAlert,\n DtlsAlertError,\n} from \"./alert\";\nimport {\n NamedCurveAlgorithmList,\n type SignatureHash,\n signatures,\n} from \"./cipher/const\";\nimport { exportKeyingMaterial } from \"./cipher/prf\";\nimport { SessionType, type SessionTypes } from \"./cipher/suites/abstract\";\nimport { CipherContext } from \"./context/cipher\";\nimport { DtlsContext } from \"./context/dtls\";\nimport { SrtpContext } from \"./context/srtp\";\nimport { TransportContext } from \"./context/transport\";\nimport { EllipticCurves } from \"./handshake/extensions/ellipticCurves\";\nimport { ExtendedMasterSecret } from \"./handshake/extensions/extendedMasterSecret\";\nimport { RenegotiationIndication } from \"./handshake/extensions/renegotiationIndication\";\nimport { Signature } from \"./handshake/extensions/signature\";\nimport { UseSRTP } from \"./handshake/extensions/useSrtp\";\nimport type { Address, Transport } from \"./imports/common\";\nimport { binaryData, debug, Event } from \"./imports/common\";\nimport type { SrtpProfile } from \"./imports/rtp\";\nimport { createPlaintext } from \"./record/builder\";\nimport { AlertDesc, AlertLevel, ContentType } from \"./record/const\";\nimport { FragmentedHandshake } from \"./record/message/fragment\";\nimport { parsePacket, parsePlainText } from \"./record/receive\";\nimport type { Extension } from \"./typings/domain\";\n\nconst { decode, types } = binaryData;\n\nconst log = debug(\"werift-dtls : packages/dtls/src/socket.ts : log\");\nconst err = debug(\"werift-dtls : packages/dtls/src/socket.ts : err\");\n\nexport class DtlsSocket {\n /** Default upper bound (ms) for waiting until an alert has been sent. */\n static AlertSendTimeoutMs = 200;\n\n public options: Options;\n public sessionType: SessionTypes;\n\n readonly onConnect = new Event();\n readonly onData = new Event<[Buffer]>();\n /**\n * Fires with a {@link DtlsAlertError} when the connection ends with a fatal\n * alert (received from the peer, or sent by this side when it rejected the\n * peer certificate), and with other errors raised by the handshake.\n */\n readonly onError = new Event<[Error]>();\n /** Fires once when the peer closed the connection with close_notify. */\n readonly onClose = new Event();\n /** Fires for every alert received from the peer (before onClose / onError). */\n readonly onAlert = new Event<[DtlsAlert]>();\n readonly transport: TransportContext;\n cipher: CipherContext;\n dtls: DtlsContext;\n srtp: SrtpContext = new SrtpContext();\n\n connected = false;\n extensions: Extension[] = [];\n onHandleHandshakes!: (assembled: FragmentedHandshake[]) => Promise<void>;\n\n private bufferFragmentedHandshakes: FragmentedHandshake[] = [];\n /** close_notify or a fatal alert was sent: no record is sent any more. */\n private alertSent = false;\n /** The alert that is being sent (shared with concurrent close calls). */\n private alertSending?: Promise<void>;\n /**\n * The connection ended (close_notify / fatal alert sent or received, or\n * close()): received records are no longer processed.\n */\n private ended = false;\n\n constructor(options: Options, sessionType: SessionTypes) {\n this.options = options;\n this.sessionType = sessionType;\n this.dtls = new DtlsContext(this.options, this.sessionType);\n this.cipher = new CipherContext(\n this.sessionType,\n this.options.cert,\n this.options.key,\n this.options.signatureHash,\n );\n this.transport = new TransportContext(this.options.transport);\n this.setupExtensions();\n this.transport.socket.onData = this.udpOnMessage;\n }\n\n renegotiation() {\n log(\"renegotiation\", this.sessionType);\n this.connected = false;\n this.cipher = new CipherContext(\n this.sessionType,\n this.options.cert,\n this.options.key,\n this.options.signatureHash,\n );\n this.dtls = new DtlsContext(this.options, this.sessionType);\n this.srtp = new SrtpContext();\n this.extensions = [];\n this.bufferFragmentedHandshakes = [];\n }\n\n /**\n * Resolves once the alert being sent (e.g. the close_notify answering the\n * peer's) has been handed to the transport or timed out. Resolves\n * immediately when none is in flight. Never rejects.\n */\n alertFlushed(): Promise<void> {\n return this.alertSending ?? Promise.resolve();\n }\n\n /** Whether the connection ended (alert, or close()). */\n get terminated() {\n return this.ended;\n }\n\n /**\n * Whether the handshake must not go on: the connection ended, or this side\n * sent close_notify (RFC 5246 §7.2.1: nothing is sent after it, so a\n * handshake that would answer or complete stops; records received after it\n * are still processed, to receive the peer's close_notify).\n */\n protected get handshakeStopped() {\n return this.ended || this.alertSent;\n }\n\n private udpOnMessage = (data: Buffer) => {\n if (this.ended) return;\n const packets = parsePacket(data);\n\n for (const packet of packets) {\n // An alert earlier in this datagram may have ended the connection.\n if (this.ended) return;\n try {\n const messages = parsePlainText(this.dtls, this.cipher)(packet);\n for (const message of messages) {\n // An alert earlier in this record (e.g. close_notify followed by a\n // fatal alert) may have ended the connection: the rest is ignored.\n if (this.ended) return;\n switch (message.type) {\n case ContentType.handshake:\n {\n // Once the handshake completed, a handshake record of an\n // epoch older than the peer's authenticated one (a plaintext\n // epoch-0 Certificate, ClientHello, ...) is unauthenticated:\n // anyone on the path can inject it, so it must not change\n // the session (overwrite the peer certificate and fail its\n // check, or reset the session through renegotiation()). It\n // is dropped. A legitimate retransmission of the peer's last\n // flight still carries its Finished at the current epoch.\n if (\n this.connected &&\n packet.recordLayerHeader.epoch < this.dtls.remoteEpoch\n ) {\n log(\n this.dtls.sessionId,\n \"drop a stale-epoch handshake record after the handshake\",\n packet.recordLayerHeader.epoch,\n );\n continue;\n }\n const handshake = message.data as FragmentedHandshake;\n const handshakes = this.handleFragmentHandshake([handshake]);\n const assembled = Object.values(\n handshakes.reduce(\n (acc: { [type: string]: FragmentedHandshake[] }, cur) => {\n if (!acc[cur.msg_type]) acc[cur.msg_type] = [];\n acc[cur.msg_type].push(cur);\n return acc;\n },\n {},\n ),\n )\n .map((v) => FragmentedHandshake.assemble(v))\n .sort((a, b) => a.msg_type - b.msg_type);\n\n this.onHandleHandshakes(assembled).catch((error) => {\n err(this.dtls.sessionId, \"onHandleHandshakes error\", error);\n this.notify(this.onError, error);\n });\n }\n break;\n case ContentType.applicationData:\n {\n this.notify(this.onData, message.data as Buffer);\n }\n break;\n case ContentType.alert:\n this.handleAlert(message.data as DtlsAlert);\n break;\n }\n }\n } catch (error) {\n // An invalid record (e.g. failed to decrypt) is discarded\n // (RFC 6347 §4.1.2.1).\n err(this.dtls.sessionId, \"catch udpOnMessage error\", error);\n }\n }\n };\n\n /**\n * Run the listeners of an event this socket reports, each isolated\n * (`Event.executeIsolated`): a listener's exception is logged, so an\n * application listener can never interrupt the socket's own processing\n * (ending the connection, closing the transport, the receive loop) nor\n * skip a listener registered after it.\n */\n protected notify<T extends any[]>(event: Event<T>, ...args: T) {\n // Per listener: one that throws neither skips the later listeners (e.g.\n // werift's own, if the application subscribed first) nor this socket.\n event.executeIsolated(\n (error) => err(this.dtls.sessionId, \"event listener failed\", error),\n ...args,\n );\n }\n\n /**\n * RFC 5246 §7.2: react to an alert received from the peer. The connection\n * is ended (flights stopped, close_notify answered or the transport\n * closed) before any listener runs, and each notification is isolated, so\n * a throwing listener does not leave the socket ended but unreported.\n */\n private handleAlert(alert: DtlsAlert) {\n const action = classifyAlert(alert);\n if (action === \"ignore\") {\n log(this.dtls.sessionId, \"ignore warning alert\", alert);\n this.notify(this.onAlert, alert);\n return;\n }\n\n this.ended = true;\n // Retransmitting a handshake flight makes no sense any more.\n this.transport.stopFlights();\n\n if (action === \"close\") {\n log(this.dtls.sessionId, \"received close_notify\");\n // RFC 5246 §7.2.1: respond with close_notify; nothing is sent after it.\n void this.sendAlert(AlertLevel.warning, AlertDesc.CloseNotify);\n // The connection is over: the socket closes its transport once the\n // reply has been sent or timed out, like after a fatal alert (the\n // application does not need to call close()).\n void this.alertFlushed().then(() => this.closeTransport());\n this.notify(this.onAlert, alert);\n this.notify(this.onClose);\n } else {\n err(this.dtls.sessionId, \"received fatal alert\", alert);\n // A fatal alert is not answered (RFC 5246 §7.2.2).\n this.alertSent = true;\n this.closeTransport();\n this.notify(this.onAlert, alert);\n this.notify(this.onError, new DtlsAlertError(alert, \"remote\"));\n }\n }\n\n /**\n * Send an alert to the peer, protected with the current epoch (plaintext\n * before ChangeCipherSpec, encrypted after it).\n *\n * Resolves once the transport has sent the record, or after `timeoutMs`\n * (default {@link DtlsSocket.AlertSendTimeoutMs}). It never rejects: a\n * failed send is only logged. Nothing is sent once close_notify or a fatal\n * alert has been sent or the transport is closed. Sending close_notify or a\n * fatal alert also stops the handshake flights (no retransmission). The\n * record is handed to the transport synchronously, so closing the socket\n * right after calling this does not drop it.\n *\n * A fatal alert ends the connection like a fatal error this side detected\n * itself: `onError` fires synchronously with a local {@link DtlsAlertError},\n * and the transport is closed once the alert has been sent (the returned\n * promise resolves after that).\n */\n sendAlert(\n level: AlertLevel,\n description: AlertDesc,\n options: { timeoutMs?: number } = {},\n ): Promise<void> {\n if (level === AlertLevel.fatal) {\n return this.endWithFatalAlert(description, undefined, options);\n }\n return this.transmitAlert(level, description, options);\n }\n\n /** Encode, protect and send one alert record (see {@link sendAlert}). */\n private transmitAlert(\n level: AlertLevel,\n description: AlertDesc,\n options: { timeoutMs?: number },\n ): Promise<void> {\n if (this.alertSent || this.transport.closed) {\n // A concurrent caller waits for the alert that is still being sent.\n return this.alertSending ?? Promise.resolve();\n }\n if (level === AlertLevel.fatal || description === AlertDesc.CloseNotify) {\n this.alertSent = true;\n // A terminating alert ends the handshake too: no handshake flight is\n // sent or retransmitted after it.\n this.transport.stopFlights();\n }\n if (level === AlertLevel.fatal) {\n this.ended = true;\n }\n\n let sending: Promise<void>;\n try {\n const record = createAlertRecord(this.dtls, this.cipher, {\n level,\n description,\n });\n log(this.dtls.sessionId, \"send alert\", {\n level,\n description,\n epoch: this.dtls.epoch,\n sequenceNumber: this.dtls.recordSequenceNumber,\n });\n sending = this.transport.send(record);\n } catch (error) {\n err(this.dtls.sessionId, \"failed to send alert\", error);\n return Promise.resolve();\n }\n\n const timeoutMs = options.timeoutMs ?? DtlsSocket.AlertSendTimeoutMs;\n const timer = new AbortController();\n const done = Promise.race([\n sending,\n setTimeout(timeoutMs, undefined, { signal: timer.signal }).then(() => {\n log(this.dtls.sessionId, \"alert send timeout\", timeoutMs);\n }),\n ])\n .catch((error) => {\n if (timer.signal.aborted) return;\n err(this.dtls.sessionId, \"failed to send alert\", error);\n })\n .finally(() => timer.abort())\n // A UDP transport hands the datagram to the socket on a later tick\n // (dgram resolves the address asynchronously): closing the socket\n // right after send() resolved would drop the alert.\n .then(() => setImmediate());\n this.alertSending = done;\n return done;\n }\n\n /**\n * Abort the handshake (or the connection) because this side detected a\n * fatal error: see {@link endWithFatalAlert}.\n */\n protected abortWithFatalAlert(description: AlertDesc, reason?: unknown) {\n void this.endWithFatalAlert(description, reason);\n }\n\n /**\n * The single ending path for a fatal alert sent by this side (the public\n * {@link sendAlert} and an internal abort): send the alert, stop the\n * flights, report a local {@link DtlsAlertError} on onError (once), and\n * close the transport once the alert has been sent or timed out. Does\n * nothing more once the connection already ended.\n */\n private endWithFatalAlert(\n description: AlertDesc,\n reason?: unknown,\n options: { timeoutMs?: number } = {},\n ): Promise<void> {\n if (this.ended || this.alertSent || this.transport.closed) {\n return this.alertSending ?? Promise.resolve();\n }\n const sending = this.transmitAlert(AlertLevel.fatal, description, options);\n this.ended = true;\n this.transport.stopFlights();\n // The transport closes once the alert was sent, whatever a listener does.\n const done = sending.then(() => this.closeTransport());\n this.alertSending = done;\n this.notify(\n this.onError,\n new DtlsAlertError(\n { level: AlertLevel.fatal, description },\n \"local\",\n reason,\n ),\n );\n return done;\n }\n\n /**\n * Call `options.verifyRemoteCertificate` with the received peer\n * certificate. When it returns false or throws, the handshake is aborted\n * with a fatal bad_certificate alert and false is returned.\n */\n protected verifyRemoteCertificate() {\n const verify = this.options.verifyRemoteCertificate;\n if (!verify) return true;\n const certificate = this.cipher.remoteCertificate;\n let reason: unknown;\n try {\n if (certificate && verify(Buffer.from(certificate))) {\n return true;\n }\n } catch (error) {\n reason = error;\n }\n err(this.dtls.sessionId, \"remote certificate rejected\", reason);\n this.abortWithFatalAlert(AlertDesc.BadCertificate, reason);\n return false;\n }\n\n /**\n * Close the transport (once; concurrent callers share the same close) and\n * resolve when it has closed. A failure (a rejection or a synchronous\n * throw of the transport's close()) is only logged: it never interrupts\n * the caller, e.g. the onError notification of a received fatal alert.\n */\n private closeTransport() {\n return this.transport.close().catch((error: unknown) => {\n err(this.dtls.sessionId, \"failed to close transport\", error);\n });\n }\n\n private setupExtensions() {\n log(this.dtls.sessionId, \"support srtpProfiles\", this.options.srtpProfiles);\n if (this.options.srtpProfiles && this.options.srtpProfiles.length > 0) {\n const useSrtp = UseSRTP.create(\n this.options.srtpProfiles,\n Buffer.from([0x00]),\n );\n this.extensions.push(useSrtp.extension);\n }\n\n {\n const curve = EllipticCurves.createEmpty();\n curve.data = NamedCurveAlgorithmList;\n this.extensions.push(curve.extension);\n }\n\n {\n const signature = Signature.createEmpty();\n // libwebrtc/OpenSSL require 4=1 , 4=3 signatureHash\n signature.data = signatures;\n this.extensions.push(signature.extension);\n }\n if (this.options.extendedMasterSecret) {\n this.extensions.push({\n type: ExtendedMasterSecret.type,\n data: Buffer.alloc(0),\n });\n }\n\n {\n const renegotiationIndication = RenegotiationIndication.createEmpty();\n this.extensions.push(renegotiationIndication.extension);\n }\n }\n\n protected waitForReady = (condition: () => boolean) =>\n new Promise<void>(async (r, f) => {\n for (let i = 0; i < 10; i++) {\n if (condition()) {\n r();\n break;\n } else {\n await setTimeout(100 * i);\n }\n }\n f(\"waitForReady timeout\");\n });\n\n handleFragmentHandshake(messages: FragmentedHandshake[]) {\n let handshakes = messages.filter((v) => {\n // find fragmented\n if (v.fragment_length !== v.length) {\n this.bufferFragmentedHandshakes.push(v);\n return false;\n }\n return true;\n });\n\n if (this.bufferFragmentedHandshakes.length > 1) {\n const [last] = this.bufferFragmentedHandshakes.slice(-1);\n if (last.fragment_offset + last.fragment_length === last.length) {\n handshakes = [...this.bufferFragmentedHandshakes, ...handshakes];\n this.bufferFragmentedHandshakes = [];\n }\n }\n return handshakes; // return un fragmented handshakes\n }\n\n /**\n * send application data. Nothing is sent once close_notify or a fatal\n * alert has been sent or received.\n */\n send = async (buf: Buffer, addr?: Address) => {\n if (this.alertSent || this.ended) {\n log(this.dtls.sessionId, \"drop application data after alert\");\n return;\n }\n const pkt = createPlaintext(this.dtls)(\n [{ type: ContentType.applicationData, fragment: buf }],\n ++this.dtls.recordSequenceNumber,\n )[0];\n await this.transport.send(this.cipher.encryptPacket(pkt).serialize(), addr);\n };\n\n /**\n * Close the socket: received records are no longer processed and a\n * handshake flight stops retransmitting.\n *\n * - `close()`: sends no alert of its own and closes the transport right\n * away, except that an alert already being sent (`sendAlert()`, the\n * close_notify answering the peer's) is let through first: the transport\n * closes once it has been sent or timed out.\n * - `close({ notify: true })`: sends close_notify first and closes the\n * transport once it has been sent, or after `timeoutMs`\n * (default {@link DtlsSocket.AlertSendTimeoutMs}).\n *\n * The returned promise resolves once the transport is closed (also when\n * the close was already started, e.g. after a fatal alert: it waits for\n * that close) and never rejects; a failing transport close() (a rejection\n * or a synchronous throw) is only logged.\n */\n async close(options: { notify?: boolean; timeoutMs?: number } = {}) {\n if (options.notify) {\n const sending = this.sendAlert(\n AlertLevel.warning,\n AlertDesc.CloseNotify,\n {\n ...(options.timeoutMs !== undefined && {\n timeoutMs: options.timeoutMs,\n }),\n },\n );\n this.ended = true;\n this.transport.stopFlights();\n await sending;\n }\n this.ended = true;\n this.transport.stopFlights();\n // Closing the transport now would drop an alert handed to it but not\n // yet written (a UDP datagram goes out on a later tick).\n await this.alertFlushed();\n // Waits for a close already in progress (e.g. after a fatal alert).\n await this.closeTransport();\n }\n\n extractSessionKeys(keyLength: number, saltLength: number) {\n const keyingMaterial = this.exportKeyingMaterial(\n \"EXTRACTOR-dtls_srtp\",\n keyLength * 2 + saltLength * 2,\n );\n\n const { clientKey, serverKey, clientSalt, serverSalt } = decode(\n keyingMaterial,\n {\n clientKey: types.buffer(keyLength),\n serverKey: types.buffer(keyLength),\n clientSalt: types.buffer(saltLength),\n serverSalt: types.buffer(saltLength),\n },\n );\n\n if (this.sessionType === SessionType.CLIENT) {\n return {\n localKey: clientKey,\n localSalt: clientSalt,\n remoteKey: serverKey,\n remoteSalt: serverSalt,\n };\n } else {\n return {\n localKey: serverKey,\n localSalt: serverSalt,\n remoteKey: clientKey,\n remoteSalt: clientSalt,\n };\n }\n }\n\n exportKeyingMaterial(label: string, length: number) {\n return exportKeyingMaterial(\n label,\n length,\n this.cipher.masterSecret,\n this.cipher.localRandom.serialize(),\n this.cipher.remoteRandom.serialize(),\n this.sessionType === SessionType.CLIENT,\n );\n }\n\n get remoteCertificate() {\n return this.cipher.remoteCertificate;\n }\n}\n\nexport interface Options {\n transport: Transport;\n srtpProfiles?: SrtpProfile[];\n cert?: string;\n key?: string;\n signatureHash?: SignatureHash;\n certificateRequest?: boolean;\n extendedMasterSecret?: boolean;\n /**\n * Verify the peer certificate (DER) during the handshake. Returning false\n * or throwing aborts the handshake with a fatal bad_certificate alert, so\n * the peer learns the failure before it considers the connection\n * established: the client checks the server certificate before sending\n * flight 5, the server checks the client certificate before sending its\n * Finished. onError receives a {@link DtlsAlertError} with\n * `source: \"local\"`.\n */\n verifyRemoteCertificate?: (certificate: Buffer) => boolean;\n}\n"]}
|