@hiroosy/baileys-lite 0.0.4 → 0.3.1
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/LICENSE +21 -0
- package/README.md +658 -10
- package/WAProto/index.js +2 -2558
- package/engine-requirements.js +3 -4
- package/package.json +8 -3
- package/src/binary/wa-binary.js +3 -25
- package/src/constants.js +7 -15
- package/src/defaults.js +2 -5
- package/src/foundation/ai-rich.js +530 -0
- package/src/foundation/audio-duration.js +43 -103
- package/src/foundation/audio-samples.js +19 -37
- package/src/foundation/boom.js +0 -7
- package/src/foundation/cache.js +4 -26
- package/src/foundation/concurrency.js +1 -19
- package/src/foundation/curve25519.js +7 -39
- package/src/foundation/link-preview.js +15 -57
- package/src/foundation/logger.js +0 -11
- package/src/foundation/long.js +4 -14
- package/src/foundation/protobuf-minimal.js +21 -53
- package/src/foundation/qrcode-terminal.js +273 -0
- package/src/foundation/sql-database.js +716 -0
- package/src/foundation/wa-crypto.js +2 -31
- package/src/foundation/zip.js +25 -41
- package/src/index.js +8 -18
- package/src/signal/libsignal.js +23 -78
- package/src/signal/signal-group.js +0 -35
- package/src/signal/signal-repository.js +10 -29
- package/src/socket/business-communities.js +12 -31
- package/src/socket/chats.js +5 -8
- package/src/socket/groups-newsletter.js +18 -17
- package/src/socket/messages-recv.js +81 -127
- package/src/socket/messages-send.js +372 -139
- package/src/socket/socket-core.js +227 -157
- package/src/socket/usync.js +2 -6
- package/src/socket-client/native-websocket.js +344 -0
- package/src/socket-client/websocket-client.js +84 -38
- package/src/utils/auth-state-core.js +14 -56
- package/src/utils/auth-state-storage.js +7 -42
- package/src/utils/chat-sync.js +4 -26
- package/src/utils/media.js +15 -71
- package/src/utils/message-compose.js +208 -85
- package/src/utils/message-processing.js +10 -65
- package/src/utils/username.js +19 -0
- package/src/utils/wa-protocol-core.js +71 -127
- package/src/vendor/jpeg-js/decoder.js +75 -136
- package/src/vendor/jpeg-js/encoder.js +179 -264
- package/src/vendor/pngjs/bitmapper.js +5 -27
- package/src/vendor/pngjs/bitpacker.js +4 -12
- package/src/vendor/pngjs/constants.js +3 -11
- package/src/vendor/pngjs/crc.js +0 -6
- package/src/vendor/pngjs/filter-pack.js +1 -7
- package/src/vendor/pngjs/filter-parse-sync.js +0 -6
- package/src/vendor/pngjs/filter-parse.js +1 -11
- package/src/vendor/pngjs/format-normaliser.js +5 -11
- package/src/vendor/pngjs/interlace.js +7 -24
- package/src/vendor/pngjs/packer-sync.js +0 -11
- package/src/vendor/pngjs/packer.js +7 -15
- package/src/vendor/pngjs/paeth-predictor.js +0 -6
- package/src/vendor/pngjs/parser-sync.js +0 -8
- package/src/vendor/pngjs/parser.js +5 -29
- package/src/vendor/pngjs/png-sync.js +0 -7
- package/src/vendor/pngjs/sync-inflate.js +7 -16
- package/src/vendor/pngjs/sync-reader.js +4 -11
- package/src/voip/WaVoipCoordinator.js +158 -0
- package/src/voip/app-data/WaAppDataStream.js +193 -0
- package/src/voip/app-data/protocol.js +172 -0
- package/src/voip/bytes.js +63 -0
- package/src/voip/call/WaCallManager.js +442 -0
- package/src/voip/call/WaCallMediaSession.js +1705 -0
- package/src/voip/call/call-state.js +203 -0
- package/src/voip/crypto/encryption.js +13 -0
- package/src/voip/crypto/primitives.js +21 -0
- package/src/voip/crypto/rtcp.js +66 -0
- package/src/voip/crypto/srtp.js +180 -0
- package/src/voip/crypto/ssrc.js +15 -0
- package/src/voip/index.js +628 -0
- package/src/voip/media/WaAudioEngine.js +486 -0
- package/src/voip/media/WaVideoEngine.js +275 -0
- package/src/voip/media/audio-codec.js +0 -0
- package/src/voip/media/audio-reorder.js +107 -0
- package/src/voip/media/h264.js +246 -0
- package/src/voip/media/mlow-codec.js +465 -0
- package/src/voip/media/rtcp.js +68 -0
- package/src/voip/media/rtp.js +242 -0
- package/src/voip/protobuf.js +30 -0
- package/src/voip/relay/WaManualRelay.js +609 -0
- package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
- package/src/voip/relay/dtls/aead.js +46 -0
- package/src/voip/relay/dtls/cert-builder.js +102 -0
- package/src/voip/relay/dtls/der.js +98 -0
- package/src/voip/relay/dtls/ecdhe.js +37 -0
- package/src/voip/relay/dtls/handshake-framing.js +100 -0
- package/src/voip/relay/dtls/handshake-messages.js +158 -0
- package/src/voip/relay/dtls/handshake.js +582 -0
- package/src/voip/relay/dtls/prf.js +39 -0
- package/src/voip/relay/dtls/record.js +56 -0
- package/src/voip/relay/relay-ack.js +141 -0
- package/src/voip/relay/sctp/association.js +434 -0
- package/src/voip/relay/sctp/crc32c.js +21 -0
- package/src/voip/relay/sctp/wire.js +226 -0
- package/src/voip/relay/stun.js +463 -0
- package/src/voip/shim/baileys-resolve.js +7 -0
- package/src/voip/shim/core.js +66 -0
- package/src/voip/shim/crypto.js +6 -0
- package/src/voip/shim/proto.js +10 -0
- package/src/voip/shim/protocol.js +130 -0
- package/src/voip/shim/transport.js +82 -0
- package/src/voip/shim/util.js +207 -0
- package/src/voip/signaling/bridge.js +102 -0
- package/src/voip/signaling/screen-share.js +60 -0
- package/src/voip/signaling/signaling.js +491 -0
- package/src/voip/types.js +69 -0
- package/src/voip/voip-deps.js +243 -0
- package/src/voip/voipClient.js +314 -0
- package/src/wam/wam-constants.js +0 -1
- package/src/wam/wam.js +2 -7
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
import { randomBytes, createHash, X509Certificate } from 'node:crypto';
|
|
2
|
+
import { EventEmitter } from 'node:events';
|
|
3
|
+
import { ContentType, encodeRecord, decodeRecords } from './record.js';
|
|
4
|
+
import { HandshakeType, encodeHandshakeMessage, decodeHandshakeFragment, HandshakeReassembler, logicalHandshakeBytes } from './handshake-framing.js';
|
|
5
|
+
import * as msg from './handshake-messages.js';
|
|
6
|
+
import { generateSelfSignedCert } from './cert-builder.js';
|
|
7
|
+
import { generateEcdheKeypair, buildEcdheSignedParams, verifyEcdheParams, signEcdheParams } from './ecdhe.js';
|
|
8
|
+
import { deriveMasterSecret, deriveKeyBlock, deriveVerifyData } from './prf.js';
|
|
9
|
+
import { encryptRecord, decryptRecord, aes128GcmParams } from './aead.js';
|
|
10
|
+
import { createNoopLogger } from '../../shim/core.js';
|
|
11
|
+
|
|
12
|
+
const RETRANSMIT_TIMEOUTS_MS = [1000, 2000, 4000, 8000, 8000];
|
|
13
|
+
const HANDSHAKE_TIMEOUT_MS = 25000;
|
|
14
|
+
|
|
15
|
+
export class DtlsClient extends EventEmitter {
|
|
16
|
+
#sendDatagram;
|
|
17
|
+
#logger;
|
|
18
|
+
#state = 'idle';
|
|
19
|
+
#messageSeq = 0;
|
|
20
|
+
#reassembler = new HandshakeReassembler();
|
|
21
|
+
#handshakeMessages = [];
|
|
22
|
+
#clientRandom;
|
|
23
|
+
#serverRandom;
|
|
24
|
+
#cookie = Buffer.alloc(0);
|
|
25
|
+
#ecdhe;
|
|
26
|
+
#cert;
|
|
27
|
+
#peerCertificates = [];
|
|
28
|
+
#pendingServerKeyExchange = null;
|
|
29
|
+
#serverRequestedClientCert = false;
|
|
30
|
+
#masterSecret;
|
|
31
|
+
#writeEpoch = 0;
|
|
32
|
+
#writeSeq = 0n;
|
|
33
|
+
#readSeqByEpoch = new Map([[0, -1n]]);
|
|
34
|
+
#keys = null;
|
|
35
|
+
#retransmitTimer = null;
|
|
36
|
+
#retransmitAttempt = 0;
|
|
37
|
+
#lastFlightDatagrams = [];
|
|
38
|
+
#overallTimeoutTimer = null;
|
|
39
|
+
|
|
40
|
+
constructor({ sendDatagram, logger }) {
|
|
41
|
+
super();
|
|
42
|
+
this.#sendDatagram = sendDatagram;
|
|
43
|
+
this.#logger = logger ?? createNoopLogger();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
start() {
|
|
47
|
+
this.#clientRandom = randomBytes(32);
|
|
48
|
+
this.#cert = generateSelfSignedCert('wa-voip');
|
|
49
|
+
this.#state = 'wait_hvr';
|
|
50
|
+
this.#sendFlight1();
|
|
51
|
+
this.#overallTimeoutTimer = setTimeout(() => this.#fail(new Error('DTLS handshake timed out overall')), HANDSHAKE_TIMEOUT_MS);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
close() {
|
|
55
|
+
this.#state = 'closed';
|
|
56
|
+
clearTimeout(this.#retransmitTimer);
|
|
57
|
+
clearTimeout(this.#overallTimeoutTimer);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
handleDatagram(datagram) {
|
|
61
|
+
if (this.#state === 'closed') return;
|
|
62
|
+
let records;
|
|
63
|
+
try {
|
|
64
|
+
records = decodeRecords(datagram);
|
|
65
|
+
} catch {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
for (const record of records) this.#handleRecord(record);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
get isConnected() { return this.#state === 'connected'; }
|
|
72
|
+
|
|
73
|
+
encryptApplicationData(plaintext) {
|
|
74
|
+
if (!this.isConnected) throw new Error('DtlsClient.encryptApplicationData: not connected yet');
|
|
75
|
+
const seq = this.#writeSeq++;
|
|
76
|
+
const fragment = encryptRecord({
|
|
77
|
+
writeKey: this.#keys.clientWriteKey, salt: this.#keys.clientWriteIv,
|
|
78
|
+
epoch: this.#writeEpoch, sequenceNumber: seq, type: ContentType.APPLICATION_DATA, plaintext,
|
|
79
|
+
});
|
|
80
|
+
return encodeRecord({ type: ContentType.APPLICATION_DATA, epoch: this.#writeEpoch, sequenceNumber: seq, fragment });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
decryptApplicationData(datagram) {
|
|
84
|
+
const out = [];
|
|
85
|
+
let records;
|
|
86
|
+
try { records = decodeRecords(datagram); } catch (e) {
|
|
87
|
+
|
|
88
|
+
this.#logger.trace('post-handshake datagram failed to decode as DTLS records', {
|
|
89
|
+
message: e.message, bytes: datagram.length, hex: Buffer.from(datagram).toString('hex')
|
|
90
|
+
});
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
for (const record of records) {
|
|
94
|
+
if (record.type !== ContentType.APPLICATION_DATA) {
|
|
95
|
+
this.#logger.trace('post-handshake non-application_data record', {
|
|
96
|
+
type: record.type, epoch: record.epoch, seq: record.sequenceNumber, fragmentLen: record.fragment.length
|
|
97
|
+
});
|
|
98
|
+
this.#handleRecord(record);
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const readFloor = this.#readSeqByEpoch.get(record.epoch) ?? -1n;
|
|
102
|
+
if (record.sequenceNumber <= readFloor) {
|
|
103
|
+
this.#logger.trace('dropping application_data as replay/duplicate', {
|
|
104
|
+
epoch: record.epoch, seq: record.sequenceNumber.toString(), readFloor: readFloor.toString()
|
|
105
|
+
});
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
try {
|
|
109
|
+
const plaintext = decryptRecord({
|
|
110
|
+
readKey: this.#keys.serverWriteKey, salt: this.#keys.serverWriteIv,
|
|
111
|
+
epoch: record.epoch, sequenceNumber: record.sequenceNumber, type: record.type, fragment: record.fragment,
|
|
112
|
+
});
|
|
113
|
+
this.#readSeqByEpoch.set(record.epoch, record.sequenceNumber);
|
|
114
|
+
this.#logger.trace('decrypted application_data', {
|
|
115
|
+
epoch: record.epoch, seq: record.sequenceNumber.toString(), plaintextLen: plaintext.length
|
|
116
|
+
});
|
|
117
|
+
out.push(plaintext);
|
|
118
|
+
} catch (e) {
|
|
119
|
+
|
|
120
|
+
this.#logger.trace('FAILED to decrypt post-handshake record', {
|
|
121
|
+
epoch: record.epoch, seq: record.sequenceNumber.toString(), fragmentLen: record.fragment.length, message: e.message
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
#sendFlight1() {
|
|
129
|
+
const chBody = msg.buildClientHello({ clientRandom: this.#clientRandom, cookie: this.#cookie });
|
|
130
|
+
const datagram = this.#packHandshakeMessage(HandshakeType.CLIENT_HELLO, chBody);
|
|
131
|
+
this.#transmitFlight([datagram]);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
#sendFlight3(serverPublicKeyPoint) {
|
|
135
|
+
this.#ecdhe = generateEcdheKeypair();
|
|
136
|
+
const preMasterSecret = this.#ecdhe.computeSharedSecret(serverPublicKeyPoint);
|
|
137
|
+
this.#masterSecret = deriveMasterSecret(preMasterSecret, this.#clientRandom, this.#serverRandom);
|
|
138
|
+
|
|
139
|
+
const certPart = this.#serverRequestedClientCert
|
|
140
|
+
? this.#packHandshakeMessage(HandshakeType.CERTIFICATE, msg.buildCertificate(this.#cert.certDer))
|
|
141
|
+
: Buffer.alloc(0);
|
|
142
|
+
|
|
143
|
+
const cke = this.#packHandshakeMessage(HandshakeType.CLIENT_KEY_EXCHANGE, msg.buildClientKeyExchange(this.#ecdhe.publicKeyPoint));
|
|
144
|
+
|
|
145
|
+
const certVerifyPart = this.#serverRequestedClientCert
|
|
146
|
+
? this.#packHandshakeMessage(HandshakeType.CERTIFICATE_VERIFY, msg.buildCertificateVerify({
|
|
147
|
+
signatureScheme: msg.SIGNATURE_SCHEME_ECDSA_SECP256R1_SHA256,
|
|
148
|
+
|
|
149
|
+
signature: signEcdheParams(this.#cert.privateKey, Buffer.concat(this.#handshakeMessages)),
|
|
150
|
+
}))
|
|
151
|
+
: Buffer.alloc(0);
|
|
152
|
+
|
|
153
|
+
this.#keys = deriveKeyBlock(this.#masterSecret, this.#clientRandom, this.#serverRandom, aes128GcmParams);
|
|
154
|
+
const handshakeHashBeforeFinished = createHash('sha256').update(Buffer.concat(this.#handshakeMessages)).digest();
|
|
155
|
+
const verifyData = deriveVerifyData(this.#masterSecret, 'client finished', handshakeHashBeforeFinished);
|
|
156
|
+
const finishedBody = msg.buildFinished(verifyData);
|
|
157
|
+
const finishedMsgSeq = this.#messageSeq++;
|
|
158
|
+
const finishedLogical = logicalHandshakeBytes({ msgType: HandshakeType.FINISHED, messageSeq: finishedMsgSeq, body: finishedBody });
|
|
159
|
+
const finishedFragments = encodeHandshakeMessage({ msgType: HandshakeType.FINISHED, messageSeq: finishedMsgSeq, body: finishedBody });
|
|
160
|
+
|
|
161
|
+
this.#handshakeMessages.push(finishedLogical);
|
|
162
|
+
|
|
163
|
+
const ccsRecord = encodeRecord({ type: ContentType.CHANGE_CIPHER_SPEC, epoch: this.#writeEpoch, sequenceNumber: this.#writeSeq++, fragment: Buffer.from([1]) });
|
|
164
|
+
this.#writeEpoch = 1;
|
|
165
|
+
this.#writeSeq = 0n;
|
|
166
|
+
|
|
167
|
+
const finishedSeq = this.#writeSeq++;
|
|
168
|
+
const encryptedFinished = encryptRecord({
|
|
169
|
+
writeKey: this.#keys.clientWriteKey, salt: this.#keys.clientWriteIv,
|
|
170
|
+
epoch: this.#writeEpoch, sequenceNumber: finishedSeq, type: ContentType.HANDSHAKE, plaintext: finishedFragments[0],
|
|
171
|
+
});
|
|
172
|
+
const finishedRecord = encodeRecord({ type: ContentType.HANDSHAKE, epoch: this.#writeEpoch, sequenceNumber: finishedSeq, fragment: encryptedFinished });
|
|
173
|
+
|
|
174
|
+
this.#state = 'wait_server_finished';
|
|
175
|
+
|
|
176
|
+
this.#transmitFlight([Buffer.concat([certPart, cke, certVerifyPart, ccsRecord, finishedRecord])]);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
#packHandshakeMessage(msgType, body) {
|
|
180
|
+
const seq = this.#messageSeq++;
|
|
181
|
+
const fragments = encodeHandshakeMessage({ msgType, messageSeq: seq, body });
|
|
182
|
+
this.#handshakeMessages.push(logicalHandshakeBytes({ msgType, messageSeq: seq, body }));
|
|
183
|
+
return Buffer.concat(fragments.map((f) => encodeRecord({ type: ContentType.HANDSHAKE, epoch: this.#writeEpoch, sequenceNumber: this.#writeSeq++, fragment: f })));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
#transmitFlight(datagrams) {
|
|
187
|
+
this.#lastFlightDatagrams = datagrams;
|
|
188
|
+
this.#retransmitAttempt = 0;
|
|
189
|
+
for (const d of datagrams) this.#sendDatagram(d);
|
|
190
|
+
this.#armRetransmit();
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
#armRetransmit() {
|
|
194
|
+
clearTimeout(this.#retransmitTimer);
|
|
195
|
+
if (this.#state === 'connected' || this.#state === 'closed') return;
|
|
196
|
+
const timeout = RETRANSMIT_TIMEOUTS_MS[Math.min(this.#retransmitAttempt, RETRANSMIT_TIMEOUTS_MS.length - 1)];
|
|
197
|
+
this.#retransmitTimer = setTimeout(() => {
|
|
198
|
+
this.#retransmitAttempt += 1;
|
|
199
|
+
for (const d of this.#lastFlightDatagrams) this.#sendDatagram(d);
|
|
200
|
+
this.#armRetransmit();
|
|
201
|
+
}, timeout);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
#handleRecord(record) {
|
|
205
|
+
if (record.type === ContentType.HANDSHAKE) {
|
|
206
|
+
if (record.epoch === 0) {
|
|
207
|
+
const decoded = decodeHandshakeFragment(record.fragment);
|
|
208
|
+
const complete = this.#reassembler.addFragment(decoded);
|
|
209
|
+
if (complete) this.#handleHandshakeMessage(complete);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (record.epoch === 1 && this.#state === 'wait_server_finished') {
|
|
213
|
+
this.#tryDecryptServerFinished(record);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (record.type === ContentType.CHANGE_CIPHER_SPEC) {
|
|
219
|
+
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (record.type === ContentType.ALERT) {
|
|
223
|
+
this.#fail(new Error(`DTLS alert received (epoch ${record.epoch}): ${record.fragment.toString('hex')}`));
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
#handleHandshakeMessage({ msgType, messageSeq, body }) {
|
|
229
|
+
if (this.#state === 'wait_hvr' && msgType === HandshakeType.HELLO_VERIFY_REQUEST) {
|
|
230
|
+
const { cookie } = msg.parseHelloVerifyRequest(body);
|
|
231
|
+
this.#cookie = cookie;
|
|
232
|
+
|
|
233
|
+
this.#handshakeMessages = [];
|
|
234
|
+
this.#messageSeq = 0;
|
|
235
|
+
this.#state = 'wait_server_flight';
|
|
236
|
+
const chBody = msg.buildClientHello({ clientRandom: this.#clientRandom, cookie: this.#cookie });
|
|
237
|
+
const datagram = this.#packHandshakeMessage(HandshakeType.CLIENT_HELLO, chBody);
|
|
238
|
+
this.#transmitFlight([datagram]);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (this.#state === 'wait_server_flight' || this.#state === 'wait_hvr') {
|
|
242
|
+
this.#state = 'wait_server_flight';
|
|
243
|
+
|
|
244
|
+
this.#handshakeMessages.push(logicalHandshakeBytes({ msgType, messageSeq, body }));
|
|
245
|
+
if (msgType === HandshakeType.SERVER_HELLO) {
|
|
246
|
+
const parsed = msg.parseServerHello(body);
|
|
247
|
+
this.#serverRandom = parsed.serverRandom;
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (msgType === HandshakeType.CERTIFICATE) {
|
|
251
|
+
this.#peerCertificates = msg.parseCertificate(body).certificates;
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (msgType === HandshakeType.SERVER_KEY_EXCHANGE) {
|
|
255
|
+
this.#pendingServerKeyExchange = msg.parseServerKeyExchange(body);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
if (msgType === HandshakeType.CERTIFICATE_REQUEST) {
|
|
259
|
+
|
|
260
|
+
this.#serverRequestedClientCert = true;
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
if (msgType === HandshakeType.SERVER_HELLO_DONE) {
|
|
264
|
+
this.#onServerHelloDone();
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
#onServerHelloDone() {
|
|
271
|
+
if (!this.#serverRandom || this.#peerCertificates.length === 0 || !this.#pendingServerKeyExchange) {
|
|
272
|
+
this.#fail(new Error('DTLS: ServerHelloDone arrived before a required prior message'));
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
try {
|
|
276
|
+
const { publicKeyPoint, signature } = this.#pendingServerKeyExchange;
|
|
277
|
+
const signedParams = buildEcdheSignedParams(this.#clientRandom, this.#serverRandom, publicKeyPoint);
|
|
278
|
+
const leaf = new X509Certificate(this.#peerCertificates[0]);
|
|
279
|
+
const ok = verifyEcdheParams(leaf.publicKey, signedParams, signature);
|
|
280
|
+
if (!ok) throw new Error('ServerKeyExchange signature verification failed');
|
|
281
|
+
this.#sendFlight3(publicKeyPoint);
|
|
282
|
+
} catch (e) {
|
|
283
|
+
this.#fail(new Error(`DTLS: ServerKeyExchange verification failed: ${e.message}`));
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
#tryDecryptServerFinished(record) {
|
|
288
|
+
const readFloor = this.#readSeqByEpoch.get(1) ?? -1n;
|
|
289
|
+
if (record.sequenceNumber <= readFloor) return;
|
|
290
|
+
let plaintext;
|
|
291
|
+
try {
|
|
292
|
+
plaintext = decryptRecord({
|
|
293
|
+
readKey: this.#keys.serverWriteKey, salt: this.#keys.serverWriteIv,
|
|
294
|
+
epoch: 1, sequenceNumber: record.sequenceNumber, type: ContentType.HANDSHAKE, fragment: record.fragment,
|
|
295
|
+
});
|
|
296
|
+
} catch (e) {
|
|
297
|
+
this.#fail(new Error(`DTLS: failed to decrypt server Finished: ${e.message}`));
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
this.#readSeqByEpoch.set(1, record.sequenceNumber);
|
|
301
|
+
const decoded = decodeHandshakeFragment(plaintext);
|
|
302
|
+
if (decoded.msgType !== HandshakeType.FINISHED) return;
|
|
303
|
+
const { verifyData } = msg.parseFinished(decoded.body);
|
|
304
|
+
const handshakeHash = createHash('sha256').update(Buffer.concat(this.#handshakeMessages)).digest();
|
|
305
|
+
const expected = deriveVerifyData(this.#masterSecret, 'server finished', handshakeHash);
|
|
306
|
+
if (!expected.equals(verifyData)) {
|
|
307
|
+
this.#fail(new Error('DTLS: server Finished verify_data mismatch — handshake integrity check failed'));
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
this.#state = 'connected';
|
|
311
|
+
clearTimeout(this.#retransmitTimer);
|
|
312
|
+
clearTimeout(this.#overallTimeoutTimer);
|
|
313
|
+
this.emit('connected');
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
#fail(err) {
|
|
317
|
+
this.#state = 'closed';
|
|
318
|
+
clearTimeout(this.#retransmitTimer);
|
|
319
|
+
clearTimeout(this.#overallTimeoutTimer);
|
|
320
|
+
this.emit('error', err);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export class DtlsServer extends EventEmitter {
|
|
325
|
+
#sendDatagram;
|
|
326
|
+
#logger;
|
|
327
|
+
#state = 'idle';
|
|
328
|
+
#messageSeq = 0;
|
|
329
|
+
#reassembler = new HandshakeReassembler();
|
|
330
|
+
#handshakeMessages = [];
|
|
331
|
+
#clientRandom;
|
|
332
|
+
#serverRandom;
|
|
333
|
+
#ecdhe;
|
|
334
|
+
#cert;
|
|
335
|
+
#masterSecret;
|
|
336
|
+
#writeEpoch = 0;
|
|
337
|
+
#writeSeq = 0n;
|
|
338
|
+
#readSeqByEpoch = new Map([[0, -1n]]);
|
|
339
|
+
#keys = null;
|
|
340
|
+
#retransmitTimer = null;
|
|
341
|
+
#retransmitAttempt = 0;
|
|
342
|
+
#lastFlightDatagrams = [];
|
|
343
|
+
#overallTimeoutTimer = null;
|
|
344
|
+
|
|
345
|
+
constructor({ sendDatagram, logger }) {
|
|
346
|
+
super();
|
|
347
|
+
this.#sendDatagram = sendDatagram;
|
|
348
|
+
this.#logger = logger ?? createNoopLogger();
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
startPassive() {
|
|
352
|
+
this.#cert = generateSelfSignedCert('wa-voip');
|
|
353
|
+
this.#state = 'wait_client_hello';
|
|
354
|
+
this.#overallTimeoutTimer = setTimeout(() => this.#fail(new Error('DTLS handshake timed out overall (passive/server role)')), HANDSHAKE_TIMEOUT_MS);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
close() {
|
|
358
|
+
this.#state = 'closed';
|
|
359
|
+
clearTimeout(this.#retransmitTimer);
|
|
360
|
+
clearTimeout(this.#overallTimeoutTimer);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
handleDatagram(datagram) {
|
|
364
|
+
if (this.#state === 'closed') return;
|
|
365
|
+
let records;
|
|
366
|
+
try {
|
|
367
|
+
records = decodeRecords(datagram);
|
|
368
|
+
} catch {
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
for (const record of records) this.#handleRecord(record);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
get isConnected() { return this.#state === 'connected'; }
|
|
375
|
+
|
|
376
|
+
encryptApplicationData(plaintext) {
|
|
377
|
+
if (!this.isConnected) throw new Error('DtlsServer.encryptApplicationData: not connected yet');
|
|
378
|
+
const seq = this.#writeSeq++;
|
|
379
|
+
const fragment = encryptRecord({
|
|
380
|
+
writeKey: this.#keys.serverWriteKey, salt: this.#keys.serverWriteIv,
|
|
381
|
+
epoch: this.#writeEpoch, sequenceNumber: seq, type: ContentType.APPLICATION_DATA, plaintext,
|
|
382
|
+
});
|
|
383
|
+
return encodeRecord({ type: ContentType.APPLICATION_DATA, epoch: this.#writeEpoch, sequenceNumber: seq, fragment });
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
decryptApplicationData(datagram) {
|
|
387
|
+
const out = [];
|
|
388
|
+
let records;
|
|
389
|
+
try { records = decodeRecords(datagram); } catch (e) {
|
|
390
|
+
this.#logger.trace('post-handshake datagram failed to decode as DTLS records', {
|
|
391
|
+
message: e.message, bytes: datagram.length, hex: Buffer.from(datagram).toString('hex')
|
|
392
|
+
});
|
|
393
|
+
return out;
|
|
394
|
+
}
|
|
395
|
+
for (const record of records) {
|
|
396
|
+
if (record.type !== ContentType.APPLICATION_DATA) {
|
|
397
|
+
this.#logger.trace('post-handshake non-application_data record', {
|
|
398
|
+
type: record.type, epoch: record.epoch, seq: record.sequenceNumber, fragmentLen: record.fragment.length
|
|
399
|
+
});
|
|
400
|
+
this.#handleRecord(record);
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
const readFloor = this.#readSeqByEpoch.get(record.epoch) ?? -1n;
|
|
404
|
+
if (record.sequenceNumber <= readFloor) continue;
|
|
405
|
+
try {
|
|
406
|
+
const plaintext = decryptRecord({
|
|
407
|
+
readKey: this.#keys.clientWriteKey, salt: this.#keys.clientWriteIv,
|
|
408
|
+
epoch: record.epoch, sequenceNumber: record.sequenceNumber, type: record.type, fragment: record.fragment,
|
|
409
|
+
});
|
|
410
|
+
this.#readSeqByEpoch.set(record.epoch, record.sequenceNumber);
|
|
411
|
+
out.push(plaintext);
|
|
412
|
+
} catch (e) {
|
|
413
|
+
this.#logger.trace('FAILED to decrypt post-handshake record', {
|
|
414
|
+
epoch: record.epoch, seq: record.sequenceNumber.toString(), fragmentLen: record.fragment.length, message: e.message
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
return out;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
#handleRecord(record) {
|
|
422
|
+
if (record.type === ContentType.HANDSHAKE) {
|
|
423
|
+
if (record.epoch === 0) {
|
|
424
|
+
const decoded = decodeHandshakeFragment(record.fragment);
|
|
425
|
+
const complete = this.#reassembler.addFragment(decoded);
|
|
426
|
+
if (complete) this.#handleHandshakeMessage(complete);
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (record.epoch === 1 && this.#state === 'wait_client_finished') {
|
|
430
|
+
this.#tryDecryptClientFinished(record);
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
if (record.type === ContentType.CHANGE_CIPHER_SPEC) return;
|
|
436
|
+
if (record.type === ContentType.ALERT) {
|
|
437
|
+
this.#fail(new Error(`DTLS alert received (epoch ${record.epoch}): ${record.fragment.toString('hex')}`));
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
#handleHandshakeMessage({ msgType, messageSeq, body }) {
|
|
443
|
+
if (this.#state === 'wait_client_hello' && msgType === HandshakeType.CLIENT_HELLO) {
|
|
444
|
+
this.#handshakeMessages.push(logicalHandshakeBytes({ msgType, messageSeq, body }));
|
|
445
|
+
const { clientRandom } = msg.parseClientHello(body);
|
|
446
|
+
this.#clientRandom = clientRandom;
|
|
447
|
+
this.#sendFlight2();
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
if (this.#state === 'wait_client_finished' && msgType === HandshakeType.CLIENT_KEY_EXCHANGE) {
|
|
451
|
+
this.#handshakeMessages.push(logicalHandshakeBytes({ msgType, messageSeq, body }));
|
|
452
|
+
const { publicKeyPoint } = msg.parseClientKeyExchange(body);
|
|
453
|
+
this.#finishKeyExchange(publicKeyPoint);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
#sendFlight2() {
|
|
459
|
+
this.#serverRandom = randomBytes(32);
|
|
460
|
+
this.#ecdhe = generateEcdheKeypair();
|
|
461
|
+
|
|
462
|
+
const shBody = msg.buildServerHello({ serverRandom: this.#serverRandom, cipherSuite: msg.CIPHER_SUITE_ECDHE_ECDSA_AES_128_GCM_SHA256 });
|
|
463
|
+
const shDatagram = this.#packHandshakeMessage(HandshakeType.SERVER_HELLO, shBody);
|
|
464
|
+
|
|
465
|
+
const certBody = msg.buildCertificate(this.#cert.certDer);
|
|
466
|
+
const certDatagram = this.#packHandshakeMessage(HandshakeType.CERTIFICATE, certBody);
|
|
467
|
+
|
|
468
|
+
const signedParams = buildEcdheSignedParams(this.#clientRandom, this.#serverRandom, this.#ecdhe.publicKeyPoint);
|
|
469
|
+
const signature = signEcdheParams(this.#cert.privateKey, signedParams);
|
|
470
|
+
const skeBody = msg.buildServerKeyExchange({ publicKeyPoint: this.#ecdhe.publicKeyPoint, signature });
|
|
471
|
+
const skeDatagram = this.#packHandshakeMessage(HandshakeType.SERVER_KEY_EXCHANGE, skeBody);
|
|
472
|
+
|
|
473
|
+
const shdBody = msg.buildServerHelloDone();
|
|
474
|
+
const shdDatagram = this.#packHandshakeMessage(HandshakeType.SERVER_HELLO_DONE, shdBody);
|
|
475
|
+
|
|
476
|
+
this.#state = 'wait_client_finished';
|
|
477
|
+
this.#transmitFlight([Buffer.concat([shDatagram, certDatagram, skeDatagram, shdDatagram])]);
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
#finishKeyExchange(clientPublicKeyPoint) {
|
|
481
|
+
try {
|
|
482
|
+
const preMasterSecret = this.#ecdhe.computeSharedSecret(clientPublicKeyPoint);
|
|
483
|
+
this.#masterSecret = deriveMasterSecret(preMasterSecret, this.#clientRandom, this.#serverRandom);
|
|
484
|
+
this.#keys = deriveKeyBlock(this.#masterSecret, this.#clientRandom, this.#serverRandom, aes128GcmParams);
|
|
485
|
+
} catch (e) {
|
|
486
|
+
this.#fail(new Error(`DTLS: server-side key derivation failed: ${e.message}`));
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
#tryDecryptClientFinished(record) {
|
|
492
|
+
const readFloor = this.#readSeqByEpoch.get(1) ?? -1n;
|
|
493
|
+
if (record.sequenceNumber <= readFloor) return;
|
|
494
|
+
if (!this.#keys) {
|
|
495
|
+
|
|
496
|
+
this.#logger.trace('client Finished arrived before key derivation completed', {});
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
let plaintext;
|
|
500
|
+
try {
|
|
501
|
+
plaintext = decryptRecord({
|
|
502
|
+
readKey: this.#keys.clientWriteKey, salt: this.#keys.clientWriteIv,
|
|
503
|
+
epoch: 1, sequenceNumber: record.sequenceNumber, type: ContentType.HANDSHAKE, fragment: record.fragment,
|
|
504
|
+
});
|
|
505
|
+
} catch (e) {
|
|
506
|
+
this.#fail(new Error(`DTLS: failed to decrypt client Finished: ${e.message}`));
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
this.#readSeqByEpoch.set(1, record.sequenceNumber);
|
|
510
|
+
const decoded = decodeHandshakeFragment(plaintext);
|
|
511
|
+
if (decoded.msgType !== HandshakeType.FINISHED) return;
|
|
512
|
+
const { verifyData } = msg.parseFinished(decoded.body);
|
|
513
|
+
|
|
514
|
+
const handshakeHashForClient = createHash('sha256').update(Buffer.concat(this.#handshakeMessages)).digest();
|
|
515
|
+
const expected = deriveVerifyData(this.#masterSecret, 'client finished', handshakeHashForClient);
|
|
516
|
+
if (!expected.equals(verifyData)) {
|
|
517
|
+
this.#fail(new Error('DTLS: client Finished verify_data mismatch — handshake integrity check failed'));
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const clientFinishedLogical = logicalHandshakeBytes({ msgType: decoded.msgType, messageSeq: decoded.messageSeq, body: decoded.body });
|
|
522
|
+
this.#handshakeMessages.push(clientFinishedLogical);
|
|
523
|
+
this.#sendServerFinished();
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
#sendServerFinished() {
|
|
527
|
+
const handshakeHash = createHash('sha256').update(Buffer.concat(this.#handshakeMessages)).digest();
|
|
528
|
+
const verifyData = deriveVerifyData(this.#masterSecret, 'server finished', handshakeHash);
|
|
529
|
+
const finishedBody = msg.buildFinished(verifyData);
|
|
530
|
+
const finishedMsgSeq = this.#messageSeq++;
|
|
531
|
+
const finishedFragments = encodeHandshakeMessage({ msgType: HandshakeType.FINISHED, messageSeq: finishedMsgSeq, body: finishedBody });
|
|
532
|
+
|
|
533
|
+
const ccsRecord = encodeRecord({ type: ContentType.CHANGE_CIPHER_SPEC, epoch: this.#writeEpoch, sequenceNumber: this.#writeSeq++, fragment: Buffer.from([1]) });
|
|
534
|
+
this.#writeEpoch = 1;
|
|
535
|
+
this.#writeSeq = 0n;
|
|
536
|
+
|
|
537
|
+
const finishedSeq = this.#writeSeq++;
|
|
538
|
+
const encryptedFinished = encryptRecord({
|
|
539
|
+
writeKey: this.#keys.serverWriteKey, salt: this.#keys.serverWriteIv,
|
|
540
|
+
epoch: this.#writeEpoch, sequenceNumber: finishedSeq, type: ContentType.HANDSHAKE, plaintext: finishedFragments[0],
|
|
541
|
+
});
|
|
542
|
+
const finishedRecord = encodeRecord({ type: ContentType.HANDSHAKE, epoch: this.#writeEpoch, sequenceNumber: finishedSeq, fragment: encryptedFinished });
|
|
543
|
+
|
|
544
|
+
this.#state = 'connected';
|
|
545
|
+
clearTimeout(this.#retransmitTimer);
|
|
546
|
+
clearTimeout(this.#overallTimeoutTimer);
|
|
547
|
+
this.#transmitFlight([Buffer.concat([ccsRecord, finishedRecord])]);
|
|
548
|
+
this.emit('connected');
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
#packHandshakeMessage(msgType, body) {
|
|
552
|
+
const seq = this.#messageSeq++;
|
|
553
|
+
const fragments = encodeHandshakeMessage({ msgType, messageSeq: seq, body });
|
|
554
|
+
this.#handshakeMessages.push(logicalHandshakeBytes({ msgType, messageSeq: seq, body }));
|
|
555
|
+
return Buffer.concat(fragments.map((f) => encodeRecord({ type: ContentType.HANDSHAKE, epoch: this.#writeEpoch, sequenceNumber: this.#writeSeq++, fragment: f })));
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
#transmitFlight(datagrams) {
|
|
559
|
+
this.#lastFlightDatagrams = datagrams;
|
|
560
|
+
this.#retransmitAttempt = 0;
|
|
561
|
+
for (const d of datagrams) this.#sendDatagram(d);
|
|
562
|
+
this.#armRetransmit();
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
#armRetransmit() {
|
|
566
|
+
clearTimeout(this.#retransmitTimer);
|
|
567
|
+
if (this.#state === 'connected' || this.#state === 'closed') return;
|
|
568
|
+
const timeout = RETRANSMIT_TIMEOUTS_MS[Math.min(this.#retransmitAttempt, RETRANSMIT_TIMEOUTS_MS.length - 1)];
|
|
569
|
+
this.#retransmitTimer = setTimeout(() => {
|
|
570
|
+
this.#retransmitAttempt += 1;
|
|
571
|
+
for (const d of this.#lastFlightDatagrams) this.#sendDatagram(d);
|
|
572
|
+
this.#armRetransmit();
|
|
573
|
+
}, timeout);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
#fail(err) {
|
|
577
|
+
this.#state = 'closed';
|
|
578
|
+
clearTimeout(this.#retransmitTimer);
|
|
579
|
+
clearTimeout(this.#overallTimeoutTimer);
|
|
580
|
+
this.emit('error', err);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { createHmac } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
function pHashSha256(secret, seed, length) {
|
|
4
|
+
const out = [];
|
|
5
|
+
let outLen = 0;
|
|
6
|
+
let a = seed;
|
|
7
|
+
while (outLen < length) {
|
|
8
|
+
a = createHmac('sha256', secret).update(a).digest();
|
|
9
|
+
const chunk = createHmac('sha256', secret).update(Buffer.concat([a, seed])).digest();
|
|
10
|
+
out.push(chunk);
|
|
11
|
+
outLen += chunk.length;
|
|
12
|
+
}
|
|
13
|
+
return Buffer.concat(out).subarray(0, length);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function prf(secret, label, seed, length) {
|
|
17
|
+
return pHashSha256(secret, Buffer.concat([Buffer.from(label, 'ascii'), seed]), length);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function deriveMasterSecret(preMasterSecret, clientRandom, serverRandom) {
|
|
21
|
+
return prf(preMasterSecret, 'master secret', Buffer.concat([clientRandom, serverRandom]), 48);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function deriveKeyBlock(masterSecret, clientRandom, serverRandom, { keyLen, fixedIvLen }) {
|
|
25
|
+
const needed = 2 * keyLen + 2 * fixedIvLen;
|
|
26
|
+
const block = prf(masterSecret, 'key expansion', Buffer.concat([serverRandom, clientRandom]), needed);
|
|
27
|
+
let offset = 0;
|
|
28
|
+
const take = (n) => { const b = block.subarray(offset, offset + n); offset += n; return b; };
|
|
29
|
+
return {
|
|
30
|
+
clientWriteKey: take(keyLen),
|
|
31
|
+
serverWriteKey: take(keyLen),
|
|
32
|
+
clientWriteIv: take(fixedIvLen),
|
|
33
|
+
serverWriteIv: take(fixedIvLen),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function deriveVerifyData(masterSecret, label, handshakeHash) {
|
|
38
|
+
return prf(masterSecret, label, handshakeHash, 12);
|
|
39
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
|
|
2
|
+
export const ContentType = Object.freeze({
|
|
3
|
+
CHANGE_CIPHER_SPEC: 20,
|
|
4
|
+
ALERT: 21,
|
|
5
|
+
HANDSHAKE: 22,
|
|
6
|
+
APPLICATION_DATA: 23,
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
export const DTLS_1_2_VERSION = Buffer.from([0xfe, 0xfd]);
|
|
10
|
+
|
|
11
|
+
const RECORD_HEADER_LEN = 13;
|
|
12
|
+
|
|
13
|
+
export function encodeEpochSeq(epoch, sequenceNumber) {
|
|
14
|
+
const buf = Buffer.alloc(8);
|
|
15
|
+
buf.writeUInt16BE(epoch, 0);
|
|
16
|
+
|
|
17
|
+
buf.writeUIntBE(Number(sequenceNumber & 0xffffffffffffn), 2, 6);
|
|
18
|
+
return buf;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function decodeEpochSeq(buf) {
|
|
22
|
+
const epoch = buf.readUInt16BE(0);
|
|
23
|
+
const sequenceNumber = BigInt(buf.readUIntBE(2, 6));
|
|
24
|
+
return { epoch, sequenceNumber };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function encodeRecord({ type, epoch, sequenceNumber, fragment }) {
|
|
28
|
+
const header = Buffer.alloc(RECORD_HEADER_LEN);
|
|
29
|
+
header.writeUInt8(type, 0);
|
|
30
|
+
DTLS_1_2_VERSION.copy(header, 1);
|
|
31
|
+
encodeEpochSeq(epoch, sequenceNumber).copy(header, 3);
|
|
32
|
+
header.writeUInt16BE(fragment.length, 11);
|
|
33
|
+
return Buffer.concat([header, fragment]);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function decodeRecords(datagram) {
|
|
37
|
+
const records = [];
|
|
38
|
+
let offset = 0;
|
|
39
|
+
while (offset + RECORD_HEADER_LEN <= datagram.length) {
|
|
40
|
+
const type = datagram.readUInt8(offset);
|
|
41
|
+
|
|
42
|
+
const { epoch, sequenceNumber } = decodeEpochSeq(datagram.subarray(offset + 3, offset + 11));
|
|
43
|
+
const length = datagram.readUInt16BE(offset + 11);
|
|
44
|
+
const fragmentStart = offset + RECORD_HEADER_LEN;
|
|
45
|
+
const fragmentEnd = fragmentStart + length;
|
|
46
|
+
if (fragmentEnd > datagram.length) break;
|
|
47
|
+
records.push({
|
|
48
|
+
type,
|
|
49
|
+
epoch,
|
|
50
|
+
sequenceNumber,
|
|
51
|
+
fragment: datagram.subarray(fragmentStart, fragmentEnd),
|
|
52
|
+
});
|
|
53
|
+
offset = fragmentEnd;
|
|
54
|
+
}
|
|
55
|
+
return records;
|
|
56
|
+
}
|