kryphocron 0.1.1

Privacy-first ATProto substrate primitives: type architecture, audit vocabulary, inter-service auth, and encryption hook surfaces
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
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! §7.2 / §7.5 verification submodule.
//!
//! [`crate::verification::verify_jwt`] wires §7.2 — the JWT
//! verification chain. [`crate::verification::verify_capability_claim`]
//! wires §7.6 — the capability-claim verification chain.
//! [`crate::verification::VerifiedJwt`] and
//! [`crate::verification::VerifiedCapabilityClaim`] are the
//! corresponding evidence types, each with private fields and
//! a crate-internal constructor.
//!
//! [`crate::verification::VerifiedSyncMessage`] (§7.5) carries
//! a verified post-handshake sync-channel message; the
//! three-message handshake establishment evidence ships as
//! [`crate::verification::VerifiedSyncHello`],
//! [`crate::verification::VerifiedSyncAccept`], and
//! [`crate::verification::VerifiedSyncEstablished`].
//!
//! See §7.2 for the JWT verification flow, §7.5 for the
//! sync-handshake protocol.

use core::marker::PhantomData;
use std::time::{Duration, Instant, SystemTime};

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine;
use ed25519_dalek::{Signature as Ed25519Signature, Verifier, VerifyingKey};
use smallvec::SmallVec;
use thiserror::Error;

use crate::authority::capability::CapabilityKind;
use crate::identity::{
    KeyId, PublicKey, ServiceIdentity, SessionId, SignatureAlgorithm, TraceId,
};
use crate::proto::Did;
use crate::resolver::{DidResolutionError, DidResolver};
use crate::sealed;
use crate::audit::BatchRejectionReason;
use crate::authority::capability::CapabilitySet;
use crate::authority::predicate::BindError;
use crate::wire::{
    accept_to_wire_bytes, decode_accept_wire, decode_established_wire,
    decode_hello_wire, decode_reject_wire, decode_wire_envelope,
    established_to_wire_bytes, hello_to_wire_bytes, reject_to_wire_bytes,
    verify_delegation_receipt, wire_envelope_is_canonical, AttributionChainWire,
    AttributionEntryWire, AttributionPrincipal, CapabilityClaim,
    DelegationReceiptPayload, HandshakeNonceTracker, JwtNonce, NonceFreshness,
    NonceIssuerKey, NoncePrincipal, NonceTracker, NonceTrackerError,
    ReceiptVerificationFailure, ResourceScope, SessionNonce, SyncChannelAccept,
    SyncChannelEstablished, SyncChannelHello, SyncChannelReject,
    SyncRequestedScope, CLAIM_DOMAIN_TAG, MAX_CAPABILITY_CLAIM_SIZE,
    MAX_HANDSHAKE_MESSAGE_SIZE,
};
use kryphocron_lexicons::SemVer;

/// JWT that passed signature **and** claim verification (§7.2).
///
/// Constructible only via [`verify_jwt`]; consumers receiving a
/// [`VerifiedJwt`] need not re-verify or trust the caller.
///
/// Outside-crate code cannot construct a [`VerifiedJwt`] via
/// struct-literal syntax — every field is private, including the
/// crate-sealed `_private: PhantomData<sealed::Token>` marker.
/// The compile-fail doctest below is the witness:
///
/// ```compile_fail
/// // Outside-crate construction must not work — the only way to
/// // obtain a `VerifiedJwt` is `verify_jwt`'s success path.
/// use kryphocron::verification::VerifiedJwt;
/// let _v = VerifiedJwt {
///     // fields are private; this fails E0451 / E0451-flavored.
/// };
/// ```
#[derive(Debug, Clone)]
pub struct VerifiedJwt {
    issuer: Did,
    audience: ServiceIdentity,
    issued_at: SystemTime,
    expires_at: SystemTime,
    scope: JwtScope,
    nonce: Option<JwtNonce>,
    algorithm: SignatureAlgorithm,
    _private: PhantomData<sealed::Token>,
}

impl VerifiedJwt {
    /// Crate-internal constructor. Reserved for [`verify_jwt`]
    /// after every §7.2 verification stage has succeeded; not
    /// reachable from outside `crate::verification`.
    #[must_use]
    pub(crate) fn new_internal(
        issuer: Did,
        audience: ServiceIdentity,
        issued_at: SystemTime,
        expires_at: SystemTime,
        scope: JwtScope,
        nonce: Option<JwtNonce>,
        algorithm: SignatureAlgorithm,
    ) -> Self {
        VerifiedJwt {
            issuer,
            audience,
            issued_at,
            expires_at,
            scope,
            nonce,
            algorithm,
            _private: PhantomData,
        }
    }

    /// Borrow the issuer DID.
    #[must_use]
    pub fn issuer(&self) -> &Did {
        &self.issuer
    }

    /// Borrow the audience service identity.
    #[must_use]
    pub fn audience(&self) -> &ServiceIdentity {
        &self.audience
    }

    /// `SystemTime` the JWT was issued.
    #[must_use]
    pub fn issued_at(&self) -> SystemTime {
        self.issued_at
    }

    /// `SystemTime` the JWT expires.
    #[must_use]
    pub fn expires_at(&self) -> SystemTime {
        self.expires_at
    }

    /// Borrow the JWT scope (§7.2).
    #[must_use]
    pub fn scope(&self) -> &JwtScope {
        &self.scope
    }

    /// Borrow the optional nonce.
    #[must_use]
    pub fn nonce(&self) -> Option<&JwtNonce> {
        self.nonce.as_ref()
    }

    /// Return the verification algorithm.
    #[must_use]
    pub fn algorithm(&self) -> SignatureAlgorithm {
        self.algorithm
    }
}

/// JWT verification configuration (§7.2).
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct JwtVerificationConfig {
    /// Maximum clock skew tolerated between issuer and verifier.
    /// Recommended: 30 seconds.
    pub max_clock_skew: Duration,
    /// Maximum permitted validity window. Recommended: 1 hour.
    pub max_validity_window: Duration,
    /// If `true`, JWTs without a nonce fail. Recommended: `false`
    /// for stateless reads, `true` for state-changing operations.
    pub require_nonce: bool,
    /// Algorithm allowlist. Recommended default:
    /// `&[SignatureAlgorithm::Ed25519]`.
    pub accepted_algorithms: &'static [SignatureAlgorithm],
}

impl Default for JwtVerificationConfig {
    fn default() -> Self {
        JwtVerificationConfig {
            max_clock_skew: Duration::from_secs(30),
            max_validity_window: Duration::from_secs(3600),
            require_nonce: false,
            accepted_algorithms: &[SignatureAlgorithm::Ed25519],
        }
    }
}

/// JWT scope vector (§7.2).
///
/// Operator-defined scope strings (typically NSID-shaped:
/// `com.atproto.repo.createRecord`). The substrate validates that
/// the requested operation falls within the scope at **capability
/// issuance time** (§4.3), not at ingress.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct JwtScope {
    /// Scope strings.
    pub scopes: SmallVec<[String; 4]>,
}

/// JWT verification failure (§7.2).
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum JwtVerificationError {
    /// Token was structurally malformed.
    #[error("JWT malformed")]
    Malformed,
    /// Algorithm not in the allowlist.
    #[error("JWT algorithm not supported: {0:?}")]
    UnsupportedAlgorithm(SignatureAlgorithm),
    /// Signature did not verify.
    #[error("JWT signature invalid")]
    SignatureInvalid,
    /// JWT was expired.
    #[error("JWT expired (exp={exp:?}, now={now:?})")]
    Expired {
        /// `exp` claim from the JWT.
        exp: SystemTime,
        /// Current time at verification.
        now: SystemTime,
    },
    /// JWT is not yet valid.
    #[error("JWT not yet valid")]
    NotYetValid {
        /// `nbf` claim from the JWT.
        nbf: SystemTime,
        /// Current time at verification.
        now: SystemTime,
        /// Clock skew tolerated.
        skew: Duration,
    },
    /// Audience mismatch.
    #[error("JWT wrong audience")]
    WrongAudience {
        /// Expected (local) audience.
        expected: ServiceIdentity,
        /// Audience claimed by JWT.
        got: ServiceIdentity,
    },
    /// Issuer DID failed to resolve.
    #[error("JWT issuer resolution failed: {0}")]
    IssuerResolutionFailed(DidResolutionError),
    /// Issuer's signing key not in DID document.
    #[error("issuer key not in DID document")]
    IssuerKeyNotInDocument,
    /// Validity window too long.
    #[error("validity window too long")]
    ValidityWindowTooLong {
        /// Requested validity window.
        window: Duration,
        /// Maximum permitted.
        max: Duration,
    },
    /// Nonce required but missing.
    #[error("nonce missing")]
    NonceMissing,
    /// Nonce was a replay.
    #[error("nonce replay")]
    NonceReplay,
}

/// Verify a raw JWT against the configured DID resolver (§7.2).
///
/// `raw` may be either the bare JWT (`header.payload.signature`)
/// or a full HTTP `Authorization` header value (`Bearer <jwt>`);
/// the function strips the `Bearer ` prefix when present.
///
/// The verification chain runs all five §7.2 stages in order:
///
/// 1. Authorization-header parsing + JWT structural parse.
/// 2. Algorithm allowlist check (default: `[Ed25519]`).
/// 3. Issuer DID resolution to obtain the signing key.
/// 4. Signature verification.
/// 5. Claims verification (iss / aud / exp / iat / nbf / nonce /
///    validity-window / scope extraction).
///
/// On success returns [`VerifiedJwt`] — an unforgeable token; the
/// crate's `ingress` paths accept it as evidence that JWT
/// verification ran without trusting the caller.
///
/// Replay protection (the [`crate::wire::NonceTracker`] check) is
/// **not** invoked inside `verify_jwt`; nonce extraction succeeds,
/// replay rejection is opt-in via a separately-supplied tracker.
///
/// Audit-emit is the caller's responsibility — the `authority`
/// module emits
/// [`crate::audit::UserAuditEvent::CapabilityIssuanceDenied`] at
/// the ingress chokepoint with
/// [`crate::authority::DenialReason::JwtVerificationFailed`]
/// carrying the returned error.
///
/// # Errors
///
/// Returns [`JwtVerificationError`] on any failure. Each variant
/// is reachable independently from the verification chain; see
/// the per-variant doc for the failure path.
pub async fn verify_jwt(
    raw: &str,
    local_audience: &ServiceIdentity,
    resolver: &dyn DidResolver,
    config: &JwtVerificationConfig,
    deadline: Instant,
    trace_id: TraceId,
) -> Result<VerifiedJwt, JwtVerificationError> {
    // 1. Strip `Bearer ` prefix if present and structurally parse
    //    the three base64url segments.
    let token = parse_authorization_header(raw)?;
    let parsed = ParsedJwt::parse(token)?;

    // 2. Allowlist enforcement. The `alg: "none"` case is rejected
    //    inside `ParsedJwt::parse` as `Malformed` so the allowlist
    //    branch is never reached for that attack class (§7.2's
    //    alg-confusion discipline: the `none` rejection is part of
    //    the parser, not the allowlist).
    if !config.accepted_algorithms.contains(&parsed.algorithm) {
        return Err(JwtVerificationError::UnsupportedAlgorithm(parsed.algorithm));
    }

    // 3. Resolve the issuer DID to obtain a signing key. The
    //    issuer DID comes from the JWT payload (`iss` claim). The
    //    JWT header's optional `kid` selects which verification
    //    method from the resolved DID document; absent `kid` means
    //    "any verification method is acceptable" — try them in
    //    document order.
    let issuer = parsed.payload_iss()?;
    let document = resolver
        .resolve(&issuer, deadline, trace_id)
        .await
        .map_err(JwtVerificationError::IssuerResolutionFailed)?;
    let public_key = select_signing_key(&document, parsed.kid_hint(), parsed.algorithm)?;

    // 4. Signature verification. Dispatch by algorithm.
    verify_signature(parsed.signing_input(), &parsed.signature, parsed.algorithm, &public_key)?;

    // 5. Claims verification. Constructs the `VerifiedJwt` on
    //    success.
    let now = SystemTime::now();
    parsed.verify_claims_and_construct(local_audience, config, issuer, now)
}

// ============================================================
// §7.2 — Authorization header + raw JWT parsing.
// ============================================================

/// Strip an optional `Bearer ` (case-insensitive scheme,
/// case-sensitive token) prefix per RFC 7235.
fn parse_authorization_header(raw: &str) -> Result<&str, JwtVerificationError> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err(JwtVerificationError::Malformed);
    }
    if let Some(rest) = trimmed
        .strip_prefix("Bearer ")
        .or_else(|| trimmed.strip_prefix("bearer "))
        .or_else(|| trimmed.strip_prefix("BEARER "))
    {
        let token = rest.trim_start();
        if token.is_empty() {
            return Err(JwtVerificationError::Malformed);
        }
        return Ok(token);
    }
    // No `Bearer ` prefix — treat the input as a bare JWT. This
    // accommodates callers that have already stripped the prefix
    // upstream.
    Ok(trimmed)
}

/// Decoded JWT segments + the original signing input (the
/// `<header>.<payload>` substring needed for signature
/// verification).
struct ParsedJwt<'a> {
    /// Parsed header JSON.
    header: serde_json::Value,
    /// Parsed payload JSON.
    payload: serde_json::Value,
    /// Decoded signature bytes.
    signature: Vec<u8>,
    /// `<header>.<payload>` substring (the signing input over
    /// which the signature is computed).
    signing_input_str: &'a str,
    /// Algorithm extracted from the header and validated against
    /// the JWT-spec algorithm name.
    algorithm: SignatureAlgorithm,
}

impl<'a> ParsedJwt<'a> {
    fn parse(token: &'a str) -> Result<Self, JwtVerificationError> {
        // A JWT has exactly two `.` separators. `splitn(3, '.')` to
        // tolerate a trailing-dot signature edge case is wrong —
        // RFC 7519 §3 commits exactly three segments separated by
        // exactly two dots.
        let mut iter = token.split('.');
        let header_b64 = iter.next().ok_or(JwtVerificationError::Malformed)?;
        let payload_b64 = iter.next().ok_or(JwtVerificationError::Malformed)?;
        let signature_b64 = iter.next().ok_or(JwtVerificationError::Malformed)?;
        if iter.next().is_some() {
            return Err(JwtVerificationError::Malformed);
        }
        if header_b64.is_empty() || payload_b64.is_empty() || signature_b64.is_empty() {
            return Err(JwtVerificationError::Malformed);
        }

        // The signing input is the concatenation of header_b64 and
        // payload_b64 with the dot retained between them (RFC 7515
        // §5.1). We need the original string, not a re-built one,
        // so signature input bytes match exactly what the issuer
        // signed.
        let signing_input_len = header_b64.len() + 1 + payload_b64.len();
        let signing_input_str = &token[..signing_input_len];

        let header_bytes = URL_SAFE_NO_PAD
            .decode(header_b64)
            .map_err(|_| JwtVerificationError::Malformed)?;
        let payload_bytes = URL_SAFE_NO_PAD
            .decode(payload_b64)
            .map_err(|_| JwtVerificationError::Malformed)?;
        let signature = URL_SAFE_NO_PAD
            .decode(signature_b64)
            .map_err(|_| JwtVerificationError::Malformed)?;

        let header: serde_json::Value = serde_json::from_slice(&header_bytes)
            .map_err(|_| JwtVerificationError::Malformed)?;
        let payload: serde_json::Value = serde_json::from_slice(&payload_bytes)
            .map_err(|_| JwtVerificationError::Malformed)?;

        let algorithm = parse_alg_header(&header)?;

        Ok(ParsedJwt {
            header,
            payload,
            signature,
            signing_input_str,
            algorithm,
        })
    }

    fn signing_input(&self) -> &[u8] {
        self.signing_input_str.as_bytes()
    }

    fn kid_hint(&self) -> Option<&str> {
        self.header.get("kid")?.as_str()
    }

    fn payload_iss(&self) -> Result<Did, JwtVerificationError> {
        let iss = self
            .payload
            .get("iss")
            .and_then(serde_json::Value::as_str)
            .ok_or(JwtVerificationError::Malformed)?;
        Did::new(iss).map_err(|_| JwtVerificationError::Malformed)
    }

    fn verify_claims_and_construct(
        self,
        local_audience: &ServiceIdentity,
        config: &JwtVerificationConfig,
        issuer: Did,
        now: SystemTime,
    ) -> Result<VerifiedJwt, JwtVerificationError> {
        let p = &self.payload;

        // `aud`. JWT standard allows a string or array; ATProto
        // convention uses a single string DID. v1 accepts only the
        // string form — array support is a future-extension
        // for the broader-ATProto-compatibility roll-out.
        let aud_str = p
            .get("aud")
            .and_then(serde_json::Value::as_str)
            .ok_or(JwtVerificationError::Malformed)?;
        let aud_did = Did::new(aud_str).map_err(|_| JwtVerificationError::Malformed)?;
        if aud_did != *local_audience.service_did() {
            // Construct a placeholder `ServiceIdentity` for the
            // `got` field — the JWT `aud` claim is a DID string,
            // not a ServiceIdentity, so we synthesize one with
            // zero key material to fit the §7.2 error variant
            // shape. See note for the shape-vs-reality
            // mismatch.
            let got_placeholder = ServiceIdentity::new_internal(
                aud_did,
                KeyId::from_bytes([0u8; 32]),
                PublicKey {
                    algorithm: SignatureAlgorithm::Ed25519,
                    bytes: [0u8; 32],
                },
                None,
            );
            return Err(JwtVerificationError::WrongAudience {
                expected: local_audience.clone(),
                got: got_placeholder,
            });
        }

        // `iat` (required per §7.2 / kickoff §5).
        let iat_secs = p
            .get("iat")
            .and_then(serde_json::Value::as_u64)
            .ok_or(JwtVerificationError::Malformed)?;
        let iat = SystemTime::UNIX_EPOCH + Duration::from_secs(iat_secs);

        // `exp` (required).
        let exp_secs = p
            .get("exp")
            .and_then(serde_json::Value::as_u64)
            .ok_or(JwtVerificationError::Malformed)?;
        let exp = SystemTime::UNIX_EPOCH + Duration::from_secs(exp_secs);

        // `nbf` (optional).
        let nbf = p
            .get("nbf")
            .and_then(serde_json::Value::as_u64)
            .map(|s| SystemTime::UNIX_EPOCH + Duration::from_secs(s));

        // Validity window: exp − iat ≤ max_validity_window. The
        // check uses unsigned-saturating subtraction since `iat`
        // greater than `exp` is itself an error caught by the
        // expiry check below.
        let window = exp.duration_since(iat).unwrap_or(Duration::ZERO);
        if window > config.max_validity_window {
            return Err(JwtVerificationError::ValidityWindowTooLong {
                window,
                max: config.max_validity_window,
            });
        }

        // Expiry. `exp` must be in the future (or within
        // `max_clock_skew` of now). Equivalent: now ≤ exp + skew.
        if now > exp + config.max_clock_skew {
            return Err(JwtVerificationError::Expired { exp, now });
        }

        // `nbf`: if present, must be in the past (within skew).
        if let Some(nbf_t) = nbf {
            if now + config.max_clock_skew < nbf_t {
                return Err(JwtVerificationError::NotYetValid {
                    nbf: nbf_t,
                    now,
                    skew: config.max_clock_skew,
                });
            }
        }

        // `iat`: must be in the past (within skew). A future-dated
        // `iat` reuses the `NotYetValid` variant since it indicates
        // the same operator-debug condition (issuer's clock ahead
        // of verifier's).
        if now + config.max_clock_skew < iat {
            return Err(JwtVerificationError::NotYetValid {
                nbf: iat,
                now,
                skew: config.max_clock_skew,
            });
        }

        // Scope extraction. ATProto convention varies between
        // `scope` and `scp` field names and between space-delimited
        // string and JSON array values. Accept both names and both
        // formats per the kickoff guidance.
        let scope = parse_scope_field(p);

        // Nonce extraction. v1 expects the nonce as a base64url-
        // encoded 16-byte value. If `require_nonce` is true and
        // missing, fail. Replay rejection is opt-in via a separate
        // `NonceTracker` integration.
        let nonce = parse_nonce_field(p, config.require_nonce)?;

        Ok(VerifiedJwt::new_internal(
            issuer,
            local_audience.clone(),
            iat,
            exp,
            scope,
            nonce,
            self.algorithm,
        ))
    }
}

/// Map a JWT `alg` header value to a [`SignatureAlgorithm`].
///
/// Returns [`JwtVerificationError::Malformed`] for missing /
/// non-string `alg` and for the literal `"none"` (per §7.2's
/// alg-confusion discipline: `none` rejection is a parser
/// concern, not an allowlist concern, so the audit channel sees
/// `Malformed` rather than the misleading
/// `UnsupportedAlgorithm(SignatureAlgorithm::Ed25519)`).
fn parse_alg_header(
    header: &serde_json::Value,
) -> Result<SignatureAlgorithm, JwtVerificationError> {
    let alg = header
        .get("alg")
        .and_then(serde_json::Value::as_str)
        .ok_or(JwtVerificationError::Malformed)?;
    if alg.eq_ignore_ascii_case("none") {
        return Err(JwtVerificationError::Malformed);
    }
    match alg {
        "EdDSA" => Ok(SignatureAlgorithm::Ed25519),
        "ES256" => Ok(SignatureAlgorithm::Es256),
        "ES256K" => Ok(SignatureAlgorithm::Es256K),
        // Unknown algorithm names are treated as malformed: the
        // JWT header `alg` field is a registered IANA value space
        // and unknowns indicate either a misformatted JWT or an
        // attempted alg-confusion attack. Either way the audit
        // signal is "this token is not parseable" rather than
        // "this algorithm is not configured."
        _ => Err(JwtVerificationError::Malformed),
    }
}

// ============================================================
// §7.2 — Signing-key resolution and signature verification.
// ============================================================

/// Pick a [`PublicKey`] from a resolved DID document for
/// signature verification.
///
/// If the JWT header carried a `kid`, look for a verification
/// method whose [`KeyId`] matches the hint. Without `kid`, return
/// the first verification method whose algorithm matches the JWT.
/// Failing to find a match returns
/// [`JwtVerificationError::IssuerKeyNotInDocument`].
///
/// `kid` matching is anchored: byte-equality on the lowercase hex
/// rendering of the [`KeyId`], OR an exact match against the
/// `#`-delimited fragment of a DID URL (`did:plc:...#<keyid>`).
/// The `#` delimiter is the anchor — a bare suffix match is
/// rejected so two keys whose hex IDs share a tail cannot
/// collide when the shorter id is the hint.
fn select_signing_key(
    document: &crate::resolver::DidDocument,
    kid_hint: Option<&str>,
    algorithm: SignatureAlgorithm,
) -> Result<PublicKey, JwtVerificationError> {
    let methods = &document.verification_methods;
    if methods.is_empty() {
        return Err(JwtVerificationError::IssuerKeyNotInDocument);
    }

    if let Some(hint) = kid_hint {
        for (kid, key) in methods {
            let kid_hex = kid_to_hex(kid);
            if kid_matches(hint, &kid_hex) {
                if key.algorithm == algorithm {
                    return Ok(*key);
                }
                return Err(JwtVerificationError::IssuerKeyNotInDocument);
            }
        }
        // Hint provided but didn't match anything.
        return Err(JwtVerificationError::IssuerKeyNotInDocument);
    }

    // No hint — first matching algorithm wins.
    for (_kid, key) in methods {
        if key.algorithm == algorithm {
            return Ok(*key);
        }
    }
    Err(JwtVerificationError::IssuerKeyNotInDocument)
}

/// Anchored `kid`-hint match.
///
/// Returns true iff `hint` is byte-equal to `hex_id` (the
/// lowercase hex rendering of a [`KeyId`]) OR `hint` is a DID URL
/// whose `#`-delimited fragment equals `hex_id`. Bare suffix
/// matches (e.g. `"prefixdeadbeef"` against `"deadbeef"`) are
/// rejected — the `#` anchor eliminates the collision surface a
/// raw `ends_with` would carry between distinct keys sharing a
/// hex-id tail.
fn kid_matches(hint: &str, hex_id: &str) -> bool {
    if hint == hex_id {
        return true;
    }
    if let Some((_, fragment)) = hint.rsplit_once('#') {
        return fragment == hex_id;
    }
    false
}

fn kid_to_hex(kid: &KeyId) -> String {
    let mut s = String::with_capacity(64);
    for b in kid.as_bytes() {
        s.push_str(&format!("{b:02x}"));
    }
    s
}

/// Verify a JWT signature for the given algorithm.
///
/// Ed25519 is fully implemented in v0.1. ES256 / ES256K stub
/// with `UnsupportedAlgorithm` until a future release commits
/// the `p256` / `k256` crate dependencies; tracked alongside
/// work.
fn verify_signature(
    signing_input: &[u8],
    signature: &[u8],
    algorithm: SignatureAlgorithm,
    public_key: &PublicKey,
) -> Result<(), JwtVerificationError> {
    match algorithm {
        SignatureAlgorithm::Ed25519 => {
            if signature.len() != ed25519_dalek::SIGNATURE_LENGTH {
                return Err(JwtVerificationError::SignatureInvalid);
            }
            let mut sig_bytes = [0u8; ed25519_dalek::SIGNATURE_LENGTH];
            sig_bytes.copy_from_slice(signature);
            let sig = Ed25519Signature::from_bytes(&sig_bytes);
            let key = VerifyingKey::from_bytes(&public_key.bytes)
                .map_err(|_| JwtVerificationError::SignatureInvalid)?;
            key.verify(signing_input, &sig)
                .map_err(|_| JwtVerificationError::SignatureInvalid)
        }
        SignatureAlgorithm::Es256 | SignatureAlgorithm::Es256K => {
            // v0.1 recognizes the variants but does not ship the
            // `p256` / `k256` crate dependencies. Operators
            // configuring these in `accepted_algorithms` will see
            // this error; ECDSA support is a v0.2+ feature gate.
            Err(JwtVerificationError::UnsupportedAlgorithm(algorithm))
        }
    }
}

// ============================================================
// §7.2 — Scope and nonce extraction.
// ============================================================

/// Parse the JWT scope claim. Accepts either `scope` or `scp` as
/// the field name and either a space-delimited string or a JSON
/// array of strings as the value. Missing or unrecognized shapes
/// yield an empty [`JwtScope`] — which §7.2's empty-is-fail-closed
/// rule treats as authorizing no operations.
fn parse_scope_field(payload: &serde_json::Value) -> JwtScope {
    let raw = payload.get("scope").or_else(|| payload.get("scp"));
    let mut scopes: SmallVec<[String; 4]> = SmallVec::new();
    if let Some(value) = raw {
        if let Some(s) = value.as_str() {
            for token in s.split_ascii_whitespace() {
                if !token.is_empty() {
                    scopes.push(token.to_string());
                }
            }
        } else if let Some(arr) = value.as_array() {
            for item in arr {
                if let Some(s) = item.as_str() {
                    if !s.is_empty() {
                        scopes.push(s.to_string());
                    }
                }
            }
        }
    }
    JwtScope { scopes }
}

/// Parse the optional JWT nonce claim. v1 accepts a base64url-
/// encoded 16-byte value. Missing nonce with `require_nonce: true`
/// fails with [`JwtVerificationError::NonceMissing`]; missing with
/// `require_nonce: false` returns `Ok(None)`.
///
/// Replay rejection is opt-in via a separately-supplied
/// [`crate::wire::NonceTracker`]; `verify_jwt` only extracts
/// the nonce.
fn parse_nonce_field(
    payload: &serde_json::Value,
    require_nonce: bool,
) -> Result<Option<JwtNonce>, JwtVerificationError> {
    let nonce_str = payload.get("nonce").and_then(serde_json::Value::as_str);
    match (nonce_str, require_nonce) {
        (None, true) => Err(JwtVerificationError::NonceMissing),
        (None, false) => Ok(None),
        (Some(s), _) => {
            let bytes = URL_SAFE_NO_PAD
                .decode(s)
                .map_err(|_| JwtVerificationError::Malformed)?;
            if bytes.len() != 16 {
                return Err(JwtVerificationError::Malformed);
            }
            let mut arr = [0u8; 16];
            arr.copy_from_slice(&bytes);
            Ok(Some(JwtNonce::from_bytes(arr)))
        }
    }
}

// ============================================================
// §7.6 capability-claim verification.
// ============================================================

/// Capability claim that has passed wire-canonicality, signature,
/// and claim verification (§7.6).
///
/// Constructible only via [`verify_capability_claim`]; consumers
/// receiving a [`VerifiedCapabilityClaim`] need not re-verify or
/// trust the caller.
///
/// Outside-crate code cannot construct via struct-literal syntax
/// — every field is private, including the crate-sealed
/// `_private: PhantomData<sealed::Token>` marker.
///
/// ```compile_fail
/// // Outside-crate construction must not work.
/// use kryphocron::verification::VerifiedCapabilityClaim;
/// let _v = VerifiedCapabilityClaim {
///     // fields private; this fails to compile.
/// };
/// ```
#[derive(Debug, Clone)]
pub struct VerifiedCapabilityClaim {
    issuer: ServiceIdentity,
    subject: Did,
    capabilities: Vec<CapabilityKind>,
    resource_scope: ResourceScope,
    trace_id: TraceId,
    issued_at: SystemTime,
    expires_at: SystemTime,
    /// Verified upstream attribution chain. `None` for
    /// [`crate::wire::ClaimOrigin::SelfOriginated`]; `Some(chain)`
    /// for `DelegatedFromUpstream`. The chain has been
    /// signature- and monotonicity-verified by
    /// [`verify_attribution_chain`].
    chain: Option<crate::AttributionChain>,
    _private: PhantomData<sealed::Token>,
}

impl VerifiedCapabilityClaim {
    /// Crate-internal constructor. Reserved for
    /// [`verify_capability_claim`] after every §7.6 verification
    /// stage has succeeded; not reachable from outside
    /// `crate::verification`.
    #[must_use]
    pub(crate) fn new_internal(
        issuer: ServiceIdentity,
        subject: Did,
        capabilities: Vec<CapabilityKind>,
        resource_scope: ResourceScope,
        trace_id: TraceId,
        issued_at: SystemTime,
        expires_at: SystemTime,
        chain: Option<crate::AttributionChain>,
    ) -> Self {
        VerifiedCapabilityClaim {
            issuer,
            subject,
            capabilities,
            resource_scope,
            trace_id,
            issued_at,
            expires_at,
            chain,
            _private: PhantomData,
        }
    }

    /// Borrow the issuer service identity.
    #[must_use]
    pub fn issuer(&self) -> &ServiceIdentity {
        &self.issuer
    }
    /// Borrow the subject DID.
    #[must_use]
    pub fn subject(&self) -> &Did {
        &self.subject
    }
    /// Borrow the requested capabilities.
    #[must_use]
    pub fn capabilities(&self) -> &[CapabilityKind] {
        &self.capabilities
    }
    /// Borrow the resource scope.
    #[must_use]
    pub fn resource_scope(&self) -> &ResourceScope {
        &self.resource_scope
    }
    /// Forensic trace id.
    #[must_use]
    pub fn trace_id(&self) -> TraceId {
        self.trace_id
    }
    /// Issued-at instant.
    #[must_use]
    pub fn issued_at(&self) -> SystemTime {
        self.issued_at
    }
    /// Expires-at instant.
    #[must_use]
    pub fn expires_at(&self) -> SystemTime {
        self.expires_at
    }
    /// Borrow the verified upstream attribution chain. Returns
    /// `None` for `SelfOriginated` claims; `Some(chain)` for
    /// `DelegatedFromUpstream` claims whose chain passed
    /// [`verify_attribution_chain`].
    #[must_use]
    pub fn chain(&self) -> Option<&crate::AttributionChain> {
        self.chain.as_ref()
    }
}

/// Sync-channel message that has passed handshake-aware
/// verification (§7.5 + §7.6).
///
/// The crate-internal constructor is reachable only via the
/// sync-handshake wiring; `VerifiedSyncMessage` is constructed
/// downstream of a verified sync handshake.
#[derive(Debug, Clone)]
pub struct VerifiedSyncMessage {
    session_identity: ServiceIdentity,
    session_id: SessionId,
    payload: VerifiedCapabilityClaim,
    _private: PhantomData<sealed::Token>,
}

impl VerifiedSyncMessage {
    /// Borrow the session-bound peer identity.
    #[must_use]
    pub fn session_identity(&self) -> &ServiceIdentity {
        &self.session_identity
    }
    /// Return the session id from the originating handshake.
    #[must_use]
    pub fn session_id(&self) -> SessionId {
        self.session_id
    }
    /// Borrow the inner verified capability claim.
    #[must_use]
    pub fn payload(&self) -> &VerifiedCapabilityClaim {
        &self.payload
    }
}

/// Capability-claim verification configuration (§7.6).
///
/// Parallel to [`JwtVerificationConfig`]; sets the same defaults
/// where the two contexts share semantics
/// (`max_clock_skew = 30s`, `accepted_algorithms = [Ed25519]`)
/// plus a 600s `max_validity_window` matching
/// [`crate::MAX_CLAIM_VALIDITY`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ClaimVerificationConfig {
    /// Maximum clock skew tolerated between issuer and verifier.
    pub max_clock_skew: Duration,
    /// Maximum permitted validity window (≤ 600s per §4.8).
    pub max_validity_window: Duration,
    /// Algorithm allowlist; default `[Ed25519]` per §7.2.
    pub accepted_algorithms: &'static [SignatureAlgorithm],
}

impl Default for ClaimVerificationConfig {
    fn default() -> Self {
        ClaimVerificationConfig {
            max_clock_skew: Duration::from_secs(30),
            max_validity_window: Duration::from_secs(600),
            accepted_algorithms: &[SignatureAlgorithm::Ed25519],
        }
    }
}

/// Capability-claim verification failure (§7.6).
///
/// Parallel structure to [`JwtVerificationError`]; the two enums
/// are intentionally separate because the failure modes differ
/// (CBOR canonicality, capability-class wire-eligibility,
/// nonce-tracker backend errors).
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum ClaimVerificationError {
    /// Wire envelope is structurally malformed: bad scheme prefix,
    /// base64url decode failure, CBOR decode failure, non-canonical
    /// CBOR encoding (the §7 round-4 hazard), missing field, type
    /// mismatch, or unrecognized capability/algorithm name.
    #[error("claim malformed")]
    Malformed,
    /// Algorithm not in the allowlist.
    #[error("claim algorithm not supported: {0:?}")]
    UnsupportedAlgorithm(SignatureAlgorithm),
    /// Signature did not verify against the issuer's signing key.
    #[error("claim signature invalid")]
    SignatureInvalid,
    /// Claim has expired.
    #[error("claim expired (exp={exp:?}, now={now:?})")]
    Expired {
        /// `expires_at` from the claim.
        exp: SystemTime,
        /// Current time at verification.
        now: SystemTime,
    },
    /// Claim is not yet valid (`issued_at` in the future beyond
    /// skew tolerance).
    #[error("claim not yet valid")]
    NotYetValid {
        /// `issued_at` from the claim.
        iat: SystemTime,
        /// Current time at verification.
        now: SystemTime,
        /// Clock skew tolerated.
        skew: Duration,
    },
    /// Audience mismatch. The `got` field carries the
    /// claimed-audience DID directly (no synthetic
    /// `ServiceIdentity` placeholder).
    #[error("claim wrong audience")]
    WrongAudience {
        /// Expected (local) audience.
        expected: ServiceIdentity,
        /// Audience claimed by the wire envelope.
        got: Did,
    },
    /// Issuer DID failed to resolve.
    #[error("claim issuer resolution failed: {0}")]
    IssuerResolutionFailed(DidResolutionError),
    /// Issuer's signing key not in DID document or rotation
    /// history.
    #[error("issuer key not in DID document")]
    IssuerKeyNotInDocument,
    /// `expires_at - issued_at` exceeds the configured maximum.
    #[error("validity window too long")]
    ValidityWindowTooLong {
        /// Requested validity window.
        window: Duration,
        /// Maximum permitted.
        max: Duration,
    },
    /// Wire envelope exceeds [`MAX_CAPABILITY_CLAIM_SIZE`].
    #[error("claim size {size} exceeds max {max}")]
    ClaimTooLarge {
        /// Wire envelope size.
        size: usize,
        /// Maximum permitted.
        max: usize,
    },
    /// Nonce previously observed under the same issuer partition
    /// within the tracker's retention window.
    #[error("claim nonce replay")]
    NonceReplay,
    /// Nonce tracker backend failure.
    #[error("nonce tracker failure: {0}")]
    NonceTrackerFailed(NonceTrackerError),
    /// §4.8 W6 violation observed at receive time: claim
    /// references a substrate-class or moderation-class
    /// capability that should never appear on the wire. The
    /// substrate's own claims fail at construction, but external
    /// claims must be re-checked because they may have been
    /// minted by a non-substrate or malicious party.
    #[error("non-wire-eligible capability {0:?} on the wire")]
    NonWireEligibleCapability(CapabilityKind),
    /// §4.8 W9 / W10 violation observed at receive time: claim's
    /// scope is not permitted for one of its declared
    /// capabilities. Belt-and-suspenders to construction-time
    /// checks.
    #[error("scope variant not permitted for class")]
    NonexhaustiveScopeForClass,
    /// §4.8 W11 / W12 / W13: claim is `DelegatedFromUpstream`
    /// but the wire chain failed receipt-verification. Carries
    /// the per-hop failure detail produced by
    /// [`verify_attribution_chain`].
    #[error("attribution chain invalid")]
    AttributionChainInvalid(BindError),
    /// §4.8 W13: claim's `capabilities` exceeds the
    /// last chain hop's `granted_capabilities`. The chain itself
    /// passed receipt verification (every hop's signature valid
    /// and inter-hop monotonicity held); the final claim attempted
    /// to grant beyond what the last hop's principal was
    /// authorized for.
    #[error("claim capabilities exceed last chain hop's granted set")]
    ClaimExceedsChainTail,
}

/// Verify a capability-claim wire envelope against the configured
/// DID resolver and nonce tracker (§7.6).
///
/// `raw_header` may be either the bare base64url-encoded wire
/// envelope or a full HTTP `Authorization` header value
/// (`KryphocronClaim <base64url>`); the function strips the scheme
/// prefix when present.
///
/// The verification chain runs all §7.6 receive-time enforcement
/// stages in order:
///
/// 1. Authorization-header scheme + base64url decode.
/// 2. Wire-bytes size ceiling ([`MAX_CAPABILITY_CLAIM_SIZE`]).
/// 3. Round-trip canonicality (re-encoded bytes byte-equal input;
///    closes the §7 round-4 hazard).
/// 4. CBOR structural decode into payload + signature.
/// 5. Algorithm allowlist check.
/// 6. Audience equality against `local_audience.service_did()`.
/// 7. W6 / W9 / W10 belt-and-suspenders against externally-minted
///    claims (substrate's own claims fail at construction).
/// 8. Validity window ≤ `config.max_validity_window`.
/// 9. `expires_at` future (within skew); `issued_at` past (within
///    skew).
/// 10. Issuer DID resolution + signing-key selection.
/// 11. Domain-separated Ed25519 signature verification over the
///     re-encoded canonical payload.
/// 12. Nonce-tracker check-and-record under the
///     `(NonceKind::CapabilityClaim, NonceIssuerKey)` partition.
/// 13. Construct [`VerifiedCapabilityClaim`] via the
///     crate-internal constructor.
///
/// On success returns [`VerifiedCapabilityClaim`] — an unforgeable
/// token that ingress paths accept as evidence that §7.6
/// verification ran without trusting the caller.
///
/// Both `ClaimOrigin::SelfOriginated` and
/// `ClaimOrigin::DelegatedFromUpstream` payloads are supported;
/// the delegated path walks the receipt chain (W11/W12/W13)
/// before returning success.
///
/// # Errors
///
/// Returns [`ClaimVerificationError`] on any failure.
pub async fn verify_capability_claim(
    raw_header: &str,
    local_audience: &ServiceIdentity,
    resolver: &dyn DidResolver,
    nonce_tracker: &dyn NonceTracker,
    config: &ClaimVerificationConfig,
    deadline: Instant,
    trace_id: TraceId,
    origin_authorized_capabilities: &CapabilitySet,
) -> Result<VerifiedCapabilityClaim, ClaimVerificationError> {
    // 1. Strip `KryphocronClaim ` prefix (case-insensitive scheme)
    //    and base64url-decode.
    let token = parse_claim_header(raw_header)?;
    let wire_bytes = URL_SAFE_NO_PAD
        .decode(token)
        .map_err(|_| ClaimVerificationError::Malformed)?;

    // 2. Wire-bytes size ceiling.
    if wire_bytes.len() > MAX_CAPABILITY_CLAIM_SIZE {
        return Err(ClaimVerificationError::ClaimTooLarge {
            size: wire_bytes.len(),
            max: MAX_CAPABILITY_CLAIM_SIZE,
        });
    }

    // 3. Round-trip canonicality. Reject non-canonical encodings
    //    as Malformed — closes the §7 round-4 hazard at the
    //    boundary.
    if !wire_envelope_is_canonical(&wire_bytes) {
        return Err(ClaimVerificationError::Malformed);
    }

    // 4. Decode the wire envelope.
    let (
        issuer,
        audience,
        subject,
        origin,
        capabilities,
        resource_scope,
        nonce,
        trace_id_field,
        issued_at,
        expires_at,
        signature,
    ) = decode_wire_envelope(&wire_bytes).map_err(|()| ClaimVerificationError::Malformed)?;

    // 5. Algorithm allowlist.
    if !config.accepted_algorithms.contains(&signature.algorithm) {
        return Err(ClaimVerificationError::UnsupportedAlgorithm(signature.algorithm));
    }

    // 6. Audience equality. The `got` field carries the claimed
    //    DID directly (not a synthetic placeholder ServiceIdentity).
    if audience.service_did() != local_audience.service_did() {
        return Err(ClaimVerificationError::WrongAudience {
            expected: local_audience.clone(),
            got: audience.service_did().clone(),
        });
    }

    // 7. W6 / W9 / W10 belt-and-suspenders. The substrate's own
    //    claims pass these checks at construction; external claims
    //    must be re-checked.
    for cap in &capabilities {
        if !cap.is_wire_eligible() {
            return Err(ClaimVerificationError::NonWireEligibleCapability(*cap));
        }
        if !class_permits_scope(cap.class(), &resource_scope) {
            return Err(ClaimVerificationError::NonexhaustiveScopeForClass);
        }
    }

    // 8. Validity window.
    let window = expires_at
        .duration_since(issued_at)
        .unwrap_or(Duration::ZERO);
    if window > config.max_validity_window {
        return Err(ClaimVerificationError::ValidityWindowTooLong {
            window,
            max: config.max_validity_window,
        });
    }

    // 9. Expiry / not-yet-valid (clock-skew tolerant).
    let now = SystemTime::now();
    if now > expires_at + config.max_clock_skew {
        return Err(ClaimVerificationError::Expired {
            exp: expires_at,
            now,
        });
    }
    if now + config.max_clock_skew < issued_at {
        return Err(ClaimVerificationError::NotYetValid {
            iat: issued_at,
            now,
            skew: config.max_clock_skew,
        });
    }

    // 10. Issuer DID resolution + signing-key selection. The
    //     verifier's request `trace_id` (not the claim's
    //     `trace_id_field`) is what attributes any rotation /
    //     invalidation audit emitted as a side-effect of this
    //     resolution: rotations detected during this verification
    //     are events of the verifier's request, not of the original
    //     issuer-side context.
    let document = resolver
        .resolve(issuer.service_did(), deadline, trace_id)
        .await
        .map_err(ClaimVerificationError::IssuerResolutionFailed)?;
    let public_key = select_signing_key_for_claim(
        &document,
        issuer.key_id(),
        signature.algorithm,
    )?;

    // 11. Re-encode the canonical payload (no signature field) and
    //     verify the signature with domain separation.
    //     SelfOriginated and DelegatedFromUpstream payloads both
    //     round-trip here.
    let received_claim = CapabilityClaim::new_internal_received(
        issuer.clone(),
        audience,
        subject.clone(),
        origin,
        capabilities.clone(),
        resource_scope.clone(),
        nonce,
        trace_id_field,
        issued_at,
        expires_at,
        signature,
    );
    let canonical_payload = received_claim.canonical_payload_bytes();
    let mut signing_input =
        Vec::with_capacity(CLAIM_DOMAIN_TAG.len() + canonical_payload.len());
    signing_input.extend_from_slice(CLAIM_DOMAIN_TAG);
    signing_input.extend_from_slice(&canonical_payload);
    verify_claim_signature(
        &signing_input,
        &received_claim.signature().bytes,
        signature.algorithm,
        &public_key,
    )?;

    // 12. Nonce-tracker check-and-record.
    let issuer_partition = NonceIssuerKey {
        principal: NoncePrincipal::Service(issuer.service_did().clone()),
        key_id: issuer.key_id(),
    };
    let nonce_bytes = *received_claim.nonce().as_bytes();
    match nonce_tracker
        .record(
            crate::wire::NonceKind::CapabilityClaim,
            &issuer_partition,
            &nonce_bytes,
            now,
        )
        .map_err(ClaimVerificationError::NonceTrackerFailed)?
    {
        NonceFreshness::Fresh => {}
        NonceFreshness::Replay { .. } => return Err(ClaimVerificationError::NonceReplay),
    }

    // 14. §4.8 W11 / W12 / W13 chain verification.
    //     If the claim is DelegatedFromUpstream, walk the chain
    //     under origin_authorized_capabilities. The verifier's
    //     request `trace_id` (not the claim's `trace_id_field`)
    //     attributes resolution-side audit emits during the walk.
    let verified_chain = match received_claim.origin() {
        crate::wire::ClaimOrigin::SelfOriginated => None,
        crate::wire::ClaimOrigin::DelegatedFromUpstream { chain } => {
            let chain_clone = chain.clone();
            let verified = verify_attribution_chain(
                &chain_clone,
                origin_authorized_capabilities,
                resolver,
                deadline,
                trace_id,
            )
            .await
            .map_err(ClaimVerificationError::AttributionChainInvalid)?;
            // §4.8 W13 final-hop monotonicity: claim.capabilities
            // ⊆ entries.last().granted_capabilities. The chain
            // walker already verified hop[0..n] monotonicity; this
            // closes the chain-tail-to-claim-payload gap.
            let last_granted = chain_clone
                .entries
                .last()
                .map(|e| e.granted_capabilities.clone())
                .unwrap_or_default();
            let claim_caps_set =
                CapabilitySet::from_kinds(received_claim.capabilities().iter().copied());
            if !last_granted.is_superset_of(&claim_caps_set) {
                return Err(ClaimVerificationError::ClaimExceedsChainTail);
            }
            Some(verified)
        }
    };

    // 15. Construct VerifiedCapabilityClaim.
    Ok(VerifiedCapabilityClaim::new_internal(
        issuer,
        subject,
        capabilities,
        resource_scope,
        trace_id_field,
        issued_at,
        expires_at,
        verified_chain,
    ))
}

/// Strip the `KryphocronClaim ` (case-insensitive) scheme prefix
/// per §7.6.
fn parse_claim_header(raw: &str) -> Result<&str, ClaimVerificationError> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err(ClaimVerificationError::Malformed);
    }
    if let Some(rest) = trimmed
        .strip_prefix("KryphocronClaim ")
        .or_else(|| trimmed.strip_prefix("kryphocronclaim "))
        .or_else(|| trimmed.strip_prefix("KRYPHOCRONCLAIM "))
    {
        let token = rest.trim_start();
        if token.is_empty() {
            return Err(ClaimVerificationError::Malformed);
        }
        return Ok(token);
    }
    // Bare token — operators that already stripped the scheme
    // upstream remain usable.
    Ok(trimmed)
}

/// Belt-and-suspenders class-vs-scope check at receive time
/// (§4.8 W9 / W10 enforcement). Mirror of `claim::check_scope_for_class`
/// expressed against [`crate::authority::CapabilityClass`].
fn class_permits_scope(
    class: crate::authority::CapabilityClass,
    scope: &ResourceScope,
) -> bool {
    use crate::authority::CapabilityClass;
    match class {
        CapabilityClass::User => matches!(scope, ResourceScope::Resource(_)),
        CapabilityClass::Channel => true,
        CapabilityClass::Substrate | CapabilityClass::Moderation => false,
    }
}

/// Pick a [`PublicKey`] from a resolved DID document for
/// capability-claim signature verification.
///
/// §7.6 dispatch: the issuer carries an explicit `KeyId`, so
/// resolution looks for an exact `KeyId` match in the DID
/// document's verification methods or the rotation history.
/// Algorithm must also match. No match →
/// `IssuerKeyNotInDocument`.
fn select_signing_key_for_claim(
    document: &crate::resolver::DidDocument,
    expected_key_id: KeyId,
    algorithm: SignatureAlgorithm,
) -> Result<PublicKey, ClaimVerificationError> {
    // Walk both the current verification_methods AND the
    // document's rotation_history.
    // §4.8 W12 commits rotation-tolerant verification — a claim
    // signed under a previously-active key still verifies if the
    // key is present in the resolved DID document's rotation
    // history. Exact-match-only would reject claims signed under
    // a key that was rotated out between issuance and verification,
    // even when the signature itself is cryptographically valid
    // against the historical key.
    for (kid, key) in document
        .verification_methods
        .iter()
        .chain(document.rotation_history.iter())
    {
        if *kid == expected_key_id && key.algorithm == algorithm {
            return Ok(*key);
        }
    }
    Err(ClaimVerificationError::IssuerKeyNotInDocument)
}

/// Verify a capability-claim signature for the given algorithm.
fn verify_claim_signature(
    signing_input: &[u8],
    signature: &[u8],
    algorithm: SignatureAlgorithm,
    public_key: &PublicKey,
) -> Result<(), ClaimVerificationError> {
    match algorithm {
        SignatureAlgorithm::Ed25519 => {
            if signature.len() != ed25519_dalek::SIGNATURE_LENGTH {
                return Err(ClaimVerificationError::SignatureInvalid);
            }
            let mut sig_bytes = [0u8; ed25519_dalek::SIGNATURE_LENGTH];
            sig_bytes.copy_from_slice(signature);
            let sig = Ed25519Signature::from_bytes(&sig_bytes);
            let key = VerifyingKey::from_bytes(&public_key.bytes)
                .map_err(|_| ClaimVerificationError::SignatureInvalid)?;
            key.verify(signing_input, &sig)
                .map_err(|_| ClaimVerificationError::SignatureInvalid)
        }
        SignatureAlgorithm::Es256 | SignatureAlgorithm::Es256K => {
            // ES256/ES256K primitives ship in a future release;
            // v0.1 stubs them with `UnsupportedAlgorithm` for both
            // JWT and capability-claim verification.
            Err(ClaimVerificationError::UnsupportedAlgorithm(algorithm))
        }
    }
}

// ============================================================
// §7.5 — sync handshake verification.
// ============================================================

/// Verification configuration for §7.5 sync-handshake messages.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SyncHandshakeVerificationConfig {
    /// Maximum tolerated wallclock skew between peer-asserted `at`
    /// and verifier's `now`. Default 30 seconds, matching §7.2's
    /// JWT clock-skew default.
    pub max_clock_skew: Duration,
    /// Verifier's local lexicon-set version. Used by the
    /// responder-side Hello verifier for the major-version skew
    /// check committed in §5.5 / §7.5 line 6650-6660.
    pub local_lexicon_set_version: SemVer,
    /// Algorithm allowlist; default `[Ed25519]`. §7.5 does not
    /// commit additional algorithms for handshake signing.
    pub accepted_algorithms: &'static [SignatureAlgorithm],
}

impl Default for SyncHandshakeVerificationConfig {
    fn default() -> Self {
        SyncHandshakeVerificationConfig {
            max_clock_skew: Duration::from_secs(30),
            local_lexicon_set_version: SemVer::new(1, 0, 0),
            accepted_algorithms: &[SignatureAlgorithm::Ed25519],
        }
    }
}

/// §7.5 handshake verification failure.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum SyncHandshakeVerificationError {
    /// Wire envelope structurally malformed (size, CBOR decode,
    /// non-canonical encoding, missing field, type mismatch).
    #[error("handshake message malformed")]
    Malformed,
    /// Message exceeded [`crate::wire::MAX_HANDSHAKE_MESSAGE_SIZE`].
    #[error("handshake message too large")]
    TooLarge,
    /// Handshake signature did not verify under the resolver-
    /// returned key material.
    #[error("handshake signature invalid")]
    SignatureInvalid,
    /// Counterparty DID resolution failed.
    #[error("handshake counterparty DID resolution failed: {0}")]
    CounterpartyResolutionFailed(DidResolutionError),
    /// Counterparty's claimed key id is not present in the
    /// resolved DID document (current methods or rotation history).
    #[error("counterparty key id not in DID document")]
    CounterpartyKeyNotInDocument,
    /// Algorithm not in the allowlist.
    #[error("handshake algorithm not supported: {0:?}")]
    UnsupportedAlgorithm(SignatureAlgorithm),
    /// Initiator's lexicon-set major version exceeds the
    /// responder's local major version (§5.5 / §7.5 line 6650).
    /// Responder-side; the responder's correct response is to
    /// emit a signed `SyncChannelResponse::Reject` with reason
    /// `LexiconSetMajorVersionMismatch`.
    #[error("initiator lexicon-set major version mismatch")]
    LexiconSetMajorVersionMismatch {
        /// Verifier's local version.
        local: SemVer,
        /// Initiator's claimed version.
        peer: SemVer,
    },
    /// Hello nonce was previously seen within the replay window.
    /// Responder-side; responder emits a signed reject with reason
    /// `HandshakeNonceReplay { first_seen_at }` and the
    /// `ChannelAuditEvent::SyncBatchRejected` audit event.
    #[error("handshake nonce replay")]
    HandshakeNonceReplay {
        /// Wallclock at which the responder first observed this
        /// nonce from this initiator.
        first_seen_at: SystemTime,
    },
    /// Backend failure consulting the [`HandshakeNonceTracker`].
    #[error("handshake nonce tracker backend unavailable: {0}")]
    NonceTrackerBackend(NonceTrackerError),
    /// `at` is more than `max_clock_skew` in the future.
    #[error("handshake `at` is in the future beyond skew tolerance")]
    NotYetValid,
    /// `at` is more than `max_clock_skew` in the past.
    #[error("handshake `at` is too old (clock skew exceeded)")]
    TooOld,
    /// Counterparty's identity does not match the expected
    /// identity for this side of the handshake. Returned by the
    /// initiator-side response verifier when the responder's
    /// `responder_identity` is not the DID the initiator sent
    /// Hello to (§7.5 "responder_identity unknown" → discard as
    /// no-message-received).
    #[error("counterparty identity mismatch")]
    CounterpartyIdentityMismatch,
}

/// §7.5 post-handshake message-verification failure.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum SyncMessageVerificationError {
    /// Inner capability-claim verification failed.
    #[error("inner claim verification failed: {0}")]
    Claim(#[from] ClaimVerificationError),
    /// Verified claim's issuer does not match the session-bound
    /// peer identity. The substrate dispatcher closes the
    /// connection on this error; mid-session identity drift is a
    /// protocol violation.
    #[error("session-bound peer identity mismatch")]
    PeerIdentityMismatch,
}

/// Hello message that has passed responder-side §7.5 verification.
///
/// Constructible only via [`verify_sync_hello`].
#[derive(Debug, Clone)]
pub struct VerifiedSyncHello {
    initiator_identity: ServiceIdentity,
    initiator_lexicon_set_version: SemVer,
    proposed_session_nonce: SessionNonce,
    requested_scope: SyncRequestedScope,
    at: SystemTime,
    _private: PhantomData<sealed::Token>,
}

impl VerifiedSyncHello {
    pub(crate) fn new_internal(
        initiator_identity: ServiceIdentity,
        initiator_lexicon_set_version: SemVer,
        proposed_session_nonce: SessionNonce,
        requested_scope: SyncRequestedScope,
        at: SystemTime,
    ) -> Self {
        VerifiedSyncHello {
            initiator_identity,
            initiator_lexicon_set_version,
            proposed_session_nonce,
            requested_scope,
            at,
            _private: PhantomData,
        }
    }
    /// Borrow the initiator identity.
    #[must_use]
    pub fn initiator_identity(&self) -> &ServiceIdentity {
        &self.initiator_identity
    }
    /// Initiator's lexicon-set version.
    #[must_use]
    pub fn initiator_lexicon_set_version(&self) -> SemVer {
        self.initiator_lexicon_set_version
    }
    /// Borrow the proposed session nonce.
    #[must_use]
    pub fn proposed_session_nonce(&self) -> &SessionNonce {
        &self.proposed_session_nonce
    }
    /// The scope requested by the initiator, **before** any §7.5
    /// federation narrowing has been applied.
    ///
    /// **WARNING: do not use for access control.** Federation
    /// peers (`PeerKind::Federation`) requesting `time_window:
    /// None` are subject to §7.5 line 6616's MUST-apply 7-day
    /// narrowing under [`crate::wire::DEFAULT_FEDERATION_TIME_WINDOW`].
    /// Internal peers (`PeerKind::Internal`) are exempt. The raw
    /// requested scope returned here is appropriate for audit
    /// logging only — for access-control decisions, ALWAYS call
    /// [`Self::narrowed_scope`] with the resolved peer kind.
    #[must_use]
    pub fn requested_scope(&self) -> &SyncRequestedScope {
        &self.requested_scope
    }
    /// The scope after §7.5 federation narrowing has been applied
    /// based on the resolved peer kind and any
    /// `TrustedWithConstraints` override.
    ///
    /// **THIS is what access-control code must consume.** The
    /// narrowing rules:
    ///
    /// - `PeerKind::Internal` → returns the requested scope
    ///   unchanged. Substrate-internal components are exempt from
    ///   the federation default per §7.5 line 6634.
    /// - `PeerKind::Federation` + non-`None` `time_window` →
    ///   returns the requested scope unchanged (the initiator
    ///   already supplied a bound).
    /// - `PeerKind::Federation` + `time_window: None` + no
    ///   operator-policy override → narrows to `Some(SyncTimeWindow
    ///   { start: now - DEFAULT_FEDERATION_TIME_WINDOW, end: now })`
    ///   per §7.5 line 6616-6626.
    /// - `PeerKind::Federation` + operator-supplied
    ///   `PeerTrustConstraints` (v0.1 placeholder; constraint-
    ///   shape-extension lands in a §7.7 spec patch) →
    ///   honors the operator constraint over the default. The
    ///   current `PeerTrustConstraints` is an empty struct (§7.7
    ///   commitment with no field shape yet); when fields land,
    ///   the override path activates here.
    ///
    /// `now` is supplied by the caller so test fixtures and
    /// deterministic-clock callers can pin behavior; production
    /// callers pass `SystemTime::now()`.
    #[must_use]
    pub fn narrowed_scope(
        &self,
        peer_kind: crate::resolver::PeerKind,
        _constraints: Option<&crate::audit::PeerTrustConstraints>,
        now: SystemTime,
    ) -> SyncRequestedScope {
        use crate::resolver::PeerKind;
        use crate::wire::{SyncTimeWindow, DEFAULT_FEDERATION_TIME_WINDOW};

        match peer_kind {
            PeerKind::Internal => self.requested_scope.clone(),
            PeerKind::Federation => {
                if self.requested_scope.time_window.is_some() {
                    self.requested_scope.clone()
                } else {
                    // §7.5 line 6616 narrowing: time_window: None
                    // → 7-day window ending now. Operator
                    // constraint override would activate here once
                    // PeerTrustConstraints carries
                    // `max_sync_scope` (a future release); current
                    // `_constraints` parameter is reserved.
                    let mut narrowed = self.requested_scope.clone();
                    let start = now
                        .checked_sub(DEFAULT_FEDERATION_TIME_WINDOW)
                        .unwrap_or(SystemTime::UNIX_EPOCH);
                    narrowed.time_window = Some(SyncTimeWindow {
                        start,
                        end: now,
                    });
                    narrowed
                }
            }
        }
    }
    /// Wallclock the initiator stamped.
    #[must_use]
    pub fn at(&self) -> SystemTime {
        self.at
    }
}

/// Accept message that has passed initiator-side §7.5 verification.
#[derive(Debug, Clone)]
pub struct VerifiedSyncAccept {
    responder_identity: ServiceIdentity,
    responder_lexicon_set_version: SemVer,
    session_id: SessionId,
    negotiated_scope: SyncRequestedScope,
    at: SystemTime,
    _private: PhantomData<sealed::Token>,
}

impl VerifiedSyncAccept {
    pub(crate) fn new_internal(
        responder_identity: ServiceIdentity,
        responder_lexicon_set_version: SemVer,
        session_id: SessionId,
        negotiated_scope: SyncRequestedScope,
        at: SystemTime,
    ) -> Self {
        VerifiedSyncAccept {
            responder_identity,
            responder_lexicon_set_version,
            session_id,
            negotiated_scope,
            at,
            _private: PhantomData,
        }
    }
    /// Borrow the responder identity.
    #[must_use]
    pub fn responder_identity(&self) -> &ServiceIdentity {
        &self.responder_identity
    }
    /// Responder's lexicon-set version.
    #[must_use]
    pub fn responder_lexicon_set_version(&self) -> SemVer {
        self.responder_lexicon_set_version
    }
    /// Session id derived by the responder.
    #[must_use]
    pub fn session_id(&self) -> SessionId {
        self.session_id
    }
    /// Borrow the negotiated (responder-narrowed) scope.
    #[must_use]
    pub fn negotiated_scope(&self) -> &SyncRequestedScope {
        &self.negotiated_scope
    }
    /// Wallclock the responder stamped.
    #[must_use]
    pub fn at(&self) -> SystemTime {
        self.at
    }
}

/// Reject message that has passed initiator-side §7.5 verification.
#[derive(Debug, Clone)]
pub struct VerifiedSyncReject {
    reason: BatchRejectionReason,
    responder_identity: ServiceIdentity,
    at: SystemTime,
    _private: PhantomData<sealed::Token>,
}

impl VerifiedSyncReject {
    pub(crate) fn new_internal(
        reason: BatchRejectionReason,
        responder_identity: ServiceIdentity,
        at: SystemTime,
    ) -> Self {
        VerifiedSyncReject {
            reason,
            responder_identity,
            at,
            _private: PhantomData,
        }
    }
    /// Borrow the rejection reason.
    #[must_use]
    pub fn reason(&self) -> &BatchRejectionReason {
        &self.reason
    }
    /// Borrow the responder identity.
    #[must_use]
    pub fn responder_identity(&self) -> &ServiceIdentity {
        &self.responder_identity
    }
    /// Wallclock the responder stamped.
    #[must_use]
    pub fn at(&self) -> SystemTime {
        self.at
    }
}

/// Verified Response: Accept or Reject (§7.5).
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum VerifiedSyncResponse {
    /// The handshake was accepted.
    Accept(VerifiedSyncAccept),
    /// The handshake was rejected with a signed reason.
    Reject(VerifiedSyncReject),
}

/// Established message that has passed responder-side §7.5
/// verification.
#[derive(Debug, Clone)]
pub struct VerifiedSyncEstablished {
    session_id: SessionId,
    at: SystemTime,
    _private: PhantomData<sealed::Token>,
}

impl VerifiedSyncEstablished {
    pub(crate) fn new_internal(session_id: SessionId, at: SystemTime) -> Self {
        VerifiedSyncEstablished {
            session_id,
            at,
            _private: PhantomData,
        }
    }
    /// Session id from the bound session.
    #[must_use]
    pub fn session_id(&self) -> SessionId {
        self.session_id
    }
    /// Wallclock the initiator stamped.
    #[must_use]
    pub fn at(&self) -> SystemTime {
        self.at
    }
}

// VerifiedSyncMessage's constructor is `pub(crate)` so only the
// verifier in this module can produce one.
impl VerifiedSyncMessage {
    pub(crate) fn new_internal(
        session_identity: ServiceIdentity,
        session_id: SessionId,
        payload: VerifiedCapabilityClaim,
    ) -> Self {
        VerifiedSyncMessage {
            session_identity,
            session_id,
            payload,
            _private: PhantomData,
        }
    }
}

/// Responder-side verifier for `SyncChannelHello` (§7.5).
///
/// Walks the §7.5 verification chain in fail-closed order:
///
/// 1. Size + canonical-CBOR round-trip canonicality (per §7
///    round-4 hazard discipline applied symmetrically).
/// 2. CBOR decode into structured fields plus the carried
///    signature.
/// 3. Algorithm allowlist enforcement (default `[Ed25519]`).
/// 4. Clock-skew bounds on the initiator's `at`.
/// 5. Major-version skew check against the verifier's local
///    lexicon-set version.
/// 6. Counterparty DID resolution + signing-key selection (walks
///    `verification_methods` AND `rotation_history` per §4.8 W12).
/// 7. Signature verification under [`crate::wire::HELLO_DOMAIN_TAG`].
/// 8. Nonce-tracker check_and_record. The nonce check happens AFTER
///    signature verification so an attacker cannot induce nonce-
///    table churn without first producing a valid signature.
///
/// On success, returns [`VerifiedSyncHello`] sealed-by-construction.
/// On any verification failure, returns the appropriate variant of
/// [`SyncHandshakeVerificationError`].
///
/// # Errors
///
/// Returns [`SyncHandshakeVerificationError`] for any failure.
pub async fn verify_sync_hello(
    wire_bytes: &[u8],
    nonce_tracker: &dyn HandshakeNonceTracker,
    resolver: &dyn DidResolver,
    config: &SyncHandshakeVerificationConfig,
    deadline: Instant,
    trace_id: TraceId,
) -> Result<VerifiedSyncHello, SyncHandshakeVerificationError> {
    if wire_bytes.len() > MAX_HANDSHAKE_MESSAGE_SIZE {
        return Err(SyncHandshakeVerificationError::TooLarge);
    }
    if !handshake_wire_is_canonical_hello(wire_bytes) {
        return Err(SyncHandshakeVerificationError::Malformed);
    }
    let (initiator_identity, initiator_ver, nonce, scope, at, signature) =
        decode_hello_wire(wire_bytes)
            .map_err(|()| SyncHandshakeVerificationError::Malformed)?;

    if !config.accepted_algorithms.contains(&signature.algorithm) {
        return Err(SyncHandshakeVerificationError::UnsupportedAlgorithm(
            signature.algorithm,
        ));
    }

    let now = SystemTime::now();
    check_at_window(at, now, config.max_clock_skew)?;

    if initiator_ver.major > config.local_lexicon_set_version.major {
        return Err(
            SyncHandshakeVerificationError::LexiconSetMajorVersionMismatch {
                local: config.local_lexicon_set_version,
                peer: initiator_ver,
            },
        );
    }

    let document = resolver
        .resolve(initiator_identity.service_did(), deadline, trace_id)
        .await
        .map_err(SyncHandshakeVerificationError::CounterpartyResolutionFailed)?;
    let public_key = select_handshake_signing_key(
        &document,
        initiator_identity.key_id(),
        signature.algorithm,
    )?;

    let sign_input = crate::wire::hello_sign_input(
        &initiator_identity,
        initiator_ver,
        &nonce,
        &scope,
        at,
    );
    if !crate::wire::verify_handshake_signature(&public_key, &sign_input, &signature) {
        return Err(SyncHandshakeVerificationError::SignatureInvalid);
    }

    // Nonce tracking AFTER signature verification: an attacker
    // forging a signature can no longer induce nonce-table churn,
    // and a legitimate replay surfaces the recorded `first_seen_at`
    // for the audit event.
    match nonce_tracker.check_and_record(&initiator_identity, &nonce, now) {
        Ok(NonceFreshness::Fresh) => {}
        Ok(NonceFreshness::Replay { first_seen_at }) => {
            return Err(SyncHandshakeVerificationError::HandshakeNonceReplay {
                first_seen_at,
            });
        }
        Err(e) => {
            return Err(SyncHandshakeVerificationError::NonceTrackerBackend(e));
        }
    }

    Ok(VerifiedSyncHello::new_internal(
        initiator_identity,
        initiator_ver,
        nonce,
        scope,
        at,
    ))
}

/// Initiator-side verifier for `SyncChannelResponse` (§7.5).
///
/// Routes by wire-decode into Accept or Reject branch and verifies
/// the responder's signature under [`crate::wire::ACCEPT_DOMAIN_TAG`] or
/// [`crate::wire::REJECT_DOMAIN_TAG`] respectively. The `expected_responder_did`
/// is the DID the initiator sent Hello to; per §7.5's "responder_
/// identity unknown is discarded as no-message-received" prose,
/// any responder identity that doesn't match this expected DID
/// returns [`SyncHandshakeVerificationError::CounterpartyIdentityMismatch`].
///
/// The wire bytes carry an outer 1-byte discriminator (0x00 for
/// Accept, 0x01 for Reject) prepended to the message bytes; this
/// is the substrate's framing choice for the on-wire envelope.
///
/// # Errors
///
/// Returns [`SyncHandshakeVerificationError`] for any failure.
pub async fn verify_sync_response(
    wire_bytes: &[u8],
    expected_responder_did: &Did,
    resolver: &dyn DidResolver,
    config: &SyncHandshakeVerificationConfig,
    deadline: Instant,
    trace_id: TraceId,
) -> Result<VerifiedSyncResponse, SyncHandshakeVerificationError> {
    if wire_bytes.is_empty() {
        return Err(SyncHandshakeVerificationError::Malformed);
    }
    let (discriminator, body) = wire_bytes.split_first().expect("non-empty");
    match discriminator {
        0x00 => verify_sync_accept(body, expected_responder_did, resolver, config, deadline, trace_id)
            .await
            .map(VerifiedSyncResponse::Accept),
        0x01 => verify_sync_reject(body, expected_responder_did, resolver, config, deadline, trace_id)
            .await
            .map(VerifiedSyncResponse::Reject),
        _ => Err(SyncHandshakeVerificationError::Malformed),
    }
}

async fn verify_sync_accept(
    wire_bytes: &[u8],
    expected_responder_did: &Did,
    resolver: &dyn DidResolver,
    config: &SyncHandshakeVerificationConfig,
    deadline: Instant,
    trace_id: TraceId,
) -> Result<VerifiedSyncAccept, SyncHandshakeVerificationError> {
    if wire_bytes.len() > MAX_HANDSHAKE_MESSAGE_SIZE {
        return Err(SyncHandshakeVerificationError::TooLarge);
    }
    if !handshake_wire_is_canonical_accept(wire_bytes) {
        return Err(SyncHandshakeVerificationError::Malformed);
    }
    let (responder_identity, responder_ver, session_id, negotiated_scope, at, signature) =
        decode_accept_wire(wire_bytes)
            .map_err(|()| SyncHandshakeVerificationError::Malformed)?;

    if responder_identity.service_did() != expected_responder_did {
        return Err(SyncHandshakeVerificationError::CounterpartyIdentityMismatch);
    }
    if !config.accepted_algorithms.contains(&signature.algorithm) {
        return Err(SyncHandshakeVerificationError::UnsupportedAlgorithm(
            signature.algorithm,
        ));
    }
    check_at_window(at, SystemTime::now(), config.max_clock_skew)?;

    let document = resolver
        .resolve(expected_responder_did, deadline, trace_id)
        .await
        .map_err(SyncHandshakeVerificationError::CounterpartyResolutionFailed)?;
    let public_key = select_handshake_signing_key(
        &document,
        responder_identity.key_id(),
        signature.algorithm,
    )?;
    let sign_input = crate::wire::accept_sign_input(
        &responder_identity,
        responder_ver,
        &session_id,
        &negotiated_scope,
        at,
    );
    if !crate::wire::verify_handshake_signature(&public_key, &sign_input, &signature) {
        return Err(SyncHandshakeVerificationError::SignatureInvalid);
    }

    Ok(VerifiedSyncAccept::new_internal(
        responder_identity,
        responder_ver,
        session_id,
        negotiated_scope,
        at,
    ))
}

async fn verify_sync_reject(
    wire_bytes: &[u8],
    expected_responder_did: &Did,
    resolver: &dyn DidResolver,
    config: &SyncHandshakeVerificationConfig,
    deadline: Instant,
    trace_id: TraceId,
) -> Result<VerifiedSyncReject, SyncHandshakeVerificationError> {
    if wire_bytes.len() > MAX_HANDSHAKE_MESSAGE_SIZE {
        return Err(SyncHandshakeVerificationError::TooLarge);
    }
    if !handshake_wire_is_canonical_reject(wire_bytes) {
        return Err(SyncHandshakeVerificationError::Malformed);
    }
    let (reason, responder_identity, at, signature) = decode_reject_wire(wire_bytes)
        .map_err(|()| SyncHandshakeVerificationError::Malformed)?;

    if responder_identity.service_did() != expected_responder_did {
        return Err(SyncHandshakeVerificationError::CounterpartyIdentityMismatch);
    }
    if !config.accepted_algorithms.contains(&signature.algorithm) {
        return Err(SyncHandshakeVerificationError::UnsupportedAlgorithm(
            signature.algorithm,
        ));
    }
    check_at_window(at, SystemTime::now(), config.max_clock_skew)?;

    let document = resolver
        .resolve(expected_responder_did, deadline, trace_id)
        .await
        .map_err(SyncHandshakeVerificationError::CounterpartyResolutionFailed)?;
    let public_key = select_handshake_signing_key(
        &document,
        responder_identity.key_id(),
        signature.algorithm,
    )?;
    let sign_input = crate::wire::reject_sign_input(&reason, &responder_identity, at);
    if !crate::wire::verify_handshake_signature(&public_key, &sign_input, &signature) {
        return Err(SyncHandshakeVerificationError::SignatureInvalid);
    }

    Ok(VerifiedSyncReject::new_internal(reason, responder_identity, at))
}

/// Responder-side verifier for `SyncChannelEstablished` (§7.5).
///
/// The responder verifies the initiator's signature over
/// `(session_id, responder_identity = self_identity, at)` under
/// [`crate::wire::ESTABLISHED_DOMAIN_TAG`]. The responder's own identity is
/// supplied as `local_identity`; the initiator's verifying key
/// must come from the prior Hello-time DID resolution (`initiator_
/// public_key`) since Established's wire envelope does NOT carry
/// the initiator identity.
///
/// # Errors
///
/// Returns [`SyncHandshakeVerificationError`] for any failure.
pub fn verify_sync_established(
    wire_bytes: &[u8],
    local_identity: &ServiceIdentity,
    initiator_public_key: &PublicKey,
    config: &SyncHandshakeVerificationConfig,
) -> Result<VerifiedSyncEstablished, SyncHandshakeVerificationError> {
    if wire_bytes.len() > MAX_HANDSHAKE_MESSAGE_SIZE {
        return Err(SyncHandshakeVerificationError::TooLarge);
    }
    if !handshake_wire_is_canonical_established(wire_bytes) {
        return Err(SyncHandshakeVerificationError::Malformed);
    }
    let (session_id, at, signature) = decode_established_wire(wire_bytes)
        .map_err(|()| SyncHandshakeVerificationError::Malformed)?;
    if !config.accepted_algorithms.contains(&signature.algorithm) {
        return Err(SyncHandshakeVerificationError::UnsupportedAlgorithm(
            signature.algorithm,
        ));
    }
    check_at_window(at, SystemTime::now(), config.max_clock_skew)?;

    let sign_input = crate::wire::established_sign_input(&session_id, local_identity, at);
    if !crate::wire::verify_handshake_signature(initiator_public_key, &sign_input, &signature) {
        return Err(SyncHandshakeVerificationError::SignatureInvalid);
    }
    Ok(VerifiedSyncEstablished::new_internal(session_id, at))
}

/// Verify a post-handshake §7.6 capability claim that arrived on
/// an established sync channel.
///
/// Wraps [`verify_capability_claim`] and additionally enforces that
/// the verified claim's issuer matches the session-bound peer
/// identity (`session_peer`). Mid-session identity drift is a
/// protocol violation and surfaces as
/// [`SyncMessageVerificationError::PeerIdentityMismatch`].
///
/// The substrate dispatcher (or its sync-message handler) is
/// responsible for the §7.5 `UnknownSessionMessage` audit emit
/// when a sync-channel message arrives with a session id not in
/// the local session table; this function operates on already-
/// looked-up session state.
///
/// # Errors
///
/// Returns [`SyncMessageVerificationError`] for any failure.
pub async fn verify_sync_message(
    raw_header: &str,
    session_id: SessionId,
    session_peer: &ServiceIdentity,
    local_audience: &ServiceIdentity,
    resolver: &dyn DidResolver,
    nonce_tracker: &dyn NonceTracker,
    config: &ClaimVerificationConfig,
    deadline: Instant,
    trace_id: TraceId,
    origin_authorized_capabilities: &CapabilitySet,
) -> Result<VerifiedSyncMessage, SyncMessageVerificationError> {
    let claim = verify_capability_claim(
        raw_header,
        local_audience,
        resolver,
        nonce_tracker,
        config,
        deadline,
        trace_id,
        origin_authorized_capabilities,
    )
    .await?;
    if claim.issuer() != session_peer {
        return Err(SyncMessageVerificationError::PeerIdentityMismatch);
    }
    Ok(VerifiedSyncMessage::new_internal(
        session_peer.clone(),
        session_id,
        claim,
    ))
}

// ============================================================
// §7.5 internal helpers.
// ============================================================

fn check_at_window(
    at: SystemTime,
    now: SystemTime,
    skew: Duration,
) -> Result<(), SyncHandshakeVerificationError> {
    if at > now + skew {
        return Err(SyncHandshakeVerificationError::NotYetValid);
    }
    // Reject `at` more than one skew window in the past — handshake
    // messages are expected to be near-real-time. Operators with
    // looser `at` semantics configure a wider `max_clock_skew`.
    if let Ok(age) = now.duration_since(at) {
        if age > skew {
            return Err(SyncHandshakeVerificationError::TooOld);
        }
    }
    Ok(())
}

fn select_handshake_signing_key(
    document: &crate::resolver::DidDocument,
    expected_key_id: KeyId,
    algorithm: SignatureAlgorithm,
) -> Result<PublicKey, SyncHandshakeVerificationError> {
    for (kid, key) in document
        .verification_methods
        .iter()
        .chain(document.rotation_history.iter())
    {
        if *kid == expected_key_id && key.algorithm == algorithm {
            return Ok(*key);
        }
    }
    Err(SyncHandshakeVerificationError::CounterpartyKeyNotInDocument)
}

fn handshake_wire_is_canonical_hello(bytes: &[u8]) -> bool {
    decode_hello_wire(bytes)
        .ok()
        .map(|d| {
            let h = SyncChannelHello {
                initiator_identity: d.0,
                initiator_lexicon_set_version: d.1,
                proposed_session_nonce: d.2,
                requested_scope: d.3,
                at: d.4,
                initiator_signature: d.5,
            };
            hello_to_wire_bytes(&h) == bytes
        })
        .unwrap_or(false)
}

fn handshake_wire_is_canonical_accept(bytes: &[u8]) -> bool {
    decode_accept_wire(bytes)
        .ok()
        .map(|d| {
            let a = SyncChannelAccept {
                responder_identity: d.0,
                responder_lexicon_set_version: d.1,
                session_id: d.2,
                negotiated_scope: d.3,
                at: d.4,
                responder_signature: d.5,
            };
            accept_to_wire_bytes(&a) == bytes
        })
        .unwrap_or(false)
}

fn handshake_wire_is_canonical_reject(bytes: &[u8]) -> bool {
    decode_reject_wire(bytes)
        .ok()
        .map(|d| {
            let r = SyncChannelReject {
                reason: d.0,
                responder_identity: d.1,
                at: d.2,
                responder_signature: d.3,
            };
            reject_to_wire_bytes(&r) == bytes
        })
        .unwrap_or(false)
}

fn handshake_wire_is_canonical_established(bytes: &[u8]) -> bool {
    decode_established_wire(bytes)
        .ok()
        .map(|d| {
            let e = SyncChannelEstablished {
                session_id: d.0,
                at: d.1,
                initiator_signature: d.2,
            };
            established_to_wire_bytes(&e) == bytes
        })
        .unwrap_or(false)
}

// ============================================================
// §4.8 W11 / W12 / W13 — attribution chain verification.
// ============================================================

/// Verify a wire-form attribution chain into a verified
/// [`crate::AttributionChain`] (§4.8 W11 / W12 / W13).
///
/// The eight-stage chain:
///
/// 1. **Depth bound:** `chain_wire.entries.len()` ≤
///    `MAX_CHAIN_DEPTH` (8) per §4.2 / §4.8.
/// 2. **Per-hop loop, in order from i = 0:**
///    1. Identify `previous_principal` — `chain_wire.origin` for
///       i = 0, otherwise `chain_wire.entries[i-1].principal`.
///    2. Resolve previous principal's DID via `DidResolver::resolve(_, trace_id)`.
///    3. **W12 algorithm check:** receipt's algorithm in allowlist
///       → else `AlgorithmNotAccepted`.
///    4. **W12 rotation tolerance + key discovery:** walk the
///       resolved DID document's `verification_methods +
///       rotation_history`. For each candidate `(key_id, key)`
///       reconstruct the canonical `DelegationReceiptPayload` with
///       `previous_key_id = key_id`, attempt signature verification.
///       The first that verifies is the signing key for this hop.
///       (Trial verification: at most
///       `MAX_ROTATION_DEPTH × MAX_CHAIN_DEPTH` Ed25519 verifies
///       per chain.)
///    5. **W12 fail modes:** no candidate verified → if any key
///       was tried under the wrong algorithm,
///       `KeyNotInRotationHistory`; if signatures were tried but
///       all failed, `SignatureInvalid`.
///    6. **W13 monotonicity:** `entries[i].granted_capabilities`
///       ⊆ `previous_authorized_capabilities` (where the previous
///       authorized set is `origin_authorized_capabilities` for
///       i = 0, else `entries[i-1].granted_capabilities`). Else
///       `CapabilityExpansion { hop, attempted, available }`.
///    7. Update `previous_authorized_capabilities` to the current
///       hop's `granted_capabilities` for the next iteration.
/// 3. Build the verified [`crate::AttributionChain`] from the wire
///    form by walking each verified hop into a
///    [`crate::AttributionEntry`].
///
/// **Fail-fast at the first failing hop.** §4.8 W13 commits the
/// `failing_hop` index in [`BindError::AttributionReceiptInvalid`]
/// as a lower bound on chain failure extent, not exhaustive.
///
/// **Timing equalization considered.** §4.6's `equalize_timing`
/// discipline absorbs the hop-by-hop variance at the consuming
/// bind paths. This verifier does NOT add equalization plumbing
/// itself — the bind paths that consume the verified chain pull
/// in equalization for the capability classes that need it.
///
/// **Pattern B authority plumbing.** The
/// `origin_authorized_capabilities` parameter is supplied by the
/// caller (typically [`verify_capability_claim`] derived from the
/// originating JWT scope or service-claim authority). The
/// alternative ("Pattern A": chain root carries the authority via
/// extended `DerivationReason` variants) was considered and
/// declined.
///
/// # Errors
///
/// Returns [`BindError::AttributionReceiptInvalid`] for any
/// receipt-verification failure with the failing hop index and
/// the specific [`ReceiptVerificationFailure`] variant.
pub async fn verify_attribution_chain(
    chain_wire: &AttributionChainWire,
    origin_authorized_capabilities: &CapabilitySet,
    resolver: &dyn DidResolver,
    deadline: Instant,
    trace_id: TraceId,
) -> Result<crate::AttributionChain, BindError> {
    // Stage 1: depth bound.
    if chain_wire.entries.len() > crate::ingress::MAX_CHAIN_DEPTH {
        return Err(BindError::AttributionReceiptInvalid {
            failing_hop: chain_wire.entries.len() as u8,
            reason: ReceiptVerificationFailure::Malformed,
        });
    }

    let static_allowlist: &[SignatureAlgorithm] = &[SignatureAlgorithm::Ed25519];

    let mut previous_principal: AttributionPrincipalRef<'_> =
        AttributionPrincipalRef::FromOrigin(&chain_wire.origin);
    let mut previous_authorized = origin_authorized_capabilities.clone();
    let mut verified_entries: Vec<crate::AttributionEntry> = Vec::new();

    for (hop_index, entry) in chain_wire.entries.iter().enumerate() {
        let hop = u8::try_from(hop_index).unwrap_or(u8::MAX);

        verify_hop(
            entry,
            hop,
            &previous_principal,
            &previous_authorized,
            static_allowlist,
            resolver,
            deadline,
            trace_id,
        )
        .await
        .map_err(|reason| BindError::AttributionReceiptInvalid {
            failing_hop: hop,
            reason,
        })?;

        // The verified hop becomes an in-process AttributionEntry.
        // The signing key id used at this hop is captured during
        // verify_hop's trial-verification; for the in-process
        // chain we record the recipient's key_id (which is what the
        // §4.2 chain shape pins).
        let key_id_used = entry.principal.key_id();
        verified_entries.push(crate::AttributionEntry {
            requester: principal_to_requester(&entry.principal),
            derivation_reason: entry.derivation_reason.clone(),
            derived_at: entry.derived_at,
            key_id_used,
        });

        previous_principal = AttributionPrincipalRef::FromEntry(&entry.principal);
        previous_authorized = entry.granted_capabilities.clone();
    }

    // Build the in-process AttributionChain from the verified
    // entries. The chain's depth invariant is enforced by the
    // crate-internal try_push helper.
    let mut chain = crate::AttributionChain::empty();
    for entry in verified_entries {
        chain
            .try_push(entry)
            .map_err(|_| BindError::AttributionReceiptInvalid {
                failing_hop: chain_wire.entries.len() as u8,
                reason: ReceiptVerificationFailure::Malformed,
            })?;
    }
    Ok(chain)
}

#[allow(clippy::too_many_arguments)]
async fn verify_hop(
    entry: &AttributionEntryWire,
    hop: u8,
    previous_principal: &AttributionPrincipalRef<'_>,
    previous_authorized: &CapabilitySet,
    accepted_algorithms: &[SignatureAlgorithm],
    resolver: &dyn DidResolver,
    deadline: Instant,
    trace_id: TraceId,
) -> Result<(), ReceiptVerificationFailure> {
    // 2c — algorithm allowlist.
    if !accepted_algorithms.contains(&entry.receipt.algorithm) {
        return Err(ReceiptVerificationFailure::AlgorithmNotAccepted(
            entry.receipt.algorithm,
        ));
    }

    // 2b — resolve previous principal's DID document.
    let previous_did = previous_principal.did();
    let document = resolver
        .resolve(previous_did, deadline, trace_id)
        .await
        .map_err(ReceiptVerificationFailure::PreviousPrincipalUnresolvable)?;

    // 2d — trial verification across the previous principal's
    // current methods + rotation history. The first key whose
    // canonical reconstruction signature-verifies is the signing
    // key for this hop.
    let recipient_did = entry.principal.did().clone();
    let recipient_key_id = entry.principal.key_id().unwrap_or(KeyId::from_bytes([0u8; 32]));

    let mut tried_any_key = false;
    let mut tried_matching_alg = false;
    for (candidate_key_id, candidate_key) in document
        .verification_methods
        .iter()
        .chain(document.rotation_history.iter())
    {
        tried_any_key = true;
        if candidate_key.algorithm != entry.receipt.algorithm {
            continue;
        }
        tried_matching_alg = true;

        let payload = DelegationReceiptPayload {
            previous_principal_did: previous_did.clone(),
            previous_key_id: *candidate_key_id,
            recipient_principal_did: recipient_did.clone(),
            recipient_key_id,
            derivation_reason: entry.derivation_reason.clone(),
            granted_capabilities: entry.granted_capabilities.clone(),
            derived_at: entry.derived_at,
        };
        if verify_delegation_receipt(&payload, &entry.receipt, candidate_key) {
            // 2f — W13 monotonicity check. Apply AFTER signature
            // verification: a forged signature would be rejected
            // before the monotonicity check has a chance to run.
            if !previous_authorized.is_superset_of(&entry.granted_capabilities) {
                return Err(ReceiptVerificationFailure::CapabilityExpansion {
                    hop,
                    attempted: entry.granted_capabilities.clone(),
                    available: previous_authorized.clone(),
                });
            }
            return Ok(());
        }
    }

    if !tried_any_key {
        // Document had no keys at all — treat as the resolved
        // principal having no signing key id we can verify
        // against.
        return Err(ReceiptVerificationFailure::KeyNotInRotationHistory {
            previous_key_id: KeyId::from_bytes([0u8; 32]),
        });
    }
    if !tried_matching_alg {
        // No keys with the receipt's algorithm — closest fit is
        // KeyNotInRotationHistory because the algorithm match is
        // structural (a key's algorithm tag is part of its
        // identity in the rotation set).
        return Err(ReceiptVerificationFailure::KeyNotInRotationHistory {
            previous_key_id: KeyId::from_bytes([0u8; 32]),
        });
    }
    Err(ReceiptVerificationFailure::SignatureInvalid)
}

/// Borrowed previous-principal accessor used inside the per-hop
/// loop. Lets the loop carry either an [`AttributionPrincipal`]
/// owned by `chain_wire.origin` or one borrowed from the prior
/// entry without cloning.
enum AttributionPrincipalRef<'a> {
    FromOrigin(&'a AttributionPrincipal),
    FromEntry(&'a AttributionPrincipal),
}

impl<'a> AttributionPrincipalRef<'a> {
    fn did(&self) -> &Did {
        match self {
            AttributionPrincipalRef::FromOrigin(p) | AttributionPrincipalRef::FromEntry(p) => {
                p.did()
            }
        }
    }
}

fn principal_to_requester(p: &AttributionPrincipal) -> crate::ingress::Requester {
    match p {
        AttributionPrincipal::User(did) => crate::ingress::Requester::Did(did.clone()),
        AttributionPrincipal::Service(s) => crate::ingress::Requester::Service(s.clone()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use async_trait::async_trait;
    use ed25519_dalek::{Signer, SigningKey};
    use std::sync::{Arc, Mutex};

    use crate::resolver::{DidDocument, DidResolutionError, DidResolver};

    // ============================================================
    // Test fixtures.
    // ============================================================

    fn local_audience() -> ServiceIdentity {
        ServiceIdentity::new_internal(
            Did::new("did:web:audience.example").unwrap(),
            KeyId::from_bytes([0u8; 32]),
            PublicKey {
                algorithm: SignatureAlgorithm::Ed25519,
                bytes: [0u8; 32],
            },
            None,
        )
    }

    fn issuer_did() -> Did {
        Did::new("did:plc:issuerexample").unwrap()
    }

    fn fixed_signing_key() -> SigningKey {
        SigningKey::from_bytes(&[7u8; 32])
    }

    fn fixed_verifying_pubkey() -> PublicKey {
        let signing = fixed_signing_key();
        PublicKey {
            algorithm: SignatureAlgorithm::Ed25519,
            bytes: signing.verifying_key().to_bytes(),
        }
    }

    fn b64u(input: &[u8]) -> String {
        URL_SAFE_NO_PAD.encode(input)
    }

    /// Construct + sign a JWT from a header JSON + payload JSON.
    fn build_jwt(header: &serde_json::Value, payload: &serde_json::Value) -> String {
        let header_b64 = b64u(serde_json::to_vec(header).unwrap().as_slice());
        let payload_b64 = b64u(serde_json::to_vec(payload).unwrap().as_slice());
        let signing_input = format!("{header_b64}.{payload_b64}");
        let sig = fixed_signing_key().sign(signing_input.as_bytes());
        let sig_b64 = b64u(&sig.to_bytes());
        format!("{signing_input}.{sig_b64}")
    }

    fn standard_payload(now_secs: u64) -> serde_json::Value {
        serde_json::json!({
            "iss": issuer_did().as_str(),
            "aud": local_audience().service_did().as_str(),
            "iat": now_secs,
            "exp": now_secs + 600,
            "scope": "tools.kryphocron.feed.read",
        })
    }

    fn ed25519_header() -> serde_json::Value {
        serde_json::json!({ "alg": "EdDSA", "typ": "JWT" })
    }

    // ============================================================
    // Mock DidResolver.
    // ============================================================

    /// In-memory mock resolver. Stores DID → (key id, public key)
    /// pairs; configurable to also return errors.
    struct MockResolver {
        documents: Mutex<std::collections::HashMap<String, Result<DidDocument, DidResolutionError>>>,
    }

    impl MockResolver {
        fn new() -> Self {
            MockResolver {
                documents: Mutex::new(std::collections::HashMap::new()),
            }
        }

        fn insert(&self, did: &Did, key_id: KeyId, key: PublicKey) {
            let doc = DidDocument {
                did: did.clone(),
                verification_methods: vec![(key_id, key)],
                rotation_history: vec![],
                services: vec![],
                also_known_as: vec![],
                resolved_at: SystemTime::now(),
                resolver_cache_max_age: Duration::from_secs(3600),
            };
            self.documents.lock().unwrap().insert(did.as_str().to_string(), Ok(doc));
        }

        fn insert_err(&self, did: &Did, err: DidResolutionError) {
            self.documents.lock().unwrap().insert(did.as_str().to_string(), Err(err));
        }
    }

    #[async_trait]
    impl DidResolver for MockResolver {
        async fn resolve(
            &self,
            did: &Did,
            _deadline: Instant,
            _trace_id: TraceId,
        ) -> Result<DidDocument, DidResolutionError> {
            self.documents
                .lock()
                .unwrap()
                .get(did.as_str())
                .cloned()
                .unwrap_or(Err(DidResolutionError::NotFound))
        }

        async fn invalidate(&self, _did: &Did, _trace_id: TraceId) {}
    }

    fn deadline() -> Instant {
        Instant::now() + Duration::from_secs(30)
    }

    fn now_secs() -> u64 {
        SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs()
    }

    fn populated_resolver() -> Arc<MockResolver> {
        let resolver = Arc::new(MockResolver::new());
        resolver.insert(&issuer_did(), KeyId::from_bytes([1u8; 32]), fixed_verifying_pubkey());
        resolver
    }

    // ============================================================
    // §7.2 default-config commitments.
    // ============================================================

    #[test]
    fn jwt_config_default_is_ed25519_only() {
        // §7.2 default allowlist commitment.
        let c = JwtVerificationConfig::default();
        assert_eq!(c.accepted_algorithms, &[SignatureAlgorithm::Ed25519]);
        assert!(!c.require_nonce);
    }

    #[test]
    fn jwt_config_defaults_match_7_2_recommendations() {
        let c = JwtVerificationConfig::default();
        assert_eq!(c.max_clock_skew, Duration::from_secs(30));
        assert_eq!(c.max_validity_window, Duration::from_secs(3600));
    }

    // ============================================================
    // §7.2 kid-matching tightening (v0.1 polish).
    // ============================================================

    #[test]
    fn kid_exact_match() {
        // Byte-equal hex id matches.
        assert!(kid_matches("deadbeef", "deadbeef"));
    }

    #[test]
    fn kid_fragment_match() {
        // DID URL with `#`-delimited fragment equals the hex id.
        assert!(kid_matches("did:plc:abc123#deadbeef", "deadbeef"));
        // Web DID + fragment shape also matches.
        assert!(kid_matches("did:web:example.com#deadbeef", "deadbeef"));
    }

    #[test]
    fn kid_suffix_no_longer_matches() {
        // Regression pin: the previous `ends_with` shape would have
        // accepted "prefixdeadbeef" as a match for "deadbeef".
        // Anchored matching rejects it — only `==` or `#`-fragment
        // matches succeed.
        assert!(!kid_matches("prefixdeadbeef", "deadbeef"));
        // A bare hex prefix collision is also rejected.
        assert!(!kid_matches("aabbccdeadbeef", "deadbeef"));
        // An empty fragment after `#` does not silently match.
        assert!(!kid_matches("did:plc:abc#", "deadbeef"));
    }

    // ============================================================
    // §7.2 parsing tests.
    // ============================================================

    #[tokio::test]
    async fn malformed_jwt_with_wrong_segment_count_returns_malformed() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        for bad in ["", "only_one_segment", "two.segments", "four.segments.are.bad"] {
            let err = verify_jwt(bad, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
                .await
                .unwrap_err();
            assert!(matches!(err, JwtVerificationError::Malformed), "input {bad:?} -> {err:?}");
        }
    }

    #[tokio::test]
    async fn malformed_jwt_with_invalid_base64url_returns_malformed() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        // `***` is not valid base64url.
        let err = verify_jwt("***.***.***", &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::Malformed));
    }

    #[tokio::test]
    async fn malformed_jwt_with_invalid_json_in_header_returns_malformed() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let bad = format!("{}.{}.{}", b64u(b"not json"), b64u(b"{}"), b64u(b"sig"));
        let err = verify_jwt(&bad, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::Malformed));
    }

    #[tokio::test]
    async fn alg_none_returns_malformed_not_unsupported() {
        // §7.2 alg-confusion discipline: `alg: "none"` → Malformed,
        // never UnsupportedAlgorithm. Important: the audit signal
        // must read "this token is not parseable" not "this
        // algorithm is not configured."
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        for none_variant in ["none", "None", "NONE", "nOnE"] {
            let header = serde_json::json!({ "alg": none_variant });
            let token = build_jwt(&header, &standard_payload(now_secs()));
            let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
                .await
                .unwrap_err();
            assert!(
                matches!(err, JwtVerificationError::Malformed),
                "alg={none_variant:?} -> {err:?}"
            );
        }
    }

    #[tokio::test]
    async fn unknown_alg_string_returns_malformed() {
        // Unknown alg names (not in the IANA registered space) are
        // Malformed — not UnsupportedAlgorithm — because they're
        // either misformatted or alg-confusion attempts.
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let header = serde_json::json!({ "alg": "MyCustomAlg" });
        let token = build_jwt(&header, &standard_payload(now_secs()));
        let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::Malformed));
    }

    #[tokio::test]
    async fn known_alg_outside_allowlist_returns_unsupported_algorithm() {
        // ES256 is a known IANA alg name; if not in the operator's
        // configured allowlist (default: Ed25519-only) this is the
        // legitimate UnsupportedAlgorithm signal.
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let header = serde_json::json!({ "alg": "ES256" });
        let token = build_jwt(&header, &standard_payload(now_secs()));
        let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::UnsupportedAlgorithm(SignatureAlgorithm::Es256)));
    }

    // ============================================================
    // §7.2 signature verification tests.
    // ============================================================

    #[tokio::test]
    async fn happy_path_verifies_an_ed25519_signed_jwt() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let payload = standard_payload(now_secs());
        let token = build_jwt(&ed25519_header(), &payload);
        let v = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap();
        assert_eq!(v.issuer().as_str(), issuer_did().as_str());
        assert_eq!(v.algorithm(), SignatureAlgorithm::Ed25519);
        assert_eq!(v.scope().scopes.as_slice(), &["tools.kryphocron.feed.read"]);
        assert!(v.nonce().is_none());
    }

    #[tokio::test]
    async fn tampered_payload_fails_signature_invalid() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let payload = standard_payload(now_secs());
        let token = build_jwt(&ed25519_header(), &payload);
        // Tamper the payload segment by re-encoding a different
        // payload while keeping the original signature.
        let mut parts = token.split('.');
        let header_b64 = parts.next().unwrap();
        let _orig_payload = parts.next().unwrap();
        let sig_b64 = parts.next().unwrap();
        let other_payload = serde_json::json!({
            "iss": issuer_did().as_str(),
            "aud": local_audience().service_did().as_str(),
            "iat": now_secs(),
            "exp": now_secs() + 600,
            "scope": "different.scope",
        });
        let other_payload_b64 = b64u(serde_json::to_vec(&other_payload).unwrap().as_slice());
        let tampered = format!("{header_b64}.{other_payload_b64}.{sig_b64}");
        let err = verify_jwt(&tampered, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::SignatureInvalid));
    }

    #[tokio::test]
    async fn tampered_signature_fails_signature_invalid() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let token = build_jwt(&ed25519_header(), &standard_payload(now_secs()));
        // Replace the signature with a same-length zero bitstring.
        let mut parts = token.rsplitn(2, '.');
        parts.next().unwrap(); // discard original sig
        let prefix = parts.next().unwrap();
        let zero_sig = b64u(&[0u8; ed25519_dalek::SIGNATURE_LENGTH]);
        let tampered = format!("{prefix}.{zero_sig}");
        let err = verify_jwt(&tampered, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::SignatureInvalid));
    }

    #[tokio::test]
    async fn wrong_key_fails_signature_invalid() {
        // Resolver returns the wrong public key for the issuer.
        let r = Arc::new(MockResolver::new());
        let wrong_key = PublicKey {
            algorithm: SignatureAlgorithm::Ed25519,
            bytes: SigningKey::from_bytes(&[99u8; 32]).verifying_key().to_bytes(),
        };
        r.insert(&issuer_did(), KeyId::from_bytes([1u8; 32]), wrong_key);
        let cfg = JwtVerificationConfig::default();
        let token = build_jwt(&ed25519_header(), &standard_payload(now_secs()));
        let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::SignatureInvalid));
    }

    // ============================================================
    // §7.2 claims verification tests.
    // ============================================================

    #[tokio::test]
    async fn expired_jwt_returns_expired_with_exp_and_now() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        // exp is 2 hours in the past, well outside skew.
        let now = now_secs();
        let payload = serde_json::json!({
            "iss": issuer_did().as_str(),
            "aud": local_audience().service_did().as_str(),
            "iat": now - 7200,
            "exp": now - 3600,
        });
        let token = build_jwt(&ed25519_header(), &payload);
        let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::Expired { .. }));
    }

    #[tokio::test]
    async fn future_dated_iat_returns_not_yet_valid() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        // iat is 5 minutes in the future, beyond skew.
        let now = now_secs();
        let payload = serde_json::json!({
            "iss": issuer_did().as_str(),
            "aud": local_audience().service_did().as_str(),
            "iat": now + 300,
            "exp": now + 600,
        });
        let token = build_jwt(&ed25519_header(), &payload);
        let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::NotYetValid { .. }));
    }

    #[tokio::test]
    async fn nbf_in_future_returns_not_yet_valid() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let now = now_secs();
        let payload = serde_json::json!({
            "iss": issuer_did().as_str(),
            "aud": local_audience().service_did().as_str(),
            "iat": now,
            "exp": now + 600,
            "nbf": now + 300,
        });
        let token = build_jwt(&ed25519_header(), &payload);
        let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::NotYetValid { .. }));
    }

    #[tokio::test]
    async fn wrong_audience_returns_wrong_audience() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let payload = serde_json::json!({
            "iss": issuer_did().as_str(),
            "aud": "did:web:somewhere.else",
            "iat": now_secs(),
            "exp": now_secs() + 600,
        });
        let token = build_jwt(&ed25519_header(), &payload);
        let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::WrongAudience { .. }));
    }

    #[tokio::test]
    async fn validity_window_too_long_returns_validity_window_too_long() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig {
            max_validity_window: Duration::from_secs(60),
            ..JwtVerificationConfig::default()
        };
        let now = now_secs();
        let payload = serde_json::json!({
            "iss": issuer_did().as_str(),
            "aud": local_audience().service_did().as_str(),
            "iat": now,
            "exp": now + 3600,
        });
        let token = build_jwt(&ed25519_header(), &payload);
        let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::ValidityWindowTooLong { .. }));
    }

    #[tokio::test]
    async fn issuer_resolution_failure_propagates() {
        let r = Arc::new(MockResolver::new());
        r.insert_err(&issuer_did(), DidResolutionError::NotFound);
        let cfg = JwtVerificationConfig::default();
        let token = build_jwt(&ed25519_header(), &standard_payload(now_secs()));
        let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::IssuerResolutionFailed(_)));
    }

    #[tokio::test]
    async fn issuer_key_not_in_document_when_document_empty() {
        let r = Arc::new(MockResolver::new());
        let empty_doc = DidDocument {
            did: issuer_did(),
            verification_methods: vec![],
            rotation_history: vec![],
            services: vec![],
            also_known_as: vec![],
            resolved_at: SystemTime::now(),
            resolver_cache_max_age: Duration::from_secs(3600),
        };
        r.documents.lock().unwrap().insert(issuer_did().as_str().to_string(), Ok(empty_doc));
        let cfg = JwtVerificationConfig::default();
        let token = build_jwt(&ed25519_header(), &standard_payload(now_secs()));
        let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::IssuerKeyNotInDocument));
    }

    // ============================================================
    // §7.2 nonce extraction tests.
    // ============================================================

    #[tokio::test]
    async fn require_nonce_true_with_missing_nonce_returns_nonce_missing() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig {
            require_nonce: true,
            ..JwtVerificationConfig::default()
        };
        let token = build_jwt(&ed25519_header(), &standard_payload(now_secs()));
        let err = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::NonceMissing));
    }

    #[tokio::test]
    async fn require_nonce_false_with_present_nonce_succeeds() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let nonce_bytes = [0xABu8; 16];
        let mut payload = standard_payload(now_secs());
        payload["nonce"] = serde_json::Value::String(b64u(&nonce_bytes));
        let token = build_jwt(&ed25519_header(), &payload);
        let v = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap();
        assert_eq!(v.nonce().unwrap().as_bytes(), &nonce_bytes);
    }

    /// §7.2 commits `NonceReplay` as a variant. `verify_jwt`
    /// itself does not wire replay protection (the `NonceTracker`
    /// integration is a separate opt-in); this test simply pins
    /// the variant exists and is constructible.
    #[test]
    fn nonce_replay_variant_is_reachable() {
        let _e = JwtVerificationError::NonceReplay;
    }

    // ============================================================
    // Scope-extraction tests.
    // ============================================================

    #[tokio::test]
    async fn scope_extracted_from_space_delimited_string() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let mut payload = standard_payload(now_secs());
        payload["scope"] = serde_json::Value::String("a.b c.d  e.f".into());
        let token = build_jwt(&ed25519_header(), &payload);
        let v = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap();
        assert_eq!(v.scope().scopes.as_slice(), &["a.b", "c.d", "e.f"]);
    }

    #[tokio::test]
    async fn scope_extracted_from_json_array() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let mut payload = standard_payload(now_secs());
        payload["scope"] = serde_json::json!(["x.y", "z.w"]);
        let token = build_jwt(&ed25519_header(), &payload);
        let v = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap();
        assert_eq!(v.scope().scopes.as_slice(), &["x.y", "z.w"]);
    }

    #[tokio::test]
    async fn scope_extracted_from_scp_field_name() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let mut payload = standard_payload(now_secs());
        payload.as_object_mut().unwrap().remove("scope");
        payload["scp"] = serde_json::Value::String("only.scope".into());
        let token = build_jwt(&ed25519_header(), &payload);
        let v = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap();
        assert_eq!(v.scope().scopes.as_slice(), &["only.scope"]);
    }

    #[tokio::test]
    async fn missing_scope_yields_empty_jwt_scope() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let mut payload = standard_payload(now_secs());
        payload.as_object_mut().unwrap().remove("scope");
        let token = build_jwt(&ed25519_header(), &payload);
        let v = verify_jwt(&token, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap();
        assert!(v.scope().scopes.is_empty());
    }

    // ============================================================
    // Authorization-header parsing tests.
    // ============================================================

    #[tokio::test]
    async fn authorization_header_with_bearer_prefix_succeeds() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let raw_token = build_jwt(&ed25519_header(), &standard_payload(now_secs()));
        let header_value = format!("Bearer {raw_token}");
        let v = verify_jwt(&header_value, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap();
        assert_eq!(v.issuer().as_str(), issuer_did().as_str());
    }

    #[tokio::test]
    async fn authorization_header_lowercase_bearer_also_succeeds() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let raw_token = build_jwt(&ed25519_header(), &standard_payload(now_secs()));
        let header_value = format!("bearer {raw_token}");
        let _v = verify_jwt(&header_value, &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn empty_authorization_header_returns_malformed() {
        let r = populated_resolver();
        let cfg = JwtVerificationConfig::default();
        let err = verify_jwt("", &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::Malformed));
        let err = verify_jwt("Bearer ", &local_audience(), &*r, &cfg, deadline(), TraceId::from_bytes([0u8; 16]))
            .await
            .unwrap_err();
        assert!(matches!(err, JwtVerificationError::Malformed));
    }

    // ============================================================
    // §7.6 capability-claim verification tests.
    // ============================================================

    use crate::wire::{CapabilityClaim, ClaimNonce, DefaultNonceTracker, ResourceScope};
    use crate::authority::CapabilityKind;
    use crate::authority::subjects::ResourceId;

    fn issuer_signing_key() -> ed25519_dalek::SigningKey {
        ed25519_dalek::SigningKey::from_bytes(&[7u8; 32])
    }

    fn issuer_service_identity() -> ServiceIdentity {
        let signing = issuer_signing_key();
        ServiceIdentity::new_internal(
            Did::new("did:plc:claimissuer").unwrap(),
            KeyId::from_bytes([0xAA; 32]),
            PublicKey {
                algorithm: SignatureAlgorithm::Ed25519,
                bytes: signing.verifying_key().to_bytes(),
            },
            None,
        )
    }

    fn audience_service_identity() -> ServiceIdentity {
        ServiceIdentity::new_internal(
            Did::new("did:web:audience.example").unwrap(),
            KeyId::from_bytes([0xBB; 32]),
            PublicKey {
                algorithm: SignatureAlgorithm::Ed25519,
                bytes: [0u8; 32],
            },
            None,
        )
    }

    fn sample_resource_id() -> ResourceId {
        ResourceId::new(
            Did::new("did:plc:owner").unwrap(),
            crate::Nsid::new("tools.kryphocron.feed.postPrivate").unwrap(),
            crate::Rkey::new("samplerkey").unwrap(),
        )
    }

    fn build_claim() -> CapabilityClaim {
        CapabilityClaim::new(
            issuer_service_identity(),
            audience_service_identity(),
            Did::new("did:plc:subject").unwrap(),
            vec![CapabilityKind::ViewPrivate],
            ResourceScope::Resource(sample_resource_id()),
            ClaimNonce::from_bytes([0xCC; 16]),
            TraceId::from_bytes([0xDD; 16]),
            Duration::from_secs(60),
            &issuer_signing_key(),
        )
        .unwrap()
    }

    fn populated_claim_resolver() -> Arc<MockResolver> {
        let resolver = Arc::new(MockResolver::new());
        let issuer = issuer_service_identity();
        resolver.insert(
            issuer.service_did(),
            issuer.key_id(),
            *issuer.key_material(),
        );
        resolver
    }

    fn b64u_wire(claim: &CapabilityClaim) -> String {
        URL_SAFE_NO_PAD.encode(claim.to_wire_bytes())
    }

    /// §7.6 default-config commitments.
    #[test]
    fn claim_config_default_is_ed25519_only() {
        let c = ClaimVerificationConfig::default();
        assert_eq!(c.accepted_algorithms, &[SignatureAlgorithm::Ed25519]);
        assert_eq!(c.max_clock_skew, Duration::from_secs(30));
        assert_eq!(c.max_validity_window, Duration::from_secs(600));
    }

    #[tokio::test]
    async fn claim_happy_path_verifies_an_ed25519_signed_claim() {
        let claim = build_claim();
        let resolver = populated_claim_resolver();
        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig::default();
        let header = format!("KryphocronClaim {}", b64u_wire(&claim));
        let v = verify_capability_claim(
            &header,
            &audience_service_identity(),
            &*resolver,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap();
        assert_eq!(v.issuer().service_did().as_str(), "did:plc:claimissuer");
        assert_eq!(v.subject().as_str(), "did:plc:subject");
        assert_eq!(v.capabilities(), &[CapabilityKind::ViewPrivate]);
    }

    #[tokio::test]
    async fn claim_replay_against_same_nonce_returns_nonce_replay() {
        let claim = build_claim();
        let resolver = populated_claim_resolver();
        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig::default();
        let header = format!("KryphocronClaim {}", b64u_wire(&claim));
        // First verification succeeds.
        let _v = verify_capability_claim(
            &header,
            &audience_service_identity(),
            &*resolver,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap();
        // Second verification of the same wire bytes (same nonce
        // under the same issuer partition) is rejected.
        let err = verify_capability_claim(
            &header,
            &audience_service_identity(),
            &*resolver,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, ClaimVerificationError::NonceReplay));
    }

    #[tokio::test]
    async fn claim_wrong_audience_returns_wrong_audience_with_did() {
        let claim = build_claim();
        let resolver = populated_claim_resolver();
        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig::default();
        let header = format!("KryphocronClaim {}", b64u_wire(&claim));
        // Verify against a different audience identity.
        let other_audience = ServiceIdentity::new_internal(
            Did::new("did:web:somewhere.else").unwrap(),
            KeyId::from_bytes([0; 32]),
            PublicKey {
                algorithm: SignatureAlgorithm::Ed25519,
                bytes: [0; 32],
            },
            None,
        );
        let err = verify_capability_claim(
            &header,
            &other_audience,
            &*resolver,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap_err();
        match err {
            ClaimVerificationError::WrongAudience { got, .. } => {
                // `got` is a Did, not a synthetic
                // ServiceIdentity placeholder.
                assert_eq!(got.as_str(), "did:web:audience.example");
            }
            other => panic!("expected WrongAudience, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn claim_with_invalid_base64url_returns_malformed() {
        let resolver = populated_claim_resolver();
        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig::default();
        let err = verify_capability_claim(
            "KryphocronClaim ***not-base64url***",
            &audience_service_identity(),
            &*resolver,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, ClaimVerificationError::Malformed));
    }

    #[tokio::test]
    async fn claim_with_non_canonical_cbor_returns_malformed() {
        // Hand-built CBOR map with non-canonical key ordering
        // (`zebra` before `apple`). Decodes successfully via
        // ciborium but fails the round-trip canonicality check.
        let non_canonical: Vec<u8> = vec![
            0xA2, 0x65, 0x7A, 0x65, 0x62, 0x72, 0x61, 0x01, 0x65, 0x61, 0x70, 0x70,
            0x6C, 0x65, 0x02,
        ];
        let header = format!("KryphocronClaim {}", URL_SAFE_NO_PAD.encode(&non_canonical));
        let resolver = populated_claim_resolver();
        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig::default();
        let err = verify_capability_claim(
            &header,
            &audience_service_identity(),
            &*resolver,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, ClaimVerificationError::Malformed));
    }

    #[tokio::test]
    async fn claim_too_large_returns_claim_too_large() {
        // A wire-bytes payload larger than MAX_CAPABILITY_CLAIM_SIZE.
        // Construct via raw bytes (not via CapabilityClaim::new
        // which would itself reject at construction).
        let oversized = vec![0u8; MAX_CAPABILITY_CLAIM_SIZE + 1];
        let header = format!("KryphocronClaim {}", URL_SAFE_NO_PAD.encode(&oversized));
        let resolver = populated_claim_resolver();
        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig::default();
        let err = verify_capability_claim(
            &header,
            &audience_service_identity(),
            &*resolver,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, ClaimVerificationError::ClaimTooLarge { .. }));
    }

    #[tokio::test]
    async fn claim_tampered_signature_fails_signature_invalid() {
        // Tamper the signature bytes specifically. Decoding the
        // wire envelope still succeeds (signature shape is the
        // same 64 bytes); the signature verification step fails
        // unambiguously with SignatureInvalid.
        let claim = build_claim();
        let resolver = populated_claim_resolver();
        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig::default();
        let wire = claim.to_wire_bytes();
        // The 64 signature bytes are the last 64 bytes of the
        // payload byte string in the canonical-CBOR encoding —
        // ciborium's `bytes(64)` head is `0x58 0x40` followed by
        // 64 raw bytes. Find the byte-string head and zero its
        // payload.
        let mut tampered = wire.clone();
        let head_pos = tampered
            .windows(2)
            .position(|w| w == [0x58, 0x40])
            .expect("wire envelope must contain a bytes(64) for the signature");
        let sig_start = head_pos + 2;
        for b in &mut tampered[sig_start..sig_start + 64] {
            *b = 0;
        }
        let header = format!("KryphocronClaim {}", URL_SAFE_NO_PAD.encode(&tampered));
        let err = verify_capability_claim(
            &header,
            &audience_service_identity(),
            &*resolver,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, ClaimVerificationError::SignatureInvalid));
    }

    /// §4.8 W8 domain-separation: a signature computed WITHOUT
    /// the `CLAIM_DOMAIN_TAG` prefix (e.g., the same canonical
    /// payload signed JWT-style with a bare-bytes signing input)
    /// must NOT verify. Otherwise an attacker who captures a
    /// signature in one domain (delegation receipt, JWT, etc.)
    /// could replay it in the capability-claim domain — exactly
    /// the cross-domain confusion W8 forecloses.
    #[tokio::test]
    async fn claim_signature_without_domain_tag_fails_verification() {
        use ed25519_dalek::Signer;

        let claim = build_claim();
        let canonical_payload = claim.canonical_payload_bytes();
        // Sign the bare canonical payload — *without* prepending
        // CLAIM_DOMAIN_TAG. This is the cross-domain forgery
        // attempt.
        let bare_sig = issuer_signing_key().sign(&canonical_payload);
        let forged_signature = crate::wire::ClaimSignature {
            algorithm: SignatureAlgorithm::Ed25519,
            bytes: bare_sig.to_bytes(),
        };
        let forged_claim = crate::wire::CapabilityClaim::new_internal_received(
            issuer_service_identity(),
            audience_service_identity(),
            Did::new("did:plc:subject").unwrap(),
            crate::wire::ClaimOrigin::SelfOriginated,
            vec![CapabilityKind::ViewPrivate],
            crate::wire::ResourceScope::Resource(sample_resource_id()),
            ClaimNonce::from_bytes([0xCC; 16]),
            TraceId::from_bytes([0xDD; 16]),
            claim.issued_at(),
            claim.expires_at(),
            forged_signature,
        );
        let header = format!("KryphocronClaim {}", URL_SAFE_NO_PAD.encode(forged_claim.to_wire_bytes()));
        let resolver = populated_claim_resolver();
        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig::default();
        let err = verify_capability_claim(
            &header,
            &audience_service_identity(),
            &*resolver,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(err, ClaimVerificationError::SignatureInvalid),
            "domain-separation bypass must fail; got {err:?}"
        );
    }

    /// §4.8 W6 belt-and-suspenders at receive: an externally-
    /// minted claim carrying a substrate-class capability must
    /// be rejected at receive even though `CapabilityClaim::new`
    /// would have caught it at construction. The substrate's own
    /// claims pass W6 at issuance; external claims may not.
    #[tokio::test]
    async fn claim_with_substrate_capability_returns_non_wire_eligible_at_receive() {
        use ed25519_dalek::Signer;

        // Build a wire envelope by hand: bypass the
        // construction-time W6 check via the crate-internal
        // received-shape constructor, then properly sign with
        // domain separation.
        let issuer = issuer_service_identity();
        let bad_caps = vec![CapabilityKind::ScanShard]; // substrate-class
        let issued_at = SystemTime::now();
        let expires_at = issued_at + Duration::from_secs(60);
        let nonce = ClaimNonce::from_bytes([0xEE; 16]);
        let trace = TraceId::from_bytes([0xFF; 16]);
        // Provisional claim with a placeholder signature so we
        // can call canonical_payload_bytes(); the signature isn't
        // included in the canonical payload anyway.
        let placeholder_sig = crate::wire::ClaimSignature {
            algorithm: SignatureAlgorithm::Ed25519,
            bytes: [0; 64],
        };
        let provisional = crate::wire::CapabilityClaim::new_internal_received(
            issuer.clone(),
            audience_service_identity(),
            Did::new("did:plc:subject").unwrap(),
            crate::wire::ClaimOrigin::SelfOriginated,
            bad_caps.clone(),
            crate::wire::ResourceScope::ClassWideAdministrative,
            nonce,
            trace,
            issued_at,
            expires_at,
            placeholder_sig,
        );
        let canonical_payload = provisional.canonical_payload_bytes();
        let mut signing_input = Vec::new();
        signing_input.extend_from_slice(crate::wire::CLAIM_DOMAIN_TAG);
        signing_input.extend_from_slice(&canonical_payload);
        let real_sig = issuer_signing_key().sign(&signing_input);
        let signed = crate::wire::CapabilityClaim::new_internal_received(
            issuer,
            audience_service_identity(),
            Did::new("did:plc:subject").unwrap(),
            crate::wire::ClaimOrigin::SelfOriginated,
            bad_caps,
            crate::wire::ResourceScope::ClassWideAdministrative,
            nonce,
            trace,
            issued_at,
            expires_at,
            crate::wire::ClaimSignature {
                algorithm: SignatureAlgorithm::Ed25519,
                bytes: real_sig.to_bytes(),
            },
        );
        let header = format!(
            "KryphocronClaim {}",
            URL_SAFE_NO_PAD.encode(signed.to_wire_bytes())
        );
        let resolver = populated_claim_resolver();
        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig::default();
        let err = verify_capability_claim(
            &header,
            &audience_service_identity(),
            &*resolver,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            ClaimVerificationError::NonWireEligibleCapability(CapabilityKind::ScanShard)
        ));
    }

    #[tokio::test]
    async fn claim_with_known_alg_outside_allowlist_returns_unsupported_algorithm() {
        let claim = build_claim();
        let resolver = populated_claim_resolver();
        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig {
            accepted_algorithms: &[],
            ..ClaimVerificationConfig::default()
        };
        let header = format!("KryphocronClaim {}", b64u_wire(&claim));
        let err = verify_capability_claim(
            &header,
            &audience_service_identity(),
            &*resolver,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            ClaimVerificationError::UnsupportedAlgorithm(SignatureAlgorithm::Ed25519)
        ));
    }

    /// §4.8 W12: a claim signed by a key that has been rotated
    /// out — present in the resolver's `rotation_history`, absent
    /// from `verification_methods` — still verifies. An
    /// exact-match-only walk would have rejected with
    /// `IssuerKeyNotInDocument` here.
    #[tokio::test]
    async fn claim_signed_by_rotated_out_key_still_verifies_via_rotation_history() {
        let claim = build_claim();
        let issuer = issuer_service_identity();
        // Build a resolver document where the issuer's current
        // key is a *different* one (rotated in), but the claim's
        // actual signing key is in rotation_history.
        let r = Arc::new(MockResolver::new());
        let rotated_in_key = ed25519_dalek::SigningKey::from_bytes(&[99u8; 32]);
        let rotated_in_pub = PublicKey {
            algorithm: SignatureAlgorithm::Ed25519,
            bytes: rotated_in_key.verifying_key().to_bytes(),
        };
        let mut doc = crate::resolver::DidDocument {
            did: issuer.service_did().clone(),
            verification_methods: vec![(KeyId::from_bytes([0xFF; 32]), rotated_in_pub)],
            rotation_history: vec![(issuer.key_id(), *issuer.key_material())],
            services: vec![],
            also_known_as: vec![],
            resolved_at: SystemTime::now(),
            resolver_cache_max_age: Duration::from_secs(3600),
        };
        // Also keep the rotation-history field's KeyId aligned
        // with the claim issuer's KeyId so the lookup matches.
        doc.rotation_history = vec![(issuer.key_id(), *issuer.key_material())];
        r.documents
            .lock()
            .unwrap()
            .insert(issuer.service_did().as_str().to_string(), Ok(doc));

        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig::default();
        let header = format!("KryphocronClaim {}", b64u_wire(&claim));
        let v = verify_capability_claim(
            &header,
            &audience_service_identity(),
            &*r,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap();
        assert_eq!(v.issuer().service_did().as_str(), "did:plc:claimissuer");
    }

    /// Negative: a claim signed by a key whose KeyId is NOT in
    /// verification_methods OR rotation_history fails with
    /// `IssuerKeyNotInDocument`. Pins that the rotation walk
    /// doesn't accept arbitrary keys (the lookup is by KeyId,
    /// not by bytewise key-material comparison).
    #[tokio::test]
    async fn claim_signed_by_unknown_key_returns_issuer_key_not_in_document() {
        let claim = build_claim();
        let issuer = issuer_service_identity();
        // The claim's `issuer.key_id()` is [0xAA; 32]
        // (per `issuer_service_identity()`). Build a document
        // whose KeyIds don't include [0xAA; 32].
        let r = Arc::new(MockResolver::new());
        let unrelated_key = ed25519_dalek::SigningKey::from_bytes(&[123u8; 32]);
        let unrelated_pub = PublicKey {
            algorithm: SignatureAlgorithm::Ed25519,
            bytes: unrelated_key.verifying_key().to_bytes(),
        };
        let doc = crate::resolver::DidDocument {
            did: issuer.service_did().clone(),
            verification_methods: vec![(KeyId::from_bytes([0x11; 32]), unrelated_pub)],
            rotation_history: vec![(KeyId::from_bytes([0x22; 32]), unrelated_pub)],
            services: vec![],
            also_known_as: vec![],
            resolved_at: SystemTime::now(),
            resolver_cache_max_age: Duration::from_secs(3600),
        };
        r.documents
            .lock()
            .unwrap()
            .insert(issuer.service_did().as_str().to_string(), Ok(doc));
        let tracker = DefaultNonceTracker::new();
        let cfg = ClaimVerificationConfig::default();
        let header = format!("KryphocronClaim {}", b64u_wire(&claim));
        let err = verify_capability_claim(
            &header,
            &audience_service_identity(),
            &*r,
            &tracker,
            &cfg,
            deadline(),
            TraceId::from_bytes([0u8; 16]),
            &CapabilitySet::empty(),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, ClaimVerificationError::IssuerKeyNotInDocument));
    }

    // ============================================================
    // §7.5 — handshake verifier smoke tests.
    // ============================================================

    fn handshake_signing_pair(seed: u8) -> (SigningKey, PublicKey) {
        let sk = SigningKey::from_bytes(&[seed; 32]);
        let vk = sk.verifying_key();
        (
            sk,
            PublicKey {
                algorithm: SignatureAlgorithm::Ed25519,
                bytes: vk.to_bytes(),
            },
        )
    }

    fn make_initiator_identity(seed: u8) -> (ServiceIdentity, SigningKey) {
        let (sk, pk) = handshake_signing_pair(seed);
        let did_str = format!("did:plc:{seed:02x}initiator0000000");
        let did = Did::new(&did_str).unwrap();
        let key_id = KeyId::from_bytes([seed; 32]);
        let id = ServiceIdentity::new_internal(did, key_id, pk, None);
        (id, sk)
    }

    fn handshake_test_resolver(initiator: &ServiceIdentity) -> Arc<MockResolver> {
        let r = Arc::new(MockResolver::new());
        r.insert(initiator.service_did(), initiator.key_id(), *initiator.key_material());
        r
    }

    /// §7.5 happy path: verify_sync_hello accepts a freshly-signed
    /// Hello and yields a sealed [`VerifiedSyncHello`].
    #[tokio::test]
    async fn verify_sync_hello_happy_path() {
        let (initiator, sk) = make_initiator_identity(0x10);
        let resolver = handshake_test_resolver(&initiator);
        let tracker = crate::wire::DefaultHandshakeNonceTracker::new();
        let cfg = SyncHandshakeVerificationConfig::default();

        let nonce = SessionNonce::from_bytes([0x42; 32]);
        let scope = SyncRequestedScope {
            nsids: smallvec::SmallVec::new(),
            time_window: None,
            direction: crate::wire::SyncDirection::Bidirectional,
        };
        let at = SystemTime::now();
        let sign_input = crate::wire::hello_sign_input(
            &initiator,
            SemVer::new(1, 0, 0),
            &nonce,
            &scope,
            at,
        );
        let sig = crate::wire::sign_handshake_payload(&sk, &sign_input);
        let hello = SyncChannelHello {
            initiator_identity: initiator.clone(),
            initiator_lexicon_set_version: SemVer::new(1, 0, 0),
            proposed_session_nonce: nonce,
            requested_scope: scope.clone(),
            initiator_signature: sig,
            at,
        };
        let bytes = hello_to_wire_bytes(&hello);

        let v = verify_sync_hello(
            &bytes,
            &tracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0xAB; 16]),
        )
        .await
        .unwrap();
        assert_eq!(v.initiator_identity(), &initiator);
        assert_eq!(v.proposed_session_nonce(), &nonce);
    }

    /// §7.5 nonce-replay path: a second verify_sync_hello call
    /// with the same nonce surfaces HandshakeNonceReplay carrying
    /// the recorded first_seen_at.
    #[tokio::test]
    async fn verify_sync_hello_replay_returns_handshake_nonce_replay() {
        let (initiator, sk) = make_initiator_identity(0x11);
        let resolver = handshake_test_resolver(&initiator);
        let tracker = crate::wire::DefaultHandshakeNonceTracker::new();
        let cfg = SyncHandshakeVerificationConfig::default();

        let nonce = SessionNonce::from_bytes([0x43; 32]);
        let scope = SyncRequestedScope {
            nsids: smallvec::SmallVec::new(),
            time_window: None,
            direction: crate::wire::SyncDirection::Receive,
        };
        let at = SystemTime::now();
        let sign_input = crate::wire::hello_sign_input(
            &initiator,
            SemVer::new(1, 0, 0),
            &nonce,
            &scope,
            at,
        );
        let sig = crate::wire::sign_handshake_payload(&sk, &sign_input);
        let hello = SyncChannelHello {
            initiator_identity: initiator.clone(),
            initiator_lexicon_set_version: SemVer::new(1, 0, 0),
            proposed_session_nonce: nonce,
            requested_scope: scope,
            initiator_signature: sig,
            at,
        };
        let bytes = hello_to_wire_bytes(&hello);

        verify_sync_hello(
            &bytes,
            &tracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0xAB; 16]),
        )
        .await
        .unwrap();

        let err = verify_sync_hello(
            &bytes,
            &tracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0xAB; 16]),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(err, SyncHandshakeVerificationError::HandshakeNonceReplay { .. }),
            "expected HandshakeNonceReplay, got {err:?}"
        );
    }

    /// §7.5 / §5.5 major-version skew: an initiator newer than the
    /// responder by a major version surfaces
    /// LexiconSetMajorVersionMismatch.
    #[tokio::test]
    async fn verify_sync_hello_rejects_major_version_skew() {
        let (initiator, sk) = make_initiator_identity(0x12);
        let resolver = handshake_test_resolver(&initiator);
        let tracker = crate::wire::DefaultHandshakeNonceTracker::new();
        let cfg = SyncHandshakeVerificationConfig {
            local_lexicon_set_version: SemVer::new(1, 0, 0),
            ..SyncHandshakeVerificationConfig::default()
        };

        let initiator_ver = SemVer::new(2, 0, 0);
        let nonce = SessionNonce::from_bytes([0x44; 32]);
        let scope = SyncRequestedScope {
            nsids: smallvec::SmallVec::new(),
            time_window: None,
            direction: crate::wire::SyncDirection::Send,
        };
        let at = SystemTime::now();
        let sign_input = crate::wire::hello_sign_input(
            &initiator, initiator_ver, &nonce, &scope, at,
        );
        let sig = crate::wire::sign_handshake_payload(&sk, &sign_input);
        let hello = SyncChannelHello {
            initiator_identity: initiator,
            initiator_lexicon_set_version: initiator_ver,
            proposed_session_nonce: nonce,
            requested_scope: scope,
            initiator_signature: sig,
            at,
        };
        let bytes = hello_to_wire_bytes(&hello);

        let err = verify_sync_hello(
            &bytes,
            &tracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0xAB; 16]),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(
                err,
                SyncHandshakeVerificationError::LexiconSetMajorVersionMismatch { .. }
            ),
            "expected LexiconSetMajorVersionMismatch, got {err:?}"
        );
    }

    /// §7.5 W8: an Established message signed by an initiator
    /// against a different responder identity than the one verifying
    /// fails signature verification (the responder identity is
    /// covered by the signature implicitly via the sign-input).
    #[test]
    fn verify_sync_established_fails_against_wrong_responder() {
        let (sk, init_pk) = handshake_signing_pair(0x20);
        let local_id_a = ServiceIdentity::new_internal(
            Did::new("did:plc:respondera000000000000").unwrap(),
            KeyId::from_bytes([0x21; 32]),
            init_pk,
            None,
        );
        let local_id_b = ServiceIdentity::new_internal(
            Did::new("did:plc:responderb000000000000").unwrap(),
            KeyId::from_bytes([0x22; 32]),
            init_pk,
            None,
        );
        let session_id = SessionId::from_bytes([0xCC; 32]);
        let at = SystemTime::now();

        // Initiator signs Established for responder A.
        let sign_input =
            crate::wire::established_sign_input(&session_id, &local_id_a, at);
        let sig = crate::wire::sign_handshake_payload(&sk, &sign_input);
        let est = SyncChannelEstablished {
            session_id,
            initiator_signature: sig,
            at,
        };
        let bytes = established_to_wire_bytes(&est);
        let cfg = SyncHandshakeVerificationConfig::default();

        // Responder B tries to verify (wrong responder context):
        // sign-input differs because local_identity differs.
        let err = verify_sync_established(&bytes, &local_id_b, &init_pk, &cfg)
            .unwrap_err();
        assert!(matches!(err, SyncHandshakeVerificationError::SignatureInvalid));

        // Responder A succeeds.
        let v = verify_sync_established(&bytes, &local_id_a, &init_pk, &cfg).unwrap();
        assert_eq!(v.session_id(), session_id);
    }

    // ============================================================
    // §7.5 — VerifiedSyncHello scope accessor split.
    // ============================================================

    fn fresh_verified_sync_hello(time_window: Option<crate::wire::SyncTimeWindow>) -> VerifiedSyncHello {
        let scope = SyncRequestedScope {
            nsids: smallvec::SmallVec::new(),
            time_window,
            direction: crate::wire::SyncDirection::Bidirectional,
        };
        VerifiedSyncHello::new_internal(
            ServiceIdentity::new_internal(
                Did::new("did:plc:initiator00000000000000").unwrap(),
                KeyId::from_bytes([0x10; 32]),
                PublicKey {
                    algorithm: SignatureAlgorithm::Ed25519,
                    bytes: [0x11; 32],
                },
                None,
            ),
            SemVer::new(1, 0, 0),
            SessionNonce::from_bytes([0x42; 32]),
            scope,
            SystemTime::now(),
        )
    }

    /// `PeerKind::Internal` is exempt from the §7.5 default
    /// federation narrowing — even with `time_window: None`, the
    /// scope is returned unchanged.
    #[test]
    fn narrowed_scope_internal_peer_unchanged_even_for_none_window() {
        let v = fresh_verified_sync_hello(None);
        let now = SystemTime::now();
        let narrowed = v.narrowed_scope(crate::resolver::PeerKind::Internal, None, now);
        assert!(narrowed.time_window.is_none());
    }

    /// `PeerKind::Federation` + `time_window: None` → narrowed to
    /// the §7.5 default 7-day window ending `now`.
    #[test]
    fn narrowed_scope_federation_peer_with_none_window_narrows_to_7_days() {
        let v = fresh_verified_sync_hello(None);
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000);
        let narrowed = v.narrowed_scope(crate::resolver::PeerKind::Federation, None, now);
        let window = narrowed.time_window.expect("federation None must narrow");
        assert_eq!(window.end, now);
        assert_eq!(
            window.start,
            now - crate::wire::DEFAULT_FEDERATION_TIME_WINDOW
        );
    }

    /// `PeerKind::Federation` + already-bounded `time_window` →
    /// returned unchanged (the initiator already supplied a
    /// bound; the default-narrowing rule applies only when the
    /// initiator left it open).
    #[test]
    fn narrowed_scope_federation_peer_with_bounded_window_unchanged() {
        let initiator_window = crate::wire::SyncTimeWindow {
            start: SystemTime::UNIX_EPOCH + Duration::from_secs(1_790_000_000),
            end: SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000),
        };
        let v = fresh_verified_sync_hello(Some(initiator_window));
        let now = SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_001);
        let narrowed = v.narrowed_scope(crate::resolver::PeerKind::Federation, None, now);
        assert_eq!(narrowed.time_window, Some(initiator_window));
    }

    /// `requested_scope` returns the unmodified initiator-requested
    /// scope regardless of peer kind. (The accessor split's whole
    /// point is that this is for audit logging only.)
    #[test]
    fn requested_scope_returns_raw_initiator_scope() {
        let v = fresh_verified_sync_hello(None);
        assert!(v.requested_scope().time_window.is_none());
    }

    // ============================================================
    // §4.8 W11 / W12 / W13 — chain verification tests.
    // ============================================================

    use crate::wire::{sign_delegation_receipt, DelegationReceipt};

    fn chain_test_pair(seed: u8) -> (SigningKey, PublicKey, KeyId, Did) {
        let sk = SigningKey::from_bytes(&[seed; 32]);
        let vk = sk.verifying_key();
        let pk = PublicKey {
            algorithm: SignatureAlgorithm::Ed25519,
            bytes: vk.to_bytes(),
        };
        let key_id = KeyId::from_bytes([seed; 32]);
        let did_str = format!("did:plc:{seed:02x}principal000000");
        let did = Did::new(&did_str).unwrap();
        (sk, pk, key_id, did)
    }

    fn chain_test_resolver_for(pairs: &[(Did, KeyId, PublicKey)]) -> Arc<MockResolver> {
        let r = Arc::new(MockResolver::new());
        for (did, key_id, key) in pairs {
            r.insert(did, *key_id, *key);
        }
        r
    }

    fn build_signed_entry(
        previous_did: &Did,
        previous_key_id: KeyId,
        previous_signing_key: &SigningKey,
        recipient_did: &Did,
        recipient_key_id: KeyId,
        recipient_pk: PublicKey,
        granted: CapabilitySet,
    ) -> AttributionEntryWire {
        let derived_at = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
        let payload = DelegationReceiptPayload {
            previous_principal_did: previous_did.clone(),
            previous_key_id,
            recipient_principal_did: recipient_did.clone(),
            recipient_key_id,
            derivation_reason: crate::ingress::DerivationReason::DropPrivilegeToAnonymous,
            granted_capabilities: granted.clone(),
            derived_at,
        };
        let receipt = sign_delegation_receipt(&payload, previous_signing_key);
        AttributionEntryWire {
            principal: AttributionPrincipal::Service(
                ServiceIdentity::new_internal(
                    recipient_did.clone(),
                    recipient_key_id,
                    recipient_pk,
                    None,
                ),
            ),
            derivation_reason: crate::ingress::DerivationReason::DropPrivilegeToAnonymous,
            derived_at,
            granted_capabilities: granted,
            receipt,
        }
    }

    /// §4.8 W11/W12/W13 happy path: a single-hop chain with valid
    /// receipt and monotonic capabilities verifies.
    #[tokio::test]
    async fn verify_attribution_chain_happy_path_single_hop() {
        let (sk_a, pk_a, kid_a, did_a) = chain_test_pair(0xA0);
        let (_sk_b, pk_b, kid_b, did_b) = chain_test_pair(0xB0);
        let resolver = chain_test_resolver_for(&[(did_a.clone(), kid_a, pk_a)]);
        let origin_caps = CapabilitySet::from_kinds(vec![CapabilityKind::ViewPrivate]);

        let entry = build_signed_entry(
            &did_a, kid_a, &sk_a,
            &did_b, kid_b, pk_b,
            origin_caps.clone(),
        );
        let chain = AttributionChainWire {
            origin: AttributionPrincipal::Service(ServiceIdentity::new_internal(
                did_a.clone(),
                kid_a,
                pk_a,
                None,
            )),
            entries: smallvec::smallvec![entry],
        };

        let verified = verify_attribution_chain(
            &chain,
            &origin_caps,
            resolver.as_ref() as &dyn DidResolver,
            deadline(),
            TraceId::from_bytes([0xCD; 16]),
        )
        .await
        .unwrap();
        assert_eq!(verified.entries().len(), 1);
    }

    /// §4.8 W13 capability-laundering probe: a hop attempting to
    /// grant a capability the previous hop did not authorize fails
    /// with `CapabilityExpansion { hop, attempted, available }`.
    #[tokio::test]
    async fn verify_attribution_chain_w13_capability_expansion_fails_closed() {
        let (sk_a, pk_a, kid_a, did_a) = chain_test_pair(0xA1);
        let (_sk_b, pk_b, kid_b, did_b) = chain_test_pair(0xB1);
        let resolver = chain_test_resolver_for(&[(did_a.clone(), kid_a, pk_a)]);

        // Origin authorized: only CreateRecord.
        let origin_caps = CapabilitySet::from_kinds(vec![CapabilityKind::ViewPrivate]);

        // Hop 0 attempts CreateRecord + DeleteRecord → expansion.
        let attempted = CapabilitySet::from_kinds(vec![
            CapabilityKind::ViewPrivate,
            CapabilityKind::EditPrivatePost,
        ]);
        let entry = build_signed_entry(
            &did_a, kid_a, &sk_a,
            &did_b, kid_b, pk_b,
            attempted,
        );
        let chain = AttributionChainWire {
            origin: AttributionPrincipal::Service(ServiceIdentity::new_internal(
                did_a.clone(),
                kid_a,
                pk_a,
                None,
            )),
            entries: smallvec::smallvec![entry],
        };

        let err = verify_attribution_chain(
            &chain,
            &origin_caps,
            resolver.as_ref() as &dyn DidResolver,
            deadline(),
            TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        match err {
            BindError::AttributionReceiptInvalid {
                failing_hop,
                reason: ReceiptVerificationFailure::CapabilityExpansion { hop, .. },
            } => {
                assert_eq!(failing_hop, 0);
                assert_eq!(hop, 0);
            }
            other => panic!("expected CapabilityExpansion at hop 0, got {other:?}"),
        }
    }

    /// §4.8 W12 SignatureInvalid: a hop whose receipt was signed
    /// by a different key than the previous principal's resolved
    /// key fails with `SignatureInvalid`.
    #[tokio::test]
    async fn verify_attribution_chain_signature_invalid() {
        let (sk_a, pk_a, kid_a, did_a) = chain_test_pair(0xA2);
        let (sk_imposter, _, _, _) = chain_test_pair(0xC2);
        let (_sk_b, pk_b, kid_b, did_b) = chain_test_pair(0xB2);
        // Resolver returns A's real public key; receipt was signed
        // by an imposter signing key → SignatureInvalid (no key in
        // A's rotation history matches).
        let resolver = chain_test_resolver_for(&[(did_a.clone(), kid_a, pk_a)]);
        let origin_caps = CapabilitySet::from_kinds(vec![CapabilityKind::ViewPrivate]);

        let entry = build_signed_entry(
            &did_a, kid_a, &sk_imposter,
            &did_b, kid_b, pk_b,
            origin_caps.clone(),
        );
        // Suppress the unused-warning for sk_a — sk_a is what
        // would have signed legitimately; we use sk_imposter.
        let _ = &sk_a;
        let chain = AttributionChainWire {
            origin: AttributionPrincipal::Service(ServiceIdentity::new_internal(
                did_a.clone(), kid_a, pk_a, None,
            )),
            entries: smallvec::smallvec![entry],
        };

        let err = verify_attribution_chain(
            &chain, &origin_caps,
            resolver.as_ref() as &dyn DidResolver,
            deadline(), TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            BindError::AttributionReceiptInvalid {
                reason: ReceiptVerificationFailure::SignatureInvalid,
                ..
            }
        ));
    }

    /// §4.8 W12 KeyNotInRotationHistory: previous principal's
    /// resolved DID document carries no Ed25519 key (only Es256).
    #[tokio::test]
    async fn verify_attribution_chain_key_not_in_rotation_history() {
        let (sk_a, _pk_a, kid_a, did_a) = chain_test_pair(0xA3);
        // Resolved doc has an Es256 key, not Ed25519. Receipt
        // claims Ed25519 algorithm.
        let pk_a_es256 = PublicKey {
            algorithm: SignatureAlgorithm::Es256,
            bytes: [0x33; 32],
        };
        let (_sk_b, pk_b, kid_b, did_b) = chain_test_pair(0xB3);
        let resolver = chain_test_resolver_for(&[(did_a.clone(), kid_a, pk_a_es256)]);
        let origin_caps = CapabilitySet::from_kinds(vec![CapabilityKind::ViewPrivate]);

        let entry = build_signed_entry(
            &did_a, kid_a, &sk_a,
            &did_b, kid_b, pk_b,
            origin_caps.clone(),
        );
        let chain = AttributionChainWire {
            origin: AttributionPrincipal::Service(ServiceIdentity::new_internal(
                did_a.clone(), kid_a, pk_a_es256, None,
            )),
            entries: smallvec::smallvec![entry],
        };

        let err = verify_attribution_chain(
            &chain, &origin_caps,
            resolver.as_ref() as &dyn DidResolver,
            deadline(), TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            BindError::AttributionReceiptInvalid {
                reason: ReceiptVerificationFailure::KeyNotInRotationHistory { .. },
                ..
            }
        ));
    }

    /// §4.8 W12 PreviousPrincipalUnresolvable: resolver returns
    /// NotFound for the previous principal's DID.
    #[tokio::test]
    async fn verify_attribution_chain_previous_principal_unresolvable() {
        let (sk_a, pk_a, kid_a, did_a) = chain_test_pair(0xA4);
        let (_sk_b, pk_b, kid_b, did_b) = chain_test_pair(0xB4);
        // Resolver insert_err for the previous principal.
        let r = Arc::new(MockResolver::new());
        r.insert_err(&did_a, DidResolutionError::NotFound);
        let origin_caps = CapabilitySet::from_kinds(vec![CapabilityKind::ViewPrivate]);

        let entry = build_signed_entry(
            &did_a, kid_a, &sk_a,
            &did_b, kid_b, pk_b,
            origin_caps.clone(),
        );
        let chain = AttributionChainWire {
            origin: AttributionPrincipal::Service(ServiceIdentity::new_internal(
                did_a.clone(), kid_a, pk_a, None,
            )),
            entries: smallvec::smallvec![entry],
        };

        let err = verify_attribution_chain(
            &chain, &origin_caps,
            r.as_ref() as &dyn DidResolver,
            deadline(), TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            BindError::AttributionReceiptInvalid {
                reason: ReceiptVerificationFailure::PreviousPrincipalUnresolvable(_),
                ..
            }
        ));
    }

    /// §4.8 W12 AlgorithmNotAccepted: receipt's algorithm is
    /// outside the verifier's allowlist (Ed25519 only in v1).
    #[tokio::test]
    async fn verify_attribution_chain_algorithm_not_accepted() {
        let (sk_a, pk_a, kid_a, did_a) = chain_test_pair(0xA5);
        let (_sk_b, pk_b, kid_b, did_b) = chain_test_pair(0xB5);
        let resolver = chain_test_resolver_for(&[(did_a.clone(), kid_a, pk_a)]);
        let origin_caps = CapabilitySet::from_kinds(vec![CapabilityKind::ViewPrivate]);

        let mut entry = build_signed_entry(
            &did_a, kid_a, &sk_a,
            &did_b, kid_b, pk_b,
            origin_caps.clone(),
        );
        // Stamp the receipt's algorithm to Es256 so the allowlist
        // check fires before signature verification.
        entry.receipt = DelegationReceipt {
            algorithm: SignatureAlgorithm::Es256,
            bytes: entry.receipt.bytes,
        };
        let chain = AttributionChainWire {
            origin: AttributionPrincipal::Service(ServiceIdentity::new_internal(
                did_a.clone(), kid_a, pk_a, None,
            )),
            entries: smallvec::smallvec![entry],
        };

        let err = verify_attribution_chain(
            &chain, &origin_caps,
            resolver.as_ref() as &dyn DidResolver,
            deadline(), TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            BindError::AttributionReceiptInvalid {
                reason: ReceiptVerificationFailure::AlgorithmNotAccepted(SignatureAlgorithm::Es256),
                ..
            }
        ));
    }

    /// §4.8 chain depth bound: chain with > MAX_CHAIN_DEPTH entries
    /// fails as Malformed before any per-hop work runs.
    #[tokio::test]
    async fn verify_attribution_chain_over_depth_returns_malformed() {
        let (sk_a, pk_a, kid_a, did_a) = chain_test_pair(0xA6);
        let (_, pk_b, kid_b, did_b) = chain_test_pair(0xB6);
        let resolver = chain_test_resolver_for(&[(did_a.clone(), kid_a, pk_a)]);
        let origin_caps = CapabilitySet::from_kinds(vec![CapabilityKind::ViewPrivate]);

        let entry = build_signed_entry(
            &did_a, kid_a, &sk_a,
            &did_b, kid_b, pk_b,
            origin_caps.clone(),
        );
        // Build MAX_CHAIN_DEPTH + 1 entries — over the cap.
        let mut entries: smallvec::SmallVec<[AttributionEntryWire; 8]> =
            smallvec::SmallVec::new();
        for _ in 0..(crate::ingress::MAX_CHAIN_DEPTH + 1) {
            entries.push(entry.clone());
        }
        let chain = AttributionChainWire {
            origin: AttributionPrincipal::Service(ServiceIdentity::new_internal(
                did_a.clone(), kid_a, pk_a, None,
            )),
            entries,
        };

        let err = verify_attribution_chain(
            &chain, &origin_caps,
            resolver.as_ref() as &dyn DidResolver,
            deadline(), TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            BindError::AttributionReceiptInvalid {
                reason: ReceiptVerificationFailure::Malformed,
                ..
            }
        ));
    }

    // ============================================================
    // §7.5 — SyncHandshakeVerificationError
    // variant test coverage round-out.
    // ============================================================

    /// Builds a valid signed Hello, returning the wire bytes plus
    /// the initiator's identity / signing key for tests that
    /// tweak fields after-the-fact.
    fn build_valid_hello(
        seed: u8,
    ) -> (Vec<u8>, ServiceIdentity, SigningKey) {
        let (initiator, sk) = make_initiator_identity(seed);
        let nonce = SessionNonce::from_bytes([seed.wrapping_mul(3); 32]);
        let scope = SyncRequestedScope {
            nsids: smallvec::SmallVec::new(),
            time_window: None,
            direction: crate::wire::SyncDirection::Bidirectional,
        };
        let at = SystemTime::now();
        let sign_input = crate::wire::hello_sign_input(
            &initiator,
            SemVer::new(1, 0, 0),
            &nonce,
            &scope,
            at,
        );
        let sig = crate::wire::sign_handshake_payload(&sk, &sign_input);
        let hello = SyncChannelHello {
            initiator_identity: initiator.clone(),
            initiator_lexicon_set_version: SemVer::new(1, 0, 0),
            proposed_session_nonce: nonce,
            requested_scope: scope,
            initiator_signature: sig,
            at,
        };
        let bytes = hello_to_wire_bytes(&hello);
        (bytes, initiator, sk)
    }

    /// Malformed: garbage bytes that don't parse as canonical CBOR.
    #[tokio::test]
    async fn verify_sync_hello_returns_malformed_for_garbage_bytes() {
        let bytes = vec![0xFF, 0xFE, 0xFD, 0xFC];
        let resolver = Arc::new(MockResolver::new());
        let tracker = crate::wire::DefaultHandshakeNonceTracker::new();
        let cfg = SyncHandshakeVerificationConfig::default();
        let err = verify_sync_hello(
            &bytes,
            &tracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, SyncHandshakeVerificationError::Malformed));
    }

    /// TooLarge: payload exceeds MAX_HANDSHAKE_MESSAGE_SIZE.
    #[tokio::test]
    async fn verify_sync_hello_returns_too_large_above_size_ceiling() {
        let bytes = vec![0u8; crate::wire::MAX_HANDSHAKE_MESSAGE_SIZE + 1];
        let resolver = Arc::new(MockResolver::new());
        let tracker = crate::wire::DefaultHandshakeNonceTracker::new();
        let cfg = SyncHandshakeVerificationConfig::default();
        let err = verify_sync_hello(
            &bytes,
            &tracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, SyncHandshakeVerificationError::TooLarge));
    }

    /// CounterpartyResolutionFailed: resolver returns NotFound for
    /// the initiator's DID.
    #[tokio::test]
    async fn verify_sync_hello_returns_counterparty_resolution_failed() {
        let (bytes, initiator, _sk) = build_valid_hello(0x30);
        let resolver = Arc::new(MockResolver::new());
        resolver.insert_err(initiator.service_did(), DidResolutionError::NotFound);
        let tracker = crate::wire::DefaultHandshakeNonceTracker::new();
        let cfg = SyncHandshakeVerificationConfig::default();
        let err = verify_sync_hello(
            &bytes,
            &tracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            SyncHandshakeVerificationError::CounterpartyResolutionFailed(_)
        ));
    }

    /// CounterpartyKeyNotInDocument: resolver returns a document
    /// without the named key.
    #[tokio::test]
    async fn verify_sync_hello_returns_counterparty_key_not_in_document() {
        let (bytes, initiator, _sk) = build_valid_hello(0x31);
        let resolver = Arc::new(MockResolver::new());
        // Insert a document with a DIFFERENT KeyId than the
        // initiator's claimed identity references.
        let other_kid = KeyId::from_bytes([0x99; 32]);
        resolver.insert(initiator.service_did(), other_kid, *initiator.key_material());
        let tracker = crate::wire::DefaultHandshakeNonceTracker::new();
        let cfg = SyncHandshakeVerificationConfig::default();
        let err = verify_sync_hello(
            &bytes,
            &tracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            SyncHandshakeVerificationError::CounterpartyKeyNotInDocument
        ));
    }

    /// UnsupportedAlgorithm: receipt's algorithm is outside the
    /// allowlist (Ed25519 only by default).
    #[tokio::test]
    async fn verify_sync_hello_returns_unsupported_algorithm() {
        let (bytes, initiator, _sk) = build_valid_hello(0x32);
        let resolver = Arc::new(MockResolver::new());
        resolver.insert(initiator.service_did(), initiator.key_id(), *initiator.key_material());
        let tracker = crate::wire::DefaultHandshakeNonceTracker::new();
        let cfg = SyncHandshakeVerificationConfig {
            // Empty allowlist — every signed signature falls outside.
            accepted_algorithms: &[],
            ..SyncHandshakeVerificationConfig::default()
        };
        let err = verify_sync_hello(
            &bytes,
            &tracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            SyncHandshakeVerificationError::UnsupportedAlgorithm(SignatureAlgorithm::Ed25519)
        ));
    }

    /// NonceTrackerBackend: tracker returns BackendUnavailable.
    /// The Mutex inside DefaultHandshakeNonceTracker is rarely
    /// poisoned in normal use; we use a custom failing tracker.
    #[tokio::test]
    async fn verify_sync_hello_returns_nonce_tracker_backend() {
        struct FailingTracker;
        impl crate::wire::HandshakeNonceTracker for FailingTracker {
            fn check_and_record(
                &self,
                _initiator: &ServiceIdentity,
                _nonce: &SessionNonce,
                _observed_at: SystemTime,
            ) -> Result<crate::wire::NonceFreshness, NonceTrackerError> {
                Err(NonceTrackerError::BackendUnavailable)
            }
            fn replay_window(&self) -> Duration {
                Duration::from_secs(60)
            }
        }
        let (bytes, initiator, _sk) = build_valid_hello(0x33);
        let resolver = Arc::new(MockResolver::new());
        resolver.insert(initiator.service_did(), initiator.key_id(), *initiator.key_material());
        let cfg = SyncHandshakeVerificationConfig::default();
        let err = verify_sync_hello(
            &bytes,
            &FailingTracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            SyncHandshakeVerificationError::NonceTrackerBackend(_)
        ));
    }

    /// NotYetValid: `at` field is in the future beyond skew
    /// tolerance. Constructed by stamping `at = now + 1 hour`.
    #[tokio::test]
    async fn verify_sync_hello_returns_not_yet_valid() {
        let (initiator, sk) = make_initiator_identity(0x34);
        let resolver = handshake_test_resolver(&initiator);
        let tracker = crate::wire::DefaultHandshakeNonceTracker::new();
        let cfg = SyncHandshakeVerificationConfig::default();
        let nonce = SessionNonce::from_bytes([0xAA; 32]);
        let scope = SyncRequestedScope {
            nsids: smallvec::SmallVec::new(),
            time_window: None,
            direction: crate::wire::SyncDirection::Bidirectional,
        };
        let at = SystemTime::now() + Duration::from_secs(3600);
        let sign_input = crate::wire::hello_sign_input(&initiator, SemVer::new(1, 0, 0), &nonce, &scope, at);
        let sig = crate::wire::sign_handshake_payload(&sk, &sign_input);
        let hello = SyncChannelHello {
            initiator_identity: initiator,
            initiator_lexicon_set_version: SemVer::new(1, 0, 0),
            proposed_session_nonce: nonce,
            requested_scope: scope,
            initiator_signature: sig,
            at,
        };
        let bytes = hello_to_wire_bytes(&hello);
        let err = verify_sync_hello(
            &bytes,
            &tracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, SyncHandshakeVerificationError::NotYetValid));
    }

    /// TooOld: `at` field is more than `max_clock_skew` in the
    /// past.
    #[tokio::test]
    async fn verify_sync_hello_returns_too_old() {
        let (initiator, sk) = make_initiator_identity(0x35);
        let resolver = handshake_test_resolver(&initiator);
        let tracker = crate::wire::DefaultHandshakeNonceTracker::new();
        let cfg = SyncHandshakeVerificationConfig::default();
        let nonce = SessionNonce::from_bytes([0xBB; 32]);
        let scope = SyncRequestedScope {
            nsids: smallvec::SmallVec::new(),
            time_window: None,
            direction: crate::wire::SyncDirection::Bidirectional,
        };
        // `at = now - 1 hour`, well past the default 30s skew.
        let at = SystemTime::now() - Duration::from_secs(3600);
        let sign_input = crate::wire::hello_sign_input(&initiator, SemVer::new(1, 0, 0), &nonce, &scope, at);
        let sig = crate::wire::sign_handshake_payload(&sk, &sign_input);
        let hello = SyncChannelHello {
            initiator_identity: initiator,
            initiator_lexicon_set_version: SemVer::new(1, 0, 0),
            proposed_session_nonce: nonce,
            requested_scope: scope,
            initiator_signature: sig,
            at,
        };
        let bytes = hello_to_wire_bytes(&hello);
        let err = verify_sync_hello(
            &bytes,
            &tracker,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, SyncHandshakeVerificationError::TooOld));
    }

    /// CounterpartyIdentityMismatch: verify_sync_response is
    /// supplied an `expected_responder_did` that does not match
    /// the responder's identity carried in the message.
    #[tokio::test]
    async fn verify_sync_response_returns_counterparty_identity_mismatch() {
        // Build a valid Accept response signed by responder A,
        // but verify against expected responder B.
        let (responder_a, sk_a) = make_initiator_identity(0x40);
        let resolver = handshake_test_resolver(&responder_a);
        let cfg = SyncHandshakeVerificationConfig::default();
        let session_id = SessionId::from_bytes([0x77; 32]);
        let scope = SyncRequestedScope {
            nsids: smallvec::SmallVec::new(),
            time_window: None,
            direction: crate::wire::SyncDirection::Bidirectional,
        };
        let at = SystemTime::now();
        let sign_input = crate::wire::accept_sign_input(
            &responder_a, SemVer::new(1, 0, 0), &session_id, &scope, at,
        );
        let sig = crate::wire::sign_handshake_payload(&sk_a, &sign_input);
        let accept = SyncChannelAccept {
            responder_identity: responder_a.clone(),
            responder_lexicon_set_version: SemVer::new(1, 0, 0),
            session_id,
            negotiated_scope: scope,
            responder_signature: sig,
            at,
        };
        let mut bytes = vec![0x00];
        bytes.extend(accept_to_wire_bytes(&accept));

        // Expected responder B (different DID).
        let did_b = Did::new("did:plc:differentresponder000").unwrap();

        let err = verify_sync_response(
            &bytes,
            &did_b,
            resolver.as_ref() as &dyn DidResolver,
            &cfg,
            deadline(),
            TraceId::from_bytes([0; 16]),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            SyncHandshakeVerificationError::CounterpartyIdentityMismatch
        ));
    }
}