exochain-node 0.2.1-beta

EXOCHAIN distributed node — single binary for joining and participating in the constitutional governance network
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
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Integration tests for the 0dentity module — §12.2.
//!
//! Per-module unit tests live in each sub-module's `#[cfg(test)]` block.
//! These tests exercise cross-module interactions: the complete onboarding arc,
//! HTTP handler behaviour, scoring consistency, and store contracts.
//!
//! All HTTP tests drive axum routers via `tower::ServiceExt::oneshot`.

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::module_inception)]
mod tests {
    use std::sync::Arc;

    use axum::{
        Router,
        body::Body,
        http::{Request, StatusCode, header},
    };
    use exo_core::{
        crypto::{self, KeyPair},
        hlc::HybridClock,
        types::{Did, Hash256, PublicKey, SecretKey, Signature},
    };
    use rand::{SeedableRng, rngs::StdRng};
    use serde_json::Value;
    use tower::ServiceExt;

    use crate::zerodentity::{
        ClaimStatus, ClaimType, IdentityClaim, IdentitySession, OTP_MAX_ATTEMPTS, OtpChallenge,
        OtpChannel, OtpState, PolarAxes, ZerodentityScore,
        api::{ApiState, zerodentity_api_router},
        attestation::{attestation_signing_payload, target_claim_id},
        onboarding::{OnboardingState, onboarding_router},
        scoring::compute_symmetry,
        store::{SharedZerodentityStore, ZerodentityStore, new_shared_store},
        types::{
            AttestationType, BehavioralSample, BehavioralSignalType, DeviceFingerprint,
            FingerprintSignal, IDENTITY_SESSION_TTL_MS,
        },
    };

    // -----------------------------------------------------------------------
    // Test helpers
    // -----------------------------------------------------------------------

    const API_TEST_NOW_MS: u64 = 1_001_000;

    fn td(id: &str) -> Did {
        Did::new(&format!("did:exo:{id}")).unwrap()
    }

    fn h(tag: &str) -> Hash256 {
        Hash256::digest(tag.as_bytes())
    }

    #[test]
    fn module_doc_retains_device_behavioral_axes_audit_status() {
        let src = include_str!("mod.rs");
        assert!(
            src.contains("# Audit status"),
            "module doc must retain the R3 audit-status section"
        );
        assert!(
            src.contains("unaudited-zerodentity-device-behavioral-axes"),
            "module doc must name the R3 feature flag"
        );
        assert!(
            src.contains("fix-onyx-4-r3-unwired-axes.md"),
            "module doc must point at the R3 initiative"
        );
    }

    fn seeded_rng(seed: u64) -> StdRng {
        StdRng::seed_from_u64(seed)
    }

    fn keypair(seed: u8) -> (PublicKey, SecretKey) {
        let pair = crypto::KeyPair::from_secret_bytes([seed; 32]).unwrap();
        (*pair.public_key(), pair.secret_key().clone())
    }

    fn signed_attest_body(
        attester: &Did,
        target: &Did,
        attestation_type: AttestationType,
        message_hash: Option<Hash256>,
        created_ms: u64,
        public_key: &PublicKey,
        secret_key: &SecretKey,
    ) -> serde_json::Value {
        let payload = attestation_signing_payload(
            attester,
            target,
            &attestation_type,
            message_hash.as_ref(),
            created_ms,
        )
        .unwrap();
        let signature = crypto::sign(&payload, secret_key);
        serde_json::json!({
            "target_did": target.as_str(),
            "attestation_type": attestation_type.to_string(),
            "message_hash": message_hash.map(|h| hex::encode(h.as_bytes())),
            "created_ms": created_ms,
            "attester_public_key": hex::encode(public_key.as_bytes()),
            "signature": hex::encode(signature.to_bytes())
        })
    }

    fn make_claim(did: &Did, ct: ClaimType, status: ClaimStatus, ms: u64) -> IdentityClaim {
        let key = format!("{ct:?}-{ms}");
        let verified_ms = if status == ClaimStatus::Verified {
            Some(ms + 500)
        } else {
            None
        };
        IdentityClaim {
            claim_hash: h(&key),
            subject_did: did.clone(),
            claim_type: ct,
            status,
            created_ms: ms,
            verified_ms,
            expires_ms: None,
            signature: Signature::Empty,
            dag_node_hash: h(&format!("dag-{key}")),
        }
    }

    fn make_signed_claim(
        did: &Did,
        ct: ClaimType,
        status: ClaimStatus,
        ms: u64,
        signature: Signature,
    ) -> IdentityClaim {
        let mut claim = make_claim(did, ct, status, ms);
        claim.signature = signature;
        claim
    }

    fn make_fingerprint(tag: &str, captured_ms: u64) -> DeviceFingerprint {
        let mut signal_hashes = std::collections::BTreeMap::new();
        signal_hashes.insert(FingerprintSignal::UserAgent, h(&format!("{tag}-ua")));
        DeviceFingerprint {
            composite_hash: h(&format!("{tag}-composite")),
            signal_hashes,
            captured_ms,
            consistency_score_bp: Some(8_000),
        }
    }

    fn make_behavioral_sample(
        tag: &str,
        signal_type: BehavioralSignalType,
        captured_ms: u64,
    ) -> BehavioralSample {
        BehavioralSample {
            sample_hash: h(&format!("{tag}-sample")),
            signal_type,
            captured_ms,
            baseline_similarity_bp: Some(7_500),
        }
    }

    fn make_session(did: &Did, token: &str, ms: u64) -> IdentitySession {
        make_session_with_public_key(did, token, ms, vec![])
    }

    fn make_session_with_public_key(
        did: &Did,
        token: &str,
        ms: u64,
        public_key: Vec<u8>,
    ) -> IdentitySession {
        IdentitySession {
            session_token: token.to_owned(),
            subject_did: did.clone(),
            public_key,
            created_ms: ms,
            last_active_ms: ms,
            revoked: false,
        }
    }

    fn test_keypair(seed: u8) -> KeyPair {
        KeyPair::from_secret_bytes([seed; 32]).unwrap()
    }

    fn bootstrap_verify_body(
        challenge_id: &str,
        code: &str,
        subject_did: &Did,
        keypair: &KeyPair,
    ) -> Value {
        let payload = crate::zerodentity::session_auth::bootstrap_signing_payload(
            challenge_id,
            subject_did,
            keypair.public_key(),
        )
        .unwrap();
        let signature = keypair.sign(&payload);
        serde_json::json!({
            "challenge_id": challenge_id,
            "code": code,
            "public_key": hex::encode(keypair.public_key().as_bytes()),
            "bootstrap_signature": hex::encode(signature.to_bytes())
        })
    }

    fn derived_did(keypair: &KeyPair) -> Did {
        crate::zerodentity::session_auth::did_from_public_key(keypair.public_key()).unwrap()
    }

    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    fn signed_claim_body(
        subject_did: &Did,
        claim_type: &str,
        provider: Option<&str>,
        verification_channel: Option<&str>,
        created_ms: u64,
        public_keypair: &KeyPair,
        signing_keypair: &KeyPair,
    ) -> Value {
        let payload = crate::zerodentity::session_auth::claim_submission_signing_payload(
            subject_did,
            claim_type,
            provider,
            verification_channel,
            created_ms,
            public_keypair.public_key(),
        )
        .unwrap();
        let signature = signing_keypair.sign(&payload);
        serde_json::json!({
            "subject_did": subject_did.as_str(),
            "claim_type": claim_type,
            "provider": provider,
            "verification_channel": verification_channel,
            "created_ms": created_ms,
            "public_key": hex::encode(public_keypair.public_key().as_bytes()),
            "signature": hex::encode(signature.to_bytes())
        })
    }

    fn request_signature_headers(
        method: &str,
        uri: &str,
        token: &str,
        nonce: &str,
        body: &[u8],
        keypair: &KeyPair,
    ) -> (String, String) {
        let body_hash = Hash256::digest(body);
        let payload = crate::zerodentity::session_auth::request_signing_payload(
            method, uri, token, nonce, &body_hash,
        )
        .unwrap();
        let signature = keypair.sign(&payload);
        (nonce.to_owned(), hex::encode(signature.to_bytes()))
    }

    fn make_score(did: &Did, bp: u32, ms: u64) -> ZerodentityScore {
        ZerodentityScore {
            subject_did: did.clone(),
            axes: PolarAxes {
                communication: bp,
                credential_depth: bp,
                device_trust: bp,
                behavioral_signature: bp,
                network_reputation: bp,
                temporal_stability: bp,
                cryptographic_strength: bp,
                constitutional_standing: bp,
            },
            composite: bp,
            computed_ms: ms,
            dag_state_hash: h("state"),
            claim_count: 1,
            symmetry: 10_000,
        }
    }

    fn onboarding_app(store: SharedZerodentityStore) -> Router {
        onboarding_app_with_fixed_clock(store, API_TEST_NOW_MS)
    }

    fn onboarding_app_with_fixed_clock(store: SharedZerodentityStore, now_ms: u64) -> Router {
        onboarding_router(OnboardingState::new_with_clock(
            store,
            HybridClock::with_wall_clock(move || now_ms),
        ))
    }

    fn api_app(store: SharedZerodentityStore) -> Router {
        configure_test_receipt_signer(&store);
        zerodentity_api_router(ApiState::new_with_clock(
            store,
            HybridClock::with_wall_clock(|| API_TEST_NOW_MS),
        ))
    }

    fn configure_test_receipt_signer(store: &SharedZerodentityStore) {
        let keypair = KeyPair::from_secret_bytes([37u8; 32]).unwrap();
        let signer = Arc::new(move |payload: &[u8]| keypair.sign(payload));
        store
            .lock()
            .unwrap()
            .set_receipt_signer(td("test-node"), signer);
    }

    async fn post_json(app: &Router, uri: &str, body: Value) -> axum::response::Response {
        let req = Request::builder()
            .method("POST")
            .uri(uri)
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(body.to_string()))
            .unwrap();
        app.clone().oneshot(req).await.unwrap()
    }

    async fn get_req(app: &Router, uri: &str) -> axum::response::Response {
        let req = Request::builder()
            .method("GET")
            .uri(uri)
            .body(Body::empty())
            .unwrap();
        app.clone().oneshot(req).await.unwrap()
    }

    async fn get_with_auth(app: &Router, uri: &str, token: &str) -> axum::response::Response {
        let req = Request::builder()
            .method("GET")
            .uri(uri)
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();
        app.clone().oneshot(req).await.unwrap()
    }

    async fn body_json(resp: axum::response::Response) -> Value {
        let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
            .await
            .unwrap();
        serde_json::from_slice(&bytes).unwrap()
    }

    // -----------------------------------------------------------------------
    // §12.2.1 — Scoring integration
    // -----------------------------------------------------------------------

    #[test]
    fn score_email_only_gives_3500_communication() {
        let did = td("score-01");
        let claims = vec![make_claim(
            &did,
            ClaimType::Email,
            ClaimStatus::Verified,
            1_000,
        )];
        let score = ZerodentityScore::compute(&did, &claims, &[], &[], 1_000_000);
        assert_eq!(score.axes.communication, 3_500);
    }

    #[test]
    fn score_phone_only_gives_3700_communication() {
        let did = td("score-02");
        let claims = vec![make_claim(
            &did,
            ClaimType::Phone,
            ClaimStatus::Verified,
            1_000,
        )];
        let score = ZerodentityScore::compute(&did, &claims, &[], &[], 1_000_000);
        assert_eq!(score.axes.communication, 3_700);
    }

    #[test]
    fn score_email_and_phone_gives_8700_communication() {
        let did = td("score-03");
        let claims = vec![
            make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            make_claim(&did, ClaimType::Phone, ClaimStatus::Verified, 2_000),
        ];
        let score = ZerodentityScore::compute(&did, &claims, &[], &[], 1_000_000);
        assert_eq!(score.axes.communication, 8_700, "3500+3700+1500=8700");
    }

    #[test]
    fn score_pending_claims_contribute_nothing_to_communication() {
        let did = td("score-04");
        let claims = vec![
            make_claim(&did, ClaimType::Email, ClaimStatus::Pending, 1_000),
            make_claim(&did, ClaimType::Phone, ClaimStatus::Pending, 2_000),
        ];
        let score = ZerodentityScore::compute(&did, &claims, &[], &[], 1_000_000);
        assert_eq!(score.axes.communication, 0);
    }

    #[test]
    fn score_composite_is_mean_of_axes() {
        let did = td("score-05");
        let claims = vec![
            make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            make_claim(&did, ClaimType::GovernmentId, ClaimStatus::Verified, 2_000),
        ];
        let score = ZerodentityScore::compute(&did, &claims, &[], &[], 5_000_000);
        let expected = score.axes.as_array().iter().copied().sum::<u32>() / 8;
        assert_eq!(score.composite, expected, "composite = mean(8 axes)");
    }

    #[test]
    fn score_is_fully_deterministic() {
        let did = td("score-06");
        let claims = vec![
            make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            make_claim(&did, ClaimType::GovernmentId, ClaimStatus::Verified, 2_000),
        ];
        let s1 = ZerodentityScore::compute(&did, &claims, &[], &[], 5_000_000);
        let s2 = ZerodentityScore::compute(&did, &claims, &[], &[], 5_000_000);
        assert_eq!(s1.composite, s2.composite);
        assert_eq!(s1.symmetry, s2.symmetry);
        assert_eq!(s1.dag_state_hash, s2.dag_state_hash);
    }

    #[test]
    fn score_claim_count_counts_only_verified() {
        let did = td("score-07");
        let claims = vec![
            make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            make_claim(&did, ClaimType::Phone, ClaimStatus::Pending, 2_000),
            make_claim(&did, ClaimType::DisplayName, ClaimStatus::Verified, 3_000),
        ];
        let score = ZerodentityScore::compute(&did, &claims, &[], &[], 5_000_000);
        assert_eq!(score.claim_count, 2, "only Verified claims counted");
    }

    #[test]
    fn score_zero_claims_gives_base_axes() {
        let did = td("score-08");
        // No claims — axes should reflect their base values (some have non-zero bases)
        let score = ZerodentityScore::compute(&did, &[], &[], &[], 1_000_000);
        // communication=0 (no email/phone), credential_depth=0, device_trust=0, behavioral=0
        assert_eq!(score.axes.communication, 0);
        assert_eq!(score.axes.device_trust, 0);
        assert_eq!(score.axes.behavioral_signature, 0);
        // network_reputation has base 1000, constitutional_standing has base 1000
        assert_eq!(score.axes.network_reputation, 1_000);
        assert_eq!(score.axes.constitutional_standing, 1_000);
    }

    #[test]
    fn score_dag_state_hash_unique_per_claim_set() {
        let did = td("score-09");
        let s1 = ZerodentityScore::compute(
            &did,
            &[make_claim(
                &did,
                ClaimType::Email,
                ClaimStatus::Verified,
                1_000,
            )],
            &[],
            &[],
            1_000_000,
        );
        let s2 = ZerodentityScore::compute(
            &did,
            &[
                make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
                make_claim(&did, ClaimType::Phone, ClaimStatus::Verified, 2_000),
            ],
            &[],
            &[],
            1_000_000,
        );
        assert_ne!(
            s1.dag_state_hash, s2.dag_state_hash,
            "different claims → different dag_state_hash"
        );
    }

    // -----------------------------------------------------------------------
    // §12.2.2 — Symmetry index
    // -----------------------------------------------------------------------

    #[test]
    fn symmetry_all_equal_axes_is_10000() {
        assert_eq!(compute_symmetry(&[5_000u32; 8]), 10_000);
    }

    #[test]
    fn symmetry_all_zero_is_zero() {
        assert_eq!(compute_symmetry(&[0u32; 8]), 0);
    }

    #[test]
    fn symmetry_highly_skewed_is_low() {
        let mut axes = [0u32; 8];
        axes[0] = 10_000;
        assert!(
            compute_symmetry(&axes) < 3_000,
            "one dominant axis → low symmetry"
        );
    }

    #[test]
    fn symmetry_slight_imbalance_is_high() {
        // One axis slightly off — symmetry should still be high
        let mut axes = [5_000u32; 8];
        axes[0] = 5_100;
        assert!(
            compute_symmetry(&axes) > 8_000,
            "slight imbalance → high symmetry"
        );
    }

    // -----------------------------------------------------------------------
    // §12.2.3 — Store + Scoring integration
    // -----------------------------------------------------------------------

    #[test]
    fn store_score_roundtrip_and_history() {
        let did = td("store-01");
        let mut store = ZerodentityStore::new();

        store.put_score(make_score(&did, 3_000, 1_000_000)).unwrap();
        store.put_score(make_score(&did, 5_000, 2_000_000)).unwrap();

        assert_eq!(store.get_score(&did).unwrap().composite, 5_000);
        assert_eq!(store.get_previous_score(&did).unwrap().composite, 3_000);

        let history = store.get_score_history(&did, None, None).unwrap();
        assert_eq!(history.len(), 2);
        assert_eq!(history[0].composite, 3_000);
        assert_eq!(history[1].composite, 5_000);
    }

    #[test]
    fn store_100_other_dids_do_not_bleed_into_target() {
        let mut store = ZerodentityStore::new();
        let target = td("target-isolated");

        for i in 0..100u32 {
            store
                .put_score(make_score(&td(&format!("noise-{i}")), i * 100, 1_000_000))
                .unwrap();
        }

        assert!(store.get_score(&target).is_none());
        assert_eq!(store.get_claims(&target).unwrap(), vec![]);
    }

    #[test]
    fn store_score_history_time_filter_works() {
        let did = td("store-02");
        let mut store = ZerodentityStore::new();

        for (bp, ms) in [(1_000u32, 1_000u64), (2_000, 5_000), (3_000, 10_000)] {
            let mut s = make_score(&did, bp, ms);
            s.computed_ms = ms;
            store.put_score(s).unwrap();
        }

        let filtered = store
            .get_score_history(&did, Some(2_000), Some(8_000))
            .unwrap();
        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].composite, 2_000);
    }

    #[test]
    fn store_otp_challenge_full_lifecycle() {
        let did = td("store-otp-01");
        let mut store = ZerodentityStore::new();
        let mut rng = seeded_rng(0xDEAD_BEEF);

        let (challenge, code) =
            OtpChallenge::new(&did, OtpChannel::Email, 1_000_000, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();

        store.insert_otp_challenge(&challenge).unwrap();

        let retrieved = store.get_otp_challenge(&cid).unwrap().unwrap();
        assert_eq!(retrieved.state, OtpState::Pending);

        let mut to_verify = retrieved;
        let result = to_verify.verify(&code, 1_001_000);
        assert_eq!(result, crate::zerodentity::OtpResult::Success);
        assert_eq!(to_verify.state, OtpState::Verified);

        store.update_otp_challenge(&to_verify).unwrap();

        let final_state = store.get_otp_challenge(&cid).unwrap().unwrap();
        assert_eq!(final_state.state, OtpState::Verified);
    }

    #[test]
    fn store_session_revoke_hides_session() {
        let did = td("store-session-01");
        let mut store = ZerodentityStore::new();
        let token = "revoke-test-token";

        store
            .insert_session(&make_session(&did, token, 1_000_000))
            .unwrap();
        assert!(store.get_session(token, 1_000_001).unwrap().is_some());

        let mut revoked = make_session(&did, token, 1_000_000);
        revoked.revoked = true;
        store.insert_session(&revoked).unwrap();

        assert!(
            store.get_session(token, 1_000_001).unwrap().is_none(),
            "revoked session must be hidden"
        );
    }

    #[test]
    fn store_session_expiry_hides_session_at_deadline() {
        let did = td("store-session-expiry");
        let mut store = ZerodentityStore::new();
        let token = "expired-test-token";
        let created_ms = 1_000_000;

        store
            .insert_session(&make_session(&did, token, created_ms))
            .unwrap();

        assert!(
            store
                .get_session(token, created_ms + IDENTITY_SESSION_TTL_MS - 1)
                .unwrap()
                .is_some(),
            "session must remain active before its absolute expiry deadline"
        );
        assert!(
            store
                .get_session(token, created_ms + IDENTITY_SESSION_TTL_MS)
                .unwrap()
                .is_none(),
            "session must be hidden at its absolute expiry deadline"
        );
    }

    #[test]
    fn store_session_expiry_fails_closed_on_deadline_overflow() {
        let did = td("store-session-overflow");
        let mut store = ZerodentityStore::new();
        let token = "overflow-test-token";
        let created_ms = u64::MAX - 1;

        store
            .insert_session(&make_session(&did, token, created_ms))
            .unwrap();

        assert!(
            store.get_session(token, created_ms).unwrap().is_none(),
            "session expiry arithmetic overflow must not create an immortal session"
        );
    }

    #[test]
    fn store_session_lookup_hides_future_created_sessions() {
        let did = td("store-session-future");
        let mut store = ZerodentityStore::new();
        let token = "future-session-token";
        let created_ms = 2_000_000;

        store
            .insert_session(&make_session(&did, token, created_ms))
            .unwrap();

        assert!(
            store.get_session(token, created_ms - 1).unwrap().is_none(),
            "sessions with future creation timestamps must fail closed"
        );
    }

    #[test]
    fn store_claims_slice_matches_tuple_vec() {
        let did = td("store-claims-01");
        let mut store = ZerodentityStore::new();

        store
            .insert_claim(
                "c1",
                &make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
        store
            .insert_claim(
                "c2",
                &make_claim(&did, ClaimType::Phone, ClaimStatus::Pending, 2_000),
            )
            .unwrap();

        let tuples = store.get_claims(&did).unwrap();
        let slice = store.get_claims_slice(&did).unwrap();
        assert_eq!(tuples.len(), slice.len());
        for ((_, c_t), c_s) in tuples.iter().zip(slice.iter()) {
            assert_eq!(c_t.claim_type, c_s.claim_type);
        }
    }

    #[test]
    fn store_get_claims_returns_canonical_created_ms_order() {
        let did = td("store-claims-canonical-order");
        let mut store = ZerodentityStore::new();

        store
            .insert_claim(
                "newer",
                &make_claim(&did, ClaimType::Phone, ClaimStatus::Verified, 2_000),
            )
            .unwrap();
        store
            .insert_claim(
                "older",
                &make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();

        let claim_ids: Vec<String> = store
            .get_claims(&did)
            .unwrap()
            .into_iter()
            .map(|(claim_id, _)| claim_id)
            .collect();

        assert_eq!(claim_ids, vec!["older".to_owned(), "newer".to_owned()]);
    }

    #[test]
    fn store_get_fingerprints_returns_canonical_captured_ms_order() {
        let did = td("store-fingerprints-canonical-order");
        let mut store = ZerodentityStore::new();

        store
            .put_fingerprint(&did, make_fingerprint("newer", 2_000))
            .unwrap();
        store
            .put_fingerprint(&did, make_fingerprint("older", 1_000))
            .unwrap();

        let captured: Vec<u64> = store
            .get_fingerprints(&did)
            .unwrap()
            .into_iter()
            .map(|fingerprint| fingerprint.captured_ms)
            .collect();

        assert_eq!(captured, vec![1_000, 2_000]);
    }

    #[test]
    fn store_get_behavioral_samples_returns_canonical_captured_ms_order() {
        let did = td("store-behavioral-canonical-order");
        let mut store = ZerodentityStore::new();

        store
            .put_behavioral(
                &did,
                make_behavioral_sample("newer", BehavioralSignalType::MouseDynamics, 2_000),
            )
            .unwrap();
        store
            .put_behavioral(
                &did,
                make_behavioral_sample("older", BehavioralSignalType::KeystrokeDynamics, 1_000),
            )
            .unwrap();

        let captured: Vec<u64> = store
            .get_behavioral_samples(&did)
            .unwrap()
            .into_iter()
            .map(|sample| sample.captured_ms)
            .collect();

        assert_eq!(captured, vec![1_000, 2_000]);
    }

    // -----------------------------------------------------------------------
    // §12.2.4 — Onboarding HTTP handlers
    // -----------------------------------------------------------------------

    #[tokio::test]
    #[cfg(not(feature = "unaudited-zerodentity-first-touch-onboarding"))]
    async fn submit_claim_refused_without_first_touch_feature_flag() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let did = td("onb-gated-default");

        let resp = post_json(
            &app,
            "/api/v1/0dentity/claims",
            serde_json::json!({
                "subject_did": did.as_str(),
                "claim_type": "DisplayName"
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let body = body_json(resp).await;
        assert_eq!(
            body["feature_flag"],
            "unaudited-zerodentity-first-touch-onboarding"
        );
        assert!(
            body["message"]
                .as_str()
                .is_some_and(|text| text.contains("fix-onyx-4-r1-onboarding-auth.md")),
            "refusal body must point at the R1 initiative: {body}"
        );
        assert!(
            store.lock().unwrap().get_claims(&did).unwrap().is_empty(),
            "default-off refusal must not persist a claim"
        );
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_returns_200_and_claim_id() {
        let app = onboarding_app(new_shared_store());
        let keypair = test_keypair(30);
        let did = derived_did(&keypair);

        let resp = post_json(
            &app,
            "/api/v1/0dentity/claims",
            signed_claim_body(
                &did,
                "DisplayName",
                None,
                None,
                1_700_000_001,
                &keypair,
                &keypair,
            ),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["status"], "Pending");
        assert!(body["claim_id"].as_str().is_some_and(|s| !s.is_empty()));
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_invalid_did_returns_400() {
        let app = onboarding_app(new_shared_store());

        let resp = post_json(
            &app,
            "/api/v1/0dentity/claims",
            serde_json::json!({
                "subject_did": "not-a-valid-did",
                "claim_type": "Email"
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_unknown_type_returns_400() {
        let app = onboarding_app(new_shared_store());

        let resp = post_json(
            &app,
            "/api/v1/0dentity/claims",
            serde_json::json!({
                "subject_did": "did:exo:alice",
                "claim_type": "Nonexistent"
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_with_otp_channel_returns_challenge_id_and_ttl() {
        let app = onboarding_app(new_shared_store());
        let keypair = test_keypair(31);
        let did = derived_did(&keypair);

        let resp = post_json(
            &app,
            "/api/v1/0dentity/claims",
            signed_claim_body(
                &did,
                "Email",
                None,
                Some("Email"),
                1_700_000_002,
                &keypair,
                &keypair,
            ),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert!(body["challenge_id"].as_str().is_some_and(|s| !s.is_empty()));
        assert!(body["challenge_ttl_ms"].as_u64().is_some());
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_uses_node_hlc_for_otp_dispatch_time() {
        let store = new_shared_store();
        let app = onboarding_app_with_fixed_clock(store.clone(), API_TEST_NOW_MS);
        let keypair = test_keypair(132);
        let did = derived_did(&keypair);
        let signed_created_ms = API_TEST_NOW_MS + OtpChannel::Email.ttl_ms() + 86_400_000;

        let resp = post_json(
            &app,
            "/api/v1/0dentity/claims",
            signed_claim_body(
                &did,
                "Email",
                None,
                Some("Email"),
                signed_created_ms,
                &keypair,
                &keypair,
            ),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        let challenge_id = body["challenge_id"]
            .as_str()
            .expect("challenge id is returned");
        let store = store.lock().unwrap();
        let challenge = store
            .get_otp_challenge(challenge_id)
            .unwrap()
            .expect("challenge is stored");
        assert_eq!(challenge.dispatched_ms, API_TEST_NOW_MS);
        assert_ne!(challenge.dispatched_ms, signed_created_ms);

        let claims = store.get_claims(&did).unwrap();
        assert_eq!(claims.len(), 1);
        assert_eq!(claims[0].1.created_ms, signed_created_ms);
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_stores_claim_in_store() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let keypair = test_keypair(32);
        let did = derived_did(&keypair);
        let created_ms = 1_700_000_003;

        post_json(
            &app,
            "/api/v1/0dentity/claims",
            signed_claim_body(&did, "Phone", None, None, created_ms, &keypair, &keypair),
        )
        .await;

        let claims = store.lock().unwrap().get_claims(&did).unwrap();
        assert_eq!(claims.len(), 1);
        assert_eq!(claims[0].1.claim_type, ClaimType::Phone);
        assert_eq!(claims[0].1.created_ms, created_ms);
        assert!(!claims[0].1.signature.is_empty());
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_rejects_missing_proof_of_possession() {
        let app = onboarding_app(new_shared_store());
        let keypair = test_keypair(33);
        let did = derived_did(&keypair);

        let resp = post_json(
            &app,
            "/api/v1/0dentity/claims",
            serde_json::json!({
                "subject_did": did.as_str(),
                "claim_type": "DisplayName"
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_rejects_public_key_that_does_not_derive_subject_did() {
        let app = onboarding_app(new_shared_store());
        let keypair = test_keypair(34);
        let did = td("not-derived-from-key");

        let resp = post_json(
            &app,
            "/api/v1/0dentity/claims",
            signed_claim_body(
                &did,
                "DisplayName",
                None,
                None,
                1_700_000_004,
                &keypair,
                &keypair,
            ),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_rejects_wrong_key_signature() {
        let app = onboarding_app(new_shared_store());
        let keypair = test_keypair(35);
        let wrong_keypair = test_keypair(36);
        let did = derived_did(&keypair);

        let resp = post_json(
            &app,
            "/api/v1/0dentity/claims",
            signed_claim_body(
                &did,
                "DisplayName",
                None,
                None,
                1_700_000_005,
                &keypair,
                &wrong_keypair,
            ),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_rejects_tampered_signed_payload() {
        let app = onboarding_app(new_shared_store());
        let keypair = test_keypair(37);
        let did = derived_did(&keypair);
        let mut body = signed_claim_body(
            &did,
            "DisplayName",
            None,
            None,
            1_700_000_006,
            &keypair,
            &keypair,
        );
        body["claim_type"] = Value::String("Email".to_owned());

        let resp = post_json(&app, "/api/v1/0dentity/claims", body).await;

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_rejects_zero_signature() {
        let app = onboarding_app(new_shared_store());
        let keypair = test_keypair(38);
        let did = derived_did(&keypair);
        let mut body = signed_claim_body(
            &did,
            "DisplayName",
            None,
            None,
            1_700_000_007,
            &keypair,
            &keypair,
        );
        body["signature"] = Value::String(hex::encode([0u8; 64]));

        let resp = post_json(&app, "/api/v1/0dentity/claims", body).await;

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_rejects_replayed_submission() {
        let app = onboarding_app(new_shared_store());
        let keypair = test_keypair(39);
        let did = derived_did(&keypair);
        let body = signed_claim_body(
            &did,
            "DisplayName",
            None,
            None,
            1_700_000_008,
            &keypair,
            &keypair,
        );

        let first = post_json(&app, "/api/v1/0dentity/claims", body.clone()).await;
        let second = post_json(&app, "/api/v1/0dentity/claims", body).await;

        assert_eq!(first.status(), StatusCode::OK);
        assert_eq!(second.status(), StatusCode::CONFLICT);
    }

    #[tokio::test]
    async fn verify_otp_correct_code_returns_verified_and_session_token() {
        let store = new_shared_store();
        let app = onboarding_app_with_fixed_clock(store.clone(), 1_001_000);
        let keypair = test_keypair(1);
        let did = derived_did(&keypair);
        let dispatched_ms = 1_000_000;

        let mut rng = seeded_rng(0xCAFE_0001);
        let (challenge, code) =
            OtpChallenge::new(&did, OtpChannel::Email, dispatched_ms, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify",
            bootstrap_verify_body(&cid, &code, &did, &keypair),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["verified"], true);
        assert!(
            body["session_token"]
                .as_str()
                .is_some_and(|s| !s.is_empty())
        );
        let session_token = body["session_token"].as_str().unwrap();
        let session = store
            .lock()
            .unwrap()
            .get_session(session_token, 1_001_000)
            .unwrap()
            .unwrap();
        assert_eq!(session.public_key, keypair.public_key().as_bytes().to_vec());
    }

    #[tokio::test]
    async fn verify_otp_replay_after_success_returns_conflict() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let keypair = test_keypair(11);
        let did = derived_did(&keypair);
        let dispatched_ms = u64::MAX / 2;

        let mut rng = seeded_rng(0xCAFE_1020);
        let (challenge, code) =
            OtpChallenge::new(&did, OtpChannel::Email, dispatched_ms, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        let first = post_json(
            &app,
            "/api/v1/0dentity/verify",
            bootstrap_verify_body(&cid, &code, &did, &keypair),
        )
        .await;
        let second = post_json(
            &app,
            "/api/v1/0dentity/verify",
            bootstrap_verify_body(&cid, &code, &did, &keypair),
        )
        .await;

        assert_eq!(first.status(), StatusCode::OK);
        assert_eq!(second.status(), StatusCode::CONFLICT);
    }

    #[tokio::test]
    async fn verify_otp_success_without_bootstrap_signature_returns_400() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let did = td("otp-bootstrap-missing");
        let dispatched_ms = u64::MAX / 2;

        let mut rng = seeded_rng(0xCAFE_1010);
        let (challenge, code) =
            OtpChallenge::new(&did, OtpChannel::Email, dispatched_ms, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify",
            serde_json::json!({
                "challenge_id": cid,
                "code": code
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn verify_otp_success_rejects_wrong_bootstrap_key() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let keypair = test_keypair(2);
        let wrong_keypair = test_keypair(3);
        let did = derived_did(&keypair);
        let dispatched_ms = u64::MAX / 2;

        let mut rng = seeded_rng(0xCAFE_1011);
        let (challenge, code) =
            OtpChallenge::new(&did, OtpChannel::Email, dispatched_ms, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        let payload = crate::zerodentity::session_auth::bootstrap_signing_payload(
            &cid,
            &did,
            keypair.public_key(),
        )
        .unwrap();
        let wrong_signature = wrong_keypair.sign(&payload);

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify",
            serde_json::json!({
                "challenge_id": cid,
                "code": code,
                "public_key": hex::encode(keypair.public_key().as_bytes()),
                "bootstrap_signature": hex::encode(wrong_signature.to_bytes())
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn verify_otp_rejects_bootstrap_key_that_does_not_derive_subject_did() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let did = td("otp-bootstrap-unbound-key");
        let keypair = test_keypair(4);
        let dispatched_ms = u64::MAX / 2;

        let mut rng = seeded_rng(0xCAFE_1012);
        let (challenge, code) =
            OtpChallenge::new(&did, OtpChannel::Email, dispatched_ms, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify",
            bootstrap_verify_body(&cid, &code, &did, &keypair),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn verify_otp_wrong_code_returns_attempts_remaining() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let did = td("otp-wrong-01");
        let dispatched_ms = u64::MAX / 2;

        let mut rng = seeded_rng(0xCAFE_0002);
        let (challenge, _code) =
            OtpChallenge::new(&did, OtpChannel::Email, dispatched_ms, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify",
            serde_json::json!({
                "challenge_id": cid,
                "code": "000000"
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["verified"], false);
        assert_eq!(
            body["attempts_remaining"].as_u64().unwrap(),
            u64::from(OTP_MAX_ATTEMPTS - 1)
        );
    }

    #[tokio::test]
    async fn verify_otp_expired_challenge_returns_410() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let did = td("otp-expired-01");
        // dispatched_ms=0 → challenge expired when wall clock > 600_000ms (year 1970+10min)
        let dispatched_ms = 0u64;

        let mut rng = seeded_rng(0xCAFE_0003);
        let (challenge, _code) =
            OtpChallenge::new(&did, OtpChannel::Email, dispatched_ms, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify",
            serde_json::json!({
                "challenge_id": cid,
                "code": "123456"
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::GONE);
    }

    #[tokio::test]
    async fn verify_otp_not_found_returns_404() {
        let app = onboarding_app(new_shared_store());

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify",
            serde_json::json!({
                "challenge_id": "does-not-exist",
                "code": "000000"
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn verify_otp_lockout_after_max_attempts_returns_429() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let did = td("otp-lock-01");
        let dispatched_ms = u64::MAX / 2;

        let mut rng = seeded_rng(0xCAFE_0004);
        let (challenge, _code) =
            OtpChallenge::new(&did, OtpChannel::Email, dispatched_ms, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        for attempt in 0..OTP_MAX_ATTEMPTS {
            let resp = post_json(
                &app,
                "/api/v1/0dentity/verify",
                serde_json::json!({
                    "challenge_id": cid,
                    "code": "999999"
                }),
            )
            .await;

            if attempt < OTP_MAX_ATTEMPTS - 1 {
                assert_eq!(resp.status(), StatusCode::OK, "attempt {attempt}");
            } else {
                assert_eq!(
                    resp.status(),
                    StatusCode::TOO_MANY_REQUESTS,
                    "final attempt"
                );
            }
        }
    }

    #[tokio::test]
    async fn resend_otp_before_cooldown_returns_429() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let did = td("otp-resend-cooldown");
        // far-future dispatched_ms → wall clock < dispatched_ms + cooldown → resend blocked
        let dispatched_ms = u64::MAX / 2;

        let mut rng = seeded_rng(0xBEEF_0101);
        let (challenge, _) =
            OtpChallenge::new(&did, OtpChannel::Email, dispatched_ms, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify/resend",
            serde_json::json!({
                "challenge_id": cid
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
    }

    #[tokio::test]
    async fn resend_otp_after_cooldown_returns_new_challenge_id() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let did = td("otp-resend-ok");
        // dispatched_ms=0 → cooldown (60_000ms) already elapsed by wall clock
        let dispatched_ms = 0u64;

        let mut rng = seeded_rng(0xBEEF_0102);
        let (challenge, _) =
            OtpChallenge::new(&did, OtpChannel::Email, dispatched_ms, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify/resend",
            serde_json::json!({
                "challenge_id": cid
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        let new_cid = body["challenge_id"].as_str().unwrap().to_owned();
        assert_ne!(new_cid, cid, "resend must return a fresh challenge_id");
        assert!(body["ttl_ms"].as_u64().unwrap() > 0);
    }

    #[tokio::test]
    async fn resend_otp_after_cooldown_consumes_original_challenge() {
        let store = new_shared_store();
        let app = onboarding_app_with_fixed_clock(store.clone(), 120_000);
        let did = td("otp-resend-consumes-original");

        let mut rng = seeded_rng(0xBEEF_0103);
        let (challenge, _) = OtpChallenge::new(&did, OtpChannel::Email, 1, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify/resend",
            serde_json::json!({
                "challenge_id": cid
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        let new_cid = body["challenge_id"].as_str().unwrap();

        let guard = store.lock().unwrap();
        let original = guard.get_otp_challenge(&cid).unwrap().unwrap();
        let replacement = guard.get_otp_challenge(new_cid).unwrap().unwrap();
        assert_eq!(original.state, OtpState::Expired);
        assert_eq!(replacement.state, OtpState::Pending);
    }

    #[tokio::test]
    async fn resend_otp_uses_injected_hlc_timestamp() {
        let store = new_shared_store();
        let app = onboarding_app_with_fixed_clock(store.clone(), 180_000);
        let did = td("otp-resend-clock");

        let mut rng = seeded_rng(0xBEEF_0104);
        let (challenge, _) = OtpChallenge::new(&did, OtpChannel::Email, 1, &mut rng).unwrap();
        let cid = challenge.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&challenge)
            .unwrap();

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify/resend",
            serde_json::json!({
                "challenge_id": cid
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        let new_cid = body["challenge_id"].as_str().unwrap();
        let replacement = store
            .lock()
            .unwrap()
            .get_otp_challenge(new_cid)
            .unwrap()
            .unwrap();

        assert_eq!(replacement.dispatched_ms, 180_000);
    }

    #[tokio::test]
    async fn resend_otp_not_found_returns_404() {
        let app = onboarding_app(new_shared_store());

        let resp = post_json(
            &app,
            "/api/v1/0dentity/verify/resend",
            serde_json::json!({
                "challenge_id": "ghost-challenge"
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    // -----------------------------------------------------------------------
    // §12.2.5 — API HTTP handlers
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn get_score_unknown_did_returns_404() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("nobody");
        let token = "score-unknown-session-token";

        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&did, token, 1_000_000))
            .unwrap();

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/score", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn get_score_without_auth_returns_401() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-score-noauth");

        store
            .lock()
            .unwrap()
            .insert_claim(
                "c1",
                &make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();

        let resp = get_req(&app, &format!("/api/v1/0dentity/{}/score", did.as_str())).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn get_score_wrong_did_session_returns_403() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let alice = td("api-score-403-alice");
        let bob = td("api-score-403-bob");
        let bob_token = "score-bob-session-token";

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "a-c1",
                &make_claim(&alice, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_session(&make_session(&bob, bob_token, 1_000_000))
                .unwrap();
        }

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/score", alice.as_str()),
            bob_token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn get_score_with_verified_email_phone_gives_8700_communication() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-score-01");
        let token = "score-session-token-01";

        {
            let mut s = store.lock().unwrap();
            s.insert_session(&make_session(&did, token, 1_000_000))
                .unwrap();
            s.insert_claim(
                "e1",
                &make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_claim(
                "p1",
                &make_claim(&did, ClaimType::Phone, ClaimStatus::Verified, 2_000),
            )
            .unwrap();
        }

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/score", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["axes"]["communication"].as_u64().unwrap(), 8_700);
        assert!(body["composite"].as_u64().unwrap() > 0);
        assert_eq!(body["claim_count"].as_u64().unwrap(), 2);
    }

    #[tokio::test]
    async fn get_score_without_as_of_uses_latest_evidence_timestamp() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-score-evidence-time");
        let token = "score-session-evidence-time";

        {
            let mut s = store.lock().unwrap();
            s.insert_session(&make_session(&did, token, 1_000_000))
                .unwrap();
            s.insert_claim(
                "e1",
                &make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_claim(
                "p1",
                &make_claim(&did, ClaimType::Phone, ClaimStatus::Verified, 2_000),
            )
            .unwrap();
        }

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/score", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["computed_ms"].as_u64().unwrap(), 2_500);
    }

    #[tokio::test]
    async fn get_score_with_as_of_uses_caller_supplied_timestamp() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-score-explicit-time");
        let token = "score-session-explicit-time";

        {
            let mut s = store.lock().unwrap();
            s.insert_session(&make_session(&did, token, 1_000_000))
                .unwrap();
            s.insert_claim(
                "c1",
                &make_claim(&did, ClaimType::DisplayName, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
        }

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/score?as_of_ms=123456", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["computed_ms"].as_u64().unwrap(), 123_456);
    }

    #[tokio::test]
    async fn get_score_rejects_zero_as_of_timestamp() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-score-zero-time");
        let token = "score-session-zero-time";

        {
            let mut s = store.lock().unwrap();
            s.insert_session(&make_session(&did, token, 1_000_000))
                .unwrap();
            s.insert_claim(
                "c1",
                &make_claim(&did, ClaimType::DisplayName, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
        }

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/score?as_of_ms=0", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let body = body_json(resp).await;
        assert_eq!(
            body["error"].as_str().unwrap(),
            "as_of_ms must be greater than 0"
        );
    }

    #[tokio::test]
    async fn get_score_is_invariant_to_claim_insertion_order() {
        let did = td("api-score-canonical-order");
        let token = "score-session-canonical-order";
        let older_post_quantum = make_signed_claim(
            &did,
            ClaimType::Email,
            ClaimStatus::Verified,
            1_000,
            Signature::PostQuantum(vec![9; 64]),
        );
        let newer_ed25519 = make_signed_claim(
            &did,
            ClaimType::Phone,
            ClaimStatus::Verified,
            2_000,
            Signature::Ed25519([8; 64]),
        );

        let ordered_store = new_shared_store();
        {
            let mut s = ordered_store.lock().unwrap();
            s.insert_session(&make_session(&did, token, 1_000_000))
                .unwrap();
            s.insert_claim("older", &older_post_quantum).unwrap();
            s.insert_claim("newer", &newer_ed25519).unwrap();
        }
        let ordered_app = api_app(ordered_store);

        let reversed_store = new_shared_store();
        {
            let mut s = reversed_store.lock().unwrap();
            s.insert_session(&make_session(&did, token, 1_000_000))
                .unwrap();
            s.insert_claim("newer", &newer_ed25519).unwrap();
            s.insert_claim("older", &older_post_quantum).unwrap();
        }
        let reversed_app = api_app(reversed_store);

        let ordered_resp = get_with_auth(
            &ordered_app,
            &format!("/api/v1/0dentity/{}/score", did.as_str()),
            token,
        )
        .await;
        let reversed_resp = get_with_auth(
            &reversed_app,
            &format!("/api/v1/0dentity/{}/score", did.as_str()),
            token,
        )
        .await;

        assert_eq!(ordered_resp.status(), StatusCode::OK);
        assert_eq!(reversed_resp.status(), StatusCode::OK);
        let ordered_body = body_json(ordered_resp).await;
        let reversed_body = body_json(reversed_resp).await;

        assert_eq!(
            ordered_body["axes"]["cryptographic_strength"],
            reversed_body["axes"]["cryptographic_strength"]
        );
        assert_eq!(
            ordered_body["axes"]["cryptographic_strength"]
                .as_u64()
                .unwrap(),
            4_000
        );
    }

    #[tokio::test]
    async fn get_score_includes_dag_state_hash_hex() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-score-02");
        let token = "score-session-dag-hash";

        {
            let mut s = store.lock().unwrap();
            s.insert_session(&make_session(&did, token, 1_000_000))
                .unwrap();
            s.insert_claim(
                "c1",
                &make_claim(&did, ClaimType::DisplayName, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
        }

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/score", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        let hash_str = body["dag_state_hash"].as_str().unwrap();
        // BLAKE3 → 32 bytes → 64 hex chars
        assert_eq!(hash_str.len(), 64, "dag_state_hash should be 64 hex chars");
    }

    #[tokio::test]
    async fn list_claims_without_auth_returns_401() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-claims-noauth");

        store
            .lock()
            .unwrap()
            .insert_claim(
                "c1",
                &make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();

        let resp = get_req(&app, &format!("/api/v1/0dentity/{}/claims", did.as_str())).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn list_claims_with_valid_session_returns_claims() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-claims-ok");
        let token = "valid-session-token-abc";

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "c1",
                &make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_claim(
                "c2",
                &make_claim(&did, ClaimType::Phone, ClaimStatus::Pending, 2_000),
            )
            .unwrap();
            s.insert_session(&make_session(&did, token, 1_000_000))
                .unwrap();
        }

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/claims", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["total"].as_u64().unwrap(), 2);
        assert_eq!(body["offset"].as_u64().unwrap(), 0);
    }

    #[tokio::test]
    async fn list_claims_wrong_did_session_returns_403() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let alice = td("api-403-alice");
        let bob = td("api-403-bob");
        let bob_token = "bob-session-token";

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "a-c1",
                &make_claim(&alice, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_session(&make_session(&bob, bob_token, 1_000_000))
                .unwrap();
        }

        // Bob's token cannot access Alice's claims
        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/claims", alice.as_str()),
            bob_token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn score_history_empty_did_returns_empty_snapshots() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("no-history");
        let token = "history-empty-session-token";

        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&did, token, 1_000_000))
            .unwrap();

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/score/history", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(body["snapshots"].as_array().unwrap().len(), 0);
    }

    #[tokio::test]
    async fn score_history_without_auth_returns_401() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-history-noauth");

        store
            .lock()
            .unwrap()
            .put_score(make_score(&did, 4_000, 1_000))
            .unwrap();

        let resp = get_req(
            &app,
            &format!("/api/v1/0dentity/{}/score/history", did.as_str()),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn score_history_wrong_did_session_returns_403() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let alice = td("api-history-403-alice");
        let bob = td("api-history-403-bob");
        let bob_token = "history-bob-session-token";

        {
            let mut s = store.lock().unwrap();
            s.put_score(make_score(&alice, 4_000, 1_000)).unwrap();
            s.insert_session(&make_session(&bob, bob_token, 1_000_000))
                .unwrap();
        }

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/score/history", alice.as_str()),
            bob_token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn score_history_is_chronological_and_complete() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-history-01");
        let token = "history-session-token-01";

        {
            let mut s = store.lock().unwrap();
            s.insert_session(&make_session(&did, token, 1_000_000))
                .unwrap();
            for (bp, ms) in [(1_000u32, 1_000u64), (3_000, 5_000), (6_000, 9_000)] {
                let mut score = make_score(&did, bp, ms);
                score.computed_ms = ms;
                s.put_score(score).unwrap();
            }
        }

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/score/history", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        let snaps = body["snapshots"].as_array().unwrap();
        assert_eq!(snaps.len(), 3);
        // Timestamps must be non-decreasing
        let times: Vec<u64> = snaps
            .iter()
            .map(|s| s["computed_ms"].as_u64().unwrap())
            .collect();
        assert!(
            times.windows(2).all(|w| w[0] <= w[1]),
            "history must be chronological"
        );
    }

    #[cfg(not(feature = "unaudited-zerodentity-device-behavioral-axes"))]
    #[tokio::test]
    async fn list_fingerprints_refused_without_device_behavioral_feature_flag() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-fp-gated");
        let token = "fp-gated-session-token";

        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&did, token, 1_000_000))
            .unwrap();

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/fingerprints", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        let body = body_json(resp).await;
        assert_eq!(
            body["feature_flag"],
            "unaudited-zerodentity-device-behavioral-axes"
        );
        assert_eq!(body["initiative"], "fix-onyx-4-r3-unwired-axes.md");
    }

    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[tokio::test]
    async fn list_fingerprints_without_auth_returns_401() {
        let app = api_app(new_shared_store());

        let resp = get_req(&app, "/api/v1/0dentity/did:exo:fp-noauth/fingerprints").await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[tokio::test]
    async fn list_fingerprints_with_valid_session_returns_200() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-fp-ok");
        let token = "fp-session-token";

        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&did, token, 1_000_000))
            .unwrap();

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/fingerprints", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        // No fingerprints stored → empty list
        assert_eq!(body["fingerprints"].as_array().unwrap().len(), 0);
    }

    // -----------------------------------------------------------------------
    // §12.2.7 — peer attestation
    // -----------------------------------------------------------------------

    async fn post_with_auth(
        app: &Router,
        uri: &str,
        token: &str,
        body: serde_json::Value,
    ) -> axum::response::Response {
        let req = Request::builder()
            .method("POST")
            .uri(uri)
            .header(header::CONTENT_TYPE, "application/json")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .body(Body::from(body.to_string()))
            .unwrap();
        app.clone().oneshot(req).await.unwrap()
    }

    async fn post_with_signed_auth(
        app: &Router,
        uri: &str,
        token: &str,
        nonce: &str,
        body: serde_json::Value,
        keypair: &KeyPair,
    ) -> axum::response::Response {
        let body_bytes = body.to_string();
        let (nonce, signature) =
            request_signature_headers("POST", uri, token, nonce, body_bytes.as_bytes(), keypair);
        let req = Request::builder()
            .method("POST")
            .uri(uri)
            .header(header::CONTENT_TYPE, "application/json")
            .header(header::AUTHORIZATION, format!("Bearer {token}"))
            .header("x-exo-nonce", nonce)
            .header("x-exo-sig", signature)
            .body(Body::from(body_bytes))
            .unwrap();
        app.clone().oneshot(req).await.unwrap()
    }

    #[tokio::test]
    async fn attest_without_auth_returns_401() {
        let app = api_app(new_shared_store());
        let resp = post_json(
            &app,
            "/api/v1/0dentity/did:exo:attester/attest",
            serde_json::json!({
                "target_did": "did:exo:target",
                "attestation_type": "Identity"
            }),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn attest_invalid_attestation_type_returns_400() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let attester = td("attest-type-err");
        let token = "attest-type-token";
        let keypair = test_keypair(11);

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "e1",
                &make_claim(&attester, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_session(&make_session_with_public_key(
                &attester,
                token,
                1_000_000,
                keypair.public_key().as_bytes().to_vec(),
            ))
            .unwrap();
        }

        let uri = format!("/api/v1/0dentity/{}/attest", attester.as_str());
        let resp = post_with_signed_auth(
            &app,
            &uri,
            token,
            "nonce-invalid-type",
            serde_json::json!({
                "target_did": "did:exo:target",
                "attestation_type": "NotAType"
            }),
            &keypair,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn attest_write_without_session_signature_returns_401() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let attester = td("attest-nosig");
        let target = td("attest-nosig-target");
        let token = "attest-nosig-token";
        let keypair = test_keypair(12);

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "e1",
                &make_claim(&attester, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_session(&make_session_with_public_key(
                &attester,
                token,
                1_000_000,
                keypair.public_key().as_bytes().to_vec(),
            ))
            .unwrap();
        }

        let resp = post_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/attest", attester.as_str()),
            token,
            serde_json::json!({
                "target_did": target.as_str(),
                "attestation_type": "Identity"
            }),
        )
        .await;

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn attest_unsigned_body_returns_400() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let attester = td("attest-unsigned-a");
        let target = td("attest-unsigned-b");
        let token = "attest-unsigned-token";
        let keypair = test_keypair(18);

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "e1",
                &make_claim(&attester, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_session(&make_session_with_public_key(
                &attester,
                token,
                1_000_000,
                keypair.public_key().as_bytes().to_vec(),
            ))
            .unwrap();
        }

        let resp = post_with_signed_auth(
            &app,
            &format!("/api/v1/0dentity/{}/attest", attester.as_str()),
            token,
            "nonce-unsigned-body",
            serde_json::json!({
                "target_did": target.as_str(),
                "attestation_type": "Identity"
            }),
            &keypair,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn attest_signed_write_rejects_wrong_key() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let attester = td("attest-wrong-key-a");
        let target = td("attest-wrong-key-b");
        let token = "attest-wrong-key-token";
        let session_keypair = test_keypair(13);
        let wrong_keypair = test_keypair(14);

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "e1",
                &make_claim(&attester, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_session(&make_session_with_public_key(
                &attester,
                token,
                1_000_000,
                session_keypair.public_key().as_bytes().to_vec(),
            ))
            .unwrap();
        }

        let uri = format!("/api/v1/0dentity/{}/attest", attester.as_str());
        let resp = post_with_signed_auth(
            &app,
            &uri,
            token,
            "nonce-wrong-key",
            serde_json::json!({
                "target_did": target.as_str(),
                "attestation_type": "Identity"
            }),
            &wrong_keypair,
        )
        .await;

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn attest_wrong_public_key_returns_400() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let attester = td("attest-wrong-public-key-a");
        let target = td("attest-wrong-public-key-b");
        let token = "attest-wrong-public-key-token";
        let session_keypair = test_keypair(19);
        let (public_key, _) = keypair(45);
        let (_, signing_key) = keypair(46);

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "e1",
                &make_claim(&attester, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_session(&make_session_with_public_key(
                &attester,
                token,
                1_000_000,
                session_keypair.public_key().as_bytes().to_vec(),
            ))
            .unwrap();
        }

        let uri = format!("/api/v1/0dentity/{}/attest", attester.as_str());
        let resp = post_with_signed_auth(
            &app,
            &uri,
            token,
            "nonce-wrong-attestation-key",
            signed_attest_body(
                &attester,
                &target,
                AttestationType::Identity,
                None,
                1_236_000,
                &public_key,
                &signing_key,
            ),
            &session_keypair,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn attest_rejects_body_key_that_differs_from_authenticated_session_key() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let attester = td("attest-session-key-a");
        let target = td("attest-session-key-b");
        let token = "attest-session-key-token";
        let session_keypair = test_keypair(20);
        let (body_public_key, body_secret_key) = keypair(47);

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "e1",
                &make_claim(&attester, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_session(&make_session_with_public_key(
                &attester,
                token,
                1_000_000,
                session_keypair.public_key().as_bytes().to_vec(),
            ))
            .unwrap();
        }

        let uri = format!("/api/v1/0dentity/{}/attest", attester.as_str());
        let resp = post_with_signed_auth(
            &app,
            &uri,
            token,
            "nonce-body-key-session-mismatch",
            signed_attest_body(
                &attester,
                &target,
                AttestationType::Identity,
                None,
                1_236_500,
                &body_public_key,
                &body_secret_key,
            ),
            &session_keypair,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

        let guard = store.lock().unwrap();
        assert!(guard.get_claims(&target).unwrap().is_empty());
        assert!(guard.get_attestation(&attester, &target).unwrap().is_none());
    }

    #[tokio::test]
    async fn attest_valid_creates_attestation_201() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let attester = td("attest-ok-a");
        let target = td("attest-ok-b");
        let token = "attest-ok-token";
        let session_keypair = test_keypair(15);

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "e1",
                &make_claim(&attester, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_session(&make_session_with_public_key(
                &attester,
                token,
                1_000_000,
                session_keypair.public_key().as_bytes().to_vec(),
            ))
            .unwrap();
        }

        let uri = format!("/api/v1/0dentity/{}/attest", attester.as_str());
        let signed_created_ms = 1_234_000;
        let resp = post_with_signed_auth(
            &app,
            &uri,
            token,
            "nonce-valid-attest",
            signed_attest_body(
                &attester,
                &target,
                AttestationType::Identity,
                None,
                signed_created_ms,
                session_keypair.public_key(),
                session_keypair.secret_key(),
            ),
            &session_keypair,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::CREATED);
        let body = body_json(resp).await;
        assert!(
            body["attestation_id"]
                .as_str()
                .is_some_and(|s| !s.is_empty())
        );
        let attestation_id = body["attestation_id"].as_str().unwrap();
        assert!(body["receipt_hash"].as_str().is_some_and(|s| s.len() == 64));

        let guard = store.lock().unwrap();
        let target_claims = guard.get_claims(&target).unwrap();
        assert_eq!(target_claims.len(), 1);
        let (claim_id, target_claim) = &target_claims[0];
        let saved_attestation = guard
            .get_attestation(&attester, &target)
            .unwrap()
            .expect("attestation stored");
        assert_eq!(saved_attestation.attestation_id, attestation_id);
        assert_eq!(saved_attestation.created_ms, signed_created_ms);
        assert_eq!(claim_id, &target_claim_id(&saved_attestation).unwrap());
        assert_eq!(target_claim.dag_node_hash, guard.dag_nodes()[0].hash);
        assert_eq!(target_claim.created_ms, API_TEST_NOW_MS);
        assert_eq!(target_claim.verified_ms, Some(API_TEST_NOW_MS));
        assert_eq!(guard.dag_nodes()[0].timestamp.physical_ms, API_TEST_NOW_MS);

        let receipts = guard.trust_receipts();
        assert_eq!(receipts.len(), 1);
        let receipt = &receipts[0];
        assert_eq!(receipt.action_type, "zerodentity.claim_verified");
        assert_eq!(receipt.action_hash, target_claim.claim_hash);
        assert_eq!(receipt.timestamp.physical_ms, API_TEST_NOW_MS);
        assert_eq!(
            body["receipt_hash"].as_str().unwrap(),
            hex::encode(receipt.receipt_hash.as_bytes())
        );
    }

    #[tokio::test]
    async fn attest_signed_write_rejects_nonce_replay() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let attester = td("attest-replay-a");
        let target = td("attest-replay-b");
        let token = "attest-replay-token";
        let session_keypair = test_keypair(16);
        let nonce = "nonce-replay";

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "e1",
                &make_claim(&attester, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_session(&make_session_with_public_key(
                &attester,
                token,
                1_000_000,
                session_keypair.public_key().as_bytes().to_vec(),
            ))
            .unwrap();
        }

        let uri = format!("/api/v1/0dentity/{}/attest", attester.as_str());
        let body = signed_attest_body(
            &attester,
            &target,
            AttestationType::Identity,
            None,
            1_237_000,
            session_keypair.public_key(),
            session_keypair.secret_key(),
        );
        let first =
            post_with_signed_auth(&app, &uri, token, nonce, body.clone(), &session_keypair).await;
        assert_eq!(first.status(), StatusCode::CREATED);

        let replay = post_with_signed_auth(&app, &uri, token, nonce, body, &session_keypair).await;
        assert_eq!(replay.status(), StatusCode::CONFLICT);
    }

    #[tokio::test]
    async fn attest_self_returns_400() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("attest-self");
        let token = "attest-self-token";
        let session_keypair = test_keypair(17);
        let (public_key, secret_key) = keypair(43);

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "e1",
                &make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_session(&make_session_with_public_key(
                &did,
                token,
                1_000_000,
                session_keypair.public_key().as_bytes().to_vec(),
            ))
            .unwrap();
        }

        let uri = format!("/api/v1/0dentity/{}/attest", did.as_str());
        let resp = post_with_signed_auth(
            &app,
            &uri,
            token,
            "nonce-self",
            signed_attest_body(
                &did,
                &did,
                AttestationType::Identity,
                None,
                1_235_000,
                &public_key,
                &secret_key,
            ),
            &session_keypair,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn list_claims_filters_by_status() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-filter-status");
        let token = "filter-token";

        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "c1",
                &make_claim(&did, ClaimType::Email, ClaimStatus::Verified, 1_000),
            )
            .unwrap();
            s.insert_claim(
                "c2",
                &make_claim(&did, ClaimType::Phone, ClaimStatus::Pending, 2_000),
            )
            .unwrap();
            s.insert_session(&make_session(&did, token, 1_000_000))
                .unwrap();
        }

        let resp = get_with_auth(
            &app,
            &format!("/api/v1/0dentity/{}/claims?status=verified", did.as_str()),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        assert_eq!(
            body["total"].as_u64().unwrap(),
            1,
            "only verified claims after filter"
        );
    }

    #[tokio::test]
    async fn get_score_invalid_did_returns_400() {
        let app = api_app(new_shared_store());
        let resp = get_req(&app, "/api/v1/0dentity/not-a-did/score").await;
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn score_history_with_time_filter() {
        let store = new_shared_store();
        let app = api_app(store.clone());
        let did = td("api-hist-filter");
        let token = "history-filter-session-token";

        {
            let mut s = store.lock().unwrap();
            s.insert_session(&make_session(&did, token, 1_000_000))
                .unwrap();
            for (bp, ms) in [(1_000u32, 1_000u64), (2_000, 5_000), (3_000, 10_000)] {
                let mut score = make_score(&did, bp, ms);
                score.computed_ms = ms;
                s.put_score(score).unwrap();
            }
        }

        let resp = get_with_auth(
            &app,
            &format!(
                "/api/v1/0dentity/{}/score/history?from_ms=3000&to_ms=7000",
                did.as_str()
            ),
            token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = body_json(resp).await;
        let snaps = body["snapshots"].as_array().unwrap();
        assert_eq!(snaps.len(), 1);
        assert_eq!(snaps[0]["composite"].as_u64().unwrap(), 2_000);
    }

    // -----------------------------------------------------------------------
    // §12.2.6 — Full onboarding arc (end-to-end)
    //
    // Exercises: DisplayName → Email OTP → verify → score 3500 →
    //            Phone OTP → verify → score 8700 → history → claims auth
    // -----------------------------------------------------------------------

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn test_full_onboarding_arc() {
        let store = new_shared_store();
        let onb = onboarding_app(store.clone());
        let api = api_app(store.clone());
        let keypair = test_keypair(21);
        let did = derived_did(&keypair);
        let did_str = did.as_str();

        // ── 1. DisplayName claim ──────────────────────────────────────────
        let resp = post_json(
            &onb,
            "/api/v1/0dentity/claims",
            signed_claim_body(&did, "DisplayName", None, None, 22_430, &keypair, &keypair),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let b = body_json(resp).await;
        assert_eq!(b["status"], "Pending");

        assert_eq!(
            store.lock().unwrap().get_claims(&did).unwrap().len(),
            1,
            "DisplayName claim should be stored"
        );

        // ── 2. Email claim (HTTP) ─────────────────────────────────────────
        let resp = post_json(
            &onb,
            "/api/v1/0dentity/claims",
            signed_claim_body(&did, "Email", None, None, 22_440, &keypair, &keypair),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);

        // ── 3. Email OTP — inject known node-time challenge + verify via HTTP ───────
        let dispatched_ms = API_TEST_NOW_MS;
        let mut rng1 = seeded_rng(0xABC1_0001);
        let (email_ch, email_code) =
            OtpChallenge::new(&did, OtpChannel::Email, dispatched_ms, &mut rng1).unwrap();
        let email_cid = email_ch.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&email_ch)
            .unwrap();

        let resp = post_json(
            &onb,
            "/api/v1/0dentity/verify",
            bootstrap_verify_body(&email_cid, &email_code, &did, &keypair),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let b = body_json(resp).await;
        assert!(b["verified"].as_bool().unwrap(), "email OTP must verify");
        let session_token = b["session_token"].as_str().unwrap().to_owned();

        // ── 4. Promote Email claim to Verified in store ───────────────────
        // (claim status promotion from OTP verification is deferred to APE-72)
        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "email-verified",
                &make_claim(&did, ClaimType::Email, ClaimStatus::Verified, dispatched_ms),
            )
            .unwrap();
        }

        // ── 5. GET /score → communication = 3500 (email only) ────────────
        let resp = get_with_auth(
            &api,
            &format!("/api/v1/0dentity/{did_str}/score"),
            &session_token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let b = body_json(resp).await;
        assert_eq!(
            b["axes"]["communication"].as_u64().unwrap(),
            3_500,
            "email-only communication axis must be 3500bp"
        );

        // ── 6. Phone claim + OTP ──────────────────────────────────────────
        let resp = post_json(
            &onb,
            "/api/v1/0dentity/claims",
            signed_claim_body(&did, "Phone", None, None, 22_450, &keypair, &keypair),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);

        let mut rng2 = seeded_rng(0xABC1_0002);
        let (phone_ch, phone_code) =
            OtpChallenge::new(&did, OtpChannel::Sms, dispatched_ms, &mut rng2).unwrap();
        let phone_cid = phone_ch.challenge_id.clone();
        store
            .lock()
            .unwrap()
            .insert_otp_challenge(&phone_ch)
            .unwrap();

        let resp = post_json(
            &onb,
            "/api/v1/0dentity/verify",
            bootstrap_verify_body(&phone_cid, &phone_code, &did, &keypair),
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let b = body_json(resp).await;
        assert!(b["verified"].as_bool().unwrap(), "phone OTP must verify");

        // Promote Phone claim to Verified
        {
            let mut s = store.lock().unwrap();
            s.insert_claim(
                "phone-verified",
                &make_claim(
                    &did,
                    ClaimType::Phone,
                    ClaimStatus::Verified,
                    dispatched_ms + 1,
                ),
            )
            .unwrap();
        }

        // ── 7. GET /score → communication = 8700 (email+phone+bonus) ─────
        let resp = get_with_auth(
            &api,
            &format!("/api/v1/0dentity/{did_str}/score"),
            &session_token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let b = body_json(resp).await;
        assert_eq!(
            b["axes"]["communication"].as_u64().unwrap(),
            8_700,
            "email+phone communication axis must be 8700bp"
        );
        assert!(
            b["composite"].as_u64().unwrap() > 0,
            "composite must be positive"
        );

        // ── 8. Store a score snapshot and check history ───────────────────
        {
            let mut s = store.lock().unwrap();
            let claims = s.get_claims_slice(&did).unwrap();
            let score = ZerodentityScore::compute(&did, &claims, &[], &[], dispatched_ms + 2);
            s.put_score(score).unwrap();
        }

        let resp = get_with_auth(
            &api,
            &format!("/api/v1/0dentity/{did_str}/score/history"),
            &session_token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let b = body_json(resp).await;
        assert!(
            !b["snapshots"].as_array().unwrap().is_empty(),
            "history must be non-empty after storing a score"
        );

        // ── 9. GET /claims with session token ─────────────────────────────
        let resp = get_with_auth(
            &api,
            &format!("/api/v1/0dentity/{did_str}/claims"),
            &session_token,
        )
        .await;
        assert_eq!(resp.status(), StatusCode::OK);
        let b = body_json(resp).await;
        assert!(
            b["total"].as_u64().unwrap() > 0,
            "claims list must be non-empty"
        );
    }

    // -----------------------------------------------------------------------
    // VCG-008 RED — created_ms freshness window (onboarding.rs submit_claim)
    // -----------------------------------------------------------------------
    //
    // `submit_claim` today only checks `created_ms != 0` (onboarding.rs:429).
    // An arbitrarily old or far-future signed payload is accepted as long as
    // the exact bytes have not been seen before (replay dedup is keyed on the
    // full signed payload + signature, not on `created_ms` freshness). These
    // two tests assert a bounded skew window is enforced against the trusted
    // session clock, mirroring `ZERODENTITY_ERASURE_MAX_FUTURE_SKEW_MS` in
    // store.rs. Both are expected to FAIL (accepted with 200 OK instead of
    // rejected) until a freshness/skew check is added.

    // A realistic wall-clock "now" (2026-01-01T00:00:00Z in epoch ms) used for
    // the freshness-window tests so that subtracting a 30-day skew stays well
    // above zero — otherwise `created_ms` could accidentally collide with the
    // pre-existing, unrelated `created_ms == 0` rejection and produce a false
    // green result.
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    const FRESHNESS_TEST_NOW_MS: u64 = 1_767_225_600_000;

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_rejects_stale_created_ms() {
        let store = new_shared_store();
        let app = onboarding_app_with_fixed_clock(store.clone(), FRESHNESS_TEST_NOW_MS);
        let keypair = test_keypair(140);
        let did = derived_did(&keypair);

        // 30 days before the trusted clock — well-formed, correctly signed,
        // but stale by any reasonable bounded skew window.
        const THIRTY_DAYS_MS: u64 = 30 * 24 * 60 * 60 * 1000;
        let stale_created_ms = FRESHNESS_TEST_NOW_MS - THIRTY_DAYS_MS;
        assert!(
            stale_created_ms > 0,
            "test fixture bug: stale_created_ms must stay positive so this test \
             exercises the freshness window, not the unrelated created_ms == 0 check"
        );

        let resp = post_json(
            &app,
            "/api/v1/0dentity/claims",
            signed_claim_body(
                &did,
                "DisplayName",
                None,
                None,
                stale_created_ms,
                &keypair,
                &keypair,
            ),
        )
        .await;

        assert_eq!(
            resp.status(),
            StatusCode::BAD_REQUEST,
            "a claim signed 30 days in the past must be rejected as stale, \
             not accepted because created_ms != 0 and the payload bytes are novel"
        );
        assert!(
            store.lock().unwrap().get_claims(&did).unwrap().is_empty(),
            "a stale-created_ms claim must not be persisted"
        );
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn submit_claim_rejects_future_created_ms_beyond_skew_window() {
        let store = new_shared_store();
        let app = onboarding_app_with_fixed_clock(store.clone(), FRESHNESS_TEST_NOW_MS);
        let keypair = test_keypair(141);
        let did = derived_did(&keypair);

        // 30 days after the trusted clock — mirrors the stale-past case but
        // on the future side of the window.
        const THIRTY_DAYS_MS: u64 = 30 * 24 * 60 * 60 * 1000;
        let future_created_ms = FRESHNESS_TEST_NOW_MS + THIRTY_DAYS_MS;

        let resp = post_json(
            &app,
            "/api/v1/0dentity/claims",
            signed_claim_body(
                &did,
                "DisplayName",
                None,
                None,
                future_created_ms,
                &keypair,
                &keypair,
            ),
        )
        .await;

        assert_eq!(
            resp.status(),
            StatusCode::BAD_REQUEST,
            "a claim signed 30 days in the future must be rejected as beyond \
             the trusted clock's bounded future-skew tolerance"
        );
        assert!(
            store.lock().unwrap().get_claims(&did).unwrap().is_empty(),
            "a future-created_ms claim beyond the skew window must not be persisted"
        );
    }

    // -----------------------------------------------------------------------
    // VCG-008 RED — bearer gate + PoP gate composition through the full router
    // -----------------------------------------------------------------------
    //
    // Every existing onboarding test above drives `onboarding_app()`, which
    // builds `onboarding_router` in isolation — it never passes through
    // `auth::require_bearer_on_writes`. Production wires the two together
    // (main.rs:1100-1136: `zerodentity_onboarding_router` merged into
    // `extra_router`, then `.layer(axum::middleware::from_fn(... auth::require_bearer_on_writes))`).
    // This test builds the router the way main.rs does, and proves both
    // gates actually compose: a request with only a valid bearer token and
    // no proof-of-possession must still be rejected (by the PoP gate inside
    // the handler), and a request with valid PoP but no bearer token must be
    // rejected at the bearer layer before it ever reaches the handler.

    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    fn full_router_with_bearer(
        store: SharedZerodentityStore,
        now_ms: u64,
        bearer_token: &str,
    ) -> Router {
        let onboarding = onboarding_app_with_fixed_clock(store, now_ms);
        let auth = crate::auth::BearerAuth {
            token: std::sync::Arc::new(zeroize::Zeroizing::new(bearer_token.to_owned())),
        };
        onboarding.layer(axum::middleware::from_fn(move |req, next| {
            let a = auth.clone();
            crate::auth::require_bearer_on_writes(a, req, next)
        }))
    }

    #[tokio::test]
    #[cfg(feature = "unaudited-zerodentity-first-touch-onboarding")]
    async fn bearer_gate_and_pop_gate_compose_through_full_router() {
        const BEARER_TOKEN: &str = "vcg-008-full-router-bearer-token";
        let store = new_shared_store();
        let app = full_router_with_bearer(store.clone(), API_TEST_NOW_MS, BEARER_TOKEN);
        let keypair = test_keypair(142);
        let did = derived_did(&keypair);

        // Case 1: valid bearer token, but NO public_key/signature (no PoP).
        // The bearer layer must let this through (POST /api/v1/0dentity/claims
        // is not in the local-signed-write allowlist, so it actually requires
        // the bearer token — but the request must still fail at the PoP gate
        // inside the handler, proving the bearer token alone is insufficient).
        let bearer_only_req = Request::builder()
            .method("POST")
            .uri("/api/v1/0dentity/claims")
            .header(header::CONTENT_TYPE, "application/json")
            .header(header::AUTHORIZATION, format!("Bearer {BEARER_TOKEN}"))
            .body(Body::from(
                serde_json::json!({
                    "subject_did": did.as_str(),
                    "claim_type": "DisplayName"
                })
                .to_string(),
            ))
            .unwrap();
        let resp = app.clone().oneshot(bearer_only_req).await.unwrap();
        assert_ne!(
            resp.status(),
            StatusCode::OK,
            "bearer token alone (no proof-of-possession) must not create a claim \
             through the composed production router"
        );
        assert!(
            store.lock().unwrap().get_claims(&did).unwrap().is_empty(),
            "bearer-only request must not persist a claim"
        );

        // Case 2: valid PoP (signed claim body), but NO bearer token at all.
        // The bearer layer must reject this before the handler's PoP check
        // ever runs.
        let pop_only_body = signed_claim_body(
            &did,
            "DisplayName",
            None,
            None,
            API_TEST_NOW_MS,
            &keypair,
            &keypair,
        );
        let pop_only_req = Request::builder()
            .method("POST")
            .uri("/api/v1/0dentity/claims")
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(pop_only_body.to_string()))
            .unwrap();
        let resp = app.clone().oneshot(pop_only_req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::UNAUTHORIZED,
            "a request with valid proof-of-possession but no bearer token must be \
             rejected at the bearer-gate layer of the composed production router"
        );
        assert!(
            store.lock().unwrap().get_claims(&did).unwrap().is_empty(),
            "PoP-only request without a bearer token must not persist a claim"
        );
    }

    // -----------------------------------------------------------------------
    // VCG-009 RED — device/behavioral sample ingestion must be consent-scoped,
    // persisted, replay-safe, bounded, and scored from STORED evidence.
    //
    // Ledger invariant (GAP-REGISTRY.md VCG-009): "Device and behavioral
    // sample fields are rejected UNLESS consent-scoped, privacy-reviewed,
    // persisted, replay-safe, and scored from STORED evidence."
    //
    // These tests drive the real HTTP surface
    // (`onboarding_app` + `POST /api/v1/0dentity/claims`) using an extended
    // body helper that carries the spec §7.1 sample fields
    // (`device_fingerprint`, `behavioral_hash`, `signal_hashes`) which
    // `SubmitClaimRequest` does not yet accept. They are gated on
    // `unaudited-zerodentity-device-behavioral-axes` alone (Gate 23 tests
    // every unaudited feature in isolation — VCG-009's own closure gate is
    // `cargo test -p exochain-node zerodentity --features
    // unaudited-zerodentity-device-behavioral-axes`), independent of
    // `unaudited-zerodentity-first-touch-onboarding`.
    // -----------------------------------------------------------------------

    /// Test-only extended claim submission body carrying the spec §7.1
    /// device/behavioral sample fields that `SubmitClaimRequest` does not
    /// yet declare. Built independently of `signed_claim_body` (which is
    /// gated on `unaudited-zerodentity-first-touch-onboarding`, a feature
    /// this test group does not enable per Gate 23 isolation).
    ///
    /// GREEN (VCG-009 corrective) closed the proof-of-possession hole by
    /// requiring `crypto::verify` over the canonical, sample-bound
    /// `device_behavioral_submission_signing_payload` (see below). This
    /// helper now signs over that exact same payload shape locally
    /// (duplicated here per Gate 23 isolation — this test group cannot
    /// depend on the production `session_auth` module) so that callers
    /// exercising the "well-formed, self-signed, real samples" happy path
    /// continue to verify against the production handler.
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[allow(clippy::too_many_arguments)]
    fn device_behavioral_claim_body(
        subject_did: &Did,
        claim_type: &str,
        created_ms: u64,
        public_keypair: &KeyPair,
        signing_keypair: &KeyPair,
        device_fingerprint_hex: &str,
        behavioral_hash_hex: &str,
        signal_hashes: &std::collections::BTreeMap<String, String>,
        consent_receipt_id: Option<&str>,
    ) -> Value {
        let payload = device_behavioral_submission_signing_payload(
            subject_did,
            Some(device_fingerprint_hex),
            Some(behavioral_hash_hex),
            signal_hashes,
            public_keypair.public_key(),
        );
        let signature = signing_keypair.sign(&payload);
        serde_json::json!({
            "subject_did": subject_did.as_str(),
            "claim_type": claim_type,
            "created_ms": created_ms,
            "public_key": hex::encode(public_keypair.public_key().as_bytes()),
            "signature": hex::encode(signature.to_bytes()),
            "device_fingerprint": device_fingerprint_hex,
            "behavioral_hash": behavioral_hash_hex,
            "signal_hashes": signal_hashes,
            "consent_receipt_id": consent_receipt_id,
        })
    }

    // -----------------------------------------------------------------------
    // VCG-009 STRENGTHEN-RED — proof-of-possession over the sample-bound
    // payload.
    //
    // The refuted green (7a7340e8) never calls `crypto::verify` in
    // `handle_device_behavioral_ingestion`: it only checks
    // `signature.is_empty()` after confirming `public_key` derives
    // `subject_did` — but a DID and a public key are BOTH spec-classified
    // Public (docs/0DENTITY-APP-SPEC.md §7.1), so that proves nothing about
    // possession of the matching PRIVATE key. Combined with a consent gate
    // that only requires "some session exists for this DID"
    // (`has_active_session_for`), an attacker who merely knows a victim's
    // public DID + public key can submit device/behavioral samples under the
    // victim's identity with a garbage signature.
    //
    // This canonical payload is the binding GREEN must implement to close
    // the hole. Domain-separated CBOR, mirroring the existing
    // `session_auth.rs` pattern (`bootstrap_signing_payload`,
    // `claim_submission_signing_payload`) so the fix is a natural extension
    // of that module rather than a bespoke scheme:
    //
    //   DeviceBehavioralSubmissionSigningPayload {
    //       domain: "exo.zerodentity.device_behavioral_submission.v1",
    //       subject_did: &str,
    //       device_fingerprint: Option<&str>,   // hex, as received on the wire
    //       behavioral_hash: Option<&str>,      // hex, as received on the wire
    //       signal_hashes: &BTreeMap<String, String>, // sorted key order (BTreeMap)
    //       public_key: &PublicKey,
    //   }
    //   encoded via `ciborium::into_writer` (canonical CBOR, same helper
    //   shape as `encode_cbor` in session_auth.rs).
    //
    // `claim_type`/`created_ms`/`provider`/`consent_receipt_id` are
    // deliberately NOT bound into this payload: they are either routing
    // metadata (claim_type/provider feed `parse_claim_type`, which is
    // orthogonal to sample authenticity) or a capability reference
    // (consent_receipt_id, checked separately by the consent gate) rather
    // than sample content. Binding `subject_did`, the sample fields, and the
    // signer's own `public_key` is what prevents (b) cross-account replay and
    // (c) sample-substitution.
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[derive(serde::Serialize)]
    struct DeviceBehavioralSubmissionSigningPayload<'a> {
        domain: &'static str,
        subject_did: &'a str,
        device_fingerprint: Option<&'a str>,
        behavioral_hash: Option<&'a str>,
        signal_hashes: &'a std::collections::BTreeMap<String, String>,
        public_key: &'a PublicKey,
    }

    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    const DEVICE_BEHAVIORAL_SUBMISSION_SIGNING_DOMAIN: &str =
        "exo.zerodentity.device_behavioral_submission.v1";

    /// Builds the exact canonical bytes a correct GREEN handler must verify
    /// the signature over. Any GREEN implementation that binds a different
    /// byte layout will fail test (d) (the happy path) here, forcing the
    /// signing payload shape to be an explicit, negotiated contract rather
    /// than an implementation accident.
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    fn device_behavioral_submission_signing_payload(
        subject_did: &Did,
        device_fingerprint_hex: Option<&str>,
        behavioral_hash_hex: Option<&str>,
        signal_hashes: &std::collections::BTreeMap<String, String>,
        public_key: &PublicKey,
    ) -> Vec<u8> {
        let payload = DeviceBehavioralSubmissionSigningPayload {
            domain: DEVICE_BEHAVIORAL_SUBMISSION_SIGNING_DOMAIN,
            subject_did: subject_did.as_str(),
            device_fingerprint: device_fingerprint_hex,
            behavioral_hash: behavioral_hash_hex,
            signal_hashes,
            public_key,
        };
        let mut encoded = Vec::new();
        ciborium::into_writer(&payload, &mut encoded)
            .expect("canonical CBOR encoding of test payload must not fail");
        encoded
    }

    /// Like `device_behavioral_claim_body`, but signs over the REAL canonical
    /// sample-bound payload (`device_behavioral_submission_signing_payload`)
    /// with an explicit, separately-controllable signing keypair — letting
    /// tests construct a victim's real DID/public_key while signing with an
    /// attacker's key (cross-account), or sign over one sample set and
    /// submit another (sample-substitution).
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[allow(clippy::too_many_arguments)]
    fn device_behavioral_claim_body_signed_over(
        subject_did: &Did,
        claim_type: &str,
        created_ms: u64,
        public_keypair: &KeyPair,
        signing_keypair: &KeyPair,
        signed_device_fingerprint_hex: Option<&str>,
        signed_behavioral_hash_hex: Option<&str>,
        signed_signal_hashes: &std::collections::BTreeMap<String, String>,
        submitted_device_fingerprint_hex: &str,
        submitted_behavioral_hash_hex: &str,
        submitted_signal_hashes: &std::collections::BTreeMap<String, String>,
        consent_receipt_id: Option<&str>,
    ) -> Value {
        let payload = device_behavioral_submission_signing_payload(
            subject_did,
            signed_device_fingerprint_hex,
            signed_behavioral_hash_hex,
            signed_signal_hashes,
            public_keypair.public_key(),
        );
        let signature = signing_keypair.sign(&payload);
        serde_json::json!({
            "subject_did": subject_did.as_str(),
            "claim_type": claim_type,
            "created_ms": created_ms,
            "public_key": hex::encode(public_keypair.public_key().as_bytes()),
            "signature": hex::encode(signature.to_bytes()),
            "device_fingerprint": submitted_device_fingerprint_hex,
            "behavioral_hash": submitted_behavioral_hash_hex,
            "signal_hashes": submitted_signal_hashes,
            "consent_receipt_id": consent_receipt_id,
        })
    }

    /// A syntactically well-formed but cryptographically meaningless
    /// signature: parses fine via `signature_from_hex` (64 bytes of hex) but
    /// was never produced by any real Ed25519 signing operation over
    /// anything. Stands in for "attacker has no private key at all and just
    /// fills the field with junk."
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    fn garbage_signature_hex() -> String {
        hex::encode([0xAAu8; 64])
    }

    /// Always-compiled (no feature gate — runs in every build including the
    /// default no-features build and the VCG-009 axes-on gate build alike):
    /// proves the score engine's default-off behavior at the scoring layer
    /// is exactly `device_behavioral_axes_enabled()`, never hard-coded true
    /// or false. This does not touch — and must not weaken — the existing
    /// `list_fingerprints_refused_without_device_behavioral_feature_flag`
    /// HTTP refusal test; it re-asserts the same default-off invariant at
    /// the scoring layer so the guarantee holds regardless of which HTTP
    /// route a future refactor puts sample reads behind.
    #[test]
    fn device_behavioral_axes_score_tracks_feature_flag_exactly() {
        let did = td("vcg009-default-off");
        let fp = make_fingerprint("default-off", 1_000);
        let sample =
            make_behavioral_sample("default-off", BehavioralSignalType::MouseDynamics, 1_000);

        let score = ZerodentityScore::compute(&did, &[], &[fp], &[sample], 5_000);

        if crate::zerodentity::device_behavioral_axes_enabled() {
            assert!(
                score.axes.device_trust > 0,
                "device_trust must be non-zero from stored fingerprints when the axes feature is ON"
            );
            assert!(
                score.axes.behavioral_signature > 0,
                "behavioral_signature must be non-zero from stored samples when the axes feature is ON"
            );
        } else {
            assert_eq!(
                score.axes.device_trust, 0,
                "device_trust must stay 0 while unaudited-zerodentity-device-behavioral-axes is off, \
                 even when fingerprints are present in the evidence slice"
            );
            assert_eq!(
                score.axes.behavioral_signature, 0,
                "behavioral_signature must stay 0 while unaudited-zerodentity-device-behavioral-axes is off, \
                 even when behavioral samples are present in the evidence slice"
            );
        }
    }

    /// (a) A submit carrying device/behavioral sample fields WITHOUT a valid,
    /// in-scope consent record is rejected and NOTHING is persisted.
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[tokio::test]
    async fn submit_claim_with_device_behavioral_fields_without_consent_is_rejected_and_not_persisted()
     {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let keypair = test_keypair(209);
        let did = derived_did(&keypair);

        let mut signal_hashes = std::collections::BTreeMap::new();
        signal_hashes.insert("CanvasRendering".to_owned(), hex::encode([7u8; 32]));
        signal_hashes.insert("WebGLParameters".to_owned(), hex::encode([8u8; 32]));

        let body = device_behavioral_claim_body(
            &did,
            "DisplayName",
            1_700_100_001,
            &keypair,
            &keypair,
            &hex::encode([9u8; 32]),
            &hex::encode([10u8; 32]),
            &signal_hashes,
            None, // no consent receipt at all
        );

        let resp = post_json(&app, "/api/v1/0dentity/claims", body).await;
        let status = resp.status();
        let body = body_json(resp).await;

        assert!(
            status == StatusCode::FORBIDDEN || status == StatusCode::BAD_REQUEST,
            "submitting device/behavioral sample fields without an in-scope consent record \
             must be refused (403/400), got {status}: {body}"
        );
        // The refusal must name consent as the reason — a generic
        // "first-touch onboarding disabled" refusal (today's actual
        // behavior under this feature alone) is not evidence that consent
        // scoping was ever evaluated.
        let error_text = body["error"].as_str().unwrap_or_default();
        let message_text = body["message"].as_str().unwrap_or_default();
        assert!(
            error_text.contains("consent") || message_text.contains("consent"),
            "the refusal for a device/behavioral submit with no consent record must cite \
             consent as the reason, got: {body}"
        );
        assert!(
            store
                .lock()
                .unwrap()
                .get_fingerprints(&did)
                .unwrap()
                .is_empty(),
            "no consent record must mean nothing is persisted to the fingerprint store"
        );
        assert!(
            store
                .lock()
                .unwrap()
                .get_behavioral_samples(&did)
                .unwrap()
                .is_empty(),
            "no consent record must mean nothing is persisted to the behavioral sample store"
        );
    }

    /// (b) A submit WITH a valid consent record persists the samples via
    /// put_fingerprint/put_behavioral, and a subsequent get_score reflects a
    /// non-zero device_trust / behavioral_signature axis derived from the
    /// STORED samples (not from the request echo).
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[tokio::test]
    async fn submit_claim_with_valid_consent_persists_samples_and_scores_from_store() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let keypair = test_keypair(210);
        let did = derived_did(&keypair);
        let token = "vcg009-consent-session-token";

        // Simulate an owner session the way other authenticated flows do —
        // GREEN must define how a consent receipt is actually registered
        // (exo_consent::gatekeeper::ConsentGate) and looked up here; this ID
        // is a placeholder for "a valid, in-scope consent record exists".
        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&did, token, 1_000_000))
            .unwrap();
        let consent_receipt_id = "vcg009-valid-consent-receipt-01";

        let mut signal_hashes = std::collections::BTreeMap::new();
        signal_hashes.insert("CanvasRendering".to_owned(), hex::encode([11u8; 32]));
        signal_hashes.insert("WebGLParameters".to_owned(), hex::encode([12u8; 32]));
        signal_hashes.insert("UserAgent".to_owned(), hex::encode([13u8; 32]));

        let body = device_behavioral_claim_body(
            &did,
            "DisplayName",
            1_700_100_002,
            &keypair,
            &keypair,
            &hex::encode([14u8; 32]),
            &hex::encode([15u8; 32]),
            &signal_hashes,
            Some(consent_receipt_id),
        );

        let resp = post_json(&app, "/api/v1/0dentity/claims", body).await;
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "a submit with a valid, in-scope consent record must succeed"
        );

        let fingerprints = store.lock().unwrap().get_fingerprints(&did).unwrap();
        assert_eq!(
            fingerprints.len(),
            1,
            "a consented submit must persist exactly one device fingerprint via put_fingerprint"
        );
        let behavioral = store.lock().unwrap().get_behavioral_samples(&did).unwrap();
        assert_eq!(
            behavioral.len(),
            1,
            "a consented submit must persist exactly one behavioral sample via put_behavioral"
        );

        // Score must reflect STORED evidence, not merely echo the request.
        let claims: Vec<_> = store
            .lock()
            .unwrap()
            .get_claims(&did)
            .unwrap()
            .into_iter()
            .map(|(_, c)| c)
            .collect();
        let score = ZerodentityScore::compute(&did, &claims, &fingerprints, &behavioral, 5_000_000);
        assert!(
            score.axes.device_trust > 0,
            "device_trust axis must be non-zero once fingerprints are persisted and read back \
             from the store, got {}",
            score.axes.device_trust
        );
        assert!(
            score.axes.behavioral_signature > 0,
            "behavioral_signature axis must be non-zero once behavioral samples are persisted \
             and read back from the store, got {}",
            score.axes.behavioral_signature
        );

        // And the HTTP score endpoint (the actual production read path) must
        // report the same thing — not just the direct store/scoring call.
        let score_resp = get_with_auth(
            &app_with_api(store.clone()),
            &format!("/api/v1/0dentity/{}/score", did.as_str()),
            token,
        )
        .await;
        assert_eq!(score_resp.status(), StatusCode::OK);
        let score_body = body_json(score_resp).await;
        assert!(
            score_body["axes"]["device_trust"].as_u64().unwrap_or(0) > 0,
            "GET /score must reflect the persisted device fingerprint, got {score_body}"
        );
        assert!(
            score_body["axes"]["behavioral_signature"]
                .as_u64()
                .unwrap_or(0)
                > 0,
            "GET /score must reflect the persisted behavioral sample, got {score_body}"
        );
    }

    /// Small helper standing in for wiring the onboarding store into the
    /// score-reading `api_app` router — VCG-009 must close this loop so a
    /// consented submit through onboarding is visible through the scoring
    /// API against the SAME store.
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    fn app_with_api(store: SharedZerodentityStore) -> Router {
        api_app(store)
    }

    /// (c) Replay-safety: submitting the same sample payload twice does not
    /// double-count / inflate the score (idempotent or explicitly deduped by
    /// content hash); a stale/replayed sample is rejected or ignored.
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[tokio::test]
    async fn submit_claim_replayed_device_behavioral_sample_does_not_double_count() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let keypair = test_keypair(211);
        let did = derived_did(&keypair);
        let token = "vcg009-replay-session-token";

        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&did, token, 1_000_000))
            .unwrap();
        let consent_receipt_id = "vcg009-valid-consent-receipt-02";

        let mut signal_hashes = std::collections::BTreeMap::new();
        signal_hashes.insert("CanvasRendering".to_owned(), hex::encode([21u8; 32]));

        let fingerprint_hex = hex::encode([22u8; 32]);
        let behavioral_hex = hex::encode([23u8; 32]);

        let body = device_behavioral_claim_body(
            &did,
            "DisplayName",
            1_700_100_003,
            &keypair,
            &keypair,
            &fingerprint_hex,
            &behavioral_hex,
            &signal_hashes,
            Some(consent_receipt_id),
        );

        let first = post_json(&app, "/api/v1/0dentity/claims", body.clone()).await;
        assert_eq!(first.status(), StatusCode::OK);

        // Replay the identical sample payload (same composite hashes, same
        // captured_ms semantics) a second time.
        let second = post_json(&app, "/api/v1/0dentity/claims", body).await;
        assert!(
            second.status() == StatusCode::OK || second.status() == StatusCode::CONFLICT,
            "a replayed identical sample submission must either be idempotently accepted \
             or explicitly rejected as a duplicate, got {}",
            second.status()
        );

        let fingerprints = store.lock().unwrap().get_fingerprints(&did).unwrap();
        assert_eq!(
            fingerprints.len(),
            1,
            "replaying the identical device fingerprint payload must not create a second \
             stored fingerprint entry (dedup by content hash), got {} entries",
            fingerprints.len()
        );
        let behavioral = store.lock().unwrap().get_behavioral_samples(&did).unwrap();
        assert_eq!(
            behavioral.len(),
            1,
            "replaying the identical behavioral sample payload must not create a second \
             stored behavioral entry (dedup by content hash), got {} entries",
            behavioral.len()
        );
    }

    /// (d) Bounded ingestion: oversized or over-count sample payloads are
    /// rejected (documented cap), no unbounded growth.
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[tokio::test]
    async fn submit_claim_oversized_signal_hashes_map_is_rejected() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let keypair = test_keypair(212);
        let did = derived_did(&keypair);
        let token = "vcg009-bounds-session-token";

        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&did, token, 1_000_000))
            .unwrap();
        let consent_receipt_id = "vcg009-valid-consent-receipt-03";

        // FingerprintSignal only has 15 documented variants (types.rs); an
        // over-count map like this cannot correspond to real signal types
        // and must be rejected as exceeding the documented ingestion cap.
        let mut signal_hashes = std::collections::BTreeMap::new();
        for i in 0..500u32 {
            let byte = u8::try_from(i % 256).unwrap_or(0);
            signal_hashes.insert(format!("UnknownSignal{i}"), hex::encode([byte; 32]));
        }

        let body = device_behavioral_claim_body(
            &did,
            "DisplayName",
            1_700_100_004,
            &keypair,
            &keypair,
            &hex::encode([30u8; 32]),
            &hex::encode([31u8; 32]),
            &signal_hashes,
            Some(consent_receipt_id),
        );

        let resp = post_json(&app, "/api/v1/0dentity/claims", body).await;
        assert_eq!(
            resp.status(),
            StatusCode::BAD_REQUEST,
            "an oversized signal_hashes map must be rejected under the documented ingestion \
             cap, got {}",
            resp.status()
        );
        assert!(
            store
                .lock()
                .unwrap()
                .get_fingerprints(&did)
                .unwrap()
                .is_empty(),
            "a rejected oversized payload must not persist a partial fingerprint"
        );
    }

    // -----------------------------------------------------------------------
    // VCG-009 STRENGTHEN-RED (corrective) — crypto-verified proof-of-
    // possession. These tests FAIL against the refuted green (7a7340e8):
    // `handle_device_behavioral_ingestion` never calls `crypto::verify`, so
    // it accepts a syntactically well-formed but cryptographically
    // meaningless signature as long as `public_key` derives `subject_did`
    // (proves nothing — a DID and public key are both Public per spec §7.1)
    // and SOME session exists for that DID (self-consent, not proof of
    // possession).
    // -----------------------------------------------------------------------

    /// (a) A device/behavioral submit whose signature does NOT
    /// cryptographically verify against `subject_did`'s public key over the
    /// canonical sample-bound payload must be REJECTED (401) and must
    /// persist NOTHING — even though `public_key` correctly derives
    /// `subject_did` and a live session exists (so the current, broken
    /// consent gate alone would happily grant this).
    ///
    /// FAILS against 7a7340e8: the handler only checks
    /// `signature.is_empty()`, so 64 bytes of `0xAA` sail straight through.
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[tokio::test]
    async fn submit_claim_with_non_verifying_signature_is_rejected_and_not_persisted() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let keypair = test_keypair(220);
        let did = derived_did(&keypair);
        let token = "vcg009-pop-garbage-session-token";

        // A live session exists for this DID — proves the old consent gate
        // (has_active_session_for) is satisfied, isolating the failure to
        // the missing crypto::verify call specifically.
        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&did, token, 1_000_000))
            .unwrap();
        let consent_receipt_id = "vcg009-pop-garbage-consent-receipt";

        let mut signal_hashes = std::collections::BTreeMap::new();
        signal_hashes.insert("CanvasRendering".to_owned(), hex::encode([40u8; 32]));

        let fingerprint_hex = hex::encode([41u8; 32]);
        let behavioral_hex = hex::encode([42u8; 32]);

        // Build the request body directly (not via
        // device_behavioral_claim_body_signed_over) so the `signature` field
        // is unambiguously garbage rather than a signature over some other
        // payload — this isolates "no valid signature at all" from the
        // cross-account/substitution cases below.
        let body = serde_json::json!({
            "subject_did": did.as_str(),
            "claim_type": "DisplayName",
            "created_ms": 1_700_100_010u64,
            "public_key": hex::encode(keypair.public_key().as_bytes()),
            "signature": garbage_signature_hex(),
            "device_fingerprint": fingerprint_hex,
            "behavioral_hash": behavioral_hex,
            "signal_hashes": signal_hashes,
            "consent_receipt_id": consent_receipt_id,
        });

        let resp = post_json(&app, "/api/v1/0dentity/claims", body).await;
        let status = resp.status();
        let body = body_json(resp).await;
        assert_eq!(
            status,
            StatusCode::UNAUTHORIZED,
            "a device/behavioral submit whose signature does not cryptographically verify \
             must be rejected 401, got {status}: {body}"
        );

        assert!(
            store
                .lock()
                .unwrap()
                .get_fingerprints(&did)
                .unwrap()
                .is_empty(),
            "a non-verifying signature must mean nothing is persisted to the fingerprint store"
        );
        assert!(
            store
                .lock()
                .unwrap()
                .get_behavioral_samples(&did)
                .unwrap()
                .is_empty(),
            "a non-verifying signature must mean nothing is persisted to the behavioral \
             sample store"
        );
        assert!(
            store.lock().unwrap().get_claims(&did).unwrap().is_empty(),
            "a non-verifying signature must mean no claim is persisted either"
        );
    }

    /// (b) Cross-account attack: the attacker constructs the VICTIM's real
    /// `subject_did` and real `public_key` (both public, both harvestable),
    /// but signs the submission with the ATTACKER's own private key instead
    /// of the victim's. A live session exists for the victim (self-consent
    /// would otherwise grant it). This must be REJECTED and NOTHING
    /// persisted to the victim's store.
    ///
    /// FAILS against 7a7340e8: signature.is_empty() is false (the attacker's
    /// signature bytes are non-empty), so this sails through and the
    /// attacker's fabricated samples land in the victim's fingerprint/
    /// behavioral stores.
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[tokio::test]
    async fn submit_claim_signed_by_attacker_key_for_victim_did_is_rejected_and_not_persisted() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let victim_keypair = test_keypair(221);
        let victim_did = derived_did(&victim_keypair);
        let attacker_keypair = test_keypair(222);
        let token = "vcg009-pop-cross-account-session-token";

        // The victim has a live session — the exact condition the current
        // has_active_session_for-based consent gate treats as sufficient.
        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&victim_did, token, 1_000_000))
            .unwrap();
        let consent_receipt_id = "vcg009-pop-cross-account-consent-receipt";

        let mut signal_hashes = std::collections::BTreeMap::new();
        signal_hashes.insert("CanvasRendering".to_owned(), hex::encode([50u8; 32]));
        let fingerprint_hex = hex::encode([51u8; 32]);
        let behavioral_hex = hex::encode([52u8; 32]);

        // The request carries the VICTIM's subject_did and public_key (so
        // `derived_did == subject_did` passes), but the payload is signed by
        // the ATTACKER's key.
        let body = device_behavioral_claim_body_signed_over(
            &victim_did,
            "DisplayName",
            1_700_100_011,
            &victim_keypair, // public_key on the wire: victim's (correct derivation)
            &attacker_keypair, // signing_keypair: attacker's — the attack
            Some(&fingerprint_hex),
            Some(&behavioral_hex),
            &signal_hashes,
            &fingerprint_hex,
            &behavioral_hex,
            &signal_hashes,
            Some(consent_receipt_id),
        );

        let resp = post_json(&app, "/api/v1/0dentity/claims", body).await;
        let status = resp.status();
        let body = body_json(resp).await;
        assert_eq!(
            status,
            StatusCode::UNAUTHORIZED,
            "a submission signed by an attacker's key over a victim's subject_did/public_key \
             must be rejected 401 even though the victim holds an active session, got \
             {status}: {body}"
        );

        assert!(
            store
                .lock()
                .unwrap()
                .get_fingerprints(&victim_did)
                .unwrap()
                .is_empty(),
            "an attacker-signed submission must not persist a fingerprint into the victim's store"
        );
        assert!(
            store
                .lock()
                .unwrap()
                .get_behavioral_samples(&victim_did)
                .unwrap()
                .is_empty(),
            "an attacker-signed submission must not persist a behavioral sample into the \
             victim's store"
        );
        assert!(
            store
                .lock()
                .unwrap()
                .get_claims(&victim_did)
                .unwrap()
                .is_empty(),
            "an attacker-signed submission must not persist a claim under the victim's DID"
        );
    }

    /// (b-alt) Same cross-account attack, but the attacker doesn't even
    /// bother deriving a real key pair for the "signature" — plain garbage
    /// bytes, over the victim's real DID + public_key, with the victim's
    /// active session in place. Belt-and-suspenders alongside the dedicated
    /// attacker-keypair variant above: proves the hole isn't merely
    /// "signature must decode as 64 bytes" but "signature must verify".
    ///
    /// FAILS against 7a7340e8 for the same reason as (a).
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[tokio::test]
    async fn submit_claim_garbage_signature_over_victim_identity_is_rejected_and_not_persisted() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let victim_keypair = test_keypair(223);
        let victim_did = derived_did(&victim_keypair);
        let token = "vcg009-pop-cross-account-garbage-session-token";

        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&victim_did, token, 1_000_000))
            .unwrap();
        let consent_receipt_id = "vcg009-pop-cross-account-garbage-consent-receipt";

        let mut signal_hashes = std::collections::BTreeMap::new();
        signal_hashes.insert("WebGLParameters".to_owned(), hex::encode([53u8; 32]));
        let fingerprint_hex = hex::encode([54u8; 32]);
        let behavioral_hex = hex::encode([55u8; 32]);

        let body = serde_json::json!({
            "subject_did": victim_did.as_str(),
            "claim_type": "DisplayName",
            "created_ms": 1_700_100_012u64,
            "public_key": hex::encode(victim_keypair.public_key().as_bytes()),
            "signature": garbage_signature_hex(),
            "device_fingerprint": fingerprint_hex,
            "behavioral_hash": behavioral_hex,
            "signal_hashes": signal_hashes,
            "consent_receipt_id": consent_receipt_id,
        });

        let resp = post_json(&app, "/api/v1/0dentity/claims", body).await;
        let status = resp.status();
        let body = body_json(resp).await;
        assert_eq!(
            status,
            StatusCode::UNAUTHORIZED,
            "an attacker who knows only a victim's public DID + public key, with a garbage \
             signature, must be rejected 401 even though the victim holds an active session, \
             got {status}: {body}"
        );
        assert!(
            store
                .lock()
                .unwrap()
                .get_fingerprints(&victim_did)
                .unwrap()
                .is_empty(),
            "the confirmed VCG-009 exploit path must not persist a fingerprint for the victim"
        );
        assert!(
            store
                .lock()
                .unwrap()
                .get_behavioral_samples(&victim_did)
                .unwrap()
                .is_empty(),
            "the confirmed VCG-009 exploit path must not persist a behavioral sample for the \
             victim"
        );
    }

    /// (c) Sample-substitution: a signature validly produced by the
    /// subject's own key over sample set A (fingerprint/behavioral/signal
    /// hashes A) must NOT authorize submitting a DIFFERENT sample set B on
    /// the wire. If the payload weren't sample-bound, an on-path attacker
    /// (or the subject's own compromised client) could swap in arbitrary
    /// fabricated evidence under a signature that was only ever meant to
    /// authorize the original samples.
    ///
    /// FAILS against 7a7340e8: the handler never calls crypto::verify at
    /// all, so it cannot possibly notice that the signature (whatever it
    /// covers) doesn't match the submitted sample bytes — this test is
    /// really "no sample-binding exists" wearing the substitution framing,
    /// and it fails for the same root reason as (a)/(b).
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[tokio::test]
    async fn submit_claim_signature_over_different_samples_is_rejected_and_not_persisted() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let keypair = test_keypair(224);
        let did = derived_did(&keypair);
        let token = "vcg009-pop-substitution-session-token";

        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&did, token, 1_000_000))
            .unwrap();
        let consent_receipt_id = "vcg009-pop-substitution-consent-receipt";

        // Sample set A — what the signature is REALLY over.
        let mut signal_hashes_a = std::collections::BTreeMap::new();
        signal_hashes_a.insert("CanvasRendering".to_owned(), hex::encode([60u8; 32]));
        let fingerprint_hex_a = hex::encode([61u8; 32]);
        let behavioral_hex_a = hex::encode([62u8; 32]);

        // Sample set B — what actually gets submitted on the wire, under the
        // signature that was only ever produced over set A.
        let mut signal_hashes_b = std::collections::BTreeMap::new();
        signal_hashes_b.insert("WebGLParameters".to_owned(), hex::encode([63u8; 32]));
        let fingerprint_hex_b = hex::encode([64u8; 32]);
        let behavioral_hex_b = hex::encode([65u8; 32]);

        let body = device_behavioral_claim_body_signed_over(
            &did,
            "DisplayName",
            1_700_100_013,
            &keypair,
            &keypair, // subject signs with their OWN key — over set A
            Some(&fingerprint_hex_a),
            Some(&behavioral_hex_a),
            &signal_hashes_a,
            &fingerprint_hex_b, // but set B is what's actually submitted
            &behavioral_hex_b,
            &signal_hashes_b,
            Some(consent_receipt_id),
        );

        let resp = post_json(&app, "/api/v1/0dentity/claims", body).await;
        let status = resp.status();
        let body = body_json(resp).await;
        assert_eq!(
            status,
            StatusCode::UNAUTHORIZED,
            "a signature validly produced over one sample set must not authorize submitting \
             a different sample set, got {status}: {body}"
        );

        assert!(
            store
                .lock()
                .unwrap()
                .get_fingerprints(&did)
                .unwrap()
                .is_empty(),
            "sample-substitution must not persist the substituted fingerprint (set B)"
        );
        assert!(
            store
                .lock()
                .unwrap()
                .get_behavioral_samples(&did)
                .unwrap()
                .is_empty(),
            "sample-substitution must not persist the substituted behavioral sample (set B)"
        );
    }

    /// (d) Happy path: a submit whose signature is a REAL Ed25519 signature
    /// by `subject_did`'s own private key, over the canonical sample-bound
    /// payload for the SAME samples actually submitted, with a valid
    /// in-scope consent record, must be ACCEPTED and persisted — and
    /// `get_score` (both the direct scoring call and the real `GET /score`
    /// HTTP surface) must reflect the stored samples. This must keep passing
    /// once GREEN closes (a)-(c); it is the control proving the fix isn't
    /// simply "reject everything".
    #[cfg(feature = "unaudited-zerodentity-device-behavioral-axes")]
    #[tokio::test]
    async fn submit_claim_with_real_signature_over_canonical_payload_is_accepted_and_scored() {
        let store = new_shared_store();
        let app = onboarding_app(store.clone());
        let keypair = test_keypair(225);
        let did = derived_did(&keypair);
        let token = "vcg009-pop-happy-path-session-token";

        store
            .lock()
            .unwrap()
            .insert_session(&make_session(&did, token, 1_000_000))
            .unwrap();
        let consent_receipt_id = "vcg009-pop-happy-path-consent-receipt";

        let mut signal_hashes = std::collections::BTreeMap::new();
        signal_hashes.insert("CanvasRendering".to_owned(), hex::encode([70u8; 32]));
        signal_hashes.insert("WebGLParameters".to_owned(), hex::encode([71u8; 32]));
        let fingerprint_hex = hex::encode([72u8; 32]);
        let behavioral_hex = hex::encode([73u8; 32]);

        let body = device_behavioral_claim_body_signed_over(
            &did,
            "DisplayName",
            1_700_100_014,
            &keypair,
            &keypair, // real signature, subject's own key, over these exact samples
            Some(&fingerprint_hex),
            Some(&behavioral_hex),
            &signal_hashes,
            &fingerprint_hex,
            &behavioral_hex,
            &signal_hashes,
            Some(consent_receipt_id),
        );

        let resp = post_json(&app, "/api/v1/0dentity/claims", body).await;
        let status = resp.status();
        let resp_body = body_json(resp).await;
        assert_eq!(
            status,
            StatusCode::OK,
            "a submit with a real signature over the canonical sample-bound payload, matching \
             consent, must be accepted, got {status}: {resp_body}"
        );

        let fingerprints = store.lock().unwrap().get_fingerprints(&did).unwrap();
        assert_eq!(
            fingerprints.len(),
            1,
            "the verified submit must persist exactly one device fingerprint"
        );
        let behavioral = store.lock().unwrap().get_behavioral_samples(&did).unwrap();
        assert_eq!(
            behavioral.len(),
            1,
            "the verified submit must persist exactly one behavioral sample"
        );

        let claims: Vec<_> = store
            .lock()
            .unwrap()
            .get_claims(&did)
            .unwrap()
            .into_iter()
            .map(|(_, c)| c)
            .collect();
        let score = ZerodentityScore::compute(&did, &claims, &fingerprints, &behavioral, 5_000_000);
        assert!(
            score.axes.device_trust > 0,
            "device_trust axis must be non-zero once the verified fingerprint is persisted and \
             read back from the store, got {}",
            score.axes.device_trust
        );
        assert!(
            score.axes.behavioral_signature > 0,
            "behavioral_signature axis must be non-zero once the verified behavioral sample is \
             persisted and read back from the store, got {}",
            score.axes.behavioral_signature
        );

        // Real HTTP score surface must agree.
        let score_resp = get_with_auth(
            &app_with_api(store.clone()),
            &format!("/api/v1/0dentity/{}/score", did.as_str()),
            token,
        )
        .await;
        assert_eq!(score_resp.status(), StatusCode::OK);
        let score_body = body_json(score_resp).await;
        assert!(
            score_body["axes"]["device_trust"].as_u64().unwrap_or(0) > 0,
            "GET /score must reflect the persisted, crypto-verified device fingerprint, got \
             {score_body}"
        );
        assert!(
            score_body["axes"]["behavioral_signature"]
                .as_u64()
                .unwrap_or(0)
                > 0,
            "GET /score must reflect the persisted, crypto-verified behavioral sample, got \
             {score_body}"
        );
    }

    /// exo-consent must be genuinely referenced from the zerodentity module
    /// (VCG-009 requires removing it from cargo-machete's ignored list once
    /// it is actually used) — this is a source-scan guard so a future GREEN
    /// cannot satisfy the other tests in this block with a fake/local stand-
    /// in for consent scoping instead of the real exo-consent crate.
    #[test]
    fn zerodentity_module_references_exo_consent_crate() {
        let sources = [
            include_str!("onboarding.rs"),
            include_str!("api.rs"),
            include_str!("store.rs"),
            include_str!("mod.rs"),
        ];
        let references_exo_consent = sources
            .iter()
            .any(|src| src.contains("exo_consent::") || src.contains("use exo_consent"));
        assert!(
            references_exo_consent,
            "the zerodentity module must reference the exo_consent crate to gate device/\
             behavioral sample persistence on real consent scoping, not a bespoke stand-in"
        );
    }
}