noxtls 0.2.11

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
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
// 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

//! TLS 1.3 client-side policy, PSK binder, and early-data helpers.

use super::*;

impl Connection {
    /// Configures SNI server_name value offered in TLS 1.3 ClientHello extension data.
    ///
    /// # Arguments
    /// * `server_name`: `Some(name)` to advertise one DNS host_name value, or `None` to disable.
    ///
    /// # Returns
    /// `Ok(())` when SNI offer policy is stored.
    ///
    /// # 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_tls13_server_name(&mut self, server_name: Option<&str>) -> Result<()> {
        match server_name {
            Some(name) if name.is_empty() => {
                Err(Error::InvalidLength("sni server_name must not be empty"))
            }
            Some(name) if name.len() > u16::MAX as usize => Err(Error::InvalidLength(
                "sni server_name length must not exceed 65535 bytes",
            )),
            Some(name) => {
                if !noxtls_is_valid_sni_dns_name(name) {
                    return Err(Error::ParseFailure("invalid sni server_name"));
                }
                self.tls13_client_server_name = Some(name.to_owned());
                self.noxtls_tls13_server_name_acknowledged = false;
                Ok(())
            }
            None => {
                self.tls13_client_server_name = None;
                self.noxtls_tls13_server_name_acknowledged = false;
                Ok(())
            }
        }
    }

    /// Enables or disables advertising OCSP stapling support via `status_request`.
    ///
    /// # Arguments
    /// * `enabled`: `true` adds `status_request` to generated TLS 1.3 ClientHello extensions.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_set_tls13_request_ocsp_stapling(&mut self, enabled: bool) {
        self.tls13_request_ocsp_stapling = enabled;
    }

    /// Enables RFC 7250 raw-public-key negotiation in ClientHello.
    pub fn noxtls_set_tls13_raw_public_keys_enabled(&mut self, enabled: bool) {
        self.tls13_client_raw_public_keys_enabled = enabled;
        if !enabled {
            self.tls13_expected_server_raw_public_key_der = None;
        }
    }

    /// Configures the expected server raw public key as DER SubjectPublicKeyInfo.
    pub fn noxtls_set_tls13_expected_server_raw_public_key(
        &mut self,
        spki_der: &[u8],
    ) -> Result<()> {
        if spki_der.is_empty() {
            return Err(Error::InvalidLength(
                "raw public key spki must not be empty",
            ));
        }
        noxtls_parse_spki_public_key_info_der(spki_der)?;
        self.tls13_client_raw_public_keys_enabled = true;
        self.tls13_expected_server_raw_public_key_der = Some(spki_der.to_vec());
        Ok(())
    }

    /// Requires a stapled OCSP response in the server certificate entry.
    ///
    /// # Arguments
    /// * `required`: `true` fails handshake when no OCSP staple is present.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_set_tls13_require_ocsp_staple(&mut self, required: bool) {
        self.tls13_require_ocsp_staple = required;
    }

    /// Configures one optional verifier hook for stapled OCSP response payloads.
    ///
    /// # Arguments
    /// * `verifier`: Optional function pointer that classifies one OCSP staple.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_set_tls13_ocsp_staple_verifier(
        &mut self,
        verifier: Option<Tls13OcspStapleVerifier>,
    ) {
        self.tls13_ocsp_staple_verifier = verifier;
    }

    /// Returns the most recently parsed server OCSP staple bytes.
    #[must_use]
    pub fn noxtls_tls13_server_ocsp_staple(&self) -> Option<&[u8]> {
        self.noxtls_tls13_server_ocsp_staple.as_deref()
    }

    /// Reports whether the most recently parsed OCSP staple passed verification policy.
    #[must_use]
    pub fn noxtls_tls13_server_ocsp_staple_verified(&self) -> bool {
        self.noxtls_tls13_server_ocsp_staple_verified
    }

    /// Enables strict policy requiring server_name acknowledgment in EncryptedExtensions.
    ///
    /// # Arguments
    /// * `required`: `true` to fail handshake when SNI was offered but not acknowledged.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_set_tls13_require_server_name_ack(&mut self, required: bool) {
        self.tls13_require_server_name_ack = required;
    }

    /// Reports whether server_name was acknowledged in parsed EncryptedExtensions.
    ///
    /// # Arguments
    /// * `self` — `Connection` carrying TLS 1.3 extension state.
    ///
    /// # Returns
    /// `true` when server_name acknowledgment was parsed from EncryptedExtensions.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_tls13_server_name_acknowledged(&self) -> bool {
        self.noxtls_tls13_server_name_acknowledged
    }

    /// Configures ALPN protocol IDs offered in TLS 1.3 ClientHello extension data.
    ///
    /// # Arguments
    /// * `protocols`: Ordered ALPN protocol IDs to advertise; empty clears configuration.
    ///
    /// # Returns
    /// `Ok(())` when ALPN offer policy is stored.
    ///
    /// # 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_tls13_alpn_protocols(&mut self, protocols: &[&str]) -> Result<()> {
        let mut parsed_protocols = Vec::with_capacity(protocols.len());
        for protocol in protocols {
            if protocol.is_empty() {
                return Err(Error::InvalidLength("alpn protocol must not be empty"));
            }
            if protocol.len() > u8::MAX as usize {
                return Err(Error::InvalidLength(
                    "alpn protocol length must not exceed 255 bytes",
                ));
            }
            let encoded = protocol.as_bytes().to_vec();
            if parsed_protocols.contains(&encoded) {
                return Err(Error::ParseFailure("duplicate alpn protocol"));
            }
            parsed_protocols.push(encoded);
        }
        self.tls13_client_alpn_protocols = parsed_protocols;
        self.noxtls_tls13_selected_alpn_protocol = None;
        Ok(())
    }

    /// Enables or disables advertising PQ key-share groups in TLS 1.3 ClientHello.
    ///
    /// # Arguments
    /// * `enabled`: `true` includes ML-KEM and hybrid key shares; `false` offers only X25519/P-256.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_set_tls13_client_offer_pq_key_shares(&mut self, enabled: bool) {
        self.tls13_client_offer_pq_key_shares = enabled;
    }

    /// Enables or disables advertising ML-DSA in TLS 1.3 signature_algorithms.
    ///
    /// # Arguments
    /// * `enabled`: `true` includes ML-DSA65 (`0x0905`); `false` advertises classical + Ed25519 only.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_set_tls13_client_offer_mldsa_signature(&mut self, enabled: bool) {
        self.tls13_client_offer_mldsa_signature = enabled;
    }

    /// Overrides TLS 1.3 cipher-suite offer order used by ClientHello builders.
    ///
    /// # Arguments
    /// * `suites`: Ordered TLS 1.3 cipher suites to advertise; empty resets to defaults.
    ///
    /// # Returns
    /// `Ok(())` when the suite offer policy is stored.
    ///
    /// # 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_tls13_client_cipher_suites(&mut self, suites: &[CipherSuite]) -> Result<()> {
        if suites.is_empty() {
            self.tls13_client_cipher_suites = None;
            return Ok(());
        }
        let mut ordered = Vec::with_capacity(suites.len());
        for suite in suites {
            if !noxtls_is_tls13_suite(*suite) {
                return Err(Error::ParseFailure(
                    "tls13 client cipher suite override contains non-tls13 suite",
                ));
            }
            if ordered.contains(suite) {
                return Err(Error::ParseFailure(
                    "tls13 client cipher suite override contains duplicates",
                ));
            }
            ordered.push(*suite);
        }
        self.tls13_client_cipher_suites = Some(ordered);
        Ok(())
    }

    /// Configures the client certificate chain and signing key used for TLS 1.3 mTLS.
    pub fn noxtls_configure_tls13_client_identity(
        &mut self,
        certificate_chain_der: &[Vec<u8>],
        signing_key: Tls13ServerIdentityKey,
    ) -> Result<()> {
        if certificate_chain_der.is_empty() {
            return Err(Error::InvalidLength(
                "tls13 client certificate chain must not be empty",
            ));
        }
        let leaf = noxtls_parse_certificate(&certificate_chain_der[0])?;
        self.tls13_client_identity_certificate_chain_der = certificate_chain_der.to_vec();
        self.tls13_client_signing_key = Some(signing_key);
        self.tls13_client_leaf_public_key_der = Some(leaf.subject_public_key);
        Ok(())
    }

    /// Returns ALPN protocol selected by last parsed TLS 1.3 EncryptedExtensions.
    ///
    /// # Arguments
    /// * `self` — `Connection` carrying parsed extension state.
    ///
    /// Builds the TLS 1.3 EndOfEarlyData handshake message.
    #[must_use]
    pub fn noxtls_build_tls13_end_of_early_data() -> Vec<u8> {
        noxtls_encode_handshake_message(HANDSHAKE_END_OF_EARLY_DATA, &[])
    }

    /// Parses EndOfEarlyData, appends it to the transcript, and closes the 0-RTT phase.
    pub fn noxtls_recv_tls13_end_of_early_data(&mut self, msg: &[u8]) -> Result<()> {
        if !self.version.uses_tls13_handshake_semantics() {
            return Err(Error::StateError(
                "EndOfEarlyData is only valid for TLS 1.3 connections",
            ));
        }
        if self.tls13_end_of_early_data_seen {
            return Err(Error::StateError(
                "tls13 EndOfEarlyData was already processed",
            ));
        }
        if !self.tls13_early_data_accepted_in_encrypted_extensions {
            return Err(Error::StateError(
                "tls13 EndOfEarlyData requires accepted early_data",
            ));
        }
        if !matches!(
            self.state,
            HandshakeState::ServerEncryptedExtensionsReceived
                | HandshakeState::ServerCertificateRequestReceived
                | HandshakeState::ServerCertificateReceived
                | HandshakeState::ServerCertificateVerified
                | HandshakeState::KeysDerived
        ) {
            return Err(Error::StateError(
                "tls13 EndOfEarlyData can only be processed after EncryptedExtensions",
            ));
        }
        let (handshake_type, body) = noxtls_parse_handshake_message(msg)?;
        if handshake_type != HANDSHAKE_END_OF_EARLY_DATA {
            return Err(Error::ParseFailure("invalid EndOfEarlyData type"));
        }
        if !body.is_empty() {
            return Err(Error::ParseFailure("EndOfEarlyData body must be empty"));
        }
        self.noxtls_append_transcript(msg);
        self.tls13_end_of_early_data_seen = true;
        Ok(())
    }

    /// Reports whether EndOfEarlyData has closed the TLS 1.3 0-RTT phase.
    #[must_use]
    pub fn noxtls_tls13_end_of_early_data_seen(&self) -> bool {
        self.tls13_end_of_early_data_seen
    }

    /// Enables or disables 0-RTT anti-replay checks for `noxtls_open_tls13_early_data_record`.
    ///
    /// # Arguments
    /// * `enabled`: `true` to reject replay/too-old sequences, `false` to bypass checks.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_set_tls13_early_data_anti_replay_enabled(&mut self, enabled: bool) {
        self.tls13_early_data_anti_replay_enabled = enabled;
        if enabled {
            self.tls13_early_data_replay_window = DtlsReplayWindow::noxtls_new();
        }
    }

    /// Enables strict 0-RTT acceptance gating before early-data record decryption.
    ///
    /// # Arguments
    /// * `required`: `true` requires prior successful ticket-policy acceptance.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_set_tls13_require_early_data_acceptance(&mut self, required: bool) {
        self.tls13_early_data_require_acceptance = required;
        self.tls13_early_data_accepted_psk = None;
        self.tls13_early_data_max_bytes = None;
        self.tls13_early_data_opened_bytes = 0;
        self.tls13_early_data_accepted_in_encrypted_extensions = false;
        self.tls13_end_of_early_data_seen = false;
    }

    /// Applies one pre-tuned operational profile for modeled TLS 1.3 early-data policy.
    ///
    /// # Arguments
    /// * `profile`: Desired profile preset.
    ///
    /// # Returns
    /// `()`.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_set_tls13_early_data_operational_profile(
        &mut self,
        profile: Tls13EarlyDataOperationalProfile,
    ) {
        let policy = match profile {
            Tls13EarlyDataOperationalProfile::Compatibility => Tls13EarlyDataOperationalPolicy {
                require_acceptance: false,
                anti_replay_enabled: false,
            },
            Tls13EarlyDataOperationalProfile::Strict => Tls13EarlyDataOperationalPolicy {
                require_acceptance: true,
                anti_replay_enabled: true,
            },
        };
        self.noxtls_set_tls13_early_data_operational_policy(policy);
    }

    /// Applies explicit operational policy controls for modeled TLS 1.3 early-data handling.
    ///
    /// # Arguments
    /// * `policy`: Policy values for acceptance and anti-replay checks.
    ///
    /// # Returns
    /// `()`.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_set_tls13_early_data_operational_policy(
        &mut self,
        policy: Tls13EarlyDataOperationalPolicy,
    ) {
        self.noxtls_set_tls13_require_early_data_acceptance(policy.require_acceptance);
        self.noxtls_set_tls13_early_data_anti_replay_enabled(policy.anti_replay_enabled);
    }

    /// Returns currently active operational policy for modeled TLS 1.3 early-data handling.
    ///
    /// # Arguments
    /// * `self` — `Connection` carrying early-data policy state.
    ///
    /// # Returns
    /// Current policy values.
    ///
    /// # Panics
    /// This function does not panic.
    #[must_use]
    pub fn noxtls_tls13_early_data_operational_policy(&self) -> Tls13EarlyDataOperationalPolicy {
        Tls13EarlyDataOperationalPolicy {
            require_acceptance: self.tls13_early_data_require_acceptance,
            anti_replay_enabled: self.tls13_early_data_anti_replay_enabled,
        }
    }

    /// Returns counters describing modeled TLS 1.3 early-data accept/reject outcomes.
    ///
    /// # Arguments
    /// * `self` — `Connection` carrying early-data telemetry.
    ///
    /// # Returns
    /// Copy of current early-data telemetry counters.
    ///
    /// # Panics
    /// This function does not panic.
    #[must_use]
    pub fn noxtls_tls13_early_data_telemetry(&self) -> Tls13EarlyDataTelemetry {
        self.noxtls_tls13_early_data_telemetry
    }

    /// Resets modeled TLS 1.3 early-data telemetry counters to zero.
    ///
    /// # Arguments
    /// * `self` — `Connection` with mutable telemetry state.
    ///
    /// # Returns
    /// `()`.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_reset_tls13_early_data_telemetry(&mut self) {
        self.noxtls_tls13_early_data_telemetry = Tls13EarlyDataTelemetry::default();
    }

    /// Exports replay-window state for modeled TLS 1.3 early-data anti-replay continuity.
    ///
    /// # Arguments
    /// * `self` — `Connection` carrying replay-window state.
    ///
    /// # Returns
    /// Serializable replay state snapshot.
    ///
    /// # Panics
    /// This function does not panic.
    #[must_use]
    pub fn noxtls_export_tls13_early_data_replay_state(&self) -> Tls13EarlyDataReplayState {
        let snapshot = self.tls13_early_data_replay_window.snapshot();
        Tls13EarlyDataReplayState {
            latest_sequence: snapshot.latest_sequence,
            bitmap: snapshot.bitmap,
            initialized: snapshot.initialized,
        }
    }

    /// Imports replay-window state for modeled TLS 1.3 early-data anti-replay continuity.
    ///
    /// # Arguments
    /// * `state`: Previously exported replay state snapshot.
    ///
    /// # Returns
    /// `Ok(())` when replay state is imported.
    ///
    /// # Errors
    /// Returns [`noxtls_core::Error`] when called on a non-TLS1.3 connection.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_import_tls13_early_data_replay_state(
        &mut self,
        state: Tls13EarlyDataReplayState,
    ) -> Result<()> {
        if !self.version.uses_tls13_handshake_semantics() {
            return Err(Error::StateError(
                "tls13 early-data replay state requires TLS 1.3 connection",
            ));
        }
        self.tls13_early_data_replay_window
            .restore_from_snapshot(DtlsReplayWindowSnapshot {
                latest_sequence: state.latest_sequence,
                bitmap: state.bitmap,
                initialized: state.initialized,
            });
        Ok(())
    }

    /// Computes TLS 1.3 PSK binder bytes for a truncated ClientHello transcript.
    ///
    /// # Arguments
    /// * `psk`: Candidate PSK bytes to validate.
    /// * `truncated_client_hello`: ClientHello bytes up to (but excluding) binder list.
    ///
    /// # Returns
    /// Binder bytes using the connection's negotiated hash policy.
    ///
    /// # 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_compute_tls13_psk_binder(
        &self,
        psk: &[u8],
        truncated_client_hello: &[u8],
    ) -> Result<Vec<u8>> {
        if !self.version.uses_tls13_handshake_semantics() {
            return Err(Error::StateError(
                "psk binder computation is only defined for TLS 1.3",
            ));
        }
        if psk.is_empty() {
            return Err(Error::InvalidLength("psk must not be empty"));
        }
        if truncated_client_hello.is_empty() {
            return Err(Error::InvalidLength(
                "truncated client hello must not be empty",
            ));
        }
        let noxtls_hash_algorithm = self.noxtls_negotiated_hash_algorithm();
        let hash_len = noxtls_hash_algorithm.output_len();
        let early_secret = noxtls_hkdf_extract_for_hash(noxtls_hash_algorithm, psk);
        let binder_key = noxtls_tls13_expand_label_for_hash(
            noxtls_hash_algorithm,
            &early_secret,
            b"res binder",
            &[],
            hash_len,
        )?;
        let finished_key = noxtls_tls13_expand_label_for_hash(
            noxtls_hash_algorithm,
            &binder_key,
            b"finished",
            &[],
            hash_len,
        )?;
        let noxtls_transcript_hash =
            noxtls_hash_bytes_for_algorithm(noxtls_hash_algorithm, truncated_client_hello);
        Ok(noxtls_finished_hmac_for_hash(
            noxtls_hash_algorithm,
            &finished_key,
            &noxtls_transcript_hash,
        ))
    }

    /// Verifies TLS 1.3 PSK binder bytes against provided ClientHello transcript prefix.
    ///
    /// # Arguments
    /// * `psk`: Candidate PSK bytes associated with the binder.
    /// * `truncated_client_hello`: ClientHello bytes up to binder list.
    /// * `received_binder`: Binder bytes received from peer.
    ///
    /// # Returns
    /// `Ok(true)` when binder matches expected value, `Ok(false)` otherwise.
    ///
    /// # 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_verify_tls13_psk_binder(
        &self,
        psk: &[u8],
        truncated_client_hello: &[u8],
        received_binder: &[u8],
    ) -> Result<bool> {
        let expected = self.noxtls_compute_tls13_psk_binder(psk, truncated_client_hello)?;
        Ok(noxtls_constant_time_eq(&expected, received_binder))
    }

    /// Verifies first PSK binder inside a TLS 1.3 ClientHello pre_shared_key extension.
    ///
    /// # Arguments
    /// * `client_hello`: Encoded ClientHello carrying pre_shared_key extension.
    /// * `psk`: Candidate PSK bytes associated with first identity.
    ///
    /// # Returns
    /// `Ok(true)` when first binder validates; `Ok(false)` otherwise.
    ///
    /// # 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_verify_client_hello_psk_binder(
        &self,
        client_hello: &[u8],
        psk: &[u8],
    ) -> Result<bool> {
        if !self.version.uses_tls13_handshake_semantics() {
            return Err(Error::StateError(
                "psk binder verification is only defined for TLS 1.3",
            ));
        }
        if psk.is_empty() {
            return Err(Error::InvalidLength("psk must not be empty"));
        }
        let received = noxtls_extract_first_psk_binder_from_client_hello(client_hello)?;
        let normalized = noxtls_zero_client_hello_psk_binders(client_hello)?;
        self.noxtls_verify_tls13_psk_binder(psk, &normalized, &received)
    }

    /// Verifies a ClientHello pre_shared_key offer against a locally-issued resumption ticket.
    ///
    /// # Arguments
    /// * `client_hello`: Encoded TLS 1.3 ClientHello.
    /// * `ticket`: Ticket metadata expected by the server.
    ///
    /// # Returns
    /// `Ok(true)` when first PSK identity matches and binder validates.
    ///
    /// # 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_verify_client_hello_psk_binder_for_ticket(
        &self,
        client_hello: &[u8],
        ticket: &ResumptionTicket,
    ) -> Result<bool> {
        self.noxtls_verify_client_hello_psk_binder_for_ticket_with_age(
            client_hello,
            ticket,
            ticket.issued_at_ms,
            u32::MAX,
        )
    }

    /// Verifies ticket identity, binder, and age/skew policy for TLS 1.3 PSK resumption.
    ///
    /// # Arguments
    /// * `client_hello`: Encoded TLS 1.3 ClientHello.
    /// * `ticket`: Ticket metadata expected by the server.
    /// * `current_time_ms`: Server-local current timestamp in milliseconds.
    /// * `max_skew_ms`: Allowed absolute age skew between expected and offered age.
    ///
    /// # Returns
    /// `Ok(true)` when identity, age policy, and binder all validate.
    ///
    /// # 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_verify_client_hello_psk_binder_for_ticket_with_age(
        &self,
        client_hello: &[u8],
        ticket: &ResumptionTicket,
        current_time_ms: u64,
        max_skew_ms: u32,
    ) -> Result<bool> {
        if !self.version.uses_tls13_handshake_semantics() {
            return Err(Error::StateError(
                "psk binder verification is only defined for TLS 1.3",
            ));
        }
        let info = noxtls_parse_client_hello_info(client_hello)?;
        let Some(identity) = info.extensions.psk_identities.first() else {
            return Ok(false);
        };
        if identity.as_slice() != ticket.identity.as_slice() {
            return Ok(false);
        }
        let Some(offered_age) = info.extensions.psk_obfuscated_ticket_ages.first().copied() else {
            return Ok(false);
        };
        if ticket.consumed {
            return Ok(false);
        }
        if !noxtls_ticket_age_matches_policy(ticket, offered_age, current_time_ms, max_skew_ms) {
            return Ok(false);
        }
        let psk = self.noxtls_derive_tls13_resumption_psk(&ticket.ticket_nonce)?;
        self.noxtls_verify_client_hello_psk_binder(client_hello, &psk)
    }

    /// Verifies ClientHello PSK binders by scanning all offered identities against ticket set.
    ///
    /// # Arguments
    /// * `client_hello`: Encoded TLS 1.3 ClientHello.
    /// * `tickets`: Candidate server tickets allowed for this connection.
    /// * `current_time_ms`: Server-local timestamp in milliseconds.
    /// * `max_skew_ms`: Allowed absolute age skew between expected and offered age.
    ///
    /// # Returns
    /// `Ok(Some(ticket_index))` for first valid ticket match, `Ok(None)` otherwise.
    ///
    /// # 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_verify_client_hello_psk_binder_for_tickets_with_age(
        &self,
        client_hello: &[u8],
        tickets: &[ResumptionTicket],
        current_time_ms: u64,
        max_skew_ms: u32,
    ) -> Result<Option<usize>> {
        if !self.version.uses_tls13_handshake_semantics() {
            return Err(Error::StateError(
                "psk binder verification is only defined for TLS 1.3",
            ));
        }
        if tickets.is_empty() {
            return Ok(None);
        }
        let info = noxtls_parse_client_hello_info(client_hello)?;
        if info.extensions.psk_identities.is_empty() || info.extensions.psk_binders.is_empty() {
            return Ok(None);
        }
        let normalized = noxtls_zero_client_hello_psk_binders(client_hello)?;
        for (identity_idx, identity) in info.extensions.psk_identities.iter().enumerate() {
            let Some(offered_age) = info
                .extensions
                .psk_obfuscated_ticket_ages
                .get(identity_idx)
                .copied()
            else {
                continue;
            };
            let Some(received_binder) = info.extensions.psk_binders.get(identity_idx) else {
                continue;
            };
            for (ticket_idx, ticket) in tickets.iter().enumerate() {
                if identity.as_slice() != ticket.identity.as_slice() {
                    continue;
                }
                if ticket.consumed {
                    continue;
                }
                if !noxtls_ticket_age_matches_policy(
                    ticket,
                    offered_age,
                    current_time_ms,
                    max_skew_ms,
                ) {
                    continue;
                }
                let psk = self.noxtls_derive_tls13_resumption_psk(&ticket.ticket_nonce)?;
                let expected_binder = self.noxtls_compute_tls13_psk_binder(&psk, &normalized)?;
                if noxtls_constant_time_eq(&expected_binder, received_binder) {
                    return Ok(Some(ticket_idx));
                }
            }
        }
        Ok(None)
    }

    /// Verifies PSK binders across multiple tickets and applies ticket usage policy.
    ///
    /// # Arguments
    /// * `client_hello`: Encoded TLS 1.3 ClientHello.
    /// * `tickets`: Mutable server ticket set considered for PSK resumption.
    /// * `current_time_ms`: Server-local timestamp in milliseconds.
    /// * `max_skew_ms`: Allowed absolute age skew between expected and offered age.
    /// * `usage_policy`: Whether accepted tickets remain reusable or are consumed.
    ///
    /// # Returns
    /// `Ok(Some(ticket_index))` for first valid ticket match, `Ok(None)` otherwise.
    ///
    /// # 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_verify_and_apply_client_hello_psk_policy(
        &self,
        client_hello: &[u8],
        tickets: &mut [ResumptionTicket],
        current_time_ms: u64,
        max_skew_ms: u32,
        usage_policy: TicketUsagePolicy,
    ) -> Result<Option<usize>> {
        let matched = self.noxtls_verify_client_hello_psk_binder_for_tickets_with_age(
            client_hello,
            tickets,
            current_time_ms,
            max_skew_ms,
        )?;
        if let Some(index) = matched {
            if usage_policy == TicketUsagePolicy::SingleUse {
                if let Some(ticket) = tickets.get_mut(index) {
                    ticket.consumed = true;
                }
            }
        }
        Ok(matched)
    }

    /// Verifies and applies PSK ticket policy against cached ticket store entries.
    ///
    /// # Arguments
    /// * `client_hello`: Encoded TLS 1.3 ClientHello.
    /// * `ticket_store`: Mutable ticket cache used for candidate lookup and policy updates.
    /// * `current_time_ms`: Server-local timestamp in milliseconds.
    /// * `max_skew_ms`: Allowed absolute age skew between expected and offered age.
    /// * `usage_policy`: Whether accepted tickets remain reusable or are consumed.
    ///
    /// # Returns
    /// `Ok(Some(ticket_index))` for first valid ticket match, `Ok(None)` otherwise.
    ///
    /// # 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_verify_and_apply_client_hello_psk_policy_with_store(
        &self,
        client_hello: &[u8],
        ticket_store: &mut TicketStore,
        current_time_ms: u64,
        max_skew_ms: u32,
        usage_policy: TicketUsagePolicy,
    ) -> Result<Option<usize>> {
        self.noxtls_verify_and_apply_client_hello_psk_policy(
            client_hello,
            ticket_store.tickets_mut(),
            current_time_ms,
            max_skew_ms,
            usage_policy,
        )
    }

    /// Evaluates ClientHello ticket policy and, on success, enables early-data acceptance context.
    ///
    /// # Arguments
    /// * `client_hello`: Encoded TLS 1.3 ClientHello carrying PSK identities.
    /// * `tickets`: Mutable server ticket set considered for PSK resumption.
    /// * `current_time_ms`: Server-local timestamp in milliseconds.
    /// * `max_skew_ms`: Allowed absolute age skew between expected and offered age.
    /// * `usage_policy`: Whether accepted tickets remain reusable or are consumed.
    ///
    /// # Returns
    /// `Ok(true)` when ticket policy passes and early-data context is installed.
    ///
    /// # 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_accept_tls13_early_data_with_ticket_policy(
        &mut self,
        client_hello: &[u8],
        tickets: &mut [ResumptionTicket],
        current_time_ms: u64,
        max_skew_ms: u32,
        usage_policy: TicketUsagePolicy,
    ) -> Result<bool> {
        let info = noxtls_parse_client_hello_info(client_hello)?;
        self.tls13_early_data_offered_in_client_hello = info.extensions.early_data_offered;
        self.tls13_early_data_accepted_in_encrypted_extensions = false;
        self.tls13_end_of_early_data_seen = false;
        self.tls13_early_data_opened_bytes = 0;
        self.noxtls_reset_tls13_early_data_transcript_to_client_hello(client_hello);
        let matched = self.noxtls_verify_and_apply_client_hello_psk_policy(
            client_hello,
            tickets,
            current_time_ms,
            max_skew_ms,
            usage_policy,
        )?;
        let Some(ticket_index) = matched else {
            self.tls13_early_data_accepted_psk = None;
            self.tls13_early_data_max_bytes = None;
            return Ok(false);
        };
        if !self.tls13_early_data_offered_in_client_hello {
            self.tls13_early_data_accepted_psk = None;
            self.tls13_early_data_max_bytes = None;
            return Ok(false);
        }
        let ticket = tickets
            .get(ticket_index)
            .ok_or(Error::StateError("matched ticket index is out of range"))?;
        if ticket.max_early_data_size == 0 {
            self.tls13_early_data_accepted_psk = None;
            self.tls13_early_data_max_bytes = None;
            return Ok(false);
        }
        let psk = self.noxtls_derive_tls13_resumption_psk(&ticket.ticket_nonce)?;
        self.tls13_early_data_accepted_psk = Some(psk);
        self.tls13_early_data_max_bytes = Some(ticket.max_early_data_size);
        self.tls13_early_data_replay_window = DtlsReplayWindow::noxtls_new();
        self.tls13_end_of_early_data_seen = false;
        Ok(true)
    }

    /// Evaluates ClientHello ticket policy via ticket store and installs early-data context.
    ///
    /// # Arguments
    /// * `client_hello`: Encoded TLS 1.3 ClientHello carrying PSK identities.
    /// * `ticket_store`: Mutable ticket cache used for candidate lookup and policy updates.
    /// * `current_time_ms`: Server-local timestamp in milliseconds.
    /// * `max_skew_ms`: Allowed absolute age skew between expected and offered age.
    /// * `usage_policy`: Whether accepted tickets remain reusable or are consumed.
    ///
    /// # Returns
    /// `Ok(true)` when ticket policy passes and early-data context is installed.
    ///
    /// # 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_accept_tls13_early_data_with_ticket_store(
        &mut self,
        client_hello: &[u8],
        ticket_store: &mut TicketStore,
        current_time_ms: u64,
        max_skew_ms: u32,
        usage_policy: TicketUsagePolicy,
    ) -> Result<bool> {
        self.noxtls_accept_tls13_early_data_with_ticket_policy(
            client_hello,
            ticket_store.tickets_mut(),
            current_time_ms,
            max_skew_ms,
            usage_policy,
        )
    }

    /// Seals a modeled TLS 1.3 early-data (0-RTT) record from PSK-derived traffic keys.
    ///
    /// # Arguments
    /// * `psk`: Resumption/external PSK bytes used to derive early-data traffic secret.
    /// * `plaintext`: Early-data plaintext bytes to protect.
    /// * `aad`: Additional authenticated data for record protection.
    /// * `sequence`: Record sequence number used for nonce construction.
    ///
    /// # Returns
    /// `ProtectedRecord` carrying encrypted early-data payload.
    ///
    /// # 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_tls13_early_data_record(
        &self,
        psk: &[u8],
        plaintext: &[u8],
        aad: &[u8],
        sequence: u64,
    ) -> Result<ProtectedRecord> {
        if !self.version.uses_tls13_handshake_semantics() {
            return Err(Error::StateError(
                "tls13 early-data records require TLS 1.3 connection",
            ));
        }
        if psk.is_empty() {
            return Err(Error::InvalidLength(
                "tls13 early-data psk must not be empty",
            ));
        }
        if plaintext.len() > self.max_record_plaintext_len {
            return Err(Error::InvalidLength(
                "record plaintext exceeds configured limit",
            ));
        }
        if self.state != HandshakeState::ClientHelloSent {
            return Err(Error::StateError(
                "tls13 early-data may only be sealed in ClientHelloSent state",
            ));
        }
        let (key, iv) = self.noxtls_derive_tls13_early_data_record_key_iv(psk)?;
        let nonce = noxtls_build_record_nonce(&iv, sequence);
        let (ciphertext, tag) = if self.noxtls_tls13_early_data_uses_chacha20_poly1305() {
            let key_32: [u8; 32] = key.as_slice().try_into().map_err(|_| {
                Error::InvalidLength("tls13 early-data chacha key must be 32 bytes")
            })?;
            noxtls_chacha20_poly1305_encrypt(&key_32, &nonce, aad, plaintext)?
        } else {
            let cipher = AesCipher::noxtls_new(&key)?;
            noxtls_aes_gcm_encrypt(&cipher, &nonce, aad, plaintext)?
        };
        Ok(ProtectedRecord {
            sequence,
            ciphertext,
            tag,
        })
    }

    /// Opens a modeled TLS 1.3 early-data (0-RTT) record from PSK-derived traffic keys.
    ///
    /// # Arguments
    /// * `psk`: Resumption/external PSK bytes used to derive early-data traffic secret.
    /// * `record`: Protected early-data record to decrypt.
    /// * `aad`: Additional authenticated data used during sealing.
    ///
    /// # Returns
    /// Decrypted early-data plaintext bytes on successful authentication.
    ///
    /// # 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_tls13_early_data_record(
        &mut self,
        psk: &[u8],
        record: &ProtectedRecord,
        aad: &[u8],
    ) -> Result<Vec<u8>> {
        if !self.version.uses_tls13_handshake_semantics() {
            self.noxtls_tls13_early_data_telemetry
                .rejected_invalid_input = self
                .noxtls_tls13_early_data_telemetry
                .rejected_invalid_input
                .saturating_add(1);
            return Err(Error::StateError(
                "tls13 early-data records require TLS 1.3 connection",
            ));
        }
        if psk.is_empty() {
            self.noxtls_tls13_early_data_telemetry
                .rejected_invalid_input = self
                .noxtls_tls13_early_data_telemetry
                .rejected_invalid_input
                .saturating_add(1);
            return Err(Error::InvalidLength(
                "tls13 early-data psk must not be empty",
            ));
        }
        if self.tls13_end_of_early_data_seen {
            self.noxtls_tls13_early_data_telemetry
                .rejected_decrypt_or_policy = self
                .noxtls_tls13_early_data_telemetry
                .rejected_decrypt_or_policy
                .saturating_add(1);
            return Err(Error::StateError(
                "tls13 early-data cannot be opened after EndOfEarlyData",
            ));
        }
        if !matches!(
            self.state,
            HandshakeState::ClientHelloSent
                | HandshakeState::ServerHelloReceived
                | HandshakeState::Finished
        ) {
            self.noxtls_tls13_early_data_telemetry
                .rejected_decrypt_or_policy = self
                .noxtls_tls13_early_data_telemetry
                .rejected_decrypt_or_policy
                .saturating_add(1);
            return Err(Error::StateError(
                "tls13 early-data may only be opened before encrypted extensions",
            ));
        }
        if self.tls13_early_data_require_acceptance {
            let Some(accepted_psk) = self.tls13_early_data_accepted_psk.as_deref() else {
                self.noxtls_tls13_early_data_telemetry
                    .rejected_missing_acceptance = self
                    .noxtls_tls13_early_data_telemetry
                    .rejected_missing_acceptance
                    .saturating_add(1);
                return Err(Error::StateError(
                    "tls13 early-data requires prior ticket-policy acceptance",
                ));
            };
            if !noxtls_constant_time_eq(accepted_psk, psk) {
                self.noxtls_tls13_early_data_telemetry.rejected_psk_mismatch = self
                    .noxtls_tls13_early_data_telemetry
                    .rejected_psk_mismatch
                    .saturating_add(1);
                return Err(Error::StateError(
                    "tls13 early-data psk does not match accepted ticket context",
                ));
            }
        }
        if self.tls13_early_data_anti_replay_enabled
            && !self
                .tls13_early_data_replay_window
                .check_and_mark(record.sequence)
        {
            self.noxtls_tls13_early_data_telemetry
                .rejected_replay_or_too_old = self
                .noxtls_tls13_early_data_telemetry
                .rejected_replay_or_too_old
                .saturating_add(1);
            return Err(Error::StateError(
                "tls13 early-data replay detected or sequence is too old",
            ));
        }
        let (key, iv) = self.noxtls_derive_tls13_early_data_record_key_iv(psk)?;
        let nonce = noxtls_build_record_nonce(&iv, record.sequence);
        let plaintext = if self.noxtls_tls13_early_data_uses_chacha20_poly1305() {
            let key_32: [u8; 32] = key.as_slice().try_into().map_err(|_| {
                Error::InvalidLength("tls13 early-data chacha key must be 32 bytes")
            })?;
            noxtls_chacha20_poly1305_decrypt(&key_32, &nonce, aad, &record.ciphertext, &record.tag)
                .map_err(|err| {
                    self.noxtls_tls13_early_data_telemetry
                        .rejected_decrypt_or_policy = self
                        .noxtls_tls13_early_data_telemetry
                        .rejected_decrypt_or_policy
                        .saturating_add(1);
                    err
                })?
        } else {
            let cipher = AesCipher::noxtls_new(&key)?;
            noxtls_aes_gcm_decrypt(&cipher, &nonce, aad, &record.ciphertext, &record.tag).map_err(
                |err| {
                    self.noxtls_tls13_early_data_telemetry
                        .rejected_decrypt_or_policy = self
                        .noxtls_tls13_early_data_telemetry
                        .rejected_decrypt_or_policy
                        .saturating_add(1);
                    err
                },
            )?
        };
        if plaintext.len() > self.max_record_plaintext_len {
            self.noxtls_tls13_early_data_telemetry
                .rejected_decrypt_or_policy = self
                .noxtls_tls13_early_data_telemetry
                .rejected_decrypt_or_policy
                .saturating_add(1);
            return Err(Error::InvalidLength(
                "record plaintext exceeds configured limit",
            ));
        }
        if let Some(max_bytes) = self.tls13_early_data_max_bytes {
            let next_total = self
                .tls13_early_data_opened_bytes
                .saturating_add(plaintext.len() as u64);
            if next_total > u64::from(max_bytes) {
                self.noxtls_tls13_early_data_telemetry
                    .rejected_decrypt_or_policy = self
                    .noxtls_tls13_early_data_telemetry
                    .rejected_decrypt_or_policy
                    .saturating_add(1);
                return Err(Error::InvalidLength(
                    "tls13 early-data exceeds accepted ticket max_early_data_size",
                ));
            }
            self.tls13_early_data_opened_bytes = next_total;
        }
        self.noxtls_tls13_early_data_telemetry.accepted_records = self
            .noxtls_tls13_early_data_telemetry
            .accepted_records
            .saturating_add(1);
        Ok(plaintext)
    }

    /// Seals one TLS 1.3 early-data wire record packet from TLSInnerPlaintext content.
    ///
    /// # Arguments
    /// * `psk`: Resumption/external PSK bytes used to derive early-data traffic secret.
    /// * `content`: Inner plaintext content bytes.
    /// * `content_type`: Inner content type byte.
    /// * `aad`: Additional authenticated data for AEAD.
    /// * `sequence`: Record sequence number used for nonce construction.
    /// * `padding_len`: Number of trailing zero padding bytes in TLSInnerPlaintext.
    ///
    /// # Returns
    /// Serialized TLSCiphertext packet 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_seal_tls13_early_data_record_packet(
        &self,
        psk: &[u8],
        content: &[u8],
        content_type: u8,
        aad: &[u8],
        sequence: u64,
        padding_len: usize,
    ) -> Result<Vec<u8>> {
        let inner = noxtls_encode_tls13_inner_plaintext(content, content_type, padding_len);
        let expected_aad = self.noxtls_build_tls13_record_aad(inner.len().saturating_add(16))?;
        let aad_to_use = if aad.is_empty() {
            &expected_aad[..]
        } else {
            aad
        };
        let record = self.noxtls_seal_tls13_early_data_record(psk, &inner, aad_to_use, sequence)?;
        self.noxtls_encode_tls13_record_packet(&record)
    }

    /// Opens one TLS 1.3 early-data wire record packet and decodes TLSInnerPlaintext.
    ///
    /// # Arguments
    /// * `psk`: Resumption/external PSK bytes used to derive early-data traffic secret.
    /// * `packet`: Serialized TLSCiphertext packet bytes.
    /// * `aad`: Additional authenticated data used during sealing.
    /// * `sequence`: Record sequence number used during sealing.
    ///
    /// # Returns
    /// Tuple `(content, content_type)` decoded from inner plaintext.
    ///
    /// # 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_tls13_early_data_record_packet(
        &mut self,
        psk: &[u8],
        packet: &[u8],
        aad: &[u8],
        sequence: u64,
    ) -> Result<(Vec<u8>, u8)> {
        let record = self.noxtls_decode_tls13_record_packet(packet, sequence)?;
        let expected_aad = self.noxtls_build_tls13_record_aad(
            record.ciphertext.len().saturating_add(record.tag.len()),
        )?;
        let aad_to_use = if aad.is_empty() {
            &expected_aad[..]
        } else {
            aad
        };
        let inner = self.noxtls_open_tls13_early_data_record(psk, &record, aad_to_use)?;
        noxtls_decode_tls13_inner_plaintext(&inner)
    }

    /// Opens a sequence of TLSCiphertext packets as server-side 0-RTT application records.
    ///
    /// # Arguments
    /// * `psk`: Accepted resumption/external PSK bytes for early-data traffic keys.
    /// * `packets`: Ordered TLSCiphertext packets from the client first flight.
    /// * `first_sequence`: Sequence number corresponding to `packets[0]`.
    ///
    /// # Returns
    /// Ordered decrypted application payloads from early-data records.
    ///
    /// # Errors
    /// Returns [`noxtls_core::Error`] when packet decoding, policy, replay checks, or inner content validation fails.
    ///
    /// # Panics
    /// This function does not panic.
    pub fn noxtls_open_tls13_early_data_client_flight_packets(
        &mut self,
        psk: &[u8],
        packets: &[Vec<u8>],
        first_sequence: u64,
    ) -> Result<Vec<Vec<u8>>> {
        let mut out = Vec::with_capacity(packets.len());
        for (idx, packet) in packets.iter().enumerate() {
            let sequence = first_sequence.saturating_add(idx as u64);
            let (payload, content_type) =
                self.noxtls_open_tls13_early_data_record_packet(psk, packet, &[], sequence)?;
            if content_type != RecordContentType::ApplicationData.to_u8() {
                return Err(Error::ParseFailure(
                    "tls13 early-data packet inner content type must be application_data",
                ));
            }
            out.push(payload);
        }
        Ok(out)
    }

    /// Accepts ClientHello ticket policy and opens early-data packets from the same client flight.
    ///
    /// # Arguments
    /// * `client_hello`: Encoded TLS 1.3 ClientHello carrying PSK and early_data offer.
    /// * `tickets`: Mutable server ticket set considered for acceptance.
    /// * `current_time_ms`: Server-local timestamp in milliseconds.
    /// * `max_skew_ms`: Allowed absolute ticket age skew.
    /// * `usage_policy`: Whether accepted tickets are reusable or single-use.
    /// * `packets`: Ordered TLSCiphertext packets from the client first flight.
    /// * `first_sequence`: Sequence number corresponding to `packets[0]`.
    ///
    /// # Returns
    /// Decrypted early-data payloads when accepted; empty vector when ticket policy does not accept.
    ///
    /// # Errors
    /// Returns [`noxtls_core::Error`] when acceptance, key derivation, packet decoding, or policy checks fail.
    ///
    /// # Panics
    /// This function does not panic.
    #[allow(clippy::too_many_arguments)]
    pub fn noxtls_accept_and_open_tls13_early_data_client_flight_with_ticket_policy(
        &mut self,
        client_hello: &[u8],
        tickets: &mut [ResumptionTicket],
        current_time_ms: u64,
        max_skew_ms: u32,
        usage_policy: TicketUsagePolicy,
        packets: &[Vec<u8>],
        first_sequence: u64,
    ) -> Result<Vec<Vec<u8>>> {
        if !self.noxtls_accept_tls13_early_data_with_ticket_policy(
            client_hello,
            tickets,
            current_time_ms,
            max_skew_ms,
            usage_policy,
        )? {
            return Ok(Vec::new());
        }
        let accepted_psk = self
            .tls13_early_data_accepted_psk
            .clone()
            .ok_or(Error::StateError(
                "tls13 early-data accepted ticket context is not installed",
            ))?;
        self.noxtls_open_tls13_early_data_client_flight_packets(
            &accepted_psk,
            packets,
            first_sequence,
        )
    }

    /// Accepts ClientHello policy from ticket store and opens early-data packets from the client flight.
    ///
    /// # Arguments
    /// * `client_hello`: Encoded TLS 1.3 ClientHello carrying PSK and early_data offer.
    /// * `ticket_store`: Mutable server ticket store used for acceptance.
    /// * `current_time_ms`: Server-local timestamp in milliseconds.
    /// * `max_skew_ms`: Allowed absolute ticket age skew.
    /// * `usage_policy`: Whether accepted tickets are reusable or single-use.
    /// * `packets`: Ordered TLSCiphertext packets from the client first flight.
    /// * `first_sequence`: Sequence number corresponding to `packets[0]`.
    ///
    /// # Returns
    /// Decrypted early-data payloads when accepted; empty vector when ticket policy does not accept.
    ///
    /// # Errors
    /// Returns [`noxtls_core::Error`] when acceptance, key derivation, packet decoding, or policy checks fail.
    ///
    /// # Panics
    /// This function does not panic.
    #[allow(clippy::too_many_arguments)]
    pub fn noxtls_accept_and_open_tls13_early_data_client_flight_with_ticket_store(
        &mut self,
        client_hello: &[u8],
        ticket_store: &mut TicketStore,
        current_time_ms: u64,
        max_skew_ms: u32,
        usage_policy: TicketUsagePolicy,
        packets: &[Vec<u8>],
        first_sequence: u64,
    ) -> Result<Vec<Vec<u8>>> {
        if !self.noxtls_accept_tls13_early_data_with_ticket_store(
            client_hello,
            ticket_store,
            current_time_ms,
            max_skew_ms,
            usage_policy,
        )? {
            return Ok(Vec::new());
        }
        let accepted_psk = self
            .tls13_early_data_accepted_psk
            .clone()
            .ok_or(Error::StateError(
                "tls13 early-data accepted ticket context is not installed",
            ))?;
        self.noxtls_open_tls13_early_data_client_flight_packets(
            &accepted_psk,
            packets,
            first_sequence,
        )
    }

    /// Returns TLS 1.3 early-data traffic-key length based on active modeled suite policy.
    ///
    /// # Arguments
    /// * `self` — `Connection` with selected cipher suite context.
    ///
    /// # Returns
    /// AES-128 uses 16 bytes; AES-256 and ChaCha20-Poly1305 use 32 bytes.
    ///
    /// # Panics
    /// This function does not panic.
    pub(super) fn noxtls_tls13_early_data_key_len(&self) -> usize {
        match self.noxtls_selected_cipher_suite {
            Some(CipherSuite::TlsAes256GcmSha384 | CipherSuite::TlsChacha20Poly1305Sha256) => 32,
            _ => 16,
        }
    }

    /// Returns whether modeled early-data record protection uses ChaCha20-Poly1305.
    ///
    /// # Arguments
    /// * `self` — `Connection` with selected cipher suite context.
    ///
    /// # Returns
    /// `true` when current modeled suite policy selects ChaCha20-Poly1305.
    ///
    /// # Panics
    /// This function does not panic.
    fn noxtls_tls13_early_data_uses_chacha20_poly1305(&self) -> bool {
        matches!(
            self.noxtls_selected_cipher_suite,
            Some(CipherSuite::TlsChacha20Poly1305Sha256)
        )
    }

    /// Resets transcript context to a single ClientHello for modeled 0-RTT server decrypt.
    ///
    /// # Arguments
    /// * `client_hello` — Encoded ClientHello message bytes to anchor early-data transcript hash.
    ///
    /// # Returns
    /// `()`.
    ///
    /// # Panics
    /// This function does not panic.
    fn noxtls_reset_tls13_early_data_transcript_to_client_hello(&mut self, client_hello: &[u8]) {
        self.transcript.clear();
        self.noxtls_transcript_hash = TranscriptHashState::noxtls_for_version(self.version);
        self.noxtls_append_transcript(client_hello);
    }

    /// Builds and records the TLS 1.3 client Certificate message for mTLS.
    pub fn noxtls_prepare_tls13_client_certificate_message(&mut self) -> Result<Vec<u8>> {
        if self.tls_role == TlsRole::Server {
            return Err(Error::StateError(
                "client certificate preparation requires client-role connection",
            ));
        }
        if !self.tls13_server_requested_client_certificate {
            return Err(Error::StateError(
                "client certificate can only be sent after CertificateRequest",
            ));
        }
        if self.state != HandshakeState::Finished {
            return Err(Error::StateError(
                "client certificate can only be prepared after server finished is processed",
            ));
        }
        if self.tls13_client_identity_certificate_chain_der.is_empty() {
            return Err(Error::StateError("tls13 client identity is not configured"));
        }
        let certificate = Self::noxtls_build_certificate_chain_message(
            &self.tls13_client_identity_certificate_chain_der,
        )?;
        self.noxtls_append_transcript(&certificate);
        Ok(certificate)
    }

    /// Builds and records the TLS 1.3 client CertificateVerify message for mTLS.
    pub fn noxtls_prepare_tls13_client_certificate_verify_message(&mut self) -> Result<Vec<u8>> {
        if self.tls_role == TlsRole::Server {
            return Err(Error::StateError(
                "client certificate verify preparation requires client-role connection",
            ));
        }
        if !self.tls13_server_requested_client_certificate {
            return Err(Error::StateError(
                "client certificate verify can only be sent after CertificateRequest",
            ));
        }
        if self.state != HandshakeState::Finished {
            return Err(Error::StateError(
                "client certificate verify can only be prepared after server finished is processed",
            ));
        }
        let signing_key = self
            .tls13_client_signing_key
            .as_ref()
            .ok_or(Error::StateError(
                "tls13 client signing key is not configured",
            ))?;
        let signed_message =
            noxtls_build_tls13_client_certificate_verify_message(&self.noxtls_transcript_hash());
        let (signature_scheme, signature) = match signing_key {
            Tls13ServerIdentityKey::P256(private_key) => {
                let (r, s) = noxtls_p256_ecdsa_sign_sha256(private_key, &signed_message)?;
                let signature = noxtls_encode_ecdsa_signature_der(&r, &s)?;
                (TLS13_SIGALG_ECDSA_SECP256R1_SHA256, signature)
            }
            _ => {
                return Err(Error::UnsupportedFeature(
                    "tls13 client CertificateVerify currently supports P-256 client identities",
                ));
            }
        };
        let certificate_verify =
            Self::noxtls_build_certificate_verify_message(signature_scheme, &signature)?;
        self.noxtls_append_transcript(&certificate_verify);
        Ok(certificate_verify)
    }

    /// Builds the client Certificate and CertificateVerify messages for a TLS 1.3 mTLS response.
    pub fn noxtls_prepare_tls13_client_authentication_messages(&mut self) -> Result<Vec<Vec<u8>>> {
        let certificate = self.noxtls_prepare_tls13_client_certificate_message()?;
        let certificate_verify = self.noxtls_prepare_tls13_client_certificate_verify_message()?;
        Ok(vec![certificate, certificate_verify])
    }

    /// Builds the client Finished handshake message and appends it to the transcript.
    ///
    /// # Arguments
    ///
    /// * `self` — Client connection that has already processed the server Finished message.
    ///
    /// # Returns
    ///
    /// On success, encoded Finished handshake message bytes ready for sealing.
    ///
    /// # Errors
    ///
    /// Returns [`noxtls_core::Error`] when called outside client role or before server Finished.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn noxtls_prepare_tls13_client_finished_message(&mut self) -> Result<Vec<u8>> {
        if self.tls_role == TlsRole::Server {
            return Err(Error::StateError(
                "client finished preparation requires client-role connection",
            ));
        }
        if self.state != HandshakeState::Finished {
            return Err(Error::StateError(
                "client finished can only be prepared after server finished is processed",
            ));
        }
        let finished = self.noxtls_build_finished_message()?;
        self.noxtls_append_transcript(&finished);
        Ok(finished)
    }
}