pingly 0.2.0

TLS and HTTP/1/2/3 fingerprint analysis server and Rust library
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
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
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
//! TLS ClientHello data captured from the wire.
//!
//! See [RFC 9846, Section 4.2.2](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.2.2)
//! for the ClientHello layout and [Section 4.3](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3)
//! for its extension block.

use std::{borrow::Cow, collections::HashSet, fmt};

use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use tls_parser::{TlsCipherSuite as ParsedTlsCipherSuite, TlsExtensionType, TlsMessageHandshake};

use super::{
    enums::{
        is_grease_value, AuthenticatedEncryptionWithAssociatedData,
        CertificateCompressionAlgorithm, CertificateStatusType, CompressionAlgorithm,
        ECPointFormat, KeyDerivationFunction, PskKeyExchangeMode, SignatureAlgorithm, TlsVersion,
    },
    group::NamedGroup,
    ja3::Ja3Fingerprint,
    ja4::Ja4Fingerprint,
    parser,
    version::SupportedVersions,
};
use crate::quic::{
    parse_transport_parameters, QuicTransportParameter, TRANSPORT_PARAMETERS_EXTENSION_ID,
};

const DEFAULT_CLIENT_HELLO_CAPACITY: usize = 2048;
const DEFAULT_CLIENT_HELLO_CAPTURE_LIMIT: usize = 64 * 1024;
const TLS_RECORD_HEADER_LEN: usize = 5;
const TLS_HANDSHAKE_HEADER_LEN: usize = 4;
const TLS_HANDSHAKE_CLIENT_HELLO: u8 = 1;
const TLS_HANDSHAKE_CONTENT_TYPE: u8 = 22;

/// Buffers raw TLS record bytes so the ClientHello can be parsed after the handshake.
///
/// Deferring parsing keeps fingerprint analysis out of the handshake path. The buffer may be filled
/// incrementally when the ClientHello spans multiple reads.
#[derive(Debug, Clone)]
pub struct ClientHelloBuffer {
    /// TLS record bytes retained through the ClientHello.
    buf: Vec<u8>,

    /// Maximum bytes retained for an incomplete or malformed capture.
    capture_limit: usize,

    /// Whether the retained records contain a complete ClientHello.
    complete: bool,

    /// Incremental framing state used to avoid rescanning retained records on every read.
    capture: ClientHelloCaptureState,
}

/// Buffers a ClientHello carried directly by a TLS handshake byte stream.
///
/// QUIC carries TLS handshake messages in CRYPTO frames without the TLS record layer used by TCP.
/// This buffer retains only the first complete ClientHello for delayed parsing. See
/// [RFC 9001, Section 4](https://www.rfc-editor.org/rfc/rfc9001#section-4).
#[derive(Debug)]
pub struct ClientHelloHandshakeBuffer {
    /// Handshake bytes retained through the complete ClientHello.
    buf: Vec<u8>,

    /// Maximum bytes retained for an incomplete or malformed capture.
    capture_limit: usize,

    /// Declared ClientHello length including its four-byte handshake header.
    handshake_len: Option<usize>,

    /// Framing error found while inspecting the handshake header.
    error: Option<ClientHelloParseStage>,
}

/// Minimal state needed to locate the end of a fragmented ClientHello.
#[derive(Debug, Clone, Default)]
struct ClientHelloCaptureState {
    /// Start of the next TLS record that has not been consumed.
    record_offset: usize,

    /// First handshake header, which may itself span TLS records.
    handshake_header: [u8; TLS_HANDSHAKE_HEADER_LEN],

    /// Number of bytes currently stored in `handshake_header`.
    handshake_header_len: usize,

    /// Declared handshake length including its four-byte header.
    handshake_len: Option<usize>,

    /// Number of ClientHello handshake bytes observed across complete records.
    handshake_bytes_seen: usize,

    /// Framing error found while incrementally inspecting the capture.
    error: Option<ClientHelloParseStage>,
}

impl ClientHelloCaptureState {
    fn consume_payload(&mut self, payload: &[u8]) -> Result<bool, ClientHelloParseStage> {
        let mut cursor = 0usize;

        if self.handshake_header_len < TLS_HANDSHAKE_HEADER_LEN {
            let remaining_header = TLS_HANDSHAKE_HEADER_LEN - self.handshake_header_len;
            let copied = remaining_header.min(payload.len());
            let header_end = self.handshake_header_len + copied;
            self.handshake_header[self.handshake_header_len..header_end]
                .copy_from_slice(&payload[..copied]);
            self.handshake_header_len = header_end;
            self.handshake_bytes_seen += copied;
            cursor = copied;

            if self.handshake_header_len < TLS_HANDSHAKE_HEADER_LEN {
                return Ok(false);
            }

            self.handshake_len =
                client_hello_handshake_len(&self.handshake_header).map_err(|error| error.stage)?;
        }

        let handshake_len = self
            .handshake_len
            .ok_or(ClientHelloParseStage::ClientHello)?;
        let remaining = handshake_len.saturating_sub(self.handshake_bytes_seen);
        let available = payload.len().saturating_sub(cursor);
        self.handshake_bytes_seen += remaining.min(available);

        Ok(self.handshake_bytes_seen >= handshake_len)
    }
}

impl ClientHelloBuffer {
    /// Creates an empty ClientHello buffer with capacity for a typical browser handshake.
    pub fn new() -> Self {
        Self::with_capacity_and_limit(
            DEFAULT_CLIENT_HELLO_CAPACITY,
            DEFAULT_CLIENT_HELLO_CAPTURE_LIMIT,
        )
    }

    /// Creates an empty buffer with at least the requested initial capacity.
    ///
    /// Requesting more than the default capture limit raises the limit to the requested capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self::with_capacity_and_limit(capacity, DEFAULT_CLIENT_HELLO_CAPTURE_LIMIT.max(capacity))
    }

    /// Creates an empty buffer with a custom maximum capture size.
    pub fn with_capture_limit(capture_limit: usize) -> Self {
        Self::with_capacity_and_limit(
            DEFAULT_CLIENT_HELLO_CAPACITY.min(capture_limit),
            capture_limit,
        )
    }

    /// Creates an empty buffer with explicit allocation and capture limits.
    ///
    /// The effective capture limit is never smaller than the requested initial capacity.
    pub fn with_capacity_and_limit(capacity: usize, capture_limit: usize) -> Self {
        Self {
            buf: Vec::with_capacity(capacity),
            capture_limit: capture_limit.max(capacity),
            capture: ClientHelloCaptureState::default(),
            complete: false,
        }
    }

    /// Creates a buffer from captured TLS record bytes.
    ///
    /// Passing a `Vec<u8>` transfers its allocation into the buffer. Slices are
    /// copied because the parser owns bytes that may outlive the input read.
    /// Bytes after the record that completes the ClientHello are discarded, matching
    /// [`Self::extend`].
    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Self {
        let buf = bytes.into();
        let capture_limit = DEFAULT_CLIENT_HELLO_CAPTURE_LIMIT.max(buf.len());
        let mut buffer = Self {
            buf,
            capture_limit,
            complete: false,
            capture: ClientHelloCaptureState::default(),
        };
        if let Some(record_end) = buffer.scan_available_records() {
            buffer.buf.truncate(record_end);
        }
        buffer
    }

    /// Attempts to parse the first complete TLS ClientHello handshake in the buffer.
    ///
    /// The buffer remains available after either success or failure, which is
    /// useful when inspecting malformed captures.
    pub fn parse(&self) -> Result<ClientHello, ClientHelloParseError> {
        ClientHello::parse(&self.buf)
    }

    /// Parses a ClientHello once all of its TLS handshake records are complete.
    ///
    /// Returns `Ok(None)` while a record or the fragmented handshake is incomplete. A complete
    /// but malformed capture returns a [`ClientHelloParseError`]. TLS record fragmentation is
    /// defined by
    /// [RFC 9846, Section 5.1](https://www.rfc-editor.org/rfc/rfc9846#section-5.1).
    pub fn try_parse(&self) -> Result<Option<ClientHello>, ClientHelloParseError> {
        if let Some(stage) = self.capture.error {
            return Err(ClientHelloParseError::new(stage));
        }
        if !self.complete {
            return Ok(None);
        }

        let Some(captured) = capture_client_hello(&self.buf)? else {
            return Ok(None);
        };

        ClientHello::parse_handshake(captured.handshake.as_ref()).map(Some)
    }

    /// Returns the currently buffered TLS bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.buf
    }

    /// Returns the number of currently buffered bytes.
    pub fn len(&self) -> usize {
        self.buf.len()
    }

    /// Returns whether no TLS bytes have been buffered yet.
    pub fn is_empty(&self) -> bool {
        self.buf.is_empty()
    }

    /// Returns whether the retained records contain a complete ClientHello.
    pub const fn is_complete(&self) -> bool {
        self.complete
    }

    /// Returns whether incremental TLS framing encountered malformed input.
    pub const fn is_invalid(&self) -> bool {
        self.capture.error.is_some()
    }

    /// Returns the maximum number of TLS bytes retained for an incomplete or malformed capture.
    pub const fn capture_limit(&self) -> usize {
        self.capture_limit
    }

    /// Returns whether the configured capture limit has been reached.
    pub fn is_full(&self) -> bool {
        self.buf.len() >= self.capture_limit
    }

    /// Appends TLS bytes until the ClientHello completes or the capture limit is reached.
    ///
    /// Returns the number of bytes retained from `data`. Bytes after the TLS record that
    /// completes the ClientHello are discarded.
    pub fn extend(&mut self, data: &[u8]) -> usize {
        if self.complete || self.is_invalid() || self.is_full() {
            return 0;
        }

        let initial_len = self.buf.len();
        let accepted = data
            .len()
            .min(self.capture_limit.saturating_sub(initial_len));
        self.buf.extend_from_slice(&data[..accepted]);

        if let Some(record_end) = self.scan_available_records() {
            self.buf.truncate(record_end);
        }

        self.buf.len().saturating_sub(initial_len)
    }

    fn scan_available_records(&mut self) -> Option<usize> {
        while !self.complete && self.capture.error.is_none() {
            let record_offset = self.capture.record_offset;
            let Some(header_end) = record_offset.checked_add(TLS_RECORD_HEADER_LEN) else {
                self.capture.error = Some(ClientHelloParseStage::TlsRecord);
                return None;
            };
            let header = self.buf.get(record_offset..header_end)?;
            if header[0] != TLS_HANDSHAKE_CONTENT_TYPE {
                self.capture.error = Some(ClientHelloParseStage::RecordMessages);
                return None;
            }

            let payload_len = usize::from(u16::from_be_bytes([header[3], header[4]]));
            if payload_len > usize::from(tls_parser::MAX_RECORD_LEN) {
                self.capture.error = Some(ClientHelloParseStage::TlsRecord);
                return None;
            }
            let Some(record_end) = header_end.checked_add(payload_len) else {
                self.capture.error = Some(ClientHelloParseStage::TlsRecord);
                return None;
            };
            let payload = self.buf.get(header_end..record_end)?;

            match self.capture.consume_payload(payload) {
                Ok(true) => {
                    self.capture.record_offset = record_end;
                    self.complete = true;
                    return Some(record_end);
                }
                Ok(false) => self.capture.record_offset = record_end,
                Err(stage) => {
                    self.capture.error = Some(stage);
                    return None;
                }
            }
        }

        None
    }
}

impl ClientHelloHandshakeBuffer {
    /// Creates an empty buffer with capacity for a typical browser ClientHello.
    pub fn new() -> Self {
        Self::with_capacity_and_limit(
            DEFAULT_CLIENT_HELLO_CAPACITY,
            DEFAULT_CLIENT_HELLO_CAPTURE_LIMIT,
        )
    }

    /// Creates an empty buffer with at least the requested initial capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self::with_capacity_and_limit(capacity, DEFAULT_CLIENT_HELLO_CAPTURE_LIMIT.max(capacity))
    }

    /// Creates an empty buffer with a custom maximum capture size.
    pub fn with_capture_limit(capture_limit: usize) -> Self {
        Self::with_capacity_and_limit(
            DEFAULT_CLIENT_HELLO_CAPACITY.min(capture_limit),
            capture_limit,
        )
    }

    /// Creates an empty buffer with explicit allocation and capture limits.
    pub fn with_capacity_and_limit(capacity: usize, capture_limit: usize) -> Self {
        Self {
            buf: Vec::with_capacity(capacity),
            capture_limit: capture_limit.max(capacity),
            handshake_len: None,
            error: None,
        }
    }

    /// Creates a buffer from raw TLS handshake bytes.
    ///
    /// Bytes after the first complete ClientHello are discarded.
    pub fn from_bytes(bytes: impl Into<Vec<u8>>) -> Self {
        let buf = bytes.into();
        let capture_limit = DEFAULT_CLIENT_HELLO_CAPTURE_LIMIT.max(buf.len());
        let mut buffer = Self {
            buf,
            capture_limit,
            handshake_len: None,
            error: None,
        };
        buffer.inspect_header();
        buffer.truncate_complete();
        buffer
    }

    /// Parses a complete ClientHello directly from TLS handshake bytes.
    pub fn parse(&self) -> Result<ClientHello, ClientHelloParseError> {
        let length = self
            .handshake_len
            .filter(|length| self.buf.len() >= *length)
            .ok_or(ClientHelloParseError::new(
                self.error.unwrap_or(ClientHelloParseStage::ClientHello),
            ))?;
        ClientHello::parse_handshake(&self.buf[..length])
    }

    /// Parses the ClientHello when enough handshake bytes have arrived.
    pub fn try_parse(&self) -> Result<Option<ClientHello>, ClientHelloParseError> {
        if let Some(stage) = self.error {
            return Err(ClientHelloParseError::new(stage));
        }
        if !self.is_complete() {
            return Ok(None);
        }
        self.parse().map(Some)
    }

    /// Appends handshake bytes until the ClientHello completes or the limit is reached.
    pub fn extend(&mut self, data: &[u8]) -> usize {
        if self.is_complete() || self.is_invalid() || self.is_full() {
            return 0;
        }

        let initial_len = self.buf.len();
        let accepted = data
            .len()
            .min(self.capture_limit.saturating_sub(initial_len));
        self.buf.extend_from_slice(&data[..accepted]);
        self.inspect_header();
        self.truncate_complete();
        self.buf.len().saturating_sub(initial_len)
    }

    /// Returns the retained TLS handshake bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.buf
    }

    /// Returns the number of retained bytes.
    pub fn len(&self) -> usize {
        self.buf.len()
    }

    /// Returns whether no bytes have been retained.
    pub fn is_empty(&self) -> bool {
        self.buf.is_empty()
    }

    /// Returns whether the retained bytes contain a complete ClientHello.
    pub fn is_complete(&self) -> bool {
        self.handshake_len
            .is_some_and(|length| self.buf.len() >= length)
    }

    /// Returns whether the handshake header was malformed.
    pub const fn is_invalid(&self) -> bool {
        self.error.is_some()
    }

    /// Returns the maximum number of bytes retained for this capture.
    pub const fn capture_limit(&self) -> usize {
        self.capture_limit
    }

    /// Returns whether the configured capture limit has been reached.
    pub fn is_full(&self) -> bool {
        self.buf.len() >= self.capture_limit
    }

    fn inspect_header(&mut self) {
        if self.handshake_len.is_some() || self.error.is_some() {
            return;
        }
        match client_hello_handshake_len(&self.buf) {
            Ok(length) => self.handshake_len = length,
            Err(error) => self.error = Some(error.stage),
        }
    }

    fn truncate_complete(&mut self) {
        if let Some(length) = self.handshake_len {
            self.buf.truncate(length);
        }
    }
}

/// A complete ClientHello handshake reassembled from its TLS records.
struct CapturedClientHello<'a> {
    /// Reassembled handshake bytes, including the four-byte handshake header.
    handshake: Cow<'a, [u8]>,
}

/// Finds and reassembles a ClientHello split across one or more TLS handshake records.
///
/// RFC 9846 permits handshake messages to cross record boundaries:
/// <https://www.rfc-editor.org/rfc/rfc9846#section-5.1>
fn capture_client_hello(
    data: &[u8],
) -> Result<Option<CapturedClientHello<'_>>, ClientHelloParseError> {
    let mut cursor = 0usize;
    let mut handshake = Vec::new();

    loop {
        let Some(header_end) = cursor.checked_add(TLS_RECORD_HEADER_LEN) else {
            return Err(ClientHelloParseError::new(ClientHelloParseStage::TlsRecord));
        };
        let Some(header) = data.get(cursor..header_end) else {
            return Ok(None);
        };
        if header[0] != TLS_HANDSHAKE_CONTENT_TYPE {
            return Err(ClientHelloParseError::new(
                ClientHelloParseStage::RecordMessages,
            ));
        }

        let payload_len = usize::from(u16::from_be_bytes([header[3], header[4]]));
        if payload_len > usize::from(tls_parser::MAX_RECORD_LEN) {
            return Err(ClientHelloParseError::new(ClientHelloParseStage::TlsRecord));
        }
        let Some(record_end) = header_end.checked_add(payload_len) else {
            return Err(ClientHelloParseError::new(ClientHelloParseStage::TlsRecord));
        };
        let Some(payload) = data.get(header_end..record_end) else {
            return Ok(None);
        };

        if handshake.is_empty() {
            if let Some(handshake_len) = client_hello_handshake_len(payload)? {
                if let Some(handshake) = payload.get(..handshake_len) {
                    return Ok(Some(CapturedClientHello {
                        handshake: Cow::Borrowed(handshake),
                    }));
                }
            }
        }

        handshake.extend_from_slice(payload);
        if let Some(handshake_len) = client_hello_handshake_len(&handshake)? {
            if handshake.len() >= handshake_len {
                handshake.truncate(handshake_len);
                return Ok(Some(CapturedClientHello {
                    handshake: Cow::Owned(handshake),
                }));
            }
        }

        cursor = record_end;
    }
}

fn client_hello_handshake_len(data: &[u8]) -> Result<Option<usize>, ClientHelloParseError> {
    let Some(header) = data.get(..TLS_HANDSHAKE_HEADER_LEN) else {
        return Ok(None);
    };
    if header[0] != TLS_HANDSHAKE_CLIENT_HELLO {
        return Err(ClientHelloParseError::new(
            ClientHelloParseStage::ClientHello,
        ));
    }

    let payload_len = usize::try_from(u32::from_be_bytes([0, header[1], header[2], header[3]]))
        .map_err(|_| ClientHelloParseError::new(ClientHelloParseStage::ClientHello))?;
    TLS_HANDSHAKE_HEADER_LEN
        .checked_add(payload_len)
        .map(Some)
        .ok_or(ClientHelloParseError::new(
            ClientHelloParseStage::ClientHello,
        ))
}

impl Default for ClientHelloHandshakeBuffer {
    fn default() -> Self {
        Self::new()
    }
}

impl From<Vec<u8>> for ClientHelloHandshakeBuffer {
    fn from(bytes: Vec<u8>) -> Self {
        Self::from_bytes(bytes)
    }
}

impl From<&[u8]> for ClientHelloHandshakeBuffer {
    fn from(bytes: &[u8]) -> Self {
        Self::from_bytes(bytes)
    }
}

impl Default for ClientHelloBuffer {
    fn default() -> Self {
        Self::new()
    }
}

impl From<Vec<u8>> for ClientHelloBuffer {
    fn from(bytes: Vec<u8>) -> Self {
        Self::from_bytes(bytes)
    }
}

impl From<&[u8]> for ClientHelloBuffer {
    fn from(bytes: &[u8]) -> Self {
        Self::from_bytes(bytes)
    }
}

/// Owned bytes serialized as canonical lowercase hexadecimal text.
///
/// This keeps binary TLS fields compact in memory while preserving the existing JSON shape.
#[derive(Clone, PartialEq, Eq, Hash, Default)]
pub struct HexBytes(Box<[u8]>);

impl HexBytes {
    /// Creates an owned byte value from owned or borrowed bytes.
    pub fn new(bytes: impl Into<Box<[u8]>>) -> Self {
        Self(bytes.into())
    }

    /// Returns the decoded bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Returns the decoded byte length.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the value contains no bytes.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Consumes the value and returns its owned bytes.
    pub fn into_bytes(self) -> Box<[u8]> {
        self.0
    }
}

impl fmt::Display for HexBytes {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.as_bytes() {
            write!(formatter, "{byte:02x}")?;
        }
        Ok(())
    }
}

impl fmt::Debug for HexBytes {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "HexBytes({self})")
    }
}

impl Serialize for HexBytes {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&hex::encode(self.as_bytes()))
    }
}

impl<'de> Deserialize<'de> for HexBytes {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let encoded = Box::<str>::deserialize(deserializer)?;
        if encoded
            .bytes()
            .any(|byte| !byte.is_ascii_digit() && !(b'a'..=b'f').contains(&byte))
        {
            return Err(de::Error::custom(
                "hexadecimal TLS bytes must use lowercase ASCII digits",
            ));
        }

        hex::decode(encoded.as_ref())
            .map(Self::from)
            .map_err(de::Error::custom)
    }
}

impl AsRef<[u8]> for HexBytes {
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl From<Vec<u8>> for HexBytes {
    fn from(bytes: Vec<u8>) -> Self {
        Self(bytes.into_boxed_slice())
    }
}

impl From<Box<[u8]>> for HexBytes {
    fn from(bytes: Box<[u8]>) -> Self {
        Self(bytes)
    }
}

impl From<&[u8]> for HexBytes {
    fn from(bytes: &[u8]) -> Self {
        Self(bytes.into())
    }
}

impl<const N: usize> From<[u8; N]> for HexBytes {
    fn from(bytes: [u8; N]) -> Self {
        Self(Vec::from(bytes).into_boxed_slice())
    }
}

/// An invalid TLS application protocol name length.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("TLS protocol names must contain 1 to 255 bytes, got {length}")]
pub struct ProtocolNameError {
    /// Invalid decoded byte length.
    pub length: usize,
}

/// An owned ALPN-compatible opaque protocol name.
///
/// RFC 7301 defines protocol names as non-empty opaque byte strings rather than UTF-8 text.
/// Valid UTF-8 names serialize as JSON strings; other names use an object containing `hex`.
/// See [RFC 7301, Section 3.1](https://www.rfc-editor.org/rfc/rfc7301.html#section-3.1).
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct ProtocolName(Box<[u8]>);

impl ProtocolName {
    /// Creates a protocol name from one to 255 bytes.
    pub fn from_bytes(bytes: impl Into<Box<[u8]>>) -> Result<Self, ProtocolNameError> {
        let bytes = bytes.into();
        if bytes.is_empty() || bytes.len() > usize::from(u8::MAX) {
            return Err(ProtocolNameError {
                length: bytes.len(),
            });
        }
        Ok(Self(bytes))
    }

    /// Returns the opaque protocol-name bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Returns the name as UTF-8 when its bytes form valid text.
    pub fn as_str(&self) -> Option<&str> {
        std::str::from_utf8(self.as_bytes()).ok()
    }

    /// Returns the protocol-name byte length.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the protocol name is empty.
    ///
    /// Valid protocol names always return `false`.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl fmt::Display for ProtocolName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(value) = self.as_str() {
            return formatter.write_str(value);
        }
        for byte in self.as_bytes() {
            write!(formatter, "{byte:02x}")?;
        }
        Ok(())
    }
}

impl fmt::Debug for ProtocolName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.as_str() {
            Some(value) => formatter.debug_tuple("ProtocolName").field(&value).finish(),
            None => write!(formatter, "ProtocolName({self})"),
        }
    }
}

impl Serialize for ProtocolName {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self.as_str() {
            Some(value) => serializer.serialize_str(value),
            None => ProtocolNameHex {
                hex: hex::encode(self.as_bytes()).into_boxed_str(),
            }
            .serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for ProtocolName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let bytes = match ProtocolNameRepr::deserialize(deserializer)? {
            ProtocolNameRepr::Text(value) => value.into_boxed_bytes(),
            ProtocolNameRepr::Bytes { hex } => hex.into_bytes(),
        };
        Self::from_bytes(bytes).map_err(de::Error::custom)
    }
}

impl AsRef<[u8]> for ProtocolName {
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl TryFrom<Vec<u8>> for ProtocolName {
    type Error = ProtocolNameError;

    fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
        Self::from_bytes(bytes)
    }
}

impl TryFrom<Box<[u8]>> for ProtocolName {
    type Error = ProtocolNameError;

    fn try_from(bytes: Box<[u8]>) -> Result<Self, Self::Error> {
        Self::from_bytes(bytes)
    }
}

impl TryFrom<&[u8]> for ProtocolName {
    type Error = ProtocolNameError;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        Self::from_bytes(bytes)
    }
}

impl TryFrom<&str> for ProtocolName {
    type Error = ProtocolNameError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::from_bytes(value.as_bytes())
    }
}

#[derive(Deserialize)]
#[serde(untagged)]
/// Accepted JSON representations of a TLS protocol name.
enum ProtocolNameRepr {
    /// A UTF-8 protocol name represented directly as JSON text.
    Text(Box<str>),

    /// An opaque protocol name represented by canonical hexadecimal bytes.
    Bytes { hex: HexBytes },
}

#[derive(Serialize)]
/// JSON representation used when a protocol name is not valid UTF-8.
struct ProtocolNameHex {
    /// Canonical lowercase hexadecimal bytes.
    hex: Box<str>,
}

/// A cipher suite offered by a TLS client.
///
/// Registered identifiers use the IANA name exposed by `tls-parser`. GREASE identifiers use
/// `GREASE`, while other unregistered identifiers use `Unknown`, so every wire ID remains in
/// the client-advertised list.
///
/// See [RFC 9846, Section 4.2.2](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.2.2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Hash)]
pub struct TlsCipherSuite {
    /// The 16-bit cipher-suite identifier observed on the wire.
    pub id: u16,

    /// The registered cipher-suite name, `GREASE`, or `Unknown`.
    pub name: Box<str>,
}

impl TlsCipherSuite {
    /// Resolves a wire identifier into its canonical display name.
    pub fn from_id(id: u16) -> Self {
        Self {
            id,
            name: Self::name_for_id(id).into(),
        }
    }

    /// Resolves a registered IANA cipher-suite name.
    ///
    /// `GREASE` and `Unknown` cannot identify a unique wire value and therefore return `None`.
    pub fn from_name(name: &str) -> Option<Self> {
        ParsedTlsCipherSuite::from_name(name).map(|cipher| Self {
            id: cipher.id.0,
            name: cipher.name.into(),
        })
    }

    /// Returns whether this identifier is reserved for GREASE.
    ///
    /// See [RFC 8701, Section 2](https://www.rfc-editor.org/rfc/rfc8701.html#section-2).
    pub fn is_grease(&self) -> bool {
        is_grease_value(self.id)
    }

    fn name_for_id(id: u16) -> &'static str {
        ParsedTlsCipherSuite::from_id(id)
            .map(|cipher| cipher.name)
            .unwrap_or_else(|| {
                if is_grease_value(id) {
                    "GREASE"
                } else {
                    "Unknown"
                }
            })
    }
}

impl From<u16> for TlsCipherSuite {
    fn from(id: u16) -> Self {
        Self::from_id(id)
    }
}

/// Deserialization shape used to validate a saved cipher-suite ID and name.
#[derive(Deserialize)]
struct TlsCipherSuiteRepr {
    /// The numeric identifier stored in JSON.
    id: u16,

    /// The human-readable name stored alongside the identifier.
    name: Box<str>,
}

impl<'de> Deserialize<'de> for TlsCipherSuite {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let repr = TlsCipherSuiteRepr::deserialize(deserializer)?;
        let expected = Self::name_for_id(repr.id);

        if repr.name.as_ref() != expected {
            return Err(de::Error::custom(format_args!(
                "TLS cipher suite {:#06x} has name {expected:?}, not {:?}",
                repr.id, repr.name,
            )));
        }

        Ok(Self {
            id: repr.id,
            name: repr.name,
        })
    }
}

/// A decoded TLS ClientHello and the negotiated version observed after the handshake.
///
/// Client-advertised vectors retain their wire order because order is significant to TLS client
/// fingerprinting.
///
/// See [RFC 9846, Section 4.2.2](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.2.2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClientHello {
    /// The wire `legacy_version` field.
    ///
    /// A TLS 1.3 client normally sends TLS 1.2 (`0x0303`) here and advertises its real preferences
    /// through the `supported_versions` extension.
    pub tls_version: TlsVersion,

    /// The protocol version selected by the server, or `None` before negotiation completes.
    pub tls_version_negotiated: Option<TlsVersion>,

    /// The 32-byte ClientHello random value encoded as lowercase hexadecimal.
    #[serde(deserialize_with = "client_hello_hex::random")]
    pub client_random: HexBytes,

    /// The legacy session identifier encoded as lowercase hexadecimal, when present.
    #[serde(deserialize_with = "client_hello_hex::session_id")]
    pub session_id: Option<HexBytes>,

    /// Compression methods in client-advertised order.
    pub compression_algorithms: Vec<CompressionAlgorithm>,

    /// Cipher suites in client-advertised order, including GREASE and unregistered identifiers.
    pub cipher_suites: Vec<TlsCipherSuite>,

    /// Decoded extensions in the order sent by the client.
    pub extensions: Vec<TlsExtension>,
}

mod client_hello_hex {
    use serde::{de, Deserialize, Deserializer};

    use super::HexBytes;

    pub(super) fn random<'de, D>(deserializer: D) -> Result<HexBytes, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = HexBytes::deserialize(deserializer)?;
        if value.len() != 32 {
            return Err(de::Error::custom(format_args!(
                "TLS ClientHello random must contain 32 bytes, got {}",
                value.len(),
            )));
        }
        Ok(value)
    }

    pub(super) fn session_id<'de, D>(deserializer: D) -> Result<Option<HexBytes>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Option::<HexBytes>::deserialize(deserializer)?;
        if let Some(value) = &value {
            if value.is_empty() || value.len() > 32 {
                return Err(de::Error::custom(format_args!(
                    "TLS legacy session ID must contain 1 to 32 bytes, got {}",
                    value.len(),
                )));
            }
        }
        Ok(value)
    }
}

/// A decoded or preserved extension from a [`ClientHello`].
///
/// Every `value` field is the numeric `ExtensionType` observed on the wire. Byte-oriented payloads
/// are serialized as lowercase hexadecimal unless a variant documents another representation.
///
/// See [RFC 9846, Section 4.3](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TlsExtension {
    /// Server names advertised through Server Name Indication (SNI).
    ///
    /// See [RFC 6066, Section 3](https://www.rfc-editor.org/rfc/rfc6066.html#section-3).
    ServerName {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::server_name")]
        value: u16,

        /// Advertised names decoded as UTF-8, replacing malformed byte sequences when necessary.
        data: Vec<Box<str>>,
    },

    /// Named groups supported for key establishment.
    ///
    /// See [RFC 9846, Section 4.3.7](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3.7).
    SupportedGroups {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::supported_groups")]
        value: u16,

        /// Named groups in client preference order.
        data: Vec<NamedGroup>,
    },

    /// Elliptic-curve point formats advertised by a pre-TLS 1.3 client.
    ///
    /// See [RFC 8422, Section 5.1.2](https://www.rfc-editor.org/rfc/rfc8422.html#section-5.1.2).
    EcPointFormats {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::ec_point_formats")]
        value: u16,

        /// Point formats in client preference order.
        data: Vec<ECPointFormat>,
    },

    /// Signature schemes accepted by the client.
    ///
    /// See [RFC 9846, Section 4.3.3](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3.3).
    SignatureAlgorithms {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::signature_algorithms")]
        value: u16,

        /// Signature schemes in client preference order.
        data: Vec<SignatureAlgorithm>,
    },

    /// A request for a stapled certificate status response.
    ///
    /// See [RFC 6066, Section 8](https://www.rfc-editor.org/rfc/rfc6066.html#section-8).
    StatusRequest {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::status_request")]
        value: u16,

        /// Parsed OCSP status request parameters.
        data: StatusRequest,
    },

    /// Application protocols offered through ALPN, such as `h2`.
    ///
    /// See [RFC 7301, Section 3.1](https://www.rfc-editor.org/rfc/rfc7301.html#section-3.1).
    ApplicationLayerProtocolNegotiation {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::alpn")]
        value: u16,

        /// Opaque protocol names in client preference order.
        data: Vec<ProtocolName>,
    },

    /// Protocol names from the former `0x4469` Application Settings code point.
    ///
    /// ALPS remains an Internet-Draft; see
    /// [draft-vvv-tls-alps](https://datatracker.ietf.org/doc/html/draft-vvv-tls-alps).
    ApplicationSettingsOld {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::application_settings_old")]
        value: u16,

        /// Application protocol names carried by the extension.
        data: Vec<ProtocolName>,
    },

    /// Protocol names from the current `0x44cd` Application Settings code point.
    ///
    /// ALPS remains an Internet-Draft; see
    /// [draft-vvv-tls-alps](https://datatracker.ietf.org/doc/html/draft-vvv-tls-alps).
    ApplicationSettings {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::application_settings")]
        value: u16,

        /// Application protocol names carried by the extension.
        data: Vec<ProtocolName>,
    },

    /// TLS versions the client is prepared to negotiate.
    ///
    /// See [RFC 9846, Section 4.3.1](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3.1).
    SupportedVersions {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::supported_versions")]
        value: u16,

        /// Protocol versions in client preference order.
        data: SupportedVersions,
    },

    /// A TLS 1.2 session ticket offered for resumption.
    ///
    /// See [RFC 5077, Section 3.2](https://www.rfc-editor.org/rfc/rfc5077.html#section-3.2).
    SessionTicket {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::session_ticket")]
        value: u16,

        /// Opaque ticket bytes encoded as lowercase hexadecimal.
        data: HexBytes,
    },

    /// Supported certificate compression algorithms.
    ///
    /// See [RFC 8879, Section 3](https://www.rfc-editor.org/rfc/rfc8879.html#section-3).
    CertificateCompression {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::certificate_compression")]
        value: u16,

        /// Compression algorithms in client preference order.
        data: Vec<CertificateCompressionAlgorithm>,
    },

    /// Maximum protected record size accepted by the client.
    ///
    /// See [RFC 8449, Section 4](https://www.rfc-editor.org/rfc/rfc8449.html#section-4).
    RecordSizeLimit {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::record_size_limit")]
        value: u16,

        /// Advertised record size limit in bytes.
        data: u16,
    },

    /// Signature schemes accepted for delegated credentials.
    ///
    /// See [RFC 9345, Section 4.1](https://www.rfc-editor.org/rfc/rfc9345.html#section-4.1).
    DelegatedCredentials {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::delegated_credentials")]
        value: u16,

        /// Supported delegated-credential signature schemes.
        data: Vec<SignatureAlgorithm>,
    },

    /// An Encrypted ClientHello (ECH) offer.
    ///
    /// See [RFC 9849, Section 5](https://www.rfc-editor.org/rfc/rfc9849.html#section-5).
    EncryptedClientHello {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::encrypted_client_hello")]
        value: u16,

        /// Parsed outer or inner ECH payload.
        data: ECHClientHello,
    },

    /// A request for Signed Certificate Timestamps through the TLS extension.
    ///
    /// See [RFC 6962, Section 3.3.1](https://www.rfc-editor.org/rfc/rfc6962.html#section-3.3.1).
    SignedCertificateTimestamp {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::signed_certificate_timestamp")]
        value: u16,

        /// Raw payload encoded as lowercase hexadecimal when one was present.
        #[serde(skip_serializing_if = "Option::is_none")]
        data: Option<HexBytes>,
    },

    /// The secure renegotiation indication used by TLS 1.2 and earlier.
    ///
    /// See [RFC 5746, Section 3.2](https://www.rfc-editor.org/rfc/rfc5746.html#section-3.2).
    RenegotiationInfo {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::renegotiation_info")]
        value: u16,
    },

    /// The Extended Master Secret indication used by TLS 1.2 and earlier.
    ///
    /// See [RFC 7627, Section 3](https://www.rfc-editor.org/rfc/rfc7627.html#section-3).
    ExtendedMasterSecret {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::extended_master_secret")]
        value: u16,
    },

    /// ClientHello padding used to alter the message length.
    ///
    /// See [RFC 7685, Section 3](https://www.rfc-editor.org/rfc/rfc7685.html#section-3).
    Padding {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::padding")]
        value: u16,

        /// Padding bytes encoded as lowercase hexadecimal.
        data: HexBytes,
    },

    /// Ephemeral key shares offered for TLS 1.3 key establishment.
    ///
    /// See [RFC 9846, Section 4.3.8](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3.8).
    KeyShare {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::key_share")]
        value: u16,

        /// Parsed key shares in client preference order.
        data: Vec<KeyShare>,
    },

    /// Key exchange modes the client permits for pre-shared keys.
    ///
    /// See [RFC 9846, Section 4.3.9](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3.9).
    PskKeyExchangeModes {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::psk_key_exchange_modes")]
        value: u16,

        /// Parsed PSK key exchange modes.
        data: PskKeyExchangeModes,
    },

    /// Pre-shared key identities and binders offered for resumption or 0-RTT.
    ///
    /// See [RFC 9846, Section 4.3.11](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3.11).
    PreSharedKey {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::pre_shared_key")]
        value: u16,

        /// Complete opaque extension payload encoded as lowercase hexadecimal.
        data: HexBytes,
    },

    /// QUIC transport parameters authenticated through the TLS handshake.
    ///
    /// The payload is defined by the negotiated QUIC version rather than TLS itself. See
    /// [RFC 9001, Section 8.2](https://www.rfc-editor.org/rfc/rfc9001#section-8.2).
    QuicTransportParameters {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::quic_transport_parameters")]
        value: u16,

        /// Decoded transport parameters retained in their original wire order.
        #[serde(deserialize_with = "deserialize_quic_transport_parameters")]
        data: Vec<QuicTransportParameter>,
    },

    /// A legacy experimental Encrypted Server Name Indication (ESNI) offer.
    ///
    /// ESNI was replaced by ECH; see
    /// [draft-ietf-tls-esni-00](https://datatracker.ietf.org/doc/html/draft-ietf-tls-esni-00).
    EncryptedServerName {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::encrypted_server_name")]
        value: u16,

        /// Recognized TLS cipher-suite name, or `Unknown`.
        ciphersuite: Box<str>,

        /// Named group used for the key share.
        group: NamedGroup,

        /// Key share bytes encoded as lowercase hexadecimal.
        key_share: HexBytes,

        /// ESNIKeys record digest encoded as lowercase hexadecimal.
        record_digest: HexBytes,

        /// Encrypted server-name bytes encoded as lowercase hexadecimal.
        encrypted_sni: HexBytes,
    },

    /// Filters applied to certificate extension object identifiers.
    ///
    /// See [RFC 9846, Section 4.3.5](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3.5).
    OidFilters {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::oid_filters")]
        value: u16,

        /// Requested certificate extension filters.
        data: Vec<OidFilter>,
    },

    /// A reserved GREASE extension used to exercise protocol extensibility.
    ///
    /// See [RFC 8701, Section 3](https://www.rfc-editor.org/rfc/rfc8701.html#section-3).
    Grease {
        /// GREASE extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::grease")]
        value: u16,
    },

    /// An extension that is valid to preserve but is not decoded into a dedicated variant.
    Opaque {
        /// Numeric extension type as observed on the wire.
        #[serde(deserialize_with = "extension_id::opaque")]
        value: u16,

        /// Raw payload encoded as lowercase hexadecimal, or `None` for an empty payload.
        data: Option<HexBytes>,
    },
}

fn deserialize_quic_transport_parameters<'de, D>(
    deserializer: D,
) -> Result<Vec<QuicTransportParameter>, D::Error>
where
    D: Deserializer<'de>,
{
    let parameters = Vec::<QuicTransportParameter>::deserialize(deserializer)?;
    let mut parameter_ids = HashSet::with_capacity(parameters.len());
    for parameter in &parameters {
        if !parameter_ids.insert(parameter.id) {
            return Err(de::Error::custom(format_args!(
                "duplicate QUIC transport parameter {}",
                parameter.id
            )));
        }
    }
    Ok(parameters)
}

mod extension_id {
    use serde::{de, Deserialize, Deserializer};
    use tls_parser::TlsExtensionType;

    use super::{is_grease_value, TRANSPORT_PARAMETERS_EXTENSION_ID};

    const CERTIFICATE_COMPRESSION: u16 = 27;
    const DELEGATED_CREDENTIALS: u16 = 34;
    const APPLICATION_SETTINGS_OLD: u16 = 17_513;
    const APPLICATION_SETTINGS: u16 = 17_613;
    const ENCRYPTED_CLIENT_HELLO: u16 = 65_037;

    const DEDICATED_TYPES: &[u16] = &[
        TlsExtensionType::ServerName.0,
        TlsExtensionType::StatusRequest.0,
        TlsExtensionType::SupportedGroups.0,
        TlsExtensionType::EcPointFormats.0,
        TlsExtensionType::SignatureAlgorithms.0,
        TlsExtensionType::ApplicationLayerProtocolNegotiation.0,
        TlsExtensionType::SignedCertificateTimestamp.0,
        TlsExtensionType::Padding.0,
        TlsExtensionType::ExtendedMasterSecret.0,
        CERTIFICATE_COMPRESSION,
        TlsExtensionType::RecordSizeLimit.0,
        DELEGATED_CREDENTIALS,
        TlsExtensionType::SessionTicketTLS.0,
        TlsExtensionType::PreSharedKey.0,
        TRANSPORT_PARAMETERS_EXTENSION_ID,
        TlsExtensionType::SupportedVersions.0,
        TlsExtensionType::PskExchangeModes.0,
        TlsExtensionType::OidFilters.0,
        TlsExtensionType::KeyShare.0,
        APPLICATION_SETTINGS_OLD,
        APPLICATION_SETTINGS,
        ENCRYPTED_CLIENT_HELLO,
        TlsExtensionType::RenegotiationInfo.0,
        TlsExtensionType::EncryptedServerName.0,
    ];

    macro_rules! exact_id {
        ($name:ident, $expected:expr) => {
            pub(super) fn $name<'de, D>(deserializer: D) -> Result<u16, D::Error>
            where
                D: Deserializer<'de>,
            {
                exact(deserializer, $expected)
            }
        };
    }

    exact_id!(server_name, TlsExtensionType::ServerName.0);
    exact_id!(status_request, TlsExtensionType::StatusRequest.0);
    exact_id!(supported_groups, TlsExtensionType::SupportedGroups.0);
    exact_id!(ec_point_formats, TlsExtensionType::EcPointFormats.0);
    exact_id!(
        signature_algorithms,
        TlsExtensionType::SignatureAlgorithms.0
    );
    exact_id!(
        alpn,
        TlsExtensionType::ApplicationLayerProtocolNegotiation.0
    );
    exact_id!(
        signed_certificate_timestamp,
        TlsExtensionType::SignedCertificateTimestamp.0
    );
    exact_id!(padding, TlsExtensionType::Padding.0);
    exact_id!(
        extended_master_secret,
        TlsExtensionType::ExtendedMasterSecret.0
    );
    exact_id!(certificate_compression, CERTIFICATE_COMPRESSION);
    exact_id!(record_size_limit, TlsExtensionType::RecordSizeLimit.0);
    exact_id!(delegated_credentials, DELEGATED_CREDENTIALS);
    exact_id!(session_ticket, TlsExtensionType::SessionTicketTLS.0);
    exact_id!(pre_shared_key, TlsExtensionType::PreSharedKey.0);
    exact_id!(quic_transport_parameters, TRANSPORT_PARAMETERS_EXTENSION_ID);
    exact_id!(supported_versions, TlsExtensionType::SupportedVersions.0);
    exact_id!(psk_key_exchange_modes, TlsExtensionType::PskExchangeModes.0);
    exact_id!(oid_filters, TlsExtensionType::OidFilters.0);
    exact_id!(key_share, TlsExtensionType::KeyShare.0);
    exact_id!(application_settings_old, APPLICATION_SETTINGS_OLD);
    exact_id!(application_settings, APPLICATION_SETTINGS);
    exact_id!(encrypted_client_hello, ENCRYPTED_CLIENT_HELLO);
    exact_id!(renegotiation_info, TlsExtensionType::RenegotiationInfo.0);
    exact_id!(
        encrypted_server_name,
        TlsExtensionType::EncryptedServerName.0
    );

    fn exact<'de, D>(deserializer: D, expected: u16) -> Result<u16, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = u16::deserialize(deserializer)?;
        if value != expected {
            return Err(de::Error::custom(format_args!(
                "TLS extension variant expects ID {expected}, got {value}"
            )));
        }
        Ok(value)
    }

    pub(super) fn grease<'de, D>(deserializer: D) -> Result<u16, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = u16::deserialize(deserializer)?;
        if !is_grease_value(value) {
            return Err(de::Error::custom(format_args!(
                "TLS GREASE extension has non-GREASE ID {value}"
            )));
        }
        Ok(value)
    }

    pub(super) fn opaque<'de, D>(deserializer: D) -> Result<u16, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = u16::deserialize(deserializer)?;
        if is_grease_value(value) || DEDICATED_TYPES.contains(&value) {
            return Err(de::Error::custom(format_args!(
                "TLS extension ID {value} has a dedicated variant"
            )));
        }
        Ok(value)
    }
}

impl TlsExtension {
    /// Returns the numeric `ExtensionType` observed on the wire.
    pub fn value(&self) -> u16 {
        match self {
            TlsExtension::ServerName { value, .. }
            | TlsExtension::SupportedGroups { value, .. }
            | TlsExtension::EcPointFormats { value, .. }
            | TlsExtension::SignatureAlgorithms { value, .. }
            | TlsExtension::StatusRequest { value, .. }
            | TlsExtension::ApplicationLayerProtocolNegotiation { value, .. }
            | TlsExtension::ApplicationSettingsOld { value, .. }
            | TlsExtension::ApplicationSettings { value, .. }
            | TlsExtension::SupportedVersions { value, .. }
            | TlsExtension::SessionTicket { value, .. }
            | TlsExtension::CertificateCompression { value, .. }
            | TlsExtension::RecordSizeLimit { value, .. }
            | TlsExtension::DelegatedCredentials { value, .. }
            | TlsExtension::EncryptedClientHello { value, .. }
            | TlsExtension::SignedCertificateTimestamp { value, .. }
            | TlsExtension::RenegotiationInfo { value }
            | TlsExtension::ExtendedMasterSecret { value }
            | TlsExtension::Padding { value, .. }
            | TlsExtension::KeyShare { value, .. }
            | TlsExtension::PskKeyExchangeModes { value, .. }
            | TlsExtension::PreSharedKey { value, .. }
            | TlsExtension::QuicTransportParameters { value, .. }
            | TlsExtension::EncryptedServerName { value, .. }
            | TlsExtension::OidFilters { value, .. }
            | TlsExtension::Grease { value }
            | TlsExtension::Opaque { value, .. } => *value,
        }
    }

    /// Returns whether this extension uses an RFC 8701 GREASE type.
    ///
    /// See [RFC 8701, Section 3](https://www.rfc-editor.org/rfc/rfc8701.html#section-3).
    pub fn is_grease(&self) -> bool {
        is_grease_value(self.value())
    }
}

/// The OCSP parameters carried by a ClientHello `status_request` extension.
///
/// See [RFC 6066, Section 8](https://www.rfc-editor.org/rfc/rfc6066.html#section-8).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Hash)]
pub struct StatusRequest {
    /// The certificate status protocol requested by the client.
    pub certificate_status_type: CertificateStatusType,

    /// Declared byte length of the OCSP responder ID list.
    pub responder_id_list: u16,

    /// Declared byte length of the OCSP request extensions.
    pub request_extensions: u16,
}

impl<'de> Deserialize<'de> for StatusRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let repr = StatusRequestRepr::deserialize(deserializer)?;
        if repr.certificate_status_type != CertificateStatusType::OCSP {
            return Err(de::Error::custom(
                "ClientHello status_request currently supports only OCSP",
            ));
        }
        if matches!(repr.responder_id_list, 1 | 2) {
            return Err(de::Error::custom(
                "an OCSP responder ID list must be empty or contain at least three bytes",
            ));
        }

        Ok(Self {
            certificate_status_type: repr.certificate_status_type,
            responder_id_list: repr.responder_id_list,
            request_extensions: repr.request_extensions,
        })
    }
}

/// Deserialization shape used to validate OCSP status request metadata.
#[derive(Deserialize)]
struct StatusRequestRepr {
    /// Saved certificate status protocol.
    certificate_status_type: CertificateStatusType,

    /// Saved responder ID list byte length.
    responder_id_list: u16,

    /// Saved request extensions byte length.
    request_extensions: u16,
}

/// The outer or inner form of an Encrypted ClientHello extension.
///
/// See [RFC 9849, Section 5](https://www.rfc-editor.org/rfc/rfc9849.html#section-5).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub enum ECHClientHello {
    /// The public ClientHelloOuter payload carrying the encrypted ClientHelloInner.
    Outer(ECHClientHelloOuter),
    /// The empty marker repeated inside ClientHelloInner.
    ///
    /// Including this marker permits the server to respond with ECH-related extensions after it
    /// discards ClientHelloOuter.
    Inner,
}

/// Encryption metadata and ciphertext carried by an ECH ClientHelloOuter.
///
/// See [RFC 9849, Section 5](https://www.rfc-editor.org/rfc/rfc9849.html#section-5).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Hash)]
pub struct ECHClientHelloOuter {
    /// The HPKE KDF and AEAD pair used to encrypt ClientHelloInner.
    pub cipher_suite: HpkeSymmetricCipherSuite,

    /// The selected ECH configuration identifier.
    pub config_id: u8,

    /// The HPKE encapsulated key encoded as lowercase hexadecimal.
    ///
    /// This can be empty in a ClientHelloOuter sent after HelloRetryRequest.
    pub enc: HexBytes,

    /// The encrypted EncodedClientHelloInner bytes encoded as lowercase hexadecimal.
    ///
    /// Its decoded byte length is recorded in `payload_length`.
    pub payload: HexBytes,

    /// The encoded `uint16` length of the encrypted payload in bytes.
    ///
    /// This is retained explicitly because `payload` is exposed as hexadecimal text.
    pub payload_length: u16,
}

impl<'de> Deserialize<'de> for ECHClientHelloOuter {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let repr = ECHClientHelloOuterRepr::deserialize(deserializer)?;
        if repr.enc.len() > usize::from(u16::MAX) {
            return Err(de::Error::custom(format_args!(
                "ECH encapsulated key exceeds 65535 bytes: {}",
                repr.enc.len(),
            )));
        }
        let payload_length = u16::try_from(repr.payload.len()).map_err(|_| {
            de::Error::custom(format_args!(
                "ECH payload exceeds 65535 bytes: {}",
                repr.payload.len(),
            ))
        })?;
        if payload_length == 0 {
            return Err(de::Error::custom("ECH outer payload must not be empty"));
        }
        if payload_length != repr.payload_length {
            return Err(de::Error::custom(format_args!(
                "ECH payload length is {}, but payload_length is {}",
                payload_length, repr.payload_length,
            )));
        }

        Ok(Self {
            cipher_suite: repr.cipher_suite,
            config_id: repr.config_id,
            enc: repr.enc,
            payload: repr.payload,
            payload_length: repr.payload_length,
        })
    }
}

/// Deserialization shape used to validate ECH vector lengths.
#[derive(Deserialize)]
struct ECHClientHelloOuterRepr {
    /// Saved HPKE cipher suite.
    cipher_suite: HpkeSymmetricCipherSuite,

    /// Saved ECH configuration identifier.
    config_id: u8,

    /// Saved HPKE encapsulated key bytes.
    enc: HexBytes,

    /// Saved encrypted ClientHelloInner bytes.
    payload: HexBytes,

    /// Saved payload byte length.
    payload_length: u16,
}

/// The HPKE KDF and AEAD pair selected for ECH encryption.
///
/// See [RFC 9849, Section 4](https://www.rfc-editor.org/rfc/rfc9849.html#section-4) and
/// [RFC 9180, Section 7.2](https://www.rfc-editor.org/rfc/rfc9180.html#section-7.2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct HpkeSymmetricCipherSuite {
    /// The HPKE key derivation function identifier.
    pub kdf_id: KeyDerivationFunction,

    /// The HPKE authenticated-encryption algorithm identifier.
    pub aead_id: AuthenticatedEncryptionWithAssociatedData,
}

/// An ephemeral key share offered by the client.
///
/// Each item retains the named-group ID and name. Non-GREASE items serialize their opaque key
/// exchange bytes under `value`; GREASE items omit those arbitrary payload bytes.
///
/// See [RFC 9846, Section 4.3.8](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3.8).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Hash)]
pub struct KeyShare {
    /// The 16-bit named-group identifier observed on the wire.
    pub id: u16,

    /// The registered group name, `GREASE`, or `Unknown`.
    pub name: Box<str>,

    /// The opaque key exchange bytes encoded as lowercase hexadecimal.
    ///
    /// GREASE key exchange bytes can contain any value and are therefore omitted.
    /// See [RFC 8701, Section 3](https://www.rfc-editor.org/rfc/rfc8701.html#section-3).
    #[serde(rename = "value", skip_serializing_if = "Option::is_none")]
    pub key_exchange: Option<HexBytes>,
}

impl KeyShare {
    fn from_wire(id: u16, key_exchange: Vec<u8>) -> Self {
        let group = NamedGroup::from(id);
        let key_exchange = (!group.is_grease()).then(|| HexBytes::from(key_exchange));

        Self {
            id: group.id,
            name: group.name,
            key_exchange,
        }
    }
}

impl<'de> Deserialize<'de> for KeyShare {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let repr = KeyShareRepr::deserialize(deserializer)?;
        let id = repr.id;
        let group = NamedGroup::from_serialized_parts(id, repr.name).map_err(|expected| {
            de::Error::custom(format_args!(
                "TLS key share group {id:#06x} has name {expected:?}, not the saved name",
            ))
        })?;

        match (group.is_grease(), repr.key_exchange) {
            (true, Some(_)) => Err(de::Error::custom(
                "GREASE key shares must omit key exchange bytes",
            )),
            (false, None) => Err(de::Error::custom(
                "non-GREASE key shares require key exchange bytes",
            )),
            (false, Some(key_exchange))
                if key_exchange.is_empty() || key_exchange.len() > usize::from(u16::MAX) =>
            {
                Err(de::Error::custom(
                    "non-GREASE key shares require 1 to 65535 key exchange bytes",
                ))
            }
            (_, key_exchange) => Ok(Self {
                id: group.id,
                name: group.name,
                key_exchange,
            }),
        }
    }
}

/// Deserialization shape used to validate a saved key-share ID, name, and payload.
#[derive(Deserialize)]
struct KeyShareRepr {
    /// The numeric named-group identifier stored in JSON.
    id: u16,

    /// The human-readable group name stored alongside the identifier.
    name: Box<str>,

    /// The optional key exchange bytes stored under the public `value` key.
    #[serde(rename = "value")]
    key_exchange: Option<HexBytes>,
}

/// Pre-shared-key key exchange modes offered by the client.
///
/// See [RFC 9846, Section 4.3.9](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3.9).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct PskKeyExchangeModes {
    /// Modes in client preference order.
    pub ke_modes: Vec<PskKeyExchangeMode>,
}

/// A certificate-extension filter from the ClientHello `oid_filters` extension.
///
/// See [RFC 9846, Section 4.3.5](https://www.rfc-editor.org/rfc/rfc9846.html#section-4.3.5).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Hash)]
pub struct OidFilter {
    /// The DER-encoded certificate extension OID, represented as lowercase hexadecimal.
    pub cert_ext_oid: HexBytes,

    /// The required certificate extension value, represented as lowercase hexadecimal.
    pub cert_ext_val: HexBytes,
}

impl<'de> Deserialize<'de> for OidFilter {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let repr = OidFilterRepr::deserialize(deserializer)?;
        if repr.cert_ext_oid.is_empty() || repr.cert_ext_oid.len() > usize::from(u8::MAX) {
            return Err(de::Error::custom(format_args!(
                "certificate extension OID must contain 1 to 255 bytes, got {}",
                repr.cert_ext_oid.len(),
            )));
        }
        if repr.cert_ext_val.len() > usize::from(u16::MAX) {
            return Err(de::Error::custom(format_args!(
                "certificate extension value exceeds 65535 bytes: {}",
                repr.cert_ext_val.len(),
            )));
        }

        Ok(Self {
            cert_ext_oid: repr.cert_ext_oid,
            cert_ext_val: repr.cert_ext_val,
        })
    }
}

/// Deserialization shape used to validate an OID filter.
#[derive(Deserialize)]
struct OidFilterRepr {
    /// Saved DER-encoded certificate extension OID.
    cert_ext_oid: HexBytes,

    /// Saved required certificate extension value.
    cert_ext_val: HexBytes,
}

/// The ClientHello layer at which binary parsing failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClientHelloParseStage {
    /// TLS record framing is incomplete or invalid.
    TlsRecord,

    /// A complete record does not contain a valid handshake message.
    RecordMessages,

    /// The first handshake message is not a ClientHello.
    ClientHello,

    /// The ClientHello extension vector is malformed.
    Extensions,

    /// The OCSP status request payload is malformed.
    StatusRequest,

    /// The ALPN protocol-name list is malformed.
    ApplicationLayerProtocolNegotiation,

    /// An Application-Layer Protocol Settings protocol-name list is malformed.
    ApplicationSettings,

    /// The delegated-credentials payload is malformed.
    DelegatedCredentials,

    /// The certificate-compression payload is malformed.
    CertificateCompression,

    /// The Encrypted ClientHello payload is malformed.
    EncryptedClientHello,

    /// The key-share vector is malformed.
    KeyShare,

    /// The QUIC transport-parameters payload is malformed.
    ///
    /// See [RFC 9001, Section 8.2](https://www.rfc-editor.org/rfc/rfc9001#section-8.2).
    QuicTransportParameters,
}

/// A structured TLS ClientHello parsing failure.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
#[error("failed to parse TLS ClientHello at {stage:?}")]
pub struct ClientHelloParseError {
    /// The layer or extension parser that rejected the input.
    pub stage: ClientHelloParseStage,

    /// The extension type involved in the failure, when applicable.
    pub extension_id: Option<u16>,

    /// The extension payload length observed on the wire, when applicable.
    pub payload_len: Option<usize>,
}

impl ClientHelloParseError {
    const fn new(stage: ClientHelloParseStage) -> Self {
        Self {
            stage,
            extension_id: None,
            payload_len: None,
        }
    }

    const fn extension(
        stage: ClientHelloParseStage,
        extension_id: u16,
        payload_len: usize,
    ) -> Self {
        Self {
            stage,
            extension_id: Some(extension_id),
            payload_len: Some(payload_len),
        }
    }
}

impl ClientHello {
    /// Records the protocol version selected after the handshake.
    ///
    /// Passing `None` clears a previously recorded negotiated version.
    pub fn set_tls_version_negotiated(&mut self, version: Option<TlsVersion>) {
        self.tls_version_negotiated = version;
    }

    /// Parses the first ClientHello from one or more complete TLS records.
    ///
    /// Unknown cipher-suite identifiers and GREASE values are preserved in the cipher_suites list.
    pub fn parse(buf: &[u8]) -> Result<Self, ClientHelloParseError> {
        match Self::parse_inner(buf) {
            Ok(client_hello) => {
                tracing::debug!(
                    capture_len = buf.len(),
                    legacy_version = %client_hello.tls_version,
                    cipher_count = client_hello.cipher_suites.len(),
                    extension_count = client_hello.extensions.len(),
                    "parsed TLS ClientHello",
                );
                Ok(client_hello)
            }
            Err(error) => {
                tracing::debug!(
                    capture_len = buf.len(),
                    stage = ?error.stage,
                    extension_id = ?error.extension_id,
                    payload_len = ?error.payload_len,
                    "failed to parse TLS ClientHello",
                );
                Err(error)
            }
        }
    }

    fn parse_inner(buf: &[u8]) -> Result<Self, ClientHelloParseError> {
        let captured = capture_client_hello(buf)?
            .ok_or(ClientHelloParseError::new(ClientHelloParseStage::TlsRecord))?;
        Self::parse_handshake(captured.handshake.as_ref())
    }

    /// Parses exactly one complete ClientHello from raw TLS handshake bytes.
    ///
    /// The input includes the four-byte handshake header and its declared body, with no trailing
    /// bytes, as defined by
    /// [RFC 9846, Section 4](https://www.rfc-editor.org/rfc/rfc9846#section-4). It has no TLS record
    /// header, matching the bytes carried by QUIC CRYPTO frames. See
    /// [RFC 9001, Section 4.1.3](https://www.rfc-editor.org/rfc/rfc9001#section-4.1.3).
    pub fn parse_handshake(handshake: &[u8]) -> Result<Self, ClientHelloParseError> {
        let Some(expected_len) = client_hello_handshake_len(handshake)? else {
            return Err(ClientHelloParseError::new(
                ClientHelloParseStage::RecordMessages,
            ));
        };
        if handshake.len() != expected_len {
            return Err(ClientHelloParseError::new(
                ClientHelloParseStage::RecordMessages,
            ));
        }

        let body = &handshake[TLS_HANDSHAKE_HEADER_LEN..];
        let (remaining, message) = tls_parser::parse_tls_handshake_msg_client_hello(body)
            .map_err(|_| ClientHelloParseError::new(ClientHelloParseStage::RecordMessages))?;
        if !remaining.is_empty() {
            return Err(ClientHelloParseError::new(
                ClientHelloParseStage::RecordMessages,
            ));
        }
        let TlsMessageHandshake::ClientHello(payload) = message else {
            return Err(ClientHelloParseError::new(
                ClientHelloParseStage::ClientHello,
            ));
        };

        let cipher_suites = payload
            .ciphers
            .iter()
            .map(|cipher| TlsCipherSuite::from(cipher.0))
            .collect();

        let mut client_hello = ClientHello {
            tls_version: TlsVersion::from(payload.version.0),
            tls_version_negotiated: None,
            cipher_suites,
            client_random: HexBytes::from(payload.random),
            session_id: payload.session_id.map(HexBytes::from),
            compression_algorithms: payload
                .comp
                .iter()
                .map(|c| CompressionAlgorithm::from(c.0))
                .collect(),
            extensions: Vec::with_capacity(5),
        };

        let Some(extension_bytes) = payload.ext else {
            return Ok(client_hello);
        };
        let (remaining, ext_list) = tls_parser::parse_tls_client_hello_extensions(extension_bytes)
            .map_err(|_| ClientHelloParseError::new(ClientHelloParseStage::Extensions))?;
        if !remaining.is_empty() {
            return Err(ClientHelloParseError::new(
                ClientHelloParseStage::Extensions,
            ));
        }

        let mut raw_extensions = extension_bytes;
        for ext in ext_list {
            let (remaining, (extension_id, extension_payload)) =
                parser::parse_tls_extension_frame(raw_extensions)
                    .map_err(|_| ClientHelloParseError::new(ClientHelloParseStage::Extensions))?;
            raw_extensions = remaining;

            tracing::trace!(extension_id, "decoding TLS ClientHello extension");

            match ext {
                tls_parser::TlsExtension::SNI(name) => {
                    client_hello.extensions.push(TlsExtension::ServerName {
                        value: extension_id,
                        data: name
                            .into_iter()
                            .map(|n| n.1)
                            .map(|n| String::from_utf8_lossy(n).into_owned().into_boxed_str())
                            .collect(),
                    });
                }
                tls_parser::TlsExtension::EllipticCurves(groups) => {
                    client_hello.extensions.push(TlsExtension::SupportedGroups {
                        value: extension_id,
                        data: groups
                            .into_iter()
                            .map(|group| NamedGroup::from(group.0))
                            .collect(),
                    });
                }
                tls_parser::TlsExtension::SupportedVersions(versions) => {
                    client_hello
                        .extensions
                        .push(TlsExtension::SupportedVersions {
                            value: extension_id,
                            data: SupportedVersions::from_ids(
                                versions.into_iter().map(|version| version.0),
                            ),
                        });
                }
                tls_parser::TlsExtension::SessionTicket(data) => {
                    client_hello.extensions.push(TlsExtension::SessionTicket {
                        value: extension_id,
                        data: HexBytes::from(data),
                    });
                }
                tls_parser::TlsExtension::SignatureAlgorithms(algorithms) => {
                    client_hello
                        .extensions
                        .push(TlsExtension::SignatureAlgorithms {
                            value: extension_id,
                            data: algorithms
                                .into_iter()
                                .map(SignatureAlgorithm::from)
                                .collect(),
                        });
                }
                tls_parser::TlsExtension::StatusRequest(data) => {
                    let Some((status, data)) = data else {
                        return Err(ClientHelloParseError::extension(
                            ClientHelloParseStage::StatusRequest,
                            extension_id,
                            extension_payload.len(),
                        ));
                    };

                    let certificate_status_type = CertificateStatusType::from(status.0);
                    if certificate_status_type != CertificateStatusType::OCSP {
                        return Err(ClientHelloParseError::extension(
                            ClientHelloParseStage::StatusRequest,
                            extension_id,
                            extension_payload.len(),
                        ));
                    }

                    let (_, (responder_id_list, request_extensions)) =
                        parser::parse_ocsp_status_request_lengths(data).map_err(|_| {
                            ClientHelloParseError::extension(
                                ClientHelloParseStage::StatusRequest,
                                extension_id,
                                extension_payload.len(),
                            )
                        })?;
                    client_hello.extensions.push(TlsExtension::StatusRequest {
                        value: extension_id,
                        data: StatusRequest {
                            certificate_status_type,
                            responder_id_list,
                            request_extensions,
                        },
                    });
                }
                tls_parser::TlsExtension::EcPointFormats(formats) => {
                    client_hello.extensions.push(TlsExtension::EcPointFormats {
                        value: extension_id,
                        data: formats.iter().map(|f| ECPointFormat::from(*f)).collect(),
                    });
                }
                tls_parser::TlsExtension::ALPN(_) => {
                    let (_, protocols) =
                        parser::parse_alpn_packet(extension_payload).map_err(|_| {
                            ClientHelloParseError::extension(
                                ClientHelloParseStage::ApplicationLayerProtocolNegotiation,
                                extension_id,
                                extension_payload.len(),
                            )
                        })?;

                    client_hello.extensions.push(
                        TlsExtension::ApplicationLayerProtocolNegotiation {
                            value: extension_id,
                            data: protocols,
                        },
                    );
                }
                tls_parser::TlsExtension::SignedCertificateTimestamp(timestamps) => {
                    client_hello
                        .extensions
                        .push(TlsExtension::SignedCertificateTimestamp {
                            value: extension_id,
                            data: timestamps.map(HexBytes::from),
                        });
                }
                tls_parser::TlsExtension::RenegotiationInfo(_) => {
                    client_hello
                        .extensions
                        .push(TlsExtension::RenegotiationInfo {
                            value: extension_id,
                        });
                }
                tls_parser::TlsExtension::Unknown(TlsExtensionType(34), algorithms) => {
                    let extension =
                        parser::parse_tls_extension_delegated_credentials(extension_id, algorithms)
                            .map_err(|_| {
                                ClientHelloParseError::extension(
                                    ClientHelloParseStage::DelegatedCredentials,
                                    extension_id,
                                    algorithms.len(),
                                )
                            })?
                            .1;
                    client_hello.extensions.push(extension);
                }
                tls_parser::TlsExtension::RecordSizeLimit(limit) => {
                    client_hello.extensions.push(TlsExtension::RecordSizeLimit {
                        value: extension_id,
                        data: limit,
                    });
                }
                tls_parser::TlsExtension::Unknown(TlsExtensionType(27), data) => {
                    let extension =
                        parser::parse_tls_extension_certificate_compression(extension_id, data)
                            .map_err(|_| {
                                ClientHelloParseError::extension(
                                    ClientHelloParseStage::CertificateCompression,
                                    extension_id,
                                    data.len(),
                                )
                            })?
                            .1;
                    client_hello.extensions.push(extension);
                }
                tls_parser::TlsExtension::Unknown(TlsExtensionType(65037), data) => {
                    let extension = parser::parse_tls_extension_ech(extension_id, data)
                        .map_err(|_| {
                            ClientHelloParseError::extension(
                                ClientHelloParseStage::EncryptedClientHello,
                                extension_id,
                                data.len(),
                            )
                        })?
                        .1;
                    client_hello.extensions.push(extension);
                }
                tls_parser::TlsExtension::Padding(padding) => {
                    client_hello.extensions.push(TlsExtension::Padding {
                        value: extension_id,
                        data: HexBytes::from(padding),
                    });
                }
                tls_parser::TlsExtension::KeyShare(data) => {
                    client_hello.extensions.push(TlsExtension::KeyShare {
                        value: extension_id,
                        data: parser::parse_key_share(data)
                            .ok_or(ClientHelloParseError::extension(
                                ClientHelloParseStage::KeyShare,
                                extension_id,
                                data.len(),
                            ))?
                            .into_iter()
                            .map(|(group, key_exchange)| KeyShare::from_wire(group, key_exchange))
                            .collect(),
                    });
                }
                tls_parser::TlsExtension::PskExchangeModes(data) => {
                    client_hello
                        .extensions
                        .push(TlsExtension::PskKeyExchangeModes {
                            value: extension_id,
                            data: PskKeyExchangeModes {
                                ke_modes: data.into_iter().map(PskKeyExchangeMode::from).collect(),
                            },
                        });
                }
                tls_parser::TlsExtension::PreSharedKey(data) => {
                    client_hello.extensions.push(TlsExtension::PreSharedKey {
                        value: extension_id,
                        data: HexBytes::from(data),
                    });
                }
                tls_parser::TlsExtension::Unknown(extension_type, data)
                    if extension_type.0 == TRANSPORT_PARAMETERS_EXTENSION_ID =>
                {
                    let parameters = parse_transport_parameters(data).map_err(|_| {
                        ClientHelloParseError::extension(
                            ClientHelloParseStage::QuicTransportParameters,
                            extension_id,
                            data.len(),
                        )
                    })?;
                    client_hello
                        .extensions
                        .push(TlsExtension::QuicTransportParameters {
                            value: extension_id,
                            data: parameters,
                        });
                }
                tls_parser::TlsExtension::Unknown(TlsExtensionType(17513), protocols) => {
                    let (_, protocols) = parser::parse_alps_packet(protocols).map_err(|_| {
                        ClientHelloParseError::extension(
                            ClientHelloParseStage::ApplicationSettings,
                            extension_id,
                            protocols.len(),
                        )
                    })?;

                    client_hello
                        .extensions
                        .push(TlsExtension::ApplicationSettingsOld {
                            value: extension_id,
                            data: protocols,
                        });
                }
                tls_parser::TlsExtension::Unknown(TlsExtensionType(17613), protocols) => {
                    let (_, protocols) = parser::parse_alps_packet(protocols).map_err(|_| {
                        ClientHelloParseError::extension(
                            ClientHelloParseStage::ApplicationSettings,
                            extension_id,
                            protocols.len(),
                        )
                    })?;

                    client_hello
                        .extensions
                        .push(TlsExtension::ApplicationSettings {
                            value: extension_id,
                            data: protocols,
                        });
                }
                tls_parser::TlsExtension::ExtendedMasterSecret => {
                    client_hello
                        .extensions
                        .push(TlsExtension::ExtendedMasterSecret {
                            value: extension_id,
                        });
                }
                tls_parser::TlsExtension::Grease(..) => {
                    client_hello.extensions.push(TlsExtension::Grease {
                        value: extension_id,
                    });
                }

                tls_parser::TlsExtension::MaxFragmentLength(data) => {
                    client_hello.extensions.push(TlsExtension::Opaque {
                        value: extension_id,
                        data: Some(HexBytes::from(data.to_be_bytes())),
                    });
                }
                tls_parser::TlsExtension::KeyShareOld(items) => {
                    client_hello.extensions.push(TlsExtension::Opaque {
                        value: extension_id,
                        data: Some(HexBytes::from(items)),
                    });
                }
                tls_parser::TlsExtension::EarlyData(data) => {
                    client_hello.extensions.push(TlsExtension::Opaque {
                        value: extension_id,
                        data: data.map(|value| HexBytes::from(value.to_be_bytes())),
                    });
                }
                tls_parser::TlsExtension::Cookie(items) => {
                    client_hello.extensions.push(TlsExtension::Opaque {
                        value: extension_id,
                        data: Some(HexBytes::from(items)),
                    });
                }
                tls_parser::TlsExtension::Heartbeat(data) => {
                    client_hello.extensions.push(TlsExtension::Opaque {
                        value: extension_id,
                        data: Some(HexBytes::from(data.to_be_bytes())),
                    });
                }
                tls_parser::TlsExtension::EncryptThenMac => {
                    client_hello.extensions.push(TlsExtension::Opaque {
                        value: extension_id,
                        data: None,
                    });
                }
                tls_parser::TlsExtension::OidFilters(oid_filters) => {
                    client_hello.extensions.push(TlsExtension::OidFilters {
                        value: extension_id,
                        data: oid_filters
                            .into_iter()
                            .map(|f| OidFilter {
                                cert_ext_oid: HexBytes::from(f.cert_ext_oid),
                                cert_ext_val: HexBytes::from(f.cert_ext_val),
                            })
                            .collect(),
                    });
                }
                tls_parser::TlsExtension::PostHandshakeAuth => {
                    client_hello.extensions.push(TlsExtension::Opaque {
                        value: extension_id,
                        data: None,
                    });
                }
                tls_parser::TlsExtension::NextProtocolNegotiation => {
                    client_hello.extensions.push(TlsExtension::Opaque {
                        value: extension_id,
                        data: None,
                    });
                }
                tls_parser::TlsExtension::EncryptedServerName {
                    ciphersuite,
                    group,
                    key_share,
                    record_digest,
                    encrypted_sni,
                } => {
                    client_hello
                        .extensions
                        .push(TlsExtension::EncryptedServerName {
                            value: extension_id,
                            ciphersuite: tls_parser::TlsCipherSuite::from_id(ciphersuite.0)
                                .map(|c| c.name)
                                .unwrap_or("Unknown")
                                .into(),
                            group: NamedGroup::from(group.0),
                            key_share: HexBytes::from(key_share),
                            record_digest: HexBytes::from(record_digest),
                            encrypted_sni: HexBytes::from(encrypted_sni),
                        });
                }

                tls_parser::TlsExtension::Unknown(_, data) => {
                    client_hello.extensions.push(TlsExtension::Opaque {
                        value: extension_id,
                        data: Some(HexBytes::from(data)),
                    });
                }
            }
        }
        if !raw_extensions.is_empty() {
            return Err(ClientHelloParseError::new(
                ClientHelloParseStage::Extensions,
            ));
        }

        Ok(client_hello)
    }

    /// Returns the QUIC transport parameters carried by this ClientHello, when present.
    ///
    /// Parameters retain their original wire order. See
    /// [RFC 9001, Section 8.2](https://www.rfc-editor.org/rfc/rfc9001#section-8.2).
    pub fn quic_transport_parameters(&self) -> Option<&[QuicTransportParameter]> {
        self.extensions
            .iter()
            .find_map(|extension| match extension {
                TlsExtension::QuicTransportParameters { data, .. } => Some(data.as_slice()),
                _ => None,
            })
    }

    /// Calculates the JA4 fingerprint and its unhashed source form.
    pub fn ja4(&self) -> Ja4Fingerprint {
        Ja4Fingerprint::from(self)
    }

    /// Calculates the JA3 source string and MD5 digest.
    pub fn ja3(&self) -> Ja3Fingerprint {
        Ja3Fingerprint::from(self)
    }
}

#[cfg(test)]
mod tests {
    use super::{
        ClientHello, ClientHelloBuffer, ClientHelloHandshakeBuffer, ClientHelloParseStage,
        ECHClientHelloOuter, HexBytes, KeyShare, ProtocolName, StatusRequest, TlsCipherSuite,
        TlsExtension,
    };
    use crate::tls::{CompressionAlgorithm, NamedGroup, SupportedVersions, TlsVersion};

    fn tls_record(payload: &[u8]) -> Vec<u8> {
        let length = u16::try_from(payload.len()).unwrap();
        let mut record = vec![0x16, 0x03, 0x03];
        record.extend_from_slice(&length.to_be_bytes());
        record.extend_from_slice(payload);
        record
    }

    fn client_hello_handshake(extensions: Option<&[u8]>) -> Vec<u8> {
        let mut body = vec![0x03, 0x03];
        body.extend_from_slice(&[0; 32]);
        body.push(0);
        body.extend_from_slice(&[0, 2, 0x13, 0x01]);
        body.extend_from_slice(&[1, 0]);
        if let Some(extensions) = extensions {
            let length = u16::try_from(extensions.len()).unwrap();
            body.extend_from_slice(&length.to_be_bytes());
            body.extend_from_slice(extensions);
        }

        let length = u32::try_from(body.len()).unwrap().to_be_bytes();
        let mut handshake = vec![1, length[1], length[2], length[3]];
        handshake.extend_from_slice(&body);
        handshake
    }

    #[test]
    fn tls_cipher_suite_resolves_and_validates_ids_and_names() {
        let known = TlsCipherSuite::from_id(0x1301);
        assert_eq!(known.id, 0x1301);
        assert_eq!(known.name.as_ref(), "TLS_AES_128_GCM_SHA256");
        assert!(!known.is_grease());

        assert_eq!(
            TlsCipherSuite::from_name("TLS_AES_128_GCM_SHA256"),
            Some(known)
        );
        assert!(TlsCipherSuite::from_name("GREASE").is_none());

        let grease = TlsCipherSuite::from_id(0x0a0a);
        assert_eq!(grease.name.as_ref(), "GREASE");
        assert!(grease.is_grease());

        let unknown = TlsCipherSuite::from_id(0xffff);
        assert_eq!(unknown.name.as_ref(), "Unknown");
        assert!(!unknown.is_grease());

        let error = serde_json::from_value::<TlsCipherSuite>(serde_json::json!({
            "id": 0x1301,
            "name": "TLS_AES_256_GCM_SHA384"
        }))
        .expect_err("mismatched cipher-suite name must fail");
        assert!(
            error
                .to_string()
                .contains("has name \"TLS_AES_128_GCM_SHA256\""),
            "{error}"
        );
    }

    #[test]
    fn hex_bytes_serialize_canonically_and_reject_invalid_text() {
        let bytes = HexBytes::from([0x00, 0xab, 0xff]);
        let json = serde_json::to_value(&bytes).expect("hex bytes serialize");

        assert_eq!(json, serde_json::json!("00abff"));
        assert_eq!(
            serde_json::from_value::<HexBytes>(json).expect("hex bytes deserialize"),
            bytes
        );

        for invalid in ["0", "00AB", "00gg"] {
            assert!(serde_json::from_value::<HexBytes>(serde_json::json!(invalid)).is_err());
        }
    }

    #[test]
    fn protocol_names_roundtrip_text_and_opaque_bytes() {
        let h2 = ProtocolName::try_from("h2").unwrap();
        let h2_json = serde_json::to_value(&h2).expect("UTF-8 protocol name serializes");
        assert_eq!(h2_json, serde_json::json!("h2"));
        assert_eq!(serde_json::from_value::<ProtocolName>(h2_json).unwrap(), h2);

        let opaque = ProtocolName::try_from(&[0xff, b'x'][..]).unwrap();
        let opaque_json = serde_json::to_value(&opaque).expect("opaque protocol name serializes");
        assert_eq!(opaque_json, serde_json::json!({"hex": "ff78"}));
        assert_eq!(
            serde_json::from_value::<ProtocolName>(opaque_json).unwrap(),
            opaque
        );

        for invalid in [
            serde_json::json!(""),
            serde_json::json!({"hex": ""}),
            serde_json::json!({"hex": "FF"}),
            serde_json::json!("a".repeat(256)),
        ] {
            assert!(serde_json::from_value::<ProtocolName>(invalid).is_err());
        }
    }

    #[test]
    fn ech_json_validates_payload_length() {
        let valid = serde_json::json!({
            "cipher_suite": {
                "kdf_id": "HKDF_SHA256",
                "aead_id": "AES_128_GCM"
            },
            "config_id": 7,
            "enc": "",
            "payload": "aa",
            "payload_length": 1
        });
        let outer = serde_json::from_value::<ECHClientHelloOuter>(valid.clone())
            .expect("valid ECH outer deserializes");
        assert_eq!(outer.payload.as_bytes(), [0xaa]);

        let mut mismatch = valid.clone();
        mismatch["payload_length"] = serde_json::json!(2);
        assert!(serde_json::from_value::<ECHClientHelloOuter>(mismatch).is_err());

        let mut empty = valid;
        empty["payload"] = serde_json::json!("");
        empty["payload_length"] = serde_json::json!(0);
        assert!(serde_json::from_value::<ECHClientHelloOuter>(empty).is_err());
    }

    #[test]
    fn key_shares_serialize_id_name_and_optional_exchange_bytes() {
        let grease = KeyShare::from_wire(0x3a3a, vec![0x00]);

        assert_eq!(grease.id, 0x3a3a);
        assert_eq!(grease.name.as_ref(), "GREASE");
        assert_eq!(grease.key_exchange, None);

        let grease_json = serde_json::to_value(&grease).expect("GREASE KeyShare serializes");
        assert_eq!(
            grease_json,
            serde_json::json!({
                "id": 0x3a3a,
                "name": "GREASE"
            })
        );

        let x25519 = KeyShare::from_wire(29, vec![0x01, 0x02]);
        let x25519_json = serde_json::to_value(&x25519).expect("x25519 KeyShare serializes");
        assert_eq!(
            x25519_json,
            serde_json::json!({
                "id": 29,
                "name": "x25519",
                "value": "0102"
            })
        );

        assert_eq!(
            serde_json::from_value::<KeyShare>(grease_json).expect("GREASE KeyShare deserializes"),
            grease
        );
        assert_eq!(
            serde_json::from_value::<KeyShare>(x25519_json).expect("x25519 KeyShare deserializes"),
            x25519
        );

        assert!(serde_json::from_value::<KeyShare>(serde_json::json!({
            "id": 29,
            "name": "x25519"
        }))
        .is_err());
        assert!(serde_json::from_value::<KeyShare>(serde_json::json!({
            "id": 29,
            "name": "x25519",
            "value": ""
        }))
        .is_err());
        assert!(serde_json::from_value::<KeyShare>(serde_json::json!({
            "id": 0x3a3a,
            "name": "GREASE",
            "value": "00"
        }))
        .is_err());
    }

    #[test]
    fn malformed_client_hello_reports_parse_stages() {
        let Err(record_error) = ClientHello::parse(&[]) else {
            panic!("expected malformed TLS record to fail");
        };
        assert_eq!(record_error.stage, ClientHelloParseStage::TlsRecord);
        assert_eq!(record_error.extension_id, None);
        assert_eq!(record_error.payload_len, None);

        let Err(message_error) = ClientHello::parse(&[0; 5]) else {
            panic!("expected malformed TLS messages to fail");
        };
        assert_eq!(message_error.stage, ClientHelloParseStage::RecordMessages);
        assert_eq!(message_error.extension_id, None);
        assert_eq!(message_error.payload_len, None);
    }

    #[test]
    fn client_hello_buffer_uses_requested_initial_capacity() {
        let mut buffer = ClientHelloBuffer::with_capacity(64);

        assert!(buffer.is_empty());
        assert!(buffer.buf.capacity() >= 64);
        assert_eq!(buffer.extend(&[1, 2, 3]), 3);
        assert_eq!(buffer.as_bytes(), [1, 2, 3]);
    }

    #[test]
    fn client_hello_buffer_distinguishes_incomplete_and_malformed_records() {
        let mut buffer = ClientHelloBuffer::from(vec![0; 4]);

        assert!(buffer.try_parse().unwrap().is_none());
        buffer.extend(&[0]);

        let error = buffer.try_parse().unwrap_err();
        assert_eq!(error.stage, ClientHelloParseStage::RecordMessages);
        assert!(buffer.is_invalid());
        assert_eq!(buffer.extend(&[1, 2, 3]), 0);
        assert_eq!(buffer.as_bytes(), &[0; 5]);

        let borrowed = ClientHelloBuffer::from(&[1, 2, 3][..]);
        assert_eq!(borrowed.as_bytes(), [1, 2, 3]);
    }

    #[test]
    fn client_hello_buffer_reassembles_records_without_an_extension_block() {
        let handshake = client_hello_handshake(None);
        let first = tls_record(&handshake[..13]);
        let second = tls_record(&handshake[13..]);
        let extra = [0x17, 0x03, 0x03, 0, 1, 0];

        let mut buffer = ClientHelloBuffer::new();
        assert_eq!(buffer.extend(&first), first.len());
        assert!(!buffer.is_complete());
        assert!(buffer.try_parse().unwrap().is_none());

        let mut tail = second.clone();
        tail.extend_from_slice(&extra);
        assert_eq!(buffer.extend(&tail), second.len());
        assert!(buffer.is_complete());
        assert_eq!(buffer.len(), first.len() + second.len());
        assert_eq!(buffer.extend(&extra), 0);

        let client_hello = buffer.try_parse().unwrap().unwrap();
        assert_eq!(client_hello.cipher_suites[0].id, 0x1301);
        assert!(client_hello.extensions.is_empty());
        assert_eq!(buffer.parse().unwrap(), client_hello);
    }

    #[test]
    fn client_hello_buffer_from_bytes_discards_following_records() {
        let expected = tls_record(&client_hello_handshake(None));
        let mut capture = expected.clone();
        capture.extend_from_slice(&[0x17, 0x03, 0x03, 0, 1, 0]);

        let buffer = ClientHelloBuffer::from(capture);

        assert!(buffer.is_complete());
        assert_eq!(buffer.as_bytes(), expected);
    }

    #[test]
    fn handshake_buffer_reassembles_quic_crypto_bytes_and_discards_tail() {
        let handshake = client_hello_handshake(None);
        let mut buffer = ClientHelloHandshakeBuffer::with_capacity(32);

        for chunk in handshake.chunks(3) {
            buffer.extend(chunk);
        }
        buffer.extend(&[0x14, 0, 0, 0]);

        assert!(buffer.is_complete());
        assert!(!buffer.is_invalid());
        assert_eq!(buffer.as_bytes(), handshake);
        assert_eq!(buffer.extend(&[0]), 0);

        let client_hello = buffer.try_parse().unwrap().unwrap();
        assert_eq!(client_hello.cipher_suites[0].id, 0x1301);

        let malformed = ClientHelloHandshakeBuffer::from(&[2, 0, 0, 0][..]);
        assert!(malformed.is_invalid());
        assert!(malformed.parse().is_err());
    }

    #[test]
    fn parse_handshake_rejects_an_incomplete_header() {
        let error = ClientHello::parse_handshake(&[1, 0, 0]).unwrap_err();

        assert_eq!(error.stage, ClientHelloParseStage::RecordMessages);
    }

    #[test]
    fn parse_handshake_rejects_a_non_client_hello_message() {
        let mut handshake = client_hello_handshake(None);
        handshake[0] = 2;

        let error = ClientHello::parse_handshake(&handshake).unwrap_err();

        assert_eq!(error.stage, ClientHelloParseStage::ClientHello);
    }

    #[test]
    fn parse_handshake_rejects_declared_length_mismatches() {
        let handshake = client_hello_handshake(None);
        let payload_len = handshake.len() - 4;

        for declared_len in [payload_len - 1, payload_len + 1] {
            let mut malformed = handshake.clone();
            let encoded = u32::try_from(declared_len).unwrap().to_be_bytes();
            malformed[1..4].copy_from_slice(&encoded[1..]);

            let error = ClientHello::parse_handshake(&malformed).unwrap_err();
            assert_eq!(error.stage, ClientHelloParseStage::RecordMessages);
        }
    }

    #[test]
    fn parse_handshake_rejects_trailing_bytes() {
        let mut handshake = client_hello_handshake(None);
        handshake.push(0);

        let error = ClientHello::parse_handshake(&handshake).unwrap_err();

        assert_eq!(error.stage, ClientHelloParseStage::RecordMessages);
    }

    #[test]
    fn client_hello_buffer_tracks_fragmented_records_incrementally() {
        let handshake = client_hello_handshake(None);
        let records = handshake.chunks(1).flat_map(tls_record).collect::<Vec<_>>();
        let mut buffer = ClientHelloBuffer::new();

        for (index, byte) in records.chunks(1).enumerate() {
            assert_eq!(buffer.extend(byte), 1);
            if index + 1 < records.len() {
                assert!(buffer.try_parse().unwrap().is_none());
            }
        }

        assert!(buffer.is_complete());
        assert!(!buffer.is_invalid());
        assert_eq!(buffer.capture.record_offset, records.len());

        let client_hello = buffer.try_parse().unwrap().unwrap();
        assert_eq!(client_hello.cipher_suites[0].id, 0x1301);
    }

    #[test]
    fn client_hello_rejects_an_unconsumed_extension_tail() {
        let handshake = client_hello_handshake(Some(&[0]));
        let error = ClientHello::parse(&tls_record(&handshake)).unwrap_err();

        assert_eq!(error.stage, ClientHelloParseStage::Extensions);
    }

    #[test]
    fn client_hello_reports_strict_extension_parse_stages() {
        let cases = [
            (
                &[0x00, 0x05, 0x00, 0x00][..],
                ClientHelloParseStage::StatusRequest,
                5,
                0,
            ),
            (
                &[0x00, 0x05, 0x00, 0x01, 0x02][..],
                ClientHelloParseStage::StatusRequest,
                5,
                1,
            ),
            (
                &[0x00, 0x10, 0x00, 0x03, 0x00, 0x01, 0x00][..],
                ClientHelloParseStage::ApplicationLayerProtocolNegotiation,
                16,
                3,
            ),
            (
                &[0x00, 0x10, 0x00, 0x06, 0x00, 0x03, 0x02, b'h', b'2', 0x00][..],
                ClientHelloParseStage::ApplicationLayerProtocolNegotiation,
                16,
                6,
            ),
            (
                &[0x44, 0xcd, 0x00, 0x02, 0x00, 0x00][..],
                ClientHelloParseStage::ApplicationSettings,
                17_613,
                2,
            ),
            (
                &[0x00, 0x39, 0x00, 0x03, 0x04, 0x02, 0x20][..],
                ClientHelloParseStage::QuicTransportParameters,
                57,
                3,
            ),
        ];

        for (extension, stage, extension_id, payload_len) in cases {
            let handshake = client_hello_handshake(Some(extension));
            let error = ClientHello::parse(&tls_record(&handshake)).unwrap_err();

            assert_eq!(error.stage, stage);
            assert_eq!(error.extension_id, Some(extension_id));
            assert_eq!(error.payload_len, Some(payload_len));
        }
    }

    #[test]
    fn status_request_deserialization_rejects_non_ocsp_metadata() {
        let valid = serde_json::json!({"certificate_status_type": "OCSP", "responder_id_list": 0, "request_extensions": 0});
        assert!(serde_json::from_value::<StatusRequest>(valid.clone()).is_ok());
        let mut unknown_type = valid.clone();
        unknown_type["certificate_status_type"] = serde_json::json!("Unknown (0x0002)");
        assert!(serde_json::from_value::<StatusRequest>(unknown_type).is_err());
        for responder_id_list in [1, 2] {
            let mut invalid_length = valid.clone();
            invalid_length["responder_id_list"] = serde_json::json!(responder_id_list);
            assert!(serde_json::from_value::<StatusRequest>(invalid_length).is_err());
        }
    }

    #[test]
    fn client_hello_buffer_enforces_the_capture_limit() {
        let mut buffer = ClientHelloBuffer::with_capture_limit(32);
        let input = vec![0; 48];

        assert_eq!(buffer.extend(&input), 32);
        assert_eq!(buffer.len(), 32);
        assert_eq!(buffer.capture_limit(), 32);
        assert!(buffer.is_full());
        assert_eq!(buffer.extend(&[1, 2, 3]), 0);

        let oversized = ClientHelloBuffer::from(&[0x16, 0x03, 0x03, 0x41, 0x01][..]);
        let error = oversized.try_parse().unwrap_err();
        assert_eq!(error.stage, ClientHelloParseStage::TlsRecord);
    }

    #[test]
    fn client_hello_json_roundtrip_preserves_fingerprints() {
        let client_hello = ClientHello {
            tls_version: TlsVersion::TLSv1_2,
            tls_version_negotiated: Some(TlsVersion::TLSv1_3),
            cipher_suites: vec![TlsCipherSuite::from(0x0a0a), TlsCipherSuite::from(0x1301)],
            client_random: HexBytes::from([0; 32]),
            session_id: None,
            compression_algorithms: vec![CompressionAlgorithm::Null],
            extensions: vec![
                TlsExtension::SupportedVersions {
                    value: 0x002b,
                    data: SupportedVersions::from_ids([0x2a2a, 0x0304]),
                },
                TlsExtension::SupportedGroups {
                    value: 0x000a,
                    data: vec![NamedGroup::from(29), NamedGroup::from(0x4a4a)],
                },
            ],
        };
        let ja3 = client_hello.ja3();
        let ja4 = client_hello.ja4();
        let json = serde_json::to_value(&client_hello).expect("ClientHello serializes");

        assert_eq!(
            json["cipher_suites"],
            serde_json::json!([
                {
                    "id": 2570,
                    "name": "GREASE"
                },
                {
                    "id": 4865,
                    "name": "TLS_AES_128_GCM_SHA256"
                }
            ])
        );
        assert_eq!(
            json["extensions"][0]["supported_versions"]["data"],
            serde_json::json!({
                "versions": [
                    {
                        "id": 10794,
                        "name": "GREASE"
                    },
                    {
                        "id": 772,
                        "name": "TLSv1_3"
                    }
                ]
            })
        );
        assert!(json.get("cipher_values").is_none());
        assert!(json.get("ciphers").is_none());
        let mut invalid_random = json.clone();
        invalid_random["client_random"] = serde_json::json!("00");
        assert!(serde_json::from_value::<ClientHello>(invalid_random).is_err());

        let mut empty_session_id = json.clone();
        empty_session_id["session_id"] = serde_json::json!("");
        assert!(serde_json::from_value::<ClientHello>(empty_session_id).is_err());

        let mut oversized_session_id = json.clone();
        oversized_session_id["session_id"] = serde_json::json!("00".repeat(33));
        assert!(serde_json::from_value::<ClientHello>(oversized_session_id).is_err());

        let mut legacy_json = json.clone();
        let legacy_object = legacy_json
            .as_object_mut()
            .expect("ClientHello serializes as an object");
        let cipher_suites = legacy_object
            .remove("cipher_suites")
            .expect("cipher_suites is present");
        legacy_object.insert("ciphers".to_owned(), cipher_suites);
        assert!(serde_json::from_value::<ClientHello>(legacy_json).is_err());

        let restored: ClientHello =
            serde_json::from_value(json.clone()).expect("ClientHello deserializes");
        assert_eq!(restored, client_hello);
        assert_eq!(restored.ja3(), ja3);
        assert_eq!(restored.ja4(), ja4);
        assert_eq!(
            serde_json::to_value(restored).expect("restored ClientHello serializes"),
            json
        );
    }

    #[test]
    fn quic_transport_parameters_are_decoded_in_client_hello() {
        let handshake = client_hello_handshake(Some(&[0x00, 0x39, 0x00, 0x03, 0x04, 0x01, 0x20]));
        let client_hello = ClientHello::parse_handshake(&handshake).expect("ClientHello parses");
        let parameters = client_hello
            .quic_transport_parameters()
            .expect("parameters exist");
        assert_eq!(parameters[0].id, 4);
        let extension = client_hello
            .extensions
            .first()
            .expect("extension is present");

        let json = serde_json::to_value(extension).expect("QUIC extension serializes");
        assert_eq!(
            json,
            serde_json::json!({
                "quic_transport_parameters": {
                    "value": 57,
                    "data": [{"id": 4, "name": "initial_max_data", "value": 32}]
                }
            })
        );
        let restored = serde_json::from_value::<TlsExtension>(json.clone())
            .expect("QUIC extension deserializes");
        assert_eq!(&restored, extension);

        let mut duplicate = json.clone();
        let parameters = duplicate["quic_transport_parameters"]["data"]
            .as_array_mut()
            .unwrap();
        for index in 0..4_096_u64 {
            parameters.push(serde_json::json!({
                "id": (1_u64 << 40) + index * 31,
                "name": "other",
                "value": ""
            }));
        }
        parameters.push(parameters[0].clone());
        let mut wrong_id = json;
        wrong_id["quic_transport_parameters"]["value"] = serde_json::json!(58);
        let opaque = serde_json::json!({"opaque": {"value": 57, "data": "040120"}});

        assert!(serde_json::from_value::<TlsExtension>(duplicate).is_err());
        assert!(serde_json::from_value::<TlsExtension>(wrong_id).is_err());
        assert!(serde_json::from_value::<TlsExtension>(opaque).is_err());
    }

    #[test]
    fn tls_extensions_reject_variant_id_mismatches() {
        let wrong_known_id = serde_json::json!({
            "supported_versions": {"value": 0, "data": {"versions": []}}
        });
        let non_grease_id = serde_json::json!({
            "grease": {"value": 0}
        });
        let dedicated_opaque_id = serde_json::json!({
            "opaque": {"value": 43, "data": null}
        });

        assert!(serde_json::from_value::<TlsExtension>(wrong_known_id).is_err());
        assert!(serde_json::from_value::<TlsExtension>(non_grease_id).is_err());
        assert!(serde_json::from_value::<TlsExtension>(dedicated_opaque_id).is_err());

        let grease = serde_json::json!({"grease": {"value": 2570}});
        let opaque = serde_json::json!({"opaque": {"value": 1, "data": null}});
        assert!(serde_json::from_value::<TlsExtension>(grease).is_ok());
        assert!(serde_json::from_value::<TlsExtension>(opaque).is_ok());
    }
}