noxtls 0.2.10

TLS/DTLS protocol and connection state machine for the noxtls Rust stack.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
// Copyright (c) 2019-2026, Argenox Technologies LLC
// All rights reserved.
//
// SPDX-License-Identifier: GPL-2.0-only OR LicenseRef-Argenox-Commercial-License
//
// This file is part of the NoxTLS Library.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by the
// Free Software Foundation; version 2 of the License.
//
// Alternatively, this file may be used under the terms of a commercial
// license from Argenox Technologies LLC.
//
// See `noxtls/LICENSE` and `noxtls/LICENSE.md` in this repository for full details.
// CONTACT: info@argenox.com

//! DTLS 1.3 record protection, active-flight tracking, and retransmit orchestration.

use super::*;

impl Connection {
    /// Installs DTLS1.3-style traffic keys and static IVs used for protected records.
    ///
    /// # Returns
    ///
    /// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
    ///
    /// # Arguments
    /// * `client_key`: Outbound client write key (AES-128-GCM).
    /// * `client_iv`: Outbound client static IV.
    /// * `server_key`: Inbound server write key (AES-128-GCM).
    /// * `server_iv`: Inbound server static IV.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_install_dtls13_traffic_keys(
        &mut self,
        client_key: [u8; 16],
        client_iv: [u8; 12],
        server_key: [u8; 16],
        server_iv: [u8; 12],
    ) -> Result<()> {
        self.noxtls_ensure_dtls13_mode()?;
        self.dtls13_client_write_key = Some(client_key);
        self.dtls13_client_write_iv = Some(client_iv);
        self.dtls13_server_write_key = Some(server_key);
        self.dtls13_server_write_iv = Some(server_iv);
        self.dtls13_inbound_replay_tracker = DtlsEpochReplayTracker::noxtls_new();
        self.dtls13_client_inbound_replay_tracker = DtlsEpochReplayTracker::noxtls_new();
        self.dtls13_pending_ack_ranges.clear();
        Ok(())
    }

    /// Returns the installed DTLS 1.3 AES-128-GCM **server** handshake write key and IV.
    ///
    /// Populated after [`Self::noxtls_derive_handshake_secret`] (or equivalent record-protection install)
    /// for TLS 1.3 / DTLS 1.3. Intended for harnesses that seal synthetic server handshake records
    /// with the same material [`Self::noxtls_open_dtls13_record`] expects.
    ///
    /// # Arguments
    ///
    /// * `&self` — `&self`.
    ///
    /// # Returns
    ///
    /// `Ok((key, iv))` when both values are installed.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when the connection is not DTLS 1.3 or keys are absent.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_dtls13_handshake_server_write_material(&self) -> Result<([u8; 16], [u8; 12])> {
        self.noxtls_ensure_dtls13_mode()?;
        let key = self.dtls13_server_write_key.ok_or(Error::StateError(
            "dtls13 server write key is not installed",
        ))?;
        let iv = self
            .dtls13_server_write_iv
            .ok_or(Error::StateError("dtls13 server write iv is not installed"))?;
        Ok((key, iv))
    }

    /// Sets the negotiated DTLS 1.3 Connection IDs used for inbound and outbound records.
    pub fn noxtls_set_dtls13_connection_ids(
        &mut self,
        inbound_connection_id: &[u8],
        outbound_connection_id: &[u8],
    ) -> Result<()> {
        self.noxtls_set_dtls13_inbound_connection_id(inbound_connection_id)?;
        self.noxtls_set_dtls13_outbound_connection_id(outbound_connection_id)
    }

    /// Sets the DTLS 1.3 Connection ID expected on inbound protected records.
    pub fn noxtls_set_dtls13_inbound_connection_id(&mut self, connection_id: &[u8]) -> Result<()> {
        self.noxtls_ensure_dtls13_mode()?;
        if connection_id.len() > u8::MAX as usize {
            return Err(Error::InvalidLength(
                "dtls13 inbound connection id is too long",
            ));
        }
        self.dtls13_inbound_connection_id.clear();
        self.dtls13_inbound_connection_id
            .extend_from_slice(connection_id);
        Ok(())
    }

    /// Sets the DTLS 1.3 Connection ID emitted on outbound protected records.
    pub fn noxtls_set_dtls13_outbound_connection_id(&mut self, connection_id: &[u8]) -> Result<()> {
        self.noxtls_ensure_dtls13_mode()?;
        if connection_id.len() > u8::MAX as usize {
            return Err(Error::InvalidLength(
                "dtls13 outbound connection id is too long",
            ));
        }
        self.dtls13_outbound_connection_id.clear();
        self.dtls13_outbound_connection_id
            .extend_from_slice(connection_id);
        Ok(())
    }

    /// Returns the DTLS 1.3 Connection ID expected on inbound protected records.
    #[must_use]
    pub fn noxtls_dtls13_inbound_connection_id(&self) -> &[u8] {
        &self.dtls13_inbound_connection_id
    }

    /// Returns the DTLS 1.3 Connection ID emitted on outbound protected records.
    #[must_use]
    pub fn noxtls_dtls13_outbound_connection_id(&self) -> &[u8] {
        &self.dtls13_outbound_connection_id
    }

    /// Sets the outbound DTLS epoch and resets per-epoch sequence to zero.
    ///
    /// # Returns
    ///
    /// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
    ///
    /// # Arguments
    /// * `epoch`: New outbound epoch value.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_set_dtls13_outbound_epoch(&mut self, epoch: u16) -> Result<()> {
        self.noxtls_ensure_dtls13_mode()?;
        if !self.dtls13_active_flight.is_empty()
            && !self.noxtls_is_dtls13_active_flight_complete()?
        {
            return Err(Error::StateError(
                "cannot change dtls13 outbound epoch while active flight is incomplete",
            ));
        }
        if epoch < self.dtls13_outbound_epoch {
            return Err(Error::StateError("dtls13 outbound epoch must be monotonic"));
        }
        self.dtls13_outbound_epoch = epoch;
        self.dtls13_outbound_sequence = 0;
        Ok(())
    }

    /// Seals one DTLS1.3 protected record with installed client traffic keys.
    ///
    /// # Arguments
    /// * `plaintext`: Payload bytes to encrypt.
    ///
    /// # Returns
    /// Serialized DTLS packet (`header || ciphertext || tag`).
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_seal_dtls13_record(&mut self, plaintext: &[u8]) -> Result<Vec<u8>> {
        self.noxtls_ensure_dtls13_mode()?;
        self.noxtls_ensure_dtls13_tx_sequence_available()?;
        let key = self.dtls13_client_write_key.ok_or(Error::StateError(
            "dtls13 client write key is not installed",
        ))?;
        let iv = self
            .dtls13_client_write_iv
            .ok_or(Error::StateError("dtls13 client write iv is not installed"))?;
        let packet = noxtls_seal_dtls13_aes128gcm_record(
            self.dtls13_outbound_epoch,
            self.dtls13_outbound_sequence,
            &key,
            &iv,
            plaintext,
        )?;
        self.dtls13_outbound_sequence = self.dtls13_outbound_sequence.saturating_add(1);
        Ok(packet)
    }

    /// Seals one DTLS1.3 protected record and schedules it for retransmission.
    ///
    /// # Arguments
    /// * `plaintext`: Payload bytes to encrypt.
    /// * `now_ms`: Current monotonic timestamp in milliseconds.
    ///
    /// # Returns
    /// Serialized DTLS packet (`header || ciphertext || tag`) tracked in retransmit state.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_seal_dtls13_record_for_flight(
        &mut self,
        plaintext: &[u8],
        now_ms: u64,
    ) -> Result<Vec<u8>> {
        self.noxtls_ensure_dtls13_mode()?;
        let packet = self.noxtls_seal_dtls13_record(plaintext)?;
        let (header, _payload) = noxtls_parse_dtls_record_packet(&packet)?;
        self.dtls_retransmit_tracker.track_outbound_with_schedule(
            header.epoch,
            header.sequence,
            &packet,
            now_ms,
            self.dtls_retransmit_initial_timeout_ms,
        )?;
        Ok(packet)
    }

    /// Seals a DTLS1.3 multi-record flight and schedules each packet for retransmission.
    ///
    /// # Arguments
    /// * `plaintext_records`: Ordered plaintext payloads to seal as individual DTLS packets.
    /// * `now_ms`: Current monotonic timestamp in milliseconds.
    ///
    /// # Returns
    /// Ordered serialized DTLS packets tracked in retransmit state.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_seal_dtls13_record_flight(
        &mut self,
        plaintext_records: &[&[u8]],
        now_ms: u64,
    ) -> Result<Vec<Vec<u8>>> {
        self.noxtls_ensure_dtls13_mode()?;
        if plaintext_records.is_empty() {
            return Err(Error::InvalidLength(
                "dtls13 record flight must contain at least one payload",
            ));
        }
        let mut packets = Vec::with_capacity(plaintext_records.len());
        for plaintext in plaintext_records {
            packets.push(self.noxtls_seal_dtls13_record_for_flight(plaintext, now_ms)?);
        }
        Ok(packets)
    }

    /// Starts a DTLS1.3 active flight and tracks its packet keys for completion checks.
    ///
    /// # Arguments
    /// * `plaintext_records`: Ordered plaintext payloads to seal as one active flight.
    /// * `now_ms`: Current monotonic timestamp in milliseconds.
    ///
    /// # Returns
    /// Ordered serialized DTLS packets for immediate transmission.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_start_dtls13_active_flight(
        &mut self,
        plaintext_records: &[&[u8]],
        now_ms: u64,
    ) -> Result<Vec<Vec<u8>>> {
        self.noxtls_ensure_dtls13_mode()?;
        if !self.dtls13_active_flight.is_empty()
            && !self.noxtls_is_dtls13_active_flight_complete()?
        {
            return Err(Error::StateError(
                "cannot start noxtls_new dtls13 active flight while previous flight is incomplete",
            ));
        }
        let packets = self.noxtls_seal_dtls13_record_flight(plaintext_records, now_ms)?;
        self.dtls13_active_flight.clear();
        for packet in &packets {
            self.dtls13_active_flight
                .push(self.noxtls_parse_dtls_packet_key(packet)?);
        }
        self.dtls13_active_flight_started_at_ms = Some(now_ms);
        self.noxtls_dtls13_active_flight_failed = false;
        Ok(packets)
    }

    /// Configures timeout budget for DTLS1.3 active-flight completion.
    ///
    /// # Returns
    ///
    /// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
    ///
    /// # Arguments
    /// * `timeout_ms`: Maximum elapsed milliseconds before active flight is considered timed out.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_set_dtls13_active_flight_timeout_ms(&mut self, timeout_ms: u64) -> Result<()> {
        self.noxtls_ensure_dtls13_mode()?;
        self.dtls13_active_flight_timeout_ms = timeout_ms.max(1);
        Ok(())
    }

    /// Opens one DTLS1.3 protected record with installed server traffic keys and replay checks.
    ///
    /// # Arguments
    /// * `packet`: Serialized DTLS protected record.
    ///
    /// # Returns
    /// Parsed DTLS header and decrypted plaintext bytes.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_open_dtls13_record(
        &mut self,
        packet: &[u8],
    ) -> Result<(DtlsRecordHeader, Vec<u8>)> {
        self.noxtls_ensure_dtls13_mode()?;
        let key = self.dtls13_server_write_key.ok_or(Error::StateError(
            "dtls13 server write key is not installed",
        ))?;
        let iv = self
            .dtls13_server_write_iv
            .ok_or(Error::StateError("dtls13 server write iv is not installed"))?;
        match noxtls_open_dtls13_unified_aes128gcm_record_with_cid(
            packet,
            &key,
            &iv,
            &mut self.dtls13_inbound_replay_tracker,
            &self.dtls13_inbound_connection_id,
        ) {
            Ok((header, plaintext)) => Ok((
                DtlsRecordHeader {
                    content_type: RecordContentType::ApplicationData,
                    version: [0xFE, 0xFC],
                    epoch: header.epoch,
                    sequence: header.sequence,
                    length: header.length.unwrap_or(0),
                },
                plaintext,
            )),
            Err(_) => noxtls_open_dtls13_aes128gcm_record(
                packet,
                &key,
                &iv,
                &mut self.dtls13_inbound_replay_tracker,
            ),
        }
    }

    /// Opens one DTLS1.3 protected record using installed client traffic keys.
    ///
    /// This is intended for server-side validation of encrypted client flights.
    ///
    /// # Arguments
    /// * `packet`: Serialized DTLS protected record.
    ///
    /// # Returns
    /// Parsed DTLS header and decrypted plaintext bytes.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_open_dtls13_client_record(
        &mut self,
        packet: &[u8],
    ) -> Result<(DtlsRecordHeader, Vec<u8>)> {
        self.noxtls_ensure_dtls13_mode()?;
        let key = self.dtls13_client_write_key.ok_or(Error::StateError(
            "dtls13 client write key is not installed",
        ))?;
        let iv = self
            .dtls13_client_write_iv
            .ok_or(Error::StateError("dtls13 client write iv is not installed"))?;
        match noxtls_open_dtls13_unified_aes128gcm_record_with_cid(
            packet,
            &key,
            &iv,
            &mut self.dtls13_client_inbound_replay_tracker,
            &self.dtls13_inbound_connection_id,
        ) {
            Ok((header, plaintext)) => Ok((
                DtlsRecordHeader {
                    content_type: RecordContentType::ApplicationData,
                    version: [0xFE, 0xFC],
                    epoch: header.epoch,
                    sequence: header.sequence,
                    length: header.length.unwrap_or(0),
                },
                plaintext,
            )),
            Err(_) => noxtls_open_dtls13_aes128gcm_record(
                packet,
                &key,
                &iv,
                &mut self.dtls13_client_inbound_replay_tracker,
            ),
        }
    }

    /// Processes encrypted DTLS server post-hello handshake flight in strict TLS1.3 message order.
    ///
    /// Expected decrypted sequence:
    /// * `EncryptedExtensions`
    /// * optional `CertificateRequest`
    /// * `Certificate`
    /// * `CertificateVerify`
    /// * `Finished`
    ///
    /// # Arguments
    /// * `packets`: Encrypted DTLS packets carrying one handshake message each.
    ///
    /// # Returns
    /// `Ok(())` when decrypted flight validates and transitions to `Finished`.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_process_dtls13_encrypted_server_flight_after_hello(
        &mut self,
        packets: &[Vec<u8>],
    ) -> Result<()> {
        self.noxtls_ensure_dtls13_mode()?;
        if self.state != HandshakeState::ServerHelloReceived {
            return Err(Error::StateError(
                "dtls13 encrypted server flight requires server hello state",
            ));
        }
        if packets.len() < 4 {
            return Err(Error::ParseFailure(
                "dtls13 encrypted server flight is too short",
            ));
        }
        let installed_server_key = self.dtls13_server_write_key;
        let installed_server_iv = self.dtls13_server_write_iv;
        if self.tls13_server_handshake_traffic_secret.is_none() {
            self.noxtls_derive_handshake_secret()?;
        }
        if installed_server_key.is_some() && installed_server_iv.is_some() {
            self.dtls13_server_write_key = installed_server_key;
            self.dtls13_server_write_iv = installed_server_iv;
        }
        let mut messages = Vec::with_capacity(packets.len());
        for packet in packets {
            let (_header, plaintext) = self.noxtls_open_dtls13_record(packet)?;
            messages.push(plaintext);
        }
        let mut index = 0_usize;
        self.noxtls_recv_encrypted_extensions(&messages[index])?;
        index += 1;
        let (next_type, _) = noxtls_parse_handshake_message(&messages[index])?;
        if next_type == HANDSHAKE_CERTIFICATE_REQUEST {
            self.noxtls_recv_certificate_request(&messages[index])?;
            index += 1;
        }
        self.noxtls_recv_certificate(&messages[index])?;
        index += 1;
        self.noxtls_recv_certificate_verify(&messages[index])?;
        index += 1;
        self.noxtls_recv_finished_message(&messages[index])?;
        index += 1;
        if index != messages.len() {
            return Err(Error::ParseFailure(
                "unexpected trailing dtls13 encrypted server handshake messages",
            ));
        }
        Ok(())
    }

    /// Processes full DTLS server handshake flight from ServerHello through encrypted post-hello flight.
    ///
    /// Expected sequence:
    /// * `ServerHello` (plaintext handshake wrapper)
    /// * encrypted post-hello packets consumed by `noxtls_process_dtls13_encrypted_server_flight_after_hello`
    ///
    /// # Arguments
    /// * `server_hello`: Encoded ServerHello handshake message.
    /// * `encrypted_packets`: Encrypted DTLS packets carrying post-hello server handshake messages.
    ///
    /// # Returns
    /// `Ok(())` when the full flight validates and transitions to `Finished`.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_process_dtls13_full_server_handshake_flight(
        &mut self,
        server_hello: &[u8],
        encrypted_packets: &[Vec<u8>],
    ) -> Result<()> {
        self.noxtls_ensure_dtls13_mode()?;
        self.noxtls_recv_server_hello(server_hello)?;
        self.noxtls_process_dtls13_encrypted_server_flight_after_hello(encrypted_packets)
    }

    /// Processes encrypted DTLS client post-hello handshake flight with strict message ordering.
    ///
    /// Allowed decrypted sequence:
    /// * `Finished`
    /// * `Certificate`, `CertificateVerify`, `Finished`
    ///
    /// # Arguments
    /// * `packets`: Encrypted DTLS packets carrying client post-hello handshake messages.
    ///
    /// # Returns
    /// `Ok(())` when decrypted message ordering is valid.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_process_dtls13_encrypted_client_flight_after_server_hello(
        &mut self,
        packets: &[Vec<u8>],
    ) -> Result<()> {
        self.noxtls_ensure_dtls13_mode()?;
        if packets.is_empty() {
            return Err(Error::ParseFailure(
                "dtls13 encrypted client flight is too short",
            ));
        }
        let mut message_types = Vec::with_capacity(packets.len());
        for packet in packets {
            let (_header, plaintext) = self.noxtls_open_dtls13_client_record(packet)?;
            let (handshake_type, _body) = noxtls_parse_handshake_message(&plaintext)?;
            message_types.push(handshake_type);
        }
        if message_types == [HANDSHAKE_FINISHED] {
            return Ok(());
        }
        if message_types
            == [
                HANDSHAKE_CERTIFICATE,
                HANDSHAKE_CERTIFICATE_VERIFY,
                HANDSHAKE_FINISHED,
            ]
        {
            return Ok(());
        }
        Err(Error::ParseFailure(
            "invalid dtls13 encrypted client flight message ordering",
        ))
    }

    /// Builds and schedules one outbound encrypted DTLS1.3 client post-hello handshake flight.
    ///
    /// Allowed plaintext message ordering:
    /// * `Finished`
    /// * `Certificate`, `CertificateVerify`, `Finished`
    ///
    /// # Arguments
    /// * `messages`: Ordered encoded handshake messages for one outbound client flight.
    /// * `now_ms`: Current monotonic timestamp in milliseconds.
    ///
    /// # Returns
    /// Encrypted DTLS packets tracked as the current active flight.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_build_dtls13_encrypted_client_flight_after_server_hello(
        &mut self,
        messages: &[Vec<u8>],
        now_ms: u64,
    ) -> Result<Vec<Vec<u8>>> {
        self.noxtls_ensure_dtls13_mode()?;
        if self.state != HandshakeState::ServerHelloReceived
            && self.state != HandshakeState::ServerCertificateVerified
            && self.state != HandshakeState::KeysDerived
        {
            return Err(Error::StateError(
                "dtls13 encrypted client flight requires post-server-hello state",
            ));
        }
        self.noxtls_validate_dtls13_client_post_hello_flight_order(messages)?;
        let plaintext_refs: Vec<&[u8]> = messages.iter().map(Vec::as_slice).collect();
        self.noxtls_start_dtls13_active_flight(&plaintext_refs, now_ms)
    }

    /// Advances outbound DTLS epoch and resets per-epoch record sequence counter.
    ///
    /// # Arguments
    ///
    /// * `self` — `&mut self`.
    ///
    /// # Returns
    /// New outbound epoch value.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_advance_dtls13_outbound_epoch(&mut self) -> Result<u16> {
        self.noxtls_ensure_dtls13_mode()?;
        if !self.dtls13_active_flight.is_empty()
            && !self.noxtls_is_dtls13_active_flight_complete()?
        {
            return Err(Error::StateError(
                "cannot advance dtls13 outbound epoch while active flight is incomplete",
            ));
        }
        if self.dtls13_outbound_epoch == u16::MAX {
            return Err(Error::StateError("dtls13 outbound epoch exhausted"));
        }
        self.dtls13_outbound_epoch = self.dtls13_outbound_epoch.saturating_add(1);
        self.dtls13_outbound_sequence = 0;
        Ok(self.dtls13_outbound_epoch)
    }

    /// Opens a locally sealed DTLS1.3 protected record using installed client traffic keys.
    ///
    /// This loopback helper is intended for local validation paths where records were produced
    /// by `noxtls_seal_dtls13_record` on the same connection instance.
    /// # Arguments
    ///
    /// * `&self` — `&self`.
    /// * `packet` — `packet: &[u8]`.
    ///
    /// # Returns
    ///
    /// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_open_own_dtls13_record(
        &self,
        packet: &[u8],
    ) -> Result<(DtlsRecordHeader, Vec<u8>)> {
        self.noxtls_ensure_dtls13_mode()?;
        let key = self.dtls13_client_write_key.ok_or(Error::StateError(
            "dtls13 client write key is not installed",
        ))?;
        let iv = self
            .dtls13_client_write_iv
            .ok_or(Error::StateError("dtls13 client write iv is not installed"))?;
        let mut replay_tracker = DtlsEpochReplayTracker::noxtls_new();
        match noxtls_open_dtls13_unified_aes128gcm_record_with_cid(
            packet,
            &key,
            &iv,
            &mut replay_tracker,
            &self.dtls13_outbound_connection_id,
        ) {
            Ok((header, plaintext)) => Ok((
                DtlsRecordHeader {
                    content_type: RecordContentType::ApplicationData,
                    version: [0xFE, 0xFC],
                    epoch: header.epoch,
                    sequence: header.sequence,
                    length: header.length.unwrap_or(0),
                },
                plaintext,
            )),
            Err(_) => {
                let mut legacy_replay_tracker = DtlsEpochReplayTracker::noxtls_new();
                noxtls_open_dtls13_aes128gcm_record(packet, &key, &iv, &mut legacy_replay_tracker)
            }
        }
    }

    /// Marks a tracked DTLS outbound packet as acknowledged using parsed record header fields.
    ///
    /// # Arguments
    /// * `packet`: DTLS record packet containing epoch/sequence metadata.
    ///
    /// # Returns
    /// `true` when matching tracked packet is found and marked acknowledged.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_mark_dtls13_record_acked_from_packet(&mut self, packet: &[u8]) -> Result<bool> {
        self.noxtls_ensure_dtls13_mode()?;
        let key = self.noxtls_parse_dtls_packet_key(packet)?;
        Ok(self.dtls_retransmit_tracker.mark_acked(key.0, key.1))
    }

    /// Marks every DTLS packet in one flight as acknowledged using packet headers.
    ///
    /// # Arguments
    /// * `packets`: DTLS packets that belong to one outbound flight.
    ///
    /// # Returns
    /// Count of packets that matched tracked records and were marked acknowledged.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_mark_dtls13_flight_acked_from_packets(
        &mut self,
        packets: &[Vec<u8>],
    ) -> Result<usize> {
        self.noxtls_ensure_dtls13_mode()?;
        let mut marked = 0_usize;
        for packet in packets {
            if self.noxtls_mark_dtls13_record_acked_from_packet(packet)? {
                marked = marked.saturating_add(1);
            }
        }
        Ok(marked)
    }

    /// Polls retransmit scheduler for due packets belonging to the current active flight.
    ///
    /// # Arguments
    /// * `now_ms`: Current monotonic timestamp in milliseconds.
    ///
    /// # Returns
    /// Due packets that should be resent for active-flight completion.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_poll_dtls13_active_flight_due_packets(
        &mut self,
        now_ms: u64,
    ) -> Result<Vec<Vec<u8>>> {
        self.noxtls_ensure_dtls13_mode()?;
        if self.dtls13_active_flight.is_empty() {
            return Ok(Vec::new());
        }
        if self.noxtls_dtls13_active_flight_has_timed_out(now_ms) {
            let _ = self.noxtls_abort_dtls13_active_flight()?;
            return Err(Error::StateError(
                "dtls13 active flight timed out before completion",
            ));
        }
        if self.noxtls_dtls13_active_flight_missing_tracked_records() {
            self.dtls13_active_flight.clear();
            self.dtls13_active_flight_started_at_ms = None;
            self.noxtls_dtls13_active_flight_failed = true;
            return Err(Error::StateError(
                "dtls13 active flight failed after retransmit budget exhausted",
            ));
        }
        let due_packets = self.noxtls_poll_dtls12_due_retransmit_packets(now_ms)?;
        let mut filtered = Vec::new();
        for packet in due_packets {
            let key = self.noxtls_parse_dtls_packet_key(&packet)?;
            if self.dtls13_active_flight.contains(&key) {
                filtered.push(packet);
            }
        }
        if self.noxtls_dtls13_active_flight_missing_tracked_records() {
            self.dtls13_active_flight.clear();
            self.dtls13_active_flight_started_at_ms = None;
            self.noxtls_dtls13_active_flight_failed = true;
            return Err(Error::StateError(
                "dtls13 active flight failed after retransmit budget exhausted",
            ));
        }
        Ok(filtered)
    }

    /// Acknowledges packets for the current active DTLS1.3 flight and prunes acked records.
    ///
    /// # Arguments
    /// * `packets`: Acked DTLS packets for this flight.
    ///
    /// # Returns
    /// Number of active-flight packets newly marked acknowledged.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_acknowledge_dtls13_active_flight_packets(
        &mut self,
        packets: &[Vec<u8>],
    ) -> Result<usize> {
        self.noxtls_ensure_dtls13_mode()?;
        if self.dtls13_active_flight.is_empty() {
            return Ok(0);
        }
        let mut marked = 0_usize;
        for packet in packets {
            let key = self.noxtls_parse_dtls_packet_key(packet)?;
            if !self.dtls13_active_flight.contains(&key) {
                continue;
            }
            if self.noxtls_mark_dtls12_record_acked(key.0, key.1)? {
                marked = marked.saturating_add(1);
            }
        }
        let _ = self.noxtls_prune_dtls12_acked_records()?;
        if self.noxtls_is_dtls13_active_flight_complete()? {
            self.dtls13_active_flight.clear();
            self.dtls13_active_flight_started_at_ms = None;
            self.noxtls_dtls13_active_flight_failed = false;
        }
        Ok(marked)
    }

    /// Aborts the current active DTLS1.3 flight and removes its retransmit obligations.
    ///
    /// # Arguments
    ///
    /// * `self` — `&mut self`.
    ///
    /// # Returns
    /// Number of active-flight records removed from retransmit tracking.
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_abort_dtls13_active_flight(&mut self) -> Result<usize> {
        self.noxtls_ensure_dtls13_mode()?;
        if self.dtls13_active_flight.is_empty() {
            return Ok(0);
        }
        for (epoch, sequence) in &self.dtls13_active_flight {
            let _ = self.dtls_retransmit_tracker.mark_acked(*epoch, *sequence);
        }
        let removed = self.noxtls_prune_dtls12_acked_records()?;
        self.dtls13_active_flight.clear();
        self.dtls13_active_flight_started_at_ms = None;
        self.noxtls_dtls13_active_flight_failed = false;
        Ok(removed)
    }

    /// Reports whether the most recent active DTLS1.3 flight failed due to retry budget exhaustion.
    #[must_use]
    /// # Arguments
    ///
    /// * `&self` — `&self`.
    ///
    /// # Returns
    ///
    /// `true` or `false` according to the checks in the function body.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_dtls13_active_flight_failed(&self) -> bool {
        self.noxtls_dtls13_active_flight_failed
    }

    /// Reports whether all packets from the current active DTLS1.3 flight are complete.
    ///
    /// A flight is complete when no tracked unacknowledged retransmit record remains
    /// for any packet key registered in `noxtls_start_dtls13_active_flight`.
    /// # Arguments
    ///
    /// * `&self` — `&self`.
    ///
    /// # Returns
    ///
    /// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub fn noxtls_is_dtls13_active_flight_complete(&self) -> Result<bool> {
        self.noxtls_ensure_dtls13_mode()?;
        if self.dtls13_active_flight.is_empty() {
            return Ok(true);
        }
        for (epoch, sequence) in &self.dtls13_active_flight {
            let still_pending = self.dtls_retransmit_tracker.records().iter().any(|record| {
                record.epoch == *epoch && record.sequence == *sequence && !record.acknowledged
            });
            if still_pending {
                return Ok(false);
            }
        }
        Ok(true)
    }

    /// Parses `(epoch, sequence)` key used for DTLS retransmit record correlation.
    ///
    /// # Arguments
    ///
    /// * `&self` — `&self`.
    /// * `packet` — `packet: &[u8]`.
    ///
    /// # Returns
    ///
    /// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    fn noxtls_parse_dtls_packet_key(&self, packet: &[u8]) -> Result<(u16, u64)> {
        for cid_len in [
            self.dtls13_outbound_connection_id.len(),
            self.dtls13_inbound_connection_id.len(),
            0,
        ] {
            if let Ok((header, _payload)) =
                noxtls_parse_dtls13_record_packet_with_cid_len(packet, cid_len)
            {
                return Ok((header.epoch, header.sequence));
            }
        }
        let (header, _payload) = noxtls_parse_dtls_record_packet(packet)?;
        Ok((header.epoch, header.sequence))
    }

    /// Reports whether active-flight elapsed time exceeded configured timeout budget.
    ///
    /// # Arguments
    ///
    /// * `&self` — `&self`.
    /// * `now_ms` — `now_ms: u64`.
    ///
    /// # Returns
    ///
    /// `true` or `false` according to the checks in the function body.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    fn noxtls_dtls13_active_flight_has_timed_out(&self, now_ms: u64) -> bool {
        let Some(started_at_ms) = self.dtls13_active_flight_started_at_ms else {
            return false;
        };
        now_ms.saturating_sub(started_at_ms) > self.dtls13_active_flight_timeout_ms
    }

    /// Returns true when active-flight keys no longer exist in retransmit tracker records.
    ///
    /// # Arguments
    ///
    /// * `&self` — `&self`.
    ///
    /// # Returns
    ///
    /// `true` or `false` according to the checks in the function body.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    fn noxtls_dtls13_active_flight_missing_tracked_records(&self) -> bool {
        self.dtls13_active_flight.iter().any(|(epoch, sequence)| {
            !self
                .dtls_retransmit_tracker
                .records()
                .iter()
                .any(|record| record.epoch == *epoch && record.sequence == *sequence)
        })
    }

    /// Validates allowed DTLS1.3 client post-hello flight message ordering.
    ///
    /// # Arguments
    ///
    /// * `&self` — `&self`.
    /// * `messages` — `messages: &[Vec<u8>]`.
    ///
    /// # Returns
    ///
    /// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    fn noxtls_validate_dtls13_client_post_hello_flight_order(
        &self,
        messages: &[Vec<u8>],
    ) -> Result<()> {
        if messages.is_empty() {
            return Err(Error::InvalidLength(
                "dtls13 encrypted client flight must contain at least one message",
            ));
        }
        let mut message_types = Vec::with_capacity(messages.len());
        for message in messages {
            let (handshake_type, _body) = noxtls_parse_handshake_message(message)?;
            message_types.push(handshake_type);
        }
        if message_types == [HANDSHAKE_FINISHED] {
            return Ok(());
        }
        if message_types
            == [
                HANDSHAKE_CERTIFICATE,
                HANDSHAKE_CERTIFICATE_VERIFY,
                HANDSHAKE_FINISHED,
            ]
        {
            return Ok(());
        }
        Err(Error::ParseFailure(
            "invalid dtls13 client post-hello flight message ordering",
        ))
    }

    /// Processes one inbound DTLS 1.3 datagram and emits transport-level events.
    pub fn process_dtls13_datagram(
        &mut self,
        input: &[u8],
        _now_ms: u64,
    ) -> Result<Vec<Dtls13TransportEvent>> {
        self.noxtls_ensure_dtls13_mode()?;
        if input.is_empty() {
            return Ok(vec![Dtls13TransportEvent::DatagramIgnored]);
        }
        let (header, plaintext) = match self.tls_role {
            TlsRole::Client => {
                let key = self.dtls13_server_write_key.ok_or(Error::StateError(
                    "dtls13 server write key is not installed",
                ))?;
                let iv = self
                    .dtls13_server_write_iv
                    .ok_or(Error::StateError("dtls13 server write iv is not installed"))?;
                noxtls_open_dtls13_unified_aes128gcm_record_with_cid(
                    input,
                    &key,
                    &iv,
                    &mut self.dtls13_inbound_replay_tracker,
                    &self.dtls13_inbound_connection_id,
                )?
            }
            TlsRole::Server => {
                let key = self.dtls13_client_write_key.ok_or(Error::StateError(
                    "dtls13 client write key is not installed",
                ))?;
                let iv = self
                    .dtls13_client_write_iv
                    .ok_or(Error::StateError("dtls13 client write iv is not installed"))?;
                noxtls_open_dtls13_unified_aes128gcm_record_with_cid(
                    input,
                    &key,
                    &iv,
                    &mut self.dtls13_client_inbound_replay_tracker,
                    &self.dtls13_inbound_connection_id,
                )?
            }
        };
        self.noxtls_track_dtls13_ack_candidate(header);
        let mut events = Vec::new();
        match noxtls_parse_handshake_message(&plaintext) {
            Ok((DTLS13_HANDSHAKE_ACK, body)) => {
                let ranges = noxtls_parse_dtls13_ack(body)?;
                let _ = noxtls_apply_dtls13_ack_ranges(&mut self.dtls_retransmit_tracker, &ranges);
                let _ = self.dtls_retransmit_tracker.prune_acked();
                events.push(Dtls13TransportEvent::Ack(ranges));
            }
            Ok((_handshake_type, _body)) => {
                events.push(Dtls13TransportEvent::Handshake(plaintext));
            }
            Err(_) if plaintext.len() == 2 => {
                events.push(Dtls13TransportEvent::Alert(plaintext));
            }
            Err(_) => {
                events.push(Dtls13TransportEvent::ApplicationData(plaintext));
            }
        }
        Ok(events)
    }

    /// Polls DTLS 1.3 timers and returns outbound retransmits or generated ACK packets.
    pub fn poll_dtls13(&mut self, now_ms: u64) -> Result<Vec<Vec<u8>>> {
        self.noxtls_ensure_dtls13_mode()?;
        let mut out = Vec::new();
        if !self.dtls13_pending_ack_ranges.is_empty() {
            let ack_body = noxtls_encode_dtls13_ack(&self.dtls13_pending_ack_ranges)?;
            let ack_message = noxtls_encode_handshake_message(DTLS13_HANDSHAKE_ACK, &ack_body);
            out.push(self.noxtls_seal_dtls13_transport_record(&ack_message)?);
            self.dtls13_pending_ack_ranges.clear();
        }
        out.extend(self.noxtls_poll_dtls13_active_flight_due_packets(now_ms)?);
        Ok(out)
    }

    /// Seals DTLS 1.3 application data into one outbound datagram.
    pub fn write_dtls13_application_data(
        &mut self,
        plaintext: &[u8],
        _now_ms: u64,
    ) -> Result<Vec<Vec<u8>>> {
        self.noxtls_ensure_dtls13_mode()?;
        if self.state != HandshakeState::Finished {
            return Err(Error::StateError(
                "cannot write dtls13 application data before handshake completion",
            ));
        }
        Ok(vec![self.noxtls_seal_dtls13_transport_record(plaintext)?])
    }

    /// Opens one inbound DTLS 1.3 application-data datagram.
    pub fn read_dtls13_application_data(
        &mut self,
        datagram: &[u8],
        now_ms: u64,
    ) -> Result<Vec<Vec<u8>>> {
        self.noxtls_ensure_dtls13_mode()?;
        if self.state != HandshakeState::Finished {
            return Err(Error::StateError(
                "cannot read dtls13 application data before handshake completion",
            ));
        }
        let mut records = Vec::new();
        for event in self.process_dtls13_datagram(datagram, now_ms)? {
            if let Dtls13TransportEvent::ApplicationData(plaintext) = event {
                records.push(plaintext);
            }
        }
        Ok(records)
    }

    fn noxtls_seal_dtls13_transport_record(&mut self, plaintext: &[u8]) -> Result<Vec<u8>> {
        self.noxtls_ensure_dtls13_tx_sequence_available()?;
        let (key, iv) = match self.tls_role {
            TlsRole::Client => (
                self.dtls13_client_write_key.ok_or(Error::StateError(
                    "dtls13 client write key is not installed",
                ))?,
                self.dtls13_client_write_iv
                    .ok_or(Error::StateError("dtls13 client write iv is not installed"))?,
            ),
            TlsRole::Server => (
                self.dtls13_server_write_key.ok_or(Error::StateError(
                    "dtls13 server write key is not installed",
                ))?,
                self.dtls13_server_write_iv
                    .ok_or(Error::StateError("dtls13 server write iv is not installed"))?,
            ),
        };
        let packet = noxtls_seal_dtls13_unified_aes128gcm_record_with_cid(
            self.dtls13_outbound_epoch,
            self.dtls13_outbound_sequence,
            &key,
            &iv,
            plaintext,
            &self.dtls13_outbound_connection_id,
        )?;
        self.dtls13_outbound_sequence = self.dtls13_outbound_sequence.saturating_add(1);
        Ok(packet)
    }

    fn noxtls_track_dtls13_ack_candidate(&mut self, header: Dtls13RecordHeader) {
        let range = Dtls13AckRange {
            epoch: header.epoch,
            start_sequence: header.sequence,
            end_sequence: header.sequence,
        };
        if self.dtls13_pending_ack_ranges.contains(&range) {
            return;
        }
        self.dtls13_pending_ack_ranges.push(range);
    }

    /// Ensures DTLS1.3 packet APIs are used only for DTLS profiles.
    ///
    /// # Arguments
    ///
    /// * `&self` — `&self`.
    ///
    /// # Returns
    ///
    /// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    fn noxtls_ensure_dtls13_mode(&self) -> Result<()> {
        if !self.version.is_dtls() {
            return Err(Error::StateError("dtls13 APIs require DTLS connection"));
        }
        Ok(())
    }

    /// Ensures DTLS outbound record sequence space remains available before sealing.
    ///
    /// # Arguments
    ///
    /// * `&self` — `&self`.
    ///
    /// # Returns
    ///
    /// On success, the `Ok` payload described by the return type; see the function body for the concrete value.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when inputs or handshake state invalidate the operation; see the function body for specific error construction sites.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    fn noxtls_ensure_dtls13_tx_sequence_available(&self) -> Result<()> {
        if self.dtls13_outbound_sequence > DTLS13_MAX_SEQUENCE {
            return Err(Error::StateError(
                "dtls13 outbound record sequence exhausted",
            ));
        }
        Ok(())
    }

    /// Mirrors installed record-protection keys into DTLS1.3 traffic state when using DTLS profile.
    ///
    /// # Arguments
    ///
    /// * `self` — `&mut self`.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    ///
    pub(crate) fn noxtls_sync_dtls13_traffic_keys_from_record_protection_state(&mut self) {
        if !self.version.is_dtls() {
            return;
        }
        self.dtls13_client_write_key = self.client_write_key.map(|full| {
            full[..16]
                .try_into()
                .expect("dtls13 shim copies first 16 bytes of traffic key material")
        });
        self.dtls13_client_write_iv = self.client_write_iv;
        self.dtls13_server_write_key = self.server_write_key.map(|full| {
            full[..16]
                .try_into()
                .expect("dtls13 shim copies first 16 bytes of traffic key material")
        });
        self.dtls13_server_write_iv = self.server_write_iv;
        self.dtls13_outbound_epoch = 0;
        self.dtls13_outbound_sequence = 0;
        self.dtls13_inbound_replay_tracker = DtlsEpochReplayTracker::noxtls_new();
        self.dtls13_client_inbound_replay_tracker = DtlsEpochReplayTracker::noxtls_new();
        self.dtls13_pending_ack_ranges.clear();
    }
}