openrtc 1.0.4

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
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
//! Session-token admission and managed-scope grant persistence methods for `Client`.
//!
//! Extracted from `core_impl.rs` to keep that file focused on endpoint, transport,
//! and connection lifecycle. All items here are `impl Client` blocks that depend
//! on `super::*` (the same `use super::*;` pattern used by the other `_impl` files).

#[cfg(not(target_arch = "wasm32"))]
use super::core_impl::log_fingerprint;
#[cfg(native)]
use super::core_impl::{
    PERSISTENT_MANAGED_ADMISSION_SCOPE, PERSISTENT_MANAGED_SCOPE_TICKET_FILE_PREFIX,
};
use super::*;

#[derive(Debug, Clone, PartialEq, Eq)]
enum IncomingApplicationAdmissionDecision {
    Forward,
    ClassifyAdmission,
    Reject(String),
}

fn incoming_application_admission_decision(
    registry_active: bool,
    admission: &crate::session_token::SessionAdmission,
    current_transport_is_admitted: bool,
) -> IncomingApplicationAdmissionDecision {
    use crate::session_token::SessionAdmission;

    if !registry_active {
        return IncomingApplicationAdmissionDecision::Forward;
    }
    if let SessionAdmission::Rejected { reason } = admission {
        return IncomingApplicationAdmissionDecision::Reject(reason.clone());
    }
    if current_transport_is_admitted {
        return IncomingApplicationAdmissionDecision::Forward;
    }
    IncomingApplicationAdmissionDecision::ClassifyAdmission
}

pub(super) fn session_scope_allows_device_binding(scope: &str) -> bool {
    let normalized = scope.trim();
    normalized == "user-device"
        || normalized == "persistent"
        || normalized == "trusted-device"
        || normalized.starts_with("trusted-device:")
}

pub(super) fn session_scope_uses_transient_peer_identity(scope: &str) -> bool {
    let normalized = scope.trim();
    !normalized.is_empty() && !session_scope_allows_device_binding(normalized)
}
#[cfg(native)]
use anyhow::Context;

/// Upper bound on how long a managed dial waits for a host's session-token
/// approval response before treating the presentation as failed. A real
/// granting host replies in well under a second; bounding the read keeps the
/// dial from wedging when the peer does not run the host token responder.
const SESSION_TOKEN_HOST_RESPONSE_TIMEOUT_MS: u64 = 5_000;

#[derive(Debug, Clone, Copy, Default)]
struct SessionTokenValidationOptions<'a> {
    payload_suffix: Option<&'a str>,
    run_side_effects: bool,
}

#[derive(Debug, Clone, Copy, Default)]
struct SessionTokenPresentationOptions<'a> {
    token_payload: Option<&'a str>,
    device_id: Option<&'a str>,
    reciprocal_requested: bool,
}

fn outgoing_session_token_stream_contract(
    is_wasm: bool,
    application_crypto_active: bool,
    persistent_control_required: bool,
) -> crate::native_protocol::SessionTokenStreamContract {
    if is_wasm || (application_crypto_active && !persistent_control_required) {
        crate::native_protocol::SessionTokenStreamContract::OneShotAdmission
    } else {
        crate::native_protocol::SessionTokenStreamContract::PersistentControl
    }
}

#[derive(Debug, Clone, Copy)]
enum SessionTokenPresentationTarget<'a> {
    Host {
        endpoint_id: iroh::EndpointId,
        connection_id: &'a str,
    },
    Endpoint {
        endpoint_id: iroh::EndpointId,
    },
}

#[cfg(native)]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct PersistedManagedScopeGrantRecord {
    pub(crate) scope: String,
    pub(crate) token: String,
    pub(crate) max_connections: u32,
}

impl Client {
    #[cfg(native)]
    async fn write_private_managed_scope_grant(
        path: &std::path::Path,
        payload: &[u8],
    ) -> anyhow::Result<()> {
        use tokio::io::AsyncWriteExt;

        let temp_path = path.with_extension(format!(
            "json.tmp-{}",
            crate::session_token::generate_payload_nonce()
        ));
        let mut options = tokio::fs::OpenOptions::new();
        options.write(true).create_new(true);
        #[cfg(unix)]
        {
            options.mode(0o600);
        }

        let write_result = async {
            let mut file = options.open(&temp_path).await.with_context(|| {
                format!(
                    "failed creating private managed scope grant: {}",
                    temp_path.display()
                )
            })?;
            file.write_all(payload).await.with_context(|| {
                format!(
                    "failed writing private managed scope grant: {}",
                    temp_path.display()
                )
            })?;
            file.flush().await.with_context(|| {
                format!(
                    "failed flushing private managed scope grant: {}",
                    temp_path.display()
                )
            })?;
            file.sync_all().await.with_context(|| {
                format!(
                    "failed syncing private managed scope grant: {}",
                    temp_path.display()
                )
            })?;
            drop(file);

            #[cfg(windows)]
            match tokio::fs::remove_file(path).await {
                Ok(()) => {}
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                Err(error) => {
                    return Err(anyhow::Error::new(error).context(format!(
                        "failed replacing managed scope grant: {}",
                        path.display()
                    )));
                }
            }

            tokio::fs::rename(&temp_path, path).await.with_context(|| {
                format!(
                    "failed installing private managed scope grant: {}",
                    path.display()
                )
            })?;

            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
                    .await
                    .with_context(|| {
                        format!(
                            "failed securing managed scope grant permissions: {}",
                            path.display()
                        )
                    })?;
            }

            Ok::<(), anyhow::Error>(())
        }
        .await;

        if write_result.is_err() {
            let _ = tokio::fs::remove_file(&temp_path).await;
        }
        write_result
    }

    pub(crate) fn admission_trace_enabled() -> bool {
        #[cfg(not(target_arch = "wasm32"))]
        {
            return std::env::var("OPENRTC_ADMISSION_VERBOSE")
                .ok()
                .map(|value| {
                    matches!(
                        value.trim().to_ascii_lowercase().as_str(),
                        "1" | "true" | "yes" | "on"
                    )
                })
                .unwrap_or(false);
        }

        #[cfg(target_arch = "wasm32")]
        {
            false
        }
    }

    /// Consume the SDK-owned session-token stream while this physical peer is
    /// pending admission or provisionally trusted through a durable native
    /// device binding. A trusted binding is local, directional evidence; the
    /// peer can still owe this side its session-token presentation. Once a
    /// session-token admission is recorded, streams pass through untouched.
    ///
    /// This method is the native single-consumer boundary: Tauri and other host
    /// bridges must call it before forwarding an accepted Iroh stream to an
    /// application runtime. Keeping the responder in Rust prevents webview
    /// startup, remount, or IPC subscription timing from stranding admission.
    #[cfg(not(target_arch = "wasm32"))]
    pub async fn route_incoming_bi_stream_for_admission(
        &self,
        remote_endpoint_id: iroh::EndpointId,
        transport_stable_id: u64,
        mut send: iroh::endpoint::SendStream,
        recv: iroh::endpoint::RecvStream,
    ) -> Result<IncomingBiStreamDisposition, String> {
        use crate::native_protocol::NativeMainMessage;
        use crate::session_token::SessionAdmission;

        let remote_node_id = remote_endpoint_id.to_string();
        let local_node_id = self
            .current_node_id()
            .await
            .ok_or_else(|| "missing local node id while routing incoming stream".to_string())?;
        let connection_id = Self::deterministic_connection_id(&local_node_id, &remote_node_id);

        let current_transport_stable_id = self
            .get_connection(remote_endpoint_id)
            .await
            .map(|connection| connection.stable_id() as u64);
        if current_transport_stable_id != Some(transport_stable_id) {
            return Err(format!(
                "stale incoming Iroh stream generation connection_id={} incoming_transport_stable_id={} current_transport_stable_id={:?}",
                connection_id, transport_stable_id, current_transport_stable_id
            ));
        }

        let registry_active = self.session_registry_active();
        let admission = self.session_admission(&connection_id);
        let session_token_admitted_logically =
            matches!(&admission, SessionAdmission::Accepted { .. });
        let application_stream_admitted = self
            .native_application_stream_admitted_for_transport(&connection_id, transport_stable_id);
        let admission_decision = incoming_application_admission_decision(
            registry_active,
            &admission,
            application_stream_admitted,
        );
        if let IncomingApplicationAdmissionDecision::Reject(reason) = &admission_decision {
            return Err(format!(
                "rejected connection cannot open application streams: {reason}"
            ));
        }
        let trusted_user_device_crypto_policy =
            self.trusted_user_device_application_crypto_is_required();
        if trusted_user_device_crypto_policy {
            self.set_connection_application_crypto_required(&connection_id);
        }
        let application_crypto_key =
            self.application_crypto_key_for_connection(Some(&connection_id));
        let application_crypto_ready = !self.connection_requires_application_crypto(&connection_id)
            || (application_crypto_key.is_some()
                && (!self.connection_requires_application_crypto_confirmation(&connection_id)
                    || self.connection_application_crypto_is_confirmed(&connection_id)));
        if admission_decision == IncomingApplicationAdmissionDecision::Forward
            && application_crypto_ready
        {
            if Self::admission_trace_enabled() {
                eprintln!(
                    "[OpenRTC][native-stream-router] classified application bi-stream connection_id={} remote_node_id={} transport_stable_id={} registry_active={} session_token_admitted_logically={} application_stream_admitted={} admission_projection={:?} inspected_bytes=0 disposition=forward",
                    connection_id,
                    remote_node_id,
                    transport_stable_id,
                    registry_active,
                    session_token_admitted_logically,
                    application_stream_admitted,
                    admission
                );
            }
            return Ok(IncomingBiStreamDisposition::Forward { send, recv });
        }

        if Self::admission_trace_enabled() {
            eprintln!(
                "[OpenRTC][native-stream-router] classifying SDK admission bi-stream connection_id={} remote_node_id={} admission_projection={:?} session_token_admitted_logically={} application_stream_admitted={}",
                connection_id,
                remote_node_id,
                admission,
                session_token_admitted_logically,
                application_stream_admitted
            );
        }

        // SDK admission control is plaintext inside Iroh's authenticated QUIC
        // stream. Product application crypto can be installed on only one side
        // when a path drops, so reauthorization must not depend on that key.
        // Retain encrypted-frame parsing for compatibility with older senders.
        let mut recv = recv;
        let mut wire_prefix = [0u8; 4];
        recv.read_exact(&mut wire_prefix)
            .await
            .map_err(|error| format!("pending admission wire prefix: {error}"))?;
        let wire_frame_len = u32::from_be_bytes(wire_prefix) as usize;

        // A token-approved route is still SDK-control-only until reciprocal
        // application key agreement is confirmed. Browser peers send their
        // key-agreement response and transport signaling as one-shot
        // native-main frames (`u32 length || 0x00 || JSON`). Consume those in
        // Rust instead of forwarding them to product code as encrypted data.
        // Observation does not advance lifecycle: only the existing handshake
        // handler may install/confirm the key and make the route eligible for
        // the Forward branch above.
        if (session_token_admitted_logically || trusted_user_device_crypto_policy)
            && !application_crypto_ready
            && wire_frame_len != 0
        {
            const MAX_PENDING_CONTROL_FRAME_BYTES: usize = 1024 * 1024;
            if wire_frame_len > MAX_PENDING_CONTROL_FRAME_BYTES {
                return Err(format!(
                    "pending application-crypto control frame too large: {wire_frame_len}"
                ));
            }
            let mut framed = vec![0u8; wire_frame_len];
            recv.read_exact(&mut framed)
                .await
                .map_err(|error| format!("pending application-crypto control frame: {error}"))?;
            let Some((&protocol, frame)) = framed.split_first() else {
                return Err("pending application-crypto control frame was empty".to_string());
            };
            if protocol != 0x00 {
                return Err(format!(
                    "product stream arrived before reciprocal application crypto was ready: protocol={protocol}"
                ));
            }
            match crate::native_protocol::parse_main_frame(frame) {
                crate::native_protocol::ParsedMainFrame::TypeScriptHandshake(handshake)
                    if trusted_user_device_crypto_policy
                        && handshake.application_key_agreement_public_key.is_some() =>
                {
                    self.maybe_handle_typescript_handshake_capabilities(
                        &connection_id,
                        Some(&remote_node_id),
                        &handshake,
                    )
                    .await;
                }
                crate::native_protocol::ParsedMainFrame::TypeScriptHandshake(_)
                | crate::native_protocol::ParsedMainFrame::TypeScriptJson(_)
                    if session_token_admitted_logically =>
                {
                    self.inspect_incoming_native_main_frame_for_transport(
                        &connection_id,
                        Some(&remote_node_id),
                        None,
                        Some(transport_stable_id),
                        frame,
                    )
                    .await?;
                }
                _ => {
                    return Err(
                        "non-control stream arrived before reciprocal application crypto was ready"
                            .to_string(),
                    );
                }
            }
            let _ = send.finish();
            if Self::admission_trace_enabled() {
                eprintln!(
                    "[OpenRTC][native-stream-router] consumed pre-confirmation SDK control frame connection_id={} remote_node_id={} transport_stable_id={} inspected_bytes={} disposition=consume",
                    connection_id,
                    remote_node_id,
                    transport_stable_id,
                    4 + wire_frame_len,
                );
            }
            return Ok(IncomingBiStreamDisposition::Consumed);
        }
        // Plain SDK framing starts `0x00 || u32(label_len)`, so its first four
        // bytes decode to zero. Older encrypted admission framing starts with a
        // non-zero ciphertext length; sniff it only for wire compatibility.
        let admission_stream_encrypted = application_crypto_key.is_some() && wire_frame_len != 0;
        let (mut send, mut recv) = match (application_crypto_key, admission_stream_encrypted) {
            (Some(key), true) => (
                crate::application_crypto_streams::PeerSendStream::encrypted(send, key),
                crate::application_crypto_streams::PeerRecvStream::encrypted_with_prefix(
                    recv,
                    key,
                    &wire_prefix,
                )
                .map_err(|error| format!("wrap encrypted pending admission stream: {error}"))?,
            ),
            _ => (
                crate::application_crypto_streams::PeerSendStream::plain(send),
                crate::application_crypto_streams::PeerRecvStream::plain(recv),
            ),
        };

        async fn read_admission_exact(
            recv: &mut crate::application_crypto_streams::PeerRecvStream,
            buffer: &mut [u8],
            context: &str,
        ) -> Result<(), String> {
            let mut offset = 0;
            while offset < buffer.len() {
                let read = recv
                    .read(&mut buffer[offset..])
                    .await
                    .map_err(|error| format!("{context}: {error}"))?;
                if read == 0 {
                    return Err(format!("{context}: stream finished early"));
                }
                offset += read;
            }
            Ok(())
        }

        const MAX_LABEL_BYTES: usize = 64;
        const MAX_NATIVE_MAIN_FRAME_BYTES: usize = 1024 * 1024;

        let mut protocol = [0u8; 1];
        if admission_stream_encrypted {
            read_admission_exact(&mut recv, &mut protocol, "pending admission protocol byte")
                .await?;
        } else {
            protocol[0] = wire_prefix[0];
        }
        if protocol[0] != 0x00 {
            return Err(format!(
                "pending admission expected native protocol byte 0, received {}",
                protocol[0]
            ));
        }

        let mut label_len = [0u8; 4];
        if admission_stream_encrypted {
            read_admission_exact(&mut recv, &mut label_len, "pending admission label length")
                .await?;
        } else {
            label_len[..3].copy_from_slice(&wire_prefix[1..]);
            read_admission_exact(
                &mut recv,
                &mut label_len[3..],
                "pending admission label length",
            )
            .await?;
        }
        let label_len = u32::from_be_bytes(label_len) as usize;
        if label_len > MAX_LABEL_BYTES {
            return Err(format!("pending admission label too large: {label_len}"));
        }
        let mut label = vec![0u8; label_len];
        read_admission_exact(&mut recv, &mut label, "pending admission label").await?;
        if label != b"main" {
            return Err(format!(
                "pending admission expected main label, received {}",
                String::from_utf8_lossy(&label)
            ));
        }

        let mut frame_len = [0u8; 4];
        read_admission_exact(&mut recv, &mut frame_len, "pending admission frame length").await?;
        let frame_len = u32::from_be_bytes(frame_len) as usize;
        if frame_len > MAX_NATIVE_MAIN_FRAME_BYTES {
            return Err(format!("pending admission frame too large: {frame_len}"));
        }
        let mut frame = vec![0u8; frame_len];
        read_admission_exact(&mut recv, &mut frame, "pending admission frame").await?;

        let parsed_frame = crate::native_protocol::parse_main_frame(&frame);
        if (session_token_admitted_logically || trusted_user_device_crypto_policy)
            && !application_crypto_ready
            && matches!(
                &parsed_frame,
                crate::native_protocol::ParsedMainFrame::TypeScriptHandshake(_)
                    | crate::native_protocol::ParsedMainFrame::TypeScriptJson(_)
            )
        {
            match &parsed_frame {
                crate::native_protocol::ParsedMainFrame::TypeScriptHandshake(handshake)
                    if trusted_user_device_crypto_policy
                        && handshake.application_key_agreement_public_key.is_some() =>
                {
                    self.install_native_control_stream(
                        &connection_id,
                        remote_endpoint_id,
                        transport_stable_id,
                        send.into_plain(),
                        recv.into_plain(),
                        "application-crypto-negotiation",
                    )
                    .await;
                    self.maybe_handle_typescript_handshake_capabilities(
                        &connection_id,
                        Some(&remote_node_id),
                        handshake,
                    )
                    .await;
                    if Self::admission_trace_enabled() {
                        eprintln!(
                            "[OpenRTC][native-stream-router] installed labeled application-crypto control route connection_id={} remote_node_id={} transport_stable_id={} inspected_bytes={} disposition=consume",
                            connection_id,
                            remote_node_id,
                            transport_stable_id,
                            1 + 4 + label_len + 4 + frame_len,
                        );
                    }
                    return Ok(IncomingBiStreamDisposition::Consumed);
                }
                _ if session_token_admitted_logically => {
                    self.inspect_incoming_native_main_frame_for_transport(
                        &connection_id,
                        Some(&remote_node_id),
                        None,
                        Some(transport_stable_id),
                        &frame,
                    )
                    .await?;
                }
                _ => {
                    return Err(
                        "non-key-agreement stream arrived before role admission".to_string()
                    );
                }
            }
            let _ = send.finish();
            if Self::admission_trace_enabled() {
                eprintln!(
                    "[OpenRTC][native-stream-router] consumed labeled pre-confirmation SDK control frame connection_id={} remote_node_id={} transport_stable_id={} inspected_bytes={} disposition=consume",
                    connection_id,
                    remote_node_id,
                    transport_stable_id,
                    1 + 4 + label_len + 4 + frame_len,
                );
            }
            return Ok(IncomingBiStreamDisposition::Consumed);
        }

        let message = match parsed_frame {
            crate::native_protocol::ParsedMainFrame::NativeMessage(message)
                if message.is_session_token_presentation() =>
            {
                message
            }
            _ => {
                if Self::admission_trace_enabled() {
                    eprintln!(
                        "[OpenRTC][native-stream-router] rejected non-token stream before role admission connection_id={} remote_node_id={} admission={:?} inspected_bytes={} disposition=deny",
                        connection_id,
                        remote_node_id,
                        admission,
                        1 + 4 + label_len + 4 + frame_len
                    );
                }
                return Err(
                    "current transport requires an SDK session-token presentation".to_string(),
                );
            }
        };
        let token = message
            .presented_session_token()
            .ok_or_else(|| "session-token-missing-in-presentation".to_string())?;
        let token_payload = message.presented_session_token_payload();
        let claimed_device_id = message.claimed_device_id();
        let stream_contract = message.session_token_stream_contract();
        let reciprocal_requested = message.session_token_reciprocal_requested();
        let response_ack_requested = message.session_token_response_ack_requested();
        let was_already_admitted = self
            .session_token_registry
            .is_session_token_admitted_for_connection(&connection_id);
        let response_guard = self
            .session_token_registry
            .try_begin_admission_response(&connection_id)
            .ok_or_else(|| "session-token-retirement-in-progress".to_string())?;

        let mut verdict = self
            .validate_session_token_for_connection_with_payload(
                &token,
                &connection_id,
                token_payload.as_deref(),
            )
            .await;
        if matches!(verdict.as_deref(), Ok("user-device")) {
            let expected_device_id = self
                .known_remote_device_id_for_incoming_transport(&connection_id, &remote_node_id)
                .await;
            if claimed_device_id.as_deref() != expected_device_id.as_deref() {
                let reason = format!(
                    "authoritative-device-mismatch: expected={:?} claimed={:?}",
                    expected_device_id, claimed_device_id,
                );
                self.reject_session_connection(&connection_id, reason.as_str());
                verdict = Err(reason);
            } else if let Some(device_id) = claimed_device_id.as_deref() {
                if !self
                    .bind_session_admission_authoritative_device_id(&connection_id, device_id)
                    .await
                {
                    let reason = "authoritative-device-bind-refused".to_string();
                    self.reject_session_connection(&connection_id, reason.as_str());
                    verdict = Err(reason);
                }
            }
        }
        let mut response = match &verdict {
            Ok(scope) => NativeMainMessage::session_token_approval(
                (!scope.is_empty()).then_some(scope.as_str()),
                &connection_id,
            ),
            Err(reason) => NativeMainMessage::session_token_rejection(reason, &connection_id),
        };
        let inline_reciprocal_stream_instance_id = format!(
            "native-admission:{}:{}",
            transport_stable_id,
            crate::session_token::generate_token(),
        );
        if verdict.is_ok()
            && reciprocal_requested
            && message.reciprocal_session_token_mode() == Some("inline-v1")
        {
            let credential = self
                .native_route_repair_credentials
                .read()
                .ok()
                .and_then(|credentials| credentials.get(&remote_node_id).cloned());
            let known_remote_device_id = self
                .known_remote_device_id_for_incoming_transport(&connection_id, &remote_node_id)
                .await;
            let local_device_id = self
                .active_session_identity()
                .map(|(_, device_id)| device_id)
                .filter(|device_id| !device_id.trim().is_empty());
            if let (Some(credential), Some(local_device_id)) = (credential, local_device_id) {
                if known_remote_device_id.as_deref()
                    == Some(credential.authoritative_device_id.as_str())
                {
                    let presentation_id = crate::session_token::generate_token();
                    match self
                        .prepare_inline_reciprocal_session_admission(
                            remote_endpoint_id,
                            transport_stable_id,
                            inline_reciprocal_stream_instance_id.as_str(),
                            presentation_id.as_str(),
                            credential.token.as_str(),
                            credential.token_payload.as_str(),
                            local_device_id.as_str(),
                            stream_contract,
                        )
                        .await
                    {
                        Ok(presentation) => {
                            response = response
                                .with_reciprocal_session_token_presentation(presentation);
                        }
                        Err(error) => eprintln!(
                            "[PlutoRTC][session-admission][inline-reciprocal-prepare] connection_id={} remote_node_id={} result=deferred error={}",
                            connection_id, remote_node_id, error,
                        ),
                    }
                } else {
                    eprintln!(
                        "[PlutoRTC][session-admission][inline-reciprocal-prepare] connection_id={} remote_node_id={} result=deferred reason=authoritative-device-mismatch",
                        connection_id, remote_node_id,
                    );
                }
            }
        }
        let serialized = serde_json::to_vec(&response)
            .map_err(|error| format!("serialize session-token response: {error}"))?;
        let mut response_frame = Vec::with_capacity(1 + 4 + 4 + 4 + serialized.len());
        response_frame.push(0x00);
        response_frame.extend_from_slice(&(4u32).to_be_bytes());
        response_frame.extend_from_slice(b"main");
        response_frame.extend_from_slice(&(serialized.len() as u32).to_be_bytes());
        response_frame.extend_from_slice(&serialized);
        send.write_all(&response_frame)
            .await
            .map_err(|error| format!("write session-token response: {error}"))?;
        send.flush()
            .await
            .map_err(|error| format!("flush session-token response: {error}"))?;
        let response_ack_message = if response_ack_requested
            && !admission_stream_encrypted
            && verdict.is_ok()
        {
            let ack_result = tokio::time::timeout(std::time::Duration::from_secs(2), async {
                let mut protocol = [0u8; 1];
                read_admission_exact(
                    &mut recv,
                    &mut protocol,
                    "session-token response ack protocol byte",
                )
                .await?;
                if protocol[0] != 0x00 {
                    return Err(format!(
                        "session-token response ack expected native protocol byte 0, received {}",
                        protocol[0]
                    ));
                }
                let mut label_len = [0u8; 4];
                read_admission_exact(
                    &mut recv,
                    &mut label_len,
                    "session-token response ack label length",
                )
                .await?;
                let label_len = u32::from_be_bytes(label_len) as usize;
                if label_len > MAX_LABEL_BYTES {
                    return Err(format!(
                        "session-token response ack label too large: {label_len}"
                    ));
                }
                let mut label = vec![0u8; label_len];
                read_admission_exact(&mut recv, &mut label, "session-token response ack label")
                    .await?;
                if label != b"main" {
                    return Err("session-token response ack expected main label".to_string());
                }
                let mut frame_len = [0u8; 4];
                read_admission_exact(
                    &mut recv,
                    &mut frame_len,
                    "session-token response ack frame length",
                )
                .await?;
                let frame_len = u32::from_be_bytes(frame_len) as usize;
                if frame_len > MAX_NATIVE_MAIN_FRAME_BYTES {
                    return Err(format!(
                        "session-token response ack frame too large: {frame_len}"
                    ));
                }
                let mut frame = vec![0u8; frame_len];
                read_admission_exact(&mut recv, &mut frame, "session-token response ack frame")
                    .await?;
                match crate::native_protocol::parse_main_frame(&frame) {
                    crate::native_protocol::ParsedMainFrame::NativeMessage(message)
                        if message.is_session_token_response_ack(&connection_id) =>
                    {
                        Ok(message)
                    }
                    _ => Err("session-token response ack frame was not a matching ACK".to_string()),
                }
            })
            .await;
            match ack_result {
                Ok(Ok(message)) => Some(message),
                Ok(Err(error)) => {
                    eprintln!(
                        "[PlutoRTC][session-token] response ACK rejected connection_id={} remote_node_id={} error={}",
                        connection_id, remote_node_id, error,
                    );
                    None
                }
                Err(_) => {
                    eprintln!(
                        "[PlutoRTC][session-token] response ACK timed out connection_id={} remote_node_id={}",
                        connection_id, remote_node_id,
                    );
                    None
                }
            }
        } else {
            None
        };
        let response_acknowledged = !response_ack_requested || response_ack_message.is_some();
        if Self::admission_trace_enabled() {
            eprintln!(
                "[OpenRTC][native-stream-router] classified SDK session-token presentation connection_id={} remote_node_id={} prior_admission={:?} inspected_bytes={} accepted={} disposition=consume",
                connection_id,
                remote_node_id,
                admission,
                1 + 4 + label_len + 4 + frame_len,
                verdict.is_ok()
            );
        }
        let scope = match verdict {
            Ok(scope) => scope,
            Err(reason) => {
                eprintln!(
                    "[PlutoRTC][session-token] native host rejected connection_id={} remote_node_id={} reason={}",
                    connection_id, remote_node_id, reason
                );
                return Ok(IncomingBiStreamDisposition::Consumed);
            }
        };

        // A written verdict is not yet a generation-bound security proof. If
        // its requested ACK never arrives, the presenter cannot know it was
        // approved and must be allowed to retry on this same physical route.
        // Leaving the inbound proof unset keeps the Rust admission router in
        // ClassifyAdmission instead of misrouting that retry as encrypted
        // product data.
        if !response_acknowledged {
            drop(response_guard);
            eprintln!(
                "[PlutoRTC][session-token] approval delivery unacknowledged connection_id={} remote_node_id={} action=leave-route-pending",
                connection_id, remote_node_id,
            );
            return Ok(IncomingBiStreamDisposition::Consumed);
        }

        let effective_stream_contract = if response_acknowledged {
            stream_contract
        } else {
            crate::native_protocol::SessionTokenStreamContract::OneShotAdmission
        };
        self.bind_inbound_native_admission_stream_contract(
            &connection_id,
            effective_stream_contract,
        );
        self.bind_inbound_session_token_transport(&connection_id, transport_stable_id);
        if reciprocal_requested {
            self.request_reciprocal_session_admission(&connection_id);
        }

        self.connection_manager
            .upsert_pending(
                connection_id.clone(),
                Some(remote_node_id.clone()),
                None,
                Some(remote_node_id.clone()),
            )
            .await;
        if self
            .get_connection(remote_endpoint_id)
            .await
            .is_some_and(|connection| connection.stable_id() as u64 == transport_stable_id)
        {
            self.connection_manager
                .set_connected_with_transport(
                    &connection_id,
                    Some(remote_node_id.clone()),
                    Some(transport_stable_id),
                    Some("incoming".to_string()),
                )
                .await;
        } else {
            self.connection_manager
                .set_connected(&connection_id, Some(remote_node_id.clone()))
                .await;
        }
        // Token validation can complete before the incoming connection has
        // been indexed. Re-apply the accepted scope after materializing the
        // record so the Rust-owned peer-session projection cannot lose it.
        if !scope.trim().is_empty() {
            self.connection_manager
                .add_scope(&connection_id, scope.as_str())
                .await;
        }
        let authoritative_device_bound = if let Some(device_id) = claimed_device_id.as_deref() {
            let bound = self
                .bind_session_admission_authoritative_device_id(&connection_id, device_id)
                .await;
            if scope == "user-device"
                && self.resume_peer_requested_auto_connect_if_authenticated(device_id)
            {
                println!(
                    "[PlutoRTC][session-admission][peer-reconnect] cleared peer-requested auto-connect suppression connection_id={} device_id={}",
                    connection_id, device_id,
                );
            }
            bound
        } else {
            false
        };
        let reciprocal_committed = if let Some(ack) = response_ack_message.as_ref() {
            if let (Some(presentation_id), Some(accepted)) = (
                ack.reciprocal_session_token_ack_presentation_id(),
                ack.reciprocal_session_token_ack_accepted(),
            ) {
                match self
                    .confirm_inline_reciprocal_session_admission(
                        remote_endpoint_id,
                        transport_stable_id,
                        inline_reciprocal_stream_instance_id.as_str(),
                        presentation_id.as_str(),
                        accepted,
                        ack.reciprocal_session_token_ack_scope().as_deref(),
                    )
                    .await
                {
                    Ok(()) => true,
                    Err(error) => {
                        eprintln!(
                            "[PlutoRTC][session-admission][inline-reciprocal-commit] connection_id={} remote_node_id={} result=pending error={}",
                            connection_id, remote_node_id, error,
                        );
                        false
                    }
                }
            } else {
                false
            }
        } else {
            false
        };
        if reciprocal_committed {
            self.clear_reciprocal_session_admission_request(&connection_id);
        }
        match effective_stream_contract {
            crate::native_protocol::SessionTokenStreamContract::PersistentControl => {
                if admission_stream_encrypted {
                    // Keyed reauthorization is always one-shot. Treat an older
                    // peer's persistent marker as one-shot too rather than
                    // installing a raw control reader behind the crypto frame.
                    let _ = send.finish();
                    drop(recv);
                } else {
                    self.install_native_control_stream(
                        &connection_id,
                        remote_endpoint_id,
                        transport_stable_id,
                        send.into_plain(),
                        recv.into_plain(),
                        "admission-host",
                    )
                    .await;
                }
            }
            crate::native_protocol::SessionTokenStreamContract::OneShotAdmission => {
                if let Err(error) = send
                    .finish_and_wait_for_peer(std::time::Duration::from_secs(2))
                    .await
                {
                    eprintln!(
                        "[PlutoRTC][session-token] host response delivery wait ended connection_id={} remote_node_id={} error={}",
                        connection_id, remote_node_id, error,
                    );
                }
                drop(recv);
            }
        }
        // Keep terminal retirement fenced until a one-shot verdict has either
        // reached the peer or exhausted its bounded delivery wait.
        drop(response_guard);
        // The initial incoming-transport readiness probe runs before
        // `accept_external_connection` has installed this leg in the native
        // node, so it may conservatively record Stale. Admission is the first
        // point where both the current physical generation and its Rust-owned
        // application route are proven. Re-confirm here, fenced to that exact
        // generation, so the accepting host projects the same routable truth as
        // the dialer without introducing another lifecycle owner.
        if self
            .connection_manager
            .current_transport_matches(&connection_id, Some(transport_stable_id))
            .await
        {
            let _ = self
                .confirm_managed_connection_readiness(&connection_id)
                .await;
        }
        if !admission_stream_encrypted {
            if let Err(error) = self
                .send_typescript_capability_update(&connection_id, "native-admission-host", None)
                .await
            {
                eprintln!(
                    "[OpenRTC][capability] native admission host advertisement failed connection_id={} error={}",
                    connection_id, error,
                );
            }
        }
        self.run_post_session_token_admission_side_effects(&connection_id, !was_already_admitted)
            .await;
        eprintln!(
            "[PlutoRTC][session-token] native host approved connection_id={} remote_node_id={} scope={} claimed_device_id={} authoritative_device_bound={}",
            connection_id,
            remote_node_id,
            scope,
            claimed_device_id.as_deref().unwrap_or("<none>"),
            authoritative_device_bound,
        );
        Ok(IncomingBiStreamDisposition::Consumed)
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) async fn native_peer_is_pending_admission(
        &self,
        remote_endpoint_id: iroh::EndpointId,
    ) -> bool {
        if !self.session_registry_active() {
            return false;
        }
        let Some(local_node_id) = self.current_node_id().await else {
            return true;
        };
        let connection_id =
            Self::deterministic_connection_id(&local_node_id, &remote_endpoint_id.to_string());
        let Some(transport_stable_id) = self
            .get_connection(remote_endpoint_id)
            .await
            .map(|connection| connection.stable_id() as u64)
        else {
            return true;
        };
        !self.native_application_stream_admitted_for_transport(&connection_id, transport_stable_id)
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn inbound_session_token_admitted_for_transport(
        &self,
        connection_id: &str,
        transport_stable_id: u64,
    ) -> bool {
        self.inbound_session_admission_transport_ids
            .read()
            .ok()
            .and_then(|proofs| proofs.get(connection_id).copied())
            == Some(transport_stable_id)
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn remote_session_token_admitted_for_transport(
        &self,
        connection_id: &str,
        transport_stable_id: u64,
    ) -> bool {
        self.remote_session_admission_proofs
            .read()
            .ok()
            .and_then(|proofs| {
                proofs
                    .get(connection_id)
                    .map(|proof| proof.transport_stable_id)
            })
            == Some(transport_stable_id)
    }

    /// Product streams are allowed once this runtime has accepted the logical
    /// session and holds every directional proof declared by the wire contract
    /// on the current physical generation. A one-shot presentation proves only
    /// the receiver's inbound direction. Persistent native control declares the
    /// directions that must remain generation-bound for managed sessions.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn native_application_stream_admitted_for_transport(
        &self,
        connection_id: &str,
        transport_stable_id: u64,
    ) -> bool {
        let admission = self.session_admission(connection_id);
        if !matches!(
            admission,
            crate::session_token::SessionAdmission::Accepted { .. }
        ) {
            return false;
        }

        let contracts = self.native_admission_stream_contracts(connection_id);
        // A durable user-device relationship is bilateral. After this side's
        // outbound presentation succeeds, the peer can still owe its reverse
        // presentation on the same physical Iroh generation. Treating the
        // single outbound proof as application-ready forwards that reverse
        // token frame into product code and strands the peer asymmetrically.
        let persistent_control_declared = matches!(
            contracts.inbound,
            Some(crate::native_protocol::SessionTokenStreamContract::PersistentControl)
        ) || matches!(
            contracts.outbound,
            Some(crate::native_protocol::SessionTokenStreamContract::PersistentControl)
        );
        let bilateral_user_device = persistent_control_declared
            && matches!(
                &admission,
                crate::session_token::SessionAdmission::Accepted {
                    scope: Some(scope),
                    ..
                } if scope.as_str() == "user-device"
            );
        let inbound_required = bilateral_user_device || contracts.inbound.is_some();
        let outbound_required = bilateral_user_device || contracts.outbound.is_some();
        if !inbound_required && !outbound_required {
            return false;
        }

        let inbound_proven =
            self.inbound_session_token_admitted_for_transport(connection_id, transport_stable_id);
        let outbound_proven =
            self.remote_session_token_admitted_for_transport(connection_id, transport_stable_id);
        let admission_proven =
            (!inbound_required || inbound_proven) && (!outbound_required || outbound_proven);
        if !admission_proven {
            return false;
        }

        if self.connection_requires_application_crypto(connection_id) {
            if self
                .application_crypto_key_for_connection(Some(connection_id))
                .is_none()
            {
                return false;
            }
            if self.connection_requires_application_crypto_confirmation(connection_id)
                && !self.connection_application_crypto_is_confirmed(connection_id)
            {
                return false;
            }
        }
        true
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn native_application_stream_pending_diagnostic(
        &self,
        connection_id: &str,
        transport_stable_id: u64,
    ) -> String {
        let contracts = self.native_admission_stream_contracts(connection_id);
        let admission = self.session_admission(connection_id);
        let bilateral_user_device = matches!(
            &admission,
            crate::session_token::SessionAdmission::Accepted {
                scope: Some(scope),
                ..
            } if scope.as_str() == "user-device"
        );
        let inbound_required = bilateral_user_device || contracts.inbound.is_some();
        let outbound_required = bilateral_user_device || contracts.outbound.is_some();
        let inbound_proven =
            self.inbound_session_token_admitted_for_transport(connection_id, transport_stable_id);
        let outbound_proven =
            self.remote_session_token_admitted_for_transport(connection_id, transport_stable_id);
        let crypto_required = self.connection_requires_application_crypto(connection_id);
        let crypto_key_installed = self
            .application_crypto_key_for_connection(Some(connection_id))
            .is_some();
        let crypto_confirmation_required =
            self.connection_requires_application_crypto_confirmation(connection_id);
        let crypto_confirmed = self.connection_application_crypto_is_confirmed(connection_id);

        format!(
            "admission={admission:?} contracts={contracts:?} inbound_required={inbound_required} inbound_proven={inbound_proven} outbound_required={outbound_required} outbound_proven={outbound_proven} crypto_required={crypto_required} crypto_key_installed={crypto_key_installed} crypto_confirmation_required={crypto_confirmation_required} crypto_confirmed={crypto_confirmed}",
        )
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn bind_inbound_session_token_transport(
        &self,
        connection_id: &str,
        transport_stable_id: u64,
    ) {
        if let Ok(mut proofs) = self.inbound_session_admission_transport_ids.write() {
            proofs.insert(connection_id.to_string(), transport_stable_id);
        }
        println!(
            "[PlutoRTC][session-admission][inbound-proof] connection_id={} transport_stable_id={}",
            connection_id, transport_stable_id,
        );
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn request_reciprocal_session_admission(&self, connection_id: &str) {
        if let Ok(mut requests) = self.pending_reciprocal_session_admission_requests.write() {
            requests.insert(connection_id.to_string());
        }
        println!(
            "[PlutoRTC][session-admission][reciprocal-request] connection_id={} state=pending",
            connection_id,
        );
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn has_pending_reciprocal_session_admission_request(
        &self,
        connection_id: &str,
    ) -> bool {
        self.pending_reciprocal_session_admission_requests
            .read()
            .ok()
            .is_some_and(|requests| requests.contains(connection_id))
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn clear_reciprocal_session_admission_request(&self, connection_id: &str) {
        let removed = self
            .pending_reciprocal_session_admission_requests
            .write()
            .ok()
            .is_some_and(|mut requests| requests.remove(connection_id));
        if removed {
            println!(
                "[PlutoRTC][session-admission][reciprocal-request] connection_id={} state=satisfied",
                connection_id,
            );
        }
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn bind_inbound_native_admission_stream_contract(
        &self,
        connection_id: &str,
        contract: crate::native_protocol::SessionTokenStreamContract,
    ) {
        if let Ok(mut contracts) = self.native_admission_stream_contracts.write() {
            contracts
                .entry(connection_id.to_string())
                .or_default()
                .inbound = Some(contract);
        }
        println!(
            "[PlutoRTC][session-admission][stream-contract] connection_id={} direction=inbound contract={:?}",
            connection_id, contract,
        );
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn bind_outbound_native_admission_stream_contract(
        &self,
        connection_id: &str,
        contract: crate::native_protocol::SessionTokenStreamContract,
    ) {
        if let Ok(mut contracts) = self.native_admission_stream_contracts.write() {
            contracts
                .entry(connection_id.to_string())
                .or_default()
                .outbound = Some(contract);
        }
        println!(
            "[PlutoRTC][session-admission][stream-contract] connection_id={} direction=outbound contract={:?}",
            connection_id, contract,
        );
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn native_admission_stream_contracts(
        &self,
        connection_id: &str,
    ) -> crate::client::NativeAdmissionStreamContracts {
        self.native_admission_stream_contracts
            .read()
            .ok()
            .and_then(|contracts| contracts.get(connection_id).copied())
            .unwrap_or_default()
    }

    /// Return whether every required direction has a current-generation proof.
    /// Persistent native-main streams are bidirectional data routes, but the
    /// admission proofs remain directional security evidence. Stream ranking
    /// may retain one route only after both user-device presentations complete.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn native_admission_route_is_ready_for_transport(
        &self,
        connection_id: &str,
        transport_stable_id: Option<u64>,
    ) -> bool {
        if let Some(transport_stable_id) = transport_stable_id {
            return self.native_application_stream_admitted_for_transport(
                connection_id,
                transport_stable_id,
            );
        }

        let contracts = self.native_admission_stream_contracts(connection_id);
        let requires_persistent_proof = matches!(
            contracts.inbound,
            Some(crate::native_protocol::SessionTokenStreamContract::PersistentControl)
        ) || matches!(
            contracts.outbound,
            Some(crate::native_protocol::SessionTokenStreamContract::PersistentControl)
        );
        if requires_persistent_proof {
            return self.native_declared_persistent_routes_are_proven(connection_id);
        }
        let inbound_ready = contracts.inbound.is_none()
            || self
                .inbound_session_admission_transport_ids
                .read()
                .ok()
                .is_some_and(|proofs| proofs.contains_key(connection_id));
        let outbound_ready = contracts.outbound.is_none()
            || self
                .remote_session_admission_proofs
                .read()
                .ok()
                .is_some_and(|proofs| proofs.contains_key(connection_id));
        inbound_ready && outbound_ready
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn native_admission_stream_is_persistent(&self, connection_id: &str) -> bool {
        let contracts = self.native_admission_stream_contracts(connection_id);
        contracts.inbound
            == Some(crate::native_protocol::SessionTokenStreamContract::PersistentControl)
            || contracts.outbound
                == Some(crate::native_protocol::SessionTokenStreamContract::PersistentControl)
    }

    /// Invalidate the generation-bound native-main route proofs owned by one
    /// physical Iroh leg without forgetting the accepted logical session.
    ///
    /// Re-presenting the same token for the same deterministic connection is
    /// idempotent in `SessionTokenRegistry`. Keeping these proofs stale would
    /// let application streams race ahead of the peer's replacement control
    /// stream; clearing them forces the existing admission flow to establish a
    /// declared Rust-owned route before the session becomes routable again.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn invalidate_native_main_route_proofs_for_transport(
        &self,
        connection_id: &str,
        transport_stable_id: u64,
    ) -> bool {
        let inbound_removed = self
            .inbound_session_admission_transport_ids
            .write()
            .ok()
            .is_some_and(|mut proofs| {
                if proofs.get(connection_id).copied() == Some(transport_stable_id) {
                    proofs.remove(connection_id);
                    true
                } else {
                    false
                }
            });
        let remote_removed = self
            .remote_session_admission_proofs
            .write()
            .ok()
            .is_some_and(|mut proofs| {
                if proofs
                    .get(connection_id)
                    .is_some_and(|proof| proof.transport_stable_id == transport_stable_id)
                {
                    proofs.remove(connection_id);
                    true
                } else {
                    false
                }
            });

        let removed = inbound_removed || remote_removed;
        if removed {
            println!(
                "[PlutoRTC][session-admission][route-invalidated] connection_id={} transport_stable_id={} inbound_removed={} remote_removed={}",
                connection_id, transport_stable_id, inbound_removed, remote_removed,
            );
        }
        removed
    }

    /// Invalidate only proofs whose wire contract requires the cached
    /// persistent native-main stream to remain alive. A one-shot admission is
    /// transport-generation evidence; it survives control-stream recreation
    /// on that same live Iroh leg and is retired only with the physical leg.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn invalidate_native_persistent_route_proofs_for_transport(
        &self,
        connection_id: &str,
        transport_stable_id: u64,
    ) -> bool {
        let contracts = self.native_admission_stream_contracts(connection_id);
        let inbound_removed = if contracts.inbound
            == Some(crate::native_protocol::SessionTokenStreamContract::PersistentControl)
        {
            self.inbound_session_admission_transport_ids
                .write()
                .ok()
                .is_some_and(|mut proofs| {
                    if proofs.get(connection_id).copied() == Some(transport_stable_id) {
                        proofs.remove(connection_id);
                        true
                    } else {
                        false
                    }
                })
        } else {
            false
        };
        let outbound_removed = if contracts.outbound
            == Some(crate::native_protocol::SessionTokenStreamContract::PersistentControl)
        {
            self.remote_session_admission_proofs
                .write()
                .ok()
                .is_some_and(|mut proofs| {
                    if proofs
                        .get(connection_id)
                        .is_some_and(|proof| proof.transport_stable_id == transport_stable_id)
                    {
                        proofs.remove(connection_id);
                        true
                    } else {
                        false
                    }
                })
        } else {
            false
        };

        let removed = inbound_removed || outbound_removed;
        if removed {
            println!(
                "[PlutoRTC][session-admission][persistent-route-invalidated] connection_id={} transport_stable_id={} inbound_removed={} outbound_removed={}",
                connection_id, transport_stable_id, inbound_removed, outbound_removed,
            );
        }
        removed
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn invalidate_native_main_route_proofs_except_transport(
        &self,
        connection_id: &str,
        current_transport_stable_id: u64,
    ) -> bool {
        let inbound_stale = self
            .inbound_session_admission_transport_ids
            .read()
            .ok()
            .and_then(|proofs| proofs.get(connection_id).copied())
            .filter(|stable_id| *stable_id != current_transport_stable_id);
        let remote_stale = self
            .remote_session_admission_proofs
            .read()
            .ok()
            .and_then(|proofs| {
                proofs
                    .get(connection_id)
                    .map(|proof| proof.transport_stable_id)
            })
            .filter(|stable_id| *stable_id != current_transport_stable_id);

        let mut removed = false;
        if let Some(stable_id) = inbound_stale {
            removed |=
                self.invalidate_native_main_route_proofs_for_transport(connection_id, stable_id);
        }
        if let Some(stable_id) = remote_stale {
            removed |=
                self.invalidate_native_main_route_proofs_for_transport(connection_id, stable_id);
        }
        removed
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn native_declared_persistent_routes_are_proven(&self, connection_id: &str) -> bool {
        let contracts = self.native_admission_stream_contracts(connection_id);
        let bilateral_user_device = matches!(
            self.session_admission(connection_id),
            crate::session_token::SessionAdmission::Accepted {
                scope: Some(scope),
                ..
            } if scope.as_str() == "user-device"
        );
        let inbound_required = bilateral_user_device
            || contracts.inbound
                == Some(crate::native_protocol::SessionTokenStreamContract::PersistentControl);
        let outbound_required = bilateral_user_device
            || contracts.outbound
                == Some(crate::native_protocol::SessionTokenStreamContract::PersistentControl);
        if !inbound_required && !outbound_required {
            return false;
        }

        let inbound_transport_stable_id = self
            .inbound_session_admission_transport_ids
            .read()
            .ok()
            .and_then(|proofs| proofs.get(connection_id).copied());
        let outbound_transport_stable_id = self
            .remote_session_admission_proofs
            .read()
            .ok()
            .and_then(|proofs| {
                proofs
                    .get(connection_id)
                    .map(|proof| proof.transport_stable_id)
            });

        if inbound_required && inbound_transport_stable_id.is_none() {
            return false;
        }
        if outbound_required && outbound_transport_stable_id.is_none() {
            return false;
        }

        if inbound_required && outbound_required {
            return inbound_transport_stable_id == outbound_transport_stable_id;
        }

        true
    }

    /// Validate an incoming session token and consume one use.
    /// Returns Ok(scope) on success, Err(reason) on failure.
    /// Empty registry = backward-compat gate (all pass).
    pub fn validate_session_token(&self, token: &str) -> Result<String, String> {
        self.session_token_registry
            .validate_and_consume(token)
            .map(|grant_scope| grant_scope.into_inner())
    }

    /// Phase 1: verdict-only admission. Returns the deterministic scope
    /// associated with `(token, connection_id)` *without* running any
    /// post-admission side effects (replacement peer accept, native WebRTC
    /// recovery, etc.). Callers that own the response writer must:
    ///
    ///   1. Call this to compute the verdict.
    ///   2. Write + flush the approval/rejection response to the wire.
    ///   3. Then invoke
    ///      [`Self::run_post_session_token_admission_side_effects`] to fire
    ///      the lifecycle hooks (replacement, WebRTC restart, ...).
    ///
    /// This separation eliminates the
    /// `[session-token-response:protocol-byte] 0 bytes read` race where a
    /// concurrent `accept_replacement_peer` could retire the very transport
    /// the response writer was about to flush onto.
    ///
    /// Existing callers that do not own a wire-level response writer (e.g.
    /// the inline TS/handshake paths in
    /// `inspect_incoming_native_main_frame`) still get the legacy "validate
    /// + side effects" semantics via
    /// [`Self::validate_session_token_for_connection_with_side_effects`].
    pub async fn validate_session_token_for_connection(
        &self,
        token: &str,
        connection_id: &str,
    ) -> Result<String, String> {
        self.validate_session_token_for_connection_with_options(
            token,
            connection_id,
            SessionTokenValidationOptions::default(),
        )
        .await
    }

    pub async fn validate_session_token_for_connection_with_payload(
        &self,
        token: &str,
        connection_id: &str,
        payload_suffix: Option<&str>,
    ) -> Result<String, String> {
        self.validate_session_token_for_connection_with_options(
            token,
            connection_id,
            SessionTokenValidationOptions {
                payload_suffix,
                run_side_effects: false,
            },
        )
        .await
    }

    /// Reserve the connection while a host adapter writes an SDK-owned
    /// session-token verdict. The guard must remain alive until the response
    /// has been flushed, then be dropped before post-admission lifecycle work.
    pub fn try_begin_session_token_response(
        &self,
        connection_id: &str,
    ) -> Option<crate::session_token::AdmissionResponseGuard> {
        self.session_token_registry
            .try_begin_admission_response(connection_id)
    }

    /// Pre-Phase-1 helper: validates and immediately runs post-admission
    /// side effects in the same call. Used by callers that do not own a
    /// dedicated response writer (i.e. paths where there is no opportunity
    /// to interleave a wire flush between the verdict and the side
    /// effects). Equivalent to the pre-Phase-1 behaviour of
    /// `validate_session_token_for_connection`.
    pub async fn validate_session_token_for_connection_with_side_effects(
        &self,
        token: &str,
        connection_id: &str,
    ) -> Result<String, String> {
        self.validate_session_token_for_connection_with_options(
            token,
            connection_id,
            SessionTokenValidationOptions {
                payload_suffix: None,
                run_side_effects: true,
            },
        )
        .await
    }

    pub async fn validate_session_token_for_connection_with_payload_and_side_effects(
        &self,
        token: &str,
        connection_id: &str,
        payload_suffix: Option<&str>,
    ) -> Result<String, String> {
        self.validate_session_token_for_connection_with_options(
            token,
            connection_id,
            SessionTokenValidationOptions {
                payload_suffix,
                run_side_effects: true,
            },
        )
        .await
    }

    async fn validate_session_token_for_connection_with_options(
        &self,
        token: &str,
        connection_id: &str,
        options: SessionTokenValidationOptions<'_>,
    ) -> Result<String, String> {
        let was_already_admitted = self
            .session_token_registry
            .is_session_token_admitted_for_connection(connection_id);
        let grant_scope = self
            .session_token_registry
            .validate_and_consume_for_connection_with_payload(
                token,
                Some(connection_id),
                options.payload_suffix,
            )?;
        if !grant_scope.as_str().trim().is_empty() {
            self.connection_manager
                .add_scope(connection_id, grant_scope.as_str())
                .await;
        }
        let scope = grant_scope.into_inner();
        if options.run_side_effects {
            self.run_post_session_token_admission_side_effects(
                connection_id,
                !was_already_admitted,
            )
            .await;
        }
        Ok(scope)
    }

    /// Run the lifecycle side effects that previously lived inline in
    /// `validate_session_token_for_connection`. Idempotent: if
    /// `is_first_presentation` is `false`, this is a no-op (matching the
    /// pre-Phase-1 behaviour where duplicate token frames were skipped).
    ///
    /// Only callers that own a session-token response writer should invoke
    /// this directly — and only *after* the response has been written and
    /// the wire flushed.
    pub async fn run_post_session_token_admission_side_effects(
        &self,
        connection_id: &str,
        is_first_presentation: bool,
    ) {
        self.commit_session_token_application_security_epoch(connection_id)
            .await;
        if !is_first_presentation {
            return;
        }

        #[cfg(all(not(target_arch = "wasm32"), feature = "transport-webrtc"))]
        {
            let current_device_identity = self
                .connection_manager
                .get_by_connection_id(connection_id)
                .await
                .and_then(|record| record.device_id.or(record.device_id_hint));
            self.accept_replacement_peer(
                connection_id,
                current_device_identity.as_deref(),
                "replacement-peer-admitted",
            )
            .await;

            // First session-token presentation for this connection_id: the
            // remote may have a fresh RTCPeerConnection (e.g. browser
            // refresh) — force-restart the WebRTC upgrade so stale ICE/SCTP
            // state is torn down. Security:
            // maybe_start_native_webrtc_upgrade re-checks session_admission —
            // this path runs after mark_accepted in
            // validate_and_consume_for_connection, so Rejected remotes
            // never reach here.
            let current_webrtc_state = self.native_webrtc_state_for_peer(connection_id).await;
            let force_restart = matches!(
                current_webrtc_state,
                Some((_, crate::transport::NativeWebRTCState::Connecting))
                    | Some((_, crate::transport::NativeWebRTCState::Connected))
            );
            if current_webrtc_state.is_some() {
                self.reset_native_webrtc_attempt_budget(connection_id, "fresh-token-presentation")
                    .await;
            }
            if let Err(error) = self
                .request_native_webrtc_recovery(
                    connection_id,
                    None,
                    crate::native_webrtc_policy::NativeWebRTCRecoveryTrigger::Native(
                        crate::native_webrtc_policy::NativeWebRTCNativeTrigger::AdmissionAccepted,
                    ),
                    crate::native_webrtc_policy::NativeWebRTCRecoveryOptions {
                        force_restart,
                        preferred_negotiation_id: None,
                        role_override: None,
                    },
                )
                .await
            {
                let ctx = self.correlation_for_connection(connection_id).await;
                crate::clog!(
                    "[NativeWebRTC]",
                    &ctx,
                    "post_admission_upgrade_trigger_failed state={:?} force_restart={} error={}",
                    current_webrtc_state,
                    force_restart,
                    error
                );
            } else if force_restart {
                let ctx = self.correlation_for_connection(connection_id).await;
                crate::clog!(
                    "[NativeWebRTC]",
                    &ctx,
                    "post_admission_upgrade_restart_requested prior_state={:?}",
                    current_webrtc_state
                );
            }
        }
        #[cfg(not(all(not(target_arch = "wasm32"), feature = "transport-webrtc")))]
        {
            let _ = connection_id;
        }
    }

    async fn normalize_session_token_scope_trust_class(
        &self,
        connection_id: &str,
        scope: Option<&str>,
    ) -> bool {
        let Some(scope) = scope.map(str::trim).filter(|scope| !scope.is_empty()) else {
            return false;
        };
        let next_is_transient = session_scope_uses_transient_peer_identity(scope);
        let replace_mixed_trust_scopes = self
            .connection_manager
            .get_scopes(connection_id)
            .await
            .iter()
            .any(|existing| {
                session_scope_uses_transient_peer_identity(existing) != next_is_transient
            });
        if replace_mixed_trust_scopes {
            self.connection_manager
                .release_scope(connection_id, None)
                .await;
            self.connection_manager
                .add_scope(connection_id, scope)
                .await;
        }
        replace_mixed_trust_scopes
    }

    /// Start an outbound capability epoch before presenting the token. Keeping
    /// crypto required closes the interval where an old settled projection
    /// could otherwise admit product traffic while replacement key agreement
    /// is still in flight.
    pub(crate) fn begin_outbound_session_token_application_security_epoch(
        &self,
        connection_id: &str,
        token: &str,
    ) -> bool {
        let current_fingerprint = crate::session_token::token_fingerprint(token);
        let committed_fingerprint = self
            .outbound_application_security_epoch_fingerprints
            .read()
            .ok()
            .and_then(|epochs| epochs.get(connection_id).cloned());
        let security_epoch_changed = match committed_fingerprint.as_deref() {
            Some(committed) => committed != current_fingerprint,
            // A key agreement may settle just before the first token verdict.
            // With no previously committed capability there is no older epoch
            // to retire; logout/revoke boundaries explicitly clear both maps.
            None => false,
        };
        if security_epoch_changed {
            self.clear_connection_application_crypto_key(connection_id);
            eprintln!(
                "[OpenRTC][admission-security] began outbound security epoch connection_id={} previous_token_fp={} current_token_fp={}",
                connection_id,
                committed_fingerprint.as_deref().unwrap_or("<uncommitted>"),
                current_fingerprint,
            );
        }
        self.set_connection_application_crypto_required(connection_id);
        security_epoch_changed
    }

    pub(crate) fn commit_outbound_session_token_application_security_epoch(
        &self,
        connection_id: &str,
        token: &str,
    ) {
        if let Ok(mut epochs) = self
            .outbound_application_security_epoch_fingerprints
            .write()
        {
            epochs.insert(
                connection_id.to_string(),
                crate::session_token::token_fingerprint(token),
            );
        }
    }

    /// Commit the capability token as an application-security epoch after its
    /// approval has reached the presenter. A different token on the same
    /// deterministic node-pair connection must not inherit the previous
    /// application key or a scope from the opposite trust class. Re-presenting
    /// the same token is intentionally idempotent so transport replacement does
    /// not reset crypto sequence state.
    async fn commit_session_token_application_security_epoch(&self, connection_id: &str) {
        let Some(current_fingerprint) = self
            .session_token_registry
            .admission_fingerprint(connection_id)
        else {
            return;
        };
        let committed_fingerprint = self
            .session_token_registry
            .application_security_epoch_fingerprint(connection_id);
        let security_epoch_changed = match committed_fingerprint.as_deref() {
            Some(committed) => committed != current_fingerprint,
            // The first approved capability adopts any key established during
            // its transport handshake. Only a committed older capability can
            // make the current key stale.
            None => false,
        };

        let admitted_scope = match self.session_admission(connection_id) {
            crate::session_token::SessionAdmission::Accepted {
                scope: Some(scope), ..
            } => Some(scope.into_inner()),
            _ => None,
        };
        if security_epoch_changed {
            self.clear_connection_application_crypto_key(connection_id);
        }
        self.set_connection_application_crypto_required(connection_id);
        let replace_mixed_trust_scopes = self
            .normalize_session_token_scope_trust_class(connection_id, admitted_scope.as_deref())
            .await;
        if security_epoch_changed {
            eprintln!(
                "[OpenRTC][admission-security] committed new security epoch connection_id={} previous_token_fp={} current_token_fp={} scopes_replaced={}",
                connection_id,
                committed_fingerprint.as_deref().unwrap_or("<uncommitted>"),
                current_fingerprint,
                replace_mixed_trust_scopes,
            );
        }
        self.session_token_registry
            .commit_application_security_epoch(connection_id);
    }

    #[cfg(native)]
    pub async fn inspect_incoming_native_main_frame(
        &self,
        connection_id: &str,
        remote_node_id: Option<&str>,
        known_device_id: Option<&str>,
        frame: &[u8],
    ) -> Result<crate::native_protocol::InspectedMainFrame, String> {
        self.inspect_incoming_native_main_frame_for_transport(
            connection_id,
            remote_node_id,
            known_device_id,
            None,
            frame,
        )
        .await
    }

    #[cfg(native)]
    pub(crate) async fn inspect_incoming_native_main_frame_for_transport(
        &self,
        connection_id: &str,
        remote_node_id: Option<&str>,
        known_device_id: Option<&str>,
        transport_stable_id: Option<u64>,
        frame: &[u8],
    ) -> Result<crate::native_protocol::InspectedMainFrame, String> {
        use crate::native_protocol::{InspectedMainFrame, ParsedMainFrame};

        match crate::native_protocol::parse_main_frame(frame) {
            ParsedMainFrame::NativeMessage(message) => {
                let is_handshake = message.is_handshake();
                let is_session_token = message.is_session_token_presentation();

                // Session-token presentation: the connecting client presents a
                // token extracted from a compound ticket.  Validate it and admit
                // the connection before any handshake or data flows.
                if is_session_token && self.session_registry_active() {
                    let token = message
                        .presented_session_token()
                        .ok_or_else(|| "session-token-missing-in-presentation".to_string())?;
                    let token_payload = message.presented_session_token_payload();
                    let presented_device_id = message.claimed_device_id();
                    let token_fp = log_fingerprint(token.as_str());
                    let presentation_ctx = crate::client::correlation::CorrelationContext::new()
                        .connection_id(connection_id)
                        .token_fp(&token_fp);
                    crate::clog!(
                        "[PlutoRTC][session-token]",
                        &presentation_ctx,
                        "received_presentation token_len={}",
                        token.len()
                    );
                    let was_already_admitted = self
                        .session_token_registry
                        .is_session_token_admitted_for_connection(connection_id);
                    let verdict = self
                        .validate_session_token_for_connection_with_payload(
                            &token,
                            connection_id,
                            token_payload.as_deref(),
                        )
                        .await;
                    let (response, accepted) = match verdict {
                        Ok(scope) => {
                            if let Some(device_id) = presented_device_id.as_deref() {
                                let _ = self
                                    .bind_session_admission_authoritative_device_id(
                                        connection_id,
                                        device_id,
                                    )
                                    .await;
                            }
                            let admitted_ctx = self
                                .correlation_for_connection(connection_id)
                                .await
                                .token_fp(&token_fp);
                            crate::clog!(
                                "[PlutoRTC][session-token]",
                                &admitted_ctx,
                                "validated_admitted"
                            );
                            (
                                crate::native_protocol::NativeMainMessage::session_token_approval(
                                    (!scope.is_empty()).then_some(scope.as_str()),
                                    connection_id,
                                ),
                                true,
                            )
                        }
                        Err(reason) => {
                            crate::clog!(
                                "[PlutoRTC][session-token]",
                                &presentation_ctx,
                                "validated_rejected reason={}",
                                reason
                            );
                            (
                                crate::native_protocol::NativeMainMessage::session_token_rejection(
                                    &reason,
                                    connection_id,
                                ),
                                false,
                            )
                        }
                    };
                    return Ok(InspectedMainFrame::SessionTokenResponse {
                        response,
                        accepted,
                        is_first_presentation: accepted && !was_already_admitted,
                    });
                }

                let claimed_device_id = message.claimed_device_id();
                let known_device_id_owned = known_device_id.map(ToOwned::to_owned);
                let admitted_device_id = if self.session_registry_active() {
                    if is_handshake {
                        // Handshake: full admission check, persists rejection on failure.
                        self.ensure_native_session_admitted(
                            connection_id,
                            remote_node_id,
                            known_device_id,
                            claimed_device_id.as_deref(),
                        )?
                    } else {
                        // Non-handshake: require existing admission without persisting
                        // rejection so a later handshake can still succeed.
                        self.require_existing_admission(
                            connection_id,
                            remote_node_id,
                            known_device_id,
                        )?
                    }
                } else {
                    None
                };

                if message.is_peer_data() {
                    let generation = self
                        .current_native_peer_data_generation(connection_id, transport_stable_id)
                        .await
                        .ok_or_else(|| "native-peer-data-stale-generation".to_string())?;
                    let protected_payload = message
                        .peer_data_payload()
                        .ok_or_else(|| "native-peer-data-payload-missing".to_string())?;
                    let payload = self
                        .open_inbound_application_payload(connection_id, &protected_payload)
                        .map_err(|error| error.to_string())?;
                    self.emit_native_peer_data(crate::client::NativePeerDataEvent {
                        connection_id: connection_id.to_string(),
                        remote_node_id: remote_node_id
                            .map(str::trim)
                            .filter(|value| !value.is_empty())
                            .map(ToOwned::to_owned),
                        transport: crate::transport_label::IROH.to_string(),
                        transport_stable_id: generation.transport_stable_id,
                        transport_generation: generation.transport_generation,
                        route_generation: generation.route_generation,
                        payload,
                    });
                    return Ok(InspectedMainFrame::ForwardOpaque);
                }

                // Only attach a handshake binding for actual handshake messages.
                let handshake = if is_handshake
                    && (claimed_device_id.is_some()
                        || known_device_id_owned.is_some()
                        || admitted_device_id.is_some())
                {
                    Some(crate::native_protocol::NativeHandshakeBinding {
                        known_device_id: known_device_id_owned,
                        claimed_device_id,
                        authoritative_device_id_hint: admitted_device_id
                            .clone()
                            .or_else(|| known_device_id.map(ToOwned::to_owned)),
                        admitted_device_id,
                    })
                } else {
                    None
                };

                Ok(InspectedMainFrame::NativeMessage { message, handshake })
            }
            ParsedMainFrame::TypeScriptHandshake(handshake) => {
                println!(
                    "[PlutoRTC] Received TS handshake on connection_id={} has_token={} registry_active={}",
                    connection_id,
                    handshake.session_token.is_some(),
                    self.session_registry_active()
                );
                if self.session_registry_active() {
                    let action = handshake.action.as_deref().unwrap_or("hello");
                    if action == "hello" {
                        match handshake.session_token.as_deref() {
                            Some(token) => {
                                // TS handshake path has no dedicated response writer
                                // we can flush before side effects, so use the
                                // pre-Phase-1 inline-side-effects helper.
                                self.validate_session_token_for_connection_with_payload_and_side_effects(
                                    token,
                                    connection_id,
                                    handshake.session_token_payload.as_deref(),
                                )
                                .await?;
                            }
                            None => {
                                // No token on a hello — this happens after a browser page
                                // refresh where the outbound connectPeer() path never ran
                                // (the desktop accepted the inbound transport and sent the
                                // hello via the native-signal-routing path, which has no
                                // pending token).  If the connection is already admitted
                                // from the previous session, reuse that admission so the
                                // capability-update handshake can proceed and trigger WebRTC
                                // upgrade.  If it is not admitted, require a fresh token.
                                self.require_existing_admission(
                                    connection_id,
                                    remote_node_id,
                                    known_device_id,
                                )?;
                            }
                        }
                    } else {
                        self.require_existing_admission(
                            connection_id,
                            remote_node_id,
                            known_device_id,
                        )?;
                    }
                }
                if let Some(device_id) = handshake.claimed_device_id.as_deref() {
                    let _ = self
                        .bind_session_admission_authoritative_device_id(connection_id, device_id)
                        .await;
                }
                self.maybe_handle_typescript_handshake_capabilities(
                    connection_id,
                    remote_node_id,
                    &handshake,
                )
                .await;
                Ok(InspectedMainFrame::ForwardOpaque)
            }
            ParsedMainFrame::TypeScriptJson(json) => {
                if self.session_registry_active() {
                    // Require existing admission without persisting rejection.
                    self.require_existing_admission(
                        connection_id,
                        remote_node_id,
                        known_device_id,
                    )?;
                }
                self.maybe_handle_typescript_json_frame(connection_id, remote_node_id, &json)
                    .await;
                Ok(InspectedMainFrame::ForwardOpaque)
            }
            ParsedMainFrame::Opaque => {
                if self.session_registry_active() {
                    // Require existing admission without persisting rejection.
                    self.require_existing_admission(
                        connection_id,
                        remote_node_id,
                        known_device_id,
                    )?;
                }
                Ok(InspectedMainFrame::ForwardOpaque)
            }
        }
    }

    #[cfg(native)]
    pub fn extract_native_handshake_device_id(&self, frame: &[u8]) -> Option<String> {
        match crate::native_protocol::parse_main_frame(frame) {
            crate::native_protocol::ParsedMainFrame::NativeMessage(message) => {
                message.claimed_device_id()
            }
            _ => None,
        }
    }

    pub fn session_registry_active(&self) -> bool {
        !self.session_token_registry.is_empty()
    }

    #[cfg(native)]
    pub fn ensure_native_stream_admitted(
        &self,
        connection_id: &str,
        remote_node_id: Option<&str>,
        known_device_id: Option<&str>,
    ) -> Result<Option<String>, String> {
        // File transfer streams should not permanently reject — only deny
        // if the connection hasn't been admitted yet.
        self.require_existing_admission(connection_id, remote_node_id, known_device_id)
    }

    pub fn session_admission(&self, connection_id: &str) -> crate::session_token::SessionAdmission {
        self.session_token_registry.admission(connection_id)
    }

    /// Complete an already-accepted session admission with the peer's
    /// authoritative device id once a later handshake/native binding proves it.
    ///
    /// Some reconnect paths validate the session token before the managed
    /// connection record has been tagged with the browser/desktop device id.
    /// The admission is valid, but trusted-device features that require an
    /// authoritative device id (for example drive-view bucket discovery) must
    /// not remain stuck in that incomplete state.
    pub async fn bind_session_admission_authoritative_device_id(
        &self,
        connection_id: &str,
        device_id: &str,
    ) -> bool {
        let device_id = device_id.trim();
        if device_id.is_empty() {
            return false;
        }

        use crate::session_token::SessionAdmission;

        match self.session_admission(connection_id) {
            SessionAdmission::Accepted {
                authoritative_device_id: Some(existing),
                ..
            } => existing == device_id,
            SessionAdmission::Accepted {
                scope: Some(scope),
                authoritative_device_id: None,
                ..
            } => {
                self.connection_manager
                    .set_device_id(connection_id, device_id.to_string())
                    .await;
                self.session_token_registry.bind_connection_scope(
                    connection_id,
                    scope.clone(),
                    Some(device_id.to_string()),
                );
                println!(
                    "[PlutoRTC][session-admission][late-authoritative-device] connection_id={} scope={} authoritative_device_id={}",
                    connection_id,
                    scope.as_str(),
                    device_id
                );
                true
            }
            SessionAdmission::Accepted {
                mechanism,
                scope: None,
                authoritative_device_id: None,
            } => {
                self.connection_manager
                    .set_device_id(connection_id, device_id.to_string())
                    .await;
                self.session_token_registry.mark_accepted(
                    connection_id,
                    mechanism,
                    None,
                    Some(device_id.to_string()),
                );
                println!(
                    "[PlutoRTC][session-admission][late-authoritative-device] connection_id={} scope= authoritative_device_id={}",
                    connection_id,
                    device_id
                );
                true
            }
            _ => false,
        }
    }

    pub fn reject_session_connection(&self, connection_id: &str, reason: &str) {
        self.session_token_registry
            .mark_rejected(connection_id, reason);
    }

    pub fn forget_session_connection(&self, connection_id: &str) {
        self.session_token_registry.forget_connection(connection_id);
        // A deterministic connection id can be reused after logout, explicit
        // disconnect, revocation, or a fresh admission window. Its prior
        // application key and ephemeral agreement belong to the retired
        // logical session, not to the node pair forever. Keeping either lets a
        // replacement scope skip key agreement and encrypt with stale material.
        // Transient transport replacement does not call this boundary and
        // therefore keeps its established application session intact.
        self.clear_connection_application_crypto_key(connection_id);
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut proofs) = self.inbound_session_admission_transport_ids.write() {
            proofs.remove(connection_id);
        }
        if let Ok(mut proofs) = self.remote_session_admission_proofs.write() {
            proofs.remove(connection_id);
        }
        if let Ok(mut pending) = self.pending_inline_reciprocal_admissions.write() {
            pending.retain(|_, transcript| transcript.connection_id != connection_id);
        }
        if let Ok(mut epochs) = self
            .outbound_application_security_epoch_fingerprints
            .write()
        {
            epochs.remove(connection_id);
        }
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut contracts) = self.native_admission_stream_contracts.write() {
            contracts.remove(connection_id);
        }
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut requests) = self.pending_reciprocal_session_admission_requests.write() {
            requests.remove(connection_id);
        }
    }

    pub fn ensure_native_session_admitted(
        &self,
        connection_id: &str,
        remote_node_id: Option<&str>,
        known_device_id: Option<&str>,
        claimed_device_id: Option<&str>,
    ) -> Result<Option<String>, String> {
        self.ensure_native_session_admitted_inner(
            connection_id,
            remote_node_id,
            known_device_id,
            claimed_device_id,
            true,
        )
    }

    /// Like `ensure_native_session_admitted` but does NOT permanently mark
    /// the connection as Rejected when admission fails.  Used for
    /// non-handshake messages so that a legitimate handshake arriving later
    /// can still succeed.
    #[cfg(native)]
    pub(crate) fn require_existing_admission(
        &self,
        connection_id: &str,
        remote_node_id: Option<&str>,
        known_device_id: Option<&str>,
    ) -> Result<Option<String>, String> {
        self.ensure_native_session_admitted_inner(
            connection_id,
            remote_node_id,
            known_device_id,
            None,
            false,
        )
    }

    pub(crate) fn ensure_native_session_admitted_inner(
        &self,
        connection_id: &str,
        remote_node_id: Option<&str>,
        known_device_id: Option<&str>,
        claimed_device_id: Option<&str>,
        persist_rejection: bool,
    ) -> Result<Option<String>, String> {
        use crate::session_token::{
            NativeTrustedConnectionContext, SessionAdmission, SessionAdmissionMechanism,
        };

        if !self.session_registry_active() {
            return Ok(None);
        }

        match self.session_token_registry.admission(connection_id) {
            SessionAdmission::Accepted {
                authoritative_device_id,
                ..
            } => {
                return Ok(authoritative_device_id);
            }
            SessionAdmission::Rejected { reason } => {
                return Err(reason);
            }
            SessionAdmission::Pending => {}
        }

        let context = NativeTrustedConnectionContext {
            connection_id: connection_id.to_string(),
            remote_node_id: remote_node_id.map(ToOwned::to_owned),
            known_device_id: known_device_id
                .map(str::trim)
                .filter(|value| !value.is_empty())
                .map(ToOwned::to_owned),
            claimed_device_id: claimed_device_id
                .map(str::trim)
                .filter(|value| !value.is_empty())
                .map(ToOwned::to_owned),
        };

        if let Some(authoritative_device_id) = self
            .session_token_registry
            .evaluate_trusted_native_connection(&context)
        {
            self.session_token_registry.mark_accepted(
                connection_id,
                SessionAdmissionMechanism::TrustedNativeBinding,
                None,
                Some(authoritative_device_id.clone()),
            );
            return Ok(Some(authoritative_device_id));
        }

        let reason = "session-token-required".to_string();
        if persist_rejection {
            self.session_token_registry
                .mark_rejected(connection_id, reason.clone());
        }
        Err(reason)
    }

    /// Register a session token in the registry.
    pub fn register_session_token(&self, token: String, scope: String, max_connections: u32) {
        self.session_token_registry.register(
            token,
            crate::session_token::GrantScope::from(scope),
            max_connections,
        );
    }

    /// Register a session token with an absolute Unix-millisecond expiry.
    pub fn register_session_token_with_expiry_ms(
        &self,
        token: String,
        scope: String,
        max_connections: u32,
        expires_at_ms: u64,
    ) {
        self.session_token_registry.register_with_expiry_ms(
            token,
            crate::session_token::GrantScope::from(scope),
            max_connections,
            Some(expires_at_ms),
        );
    }

    /// Clear all registered short-lived session tokens and admission state.
    pub fn clear_session_tokens(&self) {
        self.session_token_registry.clear();
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut proofs) = self.inbound_session_admission_transport_ids.write() {
            proofs.clear();
        }
        if let Ok(mut proofs) = self.remote_session_admission_proofs.write() {
            proofs.clear();
        }
        if let Ok(mut pending) = self.pending_inline_reciprocal_admissions.write() {
            pending.clear();
        }
        if let Ok(mut epochs) = self
            .outbound_application_security_epoch_fingerprints
            .write()
        {
            epochs.clear();
        }
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut contracts) = self.native_admission_stream_contracts.write() {
            contracts.clear();
        }
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut requests) = self.pending_reciprocal_session_admission_requests.write() {
            requests.clear();
        }
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut credentials) = self.native_route_repair_credentials.write() {
            credentials.clear();
        }
        #[cfg(native)]
        if let Ok(mut cache) = self.managed_scope_tickets.write() {
            cache.clear();
        }
    }

    /// Keep the admission gate active even before any explicit share-style
    /// tokens are issued. This lets the app enforce "all native connections
    /// must be admitted" from startup onward while still allowing trusted
    /// native bindings to pass through the verifier path.
    pub fn ensure_default_admission_gate(&self, scope: &str) {
        if self.session_registry_active() {
            return;
        }

        let token = crate::session_token::generate_token();
        self.session_token_registry.register(
            token,
            crate::session_token::GrantScope::from(scope),
            0,
        );
    }

    /// Revoke a specific session token.
    pub fn revoke_session_token(&self, token: &str) -> Vec<String> {
        let token_fp = crate::session_token::token_fingerprint(token);
        eprintln!("[PlutoRTC][teardown-trace] revoke_session_token token_fp={token_fp}");
        let affected_connections = self.session_token_registry.revoke(token);
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut proofs) = self.inbound_session_admission_transport_ids.write() {
            for connection_id in &affected_connections {
                proofs.remove(connection_id);
            }
        }
        if let Ok(mut proofs) = self.remote_session_admission_proofs.write() {
            for connection_id in &affected_connections {
                proofs.remove(connection_id);
            }
        }
        if let Ok(mut pending) = self.pending_inline_reciprocal_admissions.write() {
            pending
                .retain(|_, transcript| !affected_connections.contains(&transcript.connection_id));
        }
        if let Ok(mut epochs) = self
            .outbound_application_security_epoch_fingerprints
            .write()
        {
            for connection_id in &affected_connections {
                epochs.remove(connection_id);
            }
        }
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut contracts) = self.native_admission_stream_contracts.write() {
            for connection_id in &affected_connections {
                contracts.remove(connection_id);
            }
        }
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut requests) = self.pending_reciprocal_session_admission_requests.write() {
            for connection_id in &affected_connections {
                requests.remove(connection_id);
            }
        }
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut credentials) = self.native_route_repair_credentials.write() {
            credentials.retain(|_, credential| credential.token != token);
        }
        if !affected_connections.is_empty() {
            let client = self.clone();
            let retirement_connections = affected_connections.clone();
            n0_future::task::spawn(async move {
                client
                    .retire_revoked_session_connections(&retirement_connections)
                    .await;
            });
        }
        #[cfg(native)]
        if let Ok(mut cache) = self.managed_scope_tickets.write() {
            // We only need to know whether the persistent managed scope token
            // is being removed; avoid cloning all matching scope keys.
            let remove_persistent_scope = cache.iter().any(|(scope, entry)| {
                scope.as_str() == PERSISTENT_MANAGED_ADMISSION_SCOPE && entry.token == token
            });
            cache.retain(|_, entry| entry.token != token);

            if remove_persistent_scope {
                if let Ok(base_dir_guard) = self.native_device_base_dir.try_read() {
                    if let Some(base_dir) = base_dir_guard.clone() {
                        let path = base_dir.join(format!(
                            "{}_{}.json",
                            PERSISTENT_MANAGED_SCOPE_TICKET_FILE_PREFIX,
                            PERSISTENT_MANAGED_ADMISSION_SCOPE
                        ));
                        match std::fs::remove_file(&path) {
                            Ok(()) => println!(
                                "[PlutoRTC][ticket][managed-persist-remove] scope={} path={}",
                                PERSISTENT_MANAGED_ADMISSION_SCOPE,
                                path.display()
                            ),
                            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                            Err(error) => eprintln!(
                                "[PlutoRTC][ticket][managed-persist-remove] failed scope={} path={} error={}",
                                PERSISTENT_MANAGED_ADMISSION_SCOPE,
                                path.display(),
                                error
                            ),
                        }
                    }
                }
            }
        }
        affected_connections
    }

    /// Revoke all tokens with the given scope.
    pub async fn revoke_tokens_by_scope(&self, scope: &str) -> Vec<String> {
        let affected_connections = self
            .session_token_registry
            .revoke_by_scope(&crate::session_token::GrantScope::from(scope));
        if let Ok(mut pending) = self.pending_inline_reciprocal_admissions.write() {
            pending
                .retain(|_, transcript| !affected_connections.contains(&transcript.connection_id));
        }
        if let Ok(mut epochs) = self
            .outbound_application_security_epoch_fingerprints
            .write()
        {
            for connection_id in &affected_connections {
                epochs.remove(connection_id);
            }
        }
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut credentials) = self.native_route_repair_credentials.write() {
            // Repair credentials are derived from remote compound tickets. A
            // scope revocation cannot identify their scope without trusting the
            // cached payload again, so discard all and repopulate from fresh
            // signaling observations.
            credentials.clear();
        }
        #[cfg(native)]
        if let Ok(mut cache) = self.managed_scope_tickets.write() {
            cache.retain(|entry_scope, _| entry_scope != scope);
        }
        #[cfg(native)]
        let _ = self.delete_persisted_managed_scope_grant(scope).await;
        let endpoint_disconnects = self
            .retire_revoked_session_connections(&affected_connections)
            .await;

        eprintln!(
            "[PlutoRTC][teardown-trace] revoke_tokens_by_scope scope={} affected_connections={} endpoint_disconnects={}",
            scope,
            affected_connections.len(),
            endpoint_disconnects
        );

        affected_connections
    }

    async fn retire_revoked_session_connections(&self, connection_ids: &[String]) -> usize {
        let mut endpoint_ids = HashSet::new();
        for connection_id in connection_ids {
            if let Some(record) = self
                .connection_manager
                .get_by_connection_id(connection_id)
                .await
            {
                let endpoint_candidate = record
                    .endpoint_id
                    .clone()
                    .or_else(|| record.node_id.clone());
                if let Some(endpoint_id) = endpoint_candidate {
                    endpoint_ids.insert(endpoint_id);
                } else {
                    self.connection_manager
                        .set_closed(
                            connection_id,
                            Some(crate::lifecycle_reason::REASON_SESSION_TOKEN_REVOKED.to_string()),
                        )
                        .await;
                }
            }
        }

        let endpoint_disconnects = endpoint_ids.len();
        for endpoint_id in endpoint_ids {
            match endpoint_id.parse::<iroh::EndpointId>() {
                Ok(parsed) => {
                    let _ = self
                        .disconnect_with_reason(
                            parsed,
                            crate::lifecycle_reason::REASON_SESSION_TOKEN_REVOKED,
                        )
                        .await;
                }
                Err(_) => {
                    let records = self.connection_manager.get_by_node_id(&endpoint_id).await;
                    for record in records {
                        self.connection_manager
                            .set_closed(
                                &record.connection_id,
                                Some(
                                    crate::lifecycle_reason::REASON_SESSION_TOKEN_REVOKED
                                        .to_string(),
                                ),
                            )
                            .await;
                    }
                }
            }
        }
        endpoint_disconnects
    }

    #[cfg(native)]
    async fn managed_scope_grant_path(&self, scope: &str) -> anyhow::Result<std::path::PathBuf> {
        let base_dir = self
            .native_device_base_dir
            .read()
            .await
            .clone()
            .ok_or_else(|| anyhow::anyhow!("native device identity not initialized"))?;
        let sanitized_scope = scope
            .trim()
            .chars()
            .map(|value| match value {
                'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => value,
                _ => '-',
            })
            .collect::<String>();
        Ok(base_dir.join(format!(
            "{}_{}.json",
            PERSISTENT_MANAGED_SCOPE_TICKET_FILE_PREFIX, sanitized_scope
        )))
    }

    #[cfg(native)]
    pub(crate) async fn load_persisted_managed_scope_grant(
        &self,
        scope: &str,
    ) -> anyhow::Result<Option<PersistedManagedScopeGrantRecord>> {
        let path = match self.managed_scope_grant_path(scope).await {
            Ok(path) => path,
            Err(_) => return Ok(None),
        };

        let payload = match tokio::fs::read_to_string(&path).await {
            Ok(payload) => payload,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => {
                return Err(anyhow::Error::new(error).context(format!(
                    "failed reading persisted managed scope grant: {}",
                    path.display()
                )));
            }
        };

        let persisted = serde_json::from_str::<PersistedManagedScopeGrantRecord>(&payload)
            .with_context(|| {
                format!(
                    "failed parsing persisted managed scope grant: {}",
                    path.display()
                )
            })?;
        Ok(Some(persisted))
    }

    #[cfg(native)]
    pub(crate) async fn persist_managed_scope_grant(
        &self,
        scope: &str,
        token: &str,
        max_connections: u32,
    ) -> anyhow::Result<()> {
        if scope.trim() != PERSISTENT_MANAGED_ADMISSION_SCOPE {
            return Ok(());
        }

        let path = self.managed_scope_grant_path(scope).await?;
        if let Some(parent) = path.parent() {
            tokio::fs::create_dir_all(parent).await.with_context(|| {
                format!(
                    "failed creating managed scope persistence directory: {}",
                    parent.display()
                )
            })?;
        }

        let payload = PersistedManagedScopeGrantRecord {
            scope: scope.trim().to_string(),
            token: token.to_string(),
            max_connections,
        };
        let serialized = serde_json::to_vec_pretty(&payload)
            .context("failed serializing persisted managed scope grant")?;
        Self::write_private_managed_scope_grant(&path, &serialized).await?;
        println!(
            "[PlutoRTC][ticket][managed-persist-store] scope={} token_fp={} max_connections={} path={}",
            payload.scope,
            log_fingerprint(token),
            max_connections,
            path.display()
        );
        Ok(())
    }

    #[cfg(native)]
    pub(crate) async fn delete_persisted_managed_scope_grant(
        &self,
        scope: &str,
    ) -> anyhow::Result<()> {
        if scope.trim() != PERSISTENT_MANAGED_ADMISSION_SCOPE {
            return Ok(());
        }

        let path = match self.managed_scope_grant_path(scope).await {
            Ok(path) => path,
            Err(_) => return Ok(()),
        };
        match tokio::fs::remove_file(&path).await {
            Ok(()) => {
                println!(
                    "[PlutoRTC][ticket][managed-persist-remove] scope={} path={}",
                    scope.trim(),
                    path.display()
                );
                Ok(())
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(error) => Err(anyhow::Error::new(error).context(format!(
                "failed removing managed scope grant: {}",
                path.display()
            ))),
        }
    }

    #[cfg(native)]
    pub(crate) async fn rehydrate_persistent_managed_scope_ticket(
        &self,
        scope: &str,
    ) -> anyhow::Result<()> {
        if scope.trim() != PERSISTENT_MANAGED_ADMISSION_SCOPE {
            return Ok(());
        }

        let Some(persisted) = self.load_persisted_managed_scope_grant(scope).await? else {
            return Ok(());
        };

        self.session_token_registry.register(
            persisted.token.clone(),
            crate::session_token::GrantScope::from(persisted.scope.clone()),
            persisted.max_connections,
        );

        let mut cache = match self.managed_scope_tickets.write() {
            Ok(guard) => guard,
            Err(poisoned) => poisoned.into_inner(),
        };
        cache.insert(
            scope.trim().to_string(),
            CachedManagedScopeTicket {
                scope: crate::session_token::GrantScope::from(persisted.scope.clone()),
                token: persisted.token.clone(),
                max_connections: persisted.max_connections,
                compound_ticket: String::new(),
                iroh_ticket: String::new(),
            },
        );

        println!(
            "[PlutoRTC][ticket][managed-persist-rehydrate] scope={} token_fp={} max_connections={}",
            persisted.scope,
            log_fingerprint(persisted.token.as_str()),
            persisted.max_connections
        );
        Ok(())
    }

    pub async fn mark_connection_admitted_by_host(
        &self,
        connection_id: &str,
        scope: Option<&str>,
        authoritative_device_id: Option<String>,
    ) {
        // On some reconnect/refresh paths, the host approves the session token before
        // the admission layer has an authoritative device id handy. If we already
        // bound a device id to this connection (via native bind / handshake), use it
        // as the authoritative id so trusted-device flows (e.g. drive-view over
        // native WebRTC) don't get spuriously rejected.
        let authoritative_device_id = if authoritative_device_id.is_some() {
            authoritative_device_id
        } else {
            self.connection_manager
                .get_by_connection_id(connection_id)
                .await
                .and_then(|record| record.device_id)
        };
        if let Some(device_id) = authoritative_device_id.as_deref() {
            self.connection_manager
                .set_device_id(connection_id, device_id.to_string())
                .await;
        }

        let normalized_scope = scope
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .map(ToOwned::to_owned);

        if let Some(scope_name) = normalized_scope.as_deref() {
            self.connection_manager
                .add_scope(connection_id, scope_name)
                .await;
            self.session_token_registry.bind_connection_scope(
                connection_id,
                crate::session_token::GrantScope::from(scope_name.to_string()),
                authoritative_device_id.clone(),
            );
        } else {
            self.session_token_registry.mark_accepted(
                connection_id,
                crate::session_token::SessionAdmissionMechanism::SessionToken,
                None,
                authoritative_device_id.clone(),
            );
        }

        #[cfg(all(not(target_arch = "wasm32"), feature = "transport-webrtc"))]
        {
            self.accept_replacement_peer(
                connection_id,
                authoritative_device_id.as_deref(),
                "replacement-peer-admitted",
            )
            .await;
            let _ = self
                .clear_native_webrtc_suppression(connection_id, None)
                .await;
        }

        println!(
            "[PlutoRTC][session-admission][local-accept] connection_id={} scope={} authoritative_device_id={}",
            connection_id,
            normalized_scope.as_deref().unwrap_or(""),
            authoritative_device_id.as_deref().unwrap_or("pending")
        );
    }

    /// Admit a runtime-discovered managed user-device connection after the
    /// transport has been bound to an authoritative device id.
    ///
    /// Managed same-user device discovery is already an admission source for
    /// auto-connect; keep the session-token registry, connection scopes, and
    /// connection identity in sync so read-side admission guards do not strand
    /// a healthy connection at `session-admission-pending`.
    pub async fn mark_trusted_user_device_connection_admitted(
        &self,
        connection_id: &str,
        authoritative_device_id: &str,
    ) -> bool {
        let authoritative_device_id = authoritative_device_id.trim();
        if authoritative_device_id.is_empty() {
            return false;
        }

        let admission = self.session_admission(connection_id);
        if self.session_registry_active() {
            match &admission {
                crate::session_token::SessionAdmission::Rejected { .. } => return false,
                crate::session_token::SessionAdmission::Accepted {
                    scope: Some(scope), ..
                } if !session_scope_allows_device_binding(scope.as_str()) => {
                    println!(
                        "[PlutoRTC][session-admission][device-bind-refused] connection_id={} scope={}",
                        connection_id,
                        scope.as_str(),
                    );
                    return false;
                }
                crate::session_token::SessionAdmission::Accepted { scope: None, .. }
                | crate::session_token::SessionAdmission::Pending => return false,
                crate::session_token::SessionAdmission::Accepted { scope: Some(_), .. } => {}
            }

            if !self
                .bind_session_admission_authoritative_device_id(
                    connection_id,
                    authoritative_device_id,
                )
                .await
            {
                println!(
                    "[PlutoRTC][session-admission][device-bind-refused] connection_id={} reason=authoritative-device-mismatch",
                    connection_id,
                );
                return false;
            }
        }

        self.connection_manager
            .set_device_id(connection_id, authoritative_device_id.to_string())
            .await;
        self.connection_manager
            .add_scope(connection_id, "user-device")
            .await;

        if self.session_registry_active() {
            match admission {
                crate::session_token::SessionAdmission::Accepted { .. } => {}
                crate::session_token::SessionAdmission::Rejected { .. }
                | crate::session_token::SessionAdmission::Pending => {
                    unreachable!("non-accepted admission returned before trusted-device mutation")
                }
            }
        }

        true
    }

    #[cfg(native)]
    pub fn set_native_trusted_connection_verifier(
        &self,
        verifier: Option<crate::session_token::NativeTrustedConnectionVerifier>,
    ) {
        self.session_token_registry
            .set_native_trusted_connection_verifier(verifier);
    }

    pub async fn present_session_token_to_host(
        &self,
        endpoint_id: iroh::EndpointId,
        connection_id: &str,
        token: &str,
    ) -> Result<String, String> {
        self.present_session_token(
            SessionTokenPresentationTarget::Host {
                endpoint_id,
                connection_id,
            },
            token,
            SessionTokenPresentationOptions::default(),
        )
        .await
    }

    pub async fn present_session_token_to_host_with_payload(
        &self,
        endpoint_id: iroh::EndpointId,
        connection_id: &str,
        token: &str,
        token_payload: Option<&str>,
    ) -> Result<String, String> {
        self.present_session_token(
            SessionTokenPresentationTarget::Host {
                endpoint_id,
                connection_id,
            },
            token,
            SessionTokenPresentationOptions {
                token_payload,
                device_id: None,
                reciprocal_requested: false,
            },
        )
        .await
    }

    pub(crate) async fn present_and_accept_session_token(
        &self,
        endpoint_id: iroh::EndpointId,
        connection_id: &str,
        token: &str,
        token_payload: Option<&str>,
        remote_authoritative_device_id: Option<String>,
    ) -> Result<String, String> {
        self.present_and_accept_session_token_with_options(
            endpoint_id,
            connection_id,
            token,
            token_payload,
            remote_authoritative_device_id,
            None,
            false,
            false,
        )
        .await
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) async fn present_and_accept_session_token_for_route_repair(
        &self,
        endpoint_id: iroh::EndpointId,
        connection_id: &str,
        token: &str,
        token_payload: Option<&str>,
        remote_authoritative_device_id: Option<String>,
        claimed_local_device_id: Option<String>,
        force_presentation: bool,
        request_reciprocal: bool,
    ) -> Result<String, String> {
        self.present_and_accept_session_token_with_options(
            endpoint_id,
            connection_id,
            token,
            token_payload,
            remote_authoritative_device_id,
            claimed_local_device_id,
            force_presentation,
            request_reciprocal,
        )
        .await
    }

    pub(crate) async fn present_and_accept_session_token_with_local_claim(
        &self,
        endpoint_id: iroh::EndpointId,
        connection_id: &str,
        token: &str,
        token_payload: Option<&str>,
        remote_authoritative_device_id: Option<String>,
        claimed_local_device_id: Option<String>,
    ) -> Result<String, String> {
        self.present_and_accept_session_token_with_options(
            endpoint_id,
            connection_id,
            token,
            token_payload,
            remote_authoritative_device_id,
            claimed_local_device_id,
            false,
            false,
        )
        .await
    }

    async fn present_and_accept_session_token_with_options(
        &self,
        endpoint_id: iroh::EndpointId,
        connection_id: &str,
        token: &str,
        token_payload: Option<&str>,
        remote_authoritative_device_id: Option<String>,
        claimed_local_device_id: Option<String>,
        force_presentation: bool,
        request_reciprocal: bool,
    ) -> Result<String, String> {
        // Admission presentation is a per-physical-generation single-flight.
        // Explicit connect and the managed-session actor can legitimately meet
        // here with the same token. Join that canonical exchange instead of
        // surfacing an internal ownership race to the caller. If the owner
        // exits without producing a matching proof, acquire the guard and make
        // this caller the replacement presenter.
        #[cfg(target_arch = "wasm32")]
        let presentation_join_deadline_ms =
            js_sys::Date::now() + SESSION_TOKEN_HOST_RESPONSE_TIMEOUT_MS as f64 + 1_000.0;
        #[cfg(not(target_arch = "wasm32"))]
        let presentation_join_deadline = std::time::Instant::now()
            + std::time::Duration::from_millis(SESSION_TOKEN_HOST_RESPONSE_TIMEOUT_MS + 1_000);
        let _presentation_guard = loop {
            if let Some(guard) = self
                .session_token_registry
                .try_begin_admission_presentation(connection_id)
            {
                break guard;
            }
            if let Some(approval_scope) = self
                .current_remote_session_admission_scope(connection_id, endpoint_id, token)
                .await
            {
                println!(
                    "[PlutoRTC][session-admission][single-flight] joined canonical presentation connection_id={} endpoint_id={} token_fp={} scope={}",
                    connection_id,
                    endpoint_id,
                    super::core_impl::log_fingerprint(token),
                    approval_scope,
                );
                return Ok(approval_scope);
            }
            #[cfg(target_arch = "wasm32")]
            let expired = js_sys::Date::now() >= presentation_join_deadline_ms;
            #[cfg(not(target_arch = "wasm32"))]
            let expired = std::time::Instant::now() >= presentation_join_deadline;
            if expired {
                return Err(format!(
                    "[session-token-presentation:join-timeout] canonical presenter did not finish for {}",
                    connection_id
                ));
            }
            #[cfg(target_arch = "wasm32")]
            gloo_timers::future::sleep(std::time::Duration::from_millis(25)).await;
            #[cfg(not(target_arch = "wasm32"))]
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        };
        // Close the check-then-present race with negotiated transport handoffs
        // and duplicate app-level connect requests. The proof is fenced to the
        // exact token and physical transport generation, so replaying the same
        // request cannot add authority. The host's original device binding also
        // remains authoritative: skipping a duplicate never rebinds it to a new
        // local claim. Route repair can still force a fresh presentation after
        // it has invalidated the generation-bound proof.
        if !force_presentation {
            if let Some(approval_scope) = self
                .current_remote_session_admission_scope(connection_id, endpoint_id, token)
                .await
            {
                println!(
                    "[PlutoRTC][session-admission][remote-proof] presentation skipped connection_id={} endpoint_id={} token_fp={} scope={} reason=current-transport-already-approved",
                    connection_id,
                    endpoint_id,
                    super::core_impl::log_fingerprint(token),
                    approval_scope,
                );
                return Ok(approval_scope);
            }
        }
        let local_device_id = claimed_local_device_id
            .filter(|device_id| !device_id.trim().is_empty())
            .or_else(|| {
                self.active_session_identity()
                    .map(|(_, device_id)| device_id)
            })
            .filter(|device_id| !device_id.trim().is_empty());
        let approval_scope = self
            .present_session_token(
                SessionTokenPresentationTarget::Host {
                    endpoint_id,
                    connection_id,
                },
                token,
                SessionTokenPresentationOptions {
                    token_payload,
                    device_id: local_device_id.as_deref(),
                    reciprocal_requested: request_reciprocal,
                },
            )
            .await?;
        self.mark_connection_admitted_by_host(
            connection_id,
            if approval_scope.trim().is_empty() {
                None
            } else {
                Some(approval_scope.as_str())
            },
            remote_authoritative_device_id,
        )
        .await;
        self.normalize_session_token_scope_trust_class(
            connection_id,
            if approval_scope.trim().is_empty() {
                None
            } else {
                Some(approval_scope.as_str())
            },
        )
        .await;
        #[cfg(target_arch = "wasm32")]
        if let Some(transport_stable_id) = self
            .get_connection(endpoint_id)
            .await
            .map(|connection| connection.stable_id() as u64)
        {
            if let Ok(mut proofs) = self.remote_session_admission_proofs.write() {
                proofs.insert(
                    connection_id.to_string(),
                    RemoteSessionAdmissionProof {
                        transport_stable_id,
                        token_fingerprint: crate::session_token::token_fingerprint(token),
                        approval_scope: approval_scope.clone(),
                    },
                );
            }
            println!(
                "[PlutoRTC][session-admission][remote-proof] connection_id={} endpoint_id={} transport_stable_id={} token_fp={}",
                connection_id,
                endpoint_id,
                transport_stable_id,
                super::core_impl::log_fingerprint(token),
            );
        }
        Ok(approval_scope)
    }

    pub(crate) async fn has_current_remote_session_admission_proof(
        &self,
        connection_id: &str,
        endpoint_id: iroh::EndpointId,
        token: &str,
    ) -> bool {
        self.current_remote_session_admission_scope(connection_id, endpoint_id, token)
            .await
            .is_some()
    }

    /// Return whether this side has completed the outbound admission required
    /// by a compound endpoint ticket. Plain endpoint tickets require no
    /// session-token proof and are therefore already ready.
    pub async fn remote_session_admission_ready_for_ticket(
        &self,
        endpoint_ticket: &str,
    ) -> anyhow::Result<bool> {
        let (iroh_ticket, token_suffix) =
            crate::session_token::split_compound_ticket(endpoint_ticket.trim());
        let Some(token_suffix) = token_suffix else {
            return Ok(true);
        };
        let payload =
            crate::session_token::decode_token_payload_for_ticket(iroh_ticket, token_suffix)
                .ok_or_else(|| {
                    anyhow::anyhow!("invalid compound ticket payload for endpoint ticket")
                })?;
        let endpoint_addr = parse_endpoint_ticket(iroh_ticket)?;
        let Some(local_node_id) = self.current_node_id().await else {
            return Ok(false);
        };
        let connection_id =
            Self::deterministic_connection_id(&local_node_id, &endpoint_addr.id.to_string());
        Ok(self
            .has_current_remote_session_admission_proof(
                &connection_id,
                endpoint_addr.id,
                payload.token.as_str(),
            )
            .await)
    }

    async fn current_remote_session_admission_scope(
        &self,
        connection_id: &str,
        endpoint_id: iroh::EndpointId,
        token: &str,
    ) -> Option<String> {
        let Some(transport_stable_id) = self
            .get_connection(endpoint_id)
            .await
            .map(|connection| connection.stable_id() as u64)
        else {
            return None;
        };
        let token_fingerprint = crate::session_token::token_fingerprint(token);
        let proof = self
            .remote_session_admission_proofs
            .read()
            .ok()
            .and_then(|proofs| proofs.get(connection_id).cloned());
        let matches = proof.as_ref().is_some_and(|proof| {
            proof.transport_stable_id == transport_stable_id
                && proof.token_fingerprint == token_fingerprint
        });
        if Self::admission_trace_enabled() {
            match proof.as_ref() {
                Some(proof) => println!(
                    "[PlutoRTC][session-admission][remote-proof-check] connection_id={} endpoint_id={} current_stable_id={} proof_stable_id={} stable_id_matches={} token_matches={} result={}",
                    connection_id,
                    endpoint_id,
                    transport_stable_id,
                    proof.transport_stable_id,
                    proof.transport_stable_id == transport_stable_id,
                    proof.token_fingerprint == token_fingerprint,
                    matches,
                ),
                None => println!(
                    "[PlutoRTC][session-admission][remote-proof-check] connection_id={} endpoint_id={} current_stable_id={} result=false reason=missing-proof",
                    connection_id, endpoint_id, transport_stable_id,
                ),
            }
        }
        matches.then(|| proof.expect("matched proof exists").approval_scope)
    }

    /// Prepare one reciprocal presentation in the Rust admission owner.
    /// Browser adapters may provide the credential they learned from the
    /// authoritative directory, but the resulting transcript is fenced to the
    /// current inbound admission epoch, physical generation, and exact stream
    /// instance before any bytes are sent.
    pub async fn prepare_inline_reciprocal_session_admission(
        &self,
        endpoint_id: iroh::EndpointId,
        expected_transport_stable_id: u64,
        stream_instance_id: &str,
        presentation_id: &str,
        token: &str,
        token_payload: &str,
        device_id: &str,
        stream_contract: crate::native_protocol::SessionTokenStreamContract,
    ) -> Result<crate::native_protocol::ReciprocalSessionTokenPresentation, String> {
        let stream_instance_id = stream_instance_id.trim();
        let presentation_id = presentation_id.trim();
        let token = token.trim();
        let token_payload = token_payload.trim();
        let device_id = device_id.trim();
        if stream_instance_id.is_empty()
            || presentation_id.is_empty()
            || token.is_empty()
            || token_payload.is_empty()
            || device_id.is_empty()
        {
            return Err("reciprocal admission transcript contains an empty field".to_string());
        }
        let current_transport_stable_id = self
            .get_connection(endpoint_id)
            .await
            .map(|connection| connection.stable_id() as u64);
        if current_transport_stable_id != Some(expected_transport_stable_id) {
            return Err(format!(
                "reciprocal admission preparation belongs to a retired transport generation: expected={} current={:?}",
                expected_transport_stable_id, current_transport_stable_id,
            ));
        }
        let local_node_id = self
            .current_node_id()
            .await
            .ok_or_else(|| "missing local node id for reciprocal admission".to_string())?;
        let remote_node_id = endpoint_id.to_string();
        let connection_id = Self::deterministic_connection_id(&local_node_id, &remote_node_id);
        let inbound_admission_fingerprint = self
            .session_token_registry
            .admission_fingerprint(&connection_id)
            .ok_or_else(|| {
                "reciprocal admission preparation requires an accepted inbound token epoch"
                    .to_string()
            })?;
        let inbound_admission_epoch = self
            .session_token_registry
            .admission_epoch(&connection_id)
            .ok_or_else(|| {
                "reciprocal admission preparation requires a current admission epoch".to_string()
            })?;
        let remote_device_id = self
            .known_remote_device_id_for_incoming_transport(&connection_id, &remote_node_id)
            .await
            .filter(|remote_device_id| !remote_device_id.trim().is_empty())
            .ok_or_else(|| {
                "reciprocal admission preparation requires an authoritative remote device"
                    .to_string()
            })?;
        match self.session_admission(&connection_id) {
            crate::session_token::SessionAdmission::Accepted {
                authoritative_device_id: Some(admitted_device_id),
                ..
            } if admitted_device_id == remote_device_id => {}
            crate::session_token::SessionAdmission::Accepted { .. } => {
                return Err(
                    "reciprocal admission preparation has no matching admitted remote identity"
                        .to_string(),
                );
            }
            _ => {
                return Err(
                    "reciprocal admission preparation requires an accepted inbound admission"
                        .to_string(),
                );
            }
        }
        let active_local_device_id = self
            .active_session_identity()
            .map(|(_, local_device_id)| local_device_id)
            .filter(|local_device_id| !local_device_id.trim().is_empty())
            .ok_or_else(|| "local managed-session identity is unavailable".to_string())?;
        if active_local_device_id != device_id {
            return Err(format!(
                "reciprocal admission local device mismatch: active={} claimed={}",
                active_local_device_id, device_id,
            ));
        }
        let payload = crate::session_token::decode_token_payload(token_payload)
            .filter(crate::session_token::token_payload_metadata_is_valid)
            .ok_or_else(|| {
                "reciprocal admission token payload is invalid or expired".to_string()
            })?;
        if payload.token != token {
            return Err("reciprocal admission token payload does not match the token".to_string());
        }
        let expected_scope = payload.scope.as_str().trim().to_string();
        if expected_scope.is_empty() {
            return Err("reciprocal admission token scope is empty".to_string());
        }

        let transcript = crate::client::PendingInlineReciprocalAdmission {
            connection_id: connection_id.clone(),
            remote_node_id: remote_node_id.clone(),
            local_device_id: active_local_device_id,
            remote_device_id,
            transport_stable_id: expected_transport_stable_id,
            stream_instance_id: stream_instance_id.to_string(),
            presentation_id: presentation_id.to_string(),
            token: token.to_string(),
            token_fingerprint: crate::session_token::token_fingerprint(token),
            expected_scope,
            inbound_admission_fingerprint,
            inbound_admission_epoch,
        };
        let mut pending = self
            .pending_inline_reciprocal_admissions
            .write()
            .map_err(|_| "reciprocal admission transcript registry is unavailable".to_string())?;
        pending.retain(|_, existing| {
            existing.remote_node_id != remote_node_id
                || existing.transport_stable_id != expected_transport_stable_id
                || existing.stream_instance_id != stream_instance_id
        });
        pending.insert(presentation_id.to_string(), transcript);

        Ok(crate::native_protocol::ReciprocalSessionTokenPresentation {
            presentation_id: presentation_id.to_string(),
            token: token.to_string(),
            token_payload: token_payload.to_string(),
            device_id: device_id.to_string(),
            stream_contract,
        })
    }

    /// Commit the peer's ACK for an inline reciprocal presentation to the
    /// Rust-owned admission state. The adapter reports only the correlated ACK;
    /// token, scope expectation, identity epoch, and route generation all come
    /// from the Rust-owned preparation transcript.
    pub async fn confirm_inline_reciprocal_session_admission(
        &self,
        endpoint_id: iroh::EndpointId,
        expected_transport_stable_id: u64,
        stream_instance_id: &str,
        presentation_id: &str,
        accepted: bool,
        approval_scope: Option<&str>,
    ) -> Result<(), String> {
        let stream_instance_id = stream_instance_id.trim();
        let presentation_id = presentation_id.trim();
        let transcript = self
            .pending_inline_reciprocal_admissions
            .read()
            .map_err(|_| "reciprocal admission transcript registry is unavailable".to_string())?
            .get(presentation_id)
            .cloned()
            .ok_or_else(|| "reciprocal admission ACK has no pending transcript".to_string())?;
        if transcript.presentation_id != presentation_id
            || transcript.remote_node_id != endpoint_id.to_string()
            || transcript.transport_stable_id != expected_transport_stable_id
            || transcript.stream_instance_id != stream_instance_id
        {
            return Err(
                "reciprocal admission ACK does not match its prepared transcript".to_string(),
            );
        }
        if !accepted {
            if let Ok(mut pending) = self.pending_inline_reciprocal_admissions.write() {
                pending.remove(presentation_id);
            }
            return Ok(());
        }
        let current_transport_stable_id = self
            .get_connection(endpoint_id)
            .await
            .map(|connection| connection.stable_id() as u64);
        if current_transport_stable_id != Some(expected_transport_stable_id) {
            return Err(format!(
                "reciprocal admission ACK belongs to a retired transport generation: expected={} current={:?}",
                expected_transport_stable_id, current_transport_stable_id,
            ));
        }
        let connection_id = transcript.connection_id.clone();
        let active_local_device_id = self
            .active_session_identity()
            .map(|(_, local_device_id)| local_device_id)
            .filter(|local_device_id| !local_device_id.trim().is_empty());
        if active_local_device_id.as_deref() != Some(transcript.local_device_id.as_str()) {
            return Err("reciprocal admission ACK belongs to a retired local identity".to_string());
        }
        let current_remote_device_id = self
            .known_remote_device_id_for_incoming_transport(
                &connection_id,
                &transcript.remote_node_id,
            )
            .await;
        if current_remote_device_id.as_deref() != Some(transcript.remote_device_id.as_str()) {
            return Err(
                "reciprocal admission ACK belongs to a retired remote identity".to_string(),
            );
        }
        match self.session_admission(&connection_id) {
            crate::session_token::SessionAdmission::Accepted {
                authoritative_device_id: Some(admitted_device_id),
                ..
            } if admitted_device_id == transcript.remote_device_id => {}
            _ => {
                return Err(
                    "reciprocal admission ACK arrived outside its admitted remote identity"
                        .to_string(),
                );
            }
        }
        if !self
            .connection_manager
            .current_transport_matches(&connection_id, Some(expected_transport_stable_id))
            .await
        {
            return Err(
                "reciprocal admission ACK does not match the managed transport generation"
                    .to_string(),
            );
        }
        if self
            .session_token_registry
            .admission_fingerprint(&connection_id)
            != Some(transcript.inbound_admission_fingerprint.clone())
        {
            return Err(
                "reciprocal admission ACK belongs to a retired admission epoch".to_string(),
            );
        }
        if self.session_token_registry.admission_epoch(&connection_id)
            != Some(transcript.inbound_admission_epoch)
        {
            return Err(
                "reciprocal admission ACK belongs to a retired admission generation".to_string(),
            );
        }

        let approval_scope = approval_scope.unwrap_or_default().trim().to_string();
        if approval_scope != transcript.expected_scope {
            return Err(format!(
                "reciprocal admission ACK scope mismatch: expected={} received={}",
                transcript.expected_scope, approval_scope,
            ));
        }
        if let Ok(mut proofs) = self.remote_session_admission_proofs.write() {
            proofs.insert(
                connection_id.clone(),
                RemoteSessionAdmissionProof {
                    transport_stable_id: expected_transport_stable_id,
                    token_fingerprint: transcript.token_fingerprint.clone(),
                    approval_scope: approval_scope.clone(),
                },
            );
        } else {
            return Err("remote admission proof registry is unavailable".to_string());
        }
        self.commit_outbound_session_token_application_security_epoch(
            &connection_id,
            transcript.token.as_str(),
        );
        if let Ok(mut pending) = self.pending_inline_reciprocal_admissions.write() {
            pending.remove(presentation_id);
        }
        let _ = self
            .confirm_managed_connection_readiness_from_transport_proof(
                &connection_id,
                expected_transport_stable_id,
            )
            .await;
        println!(
            "[PlutoRTC][session-admission][inline-reciprocal-commit] connection_id={} endpoint_id={} transport_stable_id={} token_fp={} scope={}",
            connection_id,
            endpoint_id,
            expected_transport_stable_id,
            super::core_impl::log_fingerprint(transcript.token.as_str()),
            approval_scope,
        );
        Ok(())
    }

    pub async fn present_session_token_to_host_with_payload_and_device_id(
        &self,
        endpoint_id: iroh::EndpointId,
        connection_id: &str,
        token: &str,
        token_payload: Option<&str>,
        device_id: Option<&str>,
    ) -> Result<String, String> {
        self.present_session_token(
            SessionTokenPresentationTarget::Host {
                endpoint_id,
                connection_id,
            },
            token,
            SessionTokenPresentationOptions {
                token_payload,
                device_id,
                reciprocal_requested: false,
            },
        )
        .await
    }

    async fn present_session_token(
        &self,
        target: SessionTokenPresentationTarget<'_>,
        token: &str,
        options: SessionTokenPresentationOptions<'_>,
    ) -> Result<String, String> {
        let (endpoint_id, connection_id, is_endpoint_target) = match target {
            SessionTokenPresentationTarget::Host {
                endpoint_id,
                connection_id,
            } => (
                endpoint_id,
                std::borrow::Cow::Borrowed(connection_id),
                false,
            ),
            SessionTokenPresentationTarget::Endpoint { endpoint_id } => {
                let remote_node_id = endpoint_id.to_string();
                let local_node_id = self.current_node_id().await.ok_or_else(|| {
                    "missing local node id for session-token presentation".to_string()
                })?;
                (
                    endpoint_id,
                    std::borrow::Cow::Owned(Self::deterministic_connection_id(
                        &local_node_id,
                        &remote_node_id,
                    )),
                    true,
                )
            }
        };
        self.begin_outbound_session_token_application_security_epoch(connection_id.as_ref(), token);

        async fn read_peer_exact(
            recv: &mut crate::application_crypto_streams::PeerRecvStream,
            buffer: &mut [u8],
            context: &str,
        ) -> Result<(), String> {
            let mut offset = 0;
            while offset < buffer.len() {
                let read = recv
                    .read(&mut buffer[offset..])
                    .await
                    .map_err(|error| format!("[{context}] {error}"))?;
                if read == 0 {
                    return Err(format!("[{context}] stream finished early (0 bytes read)"));
                }
                offset += read;
            }
            Ok(())
        }

        async fn read_native_main_message(
            recv: &mut crate::application_crypto_streams::PeerRecvStream,
        ) -> Result<crate::native_protocol::NativeMainMessage, String> {
            let mut protocol_byte = [0u8; 1];
            read_peer_exact(
                recv,
                &mut protocol_byte,
                "session-token-response:protocol-byte",
            )
            .await?;
            if protocol_byte[0] != 0x00 {
                return Err(format!(
                    "unexpected session-token response protocol byte: {}",
                    protocol_byte[0]
                ));
            }

            let mut label_len_buf = [0u8; 4];
            read_peer_exact(recv, &mut label_len_buf, "session-token-response:label-len").await?;
            let label_len = u32::from_be_bytes(label_len_buf) as usize;
            let mut label_buf = vec![0u8; label_len];
            read_peer_exact(recv, &mut label_buf, "session-token-response:label").await?;
            if String::from_utf8_lossy(&label_buf) != "main" {
                return Err("unexpected label in session-token response".to_string());
            }

            let mut frame_len_buf = [0u8; 4];
            read_peer_exact(recv, &mut frame_len_buf, "session-token-response:frame-len").await?;
            let frame_len = u32::from_be_bytes(frame_len_buf) as usize;
            let mut frame = vec![0u8; frame_len];
            read_peer_exact(recv, &mut frame, "session-token-response:frame-body").await?;

            match crate::native_protocol::parse_main_frame(&frame) {
                crate::native_protocol::ParsedMainFrame::NativeMessage(message) => Ok(message),
                other => Err(format!(
                    "unexpected session-token response frame: {:?}",
                    other
                )),
            }
        }

        // The dial path can briefly race connection registration (especially in wasm
        // during replacement churn). Give the endpoint a short window to appear
        // before failing the entire admission flow.
        let connection = {
            #[cfg(target_arch = "wasm32")]
            let deadline_ms = js_sys::Date::now() + 2_000.0;
            #[cfg(not(target_arch = "wasm32"))]
            let deadline = std::time::Instant::now() + std::time::Duration::from_millis(2_000);
            loop {
                if let Some(conn) = self.get_connection(endpoint_id).await {
                    break conn;
                }
                #[cfg(target_arch = "wasm32")]
                let expired = js_sys::Date::now() >= deadline_ms;
                #[cfg(not(target_arch = "wasm32"))]
                let expired = std::time::Instant::now() >= deadline;
                if expired {
                    return Err(format!(
                        "missing connection for session-token presentation: {}",
                        connection_id.as_ref()
                    ));
                }
                #[cfg(target_arch = "wasm32")]
                gloo_timers::future::sleep(std::time::Duration::from_millis(25)).await;
                #[cfg(not(target_arch = "wasm32"))]
                tokio::time::sleep(std::time::Duration::from_millis(25)).await;
            }
        };

        let application_crypto_active = self
            .application_crypto_key_for_connection(Some(connection_id.as_ref()))
            .is_some();
        #[cfg(not(target_arch = "wasm32"))]
        let persistent_control_required =
            self.native_admission_stream_is_persistent(connection_id.as_ref());
        #[cfg(target_arch = "wasm32")]
        let persistent_control_required = false;
        // Once a native managed session declares a persistent control route,
        // route repair must replace that route with the same contract. Falling
        // back to a one-shot keyed presentation leaves the QUIC leg alive but
        // removes its generation-bound application-route proof when the short
        // stream closes.
        let stream_contract = outgoing_session_token_stream_contract(
            cfg!(target_arch = "wasm32"),
            application_crypto_active,
            persistent_control_required,
        );
        let token_msg = crate::native_protocol::NativeMainMessage::session_token_presentation_with_payload_and_device_id(
            token,
            options.token_payload,
            options.device_id,
        )
        .with_session_token_stream_contract(stream_contract)
        .with_session_token_reciprocal_requested(options.reciprocal_requested);
        let response_ack_requested = token_msg.session_token_response_ack_requested();
        let serialized = serde_json::to_vec(&token_msg).map_err(|error| {
            format!("failed to serialize session-token presentation: {}", error)
        })?;

        #[cfg(not(target_arch = "wasm32"))]
        let transport_stable_id = connection.stable_id() as u64;
        let (send, recv) = connection.open_bi().await.map_err(|error| {
            format!(
                "failed to open bi-stream for session-token presentation: {}",
                error
            )
        })?;
        // Admission is SDK control, not product data. Keep it independent of
        // directional application-key readiness so a reconnect can reauthorize
        // after one-sided key agreement. Iroh already authenticates and
        // encrypts this QUIC stream end to end.
        let (mut send, mut recv) = (
            crate::application_crypto_streams::PeerSendStream::plain(send),
            crate::application_crypto_streams::PeerRecvStream::plain(recv),
        );

        println!(
            "[PlutoRTC][session-token-presentation] dialer sending token connection_id={} endpoint_id={} token_fp={} payload_len={}",
            connection_id.as_ref(),
            endpoint_id,
            super::core_impl::log_fingerprint(token),
            serialized.len(),
        );

        let label = b"main";
        let label_len = (label.len() as u32).to_be_bytes();
        let frame_len = (serialized.len() as u32).to_be_bytes();

        let mut buf = Vec::with_capacity(1 + 4 + label.len() + 4 + serialized.len());
        buf.push(0x00);
        buf.extend_from_slice(&label_len);
        buf.extend_from_slice(label);
        buf.extend_from_slice(&frame_len);
        buf.extend_from_slice(&serialized);

        send.write_all(&buf)
            .await
            .map_err(|error| format!("failed to write session-token presentation: {}", error))?;
        send.flush()
            .await
            .map_err(|error| format!("failed to flush session-token presentation: {}", error))?;
        // Intentionally do NOT call `send.finish()` here. On mobile (carrier
        // NAT / iOS Network.framework), finishing the send half before the
        // response arrives lets the inbound UDP pinhole close: there are no
        // more outbound stream frames to keep the path warm, and the host's
        // response packet gets dropped at the NAT, surfacing as "connection
        // lost" on the dialer's recv. The host parser at
        // `consume_pending_sdk_token_stream` reads length-prefixed bytes —
        // it never depends on seeing the FIN bit to know the payload boundary.
        // We finish the send half AFTER the response byte is read.
        println!(
            "[PlutoRTC][session-token-presentation] dialer write done connection_id={} endpoint_id={} awaiting host response",
            connection_id.as_ref(),
            endpoint_id,
        );

        // Bound the host-response read. A genuine granting host replies promptly,
        // but a peer that does not run the host token responder (e.g. a browser
        // dialing another user-owned browser in a mesh) would otherwise leave this
        // `read_exact` awaiting forever — wedging the entire managed dial so it
        // never returns, and starving the higher-level Client handshake (hello +
        // application key agreement) that the dialer must still perform. The
        // caller treats a presentation error as non-fatal, so a timeout simply
        // lets the connection fall through to the trust-based application route.
        let response = {
            use futures::FutureExt;
            let read_fut = read_native_main_message(&mut recv).fuse();
            futures::pin_mut!(read_fut);
            #[cfg(target_arch = "wasm32")]
            let timeout = gloo_timers::future::sleep(std::time::Duration::from_millis(
                SESSION_TOKEN_HOST_RESPONSE_TIMEOUT_MS,
            ))
            .fuse();
            #[cfg(not(target_arch = "wasm32"))]
            let timeout = tokio::time::sleep(std::time::Duration::from_millis(
                SESSION_TOKEN_HOST_RESPONSE_TIMEOUT_MS,
            ))
            .fuse();
            futures::pin_mut!(timeout);
            futures::select! {
                result = read_fut => result,
                _ = timeout => Err(format!(
                    "[session-token-response:timeout] no host response within {}ms",
                    SESSION_TOKEN_HOST_RESPONSE_TIMEOUT_MS
                )),
            }
        }
        .map_err(|error| {
            eprintln!(
                "[PlutoRTC][session-token-presentation] dialer recv FAILED connection_id={} endpoint_id={} token_fp={} error={}",
                connection_id.as_ref(),
                endpoint_id,
                super::core_impl::log_fingerprint(token),
                error
            );
            error
        })?;
        if !response.is_session_token_response() {
            let _ = send.finish();
            return Err(
                "host returned unexpected response to session-token presentation".to_string(),
            );
        }

        if response.session_token_approved() == Some(true) {
            #[cfg(not(target_arch = "wasm32"))]
            let (reciprocal_acceptance, reciprocal_ack) = if options.reciprocal_requested {
                let current_transport_stable_id = self
                    .get_connection(endpoint_id)
                    .await
                    .map(|connection| connection.stable_id() as u64);
                if current_transport_stable_id != Some(transport_stable_id) {
                    let _ = send.finish();
                    return Err(format!(
                        "physical transport changed before reciprocal session admission could be validated: response={} current={:?}",
                        transport_stable_id, current_transport_stable_id,
                    ));
                }
                if response.reciprocal_session_token_mode() != Some("inline-v1") {
                    (None, None)
                } else {
                    match response.reciprocal_session_token_presentation_state() {
                    crate::native_protocol::ReciprocalSessionTokenPresentationState::Present(
                        presentation,
                    ) => {
                        let presentation_id = presentation.presentation_id.clone();
                        let reciprocal_remote_node_id = endpoint_id.to_string();
                        let expected_remote_device_id = self
                            .known_remote_device_id_for_incoming_transport(
                                connection_id.as_ref(),
                                reciprocal_remote_node_id.as_str(),
                            )
                            .await;
                        if expected_remote_device_id.as_deref()
                            != Some(presentation.device_id.as_str())
                        {
                            (
                                None,
                                Some((
                                    presentation_id,
                                    false,
                                    None,
                                    Some("authoritative-device-mismatch".to_string()),
                                )),
                            )
                        } else if presentation.stream_contract != stream_contract {
                            (
                                None,
                                Some((
                                    presentation_id,
                                    false,
                                    None,
                                    Some("stream-contract-mismatch".to_string()),
                                )),
                            )
                        } else {
                            let was_already_admitted = self
                                .session_token_registry
                                .is_session_token_admitted_for_connection(connection_id.as_ref());
                            match self
                                .validate_session_token_for_connection_with_payload(
                                    presentation.token.as_str(),
                                    connection_id.as_ref(),
                                    Some(presentation.token_payload.as_str()),
                                )
                                .await
                            {
                                Ok(scope) => {
                                    let device_bound = self
                                        .bind_session_admission_authoritative_device_id(
                                            connection_id.as_ref(),
                                            presentation.device_id.as_str(),
                                        )
                                        .await;
                                    if !device_bound {
                                        self.reject_session_connection(
                                            connection_id.as_ref(),
                                            "reciprocal-authoritative-device-mismatch",
                                        );
                                        (
                                            None,
                                            Some((
                                                presentation_id,
                                                false,
                                                None,
                                                Some("authoritative-device-mismatch".to_string()),
                                            )),
                                        )
                                    } else {
                                        self.bind_inbound_native_admission_stream_contract(
                                            connection_id.as_ref(),
                                            stream_contract,
                                        );
                                        self.bind_inbound_session_token_transport(
                                            connection_id.as_ref(),
                                            transport_stable_id,
                                        );
                                        (
                                            Some((
                                                presentation,
                                                scope.clone(),
                                                was_already_admitted,
                                            )),
                                            Some((presentation_id, true, Some(scope), None)),
                                        )
                                    }
                                }
                                Err(error) => (
                                    None,
                                    Some((
                                        presentation_id,
                                        false,
                                        None,
                                        Some(format!("token-rejected:{error}")),
                                    )),
                                ),
                            }
                        }
                    }
                    crate::native_protocol::ReciprocalSessionTokenPresentationState::Malformed => (
                        None,
                        response.reciprocal_session_token_presentation_id().map(
                            |presentation_id| {
                                (
                                    presentation_id,
                                    false,
                                    None,
                                    Some("malformed-presentation".to_string()),
                                )
                            },
                        ),
                    ),
                    crate::native_protocol::ReciprocalSessionTokenPresentationState::Absent => {
                        (None, None)
                    }
                }
                }
            } else {
                (None, None)
            };
            if response_ack_requested {
                let ack = crate::native_protocol::NativeMainMessage::session_token_response_ack(
                    connection_id.as_ref(),
                );
                #[cfg(not(target_arch = "wasm32"))]
                let ack = match reciprocal_ack.as_ref() {
                    Some((presentation_id, accepted, scope, reason)) => ack
                        .with_reciprocal_session_token_ack(
                            presentation_id,
                            *accepted,
                            scope.as_deref(),
                            reason.as_deref(),
                        ),
                    None => ack,
                };
                let serialized_ack = serde_json::to_vec(&ack).map_err(|error| {
                    format!("failed to serialize session-token response ACK: {error}")
                })?;
                let mut ack_frame = Vec::with_capacity(1 + 4 + 4 + 4 + serialized_ack.len());
                ack_frame.push(0x00);
                ack_frame.extend_from_slice(&(4u32).to_be_bytes());
                ack_frame.extend_from_slice(b"main");
                ack_frame.extend_from_slice(&(serialized_ack.len() as u32).to_be_bytes());
                ack_frame.extend_from_slice(&serialized_ack);
                send.write_all(&ack_frame).await.map_err(|error| {
                    format!("failed to write session-token response ACK: {error}")
                })?;
                send.flush().await.map_err(|error| {
                    format!("failed to flush session-token response ACK: {error}")
                })?;
                println!(
                    "[PlutoRTC][session-token-presentation] dialer acknowledged host response connection_id={} endpoint_id={} stream_contract={:?}",
                    connection_id.as_ref(),
                    endpoint_id,
                    stream_contract,
                );
            }
            #[cfg(not(target_arch = "wasm32"))]
            let reciprocal_committed = reciprocal_acceptance.is_some();
            #[cfg(not(target_arch = "wasm32"))]
            if let Some((presentation, reciprocal_scope, was_already_admitted)) =
                reciprocal_acceptance
            {
                let current_transport_stable_id = self
                    .get_connection(endpoint_id)
                    .await
                    .map(|connection| connection.stable_id() as u64);
                if current_transport_stable_id != Some(transport_stable_id) {
                    let _ = send.finish();
                    return Err(format!(
                        "physical transport changed before reciprocal session admission could be bound: response={} current={:?}",
                        transport_stable_id, current_transport_stable_id,
                    ));
                }
                self.run_post_session_token_admission_side_effects(
                    connection_id.as_ref(),
                    !was_already_admitted,
                )
                .await;
                println!(
                    "[PlutoRTC][session-admission][reciprocal-response] connection_id={} endpoint_id={} transport_stable_id={} scope={} claimed_device_id={} result=bound",
                    connection_id.as_ref(),
                    endpoint_id,
                    transport_stable_id,
                    reciprocal_scope,
                    presentation.device_id,
                );
            }
            let scope = response.approved_session_scope().unwrap_or_default();
            println!(
                "[PlutoRTC] Host approved session-token presentation connection_id={} endpoint_id={} scope={}",
                connection_id.as_ref(),
                endpoint_id,
                scope
            );
            if is_endpoint_target && !scope.is_empty() {
                println!(
                    "[PlutoRTC] Session-token presentation approved for connection_id={} scope={}",
                    connection_id.as_ref(),
                    scope
                );
            }
            self.commit_outbound_session_token_application_security_epoch(
                connection_id.as_ref(),
                token,
            );
            #[cfg(not(target_arch = "wasm32"))]
            {
                let current_transport_stable_id = self
                    .get_connection(endpoint_id)
                    .await
                    .map(|connection| connection.stable_id() as u64);
                if current_transport_stable_id != Some(transport_stable_id) {
                    let _ = send.finish();
                    return Err(format!(
                        "physical transport changed before session approval could be bound: approved={} current={:?}",
                        transport_stable_id, current_transport_stable_id,
                    ));
                }
                if let Ok(mut proofs) = self.remote_session_admission_proofs.write() {
                    proofs.insert(
                        connection_id.to_string(),
                        RemoteSessionAdmissionProof {
                            transport_stable_id,
                            token_fingerprint: crate::session_token::token_fingerprint(token),
                            approval_scope: scope.clone(),
                        },
                    );
                }
                if !options.reciprocal_requested || reciprocal_committed {
                    self.clear_reciprocal_session_admission_request(connection_id.as_ref());
                }
                println!(
                    "[PlutoRTC][session-admission][remote-proof] connection_id={} endpoint_id={} transport_stable_id={} token_fp={}",
                    connection_id.as_ref(),
                    endpoint_id,
                    transport_stable_id,
                    super::core_impl::log_fingerprint(token),
                );
                self.bind_outbound_native_admission_stream_contract(
                    connection_id.as_ref(),
                    stream_contract,
                );
                match (send, recv, stream_contract) {
                    (
                        crate::application_crypto_streams::PeerSendStream::Plain(send),
                        crate::application_crypto_streams::PeerRecvStream::Plain(recv),
                        crate::native_protocol::SessionTokenStreamContract::PersistentControl,
                    ) => {
                        self.install_native_control_stream(
                            connection_id.as_ref(),
                            endpoint_id,
                            transport_stable_id,
                            send,
                            recv,
                            "admission-dialer",
                        )
                        .await;
                    }
                    (send, _, _) => {
                        let _ = send.finish();
                    }
                }
                if !application_crypto_active {
                    if let Err(error) = self
                        .send_typescript_capability_update(
                            connection_id.as_ref(),
                            "native-admission-dialer",
                            None,
                        )
                        .await
                    {
                        eprintln!(
                            "[OpenRTC][capability] native admission dialer advertisement failed connection_id={} error={}",
                            connection_id.as_ref(), error,
                        );
                    }
                }
                // A successful response is already a round trip over this
                // exact physical Iroh generation. Consume that stronger proof
                // directly instead of launching a second ping that can race a
                // replacement. Application crypto remains an independent
                // product-routability gate.
                let _ = self
                    .confirm_managed_connection_readiness_from_transport_proof(
                        connection_id.as_ref(),
                        transport_stable_id,
                    )
                    .await;
            }
            #[cfg(target_arch = "wasm32")]
            let _ = send.finish();
            return Ok(scope);
        }

        let _ = send.finish();
        let reason = response
            .session_token_error()
            .unwrap_or_else(|| "session-token-rejected".to_string());
        Err(reason)
    }

    pub async fn present_session_token_to_endpoint(
        &self,
        endpoint_id: iroh::EndpointId,
        token: &str,
    ) -> Result<String, String> {
        self.present_session_token(
            SessionTokenPresentationTarget::Endpoint { endpoint_id },
            token,
            SessionTokenPresentationOptions::default(),
        )
        .await
    }

    pub async fn present_session_token_to_endpoint_with_payload(
        &self,
        endpoint_id: iroh::EndpointId,
        token: &str,
        token_payload: Option<&str>,
    ) -> Result<String, String> {
        self.present_session_token(
            SessionTokenPresentationTarget::Endpoint { endpoint_id },
            token,
            SessionTokenPresentationOptions {
                token_payload,
                device_id: None,
                reciprocal_requested: false,
            },
        )
        .await
    }

    pub async fn present_session_token_to_endpoint_with_payload_and_device_id(
        &self,
        endpoint_id: iroh::EndpointId,
        token: &str,
        token_payload: Option<&str>,
        device_id: Option<&str>,
    ) -> Result<String, String> {
        self.present_session_token(
            SessionTokenPresentationTarget::Endpoint { endpoint_id },
            token,
            SessionTokenPresentationOptions {
                token_payload,
                device_id,
                reciprocal_requested: false,
            },
        )
        .await
    }
}

#[cfg(test)]
mod admission_security_tests {
    use super::{
        incoming_application_admission_decision, outgoing_session_token_stream_contract,
        IncomingApplicationAdmissionDecision,
    };
    use crate::client::Client;
    use crate::native_protocol::SessionTokenStreamContract;
    use crate::session_token::{GrantScope, SessionAdmission, SessionAdmissionMechanism};

    #[test]
    fn rejected_connection_never_forwards_later_application_streams() {
        let decision = incoming_application_admission_decision(
            true,
            &SessionAdmission::Rejected {
                reason: "invalid token".to_string(),
            },
            false,
        );
        assert_eq!(
            decision,
            IncomingApplicationAdmissionDecision::Reject("invalid token".to_string())
        );
    }

    #[test]
    fn active_registry_requires_current_transport_proof() {
        let accepted = SessionAdmission::Accepted {
            mechanism: SessionAdmissionMechanism::SessionToken,
            scope: Some(GrantScope::from("user-device")),
            authoritative_device_id: None,
        };
        assert_eq!(
            incoming_application_admission_decision(true, &accepted, false),
            IncomingApplicationAdmissionDecision::ClassifyAdmission
        );
        assert_eq!(
            incoming_application_admission_decision(true, &accepted, true),
            IncomingApplicationAdmissionDecision::Forward
        );
        assert_eq!(
            incoming_application_admission_decision(false, &SessionAdmission::Pending, false),
            IncomingApplicationAdmissionDecision::Forward
        );
    }

    #[test]
    fn native_route_repair_preserves_declared_persistent_control() {
        assert_eq!(
            outgoing_session_token_stream_contract(false, true, true),
            SessionTokenStreamContract::PersistentControl
        );
        assert_eq!(
            outgoing_session_token_stream_contract(false, true, false),
            SessionTokenStreamContract::OneShotAdmission
        );
        assert_eq!(
            outgoing_session_token_stream_contract(false, false, false),
            SessionTokenStreamContract::PersistentControl
        );
        assert_eq!(
            outgoing_session_token_stream_contract(true, false, true),
            SessionTokenStreamContract::OneShotAdmission
        );
    }

    #[cfg(all(native, unix))]
    #[tokio::test]
    async fn persisted_managed_scope_grant_is_atomically_replaced_and_owner_only() {
        use std::os::unix::fs::PermissionsExt;

        let directory = std::env::temp_dir().join(format!(
            "openrtc-private-grant-{}",
            crate::session_token::generate_payload_nonce()
        ));
        tokio::fs::create_dir_all(&directory)
            .await
            .expect("create test directory");
        let path = directory.join("openrtc_managed_scope_ticket_user-device.json");

        Client::write_private_managed_scope_grant(&path, br#"{"token":"first"}"#)
            .await
            .expect("write first grant");
        Client::write_private_managed_scope_grant(&path, br#"{"token":"second"}"#)
            .await
            .expect("replace grant");

        assert_eq!(
            tokio::fs::read(&path).await.expect("read grant"),
            br#"{"token":"second"}"#
        );
        let mode = tokio::fs::metadata(&path)
            .await
            .expect("stat grant")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o600);

        tokio::fs::remove_dir_all(directory)
            .await
            .expect("remove test directory");
    }
}