summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/transport.js
blob: 809bb830a8cb439a5f584091bc75b9c2884bb226 (plain) (blame)
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
/**
 * MeshBay Browser Transport — WebRTC DataChannel client.
 *
 * Connects to a MeshBay node via WebRTC DataChannel (P2P, E2E).
 * The hub is only used for signaling (SDP/ICE relay) — after connection,
 * all data flows directly between browser and node.
 *
 * Wire format: length-prefixed msgpack (4-byte big-endian + msgpack payload).
 * Same format as QUIC and TCP+TLS transports on the node side.
 *
 * Usage:
 *   const transport = new MeshBayTransport(hubUrl, accessToken);
 *   await transport.connect(nodeId, jwtToken, groupId);
 *   const index = await transport.fetchIndex();
 *   const chunk = await transport.fetchChunk(fileId, 0);
 *   transport.close();
 */

async function _pkFromSk(skPkcs8B64) {
  const raw = Uint8Array.from(atob(skPkcs8B64), c => c.charCodeAt(0));
  const sk = await crypto.subtle.importKey('pkcs8', raw, { name: 'X25519' }, true, ['deriveBits']);
  const jwk = await crypto.subtle.exportKey('jwk', sk);
  const b64url = jwk.x;
  const b64 = b64url.replace(/-/g, '+').replace(/_/g, '/');
  const pad = b64.length % 4;
  return pad ? b64 + '='.repeat(4 - pad) : b64;
}

async function _pkEdFromSk(skPkcs8B64) {
  const raw = Uint8Array.from(atob(skPkcs8B64), c => c.charCodeAt(0));
  const sk = await crypto.subtle.importKey('pkcs8', raw, { name: 'Ed25519' }, true, ['sign']);
  const jwk = await crypto.subtle.exportKey('jwk', sk);
  const b64 = jwk.x.replace(/-/g, '+').replace(/_/g, '/');
  const pad = b64.length % 4;
  return pad ? b64 + '='.repeat(4 - pad) : b64;
}

// 48 KB is what fits comfortably in one SCTP message across stacks; the window is
// what makes the rate independent of the round trip. 32 × 48 KB = 1.5 MB in
// flight, which saturates any path up to roughly 100 Mb/s at 100 ms.
const UPLOAD_CHUNK_SIZE = 48 * 1024;
const UPLOAD_WINDOW = 32;
const UPLOAD_BUFFER_HIGH = 1024 * 1024;

// Segments of 256 KB: 24 in flight is 6 MB, enough to keep playback fed over a
// slow link and small enough that nothing accumulates.
// How long to collect ICE candidates before sending the offer anyway. Long
// enough for a STUN round trip on a slow link, short enough that a STUN server
// that never answers costs a pause rather than the whole attempt.
const ICE_GATHER_TIMEOUT_MS = 4000;

const STREAM_CREDITS = 24;

function _aborted() {
  const err = new Error('Cancelled');
  err.name = 'AbortError';
  return err;
}

// Every request type that goes through the two-step admin_challenge /
// admin_response flow (_authorizeAdminOp below) — one entry per
// `_authorizeAdminOp(msg, expectedOp, ...)` call site. Found live: enabling
// the Music app and then saving its root folder in the same Settings visit
// (the new merged Directories section makes this a natural, fast
// back-to-back sequence) fired two of these within milliseconds of each
// other. Both admin_challenge replies, and both domain acks afterward,
// were routed by nothing more than "whichever request happens to be
// oldest pending" — apps_enabled's challenge stole audio_root's slot, then
// audio_root's own request just sat there until its 30s timeout, having
// never received a challenge to answer at all. Keying both hops by op name
// (below, in _key and in _dispatch) fixes this without needing the node to
// change anything — `op` is already on every admin_challenge, and this
// list is what lets a response two steps later be tied back to the right
// one.
const ADMIN_OP_TYPES = new Set([
  'tmdb_override', 'tmdb_rematch', 'tmdb_config', 'tmdb_enabled', 'video_root', 'audio_root',
  'photo_roots',
  'musicbrainz_enabled', 'file_delete', 'dir_delete',
  'member_upload', 'apps_enabled', 'set_scan_settings', 'member_revoke',
  'root_add', 'root_remove', 'member_unpin', 'gek_rotate', 'group_attach',
  'group_detach', 'invite_create',
]);

// ── Diagnostic trace (opt-in, off by default) ───────────────────────────────
// Ring buffer of transport health events (connection/ICE/DataChannel state
// transitions, request timeouts, visibility changes, periodic health pings),
// persisted to localStorage so a connection that gets stuck can be inspected
// after the fact — the field case this exists for is a phone with no
// devtools attached. Added while chasing a report of the transport going
// unresponsive after a mobile screen lock of several minutes; kept in the
// tree afterward rather than ripped out, since the next hard-to-reproduce
// connection bug will want the same thing and it costs nothing while off.
//
// Enable once by opening the app with ?trace=1 in the URL — this persists in
// localStorage, so every later visit stays in trace mode until ?trace=0
// clears it. Read the log back at any time by navigating to #mb-debug (e.g.
// https://meshbay.org/app/#mb-debug), which replaces the page with a plain
// text dump — no devtools required.
const TRACE_KEY = 'mb_trace';
const TRACE_LOG_KEY = 'mb_trace_log';
const TRACE_MAX = 500;
// How often to probe the channel with a ping while trace mode is on — purely
// diagnostic (to see when a health check starts failing), not a keepalive:
// must stay opt-in, never run by default.
const TRACE_PING_INTERVAL_MS = 25000;

(function _initTraceFlag() {
  try {
    const params = new URLSearchParams(location.search);
    if (params.has('trace')) {
      if (params.get('trace') === '0') localStorage.removeItem(TRACE_KEY);
      else localStorage.setItem(TRACE_KEY, '1');
    }
  } catch { /* localStorage unavailable (private mode, etc.) — trace stays off */ }
})();

function traceEnabled() {
  try { return localStorage.getItem(TRACE_KEY) === '1'; } catch { return false; }
}

function trace(event, data) {
  if (!traceEnabled()) return;
  try {
    const buf = JSON.parse(localStorage.getItem(TRACE_LOG_KEY) || '[]');
    buf.push({ t: new Date().toISOString(), event, ...data });
    while (buf.length > TRACE_MAX) buf.shift();
    localStorage.setItem(TRACE_LOG_KEY, JSON.stringify(buf));
  } catch { /* storage full or unavailable — tracing is best-effort */ }
}

window.MeshBayTrace = {
  enabled: traceEnabled,
  dump() {
    try { return JSON.parse(localStorage.getItem(TRACE_LOG_KEY) || '[]'); } catch { return []; }
  },
  clear() { try { localStorage.removeItem(TRACE_LOG_KEY); } catch { /* ignore */ } },
};

// STUN, two providers deep. On the desktop client the hostnames are resolved in
// the main process (Node's resolver) and handed back as IPs: Chromium's P2P
// socket manager fails every STUN hostname with ERR_NAME_NOT_RESOLVED in some
// restricted-resolver environments (a libvirt/KVM guest was where this surfaced)
// even though every other resolver on the box works. In a browser there is no
// `meshbay` bridge and the hostnames are used directly — a browser resolves them
// fine. Resolved once per run; a provider changing IPs is picked up on restart.
const STUN_URLS = [
  'stun:stun.l.google.com:19302',
  'stun:stun1.l.google.com:19302',
  'stun:stun.cloudflare.com:3478',
  'stun:stun.services.mozilla.com:3478',
];
let _iceServersPromise = null;
function iceServers() {
  if (!_iceServersPromise) {
    _iceServersPromise = (async () => {
      let urls = STUN_URLS;
      if (window.meshbay && typeof window.meshbay.resolveStun === 'function') {
        try {
          const r = await window.meshbay.resolveStun(STUN_URLS);
          if (Array.isArray(r) && r.length) urls = r;
        } catch { /* keep the hostname form */ }
      }
      return urls.map((u) => ({ urls: u }));
    })();
  }
  return _iceServersPromise;
}

function _showTraceView() {
  {
    const renderTraceView = () => {
      const log = window.MeshBayTrace.dump();
      const text = JSON.stringify(log, null, 2);
      document.body.innerHTML = '';
      document.title = 'MeshBay — Diagnostic';
      const bar = document.createElement('div');
      bar.style.cssText = 'font-family:monospace;padding:8px;';
      const copyBtn = document.createElement('button');
      copyBtn.textContent = 'Copier';
      copyBtn.onclick = () => { navigator.clipboard.writeText(text).catch(() => {}); };
      const clearBtn = document.createElement('button');
      clearBtn.textContent = 'Vider';
      clearBtn.onclick = () => { window.MeshBayTrace.clear(); renderTraceView(); };
      const refreshBtn = document.createElement('button');
      refreshBtn.textContent = 'Rafraîchir';
      refreshBtn.onclick = renderTraceView;
      const info = document.createElement('span');
      info.textContent = ` — ${log.length} évènement(s) — trace ${traceEnabled() ? 'active' : 'inactive'}`;
      info.style.marginLeft = '8px';
      bar.append(copyBtn, clearBtn, refreshBtn, info);
      const pre = document.createElement('pre');
      pre.style.cssText = 'font-family:monospace;font-size:11px;white-space:pre-wrap;'
        + 'word-break:break-all;padding:8px;';
      pre.textContent = text;
      document.body.append(bar, pre);
    };
    renderTraceView();
  }
}

// Fragment-only URL changes (typing #mb-debug into an already-loaded page,
// or a link to it) do not reload the document, so DOMContentLoaded alone
// would miss them — hashchange is what a same-document navigation fires.
if (location.hash === '#mb-debug') {
  document.addEventListener('DOMContentLoaded', _showTraceView);
}
window.addEventListener('hashchange', () => {
  if (location.hash === '#mb-debug') _showTraceView();
});

// This build's half of the version range (meshbay_common/handshake.py's
// MNP_VERSION and MNP_MIN_SUPPORTED). Declared on the handshake — the only
// message where it is read — so a node we cannot speak to refuses us with a
// code, instead of the mismatch surfacing as a field that is not there.
//
// The `v: '0.1'` on every other message in this file is the historical value
// and is read by nothing; it is left alone deliberately. The range is
// negotiated once, at the start, not restated per message.
const MNP_V = '1.0';
const MNP_V_MIN = '1.0';

// Codes a NODE sends us, in its own vocabulary (meshbay_common/handshake.py's
// check_version): `version_too_old` means *we* are too old for it,
// `version_too_new` that it is too old for what we require. The client's own
// check of the node names its two conditions separately — see
// _checkNodeVersion, where reusing this table's wording would read backwards.
const HANDSHAKE_REFUSALS = {
  version_too_old: 'This page is older than the node it is talking to. '
    + 'Reload to pick up the current version.',
  version_too_new: 'This node is running an older MeshBay than this page needs. '
    + 'Its operator has to update it.',
  version_unreadable: 'The node could not read this page\'s protocol version.',
};

const JOIN_REFUSALS = {
  code_required: 'This node does not know this browser yet. Ask the node operator '
    + 'for a pairing code (meshbay-node operator pair).',
  code_invalid: 'That pairing code is not valid — it may be mistyped, expired, '
    + 'already used, or issued for a different account.',
  key_changed: 'This account is already paired with a different key on this node. '
    + 'If you reset your keys, the operator must unpin you before pairing again.',
  not_authorized_for_group: 'The node does not list you as a member of this group. '
    + 'Being a member on the hub is not enough — ask the operator for an invite.',
  no_gek: 'This group has no key yet. The node operator must run '
    + '`meshbay-node gek-init` for it.',
  signature_invalid: 'The node rejected the signature over your keys.',
  stale_request: 'Your clock is too far from the node\'s — check the system time.',
  group_mismatch: 'The node refused a request naming a different group.',
};

class MeshBayTransport {
  constructor(hubUrl, accessToken) {
    this._hubUrl = hubUrl;
    this._accessToken = accessToken;
    this._pc = null;
    this._channel = null;
    this._pending = new Map();
    this._seqId = 0;
    this._recvBuf = new Uint8Array(0);
    this._connected = false;
    this._onChat = null;
    this._onStreamInit = null;
    this._onStreamData = null;
    this._onStreamEnd = null;
    this._onStreamError = null;
    this._onIndexSync = null;
    // filename → the uploader waiting on it. Keyed rather than FIFO because
    // several uploads may be in flight at once and their acks interleave; the
    // node names the file in every one.
    this._uploaders = new Map();
    // Set once close() runs — stops the automatic reconnect from firing on a
    // connection the caller tore down on purpose (leaving the group, page
    // unload), which would otherwise race back in right as everything else
    // is being torn down.
    this._closed = false;
    // The arguments connect() was last given, minus the token (refreshed at
    // reconnect time — see onNeedToken) and sessionKeys (kept live on `this`,
    // since a reconnect must reuse the identity connect() settled on, not
    // whatever the very first caller passed in — see _reconnectLoop).
    this._connectArgs = null;
    this._lastToken = null;
    this._reconnectPromise = null;
    this._reconnectAttempts = 0;
    // True only for the duration of the connect() call _reconnectLoop makes
    // to actually retry — as opposed to the backoff delay around it, which
    // is most of _reconnectPromise's lifetime. Needed because that connect()
    // call sends its own handshake through _sendAndWait, which would
    // otherwise see the very _reconnectPromise it is running inside of as
    // "a reconnect to wait for" and stall every handshake step for the full
    // 6s gate below before ever sending it.
    this._inReconnectAttempt = false;
    this._onReconnected = null;
    this._onNeedToken = null;
    // Cuts the backoff wait short the moment the page is foregrounded again —
    // found live to matter: a screen lock throttles the tab's own timers
    // along with everything else, so a backoff already counting down when the
    // phone locked can run for minutes of *wall clock* past its nominal delay
    // before it next gets to run at all. Set once, here, rather than inside
    // connect() like the diagnostic listener above it — this one has to
    // survive every reconnect attempt, not restart with each one.
    this._reconnectWakeResolve = null;
    this._onVisibilityWake = () => {
      if (document.visibilityState === 'visible') this._wakeReconnect();
    };
    document.addEventListener('visibilitychange', this._onVisibilityWake);
  }

  /** Cuts short a reconnect currently backing off (see _reconnectLoop). A
   * no-op when nothing is waiting, so this is safe to call unconditionally. */
  _wakeReconnect() {
    if (this._reconnectWakeResolve) {
      this._reconnectWakeResolve();
      this._reconnectWakeResolve = null;
    }
  }

  get connected() { return this._connected; }

  set onChat(fn) { this._onChat = fn; }
  set onStreamInit(fn) { this._onStreamInit = fn; }
  set onStreamData(fn) { this._onStreamData = fn; }
  set onStreamEnd(fn) { this._onStreamEnd = fn; }
  set onStreamError(fn) { this._onStreamError = fn; }
  set onIndexSync(fn) { this._onIndexSync = fn; }
  set onIndexDelta(fn) { this._onIndexDelta = fn; }
  set onUploadPolicy(fn) { this._onUploadPolicy = fn; }
  set onAppsEnabled(fn) { this._onAppsEnabled = fn; }
  set onTmdbConfig(fn) { this._onTmdbConfig = fn; }
  set onTmdbEnabled(fn) { this._onTmdbEnabled = fn; }
  set onVideoRoot(fn) { this._onVideoRoot = fn; }
  set onAudioRoot(fn) { this._onAudioRoot = fn; }
  set onPhotoRoots(fn) { this._onPhotoRoots = fn; }
  set onMusicbrainzEnabled(fn) { this._onMusicbrainzEnabled = fn; }
  set onIndexProgress(fn) { this._onIndexProgress = fn; }
  // Fired when a message that must open under the group key does not —
  // see _failSession. The session is over by the time this runs.
  set onSessionFailed(fn) { this._onSessionFailed = fn; }
  // Fired once an automatic reconnect (see _reconnectLoop) lands a fresh
  // handshake, so a consumer with something mid-flight on the old channel —
  // today only the video player — can pick back up rather than sit dead.
  set onReconnected(fn) { this._onReconnected = fn; }
  // Reconnecting redoes the handshake, which needs a JWT that may have gone
  // stale while the connection was down for minutes. Without this the
  // reconnect resends whatever token the original connect() call captured,
  // which the node's clock-skew check (stale_request) or plain expiry can
  // by then have already invalidated. Set to whatever the caller uses to
  // refresh the hub session token (see group-page.js's ensureFreshToken).
  set onNeedToken(fn) { this._onNeedToken = fn; }

  get sessionKeys() { return this._sessionKeys; }

  /** Set on a first join: the identity created for this node, still to be left with it. */
  get newNodeBundle() { return this._newNodeBundle || null; }
  set newNodeBundle(v) { this._newNodeBundle = v; }

  /** The recovery-wrapped copy of that same first-join identity, when a recovery key was in hand. */
  get newNodeBundleRecovery() { return this._newNodeBundleRecovery || null; }
  set newNodeBundleRecovery(v) { this._newNodeBundleRecovery = v; }

  async connect(nodeId, jwtToken, groupId, gekRaw, sessionKeys, bundleKey, username,
                userId, joinCode, recoveryKey) {
    // Remembered for _reconnectLoop, which calls connect() again with these
    // same values (plus a freshly-fetched token and the identity connect()
    // itself settles on below) after the WebRTC connection is declared
    // "failed" — see the pc.onconnectionstatechange handler further down.
    this._connectArgs = {
      nodeId, groupId, gekRaw, bundleKey, username, userId, joinCode, recoveryKey,
    };
    this._lastToken = jwtToken;
    // The constructor sets this once from whatever token the caller had at
    // the time — and the signaling POST below reads *this*, not `jwtToken`.
    // A reconnect passes a freshly-fetched `jwtToken` (see onNeedToken) but
    // that never reached here before, so the signaling call kept using the
    // original token no matter how many minutes had passed or how many
    // reconnect attempts fetched a new one — confirmed live: every attempt
    // failed "Signaling failed: 401 Invalid or expired token" in a loop,
    // never actually trying the fresh token connect() had just been handed.
    this._accessToken = jwtToken;
    this._gekRaw = gekRaw || null;
    this._sessionKeys = sessionKeys || null;
    this._bundleKey = bundleKey || null;
    this._recoveryKey = recoveryKey || null;
    this._username = username || null;
    this._userId = userId || null;
    this._newNodeBundle = null;
    this._newNodeBundleRecovery = null;
    this._joinError = null;
    this._pc = new RTCPeerConnection({ iceServers: await iceServers() });

    this._channel = this._pc.createDataChannel('mnp', { ordered: true });
    this._channel.binaryType = 'arraybuffer';

    let channelReject = null;
    const channelReady = new Promise((resolve, reject) => {
      channelReject = reject;
      const timeout = setTimeout(() => reject(new Error('DataChannel open timeout')), 30000);
      this._channel.onopen = () => {
        clearTimeout(timeout);
        this._connected = true;
        trace('channel_open', {});
        resolve();
      };
    });

    this._channel.onmessage = (event) => this._onMessage(event.data);
    this._channel.onclose = (ev) => {
      console.warn('[MeshBay] DataChannel closed', this._channel?.readyState, ev);
      trace('channel_close', {
        readyState: this._channel?.readyState,
        pc: this._pc?.connectionState,
        ice: this._pc?.iceConnectionState,
      });
      this._connected = false;
      if (channelReject) channelReject(new Error('DataChannel closed'));
      for (const [, p] of this._pending) p.reject(new Error('DataChannel closed'));
      this._pending.clear();
    };
    this._channel.onerror = (ev) => {
      console.error('[MeshBay] DataChannel error', ev);
      trace('channel_error', {
        pc: this._pc?.connectionState,
        ice: this._pc?.iceConnectionState,
      });
      if (channelReject) channelReject(new Error('DataChannel error'));
    };

    // Captured locally rather than read back through `this._pc`: once a
    // reconnect replaces it, a late event from this (by then orphaned) pc
    // must still be judged against the pc it actually came from, not
    // whatever is current — the `pc === this._pc` check below is what that
    // buys.
    const pc = this._pc;
    pc.onconnectionstatechange = () => {
      console.log('[MeshBay] PC state:', pc.connectionState);
      trace('pc_state', { state: pc.connectionState });
      // "failed" is ICE's own verdict that nothing here will recover on its
      // own (unlike a transient "disconnected", which often clears itself) —
      // confirmed live: mobile screen lock for several minutes reliably
      // produces disconnected → failed about 10s apart, on both ends, and
      // nothing today ever moves past that without a full page reload.
      // `channel.readyState` is no help distinguishing this: it was observed
      // staying "open" throughout, so every send from here on would simply
      // sit out its own timeout instead of failing fast.
      if (pc.connectionState === 'failed' && pc === this._pc && !this._closed) {
        this._connected = false;
        this._reconnect();
        const err = new Error('WebRTC connection lost');
        err.name = 'TransportLostError';
        for (const [, p] of this._pending) p.reject(err);
        this._pending.clear();
      }
    };
    pc.oniceconnectionstatechange = () => {
      console.log('[MeshBay] ICE state:', pc.iceConnectionState);
      trace('ice_state', { state: pc.iceConnectionState });
    };

    // Diagnostic-only: a periodic health ping and a resume-triggered one, so
    // a trace captures exactly what state the connection was in right as the
    // page comes back from being backgrounded/locked — never active unless
    // trace mode is on (see TRACE_KEY above).
    //
    // connect() runs again on every reconnect attempt (see _reconnectLoop),
    // and each run used to add its own listener/interval on top of the
    // previous one without ever removing it — confirmed live: 8 failed
    // attempts during one screen lock left 8 duplicate `visibility` trace
    // lines firing off the same real event. Disposing of the prior instance
    // first is what keeps this to one.
    if (this._diagCleanup) { this._diagCleanup(); this._diagCleanup = null; }
    if (traceEnabled()) {
      const healthPing = async (reason) => {
        const before = {
          pc: this._pc?.connectionState,
          ice: this._pc?.iceConnectionState,
          channel: this._channel?.readyState,
        };
        const start = Date.now();
        try {
          await this.ping(8000);
          trace('health_ping', { reason, ok: true, rtt_ms: Date.now() - start, ...before });
        } catch (e) {
          trace('health_ping', { reason, ok: false, error: String(e && e.message || e),
                                  elapsed_ms: Date.now() - start, ...before });
        }
      };
      const onVisibility = () => {
        trace('visibility', {
          state: document.visibilityState,
          pc: this._pc?.connectionState,
          ice: this._pc?.iceConnectionState,
          channel: this._channel?.readyState,
        });
        if (document.visibilityState === 'visible' && this._channel?.readyState === 'open') {
          healthPing('resume');
        }
      };
      document.addEventListener('visibilitychange', onVisibility);
      const healthInterval = setInterval(() => {
        if (this._channel?.readyState === 'open') healthPing('interval');
      }, TRACE_PING_INTERVAL_MS);
      this._diagCleanup = () => {
        document.removeEventListener('visibilitychange', onVisibility);
        clearInterval(healthInterval);
      };
    }

    const offer = await this._pc.createOffer();
    await this._pc.setLocalDescription(offer);

    // Wait for candidates, but not indefinitely.
    //
    // This is non-trickle signaling: the offer carries its candidates, so the
    // SDP is only sent once gathering is done. When gathering *never* finishes
    // — a STUN server that is slow, filtered, or being resolved through a DNS
    // that is not answering — this promise never settles, and joining a group
    // hangs with no error and nothing on screen. Reported after exactly that,
    // and it succeeded on a later attempt, which is the shape of a network
    // wait rather than a refusal.
    //
    // Past the deadline the offer goes out with whatever has been gathered.
    // Host candidates are already there, which is enough on a LAN — the case
    // this project cares most about — and the reflexive ones normally arrive
    // in well under a second when STUN is reachable at all. A partial offer
    // that usually connects beats a promise that never returns.
    await new Promise((resolve) => {
      if (this._pc.iceGatheringState === 'complete') return resolve();
      const done = () => { clearTimeout(timer); resolve(); };
      const timer = setTimeout(() => {
        console.warn('[MeshBay] ICE gathering did not finish in',
                     ICE_GATHER_TIMEOUT_MS, 'ms — offering what we have');
        done();
      }, ICE_GATHER_TIMEOUT_MS);
      this._pc.onicegatheringstatechange = () => {
        if (this._pc.iceGatheringState === 'complete') done();
      };
    });

    // Signaling is a hub call like any other, so it goes the same way — in the
    // application that means through the main process, because the renderer's
    // app:// origin is refused by CORS.
    const call = (window.MeshBayPlatform && window.MeshBayPlatform.apiFetch)
      || fetch;
    const resp = await call(
      `${this._hubUrl}/v1/nodes/${nodeId}/webrtc/offer`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this._accessToken}`,
      },
      body: JSON.stringify({
        sdp: this._pc.localDescription.sdp,
        ice_candidates: [],
      }),
    });

    if (!resp.ok) {
      const detail = await resp.json().catch(() => ({}));
      throw new Error(`Signaling failed: ${resp.status} ${detail.detail || ''}`);
    }

    const answer = await resp.json();
    this._rawAnswerSdp = answer.sdp;
    await this._pc.setRemoteDescription({ type: 'answer', sdp: answer.sdp });

    await channelReady;
    console.log('[MeshBay] DataChannel open, sending handshake for group', groupId,
                'channel=', this._channel?.readyState,
                'crypto=', !!window.MeshBayCrypto);

    // The client nonce is what makes the NODE's proof fresh (C3) — without it a
    // recorded handshake_ack could be replayed by an impersonating peer.
    this._nonceClient = crypto.getRandomValues(new Uint8Array(32));

    const reply = await this._sendAndWait({
      type: 'handshake',
      v: MNP_V,
      v_min: MNP_V_MIN,
      token: jwtToken,
      group_id: groupId || '',
      nonce: window.MeshBayCrypto.b64encode(this._nonceClient),
    });
    console.log('[MeshBay] Handshake reply:', reply.type);

    if (reply.type === 'handshake_challenge') {
      // The node's half of the range. Checked before anything else in this
      // block, because everything below — the join, the proof, the sealed ack
      // — assumes both sides mean the same thing by each message.
      _checkNodeVersion(reply);
      if (!window.MeshBayCrypto) {
        throw new Error('Node requires GEK proof but no crypto available');
      }

      // Recorded the moment the challenge arrives, because everything below may
      // need them — joining, in particular, happens before the proof and signs a
      // transcript over both. Reading them further down, next to the proof that
      // also uses them, meant join_request ran with neither.
      //
      // nonce_node ties a join to this connection, so one cannot be lifted onto
      // another. node_pk is announced here because a first-time member has no
      // GEK and so cannot complete the handshake that would prove it; it is
      // unverified at this point and checked against the ack below.
      this._nonceNode = window.MeshBayCrypto.b64decode(reply.nonce);
      this.nodePk = reply.node_pk || null;

      // Our identity for THIS node: fetched from it, or created if this is a
      // first join. Keys are per node, so there is nothing to carry between
      // them — and an operator who cracks the copy on their own disk gets a key
      // that opens nothing anywhere else.
      let fresh = false;
      if (!this._sessionKeys && this._bundleKey && window.MeshBayKeys) {
        const kpResp = await this._sendAndWait({
          type: 'keypair_bundle_fetch', v: '0.1',
        });
        let keys = null;
        let openErr = null;
        if (kpResp.type === 'keypair_bundle_resp' && kpResp.found) {
          try {
            keys = await window.MeshBayKeys.decryptBundleWithKey(
              kpResp.bundle_enc, this._bundleKey);
          } catch (e) {
            openErr = e;
            // The passphrase key did not open the bundle. If we hold a recovery
            // key and the node kept a recovery copy, try that — Flow B
            // (docs/auth-confirm.md §4.5): recovering an identity after a lost
            // passphrase, before re-wrapping it under the new one.
            if (this._recoveryKey && kpResp.bundle_enc_recovery) {
              try {
                keys = await window.MeshBayKeys.decryptBundleWithKey(
                  kpResp.bundle_enc_recovery, this._recoveryKey);
                this._recoveredFromRecovery = true;
              } catch { /* recovery copy did not open either */ }
            }
          }
        }

        if (!keys && this._rewrapOnly) {
          // A passphrase-change / backfill run must recover the *existing*
          // identity or report the node — never mint a new one. These strings
          // are shown on the reset / backfill screens.
          throw new Error(
            !kpResp.found ? 'no identity on this node'
              : this._recoveryKey
                ? (kpResp.bundle_enc_recovery
                    ? "recovery key does not open this node's bundle"
                    : 'no recovery copy on this node')
                : (openErr && openErr.message) || 'could not open the stored identity');
        }

        if (keys) {
          const pkXB64 = await _pkFromSk(keys.skX);
          this._sessionKeys = { skXB64: keys.skX, skEdB64: keys.skEd, pkXB64 };
        } else {
          // Either the node has never seen us, or it holds a stale bundle we
          // cannot open (wrapped under a passphrase we no longer use, with no
          // usable recovery copy — e.g. an unpin that left the old bundle
          // behind). Mint a fresh identity and let the join path take over; a
          // successful join overwrites whatever was stored. A recovery-wrapped
          // copy is left too when a recovery key is in hand (§4.3).
          const id = await window.MeshBayKeys.generateNodeIdentity(
            this._bundleKey, this._recoveryKey);
          this._sessionKeys = {
            skEdB64: id.skEdB64, skXB64: id.skXB64, pkXB64: id.pkXB64,
          };
          this._newNodeBundle = id.bundleEnc;
          this._newNodeBundleRecovery = id.bundleEncRecovery || null;
          fresh = true;
        }
      }

      // An identity this node already knows still needs its group key, which the
      // node wraps on every connection.
      if (!gekRaw && this._sessionKeys && !fresh) {
        const bundleResp = await this._sendAndWait({
          type: 'gek_bundle_fetch', v: '0.1',
        });
        if (bundleResp.type === 'gek_bundle_resp' && bundleResp.found) {
          const skXRaw = Uint8Array.from(atob(this._sessionKeys.skXB64), c => c.charCodeAt(0));
          const myPkX = Uint8Array.from(atob(this._sessionKeys.pkXB64), c => c.charCodeAt(0));
          try {
            gekRaw = await window.MeshBayCrypto.unwrapGEK(bundleResp, skXRaw, myPkX);
            this._gekRaw = gekRaw;
          } catch (e) {
            console.warn('[MeshBay] stored GEK bundle did not open; joining instead');
          }
        }
      }

      // No stored bundle: ask the node to recognise us and wrap the key itself.
      // This is the normal path for anyone who joined after the invite redesign —
      // no bundle is pre-stored for members any more. A code is needed only the
      // first time this node sees this account.
      if (!gekRaw && this._sessionKeys && userId) {
        try {
          gekRaw = await this.joinGroup(userId, groupId, joinCode);
        } catch (e) {
          // The UI turns this into "ask the operator for an invite code".
          this._joinError = e;
        }
      }

      if (!gekRaw && !this._sessionKeys) {
        // No key in this browser to sign or unwrap with — `bundleKey` was null.
        // The caller (group-page.js) shows a passphrase prompt on this reason
        // and retries; a code prompt would be useless, since a code proves who
        // you are and there is no key to bind it to.
        const err = new Error('Your passphrase is needed to unlock your keys in this browser.');
        err.reason = 'no_keys';
        throw err;
      }

      if (!gekRaw) {
        throw this._joinError
          || new Error('Node requires GEK proof but no GEK available');
      }

      const C = window.MeshBayCrypto;
      // Node's answer SDP carries ITS fingerprint; our offer carries ours. Throws
      // if either is missing rather than proceeding with an unbound proof (L4).
      const binding = C.webrtcBinding(
        _extractDtlsFingerprint(this._pc.localDescription.sdp),
        _extractDtlsFingerprint(this._rawAnswerSdp),
      );
      const nonceNode = this._nonceNode;   // captured when the challenge arrived
      const gid = groupId || '';

      const proof = await C.handshakeProof(
        gekRaw, 'client', gid, this._nonceClient, nonceNode, binding);

      const ack = await this._sendAndWait({
        type: 'handshake_response',
        v: '0.1',
        proof: C.b64encode(proof),
      });
      if (ack.type !== 'handshake_ack') {
        throw new Error('GEK proof rejected: ' + (ack.detail || JSON.stringify(ack)));
      }

      // Authenticate the NODE before trusting anything it says (C3). Until this
      // ran, node_pk was decorative: a peer that had hijacked signaling could
      // accept our proof, ignore it, and serve a forged index, chat history and
      // is_node_admin flag.
      const expected = await C.handshakeProof(
        gekRaw, 'node', gid, this._nonceClient, nonceNode, binding);
      if (!ack.proof || !C.constantTimeEqual(C.b64decode(ack.proof), expected)) {
        throw new Error('Node failed to prove GEK possession — refusing connection');
      }
      const transcript = C.handshakeTranscript(
        'node', gid, this._nonceClient, nonceNode, binding);
      if (!ack.node_pk || !ack.sig
          || !await C.verifyNodeSignature(ack.node_pk, ack.sig, transcript)) {
        throw new Error('Node signature invalid — refusing connection');
      }
      // Trust On First Use (11.5.8). With C6 closed, a substituted node already
      // fails the GEK proof — this covers the case where an attacker HAS the GEK
      // (an ex-member, or a leaked key) and swaps the node underneath.
      // Strict refusal: a warning users can click through is decorative.
      // The key announced in the challenge must be the one that just proved
      // itself. A peer that changed identity mid-handshake is not one to trust
      // with anything, including a join we may already have signed for it.
      if (this.nodePk && this.nodePk !== ack.node_pk) {
        throw new Error('Node identity changed during the handshake — refusing');
      }
      _checkNodePin(nodeId, ack.node_pk);
      this.nodePk = ack.node_pk;

      // Verify, then decrypt — in that order, and the order is the point. Every
      // check above decides whether this peer is worth trusting at all; opening
      // the payload first would mean acting on data from a peer we have not yet
      // authenticated.
      //
      // A payload that does not open aborts the connection. It is emphatically
      // not an empty config: `enabled_apps` missing reads as "the operator
      // disabled every app" (the documented client-side fallback is the
      // opposite — show them all), and either reading is indistinguishable from
      // a legitimate state, which is what makes a silent fallback worse than a
      // stop.
      let config;
      try {
        config = msgpack_decode(
          await C.openGroup(gekRaw, 'ack', 'handshake_ack', gid, ack));
      } catch (e) {
        throw new Error(
          'handshake_ack did not open under the group key — refusing connection: '
          + (e && e.message || e));
      }
      delete ack.nonce;
      delete ack.ct;
      Object.assign(ack, config);

      return ack;
    }

    // A node that answers a handshake with anything other than a challenge is not
    // running the mutual protocol. Accepting a bare handshake_ack here would let a
    // peer skip proving GEK possession entirely (C3/C6).
    console.warn('[MeshBay] Handshake rejected:', reply.detail, 'code:', reply.code);
    const rejected = new Error(
      HANDSHAKE_REFUSALS[reply.code]
      || ('MNP handshake rejected: ' + (reply.detail || `unexpected ${reply.type}`)));
    rejected.reason = reply.code || '';
    throw rejected;
  }

  /**
   * Kick off (or join, if one is already running) the automatic reconnect
   * after the WebRTC connection is declared unrecoverable. Idempotent: every
   * caller racing to reconnect at once — the connectionstatechange handler,
   * and any request that lands in the gap _sendAndWait waits out below —
   * shares the one attempt instead of piling up parallel handshakes against
   * the node.
   */
  _reconnect() {
    if (this._closed) return Promise.resolve();
    if (!this._reconnectPromise) {
      this._reconnectPromise = this._reconnectLoop().finally(() => {
        this._reconnectPromise = null;
      });
    }
    return this._reconnectPromise;
  }

  /**
   * Redo the signaling handshake from scratch — the only thing that works
   * once aiortc has declared a connection "failed": the node discards that
   * session the moment it sees the same state (webrtc_server.py's
   * on_state_change), so there is no lower-level session left to resume, only
   * a fresh one to negotiate. Retries with capped exponential backoff
   * (1s, 2s, 4s ... 30s) rather than a fixed number of attempts, because the
   * two real causes seen so far — a mobile carrier dropping the NAT mapping
   * during screen lock, and the node's own machine being briefly unreachable
   * — both resolve on their own eventually, and there is no good moment to
   * decide the user would rather see a dead app than keep waiting.
   */
  async _reconnectLoop() {
    this._reconnectAttempts = 0;
    while (!this._closed) {
      this._reconnectAttempts += 1;
      const delayMs = Math.min(30000, 1000 * 2 ** (this._reconnectAttempts - 1));
      trace('reconnect_wait', { attempt: this._reconnectAttempts, delay_ms: delayMs });
      // Interruptible: _wakeReconnect (fired on visibilitychange → visible)
      // resolves this immediately instead of waiting out the rest of a
      // backoff that was mostly spent while nothing could succeed anyway.
      await new Promise((resolve) => {
        const timer = setTimeout(resolve, delayMs);
        this._reconnectWakeResolve = () => { clearTimeout(timer); resolve(); };
      });
      this._reconnectWakeResolve = null;
      if (this._closed) return;
      try {
        // Best-effort: these are already unusable, but leaving them wired up
        // risks a stray late event from the old pc doing something once a
        // new one is in `this._pc` — the `pc === this._pc` guard above closes
        // most of that gap, this closes the rest.
        try { this._channel && this._channel.close(); } catch { /* already gone */ }
        try { this._pc && this._pc.close(); } catch { /* already gone */ }
        const args = this._connectArgs;
        const token = this._onNeedToken ? await this._onNeedToken() : this._lastToken;
        trace('reconnect_attempt', { attempt: this._reconnectAttempts });
        this._inReconnectAttempt = true;
        try {
          await this.connect(args.nodeId, token, args.groupId, args.gekRaw,
                              this._sessionKeys, args.bundleKey, args.username,
                              args.userId, args.joinCode);
        } finally {
          this._inReconnectAttempt = false;
        }
        trace('reconnect_ok', { attempt: this._reconnectAttempts });
        console.log('[MeshBay] Reconnected after', this._reconnectAttempts, 'attempt(s)');
        if (this._onReconnected) {
          try { this._onReconnected(); } catch (e) {
            console.error('[MeshBay] onReconnected handler threw:', e);
          }
        }
        return;
      } catch (e) {
        trace('reconnect_attempt_failed', {
          attempt: this._reconnectAttempts, error: String(e && e.message || e),
        });
        console.warn('[MeshBay] Reconnect attempt', this._reconnectAttempts,
                     'failed:', e.message);
        // Loop again with a longer backoff — closing over `args`/`token`
        // freshly next time, in case the token was the actual problem.
      }
    }
  }

  /**
   * Pair this browser with the node using a one-time code (M3, and the same
   * substitution as H3).
   *
   * The node has no way to know which key belongs to its operator unless someone
   * tells it locally — asking the hub would let the hub name itself node
   * administrator. The code comes from `meshbay-node operator pair`, over SSH, and
   * the hub never sees it.
   */
  async pairOperator(userId, code) {
    if (!this._connected) throw new Error('Not connected to the node');
    if (!userId) throw new Error('Missing user id');
    if (!this._sessionKeys || !this._sessionKeys.skEdB64 || !this._sessionKeys.skXB64) {
      throw new Error('Identity keys unavailable in this browser — sign in again');
    }
    if (!this._nonceNode || !this.nodePk) {
      throw new Error('Handshake incomplete — reconnect and retry');
    }

    const C = window.MeshBayCrypto;
    // Both public keys are derived from OUR OWN secret keys, never read back from
    // the hub: signing a public key the directory handed us would reintroduce the
    // substitution this whole mechanism exists to close.
    const pkEdB64 = await _pkEdFromSk(this._sessionKeys.skEdB64);
    const pkXB64 = await _pkFromSk(this._sessionKeys.skXB64);
    const ts = Math.floor(Date.now() / 1000);

    // group_id is empty: operator authority is node-wide, not per group.
    const transcript = C.joinTranscript(
      this.nodePk, '', userId, pkEdB64, pkXB64, this._nonceNode, ts);
    const sig = await window.MeshBayKeys.signBytes(this._sessionKeys.skEdB64, transcript);

    const resp = await this._sendAndWait({
      type: 'join_request',
      v: '0.1',
      group_id: '',
      pk_ed25519: pkEdB64,
      pk_x25519: pkXB64,
      code: code || '',
      ts,
      sig,
    });

    if (resp.type === 'error') throw new Error(resp.detail || 'Pairing refused');
    if (resp.type !== 'join_result' || !resp.ok) {
      const reason = resp.reason || 'unknown';
      const err = new Error(JOIN_REFUSALS[reason] || `Pairing refused: ${reason}`);
      err.reason = reason;
      throw err;
    }
    this.memberRole = 'operator';
    return resp;
  }

  /**
   * The full index. Resolves with the sealed payload already opened —
   * `_applyIndexMessage` does that before it hands the message to whoever is
   * waiting, so both the reply to this call and the node's own unsolicited
   * pushes go through one decrypt path.
   */
  async fetchIndex() {
    const msg = await this._sendAndWait({ type: 'index_sync', v: '0.1' });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  async fetchChunk(fileId, chunkIndex) {
    const msg = await this._sendAndWait({
      type: 'file_req',
      v: '0.1',
      file_id: fileId,
      chunk_index: chunkIndex,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  /**
   * TMDB metadata for one file (Videos app, docs/mediacenter.md §5.4).
   * Keyed by the entry's own `id` (its content hash) — never a path: a
   * path names the *folder* a file is in (indexer.py's `_virtual_dir`), so
   * two files sharing a folder (any multi-episode season) would resolve to
   * whichever entry the node's index happened to return first (found live
   * via the Music app's identical bug, 2026-08-25 — see webrtc_server.py's
   * `_do_media_meta_request`).
   * `confidence: 0` (no tmdb_id, no fields) means no confident match —
   * the caller falls back to a thumbnail-only card (§4.1), not an error.
   */
  async fetchMediaMeta(fileId) {
    const msg = await this._sendAndWait({ type: 'media_meta_req', v: '0.6', file_id: fileId });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  /**
   * Unfurl a URL pasted in chat. The node fetches it (the browser cannot —
   * CSP and CORS — and would leak every reader's IP), parses an OpenGraph
   * card, and caches any image in its thumb store; `image_thumb_hash` then
   * rides the normal file_req path like a poster. `ok: false` means "no
   * preview" (blocked, unreachable, not HTML) — the caller just shows the
   * bare link. Keyed by url: a message with several links fires one each.
   */
  async fetchLinkPreview(url) {
    const msg = await this._sendAndWait({ type: 'link_preview_req', v: '0.6', url });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  /**
   * One season's own overview/air_date/poster (docs/mediacenter.md §5.4's
   * per-season view) — a show's own tmdb_meta is one static field that does
   * not necessarily describe every season alike, found live: a 3-season
   * show whose overview read as season-3-specific for every season.
   * Keyed like media_meta_req: a season-tab bar can fire a request per tab
   * before the previous one lands, and matching by arrival order would hand
   * one season's data to a different season's tab whenever two responses
   * reordered.
   */
  async fetchSeasonMeta(tmdbId, season) {
    const msg = await this._sendAndWait({
      type: 'season_meta_req', v: '0.6', tmdb_id: tmdbId, season,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  /**
   * Raw TMDB search candidates for an operator correcting a wrong automatic
   * match — unlike fetchMediaMeta, this never collapses to one best guess:
   * a human picks from several, so several is the point. Read-only, not an
   * admin op: it looks nothing up in this node's own state and changes
   * nothing, so it needs no signature (mirrors why media_meta_req isn't
   * signed either).
   */
  async searchTmdb(mediaType, query) {
    const msg = await this._sendAndWait({
      type: 'tmdb_search_req', v: '0.6', media_type: mediaType, query,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  /**
   * Correct a wrong automatic TMDB match. Signed like setVideoRoot/
   * setTmdbConfig: it replaces what every member sees for a show/movie,
   * node-wide (media_cache is shared, not per-viewer) — an unsigned
   * override would let any member vandalize another show's metadata.
   * Applies to every file sharing the representative one's display_title,
   * not just the file the operator happened to be looking at (webrtc_
   * server.py's _admin_exec_tmdb_override). Keyed by `fileId`, not a path
   * — same reasoning as fetchMediaMeta above.
   */
  async overrideTmdbMatch(fileId, tmdbId, mediaType, signFn) {
    const msg = await this._sendAndWait({
      type: 'tmdb_override', v: '0.7', file_id: fileId, tmdb_id: tmdbId, media_type: mediaType,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      const subject = `file_id=${fileId},tmdb_id=${tmdbId},media_type=${mediaType}`;
      return this._authorizeAdminOp(msg, 'tmdb_override', subject, signFn);
    }
    return msg;
  }

  /**
   * Drop one file's cached TMDB match so it re-resolves with the node's
   * current matcher (§10.1/V13) — the one-click alternative to the full
   * search-and-pick flow. Signed for the same reason as overrideTmdbMatch.
   */
  async rematchTmdbMatch(fileId, signFn) {
    const msg = await this._sendAndWait({
      type: 'tmdb_rematch', v: '0.7', file_id: fileId,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'tmdb_rematch', `file_id=${fileId}`, signFn);
    }
    return msg;
  }

  /**
   * Set/clear a custom TMDB API token, and/or set the language TMDB is
   * queried in (e.g. "fr-FR") — one for the whole node, since both are one
   * operator's shared credential/cache, not a per-group concern (see
   * setTmdbEnabled below for the per-group on/off switch). Signed like
   * setAppsEnabled/setMemberUpload — an unsigned change would let any
   * member alter outbound third-party network traffic the operator never
   * agreed to (docs/mediacenter.md §5.5, §8). `token: ''` explicitly clears
   * a previously-set custom token; omit it (undefined/null), like
   * `language`, to leave whatever is stored unchanged.
   */
  async setTmdbConfig(token, language, signFn) {
    const msg = await this._sendAndWait({
      type: 'tmdb_config', v: '0.7',
      token: token === undefined ? null : token,
      language: language === undefined ? null : language,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      // Must match the node's subject byte-for-byte (webrtc_server.py
      // _do_tmdb_config) — the token itself is never part of the subject
      // (it would end up in the audit log in plaintext), only whether one
      // was supplied. The language is not a secret, so it appears as-is.
      const subject = `custom_token=${token ? 'yes' : 'no'},language=${language || 'default'}`;
      return this._authorizeAdminOp(msg, 'tmdb_config', subject, signFn);
    }
    return msg;
  }

  /**
   * Whether TMDB lookups run for this group at all — per-group (2026-08-24,
   * used to be node-wide): a real media-library group and a test/demo group
   * on the same node need not share the decision to spend TMDB quota and
   * make outbound requests. Signed like setVideoRoot — it decides whether
   * this group's members' Videos tab ever makes outbound TMDB traffic.
   */
  async setTmdbEnabled(enabled, signFn) {
    const msg = await this._sendAndWait({
      type: 'tmdb_enabled', v: '0.7', enabled: Boolean(enabled),
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      // Must match the node's subject byte-for-byte (webrtc_server.py
      // _do_tmdb_enabled): Python's f"{bool}" is "True"/"False", not JS's
      // lowercase.
      const subject = enabled ? 'True' : 'False';
      return this._authorizeAdminOp(msg, 'tmdb_enabled', subject, signFn);
    }
    return msg;
  }

  /**
   * Which folder (possibly a subfolder of a shared root) the Videos app
   * treats as its entry point for this group. `path: ''` means the whole
   * group index. Signed like setAppsEnabled — it decides what every
   * member's Videos tab shows.
   */
  async setVideoRoot(path, signFn) {
    const clean = (path || '').replace(/^\/+|\/+$/g, '');
    const msg = await this._sendAndWait({ type: 'video_root', v: '0.5', path: clean });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'video_root', clean, signFn);
    }
    return msg;
  }

  /**
   * Same shape as setVideoRoot above — the Music app's own entry point.
   */
  async setAudioRoot(path, signFn) {
    const clean = (path || '').replace(/^\/+|\/+$/g, '');
    console.log('[MeshBay] setAudioRoot: sending request, path=', JSON.stringify(clean));
    const msg = await this._sendAndWait({ type: 'audio_root', v: '0.10', path: clean });
    console.log('[MeshBay] setAudioRoot: first reply =', msg);
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'audio_root', clean, signFn);
    }
    return msg;
  }

  /**
   * Which folder(s) the Photos app treats as its entry points for this
   * group (docs/photos.md §2.1). Unlike setVideoRoot/setAudioRoot, `roots`
   * is a whole set, replaced in one signed op — same shape as
   * setAppsEnabled. The client normalizes the same way the node does
   * (webrtc_server.py's `_do_photo_roots`: trim slashes, drop empties,
   * dedupe, sort) so the subject built here matches byte-for-byte what the
   * node signs the challenge against.
   */
  async setPhotoRoots(roots, signFn) {
    const clean = [...new Set(
      (roots || []).map((r) => (r || '').replace(/^\/+|\/+$/g, '')).filter(Boolean),
    )].sort();
    const msg = await this._sendAndWait({ type: 'photo_roots', v: '0.11', roots: clean });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'photo_roots', clean.join(','), signFn);
    }
    return msg;
  }

  /**
   * MusicBrainz metadata for one track (Music app, docs/musicbay.md §4.3)
   * — same shape as fetchMediaMeta, minus a season/episode concept:
   * album-level (release), resolved from the track's own artist/album
   * fields already in the index. Keyed by the track's own `id` (content
   * hash), not a path — a path names the *folder* a track is in, and an
   * album is one folder with many tracks in it; three unrelated albums
   * shared one folder's track's cover before this fix (found live,
   * 2026-08-25). `confidence: 0` means no confident match (or MusicBrainz
   * off for this group, or nothing configured) — the caller falls back to
   * the embedded/no cover it already had, not an error.
   */
  async fetchMusicMeta(fileId) {
    const msg = await this._sendAndWait({ type: 'music_meta_req', v: '0.9', file_id: fileId });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  /**
   * Server-side transcode of a Music-app file the browser's own <audio>
   * element cannot decode at all (WMA, Musepack) into AAC/M4A. Returns
   * `{ hash, size, mime }` — the *cache* hash to pull through the normal
   * file_req/chunk path (fetchChunk/pipelinedDownload), not the file's own
   * id, the same indirection already used for a TMDB poster or a
   * MusicBrainz cover. Cached node-side after the first call, but ffmpeg
   * still has to run at least once and a transcode slot can be busy, so
   * this gets a longer timeout than the metadata lookups above.
   */
  async requestAudioTranscode(fileId) {
    const msg = await this._sendAndWait(
      { type: 'audio_transcode_req', v: '0.9', file_id: fileId }, 120000);
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  /**
   * Whether MusicBrainz lookups run for this group at all — per-group from
   * the start (docs/musicbay.md §3.2/§6). Signed like setTmdbEnabled.
   */
  async setMusicbrainzEnabled(enabled, signFn) {
    const msg = await this._sendAndWait({
      type: 'musicbrainz_enabled', v: '0.8', enabled: Boolean(enabled),
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      // Python's f"{bool}" is "True"/"False", not JS's lowercase — must
      // match webrtc_server.py _do_musicbrainz_enabled byte-for-byte.
      const subject = enabled ? 'True' : 'False';
      return this._authorizeAdminOp(msg, 'musicbrainz_enabled', subject, signFn);
    }
    return msg;
  }

  async fetchStreamSegment(fileId, segmentIndex, segmentDuration) {
    const msg = await this._sendAndWait({
      type: 'stream_seg',
      v: '0.1',
      file_id: fileId,
      segment_index: segmentIndex,
      segment_duration: segmentDuration || 4,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    return _b64decode(msg.data_b64);
  }

  /**
   * A page of chat history, newest first by default.
   *
   * `before` is a message id, not a timestamp: it pages backwards from the
   * newest, which is the direction a conversation is read. Asking without it
   * used to mean `since: 0`, which paged *forwards* from the very first message
   * — so a busy group opened on its oldest page and never showed the recent
   * exchange.
   *
   * Returns { messages, hasMore } — hasMore says whether anything older exists,
   * so the "load older" control knows when to stop offering.
   */
  async fetchChatHistory({ before = null, limit = 100 } = {}) {
    const msg = await this._sendAndWait({
      type: 'chat_hist',
      v: '0.2',
      before: before,
      limit: limit,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    return { messages: msg.messages || [], hasMore: !!msg.has_more };
  }

  /**
   * Liveness on this already-open channel. Resolves with the round trip in ms,
   * rejects on timeout — a DataChannel whose peer vanished without closing
   * still reads as connected, and nothing else here notices until a real
   * request hangs.
   */
  async ping(timeoutMs = 5000) {
    const token = Math.random().toString(36).slice(2);
    const started = performance.now();
    const msg = await this._sendAndWait({ type: 'ping', v: '0.2', token }, timeoutMs);
    if (msg.type === 'error') throw new Error(msg.detail);
    return Math.round(performance.now() - started);
  }

  async sendChat(payload, iteration, threadId, senderName) {
    const msg = await this._sendAndWait({
      type: 'chat_msg',
      v: '0.1',
      payload: payload,
      iteration: iteration || 0,
      thread_id: threadId || null,
      sender_name: senderName || null,
    });
    return msg;
  }

  /**
   * Authorize a privileged node operation with the user's Ed25519 identity key.
   *
   * The client rebuilds the signed transcript from the challenge fields and refuses
   * to sign unless the operation and subject match what the user actually asked for.
   * Previously the node sent 32 opaque random bytes and the client signed them
   * blind, which let any peer obtain a signature over content of its choosing
   * (finding H5).
   */
  async _authorizeAdminOp(challenge, expectedOp, expectedSubject, signFn) {
    if (challenge.op !== expectedOp || challenge.subject !== expectedSubject) {
      throw new Error(
        `Refusing to sign: node asked to authorize "${challenge.op}" on ` +
        `"${challenge.subject}", but the requested action was "${expectedOp}" ` +
        `on "${expectedSubject}"`);
    }
    if (!signFn) throw new Error('Admin challenge received but no signing key available');

    const transcript = window.MeshBayCrypto.adminTranscript(
      challenge.op, challenge.node_pk, challenge.group_id,
      challenge.subject, challenge.nonce, challenge.ts);

    const signature = await signFn(transcript);
    console.log('[MeshBay] _authorizeAdminOp: signed', challenge.op, 'op_id=', challenge.op_id,
               '— sending admin_response');
    const ack = await this._sendAndWait({
      type: 'admin_response',
      v: '0.1',
      op_id: challenge.op_id,
      signature,
      // Not read by the node (_do_admin_response only looks at op_id and
      // signature) — carried so _sendAndWait can key this reply by op, the
      // same way the admin_challenge that preceded it was keyed. Without
      // it, two admin_response replies in flight together (e.g. one op's
      // audio_root_ack arriving while another's apps_enabled_ack is still
      // pending) are matched by nothing more than arrival order.
      op: challenge.op,
    });
    console.log('[MeshBay] _authorizeAdminOp:', challenge.op, 'admin_response reply =', ack);
    if (ack.type === 'error') throw new Error(ack.detail);
    return ack;
  }

  async deleteFile(fileId, signFn) {
    const msg = await this._sendAndWait({
      type: 'file_delete',
      v: '0.1',
      file_id: fileId,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'file_delete', fileId, signFn);
    }
    return msg;
  }

  /**
   * Remove an empty directory. Operator only, and the node checks that — this
   * signs with the identity it pinned for us, exactly like deleting a file.
   */
  async deleteDirectory(dir, signFn) {
    const msg = await this._sendAndWait({
      type: 'dir_delete',
      v: '0.1',
      dir,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      // `dir`, not msg.subject: comparing the node's answer against itself is
      // no check at all, and the point of this one is that we know what we
      // asked for without being told.
      return this._authorizeAdminOp(msg, 'dir_delete', dir, signFn);
    }
    return msg;
  }

  /**
   * Stop this node serving the group key to someone. Operator only.
   *
   * Only the node can do this: its roster decides who it serves. Removing them
   * on the hub is the other half, and neither implies the other.
   */
  /**
   * Turn uploading by ordinary members on or off.
   *
   * Signed by the operator like any other privileged operation — the node
   * refuses an unsigned one, which is what stops a member turning it back on.
   */
  async setMemberUpload(allowed, signFn) {
    const msg = await this._sendAndWait({
      type: 'member_upload', v: '0.1', allowed: Boolean(allowed),
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(
        msg, 'member_upload', allowed ? 'on' : 'off', signFn);
    }
    return msg;
  }

  /**
   * Turn a group "application" (Chat, Files, ...) on or off for everyone.
   *
   * Takes the whole set in one signed message rather than one op per app, so
   * ticking several boxes in Settings costs one signature. `apps` is sorted
   * and joined the same way on the node before it is shown for signing —
   * `_authorizeAdminOp` below checks the two match.
   */
  async setAppsEnabled(apps, signFn) {
    const msg = await this._sendAndWait({
      type: 'apps_enabled', v: '0.1', apps,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(
        msg, 'apps_enabled', [...apps].sort().join(','), signFn);
    }
    return msg;
  }

  /**
   * How often the node's reconciliation backstop runs, and how long it
   * waits after a file's last write before hashing it (indexer.py
   * DirectoryIndexer). Whole seconds only: the node builds the signing
   * subject with Python's `%g` (drops a trailing ".0"), and the simplest
   * way to always match it byte-for-byte from JS is to never send a
   * fractional value in the first place.
   */
  async setScanSettings(reconcileIntervalSecs, debounceSecs, signFn) {
    const reconcile = Math.round(reconcileIntervalSecs);
    const debounce = Math.round(debounceSecs);
    const msg = await this._sendAndWait({
      type: 'set_scan_settings', v: '0.1',
      reconcile_interval_secs: reconcile, debounce_secs: debounce,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(
        msg, 'set_scan_settings', `${reconcile},${debounce}`, signFn);
    }
    return msg;
  }

  async revokeMember(userId, signFn) {
    const msg = await this._sendAndWait({
      type: 'member_revoke', v: '0.1', user_id: userId,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'member_revoke', userId, signFn);
    }
    return msg;
  }

  // ── Node management (D5) ───────────────────────────────────────────────

  async fetchNodeStatus() {
    const msg = await this._sendAndWait({ type: 'node_status', v: '0.1' });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  async updateNodeSettings(settings) {
    const msg = await this._sendAndWait({
      type: 'node_settings_set', v: '0.1', settings,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  async addRoot(groupId, path, { name, kind, upload } = {}, signFn) {
    const msg = await this._sendAndWait({
      type: 'root_add', v: '0.1',
      group_id: groupId, path,
      name: name || '', kind: kind || 'generic', upload: !!upload,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'root_add', path, signFn);
    }
    return msg;
  }

  async removeRoot(groupId, rootName, signFn) {
    const msg = await this._sendAndWait({
      type: 'root_remove', v: '0.1',
      group_id: groupId, root_name: rootName,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'root_remove', rootName, signFn);
    }
    return msg;
  }

  async unpinMember(userId, signFn) {
    const msg = await this._sendAndWait({
      type: 'member_unpin', v: '0.1', user_id: userId,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'member_unpin', userId, signFn);
    }
    return msg;
  }

  async rotateGek(groupId, signFn) {
    const msg = await this._sendAndWait({
      type: 'gek_rotate', v: '0.1', group_id: groupId,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'gek_rotate', groupId, signFn);
    }
    return msg;
  }

  async fetchRoster(groupId) {
    const msg = await this._sendAndWait({
      type: 'roster_read', v: '0.1', group_id: groupId || '',
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  async fetchDenylist() {
    const msg = await this._sendAndWait({ type: 'denylist_read', v: '0.1' });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  async clearDenylist(subject) {
    const msg = await this._sendAndWait({
      type: 'denylist_clear', v: '0.1', subject: subject || '',
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  async attachGroup(name, sharedDir, uploadDir, signFn) {
    const msg = await this._sendAndWait({
      type: 'group_attach', v: '0.1',
      name, shared_dir: sharedDir, upload_dir: uploadDir || '',
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'group_attach', name, signFn);
    }
    return msg;
  }

  async detachGroup(name, signFn) {
    const msg = await this._sendAndWait({
      type: 'group_detach', v: '0.1', name,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'group_detach', name, signFn);
    }
    return msg;
  }

  async reloadConfig() {
    const msg = await this._sendAndWait({ type: 'node_reload', v: '0.1' });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  /**
   * Ask for a video stream, and say how much we can take.
   *
   * `credits` bounds what is in flight. Without it the node pushes the whole
   * film as fast as ffmpeg produces it and the browser holds all of it while
   * MediaSource consumes a segment at a time — which is fine for a clip and
   * fatal for anything worth streaming.
   */
  requestStream(fileId, credits = STREAM_CREDITS, start = 0) {
    // `start` is a seek: the node retires whatever this session was streaming
    // and spawns ffmpeg again from there. Omitted or zero is the film's
    // beginning, which is what an 0.1 node understands.
    console.log('[stream] sending stream_req start:', start, 'credits:', credits);
    this._send({ type: 'stream_req', v: '0.1', file_id: fileId, credits, start });
  }

  /** Room for `n` more segments. */
  grantStreamCredit(n = 1) {
    if (!this._connected) return;
    console.log('[stream] grant credit:', n);
    this._send({ type: 'stream_more', v: '0.1', n });
  }

  /**
   * Tell the node what the player sees.
   *
   * A hang on a phone is unreadable from here: there is no console to open and
   * the node's own log shows a stream it is feeding perfectly well. This puts
   * the two halves in one file. The node only logs it.
   */
  sendStreamDiag(diag) {
    if (!this._connected) return;
    try { this._send({ type: 'client_diag', v: '0.1', ...diag }); } catch { /* gone */ }
  }

  /**
   * Nobody is watching any more.
   *
   * Closing the viewer used to say nothing to the node, which went on
   * transcoding and holding one of its two slots until the credit timeout — so
   * the next video answered "server busy".
   */
  stopStream() {
    if (!this._connected) return;
    try { this._send({ type: 'stream_stop', v: '0.1' }); } catch { /* gone */ }
  }

  /**
   * Push a whole file, several chunks in flight at once.
   *
   * One chunk per round trip is 48 KB of throughput per RTT no matter how much
   * bandwidth there is: 4.8 MB/s on a 10 ms path, 480 KB/s on a 100 ms one, and
   * the sender is idle for almost all of it — which also keeps SCTP's congestion
   * window shut, so the transport never gets a chance to speed up either. A
   * window of chunks makes the rate depend on bandwidth rather than distance.
   *
   * Order is not at risk: a DataChannel is ordered and reliable by default, and
   * the node refuses any chunk that is not the one it expects next.
   *
   * The node decides where this lands (uploads/) and under what name — it finds a
   * free one rather than replacing anything. The ack says which, and that is what
   * this returns.
   */
  async uploadFile(file, { chunkSize, onProgress, signal } = {}) {
    // The same file twice at once would confuse the node, which keys its own
    // upload state by name — and would race for the same destination.
    if (this._uploaders.has(file.name)) {
      throw new Error(`${file.name} is already being uploaded`);
    }
    const size = chunkSize || UPLOAD_CHUNK_SIZE;
    const total = Math.max(1, Math.ceil(file.size / size));
    let acked = 0;
    let stored = null;
    let failure = null;

    const acks = [];
    this._uploaders.set(file.name, (msg) => {
      if (msg.type === 'error') {
        failure = new Error(msg.detail || 'Upload refused');
      } else if (msg.stored_as) {
        stored = msg;
      }
      acked += 1;
      if (onProgress) onProgress(Math.min(file.size, acked * size), file.size);
      const waiter = acks.shift();
      if (waiter) waiter();
    });

    const nextAck = () => new Promise(r => acks.push(r));

    try {
      for (let i = 0; i < total; i++) {
        if (signal && signal.aborted) throw _aborted();
        // Backpressure: without it the whole file lands in the browser's send
        // buffer in seconds and the progress bar becomes a work of fiction.
        while (this._channel && this._channel.bufferedAmount > UPLOAD_BUFFER_HIGH) {
          if (signal && signal.aborted) throw _aborted();
          await new Promise(r => setTimeout(r, 20));
        }
        while (i - acked >= UPLOAD_WINDOW) {
          await nextAck();
          if (failure) throw failure;
        }
        if (failure) throw failure;

        const buf = new Uint8Array(
          await file.slice(i * size, (i + 1) * size).arrayBuffer());
        this._send({
          type: 'file_upload',
          v: '0.1',
          filename: file.name,
          chunk_index: i,
          total_chunks: total,
          data: buf,
        });
      }
      while (acked < total) {
        await nextAck();
        if (failure) throw failure;
      }
    } finally {
      this._uploaders.delete(file.name);
    }
    return stored || {};
  }

  /** Create a directory under the current one. Any member may. */
  async createDirectory(dir, name) {
    const msg = await this._sendAndWait({
      type: 'dir_create', v: '0.1', dir: dir || '', name,
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  /**
   * Ask the node for a one-time pairing code admitting `userId` to this group.
   *
   * This replaces wrapping the group key in the browser. We no longer fetch the
   * invitee's public key from the hub, so the hub can no longer answer with its own
   * and be handed the group key (H3). The node wraps the key later, itself, for a
   * key the invitee proves possession of.
   *
   * Returns {code, expires_at} — the code is displayed once and passed to the
   * invitee out of band.
   */
  async createInvite(userId, groupId, username, signFn) {
    const msg = await this._sendAndWait({
      type: 'invite_create',
      v: '0.1',
      user_id: userId,
      group_id: groupId,
      username: username || '',
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    if (msg.type === 'admin_challenge') {
      return this._authorizeAdminOp(msg, 'invite_create', userId, signFn);
    }
    return msg;
  }

  /**
   * Ask the node to recognise us and hand over the group key.
   *
   * Sent when we hold no GEK for a group. `code` is needed only the first time
   * this node sees this account (and not at all in an open-join group).
   */
  async joinGroup(userId, groupId, code) {
    if (!this._sessionKeys || !this._sessionKeys.skEdB64 || !this._sessionKeys.skXB64) {
      throw new Error('Identity keys unavailable in this browser — sign in again');
    }
    if (!this._nonceNode || !this.nodePk) {
      throw new Error('Handshake incomplete — reconnect and retry');
    }

    const C = window.MeshBayCrypto;
    const pkEdB64 = await _pkEdFromSk(this._sessionKeys.skEdB64);
    const pkXB64 = await _pkFromSk(this._sessionKeys.skXB64);
    const ts = Math.floor(Date.now() / 1000);

    const transcript = C.joinTranscript(
      this.nodePk, groupId || '', userId, pkEdB64, pkXB64, this._nonceNode, ts);
    const sig = await window.MeshBayKeys.signBytes(this._sessionKeys.skEdB64, transcript);

    const resp = await this._sendAndWait({
      type: 'join_request',
      v: '0.1',
      group_id: groupId || '',
      pk_ed25519: pkEdB64,
      pk_x25519: pkXB64,
      code: code || '',
      ts,
      sig,
    });

    if (resp.type === 'error') throw new Error(resp.detail || 'Join refused');
    if ((resp.type !== 'join_result' || !resp.ok) || !resp.gek) {
      const reason = resp.reason || 'unknown';
      const err = new Error(JOIN_REFUSALS[reason] || `Join refused: ${reason}`);
      // The UI reacts to `code_required` by asking for one; everything else is
      // shown as-is.
      err.reason = reason;
      throw err;
    }

    // Unwrap with our own secret key — the node wrapped for the public key we
    // just proved we hold, so nobody else can open this.
    const skXRaw = Uint8Array.from(atob(this._sessionKeys.skXB64), c => c.charCodeAt(0));
    const myPkX = Uint8Array.from(atob(pkXB64), c => c.charCodeAt(0));
    const gekRaw = await C.unwrapGEK(resp, skXRaw, myPkX);
    this._gekRaw = gekRaw;
    // What the node's roster says this identity is, which is not what the hub
    // says: `operator` here means this browser's key was paired with the node,
    // not merely that the account owns it.
    this.memberRole = resp.role || '';
    return gekRaw;
  }

  // ── Device linking ─────────────────────────────────────────────────────
  //
  // Identity keys are per node, so a browser and a desktop client are two keys
  // on one account here. A new one is admitted by a key this node already
  // pinned — never by the hub, which holds no user keys and so cannot
  // countersign anything. See docs/desktop-client-v1.md §4.

  /**
   * Ask to be added, and return the code to show the person.
   *
   * They read it off this screen and type it into a device already paired with
   * this node. The code is hashed together with our own keys, so that other
   * device cannot be handed a substituted key and sign for it by mistake.
   */
  async requestDeviceAdd(userId) {
    if (!this._sessionKeys || !this._sessionKeys.skEdB64) {
      throw new Error('Identity keys unavailable in this browser — sign in again');
    }
    if (!this._nonceNode || !this.nodePk) {
      throw new Error('Handshake incomplete — reconnect and retry');
    }
    const C = window.MeshBayCrypto;
    const pkEdB64 = await _pkEdFromSk(this._sessionKeys.skEdB64);
    const pkXB64 = await _pkFromSk(this._sessionKeys.skXB64);

    // 40 bits from the platform CSPRNG, in the same alphabet as a pairing code
    // so it reads and types the same way.
    const alphabet = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
    const bytes = crypto.getRandomValues(new Uint8Array(8));
    const raw = Array.from(bytes, b => alphabet[b % alphabet.length]).join('');
    const code = `${raw.slice(0, 4)}-${raw.slice(4)}`;

    const codeHash = await C.deviceCodeHash(
      C.normalizeCode(code), pkEdB64, pkXB64);
    const ts = Math.floor(Date.now() / 1000);
    const transcript = C.deviceRequestTranscript(
      this.nodePk, userId, pkEdB64, pkXB64, codeHash, this._nonceNode, ts);
    const sig = await window.MeshBayKeys.signBytes(
      this._sessionKeys.skEdB64, transcript);

    const resp = await this._sendAndWait({
      type: 'device_add_request', v: '0.1',
      pk_ed25519: pkEdB64, pk_x25519: pkXB64, code_hash: codeHash, ts, sig,
    });
    if (resp.type === 'error') throw new Error(resp.detail || 'Refused');
    return { code, expiresAt: resp.expires_at };
  }

  /**
   * Approve a device waiting with this code.
   *
   * The node is a mailbox: it is asked for a request matching
   * sha256(code ‖ keys), and the keys in that hash came from the device that
   * filed it. A node returning something else produces no match, so there is
   * nothing to sign and nothing for a person to misread.
   */
  async approveDevice(userId, code) {
    if (!this._sessionKeys || !this._sessionKeys.skEdB64) {
      throw new Error('Identity keys unavailable in this browser — sign in again');
    }
    if (!this._nonceNode || !this.nodePk) {
      throw new Error('Handshake incomplete — reconnect and retry');
    }
    const C = window.MeshBayCrypto;
    const normalized = C.normalizeCode(code);

    // The code never leaves this browser. The node lists what is pending, each
    // with the hash the requesting device computed over the code and its own
    // keys; we recompute and keep the one that matches. A node offering
    // fabricated keys would have to produce a hash matching sha256(code ‖
    // fabricated) — and it does not know the code.
    const listed = await this._sendAndWait({ type: 'device_lookup', v: '0.1' });
    if (listed.type === 'error') throw new Error(listed.detail || 'Not found');

    let match = null;
    for (const req of listed.requests || []) {
      const expect = await C.deviceCodeHash(
        normalized, req.pk_ed25519, req.pk_x25519);
      if (expect === req.code_hash) { match = req; break; }
    }
    if (!match) {
      throw new Error('No device is waiting with that code');
    }
    return this._countersign(userId, match.code_hash,
                             match.pk_ed25519, match.pk_x25519);
  }

  async _countersign(userId, codeHash, pkEdB64, pkXB64) {
    const C = window.MeshBayCrypto;
    const ts = Math.floor(Date.now() / 1000);
    const transcript = C.deviceAddTranscript(
      this.nodePk, userId, pkEdB64, pkXB64, this._nonceNode, ts);
    const sig = await window.MeshBayKeys.signBytes(
      this._sessionKeys.skEdB64, transcript);
    const resp = await this._sendAndWait({
      type: 'device_add', v: '0.1',
      pk_ed25519: pkEdB64, pk_x25519: pkXB64, code_hash: codeHash, ts, sig,
    });
    if (resp.type === 'error') throw new Error(resp.detail || 'Refused');
    return resp;
  }

  async listDevices() {
    const resp = await this._sendAndWait({ type: 'device_list', v: '0.1' });
    if (resp.type === 'error') throw new Error(resp.detail || 'Refused');
    return { devices: resp.devices || [], pending: resp.pending || 0 };
  }

  /** Retire a device — a lost laptop. Countersigned like an addition. */
  async revokeDevice(userId, pkEdB64, pkXB64) {
    const C = window.MeshBayCrypto;
    const ts = Math.floor(Date.now() / 1000);
    const transcript = C.deviceAddTranscript(
      this.nodePk, userId, pkEdB64, pkXB64, this._nonceNode, ts);
    const sig = await window.MeshBayKeys.signBytes(
      this._sessionKeys.skEdB64, transcript);
    const resp = await this._sendAndWait({
      type: 'device_revoke', v: '0.1', pk_ed25519: pkEdB64, ts, sig,
    });
    if (resp.type === 'error') throw new Error(resp.detail || 'Refused');
    return resp;
  }

  /**
   * Withdraw our key backup from this node.
   *
   * The counterpart of storeKeypairBundle: turning the setting off has to remove
   * what is already stored, not merely stop adding to it — otherwise the blob
   * stays on every node the account has ever joined (C4).
   */
  async deleteKeypairBundle() {
    const msg = await this._sendAndWait({
      type: 'keypair_bundle_delete', v: '0.1',
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  async storeKeypairBundle(bundleEnc, recoveryEnc) {
    const msg = await this._sendAndWait({
      type: 'keypair_bundle_store',
      v: '0.1',
      bundle_enc: bundleEnc,
      // MNP 0.14, optional: the recovery-wrapped copy. Omitted for a plain
      // re-backup; the node keeps any copy it already holds.
      ...(recoveryEnc ? { bundle_enc_recovery: recoveryEnc } : {}),
    });
    if (msg.type === 'error') throw new Error(msg.detail);
    return msg;
  }

  get gekRaw() { return this._gekRaw; }

  /**
   * Give an automatic reconnect already in progress (see _reconnectLoop) a
   * bounded chance to land before giving up.
   *
   * _sendAndWait does this internally for every request that goes through
   * it, so most callers never need this directly. It exists for the ones
   * that check `transport.connected` themselves before doing anything else —
   * music-player.js's fetchTrackBlob is the one this was written for: found
   * live throwing "Transport not connected" on the track *after* a
   * screen-lock reconnect had already been under way for a while, because
   * that check ran, saw `connected` still false, and threw before the
   * reconnect it only had to wait a few seconds for got the chance to finish.
   * A no-op — returns immediately — when nothing is being reconnected,
   * including once one has already succeeded, so it is safe to call
   * unconditionally ahead of such a check.
   */
  async waitForReconnect(timeoutMs = 6000) {
    if (!this._reconnectPromise) return;
    await Promise.race([
      this._reconnectPromise.catch(() => {}),
      new Promise((r) => setTimeout(r, timeoutMs)),
    ]);
  }

  close() {
    // Must be set before pc.close() below: that close() itself can drive the
    // pc to "closed" synchronously, and the connectionstatechange handler
    // only skips reconnecting because of this flag, not because "closed" is
    // absent from its own trigger condition.
    this._closed = true;
    document.removeEventListener('visibilitychange', this._onVisibilityWake);
    this._wakeReconnect();
    if (this._diagCleanup) { this._diagCleanup(); this._diagCleanup = null; }
    if (this._channel) this._channel.close();
    if (this._pc) this._pc.close();
    this._connected = false;
    for (const [, p] of this._pending) p.reject(new Error('Transport closed'));
    this._pending.clear();
  }

  // ── Internal ──────────────────────────────────────────────────────────────

  /**
   * Queue one sealed index message for opening.
   *
   * Opening is asynchronous and `_dispatch` is not, so two messages handled
   * independently would be applied in whichever order their decrypt promises
   * happened to settle. A delta applied before the sync it is based on — or
   * before an earlier delta — is a silently wrong view of the group, so they
   * are opened one at a time, in arrival order.
   */
  _queueIndexMessage(msg) {
    this._indexChain = (this._indexChain || Promise.resolve())
      .then(() => this._applyIndexMessage(msg))
      .catch((e) => this._failSession(
        `${msg.type} did not open under the group key`, e));
  }

  async _applyIndexMessage(msg) {
    const groupId = msg.group_id || (this._connectArgs && this._connectArgs.groupId) || '';
    const payload = msgpack_decode(await window.MeshBayCrypto.openGroup(
      this._gekRaw, 'index', msg.type, groupId, msg));
    // The routing fields stay, the envelope's own two go, the payload lands on
    // top — so every consumer keeps reading the flat message it always read.
    const opened = { ...msg, ...payload };
    delete opened.nonce;
    delete opened.ct;

    if (msg.type === 'index_sync') {
      if (this._onIndexSync) this._onIndexSync(opened);
      for (const [, handler] of this._pending) {
        if (handler._reqType === 'index_sync') {
          handler.resolve(opened);
          break;
        }
      }
      return;
    }
    if (this._onIndexDelta) this._onIndexDelta(opened);
  }

  /**
   * Stop, rather than carry on with a degraded view.
   *
   * A payload that does not open is not an empty index and not a config
   * change — it is a peer we cannot talk to. Reconnecting would only reach the
   * same peer with the same key, so the session ends and the failure is named.
   */
  _failSession(what, cause) {
    const err = new Error(`${what}: ${(cause && cause.message) || cause}`);
    console.error('[MeshBay]', err.message);
    for (const [, handler] of this._pending) handler.reject(err);
    this._pending.clear();
    if (this._onSessionFailed) this._onSessionFailed(err);
    this.close();
  }

  async _sendAndWait(obj, timeoutMs = 30000) {
    // A reconnect already in flight (see _reconnectLoop) means the channel
    // this would send on is the one just declared dead. `_inReconnectAttempt`
    // excludes the handshake connect() itself makes while reconnecting — that
    // call runs *inside* this same _reconnectPromise, which cannot resolve
    // until it returns, so waiting on it here would just be waiting on
    // itself for the full 6s, on every step of the handshake, every time.
    if (!this._inReconnectAttempt) await this.waitForReconnect(6000);
    return new Promise((resolve, reject) => {
      const id = this._seqId++;
      const timeout = setTimeout(() => {
        this._pending.delete(id);
        console.error('[MeshBay] Response timeout for', obj.type,
                      'after', timeoutMs, 'ms, channel=', this._channel?.readyState);
        trace('send_timeout', {
          reqType: obj.type, timeoutMs,
          pc: this._pc?.connectionState, ice: this._pc?.iceConnectionState,
          channel: this._channel?.readyState,
        });
        reject(new Error('Response timeout'));
      }, timeoutMs);
      this._pending.set(id, {
        _reqType: obj.type,
        // Chunks are the one request that runs several at a time and can be
        // interleaved with anything else on the channel. Matching them by
        // arrival order was only ever true by luck; this makes it true.
        //
        // A ping is keyed for the same reason and a sharper one: it is sent
        // *while* other traffic is in flight, so the fallback below would hand
        // a pong to whatever was waiting — resolving a history request with a
        // message that has no messages in it, and emptying the conversation.
        // media_meta_req is the same shape as file_req: video-app.js fires
        // one per visible poster-grid tile, several at a time — matching by
        // arrival order handed one tile's TMDB result to a different tile
        // whenever two responses reordered (reproduced live: which of two
        // shows got the confident match flipped across reloads).
        _key: obj.type === 'file_req'
          ? `chunk:${obj.file_id}:${obj.chunk_index}`
          : obj.type === 'ping' ? `ping:${obj.token}`
          : obj.type === 'media_meta_req' ? `media_meta:${obj.file_id}`
          // One chat message can carry several links, each unfurled on its
          // own; matching by arrival order would swap two cards.
          : obj.type === 'link_preview_req' ? `link_preview:${obj.url}`
          // Same reordering hazard as media_meta_req: an album grid fires
          // one music_meta_req per visible tile, several at a time.
          : obj.type === 'music_meta_req' ? `music_meta:${obj.file_id}`
          // Same reordering hazard as media_meta_req: a season-tab bar or a
          // search box can have more than one of these in flight at once.
          : obj.type === 'season_meta_req' ? `season_meta:${obj.tmdb_id}:${obj.season}`
          : obj.type === 'tmdb_search_req' ? `tmdb_search:${obj.media_type}:${obj.query}`
          // Same reordering hazard as media_meta_req: the player prefetches
          // the next track while the current one may still be transcoding.
          : obj.type === 'audio_transcode_req' ? `audio_transcode:${obj.file_id}`
          // Two-step admin-op flow (_authorizeAdminOp) — see ADMIN_OP_TYPES'
          // own comment for the race this closes. The initial request and
          // the admin_response that follows it are keyed the same way
          // (`admin:${op}`) precisely so a reply belongs to the request
          // that named that op, not to whichever admin op happened to be
          // submitted first.
          : ADMIN_OP_TYPES.has(obj.type) ? `admin:${obj.type}`
          : obj.type === 'admin_response' ? `admin:${obj.op}`
          : null,
        resolve: (msg) => { clearTimeout(timeout); this._pending.delete(id); resolve(msg); },
        reject: (err) => { clearTimeout(timeout); this._pending.delete(id); reject(err); },
      });
      this._send(obj);
    });
  }

  _send(obj) {
    if (!this._channel || this._channel.readyState !== 'open') {
      throw new Error(`DataChannel not open (state: ${this._channel?.readyState})`);
    }
    const encoded = msgpack_encode(obj);
    const header = new Uint8Array(4);
    new DataView(header.buffer).setUint32(0, encoded.byteLength, false);
    const frame = new Uint8Array(4 + encoded.byteLength);
    frame.set(header);
    frame.set(encoded, 4);
    this._channel.send(frame);
  }

  _onMessage(data) {
    const incoming = new Uint8Array(data);
    this._msgCount = (this._msgCount || 0) + 1;
    if (this._msgCount <= 3) {
      console.log('[MeshBay] recv', incoming.length, 'bytes, msg #' + this._msgCount);
    }
    const combined = new Uint8Array(this._recvBuf.length + incoming.length);
    combined.set(this._recvBuf);
    combined.set(incoming, this._recvBuf.length);
    this._recvBuf = combined;

    while (this._recvBuf.length >= 4) {
      const len = new DataView(this._recvBuf.buffer, this._recvBuf.byteOffset).getUint32(0, false);
      if (this._recvBuf.length < 4 + len) break;
      const msgBytes = this._recvBuf.slice(4, 4 + len);
      this._recvBuf = this._recvBuf.slice(4 + len);

      const msg = msgpack_decode(msgBytes);
      this._dispatch(msg);
    }
  }

  _dispatch(msg) {
    // Two-step admin-op flow (_authorizeAdminOp, ADMIN_OP_TYPES) — resolve
    // by (op) key before anything below gets a chance to steal it via the
    // generic "oldest pending" fallback further down. Returns as soon as a
    // match resolves: this transport instance is the one that submitted
    // the request, and its own caller already updates local state from
    // what *it* sent (setAppsEnabled/setVideoRoot/... callers all do
    // `onX(next)` with their own local value, never by reading the ack),
    // so the broadcast-oriented per-type handlers below — there for every
    // *other* connected client learning the change — have nothing left to
    // add for this one. A message nobody here is waiting on (the common
    // case: this key match finds nothing) falls through exactly as before.
    if (msg.type === 'admin_challenge' && msg.op) {
      // Unlike an *_ack, this one is never a broadcast — the node only
      // ever sends it as a private reply to whichever session just
      // submitted the op it names (_issue_admin_challenge, one `self._send`
      // call, no peer loop) — so a session with no matching key genuinely
      // has nothing further to do with it either, and falling through to
      // "oldest pending" here can only ever be wrong, never a fallback
      // that happens to be right.
      const key = `admin:${msg.op}`;
      let matched = false;
      for (const [, handler] of this._pending) {
        if (handler._key === key) { handler.resolve(msg); matched = true; break; }
      }
      if (!matched) {
        // Should not happen — every caller that can receive this type keys
        // its own request the same way. Logged rather than silently
        // dropped (the old fallback below at least warned, however wrongly
        // it guessed) so a real mismatch is still visible instead of
        // looking exactly like the request never left the browser at all.
        console.warn('[MeshBay] admin_challenge for op=', msg.op, 'op_id=', msg.op_id,
                     'matched no pending request (pending keys:',
                     [...this._pending.values()].map(h => h._key), ')');
      }
      return;
    } else if (typeof msg.type === 'string' && msg.type.endsWith('_ack')) {
      const key = `admin:${msg.type.slice(0, -4)}`;
      for (const [, handler] of this._pending) {
        if (handler._key === key) { handler.resolve(msg); return; }
      }
    }

    // While an upload is in flight the acks are its own, and there are many of
    // them: they must not be handed to whatever request happens to be oldest in
    // the pending map.
    if (msg.type === 'file_upload_ack' && this._uploaders.has(msg.filename)) {
      this._uploaders.get(msg.filename)(msg);
      return;
    }
    // An upload refusal names the file it is about, so only that upload fails.
    // It did not use to, and there was no way to tell whose error it was, so
    // every upload in flight was failed together — send a second file whose
    // name the node dislikes and both died. The broadcast is kept for a node
    // that does not name it, where guessing wrong is worse than stopping.
    if (msg.type === 'error' && this._uploaders.size) {
      if (msg.filename && this._uploaders.has(msg.filename)) {
        this._uploaders.get(msg.filename)(msg);
        return;
      }
      if (!msg.filename) {
        for (const handler of [...this._uploaders.values()]) handler(msg);
        return;
      }
      // Named, but for an upload that is no longer running — not ours to act on.
      return;
    }
    if (msg.type === 'chat_msg' && this._onChat) {
      this._onChat(msg);
      return;
    }
    if (msg.type === 'stream_init') {
      console.log('[stream] recv stream_init, start:', msg.start, 'codec:', msg.codec, 'handler:', !!this._onStreamInit);
      if (this._onStreamInit) this._onStreamInit(msg);
      return;
    }
    if (msg.type === 'stream_data') {
      if (this._onStreamData) this._onStreamData(msg);
      return;
    }
    if (msg.type === 'stream_end') {
      console.log('[stream] recv stream_end');
      if (this._onStreamEnd) this._onStreamEnd(msg);
      return;
    }

    // The operator changed who may upload. Unsolicited: it arrives at everyone
    // connected, not only at whoever asked. It still has to reach a pending
    // caller — the operator's own request resolves on this reply — so it falls
    // through to the matching below rather than returning here.
    if (msg.type === 'member_upload_ack' && this._onUploadPolicy) {
      this._onUploadPolicy(Boolean(msg.allowed));
    }

    // Same shape: the operator changed which apps are shown, and everyone
    // connected hears about it without reconnecting.
    if (msg.type === 'apps_enabled_ack' && this._onAppsEnabled) {
      this._onAppsEnabled(msg.apps || []);
    }

    // Node-wide (not per-group) — the operator supplied/cleared a custom
    // token, or changed the query language. `token_customized` only says
    // whether one is set, never the token itself.
    if (msg.type === 'tmdb_config_ack' && this._onTmdbConfig) {
      this._onTmdbConfig({
        tokenCustomized: Boolean(msg.token_customized),
        language: msg.language || '',
      });
    }

    // Per-group (2026-08-24, used to be folded into tmdb_config_ack above) —
    // the operator turned TMDB on/off for this group specifically.
    if (msg.type === 'tmdb_enabled_ack' && this._onTmdbEnabled) {
      this._onTmdbEnabled(Boolean(msg.enabled));
    }

    // Same shape: an operator corrected a wrong automatic TMDB match, and
    // everyone connected needs to know their poster grid/detail modal for
    // this show is now stale — falls through so the operator's own
    // admin_response promise resolves on this same message, exactly like
    // member_upload_ack/apps_enabled_ack above.
    if (msg.type === 'tmdb_override_ack' && this._onTmdbOverride) {
      this._onTmdbOverride({
        fileId: msg.file_id || '', tmdbId: msg.tmdb_id || '', mediaType: msg.media_type || '',
      });
    }
    // Same shape: the operator dropped one file's match to have it
    // re-resolved (§10.1/V13). No tmdbId — the node re-derives it.
    if (msg.type === 'tmdb_rematch_ack' && this._onTmdbOverride) {
      this._onTmdbOverride({ fileId: msg.file_id || '', tmdbId: '', mediaType: '' });
    }

    // Same shape: the operator changed which folder is the Videos app's
    // entry point for this group.
    if (msg.type === 'video_root_ack' && this._onVideoRoot) {
      this._onVideoRoot(msg.path || '');
    }

    // Same shape: the operator changed which folder is the Music app's
    // entry point for this group.
    if (msg.type === 'audio_root_ack' && this._onAudioRoot) {
      this._onAudioRoot(msg.path || '');
    }

    // Same shape: the operator replaced the Photos app's whole root set
    // for this group (docs/photos.md §2.1).
    if (msg.type === 'photo_roots_ack' && this._onPhotoRoots) {
      this._onPhotoRoots(msg.roots || []);
    }

    // Per-group, like tmdb_enabled_ack above.
    if (msg.type === 'musicbrainz_enabled_ack' && this._onMusicbrainzEnabled) {
      this._onMusicbrainzEnabled(Boolean(msg.enabled));
    }

    // The operator's node is scanning — never the entries themselves, just
    // enough to animate a presence dot. Pushed periodically while it runs,
    // plus once more on the transition back to idle (daemon.py
    // _progress_pusher). UNLIKE member_upload_ack/apps_enabled_ack above,
    // this is never a reply to anything this browser asked for — nobody
    // calls _sendAndWait for it — so it MUST return here. Falling through
    // to the "oldest pending" guess below hands it to whatever unrelated
    // request happens to be waiting (a handshake, a chat history fetch),
    // which then waits forever for its real answer while this one already
    // "arrived" — and every message after that is one slot off too. Found
    // live: a group mid-scan corrupted its own handshake and chat history
    // this way, arriving roughly every 2s for as long as scanning ran.
    if (msg.type === 'index_progress') {
      if (this._onIndexProgress) {
        this._onIndexProgress({
          scanning: Boolean(msg.scanning),
          scanned_bytes: msg.scanned_bytes || 0,
          total_bytes: msg.total_bytes || 0,
        });
      }
      return;
    }

    // Same reasoning as index_progress: nobody awaits this one either, it
    // is purely informational (group-settings.js does not currently act on
    // it), so it must not be left to fall through to the oldest pending
    // request.
    if (msg.type === 'set_scan_settings_ack') {
      return;
    }

    // Both index messages carry their payload sealed under a GEK-derived
    // subkey (MNP 1.0), so they cannot be acted on from here — _dispatch is
    // synchronous and opening one is not. `index_delta` is the incremental
    // form: additions/deletions/updates, never the whole index, and it only
    // ever arrives after the full index this browser already has (the node's
    // first push to a newly connected peer is always index_sync, see
    // daemon.py _broadcast_index_change), so there is always a base to apply
    // it to.
    if (msg.type === 'index_sync' || msg.type === 'index_delta') {
      this._queueIndexMessage(msg);
      return;
    }

    if (msg.type === 'file_chunk') {
      const key = `chunk:${msg.file_id}:${msg.chunk_index}`;
      for (const [, handler] of this._pending) {
        // A node from before the reply carried a file_id: fall back to the
        // index, which is still better than the oldest pending request.
        const match = msg.file_id
          ? handler._key === key
          : handler._key && handler._key.endsWith(`:${msg.chunk_index}`);
        if (match) {
          handler.resolve(msg);
          return;
        }
      }
      // Nobody asked for it any more — a cancelled download, most likely. It
      // must not be handed to whatever request happens to be waiting.
      console.warn('[MeshBay] file_chunk for nobody', msg.file_id, msg.chunk_index);
      return;
    }

    // "Server busy, retry shortly" and friends arrive as a bare error while a
    // stream is being set up, with no request waiting for them. They used to
    // fall through to the oldest pending handler — usually nobody — so the
    // player sat on "buffering" with the answer already in hand.
    if (msg.type === 'error' && this._onStreamError) {
      this._onStreamError(msg);
      return;
    }

    if (msg.type === 'pong') {
      const key = `ping:${msg.token}`;
      for (const [, handler] of this._pending) {
        if (handler._key === key) { handler.resolve(msg); return; }
      }
      // A pong for a probe that already timed out. It must not fall through to
      // the oldest pending request.
      return;
    }

    if (msg.type === 'media_meta_resp') {
      const key = `media_meta:${msg.file_id}`;
      for (const [, handler] of this._pending) {
        if (handler._key === key) { handler.resolve(msg); return; }
      }
      // Nobody asked for this file any more (tile scrolled out and a fresh
      // request superseded it, most likely) — must not fall through to the
      // oldest pending request, which would hand a different tile's promise
      // a TMDB result for a file it never asked about.
      return;
    }

    // Same reasoning as media_meta_resp: keyed by url, and "nobody's waiting"
    // must not fall through.
    if (msg.type === 'link_preview_resp') {
      const key = `link_preview:${msg.url}`;
      for (const [, handler] of this._pending) {
        if (handler._key === key) { handler.resolve(msg); return; }
      }
      return;
    }

    // Same reasoning as media_meta_resp: keyed, not arrival-order, and
    // "nobody's waiting any more" must not fall through either.
    if (msg.type === 'music_meta_resp') {
      const key = `music_meta:${msg.file_id}`;
      for (const [, handler] of this._pending) {
        if (handler._key === key) { handler.resolve(msg); return; }
      }
      return;
    }

    // Same reasoning as music_meta_resp: keyed, not arrival-order — the
    // player can have a transcode of the current track and a prefetch of
    // the next one in flight together.
    if (msg.type === 'audio_transcode_resp') {
      const key = `audio_transcode:${msg.file_id}`;
      for (const [, handler] of this._pending) {
        if (handler._key === key) { handler.resolve(msg); return; }
      }
      return;
    }

    // Same reasoning as media_meta_resp: keyed, not arrival-order, and
    // "nobody's waiting any more" must not fall through either.
    if (msg.type === 'season_meta_resp') {
      const key = `season_meta:${msg.tmdb_id}:${msg.season}`;
      for (const [, handler] of this._pending) {
        if (handler._key === key) { handler.resolve(msg); return; }
      }
      return;
    }

    if (msg.type === 'tmdb_search_resp') {
      const key = `tmdb_search:${msg.media_type}:${msg.query}`;
      for (const [, handler] of this._pending) {
        if (handler._key === key) { handler.resolve(msg); return; }
      }
      return;
    }

    // chat_hist_resp answers a `chat_hist` request, but under a different
    // type string — unlike index_sync, which is asked for and answered under
    // the same name, so the generic fallback below happens to work for it by
    // accident. Without this check, whenever a chat_hist_resp arrives while
    // something else this browser asked for (fetchIndex, even the handshake
    // itself) is still the oldest pending entry, it gets handed to that
    // instead: the request chat_hist_resp actually belongs to then hangs
    // until _sendAndWait's own 30s timeout, and whatever it stole from
    // resolves with the wrong shape entirely — reproduced live as a
    // consistent ~30s hang immediately after a successful handshake, for one
    // specific group and not others connected the same way, which is exactly
    // what depending on response arrival order rather than on request type
    // predicts: it fires only when the two responses happen to reorder.
    if (msg.type === 'chat_hist_resp') {
      for (const [, handler] of this._pending) {
        if (handler._reqType === 'chat_hist') {
          handler.resolve(msg);
          return;
        }
      }
      console.warn('[MeshBay] chat_hist_resp with no matching chat_hist pending');
      return;
    }

    // A bare `ack` answers three requests: sending a chat message, and storing
    // or withdrawing a keypair bundle. The bundle acks name themselves in
    // `detail`; the chat one carries nothing at all, so it was left to the
    // arrival-order guess below — and that guess is wrong whenever anything
    // else this browser asked for is still waiting. The ack went to *that*
    // request, and the chat send waited out its own 30s timeout instead.
    //
    // What that looked like, and what this was found from: typing a message
    // froze the Chat tab. The composer is disabled while a send is in flight,
    // so it stopped accepting clicks and keys; the message never appeared;
    // and it was there all along on the next visit to the tab, because the
    // node had stored it and answered — into somebody else's promise. One
    // unanswered request is enough, and an unanswered request is ordinary
    // rather than exceptional: the node refuses an unknown file_id with a
    // bare `error`, which names no request either and so reaches none, and a
    // Videos tab that asked about a file the index no longer has leaves a
    // `media_meta_req` sitting in `_pending` for the full 30s.
    if (msg.type === 'ack') {
      const named = msg.detail === 'keypair_bundle_stored' ? 'keypair_bundle_store'
        : msg.detail === 'keypair_bundle_deleted' ? 'keypair_bundle_delete'
        : null;
      // Without a `detail` it is a chat ack — but a node that names neither
      // is answering whichever of the three this browser has outstanding, so
      // the reply is placed rather than dropped.
      const wanted = named
        ? [named]
        : ['chat_msg', 'keypair_bundle_store', 'keypair_bundle_delete'];
      for (const want of wanted) {
        for (const [, handler] of this._pending) {
          if (handler._reqType === want) { handler.resolve(msg); return; }
        }
      }
      console.warn('[MeshBay] ack (detail=', msg.detail, ') with nothing waiting');
      return;
    }

    // Everything above is routed by something in the message. What is left is
    // matched by arrival order, which is only ever a guess — and a wrong guess
    // here hands one request's answer to another, which then waits for a reply
    // that already came. Logged so that guess is visible.
    const oldest = this._pending.entries().next();
    if (!oldest.done) {
      const [, handler] = oldest.value;
      if (msg.type !== handler._reqType + '_resp' && handler._reqType !== 'index_sync') {
        console.warn('[MeshBay] unrouted', msg.type,
                     '-> oldest pending', handler._reqType,
                     '(pending:', this._pending.size, ')');
      }
      handler.resolve(msg);
    } else {
      console.warn('[MeshBay] unrouted', msg.type, 'with nothing waiting');
    }
  }
}

// ── Minimal msgpack encode/decode ────────────────────────────────────────────
// Covers the subset used by MNP: maps, strings, integers, binary, arrays, null.

function msgpack_encode(obj) {
  const parts = [];
  _encodeValue(obj, parts);
  const total = parts.reduce((s, p) => s + p.length, 0);
  const result = new Uint8Array(total);
  let off = 0;
  for (const p of parts) { result.set(p, off); off += p.length; }
  return result;
}

function _encodeValue(val, parts) {
  if (val === null || val === undefined) {
    parts.push(new Uint8Array([0xc0]));
  } else if (typeof val === 'boolean') {
    parts.push(new Uint8Array([val ? 0xc3 : 0xc2]));
  } else if (typeof val === 'number') {
    if (Number.isInteger(val)) {
      if (val >= 0 && val <= 127) {
        parts.push(new Uint8Array([val]));
      } else if (val >= 0 && val <= 0xff) {
        parts.push(new Uint8Array([0xcc, val]));
      } else if (val >= 0 && val <= 0xffff) {
        const b = new Uint8Array(3); b[0] = 0xcd;
        new DataView(b.buffer).setUint16(1, val, false);
        parts.push(b);
      } else if (val >= 0 && val <= 0xffffffff) {
        const b = new Uint8Array(5); b[0] = 0xce;
        new DataView(b.buffer).setUint32(1, val, false);
        parts.push(b);
      } else if (val >= 0 && val <= Number.MAX_SAFE_INTEGER) {
        // Same split as the 0xcf decoder case above, in reverse — without
        // this, a value over 0xffffffff fell to the plain int32 branch
        // below and silently wrapped to a wrong, unrelated number instead
        // of failing loudly.
        const b = new Uint8Array(9); b[0] = 0xcf;
        const dv = new DataView(b.buffer);
        dv.setUint32(1, Math.floor(val / 4294967296), false);
        dv.setUint32(5, val % 4294967296, false);
        parts.push(b);
      } else if (val >= -32 && val < 0) {
        parts.push(new Uint8Array([val & 0xff]));
      } else if (val >= -128 && val < 0) {
        const b = new Uint8Array(2); b[0] = 0xd0; b[1] = val & 0xff;
        parts.push(b);
      } else {
        const b = new Uint8Array(5); b[0] = 0xd2;
        new DataView(b.buffer).setInt32(1, val, false);
        parts.push(b);
      }
    } else {
      const b = new Uint8Array(9); b[0] = 0xcb;
      new DataView(b.buffer).setFloat64(1, val, false);
      parts.push(b);
    }
  } else if (typeof val === 'string') {
    const encoded = new TextEncoder().encode(val);
    if (encoded.length <= 31) {
      parts.push(new Uint8Array([0xa0 | encoded.length]));
    } else if (encoded.length <= 0xff) {
      parts.push(new Uint8Array([0xd9, encoded.length]));
    } else if (encoded.length <= 0xffff) {
      const b = new Uint8Array(3); b[0] = 0xda;
      new DataView(b.buffer).setUint16(1, encoded.length, false);
      parts.push(b);
    } else {
      const b = new Uint8Array(5); b[0] = 0xdb;
      new DataView(b.buffer).setUint32(1, encoded.length, false);
      parts.push(b);
    }
    parts.push(encoded);
  } else if (val instanceof Uint8Array) {
    if (val.length <= 0xff) {
      parts.push(new Uint8Array([0xc4, val.length]));
    } else if (val.length <= 0xffff) {
      const b = new Uint8Array(3); b[0] = 0xc5;
      new DataView(b.buffer).setUint16(1, val.length, false);
      parts.push(b);
    } else {
      const b = new Uint8Array(5); b[0] = 0xc6;
      new DataView(b.buffer).setUint32(1, val.length, false);
      parts.push(b);
    }
    parts.push(val);
  } else if (Array.isArray(val)) {
    if (val.length <= 15) {
      parts.push(new Uint8Array([0x90 | val.length]));
    } else if (val.length <= 0xffff) {
      const b = new Uint8Array(3); b[0] = 0xdc;
      new DataView(b.buffer).setUint16(1, val.length, false);
      parts.push(b);
    } else {
      const b = new Uint8Array(5); b[0] = 0xdd;
      new DataView(b.buffer).setUint32(1, val.length, false);
      parts.push(b);
    }
    for (const item of val) _encodeValue(item, parts);
  } else if (typeof val === 'object') {
    const keys = Object.keys(val);
    if (keys.length <= 15) {
      parts.push(new Uint8Array([0x80 | keys.length]));
    } else if (keys.length <= 0xffff) {
      const b = new Uint8Array(3); b[0] = 0xde;
      new DataView(b.buffer).setUint16(1, keys.length, false);
      parts.push(b);
    } else {
      const b = new Uint8Array(5); b[0] = 0xdf;
      new DataView(b.buffer).setUint32(1, keys.length, false);
      parts.push(b);
    }
    for (const k of keys) {
      _encodeValue(k, parts);
      _encodeValue(val[k], parts);
    }
  }
}

function msgpack_decode(buf) {
  const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
  const [val] = _decodeValue(buf, view, 0);
  return val;
}

function _decodeValue(buf, view, offset) {
  const byte = buf[offset];

  if (byte <= 0x7f) return [byte, offset + 1];
  if ((byte & 0xe0) === 0xe0) return [byte - 256, offset + 1];
  if ((byte & 0xa0) === 0xa0) {
    const len = byte & 0x1f;
    return [new TextDecoder().decode(buf.slice(offset + 1, offset + 1 + len)), offset + 1 + len];
  }
  if ((byte & 0xf0) === 0x90) {
    const len = byte & 0x0f;
    return _decodeArray(buf, view, offset + 1, len);
  }
  if ((byte & 0xf0) === 0x80) {
    const len = byte & 0x0f;
    return _decodeMap(buf, view, offset + 1, len);
  }

  switch (byte) {
    case 0xc0: return [null, offset + 1];
    case 0xc2: return [false, offset + 1];
    case 0xc3: return [true, offset + 1];
    case 0xc4: { const len = buf[offset + 1]; return [buf.slice(offset + 2, offset + 2 + len), offset + 2 + len]; }
    case 0xc5: { const len = view.getUint16(offset + 1, false); return [buf.slice(offset + 3, offset + 3 + len), offset + 3 + len]; }
    case 0xc6: { const len = view.getUint32(offset + 1, false); return [buf.slice(offset + 5, offset + 5 + len), offset + 5 + len]; }
    case 0xcc: return [buf[offset + 1], offset + 2];
    case 0xcd: return [view.getUint16(offset + 1, false), offset + 3];
    case 0xce: return [view.getUint32(offset + 1, false), offset + 5];
    // uint64/int64 — never emitted by this file's own encoder (a JS number
    // above 0xffffffff falls to float64 there), but the node's real msgpack
    // library sends a plain uint64 for any Python int over ~4.3 billion, and
    // a raw byte count crosses that easily (found live: IndexProgress.
    // scanned_bytes/total_bytes in the handshake ack, indexer.py, for a
    // group whose total library size exceeds ~4 GB). Split into two 32-bit
    // halves rather than DataView's getBigUint64/getBigInt64 — a BigInt
    // would silently poison every arithmetic use of these fields elsewhere
    // (percentage math, comparisons) — and every real byte count fits in a
    // plain JS number well under Number.MAX_SAFE_INTEGER (2^53).
    case 0xcf: {
      const hi = view.getUint32(offset + 1, false);
      const lo = view.getUint32(offset + 5, false);
      return [hi * 4294967296 + lo, offset + 9];
    }
    case 0xd3: {
      const hi = view.getInt32(offset + 1, false);
      const lo = view.getUint32(offset + 5, false);
      return [hi * 4294967296 + lo, offset + 9];
    }
    case 0xcb: return [view.getFloat64(offset + 1, false), offset + 9];
    case 0xd0: return [view.getInt8(offset + 1), offset + 2];
    case 0xd1: return [view.getInt16(offset + 1, false), offset + 3];
    case 0xd2: return [view.getInt32(offset + 1, false), offset + 5];
    case 0xd9: {
      const len = buf[offset + 1];
      return [new TextDecoder().decode(buf.slice(offset + 2, offset + 2 + len)), offset + 2 + len];
    }
    case 0xda: {
      const len = view.getUint16(offset + 1, false);
      return [new TextDecoder().decode(buf.slice(offset + 3, offset + 3 + len)), offset + 3 + len];
    }
    case 0xdb: {
      const len = view.getUint32(offset + 1, false);
      return [new TextDecoder().decode(buf.slice(offset + 5, offset + 5 + len)), offset + 5 + len];
    }
    case 0xdc: { const len = view.getUint16(offset + 1, false); return _decodeArray(buf, view, offset + 3, len); }
    case 0xdd: { const len = view.getUint32(offset + 1, false); return _decodeArray(buf, view, offset + 5, len); }
    case 0xde: { const len = view.getUint16(offset + 1, false); return _decodeMap(buf, view, offset + 3, len); }
    case 0xdf: { const len = view.getUint32(offset + 1, false); return _decodeMap(buf, view, offset + 5, len); }
    default: throw new Error(`Unknown msgpack type: 0x${byte.toString(16)}`);
  }
}

function _decodeArray(buf, view, offset, count) {
  const arr = [];
  for (let i = 0; i < count; i++) {
    const [val, newOff] = _decodeValue(buf, view, offset);
    arr.push(val);
    offset = newOff;
  }
  return [arr, offset];
}

function _decodeMap(buf, view, offset, count) {
  const obj = {};
  for (let i = 0; i < count; i++) {
    const [key, off1] = _decodeValue(buf, view, offset);
    const [val, off2] = _decodeValue(buf, view, off1);
    obj[key] = val;
    offset = off2;
  }
  return [obj, offset];
}

function _b64decode(b64) {
  const binary = atob(b64);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
  return bytes;
}

function _extractDtlsFingerprint(sdp) {
  const match = sdp.match(/a=fingerprint:sha-256 ([0-9A-Fa-f:]+)/);
  if (!match) return new Uint8Array(0);
  const hex = match[1].replace(/:/g, '');
  const bytes = new Uint8Array(hex.length / 2);
  for (let i = 0; i < hex.length; i += 2)
    bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
  return bytes;
}

// ── Node identity pinning (11.5.8) ───────────────────────────────────────────

const NODE_PIN_PREFIX = 'mb_nodepin_';

/**
 * The node's half of the version range, from `handshake_challenge`.
 *
 * Mirrors meshbay_common/handshake.py::check_version(). A node that declares no
 * range at all is a node that predates negotiation — that is every 0.x node, and
 * none of them can serve a sealed index or a sealed ack — so it is refused here
 * rather than left to fail later as a message that will not open.
 */
function _checkNodeVersion(reply) {
  const parse = (v) => {
    const m = /^(\d+)\.(\d+)$/.exec(String(v || ''));
    return m ? [Number(m[1]), Number(m[2])] : null;
  };
  const cmp = (a, b) => (a[0] - b[0]) || (a[1] - b[1]);
  const fail = (reason, message) => {
    const e = new Error(message);
    e.reason = reason;
    throw e;
  };

  const theirs = parse(reply.v);
  if (!theirs) {
    fail('node_version_unreadable',
         'The node did not declare a readable protocol version.');
  }
  // No declared minimum means "only what I speak" — the correct reading of a
  // node from before this field existed.
  const theirMin = parse(reply.v_min) || theirs;
  if (cmp(theirs, parse(MNP_V_MIN)) < 0) {
    fail('node_too_old',
         'This node is running an older MeshBay than this page needs. '
         + 'Its operator has to update it.');
  }
  if (cmp(theirMin, parse(MNP_V)) > 0) {
    fail('client_too_old',
         'This page is older than the node it is talking to. '
         + 'Reload to pick up the current version.');
  }
}

function _checkNodePin(nodeId, nodePk) {
  if (!nodeId || !nodePk) return;
  const key = NODE_PIN_PREFIX + nodeId;

  let pinned = null;
  try { pinned = localStorage.getItem(key); } catch { return; }

  if (pinned === null) {
    try { localStorage.setItem(key, nodePk); } catch {}
    return;
  }
  if (pinned !== nodePk) {
    throw new Error(
      'This node\'s identity key has changed. That is expected only if its ' +
      'operator reinstalled the node — otherwise someone may be impersonating ' +
      'it. Verify with the operator out of band, then clear the pin in ' +
      'Settings to accept the new key.');
  }
}

/** Forget a pinned node identity — the deliberate escape hatch for a legitimate rotation. */
function clearNodePin(nodeId) {
  try {
    if (nodeId) localStorage.removeItem(NODE_PIN_PREFIX + nodeId);
    else {
      for (const k of Object.keys(localStorage))
        if (k.startsWith(NODE_PIN_PREFIX)) localStorage.removeItem(k);
    }
  } catch {}
}

function pinnedNodeCount() {
  try {
    return Object.keys(localStorage).filter(k => k.startsWith(NODE_PIN_PREFIX)).length;
  } catch { return 0; }
}

// ── Passphrase change: re-wrap every reachable identity bundle ───────────────
//
// docs/auth-confirm.md §3.2. The passphrase-derived bundle_key encrypts this
// account's per-node identity on every node it has joined. Changing the
// passphrase changes that key, so each bundle must be read with the old key and
// written back with the new one — on the node, while both keys are in hand.
//
// The reachable set is the online nodes of the account's current groups. A node
// that is offline, or belongs to a group left since, cannot be reached here and
// is reported so the caller can tell the user to ask that group's operator to
// unpin them and issue a fresh code (§3.4).

function _acHubFetch(hubUrl, path, init) {
  const p = typeof window !== 'undefined' && window.MeshBayPlatform;
  const url = (hubUrl || '') + path;
  return (p && p.apiFetch) ? p.apiFetch(url, init) : fetch(url, init);
}

async function _acHubGet(hubUrl, token, path) {
  const r = await _acHubFetch(hubUrl, path, {
    headers: { Authorization: `Bearer ${token}` },
  });
  if (!r.ok) throw new Error(`${path} → ${r.status}`);
  return r.json();
}

function _acWithTimeout(promise, ms, label) {
  let timer;
  return Promise.race([
    promise.finally(() => clearTimeout(timer)),
    new Promise((_, rej) => {
      timer = setTimeout(() => rej(new Error(`${label} timed out`)), ms);
    }),
  ]);
}

/**
 * @param {object} o
 * @param {string} o.hubUrl        same base the SPA uses for the hub
 * @param {string} o.token         a fresh access token
 * @param {string} o.username
 * @param {string} o.userId
 * @param {string} [o.oldPassphrase]  omit in Flow B — connect falls back to the recovery copy
 * @param {string} o.newPassphrase
 * @param {string} [o.recoveryKey]   the recovery mnemonic (Flow B, docs/auth-confirm.md §4.5).
 *                                   When given, the recovery-wrapped copy is read where the
 *                                   passphrase copy cannot be, and a fresh one is written back.
 * @param {(p:{done:number,total:number})=>void} [o.onProgress]
 * @returns {Promise<{updated:Array,unreachable:Array,failed:Array,newBundleKey:object}>}
 */
async function rewrapAllNodes(o) {
  const K = window.MeshBayKeys;
  if (!K || !K.deriveEncryptionKey) {
    throw new Error('key module unavailable');
  }
  let oldKey, newKey;
  if (o.bundleKey) {
    // "Keep the current passphrase key, just add / refresh the recovery copy"
    // — the Profile backfill (docs/auth-confirm.md §4.3). `o.bundleKey` is the
    // live {v2,v1} session key, so no passphrase is needed.
    oldKey = newKey = o.bundleKey;
  } else {
    // Flow B has no old passphrase; connect will fail the passphrase decrypt and
    // fall back to the recovery copy, so a placeholder key is fine for `oldKey`.
    const oldPass = o.oldPassphrase || o.newPassphrase;
    oldKey = {
      v2: await K.deriveEncryptionKey(oldPass, o.username),
      v1: await K.deriveEncryptionKeyV1(oldPass, o.username),
    };
    newKey = {
      v2: await K.deriveEncryptionKey(o.newPassphrase, o.username),
      v1: await K.deriveEncryptionKeyV1(o.newPassphrase, o.username),
    };
  }
  const recoveryKey = o.recoveryKey
    ? await K.deriveRecoveryKey(o.recoveryKey, o.username)
    : null;

  const mine = await _acHubGet(o.hubUrl, o.token, '/v1/groups/mine');
  const groups = mine.groups || (Array.isArray(mine) ? mine : []);
  const updated = [], unreachable = [], failed = [];

  for (const g of groups) {
    const label = g.owner_username ? `${g.name}@${g.owner_username}` : g.name;
    let nodes = [];
    try {
      const nd = await _acHubGet(o.hubUrl, o.token, `/v1/groups/${g.id}/nodes`);
      nodes = nd.nodes || [];
    } catch (e) {
      failed.push({ groupId: g.id, name: label, reason: e.message });
      if (o.onProgress) o.onProgress({ done: updated.length + unreachable.length + failed.length, total: groups.length });
      continue;
    }
    if (nodes.length === 0) {
      unreachable.push({ groupId: g.id, name: label, reason: 'node offline' });
      if (o.onProgress) o.onProgress({ done: updated.length + unreachable.length + failed.length, total: groups.length });
      continue;
    }

    let anyOk = false, lastErr = null;
    for (const n of nodes) {
      const tp = new MeshBayTransport(o.hubUrl, o.token);
      // Recover the *existing* identity or report this node — never mint a new
      // one just because the stored bundle would not open.
      tp._rewrapOnly = true;
      try {
        await _acWithTimeout(
          tp.connect(n.node_id, o.token, g.id, null, null, oldKey,
                     o.username, o.userId, null, recoveryKey),
          30000, 'connect');
        if (tp.newNodeBundle) {
          // No identity existed on this node — connect just minted one under
          // the old key. Don't persist it: the next time this group is opened
          // the normal flow creates one under the current key, and storing it
          // here could also walk back a deliberate bundle withdrawal. Nothing
          // is stranded, so this node needs no fix.
          anyOk = true;
          continue;
        }
        const sk = tp.sessionKeys;
        if (!sk) { lastErr = new Error('identity not recovered'); continue; }
        const skEd = Uint8Array.from(atob(sk.skEdB64), c => c.charCodeAt(0));
        const skX = Uint8Array.from(atob(sk.skXB64), c => c.charCodeAt(0));
        const reEnc = await K.encryptBundleWithKey(skEd, skX, newKey.v2);
        // In Flow B, refresh the recovery copy too (same R) so the node's
        // passphrase copy and recovery copy stay in step.
        const reRecovery = recoveryKey
          ? await K.encryptBundleWithKey(skEd, skX, recoveryKey)
          : null;
        await tp.storeKeypairBundle(reEnc, reRecovery);
        anyOk = true;
      } catch (e) {
        lastErr = e;
      } finally {
        try { tp.close(); } catch { /* already gone */ }
      }
    }

    if (anyOk) updated.push({ groupId: g.id, name: label });
    else failed.push({ groupId: g.id, name: label,
                       reason: (lastErr && lastErr.message) || 'unreachable' });
    if (o.onProgress) o.onProgress({ done: updated.length + unreachable.length + failed.length, total: groups.length });
  }

  return { updated, unreachable, failed, newBundleKey: newKey };
}

// Export
MeshBayTransport.clearNodePin = clearNodePin;
MeshBayTransport.pinnedNodeCount = pinnedNodeCount;
MeshBayTransport.rewrapAllNodes = rewrapAllNodes;
window.MeshBayTransport = MeshBayTransport;