freenet 0.2.132

Freenet core software
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
function freenetBridge(authToken, userToken, hostedMode) {
  'use strict';
  var LOCAL_API_ORIGIN = location.origin;
  var MAX_CONNECTIONS = 32;
  var iframe = document.getElementById('app');
  var connections = new Map();
  var lastClipboard = 0;
  var lastDownload = 0;
  // Peer-restart recovery signal: the node closes a socket whose auth token is
  // stale (e.g. after a restart wiped its in-memory token map) with the trusted
  // WebSocket application close code 4401 (AUTH_TOKEN_INVALID_CLOSE_CODE in
  // client_events/websocket.rs; matched in isTrustedStaleTokenClose below). It
  // rides the close frame of a socket the shell opened to the node, so a
  // sandboxed contract cannot forge it. Recovery fires when the framed app
  // reopens its WebSocket after the restart and the node rejects the now-stale
  // token with a 4401 close (the 4401 rides that reconnect, NOT the death of
  // the original socket, which just closes when the node goes down); the shell
  // does not poll — it reacts to that close. The app never has to ASK for a
  // reload (this replaces the old, spoofable message-body byte scan), but
  // recovery does depend on the app reconnecting its socket.
  //
  // recoveryReloadTriggered guards against more than one recovery reload from a
  // single document: location.replace navigates away, so any further 4401 closes
  // in the same tick must not stack. The real CROSS-document loop bound is the
  // URL-param cap in reloadUrlCapDecision (fail-closed, storage-independent).
  var recoveryReloadTriggered = false;
  var notifyAffordanceShown = false;
  var notifySnoozedThisSession = false;
  // Fallback consent store for when localStorage is unavailable (private mode),
  // so consent still works for the current session and 'granted' is honest.
  var inMemoryConsent = Object.create(null);
  // Per-tag + global rate limiter for the notification proxy (see the
  // marker-bracketed `makeNotifyRateLimiter` factory below, unit-tested in
  // shell_bridge_notifications.test.mjs). Its rolling global window is
  // persisted per-contract via makeNotifyRateStore so a full page reload can't
  // reset the flood cap (#4849).
  var notifyLimiter = makeNotifyRateLimiter(makeNotifyRateStore());
  // bfcache restore does NOT re-run this IIFE, so a page restored from the
  // back-forward cache keeps its stale in-memory flood-cap window. Resync it
  // from the store on a persisted `pageshow` so a Back-restored contract page
  // can't reset the cap (#4849). The shell's open WebSockets (the proxied
  // app socket and the permission-event socket)
  // usually make it bfcache-ineligible, but this doesn't rely on that.
  window.addEventListener('pageshow', function (e) {
    if (e && e.persisted) notifyLimiter.resync();
  });

  // FAIL CLOSED whenever a HOSTED browser has no usable per-user token (#4381).
  //
  // In hosted mode a browser must ALWAYS operate under its own per-user token;
  // there is no legitimate "hosted browser as anonymous Local" state — that is
  // exactly the shared-namespace contamination we refuse. The backend's
  // permissive no-token -> Local mapping exists for the gate's own first-connect
  // reasons, but the shell enforces per-user for browsers by refusing when it
  // has no token.
  //
  // `userToken` ends up undefined for either reason, and BOTH must fail closed:
  //   - hosted + http: the plaintext-transmit guards (SHELL_USER_TOKEN_JS's
  //     `location.protocol !== 'https:'` early return + the attach-side https
  //     guard) deliberately withhold the token, so it arrives undefined here.
  //   - hosted + https + storage/crypto failure: localStorage unavailable, or
  //     crypto.getRandomValues / setItem throws, so SHELL_USER_TOKEN_JS's catch
  //     returns undefined.
  // Keying off `!userToken` (rather than re-checking the protocol) covers both
  // with one condition. hosted + https + token-minted -> userToken truthy ->
  // operate (per-user), unchanged. Non-hosted -> hostedMode undefined -> false
  // -> inert, unchanged.
  //
  // We do NOT load the app iframe (so it cannot operate on the shared Local
  // namespace) and we render a clear message instead; the WS-open handler
  // below also refuses every connection while in this state, as a second
  // independent barrier.
  var hostedNoToken = hostedMode === true && !userToken;
  if (hostedNoToken) {
    // The token is missing for one of three reasons; tailor the guidance so
    // the user can actually recover instead of hitting a dead end (#4645).
    // `window.origin` serializes to the string "null" for an opaque
    // (sandboxed) origin, which is the tell-tale of the DOMINANT case: this
    // page was opened as a NEW TAB/WINDOW from inside a Freenet app (the
    // browser's "open link in new tab", a middle-click, a right-click menu,
    // window.open, or a target=_blank link) back when such a context INHERITED
    // the app iframe's sandbox: opaque origin, so localStorage throws and the
    // per-user token can't be read. Re-opening the SAME address as a normal
    // top-level tab got a real origin and worked.
    //
    // #5100 removed that cause: the app iframe carries
    // `allow-popups-to-escape-sandbox`, so a tab opened from inside an app is a
    // real top-level document at this origin, and the shell itself is never
    // framed (X-Frame-Options: DENY). This branch should therefore be
    // unreachable now. It stays as a fail-safe rather than being deleted,
    // because the only thing standing between here and the old behaviour is
    // that one attribute — if it is ever dropped again, this is the guidance
    // that keeps a hosted user from a silent dead end. If you are reading this
    // because you saw the panel in the wild, the escape flag is gone or a
    // browser is ignoring it, and that is the bug to chase.
    //
    // The other two cases (served over plain http, or storage genuinely
    // disabled) are unaffected and remain live.
    var opaqueOrigin = window.origin === 'null';
    var plaintext = location.protocol !== 'https:';
    // Plaintext is the HARD blocker: over http the token is never minted or
    // transmitted (SHELL_USER_TOKEN_JS refuses), so re-opening in a normal tab
    // still fails until the connection is https. So when the page is served
    // insecurely that guidance wins even if the tab is ALSO a sandboxed popup.
    // Only a SECURE sandboxed tab is recoverable by re-opening, so that is the
    // one case that gets the "open in a normal tab" copy-URL affordance.
    var reopenCase = opaqueOrigin && !plaintext;
    var panel = document.createElement('div');
    panel.setAttribute('role', 'alert');
    panel.style.cssText =
      'position:fixed;inset:0;display:flex;align-items:center;' +
      'justify-content:center;padding:2rem;box-sizing:border-box;' +
      'font:16px/1.6 system-ui,-apple-system,Segoe UI,Roboto,sans-serif;' +
      'color:#1a1a1a;background:#fff;';
    var inner = document.createElement('div');
    inner.style.cssText = 'max-width:34rem;width:100%;text-align:left;';
    var h = document.createElement('h1');
    h.style.cssText = 'font-size:1.25rem;margin:0 0 0.75rem;';
    var lead = document.createElement('p');
    lead.style.cssText = 'margin:0 0 1rem;';
    if (plaintext) {
      h.textContent = 'Secure connection required';
      lead.textContent =
        'This hosted Freenet node needs an https:// connection to protect ' +
        'your per-user access key, so the app won’t load over plain ' +
        'http. Reconnect using the https:// address.';
    } else if (opaqueOrigin) {
      h.textContent = 'Open this app in a normal tab';
      lead.textContent =
        'This page opened in a new tab or window from inside a Freenet app ' +
        '(for example via "open link in new tab", a middle-click, or a ' +
        'right-click menu). Tabs opened that way run in a restricted mode ' +
        'that can’t reach the access key this hosted node uses to keep ' +
        'your data separate, so the app won’t load here. The address in this ' +
        'tab looks normal, so reloading or retyping it here seems like it ' +
        'should work. It will not: this tab itself is the one stuck in ' +
        'restricted mode. Open a brand-new tab to continue.';
    } else {
      h.textContent = 'Browser storage required';
      lead.textContent =
        'This hosted Freenet node keeps a per-user access key in your ' +
        'browser to keep your data separate, but storage is unavailable ' +
        'here (it can be blocked in private-browsing mode or by browser ' +
        'settings). Enable storage for this site, or use a different ' +
        'browser, then reload.';
    }
    inner.appendChild(h);
    inner.appendChild(lead);
    // For the secure restricted-tab case, re-opening the same address in a
    // normal tab is the fix, so surface the URL with a one-click copy. We
    // deliberately do NOT offer a "retry" button that re-opens the app in a
    // popup: a popup spawned from this (already sandboxed) context would
    // inherit the sandbox again and hit the exact same dead end, so the user
    // must open a fresh top-level tab themselves. (Gated on reopenCase, not
    // opaqueOrigin, so an http+sandboxed page doesn't offer to re-open a URL
    // that still can't mint a token — see the plaintext heading above.)
    if (reopenCase) {
      var howto = document.createElement('p');
      howto.style.cssText = 'margin:0 0 0.5rem;';
      howto.textContent =
        'Open a brand-new browser tab yourself (Ctrl/Cmd+T), then paste this ' +
        'address into it. Reloading or editing the address in this tab will ' +
        'not work:';
      inner.appendChild(howto);
      var row = document.createElement('div');
      row.style.cssText = 'display:flex;gap:0.5rem;flex-wrap:wrap;';
      var field = document.createElement('input');
      field.type = 'text';
      field.readOnly = true;
      field.value = location.href;
      field.style.cssText =
        'flex:1 1 16rem;min-width:0;padding:0.5rem 0.6rem;' +
        'font:13px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;' +
        'border:1px solid #ccc;border-radius:6px;color:#1a1a1a;background:#fafafa;';
      field.addEventListener('focus', function () {
        field.select();
      });
      field.addEventListener('click', function () {
        field.select();
      });
      var copyBtn = document.createElement('button');
      copyBtn.type = 'button';
      copyBtn.textContent = 'Copy address';
      copyBtn.style.cssText =
        'padding:0.5rem 0.9rem;border:1px solid #2563eb;border-radius:6px;' +
        'background:#2563eb;color:#fff;font:14px system-ui,sans-serif;' +
        'cursor:pointer;';
      var status = document.createElement('span');
      status.setAttribute('role', 'status');
      status.style.cssText = 'align-self:center;font-size:13px;color:#4b5563;';
      copyBtn.addEventListener('click', function () {
        function fallback() {
          field.select();
          status.textContent = 'Press Ctrl/Cmd+C to copy';
        }
        // navigator.clipboard is often unavailable or rejects in a sandboxed
        // (opaque-origin) context, so always keep the select-and-Ctrl+C path.
        if (navigator.clipboard && navigator.clipboard.writeText) {
          navigator.clipboard.writeText(location.href).then(
            function () {
              status.textContent = 'Copied';
            },
            function () {
              fallback();
            },
          );
        } else {
          fallback();
        }
      });
      row.appendChild(field);
      row.appendChild(copyBtn);
      inner.appendChild(row);
      inner.appendChild(status);
    }
    panel.appendChild(inner);
    // Remove the (not-yet-loaded, data-src) iframe and show the message. The
    // iframe never had its .src set, so the app never started.
    if (iframe && iframe.parentNode) {
      iframe.parentNode.removeChild(iframe);
    }
    document.body.appendChild(panel);
    document.title = 'Freenet: app not loaded here';
    // Keep listening for iframe messages purely so the WS-open handler can
    // return an 'error' to any app that somehow loaded; but we never set
    // iframe.src, so in practice nothing runs. Fall through to install the
    // message listener (whose 'open' case refuses while hostedNoToken).
  } else {
    // Build iframe src from data-src, appending any URL hash for deep
    // linking. Using data-src (not src) in the HTML means the iframe
    // doesn't start loading until we set .src here, so there is exactly
    // one load -- with the hash already in the URL.
    var iframeDataSrc = iframe.getAttribute('data-src');
    // Cache the contract web prefix; used by nav/popstate path validation.
    // Cross-contract navigation updates this when it accepts a new path
    // so it always reflects the currently loaded contract (see navigate
    // handler below).
    var CONTRACT_PREFIX_RE = /^(\/v[12]\/contract\/web\/[^/]+\/)/;
    var contractPrefixMatch = iframeDataSrc.match(CONTRACT_PREFIX_RE);
    var contractPrefix = contractPrefixMatch ? contractPrefixMatch[1] : null;
    var iframeSrc = iframeDataSrc;
    if (location.hash) {
      iframeSrc += location.hash.slice(0, 8192);
    }
    iframe.src = iframeSrc;
    // Seed history state so that back-navigating to the initial entry still
    // has an identifiable __freenet_nav__ record. Using replaceState avoids
    // adding a new entry — we just tag the existing one.
    if (contractPrefix) {
      try {
        history.replaceState(
          { __freenet_nav__: true, iframePath: iframeSrc },
          '',
        );
      } catch (e) {}
    }
  } // end of the non-fail-closed iframe-load block

  function sendToIframe(msg) {
    if (!iframe || !iframe.contentWindow) return;
    iframe.contentWindow.postMessage(msg, '*');
  }

  // --- Browser notifications proxy ---------------------------------------
  // The app runs in the sandboxed (opaque-origin) iframe and CANNOT use the
  // Notifications API. The shell is same-origin with the node (a real origin)
  // and can. So the app postMessages the shell, which shows the notification.
  //
  // Permission scope: the Notifications permission is per-ORIGIN, and every
  // contract on this gateway shares the shell's origin (they differ only by
  // path). A browser grant is therefore gateway-WIDE. To keep it effectively
  // per-contract we additionally require a stored per-contract consent flag
  // before EVER showing a notification, and we only ask for the browser
  // permission from a real click on the in-shell affordance below. So one
  // contract's grant never lets a different contract on the same gateway
  // notify the user without its own explicit opt-in.
  function contractConsentKey() {
    // Derive the contract key from the trusted, server-routed path
    // (/v[12]/contract/web/<KEY>/...), NEVER from message content — otherwise a
    // contract could claim another contract's consent. Covers both API versions
    // (v1 and v2) so a v2 load isn't stranded. This is a looser, unanchored
    // match than CONTRACT_PREFIX_RE (which is anchored), which is fine because
    // `location.pathname` is server-controlled and can't contain `?`/`#`.
    var m = location.pathname.match(/\/v[12]\/contract\/web\/([^/?#]+)/);
    return m ? 'freenet_notify:' + m[1] : null;
  }

  function contractSnoozeKey() {
    var k = contractConsentKey();
    return k ? k + ':snooze' : null;
  }

  function contractHasConsent() {
    var k = contractConsentKey();
    if (!k) return false;
    try {
      if (localStorage.getItem(k) === 'granted') return true;
    } catch (e) {}
    // Fall back to the in-memory record so a private-mode shell (where
    // localStorage throws) still delivers this session's notifications.
    return inMemoryConsent[k] === true;
  }

  // Records consent; returns false only when there's no contract key to gate on
  // (so the caller must not report 'granted'). Always records in memory so the
  // session works even if persistence fails; persistence is best-effort.
  function setContractConsent() {
    var k = contractConsentKey();
    if (!k) return false;
    inMemoryConsent[k] = true;
    try {
      localStorage.setItem(k, 'granted');
    } catch (e) {}
    return true;
  }

  var NOTIFY_SNOOZE_MS = 24 * 60 * 60 * 1000; // 24h "Not now" cooldown

  function isNotifySnoozed() {
    if (notifySnoozedThisSession) return true;
    var k = contractSnoozeKey();
    if (!k) return false;
    try {
      var v = localStorage.getItem(k);
      if (!v) return false;
      var ts = parseInt(v, 10);
      return isFinite(ts) && Date.now() - ts < NOTIFY_SNOOZE_MS;
    } catch (e) {
      return false;
    }
  }

  function setNotifySnoozed() {
    // In-memory flag makes dismissal effective THIS session even against a
    // contract that spams notification_enable_prompt; the persisted timestamp
    // makes "Not now" stick across reloads for NOTIFY_SNOOZE_MS.
    notifySnoozedThisSession = true;
    var k = contractSnoozeKey();
    if (!k) return;
    try {
      localStorage.setItem(k, String(Date.now()));
    } catch (e) {}
  }

  // Contract-scoped persistence for the notification rate limiter's rolling
  // global window, so a full page reload can't reset the flood cap (#4849): a
  // consented contract could otherwise fire the whole GLOBAL_MAX budget, force
  // a reload (e.g. a same-contract v1<->v2 `navigate`, which the shell treats
  // as cross-contract and reloads the top document), and start over with an
  // empty limiter. Keyed by the SAME version-less contract key as consent
  // (`freenet_notify:<key>`), so the window survives that v1<->v2 reload while
  // staying isolated per contract. sessionStorage is the right store: per-tab
  // (each tab is its own notification surface), same-origin so it persists
  // across the shell's in-place navigate, and auto-cleared when the tab closes.
  // Returns null when there's no contract key — the limiter then runs in-memory
  // only, which is harmless because without a contract key there is no consent
  // and so no notification ever fires.
  // notify-rate-store:BEGIN — the sessionStorage adapter for the flood-cap
  // window. Extracted verbatim between these markers by
  // shell_bridge_notifications.test.mjs (with stubbed `sessionStorage` /
  // `contractConsentKey`) so its load/save behavior — the Array.isArray guard,
  // JSON round-trip, non-finite + future-timestamp filtering, and fail-safe
  // try/catch — is actually exercised, not just source-grepped.
  function makeNotifyRateStore() {
    var ckey = contractConsentKey();
    if (!ckey) return null;
    var storeKey = ckey + ':rate';
    return {
      load: function () {
        try {
          var raw = sessionStorage.getItem(storeKey);
          if (!raw) return null;
          var arr = JSON.parse(raw);
          if (!Array.isArray(arr)) return null;
          // Drop non-finite entries, and any timestamp in the FUTURE relative
          // to now: a backward wall-clock correction between loads would
          // otherwise leave future-dated entries that the 60s window filter
          // keeps (its `now - t` goes negative), locking out notifications
          // until the clock catches up. Clamping here bounds that to 60s (#4849).
          var nowMs = Date.now();
          return arr.filter(function (t) {
            return typeof t === 'number' && isFinite(t) && t <= nowMs;
          });
        } catch (e) {
          return null;
        }
      },
      save: function (recent) {
        try {
          sessionStorage.setItem(storeKey, JSON.stringify(recent));
        } catch (e) {}
      },
    };
  }
  // notify-rate-store:END

  // A per-tag throttle (so distinct rooms aren't dropped) plus a rolling global
  // cap (so a consented contract can't flood with unique tags), with a bounded
  // per-tag map so a distinct-tag flood can't grow memory unbounded. `ok(tag,
  // now)` takes the clock as an argument (rather than reading `Date.now()`
  // inside) so the extracted factory is deterministically unit-testable.
  //
  // notify-rate-limiter:BEGIN — self-contained; extracted verbatim between these
  // markers and unit-tested by
  // crates/core/src/server/shell_bridge_notifications.test.mjs. Keep it pure
  // (no reference to anything outside this function) so the extraction works.
  function makeNotifyRateLimiter(store) {
    var TAG_MIN_MS = 3000; // same-tag throttle window
    var GLOBAL_MAX = 20; // max notifications per rolling window
    var GLOBAL_WINDOW_MS = 60000;
    var MAP_CAP = 128; // bound the per-tag map; evict down to MAP_CAP/2
    var tagTimes = Object.create(null);
    // The rolling global window of accepted-notification timestamps. Optionally
    // rehydrated from an injected `store` so a full page RELOAD can't reset the
    // flood cap (#4849). `store` is an optional {load, save} adapter, kept OUT
    // of this factory so the factory stays pure (references only its params and
    // locals) and the Node unit test can extract it verbatim between the
    // markers and drive it — or inject an in-memory store. Any stale entries in
    // a rehydrated window are dropped by the window filter on the first `ok`.
    var recent = [];
    if (store && typeof store.load === 'function') {
      var loaded = store.load();
      if (loaded && loaded.length) recent = loaded;
    }
    return {
      ok: function (tag, now) {
        var last = tagTimes[tag];
        if (last !== undefined && now - last < TAG_MIN_MS) return false;
        recent = recent.filter(function (t) {
          return now - t < GLOBAL_WINDOW_MS;
        });
        if (recent.length >= GLOBAL_MAX) return false;
        tagTimes[tag] = now;
        recent.push(now);
        // Persist the window so a reload rehydrates it (see #4849). Saved only
        // on the accept path: a stale (unfiltered) persisted window is dropped
        // by the filter above on the next load, so this is always conservative.
        if (store && typeof store.save === 'function') store.save(recent);
        var keys = Object.keys(tagTimes);
        if (keys.length > MAP_CAP) {
          keys.sort(function (a, b) {
            return tagTimes[a] - tagTimes[b];
          });
          for (var i = 0; i < keys.length - MAP_CAP / 2; i++) {
            delete tagTimes[keys[i]];
          }
        }
        return true;
      },
      // Re-read the persisted window into `recent`. Used on bfcache restore: a
      // back-forward-cache page keeps its stale in-memory window and never
      // re-runs the constructor, so a Back-restored older contract page could
      // otherwise reset the flood cap (#4849). Conservative — replaces only
      // when the store has a non-empty window, so a transient empty/error load
      // never resets an in-memory window.
      resync: function () {
        if (store && typeof store.load === 'function') {
          var loaded = store.load();
          if (loaded && loaded.length) recent = loaded;
        }
      },
      // Current size of the per-tag map, so the unit test can assert the
      // MAP_CAP eviction actually bounds it (removing the eviction block would
      // let this grow past MAP_CAP and fail the test). Not used in production.
      tagCount: function () {
        return Object.keys(tagTimes).length;
      },
    };
  }
  // notify-rate-limiter:END

  // Fail-CLOSED, storage-independent cap on shell recovery reloads (MAJOR #2).
  // The cap state lives in the `_freload` query param the reload itself sets, as
  // "<windowStartMs>-<count>": location.replace carries the URL across the
  // reload, and the TOP document's URL is NOT writable by the sandboxed contract
  // (it can read its own referrer but cannot set the top location), so the count
  // cannot be reset by a misbehaving iframe. Unlike sessionStorage (which is
  // swallowed in private/no-storage mode, resetting the window every document
  // and failing OPEN), the URL is always present — so the cap holds even with no
  // storage. Returns { allow, url }: allow=false means the cap is hit.
  //
  // reload-url-cap:BEGIN — pure, extracted & unit-tested by
  // shell_bridge_reload.test.mjs. Keep it pure (only params/locals) so the
  // extraction works.
  function reloadUrlCapDecision(href, now) {
    var PARAM = '_freload';
    var MAX = 3; // max recovery reloads per rolling window
    var WINDOW_MS = 60000; // rolling window
    var url;
    try {
      url = new URL(href);
    } catch (e) {
      return { allow: false, url: href };
    }
    var raw = url.searchParams.get(PARAM);
    var windowStart = now;
    var count = 0;
    if (raw) {
      var dash = raw.indexOf('-');
      var ts = parseInt(dash >= 0 ? raw.slice(0, dash) : raw, 10);
      var c = dash >= 0 ? parseInt(raw.slice(dash + 1), 10) : 0;
      // Only continue an existing window when its start is a sane, non-future
      // timestamp still inside the window; otherwise start a fresh window. A
      // malformed value (only reachable by a user hand-editing the URL, never by
      // the contract) just resets to a fresh window — the loop bound still holds
      // because each reload re-reads and re-increments the count it wrote.
      if (isFinite(ts) && ts <= now && now - ts < WINDOW_MS) {
        windowStart = ts;
        count = isFinite(c) && c > 0 ? c : 0;
      }
    }
    if (count >= MAX) return { allow: false, url: url.toString() };
    url.searchParams.set(PARAM, windowStart + '-' + (count + 1));
    return { allow: true, url: url.toString() };
  }
  // reload-url-cap:END

  // Whether a WebSocket close should trigger recovery: ONLY the node's trusted
  // stale-token code (4401 = AUTH_TOKEN_INVALID_CLOSE_CODE) on a close the shell
  // did NOT initiate itself. `clientClosed` is true for iframe-requested closes
  // (see the close proxy), so a contract cannot forge the trigger by asking the
  // shell to close its own socket with code 4401.
  // close-recovery-decision:BEGIN — pure, unit-tested by shell_bridge_reload.test.mjs.
  function isTrustedStaleTokenClose(code, clientClosed) {
    return code === 4401 && !clientClosed;
  }
  // Clamp any WebSocket application-range (4000-4999) close code the iframe asks
  // the shell to send down to a normal close, so it can never surface 4401 (or
  // any app code) to the onclose handler — a second, independent guard on top of
  // the `clientClosed` mark against a contract forging the recovery trigger.
  function clampProxiedCloseCode(code) {
    if (typeof code === 'number' && code >= 4000 && code <= 4999) return 1000;
    return code;
  }
  // close-recovery-decision:END

  // Re-fetch THIS shell HTML to mint a fresh auth token — the autonomous
  // recovery a manual refresh performs, now driven by the node's trusted 4401
  // close (see AUTH_TOKEN_INVALID_CLOSE_CODE) rather than any iframe request.
  // Bounded fail-closed by reloadUrlCapDecision, and once-per-document by
  // recoveryReloadTriggered. location.replace (not assign) leaves no dead
  // history entry.
  function triggerRecoveryReload() {
    if (recoveryReloadTriggered) return;
    var decision = reloadUrlCapDecision(location.href, Date.now());
    if (!decision.allow) return;
    recoveryReloadTriggered = true;
    try {
      location.replace(decision.url);
    } catch (e) {
      location.reload();
    }
  }

  function notifyStatusToIframe(status) {
    sendToIframe({
      __freenet_shell__: true,
      type: 'notification_status',
      status: status,
    });
  }

  // Show a small, clearly host-owned affordance and, on a REAL click in this
  // shell frame, request the browser permission. The prompt must be triggered
  // by a gesture in the shell: a click inside the sandboxed iframe does not
  // reliably grant the shell the transient activation the browser requires for
  // Notification.requestPermission().
  // notify-offer:BEGIN (extracted verbatim by shell_bridge_notifications.test.mjs)
  // Like showAppNotification, every `notification_enable_prompt` gets exactly
  // one status reply — including the already-showing case, which would
  // otherwise answer with silence a client can't tell from a lost message.
  function maybeOfferNotifications() {
    if (typeof Notification === 'undefined') {
      notifyStatusToIframe('unsupported');
      return;
    }
    if (Notification.permission === 'denied') {
      notifyStatusToIframe('denied');
      return;
    }
    if (Notification.permission === 'granted' && contractHasConsent()) {
      // Returning user who already opted in: pre-warm the notification service
      // worker now so it's active before the first message arrives (mobile
      // needs it to show anything; racing its activation would drop the first).
      ensureNotifyServiceWorker();
      notifyStatusToIframe('granted');
      return;
    }
    // Respect a prior "Not now": makes dismissal effective against a contract
    // that re-sends notification_enable_prompt, and persists for a cooldown.
    if (isNotifySnoozed()) {
      notifyStatusToIframe('dismissed');
      return;
    }
    if (notifyAffordanceShown) {
      // The bar is already on screen awaiting a click: the prompt is pending,
      // not lost. Reply so a client can tell "still deciding" from "dropped".
      notifyStatusToIframe('default');
      return;
    }
    notifyAffordanceShown = true;

    var bar = document.createElement('div');
    bar.setAttribute('role', 'dialog');
    bar.setAttribute('aria-label', 'Enable notifications');
    bar.style.cssText =
      'position:fixed;left:50%;bottom:16px;transform:translateX(-50%);' +
      'z-index:2147483647;display:flex;align-items:center;gap:12px;' +
      'max-width:calc(100% - 32px);padding:10px 14px;border-radius:10px;' +
      'background:#1b1f24;color:#fff;font:14px/1.3 system-ui,sans-serif;' +
      'box-shadow:0 4px 20px rgba(0,0,0,0.35);';
    var label = document.createElement('span');
    label.textContent = 'Get notified of new messages?';
    label.style.cssText = 'flex:1;';
    var enable = document.createElement('button');
    enable.textContent = 'Enable';
    enable.style.cssText =
      'cursor:pointer;border:none;border-radius:6px;padding:6px 12px;' +
      'background:#007FFF;color:#fff;font:inherit;font-weight:600;';
    var dismiss = document.createElement('button');
    dismiss.textContent = 'Not now';
    dismiss.style.cssText =
      'cursor:pointer;border:none;border-radius:6px;padding:6px 10px;' +
      'background:transparent;color:#9aa4b2;font:inherit;';

    function close() {
      notifyAffordanceShown = false;
      try {
        document.body.removeChild(bar);
      } catch (e) {}
    }
    enable.addEventListener('click', function () {
      var called = false;
      var done = function (perm) {
        if (called) return; // some browsers fire BOTH the callback and promise
        called = true;
        if (perm === 'granted' && setContractConsent()) {
          // Pre-warm the notification service worker the instant the user opts
          // in, so it's active by the time the first message arrives (mobile
          // needs it to show anything at all).
          ensureNotifyServiceWorker();
          notifyStatusToIframe('granted');
        } else if (perm === 'granted') {
          // Granted but no contract key to gate on — nothing would deliver.
          notifyStatusToIframe('undeliverable');
        } else {
          notifyStatusToIframe(perm === 'denied' ? 'denied' : 'default');
        }
        close();
      };
      try {
        // requestPermission is promise-based on modern browsers and
        // callback-based on older ones — support both. Resolve `done` on
        // rejection too, so a failed prompt never strands the affordance.
        var p = Notification.requestPermission(done);
        if (p && typeof p.then === 'function') {
          p.then(done, function () {
            done('default');
          });
        }
      } catch (e) {
        done('default');
      }
    });
    dismiss.addEventListener('click', function () {
      setNotifySnoozed();
      notifyStatusToIframe('dismissed');
      close();
    });
    bar.appendChild(label);
    bar.appendChild(enable);
    bar.appendChild(dismiss);
    document.body.appendChild(bar);
  }
  // notify-offer:END

  // --- Service-worker fallback for notifications (mobile) ----------------
  // Desktop browsers show notifications with the page-level `new
  // Notification(...)` constructor (used unchanged in showAppNotification).
  // Mobile browsers (Chrome / Firefox on Android) REFUSE that constructor — it
  // throws, and the ONLY supported way to show a notification there is
  // ServiceWorkerRegistration.showNotification(). So we register a tiny
  // same-origin service worker (served at NOTIFY_SW_URL) and use it ONLY as the
  // fallback when the constructor throws. Desktop behavior is therefore
  // unchanged; the worker path exists solely to make mobile work.
  //
  // The worker also routes a notification click back to this shell: the click
  // fires in the worker (not the page), so the worker posts it to the shell,
  // which forwards it to the iframe as the same `notification_click` the
  // page-level onclick path emits. Registration is lazy — only users who have
  // enabled notifications register the worker (pre-warmed on opt-in in
  // maybeOfferNotifications). On DESKTOP the constructor succeeds first, so the
  // worker is never used to display: desktop's notification DISPLAY and CLICK
  // path are unchanged, and only a dormant same-origin worker is registered so
  // mobile has it ready.
  var NOTIFY_SW_URL = '/freenet-notify-sw.js';
  var notifySwPromise = null;
  var notifySwMsgListenerAdded = false;

  // Reading the serviceWorker property off navigator THROWS a SecurityError in
  // a sandboxed document without 'allow-same-origin' — the property EXISTS on
  // Navigator
  // (so an `in`-operator feature-check passes) but its getter
  // throws. A feature-check must therefore attempt the read itself. The shell
  // top page is not sandboxed today, but this bridge must never assume that:
  // in 0.2.107 an unguarded read here threw during the eager
  // installNotifyClickListener() call and killed freenetBridge before its
  // message handlers installed, breaking every locally-served web app (#4945).
  function serviceWorkerOrNull() {
    try {
      return typeof navigator !== 'undefined'
        ? navigator.serviceWorker || null
        : null;
    } catch (e) {
      return null;
    }
  }

  // Forward a worker-posted notification click to the iframe. Installed at most
  // once, and EAGERLY at shell startup (see the call below) — NOT only on lazy
  // SW registration: a persistent notification can outlive a shell reload, and
  // if it's clicked before the reloaded app triggers notification setup, the
  // worker posts the click to this (matching) client and we must already be
  // listening or the click is lost. Listening is harmless when no worker is
  // registered, so it doesn't require a secure context.
  function installNotifyClickListener() {
    if (notifySwMsgListenerAdded) return;
    var sw = serviceWorkerOrNull();
    if (!sw) {
      return;
    }
    notifySwMsgListenerAdded = true;
    sw.addEventListener('message', function (event) {
      var d = event && event.data;
      if (!d || d.__freenet_notify_click__ !== true) return;
      try {
        window.focus();
      } catch (e) {}
      sendToIframe({
        __freenet_shell__: true,
        type: 'notification_click',
        tag: typeof d.tag === 'string' ? d.tag : null,
      });
    });
  }

  function ensureNotifyServiceWorker() {
    if (notifySwPromise) return notifySwPromise;
    if (!serviceWorkerOrNull() || !window.isSecureContext) {
      // No SW support, or an insecure (plain-http, non-localhost) origin where
      // registration would fail. This is permanent for the page, so cache it —
      // the page-level constructor path covers these (desktop) cases.
      notifySwPromise = Promise.resolve(null);
      return notifySwPromise;
    }
    installNotifyClickListener();
    try {
      notifySwPromise = navigator.serviceWorker.register(NOTIFY_SW_URL).then(
        function (reg) {
          return reg;
        },
        function () {
          // Don't cache a TRANSIENT failure (e.g. the script fetch failing
          // during a node restart) for the whole page lifetime — clear the memo
          // so a later notification retries registration.
          notifySwPromise = null;
          return null;
        },
      );
    } catch (e) {
      // A synchronous throw from register() is unusual; allow a retry too.
      notifySwPromise = null;
      return Promise.resolve(null);
    }
    return notifySwPromise;
  }

  // Resolve to a ServiceWorkerRegistration able to showNotification(), or null
  // if unavailable within `timeoutMs`. Bounded so a slow/never-activating worker
  // never stalls a notification — the caller reports it undeliverable instead.
  function notifyRegistrationReady(timeoutMs) {
    var swContainer = serviceWorkerOrNull();
    if (!swContainer) {
      return Promise.resolve(null);
    }
    return ensureNotifyServiceWorker().then(function (reg) {
      if (!reg) return null;
      if (reg.active) return reg;
      // Registered but not yet active (first visit): wait briefly for it.
      return new Promise(function (resolve) {
        var settled = false;
        var t = setTimeout(function () {
          if (!settled) {
            settled = true;
            resolve(null);
          }
        }, timeoutMs);
        swContainer.ready.then(
          function (ready) {
            if (!settled) {
              settled = true;
              clearTimeout(t);
              resolve(ready || null);
            }
          },
          function () {
            if (!settled) {
              settled = true;
              clearTimeout(t);
              resolve(null);
            }
          },
        );
      });
    });
  }

  // notify-show:BEGIN (extracted verbatim by shell_bridge_notifications.test.mjs)
  // Every well-formed `notification` message gets exactly one status reply:
  // EVERY path out of this function posts one, whether it displayed or dropped.
  // The display paths re-affirm 'granted', and that re-affirmation is what
  // retracts an earlier 'undeliverable' — e.g. the first notification of a
  // session racing the service worker's activation — which otherwise stuck for
  // the whole session (#5043). Two bounds on the guarantee: a `notification`
  // whose `title` isn't a string never reaches here (the dispatcher's type
  // check drops it), and delivery of the status itself is best-effort, since
  // sendToIframe no-ops when the iframe is gone.
  function showAppNotification(msg) {
    if (typeof Notification === 'undefined') {
      notifyStatusToIframe('unsupported');
      return;
    }
    // Gate on BOTH the browser permission and this contract's own consent.
    // A framed app can't read Notification.permission itself (opaque origin),
    // so a permission revoked in site settings after a 'granted' is only
    // visible to it if we report it here.
    if (Notification.permission !== 'granted') {
      notifyStatusToIframe(
        Notification.permission === 'denied' ? 'denied' : 'default',
      );
      return;
    }
    if (!contractConsentKey()) {
      // No contract key to gate consent on: permanent for this page, and
      // re-prompting can never fix it. maybeOfferNotifications reports the same
      // condition as 'undeliverable'; keep the two in agreement rather than
      // sending the app into a prompt loop it cannot win.
      notifyStatusToIframe('undeliverable');
      return;
    }
    if (!contractHasConsent()) {
      // Browser-granted but this contract isn't opted in. Reported as 'default'
      // — the same client-visible meaning as a browser 'default': not enabled
      // yet, and the next notification_enable_prompt can still fix it.
      notifyStatusToIframe('default');
      return;
    }
    // Notification renders text only (no markup), so no HTML-injection risk;
    // still cap length to prevent oversized/abusive content.
    var title = String(msg.title).slice(0, 128);
    var opts = {};
    if (typeof msg.body === 'string') opts.body = msg.body.slice(0, 256);
    // Coalesce per contract (+ optional app tag) so a busy room replaces rather
    // than stacks notifications; scope the tag to the contract so contracts
    // can't collide.
    var ckey = contractConsentKey() || 'freenet_notify:app';
    opts.tag =
      ckey + ':' + (typeof msg.tag === 'string' ? msg.tag.slice(0, 64) : 'msg');
    // Per-tag throttle + rolling global cap: distinct rooms aren't dropped, but
    // a consented contract can't flood with unique tags.
    if (!notifyLimiter.ok(opts.tag, Date.now())) {
      // Coalesced by the shell's own flood policy, NOT a delivery problem:
      // permission and consent are both intact. Report 'granted' so the app
      // can't confuse a throttled message with a lost one — and so a throttled
      // message still retracts a stale 'undeliverable'. Reporting
      // 'undeliverable' here would be the #5043 bug in reverse: a working,
      // deliberately-throttled setup made to look broken.
      notifyStatusToIframe('granted');
      return;
    }
    // Cap the routing tag like opts.tag — it's attacker-controlled (the app
    // supplies msg.tag) and is echoed back into the iframe on click.
    var routeTag = typeof msg.tag === 'string' ? msg.tag.slice(0, 64) : null;
    // Carry the room tag AND this shell's own URL so the worker's
    // notificationclick routes the click back to THIS contract's shell (and
    // reopens it if closed) — never another contract's tab. fnUrl is the shell's
    // own same-origin location; the framed app can influence its subpath/hash
    // (via the navigate proxy) but NOT the leading /v[12]/contract/web/<key>/
    // segment, which is the only part the worker routes on. Harmless on the
    // page-level path (which routes via n.onclick).
    // Cap fnUrl length too (2048, matching the clipboard cap). Deliberately a
    // different cap than the 8192 hash limit; a 1024-char cap is avoided here
    // because the hash-limit guard test forbids that exact literal file-wide.
    opts.data = { fnTag: routeTag, fnUrl: location.href.slice(0, 2048) };

    // Desktop: use the page-level constructor, UNCHANGED. Mobile: it throws
    // (unsupported), so we fall through to the service-worker path below — the
    // only way to show a notification on mobile.
    var shownByConstructor = false;
    try {
      var n = new Notification(title, opts);
      // Set the instant the constructor returns: it has ALREADY displayed, so a
      // throw from anything below (an exotic onclick setter) must not fall
      // through to the worker path and display the same notification twice.
      shownByConstructor = true;
      n.onclick = function () {
        try {
          window.focus();
        } catch (e) {}
        // Tell the app which notification was clicked so it can route to the room.
        sendToIframe({
          __freenet_shell__: true,
          type: 'notification_click',
          tag: routeTag,
        });
        try {
          n.close();
        } catch (e) {}
      };
    } catch (e) {
      // EXPECTED on mobile Chrome/Firefox: the non-persistent `new
      // Notification()` constructor is unsupported and throws, so we deliver via
      // the service worker below. Logged because on DESKTOP this same throw
      // means a real bug (malformed opts, permission lost between the check and
      // the call) and is otherwise indistinguishable from the mobile path.
      try {
        console.debug('freenet: Notification constructor threw', e);
      } catch (e2) {}
    }
    // Report OUTSIDE the try: the try must contain only the display attempt, so
    // its catch means "constructor unsupported" and nothing else. A throw from
    // the status post inside it would look like a constructor failure and fall
    // through to a second, duplicate delivery.
    if (shownByConstructor) {
      notifyStatusToIframe('granted');
      return;
    }

    // Post at most once from the async chain: the .catch below is a backstop for
    // the whole chain, INCLUDING a throw from a status post in the success
    // branch, which would otherwise turn one reply into two.
    var swReplied = false;
    function swReply(status) {
      if (swReplied) return;
      swReplied = true;
      notifyStatusToIframe(status);
    }

    notifyRegistrationReady(1500)
      .then(function (reg) {
        if (reg && typeof reg.showNotification === 'function') {
          // Return the inner promise so a rejection (or a synchronous throw, or
          // a non-thenable return) lands in the single .catch below.
          return reg.showNotification(title, opts).then(function () {
            // Delivered: re-affirm, retracting any earlier 'undeliverable'.
            swReply('granted');
          });
        }
        // No usable service worker (e.g. an insecure-context http origin) AND
        // the page-level constructor threw: nothing can display it. Tell the app
        // so it need not keep sending; the in-app unread badge is the fallback.
        swReply('undeliverable');
      })
      .catch(function () {
        // Anything else the worker path can throw or reject with — a
        // SecurityError from a sandboxed service-worker property read (the
        // #4945 getter hazard, see serviceWorkerOrNull), a showNotification
        // that throws or returns a non-promise. Nothing was
        // displayed, so the app must hear about it rather than wait forever.
        swReply('undeliverable');
      });
  }
  // notify-show:END

  // Install the click-forward listener eagerly on every shell load (see
  // installNotifyClickListener) so a click on a persistent notification that
  // outlived a reload is still delivered even before the reloaded app triggers
  // notification setup. Cheap and inert when no worker ever posts.
  installNotifyClickListener();

  window.addEventListener('message', function (event) {
    if (event.source !== iframe.contentWindow) return;
    var msg = event.data;
    if (!msg) return;

    // Handle shell-level messages (title, favicon) from iframe
    if (msg.__freenet_shell__) {
      if (msg.type === 'title' && typeof msg.title === 'string') {
        // Truncate to prevent UI spoofing with excessively long titles
        document.title = msg.title.slice(0, 128);
      } else if (msg.type === 'favicon' && typeof msg.href === 'string') {
        // Only allow https: and data: schemes to prevent exfiltration
        try {
          var scheme = msg.href.split(':')[0].toLowerCase();
          if (scheme !== 'https' && scheme !== 'data') return;
        } catch (e) {
          return;
        }
        var link = document.querySelector('link[rel="icon"]');
        if (link) link.href = msg.href;
      } else if (msg.type === 'hash' && typeof msg.hash === 'string') {
        // Only allow # fragments — reject anything that could modify path/query.
        // Note: replaceState (not pushState) is intentional — avoids polluting
        // browser history with every in-app route change. This also means
        // replaceState does NOT fire popstate or hashchange, preventing loops.
        var h = msg.hash.slice(0, 8192);
        if (h.length > 0 && h.charAt(0) === '#') {
          // Preserve the existing state object (which may carry our
          // __freenet_nav__ marker) so popstate can still restore the iframe.
          // If the current entry is tagged, also update its iframePath to
          // include the new fragment — otherwise back/forward would restore
          // the iframe without the user's current fragment position.
          var curState = history.state;
          if (
            curState &&
            curState.__freenet_nav__ === true &&
            typeof curState.iframePath === 'string'
          ) {
            var basePath = curState.iframePath.split('#')[0];
            history.replaceState(
              { __freenet_nav__: true, iframePath: basePath + h },
              '',
              h,
            );
          } else {
            history.replaceState(history.state, '', h);
          }
        }
      } else if (msg.type === 'clipboard' && typeof msg.text === 'string') {
        // Sandboxed iframes can't use navigator.clipboard due to permissions
        // policy. Proxy clipboard writes through the trusted shell instead.
        // Write-only — no readText proxy to prevent exfiltration.
        // Rate-limited to 1 write/sec to prevent clipboard spam from
        // malicious contracts. Requires transient user activation (browser
        // enforced) — works when the iframe sends this in a click handler.
        var now = Date.now();
        if (now - lastClipboard >= 1000) {
          lastClipboard = now;
          try {
            navigator.clipboard.writeText(msg.text.slice(0, 2048));
          } catch (e) {}
        }
        // NOTE: there is deliberately no iframe-initiated `type:'reload'` handler.
        // Peer-restart recovery is driven autonomously by the node's trusted 4401
        // close code (see triggerRecoveryReload / the ws.onclose handler), NOT by
        // the sandboxed app asking — a request the app could otherwise abuse to
        // force top-level reloads / token minting. river#400's reload message is
        // an intentional no-op on new nodes (the two are decoupled).
      } else if (
        msg.type === 'download' &&
        typeof msg.filename === 'string' &&
        typeof msg.base64 === 'string'
      ) {
        // Download proxy: contracts inside the sandboxed (null-origin)
        // iframe can't reliably trigger file downloads — `<a download>`
        // either silently fails (Firefox) or saves to an inaccessible
        // location (Chrome). The shell runs in the real origin and
        // can do it normally.
        //
        // Validation:
        //  - filename: stripped of path separators and leading dots,
        //    capped at 128 chars, no nulls
        //  - mimeType: only a small allowlist (data URLs from arbitrary
        //    types could be exploited by malicious contracts)
        //  - base64: capped at ~10 MiB raw bytes
        //  - rate-limit: 1 download per 2s, same reasoning as clipboard
        var now2 = Date.now();
        if (now2 - lastDownload < 2000) {
          console.warn('[freenet] download rate-limited (>1 per 2s)');
          return;
        }
        // Charge the rate-limit budget for *every* attempt (even rejected
        // ones) so a malicious iframe can't burn host CPU by spamming
        // invalid payloads at high frequency.
        lastDownload = now2;
        var rawName = msg.filename;
        if (rawName.indexOf('\0') !== -1) {
          console.warn('[freenet] download rejected: null byte in filename');
          return;
        }
        // Strip path components — keep only the basename. Normalise
        // both `/` and `\` so a malicious contract can't smuggle in a
        // backslash on POSIX.
        var slash = rawName.lastIndexOf('/');
        if (slash >= 0) rawName = rawName.slice(slash + 1);
        var bslash = rawName.lastIndexOf('\\');
        if (bslash >= 0) rawName = rawName.slice(bslash + 1);
        // Strip leading dots so a contract can't write a dotfile.
        while (rawName.charAt(0) === '.') rawName = rawName.slice(1);
        rawName = rawName.slice(0, 128);
        if (rawName.length === 0) {
          console.warn(
            '[freenet] download rejected: empty filename after sanitisation',
          );
          return;
        }
        var mime =
          typeof msg.mimeType === 'string'
            ? msg.mimeType
            : 'application/octet-stream';
        var ALLOWED_MIME = {
          'application/json': 1,
          'application/octet-stream': 1,
          'text/plain': 1,
          'text/csv': 1,
        };
        // Disallowed MIMEs are downgraded to octet-stream rather than
        // rejected, so callers always get *some* download — but log it
        // so the contract author can fix the mismatch.
        if (!ALLOWED_MIME[mime]) {
          console.warn(
            '[freenet] download MIME ' +
              mime +
              ' downgraded to application/octet-stream',
          );
          mime = 'application/octet-stream';
        }
        // base64 max length ≈ 4/3 * raw size; 10 MiB raw → ~13.4 MiB b64.
        // Round up to 14 MiB for a small safety margin.
        if (msg.base64.length > 14 * 1024 * 1024) {
          console.warn(
            '[freenet] download rejected: payload exceeds 14 MiB base64 cap',
          );
          return;
        }
        var raw;
        try {
          raw = atob(msg.base64);
        } catch (e) {
          console.warn('[freenet] download rejected: base64 decode failed');
          return;
        }
        var len = raw.length;
        var bytes = new Uint8Array(len);
        for (var i = 0; i < len; i++) bytes[i] = raw.charCodeAt(i) & 0xff;
        var blob;
        try {
          blob = new Blob([bytes], { type: mime });
        } catch (e) {
          console.warn('[freenet] download rejected: Blob construction failed');
          return;
        }
        var url;
        try {
          url = URL.createObjectURL(blob);
        } catch (e) {
          console.warn('[freenet] download rejected: createObjectURL failed');
          return;
        }
        var a = document.createElement('a');
        a.href = url;
        a.download = rawName;
        a.style.display = 'none';
        document.body.appendChild(a);
        try {
          a.click();
        } catch (e) {}
        document.body.removeChild(a);
        // Defer revoke so the browser has time to start the download.
        setTimeout(function () {
          try {
            URL.revokeObjectURL(url);
          } catch (e) {}
        }, 60000);
      } else if (msg.type === 'notification_enable_prompt') {
        // The app (opaque origin) can't use the Notifications API itself, so it
        // asks the shell to offer notifications. We show an in-shell affordance
        // and fire the actual permission prompt from a real click in THIS frame
        // (see maybeOfferNotifications for why the gesture must be here).
        maybeOfferNotifications();
      } else if (msg.type === 'notification' && typeof msg.title === 'string') {
        // The app asks the shell to display a browser notification. Gated on
        // the browser permission AND this contract's own stored consent, and
        // rate-limited + length-capped (content is attacker-controlled message
        // text). See showAppNotification.
        showAppNotification(msg);
      } else if (msg.type === 'navigate' && typeof msg.href === 'string') {
        // Navigation from the sandboxed iframe. The iframe cannot navigate
        // the top window itself, so it postMessages the shell, which does
        // one of two things:
        //
        //   1. SAME-CONTRACT hop (subpage inside the current contract's
        //      webapp): update iframe.src in place. This preserves the
        //      running shell, auth token, and in-memory state — matching
        //      what a multi-page webapp expects for client-side routing.
        //
        //   2. CROSS-CONTRACT hop (link to a different Freenet contract):
        //      fall through to a top-level window.location.assign. The
        //      gateway serves a fresh shell via `contract_home` for the
        //      new contract, which generates a new auth token and origin
        //      attribution. Reusing the current iframe for a different
        //      contract would keep the old auth token bound to the
        //      original contract, so the server would misattribute every
        //      subsequent delegate/API request (see PR review: Codex P1).
        //
        // This is the fix for the "Delta cannot link to other Freenet
        // contracts without forcing a new tab" report: cross-contract
        // links now navigate in place via a full shell reload, instead of
        // being silently dropped.
        //
        // Security posture:
        // - Same-origin only (rejects cross-site). The sandbox still
        //   blocks contract JS from reading gateway cookies or same-origin
        //   state.
        // - Target path must match the contract-webapp shape
        //   /v[12]/contract/web/{key}/... . This rejects /v1/node/...,
        //   /v1/delegate/..., or any other gateway endpoint as a
        //   navigation target.
        // - Sandbox iframe attributes are NOT widened. The shell remains
        //   the sole code with top-level navigation authority.
        // - Cross-contract navigation via window.location.assign is the
        //   same privilege level as a user middle-clicking a link today
        //   (target="_blank" + allow-popups already escapes the sandbox
        //   and can reach any Freenet contract). The difference is that
        //   the destination now loads in the same tab instead of a new
        //   one.
        //
        // Cap href length to prevent a malicious contract from bloating
        // history.state or the address bar with arbitrarily large URLs.
        if (msg.href.length > 4096) return;
        try {
          var resolved = new URL(msg.href, iframe.src);
          // Same-origin only.
          if (resolved.origin !== location.origin) return;
          var cleanPath = resolved.pathname;
          // Contract-webapp shape check. This is the security boundary
          // that prevents the handler from being used to navigate to
          // gateway internals (/v1/node/..., /v1/delegate/...) or to
          // non-contract paths in general. The contract-key segment is
          // validated server-side in the freshly-loaded shell path via
          // ContractInstanceId::from_bytes, so we only need a loose
          // shape check here — a bogus key still produces a 4xx from the
          // gateway, not a silent bypass.
          var newPrefixMatch = cleanPath.match(CONTRACT_PREFIX_RE);
          if (!newPrefixMatch) return;
          var newContractPrefix = newPrefixMatch[1];
          // Cap the hash component to match the 8192-byte cap used by
          // the hash-forwarding path; the iframe path is stored in
          // history.state so unbounded hashes would bloat the per-tab
          // history record.
          var cappedHash = resolved.hash ? resolved.hash.slice(0, 8192) : '';

          if (newContractPrefix === contractPrefix) {
            // SAME-CONTRACT: update iframe.src in place. This preserves
            // the running shell, auth token, and client-side state.
            //
            // Close any open WebSocket connections from the previous
            // page to prevent resource leaks. The old iframe document
            // will be destroyed when src changes, orphaning any
            // connection callbacks.
            connections.forEach(function (ws) {
              try {
                ws.close();
              } catch (e) {}
            });
            connections.clear();
            // Build new sandbox URL preserving __sandbox=1
            resolved.searchParams.set('__sandbox', '1');
            var newIframePath =
              resolved.pathname + resolved.search + cappedHash;
            iframe.src = newIframePath;
            // Push a history entry so back/forward navigate between
            // visited subpages, and update the address bar to the
            // non-sandbox URL. The sandbox flag is intentionally omitted
            // from the outer URL; the shell always re-adds it when
            // loading the iframe. See issue #3839.
            try {
              history.pushState(
                { __freenet_nav__: true, iframePath: newIframePath },
                '',
                cleanPath + cappedHash,
              );
            } catch (e) {}
          } else {
            // CROSS-CONTRACT: top-level navigation. The gateway's
            // contract_home handler re-runs and generates a fresh auth
            // token + origin attribution for the destination contract.
            // The browser's normal back/forward history takes care of
            // cross-contract restoration — no popstate handling needed.
            //
            // Include `resolved.search` so any query parameters the link
            // carries (e.g. app-level routing args) survive the hop. The
            // destination shell page strips the sensitive routing params
            // (`__sandbox`, `authToken`) before forwarding the rest into
            // the iframe's `location.search`. The gateway's subpage
            // handler redirects non-root HTML loads to the shell route
            // (see `web_subpages` `Sec-Fetch-Dest` handling), which
            // preserves the filtered query string all the way through,
            // so `/v1/contract/web/{key}/page2?invite=…` still lands on
            // a shell that issues an auth token and forwards `invite`
            // into the iframe.
            try {
              window.location.assign(cleanPath + resolved.search + cappedHash);
            } catch (e) {}
          }
        } catch (e) {}
      } else if (msg.type === 'open_url' && typeof msg.url === 'string') {
        // Open a URL in a new tab.
        //
        // Nothing the node injects posts this any more. PR #3818 removed the
        // popup sandbox-escape flag from the app iframe and introduced this
        // bridge in its place, because a popup the sandboxed iframe opened
        // itself inherited the opaque origin — breaking CORS on target sites,
        // and on a hosted node losing the per-user key. #5100 put the flag
        // back (a natively-opened popup is now a real top-level document at
        // this origin, which is the only shape that works in every browser),
        // so both the anchor interceptor and the `window.open` override that
        // used to forward here are gone.
        //
        // The handler stays because it is still REACHABLE, and that is the
        // whole point of the gate below: any contract can postMessage
        // `open_url` directly. Deleting it would be fine only if nothing could
        // send it, which is not the case.
        //
        // Security model: this scheme allow-list is the PRIMARY gate, not
        // defence in depth. A malicious contract iframe can postMessage
        // `open_url` directly without going through the upstream
        // navigation interceptor, so the URL parser + scheme check below
        // is what blocks `javascript:` / `data:` / `file:` etc.
        //
        // Both http and https are accepted because user-pasted markdown
        // links commonly target self-hosted services with no TLS
        // configured. freenet/river#231 was exactly that: the network
        // telemetry dashboard was plain HTTP at the time (it has since
        // moved to HTTPS), and an https-only filter silently swallowed
        // every click on it. Auth tokens never travel through this path
        // — the only operation is `window.open(url, '_blank',
        // 'noopener,noreferrer')` — so HTTP doesn't expose credentials.
        // See freenet/river#231.
        //
        // Do NOT name the dashboard's host here: this file is inlined
        // verbatim into the shell page, and
        // `shell_page_contains_iframe_and_bridge` greps the rendered page
        // for the project's public domain and fails on ANY occurrence,
        // comments included (external-origin / CORS guard). The live URL
        // lives in scripts/check-endpoints.sh.
        //
        // Private networks (RFC1918 192.168/16, 10/8, 172.16-31/12 and
        // RFC4193 fc00::/7, link-local fe80::/10) are deliberately NOT
        // blocked. A user who pastes a link to their home router or NAS
        // expects the link to work; the threat model here is that a
        // *malicious contract* might forge a markdown link to a LAN
        // admin panel and trick the user into clicking, which is a
        // social-engineering attack class we accept.
        try {
          var u = new URL(msg.url);
          if (u.protocol !== 'https:' && u.protocol !== 'http:') return;
          // WHATWG URL.hostname serializes an IPv6 literal WITH brackets, so
          // `http://[::1]/` has hostname `[::1]`, NOT `::1`. Strip the brackets
          // before comparing, or the `::1` arm never matches and a forged link
          // to the viewer's IPv6 loopback slips past this refusal.
          var h = u.hostname
            .toLowerCase()
            .replace(/^\[/, '')
            .replace(/\]$/, '');
          if (
            h === 'localhost' ||
            h === '127.0.0.1' ||
            h === '::1' ||
            h === '0.0.0.0'
          )
            return;
          // Honour shift-click by requesting a popup-style window feature
          // (freenet/freenet-core#3853). Firefox honours this as "open in
          // a new window"; other browsers may still open a tab, which is
          // an acceptable fallback. ctrl / meta / middle-click cannot be
          // preserved from a postMessage handler because browsers only
          // honour background-tab placement when window.open is called
          // from a direct user gesture, so we route those through the
          // same default-tab path as plain left-click.
          if (msg.shiftKey === true) {
            window.open(u.href, '_blank', 'noopener,noreferrer,popup');
          } else {
            window.open(u.href, '_blank', 'noopener,noreferrer');
          }
        } catch (e) {}
      }
      return;
    }

    if (!msg.__freenet_ws__) return;

    switch (msg.type) {
      case 'open': {
        // FAIL CLOSED (#4381): a hosted browser with no per-user token must
        // never open a socket, because that connection would land on the
        // SHARED Local namespace (cross-user contamination). The token is
        // absent over plaintext http (withheld) or on a storage/crypto
        // failure. Refuse every open while hosted+no-token — a second
        // independent barrier on top of not loading the iframe at all (see the
        // hostedNoToken block at the top of freenetBridge).
        if (hostedNoToken) {
          sendToIframe({ __freenet_ws__: true, type: 'error', id: msg.id });
          return;
        }
        // Limit concurrent connections to prevent resource exhaustion
        if (connections.size >= MAX_CONNECTIONS) {
          sendToIframe({ __freenet_ws__: true, type: 'error', id: msg.id });
          return;
        }
        // Security: only allow WebSocket connections to the local API server itself.
        // Validate protocol explicitly and compare origin.
        try {
          var u = new URL(msg.url);
          if (u.protocol !== 'ws:' && u.protocol !== 'wss:') {
            sendToIframe({ __freenet_ws__: true, type: 'error', id: msg.id });
            return;
          }
          var httpProto = u.protocol === 'wss:' ? 'https:' : 'http:';
          if (httpProto + '//' + u.host !== LOCAL_API_ORIGIN) {
            sendToIframe({ __freenet_ws__: true, type: 'error', id: msg.id });
            return;
          }
        } catch (e) {
          sendToIframe({ __freenet_ws__: true, type: 'error', id: msg.id });
          return;
        }
        // Strip any caller-supplied credentials BEFORE we inject our own, so
        // the sandboxed app can never choose its own auth/user identity by
        // putting these params on the WebSocket URL it asks us to open. This
        // matters most for `userToken`: the conditional `set` below is skipped
        // when our minted token is undefined (localStorage disabled / private
        // mode in hosted mode), and without this delete a caller-supplied
        // `userToken` (from the app, or reflected via a deep-link into the WS
        // URL) would survive and let the app pick its own per-user secret
        // namespace. The app must NEVER influence the namespace — only the
        // shell-minted token may reach the backend. `authToken` is deleted for
        // symmetric defense-in-depth even though the unconditional `set` below
        // already overrides any caller value.
        u.searchParams.delete('authToken');
        u.searchParams.delete('userToken');
        // Inject auth token into the WebSocket URL
        u.searchParams.set('authToken', authToken);
        // In hosted mode also present the durable per-user token so the node
        // can scope a per-user delegate-secret namespace (P2 of #4381). The
        // token is undefined in non-hosted mode, so the param is omitted (and,
        // combined with the delete above, the URL carries no userToken at all).
        // The `location.protocol === 'https:'` guard is a SECOND, independent
        // REFUSE-PLAINTEXT-TOKEN barrier (the first is in SHELL_USER_TOKEN_JS,
        // which never mints the token on an http page): two guards so a future
        // refactor of either site can't reopen the plaintext-leak path. The
        // shell is same-origin with the node, so `location.protocol` reflects
        // whether the shell itself was served over TLS.
        if (userToken && location.protocol === 'https:') {
          u.searchParams.set('userToken', userToken);
        }
        var ws = new WebSocket(u.toString(), msg.protocols || undefined);
        ws.binaryType = 'arraybuffer';
        connections.set(msg.id, ws);

        ws.onopen = function () {
          sendToIframe({ __freenet_ws__: true, type: 'open', id: msg.id });
        };
        ws.onmessage = function (e) {
          var transfer = e.data instanceof ArrayBuffer ? [e.data] : [];
          iframe.contentWindow.postMessage(
            {
              __freenet_ws__: true,
              type: 'message',
              id: msg.id,
              data: e.data,
            },
            '*',
            transfer,
          );
        };
        ws.onclose = function (e) {
          sendToIframe({
            __freenet_ws__: true,
            type: 'close',
            id: msg.id,
            code: e.code,
            reason: e.reason,
          });
          connections.delete(msg.id);
          // Trusted stale-token signal: the node closes a socket whose auth
          // token is stale with code AUTH_TOKEN_INVALID_CLOSE_CODE (4401). Only
          // a SERVER-initiated close carries it — the close proxy below marks
          // iframe-requested closes with `_clientClosed` and clamps app-range
          // codes, so a contract can't forge 4401 by asking the shell to close
          // its own socket. On a genuine 4401 the shell re-mints its token by
          // reloading itself (bounded, fail-closed) — no iframe request needed.
          if (isTrustedStaleTokenClose(e.code, ws._clientClosed)) {
            triggerRecoveryReload();
          }
        };
        ws.onerror = function () {
          sendToIframe({ __freenet_ws__: true, type: 'error', id: msg.id });
          connections.delete(msg.id);
        };
        break;
      }
      case 'send': {
        var ws = connections.get(msg.id);
        if (ws && ws.readyState === WebSocket.OPEN) {
          ws.send(msg.data);
        }
        break;
      }
      case 'close': {
        var ws = connections.get(msg.id);
        if (ws) {
          // Mark this as an iframe-requested close so the onclose handler above
          // does NOT treat its code as the node's trusted 4401 stale-token
          // signal. Also clamp any app-range (4000-4999) code the iframe asks
          // for down to a normal close, so it can't even surface 4401 to
          // onclose: two independent guards against the contract forging the
          // recovery trigger by requesting a close.
          ws._clientClosed = true;
          ws.close(clampProxiedCloseCode(msg.code), msg.reason);
          connections.delete(msg.id);
        }
        break;
      }
    }
  });

  // Forward runtime hash changes (browser back/forward, manual URL edits)
  function forwardHash() {
    if (location.hash) {
      sendToIframe({
        __freenet_shell__: true,
        type: 'hash',
        hash: location.hash.slice(0, 8192),
      });
    }
  }
  // popstate fires when the user presses back/forward. If the popped entry
  // carries our __freenet_nav__ marker, restore the iframe to the matching
  // subpage. Otherwise, fall back to forwarding the hash. See issue #3839.
  window.addEventListener('popstate', function (ev) {
    var state = ev.state;
    if (
      state &&
      state.__freenet_nav__ === true &&
      typeof state.iframePath === 'string'
    ) {
      // Security: path must still live under this contract's web prefix.
      // A stale state object from a different contract must not be able to
      // redirect the iframe elsewhere.
      if (contractPrefix && state.iframePath.indexOf(contractPrefix) === 0) {
        // No-op if the iframe is already on the target path (e.g. popstate
        // fired from a bfcache restore where iframe state was retained).
        // This avoids a spurious reload that would tear down live WebSocket
        // connections unnecessarily.
        if (iframe.src.indexOf(state.iframePath) === -1) {
          connections.forEach(function (ws) {
            try {
              ws.close();
            } catch (e) {}
          });
          connections.clear();
          iframe.src = state.iframePath;
        }
        return;
      }
    }
    forwardHash();
  });
  window.addEventListener('hashchange', forwardHash);

  // Permission prompt overlay: render a modal in the shell page's DOM
  // (outside the sandboxed iframe) whenever a delegate permission prompt
  // is pending. The shell is trusted and same-origin with the gateway, so
  // the sandboxed contract cannot reach into this DOM. See issue #3836.
  //
  // Every open Freenet tab subscribes to /permission/events/ws (a WebSocket)
  // and renders the overlay as soon as the gateway pushes a `prompt_added`
  // event. When the user responds in one tab, the gateway emits
  // `prompt_removed` and every tab dismisses its card. This was originally a
  // 3-second polling loop with a visibility-skip optimisation that caused the
  // originating tab to silently miss prompts whenever it wasn't foregrounded;
  // a pushed channel eliminates both the polling-floor latency and the
  // visibility race. It was Server-Sent Events until #5213, when per-tab SSE
  // turned out to exhaust the browser's per-origin HTTP connection budget --
  // see the full explanation at `openPermSocket` below.
  // perm-overlay-flow:BEGIN — the delegate permission-prompt overlay and its
  // event channel. #3836 requires that NOTHING in this whole region
  // constructs a browser Notification: delegate permission prompts must render
  // as in-page overlay cards, never as OS notifications a user can miss or
  // dismiss. The Rust guard `shell_page_permission_overlay_present_and_safe`
  // scans this marker-bounded region (NOT a code anchor), so the
  // `prompt_added`/`prompt_removed` handling below — part of the prompt-render
  // flow — is INSIDE the guarded region (#4849 F2). The legitimate
  // message-notification code (showAppNotification) sits far above BEGIN, so it
  // is outside this region and unaffected.
  var overlayRoot = null;
  // Null-prototype for the same reason as removalObservedAt: a key spelled
  // `__proto__` must be an ordinary own key, not a prototype assignment that
  // makes the card unhideable and leaks into every other lookup.
  var overlayCards = Object.create(null); // nonce -> card element
  var OVERLAY_CSS =
    '#__freenet_perm_overlay{position:fixed;inset:0;z-index:2147483647;' +
    'background:rgba(8,10,14,0.62);backdrop-filter:blur(4px);' +
    '-webkit-backdrop-filter:blur(4px);display:none;align-items:center;' +
    'justify-content:center;padding:20px;overflow:auto;' +
    'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;}' +
    '#__freenet_perm_overlay .fn-card{--bg:#0f1419;--fg:#e6e8eb;--card:#1a2028;' +
    '--accent:#3b82f6;--border:#2d3748;--warn:#f59e0b;--muted:#9ca3af;' +
    'background:var(--card);color:var(--fg);border:1px solid var(--border);' +
    'border-radius:14px;padding:28px;max-width:520px;width:100%;margin:12px 0;' +
    'box-shadow:0 12px 40px rgba(0,0,0,0.5);box-sizing:border-box;}' +
    '@media (prefers-color-scheme: light){#__freenet_perm_overlay .fn-card{' +
    '--bg:#f5f5f5;--fg:#1a1a1a;--card:#ffffff;--accent:#2563eb;' +
    '--border:#d1d5db;--warn:#d97706;--muted:#6b7280;' +
    'box-shadow:0 12px 40px rgba(0,0,0,0.18);}}' +
    '#__freenet_perm_overlay .fn-header{display:flex;align-items:center;gap:12px;' +
    'margin-bottom:18px;}' +
    '#__freenet_perm_overlay .fn-icon{font-size:28px;line-height:1;}' +
    '#__freenet_perm_overlay .fn-title{font-size:18px;font-weight:600;margin:0;' +
    'color:var(--fg);}' +
    '#__freenet_perm_overlay .fn-msg-label{font-size:11px;color:var(--muted);' +
    'text-transform:uppercase;letter-spacing:0.5px;margin-bottom:6px;}' +
    '#__freenet_perm_overlay .fn-msg{font-size:15px;line-height:1.5;margin:0 0 22px 0;' +
    'padding:14px 16px;background:var(--bg);border-left:3px solid var(--warn);' +
    'border-radius:4px;white-space:pre-wrap;word-wrap:break-word;color:var(--fg);}' +
    '#__freenet_perm_overlay .fn-msg-pre{font-family:ui-monospace,SFMono-Regular,' +
    'Menlo,Monaco,Consolas,monospace;font-size:12px;line-height:1.45;' +
    'max-height:300px;overflow:auto;}' +
    '#__freenet_perm_overlay .fn-btns{display:flex;gap:10px;flex-wrap:wrap;}' +
    '#__freenet_perm_overlay .fn-btn{padding:10px 20px;border-radius:8px;' +
    'font-size:14px;cursor:pointer;flex:1;min-width:100px;font-weight:500;' +
    'border:1px solid var(--border);background:var(--card);color:var(--fg);' +
    'transition:transform 0.12s, opacity 0.12s, filter 0.12s;font-family:inherit;}' +
    '#__freenet_perm_overlay .fn-btn.primary{background:var(--accent);' +
    'color:#fff;border-color:var(--accent);}' +
    '#__freenet_perm_overlay .fn-btn:hover:not(:disabled){transform:translateY(-1px);' +
    'filter:brightness(1.08);}' +
    '#__freenet_perm_overlay .fn-btn:disabled{opacity:0.55;cursor:not-allowed;}' +
    '#__freenet_perm_overlay .fn-delegate-line{font-size:12px;color:var(--muted);' +
    'margin-top:10px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;}' +
    '#__freenet_perm_overlay .fn-delegate-line .hash{user-select:all;}' +
    '#__freenet_perm_overlay .fn-tech{margin-top:10px;font-size:12px;color:var(--muted);}' +
    '#__freenet_perm_overlay .fn-tech summary{cursor:pointer;user-select:none;}' +
    '#__freenet_perm_overlay .fn-tech dl{margin:8px 0 0 16px;}' +
    '#__freenet_perm_overlay .fn-tech dt{font-weight:600;color:var(--fg);margin-top:6px;}' +
    '#__freenet_perm_overlay .fn-tech dd{margin:2px 0 0 0;font-family:ui-monospace,' +
    'SFMono-Regular,Menlo,Consolas,monospace;word-break:break-all;user-select:all;}' +
    '#__freenet_perm_overlay .fn-timer{margin-top:14px;font-size:12px;' +
    'color:var(--muted);text-align:center;}';
  // Auto-deny duration in seconds, mirroring the standalone /permission/{nonce}
  // fallback page. Tracked client-side only; the server enforces the real
  // timeout and will clear the nonce regardless.
  var OVERLAY_AUTO_DENY_SECONDS = 60;
  function ensureOverlayRoot() {
    if (overlayRoot) return overlayRoot;
    var style = document.createElement('style');
    style.textContent = OVERLAY_CSS;
    document.head.appendChild(style);
    overlayRoot = document.createElement('div');
    overlayRoot.id = '__freenet_perm_overlay';
    overlayRoot.setAttribute('role', 'dialog');
    overlayRoot.setAttribute('aria-modal', 'true');
    overlayRoot.setAttribute('aria-label', 'Delegate permission request');
    document.body.appendChild(overlayRoot);
    // Escape-to-dismiss: routes to the last button in the most-recently-added
    // card, which (by the standard delegate convention Allow Once / Always
    // Allow / Deny) is the Deny button. If the delegate supplied a single
    // label this is a no-op — Escape just does nothing.
    document.addEventListener('keydown', function (e) {
      if (e.key !== 'Escape') return;
      if (!overlayRoot || overlayRoot.style.display === 'none') return;
      var nonces = Object.keys(overlayCards);
      if (nonces.length === 0) return;
      var nonce = nonces[nonces.length - 1];
      var card = overlayCards[nonce];
      var btns = card.querySelectorAll('button');
      if (btns.length < 2) return; // no non-primary option, ignore
      btns[btns.length - 1].click();
      e.preventDefault();
    });
    return overlayRoot;
  }
  function setText(el, text) {
    // textContent avoids any HTML interpretation of delegate-controlled
    // strings. Delegate-provided fields are never parsed as markup.
    el.textContent = text == null ? '' : String(text);
  }
  // Truncate a hash for display: first8…last5. Mirrors truncate_hash() in
  // crates/core/src/server/client_api/permission_prompts.rs so the overlay
  // and the standalone /permission/{nonce} fallback page render identically.
  // Handles multi-byte unicode by iterating Array.from(...) which gives
  // codepoints, not UTF-16 code units.
  function truncateHash(s) {
    if (typeof s !== 'string' || s.length === 0) return '';
    var chars = Array.from(s);
    if (chars.length <= 14) return s;
    return (
      chars.slice(0, 8).join('') +
      '\u2026' +
      chars.slice(chars.length - 5).join('')
    );
  }
  // Render the Caller row from the tagged caller object. Forward-compatible:
  // an unknown `kind` (e.g. a future "delegate" variant from issue #3860)
  // falls through to a neutral "Unknown caller" so the overlay does NOT
  // pretend to render an identity it doesn't understand.
  function formatCaller(caller) {
    if (!caller || typeof caller !== 'object') {
      return { display: 'No app caller', full: '' };
    }
    if (caller.kind === 'webapp' && typeof caller.hash === 'string') {
      return {
        display: 'Freenet app ' + truncateHash(caller.hash),
        full: caller.hash,
      };
    }
    if (caller.kind === 'none') {
      return { display: 'No app caller', full: '' };
    }
    return { display: 'Unknown caller', full: '' };
  }
  function createCard(p) {
    var card = document.createElement('div');
    card.className = 'fn-card';
    card.setAttribute('data-nonce', p.nonce);

    var header = document.createElement('div');
    header.className = 'fn-header';
    var icon = document.createElement('span');
    icon.className = 'fn-icon';
    icon.textContent = '\u{1F512}';
    var title = document.createElement('h1');
    title.className = 'fn-title';
    title.textContent = 'Permission Request';
    header.appendChild(icon);
    header.appendChild(title);
    card.appendChild(header);

    // "Delegate says:" authorship label is non-negotiable: a malicious
    // delegate would otherwise be able to write text like "Freenet verified
    // this request" with no way for the user to tell who authored it. The
    // text below the label is delegate-controlled; the label tells the user
    // that. See the trust-model rationale in permission_prompts.rs.
    var msgLabel = document.createElement('div');
    msgLabel.className = 'fn-msg-label';
    msgLabel.textContent = 'Delegate says:';
    card.appendChild(msgLabel);
    // Try to render the delegate-supplied message as pretty-printed JSON
    // when it parses as JSON. Falls back to a plain paragraph for plain
    // text. The pretty form makes structured token requests legible
    // (#190) — users routinely see one-line blobs like
    //   {"token":{"max_age":"31536000 seconds","tier":"Min10"},...}
    // and have to mentally parse them to make a security decision.
    //
    // Security: still rendered via textContent (setText), so no HTML
    // interpretation. Long values are wrapped via CSS (white-space:
    // pre-wrap on .fn-msg-pre). Render is best-effort: any parse error
    // falls back to the original raw string in a <p>.
    var rawMsg = p.message || 'A delegate is requesting permission.';
    var pretty = null;
    if (typeof rawMsg === 'string' && rawMsg.length > 0) {
      var trimmed = rawMsg.trim();
      if (
        trimmed.length <= 64 * 1024 &&
        (trimmed.charAt(0) === '{' || trimmed.charAt(0) === '[')
      ) {
        try {
          var parsed = JSON.parse(trimmed);
          pretty = JSON.stringify(parsed, null, 2);
          // Cap rendered output at 16 KiB after pretty-printing so a
          // hostile delegate can't force a multi-MiB layout pass.
          if (pretty.length > 16 * 1024) {
            pretty = pretty.slice(0, 16 * 1024) + '\n';
          }
        } catch (e) {
          pretty = null;
        }
      }
    }
    if (pretty !== null) {
      var msgPre = document.createElement('pre');
      msgPre.className = 'fn-msg fn-msg-pre';
      setText(msgPre, pretty);
      card.appendChild(msgPre);
    } else {
      var msg = document.createElement('p');
      msg.className = 'fn-msg';
      setText(msg, rawMsg);
      card.appendChild(msg);
    }

    var buttons = document.createElement('div');
    buttons.className = 'fn-btns';
    var labels =
      Array.isArray(p.labels) && p.labels.length > 0 ? p.labels : ['OK'];
    labels.forEach(function (label, idx) {
      var b = document.createElement('button');
      b.className = 'fn-btn' + (idx === 0 ? ' primary' : '');
      setText(b, label);
      b.addEventListener('click', function () {
        respondToPrompt(p.nonce, idx, card);
      });
      buttons.appendChild(b);
    });
    card.appendChild(buttons);

    // Inline truncated delegate hash, always visible. Gives the user a
    // passive anomaly signal: a returning user who recognises their
    // delegate's fingerprint can spot an impostor without expanding the
    // Technical details disclosure. Full hash is in the Technical details
    // pane below and copyable via user-select: all on .hash.
    var delegateLine = document.createElement('div');
    delegateLine.className = 'fn-delegate-line';
    var delegateLabel = document.createElement('span');
    delegateLabel.textContent = 'Delegate: ';
    delegateLine.appendChild(delegateLabel);
    var delegateHashSpan = document.createElement('span');
    delegateHashSpan.className = 'hash';
    var delegateFull = typeof p.delegate_key === 'string' ? p.delegate_key : '';
    setText(delegateHashSpan, truncateHash(delegateFull) || '(none)');
    if (delegateFull) {
      delegateHashSpan.setAttribute('title', delegateFull);
    }
    delegateLine.appendChild(delegateHashSpan);
    card.appendChild(delegateLine);

    // Technical details disclosure. Holds the full delegate hash and the
    // Caller row. Closed by default — the user's decision is timing/intent
    // ("did I just trigger this?"), not hash matching. Power users hover or
    // copy via user-select: all to audit the unabbreviated value.
    var details = document.createElement('details');
    details.className = 'fn-tech';
    var summary = document.createElement('summary');
    summary.textContent = 'Technical details';
    details.appendChild(summary);
    var dl = document.createElement('dl');
    var dtDelegate = document.createElement('dt');
    dtDelegate.textContent = 'Delegate';
    var ddDelegate = document.createElement('dd');
    setText(ddDelegate, delegateFull || '(none)');
    if (delegateFull) {
      ddDelegate.setAttribute('title', delegateFull);
    }
    var dtCaller = document.createElement('dt');
    dtCaller.textContent = 'Caller';
    var ddCaller = document.createElement('dd');
    var callerRendered = formatCaller(p.caller);
    setText(ddCaller, callerRendered.display);
    if (callerRendered.full) {
      ddCaller.setAttribute('title', callerRendered.full);
    }
    dl.appendChild(dtDelegate);
    dl.appendChild(ddDelegate);
    dl.appendChild(dtCaller);
    dl.appendChild(ddCaller);
    details.appendChild(dl);
    card.appendChild(details);

    // Countdown mirroring the standalone permission page. The real timeout
    // lives server-side; this is a hint for the user that the prompt won't
    // wait forever. On expiry the next poll drops the card via the
    // reconciliation path, so we don't need a local hide here.
    var timer = document.createElement('div');
    timer.className = 'fn-timer';
    var remaining = OVERLAY_AUTO_DENY_SECONDS;
    timer.textContent = 'Auto-deny in ' + remaining + 's';
    card._fnTimerId = setInterval(function () {
      remaining -= 1;
      if (remaining <= 0) {
        clearInterval(card._fnTimerId);
        timer.textContent = 'Auto-denied';
        return;
      }
      timer.textContent = 'Auto-deny in ' + remaining + 's';
    }, 1000);
    card.appendChild(timer);
    return card;
  }
  // Monotonic millisecond clock for the causal-ordering comparison in
  // reconcileFromPending. `Date.now()` is wall-clock and steps BACKWARDS on an
  // NTP correction, a VM resume, or a user changing the system clock; a
  // backwards step between `issuedAt` and a later `showCard` makes the card
  // look older than the request that could not have seen it, which re-opens
  // the exact prompt-destroying window the comparison exists to close.
  // `performance.now()` cannot step backwards. Fall back to Date.now() only
  // where performance is unavailable, which is no worse than before.
  function permNow() {
    return typeof performance !== 'undefined' && performance && performance.now
      ? performance.now()
      : Date.now();
  }
  // When each nonce's removal was OBSERVED, on the monotonic clock. See the
  // add-pass guard in reconcileFromPending.
  //
  // PER NONCE, not one global timestamp. A single shared stamp meant a removal
  // of ANY nonce suppressed the add of EVERY nonce, and on the `resync` path
  // that loss is permanent: resync exists precisely because the server DROPPED
  // `prompt_added` frames, so the socket will never resend them; the socket is
  // healthy, so the 3s poll is stopped and there is no retry; and a
  // `prompt_removed` arriving in the few ms while resync's `/permission/pending`
  // fetch is in flight would skip the dropped prompt forever. It would sit
  // invisible until the server auto-denied it. A backgrounded tab draining a
  // churn burst is exactly what produces the lag AND exactly what delivers a
  // removal in that window, so it is the expected shape of the recovery rather
  // than a contrived race. Suppressing only the nonce actually removed keeps
  // the resurrection fix while removing the collateral.
  //
  // Bounded, and pruned against the OLDEST IN-FLIGHT request rather than a bare
  // wall-clock window. An entry only matters to a reconcile whose `issuedAt`
  // precedes it, so once no outstanding request is older than the entry, the
  // entry can never change an outcome and is safe to drop.
  //
  // A fixed window alone would be wrong in exactly the case that matters: a
  // wedged node leaves `/permission/pending` fetches outstanding for minutes
  // (they carry no timeout, and the poll keeps firing every 3s), so a removal
  // could be pruned while a request older than it was still in flight — and
  // that request landing afterwards would resurrect the answered prompt, the
  // very bug this map exists to prevent. The window is kept as a backstop for
  // the no-requests-in-flight case so a long-lived tab cannot accumulate
  // entries.
  //
  // The in-flight exemption is OVERRIDDEN BY ABSOLUTE AGE, per the project rule
  // that a GC exemption must either expire or be overridden. Without that
  // override this had the exact recurring shape the rule exists to catch: a
  // single `/permission/pending` fetch that never resolves freezes
  // `oldestInFlight` at that instant, every removal recorded afterwards
  // satisfies `at >= oldestInFlight` forever, and neither the record map nor
  // the in-flight list can ever shrink again — a sustained node hang would turn
  // this into unbounded per-tab growth for the rest of the session rather than
  // for the hang's duration.
  //
  // So a request outstanding longer than the hard bound is treated as DEAD and
  // dropped from the in-flight list: no real response is coming, and its
  // absence lets `oldestInFlight` advance so records become collectable again.
  // Records themselves get the same absolute override as a second line of
  // defence, so neither structure depends on the other being correct.
  //
  // `Object.create(null)`: no prototype, so a nonce spelled `__proto__` or
  // `constructor` is an ordinary own key and cannot reach Object.prototype.
  // Nonces are 32 hex chars today, but this must not depend on that.
  // perm-removal-memory:BEGIN
  // Extracted and RUN by shell_bridge_permission_ws.test.mjs. It used to
  // re-implement these in the harness, which meant every test of the last two
  // rounds asserted properties of the duplicate: deleting the real guard,
  // never stamping, or reverting the whole in-flight prune all left the suite
  // green. Keep the markers, and never satisfy one of these names from the
  // test side again.
  var REMOVAL_MEMORY_MS = 60000;
  var REMOVAL_MEMORY_HARD_MS = 600000;
  var removalObservedAt = Object.create(null);
  // `issuedAt` of every reconcile whose response has not landed yet.
  var reconcilesInFlight = [];
  function noteReconcileStarted(issuedAt) {
    reconcilesInFlight.push(issuedAt);
  }
  function noteReconcileFinished(issuedAt) {
    var i = reconcilesInFlight.indexOf(issuedAt);
    if (i >= 0) reconcilesInFlight.splice(i, 1);
  }
  function noteRemovalObserved(nonce) {
    var now = permNow();
    if (typeof nonce === 'string') removalObservedAt[nonce] = now;
    // Drop dead requests FIRST, so the floor they hold can advance.
    var live = [];
    var oldestInFlight = Infinity;
    for (var i = 0; i < reconcilesInFlight.length; i++) {
      var t = reconcilesInFlight[i];
      if (now - t > REMOVAL_MEMORY_HARD_MS) continue;
      live.push(t);
      if (t < oldestInFlight) oldestInFlight = t;
    }
    reconcilesInFlight = live;
    for (var k in removalObservedAt) {
      var at = removalObservedAt[k];
      // Past the absolute bound: collected regardless of what is in flight.
      if (now - at > REMOVAL_MEMORY_HARD_MS) {
        delete removalObservedAt[k];
        continue;
      }
      // Still able to affect an outstanding request: keep.
      if (at >= oldestInFlight) continue;
      if (now - at > REMOVAL_MEMORY_MS) delete removalObservedAt[k];
    }
  }
  function removalObservedSince(nonce, since) {
    var at = removalObservedAt[nonce];
    return at !== undefined && at >= since;
  }
  // perm-removal-memory:END
  function showCard(nonce, card) {
    var root = ensureOverlayRoot();
    root.appendChild(card);
    root.style.display = 'flex';
    // When this card became visible. `reconcileFromPending` compares against
    // it so a snapshot taken BEFORE the card existed cannot hide it. See the
    // causal-ordering note there.
    card._fnShownAt = permNow();
    overlayCards[nonce] = card;
    // Move keyboard focus to the primary button so Enter/Space answer the
    // prompt without requiring a mouse click.
    var primary = card.querySelector('.fn-btn.primary');
    if (primary && typeof primary.focus === 'function') {
      try {
        primary.focus();
      } catch (e) {}
    }
  }
  function hideCard(nonce) {
    // Note the removal BEFORE the early return. Every removal path funnels
    // here — the socket's `prompt_removed`, the 404 from `/respond` meaning
    // another tab answered, and reconcile's own hide pass — so this one line
    // is what keeps `reconcileFromPending`'s add-pass staleness check honest.
    // Above the return on purpose: a `prompt_removed` for a nonce this tab
    // never rendered is still an OBSERVED removal, and it is exactly the case
    // a stale snapshot would otherwise resurrect.
    noteRemovalObserved(nonce);
    var card = overlayCards[nonce];
    if (!card) return;
    if (card._fnTimerId) {
      clearInterval(card._fnTimerId);
      card._fnTimerId = null;
    }
    if (card.parentNode) card.parentNode.removeChild(card);
    delete overlayCards[nonce];
    if (overlayRoot && Object.keys(overlayCards).length === 0) {
      overlayRoot.style.display = 'none';
    }
  }
  function respondToPrompt(nonce, index, card) {
    var btns = card.querySelectorAll('button');
    btns.forEach(function (b) {
      b.disabled = true;
      b.style.opacity = '0.5';
    });
    fetch('/permission/' + encodeURIComponent(nonce) + '/respond', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ index: index }),
    })
      .then(function (r) {
        // 404 means another tab already answered (or it auto-denied) — hide
        // the overlay here as well so the user isn't staring at a dead button.
        if (r.ok || r.status === 404) {
          hideCard(nonce);
        } else {
          btns.forEach(function (b) {
            b.disabled = false;
            b.style.opacity = '1';
          });
        }
      })
      .catch(function () {
        btns.forEach(function (b) {
          b.disabled = false;
          b.style.opacity = '1';
        });
      });
  }
  // Snapshot the current pending list and reconcile against the open overlay
  // cards. Used for initial bootstrap, on `resync` events when a subscriber
  // lagged, and as a fallback while the socket is down or reconnecting.
  //
  // The hide pass is gated on CAUSAL ORDERING, not recency, and that gate is
  // load-bearing: without it this function silently and permanently destroys
  // live prompts. The fetch is async and nothing cancels an in-flight one, so
  // the sequence below is reachable on an ordinary node restart:
  //
  //   1. socket closes -> startFallbackPoll() issues fetch F1 (node is
  //      restarting, so F1 is slow)
  //   2. socket reconnects -> onopen calls stopFallbackPoll(), which clears
  //      the INTERVAL but cannot cancel F1, still in flight
  //   3. prompt X is raised and arrives over the socket -> showCard(X)
  //   4. F1 resolves carrying the PRE-restart list, which has no X -> X is
  //      hidden, with a healthy socket and no poll running to re-add it
  //
  // X then auto-denies at the server timeout and the user never sees it. A
  // generation counter would fix "stale response wins" but NOT step 3->4,
  // because F1 is the newest response at the moment it lands. Comparing each
  // card's `_fnShownAt` against when this request was ISSUED is what makes it
  // correct: a snapshot taken before the card existed can never hide it.
  // perm-reconcile:BEGIN
  // Extracted verbatim by shell_bridge_permission_ws.test.mjs, which runs it
  // against injected `fetch` / `permNow` / card helpers. Keep the markers.
  function reconcileFromPending() {
    var issuedAt = permNow();
    var pending;
    try {
      pending = fetch('/permission/pending');
    } catch (err) {
      // A SYNCHRONOUS throw must not leave a registration behind. Registering
      // before the call meant such a throw skipped the deregistering `.then`
      // entirely and that entry pinned the prune floor forever.
      return;
    }
    // Registered only once the request actually exists, so every registration
    // has a matching deregistration path.
    noteReconcileStarted(issuedAt);
    pending
      .then(function (r) {
        return r.json();
      })
      .then(function (prompts) {
        if (!Array.isArray(prompts)) return;
        var seen = Object.create(null);
        // The ADD pass needs the mirror of the hide pass's causal check. A
        // stale snapshot can otherwise RESURRECT a prompt that was answered
        // after the request went out: F1 is issued and sees X; X is answered
        // in another tab; F1 lands, X is absent from overlayCards, so X is
        // shown again. With a healthy socket nothing then removes the ghost,
        // and the user is looking at a delegate-authored security prompt for a
        // dead nonce until they click it (404 -> hide) or the socket cycles.
        //
        // Skip only the nonce whose OWN removal this snapshot could not have
        // seen. Suppressing every add on any removal is what created a
        // permanent loss on the resync path; see removalObservedAt.
        prompts.forEach(function (p) {
          if (!p || typeof p.nonce !== 'string') return;
          seen[p.nonce] = true;
          if (overlayCards[p.nonce]) return;
          if (removalObservedSince(p.nonce, issuedAt)) return;
          showCard(p.nonce, createCard(p));
        });
        Object.keys(overlayCards).forEach(function (nonce) {
          if (seen[nonce]) return;
          var card = overlayCards[nonce];
          // Only hide what this snapshot could actually have observed.
          // `>=`, not `>`. With `permNow()` on `performance.now()` — a
          // sub-millisecond float — an exact tie is essentially unreachable, so
          // this is about which way to resolve one if it ever happens rather
          // than a case we expect. Keep the card: the two errors are not
          // symmetric. A card kept one beat too long is corrected by the next
          // event or reconcile; a card hidden wrongly destroys a live security
          // prompt outright.
          if (card && card._fnShownAt >= issuedAt) return;
          hideCard(nonce);
        });
      })
      .catch(function () {})
      // Deregister on EVERY outcome — including the non-array early return and
      // a rejected fetch — or a single failure would pin the prune floor
      // forever and the map would grow without bound.
      .then(function () {
        noteReconcileFinished(issuedAt);
      });
  }
  // perm-reconcile:END

  // Open a WebSocket so prompts appear with no polling delay and on every
  // open Freenet tab regardless of foreground/background state.
  //
  // Why a WebSocket rather than Server-Sent Events (#5213): every open tab
  // holds this channel for its entire life, and every Freenet app is served
  // from the SAME origin. Over SSE that permanently consumed one of the
  // browser's ~6 HTTP/1.1 connections per origin PER TAB, so at six open tabs
  // the budget was gone and a seventh tab's own document, wasm and asset
  // requests queued behind the held-open streams forever. Nothing errored, so
  // no fallback fired and the app sat on "Loading..." indefinitely. Browsers
  // pool WebSockets separately and far more generously (~255 per profile in
  // Chrome, 200 in Firefox), so this channel no longer competes with page
  // loads. Do NOT move this back onto a long-lived HTTP request.
  //
  // Unlike EventSource, a WebSocket does NOT auto-reconnect, so we reconnect
  // ourselves with exponential backoff plus jitter. While disconnected we run
  // the same 3-second /permission/pending poll the SSE path used, so a tab
  // whose socket fails (node restart, cap rejection, transient error) still
  // receives prompt updates. The poll stops as soon as the socket re-opens,
  // and every (re)connect re-bootstraps from /permission/pending so nothing
  // is missed across the gap.
  // Reconnect state. Backoff starts at 1s and doubles to a 30s ceiling,
  // reset to 1s once the socket has proved stable.
  // perm-ws-machine:BEGIN — the stateful half of the permission-event socket:
  // connection state, reconnect scheduling, and the open/close transitions.
  // shell_bridge_permission_ws.test.mjs extracts this whole region and runs it
  // against stubbed `WebSocket`/timers/`fetch`, so the reconnect behaviour is
  // tested rather than merely name-pinned. Everything this region needs from
  // outside (showCard/hideCard/createCard/overlayCards/reconcileFromPending/
  // startFallbackPoll/stopFallbackPoll/location) is referenced but not
  // defined here, and the test supplies those.
  // The idempotency guard here is load-bearing as of #5213: openPermSocket
  // starts the poll before the handshake resolves AND onclose starts it again,
  // so every retry cycle calls this twice. Without the guard each cycle would
  // leak a fresh interval hammering /permission/pending forever — an unbounded
  // silent loop of exactly the shape this file's comments warn about. Kept
  // inside the marker region so the test drives the REAL interval bookkeeping
  // rather than a stub that cannot express the leak.
  var fallbackPollHandle = null;
  function startFallbackPoll() {
    if (fallbackPollHandle !== null) return;
    fallbackPollHandle = setInterval(reconcileFromPending, 3000);
    reconcileFromPending();
  }
  function stopFallbackPoll() {
    if (fallbackPollHandle === null) return;
    clearInterval(fallbackPollHandle);
    fallbackPollHandle = null;
  }
  var permSocket = null;
  var permReconnectDelay = 1000;
  var permReconnectHandle = null;
  var permStableTimer = null;
  var PERM_RECONNECT_MAX = 30000;
  // How long a socket must stay open before we treat it as healthy and reset
  // the backoff. See the note in `onopen`.
  var PERM_STABLE_AFTER = 10000;
  var permConsecutiveFailures = 0;
  var PERM_WARN_AFTER_FAILURES = 5;

  // perm-ws-decisions:BEGIN — pure helpers for the permission WebSocket,
  // extracted so shell_bridge_permission_ws.test.mjs can exercise them
  // directly. Keep them free of DOM/global access: everything they need
  // arrives as an argument, which is what makes them testable at all.
  //
  // This block must stay NESTED INSIDE `perm-overlay-flow`. Hoisting these
  // pure helpers to module scope is the obvious next refactor, and it would
  // break the #4849 F2 guard: every remaining prompt-added / prompt-removed
  // event-name literal inside the guarded region now lives in
  // `permEventAction` below, and F2's non-vacuity check asserts the region
  // still contains them. (Written WITHOUT the quoted literals on purpose —
  // spelling them here makes the pin match its own signpost and pass
  // vacuously, which is the self-match class AGENTS.md says has shipped
  // twice.) It fails loudly, but the message points at the guard
  // rather than at the move, so this note is the signpost.
  function permSocketUrl(loc) {
    // Derive the scheme from the page so a TLS-served shell upgrades to wss
    // rather than tripping the browser's mixed-content block.
    var scheme = loc.protocol === 'https:' ? 'wss://' : 'ws://';
    return scheme + loc.host + '/permission/events/ws';
  }

  // Exponential backoff with a ceiling. Separate from the jitter below so the
  // growth curve can be asserted without a stubbed RNG.
  function nextPermReconnectDelay(current, max) {
    return Math.min(current * 2, max);
  }

  // +/-20% jitter so every tab recovering from one node restart doesn't
  // reconnect in lockstep and hammer the subscriber cap. `rand` is
  // `Math.random()`'s output, passed in so the spread is testable.
  function permReconnectJitter(delay, rand) {
    return delay * (0.8 + rand * 0.4);
  }

  // Classify one inbound envelope. Returns the action the imperative wrapper
  // should take, so malformed or delegate-controlled payloads are rejected in
  // one auditable place rather than across three branches. Event names and
  // `data` shapes are identical to the SSE stream this replaced; only the
  // framing differs (the name rides inside the JSON envelope because a
  // WebSocket frame has no `event:` slot).
  function permEventAction(envelope) {
    if (!envelope || typeof envelope.event !== 'string')
      return { action: 'ignore' };
    var data = envelope.data;
    if (envelope.event === 'resync') return { action: 'resync' };
    if (
      envelope.event === 'prompt_added' ||
      envelope.event === 'prompt_removed'
    ) {
      if (!data || typeof data.nonce !== 'string') return { action: 'ignore' };
      return {
        action: envelope.event === 'prompt_added' ? 'add' : 'remove',
        nonce: data.nonce,
        data: data,
      };
    }
    return { action: 'ignore' };
  }
  // perm-ws-decisions:END

  function handlePermEnvelope(envelope) {
    var decision = permEventAction(envelope);
    if (decision.action === 'add') {
      if (overlayCards[decision.nonce]) return;
      showCard(decision.nonce, createCard(decision.data));
    } else if (decision.action === 'remove') {
      hideCard(decision.nonce);
    } else if (decision.action === 'resync') {
      // The server emits `resync` when its broadcast channel laps a slow
      // subscriber. Reconcile from the polling endpoint instead of clearing
      // first: the reconcile path's diff already adds new cards and hides
      // ones that disappeared, with no flicker on cards that survive.
      reconcileFromPending();
    }
  }

  function schedulePermReconnect() {
    if (permReconnectHandle !== null) return;
    // Make a persistently degraded tab diagnosable. A tab stuck on the 3s poll
    // (a proxy eating the upgrade, a node stuck at the subscriber cap, a
    // downgraded node with no /ws route) still shows prompts, so it is
    // otherwise indistinguishable from a healthy one. #5213 was hard to find
    // for exactly that reason: nothing errored, so nothing surfaced. One line
    // at a threshold, not per attempt, so it cannot become its own noise.
    permConsecutiveFailures++;
    if (permConsecutiveFailures === PERM_WARN_AFTER_FAILURES) {
      try {
        console.warn(
          'Freenet: permission-event WebSocket has failed ' +
            PERM_WARN_AFTER_FAILURES +
            ' times; falling back to polling. Prompts still work but arrive up to 3s late.',
        );
      } catch (e) {}
    }
    var jittered = permReconnectJitter(permReconnectDelay, Math.random());
    permReconnectHandle = setTimeout(function () {
      permReconnectHandle = null;
      openPermSocket();
    }, jittered);
    permReconnectDelay = nextPermReconnectDelay(
      permReconnectDelay,
      PERM_RECONNECT_MAX,
    );
  }

  function openPermSocket() {
    // Poll FIRST, and let `onopen` stop it. The poll is the always-on safety
    // net and the socket is the accelerator, which is what this design claims
    // to be. Starting it only from `onclose` left one gap: if the upgrade
    // HANGS rather than fails — a reverse proxy swallowing `Upgrade:`, the
    // common WebSocket-through-proxy failure — no close event fires, so a tab
    // showed no prompts and ran no poll until the browser's own handshake
    // timeout. This also covers the initial bootstrap, since startFallbackPoll
    // reconciles immediately.
    startFallbackPoll();
    // Retire any previous socket BEFORE opening a new one. The identity guard
    // on `onclose` exists for the case where a future trigger opens a second
    // socket, but on its own it makes that case WORSE: the guard's early
    // return also skips the `permStableTimer` cleanup, so socket A's timer
    // outlives A, fires, and both resets the backoff for a dead socket and
    // nulls the handle belonging to socket B — silently defeating the
    // anti-flap protection in precisely the scenario the guard names. Clearing
    // here means the invariant holds however this function comes to be called.
    if (permStableTimer !== null) {
      clearTimeout(permStableTimer);
      permStableTimer = null;
    }
    // A pending reconnect is deliberately LEFT ARMED. Two reviewers reached
    // opposite conclusions here and the tiebreak is which failure self-heals:
    //
    //   clearing it   — a hung upgrade (no open, no close: the common
    //                   WebSocket-through-proxy failure this file names above)
    //                   leaves no pending retry at all, so the tab sits on the
    //                   3s poll for the rest of its life.
    //   leaving it    — the stale timer may fire and close a HEALTHY socket,
    //                   which immediately triggers onclose -> reconnect. One
    //                   wasted cycle, then back to normal.
    //
    // Permanent degradation loses to a transient blip, so the timer stays. The
    // completing half, if a `visibilitychange`/`online` trigger is ever added,
    // is a handshake watchdog rather than clearing this.
    if (permSocket !== null) {
      var stale = permSocket;
      permSocket = null;
      try {
        stale.close();
      } catch (err) {}
    }
    var sock;
    try {
      sock = new WebSocket(permSocketUrl(location));
    } catch (err) {
      // Constructor throws on a malformed URL or a blocked scheme. Treat it
      // exactly like a dropped socket: the poll is already running, so just
      // schedule the retry.
      schedulePermReconnect();
      return;
    }
    permSocket = sock;
    sock.onopen = function () {
      stopFallbackPoll();
      reconcileFromPending();
      // Reset the backoff only once the socket has PROVEN stable, not the
      // instant it opens. A peer that accepts the upgrade and drops it
      // immediately (a reverse proxy that half-supports WebSockets) would
      // otherwise pin the cycle at open -> reset to 1s -> close -> retry in
      // ~1s, forever, with no growth and two /permission/pending fetches per
      // cycle. That is the same shape of silent unbounded loop as #5213.
      permStableTimer = setTimeout(function () {
        permStableTimer = null;
        permReconnectDelay = 1000;
        // Reset the failure counter HERE, with the backoff, not on bare open.
        // Resetting it the instant the socket opened meant the accept-then-drop
        // case — the exact scenario the stability window exists for — grew the
        // backoff as intended but never reached PERM_WARN_AFTER_FAILURES, so a
        // permanently degraded tab stayed undiagnosable.
        permConsecutiveFailures = 0;
      }, PERM_STABLE_AFTER);
    };
    sock.onmessage = function (e) {
      try {
        handlePermEnvelope(JSON.parse(e.data));
      } catch (err) {}
    };
    // Recovery is driven from `close` alone. The socket always fires `close`
    // after `error`, so handling both would double-schedule the reconnect and
    // halve the effective backoff.
    //
    // Everything here is inside the identity guard. Only the CURRENT socket's
    // close may drive recovery: if a future trigger (a `visibilitychange` or
    // `online` handler, the natural next addition) ever opens a second socket,
    // a stale socket's close would otherwise schedule a reconnect that
    // orphans the live one, leaking a server-side slot until its send timeout.
    sock.onclose = function () {
      if (permSocket !== sock) return;
      permSocket = null;
      if (permStableTimer !== null) {
        clearTimeout(permStableTimer);
        permStableTimer = null;
      }
      startFallbackPoll();
      schedulePermReconnect();
    };
  }
  // perm-ws-machine:END

  if (typeof WebSocket !== 'undefined') {
    // openPermSocket starts the fallback poll itself, which also performs the
    // initial bootstrap reconcile, so there is no separate bootstrap call
    // here and no redundant fetch per retry.
    openPermSocket();
  } else {
    // WebSocket missing in some embedded webviews -- fall back to the
    // legacy 3-second poll so users on those clients still see prompts.
    startFallbackPoll();
  }
  // perm-overlay-flow:END
}