openrtc 2.8.5

OpenRTC: a Rust-first P2P runtime for device discovery, signaling, and iroh/QUIC networking.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
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
//! Provider-neutral OpenRTC 2.0 control-plane client for pure native hosts.
//!
//! Consumer applications own authentication, attestation registration, and
//! secure private-key storage. OpenRTC owns assertion exchange, device
//! enrollment, avenue-scoped gateway grants, renewal, and replay-safe device
//! proofs. No Firebase type or project identifier is exposed by this module.

pub use crate::native_key_store::{load_or_create_endpoint_key, FileSigner};

pub use crate::native_coordination_gateway::{
    NativeAuthorityAssignment, NativeAuthorityInterestAssignment, NativeCapabilities,
    NativeCapabilityHandle, NativeCapabilityKind, NativeGatewayGrant, NativeGatewayGrantProvider,
    NativeGatewayGrantRequest, NativeServiceErrorObservation,
};

#[cfg(feature = "adaptive-room-sentinel")]
#[doc(hidden)]
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdaptiveRoomSentinelOwnerLimits {
    pub max_reconnect_attempts: u8,
    pub max_operation_attempts: usize,
    pub max_prepare_page_members: usize,
    pub max_artifact_chunks: usize,
}

#[cfg(feature = "adaptive-room-sentinel")]
#[doc(hidden)]
pub fn adaptive_room_sentinel_owner_limits() -> AdaptiveRoomSentinelOwnerLimits {
    AdaptiveRoomSentinelOwnerLimits {
        max_reconnect_attempts: crate::native_coordination_gateway::MAX_RECONNECT_ATTEMPTS,
        max_operation_attempts: crate::native_coordination_gateway::MAX_OPERATION_ATTEMPTS,
        max_prepare_page_members: crate::managed_group_controller::MAX_PREPARE_PAGE_MEMBERS,
        max_artifact_chunks: crate::managed_group_controller::MAX_ARTIFACT_CHUNKS,
    }
}

/// Narrow Rust-native controller used by trusted host adapters such as the
/// first-party Tauri plugin. The avenue remains the membership owner; this
/// wrapper exposes only typed crypto actions and opaque sealed state.
#[cfg(feature = "managed-group-encryption")]
pub struct NativeManagedGroupController {
    inner: crate::managed_group_controller::ManagedGroupController,
}

#[cfg(feature = "managed-group-encryption")]
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeManagedProtectedPayload {
    pub payload: String,
    pub sealed_state: String,
}

#[cfg(feature = "managed-group-encryption")]
impl NativeManagedGroupController {
    pub fn new(
        device_id: &str,
        wrapping_key: [u8; 32],
        sealed_state: Option<&[u8]>,
    ) -> Result<Self> {
        Ok(Self {
            inner: crate::managed_group_controller::ManagedGroupController::new(
                device_id,
                wrapping_key,
                sealed_state,
            )?,
        })
    }

    pub fn publish_key_package(&self) -> Result<Value> {
        Ok(serde_json::to_value(self.inner.publish_key_package()?)?)
    }

    pub fn handle_prepare_page(&mut self, page: Value) -> Result<Vec<Value>> {
        let page = serde_json::from_value(page)?;
        self.inner
            .handle_prepare_page(page)?
            .into_iter()
            .map(|action| serde_json::to_value(action).map_err(Into::into))
            .collect()
    }

    pub fn handle_artifact_chunk(&mut self, chunk: Value) -> Result<Vec<Value>> {
        let chunk = serde_json::from_value(chunk)?;
        self.inner
            .handle_artifact_chunk(chunk)?
            .into_iter()
            .map(|action| serde_json::to_value(action).map_err(Into::into))
            .collect()
    }

    #[allow(clippy::too_many_arguments)]
    pub fn seal_payload(
        &mut self,
        architecture_epoch: u64,
        encryption_epoch: u64,
        message_id: &str,
        channel: &str,
        priority: u8,
        zone_id: Option<&str>,
        payload: &[u8],
    ) -> Result<NativeManagedProtectedPayload> {
        let protected = self.inner.seal_payload(
            architecture_epoch,
            encryption_epoch,
            message_id,
            channel,
            priority,
            zone_id,
            payload,
        )?;
        Ok(NativeManagedProtectedPayload {
            payload: base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(protected.data),
            sealed_state: base64::engine::general_purpose::URL_SAFE_NO_PAD
                .encode(protected.sealed_state),
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub fn open_payload(
        &mut self,
        architecture_epoch: u64,
        encryption_epoch: u64,
        message_id: &str,
        channel: &str,
        priority: u8,
        zone_id: Option<&str>,
        ciphertext: &[u8],
    ) -> Result<NativeManagedProtectedPayload> {
        let protected = self.inner.open_payload(
            architecture_epoch,
            encryption_epoch,
            message_id,
            channel,
            priority,
            zone_id,
            ciphertext,
        )?;
        Ok(NativeManagedProtectedPayload {
            payload: base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(protected.data),
            sealed_state: base64::engine::general_purpose::URL_SAFE_NO_PAD
                .encode(protected.sealed_state),
        })
    }
}
#[cfg(feature = "managed-group-encryption")]
pub use crate::native_coordination_gateway::{
    InMemoryNativeManagedGroupStateStore, NativeManagedGroupStateStore, NativeManagedRoomMessage,
    NativeManagedRoomPublish,
};
use crate::signaling::{
    Device, DeviceCapabilities, DeviceEvent, SessionEvent, SignalingBackend, SignalingSession,
};
use anyhow::{anyhow, bail, Context, Result};
use async_trait::async_trait;
use base64::Engine as _;
use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use futures::stream::BoxStream;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::fmt;
use std::sync::{Arc, Mutex as StdMutex};
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::{watch, Mutex};
use uuid::Uuid;

pub const OPENRTC_PRODUCTION_CONTROL_PLANE: &str = "https://api.openrtc.app";
const DEVICE_CERTIFICATE_RENEW_SKEW_MS: u64 = 24 * 60 * 60_000;
const SOURCE_RENEW_SKEW_MS: u64 = 5 * 60_000;
const REQUEST_TIMEOUT_SECONDS: u64 = 15;

#[derive(Debug)]
pub struct ControlPlaneHttpError {
    pub(crate) status: u16,
    pub(crate) message: String,
    pub(crate) reason: Option<String>,
    pub service_error: Option<crate::service_errors::ServiceError>,
}

impl ControlPlaneHttpError {
    pub(crate) fn is_retryable(&self) -> bool {
        if let Some(service) = &self.service_error {
            return service.retryable;
        }
        self.status == 408 || self.status == 425 || self.status == 429 || self.status >= 500
    }
}

impl fmt::Display for ControlPlaneHttpError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "OpenRTC control-plane request failed ({}): {}",
            self.status, self.message
        )
    }
}

impl std::error::Error for ControlPlaneHttpError {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdentityAssertion {
    pub token: String,
    pub provider_id: Option<String>,
}

/// Application-owned source of short-lived OIDC/JWKS assertions.
///
/// Implementations may use Firebase Auth, Auth0, Clerk, a custom backend, or
/// another registered issuer. The OpenRTC crate never initializes that IdP.
#[async_trait]
pub trait AssertionProvider: Send + Sync {
    async fn assertion(&self, force_refresh: bool) -> Result<IdentityAssertion>;

    /// Returns an assertion for the exact durable installation being enrolled.
    ///
    /// Consumer backends may enforce product device allowances while minting
    /// the assertion, so the native API must expose the same device binding as
    /// the browser/WASM `AuthProvider`. The default preserves source
    /// compatibility for identity providers that do not perform per-device
    /// product admission.
    async fn assertion_for_device(
        &self,
        force_refresh: bool,
        _device_id: &str,
    ) -> Result<IdentityAssertion> {
        self.assertion(force_refresh).await
    }

    /// Returns a newly authorized assertion after OpenRTC reports that this
    /// installation ID is bound to a different public key. Consumer backends
    /// should require recent interactive authentication before adding their
    /// recovery authorization claim. This is never called for another 412.
    async fn assertion_for_device_recovery(&self, device_id: &str) -> Result<IdentityAssertion> {
        self.assertion_for_device(true, device_id).await
    }

    /// Stable, non-secret local identifier for one signed-in principal. It
    /// changes on login/logout/account switch, never on access-token refresh.
    /// OpenRTC hashes it with the app and install-key thumbprint before asking
    /// the certificate store for a cold-start lookup. `None` preserves the RC
    /// assertion-first compatibility behavior.
    fn session_key(&self) -> Result<Option<String>> {
        Ok(None)
    }

    /// Monotonic application-owned login epoch. Increment it only for login,
    /// logout, account switch, or explicit revocation--never for an ordinary
    /// OAuth access-token refresh.
    fn identity_epoch(&self) -> u64 {
        0
    }

    /// Optional immediate epoch observer. OpenRTC closes every capability
    /// created under the old epoch when this value changes. Hosts without an
    /// observer must explicitly close their handles during logout/account
    /// switch; grant renewal still fails closed if `identity_epoch()` changed.
    fn subscribe_identity_epoch(&self) -> Option<watch::Receiver<u64>> {
        None
    }
}

/// Host secure-storage bridge for the per-install Ed25519 device key.
/// Private key bytes never enter the OpenRTC runtime.
pub trait DeviceSigner: Send + Sync {
    fn public_jwk(&self, app_tag: &str) -> Result<Value>;
    fn sign(&self, app_tag: &str, challenge: &[u8]) -> Result<Vec<u8>>;
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StoredCertificate {
    pub app_tag: String,
    pub principal_id: String,
    pub device_id: String,
    pub token: String,
    pub expires_at_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_key_hash: Option<String>,
    /// Public verification material returned alongside the certificate. Old
    /// cache entries intentionally fail closed and re-enroll once.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signing_public_jwk: Option<Value>,
}

/// Application-owned durable certificate storage. Desktop applications should
/// protect this value with owner-only file permissions or the OS credential
/// store. A certificate is public-key bound, but remains bearer authorization
/// and therefore must not be placed in logs or world-readable preferences.
#[async_trait]
pub trait CertificateStore: Send + Sync {
    async fn load(
        &self,
        app_tag: &str,
        principal_id: &str,
        device_id: &str,
    ) -> Result<Option<StoredCertificate>>;

    async fn save(&self, certificate: &StoredCertificate) -> Result<()>;

    /// Optional cold-start lookup that avoids fetching an IdP assertion merely
    /// to rediscover the stable OpenRTC principal. Production stores should
    /// index the already-hashed value; raw consumer session identifiers must
    /// never be persisted by OpenRTC.
    async fn load_for_session(
        &self,
        _app_tag: &str,
        _session_key_hash: &str,
        _device_id: &str,
    ) -> Result<Option<StoredCertificate>> {
        Ok(None)
    }

    async fn remove(&self, app_tag: &str, principal_id: &str, device_id: &str) -> Result<()>;
}

/// Network-idle, process-local certificate cache for prototypes and tests.
/// Production native applications should supply durable protected storage.
#[derive(Default)]
pub struct InMemoryCertificate {
    certificate: StdMutex<Option<StoredCertificate>>,
}

#[async_trait]
impl CertificateStore for InMemoryCertificate {
    async fn load(
        &self,
        app_tag: &str,
        principal_id: &str,
        device_id: &str,
    ) -> Result<Option<StoredCertificate>> {
        Ok(self
            .certificate
            .lock()
            .map_err(|_| anyhow!("native device certificate cache is poisoned"))?
            .clone()
            .filter(|value| {
                value.app_tag == app_tag
                    && value.principal_id == principal_id
                    && value.device_id == device_id
            }))
    }

    async fn save(&self, certificate: &StoredCertificate) -> Result<()> {
        *self
            .certificate
            .lock()
            .map_err(|_| anyhow!("native device certificate cache is poisoned"))? =
            Some(certificate.clone());
        Ok(())
    }

    async fn load_for_session(
        &self,
        app_tag: &str,
        session_key_hash: &str,
        device_id: &str,
    ) -> Result<Option<StoredCertificate>> {
        Ok(self
            .certificate
            .lock()
            .map_err(|_| anyhow!("native device certificate cache is poisoned"))?
            .clone()
            .filter(|value| {
                value.app_tag == app_tag
                    && value.device_id == device_id
                    && value.session_key_hash.as_deref() == Some(session_key_hash)
            }))
    }

    async fn remove(&self, app_tag: &str, principal_id: &str, device_id: &str) -> Result<()> {
        let mut guard = self
            .certificate
            .lock()
            .map_err(|_| anyhow!("native device certificate cache is poisoned"))?;
        if guard.as_ref().is_some_and(|value| {
            value.app_tag == app_tag
                && value.principal_id == principal_id
                && value.device_id == device_id
        }) {
            *guard = None;
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AttestationEvidence {
    pub kind: String,
    pub token: String,
}

/// Optional application-owned managed-attestation bridge. It is invoked only
/// during enrollment or certificate renewal, never as a socket heartbeat.
#[async_trait]
pub trait AttestationProvider: Send + Sync {
    async fn evidence(&self, challenge: &str, api_key: &str) -> Result<AttestationEvidence>;
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Features {
    pub iroh_relay: bool,
    pub managed_turn: bool,
    pub moq: bool,
    pub ble: bool,
    pub advanced_fanout: bool,
    pub durable_membership: bool,
}

/// Public presentation metadata for one enrolled native installation.
///
/// This is deliberately provider-neutral and mirrors the browser/WASM v2
/// device profile. It is persisted by the OpenRTC control plane so durable
/// user-device discovery does not depend on a live presence frame to learn a
/// useful name or platform.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceProfile {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub platform: Option<String>,
}

#[derive(Clone, Default)]
pub struct DeviceOptions {
    pub max_peers: Option<u32>,
    pub features: Features,
    pub attestation: Option<Arc<dyn AttestationProvider>>,
    pub identity_relay: Option<CredentialRelay>,
    pub device_profile: Option<DeviceProfile>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CapabilityOptions {
    pub max_peers: Option<u32>,
    pub features: Features,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RoomArchitectureMode {
    #[default]
    Auto,
    Mesh,
    Sparse,
    Managed,
    Authority,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RoomDelivery {
    #[default]
    Reliable,
    LatestState,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EffectiveRoomArchitecture {
    Mesh,
    Sparse,
    Managed,
    Authority,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RoomArchitecturePhase {
    Preparing,
    Settled,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RoomArchitectureReason {
    Size,
    Traffic,
    Latency,
    Cost,
    Capacity,
    Manual,
    Recovery,
}

/// Customer-safe room policy projection delivered by the avenue gateway.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RoomArchitectureSnapshot {
    pub requested: RoomArchitectureMode,
    pub effective: EffectiveRoomArchitecture,
    pub epoch: u64,
    pub phase: RoomArchitecturePhase,
    pub reason: RoomArchitectureReason,
    pub held_credits_usd: f64,
    pub quote_expires_at_ms: u64,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RoomOptions {
    pub max_peers: Option<u32>,
    pub features: Features,
    pub architecture: RoomArchitectureMode,
    pub delivery: RoomDelivery,
}

/// Developer-backend-only configuration for one authoritative room replica.
/// The service grant is bound to this replica's device signer; the separate
/// assignment signer can be shared by equivalent replicas after an
/// application-owned state handoff.
pub struct RoomAuthorityOptions {
    pub service_id: String,
    pub generation: u64,
    pub shard_ids: Vec<String>,
    /// Total room members including services, within 1..=50. None uses app policy.
    pub max_peers: Option<u32>,
    pub features: Features,
    pub assignment_signer: Arc<dyn DeviceSigner>,
}

/// One connected developer authority capability. It uses the same native
/// gateway and Rust peer-session owner as every other room; it adds only the
/// signed AOI assignment permission carried by its server-minted grant.
pub struct RoomAuthority {
    handle: NativeCapabilityHandle,
    app_tag: String,
    service_id: String,
    generation: u64,
    shard_ids: Vec<String>,
    assignment_signer: Arc<dyn DeviceSigner>,
}

impl RoomAuthority {
    pub fn subscribe_service_errors(
        &self,
    ) -> Result<tokio::sync::broadcast::Receiver<NativeServiceErrorObservation>> {
        self.handle.subscribe_service_errors()
    }

    /// Compose the dedicated native runtime for this service room.
    ///
    /// The authenticated gateway supplies the permitted edges to the existing
    /// Rust peer-session actor. This does not initialize an endpoint, publish
    /// presence, or require JavaScript. One authority handle composes one client.
    pub async fn compose_client(
        &self,
        builder: crate::client::ClientBuilder,
    ) -> Result<Arc<crate::Client>> {
        self.handle.compose_authority_client(builder).await
    }

    pub fn signaling(&self) -> Arc<dyn SignalingBackend> {
        self.handle.signaling()
    }

    pub fn room_architecture(&self) -> Result<Option<RoomArchitectureSnapshot>> {
        self.handle.room_architecture()
    }

    pub async fn publish_assignment(
        &self,
        revision: u64,
        subject_device_id: impl Into<String>,
        shard_id: impl Into<String>,
        priority_device_ids: Vec<String>,
        relevant_entity_ids: Vec<String>,
        ttl_ms: u64,
    ) -> Result<NativeAuthorityInterestAssignment> {
        if revision == 0 || ttl_ms == 0 || ttl_ms > 2 * 60_000 {
            bail!("authority assignment revision or TTL is invalid");
        }
        let subject_device_id = bounded_id("subject_device_id", subject_device_id.into())?;
        let shard_id = bounded_id("shard_id", shard_id.into())?;
        if !self.shard_ids.contains(&shard_id) {
            bail!("authority assignment shard is not owned by this service replica");
        }
        crate::native_coordination_gateway::validate_native_authority_assignment_targets(
            &priority_device_ids,
            &relevant_entity_ids,
        )?;
        let issued_at_ms = now_ms();
        let assignment = NativeAuthorityInterestAssignment {
            policy_version: "room-authority-assignment-v1".to_string(),
            service_id: self.service_id.clone(),
            generation: self.generation,
            revision,
            subject_device_id,
            shard_id,
            priority_device_ids,
            relevant_entity_ids,
            issued_at_ms,
            expires_at_ms: issued_at_ms.saturating_add(ttl_ms),
        };
        let payload =
            serde_json::to_vec(&assignment).context("encode native authority assignment")?;
        let signature = self.assignment_signer.sign(&self.app_tag, &payload)?;
        if signature.len() != 64 {
            bail!("native authority assignment signer returned an invalid Ed25519 signature");
        }
        self.handle
            .publish_authority_assignment(
                assignment.clone(),
                base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(signature),
            )
            .await?;
        Ok(assignment)
    }

    pub async fn close(&self) {
        self.handle.close().await;
    }
}

impl From<CapabilityOptions> for RoomOptions {
    fn from(value: CapabilityOptions) -> Self {
        Self {
            max_peers: value.max_peers,
            features: value.features,
            architecture: RoomArchitectureMode::Auto,
            delivery: RoomDelivery::Reliable,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AnonymousKind {
    Space,
    Room,
    Ticket,
}

impl AnonymousKind {
    fn source_kind(self) -> &'static str {
        match self {
            Self::Space => "space",
            Self::Room => "room",
            Self::Ticket => "ticket",
        }
    }
}

/// Mutable opaque-credential relay for native runtimes constructed before the
/// application finishes login. It carries only OpenRTC-issued device
/// certificates and follows certificate renewal performed by the grant owner.
#[derive(Clone, Default)]
pub struct CredentialRelay {
    value: Arc<StdMutex<Option<String>>>,
}

impl CredentialRelay {
    pub fn provider(&self) -> Box<dyn Fn() -> Option<String> + Send + Sync> {
        let state = self.value.clone();
        Box::new(move || state.lock().ok().and_then(|value| value.clone()))
    }

    fn set(&self, value: Option<String>) -> Result<()> {
        *self
            .value
            .lock()
            .map_err(|_| anyhow!("native identity credential state is poisoned"))? = value;
        Ok(())
    }
}

/// One-time, fail-closed signaling installation point for native hosts whose
/// process is created before user authentication completes. Installation may
/// happen exactly once; replacement requires closing and rebuilding the
/// capability/runtime so this cannot become a shadow lifecycle owner.
#[derive(Default)]
pub struct SignalingSlot {
    backend: tokio::sync::RwLock<Option<Arc<dyn SignalingBackend>>>,
}

impl SignalingSlot {
    pub async fn install(&self, backend: Arc<dyn SignalingBackend>) -> Result<()> {
        let mut current = self.backend.write().await;
        if current.is_some() {
            bail!("native OpenRTC capability signaling is already installed");
        }
        *current = Some(backend);
        Ok(())
    }

    async fn current(&self) -> Result<Arc<dyn SignalingBackend>> {
        self.backend
            .read()
            .await
            .clone()
            .ok_or_else(|| anyhow!("native OpenRTC capability is not active"))
    }
}

#[async_trait]
impl SignalingBackend for SignalingSlot {
    async fn update_presence(
        &self,
        user_id: &str,
        local_node_id: &str,
        ticket_str: &str,
        is_online: bool,
        name: &str,
        ttl_ms: u64,
        metadata: Option<&str>,
    ) -> Result<()> {
        self.current()
            .await?
            .update_presence(
                user_id,
                local_node_id,
                ticket_str,
                is_online,
                name,
                ttl_ms,
                metadata,
            )
            .await
    }

    async fn set_offline(&self, user_id: &str, local_node_id: &str) -> Result<()> {
        self.current()
            .await?
            .set_offline(user_id, local_node_id)
            .await
    }

    async fn update_live_presence(
        &self,
        user_id: &str,
        local_node_id: &str,
        ticket_str: &str,
        name: &str,
        metadata: Option<&str>,
    ) -> Result<()> {
        self.current()
            .await?
            .update_live_presence(user_id, local_node_id, ticket_str, name, metadata)
            .await
    }

    async fn set_live_presence_offline(&self, user_id: &str, local_node_id: &str) -> Result<()> {
        self.current()
            .await?
            .set_live_presence_offline(user_id, local_node_id)
            .await
    }

    async fn update_device(
        &self,
        user_id: &str,
        device_id: &str,
        device_name: Option<&str>,
        capabilities: Option<DeviceCapabilities>,
        metadata: Option<&str>,
    ) -> Result<()> {
        self.current()
            .await?
            .update_device(user_id, device_id, device_name, capabilities, metadata)
            .await
    }

    async fn delete_device(&self, user_id: &str, device_id: &str) -> Result<()> {
        self.current()
            .await?
            .delete_device(user_id, device_id)
            .await
    }

    async fn set_excluded_peers(
        &self,
        user_id: &str,
        local_node_id: &str,
        excluded_peers: &[String],
    ) -> Result<()> {
        self.current()
            .await?
            .set_excluded_peers(user_id, local_node_id, excluded_peers)
            .await
    }

    async fn search_devices(
        &self,
        user_id: &str,
        exclude_node_id: Option<&str>,
    ) -> Result<Vec<Device>> {
        self.current()
            .await?
            .search_devices(user_id, exclude_node_id)
            .await
    }

    async fn list_devices(
        &self,
        user_id: &str,
        exclude_node_id: Option<&str>,
    ) -> Result<Vec<Device>> {
        self.current()
            .await?
            .list_devices(user_id, exclude_node_id)
            .await
    }

    async fn send_message(
        &self,
        sender_id: &str,
        target_id: &str,
        payload: &str,
        state: Option<&str>,
        reply_payload: Option<&str>,
    ) -> Result<String> {
        self.current()
            .await?
            .send_message(sender_id, target_id, payload, state, reply_payload)
            .await
    }

    async fn subscribe_devices(
        &self,
        user_id: &str,
    ) -> Result<BoxStream<'static, Result<Vec<DeviceEvent>>>> {
        self.current().await?.subscribe_devices(user_id).await
    }

    async fn create_session(&self, session: SignalingSession) -> Result<()> {
        self.current().await?.create_session(session).await
    }

    async fn update_session(&self, session_id: &str, update_data: Value) -> Result<()> {
        self.current()
            .await?
            .update_session(session_id, update_data)
            .await
    }

    async fn subscribe_sessions(
        &self,
        local_device_id: &str,
    ) -> Result<BoxStream<'static, Result<Vec<SessionEvent>>>> {
        self.current()
            .await?
            .subscribe_sessions(local_device_id)
            .await
    }
}

#[derive(Debug, Clone)]
struct CredentialSource {
    token: String,
    expires_at_ms: u64,
    principal_id: String,
    relay: RelayAvailability,
}

#[derive(Debug, Clone)]
struct AnonymousCredentialSource {
    token: String,
    expires_at_ms: u64,
    principal_id: String,
    device_id: String,
    requested_id: String,
    avenue_id: String,
    relay: RelayAvailability,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RelayAvailability {
    pub iroh_relay: bool,
    pub managed_turn: bool,
}

fn relay_availability(
    iroh_relay: Option<bool>,
    managed_turn: bool,
    legacy_relay: Option<bool>,
) -> RelayAvailability {
    RelayAvailability {
        iroh_relay: iroh_relay.or(legacy_relay).unwrap_or(true),
        // The legacy relay claim never proves that managed TURN is deployed.
        managed_turn,
    }
}

fn relay_availability_from_token(token: &str) -> Result<RelayAvailability> {
    let claims = decode_claims(token)?;
    Ok(relay_availability(
        claims.get("irohRelay").and_then(Value::as_bool),
        claims
            .get("managedTurn")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        claims.get("relay").and_then(Value::as_bool),
    ))
}

fn available_features(mut requested: Features, relay: RelayAvailability) -> Features {
    requested.iroh_relay &= relay.iroh_relay;
    requested.managed_turn &= relay.managed_turn;
    requested
}

#[derive(Clone)]
pub struct ControlPlane {
    inner: Arc<ControlPlaneInner>,
}

struct ControlPlaneInner {
    api_key: String,
    app_tag: String,
    endpoint: String,
    gateway_endpoint: String,
    http: reqwest::Client,
    assertion_provider: Option<Arc<dyn AssertionProvider>>,
    signer: Arc<dyn DeviceSigner>,
    certificate_store: Arc<dyn CertificateStore>,
    #[cfg(feature = "managed-group-encryption")]
    managed_group_store:
        StdMutex<Arc<dyn crate::native_coordination_gateway::NativeManagedGroupStateStore>>,
    auth_epoch: Mutex<AuthEpochState>,
}

#[derive(Debug, Clone)]
struct CachedIdentity {
    response: AssertionExchangeResponse,
    expires_at_ms: u64,
    device_id: String,
}

#[derive(Debug, Default)]
struct AuthEpochState {
    epoch: Option<u64>,
    identity: Option<CachedIdentity>,
}

/// An authenticated device-mesh capability plus its stable app-scoped
/// principal. The handle remains network-idle until the runtime publishes its
/// initial presence, and `close()` stops its socket and grant-refresh owner.
pub struct Devices {
    pub principal_id: String,
    pub handle: NativeCapabilityHandle,
    identity_relay: CredentialRelay,
    identity_epoch_monitor: Option<tokio::task::JoinHandle<()>>,
    relay: RelayAvailability,
}

/// A backend-free native capability. Its install-bound principal and device
/// identity come from the host-secure Ed25519 key, and the handle owns exactly
/// one live avenue.
pub struct AnonymousCapability {
    pub principal_id: String,
    pub handle: NativeCapabilityHandle,
    relay: RelayAvailability,
}

impl Devices {
    pub fn relay_availability(&self) -> RelayAvailability {
        self.relay
    }
    /// Opaque device certificate used by Rust peer-session admission. The
    /// provider observes certificate renewal without exposing any private key.
    pub fn identity_credential_provider(&self) -> Box<dyn Fn() -> Option<String> + Send + Sync> {
        self.identity_relay.provider()
    }

    /// Install this one avenue in the shared Rust runtime. The returned
    /// backend remains owned by this disposable capability handle.
    pub fn signaling(&self) -> Arc<dyn SignalingBackend> {
        self.handle.signaling()
    }

    /// Return media already bound to this devices avenue. The capability key
    /// remains internal while native and browser peers share the same scoped
    /// stream envelope.
    pub fn media_connection(
        &self,
        client: Arc<crate::Client>,
        peer_id: impl Into<String>,
    ) -> Result<crate::media::MediaConnection> {
        media_connection_for_capability(&self.handle, client, peer_id)
    }

    pub fn is_closed(&self) -> bool {
        self.handle.is_closed()
    }

    pub async fn close(&self) {
        if let Some(monitor) = &self.identity_epoch_monitor {
            monitor.abort();
        }
        self.handle.close().await;
    }
}

impl Drop for Devices {
    fn drop(&mut self) {
        if let Some(monitor) = &self.identity_epoch_monitor {
            monitor.abort();
        }
    }
}

impl AnonymousCapability {
    /// Compose the Rust peer-session owner for an authority-room consumer.
    ///
    /// Join with `RoomArchitectureMode::Authority` first. No service secret or
    /// JavaScript runtime is needed: the gateway supplies assigned routes and
    /// receiver permissions to the same owner used by `RoomAuthority`.
    /// Other avenue architectures are not supported by this composition helper.
    pub async fn compose_client(
        &self,
        builder: crate::client::ClientBuilder,
    ) -> Result<Arc<crate::Client>> {
        self.handle.compose_authority_client(builder).await
    }

    pub fn relay_availability(&self) -> RelayAvailability {
        self.relay
    }
    /// Install this one avenue in the shared Rust runtime. Capability/grant
    /// renewal remains internal and does not replace a healthy socket.
    pub fn signaling(&self) -> Arc<dyn SignalingBackend> {
        self.handle.signaling()
    }

    pub fn room_architecture(&self) -> Result<Option<RoomArchitectureSnapshot>> {
        self.handle.room_architecture()
    }

    pub fn subscribe_room_architecture(
        &self,
    ) -> Result<watch::Receiver<Option<RoomArchitectureSnapshot>>> {
        self.handle.subscribe_room_architecture()
    }

    /// Return media already bound to this space, room, or ticket capability.
    pub fn media_connection(
        &self,
        client: Arc<crate::Client>,
        peer_id: impl Into<String>,
    ) -> Result<crate::media::MediaConnection> {
        media_connection_for_capability(&self.handle, client, peer_id)
    }

    pub fn is_closed(&self) -> bool {
        self.handle.is_closed()
    }

    pub async fn close(&self) {
        self.handle.close().await;
    }
}

fn media_connection_for_capability(
    handle: &NativeCapabilityHandle,
    client: Arc<crate::Client>,
    peer_id: impl Into<String>,
) -> Result<crate::media::MediaConnection> {
    let kind = match handle.kind() {
        NativeCapabilityKind::Devices => "devices",
        NativeCapabilityKind::Space => "space",
        NativeCapabilityKind::Room => "room",
        NativeCapabilityKind::Ticket => "ticket",
    };
    crate::media::MediaConnection::for_capability(client, peer_id, kind, handle.id())
}

impl ControlPlane {
    pub fn new(
        api_key: &str,
        assertion_provider: Arc<dyn AssertionProvider>,
        signer: Arc<dyn DeviceSigner>,
        certificate_store: Arc<dyn CertificateStore>,
    ) -> Result<Self> {
        let api_key = crate::validate_api_key(api_key)?.to_string();
        let app_tag = crate::app_tag_from_api_key(&api_key);
        Ok(Self {
            inner: Arc::new(ControlPlaneInner {
                api_key,
                app_tag,
                endpoint: OPENRTC_PRODUCTION_CONTROL_PLANE.to_string(),
                gateway_endpoint:
                    crate::native_coordination_gateway::OPENRTC_PRODUCTION_COORDINATION_GATEWAY
                        .to_string(),
                http: reqwest::Client::builder()
                    .timeout(std::time::Duration::from_secs(REQUEST_TIMEOUT_SECONDS))
                    .build()?,
                assertion_provider: Some(assertion_provider),
                signer,
                certificate_store,
                #[cfg(feature = "managed-group-encryption")]
                managed_group_store: StdMutex::new(Arc::new(
                    crate::native_coordination_gateway::InMemoryNativeManagedGroupStateStore::default(),
                )),
                auth_epoch: Mutex::new(AuthEpochState::default()),
            }),
        })
    }

    /// Construct the API-key-only native prototype surface. Construction is
    /// network-idle. A capability request occurs only when `join_space`,
    /// `join_room`, or `issue_ticket` is awaited.
    pub fn anonymous(api_key: &str, signer: Arc<dyn DeviceSigner>) -> Result<Self> {
        let api_key = crate::validate_api_key(api_key)?.to_string();
        let app_tag = crate::app_tag_from_api_key(&api_key);
        Ok(Self {
            inner: Arc::new(ControlPlaneInner {
                api_key,
                app_tag,
                endpoint: OPENRTC_PRODUCTION_CONTROL_PLANE.to_string(),
                gateway_endpoint:
                    crate::native_coordination_gateway::OPENRTC_PRODUCTION_COORDINATION_GATEWAY
                        .to_string(),
                http: reqwest::Client::builder()
                    .timeout(std::time::Duration::from_secs(REQUEST_TIMEOUT_SECONDS))
                    .build()?,
                assertion_provider: None,
                signer,
                certificate_store: Arc::new(InMemoryCertificate::default()),
                #[cfg(feature = "managed-group-encryption")]
                managed_group_store: StdMutex::new(Arc::new(
                    crate::native_coordination_gateway::InMemoryNativeManagedGroupStateStore::default(),
                )),
                auth_epoch: Mutex::new(AuthEpochState::default()),
            }),
        })
    }

    pub fn app_tag(&self) -> &str {
        &self.inner.app_tag
    }

    /// Replace the process-local prototype store with durable owner-only
    /// app-private storage before joining a managed room.
    #[cfg(feature = "managed-group-encryption")]
    pub fn set_managed_group_state_store(
        &self,
        store: Arc<dyn crate::native_coordination_gateway::NativeManagedGroupStateStore>,
    ) -> Result<()> {
        *self
            .inner
            .managed_group_store
            .lock()
            .map_err(|_| anyhow!("native managed group state store lock is poisoned"))? = store;
        Ok(())
    }

    pub fn with_testing_endpoints(
        self,
        control_plane: impl Into<String>,
        gateway: impl Into<String>,
    ) -> Result<Self> {
        #[cfg(any(test, feature = "testing-endpoints"))]
        {
            let mut control = self;
            let control_plane = validate_endpoint(control_plane.into())?;
            let gateway = validate_endpoint(gateway.into())?;
            Arc::get_mut(&mut control.inner)
                .ok_or_else(|| anyhow!("testing endpoints must be set before cloning the client"))?
                .endpoint = control_plane;
            Arc::get_mut(&mut control.inner)
                .ok_or_else(|| anyhow!("testing endpoints must be set before cloning the client"))?
                .gateway_endpoint = gateway;
            Ok(control)
        }
        #[cfg(not(any(test, feature = "testing-endpoints")))]
        {
            let _ = (control_plane.into(), gateway.into());
            Err(anyhow!(
                "testing endpoints require the OpenRTC testing-endpoints feature"
            ))
        }
    }

    pub async fn devices(
        &self,
        device_id: impl Into<String>,
        platform_type: impl Into<String>,
        options: DeviceOptions,
    ) -> Result<Devices> {
        let device_id = bounded_id("device_id", device_id.into())?;
        let platform_type = bounded_id("platform_type", platform_type.into())?;
        let device_profile = normalized_device_profile(options.device_profile, &platform_type)?;
        let assertion_provider = self.inner.assertion_provider.as_ref().ok_or_else(|| {
            anyhow!("authenticated devices require a native identity assertion provider")
        })?;
        let mut epoch_receiver = assertion_provider.subscribe_identity_epoch();
        let identity_epoch = epoch_receiver
            .as_ref()
            .map(|receiver| *receiver.borrow())
            .unwrap_or_else(|| assertion_provider.identity_epoch());
        let source = self
            .device_certificate(
                &device_id,
                device_profile.as_ref(),
                options.attestation.as_deref(),
                identity_epoch,
            )
            .await?;
        let principal_id = source.principal_id.clone();
        let relay = source.relay;
        let identity_relay = options.identity_relay.clone().unwrap_or_default();
        identity_relay.set(Some(source.token.clone()))?;
        let grant_provider: Arc<dyn NativeGatewayGrantProvider> =
            Arc::new(ControlPlaneGrantProvider {
                control_plane: self.clone(),
                device_id: device_id.clone(),
                source: Mutex::new(source),
                max_peers: options.max_peers,
                features: options.features,
                device_profile,
                attestation: options.attestation,
                identity_relay: identity_relay.clone(),
                identity_epoch,
            });
        let capabilities = NativeCapabilities::new(
            &self.inner.api_key,
            device_id,
            platform_type,
            grant_provider,
        )?;
        #[cfg(feature = "managed-group-encryption")]
        let capabilities = capabilities.with_managed_group_storage(
            self.inner.signer.clone(),
            self.inner
                .managed_group_store
                .lock()
                .map_err(|_| anyhow!("native managed group state store lock is poisoned"))?
                .clone(),
        );
        #[cfg(any(test, feature = "testing-endpoints"))]
        let capabilities = capabilities.with_testing_endpoint(&self.inner.gateway_endpoint)?;
        let handle = capabilities.devices(principal_id.clone())?;
        let identity_epoch_monitor = epoch_receiver.take().map(|receiver| {
            spawn_identity_epoch_monitor(
                receiver,
                identity_epoch,
                handle.closer(),
                identity_relay.clone(),
            )
        });
        Ok(Devices {
            handle,
            principal_id,
            identity_relay,
            identity_epoch_monitor,
            relay,
        })
    }

    pub async fn join_space(
        &self,
        id: impl Into<String>,
        platform_type: impl Into<String>,
        options: CapabilityOptions,
    ) -> Result<AnonymousCapability> {
        self.anonymous_capability(
            AnonymousKind::Space,
            id.into(),
            platform_type.into(),
            options,
            None,
            None,
        )
        .await
    }

    pub async fn join_room(
        &self,
        id: impl Into<String>,
        platform_type: impl Into<String>,
        options: impl Into<RoomOptions>,
    ) -> Result<AnonymousCapability> {
        let options = options.into();
        self.anonymous_capability(
            AnonymousKind::Room,
            id.into(),
            platform_type.into(),
            CapabilityOptions {
                max_peers: options.max_peers,
                features: options.features,
            },
            Some(options.architecture),
            Some(options.delivery),
        )
        .await
    }

    /// Join a room as a developer-hosted authoritative service replica.
    ///
    /// `secret_key` is sent only to the developer-server control-plane route;
    /// it is never included in a gateway frame or exposed through TypeScript.
    pub async fn join_authority_room(
        &self,
        secret_key: impl Into<String>,
        room_id: impl Into<String>,
        device_id: impl Into<String>,
        platform_type: impl Into<String>,
        options: RoomAuthorityOptions,
    ) -> Result<RoomAuthority> {
        if options
            .max_peers
            .is_some_and(|count| !(1..=50).contains(&count))
        {
            bail!("authority service maxPeers must be within 1..50 room members");
        }
        let secret_key = required("secret_key", secret_key.into())?;
        if !secret_key.starts_with("sk_") || secret_key.len() > 128 {
            bail!("authority service secret key is invalid");
        }
        let room_id = bounded_id("room_id", room_id.into())?;
        let device_id = bounded_id("device_id", device_id.into())?;
        let platform_type = bounded_id("platform_type", platform_type.into())?;
        let service_id = bounded_id("service_id", options.service_id)?;
        if service_id.len() > 80 || options.generation == 0 {
            bail!("authority service identity or generation is invalid");
        }
        if options.shard_ids.is_empty() || options.shard_ids.len() > 64 {
            bail!("authority service must own from 1 to 64 shards");
        }
        let mut shard_ids = options
            .shard_ids
            .into_iter()
            .map(|value| bounded_id("shard_id", value))
            .collect::<Result<Vec<_>>>()?;
        let shard_count = shard_ids.len();
        if shard_ids.iter().any(|value| value.len() > 80) {
            bail!("authority service shard identifier is invalid");
        }
        shard_ids.sort();
        shard_ids.dedup();
        if shard_ids.len() != shard_count {
            bail!("authority service shard identifiers must be unique");
        }
        let assignment_public_jwk = options.assignment_signer.public_jwk(&self.inner.app_tag)?;
        validate_public_jwk(&assignment_public_jwk)?;
        let grant_provider: Arc<dyn NativeGatewayGrantProvider> =
            Arc::new(AuthorityServiceGrantProvider {
                control_plane: self.clone(),
                secret_key,
                service_id: service_id.clone(),
                generation: options.generation,
                shard_ids: shard_ids.clone(),
                assignment_public_jwk,
                device_id: device_id.clone(),
                max_peers: options.max_peers,
                features: options.features,
            });
        let capabilities = NativeCapabilities::new(
            &self.inner.api_key,
            device_id,
            platform_type,
            grant_provider,
        )?;
        #[cfg(any(test, feature = "testing-endpoints"))]
        let capabilities = capabilities.with_testing_endpoint(&self.inner.gateway_endpoint)?;
        let handle = capabilities.join_room_with_options(
            room_id,
            RoomArchitectureMode::Authority,
            RoomDelivery::Reliable,
        )?;
        Ok(RoomAuthority {
            handle,
            app_tag: self.inner.app_tag.clone(),
            service_id,
            generation: options.generation,
            shard_ids,
            assignment_signer: options.assignment_signer,
        })
    }

    pub async fn issue_ticket(
        &self,
        id: impl Into<String>,
        platform_type: impl Into<String>,
        options: CapabilityOptions,
    ) -> Result<AnonymousCapability> {
        self.anonymous_capability(
            AnonymousKind::Ticket,
            id.into(),
            platform_type.into(),
            options,
            None,
            None,
        )
        .await
    }

    async fn anonymous_capability(
        &self,
        kind: AnonymousKind,
        id: String,
        platform_type: String,
        options: CapabilityOptions,
        architecture: Option<RoomArchitectureMode>,
        room_delivery: Option<RoomDelivery>,
    ) -> Result<AnonymousCapability> {
        let platform_type = bounded_id("platform_type", platform_type)?;
        let requested_id = bounded_id("capability_id", id)?;
        let source = self
            .anonymous_source(
                kind,
                requested_id,
                options.max_peers,
                architecture,
                room_delivery,
            )
            .await?;
        let principal_id = source.principal_id.clone();
        let device_id = source.device_id.clone();
        let avenue_id = source.avenue_id.clone();
        let relay = source.relay;
        let grant_provider: Arc<dyn NativeGatewayGrantProvider> =
            Arc::new(AnonymousControlPlaneGrantProvider {
                control_plane: self.clone(),
                source: Mutex::new(source),
                kind,
                max_peers: options.max_peers,
                features: options.features,
                architecture,
                room_delivery,
            });
        let capabilities = NativeCapabilities::new(
            &self.inner.api_key,
            device_id,
            platform_type,
            grant_provider,
        )?;
        #[cfg(feature = "managed-group-encryption")]
        let capabilities = capabilities.with_managed_group_storage(
            self.inner.signer.clone(),
            self.inner
                .managed_group_store
                .lock()
                .map_err(|_| anyhow!("native managed group state store lock is poisoned"))?
                .clone(),
        );
        #[cfg(any(test, feature = "testing-endpoints"))]
        let capabilities = capabilities.with_testing_endpoint(&self.inner.gateway_endpoint)?;
        let handle = match kind {
            AnonymousKind::Space => capabilities.join_space(avenue_id)?,
            AnonymousKind::Room => capabilities.join_room_with_options(
                avenue_id,
                architecture.unwrap_or_default(),
                room_delivery.unwrap_or_default(),
            )?,
            AnonymousKind::Ticket => capabilities.issue_ticket(avenue_id)?,
        };
        Ok(AnonymousCapability {
            principal_id,
            handle,
            relay,
        })
    }

    async fn anonymous_source(
        &self,
        kind: AnonymousKind,
        requested_id: String,
        max_peers: Option<u32>,
        architecture: Option<RoomArchitectureMode>,
        room_delivery: Option<RoomDelivery>,
    ) -> Result<AnonymousCredentialSource> {
        let original_requested_id = requested_id.clone();
        let avenue_id = native_capability_avenue_id(&self.inner.api_key, kind, &requested_id);
        let proof = self.device_proof(|nonce, issued_at| {
            format!(
                "openrtc:v2:capability:{}:{}:{}:{}:{}",
                self.inner.api_key,
                kind.source_kind(),
                avenue_id,
                nonce,
                issued_at
            )
        })?;
        let mut body = json!({
            "avenue": { "kind": kind.source_kind(), "id": avenue_id },
            "deviceProof": proof,
        });
        if let Some(max_peers) = max_peers {
            body["maxPeers"] = json!(max_peers);
        }
        if let Some(architecture) = architecture {
            body["architecture"] = json!(architecture);
        }
        if let Some(room_delivery) = room_delivery {
            body["roomDelivery"] = json!(room_delivery);
        }
        let response: CapabilityResponse = self.post("/v2/capabilities", body).await?;
        let token = required("capability", response.capability)?;
        let principal_id = required_claim_string(&token, "principalId")?;
        let thumbprint = required_claim_string(&token, "deviceKeyThumbprint")?;
        let claim_exp = decode_claims(&token)?
            .get("exp")
            .and_then(Value::as_u64)
            .ok_or_else(|| anyhow!("OpenRTC capability is missing exp"))?;
        if claim_exp != response.expires_at
            || response.avenue.kind != kind.source_kind()
            || response.avenue.id != avenue_id
        {
            bail!("OpenRTC capability response scope is inconsistent");
        }
        Ok(AnonymousCredentialSource {
            token,
            expires_at_ms: response.expires_at.saturating_mul(1_000),
            principal_id,
            device_id: format!("anon_{}", thumbprint.chars().take(32).collect::<String>()),
            requested_id: original_requested_id,
            avenue_id,
            relay: relay_availability(response.iroh_relay, response.managed_turn, response.relay),
        })
    }

    async fn device_certificate(
        &self,
        device_id: &str,
        device_profile: Option<&DeviceProfile>,
        attestation: Option<&dyn AttestationProvider>,
        identity_epoch: u64,
    ) -> Result<CredentialSource> {
        let device_key_thumbprint =
            native_device_key_thumbprint(&self.inner.signer.public_jwk(&self.inner.app_tag)?)?;
        let assertion_provider = self.inner.assertion_provider.as_ref().ok_or_else(|| {
            anyhow!("authenticated devices require a native identity assertion provider")
        })?;
        let session_key_hash = assertion_provider
            .session_key()?
            .filter(|value| !value.trim().is_empty())
            .map(|value| {
                native_session_key_hash(&self.inner.app_tag, &device_key_thumbprint, value.trim())
            });
        if let Some(session_key_hash) = session_key_hash.as_deref() {
            if let Some(cached) = self
                .inner
                .certificate_store
                .load_for_session(&self.inner.app_tag, session_key_hash, device_id)
                .await?
                .filter(|value| certificate_is_reusable(value, &device_key_thumbprint, now_ms()))
            {
                return Ok(CredentialSource {
                    relay: relay_availability_from_token(&cached.token)?,
                    token: cached.token,
                    expires_at_ms: cached.expires_at_ms,
                    principal_id: cached.principal_id,
                });
            }
        }

        let identity = self
            .identity_for_epoch(identity_epoch, device_id, false)
            .await?;
        let principal_id = bounded_id("principal_id", identity.response.principal_id.clone())?;

        if let Some(cached) = self
            .inner
            .certificate_store
            .load(&self.inner.app_tag, &principal_id, device_id)
            .await?
            .filter(|value| certificate_is_reusable(value, &device_key_thumbprint, now_ms()))
        {
            return Ok(CredentialSource {
                relay: relay_availability_from_token(&cached.token)?,
                token: cached.token,
                expires_at_ms: cached.expires_at_ms,
                principal_id,
            });
        }

        // Identity sessions are intentionally short-lived. Reuse one only
        // inside the same host-declared login epoch, and exchange again only
        // when enrollment actually needs a fresh session. The provider's own
        // cached assertion is tried first; force refresh remains 401-driven.
        let identity = if identity.expires_at_ms > now_ms().saturating_add(30_000) {
            identity
        } else {
            self.identity_for_epoch(identity_epoch, device_id, true)
                .await?
        };
        if identity.response.principal_id != principal_id {
            bail!("native identity principal changed without advancing its login epoch");
        }

        let enrollment = match self
            .enroll_device(
                &identity.response.identity_session,
                &principal_id,
                device_id,
                device_profile,
                attestation,
                false,
            )
            .await
        {
            Ok(enrollment) => enrollment,
            Err(error) if is_native_device_key_recovery_required(&error) => {
                let recovery_identity = self.exchange_recovery_identity(device_id).await?;
                if recovery_identity.principal_id != principal_id {
                    bail!("native identity principal changed during device-key recovery");
                }
                self.enroll_device(
                    &recovery_identity.identity_session,
                    &principal_id,
                    device_id,
                    device_profile,
                    attestation,
                    true,
                )
                .await
                .context("recover native OpenRTC device key")?
            }
            Err(error) => return Err(error).context("enroll native OpenRTC device"),
        };
        let expires_at_ms = enrollment
            .expires_at
            .checked_mul(1_000)
            .ok_or_else(|| anyhow!("device certificate expiry overflow"))?;
        let stored = StoredCertificate {
            app_tag: self.inner.app_tag.clone(),
            principal_id: principal_id.clone(),
            device_id: device_id.to_string(),
            token: required("device certificate", enrollment.device_certificate)?,
            expires_at_ms,
            session_key_hash,
            signing_public_jwk: Some(enrollment.signing_public_jwk),
        };
        validate_stored_certificate(&stored, &device_key_thumbprint)?;
        self.inner.certificate_store.save(&stored).await?;
        Ok(CredentialSource {
            relay: relay_availability_from_token(&stored.token)?,
            token: stored.token,
            expires_at_ms,
            principal_id,
        })
    }

    async fn enroll_device(
        &self,
        identity_session: &str,
        principal_id: &str,
        device_id: &str,
        device_profile: Option<&DeviceProfile>,
        attestation: Option<&dyn AttestationProvider>,
        recover_device_key: bool,
    ) -> Result<DeviceEnrollmentResponse> {
        let proof = self.device_proof(|nonce, issued_at| {
            format!(
                "openrtc:v2:device-enroll:{}:{}:{}:{}:{}",
                self.inner.app_tag, principal_id, device_id, nonce, issued_at
            )
        })?;
        let attestation_value = if let Some(provider) = attestation {
            let challenge = format!(
                "openrtc:v2:attestation:{}:{}:{}:{}",
                self.inner.app_tag, principal_id, device_id, proof.nonce
            );
            Some(provider.evidence(&challenge, &self.inner.api_key).await?)
        } else {
            None
        };
        let mut body = json!({
            "identitySession": identity_session,
            "deviceId": device_id,
            "deviceProof": proof,
        });
        if let Some(device_profile) = device_profile {
            body["deviceProfile"] = json!(device_profile);
        }
        if let Some(attestation) = attestation_value {
            body["attestation"] = json!(attestation);
        }
        if recover_device_key {
            body["recoverDeviceKey"] = json!(true);
        }
        self.post("/v2/devices/enroll", body).await
    }

    async fn exchange_recovery_identity(
        &self,
        device_id: &str,
    ) -> Result<AssertionExchangeResponse> {
        let assertion_provider = self.inner.assertion_provider.as_ref().ok_or_else(|| {
            anyhow!("authenticated devices require a native identity assertion provider")
        })?;
        let assertion = assertion_provider
            .assertion_for_device_recovery(device_id)
            .await
            .context("obtain consumer device-key recovery assertion")?;
        let assertion_token = required("identity assertion", assertion.token)?;
        let mut body = json!({ "assertion": assertion_token });
        if let Some(provider_id) = assertion.provider_id {
            body["providerId"] = json!(provider_id);
        }
        self.post("/v2/assertions/exchange", body)
            .await
            .context("exchange consumer device-key recovery assertion")
    }

    async fn exchange_identity_after_rejection(
        &self,
        force_assertion_refresh: bool,
        device_id: &str,
    ) -> Result<AssertionExchangeResponse> {
        Ok(
            match self
                .exchange_identity(force_assertion_refresh, device_id)
                .await
            {
                Ok(identity) => identity,
                Err(error)
                    if !force_assertion_refresh
                        && error
                            .downcast_ref::<ControlPlaneHttpError>()
                            .is_some_and(|failure| failure.status == 401) =>
                {
                    // Match the browser/WASM contract: use the consumer's cached
                    // identity first and request one fresh assertion only after an
                    // explicit rejection. No timer or unbounded validation loop is
                    // introduced.
                    self.exchange_identity(true, device_id).await?
                }
                Err(error) => return Err(error),
            },
        )
    }

    async fn identity_for_epoch(
        &self,
        identity_epoch: u64,
        device_id: &str,
        require_unexpired_session: bool,
    ) -> Result<CachedIdentity> {
        let assertion_provider = self.inner.assertion_provider.as_ref().ok_or_else(|| {
            anyhow!("authenticated devices require a native identity assertion provider")
        })?;
        if assertion_provider.identity_epoch() != identity_epoch {
            bail!("native identity changed before OpenRTC capability activation");
        }
        let mut state = self.inner.auth_epoch.lock().await;
        if state.epoch != Some(identity_epoch) {
            state.epoch = Some(identity_epoch);
            state.identity = None;
        }
        if let Some(identity) = state
            .identity
            .clone()
            .filter(|identity| identity.device_id == device_id)
        {
            if !require_unexpired_session
                || identity.expires_at_ms > now_ms().saturating_add(30_000)
            {
                if assertion_provider.identity_epoch() != identity_epoch {
                    state.identity = None;
                    bail!("native identity changed during capability activation");
                }
                return Ok(identity);
            }
        }
        let response = self
            .exchange_identity_after_rejection(false, device_id)
            .await?;
        if assertion_provider.identity_epoch() != identity_epoch {
            state.identity = None;
            bail!("native identity changed during assertion exchange");
        }
        let expires_at_ms = response
            .expires_at
            .checked_mul(1_000)
            .ok_or_else(|| anyhow!("identity session expiry overflow"))?;
        let identity = CachedIdentity {
            response,
            expires_at_ms,
            device_id: device_id.to_string(),
        };
        state.identity = Some(identity.clone());
        Ok(identity)
    }

    async fn exchange_identity(
        &self,
        force_refresh: bool,
        device_id: &str,
    ) -> Result<AssertionExchangeResponse> {
        let assertion_provider = self.inner.assertion_provider.as_ref().ok_or_else(|| {
            anyhow!("authenticated devices require a native identity assertion provider")
        })?;
        let assertion = assertion_provider
            .assertion_for_device(force_refresh, device_id)
            .await
            .context("obtain consumer identity assertion")?;
        let assertion_token = required("identity assertion", assertion.token)?;
        let mut assertion_body = json!({ "assertion": assertion_token });
        if let Some(provider_id) = assertion.provider_id {
            assertion_body["providerId"] = json!(provider_id);
        }
        self.post("/v2/assertions/exchange", assertion_body)
            .await
            .context("exchange consumer identity assertion")
    }

    fn device_proof(
        &self,
        challenge: impl FnOnce(&str, u64) -> String,
    ) -> Result<NativeDeviceProof> {
        let public_key_jwk = self.inner.signer.public_jwk(&self.inner.app_tag)?;
        validate_public_jwk(&public_key_jwk)?;
        let nonce = Uuid::new_v4().simple().to_string();
        let issued_at = now_seconds();
        let challenge = challenge(&nonce, issued_at);
        let signature = self
            .inner
            .signer
            .sign(&self.inner.app_tag, challenge.as_bytes())?;
        if signature.len() != 64 {
            bail!("native device signer returned an invalid Ed25519 signature");
        }
        Ok(NativeDeviceProof {
            public_key_jwk,
            signature: base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(signature),
            nonce,
            issued_at,
        })
    }

    async fn post<T: for<'de> Deserialize<'de>>(&self, path: &str, body: Value) -> Result<T> {
        let mut object = body
            .as_object()
            .cloned()
            .ok_or_else(|| anyhow!("native control-plane body must be an object"))?;
        object.insert("apiKey".to_string(), json!(self.inner.api_key));
        self.post_json(path, Value::Object(object), None).await
    }

    async fn post_with_bearer<T: for<'de> Deserialize<'de>>(
        &self,
        path: &str,
        body: Value,
        bearer: &str,
    ) -> Result<T> {
        if !bearer.starts_with("sk_") || bearer.len() > 128 {
            bail!("native authority service secret is invalid");
        }
        self.post_json(path, body, Some(bearer)).await
    }

    async fn post_json<T: for<'de> Deserialize<'de>>(
        &self,
        path: &str,
        body: Value,
        bearer: Option<&str>,
    ) -> Result<T> {
        let url = format!("{}{}", self.inner.endpoint.trim_end_matches('/'), path);
        let request_id = format!("native_{}", Uuid::new_v4().simple());
        let serialized = serde_json::to_vec(&body).context("encode OpenRTC request")?;

        for attempt in 0..2 {
            let mut request = self
                .inner
                .http
                .post(&url)
                .header("X-OpenRTC-Idempotency-Key", &request_id)
                .header(reqwest::header::CONTENT_TYPE, "application/json")
                .body(serialized.clone());
            if let Some(bearer) = bearer {
                request = request.bearer_auth(bearer);
            }
            let response = request.send().await;
            let response = match response {
                Ok(response) => response,
                Err(_error) if attempt == 0 => {
                    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                    continue;
                }
                Err(error) => return Err(error).context("send OpenRTC request"),
            };
            let status = response.status();
            if !status.is_success() {
                let payload = response.json::<Value>().await.unwrap_or(Value::Null);
                let message = payload
                    .get("error")
                    .and_then(Value::as_str)
                    .unwrap_or("OpenRTC control-plane request failed")
                    .chars()
                    .take(256)
                    .collect::<String>();
                let error = ControlPlaneHttpError {
                    service_error: crate::service_errors::ServiceError::from_value(&payload),
                    status: status.as_u16(),
                    message,
                    reason: payload
                        .get("reason")
                        .and_then(Value::as_str)
                        .filter(|value| {
                            !value.is_empty()
                                && value.len() <= 80
                                && value.bytes().all(|byte| {
                                    byte.is_ascii_lowercase()
                                        || byte.is_ascii_digit()
                                        || byte == b'-'
                                })
                        })
                        .map(str::to_string),
                };
                // Preserve the legacy transient HTTP fallback, but do not
                // retry a typed service denial before its retry policy can
                // reach the existing lifecycle owner.
                if attempt == 0
                    && error.service_error.is_none()
                    && matches!(
                        status,
                        reqwest::StatusCode::BAD_GATEWAY
                            | reqwest::StatusCode::SERVICE_UNAVAILABLE
                            | reqwest::StatusCode::GATEWAY_TIMEOUT
                    )
                {
                    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                    continue;
                }
                return Err(anyhow::Error::new(error));
            }
            return response
                .json::<T>()
                .await
                .context("decode OpenRTC response");
        }
        unreachable!("native control-plane retry loop has two terminal attempts")
    }
}

fn is_native_device_key_recovery_required(error: &anyhow::Error) -> bool {
    error
        .downcast_ref::<ControlPlaneHttpError>()
        .is_some_and(|failure| {
            failure.status == 412
                && failure.reason.as_deref() == Some("device-key-recovery-required")
        })
}

fn spawn_identity_epoch_monitor(
    mut receiver: watch::Receiver<u64>,
    identity_epoch: u64,
    closer: crate::native_coordination_gateway::NativeCapabilityCloser,
    relay: CredentialRelay,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        loop {
            if receiver.changed().await.is_err() {
                return;
            }
            if *receiver.borrow_and_update() != identity_epoch {
                let _ = relay.set(None);
                closer.close().await;
                return;
            }
        }
    })
}

struct ControlPlaneGrantProvider {
    control_plane: ControlPlane,
    device_id: String,
    source: Mutex<CredentialSource>,
    max_peers: Option<u32>,
    features: Features,
    device_profile: Option<DeviceProfile>,
    attestation: Option<Arc<dyn AttestationProvider>>,
    identity_relay: CredentialRelay,
    identity_epoch: u64,
}

struct AnonymousControlPlaneGrantProvider {
    control_plane: ControlPlane,
    source: Mutex<AnonymousCredentialSource>,
    kind: AnonymousKind,
    max_peers: Option<u32>,
    features: Features,
    architecture: Option<RoomArchitectureMode>,
    room_delivery: Option<RoomDelivery>,
}

struct AuthorityServiceGrantProvider {
    control_plane: ControlPlane,
    secret_key: String,
    service_id: String,
    generation: u64,
    shard_ids: Vec<String>,
    assignment_public_jwk: Value,
    device_id: String,
    max_peers: Option<u32>,
    features: Features,
}

#[async_trait]
impl NativeGatewayGrantProvider for ControlPlaneGrantProvider {
    async fn grant(&self, request: NativeGatewayGrantRequest) -> Result<NativeGatewayGrant> {
        if request.device_id != self.device_id {
            bail!("gateway grant request device does not match enrolled device");
        }
        let mut source = self.source.lock().await;
        if source.expires_at_ms <= now_ms().saturating_add(SOURCE_RENEW_SKEW_MS) {
            *source = self
                .control_plane
                .device_certificate(
                    &self.device_id,
                    self.device_profile.as_ref(),
                    self.attestation.as_deref(),
                    self.identity_epoch,
                )
                .await?;
            self.identity_relay.set(Some(source.token.clone()))?;
        }
        let source_jti = required_claim_string(&source.token, "jti")?;
        let proof = self.control_plane.device_proof(|nonce, issued_at| {
            format!(
                "openrtc:v2:gateway-grant:{}:{}:{}:{}:{}:{}",
                source_jti,
                request.avenue.kind,
                request.avenue.id,
                request.runtime_instance_id,
                nonce,
                issued_at
            )
        })?;
        let mut grant_body = json!({
            "credentialType": "device-certificate",
            "credential": source.token,
            "avenue": request.avenue,
            "runtimeInstanceId": request.runtime_instance_id,
            "ticketFingerprint": request.ticket_fingerprint,
            "deviceProof": proof,
            "features": available_features(self.features.clone(), source.relay),
        });
        if let Some(refresh_grant) = request.refresh_grant {
            grant_body["refreshGrant"] = json!(refresh_grant);
        }
        if let Some(max_peers) = self.max_peers {
            grant_body["maxPeers"] = json!(max_peers);
        }
        if let Some(architecture) = request.architecture {
            grant_body["architecture"] = json!(architecture);
        }
        if let Some(room_delivery) = request.room_delivery {
            grant_body["roomDelivery"] = json!(room_delivery);
        }
        if let Some(device_profile) = &self.device_profile {
            grant_body["deviceProfile"] = json!(device_profile);
        }
        let response: GatewayGrantResponse = self
            .control_plane
            .post("/v2/gateway/grants", grant_body)
            .await?;
        if response.gateway_url.trim_end_matches('/')
            != self
                .control_plane
                .inner
                .gateway_endpoint
                .trim_end_matches('/')
        {
            bail!("OpenRTC returned an unexpected native gateway origin");
        }
        Ok(NativeGatewayGrant {
            protocol_version: response.protocol_version,
            gateway_url: response.gateway_url,
            route_key: response.route_key,
            token: response.token,
            expires_at_ms: response.expires_at_ms,
        })
    }
}

#[async_trait]
impl NativeGatewayGrantProvider for AnonymousControlPlaneGrantProvider {
    async fn grant(&self, request: NativeGatewayGrantRequest) -> Result<NativeGatewayGrant> {
        let mut source = self.source.lock().await;
        if request.device_id != source.device_id {
            bail!("gateway grant request device does not match the capability install key");
        }
        if source.expires_at_ms <= now_ms().saturating_add(SOURCE_RENEW_SKEW_MS) {
            *source = self
                .control_plane
                .anonymous_source(
                    self.kind,
                    source.requested_id.clone(),
                    self.max_peers,
                    self.architecture,
                    self.room_delivery,
                )
                .await?;
        }
        let expected_kind = match self.kind {
            AnonymousKind::Ticket => "session",
            _ => self.kind.source_kind(),
        };
        if request.avenue.kind != expected_kind || request.avenue.id != source.avenue_id {
            bail!("gateway grant request avenue does not match the capability");
        }
        let source_jti = required_claim_string(&source.token, "jti")?;
        let proof = self.control_plane.device_proof(|nonce, issued_at| {
            format!(
                "openrtc:v2:gateway-grant:{}:{}:{}:{}:{}:{}",
                source_jti,
                request.avenue.kind,
                request.avenue.id,
                request.runtime_instance_id,
                nonce,
                issued_at
            )
        })?;
        let mut grant_body = json!({
            "credentialType": "capability",
            "credential": source.token,
            "avenue": request.avenue,
            "runtimeInstanceId": request.runtime_instance_id,
            "ticketFingerprint": request.ticket_fingerprint,
            "deviceProof": proof,
            "features": available_features(self.features.clone(), source.relay),
        });
        if let Some(refresh_grant) = request.refresh_grant {
            grant_body["refreshGrant"] = json!(refresh_grant);
        }
        if let Some(max_peers) = self.max_peers {
            grant_body["maxPeers"] = json!(max_peers);
        }
        if let Some(architecture) = request.architecture {
            grant_body["architecture"] = json!(architecture);
        }
        if let Some(room_delivery) = request.room_delivery {
            grant_body["roomDelivery"] = json!(room_delivery);
        }
        let response: GatewayGrantResponse = self
            .control_plane
            .post("/v2/gateway/grants", grant_body)
            .await?;
        if response.gateway_url.trim_end_matches('/')
            != self
                .control_plane
                .inner
                .gateway_endpoint
                .trim_end_matches('/')
        {
            bail!("OpenRTC returned an unexpected native gateway origin");
        }
        Ok(NativeGatewayGrant {
            protocol_version: response.protocol_version,
            gateway_url: response.gateway_url,
            route_key: response.route_key,
            token: response.token,
            expires_at_ms: response.expires_at_ms,
        })
    }
}

#[async_trait]
impl NativeGatewayGrantProvider for AuthorityServiceGrantProvider {
    async fn grant(&self, request: NativeGatewayGrantRequest) -> Result<NativeGatewayGrant> {
        if request.device_id != self.device_id
            || request.avenue.kind != "room"
            || request.architecture != Some(RoomArchitectureMode::Authority)
        {
            bail!("authority service grant request scope is invalid");
        }
        let assignment_key_x = self
            .assignment_public_jwk
            .get("x")
            .and_then(Value::as_str)
            .ok_or_else(|| anyhow!("authority assignment public key is invalid"))?;
        let proof = self.control_plane.device_proof(|nonce, issued_at| {
            format!(
                "openrtc:v2:authority-service-grant:{}:{}:{}:{}:{}:{}:{}:{}:{}",
                self.control_plane.inner.app_tag,
                request.avenue.id,
                self.service_id,
                self.generation,
                self.shard_ids.join(","),
                assignment_key_x,
                request.runtime_instance_id,
                nonce,
                issued_at,
            )
        })?;
        let mut body = json!({
            "avenue": request.avenue,
            "serviceId": self.service_id,
            "generation": self.generation,
            "shardIds": self.shard_ids,
            "assignmentPublicKeyJwk": self.assignment_public_jwk,
            "deviceId": self.device_id,
            "runtimeInstanceId": request.runtime_instance_id,
            "ticketFingerprint": request.ticket_fingerprint,
            "deviceProof": proof,
            "features": self.features,
        });
        if let Some(max_peers) = self.max_peers {
            body["maxPeers"] = json!(max_peers);
        }
        if let Some(refresh_grant) = request.refresh_grant {
            body["refreshGrant"] = json!(refresh_grant);
        }
        let response: GatewayGrantResponse = self
            .control_plane
            .post_with_bearer("/v2/developer/authority/grants", body, &self.secret_key)
            .await?;
        if response.gateway_url.trim_end_matches('/')
            != self
                .control_plane
                .inner
                .gateway_endpoint
                .trim_end_matches('/')
        {
            bail!("OpenRTC returned an unexpected native gateway origin");
        }
        Ok(NativeGatewayGrant {
            protocol_version: response.protocol_version,
            gateway_url: response.gateway_url,
            route_key: response.route_key,
            token: response.token,
            expires_at_ms: response.expires_at_ms,
        })
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct NativeDeviceProof {
    public_key_jwk: Value,
    signature: String,
    nonce: String,
    issued_at: u64,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AssertionExchangeResponse {
    identity_session: String,
    principal_id: String,
    expires_at: u64,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct DeviceEnrollmentResponse {
    device_certificate: String,
    expires_at: u64,
    signing_public_jwk: Value,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CapabilityResponse {
    capability: String,
    expires_at: u64,
    avenue: CapabilityAvenueResponse,
    #[serde(default)]
    iroh_relay: Option<bool>,
    #[serde(default)]
    managed_turn: bool,
    #[serde(default)]
    relay: Option<bool>,
}

#[derive(Deserialize)]
struct CapabilityAvenueResponse {
    kind: String,
    id: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GatewayGrantResponse {
    protocol_version: u8,
    gateway_url: String,
    route_key: String,
    token: String,
    expires_at_ms: u64,
}

fn now_seconds() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

fn now_ms() -> u64 {
    now_seconds().saturating_mul(1_000)
}

fn required(field: &str, value: String) -> Result<String> {
    let value = value.trim().to_string();
    if value.is_empty() {
        bail!("{field} is required");
    }
    Ok(value)
}

fn bounded_id(field: &str, value: String) -> Result<String> {
    let value = required(field, value)?;
    if value.len() > 160
        || !value.bytes().all(|byte| {
            byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':' | b'@')
        })
    {
        bail!("{field} is invalid");
    }
    Ok(value)
}

fn bounded_visible_text(field: &str, value: String, max_len: usize) -> Result<String> {
    let value = required(field, value)?;
    if value.len() > max_len || value.chars().any(char::is_control) {
        bail!("{field} is invalid");
    }
    Ok(value)
}

fn normalized_device_profile(
    profile: Option<DeviceProfile>,
    platform_type: &str,
) -> Result<Option<DeviceProfile>> {
    let profile = profile.unwrap_or_default();
    let name = profile
        .name
        .map(|value| bounded_visible_text("device_profile.name", value, 120))
        .transpose()?;
    let platform = Some(bounded_visible_text(
        "device_profile.platform",
        profile
            .platform
            .unwrap_or_else(|| platform_type.to_string()),
        80,
    )?);
    Ok(Some(DeviceProfile { name, platform }))
}

fn native_capability_avenue_id(api_key: &str, kind: AnonymousKind, requested_id: &str) -> String {
    if kind != AnonymousKind::Space {
        return requested_id.to_string();
    }
    let digest =
        <sha2::Sha256 as sha2::Digest>::digest(format!("{api_key}:{requested_id}").as_bytes());
    hex::encode(digest)
}

#[cfg(any(test, feature = "testing-endpoints"))]
fn validate_endpoint(value: String) -> Result<String> {
    let parsed = reqwest::Url::parse(value.trim())?;
    if !matches!(parsed.scheme(), "https" | "http")
        || parsed.host_str().is_none()
        || !parsed.username().is_empty()
        || parsed.password().is_some()
        || parsed.query().is_some()
        || parsed.fragment().is_some()
    {
        bail!("OpenRTC testing endpoint is invalid");
    }
    Ok(parsed.as_str().trim_end_matches('/').to_string())
}

fn validate_public_jwk(value: &Value) -> Result<()> {
    let object = value
        .as_object()
        .ok_or_else(|| anyhow!("native device public key is invalid"))?;
    let x = object.get("x").and_then(Value::as_str).unwrap_or_default();
    if object.get("kty").and_then(Value::as_str) != Some("OKP")
        || object.get("crv").and_then(Value::as_str) != Some("Ed25519")
        || object.contains_key("d")
        || x.len() != 43
        || !x
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
    {
        bail!("native device public key must be a public Ed25519 JWK");
    }
    Ok(())
}

fn decode_claims(token: &str) -> Result<Value> {
    let payload = token
        .split('.')
        .nth(1)
        .ok_or_else(|| anyhow!("OpenRTC credential is malformed"))?;
    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(payload)
        .context("decode OpenRTC credential claims")?;
    serde_json::from_slice(&bytes).context("parse OpenRTC credential claims")
}

fn required_claim_string(token: &str, name: &str) -> Result<String> {
    decode_claims(token)?
        .get(name)
        .and_then(Value::as_str)
        .map(str::to_string)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| anyhow!("OpenRTC credential is missing {name}"))
}

fn native_device_key_thumbprint(public_key_jwk: &Value) -> Result<String> {
    validate_public_jwk(public_key_jwk)?;
    let canonical = json!({
        "crv": public_key_jwk.get("crv").and_then(Value::as_str),
        "kty": public_key_jwk.get("kty").and_then(Value::as_str),
        "x": public_key_jwk.get("x").and_then(Value::as_str),
    });
    let bytes = serde_json::to_vec(&canonical)?;
    let digest = <sha2::Sha256 as sha2::Digest>::digest(bytes);
    Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest))
}

fn native_session_key_hash(
    app_tag: &str,
    device_key_thumbprint: &str,
    session_key: &str,
) -> String {
    let digest = <sha2::Sha256 as sha2::Digest>::digest(
        format!(
            "openrtc:v2:session\0{}\0{}\0{}",
            app_tag, device_key_thumbprint, session_key,
        )
        .as_bytes(),
    );
    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest)
}

fn validate_stored_certificate(
    value: &StoredCertificate,
    device_key_thumbprint: &str,
) -> Result<()> {
    let signing_public_jwk = value
        .signing_public_jwk
        .as_ref()
        .ok_or_else(|| anyhow!("stored OpenRTC device certificate has no verification key"))?;
    verify_device_certificate_signature(&value.token, signing_public_jwk)?;
    let claims = decode_claims(&value.token)?;
    let issued_at = claims.get("iat").and_then(Value::as_u64);
    let expires_at = claims.get("exp").and_then(Value::as_u64);
    if claims.get("iss").and_then(Value::as_str) != Some("openrtc")
        || claims.get("aud").and_then(Value::as_str) != Some("openrtc:v2:gateway-grant")
        || claims.get("typ").and_then(Value::as_str) != Some("device-certificate")
        || claims.get("appTag").and_then(Value::as_str) != Some(value.app_tag.as_str())
        || claims.get("principalId").and_then(Value::as_str) != Some(value.principal_id.as_str())
        || claims.get("principalKey").and_then(Value::as_str).is_none()
        || claims.get("deviceId").and_then(Value::as_str) != Some(value.device_id.as_str())
        || claims.get("deviceKeyThumbprint").and_then(Value::as_str) != Some(device_key_thumbprint)
        || claims.get("jti").and_then(Value::as_str).is_none()
        || issued_at.is_none()
        || expires_at.and_then(|exp| exp.checked_mul(1_000)) != Some(value.expires_at_ms)
        || issued_at
            .zip(expires_at)
            .is_none_or(|(iat, exp)| iat >= exp)
    {
        bail!("stored OpenRTC device certificate scope is invalid");
    }
    Ok(())
}

fn verify_device_certificate_signature(token: &str, public_jwk: &Value) -> Result<()> {
    let mut parts = token.split('.');
    let header_segment = parts
        .next()
        .ok_or_else(|| anyhow!("invalid certificate JWT"))?;
    let claims_segment = parts
        .next()
        .ok_or_else(|| anyhow!("invalid certificate JWT"))?;
    let signature_segment = parts
        .next()
        .ok_or_else(|| anyhow!("invalid certificate JWT"))?;
    if parts.next().is_some() {
        bail!("invalid certificate JWT");
    }
    let header: Value = serde_json::from_slice(
        &base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(header_segment)
            .context("decode certificate header")?,
    )?;
    if header.get("alg").and_then(Value::as_str) != Some("EdDSA")
        || public_jwk.get("kty").and_then(Value::as_str) != Some("OKP")
        || public_jwk.get("crv").and_then(Value::as_str) != Some("Ed25519")
        || header.get("kid").and_then(Value::as_str)
            != public_jwk.get("kid").and_then(Value::as_str)
    {
        bail!("unsupported OpenRTC certificate signing key");
    }
    let public_key = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(
            public_jwk
                .get("x")
                .and_then(Value::as_str)
                .ok_or_else(|| anyhow!("certificate signing key is missing x"))?,
        )
        .context("decode certificate signing key")?;
    let public_key: [u8; 32] = public_key
        .try_into()
        .map_err(|_| anyhow!("certificate signing key has invalid length"))?;
    let verifying_key =
        VerifyingKey::from_bytes(&public_key).context("parse certificate signing key")?;
    let signature = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(signature_segment)
        .context("decode certificate signature")?;
    let signature = Signature::from_slice(&signature).context("parse certificate signature")?;
    verifying_key
        .verify(
            format!("{header_segment}.{claims_segment}").as_bytes(),
            &signature,
        )
        .context("verify OpenRTC device certificate")
}

fn certificate_is_reusable(
    value: &StoredCertificate,
    device_key_thumbprint: &str,
    at_ms: u64,
) -> bool {
    value.expires_at_ms > at_ms.saturating_add(DEVICE_CERTIFICATE_RENEW_SKEW_MS)
        && validate_stored_certificate(value, device_key_thumbprint).is_ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use ed25519_dalek::{Signer as _, SigningKey};
    use std::sync::atomic::{AtomicU64, Ordering};
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    struct TestSigner;

    struct NeverGrantProvider;

    #[async_trait]
    impl NativeGatewayGrantProvider for NeverGrantProvider {
        async fn grant(&self, _request: NativeGatewayGrantRequest) -> Result<NativeGatewayGrant> {
            bail!("inactive epoch-retirement test must not request a gateway grant")
        }
    }

    #[derive(Default)]
    struct RecordingAssertionProvider {
        force_refreshes: StdMutex<Vec<bool>>,
        device_ids: StdMutex<Vec<String>>,
        identity_epoch: AtomicU64,
    }

    #[async_trait]
    impl AssertionProvider for RecordingAssertionProvider {
        async fn assertion(&self, force_refresh: bool) -> Result<IdentityAssertion> {
            self.force_refreshes.lock().unwrap().push(force_refresh);
            Ok(IdentityAssertion {
                token: if force_refresh { "fresh" } else { "stale" }.to_string(),
                provider_id: None,
            })
        }

        async fn assertion_for_device(
            &self,
            force_refresh: bool,
            device_id: &str,
        ) -> Result<IdentityAssertion> {
            self.device_ids.lock().unwrap().push(device_id.to_string());
            self.assertion(force_refresh).await
        }

        fn identity_epoch(&self) -> u64 {
            self.identity_epoch.load(Ordering::Acquire)
        }
    }

    impl DeviceSigner for TestSigner {
        fn public_jwk(&self, _app_tag: &str) -> Result<Value> {
            Ok(json!({
                "kty": "OKP",
                "crv": "Ed25519",
                "x": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
            }))
        }

        fn sign(&self, _app_tag: &str, _challenge: &[u8]) -> Result<Vec<u8>> {
            Ok(vec![0; 64])
        }
    }

    fn signed_certificate(
        app_tag: &str,
        principal_id: &str,
        device_id: &str,
        expires_at: u64,
    ) -> (String, Value) {
        let signing_key = SigningKey::from_bytes(&[7_u8; 32]);
        let kid = "test-signing-key";
        let header = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(
            serde_json::to_vec(&json!({ "alg": "EdDSA", "typ": "JWT", "kid": kid })).unwrap(),
        );
        let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(
            serde_json::to_vec(&json!({
                "iss": "openrtc",
                "aud": "openrtc:v2:gateway-grant",
                "typ": "device-certificate",
                "appTag": app_tag,
                "principalId": principal_id,
                "principalKey": "principal-key",
                "deviceId": device_id,
                "deviceKeyThumbprint": "thumbprint",
                "iat": expires_at - 60,
                "exp": expires_at,
                "jti": "test-jti",
            }))
            .unwrap(),
        );
        let signing_input = format!("{header}.{claims}");
        let signature = signing_key.sign(signing_input.as_bytes());
        let token = format!(
            "{signing_input}.{}",
            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(signature.to_bytes())
        );
        let public_jwk = json!({
            "kty": "OKP",
            "crv": "Ed25519",
            "alg": "EdDSA",
            "kid": kid,
            "x": base64::engine::general_purpose::URL_SAFE_NO_PAD
                .encode(signing_key.verifying_key().to_bytes()),
        });
        (token, public_jwk)
    }

    #[test]
    fn cached_certificate_is_scope_bound_and_renews_a_day_early() {
        let now = now_ms();
        let expires_at = now / 1_000 + 2 * 24 * 60 * 60;
        let (token, public_jwk) =
            signed_certificate("app_0000000000000000", "principal", "device", expires_at);
        let value = StoredCertificate {
            app_tag: "app_0000000000000000".to_string(),
            principal_id: "principal".to_string(),
            device_id: "device".to_string(),
            token,
            expires_at_ms: expires_at * 1_000,
            session_key_hash: Some("session-hash".to_string()),
            signing_public_jwk: Some(public_jwk),
        };
        assert!(certificate_is_reusable(&value, "thumbprint", now));
        assert!(!certificate_is_reusable(
            &value,
            "thumbprint",
            value.expires_at_ms - DEVICE_CERTIFICATE_RENEW_SKEW_MS + 1,
        ));

        let mut wrong = value.clone();
        wrong.device_id = "other-device".to_string();
        assert!(!certificate_is_reusable(&wrong, "thumbprint", now));
        assert!(!certificate_is_reusable(&value, "rotated-thumbprint", now));

        let mut tampered = value.clone();
        tampered.principal_id = "attacker".to_string();
        assert!(!certificate_is_reusable(&tampered, "thumbprint", now));

        let mut missing_key = value.clone();
        missing_key.signing_public_jwk = None;
        assert!(!certificate_is_reusable(&missing_key, "thumbprint", now));
    }

    #[test]
    fn device_public_jwk_rejects_private_material() {
        assert!(validate_public_jwk(&json!({
            "kty": "OKP",
            "crv": "Ed25519",
            "x": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
        }))
        .is_ok());
        assert!(validate_public_jwk(&json!({
            "kty": "OKP",
            "crv": "Ed25519",
            "x": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
            "d": "secret",
        }))
        .is_err());
    }

    #[test]
    fn native_device_profile_defaults_platform_and_rejects_control_text() {
        assert_eq!(
            normalized_device_profile(None, "ios").unwrap(),
            Some(DeviceProfile {
                name: None,
                platform: Some("ios".to_string()),
            }),
        );
        assert_eq!(
            normalized_device_profile(
                Some(DeviceProfile {
                    name: Some("Bryant's iPhone".to_string()),
                    platform: None,
                }),
                "ios",
            )
            .unwrap(),
            Some(DeviceProfile {
                name: Some("Bryant's iPhone".to_string()),
                platform: Some("ios".to_string()),
            }),
        );
        assert!(normalized_device_profile(
            Some(DeviceProfile {
                name: Some("unsafe\nname".to_string()),
                platform: Some("ios".to_string()),
            }),
            "ios",
        )
        .is_err());
    }

    #[test]
    fn native_relay_capabilities_do_not_infer_managed_turn_from_legacy_relay() {
        let legacy = relay_availability(None, false, Some(true));
        assert_eq!(
            legacy,
            RelayAvailability {
                iroh_relay: true,
                managed_turn: false,
            }
        );

        let requested = Features {
            iroh_relay: true,
            managed_turn: true,
            ..Features::default()
        };
        assert_eq!(
            available_features(requested, legacy),
            Features {
                iroh_relay: true,
                managed_turn: false,
                ..Features::default()
            }
        );
    }

    #[test]
    fn native_service_error_retryability_overrides_http_status() {
        let mut error = ControlPlaneHttpError {
            status: 429,
            message: "paused".into(),
            reason: None,
            service_error: None,
        };
        assert!(error.is_retryable());
        error.service_error = crate::service_errors::ServiceError::from_value(&serde_json::json!({
            "code": "credit-exhausted", "retryable": false, "scope": "account", "requestId": "request-1"
        }));
        assert!(!error.is_retryable());
        error.status = 503;
        assert!(!error.is_retryable());
        error.service_error = crate::service_errors::ServiceError::from_value(&serde_json::json!({
            "code": "app-rate-limited", "retryable": true, "retryAfterMs": 2300
        }));
        assert!(error.is_retryable());
        assert_eq!(error.service_error.unwrap().retry_after_ms, Some(2300));
    }

    #[test]
    fn native_device_key_recovery_requires_exact_status_and_reason() {
        let required = anyhow::Error::new(ControlPlaneHttpError {
            service_error: None,
            status: 412,
            message: "recovery required".to_string(),
            reason: Some("device-key-recovery-required".to_string()),
        });
        assert!(is_native_device_key_recovery_required(&required));

        for (status, reason) in [
            (403, Some("device-key-recovery-required")),
            (412, Some("device-certificate-revoked")),
            (412, None),
        ] {
            let unrelated = anyhow::Error::new(ControlPlaneHttpError {
                service_error: None,
                status,
                message: "unrelated".to_string(),
                reason: reason.map(str::to_string),
            });
            assert!(!is_native_device_key_recovery_required(&unrelated));
        }
    }

    #[tokio::test]
    async fn authority_capacity_is_bounded_before_network_or_runtime_start() {
        let control =
            ControlPlane::anonymous(crate::test_constants::TEST_API_KEY, Arc::new(TestSigner))
                .unwrap();
        for max_peers in [
            None,
            Some(0),
            Some(1),
            Some(8),
            Some(50),
            Some(51),
            Some(5_000),
        ] {
            let result = control
                .join_authority_room(
                    "sk_test_service",
                    "room",
                    "service",
                    "native",
                    RoomAuthorityOptions {
                        service_id: "authority".into(),
                        generation: 1,
                        shard_ids: vec!["main".into()],
                        max_peers,
                        features: Features::default(),
                        assignment_signer: Arc::new(TestSigner),
                    },
                )
                .await;
            if max_peers.is_some_and(|count| !(1..=50).contains(&count)) {
                assert!(result.err().unwrap().to_string().contains("maxPeers"));
            } else {
                result.unwrap().close().await;
            }
        }
    }

    #[tokio::test]
    async fn anonymous_constructor_is_network_idle_and_rejects_authenticated_devices() {
        let control =
            ControlPlane::anonymous(crate::test_constants::TEST_API_KEY, Arc::new(TestSigner))
                .expect("anonymous v2 control plane");
        assert_eq!(
            control.app_tag(),
            crate::app_tag_from_api_key(crate::test_constants::TEST_API_KEY),
        );
        let error = control
            .device_certificate("device", None, None, 0)
            .await
            .expect_err("anonymous clients do not own consumer authentication");
        assert!(error.to_string().contains("identity assertion provider"));
    }

    #[tokio::test]
    async fn control_plane_retry_reuses_the_exact_body_and_idempotency_key() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let observed = Arc::new(Mutex::new(Vec::<(String, Vec<u8>)>::new()));
        let server_observed = observed.clone();
        let server = tokio::spawn(async move {
            for attempt in 0..2 {
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut bytes = Vec::new();
                let mut buffer = [0_u8; 4096];
                let header_end = loop {
                    let read = stream.read(&mut buffer).await.unwrap();
                    assert!(read > 0);
                    bytes.extend_from_slice(&buffer[..read]);
                    if let Some(index) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
                        break index + 4;
                    }
                };
                let headers = String::from_utf8_lossy(&bytes[..header_end]).to_string();
                let content_length = headers
                    .lines()
                    .find_map(|line| {
                        let (name, value) = line.split_once(':')?;
                        name.eq_ignore_ascii_case("content-length")
                            .then(|| value.trim().parse::<usize>().unwrap())
                    })
                    .unwrap_or(0);
                while bytes.len() < header_end + content_length {
                    let read = stream.read(&mut buffer).await.unwrap();
                    assert!(read > 0);
                    bytes.extend_from_slice(&buffer[..read]);
                }
                let request_id = headers
                    .lines()
                    .find_map(|line| {
                        let (name, value) = line.split_once(':')?;
                        name.eq_ignore_ascii_case("x-openrtc-idempotency-key")
                            .then(|| value.trim().to_string())
                    })
                    .expect("idempotency header");
                server_observed.lock().await.push((
                    request_id,
                    bytes[header_end..header_end + content_length].to_vec(),
                ));

                let (status, body) = if attempt == 0 {
                    ("503 Service Unavailable", r#"{"error":"retry"}"#)
                } else {
                    ("200 OK", r#"{"ok":true}"#)
                };
                stream
                    .write_all(
                        format!(
                            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                            body.len(),
                        )
                        .as_bytes(),
                    )
                    .await
                    .unwrap();
            }
        });

        let control =
            ControlPlane::anonymous(crate::test_constants::TEST_API_KEY, Arc::new(TestSigner))
                .unwrap()
                .with_testing_endpoints(format!("http://{address}"), "http://127.0.0.1:1")
                .unwrap();
        let response: Value = control
            .post("/retry", json!({ "intent": "same" }))
            .await
            .unwrap();
        assert_eq!(response, json!({ "ok": true }));
        server.await.unwrap();

        let observed = observed.lock().await;
        assert_eq!(observed.len(), 2);
        assert_eq!(observed[0], observed[1]);
    }

    #[tokio::test]
    async fn native_identity_refreshes_once_only_after_unauthorized() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            for attempt in 0..2 {
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut bytes = Vec::new();
                let mut buffer = [0_u8; 4096];
                let header_end = loop {
                    let read = stream.read(&mut buffer).await.unwrap();
                    assert!(read > 0);
                    bytes.extend_from_slice(&buffer[..read]);
                    if let Some(index) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
                        break index + 4;
                    }
                };
                let headers = String::from_utf8_lossy(&bytes[..header_end]);
                let content_length = headers
                    .lines()
                    .find_map(|line| {
                        let (name, value) = line.split_once(':')?;
                        name.eq_ignore_ascii_case("content-length")
                            .then(|| value.trim().parse::<usize>().unwrap())
                    })
                    .unwrap_or(0);
                while bytes.len() < header_end + content_length {
                    let read = stream.read(&mut buffer).await.unwrap();
                    assert!(read > 0);
                    bytes.extend_from_slice(&buffer[..read]);
                }
                let request_body: Value =
                    serde_json::from_slice(&bytes[header_end..header_end + content_length])
                        .unwrap();
                let expected_assertion = if attempt == 0 { "stale" } else { "fresh" };
                assert_eq!(
                    request_body.get("assertion").and_then(Value::as_str),
                    Some(expected_assertion),
                );
                let (status, body) = if attempt == 0 {
                    ("401 Unauthorized", r#"{"error":"assertion rejected"}"#)
                } else {
                    (
                        "200 OK",
                        r#"{"identitySession":"identity","principalId":"principal","expiresAt":4102444800}"#,
                    )
                };
                stream
                    .write_all(
                        format!(
                            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                            body.len(),
                        )
                        .as_bytes(),
                    )
                    .await
                    .unwrap();
            }
        });

        let provider = Arc::new(RecordingAssertionProvider::default());
        let control = ControlPlane::new(
            crate::test_constants::TEST_API_KEY,
            provider.clone(),
            Arc::new(TestSigner),
            Arc::new(InMemoryCertificate::default()),
        )
        .unwrap()
        .with_testing_endpoints(format!("http://{address}"), "http://127.0.0.1:1")
        .unwrap();

        let identity = control
            .exchange_identity_after_rejection(false, "device-a")
            .await
            .unwrap();
        assert_eq!(identity.principal_id, "principal");
        assert_eq!(*provider.force_refreshes.lock().unwrap(), vec![false, true]);
        server.await.unwrap();
    }

    #[tokio::test]
    async fn native_identity_exchange_is_coalesced_per_host_login_epoch_and_device() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            for attempt in 0..2 {
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut bytes = Vec::new();
                let mut buffer = [0_u8; 4096];
                let header_end = loop {
                    let read = stream.read(&mut buffer).await.unwrap();
                    assert!(read > 0);
                    bytes.extend_from_slice(&buffer[..read]);
                    if let Some(index) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
                        break index + 4;
                    }
                };
                let headers = String::from_utf8_lossy(&bytes[..header_end]);
                let content_length = headers
                    .lines()
                    .find_map(|line| {
                        let (name, value) = line.split_once(':')?;
                        name.eq_ignore_ascii_case("content-length")
                            .then(|| value.trim().parse::<usize>().unwrap())
                    })
                    .unwrap_or(0);
                while bytes.len() < header_end + content_length {
                    let read = stream.read(&mut buffer).await.unwrap();
                    assert!(read > 0);
                    bytes.extend_from_slice(&buffer[..read]);
                }
                let body = format!(
                    r#"{{"identitySession":"identity-{attempt}","principalId":"principal-{attempt}","expiresAt":4102444800}}"#,
                );
                stream
                    .write_all(
                        format!(
                            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                            body.len(),
                        )
                        .as_bytes(),
                    )
                    .await
                    .unwrap();
            }
        });

        let provider = Arc::new(RecordingAssertionProvider::default());
        let control = ControlPlane::new(
            crate::test_constants::TEST_API_KEY,
            provider.clone(),
            Arc::new(TestSigner),
            Arc::new(InMemoryCertificate::default()),
        )
        .unwrap()
        .with_testing_endpoints(format!("http://{address}"), "http://127.0.0.1:1")
        .unwrap();

        let first = control
            .identity_for_epoch(0, "device-a", false)
            .await
            .unwrap();
        let reused = control
            .identity_for_epoch(0, "device-a", false)
            .await
            .unwrap();
        assert_eq!(first.response.principal_id, "principal-0");
        assert_eq!(reused.response.principal_id, "principal-0");
        assert_eq!(*provider.force_refreshes.lock().unwrap(), vec![false]);

        // A second installation in the same signed-in epoch must obtain its
        // own consumer assertion. Reusing device-a's identity session would
        // bypass consumer-owned product device admission.
        let next = control
            .identity_for_epoch(0, "device-b", false)
            .await
            .unwrap();
        assert_eq!(next.response.principal_id, "principal-1");
        assert_eq!(
            *provider.force_refreshes.lock().unwrap(),
            vec![false, false]
        );
        assert_eq!(
            *provider.device_ids.lock().unwrap(),
            vec!["device-a".to_string(), "device-b".to_string()]
        );
        server.await.unwrap();
    }

    #[tokio::test]
    async fn native_login_epoch_change_retires_the_old_capability_without_network_work() {
        let capabilities = NativeCapabilities::new(
            crate::test_constants::TEST_API_KEY,
            "device",
            "native",
            Arc::new(NeverGrantProvider),
        )
        .unwrap();
        let handle = capabilities.devices("principal").unwrap();
        let relay = CredentialRelay::default();
        relay.set(Some("device-certificate".to_string())).unwrap();
        let credential = relay.provider();
        let (epoch_sender, epoch_receiver) = watch::channel(7_u64);
        let monitor = spawn_identity_epoch_monitor(epoch_receiver, 7, handle.closer(), relay);

        epoch_sender.send(8).unwrap();
        tokio::time::timeout(std::time::Duration::from_secs(1), monitor)
            .await
            .expect("epoch retirement must be prompt")
            .unwrap();
        assert!(handle.is_closed());
        assert_eq!(credential(), None);
    }

    #[test]
    fn native_space_namespace_matches_browser_derivation() {
        let api_key = crate::test_constants::TEST_API_KEY;
        let requested = "portfolio-cursors";
        let expected = hex::encode(<sha2::Sha256 as sha2::Digest>::digest(
            format!("{api_key}:{requested}").as_bytes(),
        ));
        assert_eq!(
            native_capability_avenue_id(api_key, AnonymousKind::Space, requested),
            expected,
        );
        assert_eq!(
            native_capability_avenue_id(api_key, AnonymousKind::Room, "match-123"),
            "match-123",
        );
    }

    #[tokio::test]
    async fn signaling_slot_installs_once_and_fails_closed_before_activation() {
        let slot = SignalingSlot::default();
        assert!(slot.search_devices("principal", None).await.is_err());
        slot.install(Arc::new(crate::signaling::GatewayRequiredSignalingBackend))
            .await
            .expect("first capability installs");
        assert!(slot
            .install(Arc::new(crate::signaling::GatewayRequiredSignalingBackend,))
            .await
            .is_err());
    }
}