1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
|
/**
* 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;
// "Where am I?", asked as an ordinary sealed upload chunk with no bytes rather
// than on a clear message. Mirrors UPLOAD_PROBE_INDEX in
// meshbay_common/protocol.py; the node writes nothing and answers with
// `resume_from`, and one that predates it refuses the index, which reads as
// "start from the beginning".
const UPLOAD_PROBE_INDEX = -1;
// How long to wait for that answer before assuming there is none. A node that
// answers neither the probe nor its refusal must not leave an upload waiting
// for ever, and starting over is always safe.
const UPLOAD_PROBE_TIMEOUT_MS = 5000;
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 app_directories' slot,
// then that 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.
// Acks the node *broadcasts* to everyone in the group, which the requester
// therefore also has to be handed.
//
// `_dispatch` resolves an admin ack against the pending request and returns,
// which is right for an op whose caller already knows the value it chose. It is
// wrong for these: every *other* connected client learns the change from the
// broadcast, and the one that asked for it is the only one that does not,
// because its own request swallowed its copy. Found twice — first on the root
// table, then on Chat's directory, where it meant the pane went on showing an
// unsaved-looking draft after a save that had worked.
const BROADCAST_ACK_TYPES = new Set([
'root_update_ack', 'root_eject_ack', 'root_plug_ack',
'root_add_ack', 'root_remove_ack',
'app_directories_ack', 'chat_directory_ack', 'chat_link_preview_ack',
'chat_epoch_ack', 'search_listed_ack',
]);
/** Hand a broadcast ack to the callback that would have had it from a peer. */
function _replayBroadcast(transport, msg) {
if (msg.type === 'app_directories_ack' && transport._onAppDirectories) {
transport._onAppDirectories(msg.app, msg.directories || []);
} else if (msg.type === 'chat_directory_ack' && transport._onChatDirectory) {
transport._onChatDirectory(msg.path || '');
} else if (msg.type === 'chat_link_preview_ack' && transport._onChatLinkPreview) {
transport._onChatLinkPreview(Boolean(msg.enabled));
} else if (msg.type === 'search_listed_ack' && transport._onSearchListed) {
transport._onSearchListed(msg.listed !== false);
} else if (msg.type === 'chat_epoch_ack') {
transport._applyChatEpoch(msg);
} else if (transport._onRootsChanged) {
transport._onRootsChanged(msg);
}
}
const ADMIN_OP_TYPES = new Set([
'tmdb_override', 'tmdb_rematch', 'tmdb_config', 'tmdb_enabled',
'musicbrainz_enabled', 'file_delete', 'dir_delete',
'apps_enabled', 'set_scan_settings', 'member_revoke',
'root_add', 'root_remove', 'root_update', 'root_eject', 'root_plug',
'app_directories', 'chat_directory', 'chat_link_preview', 'chat_epoch',
'search_listed', '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,
// So a module that is not this one can write to the same buffer. The
// composer's own state is the half of the "chat hangs, the textbox is dead"
// report transport.js cannot see, and it belongs in the same timeline as the
// channel events it has to be read against.
record: trace,
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',
// Mozilla retired stun.services.mozilla.com; the name no longer resolves.
// Google + Cloudflare still cover a single-provider outage.
];
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 = '3.0';
// Raised with it on the 3.0 flag day. A node older than 3.0 cannot grant the
// lease this client opens for every download and upload, so talking to one
// would mean every transfer failing for a reason the person cannot act on.
// Refusing it at the handshake says so once, in a sentence.
const MNP_V_MIN = '3.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.',
// Surfaced only when it was the *last* node the hub offered for the group —
// group-page.js moves on to the next one on this code rather than stopping.
not_hosted: 'No node the hub offered for this group is hosting it. Its '
+ 'operator has to attach it on the node that holds its files.',
};
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.',
};
/**
* One transfer's slot on the node, from this side.
*
* The contract the transfer store depends on: `acquire()` resolves when the
* node has granted the slot (immediately on a node that hands out none), and
* `release(reason)` gives it back exactly once. Nothing else in the client
* speaks to the node about slots.
*
* Two things here exist only because a queue can lie, and both are the
* difference between "waiting" and "waiting for ever":
*
* - **the watchdog.** A grant is pushed, not polled, so a lost push leaves
* this side waiting on a node that believes it has started. Re-asking is
* free — the node is idempotent on `tr` — and it is the only thing that
* recovers a message that did not arrive.
* - **release is idempotent and unconditional.** A slot given back twice
* costs nothing; one never given back is a member who cannot transfer
* again until a timeout the node runs on its own.
*/
const LEASE_WATCHDOG_MS = 60000;
class Lease {
constructor(transport, tr, kind, bytes, chunks, onState) {
this.transport = transport;
this.tr = tr;
this.kind = kind;
this.bytes = bytes;
this.chunks = chunks;
this.state = 'opening';
this.ahead = 0;
this.closed = false;
this._onState = onState;
this._granted = null;
this._watchdog = 0;
this._wait = new Promise((resolve) => { this._granted = resolve; });
}
_request() {
// A closed channel is not a failure here, and must not throw: the transport
// reconnects on its own, `_reopenTransfers` re-asks for every live lease
// when it does, and the watchdog below asks again meanwhile.
//
// This is the same tolerance `_fetchChunkResilient` already gives a chunk
// request — and before leases existed, a chunk request was the first thing
// to touch the channel, so a download started on a briefly dead connection
// simply retried. Asking for a slot first made `_send` the first contact
// and threw "DataChannel not open (state: closed)" out of `downloadEntry`,
// where nothing catches it: a download that used to recover became an
// error with no row in the widget to show it. Found by downloading a file
// right after a connection dropped.
try {
this.transport._send({
type: 'transfer_open', v: '0.1', tr: this.tr, kind: this.kind,
bytes: this.bytes, chunks: this.chunks,
});
} catch (err) {
console.warn('[MeshBay] could not ask for a slot yet:', err.message);
}
this._arm();
}
_arm() {
clearTimeout(this._watchdog);
if (this.closed || this.state === 'granted') return;
this._watchdog = setTimeout(() => {
if (this.closed || this.state === 'granted') return;
console.warn('[MeshBay] no answer for transfer', this.tr.slice(0, 8),
'- asking again');
this._request();
}, LEASE_WATCHDOG_MS);
}
_apply(msg) {
if (this.closed) return;
this.state = msg.state;
this.ahead = msg.ahead || 0;
this.used = msg.used;
this.cap = msg.cap;
if (msg.state === 'granted') {
clearTimeout(this._watchdog);
this._granted();
} else if (msg.state === 'closed') {
// The node ended it: reclaimed as idle, or revoked. Not an error here —
// whoever is running the transfer finds out through its own failure — but
// the slot is gone and asking again is the only way back.
clearTimeout(this._watchdog);
} else {
this._arm();
}
if (this._onState) {
try { this._onState(this); } catch (e) {
console.error('[MeshBay] lease state handler threw:', e);
}
}
}
/** Resolves once the node has granted the slot. */
acquire() { return this._wait; }
/**
* Give the slot back. Safe to call twice, and safe on a dead transport: a
* lease that is not released is a member who cannot start another transfer
* until the node times it out, so this must never be conditional on anything.
*/
release(reason = 'done') {
if (this.closed) return;
this.closed = true;
clearTimeout(this._watchdog);
this.transport._leases.delete(this.tr);
try {
this.transport._send({ type: 'transfer_close', v: '0.1', tr: this.tr,
reason });
} catch { /* the connection is gone, and so is the lease with it */ }
}
}
class MeshBayTransport {
constructor(hubUrl, accessToken) {
this._hubUrl = hubUrl;
this._accessToken = accessToken;
this._pc = null;
this._channel = null;
this._pending = new Map();
// Set the first time this connection sees a reply that names the request
// it answers (see _dispatch). A node either stamps every reply or none,
// so one is proof for the connection — and once there is proof, the
// arrival-order fallback at the bottom of _dispatch is never right again.
this._correlates = false;
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;
// upload_id → the uploader waiting on it. Keyed rather than FIFO because
// several uploads may be in flight at once and their acks interleave.
//
// It was keyed by filename until MNP 2.0, which is no longer possible: the
// name is sealed under the group key, and echoing it in clear so the two
// sides could match on it would give back precisely what the seal is for.
// `upload_id` is drawn per upload here and is opaque to the node.
this._uploaders = new Map();
// Names, not ids: the "already being uploaded" guard is about the file the
// caller passed, and two `uploadFile` calls for one file draw two ids.
this._inFlightUploads = new Set();
// tr → Lease. A transfer's slot on the node, from the client's side.
this._leases = new Map();
// Set from the handshake ack: a node that answers with `transfer_limits`
// speaks transfer slots. Used instead of a timeout, because "no answer
// yet" and "this node will never answer" are indistinguishable in time and
// guessing wrong either stalls every download or defeats the cap.
this._transferLimits = null;
// 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;
// Which device key THIS connection has identified itself to the node with.
// Empty means "not identified": nothing can be sealed, so nothing can be
// posted to chat. Written only through _setDevicePk, which is what makes
// the change visible to a reader — see onDeviceIdentity.
this.devicePk = '';
this._onDeviceIdentity = 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 onRootsChanged(fn) { this._onRootsChanged = fn; }
/** The MNP version the connected node declared, or '' before a handshake. */
get nodeVersion() { return this._nodeVersion || ''; }
/** This member's own caps in this group, or null when the node said nothing. */
get transferLimits() { return this._transferLimits; }
set onAppsEnabled(fn) { this._onAppsEnabled = fn; }
set onAppDirectories(fn) { this._onAppDirectories = fn; }
set onChatDirectory(fn) { this._onChatDirectory = fn; }
set onChatLinkPreview(fn) { this._onChatLinkPreview = fn; }
set onSearchListed(fn) { this._onSearchListed = fn; }
set onChatEpoch(fn) { this._onChatEpoch = fn; }
set onTmdbConfig(fn) { this._onTmdbConfig = fn; }
set onTmdbEnabled(fn) { this._onTmdbEnabled = 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; }
/**
* Told whenever this connection's device identity changes — including to
* *nothing*, which is the case that mattered.
*
* `devicePk` is settled inside connect(), so a reconnect can clear it long
* after the page last rendered. A reader that computed "can I post?" from the
* field itself — chat-app.js did, through a ref — had no way to learn the
* answer had changed, and the composer stayed disabled on a connection with
* nothing whatever wrong with it and not one line in the console.
*/
set onDeviceIdentity(fn) { this._onDeviceIdentity = 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;
// The group this connection is for. Kept on the instance because the
// handshake is not the only thing that needs it any more: device_hello and
// the chat envelope both bind to it, and both run outside connect()'s scope.
this._groupId = groupId || '';
this._newNodeBundle = null;
this._newNodeBundleRecovery = null;
this._joinError = null;
// Per connection, for the same reason the chat keys and the roster are
// dropped further down: the device the *previous* connection identified
// itself with is not this one's, and leaving it standing is how a
// reconnect that never got as far as announcing a device still looked, to
// the composer, exactly like one that had.
this._setDevicePk('', 'new connection');
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();
};
});
// Marks it handled, and nothing else — `await channelReady` below still
// sees the rejection. Without it, a connect() that gives up earlier (at
// signaling, say) leaves this promise with nobody attached, and closing the
// peer connection then rejects it into an "Uncaught (in promise)
// DataChannel closed" on the console. Every failed reconnect attempt
// printed one, which is noise in exactly the log a freeze gets read from.
channelReady.catch(() => { /* the awaiter below reports it */ });
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);
// Kept for diagnostics only. Nothing branches on it: the range check
// above is what decides whether these two can talk at all, and a peer it
// admits speaks every message in this file.
this._nodeVersion = String(reply.v || '');
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);
this._transferLimits = ack.transfer_limits || null;
// From the *sealed* part of the ack: a forged epoch would have this
// client sealing under a key the group has retired.
this.chatEpoch = ack.chat_epoch || 0;
// Per connection: a reconnect may land on a node whose epoch has moved,
// and keeping a stale set would silently seal under a retired key.
this._chatKeys = null;
this._chatKeysInFlight = null;
this._roster = null;
this._rosterInFlight = null;
// Tell the node which of this account's devices is on this connection,
// after the ack and unconditionally: a peer `check_version` admitted
// speaks this message, and identifying the device is what makes chat
// possible at all.
await this._announceDevice().catch((e) => {
console.warn('[MeshBay] device_hello failed — chat will not work:', e);
});
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;
}
/**
* Record — and announce — the device key this connection is identified by.
*
* Every write to `devicePk` goes through here, for two reasons: it is traced,
* so a session that ends up unable to post says so and says when; and it
* tells the page, which had no other way to find out that the answer moved.
*/
_setDevicePk(pk, why) {
const next = pk || '';
if (next === this.devicePk) return next;
this.devicePk = next;
console.log('[MeshBay] device identity:',
next ? 'identified' : 'NOT identified — chat cannot post',
'(' + why + ')');
trace('device_identity', { identified: !!next, why });
if (this._onDeviceIdentity) {
try { this._onDeviceIdentity(!!next); } catch (e) {
console.error('[MeshBay] onDeviceIdentity handler threw:', e);
}
}
return next;
}
/**
* "This connection is device X of account Y", signed with the device key.
*
* Best effort by construction: a browser that has not recovered its identity
* keys has nothing to sign with. What it is *not* is silent — and it had
* three exits that were. Two early returns left whatever the previous
* connection had settled on standing; and a reply that is not
* `device_hello_ack` wiped the key without a word, because an `error` reply
* does not throw and so never reached the `.catch()` at the call site. The
* result is a chat that cannot post on a connection with nothing else wrong
* with it, which is unreadable from the outside — the shape of the "chat
* hangs, the textbox is dead" report. Every exit below names itself.
*/
async _announceDevice() {
if (!this._sessionKeys || !this._sessionKeys.skEdB64) {
return this._setDevicePk('', 'no identity key in this session');
}
if (!this._nonceNode || !this.nodePk || !this._userId) {
return this._setDevicePk('', 'handshake state incomplete');
}
const C = window.MeshBayCrypto;
// Derived from our own secret key, never read back from anywhere — the same
// rule as pairOperator: signing a public key someone handed us is the
// substitution this mechanism exists to close.
const pkEdB64 = await _pkEdFromSk(this._sessionKeys.skEdB64);
const ts = Math.floor(Date.now() / 1000);
const transcript = C.deviceHelloTranscript(
this.nodePk, this._groupId || '', this._userId, pkEdB64,
this._nonceNode, ts);
const sig = await window.MeshBayKeys.signBytes(
this._sessionKeys.skEdB64, transcript);
const resp = await this._sendAndWait({
type: 'device_hello', v: '2.0', pk_ed25519: pkEdB64, ts, sig,
});
if (!resp || resp.type !== 'device_hello_ack') {
return this._setDevicePk('', 'node answered ' + ((resp && resp.type) || 'nothing')
+ ((resp && resp.detail) ? ': ' + resp.detail : ''));
}
return this._setDevicePk(pkEdB64, 'device_hello_ack');
}
/**
* 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)');
// Before the caller's own hook: a transfer that resumes mid-chunk must
// have asked for its slot back first, or its next `file_req` carries a
// `tr` the node has never heard of.
this._reopenTransfers();
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;
}
// ── Transfer slots ─────────────────────────────────────────────────────────
/**
* Ask the node for a slot, and wait until it says yes.
*
* `tr` is drawn here, not by the node — 16 random bytes, exactly like
* `upload_id` — which is what makes re-opening after a reconnect idempotent
* rather than a second charge against the member's cap.
*
* On a node that predates transfer slots this resolves at once and costs
* nothing: there is no cap to respect and no message that would be
* understood.
*/
openTransfer({ kind = 'download', bytes = 0, chunks = 0, onState = null } = {}) {
const tr = _hex(crypto.getRandomValues(new Uint8Array(16)));
const lease = new Lease(this, tr, kind, bytes, chunks, onState);
this._leases.set(tr, lease);
lease._request();
return lease;
}
/** Re-ask for every live lease. Called after a reconnect. */
_reopenTransfers() {
for (const lease of this._leases.values()) {
// The node lost the lease with the session, so this is a fresh request
// for the same `tr` — which the node treats as the same transfer rather
// than a second one.
if (!lease.closed) lease._request();
}
}
async fetchChunk(fileId, chunkIndex, tr = '') {
const msg = await this._sendAndWait({
type: 'file_req',
v: '0.1',
file_id: fileId,
chunk_index: chunkIndex,
// Present only when this download holds a slot. The node does not require
// it yet; carrying it is what lets the node see the transfer is alive and
// not reclaim its slot as idle.
...(tr ? { tr } : {}),
});
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
* 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/updateRoot — 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 the rest — 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;
}
async setAppDirectories(appKey, directories, signFn) {
const clean = [...new Set(
(directories || []).map((d) => (d || '').replace(/^\/+|\/+$/g, '')).filter(Boolean),
)].sort();
const msg = await this._sendAndWait({
type: 'app_directories', v: '1.1', app: appKey, directories: clean,
});
if (msg.type === 'error') throw new Error(msg.detail);
if (msg.type === 'admin_challenge') {
return this._authorizeAdminOp(
msg, 'app_directories', `${appKey}:${clean.join(',')}`, signFn);
}
return msg;
}
/**
* Where chat attachments are written.
*
* Its own message rather than `setAppDirectories('chat', ...)`: this one is
* a destination, and the node refuses a read-only root for it. A caller
* reaching for the generic form would get a refusal it has no reason to
* expect, so the difference is in the name.
*/
async setChatDirectory(path, signFn) {
const clean = (path || '').replace(/^\/+|\/+$/g, '');
const msg = await this._sendAndWait({
type: 'chat_directory', v: '1.1', path: clean,
});
if (msg.type === 'error') throw new Error(msg.detail);
if (msg.type === 'admin_challenge') {
return this._authorizeAdminOp(msg, 'chat_directory', clean, signFn);
}
return msg;
}
/** Whether the node unfurls links members post in this group's chat. */
async setChatLinkPreview(enabled, signFn) {
const msg = await this._sendAndWait({
type: 'chat_link_preview', v: '1.1', enabled: Boolean(enabled),
});
if (msg.type === 'error') throw new Error(msg.detail);
if (msg.type === 'admin_challenge') {
return this._authorizeAdminOp(
msg, 'chat_link_preview', enabled ? 'on' : 'off', signFn);
}
return msg;
}
/**
* Whether this group's files appear in members' cross-group Search.
* Presentation only — opening the group lists everything regardless.
*/
async setSearchListed(listed, signFn) {
const msg = await this._sendAndWait({
type: 'search_listed', v: '3.0', listed: Boolean(listed),
});
if (msg.type === 'error') throw new Error(msg.detail);
if (msg.type === 'admin_challenge') {
return this._authorizeAdminOp(
msg, 'search_listed', listed ? 'on' : 'off', signFn);
}
return msg;
}
/**
* Open a new chat epoch by hand. Operator only, and signed.
*
* Not a switch — there is nothing to turn on. The removals that matter open
* an epoch by themselves; this is the operator saying "move the key anyway",
* the same instruction as `rotateGek` and signed for the same reason.
*/
async rotateChatEpoch(signFn) {
// This connection's own group, not a parameter. Every settings pane takes
// the same props by design (`test_app_settings_plugin.py`), so reaching for
// a `groupId` here would make the loop that renders them conditional — and
// the transport already knows which group it is connected to.
const groupId = this._groupId || '';
const msg = await this._sendAndWait({
type: 'chat_epoch', v: '2.0', group_id: groupId,
});
if (msg.type === 'error') throw new Error(msg.detail);
if (msg.type === 'admin_challenge') {
return this._authorizeAdminOp(msg, 'chat_epoch', groupId, 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;
}
/**
* 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);
const rows = msg.messages || [];
const messages = [];
for (const row of rows) messages.push(await this._openChatMessage(row));
return { messages, hasMore: !!msg.has_more };
}
/**
* Turn one stored or relayed chat message into what the panel renders.
*
* **The one place that decides how a message is read.** Live messages and
* history arrive by different routes and used to be shaped at each of them;
* with a `format` column and more than one way to read a payload, two copies
* of that decision is two places to get it wrong, and the disagreement would
* show up only in history.
*
* `payload` is bytes on the wire now — the node stopped decoding it as UTF-8,
* which mangled anything that was not text. A message that cannot be read
* comes back marked rather than thrown away: a gap in a conversation the
* reader can see is honest, and silently dropping messages is not.
*/
async _openChatMessage(row) {
const base = {
id: row.id,
sender_id: row.sender_id,
sender_name: row.sender_name || '',
timestamp: row.timestamp,
thread_id: row.thread_id,
};
const format = row.format || 0;
if (format === 0) {
return { ...base, payload: _asText(row.payload) };
}
if (format !== 1) {
return { ...base, payload: '', unreadable: 'format' };
}
return this._openSealedChat(base, row);
}
/**
* 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);
}
/**
* Send one message, sealed under this group's current chat epoch key and
* signed with this device's key.
*
* There is no plaintext path. MNP 2.0 has no unencrypted chat and the node
* refuses one, so a fallback here could only ever produce a refusal the user
* cannot act on — and a client that quietly posted in clear into a group
* whose members believe their chat is encrypted is the downgrade the whole
* design is about not having.
*
* `sender_name` goes **inside** the envelope. On the wire it is a field any
* peer can set to anything, and the node caches it to render history — so
* display-name spoofing is free while chat is plaintext. Sealed and signed,
* it is as authenticated as the message it names.
*
* Refuses rather than falls back. A client that cannot seal must not quietly
* post in clear into a group whose members believe their chat is encrypted;
* the node refuses it too, and the two refusals agreeing is the point.
*/
async sendChat(text, iteration, threadId, senderName) {
const keys = await this.chatKeys();
const epoch = this.chatEpoch || keys.current;
const epochKey = keys.byEpoch.get(epoch);
if (!epochKey) throw new Error('No chat key for this group — reconnect');
if (!this.devicePk || !this._sessionKeys || !this._sessionKeys.skEdB64) {
throw new Error('This device is not identified to the node — reconnect');
}
const C = window.MeshBayCrypto;
const gid = this._groupId || '';
const plaintext = msgpack_encode({
text: String(text),
thread_id: threadId || null,
sender_name: senderName || '',
sent_at: Math.floor(Date.now() / 1000),
});
const { nonce, ct } = await C.sealChat(
epochKey, gid, epoch, this.devicePk, plaintext);
const device = C.b64decode(this.devicePk);
const sig = C.b64decode(await window.MeshBayKeys.signBytes(
this._sessionKeys.skEdB64,
C.chatSigningTranscript(gid, epoch, device, nonce, ct)));
const msg = await this._sendAndWait({
type: 'chat_msg',
v: '2.0',
format: 1,
epoch,
ct,
nonce,
device,
sig,
thread_id: threadId || null,
// Deliberately absent: the display name is inside the envelope now.
sender_name: null,
});
// Every other request in this file refuses an `error` reply; this one
// returned it as though the node had accepted the message. It never
// mattered while a refusal reached the wrong caller anyway — now that a
// reply finds the request that made it, a message the node rejected would
// otherwise appear in the conversation as sent. It rejects more of them
// than it used to: a stale epoch, an envelope the node dislikes, or a
// device claim that is not this connection's all come back as `error`.
if (msg.type === 'error') throw new Error(msg.detail || 'chat send refused');
return msg;
}
/**
* This group's chat epoch moved.
*
* An epoch opens when somebody is removed, and a client that kept sealing
* under the retired key would be writing messages the group can still read
* but that the removed member could read too. Dropping the cached keys is
* what makes the next send fetch the new one.
*/
_applyChatEpoch(msg) {
if (msg.epoch) this.chatEpoch = msg.epoch;
this._chatKeys = null;
this._chatKeysInFlight = null;
if (this._onChatEpoch) this._onChatEpoch(this.chatEpoch);
}
/**
* Who is in this group and which device keys they hold — verified here, not
* taken on the node's word.
*
* Tier 2 of `desktop-client-v1.md` §4.8. The node relays, for each device,
* the already-pinned key that countersigned it and the signature itself; this
* walks that from each account's first device outwards and keeps only the
* devices it could actually reach. A device the node asserts but cannot
* evidence is reported as unverified rather than dropped — the reader is
* shown a gap, never a silent absence.
*
* The property this buys, stated exactly: once a client has seen an account,
* a node that later substitutes a key for it is **detected**. It buys nothing
* at first sight, where there is nothing to compare against — that boundary
* is `per-node-identity-v1.md`'s and does not move.
*/
async groupRoster() {
if (this._roster) return this._roster;
if (this._rosterInFlight) return this._rosterInFlight;
this._rosterInFlight = (async () => {
const resp = await this._sendAndWait({
type: 'group_roster_req', v: '2.0', group_id: this._groupId || '',
});
if (resp.type === 'error') throw new Error(resp.detail);
const payload = msgpack_decode(await window.MeshBayCrypto.openGroup(
this._gekRaw, 'roster', 'group_roster_resp', this._groupId || '', resp));
this._roster = await _verifyRoster(payload, this.nodePk);
return this._roster;
})();
try {
return await this._rosterInFlight;
} finally {
this._rosterInFlight = null;
}
}
/**
* How this client regards `devicePk` as a device of `userId`.
*
* 'pinned' seen before, and the same key — nothing to say
* 'linked' new, and countersigned by a key already pinned for it
* 'first' first sight of this account: trust on first use
* 'changed' a key this account has not shown before and cannot evidence
*
* Only `changed` is worth a person's attention, and it is the one notice
* §4.8 budgets for. `first` is not an alarm — every account is new once, and
* treating that as a warning is how a warning stops being read.
*/
async accountDeviceStatus(userId, devicePk) {
let roster;
try {
roster = await this.groupRoster();
} catch {
return 'unknown';
}
const known = await _readPinnedAccount(this.nodePk, userId);
const entry = roster.byAccount.get(userId);
if (known && known.includes(devicePk)) return 'pinned';
if (!known) {
// First sight, so **everything the node says** is pinned — not only what
// a chain reaches. There is nothing to compare against yet: that is what
// trust-on-first-use means, and pinning only the verified subset would
// raise "key changed" on a legitimate second device whose
// countersignature simply predates it being kept. What TOFU buys is that
// a substitution *later* is visible; it cannot buy anything now.
if (entry) await _writePinnedAccount(this.nodePk, userId, entry.all);
return entry && entry.all.includes(devicePk) ? 'first' : 'changed';
}
if (entry && entry.verified.includes(devicePk)
&& entry.chain.get(devicePk)
&& known.includes(entry.chain.get(devicePk))) {
// Countersigned by a key we already trust for this account: a second
// device of someone we know, admitted without anybody comparing digits.
await _writePinnedAccount(this.nodePk, userId,
[...new Set([...known, devicePk])]);
return 'linked';
}
return 'changed';
}
/**
* Every chat epoch key for this group, fetched once per connection.
*
* Every epoch, not just the current one — that is what lets a device linked
* this morning read a conversation from last year, and a member who joined
* yesterday read the history the group already had. The node decides which
* epochs a member is entitled to; this asks for what it is given.
*/
async chatKeys() {
if (this._chatKeys) return this._chatKeys;
if (this._chatKeysInFlight) return this._chatKeysInFlight;
this._chatKeysInFlight = (async () => {
const resp = await this._sendAndWait({
type: 'chat_keys_req', v: '2.0', group_id: this._groupId || '',
});
if (resp.type === 'error') throw new Error(resp.detail);
// Sealed under a group-derived subkey. A payload that does not open is
// not "no keys" — it is a peer we cannot talk to, and treating it as an
// empty set would present an encrypted group as one with no history.
const payload = msgpack_decode(await window.MeshBayCrypto.openGroup(
this._gekRaw, 'chat_keys', 'chat_keys_resp', this._groupId || '', resp));
const byEpoch = new Map();
for (const e of payload.epochs || []) byEpoch.set(e.epoch, e.key);
this._chatKeys = { byEpoch, current: payload.current || 0 };
return this._chatKeys;
})();
try {
return await this._chatKeysInFlight;
} finally {
this._chatKeysInFlight = null;
}
}
/**
* Open one sealed message, or mark it unreadable and say why.
*
* Authorship is established **before** decryption: the signature is over the
* ciphertext, so a message that does not verify is never rendered as having
* been written by the account it claims — which is the whole point of signing
* rather than trusting the node's `sender_id`.
*
* An unreadable message is kept and marked, never dropped. A gap the reader
* can see is honest; a conversation quietly missing messages is not.
*/
async _openSealedChat(base, row) {
const C = window.MeshBayCrypto;
const gid = this._groupId || '';
const epoch = row.epoch || 0;
const device = row.device;
const nonce = row.nonce;
const ct = row.ct;
if (!device || !nonce || !ct || !row.sig) {
return { ...base, payload: '', unreadable: 'envelope' };
}
if (!await C.verifyChatSignature(device, gid, epoch, nonce, ct, row.sig)) {
return { ...base, payload: '', unreadable: 'signature' };
}
let keys;
try {
keys = await this.chatKeys();
} catch {
return { ...base, payload: '', unreadable: 'keys' };
}
const epochKey = keys.byEpoch.get(epoch);
if (!epochKey) return { ...base, payload: '', unreadable: 'epoch' };
const deviceB64 = C.b64encode(device);
try {
const plain = msgpack_decode(
await C.openChat(epochKey, gid, epoch, deviceB64, nonce, ct));
// The signature proves *a device* wrote this. Whether that device belongs
// to the account the node named is a separate question, and one this
// client answers for itself from the roster (Tier 2) rather than taking
// `sender_id` on trust. `changed` is the only value worth a notice.
const trust = await this.accountDeviceStatus(base.sender_id, deviceB64);
return {
...base,
payload: String(plain.text || ''),
sender_name: plain.sender_name || base.sender_name,
thread_id: plain.thread_id ?? base.thread_id,
device: deviceB64,
verified: true,
trust,
};
} catch {
return { ...base, payload: '', unreadable: 'decrypt' };
}
}
/**
* 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
// app_directories_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 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) {
// Files cannot be turned off — MNP permits root exploration regardless of
// this list, so hiding the tab only ever misled — and the node adds it if
// it is missing. That normalisation has to happen *here too*: the subject
// below is rebuilt from what this client sent, and compared byte for byte
// against what the node put in the challenge. A list arriving here without
// `files` would produce two different strings and `_authorizeAdminOp`
// would refuse to sign an op the operator did ask for. It is reachable
// only from a caller that builds the list from something other than the
// node's own answer, which is exactly the kind of caller a later phase
// adds. (`apps.js` marks it `alwaysEnabled`; this file is a classic
// script and cannot import it.)
const full = apps.includes('files') ? [...apps] : ['files', ...apps];
const msg = await this._sendAndWait({
type: 'apps_enabled', v: '0.1', apps: full,
});
if (msg.type === 'error') throw new Error(msg.detail);
if (msg.type === 'admin_challenge') {
return this._authorizeAdminOp(
msg, 'apps_enabled', [...full].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, writable, removable } = {}, signFn) {
const msg = await this._sendAndWait({
type: 'root_add', v: '1.1',
group_id: groupId, path,
name: name || '', kind: kind || 'generic',
writable: !!writable, removable: !!removable,
});
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 updateRoot(groupId, rootName, { writable, removable } = {}, signFn) {
const updates = [];
if (writable !== undefined) updates.push(`rw=${writable ? 'on' : 'off'}`);
if (removable !== undefined) updates.push(`rem=${removable ? 'on' : 'off'}`);
const subject = updates.length ? `${rootName}:${updates.join(',')}` : rootName;
const msg = await this._sendAndWait({
type: 'root_update', v: '1.1',
group_id: groupId, root_name: rootName,
...(writable !== undefined && { writable }),
...(removable !== undefined && { removable }),
});
if (msg.type === 'error') throw new Error(msg.detail);
if (msg.type === 'admin_challenge') {
return this._authorizeAdminOp(msg, 'root_update', subject, signFn);
}
return msg;
}
async ejectRoot(groupId, rootName, signFn) {
const msg = await this._sendAndWait({
type: 'root_eject', v: '1.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_eject', rootName, signFn);
}
return msg;
}
async plugRoot(groupId, rootName, signFn) {
const msg = await this._sendAndWait({
type: 'root_plug', v: '1.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_plug', 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.
*
* `dir` names the folder to upload into, as a virtual path
* (`Media/Films/1999`) — where the sender is actually looking. The node
* resolves it against the group's own roots, which refuses `..`, absolute
* segments and anything escaping its root; it is a place among the group's
* folders, never a path on the operator's filesystem.
*
* `root` is the older, coarser form: the root's name and nothing below it.
* Kept because a node that predates `dir` reads it, and because Chat has no
* folder on screen to name. Omitting both leaves the node to pick, which it
* only does for a client old enough to have had one destination.
*/
async uploadFile(file, { chunkSize, onProgress, signal, root, dir,
tr = '' } = {}) {
// 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. The guard
// is by name for that reason, even though the map below is keyed by id.
if (this._inFlightUploads.has(file.name)) {
throw new Error(`${file.name} is already being uploaded`);
}
if (!this._gekRaw) throw new Error('This group has no key on this device');
const C = window.MeshBayCrypto;
const groupId = (this._connectArgs && this._connectArgs.groupId) || '';
this._inFlightUploads.add(file.name);
const uploadId = _hex(crypto.getRandomValues(new Uint8Array(16)));
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 = [];
const wake = () => {
acked += 1;
if (onProgress) onProgress(Math.min(file.size, acked * size), file.size);
const waiter = acks.shift();
if (waiter) waiter();
};
// "Where am I?" — resolved by the node's answer to the probe chunk below,
// or by anything that says this node cannot answer it.
let settleProbe = null;
const probed = new Promise((r) => { settleProbe = r; });
const answerProbe = (from) => {
if (!settleProbe) return false;
const done = settleProbe;
settleProbe = null;
done(from);
return true;
};
this._uploaders.set(uploadId, (msg) => {
if (msg.type === 'error') {
// A node that predates the probe refuses its index. That is not a
// failure — it is the answer "start from the beginning", which is what
// this client did before there was anything to ask.
if (answerProbe(0)) return;
failure = new Error(msg.detail || 'Upload refused');
wake();
return;
}
// The ack is sealed too — `stored_as` and the folder it landed in name
// the operator's content. Opening it is what makes the result usable, so
// a failure here fails the upload rather than being swallowed: a chat
// attachment that cannot learn its stored name would point at nothing.
C.openGroup(this._gekRaw, 'upload', 'file_upload_ack', groupId, msg)
.then((plain) => {
const payload = msgpack_decode(plain);
if (payload.stored_as) stored = payload;
// Only the probe's answer carries this, so the two are told apart
// without trusting the index the node echoed back in clear.
if (typeof payload.resume_from === 'number') return answerProbe(payload.resume_from);
return false;
})
.catch((e) => {
failure = new Error(
`The node's upload reply did not open under the group key (${e.message})`);
return false;
})
// A probe's answer is not a chunk: waking here would credit the
// progress bar with a chunk that was never sent.
.then((wasProbe) => { if (!wasProbe) wake(); });
});
const nextAck = () => new Promise(r => acks.push(r));
try {
// Ask before sending anything. An upload interrupted at 99% used to start
// again from zero, because the node kept its position on the connection
// that was lost — see `uploads.py`. The question goes inside the seal, as
// a chunk with no bytes, because naming the file on a clear message is
// exactly what sealing this path was for.
// Sealed first, spread second — the same shape as the chunk loop below,
// and not only for symmetry: `test_the_upload_itself_is_sealed` reads
// this call and fails if a filename appears in it, which is how it can
// tell a field outside the seal from one inside it.
const probeSealed = await C.sealGroup(
this._gekRaw, 'upload', 'file_upload', groupId,
msgpack_encode({ filename: file.name, data: new Uint8Array(0),
dir: dir || '', root: root || '' }));
this._send({
type: 'file_upload',
v: '0.1',
upload_id: uploadId,
chunk_index: UPLOAD_PROBE_INDEX,
total_chunks: total,
...(tr ? { tr } : {}),
...probeSealed,
});
// Bounded: a node that answers neither the probe nor its refusal must not
// leave an upload waiting for ever. Starting over is always safe.
let from = await Promise.race([
probed,
new Promise((r) => setTimeout(() => { answerProbe(0); r(0); },
UPLOAD_PROBE_TIMEOUT_MS)),
]);
// Defensive: a node reporting a position at or past the end would have
// renamed the file and dropped its state, so this cannot happen — and if
// it does, sending everything again is the answer that cannot corrupt.
if (!(from > 0) || from >= total) from = 0;
if (from > 0) {
acked = from;
if (onProgress) onProgress(Math.min(file.size, from * size), file.size);
}
for (let i = from; i < total; i++) {
if (signal && signal.aborted) throw _aborted();
// Between two chunks, never inside one — the node refuses a chunk that
// is not the one it expects, so a position is the only thing worth
// remembering. Nothing is recorded here beyond that: the node holds the
// real position, and the probe above is what asks for it on the way
// back in, which makes resuming correct even across a reconnect.
if (signal && signal.paused) {
signal.resumeFrom = i;
const paused = new Error('Paused');
paused.name = 'PausedError';
throw paused;
}
// 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());
// The name, the destination and the bytes go inside the seal together.
// Mirrors `file_upload_wire` in meshbay_common/protocol.py; only the
// fields the node routes on stay outside it.
const sealed = await C.sealGroup(
this._gekRaw, 'upload', 'file_upload', groupId,
msgpack_encode({ filename: file.name, data: buf,
dir: dir || '', root: root || '' }));
this._send({
type: 'file_upload',
v: '0.1',
upload_id: uploadId,
chunk_index: i,
total_chunks: total,
...(tr ? { tr } : {}),
...sealed,
});
}
while (acked < total) {
await nextAck();
if (failure) throw failure;
}
} finally {
this._uploaders.delete(uploadId);
this._inFlightUploads.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);
// The node's first push to a newly connected peer is an index_sync
// nobody asked for, so there is not always a request to resolve. When
// there is, `req_id` says which one — the type match below is what a
// node too old to stamp one leaves us, and it is why two fetches in
// flight at once used to resolve the wrong one.
const handler = opened.req_id !== undefined && opened.req_id !== null
? this._pending.get(opened.req_id)
: [...this._pending.values()].find(h => h._reqType === 'index_sync');
if (handler) handler.resolve(opened);
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); },
});
// The id goes on the wire (MNP 1.1+): a node that understands it stamps
// the reply with it, and _dispatch matches on that alone. It used to be
// local to this map, which is why every reply had to be recognised by
// some field of its own — and why the ones that carry no such field
// reached their caller by luck. An older node ignores the extra key and
// is routed by the per-type fallbacks below, exactly as before.
// `_send` throws synchronously when the channel is not open. Rejecting
// on that is right, but the pending entry and its 30s timer were left
// behind — so a request that never reached the wire still logged a
// "Response timeout" half a minute later, for a reply nobody was owed.
try {
this._send({ ...obj, req_id: id });
} catch (e) {
clearTimeout(timeout);
this._pending.delete(id);
reject(e);
}
});
}
_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) {
// A reply that names the request it answers. Nothing below this needs to
// recognise it, and nothing below this may see it: every remaining branch
// exists to identify a reply by some field of its own, which is the job
// this makes unnecessary.
//
// What is left underneath is genuinely unsolicited — a broadcast to every
// connected client, a push, a challenge — or a reply from a node too old
// to stamp one, which is what the per-type keys are for now.
if (msg.req_id !== undefined && msg.req_id !== null) {
this._correlates = true;
// The one exception, and the only one: an index message is sealed under
// the GEK and cannot be handed to its caller until it is opened, which
// is not something this synchronous function can do. Resolving it here
// would give `fetchIndex` the envelope — nonce and ciphertext, no
// entries — and skip `_onIndexSync` entirely. `_queueIndexMessage`
// opens it and then resolves, by this same id.
const sealed = msg.type === 'index_sync' || msg.type === 'index_delta';
if (!sealed) {
const handler = this._pending.get(msg.req_id);
if (handler) {
handler.resolve(msg);
// The acks whose *broadcast* half their own requester also needs:
// every other client learns the change from the broadcast, and the
// one that asked for it is the only one that would not, because its
// own request swallowed its copy. Same call the keyed `_ack` branch
// below makes, for the same reason.
if (BROADCAST_ACK_TYPES.has(msg.type)) _replayBroadcast(this, msg);
return;
}
// Answers a request that is no longer waiting: it gave up at its own
// timeout, or a reconnect rejected everything in flight. It belongs to
// nobody, and the whole point of this change is that it is not offered
// to somebody else instead.
console.warn('[MeshBay] late reply to req', msg.req_id, '(', msg.type,
') — nothing waiting');
return;
}
}
// 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/setAppDirectories/... 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);
// The comment above ("its own caller already updates local state
// from what it sent") is true of every op whose caller passes the
// value it just chose to an onX(next). The root ops are not like
// that: what changes is the whole roots table, which only the node
// can compute — availability, the eject that the plug refused, the
// name it settled on. Returning here left the operator who clicked
// Eject as the one client that never saw it happen, while every
// other peer got the broadcast. So this one type is handed on.
if (BROADCAST_ACK_TYPES.has(msg.type)) _replayBroadcast(this, 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.upload_id)) {
this._uploaders.get(msg.upload_id)(msg);
return;
}
// An upload refusal names the upload 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
// refusal that names none, where guessing wrong is worse than stopping.
if (msg.type === 'error' && this._uploaders.size) {
if (msg.upload_id && this._uploaders.has(msg.upload_id)) {
this._uploaders.get(msg.upload_id)(msg);
return;
}
if (!msg.upload_id) {
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) {
// Shaped through the same reader as history, and asynchronously — a live
// message and a stored one are the same message, and a second way of
// reading one is a second thing to get wrong.
this._openChatMessage(msg)
.then(m => { if (this._onChat) this._onChat(m); })
.catch(e => console.warn('[MeshBay] chat message unreadable', e));
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 which apps are shown, and everyone
// connected hears about it without reconnecting.
if (msg.type === 'apps_enabled_ack' && this._onAppsEnabled) {
this._onAppsEnabled(msg.apps || []);
}
// An application was pointed at different folders. One handler for every
// app — the callback is given the app's name and decides.
if (msg.type === 'app_directories_ack' && this._onAppDirectories) {
this._onAppDirectories(msg.app, msg.directories || []);
}
if (msg.type === 'chat_directory_ack' && this._onChatDirectory) {
this._onChatDirectory(msg.path || '');
}
if (msg.type === 'chat_link_preview_ack' && this._onChatLinkPreview) {
this._onChatLinkPreview(Boolean(msg.enabled));
}
if (msg.type === 'search_listed_ack' && this._onSearchListed) {
this._onSearchListed(msg.listed !== false);
}
if (msg.type === 'chat_epoch_ack') {
this._applyChatEpoch(msg);
return;
}
// 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: '' });
}
// Per-group, like tmdb_enabled_ack above.
if (msg.type === 'musicbrainz_enabled_ack' && this._onMusicbrainzEnabled) {
this._onMusicbrainzEnabled(Boolean(msg.enabled));
}
// A root's flags changed, or one was ejected, plugged, added or removed.
// Broadcast by the node to every peer, so everyone's table updates without
// waiting for the next index_sync.
if (msg.type === 'root_update_ack' || msg.type === 'root_eject_ack'
|| msg.type === 'root_plug_ack' || msg.type === 'root_add_ack'
|| msg.type === 'root_remove_ack') {
if (this._onRootsChanged) this._onRootsChanged(msg);
}
// 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.
// Routed by `tr`, and only by `tr`. A grant arrives unsolicited, minutes
// after the request that produced it, so falling through to "the oldest
// pending request" would hand a chat send or a handshake somebody else's
// slot — the class of defect `req_id` was introduced for.
if (msg.type === 'transfer_state') {
const lease = this._leases.get(msg.tr);
if (lease) lease._apply(msg);
else if (msg.state === 'granted') {
// A grant for a transfer this page has forgotten (a reload, a cancel
// that raced the grant). Handing it back at once matters: otherwise the
// node holds it until the 30 s acceptance deadline, and everyone behind
// it waits for nothing.
this._send({ type: 'transfer_close', v: '0.1', tr: msg.tr,
reason: 'cancelled' });
}
return;
}
if (msg.type === 'index_progress') {
if (this._onIndexProgress) {
// `kind`, `root_pos`, `queued` and the file counts are absent from a
// node older than the indexing dock; index-dock-model.js reads them
// missing as idle defaults.
this._onIndexProgress({
scanning: Boolean(msg.scanning),
scanned_bytes: msg.scanned_bytes || 0,
total_bytes: msg.total_bytes || 0,
files_done: msg.files_done || 0,
files_total: msg.files_total || 0,
kind: msg.kind || '',
root_pos: Number.isInteger(msg.root_pos) ? msg.root_pos : -1,
queued: Number.isInteger(msg.queued) ? msg.queued : 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;
}
// device_hello_ack ends in `_ack` but is not an admin op, so the admin
// branch looks it up under `admin:device_hello` and finds nothing. A 2.0
// node stamps `req_id` and this is never reached; it is the per-type key
// for a node that does not, alongside chat_hist_resp above.
if (msg.type === 'device_hello_ack') {
for (const [, handler] of this._pending) {
if (handler._reqType === 'device_hello') { handler.resolve(msg); return; }
}
console.warn('[MeshBay] device_hello_ack with no matching request');
return;
}
// Same shape as chat_hist_resp above, and found the same way — by driving
// the panel rather than by reading this file. Before `req_id` existed,
// `chat_keys_resp` fell to the arrival-order guess and was handed to
// whatever was oldest in `_pending`; `chat_send_probe.py` caught it on its
// first run, with the Videos tab's unanswered `media_meta_req` swallowing
// the chat keys and the send then waiting out its own 30s timeout with the
// composer disabled. `req_id` is what closes that class now, and this is
// the per-type key for a node that does not stamp one.
if (msg.type === 'chat_keys_resp') {
for (const [, handler] of this._pending) {
if (handler._reqType === 'chat_keys_req') { handler.resolve(msg); return; }
}
console.warn('[MeshBay] chat_keys_resp with no matching request');
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
// used to be matched by arrival order — a guess, and a wrong guess hands
// one request's answer to another, which then waits out its own 30s
// timeout for a reply that already came and went. That is how the Chat
// composer, disabled while a send is in flight, could stay disabled for
// thirty seconds on a message the node had already stored.
//
// A node that stamps its replies (`req_id`, handled at the top) has taken
// every one of its answers out of this path, so anything arriving here is
// unsolicited and the guess can only ever be wrong. Dropping it loses
// nothing and stops the theft.
if (this._correlates) {
console.warn('[MeshBay] unsolicited', msg.type, '— dropped (pending:',
this._pending.size, ')');
return;
}
// Only a node too old to stamp anything reaches here, where arrival order
// is still the only thing there is. Kept deliberately, and no wider than
// it was: the alternative for such a node is that half the protocol
// (device_list_result, join_result, the handshake's own replies) reaches
// nobody at all.
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');
}
}
}
/**
* Walk each account's devices outwards from the one nobody countersigned.
*
* A device is *verified* when a chain of real signatures reaches it from that
* account's root — the device an operator code admitted, which by definition
* has no countersignature and is the trust-on-first-use anchor. Anything the
* node lists but cannot evidence stays out of `verified`, so a substituted key
* is not laundered into the set merely by being mentioned.
*
* Devices pinned before the evidence was kept (2026-09-07) carry no signature
* and are treated exactly like a root: honest about what they are, rather than
* quietly accepted as verified.
*/
async function _verifyRoster(payload, nodePk) {
const C = window.MeshBayCrypto;
const byAccount = new Map();
const devices = payload.devices || [];
const per = new Map();
for (const d of devices) {
if (!per.has(d.user_id)) per.set(d.user_id, []);
per.get(d.user_id).push(d);
}
for (const [userId, list] of per) {
// Roots first: no countersigner, or one whose evidence was never stored.
const verified = [];
const chain = new Map();
const pending = [];
for (const d of list) {
// A root is a device that names **no** countersigner: an operator code
// admitted it, and there is nothing to verify.
//
// Naming one and carrying no proof is *not* a root, and treating it as
// one was a hole this file's tests caught: a node that writes the roster
// can put any key it likes in an account's row, and if "no signature"
// meant "root" it would have been laundered straight into `verified`.
// Such a device is unevidenced — which is also the honest reading of one
// pinned before the evidence was kept.
if (!d.added_by_pk) verified.push(d.pk_ed25519);
else pending.push(d);
}
// Then repeatedly admit anything countersigned by something already in.
let progress = true;
while (progress && pending.length) {
progress = false;
for (let i = pending.length - 1; i >= 0; i--) {
const d = pending[i];
if (!verified.includes(d.added_by_pk)) continue;
let ok = false;
try {
const transcript = C.deviceAddTranscript(
payload.node_pk || nodePk, userId, d.pk_ed25519, d.pk_x25519,
C.b64decode(d.add_nonce), d.add_ts);
ok = await C.verifyNodeSignature(d.added_by_pk, d.add_sig, transcript);
} catch { ok = false; }
if (ok) {
verified.push(d.pk_ed25519);
chain.set(d.pk_ed25519, d.added_by_pk);
pending.splice(i, 1);
progress = true;
}
}
}
byAccount.set(userId, {
username: (list[0] || {}).username || '',
all: list.map(d => d.pk_ed25519),
verified,
chain,
// Listed by the node and not reachable by any chain of signatures.
unevidenced: pending.map(d => d.pk_ed25519),
});
}
return { byAccount };
}
// Which device keys this browser has accepted for each account, per node.
// localStorage rather than a runtime capability: it is a per-viewer
// convenience whose loss costs one "first sight" and never a wrong answer —
// forgetting a pin makes the next key read as `first`, not as verified.
const _PIN_NS = 'meshbay_account_pins';
function _pinKey(nodePk, userId) {
return `${_PIN_NS}:${nodePk || ''}:${userId}`;
}
async function _readPinnedAccount(nodePk, userId) {
try {
const raw = localStorage.getItem(_pinKey(nodePk, userId));
return raw ? JSON.parse(raw) : null;
} catch { return null; }
}
async function _writePinnedAccount(nodePk, userId, keys) {
try {
localStorage.setItem(_pinKey(nodePk, userId), JSON.stringify(keys));
} catch { /* private window, or storage refused — one more "first sight" */ }
}
/**
* A wire payload as text.
*
* A plaintext message arrives as a string from the node; msgpack `bin` arrives
* as a Uint8Array. Both have to render.
*
* This function was deleted once, with an unrelated helper that sat next to it,
* and nothing complained: its only caller is inside `_openChatMessage`, whose
* rejection the chat panel swallows in a `.catch()` that just marks the page
* unloaded. The visible result was a conversation that rendered completely
* empty, with no error in the console and the node answering perfectly — found
* by `chat_send_probe.py`, not by reading this file.
*/
function _asText(payload) {
if (payload instanceof Uint8Array) return new TextDecoder().decode(payload);
if (payload == null) return '';
return String(payload);
}
// ── 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 _hex(bytes) {
return [...bytes].map(b => b.toString(16).padStart(2, '0')).join('');
}
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;
|