courierust 1.0.8

A zero-dependency, self-contained HTTP/1.1 + HTTP/2 + HTTP/3 (QUIC) + WebSocket + gRPC stack with a from-scratch TLS 1.2/1.3, a work-stealing scheduler, RFC 9218 priority and JA3/JA4 fingerprints.
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
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
//! TLS 1.3 handshake state machines (RFC 8446 §4).
//!
//! Implements the client and server sides of a full 1-RTT handshake:
//! ClientHello / ServerHello / EncryptedExtensions / Certificate /
//! CertificateVerify / Finished. Only X25519 key exchange is offered;
//! the negotiated suite is chosen by the server from the supported set.
//!
//! The Finished verify_data is computed over the transcript hash taken
//! *before* the Finished message is appended (as in rustls/OpenSSL);
//! the Finished message is then added to the transcript for deriving
//! the application traffic secrets.

use super::crypto::hash::Digest;
use super::crypto::hmac::hmac;

use super::crypto::x25519;
use super::key_schedule::{CipherSuite, KeySchedule, TrafficKeys, Transcript};
use super::record::*;
use super::{TlsError, TlsResult};
use alloc::string::String;
use alloc::vec::Vec;

/// Handshake message types (RFC 8446 §4).
pub(crate) const HS_CLIENT_HELLO: u8 = 1;
pub(crate) const HS_SERVER_HELLO: u8 = 2;
pub(crate) const HS_KEY_UPDATE: u8 = 24;
pub(crate) const HS_NEW_SESSION_TICKET: u8 = 4;
pub(crate) const HS_ENCRYPTED_EXTENSIONS: u8 = 8;
pub(crate) const HS_CERTIFICATE: u8 = 11;
pub(crate) const HS_CERTIFICATE_REQUEST: u8 = 13;
pub(crate) const HS_CERTIFICATE_VERIFY: u8 = 15;
pub(crate) const HS_FINISHED: u8 = 20;
/// Synthetic `message_hash` handshake type used after a HelloRetryRequest
/// (RFC 8446 §4.4.1).
pub(crate) const HS_MESSAGE_HASH: u8 = 254;

/// HelloRetryRequest random: SHA-256("HelloRetryRequest") (RFC 8446 §4.1.3).
pub(crate) const HRR_RANDOM: [u8; 32] = [
    0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91,
    0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c,
];

/// Extension types.
const EXT_SERVER_NAME: u16 = 0x0000;
const EXT_SUPPORTED_GROUPS: u16 = 0x000a;
const EXT_EC_POINT_FORMATS: u16 = 0x000b;
const EXT_SIGNATURE_ALGORITHMS: u16 = 0x000d;
const EXT_ALPN: u16 = 0x0010;
const EXT_SUPPORTED_VERSIONS: u16 = 0x002b;
/// cookie extension (RFC 8446 §4.2.2) — sent in the HelloRetryRequest and
/// echoed verbatim by the client in the retried ClientHello.
pub(crate) const EXT_COOKIE: u16 = 0x002c;
const EXT_KEY_SHARE: u16 = 0x0033;
/// QUIC transport parameters (RFC 9001 section 5.2).
pub(crate) const EXT_QUIC_TRANSPORT_PARAMETERS: u16 = 0x0039;
/// Secure renegotiation indicator (RFC 5746 §3.2): empty for a fresh
/// handshake. TLS 1.2 servers require it to permit renegotiation; TLS
/// 1.3 does not use it.
const EXT_RENEGOTIATION_INFO: u16 = 0xff01;

/// Named group for X25519.
pub(crate) const GROUP_X25519: u16 = 0x001d;

/// Signature schemes offered (RFC 8446 §4.2.3): RSA-PSS-PSS, RSA-PSS-RSAE,
/// ECDSA P-256, Ed25519, and RSA PKCS#1.
const SIGNATURE_SCHEMES: &[u16] = &[
    0x0809, // rsa_pss_pss_sha256
    0x080a, // rsa_pss_pss_sha384
    0x0804, // rsa_pss_rsae_sha256
    0x0805, // rsa_pss_rsae_sha384
    0x0403, // ecdsa_secp256r1_sha256
    0x0807, // ed25519
    0x0401, // rsa_pkcs1_sha256
    0x0501, // rsa_pkcs1_sha384
];

/// Encode a handshake message: type || length(3) || body.
pub(crate) fn encode_hs(msg_type: u8, body: &[u8]) -> Vec<u8> {
    let len = body.len() as u32;
    let mut out = Vec::with_capacity(4 + body.len());
    out.push(msg_type);
    out.extend_from_slice(&[(len >> 16) as u8, (len >> 8) as u8, len as u8]);
    out.extend_from_slice(body);
    out
}

/// A parsed handshake message from a stream of handshake bytes.
pub(crate) struct HsMessage<'a> {
    pub(crate) msg_type: u8,
    pub(crate) body: &'a [u8],
}

/// Parse a single handshake message (4-byte header + body).
pub(crate) fn parse_hs(buf: &[u8]) -> Option<HsMessage<'_>> {
    if buf.len() < 4 {
        return None;
    }
    let len = ((buf[1] as usize) << 16) | ((buf[2] as usize) << 8) | buf[3] as usize;
    if 4 + len > buf.len() {
        return None;
    }
    Some(HsMessage {
        msg_type: buf[0],
        body: &buf[4..4 + len],
    })
}

/// If `buf` starts with a complete handshake message, return it.
pub(crate) fn peek_complete_hs(buf: &[u8]) -> Option<HsMessage<'_>> {
    parse_hs(buf).filter(|m| 4 + m.body.len() <= buf.len())
}

/// Whether `buf` contains a complete `Finished` handshake message.
///
/// In a 1-RTT handshake the Finished is the final message of the peer's
/// first flight, so "a complete Finished is buffered" is the right
/// condition for [`TlsIo::read_encrypted_handshake`] to stop: it must
/// keep consuming records until the whole flight is present (a server
/// may fragment EncryptedExtensions / Certificate / CertificateVerify /
/// Finished across several records). Walks complete messages only, so a
/// partial trailing message simply means "keep reading".
pub(crate) fn has_complete_finished(buf: &[u8]) -> bool {
    let mut off = 0;
    while off + 4 <= buf.len() {
        let len = ((buf[off + 1] as usize) << 16)
            | ((buf[off + 2] as usize) << 8)
            | buf[off + 3] as usize;
        if off + 4 + len > buf.len() {
            return false; // trailing message is incomplete
        }
        if buf[off] == HS_FINISHED {
            return true;
        }
        off += 4 + len;
    }
    false
}

/// Read a u8/u16/u24 from a cursor.
struct Cur<'a> {
    data: &'a [u8],
    pos: usize,
}

impl<'a> Cur<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self { data, pos: 0 }
    }
    fn u8(&mut self) -> Option<u8> {
        let v = *self.data.get(self.pos)?;
        self.pos += 1;
        Some(v)
    }
    fn u16(&mut self) -> Option<u16> {
        let b = self.take(2)?;
        Some(u16::from_be_bytes([b[0], b[1]]))
    }
    fn u24(&mut self) -> Option<usize> {
        let b = self.take(3)?;
        Some(((b[0] as usize) << 16) | ((b[1] as usize) << 8) | b[2] as usize)
    }
    fn take(&mut self, n: usize) -> Option<&'a [u8]> {
        if self.pos + n > self.data.len() {
            return None;
        }
        let s = &self.data[self.pos..self.pos + n];
        self.pos += n;
        Some(s)
    }
    fn rest(&self) -> &'a [u8] {
        &self.data[self.pos..]
    }
    fn done(&self) -> bool {
        self.pos == self.data.len()
    }
}

/// A parsed extension: type + content.
struct Ext<'a> {
    ext_type: u16,
    content: &'a [u8],
}

/// Parse the extension list of a handshake message body.
fn parse_extensions(body: &[u8]) -> Option<Vec<Ext<'_>>> {
    let mut c = Cur::new(body);
    let total = c.u16()? as usize;
    let ext_bytes = c.take(total)?;
    let mut out = Vec::new();
    let mut e = Cur::new(ext_bytes);
    while !e.done() {
        let ext_type = e.u16()?;
        let len = e.u16()? as usize;
        let content = e.take(len)?;
        out.push(Ext { ext_type, content });
    }
    Some(out)
}

/// The offered cipher suites the client sends.
const CLIENT_SUITES: &[CipherSuite] = &[
    CipherSuite::TlsChaCha20Poly1305Sha256,
    CipherSuite::TlsAes128GcmSha256,
    CipherSuite::TlsAes256GcmSha384,
];

/// The negotiated handshake result shared by both sides.
pub(crate) struct HandshakeResult {
    pub(crate) suite: CipherSuite,
    pub(crate) keys: AppKeys,
    pub(crate) alpn: Option<Vec<u8>>,
    pub(crate) server_name: Option<String>,
    pub(crate) peer_cert: Option<Vec<u8>>,
    /// True when the handshake was resumed from a PSK.
    pub(crate) resumed: bool,
    /// Server side: the resumption master secret, used to issue a
    /// NewSessionTicket after the handshake.
    pub(crate) resumption_master: Option<Vec<u8>>,
}

/// The application traffic keys (write = client, read = server and
/// vice-versa), fully derived, plus the traffic secrets behind them:
/// RFC 8446 §7.2 derives a `KeyUpdate`'s next generation from the secret,
/// which cannot be recovered from the key.
#[derive(Debug, Clone)]
pub(crate) struct AppKeys {
    pub(crate) write: TrafficKeys,
    pub(crate) read: TrafficKeys,
    pub(crate) write_secret: Vec<u8>,
    pub(crate) read_secret: Vec<u8>,
}

// ---------------------------------------------------------------------
// ClientHello construction
// ---------------------------------------------------------------------

/// Build a ClientHello with an optional QUIC transport-parameters
/// extension. The ordinary TLS path passes `None`. This is the TLS 1.3
/// client hello used by the QUIC path (RFC 9001 requires TLS 1.3); the
/// TCP connector uses [`build_client_hello_negotiated`] instead so it
/// can also speak TLS 1.2.
pub(crate) fn build_client_hello_with_transport_params(
    random: &[u8; 32],
    key_share: &[u8; 32],
    alpn: &[Vec<u8>],
    server_name: Option<&str>,
    transport_params: Option<&[u8]>,
) -> Vec<u8> {
    build_client_hello_negotiated(
        random,
        Some(key_share),
        alpn,
        server_name,
        transport_params,
        true,
        false,
    )
}

/// Build a ClientHello covering a configurable version window.
///
/// * `key_share` — `Some` includes an X25519 share; `None` emits an
///   empty `client_shares` vector (RFC 8446 §4.2.8 allows requesting
///   group selection, which makes the server answer with a
///   HelloRetryRequest).
/// * `offer13` — include `supported_versions` (0x0304) and the TLS 1.3
///   suites.
/// * `offer12` — also include the TLS 1.2 AEAD ECDHE suites and the
///   `ec_point_formats` extension, so a TLS 1.2-only server can
///   negotiate TLS 1.2.
///
/// `supported_groups` always lists X25519 and secp256r1 (the latter is
/// what a TLS 1.2 ECDHE server needs); `signature_algorithms` carries
/// both the TLS 1.3 and the TLS 1.2 scheme sets.
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_client_hello_negotiated(
    random: &[u8; 32],
    key_share: Option<&[u8; 32]>,
    alpn: &[Vec<u8>],
    server_name: Option<&str>,
    transport_params: Option<&[u8]>,
    offer13: bool,
    offer12: bool,
) -> Vec<u8> {
    let mut body = Vec::new();
    body.extend_from_slice(&[0x03, 0x03]);
    body.extend_from_slice(random);
    body.push(0);
    let mut suite_wires: Vec<u16> = Vec::new();
    if offer13 {
        suite_wires.extend(CLIENT_SUITES.iter().map(|s| s.wire()));
    }
    if offer12 {
        suite_wires.extend(super::tls12::CLIENT_SUITES_12.iter().map(|s| s.wire()));
    }
    body.extend_from_slice(&(suite_wires.len() as u16 * 2).to_be_bytes());
    for s in &suite_wires {
        body.extend_from_slice(&s.to_be_bytes());
    }
    body.extend_from_slice(&[1, 0]);

    // extensions
    let mut exts: Vec<(u16, Vec<u8>)> = Vec::new();

    if let Some(name) = server_name {
        let name_bytes = name.as_bytes();
        let mut server_name_ext = Vec::new();
        let mut name_list = Vec::new();
        name_list.push(0); // host_name
        name_list.extend_from_slice(&(name_bytes.len() as u16).to_be_bytes());
        name_list.extend_from_slice(name_bytes);
        server_name_ext.extend_from_slice(&(name_list.len() as u16).to_be_bytes());
        server_name_ext.extend_from_slice(&name_list);
        exts.push((EXT_SERVER_NAME, server_name_ext));
    }

    let mut groups = Vec::new();
    if offer13 {
        groups.extend_from_slice(&[0x00, 0x04]); // 2 curves
        groups.extend_from_slice(&GROUP_X25519.to_be_bytes()); // X25519
        groups.extend_from_slice(&super::tls12::GROUP_SECP256R1.to_be_bytes()); // secp256r1
    } else {
        groups.extend_from_slice(&[0x00, 0x02]); // 1 curve
        groups.extend_from_slice(&super::tls12::GROUP_SECP256R1.to_be_bytes());
    }
    exts.push((EXT_SUPPORTED_GROUPS, groups));

    // signature_algorithms: TLS 1.3 schemes + TLS 1.2 schemes.
    let mut sigs = Vec::new();
    let mut sig_schemes: Vec<u16> = SIGNATURE_SCHEMES.to_vec();
    sig_schemes.extend_from_slice(super::tls12::TLS12_SIGNATURE_ALGORITHMS);
    sigs.extend_from_slice(&(sig_schemes.len() as u16 * 2).to_be_bytes());
    for s in &sig_schemes {
        sigs.extend_from_slice(&s.to_be_bytes());
    }
    exts.push((EXT_SIGNATURE_ALGORITHMS, sigs));

    // ec_point_formats (required by TLS 1.2 ECDHE): uncompressed only.
    if offer12 {
        exts.push((EXT_EC_POINT_FORMATS, vec![1, 0]));
        exts.push((EXT_RENEGOTIATION_INFO, vec![0x00]));
    }

    // supported_versions + key_share only when offering TLS 1.3.
    if offer13 {
        let mut versions = Vec::new();
        versions.extend_from_slice(&[0x02, 0x03, 0x04]);
        exts.push((EXT_SUPPORTED_VERSIONS, versions));

        let mut ks = Vec::new();
        match key_share {
            Some(share) => {
                ks.extend_from_slice(&[0x00, 0x24]); // 2 bytes list len = 36
                ks.extend_from_slice(&GROUP_X25519.to_be_bytes());
                ks.extend_from_slice(&[0x00, 0x20]); // 32-byte key
                ks.extend_from_slice(share);
            }
            // Empty client_shares: ask the server to pick a group.
            None => ks.extend_from_slice(&[0x00, 0x00]),
        }
        exts.push((EXT_KEY_SHARE, ks));
    }

    // ALPN (RFC 7301)
    if !alpn.is_empty() {
        let mut alpn_body = Vec::new();
        let mut proto_list = Vec::new();
        for p in alpn {
            proto_list.push(p.len() as u8);
            proto_list.extend_from_slice(p);
        }
        alpn_body.extend_from_slice(&(proto_list.len() as u16).to_be_bytes());
        alpn_body.extend_from_slice(&proto_list);
        exts.push((EXT_ALPN, alpn_body));
    }

    if let Some(params) = transport_params {
        exts.push((EXT_QUIC_TRANSPORT_PARAMETERS, params.to_vec()));
    }

    let mut ext_bytes = Vec::new();
    for (t, c) in exts {
        ext_bytes.extend_from_slice(&t.to_be_bytes());
        ext_bytes.extend_from_slice(&(c.len() as u16).to_be_bytes());
        ext_bytes.extend_from_slice(&c);
    }
    body.extend_from_slice(&(ext_bytes.len() as u16).to_be_bytes());
    body.extend_from_slice(&ext_bytes);

    encode_hs(HS_CLIENT_HELLO, &body)
}

/// Whether a ServerHello negotiates TLS 1.3: true when the
/// `supported_versions` extension is present with value 0x0304. A TLS
/// 1.2 ServerHello carries no such extension. Used by the connector to
/// dispatch between the TLS 1.3 and TLS 1.2 paths.
pub(crate) fn server_hello_negotiates_tls13(body: &[u8]) -> bool {
    let mut c = Cur::new(body);
    // legacy_version (must be 0x0303), random (32), session id.
    if c.u16().is_none() || c.take(32).is_none() {
        return false;
    }
    let sid_len = match c.u8() {
        Some(n) => n as usize,
        None => return false,
    };
    if c.take(sid_len).is_none() {
        return false;
    }
    // cipher_suite (2), compression (1), then extensions.
    if c.take(3).is_none() {
        return false;
    }
    let Some(exts) = parse_extensions(c.rest()) else {
        return false;
    };
    for e in exts {
        if e.ext_type == EXT_SUPPORTED_VERSIONS {
            let mut v = Cur::new(e.content);
            if let Some(ver) = v.u16() {
                return ver == 0x0304;
            }
        }
    }
    false
}

/// Whether a ClientHello offers TLS 1.3 (`supported_versions` contains
/// 0x0304). Used by the acceptor to decide between the TLS 1.3 and
/// TLS 1.2 paths before running either state machine.
pub(crate) fn client_hello_offers_tls13(body: &[u8]) -> TlsResult<bool> {
    let mut c = Cur::new(body);
    if c.u16().is_none() || c.take(32).is_none() {
        return Err(TlsError::Protocol("bad CH".into()));
    }
    let sid_len = c.u8().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
    if sid_len > 32 {
        return Err(TlsError::Protocol("bad CH sid".into()));
    }
    c.take(sid_len)
        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
    let suites_len = c.u16().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
    // `% 2 != 0` is total (usize remainder never overflows; constant
    // non-zero divisor cannot panic).
    if suites_len < 2 || suites_len % 2 != 0 {
        return Err(TlsError::Protocol("bad CH suites".into()));
    }
    c.take(suites_len)
        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
    let comp_len = c.u8().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
    c.take(comp_len)
        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
    let exts =
        parse_extensions(c.rest()).ok_or_else(|| TlsError::Protocol("bad CH exts".into()))?;
    for e in exts {
        if e.ext_type == EXT_SUPPORTED_VERSIONS {
            let mut v = Cur::new(e.content);
            let list_len = v
                .u8()
                .ok_or_else(|| TlsError::Protocol("bad versions".into()))?
                as usize;
            let list = v
                .take(list_len)
                .ok_or_else(|| TlsError::Protocol("bad versions".into()))?;
            let mut lc = Cur::new(list);
            while !lc.done() {
                if let Some(ver) = lc.u16() {
                    if ver == 0x0304 {
                        return Ok(true);
                    }
                }
            }
        }
    }
    Ok(false)
}

// ---------------------------------------------------------------------
// ServerHello parsing
// ---------------------------------------------------------------------

/// Result of parsing a ServerHello.
pub(crate) struct ServerHelloInfo {
    pub(crate) random: [u8; 32],
    pub(crate) suite: CipherSuite,
    pub(crate) key_share: [u8; 32],
    /// The echoed legacy_session_id (must equal the one we sent).
    pub(crate) session_id: Vec<u8>,
    /// True when the server accepted our resumption PSK.
    pub(crate) resumed: bool,
}

pub(crate) fn parse_server_hello(body: &[u8]) -> TlsResult<ServerHelloInfo> {
    let mut c = Cur::new(body);
    let legacy = c.u16().ok_or_else(|| TlsError::Protocol("bad SH".into()))?;
    if legacy != 0x0303 {
        return Err(TlsError::Protocol("bad SH legacy version".into()));
    }
    let mut random = [0u8; 32];
    random.copy_from_slice(
        c.take(32)
            .ok_or_else(|| TlsError::Protocol("bad SH".into()))?,
    );
    let sid_len = c.u8().ok_or_else(|| TlsError::Protocol("bad SH".into()))? as usize;
    if sid_len > 32 {
        return Err(TlsError::Protocol("bad SH session id".into()));
    }
    let session_id = c
        .take(sid_len)
        .ok_or_else(|| TlsError::Protocol("bad SH".into()))?
        .to_vec();
    let suite_wire = c.u16().ok_or_else(|| TlsError::Protocol("bad SH".into()))?;
    let suite = CipherSuite::from_wire(suite_wire)
        .ok_or_else(|| TlsError::Protocol("unsupported suite".into()))?;
    let comp = c.u8().ok_or_else(|| TlsError::Protocol("bad SH".into()))?;
    if comp != 0 {
        return Err(TlsError::Protocol("bad SH compression".into()));
    }
    let exts =
        parse_extensions(c.rest()).ok_or_else(|| TlsError::Protocol("bad SH exts".into()))?;
    let mut key_share = None;
    let mut saw_supported_versions = false;
    let mut resumed = false;
    for e in exts {
        match e.ext_type {
            EXT_SUPPORTED_VERSIONS => {
                let mut v = Cur::new(e.content);
                let ver = v
                    .u16()
                    .ok_or_else(|| TlsError::Protocol("bad SH ver".into()))?;
                if ver != 0x0304 {
                    return Err(TlsError::Protocol("server does not speak TLS 1.3".into()));
                }
                saw_supported_versions = true;
            }
            super::session::EXT_PRE_SHARED_KEY => {
                let mut v = Cur::new(e.content);
                let selected = v
                    .u16()
                    .ok_or_else(|| TlsError::Protocol("bad SH psk".into()))?;
                if selected != 0 {
                    return Err(TlsError::Protocol("server selected unknown PSK".into()));
                }
                if !v.done() {
                    return Err(TlsError::Protocol("bad SH psk".into()));
                }
                resumed = true;
            }
            EXT_KEY_SHARE => {
                let mut v = Cur::new(e.content);
                let group = v
                    .u16()
                    .ok_or_else(|| TlsError::Protocol("bad SH ks".into()))?;
                let klen = v
                    .u16()
                    .ok_or_else(|| TlsError::Protocol("bad SH ks".into()))?
                    as usize;
                if group != GROUP_X25519 || klen != 32 {
                    return Err(TlsError::Protocol("unexpected key share".into()));
                }
                let mut k = [0u8; 32];
                k.copy_from_slice(
                    v.take(32)
                        .ok_or_else(|| TlsError::Protocol("bad SH ks".into()))?,
                );
                key_share = Some(k);
            }
            _ => {}
        }
    }
    if !saw_supported_versions || key_share.is_none() {
        return Err(TlsError::Protocol("SH missing required extensions".into()));
    }
    Ok(ServerHelloInfo {
        random,
        suite,
        key_share: key_share.unwrap(),
        session_id,
        resumed,
    })
}

// ---------------------------------------------------------------------
// EncryptedExtensions parsing
// ---------------------------------------------------------------------

/// The parsed content of an EncryptedExtensions message: the negotiated
/// ALPN protocol (if any) and the QUIC transport parameters (if present).
/// Per RFC 9001 §8.2 the server's `quic_transport_parameters` extension is
/// carried in EncryptedExtensions, never in the ServerHello.
#[allow(clippy::type_complexity)]
pub(crate) fn parse_encrypted_extensions(
    body: &[u8],
) -> TlsResult<(Option<Vec<u8>>, Option<Vec<u8>>)> {
    let exts = parse_extensions(body).ok_or_else(|| TlsError::Protocol("bad EE".into()))?;
    let mut alpn = None;
    let mut transport_params = None;
    for e in exts {
        if e.ext_type == EXT_ALPN {
            let mut c = Cur::new(e.content);
            let list_len =
                c.u16()
                    .ok_or_else(|| TlsError::Protocol("bad alpn".into()))? as usize;
            let list = c
                .take(list_len)
                .ok_or_else(|| TlsError::Protocol("bad alpn".into()))?;
            let mut lc = Cur::new(list);
            let plen =
                lc.u8()
                    .ok_or_else(|| TlsError::Protocol("bad alpn".into()))? as usize;
            let proto = lc
                .take(plen)
                .ok_or_else(|| TlsError::Protocol("bad alpn".into()))?;
            if !lc.done() {
                return Err(TlsError::Protocol("bad alpn".into()));
            }
            alpn = Some(proto.to_vec());
        } else if e.ext_type == EXT_QUIC_TRANSPORT_PARAMETERS {
            transport_params = Some(e.content.to_vec());
        }
    }
    Ok((alpn, transport_params))
}

// ---------------------------------------------------------------------
// Certificate parsing
// ---------------------------------------------------------------------

/// Parse a TLS 1.3 Certificate message into its request context and DER
/// entries (leaf first).
///
/// `certificate_request_context` must be echoed by the responder, and
/// RFC 8446 §4.4.2 allows no entry extensions in this version: both are
/// enforced here so a peer cannot smuggle data past the handshake.
pub(crate) fn parse_certificate(body: &[u8]) -> TlsResult<(Vec<u8>, Vec<Vec<u8>>)> {
    let mut c = Cur::new(body);
    let bad = || TlsError::Protocol("bad cert".into());
    let ctx_len = c.u8().ok_or_else(bad)? as usize;
    let ctx = c.take(ctx_len).ok_or_else(bad)?.to_vec();
    let list_len = c.u24().ok_or_else(bad)?;
    let list = c.take(list_len).ok_or_else(bad)?;
    let mut lc = Cur::new(list);
    let mut out = Vec::new();
    while !lc.done() {
        let cert_len = lc.u24().ok_or_else(bad)?;
        let cert = lc.take(cert_len).ok_or_else(bad)?;
        out.push(cert.to_vec());
        let ext_len = lc.u16().ok_or_else(bad)? as usize;
        if ext_len != 0 {
            return Err(TlsError::Protocol(
                "Certificate entry extensions are not defined in TLS 1.3".into(),
            ));
        }
    }
    Ok((ctx, out))
}

/// Parse a TLS 1.3 Certificate message and return all certificate DER
/// entries (leaf first).
pub(crate) fn parse_certificate_list(body: &[u8]) -> TlsResult<Vec<Vec<u8>>> {
    parse_certificate(body).map(|(_, entries)| entries)
}

/// Build a TLS 1.3 Certificate message (RFC 8446 §4.4.2).
pub(crate) fn build_certificate(context: &[u8], chain: &[Vec<u8>]) -> Vec<u8> {
    let mut body = Vec::new();
    body.push(context.len() as u8);
    body.extend_from_slice(context);
    let mut entries = Vec::new();
    for der in chain {
        entries.extend_from_slice(&[
            (der.len() >> 16) as u8,
            (der.len() >> 8) as u8,
            der.len() as u8,
        ]);
        entries.extend_from_slice(der);
        entries.extend_from_slice(&[0x00, 0x00]); // entry extensions
    }
    body.extend_from_slice(&[
        (entries.len() >> 16) as u8,
        (entries.len() >> 8) as u8,
        entries.len() as u8,
    ]);
    body.extend_from_slice(&entries);
    encode_hs(HS_CERTIFICATE, &body)
}

/// The signature schemes this stack can *produce* for a CertificateVerify.
/// RSA uses PKCS#1 v1.5 (the PSS schemes are verification-only here),
/// ECDSA follows the suite hash, Ed25519 is RFC 8032.
pub(crate) const CERT_VERIFY_SCHEMES: [u16; 7] = [
    0x0403, // ecdsa_secp256r1_sha256
    0x0503, // ecdsa_secp384r1_sha384
    0x0603, // ecdsa_secp521r1_sha512
    0x0807, // ed25519
    0x0401, // rsa_pkcs1_sha256
    0x0501, // rsa_pkcs1_sha384
    0x0601, // rsa_pkcs1_sha512
];

/// Build a CertificateRequest message (RFC 8446 §4.4.2).
///
/// The main-handshake context is empty, and `signature_algorithms` is the
/// one extension the RFC makes mandatory here — a client that is asked to
/// authenticate has to know which schemes will be accepted.
pub(crate) fn build_certificate_request(context: &[u8]) -> Vec<u8> {
    let mut alg_list = Vec::new();
    for scheme in CERT_VERIFY_SCHEMES {
        alg_list.extend_from_slice(&scheme.to_be_bytes());
    }
    let mut algs = Vec::new();
    algs.extend_from_slice(&(alg_list.len() as u16).to_be_bytes());
    algs.extend_from_slice(&alg_list);
    let mut exts = Vec::new();
    exts.extend_from_slice(&EXT_SIGNATURE_ALGORITHMS.to_be_bytes());
    exts.extend_from_slice(&(algs.len() as u16).to_be_bytes());
    exts.extend_from_slice(&algs);
    let mut body = Vec::new();
    body.push(context.len() as u8);
    body.extend_from_slice(context);
    body.extend_from_slice(&(exts.len() as u16).to_be_bytes());
    body.extend_from_slice(&exts);
    encode_hs(HS_CERTIFICATE_REQUEST, &body)
}

/// Parse a CertificateRequest: the request context and the offered
/// signature schemes.
///
/// A non-empty context means post-handshake authentication, which this
/// stack does not implement — refusing it is the only honest answer, and
/// it also keeps the transcript unambiguous.
pub(crate) fn parse_certificate_request(body: &[u8]) -> TlsResult<(Vec<u8>, Vec<u16>)> {
    let mut c = Cur::new(body);
    let bad = || TlsError::Protocol("bad CertificateRequest".into());
    let ctx_len = c.u8().ok_or_else(bad)? as usize;
    let ctx = c.take(ctx_len).ok_or_else(bad)?.to_vec();
    if !ctx.is_empty() {
        return Err(TlsError::Protocol(
            "post-handshake CertificateRequest is not supported".into(),
        ));
    }
    let ext_len = c.u16().ok_or_else(bad)? as usize;
    let exts = c.take(ext_len).ok_or_else(bad)?;
    let mut ec = Cur::new(exts);
    let mut schemes = Vec::new();
    while !ec.done() {
        let ext_type = ec.u16().ok_or_else(bad)?;
        let len = ec.u16().ok_or_else(bad)? as usize;
        let ext = ec.take(len).ok_or_else(bad)?;
        if ext_type == EXT_SIGNATURE_ALGORITHMS {
            let mut sc = Cur::new(ext);
            let total = sc.u16().ok_or_else(bad)? as usize;
            let list = sc.take(total).ok_or_else(bad)?;
            if list.len() % 2 != 0 {
                return Err(TlsError::Protocol("bad signature_algorithms".into()));
            }
            for pair in list.chunks(2) {
                schemes.push(u16::from_be_bytes([pair[0], pair[1]]));
            }
        }
    }
    Ok((ctx, schemes))
}

// ---------------------------------------------------------------------
// CertificateVerify parsing
// ---------------------------------------------------------------------

pub(crate) struct CertVerify {
    pub(crate) scheme: u16,
    pub(crate) signature: Vec<u8>,
}

pub(crate) fn parse_cert_verify(body: &[u8]) -> TlsResult<CertVerify> {
    let mut c = Cur::new(body);
    let scheme = c.u16().ok_or_else(|| TlsError::Protocol("bad CV".into()))?;
    let sig_len = c.u16().ok_or_else(|| TlsError::Protocol("bad CV".into()))? as usize;
    let signature = c
        .take(sig_len)
        .ok_or_else(|| TlsError::Protocol("bad CV".into()))?
        .to_vec();
    if !c.done() {
        return Err(TlsError::Protocol("bad CV".into()));
    }
    Ok(CertVerify { scheme, signature })
}

/// The signature message for CertificateVerify (RFC 8446 §4.4.3).
pub(crate) fn cert_verify_message(handshake_hash: &[u8], client: bool) -> Vec<u8> {
    let context: &[u8] = if client {
        b"TLS 1.3, client CertificateVerify\x00"
    } else {
        b"TLS 1.3, server CertificateVerify\x00"
    };
    let mut out = vec![0x20u8; 64];
    out.extend_from_slice(context);
    out.extend_from_slice(handshake_hash);
    out
}

/// Verify a CertificateVerify signature given the peer's SPKI and the
/// transcript hash. Returns Ok(()) if valid.
pub(crate) fn verify_cert_verify(
    cv: &CertVerify,
    spki: &super::x509::Spki,
    handshake_hash: &[u8],
    client: bool,
    suite: CipherSuite,
) -> TlsResult<()> {
    use super::crypto::rsa::{verify_rsa_pkcs1v15, RsaPublicKey};
    use super::crypto::{ecdsa, ed25519};
    use super::x509::der::{
        parse_rsa_public_key, OID_EC_PUBLIC_KEY, OID_ED25519, OID_RSA_ENCRYPTION,
    };

    let msg = cert_verify_message(handshake_hash, client);
    let hash = {
        let mut d: super::crypto::hash::BoxDigest = match suite.hash() {
            super::key_schedule::SuiteHash::Sha256 => Box::<super::crypto::hash::Sha256>::default(),
            super::key_schedule::SuiteHash::Sha384 => Box::<super::crypto::hash::Sha384>::default(),
        };
        d.update(&msg);
        d.finalize()
    };

    if spki.oid == OID_RSA_ENCRYPTION {
        let (n, e) = parse_rsa_public_key(&spki.key)
            .ok_or_else(|| TlsError::Certificate("bad RSA SPKI".into()))?;
        let key = RsaPublicKey { n, e };
        let ok = match cv.scheme {
            0x0804 if suite.hash() == super::key_schedule::SuiteHash::Sha256 => {
                let mut h = super::crypto::hash::Sha256::default();
                key.verify_pss(&mut h, &msg, 32, &cv.signature)
            }
            0x0805 if suite.hash() == super::key_schedule::SuiteHash::Sha384 => {
                let mut h = super::crypto::hash::Sha384::default();
                key.verify_pss(&mut h, &msg, 48, &cv.signature)
            }
            0x0401 if suite.hash() == super::key_schedule::SuiteHash::Sha256 => {
                verify_rsa_pkcs1v15(&key, false, &hash, &cv.signature)
            }
            0x0501 if suite.hash() == super::key_schedule::SuiteHash::Sha384 => {
                verify_rsa_pkcs1v15(&key, true, &hash, &cv.signature)
            }
            _ => false,
        };
        if ok {
            Ok(())
        } else {
            Err(TlsError::Certificate(
                "RSA signature verification failed".into(),
            ))
        }
    } else if spki.oid == OID_EC_PUBLIC_KEY {
        let (curve, expected_scheme) = match suite.hash() {
            super::key_schedule::SuiteHash::Sha256 => (ecdsa::Curve::P256, 0x0403),
            super::key_schedule::SuiteHash::Sha384 => (ecdsa::Curve::P384, 0x0503),
        };
        if cv.scheme != expected_scheme || spki.ec_curve != Some(curve) {
            return Err(TlsError::Certificate("unsupported EC signature".into()));
        }
        let clen = curve.coord_len();
        if spki.key.len() != 1 + 2 * clen || spki.key[0] != 0x04 {
            return Err(TlsError::Certificate("bad EC SPKI".into()));
        }
        let qx = &spki.key[1..1 + clen];
        let qy = &spki.key[1 + clen..1 + 2 * clen];
        if ecdsa::verify_der(curve, qx, qy, &hash, &cv.signature) {
            Ok(())
        } else {
            Err(TlsError::Certificate(
                "ECDSA signature verification failed".into(),
            ))
        }
    } else if spki.oid == OID_ED25519 {
        if cv.scheme != 0x0807 || spki.key.len() != 32 {
            return Err(TlsError::Certificate(
                "unsupported Ed25519 signature".into(),
            ));
        }
        let mut pk = [0u8; 32];
        pk.copy_from_slice(&spki.key);
        let mut sig = [0u8; 64];
        if cv.signature.len() != 64 {
            return Err(TlsError::Certificate("bad Ed25519 signature length".into()));
        }
        sig.copy_from_slice(&cv.signature);
        if ed25519::verify(&pk, &msg, &sig) {
            Ok(())
        } else {
            Err(TlsError::Certificate(
                "Ed25519 signature verification failed".into(),
            ))
        }
    } else {
        Err(TlsError::Certificate("unknown key type".into()))
    }
}

// ---------------------------------------------------------------------
// Finished
// ---------------------------------------------------------------------

/// Compute the Finished verify_data.
pub(crate) fn finished_verify_data(
    ks: &KeySchedule,
    secret: &[u8],
    transcript_hash: &[u8],
) -> Vec<u8> {
    let fk = ks.finished_key(secret);
    let mut d = ks.suite().hash().new_digest();
    hmac(d.as_mut(), &fk, transcript_hash)
}

// ---------------------------------------------------------------------
// Client handshake
// ---------------------------------------------------------------------

/// Client-side handshake driver.
/// Fill `buf` from OS entropy, failing the handshake when the source is
/// unavailable. Never proceed with zeroed bytes: an all-zero X25519
/// private key makes the ECDHE shared secret predictable.
pub(crate) fn fill_entropy(buf: &mut [u8]) -> TlsResult<()> {
    if super::crypto::rng::fill_random(buf) {
        Ok(())
    } else {
        Err(TlsError::Internal(
            "cryptographic RNG unavailable; refusing to generate a predictable key".into(),
        ))
    }
}

/// RFC 7748 §6.1: an X25519 peer share that is a low-order point (such
/// as u = 0) yields an all-zero shared secret. Reject it instead of
/// silently keying the connection with a predictable all-zero value.
/// rustls/BoringSSL abort the handshake on this condition.
pub(crate) fn validate_shared_secret(shared: &[u8; 32]) -> TlsResult<()> {
    if shared.iter().all(|&b| b == 0) {
        return Err(TlsError::Protocol(
            "peer X25519 share produced an all-zero shared secret".into(),
        ));
    }
    Ok(())
}

pub(crate) struct ClientHandshake {
    pub(crate) server_name: Option<String>,
    pub(crate) verify: bool,
    /// A resumption PSK to offer (RFC 8446 §4.2.11), with its suite.
    pub(crate) psk: Option<(Vec<u8>, CipherSuite)>,
    /// The client certificate to present when the server asks for one
    /// (mTLS). `None` answers a CertificateRequest with an empty
    /// Certificate — which a server that *requires* authentication
    /// rejects, as it should.
    pub(crate) identity: Option<super::Identity>,
}

impl ClientHandshake {
    /// Continue a client handshake whose ClientHello has already been
    /// sent and whose ServerHello has already been read (used by the
    /// version-negotiating connector, which must see the ServerHello to
    /// decide between the TLS 1.3 and TLS 1.2 paths).
    #[allow(clippy::too_many_arguments)]
    /// * `hrr` — when the handshake went through a HelloRetryRequest,
    ///   the `(ClientHello1, HelloRetryRequest, ClientHello2)` messages;
    ///   the transcript then starts with `message_hash(Hash(CH1)) ||
    ///   HRR || CH2` (RFC 8446 §4.4.1) instead of a single ClientHello.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn run_from_server_hello<
        R: crate::courierust_io::Read,
        W: crate::courierust_io::Write,
    >(
        &self,
        io: &mut super::TlsIo<R, W>,
        roots: &super::x509::RootStore,
        now: i64,
        ch: &[u8],
        _random: &[u8; 32],
        priv_key: &[u8; 32],
        sh_body: &[u8],
        hrr: Option<(&[u8], &[u8], &[u8])>,
    ) -> TlsResult<HandshakeResult> {
        let sh = parse_server_hello(sh_body)?;
        if !sh.session_id.is_empty() {
            return Err(TlsError::Protocol("ServerHello session id mismatch".into()));
        }

        let mut transcript = Transcript::new(sh.suite.hash());
        match hrr {
            Some((ch1, hrr_msg, ch2)) => {
                transcript.update(&message_hash_message(ch1, sh.suite));
                transcript.update(hrr_msg);
                transcript.update(ch2);
            }
            None => transcript.update(ch),
        }
        let sh_msg = encode_hs(HS_SERVER_HELLO, sh_body);
        transcript.update(&sh_msg);

        let shared = x25519::x25519(priv_key, &sh.key_share);
        validate_shared_secret(&shared)?;
        let th = transcript.current_hash();
        let mut ks = if sh.resumed {
            let (psk, psk_suite) = self
                .psk
                .clone()
                .ok_or_else(|| TlsError::Protocol("server resumed without a PSK offer".into()))?;
            if psk_suite != sh.suite {
                return Err(TlsError::Protocol(
                    "resumption cipher suite does not match the PSK".into(),
                ));
            }
            KeySchedule::handshake_with_psk(sh.suite, &shared, &psk, &th)
        } else {
            KeySchedule::handshake(sh.suite, &shared, &th)
        };
        let _ = sh.random;

        let s_hs_keys = ks.server_handshake_keys();
        let plaintext = io.read_encrypted_handshake(sh.suite, &s_hs_keys)?;
        let mut messages = Vec::new();
        let mut rest = &plaintext[..];
        while !rest.is_empty() {
            let m =
                parse_hs(rest).ok_or_else(|| TlsError::Protocol("bad handshake stream".into()))?;
            let total = 4 + m.body.len();
            messages.push((m.msg_type, m.body.to_vec()));
            rest = &rest[total..];
        }

        let mut peer_chain = None;
        let mut cv = None;
        let mut negotiated_alpn = None;
        let mut saw_ee = false;
        // A CertificateRequest (mTLS, RFC 8446 §4.4.2) arrives after
        // EncryptedExtensions and before the server's Certificate; the
        // schemes it offers bound what this client may sign with.
        let mut client_auth: Option<Vec<u16>> = None;
        let mut saw_certificate = false;
        for (t, body) in &messages {
            match *t {
                HS_ENCRYPTED_EXTENSIONS => {
                    let (alpn, _transport_params) = parse_encrypted_extensions(body)?;
                    negotiated_alpn = alpn;
                    saw_ee = true;
                }
                HS_CERTIFICATE_REQUEST => {
                    if client_auth.is_some() || saw_certificate {
                        return Err(TlsError::Protocol("CertificateRequest out of order".into()));
                    }
                    let (_context, schemes) = parse_certificate_request(body)?;
                    client_auth = Some(schemes);
                }
                HS_CERTIFICATE => {
                    saw_certificate = true;
                    peer_chain = Some(parse_certificate_list(body)?);
                }
                HS_CERTIFICATE_VERIFY => {
                    cv = Some(parse_cert_verify(body)?);
                }
                HS_FINISHED => {}
                _ => {
                    return Err(TlsError::Protocol("unexpected server message".into()));
                }
            }
        }
        if !saw_ee {
            return Err(TlsError::Protocol("missing EncryptedExtensions".into()));
        }
        let peer_chain =
            peer_chain.ok_or_else(|| TlsError::Protocol("missing Certificate".into()))?;
        if peer_chain.is_empty() {
            return Err(TlsError::Protocol("empty certificate list".into()));
        }
        let peer_cert_der = peer_chain[0].clone();
        let cv = cv.ok_or_else(|| TlsError::Protocol("missing CertificateVerify".into()))?;

        for (t, body) in &messages {
            if *t == HS_ENCRYPTED_EXTENSIONS || *t == HS_CERTIFICATE_REQUEST || *t == HS_CERTIFICATE
            {
                transcript.update(&encode_hs(*t, body));
            }
        }
        let cv_hash = transcript.current_hash();

        let leaf = super::x509::parse_certificate(&peer_cert_der)?;
        let spki = leaf.spki.clone();
        if self.verify {
            let name = self.server_name.as_deref().unwrap_or("");
            if !super::x509::hostname_matches(name, &leaf.dns_names, &leaf.ip_names) {
                return Err(TlsError::Certificate("hostname mismatch".into()));
            }
            super::x509::validate_chain(roots, &peer_chain, now)?;
            if !super::x509::has_server_auth_eku(&leaf) {
                return Err(TlsError::Certificate(
                    "leaf certificate lacks TLS serverAuth EKU".into(),
                ));
            }
        }

        // Verify the CertificateVerify signature.
        verify_cert_verify(&cv, &spki, &cv_hash, false, sh.suite)?;

        // Add CV to transcript.
        transcript.update(&encode_hs(HS_CERTIFICATE_VERIFY, &cv_body(&messages)));

        // Verify server Finished (hash before Finished).
        let finished_body = messages
            .iter()
            .find(|(t, _)| *t == HS_FINISHED)
            .map(|(_, b)| b.clone())
            .ok_or_else(|| TlsError::Protocol("missing Finished".into()))?;
        let server_fin_hash = transcript.current_hash();
        let expected_fin = finished_verify_data(&ks, ks.server_handshake(), &server_fin_hash);
        if !constant_time_eq(&expected_fin, &finished_body) {
            return Err(TlsError::Alert {
                level: 2,
                description: 51, // decrypt_error
            });
        }

        transcript.update(&encode_hs(HS_FINISHED, &finished_body));
        let after_fin_hash = transcript.current_hash();
        ks.application(&after_fin_hash)?;

        // mTLS (RFC 8446 §4.4.2): answer a CertificateRequest with the
        // client certificate and a CertificateVerify over the transcript
        // that now ends at the server's Finished. With no suitable
        // certificate the mandated answer is an *empty* Certificate, not
        // silence — the server decides whether that is acceptable.
        let mut client_flight = Vec::new();
        if let Some(schemes) = client_auth {
            client_flight = match &self.identity {
                Some(identity) => {
                    let cert = build_certificate(&[], &identity.cert_chain);
                    transcript.update(&cert);
                    let cv_hash = transcript.current_hash();
                    let content = cert_verify_message(&cv_hash, true);
                    let (scheme, signature) = super::sign::sign_cert_verify(
                        identity, &content, sh.suite,
                    )?
                    .ok_or_else(|| TlsError::Certificate("client identity cannot sign".into()))?;
                    if !schemes.is_empty() && !schemes.contains(&scheme) {
                        return Err(TlsError::Certificate(
                            "the server does not accept the scheme this client certificate \
                             signs with"
                                .into(),
                        ));
                    }
                    let mut cv_body = Vec::new();
                    cv_body.extend_from_slice(&scheme.to_be_bytes());
                    cv_body.extend_from_slice(&(signature.len() as u16).to_be_bytes());
                    cv_body.extend_from_slice(&signature);
                    let cv = encode_hs(HS_CERTIFICATE_VERIFY, &cv_body);
                    transcript.update(&cv);
                    let mut flight = cert;
                    flight.extend_from_slice(&cv);
                    flight
                }
                None => {
                    let cert = build_certificate(&[], &[]);
                    transcript.update(&cert);
                    cert
                }
            };
        }

        let client_fin_hash = transcript.current_hash();
        let client_fin = finished_verify_data(&ks, ks.client_handshake(), &client_fin_hash);
        let client_fin_msg = encode_hs(HS_FINISHED, &client_fin);
        client_flight.extend_from_slice(&client_fin_msg);
        let c_hs_keys = ks.client_handshake_keys();
        io.write_encrypted_record(sh.suite, &c_hs_keys, CONTENT_HANDSHAKE, &client_flight)?;
        transcript.update(&client_fin_msg);

        let resumption_master = Some(ks.resumption_master(&transcript.current_hash()));

        let write = ks.client_application_keys();
        let read = ks.server_application_keys();
        Ok(HandshakeResult {
            suite: sh.suite,
            keys: AppKeys {
                write,
                read,
                write_secret: ks.client_application_secret().to_vec(),
                read_secret: ks.server_application_secret().to_vec(),
            },
            alpn: negotiated_alpn,
            server_name: self.server_name.clone(),
            peer_cert: Some(peer_cert_der),
            resumed: sh.resumed,
            resumption_master,
        })
    }
}

/// Recover the raw body bytes of the CertificateVerify message from the
/// message list (used to continue the transcript).
fn cv_body(messages: &[(u8, Vec<u8>)]) -> Vec<u8> {
    messages
        .iter()
        .find(|(t, _)| *t == HS_CERTIFICATE_VERIFY)
        .map(|(_, b)| b.clone())
        .unwrap_or_default()
}

/// Constant-time comparison.
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff = 0u8;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

// ---------------------------------------------------------------------
// Server handshake
// ---------------------------------------------------------------------

/// Server-side handshake driver.
pub(crate) struct ServerHandshake {
    pub(crate) identity: super::Identity,
    pub(crate) alpn: Vec<Vec<u8>>,
    /// Key used to encrypt/decrypt session tickets. `None` disables
    /// session resumption (the QUIC path passes None).
    pub(crate) ticket_key: Option<[u8; 32]>,
    /// Current Unix time (used to validate ticket age).
    pub(crate) now: i64,
    /// Client authentication (mTLS). `None` sends no CertificateRequest,
    /// which is what a plain server does; when set, the client's chain is
    /// validated against its roots, and an anonymous client is rejected
    /// if the configuration requires one.
    pub(crate) client_auth: Option<super::ClientAuth>,
}

impl ServerHandshake {
    /// Continue a server handshake whose ClientHello has already been
    /// read (used by the version-negotiating acceptor).
    pub(crate) fn run_from_client_hello<
        R: crate::courierust_io::Read,
        W: crate::courierust_io::Write,
    >(
        &self,
        io: &mut super::TlsIo<R, W>,
        ch_body: &[u8],
    ) -> TlsResult<HandshakeResult> {
        let suite_hash_pref = super::sign::tls13_suite_hash_pref(&self.identity);

        // 1. Read ClientHello. If the client supports X25519 but did not
        //    offer a share, send a HelloRetryRequest (RFC 8446 §4.1.4)
        //    and read the retried ClientHello. The transcript replaces
        //    ClientHello1 with message_hash(Hash(ClientHello1)) and then
        //    appends HelloRetryRequest and ClientHello2 (§4.4.1); a PSK
        //    binder in ClientHello2 is computed over CH1 || HRR ||
        //    Truncate(CH2) (§4.2.11.2).
        let mut ch = parse_client_hello(ch_body, suite_hash_pref)?;
        let mut transcript = Transcript::new(ch.suite.hash());
        // The ClientHello body that carries the resumption offer, plus
        // the (ClientHello1, HelloRetryRequest) pair when a retry
        // happened (the CH2 binder is over CH1 || HRR || Truncate(CH2)).
        let mut resume_body: Vec<u8> = ch_body.to_vec();
        let mut hrr_prefix: Option<(Vec<u8>, Vec<u8>)> = None;
        if ch.key_share.is_none() {
            if !ch.x25519_in_groups {
                return Err(TlsError::Protocol(
                    "no mutually supported key exchange group".into(),
                ));
            }
            let hrr = build_hello_retry_request(ch.suite, &ch.session_id);
            io.write_plaintext_record(CONTENT_HANDSHAKE, &hrr)?;
            let (ct2, ch2) = io.read_plaintext_record()?;
            if ct2 != CONTENT_HANDSHAKE || ch2.len() < 4 || ch2[0] != HS_CLIENT_HELLO {
                return Err(TlsError::Protocol("expected a retried ClientHello".into()));
            }
            let ch2_body = ch2[4..].to_vec();
            let ch2_info = parse_client_hello(&ch2_body, suite_hash_pref)?;
            let ch2_share = ch2_info.key_share.ok_or_else(|| {
                TlsError::Protocol("retried ClientHello lacks an X25519 share".into())
            })?;
            if ch2_info.suite != ch.suite {
                return Err(TlsError::Protocol(
                    "retried ClientHello changed the cipher suite".into(),
                ));
            }
            let ch1_msg = encode_hs(HS_CLIENT_HELLO, ch_body);
            transcript.update(&message_hash_message(&ch1_msg, ch.suite));
            transcript.update(&hrr);
            transcript.update(&encode_hs(HS_CLIENT_HELLO, &ch2_body));
            ch.key_share = Some(ch2_share);
            ch.session_id = ch2_info.session_id;
            ch.server_name = ch2_info.server_name;
            ch.alpn = ch2_info.alpn;
            ch.transport_params = ch2_info.transport_params;
            resume_body = ch2_body;
            hrr_prefix = Some((ch1_msg, hrr));
        } else {
            transcript.update(&encode_hs(HS_CLIENT_HELLO, ch_body));
        }

        // 1b. Resumption: a well-formed pre_shared_key offer whose ticket
        // decrypts, matches the negotiated suite, and carries a valid
        // binder resumes the session (RFC 8446 §4.2.11). Any failure
        // falls back to a full handshake (the client proceeds without the
        // PSK), except a malformed offer, which is a protocol error.
        let mut resumed = false;
        let mut resume_psk: Option<Vec<u8>> = None;
        if let Some(offer) = super::session::parse_pre_shared_key(&resume_body)? {
            if let Some(key) = self.ticket_key {
                if let Ok((ticket_suite, psk)) =
                    super::session::decrypt_ticket(&key, &offer.ticket, self.now)
                {
                    let binder_ok = match &hrr_prefix {
                        Some((ch1, hrr)) => super::session::verify_binder_hrr(
                            ch1,
                            hrr,
                            &resume_body,
                            &offer,
                            ch.suite,
                            &psk,
                        ),
                        None => super::session::verify_binder(&resume_body, &offer, ch.suite, &psk),
                    };
                    if ticket_suite == ch.suite && binder_ok {
                        resumed = true;
                        resume_psk = Some(psk);
                    }
                }
            }
        }

        // 2. ECDHE + ServerHello. Same fail-closed entropy requirement as
        //    the client: an all-zero server private key would make the
        //    session keys predictable to a passive attacker.
        let ch_share = ch.key_share.expect("X25519 share resolved above");
        let mut s_priv = [0u8; 32];
        fill_entropy(&mut s_priv)?;
        let s_pub = x25519::x25519(&s_priv, &x25519::BASE_POINT);
        let shared = x25519::x25519(&s_priv, &ch_share);
        validate_shared_secret(&shared)?;
        let mut random = [0u8; 32];
        fill_entropy(&mut random)?;
        let sh = if resumed {
            super::session::build_server_hello_psk(&random, &s_pub, ch.suite, &ch.session_id)
        } else {
            build_server_hello(&random, &s_pub, ch.suite, &ch.session_id)
        };
        io.write_plaintext_record(CONTENT_HANDSHAKE, &sh)?;
        let sh_body = sh[4..].to_vec();
        transcript.update(&encode_hs(HS_SERVER_HELLO, &sh_body));

        let th = transcript.current_hash();
        let mut ks = if resumed {
            let psk = resume_psk.expect("resume psk set above");
            KeySchedule::handshake_with_psk(ch.suite, &shared, &psk, &th)
        } else {
            KeySchedule::handshake(ch.suite, &shared, &th)
        };

        // 3. EncryptedExtensions, Certificate, CertificateVerify, Finished.
        let mut ee_body = Vec::new();
        // ALPN (RFC 7301): the server selects exactly ONE protocol from
        // the client's offer, in server-preference order.
        let negotiated_alpn = self
            .alpn
            .iter()
            .find(|p| ch.alpn.iter().any(|c| c == *p))
            .cloned();
        let mut ee_exts: Vec<(u16, Vec<u8>)> = Vec::new();
        if let Some(proto) = &negotiated_alpn {
            let mut proto_list = Vec::new();
            proto_list.push(proto.len() as u8);
            proto_list.extend_from_slice(proto);
            let mut alpn_body = Vec::new();
            alpn_body.extend_from_slice(&(proto_list.len() as u16).to_be_bytes());
            alpn_body.extend_from_slice(&proto_list);
            ee_exts.push((EXT_ALPN, alpn_body));
        }
        let mut ee_bytes = Vec::new();
        for (t, c) in ee_exts {
            ee_bytes.extend_from_slice(&t.to_be_bytes());
            ee_bytes.extend_from_slice(&(c.len() as u16).to_be_bytes());
            ee_bytes.extend_from_slice(&c);
        }
        ee_body.extend_from_slice(&(ee_bytes.len() as u16).to_be_bytes());
        ee_body.extend_from_slice(&ee_bytes);
        let ee = encode_hs(HS_ENCRYPTED_EXTENSIONS, &ee_body);

        // Certificate message.
        let cert = build_certificate(&[], &self.identity.cert_chain);

        // mTLS: the CertificateRequest goes between EncryptedExtensions
        // and Certificate, and the transcript follows the wire order.
        let cr = self
            .client_auth
            .as_ref()
            .map(|_| build_certificate_request(&[]));
        transcript.update(&ee);
        if let Some(cr) = &cr {
            transcript.update(cr);
        }
        transcript.update(&cert);

        // CertificateVerify: sign the transcript hash. Per RFC 8446
        // §4.4.3 the signature is computed over the concatenation
        // `64 x 0x20 || "TLS 1.3, server CertificateVerify" || 0x00 ||
        // transcript-hash` (the digest schemes hash that content; Ed25519
        // signs it verbatim).
        let cv_hash = transcript.current_hash();
        let sig_content = cert_verify_message(&cv_hash, false);
        let cv = match super::server_sign(&self.identity, &sig_content, ch.suite)? {
            Some((scheme, signature)) => {
                let mut cv_body = Vec::new();
                cv_body.extend_from_slice(&scheme.to_be_bytes());
                cv_body.extend_from_slice(&(signature.len() as u16).to_be_bytes());
                cv_body.extend_from_slice(&signature);
                encode_hs(HS_CERTIFICATE_VERIFY, &cv_body)
            }
            None => {
                // No signing identity configured — reject (server must
                // authenticate).
                return Err(TlsError::Certificate(
                    "no server identity configured".into(),
                ));
            }
        };
        transcript.update(&cv);

        // Finished: hash before adding Finished.
        let fin_hash = transcript.current_hash();
        let fin = finished_verify_data(&ks, ks.server_handshake(), &fin_hash);
        let fin_msg = encode_hs(HS_FINISHED, &fin);
        transcript.update(&fin_msg);

        // Derive app secrets (transcript includes server Finished).
        let after_fin_hash = transcript.current_hash();
        ks.application(&after_fin_hash)?;

        // Send the encrypted flight.
        let s_hs_keys = ks.server_handshake_keys();
        let mut flight = ee;
        if let Some(cr) = &cr {
            flight.extend_from_slice(cr);
        }
        flight.extend_from_slice(&cert);
        flight.extend_from_slice(&cv);
        flight.extend_from_slice(&fin_msg);
        io.write_encrypted_record(ch.suite, &s_hs_keys, CONTENT_HANDSHAKE, &flight)?;

        // 4. Read the client flight: [Certificate, CertificateVerify,]
        //    Finished (RFC 8446 §4.4.2).
        let c_hs_keys = ks.client_handshake_keys();
        let plaintext = io.read_encrypted_handshake(ch.suite, &c_hs_keys)?;
        let mut off = 0usize;
        let mut client_cert: Option<(Vec<u8>, Vec<Vec<u8>>)> = None;
        let mut client_cv: Option<CertVerify> = None;
        let mut finished_body: Option<Vec<u8>> = None;
        while off + 4 <= plaintext.len() {
            let m = parse_hs(&plaintext[off..])
                .ok_or_else(|| TlsError::Protocol("bad client flight".into()))?;
            let total = 4 + m.body.len();
            match m.msg_type {
                HS_CERTIFICATE if client_cert.is_none() && client_cv.is_none() => {
                    let parsed = parse_certificate(m.body)?;
                    if !parsed.0.is_empty() {
                        return Err(TlsError::Protocol(
                            "client certificate request context mismatch".into(),
                        ));
                    }
                    transcript.update(&plaintext[off..off + total]);
                    client_cert = Some(parsed);
                }
                HS_CERTIFICATE_VERIFY if client_cert.is_some() && client_cv.is_none() => {
                    let cv = parse_cert_verify(m.body)?;
                    let entries = &client_cert.as_ref().expect("checked above").1;
                    if entries.is_empty() {
                        return Err(TlsError::Protocol(
                            "CertificateVerify without a client certificate".into(),
                        ));
                    }
                    let cv_hash = transcript.current_hash();
                    let leaf = super::x509::parse_certificate(&entries[0])?;
                    if let Err(e) = verify_cert_verify(&cv, &leaf.spki, &cv_hash, true, ch.suite) {
                        // bad_certificate (42): the signature does not
                        // prove possession of the offered certificate.
                        send_alert(io, ch.suite, &ks.server_application_keys(), 2, 42)?;
                        return Err(e);
                    }
                    transcript.update(&plaintext[off..off + total]);
                    client_cv = Some(cv);
                }
                HS_FINISHED if finished_body.is_none() => {
                    finished_body = Some(m.body.to_vec());
                }
                _ => return Err(TlsError::Protocol("unexpected client message".into())),
            }
            off += total;
        }
        if off != plaintext.len() {
            return Err(TlsError::Protocol(
                "trailing bytes in the client flight".into(),
            ));
        }

        // mTLS policy. An empty certificate list is the mandated way to
        // decline (RFC 8446 §4.4.2) — accepted only when this server
        // asked for authentication without requiring it. A certificate
        // that *is* offered is always validated: chain against the
        // configured roots, validity window, and the clientAuth EKU.
        let client_cert = match client_cert {
            Some((_, entries)) if entries.is_empty() => None,
            other => other,
        };
        match (&self.client_auth, &client_cert) {
            (None, Some(_)) => {
                send_alert(io, ch.suite, &ks.server_application_keys(), 2, 10)?;
                return Err(TlsError::Protocol(
                    "client sent a certificate that was not requested".into(),
                ));
            }
            (Some(auth), Some((_, entries))) => {
                let leaf = super::x509::parse_certificate(&entries[0])?;
                let refused = super::x509::validate_chain(auth.roots(), entries, self.now)
                    .and_then(|()| {
                        if super::x509::has_client_auth_eku(&leaf) {
                            Ok(())
                        } else {
                            Err(TlsError::Certificate(
                                "client certificate does not carry the clientAuth EKU".into(),
                            ))
                        }
                    });
                if let Err(e) = refused {
                    // bad_certificate (42): the chain or its key usage
                    // does not qualify.
                    send_alert(io, ch.suite, &ks.server_application_keys(), 2, 42)?;
                    return Err(e);
                }
                if client_cv.is_none() {
                    send_alert(io, ch.suite, &ks.server_application_keys(), 2, 47)?;
                    return Err(TlsError::Protocol(
                        "client certificate without a CertificateVerify".into(),
                    ));
                }
            }
            (Some(auth), None) => {
                if auth.is_required() {
                    // RFC 8446 §6.2: `certificate_required` (116).
                    send_alert(io, ch.suite, &ks.server_application_keys(), 2, 116)?;
                    return Err(TlsError::Alert {
                        level: 2,
                        description: 116,
                    });
                }
            }
            (None, None) => {}
        }

        let finished_body =
            finished_body.ok_or_else(|| TlsError::Protocol("missing client Finished".into()))?;
        let client_fin_hash = transcript.current_hash();
        let expected = finished_verify_data(&ks, ks.client_handshake(), &client_fin_hash);
        if !constant_time_eq(&expected, &finished_body) {
            return Err(TlsError::Alert {
                level: 2,
                description: 51,
            });
        }
        transcript.update(&encode_hs(HS_FINISHED, &finished_body));

        let write = ks.server_application_keys();
        let read = ks.client_application_keys();

        // The application keys start a fresh record sequence space
        // (RFC 8446 §5.2: sequence numbers reset at each key change).
        io.reset_sequences();

        // 5. Issue a NewSessionTicket (session resumption, RFC 8446
        //    §4.6.1). Sent after the handshake, protected by the server
        //    application keys. The PSK is derived from the resumption
        //    master secret with a fresh nonce and encrypted inside the
        //    ticket with the server-held ticket key.
        if let Some(key) = self.ticket_key {
            let mut nonce = [0u8; 8];
            fill_entropy(&mut nonce)?;
            let psk = ks.resumption_psk(&transcript.current_hash(), &nonce);
            let ticket = super::session::encrypt_ticket(&key, ch.suite, &psk, self.now);
            let msg = super::session::build_new_session_ticket(
                super::session::SESSION_LIFETIME_SECS as u32,
                &nonce,
                &ticket,
            );
            io.write_encrypted_record(ch.suite, &write, CONTENT_HANDSHAKE, &msg)?;
        }

        Ok(HandshakeResult {
            suite: ch.suite,
            keys: AppKeys {
                write,
                read,
                write_secret: ks.server_application_secret().to_vec(),
                read_secret: ks.client_application_secret().to_vec(),
            },
            alpn: negotiated_alpn,
            server_name: ch.server_name,
            // The authenticated peer's leaf, for the layer above to
            // authorize on (mTLS): `None` when no certificate was asked
            // for, or when the client declined an optional request.
            peer_cert: client_cert.map(|(_, entries)| entries[0].clone()),
            resumed,
            resumption_master: None,
        })
    }
}

/// Send an alert to the peer (RFC 8446 §6.2). A refusal has to be
/// *signalled*, not just implied by a closed stream. The record is
/// protected with the application keys: once the server's Finished is on
/// the wire that is the epoch the peer reads from, and where its read
/// sequence numbers restart.
fn send_alert<R: crate::courierust_io::Read, W: crate::courierust_io::Write>(
    io: &mut super::TlsIo<R, W>,
    suite: CipherSuite,
    keys: &TrafficKeys,
    level: u8,
    description: u8,
) -> TlsResult<()> {
    io.reset_sequences();
    io.write_encrypted_record(suite, keys, CONTENT_ALERT, &[level, description])
}

/// Parsed ClientHello essentials.
pub(crate) struct ClientHelloInfo {
    pub(crate) suite: CipherSuite,
    /// The client's X25519 key share, when one was offered.
    pub(crate) key_share: Option<[u8; 32]>,
    /// Whether X25519 appears in the client's `supported_groups` (used to
    /// decide between a HelloRetryRequest and a hard failure).
    pub(crate) x25519_in_groups: bool,
    pub(crate) server_name: Option<String>,
    /// ALPN protocols offered by the client.
    pub(crate) alpn: Vec<Vec<u8>>,
    /// The client's legacy_session_id (RFC 8446 §4.1.3: the server MUST
    /// echo it verbatim in the ServerHello, or a conforming client will
    /// abort with illegal_parameter).
    pub(crate) session_id: Vec<u8>,
    /// QUIC transport parameters, when present.
    pub(crate) transport_params: Option<Vec<u8>>,
}

/// Parse a ClientHello. `suite_hash_pref` (from the server identity key)
/// restricts the chosen cipher suite to one whose hash matches the EC
/// identity curve, so the CertificateVerify scheme is always valid.
pub(crate) fn parse_client_hello(
    body: &[u8],
    suite_hash_pref: Option<super::key_schedule::SuiteHash>,
) -> TlsResult<ClientHelloInfo> {
    let mut c = Cur::new(body);
    // legacy_version
    c.u16().ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
    c.take(32)
        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?; // random
    let sid_len = c.u8().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
    if sid_len > 32 {
        return Err(TlsError::Protocol("bad CH sid".into()));
    }
    let session_id = c
        .take(sid_len)
        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?
        .to_vec();
    // cipher suites
    let suites_len = c.u16().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
    if suites_len < 2 || suites_len % 2 != 0 {
        return Err(TlsError::Protocol("bad CH suites".into()));
    }
    let suites = c
        .take(suites_len)
        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
    let mut offered: Vec<u16> = Vec::new();
    for w in suites.chunks(2) {
        offered.push(u16::from_be_bytes([w[0], w[1]]));
    }
    // compression
    let comp_len = c.u8().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
    c.take(comp_len)
        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;

    let exts =
        parse_extensions(c.rest()).ok_or_else(|| TlsError::Protocol("bad CH exts".into()))?;
    let mut key_share = None;
    let mut x25519_in_groups = false;
    let mut server_name = None;
    let mut client_alpn: Vec<Vec<u8>> = Vec::new();
    let mut saw_versions = false;
    let mut transport_params = None;
    for e in exts {
        match e.ext_type {
            EXT_SUPPORTED_VERSIONS => {
                let mut v = Cur::new(e.content);
                let list_len = v.u8().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
                let list = v
                    .take(list_len)
                    .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
                if list.contains(&0x03) && list.contains(&0x04) {
                    saw_versions = true;
                }
            }
            EXT_SUPPORTED_GROUPS => {
                let mut v = Cur::new(e.content);
                let list_len = v.u16().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
                let list = v
                    .take(list_len)
                    .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
                let mut lc = Cur::new(list);
                while !lc.done() {
                    let group = lc
                        .u16()
                        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
                    if group == GROUP_X25519 {
                        x25519_in_groups = true;
                    }
                }
            }
            EXT_KEY_SHARE => {
                let mut v = Cur::new(e.content);
                let list_len = v.u16().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
                let list = v
                    .take(list_len)
                    .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
                let mut lc = Cur::new(list);
                while !lc.done() {
                    let group = lc
                        .u16()
                        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
                    let klen = lc
                        .u16()
                        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?
                        as usize;
                    let k = lc
                        .take(klen)
                        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
                    if group == GROUP_X25519 && klen == 32 {
                        let mut ks = [0u8; 32];
                        ks.copy_from_slice(k);
                        key_share = Some(ks);
                    }
                }
            }
            EXT_ALPN => {
                let mut v = Cur::new(e.content);
                let list_len = v.u16().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
                let list = v
                    .take(list_len)
                    .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
                let mut lc = Cur::new(list);
                while !lc.done() {
                    let plen = lc.u8().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
                    let p = lc
                        .take(plen)
                        .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
                    client_alpn.push(p.to_vec());
                }
            }
            EXT_SERVER_NAME => {
                let mut v = Cur::new(e.content);
                let list_len = v.u16().ok_or_else(|| TlsError::Protocol("bad CH".into()))? as usize;
                let list = v
                    .take(list_len)
                    .ok_or_else(|| TlsError::Protocol("bad CH".into()))?;
                let mut lc = Cur::new(list);
                if let Some(typ) = lc.u8() {
                    if typ == 0 {
                        let nlen = lc
                            .u16()
                            .ok_or_else(|| TlsError::Protocol("bad CH".into()))?
                            as usize;
                        if let Some(name) = lc.take(nlen) {
                            if let Ok(s) = core::str::from_utf8(name) {
                                server_name = Some(s.to_string());
                            }
                        }
                    }
                }
            }
            EXT_QUIC_TRANSPORT_PARAMETERS => {
                if transport_params.is_some() {
                    return Err(TlsError::Protocol(
                        "duplicate QUIC transport parameters".into(),
                    ));
                }
                transport_params = Some(e.content.to_vec());
            }
            _ => {}
        }
    }
    if !saw_versions {
        return Err(TlsError::Protocol("CH missing supported_versions".into()));
    }
    // Choose the first offered suite we support whose hash matches the
    // identity key (for EC identities the TLS 1.3 ECDSA scheme is fixed
    // by the suite hash).
    let suite = CLIENT_SUITES
        .iter()
        .copied()
        .filter(|s| suite_hash_pref.map_or(true, |h| s.hash() == h))
        .find(|s| offered.contains(&s.wire()))
        .ok_or_else(|| TlsError::Protocol("no shared cipher suite".into()))?;
    Ok(ClientHelloInfo {
        suite,
        key_share,
        x25519_in_groups,
        session_id,
        server_name,
        alpn: client_alpn,
        transport_params,
    })
}

/// Whether a ServerHello is actually a HelloRetryRequest (RFC 8446
/// §4.1.3: the random value equals SHA-256("HelloRetryRequest")).
pub(crate) fn is_hello_retry_request(body: &[u8]) -> bool {
    let mut c = Cur::new(body);
    if c.u16().is_none() {
        return false;
    }
    match c.take(32) {
        Some(r) => r == HRR_RANDOM,
        None => false,
    }
}

/// A parsed HelloRetryRequest (RFC 8446 §4.1.4).
pub(crate) struct HrrInfo {
    /// The group the server wants a share for (key_share extension).
    pub(crate) selected_group: u16,
}

/// Parse a HelloRetryRequest body. The client MUST verify that
/// `supported_versions` is 0x0304 and that `key_share` carries the
/// selected group; the caller then decides whether it can comply.
pub(crate) fn parse_hello_retry_request(body: &[u8]) -> Result<HrrInfo, TlsError> {
    let mut c = Cur::new(body);
    c.u16()
        .ok_or_else(|| TlsError::Protocol("bad HRR".into()))?; // legacy_version
    let random = c
        .take(32)
        .ok_or_else(|| TlsError::Protocol("bad HRR".into()))?;
    if random != HRR_RANDOM {
        return Err(TlsError::Protocol("not a HelloRetryRequest".into()));
    }
    let sid_len = c.u8().ok_or_else(|| TlsError::Protocol("bad HRR".into()))? as usize;
    c.take(sid_len)
        .ok_or_else(|| TlsError::Protocol("bad HRR".into()))?; // session id echo
    c.u16()
        .ok_or_else(|| TlsError::Protocol("bad HRR".into()))?; // cipher_suite
    let comp = c.u8().ok_or_else(|| TlsError::Protocol("bad HRR".into()))?;
    if comp != 0 {
        return Err(TlsError::Protocol("bad HRR compression".into()));
    }
    let exts =
        parse_extensions(c.rest()).ok_or_else(|| TlsError::Protocol("bad HRR exts".into()))?;
    let mut selected_group = None;
    let mut saw_versions = false;
    for e in exts {
        match e.ext_type {
            EXT_SUPPORTED_VERSIONS => {
                let mut v = Cur::new(e.content);
                let ver = v
                    .u16()
                    .ok_or_else(|| TlsError::Protocol("bad HRR ver".into()))?;
                if ver != 0x0304 {
                    return Err(TlsError::Protocol(
                        "HRR selected a version below TLS 1.3".into(),
                    ));
                }
                saw_versions = true;
            }
            EXT_KEY_SHARE => {
                let mut v = Cur::new(e.content);
                selected_group = Some(
                    v.u16()
                        .ok_or_else(|| TlsError::Protocol("bad HRR key_share".into()))?,
                );
            }
            EXT_COOKIE => {
                // Validate the stateless cookie's framing; this client has
                // no re-issue path, so the content is not retained.
                let mut v = Cur::new(e.content);
                let len = v
                    .u16()
                    .ok_or_else(|| TlsError::Protocol("bad HRR cookie".into()))?
                    as usize;
                v.take(len)
                    .ok_or_else(|| TlsError::Protocol("bad HRR cookie".into()))?;
            }
            _ => {}
        }
    }
    if !saw_versions || selected_group.is_none() {
        return Err(TlsError::Protocol("HRR missing required extensions".into()));
    }
    Ok(HrrInfo {
        selected_group: selected_group.unwrap(),
    })
}

/// Build a HelloRetryRequest (full message) requesting an X25519 share,
/// echoing the client's session id (RFC 8446 §4.1.4).
pub(crate) fn build_hello_retry_request(suite: CipherSuite, session_id: &[u8]) -> Vec<u8> {
    let mut body = Vec::new();
    body.extend_from_slice(&[0x03, 0x03]); // legacy_version
    body.extend_from_slice(&HRR_RANDOM);
    body.push(session_id.len() as u8);
    body.extend_from_slice(session_id);
    body.extend_from_slice(&suite.wire().to_be_bytes());
    body.push(0); // legacy_compression_method
                  // Extensions: supported_versions (selected) + key_share (selected_group).
    let mut exts = Vec::new();
    let mut sv = Vec::new();
    sv.extend_from_slice(&0x0304u16.to_be_bytes());
    exts.extend_from_slice(&EXT_SUPPORTED_VERSIONS.to_be_bytes());
    exts.extend_from_slice(&(sv.len() as u16).to_be_bytes());
    exts.extend_from_slice(&sv);
    let mut ks = Vec::new();
    ks.extend_from_slice(&GROUP_X25519.to_be_bytes());
    exts.extend_from_slice(&EXT_KEY_SHARE.to_be_bytes());
    exts.extend_from_slice(&(ks.len() as u16).to_be_bytes());
    exts.extend_from_slice(&ks);
    body.extend_from_slice(&(exts.len() as u16).to_be_bytes());
    body.extend_from_slice(&exts);
    encode_hs(HS_SERVER_HELLO, &body)
}

/// RFC 8446 §4.4.1: replace ClientHello1 in the transcript with the
/// synthetic `message_hash` handshake message carrying Hash(ClientHello1).
fn message_hash_message(ch1: &[u8], suite: CipherSuite) -> Vec<u8> {
    let mut d = suite.hash().new_digest();
    d.update(ch1);
    let h = d.finalize();
    encode_hs(HS_MESSAGE_HASH, &h)
}

/// Build a ServerHello (full message) for the given suite and key share.
/// The client's `session_id` is echoed verbatim (RFC 8446 §4.1.3).
pub(crate) fn build_server_hello(
    random: &[u8; 32],
    key_share: &[u8; 32],
    suite: CipherSuite,
    session_id: &[u8],
) -> Vec<u8> {
    build_server_hello_with_transport_params(random, key_share, suite, session_id, None)
}

/// Build a ServerHello with an optional QUIC transport-parameters
/// extension. The ordinary TLS path passes `None`.
pub(crate) fn build_server_hello_with_transport_params(
    random: &[u8; 32],
    key_share: &[u8; 32],
    suite: CipherSuite,
    session_id: &[u8],
    transport_params: Option<&[u8]>,
) -> Vec<u8> {
    let mut body = Vec::new();
    body.extend_from_slice(&[0x03, 0x03]);
    body.extend_from_slice(random);
    // legacy_session_id_echo: must match the client's session id.
    body.push(session_id.len() as u8);
    body.extend_from_slice(session_id);
    body.extend_from_slice(&suite.wire().to_be_bytes());
    body.push(0); // compression null

    let mut exts: Vec<(u16, Vec<u8>)> = Vec::new();
    let mut ks = Vec::new();
    ks.extend_from_slice(&GROUP_X25519.to_be_bytes());
    ks.extend_from_slice(&[0x00, 0x20]);
    ks.extend_from_slice(key_share);
    exts.push((EXT_KEY_SHARE, ks));
    let mut versions = Vec::new();
    versions.extend_from_slice(&[0x03, 0x04]);
    exts.push((EXT_SUPPORTED_VERSIONS, versions));
    if let Some(params) = transport_params {
        exts.push((EXT_QUIC_TRANSPORT_PARAMETERS, params.to_vec()));
    }

    let mut ext_bytes = Vec::new();
    for (t, c) in exts {
        ext_bytes.extend_from_slice(&t.to_be_bytes());
        ext_bytes.extend_from_slice(&(c.len() as u16).to_be_bytes());
        ext_bytes.extend_from_slice(&c);
    }
    body.extend_from_slice(&(ext_bytes.len() as u16).to_be_bytes());
    body.extend_from_slice(&ext_bytes);
    encode_hs(HS_SERVER_HELLO, &body)
}