nsh-core 0.8.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
//! Capabilities: what an app may reach outside its VM.
//!
//! An app declares them in `nsh.json` (`"capabilities"`); the app embedding
//! nsh may grant less ([`Access`]): a request must be allowed by both.
//! Everything is denied unless listed. `nsh.json` and signed packages are
//! read leniently ([`Capabilities::from_json_lenient`]): a newer NSH may
//! declare what this one does not know, which is then not granted (the
//! toolchain warns of it, so a typo is still seen at build time).
//!
//! ```json
//! "capabilities": {
//!   "network": {
//!     "hosts": ["api.example.com", "*.cdn.example.com"],
//!     "http": [{ "host": "quotes.example.com", "methods": ["GET"], "pathPrefix": "/v1/" }],
//!     "sockets": ["mqtt.example.com:8883"]
//!   },
//!   "webview": { "hosts": ["*.example.com"], "input": true },
//!   "statusBar": true,
//!   "application": true,
//!   "homeDir": true,
//!   "host": ["getUserInfo", "bridge.*"],
//!   "openUrl": { "schemes": ["https", "mailto"] }
//! }
//! ```
//!
//! `share` lets the app show the system's share sheet (`Share` of
//! `nsh-extra`, which checks it): what it shares leaves the app where the user sends
//! it, and the files it shares are also checked against `fs.read`.
//! `openUrl` lets the app open URLs outside it (`openUrl` of `nsh/device`,
//! [`crate::open_url`]: the browser, the mail or phone app, other apps'
//! schemes): `true` for every scheme, `{ "schemes": [...] }` for those
//! listed. `network` covers `fetch` (every redirect is checked again), remote
//! images (also canvas images and `Image.getSize` / `prefetch`) and video
//! sources; `asset:` URIs are always allowed. WebSockets are HTTP upgrades:
//! a `ws:` / `wss:` URL is checked as a GET of the same URL over `http:` /
//! `https:` (or under its own scheme, for legacy rules that list it).
//! `network.sockets` grants raw TCP (`net.connect`) to exact `host:port`
//! pairs only: no wildcards, and neither `hosts` nor `http` grants imply
//! one. `webview` lists the hosts a web view may show and navigate to (its
//! pages' own subresources are the web content's business); its `input`
//! lets a web view's ref give the page trusted input (`sendInput`), which
//! carries user activation and is granted only when declared, also for
//! apps without a declaration; its `runtimeOrigin` lets a web view's
//! `allowOrigin` prop add one origin, decided while the app runs, to the
//! hosts that web view may show ([`WebOrigin`]), also granted only when
//! declared. `host` lists
//! the functions of the embedding app `nsh/host` may call: names (1 to 128
//! of `[A-Za-z0-9_.:-]`, without `..`; the core refuses calls of any other
//! name), or prefixes of them ending in `*` (`true`: all of them); the
//! host's events need no grant, the host sends them. `application` lets
//! the app act on the application as a whole (`nsh/desktop`'s main window,
//! application menu, tray, global shortcuts, `Application.quit`, `restart`
//! and `setLaunchAtLogin`, and `nsh/mobile`'s `AppSettings.open`, the app's
//! page in the system's settings; context menus, shown in the app's own
//! view, and the windows `windows` grants need none); `homeDir` lets `os.homedir()` tell the
//! user's home directory. An app without `"capabilities"` (a standalone
//! app, its developer's own) retains unrestricted HTTP, web views, the
//! status bar, the clipboard, the picker, the share sheet, speech
//! recognition, opening URLs, the application and the home directory; raw sockets, processes, the
//! filesystem and the host's functions always require an explicit
//! declaration.

//! A `network.http` rule names a `host` (a pattern, as in `hosts`); every
//! other key narrows it and is optional: `methods` (any when left out),
//! `schemes` or `scheme` (any of http, https, ws, wss), `port` (any),
//! `paths` (exact) and `pathPrefixes` / `pathPrefix` / `path_prefixes`
//! (whole segments: `/v1` covers `/v1` and `/v1/x`, not `/v10`). Without
//! paths or prefixes a rule covers every path. Rules serialize in one form:
//! `schemes` and `pathPrefixes`.

use std::{
    borrow::Cow,
    path::{Component, Path, PathBuf},
};

use serde_json::{Map, Value};

/// A host pattern: `*` (any host), `*.example.com` (its subdomains) or a
/// host name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostPattern(String);

impl HostPattern {
    /// Parses a pattern (lower-cased).
    pub fn new(pattern: &str) -> Result<Self, String> {
        let p = pattern.trim().to_ascii_lowercase();
        let host = p.strip_prefix("*.").unwrap_or(&p);
        let valid = p == "*"
            || (!host.is_empty()
                && host.chars().all(|c| {
                    c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '[' | ']')
                }));
        if valid {
            Ok(Self(p))
        } else {
            Err(format!("invalid host pattern `{pattern}`"))
        }
    }

    /// Whether `host` (lower case) matches.
    pub fn matches(&self, host: &str) -> bool {
        match self.0.strip_prefix("*.") {
            _ if self.0 == "*" => true,
            Some(suffix) => {
                host.len() > suffix.len() + 1 && host.ends_with(suffix) && {
                    let dot = host.len() - suffix.len() - 1;
                    host.as_bytes()[dot] == b'.'
                }
            }
            None => self.0 == host,
        }
    }

    /// The pattern as written (lower case).
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Whether it is `*`, which covers every host.
    fn is_any(&self) -> bool {
        self.0 == "*"
    }
}

/// A finer HTTP grant: a host, narrowed by any of methods, schemes, a port,
/// exact paths and path prefixes (each left empty: any).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HttpGrant {
    /// The host.
    pub host: HostPattern,
    /// Upper-case methods; empty: any.
    pub methods: Vec<String>,
    /// Lower-case schemes (`http`, `https`, `ws`, `wss`); empty: any of them.
    pub schemes: Vec<String>,
    /// The port, the scheme's default when the URL has none; `None`: any.
    pub port: Option<u16>,
    /// Exact paths (without the query), as requests send them: WHATWG's
    /// serialization (`/my%20photos`), which parsing a grant writes them
    /// in; a path written otherwise matches nothing.
    pub paths: Vec<String>,
    /// Path prefixes, matching whole segments (`/v1` covers `/v1/x`, not
    /// `/v10`). With `paths`, a path matching either is covered; with
    /// neither, every path is. Written as `paths` are.
    pub path_prefixes: Vec<String>,
}

impl Default for HttpGrant {
    fn default() -> Self {
        Self {
            host: HostPattern(String::new()),
            methods: Vec::new(),
            schemes: Vec::new(),
            port: None,
            paths: Vec::new(),
            path_prefixes: Vec::new(),
        }
    }
}

impl HttpGrant {
    fn allows(&self, method: &str, url: &UrlParts<'_>) -> bool {
        let default_port = match url.scheme.as_str() {
            "https" | "wss" => 443,
            _ => 80,
        };
        let path = url.path.split(['?', '#']).next().unwrap_or("/");
        let path = if path.is_empty() { "/" } else { path };
        self.host.matches(&url.host)
            && (self.methods.is_empty()
                || self.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
            && (self.schemes.is_empty() || self.schemes.contains(&url.scheme))
            && self
                .port
                .is_none_or(|p| url.port.unwrap_or(default_port) == p)
            && ((self.paths.is_empty() && self.path_prefixes.is_empty())
                || self.paths.iter().any(|allowed| allowed == path)
                || self.path_prefixes.iter().any(|prefix| {
                    path.strip_prefix(prefix.as_str()).is_some_and(|tail| {
                        tail.is_empty() || prefix.ends_with('/') || tail.starts_with('/')
                    })
                }))
    }

    /// Whether it grants `method` on every host, port and path of `scheme`:
    /// all a URL that parsers read differently can be held to.
    fn allows_anywhere(&self, method: &str, scheme: &str) -> bool {
        self.host.is_any()
            && (self.methods.is_empty()
                || self.methods.iter().any(|m| m.eq_ignore_ascii_case(method)))
            && (self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme))
            && self.port.is_none()
            && self.paths.is_empty()
            && self.path_prefixes.is_empty()
    }
}

/// `capabilities.network`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct NetworkGrants {
    /// Reachable with any method.
    pub hosts: Vec<HostPattern>,
    /// Finer grants.
    pub http: Vec<HttpGrant>,
    /// Raw TCP destinations (`net.connect`).
    pub sockets: Vec<SocketGrant>,
}

/// One raw TCP destination: an exact host and port, written `host:port`
/// (`[::1]:port` for IPv6). A socket bypasses every HTTP rule (methods,
/// paths, schemes), so it is granted per port and never by a pattern.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SocketGrant {
    host: String,
    port: u16,
}

impl SocketGrant {
    /// Parses `host:port` (host lower-cased; port 1 to 65535).
    pub fn new(grant: &str) -> Result<Self, String> {
        let invalid = || {
            format!(
                "invalid socket grant `{grant}`: expected an exact `host:port` (`[::1]:port` for IPv6), without wildcards"
            )
        };
        let (host, port) = grant.trim().rsplit_once(':').ok_or_else(invalid)?;
        let port = port
            .parse::<u16>()
            .ok()
            .filter(|p| *p != 0)
            .ok_or_else(invalid)?;
        let host = host.to_ascii_lowercase();
        let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
            Some(v6)
                if !v6.is_empty()
                    && v6
                        .chars()
                        .all(|c| c.is_ascii_hexdigit() || matches!(c, ':' | '.')) =>
            {
                v6.to_owned()
            }
            Some(_) => return Err(invalid()),
            None if !host.is_empty()
                && host
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')) =>
            {
                host.trim_end_matches('.').to_owned()
            }
            None => return Err(invalid()),
        };
        Ok(Self { host, port })
    }

    /// The host (lower case, IPv6 without brackets).
    pub fn host(&self) -> &str {
        &self.host
    }

    /// The port.
    pub fn port(&self) -> u16 {
        self.port
    }

    /// The `host:port` form [`Self::new`] reads.
    pub fn to_string_form(&self) -> String {
        if self.host.contains(':') {
            format!("[{}]:{}", self.host, self.port)
        } else {
            format!("{}:{}", self.host, self.port)
        }
    }
}

/// Commands an app may execute. Names are exact, without shell expansion.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct ProcessGrants {
    /// Exact executable names or absolute executable paths.
    pub execute: Vec<String>,
    /// The app may ask its host to handle an exit request.
    pub exit: bool,
    /// Additional environment variable names visible to the app.
    pub env: Vec<String>,
}

/// Filesystem roots an app may read or write. `${dataDir}` is resolved by
/// the host to this app's own data directory, never to a JS supplied root.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct FileGrants {
    /// Roots available for read operations.
    pub read: Vec<String>,
    /// Roots available for mutation operations.
    pub write: Vec<String>,
}

/// Host-selected anchors for manifest paths. Apps cannot supply these roots.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct TrustedPaths {
    /// The application source/package directory.
    pub plugin_dir: Option<PathBuf>,
    /// The native user's home directory, when known.
    pub home_dir: Option<PathBuf>,
}
impl TrustedPaths {
    /// Expand one manifest root against host anchors. Relative roots are
    /// anchored to the application directory. Unknown anchors never grant access.
    pub fn resolve_root(&self, root: &str, data_dir: &Path) -> Result<PathBuf, String> {
        validate_path_pattern(root)?;
        for (placeholder, anchor) in [
            ("${dataDir}", Some(data_dir)),
            ("${pluginDir}", self.plugin_dir.as_deref()),
            ("${homeDir}", self.home_dir.as_deref()),
        ] {
            if let Some(tail) = root.strip_prefix(placeholder) {
                let anchor = anchor
                    .filter(|p| absolute(p))
                    .ok_or_else(|| format!("host anchor {placeholder} unavailable"))?;
                // Component by component: `/` separates nothing in a
                // verbatim Windows anchor.
                let tail: PathBuf = tail.split('/').filter(|part| !part.is_empty()).collect();
                return within(anchor, &tail, root);
            }
        }
        let path = PathBuf::from(root);
        if absolute(&path) {
            Ok(path)
        } else {
            let anchor = self
                .plugin_dir
                .as_deref()
                .filter(|p| absolute(p))
                .ok_or_else(|| {
                    "host application directory unavailable for relative filesystem root".to_owned()
                })?;
            within(anchor, &path, root)
        }
    }
}

/// `path` without `.` and `..`, resolved by its text.
pub(crate) fn lexical(path: &Path) -> PathBuf {
    use std::path::Component;
    let mut out = PathBuf::new();
    for part in path.components() {
        match part {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => (),
            other => out.push(other.as_os_str()),
        }
    }
    out
}

/// The canonical form of the nearest existing ancestor, with the rest
/// appended.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn resolved(path: &Path) -> Result<PathBuf, String> {
    let mut current = path.to_path_buf();
    let mut tail = Vec::new();
    loop {
        if let Ok(mut real) = canonicalize(&current) {
            real.extend(tail.into_iter().rev());
            return Ok(real);
        }
        let name = current
            .file_name()
            .ok_or("invalid filesystem path")?
            .to_owned();
        if !current.pop() {
            return Err("invalid filesystem path".into());
        }
        tail.push(name);
    }
}

/// The rest of `path` past `root`, when `path` is in it (component by
/// component; ignoring ASCII case on Windows, as its file systems do).
pub(crate) fn inside(path: &Path, root: &Path) -> Option<PathBuf> {
    let mut rest = path.components();
    for part in root.components() {
        let next = rest.next()?;
        let same = if cfg!(windows) {
            next.as_os_str()
                .to_string_lossy()
                .eq_ignore_ascii_case(&part.as_os_str().to_string_lossy())
        } else {
            next == part
        };
        if !same {
            return None;
        }
    }
    Some(rest.collect())
}

/// The rest of `path` in root `(expanded, canonical)`: under either form
/// (`/var/…` and `/private/var/…` on macOS).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn in_root(path: &Path, (expanded, canonical): &(PathBuf, PathBuf)) -> Option<PathBuf> {
    inside(path, canonical).or_else(|| inside(path, expanded))
}

/// Whether apps have the native file system here that `capabilities.fs`
/// grants (`fs/promises`, local media files, shared files): on every
/// native OS (the desktops, iOS, Android — the capability confines each
/// call to the roots the app declares, whatever the sandbox around
/// them), never on the web, whose `fs/promises` works on the host's
/// private virtual file system and whose pages name no local file.
pub fn native_files(os: crate::platform::Os) -> bool {
    cfg!(not(target_arch = "wasm32")) && os != crate::platform::Os::Web
}

/// The `capabilities.fs.read` roots local media files are read under, as
/// `fs/promises` reads files: the app's declared roots and the host's grant
/// (which narrows them), their anchors (`${dataDir}`, `${pluginDir}`,
/// `${homeDir}`) expanded and resolved once, when they are made
/// ([`Access::media_url`]).
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
pub struct MediaFiles {
    /// The declared roots, expanded and canonical (`/var/…` and
    /// `/private/var/…` on macOS).
    declared: Vec<(PathBuf, PathBuf)>,
    /// The host grant's, when it has one.
    granted: Option<Vec<(PathBuf, PathBuf)>>,
}

impl MediaFiles {
    /// `access`'s read roots, expanded against `data_dir` and `paths`.
    /// Where the platform has no file system for apps (`available`
    /// false: the web, as for `fs/promises`), none.
    pub fn new(
        access: &Access,
        data_dir: Option<&Path>,
        paths: &TrustedPaths,
        available: bool,
    ) -> Self {
        #[cfg(target_arch = "wasm32")]
        {
            let _ = (access, data_dir, paths, available);
            Self::default()
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            if !available {
                return Self::default();
            }
            let data = data_dir.map(Path::to_path_buf).unwrap_or_default();
            let roots = |grants: &Capabilities| {
                grants
                    .fs
                    .read
                    .iter()
                    .filter_map(|root| {
                        let expanded = lexical(&paths.resolve_root(root, &data).ok()?);
                        let canonical = resolved(&expanded).ok()?;
                        Some((expanded, canonical))
                    })
                    .collect()
            };
            Self {
                declared: roots(&access.declared),
                granted: access.granted.as_ref().map(roots),
            }
        }
    }

    /// Opens `path` (what [`Access::media_url`] granted) to read through
    /// the declared root that holds it, as `fs/promises` reads: every
    /// component is opened inside the root, so a link made after the check
    /// cannot lead out of it. `None` with no roots (an app reading what the
    /// platform allows): the caller opens the path itself.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn open(&self, path: &Path) -> Option<std::io::Result<std::fs::File>> {
        if self.declared.is_empty() {
            return None;
        }
        let refused = || std::io::Error::new(std::io::ErrorKind::PermissionDenied, "not granted");
        let path = lexical(path);
        if !self
            .declared
            .iter()
            .any(|root| in_root(&path, root).is_some())
        {
            return Some(Err(refused()));
        }
        // Opened under the narrowest root that grants it: the host's grant
        // when there is one (inside a declared root), so a link in it cannot
        // reach the rest of a wider declared root.
        let granted: Vec<&(PathBuf, PathBuf)> = match &self.granted {
            Some(roots) => roots
                .iter()
                .filter(|(_, canonical)| {
                    self.declared
                        .iter()
                        .any(|(_, declared)| inside(canonical, declared).is_some())
                })
                .collect(),
            None => self.declared.iter().collect(),
        };
        // The innermost root holding it (a nested root may be reached
        // through a link in its parent's).
        let Some(((_, canonical), relative)) = granted
            .into_iter()
            .filter_map(|root| Some((root, in_root(&path, root)?)))
            .max_by_key(|((_, canonical), _)| canonical.components().count())
        else {
            return Some(Err(refused()));
        };
        Some((|| {
            let dir = crate::runtime::fs::confined::open_root(canonical)?;
            let file = crate::runtime::fs::confined::open_file(&dir, &relative, false)?;
            Ok(file.into_std())
        })())
    }

    /// `path`'s canonical form, if a declared root holds it and the host's
    /// grant does too. Symlinks are resolved here, not by the loader: the
    /// platform's loaders open what they are given, with nothing to keep
    /// them in a root (`fs/promises` works in the opened root instead).
    fn readable(&self, path: &Path) -> Option<PathBuf> {
        #[cfg(target_arch = "wasm32")]
        {
            let _ = path;
            None
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            if !absolute(path) || self.declared.is_empty() {
                return None;
            }
            // By its text first, as `fs/promises` checks: a path outside
            // the roots is refused with no disk work on the engine thread.
            let path = lexical(path);
            let within = |roots: &[(PathBuf, PathBuf)]| {
                roots.iter().any(|root| in_root(&path, root).is_some())
            };
            if !within(&self.declared) || !self.granted.as_deref().is_none_or(within) {
                return None;
            }
            // Then resolved, on every check (a path granted once may be a
            // link out of the root by the next), as `authorize_file`
            // resolves: a link whose target does not exist is refused, not
            // taken for a file to come.
            #[cfg(test)]
            RESOLVES.with(|n| n.set(n.get() + 1));
            let real = resolved_path(&path).ok()?;
            let holds = |roots: &[(PathBuf, PathBuf)]| {
                roots
                    .iter()
                    .any(|(_, canonical)| inside(&real, canonical).is_some())
            };
            (holds(&self.declared) && self.granted.as_deref().is_none_or(holds)).then_some(real)
        }
    }
}

#[cfg(test)]
thread_local! {
    /// How many local media paths this thread resolved on the disk (a
    /// test's evidence that a path outside the roots was not).
    static RESOLVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// How many local media paths this thread has resolved on the disk.
#[cfg(test)]
pub(crate) fn resolves() -> usize {
    RESOLVES.with(std::cell::Cell::get)
}

/// Virtual browser paths use Unix roots. `Path::is_absolute` on
/// wasm32-unknown-unknown always returns false because it has no OS prefix.
pub(crate) fn absolute(path: &Path) -> bool {
    if cfg!(target_arch = "wasm32") {
        path.has_root()
    } else {
        path.is_absolute()
    }
}

/// `tail` joined to `anchor`, when it stays there: names only. On Windows
/// a drive (`C:/Windows`), a share (`\\srv\share`) or a rooted path
/// (`\Users`) would replace or leave the anchor in `join`.
fn within(anchor: &Path, tail: &Path, root: &str) -> Result<PathBuf, String> {
    use std::path::Component;
    let names = tail
        .components()
        .all(|c| matches!(c, Component::Normal(_) | Component::CurDir));
    let mut path = anchor.to_path_buf();
    path.extend(tail.components().filter(|c| *c != Component::CurDir));
    if names && path.starts_with(anchor) {
        Ok(path)
    } else {
        Err(format!("filesystem root `{root}` leaves its anchor"))
    }
}

/// Whether environment names `a` and `b` are one variable: ignoring ASCII
/// case on Windows, whose environment does; exactly elsewhere (`lang` is
/// not `LANG` on Unix).
pub(crate) fn env_names_match(a: &str, b: &str) -> bool {
    if cfg!(windows) {
        a.eq_ignore_ascii_case(b)
    } else {
        a == b
    }
}

/// What a web view's page may capture (`capabilities.webview.media`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WebMedia {
    /// `"microphone"`: audio input.
    Microphone,
    /// `"camera"`: video input.
    Camera,
}

impl WebMedia {
    /// Its name in `capabilities.webview.media`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Microphone => "microphone",
            Self::Camera => "camera",
        }
    }
}

/// What an app may do (one declaration, or one grant).
/// Start with [`Self::default`] and set the fields to grant; new capabilities
/// default to denied.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct Capabilities {
    /// Explicit native subprocess grants.
    pub process: ProcessGrants,
    /// Explicit native filesystem grants.
    pub fs: FileGrants,
    /// `fetch`, remote images and video.
    pub network: NetworkGrants,
    /// The hosts web views may show; `None`: no web views.
    pub webview: Option<Vec<HostPattern>>,
    /// Web views may take trusted input (`sendInput`, `webview.input`):
    /// never without a declaration ([`Capabilities::all`] leaves it off).
    pub webview_input: bool,
    /// A web view's `allowOrigin` adds one origin to the hosts it may show
    /// (`webview.runtimeOrigin`): never without a declaration
    /// ([`Capabilities::all`] leaves it off).
    pub webview_runtime_origin: bool,
    /// What web views' pages may capture (`webview.media`): never without a
    /// declaration ([`Capabilities::all`] leaves it empty).
    pub webview_media: Vec<WebMedia>,
    /// The app may set the status bar.
    pub status_bar: bool,
    /// The app may read and write the system clipboard (`nsh/clipboard`).
    pub clipboard: bool,
    /// The app may show the system's picker (`nsh/picker`): the files the
    /// user picks in it reach the app.
    pub picker: bool,
    /// The app may show the system's share sheet (`Share` of `nsh-extra`): the
    /// text, links and files it shares leave the app where the user sends
    /// them.
    pub share: bool,
    /// The app may recognize the user's speech (`Speech` of `nsh-extra`): the
    /// microphone listens while a session runs, and the transcript reaches
    /// the app.
    pub speech: bool,
    /// The app may show notifications and set its badge (`Notifications` of
    /// `nsh`). The user's permission is the system's, on top of this.
    pub notifications: bool,
    /// The app may play sound (`Sound` and `AudioPlayer` of `nsh`).
    pub audio: bool,
    /// The app may act on the application as a whole: the main window, the
    /// application menu, the tray, global shortcuts, quitting, restarting
    /// and launching at login (`nsh/desktop`), and the app's page in the
    /// system's settings (`nsh/mobile`'s `AppSettings`).
    pub application: bool,
    /// `os.homedir()` may tell the user's home directory.
    pub home_dir: bool,
    /// The functions of the embedding app `nsh/host` may call: names, or
    /// prefixes ending in `*` (`"*"`: all); empty: none, also for apps
    /// without a declaration ([`Capabilities::all`]).
    pub host: Vec<String>,
    /// The URLs the app may open outside it (`openUrl` of `nsh/device`);
    /// `None`: none.
    pub open_url: Option<OpenUrlGrant>,
    /// The windows the app may open and what they may do (`nsh/desktop`'s
    /// `Window`); `None`: no window of the app's own. The first window needs
    /// the grant too: no window is privileged.
    pub windows: Option<WindowsGrant>,
}

/// The windows an app may open (`capabilities.windows`). Overlays,
/// click-through windows and capture protection, which can pass for the
/// system's UI over other apps, are granted only when declared.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct WindowsGrant {
    /// The kinds it may open; empty: every kind but `overlay`, which needs
    /// [`Self::overlay`] as well.
    pub kinds: Vec<crate::desktop::WindowKind>,
    /// The levels its windows may float at; empty: every level.
    pub levels: Vec<crate::desktop::WindowLevel>,
    /// How many windows it may have open at once, its first window included;
    /// `None`: any number.
    pub max: Option<u32>,
    /// Overlays and click-through windows (`pointerEvents: "none"` or
    /// `"box-none"`).
    pub overlay: bool,
}

impl WindowsGrant {
    fn allows_kind(&self, kind: crate::desktop::WindowKind) -> bool {
        use crate::desktop::WindowKind;
        if kind == WindowKind::Overlay && !self.overlay {
            return false;
        }
        self.kinds.is_empty() || self.kinds.contains(&kind)
    }

    fn allows_level(&self, level: crate::desktop::WindowLevel) -> bool {
        self.levels.is_empty() || self.levels.contains(&level)
    }
}

/// Which URLs an app may open outside it (`capabilities.openUrl`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct OpenUrlGrant {
    /// The schemes it may open, lower case (`https`, `mailto`, `tel`);
    /// empty: every scheme (`"openUrl": true`).
    pub schemes: Vec<String>,
}

impl OpenUrlGrant {
    /// Whether it grants URLs of `scheme` (lower case).
    pub fn allows(&self, scheme: &str) -> bool {
        self.schemes.is_empty() || self.schemes.iter().any(|s| s == scheme)
    }
}

/// The parts of a URL the checks look at.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UrlParts<'a> {
    /// Lower-case scheme.
    pub scheme: String,
    /// Lower-case host (without port or user info).
    pub host: String,
    /// The path (and query), `/` when empty.
    pub path: &'a str,
    /// Explicit URL port.
    pub port: Option<u16>,
}

/// Splits an absolute URL into scheme, host and path; `None` when it has no
/// `scheme://host`, or when URL parsers would read it differently: a
/// backslash before the query, an ASCII control character, or a host with
/// percent-encoding or a forbidden host code point.
pub fn parse_url(url: &str) -> Option<UrlParts<'_>> {
    read_url(url).ok()
}

/// What a refusal of `url` advises: the host to add to
/// `capabilities.{capability}`, or, for a URL without parts, how to write
/// it, since adding the URL itself would never grant it.
pub(crate) fn grant_advice(url: &str, capability: &str) -> String {
    match parse_url(url) {
        Some(parts) => format!(
            "add `{}` to capabilities.{capability} in nsh.json",
            parts.host
        ),
        None => NO_HOST_ADVICE.to_owned(),
    }
}

/// [`grant_advice`] for a media source, read as [`Access::media_url`] reads
/// it: a local file is the `fs` capability's; a protocol-relative source
/// (`//host/…`) names the host it resolves to against `base`, the page's
/// address, and without one has no scheme to load with.
pub(crate) fn media_grant_advice(uri: &str, base: Option<&str>) -> String {
    if native_relative(uri, base) {
        return RELATIVE_ADVICE.to_owned();
    }
    if starts_with_ignoring_case(uri, "asset:") && !is_inside_assets(uri) {
        return ASSET_ADVICE.to_owned();
    }
    if media_capability(uri, base) == "fs" {
        return LOCAL_FILE_ADVICE.to_owned();
    }
    let unambiguous = !uri.contains('\\') && !uri.bytes().any(|b| b.is_ascii_control());
    if scheme_of(uri).is_none() && uri.starts_with("//") && unambiguous {
        let resolved = base
            .and_then(|base| url::Url::parse(base).ok())
            .and_then(|base| base.join(uri).ok());
        return match resolved {
            Some(url) => grant_advice(url.as_str(), "network"),
            None => NO_SCHEME_ADVICE.to_owned(),
        };
    }
    grant_advice(uri, "network")
}

/// The capability that grants media source `uri` against `base`, as
/// [`Access::media_url`] reads it: `"fs"` for a local file (a `file:` URL;
/// with no base, an absolute or drive path), else `"network"`.
pub(crate) fn media_capability(uri: &str, base: Option<&str>) -> &'static str {
    if starts_with_ignoring_case(uri, "asset:") || native_relative(uri, base) {
        return "fs";
    }
    let local =
        (base.is_none() || starts_with_ignoring_case(uri, "file:")) && local_file(uri).is_some();
    if local { "fs" } else { "network" }
}

/// [`media_grant_advice`] for a relative path in a native app.
const RELATIVE_ADVICE: &str = "a relative path names no file in a native app: name a bundled file as `asset:/…`, or import it";

/// [`media_grant_advice`] for a bundled file whose path leaves the app's
/// files, which no grant covers.
const ASSET_ADVICE: &str = "bundled files are named by a path inside the app's files";

/// [`media_grant_advice`] for a local file.
const LOCAL_FILE_ADVICE: &str =
    "a local file is read under capabilities.fs.read in nsh.json: add a root that holds it";

/// [`media_grant_advice`] for a protocol-relative source without a base.
const NO_SCHEME_ADVICE: &str =
    "it names no scheme and has no page to take one from: write it as an http(s) URL";

/// [`grant_advice`] for a URL without parts.
const NO_HOST_ADVICE: &str = "it names no host a grant could add: write it as an http(s) URL with a host, a backslash as `%5C` and no control characters";

/// Whether media source `uri` is the app's own, which stays as written: a
/// bundled file (`asset:`) or bytes it has (`data:`, `blob:`, an in-memory
/// image's `data:…;nsh-key=` key).
fn is_own_media(uri: &str) -> bool {
    ["asset:", "data:", "blob:"]
        .iter()
        .any(|prefix| starts_with_ignoring_case(uri, prefix))
}

/// Whether the bundled file `url` (`asset:/<path>`, as the host joins it to
/// its asset directory) stays inside the app's files whichever way a host
/// maps it: the path is relative, and no segment is empty, `.` or `..`
/// (encoded or not) or holds a backslash, a NUL or a colon (a Windows
/// drive), raw or percent-encoded, or an encoded `/`. Hosts join the path
/// to their directory as it comes, so they never see one that escapes it.
/// `fetch` checks the path a request reads (`nsh-engine`); a media source
/// is checked whole, query included, since the image loader joins it as
/// written.
pub fn is_inside_assets(url: &str) -> bool {
    let Some(path) = url.get(6..).and_then(|rest| rest.strip_prefix('/')) else {
        return false;
    };
    path.split('/').all(|segment| {
        let bytes = segment.as_bytes();
        let encoded = |code: &[u8; 3]| bytes.windows(3).any(|w| w.eq_ignore_ascii_case(code));
        !only_dots(bytes)
            && !bytes.iter().any(|b| matches!(b, b'\\' | b'\0' | b':'))
            && ![b"%2f", b"%5c", b"%00", b"%3a"]
                .iter()
                .any(|code| encoded(code))
    })
}

/// Whether `segment` is empty, `.` or `..`, a dot written as itself or as
/// `%2e` (any case).
fn only_dots(segment: &[u8]) -> bool {
    let (mut dots, mut at) = (0, 0);
    while at < segment.len() {
        if segment[at] == b'.' {
            at += 1;
        } else if segment[at..].len() >= 3
            && segment[at] == b'%'
            && segment[at + 1] == b'2'
            && segment[at + 2].eq_ignore_ascii_case(&b'e')
        {
            at += 3;
        } else {
            return false;
        }
        dots += 1;
        if dots > 2 {
            return false;
        }
    }
    true
}

/// Whether `uri`, read as WHATWG's parser reads it, names a host: it has
/// a scheme or starts with `//` or a backslash ([`Access::media_url`]).
fn names_host(uri: &str) -> bool {
    let stripped = whatwg_stripped(uri);
    scheme_of(&stripped).is_some()
        || stripped.starts_with("//")
        || stripped.starts_with('\\')
        || stripped.starts_with("/\\")
}

/// Whether media source `uri` is a relative path in a native app (no
/// `base`), which names no file of the app's ([`Access::media_url`]).
fn native_relative(uri: &str, base: Option<&str>) -> bool {
    base.is_none()
        && !uri.trim().is_empty()
        && !is_own_media(uri)
        && local_file(uri).is_none()
        && !names_host(uri)
}

/// `path` (starting with `/`) as a request sends it: WHATWG's serialization
/// (`/my photos` → `/my%20photos`, `/über` → `/%C3%BCber`). `None` when a
/// segment is `.` or `..`, encoded or not and as WHATWG splits it (at `\\`
/// too, tabs and newlines dropped), which a request never sends.
fn path_as_sent(path: &str) -> Option<String> {
    // Read as WHATWG reads it: tabs and newlines dropped, a backslash a `/`.
    let path: String = path
        .chars()
        .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
        .map(|c| if c == '\\' { '/' } else { c })
        .collect();
    let dots = path.split('/').any(|segment| {
        let segment = segment.to_ascii_lowercase().replace("%2e", ".");
        segment == "." || segment == ".."
    });
    if dots {
        return None;
    }
    let url = url::Url::parse(&format!("http://h{path}")).ok()?;
    Some(url.path().to_owned())
}

/// Whether `text` starts with `prefix`, ignoring ASCII case.
fn starts_with_ignoring_case(text: &str, prefix: &str) -> bool {
    text.get(..prefix.len())
        .is_some_and(|head| head.eq_ignore_ascii_case(prefix))
}

/// The local file media source `uri` names, if it names one: a `file:` URL's
/// path (`Some(None)` when it names none), an absolute path, or a Windows
/// drive path (`C:\…`, `C:/…`, which WHATWG's parser would take for a
/// one-letter scheme). A path starting with `//` or `/\` names a host.
fn local_file(uri: &str) -> Option<Option<PathBuf>> {
    if starts_with_ignoring_case(uri, "file:") {
        return Some(file_url_path(uri));
    }
    let drive = matches!(uri.as_bytes(), [d, b':', b'\\' | b'/', ..] if d.is_ascii_alphabetic());
    let rooted = uri.starts_with('/') && !uri.starts_with("//") && !uri.starts_with("/\\");
    (drive || rooted).then(|| Some(PathBuf::from(uri)))
}

/// The path `file:` URL `uri` names, decoded as a URL is (percent
/// encoding included). What [`media_url`] checks is what the platforms'
/// loaders read: they resolve `file:` sources with this, never by
/// stripping the prefix. The web has no local files to name.
#[doc(hidden)]
pub fn file_url_path(uri: &str) -> Option<PathBuf> {
    #[cfg(target_arch = "wasm32")]
    {
        let _ = uri;
        None
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        url::Url::parse(uri).ok()?.to_file_path().ok()
    }
}

/// The `file:` URL of `path` (which [`file_url_path`] reads back).
fn file_url_of(path: &Path) -> Option<String> {
    #[cfg(target_arch = "wasm32")]
    {
        let _ = path;
        None
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        url::Url::from_file_path(path).ok().map(String::from)
    }
}

/// `uri` as WHATWG's parser reads it: without leading and trailing spaces
/// and C0 controls, and without tabs and newlines.
fn whatwg_stripped(uri: &str) -> Cow<'_, str> {
    let trimmed = uri.trim_matches(|c: char| c <= ' ');
    if trimmed.contains(['\t', '\n', '\r']) {
        Cow::Owned(trimmed.replace(['\t', '\n', '\r'], ""))
    } else {
        Cow::Borrowed(trimmed)
    }
}

/// The scheme `uri` starts with (`[A-Za-z][A-Za-z0-9+.-]*:`), if any.
fn scheme_of(uri: &str) -> Option<&str> {
    let (scheme, _) = uri.split_once(':')?;
    let mut chars = scheme.chars();
    (chars.next()?.is_ascii_alphabetic()
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')))
    .then_some(scheme)
}

/// Whether an app without capabilities loads media source `uri`: as before
/// its sources were read as WHATWG's parser reads them, anything without
/// `://`, and URLs `allows_http` grants.
fn media_as_written(uri: &str, allows_http: impl Fn(&str) -> bool) -> bool {
    !uri.contains("://") || is_own_media(uri) || local_file(uri).is_some() || allows_http(uri)
}

/// `serialized`, or `written` when the two are the same.
fn written_or(written: &str, serialized: String) -> Cow<'_, str> {
    if serialized == written {
        Cow::Borrowed(written)
    } else {
        Cow::Owned(serialized)
    }
}

/// Why [`read_url`] gives no parts.
enum Unread {
    /// No `scheme://host`.
    NotUrl,
    /// A URL parsers read as different hosts, ports or paths, with its
    /// lower-case scheme: only a grant of every host covers it.
    Ambiguous(String),
}

/// [`parse_url`], saying why a string has no parts.
fn read_url(url: &str) -> Result<UrlParts<'_>, Unread> {
    let (scheme, rest) = url.split_once("://").ok_or(Unread::NotUrl)?;
    if scheme.is_empty()
        || !scheme
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
    {
        return Err(Unread::NotUrl);
    }
    let scheme = scheme.to_ascii_lowercase();
    // WHATWG's parser (the web views') ends the host at a backslash and reads
    // one in the path as `/`, and it drops tab, LF and CR; Foundation's
    // `NSURL` (native media loads) keeps a backslash in the user info. Before
    // the query, one could name a host or path here other than the one that
    // loads; in the query no parser reads it as a host or path.
    let head = url.split(['?', '#']).next().unwrap_or(url);
    if head.contains('\\') || url.bytes().any(|b| b.is_ascii_control()) {
        return Err(Unread::Ambiguous(scheme));
    }
    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let (authority, path) = rest.split_at(end);
    // User info ends at the last `@`: `https://good.com@evil.com/` is evil.com.
    let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
    let host = if let Some(v6) = host_port.strip_prefix('[') {
        format!("[{}]", v6.split_once(']').ok_or(Unread::NotUrl)?.0)
    } else {
        host_port.split(':').next().unwrap_or_default().to_owned()
    };
    if host.is_empty() {
        return Err(Unread::NotUrl);
    }
    // WHATWG's parser decodes a host's percent-encoding and refuses its
    // forbidden host code points: a host with either is not the one granted.
    if host.contains(['%', ' ', '<', '>', '^', '|'])
        || (!host_port.starts_with('[') && host.contains(['[', ']']))
    {
        return Err(Unread::Ambiguous(scheme));
    }
    let port = if host_port.starts_with('[') {
        host_port
            .split_once(']')
            .and_then(|(_, rest)| rest.strip_prefix(':'))
            .map(str::parse::<u16>)
            .transpose()
    } else {
        host_port
            .split_once(':')
            .map(|(_, port)| port.parse::<u16>())
            .transpose()
    }
    .map_err(|_| Unread::NotUrl)?;
    Ok(UrlParts {
        scheme,
        host: host.to_ascii_lowercase().trim_end_matches('.').to_owned(),
        path: if path.is_empty() { "/" } else { path },
        port,
    })
}

/// One origin a web view may show besides the hosts `webview.hosts`
/// grants: its `allowOrigin`, for an origin known only while the app runs
/// (a server the user named, a computer on the local network). Exact:
/// the same scheme (`http` or `https`), the same host (ASCII, compared in
/// lower case, never a subdomain or a suffix) and the same port (the
/// scheme's default when none is written).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct WebOrigin {
    scheme: String,
    host: String,
    port: u16,
}

impl WebOrigin {
    /// Reads `origin`, `scheme://host[:port]` with `http` or `https` and
    /// nothing else: no user info, no path but `/`, no query or fragment,
    /// an ASCII host (IDNA hosts are written in punycode) and no wildcard.
    pub fn parse(origin: &str) -> Result<Self, String> {
        let refused = |why: &str| Err(format!("`{origin}` is not an origin: {why}"));
        let Some((scheme, rest)) = origin.split_once("://") else {
            return refused("it is not `http://host` or `https://host`");
        };
        let scheme = scheme.to_ascii_lowercase();
        if !matches!(scheme.as_str(), "http" | "https") {
            return refused("its scheme is not http or https");
        }
        let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
        let (authority, after) = rest.split_at(end);
        if !matches!(after, "" | "/") {
            return refused("it has a path, a query or a fragment");
        }
        if authority.contains('@') {
            return refused("it has user info");
        }
        if !authority.is_ascii() || authority.contains('*') {
            return refused("its host is not an ASCII host name or address");
        }
        let Ok(parts) = read_url(origin) else {
            return refused("its host or port cannot be read");
        };
        let port = parts.port.unwrap_or(default_port(&scheme));
        Ok(Self {
            scheme,
            host: parts.host,
            port,
        })
    }

    /// Whether `url` is at this origin: its scheme, host and port (the
    /// scheme's default when it writes none). A `blob:` URL is at the
    /// origin it embeds; an opaque one (`blob:null/…`) is at none.
    pub fn contains(&self, url: &str) -> bool {
        let url = blob_origin(url).unwrap_or(url);
        read_url(url).is_ok_and(|parts| {
            parts.scheme == self.scheme
                && parts.host == self.host
                && parts.port.unwrap_or(default_port(&parts.scheme)) == self.port
        })
    }
}

/// `scheme://host`, with `:port` when it is not the scheme's default.
impl std::fmt::Display for WebOrigin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}://{}", self.scheme, self.host)?;
        if self.port != default_port(&self.scheme) {
            write!(f, ":{}", self.port)?;
        }
        Ok(())
    }
}

/// The hosts one web view may show and navigate to, narrower than the
/// app's grant: its `allowNavigation`, the same host patterns as
/// `webview.hosts` (`*`, `*.example.com`, a host name). It only takes
/// away: an `http` or `https` URL must match one of them as well as be
/// granted by the app's capabilities, and an empty list refuses every web
/// page. URLs of other schemes (`about:blank`, the app's own `file://`
/// page and URL schemes) are left to the app's rules. The check runs where
/// the platform decides a navigation, before its request is made.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WebHosts(Vec<HostPattern>);

impl WebHosts {
    /// Reads `patterns`, failing on the first that is not a host pattern.
    pub fn parse<S: AsRef<str>>(patterns: &[S]) -> Result<Self, String> {
        patterns
            .iter()
            .map(|p| HostPattern::new(p.as_ref()))
            .collect::<Result<Vec<_>, _>>()
            .map(Self)
    }

    /// Whether `url` stays within these hosts: true for a URL that is not
    /// `http` or `https`.
    pub fn allows(&self, url: &str) -> bool {
        let url = blob_origin(url).unwrap_or(url);
        let scheme = url.split_once(':').map(|(s, _)| s.to_ascii_lowercase());
        if !matches!(scheme.as_deref(), Some("http" | "https")) {
            return true;
        }
        match read_url(url) {
            Ok(parts) => self.0.iter().any(|h| h.matches(&parts.host)),
            Err(Unread::Ambiguous(_)) => self.0.iter().any(HostPattern::is_any),
            Err(Unread::NotUrl) => false,
        }
    }

    /// The patterns, as written (lower case).
    pub fn patterns(&self) -> impl Iterator<Item = &str> {
        self.0.iter().map(HostPattern::as_str)
    }
}

/// The patterns one per line, which [`WebHosts::parse`] reads back after
/// splitting the lines.
impl std::fmt::Display for WebHosts {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (i, p) in self.0.iter().enumerate() {
            if i > 0 {
                f.write_str("\n")?;
            }
            f.write_str(p.as_str())?;
        }
        Ok(())
    }
}

/// The port a URL of `scheme` uses when it writes none (0: none).
fn default_port(scheme: &str) -> u16 {
    match scheme {
        "http" => 80,
        "https" => 443,
        _ => 0,
    }
}

/// The origin a `blob:` URL embeds (`blob:<origin>/<id>`, as
/// `URL.createObjectURL` writes it), when `url` is one. A blob's origin is
/// its creator's: a browser only makes a blob URL in the origin of the
/// document that made it, so checking the embedded origin checks the page.
fn blob_origin(url: &str) -> Option<&str> {
    url.get(..5)
        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("blob:"))
        .then(|| &url[5..])
        .filter(|origin| !origin.is_empty())
}

impl Capabilities {
    /// Legacy unrestricted APIs for apps without a declaration. Socket,
    /// process, filesystem and host function grants stay empty and always
    /// require explicit opt-in.
    pub fn all() -> Self {
        let any = vec![HostPattern("*".into())];
        Self {
            network: NetworkGrants {
                hosts: any.clone(),
                http: Vec::new(),
                sockets: Vec::new(),
            },
            webview: Some(any),
            status_bar: true,
            clipboard: true,
            picker: true,
            share: true,
            speech: true,
            notifications: true,
            audio: true,
            application: true,
            home_dir: true,
            open_url: Some(OpenUrlGrant::default()),
            // Every kind and level, but no overlays or capture protection.
            windows: Some(WindowsGrant::default()),
            // The host's functions are never granted without a declaration.
            ..Self::default()
        }
    }

    /// Parses `capabilities` strictly: unknown keys are errors. What NSH
    /// itself reads (`nsh.json`, bundles, packages, grants) goes through
    /// [`Capabilities::from_json_lenient`], which a newer NSH's keys do not
    /// break.
    pub fn from_json(value: &Value) -> Result<Self, String> {
        Self::parse(value, None)
    }

    /// Parses capabilities a newer NSH may have written (`nsh.json`,
    /// bundles, signed packages, grants): what it cannot read never grants
    /// anything. An unknown capability is not granted; an unknown key inside
    /// one (a restriction this runtime cannot apply) drops what it is in,
    /// the whole capability or the `http` grant; a value of a form it does
    /// not know drops its capability (or its `http` grant), and the others
    /// stay. Declared capabilities allow only what they list, so what is
    /// dropped is denied. Only a declaration that is no object is denied
    /// whole. Returns what was dropped (`capabilities.bluetooth`, ...) with
    /// the capabilities.
    pub fn from_json_lenient(value: &Value) -> Result<(Self, Vec<String>), String> {
        let mut dropped = Vec::new();
        let Value::Object(obj) = value else {
            dropped.push(format!(
                "capabilities ({value} is not an object): all of them"
            ));
            return Ok((Self::default(), dropped));
        };
        // Each capability on its own: one that fails is dropped, alone.
        let mut readable = Map::new();
        for (key, v) in obj {
            let one = Value::Object(Map::from_iter([(key.clone(), v.clone())]));
            let mut its_dropped = Vec::new();
            match Self::parse(&one, Some(&mut its_dropped)) {
                Ok(_) => {
                    dropped.append(&mut its_dropped);
                    readable.insert(key.clone(), v.clone());
                }
                Err(e) => dropped.push(format!("capabilities.{key} ({e})")),
            }
        }
        let caps = Self::parse(&Value::Object(readable), Some(&mut Vec::new()))?;
        Ok((caps, dropped))
    }

    /// `dropped`: lenient, recording what unknown keys dropped; `None`:
    /// strict.
    fn parse(value: &Value, mut dropped: Option<&mut Vec<String>>) -> Result<Self, String> {
        const KNOWN: [&str; 16] = [
            "windows",
            "network",
            "webview",
            "statusBar",
            "clipboard",
            "picker",
            "share",
            "speech",
            "notifications",
            "audio",
            "application",
            "homeDir",
            "openUrl",
            "process",
            "fs",
            "host",
        ];
        let obj = object(value, "capabilities")?;
        for key in obj.keys().filter(|k| !KNOWN.contains(&k.as_str())) {
            match dropped.as_deref_mut() {
                // A capability of a newer runtime: not granted.
                Some(dropped) => dropped.push(format!("capabilities.{key}")),
                None => return Err(unknown_key("capabilities", key, &KNOWN)),
            }
        }
        let lenient = dropped.is_some();
        // The `http` grants dropped, recorded once `check` is done with
        // `dropped`.
        let mut http_dropped = Vec::new();
        // Whether `obj` (`what`) has only `keys`; lenient, an unknown key
        // drops `name` (what it is in): recorded, and `false` returned.
        let mut check = |obj: &Map<String, Value>,
                         what: &str,
                         keys: &[&str],
                         name: &str|
         -> Result<bool, String> {
            let Some(key) = obj.keys().find(|k| !keys.contains(&k.as_str())) else {
                return Ok(true);
            };
            match dropped.as_deref_mut() {
                Some(dropped) => {
                    dropped.push(format!("{name} (unknown key `{key}`)"));
                    Ok(false)
                }
                None => Err(unknown_key(what, key, keys)),
            }
        };
        let mut caps = Capabilities::default();
        if let Some(network) = obj.get("network") {
            let network = object(network, "capabilities.network")?;
            if check(
                network,
                "capabilities.network",
                &["hosts", "http", "sockets"],
                "capabilities.network",
            )? {
                if let Some(hosts) = network.get("hosts") {
                    caps.network.hosts = patterns(hosts, "capabilities.network.hosts")?;
                }
                if let Some(sockets) = network.get("sockets") {
                    caps.network.sockets = strings(sockets, "capabilities.network.sockets")?
                        .iter()
                        .map(|s| SocketGrant::new(s))
                        .collect::<Result<_, _>>()?;
                }
                if let Some(http) = network.get("http") {
                    let list = http
                        .as_array()
                        .ok_or("capabilities.network.http must be an array")?;
                    for (i, grant) in list.iter().enumerate() {
                        let name = format!("capabilities.network.http[{i}]");
                        let parsed = object(grant, "capabilities.network.http[]").and_then(|g| {
                            let keys = [
                                "host",
                                "methods",
                                "scheme",
                                "schemes",
                                "port",
                                "paths",
                                "pathPrefix",
                                "pathPrefixes",
                                "path_prefixes",
                            ];
                            Ok(
                                match check(g, "capabilities.network.http[]", &keys, &name)? {
                                    true => Some(http_grant(g)?),
                                    false => None,
                                },
                            )
                        });
                        match parsed {
                            Ok(Some(grant)) => caps.network.http.push(grant),
                            Ok(None) => {}
                            // Lenient: a grant of a form this runtime does
                            // not know is dropped alone.
                            Err(e) if lenient => http_dropped.push(format!("{name} ({e})")),
                            Err(e) => return Err(e),
                        }
                    }
                }
            }
        }
        if let Some(webview) = obj.get("webview") {
            let webview = object(webview, "capabilities.webview")?;
            if check(
                webview,
                "capabilities.webview",
                &["hosts", "input", "media", "runtimeOrigin"],
                "capabilities.webview",
            )? {
                caps.webview = Some(match webview.get("hosts") {
                    Some(hosts) => patterns(hosts, "capabilities.webview.hosts")?,
                    None => Vec::new(),
                });
                if let Some(input) = webview.get("input") {
                    caps.webview_input = input
                        .as_bool()
                        .ok_or("capabilities.webview.input must be a boolean")?;
                }
                if let Some(runtime_origin) = webview.get("runtimeOrigin") {
                    caps.webview_runtime_origin = runtime_origin
                        .as_bool()
                        .ok_or("capabilities.webview.runtimeOrigin must be a boolean")?;
                }
                if let Some(media) = webview.get("media") {
                    caps.webview_media = strings(media, "capabilities.webview.media")?
                        .iter()
                        .map(|kind| match kind.as_str() {
                            "microphone" => Ok(WebMedia::Microphone),
                            "camera" => Ok(WebMedia::Camera),
                            _ => Err(format!(
                                "capabilities.webview.media takes `microphone` and `camera`, not `{kind}`"
                            )),
                        })
                        .collect::<Result<_, _>>()?;
                }
            }
        }
        if let Some(status_bar) = obj.get("statusBar") {
            caps.status_bar = status_bar
                .as_bool()
                .ok_or("capabilities.statusBar must be a boolean")?;
        }
        if let Some(clipboard) = obj.get("clipboard") {
            caps.clipboard = clipboard
                .as_bool()
                .ok_or("capabilities.clipboard must be a boolean")?;
        }
        if let Some(picker) = obj.get("picker") {
            caps.picker = picker
                .as_bool()
                .ok_or("capabilities.picker must be a boolean")?;
        }
        if let Some(share) = obj.get("share") {
            caps.share = share
                .as_bool()
                .ok_or("capabilities.share must be a boolean")?;
        }
        if let Some(speech) = obj.get("speech") {
            caps.speech = speech
                .as_bool()
                .ok_or("capabilities.speech must be a boolean")?;
        }
        if let Some(notifications) = obj.get("notifications") {
            caps.notifications = notifications
                .as_bool()
                .ok_or("capabilities.notifications must be a boolean")?;
        }
        if let Some(audio) = obj.get("audio") {
            caps.audio = audio
                .as_bool()
                .ok_or("capabilities.audio must be a boolean")?;
        }
        if let Some(application) = obj.get("application") {
            caps.application = application
                .as_bool()
                .ok_or("capabilities.application must be a boolean")?;
        }
        if let Some(home_dir) = obj.get("homeDir") {
            caps.home_dir = home_dir
                .as_bool()
                .ok_or("capabilities.homeDir must be a boolean")?;
        }
        if let Some(open_url) = obj.get("openUrl") {
            match open_url {
                Value::Bool(granted) => {
                    caps.open_url = granted.then(OpenUrlGrant::default);
                }
                Value::Object(grant) => {
                    if check(
                        grant,
                        "capabilities.openUrl",
                        &["schemes"],
                        "capabilities.openUrl",
                    )? {
                        let schemes = match grant.get("schemes") {
                            Some(schemes) => strings(schemes, "capabilities.openUrl.schemes")?,
                            None => Vec::new(),
                        };
                        if schemes.iter().any(|s| {
                            s.is_empty()
                                || !s.starts_with(|c: char| c.is_ascii_alphabetic())
                                || !s
                                    .chars()
                                    .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
                        }) {
                            return Err(
                                "capabilities.openUrl.schemes needs URL schemes (`https`, `mailto`)"
                                    .into(),
                            );
                        }
                        caps.open_url = Some(OpenUrlGrant {
                            schemes: schemes.iter().map(|s| s.to_ascii_lowercase()).collect(),
                        });
                    }
                }
                _ => {
                    return Err(
                        "capabilities.openUrl must be a boolean or an object of `schemes`".into(),
                    );
                }
            }
        }
        if let Some(process) = obj.get("process") {
            let process = object(process, "capabilities.process")?;
            if check(
                process,
                "capabilities.process",
                &["execute", "exit", "env"],
                "capabilities.process",
            )? {
                if let Some(execute) = process.get("execute") {
                    caps.process.execute = strings(execute, "capabilities.process.execute")?;
                    if caps.process.execute.iter().any(|s| !valid_command(s)) {
                        return Err("capabilities.process.execute needs exact executable names or absolute paths".into());
                    }
                }
                if let Some(exit) = process.get("exit") {
                    caps.process.exit = exit
                        .as_bool()
                        .ok_or("capabilities.process.exit must be a boolean")?;
                }
                if let Some(env) = process.get("env") {
                    caps.process.env = strings(env, "capabilities.process.env")?;
                    if caps
                        .process
                        .env
                        .iter()
                        .any(|name| name.is_empty() || name.contains(['=', '\0']))
                    {
                        return Err(
                            "capabilities.process.env needs nonempty environment variable names"
                                .into(),
                        );
                    }
                }
            }
        }
        if let Some(fs) = obj.get("fs") {
            let fs = object(fs, "capabilities.fs")?;
            if check(fs, "capabilities.fs", &["read", "write"], "capabilities.fs")? {
                for (key, target) in [("read", &mut caps.fs.read), ("write", &mut caps.fs.write)] {
                    if let Some(value) = fs.get(key) {
                        *target = strings(value, &format!("capabilities.fs.{key}"))?;
                        for root in target.iter() {
                            validate_path_pattern(root)?;
                        }
                    }
                }
            }
        }
        if let Some(windows) = obj.get("windows") {
            match windows {
                Value::Bool(granted) => caps.windows = granted.then(WindowsGrant::default),
                Value::Object(grant) => {
                    if check(
                        grant,
                        "capabilities.windows",
                        &["kinds", "levels", "max", "overlay"],
                        "capabilities.windows",
                    )? {
                        caps.windows = Some(windows_grant(grant)?);
                    }
                }
                _ => {
                    return Err(
                        "capabilities.windows must be a boolean or an object of `kinds`, `levels`, `max` and `overlay`"
                            .into(),
                    );
                }
            }
        }
        if let Some(host) = obj.get("host") {
            caps.host = match host {
                Value::Bool(all) => {
                    if *all {
                        vec!["*".into()]
                    } else {
                        Vec::new()
                    }
                }
                _ => {
                    let names = strings(host, "capabilities.host")
                        .map_err(|e| format!("{e} (or a boolean)"))?;
                    if let Some(bad) = names.iter().find(|n| match n.strip_suffix('*') {
                        Some(prefix) => !prefix.is_empty() && !valid_host_name(prefix),
                        None => !valid_host_name(n),
                    }) {
                        return Err(format!(
                            "capabilities.host: invalid function `{bad}` (a name of {HOST_NAME_CHARS}, or a prefix of them ending in `*`)"
                        ));
                    }
                    names
                }
            };
        }
        if let Some(dropped) = dropped {
            dropped.append(&mut http_dropped);
        }
        Ok(caps)
    }

    /// The JSON form [`Capabilities::from_json`] reads.
    pub fn to_json(&self) -> Value {
        let mut obj = self.to_json_without_windows();
        // Only when granted: older runtimes read what newer signers write.
        if let (Value::Object(obj), Some(w)) = (&mut obj, &self.windows) {
            let mut o = Map::new();
            if !w.kinds.is_empty() {
                o.insert(
                    "kinds".into(),
                    w.kinds
                        .iter()
                        .map(|k| window_kind_name(*k))
                        .collect::<Vec<_>>()
                        .into(),
                );
            }
            if !w.levels.is_empty() {
                o.insert(
                    "levels".into(),
                    w.levels
                        .iter()
                        .map(|l| window_level_name(*l))
                        .collect::<Vec<_>>()
                        .into(),
                );
            }
            if let Some(max) = w.max {
                o.insert("max".into(), max.into());
            }
            if w.overlay {
                o.insert("overlay".into(), true.into());
            }
            obj.insert("windows".into(), Value::Object(o));
        }
        obj
    }

    fn to_json_without_windows(&self) -> Value {
        let list =
            |l: &[HostPattern]| Value::from(l.iter().map(|p| p.0.clone()).collect::<Vec<_>>());
        let mut network = Map::new();
        network.insert("hosts".into(), list(&self.network.hosts));
        let http: Vec<Value> = self
            .network
            .http
            .iter()
            .map(|g| {
                let mut o = Map::new();
                o.insert("host".into(), g.host.0.clone().into());
                if !g.methods.is_empty() {
                    o.insert("methods".into(), g.methods.clone().into());
                }
                if !g.schemes.is_empty() {
                    o.insert("schemes".into(), g.schemes.clone().into());
                }
                if let Some(port) = g.port {
                    o.insert("port".into(), port.into());
                }
                if !g.paths.is_empty() {
                    o.insert("paths".into(), g.paths.clone().into());
                }
                if !g.path_prefixes.is_empty() {
                    o.insert("pathPrefixes".into(), g.path_prefixes.clone().into());
                }
                Value::Object(o)
            })
            .collect();
        network.insert("http".into(), http.into());
        if !self.network.sockets.is_empty() {
            let sockets: Vec<String> = self
                .network
                .sockets
                .iter()
                .map(SocketGrant::to_string_form)
                .collect();
            network.insert("sockets".into(), sockets.into());
        }
        let mut obj = Map::new();
        obj.insert("network".into(), Value::Object(network));
        obj.insert(
            "process".into(),
            serde_json::json!({"execute": self.process.execute, "exit": self.process.exit, "env": self.process.env}),
        );
        obj.insert(
            "fs".into(),
            serde_json::json!({"read": self.fs.read, "write": self.fs.write}),
        );
        if let Some(hosts) = &self.webview {
            let mut w = Map::new();
            w.insert("hosts".into(), list(hosts));
            // Only when granted: older runtimes read what newer signers write.
            if self.webview_input {
                w.insert("input".into(), true.into());
            }
            if self.webview_runtime_origin {
                w.insert("runtimeOrigin".into(), true.into());
            }
            if !self.webview_media.is_empty() {
                let media = self.webview_media.iter().map(|m| m.as_str().into());
                w.insert("media".into(), Value::Array(media.collect()));
            }
            obj.insert("webview".into(), Value::Object(w));
        }
        obj.insert("statusBar".into(), self.status_bar.into());
        obj.insert("clipboard".into(), self.clipboard.into());
        obj.insert("picker".into(), self.picker.into());
        // Only when granted: older runtimes read what newer signers write.
        if self.share {
            obj.insert("share".into(), true.into());
        }
        if self.speech {
            obj.insert("speech".into(), true.into());
        }
        if self.notifications {
            obj.insert("notifications".into(), true.into());
        }
        if self.audio {
            obj.insert("audio".into(), true.into());
        }
        if self.application {
            obj.insert("application".into(), true.into());
        }
        if self.home_dir {
            obj.insert("homeDir".into(), true.into());
        }
        if !self.host.is_empty() {
            obj.insert("host".into(), self.host.clone().into());
        }
        obj.insert(
            "openUrl".into(),
            match &self.open_url {
                None => false.into(),
                Some(grant) if grant.schemes.is_empty() => true.into(),
                Some(grant) => serde_json::json!({ "schemes": grant.schemes }),
            },
        );
        Value::Object(obj)
    }

    fn allows_http(&self, method: &str, url: &UrlParts<'_>) -> bool {
        if !matches!(url.scheme.as_str(), "http" | "https" | "ws" | "wss") {
            return false;
        }
        self.network.hosts.iter().any(|h| h.matches(&url.host))
            || self.network.http.iter().any(|g| g.allows(method, url))
    }

    /// Whether `method` may reach every host, port and path of `scheme`.
    fn allows_http_anywhere(&self, method: &str, scheme: &str) -> bool {
        matches!(scheme, "http" | "https" | "ws" | "wss")
            && (self.network.hosts.iter().any(HostPattern::is_any)
                || self
                    .network
                    .http
                    .iter()
                    .any(|g| g.allows_anywhere(method, scheme)))
    }

    fn allows_host(&self, name: &str) -> bool {
        self.host.iter().any(|g| match g.strip_suffix('*') {
            Some(prefix) => name.starts_with(prefix),
            None => g == name,
        })
    }

    fn allows_webview(&self, url: &UrlParts<'_>) -> bool {
        matches!(url.scheme.as_str(), "http" | "https")
            && self
                .webview
                .as_ref()
                .is_some_and(|hosts| hosts.iter().any(|h| h.matches(&url.host)))
    }

    /// Whether a web view may show every host of `scheme`.
    fn allows_webview_anywhere(&self, scheme: &str) -> bool {
        matches!(scheme, "http" | "https")
            && self
                .webview
                .as_ref()
                .is_some_and(|hosts| hosts.iter().any(HostPattern::is_any))
    }
}

/// What host function names (`nsh/host`) are made of, for messages.
pub const HOST_NAME_CHARS: &str = "1 to 128 of A-Z a-z 0-9 _ . : -, without `..`";

/// Whether `name` may name a function of the embedding host: 1 to 128 of
/// `[A-Za-z0-9_.:-]`, without `..`. Hosts may put a name in a path or a URL,
/// so no name escapes the prefix a grant gives it.
pub fn valid_host_name(name: &str) -> bool {
    (1..=128).contains(&name.len())
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'-'))
        && !name.contains("..")
}

fn valid_command(command: &str) -> bool {
    !command.is_empty()
        && !command.contains(['\0', '*'])
        // `absolute`, not `Path::is_absolute`: in the browser that is false for
        // every path, so `/bin/sh` refused the whole manifest and the app never
        // started there. A rooted path counts on Windows too, where
        // `is_absolute` wants a drive (`/bin/sh`): one manifest serves every
        // platform.
        && (Path::new(command).has_root()
            || absolute(Path::new(command))
            // A bare name has no drive (`C:git` is relative to the host's
            // directory on drive C).
            || (!command.contains(['/', '\\', ':']) && command != "." && command != "..")
            // A bundled file of the app's, run where the host put it
            // (`process.run` of an `asset:/…` program resolves it there).
            || command.starts_with("asset:/"))
}

fn validate_path_pattern(path: &str) -> Result<(), String> {
    if [
        "$HOME",
        "${HOME}",
        "$USERPROFILE",
        "${USERPROFILE}",
        "%USERPROFILE%",
        "~",
    ]
    .into_iter()
    .any(|prefix| {
        path.strip_prefix(prefix)
            .is_some_and(|tail| tail.is_empty() || tail.starts_with(['/', '\\']))
    }) {
        return Err("use ${homeDir} for the native home directory".into());
    }
    let placeholder = ["${dataDir}", "${pluginDir}", "${homeDir}"]
        .into_iter()
        .find(|prefix| path.starts_with(prefix));
    let tail = placeholder.and_then(|prefix| path.strip_prefix(prefix));
    if path.is_empty()
        || path.contains(['\0', '*'])
        || tail.is_some_and(|s| !s.is_empty() && !s.starts_with('/'))
        || (placeholder.is_none() && path.contains("${"))
        || tail.is_some_and(|s| s.contains("${"))
        || Path::new(path)
            .components()
            .any(|p| matches!(p, Component::ParentDir))
    {
        return Err(
            "filesystem roots must use valid host placeholders and contain no traversal".into(),
        );
    }
    Ok(())
}

/// `path` resolved as [`std::fs::canonicalize`] resolves it, in the plain
/// form where Windows has one: canonicalizing there gives verbatim paths
/// (`\\?\C:\app`), which no path a host or app writes starts with, and
/// in which `/` separates nothing. Grants, requests and trusted anchors
/// are all compared in this form.
pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
    let path = std::fs::canonicalize(path)?;
    #[cfg(windows)]
    if let Some(plain) = path.to_str().and_then(without_verbatim_prefix) {
        return Ok(PathBuf::from(plain));
    }
    Ok(path)
}

/// The plain form of the Windows verbatim path `path` (`\\?\C:\a` →
/// `C:\a`, `\\?\UNC\server\share\a` → `\\server\share\a`), when it
/// names the same file: under the legacy length limit, and no component
/// that the plain form would read otherwise (empty, `.` or `..`, holding
/// `/`, ending in a dot or space, or a device name such as `NUL` or
/// `com1.txt`). `None` for any other path, which then stays as it is.
/// Text only, so its tests run on every platform.
#[cfg_attr(not(windows), allow(dead_code))]
fn without_verbatim_prefix(path: &str) -> Option<String> {
    let rest = path.strip_prefix(r"\\?\")?;
    let (plain, tail) = if let Some(unc) = rest.strip_prefix(r"UNC\") {
        (format!(r"\\{unc}"), unc)
    } else {
        let bytes = rest.as_bytes();
        if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || &bytes[1..3] != b":\\" {
            return None;
        }
        (rest.to_owned(), &rest[3..])
    };
    if plain.len() >= 260 {
        return None;
    }
    // A trailing separator ends a root (`C:\`) or a directory.
    let tail = tail.strip_suffix('\\').unwrap_or(tail);
    let device = |name: &str| {
        let stem = name.split('.').next().unwrap_or(name).trim_end();
        ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"]
            .iter()
            .any(|d| stem.eq_ignore_ascii_case(d))
            || (stem.len() == 4
                && ["COM", "LPT"]
                    .iter()
                    .any(|d| stem[..3].eq_ignore_ascii_case(d))
                && matches!(stem.as_bytes()[3], b'1'..=b'9'))
    };
    let plain_component = |c: &str| {
        !c.is_empty()
            && c != "."
            && c != ".."
            && !c.contains('/')
            && !c.ends_with(['.', ' '])
            && !device(c)
    };
    (tail.is_empty() || tail.split('\\').all(plain_component)).then_some(plain)
}

// Resolve every existing ancestor, including symlinks. Missing tails are
// permitted so creation receives the same boundary checks as reads.
/// Why [`Access::authorize_file`] refused a path.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FileRefusal {
    /// It names no file it can check: relative, with `..`, an unknown
    /// anchor, or unreadable (why).
    Invalid(String),
    /// No grant of the capabilities covers it (why).
    NotGranted(String),
}

impl std::fmt::Display for FileRefusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FileRefusal::Invalid(why) | FileRefusal::NotGranted(why) => f.write_str(why),
        }
    }
}

fn resolved_path(path: &Path) -> Result<PathBuf, String> {
    if !absolute(path) || path.components().any(|p| matches!(p, Component::ParentDir)) {
        return Err("filesystem paths must be absolute and contain no parent traversal".into());
    }
    let mut cursor = path;
    let mut tail = Vec::new();
    loop {
        match std::fs::symlink_metadata(cursor) {
            Ok(_) => {
                let mut resolved = canonicalize(cursor).map_err(|e| e.to_string())?;
                for part in tail.into_iter().rev() {
                    resolved.push(part);
                }
                return Ok(resolved);
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                tail.push(
                    cursor
                        .file_name()
                        .ok_or("invalid filesystem path")?
                        .to_owned(),
                );
                cursor = cursor.parent().ok_or("invalid filesystem path")?;
            }
            Err(e) => return Err(e.to_string()),
        }
    }
}

fn object<'a>(value: &'a Value, what: &str) -> Result<&'a Map<String, Value>, String> {
    value
        .as_object()
        .ok_or_else(|| format!("{what} must be an object"))
}

const WINDOW_KINDS: [(&str, crate::desktop::WindowKind); 5] = [
    ("normal", crate::desktop::WindowKind::Normal),
    ("dialog", crate::desktop::WindowKind::Dialog),
    ("panel", crate::desktop::WindowKind::Panel),
    ("popup", crate::desktop::WindowKind::Popup),
    ("overlay", crate::desktop::WindowKind::Overlay),
];

const WINDOW_LEVELS: [(&str, crate::desktop::WindowLevel); 4] = [
    ("normal", crate::desktop::WindowLevel::Normal),
    ("floating", crate::desktop::WindowLevel::Floating),
    ("aboveDock", crate::desktop::WindowLevel::AboveDock),
    ("desktopIcon", crate::desktop::WindowLevel::DesktopIcon),
];

fn window_kind_name(kind: crate::desktop::WindowKind) -> &'static str {
    WINDOW_KINDS
        .iter()
        .find(|(_, k)| *k == kind)
        .map_or("normal", |(n, _)| n)
}

fn window_level_name(level: crate::desktop::WindowLevel) -> &'static str {
    WINDOW_LEVELS
        .iter()
        .find(|(_, l)| *l == level)
        .map_or("normal", |(n, _)| n)
}

/// `capabilities.windows` as an object.
fn windows_grant(grant: &Map<String, Value>) -> Result<WindowsGrant, String> {
    let mut out = WindowsGrant::default();
    if let Some(kinds) = grant.get("kinds") {
        for name in strings(kinds, "capabilities.windows.kinds")? {
            let Some((_, kind)) = WINDOW_KINDS.iter().find(|(n, _)| *n == name) else {
                return Err(format!(
                    "capabilities.windows.kinds: unknown kind `{name}` (normal, dialog, panel, popup or overlay)"
                ));
            };
            out.kinds.push(*kind);
        }
    }
    if let Some(levels) = grant.get("levels") {
        for name in strings(levels, "capabilities.windows.levels")? {
            let Some((_, level)) = WINDOW_LEVELS.iter().find(|(n, _)| *n == name) else {
                return Err(format!(
                    "capabilities.windows.levels: unknown level `{name}` (normal, floating, aboveDock or desktopIcon)"
                ));
            };
            out.levels.push(*level);
        }
    }
    if let Some(max) = grant.get("max") {
        out.max = Some(
            max.as_u64()
                .and_then(|m| u32::try_from(m).ok())
                .ok_or("capabilities.windows.max must be a whole number")?,
        );
    }
    if let Some(v) = grant.get("overlay") {
        out.overlay = v
            .as_bool()
            .ok_or("capabilities.windows.overlay must be a boolean")?;
    }
    Ok(out)
}

fn unknown_key(what: &str, key: &str, known: &[&str]) -> String {
    format!("{what}: unknown key `{key}` (known: {})", known.join(", "))
}

fn strings(value: &Value, what: &str) -> Result<Vec<String>, String> {
    value
        .as_array()
        .and_then(|a| a.iter().map(|v| v.as_str().map(str::to_owned)).collect())
        .ok_or_else(|| format!("{what} must be an array of strings"))
}

/// One `network.http` rule: `host`, and any of `methods`, `scheme` /
/// `schemes`, `port`, `paths` and `pathPrefix` / `pathPrefixes` /
/// `path_prefixes` (the spellings of one key are merged).
fn http_grant(g: &Map<String, Value>) -> Result<HttpGrant, String> {
    let what = "capabilities.network.http[]";
    let host = g
        .get("host")
        .and_then(Value::as_str)
        .ok_or_else(|| format!("{what} needs a `host`"))?;
    // A key as a string or an array of strings.
    let list = |key: &str| -> Result<Vec<String>, String> {
        match g.get(key) {
            None => Ok(Vec::new()),
            Some(Value::String(s)) => Ok(vec![s.clone()]),
            Some(v) => strings(v, &format!("{what}.{key}")),
        }
    };
    let methods = list("methods")?
        .into_iter()
        .map(|m| {
            if !m.is_empty() && m.bytes().all(|b| b.is_ascii_alphabetic() || b == b'-') {
                Ok(m.to_ascii_uppercase())
            } else {
                Err(format!("{what}.methods: `{m}` is not an HTTP method"))
            }
        })
        .collect::<Result<Vec<_>, _>>()?;
    let mut schemes = Vec::new();
    for scheme in list("scheme")?.into_iter().chain(list("schemes")?) {
        let scheme = scheme.to_ascii_lowercase();
        if !matches!(scheme.as_str(), "http" | "https" | "ws" | "wss") {
            return Err(format!(
                "{what}.schemes: `{scheme}` is not http, https, ws or wss"
            ));
        }
        if !schemes.contains(&scheme) {
            schemes.push(scheme);
        }
    }
    let port = match g.get("port") {
        None => None,
        Some(v) => Some(
            v.as_u64()
                .and_then(|p| u16::try_from(p).ok())
                .filter(|&p| p != 0)
                .ok_or_else(|| format!("{what}.port must be a port from 1 to 65535"))?,
        ),
    };
    let paths = list("paths")?;
    let mut path_prefixes = Vec::new();
    for prefix in list("pathPrefix")?
        .into_iter()
        .chain(list("pathPrefixes")?)
        .chain(list("path_prefixes")?)
    {
        if !path_prefixes.contains(&prefix) {
            path_prefixes.push(prefix);
        }
    }
    // A path is matched as written: a pattern in it would match nothing.
    if let Some(bad) = paths
        .iter()
        .chain(&path_prefixes)
        .find(|p| !p.starts_with('/') || p.contains(['*', '?', '#']))
    {
        return Err(format!(
            "{what}: path `{bad}` must start with / and has no `*`, `?` or `#` (paths match as written)"
        ));
    }
    // Requests are matched as WHATWG's parser sends them (`/my%20photos`),
    // so the grant's paths are read the same way.
    let as_sent = |list: Vec<String>| -> Result<Vec<String>, String> {
        let mut sent = Vec::new();
        for path in list {
            let path = path_as_sent(&path).ok_or_else(|| {
                format!("{what}: path `{path}` has a `.` or `..` segment, which no request sends")
            })?;
            if !sent.contains(&path) {
                sent.push(path);
            }
        }
        Ok(sent)
    };
    let paths = as_sent(paths)?;
    let path_prefixes = as_sent(path_prefixes)?;
    Ok(HttpGrant {
        host: HostPattern::new(host)?,
        methods,
        schemes,
        port,
        paths,
        path_prefixes,
    })
}

fn patterns(value: &Value, what: &str) -> Result<Vec<HostPattern>, String> {
    strings(value, what)?
        .iter()
        .map(|p| HostPattern::new(p))
        .collect()
}

/// What an app may do: its declaration and the embedder's grant (when the
/// embedder limits it); an action must be allowed by both.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Access {
    /// What the app declared (everything without a declaration).
    pub declared: Capabilities,
    /// What the embedding app grants it at most (`None`: what it declared).
    pub granted: Option<Capabilities>,
}

impl Default for Access {
    fn default() -> Self {
        Self::all()
    }
}

impl Access {
    /// Everything allowed.
    pub fn all() -> Self {
        Self {
            declared: Capabilities::all(),
            granted: None,
        }
    }

    fn each(&self, f: impl Fn(&Capabilities) -> bool) -> bool {
        f(&self.declared) && self.granted.as_ref().is_none_or(f)
    }

    /// True when nothing is restricted (no check needed, redirects may be
    /// followed by the platform).
    pub fn is_unrestricted(&self) -> bool {
        let all = Capabilities::all();
        self.declared == all && self.granted.as_ref().is_none_or(|g| *g == all)
    }

    /// Whether an exact command is declared and granted. These capabilities
    /// always require explicit opt-in, including for legacy standalone apps.
    pub fn allows_process(&self, command: &str) -> bool {
        valid_command(command) && self.each(|c| c.process.execute.iter().any(|p| p == command))
    }

    /// Whether the app may request an exit from its host. This never exits the
    /// embedding process by itself; the host supplies the meaning of the request.
    pub fn allows_exit(&self) -> bool {
        self.each(|caps| caps.process.exit)
    }

    /// Whether an environment variable is visible. The built-in metadata names
    /// are always visible; other names require both app and host permission.
    pub fn allows_env(&self, name: &str) -> bool {
        let defaults = include_str!("default-env").lines().filter_map(|line| {
            let name = line.split('#').next().unwrap_or_default().trim();
            (!name.is_empty()).then_some(name)
        });
        defaults
            .into_iter()
            .any(|allowed| env_names_match(allowed, name))
            || self.each(|caps| {
                caps.process
                    .env
                    .iter()
                    .any(|allowed| env_names_match(allowed, name))
            })
    }

    /// Resolve a filesystem path within both the declaration and host grant.
    /// `data_dir` is an app-specific directory supplied only by the host.
    pub fn authorize_file(
        &self,
        path: &Path,
        data_dir: &Path,
        write: bool,
    ) -> Result<PathBuf, FileRefusal> {
        self.authorize_file_with_paths(path, data_dir, &TrustedPaths::default(), write)
    }

    /// Authorize a file with trusted host source and home directory anchors.
    pub fn authorize_file_with_paths(
        &self,
        path: &Path,
        data_dir: &Path,
        paths: &TrustedPaths,
        write: bool,
    ) -> Result<PathBuf, FileRefusal> {
        let requested = if let Some(text) = path.to_str().filter(|s| s.starts_with("${")) {
            paths
                .resolve_root(text, data_dir)
                .map_err(FileRefusal::Invalid)?
        } else {
            path.to_owned()
        };
        let resolved = resolved_path(&requested).map_err(FileRefusal::Invalid)?;
        let allowed = self.each(|c| {
            let roots = if write { &c.fs.write } else { &c.fs.read };
            roots.iter().any(|root| {
                paths
                    .resolve_root(root, data_dir)
                    .and_then(|r| resolved_path(&r))
                    .is_ok_and(|root| resolved.starts_with(root))
            })
        });
        if allowed {
            Ok(resolved)
        } else {
            Err(FileRefusal::NotGranted(format!(
                "filesystem {} is not granted by capabilities.fs",
                if write { "write" } else { "read" }
            )))
        }
    }

    /// Whether a raw TCP connection to `host:port` may be opened: only an
    /// exact `network.sockets` grant allows it, never `hosts` or `http`
    /// grants, and [`Capabilities::all`] grants none.
    pub fn allows_socket(&self, host: &str, port: u16) -> bool {
        if host.is_empty() || host.contains(['/', '@', '?', '#', '\0']) {
            return false;
        }
        let host = host.to_ascii_lowercase();
        let host = host
            .strip_prefix('[')
            .and_then(|h| h.strip_suffix(']'))
            .unwrap_or(&host)
            .trim_end_matches('.');
        self.each(|c| {
            c.network
                .sockets
                .iter()
                .any(|grant| grant.port == port && grant.host == host)
        })
    }

    /// Whether a WebSocket to `url` (`ws:` / `wss:`) may connect. The
    /// handshake is an HTTP GET, so it is checked as a GET of the same URL
    /// over `http:` / `https:`; legacy rules may also list `ws` / `wss`.
    pub fn allows_websocket(&self, url: &str) -> bool {
        let http = if let Some(rest) = url.strip_prefix("wss:") {
            format!("https:{rest}")
        } else if let Some(rest) = url.strip_prefix("ws:") {
            format!("http:{rest}")
        } else {
            return false;
        };
        self.allows_http("GET", &http) || self.allows_http("GET", url)
    }

    /// Whether `fetch(url, { method })` may go out. `asset:` URIs are always
    /// allowed.
    pub fn allows_http(&self, method: &str, url: &str) -> bool {
        if url.starts_with("asset:") {
            return true;
        }
        match read_url(url) {
            // A URL WHATWG's parser cannot read is none the loaders load.
            Ok(parts) => {
                url::Url::parse(url).is_ok_and(|whatwg| self.allows_parts(method, parts, &whatwg))
            }
            // Whatever host a parser reads, a grant of every host covers it.
            Err(Unread::Ambiguous(scheme)) => {
                self.each(|c| c.allows_http_anywhere(method, &scheme))
            }
            Err(Unread::NotUrl) => false,
        }
    }

    /// [`Self::allows_http`] for `url` that `whatwg` is WHATWG's parse of:
    /// a rule's paths are matched against the path a server is sent, dot
    /// segments, percent-encoded ones too, resolved as that parser resolves
    /// them.
    fn allows_parsed(&self, method: &str, url: &str, whatwg: &url::Url) -> bool {
        match read_url(url) {
            Ok(parts) => self.allows_parts(method, parts, whatwg),
            Err(Unread::Ambiguous(scheme)) => {
                self.each(|c| c.allows_http_anywhere(method, &scheme))
            }
            Err(Unread::NotUrl) => false,
        }
    }

    /// Whether the rules grant `parts` with the path WHATWG's parse of the
    /// URL, `whatwg`, sends.
    fn allows_parts(&self, method: &str, parts: UrlParts<'_>, whatwg: &url::Url) -> bool {
        let parts = UrlParts {
            path: whatwg.path(),
            ..parts
        };
        self.each(|c| c.allows_http(method, &parts))
    }

    /// The URL a request to `url` goes out with, if the app may make it:
    /// its WHATWG serialization, which [`Self::allows_http`] checks, so the
    /// loader requests what was granted. `asset:` URIs stay as written.
    pub fn http_url<'a>(&self, method: &str, url: &'a str) -> Option<Cow<'a, str>> {
        if url.starts_with("asset:") {
            return Some(Cow::Borrowed(url));
        }
        let whatwg = url::Url::parse(url).ok()?;
        self.allows_parsed(method, whatwg.as_str(), &whatwg)
            .then(|| written_or(url, whatwg.into()))
    }

    /// Whether a media URL (image, video, canvas image) may be loaded:
    /// [`Self::media_url`] with no base, so a `//` source names no URL, and
    /// no file roots, so an app with capabilities loads no local file.
    pub fn allows_media(&self, uri: &str) -> bool {
        self.media_url(uri, None, None).is_some()
    }

    /// What a media source (image, video, canvas image, sound) loads, if the
    /// app may load it. `asset:` URIs are the app's own files; `data:` URIs
    /// and `blob:` URLs (`URL.createObjectURL`) are bytes the app already
    /// has: these stay as written. A source with no scheme that does not
    /// start with `/` or a backslash is relative: the page's with a base,
    /// and with none (a native app, whose players read it against the
    /// working directory) it loads nothing. A local
    /// file (a `file:` URL; with no base, as in native apps, an absolute
    /// path; on the web `/…` is the page's) is read under `files`, the
    /// `capabilities.fs.read` roots ([`MediaFiles`]; `None`: none), and
    /// loads as its canonical path, in the form it was written. A source with a
    /// scheme, or one that starts with `//` (resolved against `base`, the
    /// page's URL on the web, whose scheme it takes; with no base it names
    /// no URL, as `fetch`'s), names a host: it is checked as WHATWG's parser
    /// reads it and loads as its serialization, so the loader loads what
    /// was granted. A backslash before the query or a control character is
    /// read differently by other parsers (Foundation's `NSURL`): only a
    /// grant of every host covers such a source, as written. An app without
    /// capabilities loads what it writes, unchecked.
    pub fn media_url<'a>(
        &self,
        uri: &'a str,
        base: Option<&str>,
        files: Option<&MediaFiles>,
    ) -> Option<Cow<'a, str>> {
        if is_own_media(uri) {
            // A bundled file's path stays in the app's files, as `fetch`
            // reads one; an app without capabilities reads what it names.
            let inside = !starts_with_ignoring_case(uri, "asset:") || is_inside_assets(uri);
            return (inside || self.is_unrestricted()).then_some(Cow::Borrowed(uri));
        }
        if self.is_unrestricted() {
            return media_as_written(uri, |url| self.allows_http("GET", url))
                .then_some(Cow::Borrowed(uri));
        }
        let file_url = starts_with_ignoring_case(uri, "file:");
        if (base.is_none() || file_url)
            && let Some(path) = local_file(uri)
        {
            let real = files?.readable(&path?)?;
            let loads = if file_url {
                file_url_of(&real)?
            } else {
                real.into_os_string().into_string().ok()?
            };
            return Some(written_or(uri, loads));
        }
        // WHATWG's parser reads the source with leading and trailing spaces
        // and C0 controls and every tab and newline dropped.
        let stripped = whatwg_stripped(uri);
        let scheme = scheme_of(&stripped);
        let names_host = scheme.is_some()
            || stripped.starts_with("//")
            || stripped.starts_with(['\\'])
            || stripped.starts_with("/\\");
        if !names_host {
            // A relative path is the page's on the web. A native app has no
            // page: the platforms read one against the process's working
            // directory (desktop videos, Android images) or not at all.
            return (base.is_some() || uri.trim().is_empty()).then_some(Cow::Borrowed(uri));
        }
        // Only a source without a scheme takes the base's.
        let base = || base.and_then(|b| url::Url::parse(b).ok());
        // Spaces and C0 controls around it, which WHATWG's parser drops,
        // are dropped here too, and the loader gets the serialization, never
        // the source as written. What other parsers read another way (a
        // backslash, a control inside, tabs and newlines included, an odd
        // host) is ambiguous (#979).
        let trimmed = uri.trim_matches(|c: char| c <= ' ');
        let head = trimmed.split(['?', '#']).next().unwrap_or(trimmed);
        if head.contains('\\')
            || trimmed.bytes().any(|b| b.is_ascii_control())
            || matches!(read_url(trimmed), Err(Unread::Ambiguous(_)))
        {
            let scheme = match scheme {
                Some(scheme) => scheme.to_ascii_lowercase(),
                None => base()?.scheme().to_owned(),
            };
            return self
                .each(|c| c.allows_http_anywhere("GET", &scheme))
                .then_some(Cow::Borrowed(uri));
        }
        let parsed = match scheme {
            Some(_) => url::Url::parse(trimmed),
            None => base()?.join(trimmed),
        }
        .ok()?;
        self.allows_parsed("GET", parsed.as_str(), &parsed)
            .then(|| written_or(uri, parsed.into()))
    }

    /// The next URL of a media load that was redirected from `base` to
    /// `location`, if the app may load it: the redirect must stay on
    /// `http(s)` and pass the same check as a first request, so loaders
    /// follow redirects themselves, one hop at a time, and never contact
    /// a target the app is not granted.
    pub fn media_redirect(&self, base: &str, location: &str) -> Result<String, String> {
        let url = resolve_reference(base, location);
        if !(url.starts_with("http://") || url.starts_with("https://")) {
            return Err(format!("redirect to `{url}` is not an http(s) URL"));
        }
        if !self.is_unrestricted() && !self.allows_media(&url) {
            return Err(format!(
                "redirect to `{url}` is not granted by capabilities.network"
            ));
        }
        Ok(url)
    }

    /// Whether web views are granted at all (inline HTML needs only this).
    pub fn allows_webviews(&self) -> bool {
        self.each(|c| c.webview.is_some())
    }

    /// Whether a web view may show (or navigate to) `url`; `about:blank`
    /// whenever web views are granted. A `blob:` URL is the blob's
    /// creator's: it is granted when the origin it embeds is, so a page may
    /// show and download its own blobs, and a blob of a host it may not
    /// show is not granted. An opaque blob (`blob:null/…`) names no origin
    /// and is not granted.
    pub fn allows_webview(&self, url: &str) -> bool {
        if url == "about:blank" {
            return self.allows_webviews();
        }
        let url = blob_origin(url).unwrap_or(url);
        match read_url(url) {
            Ok(parts) => self.each(|c| c.allows_webview(&parts)),
            Err(Unread::Ambiguous(scheme)) => self.each(|c| c.allows_webview_anywhere(&scheme)),
            Err(Unread::NotUrl) => false,
        }
    }

    /// Whether a web view may show (or navigate to) `url`, granted by
    /// `webview.hosts` ([`Self::allows_webview`]) or, when the app may add
    /// one at run time ([`Self::allows_runtime_origin`]), at `origin`, the
    /// web view's own `allowOrigin`.
    pub fn allows_webview_with(&self, url: &str, origin: Option<&WebOrigin>) -> bool {
        self.allows_webview(url)
            || origin.is_some_and(|o| self.allows_runtime_origin() && o.contains(url))
    }

    /// [`Self::allows_webview_with`], narrowed by the web view's own
    /// `allowNavigation` (`hosts`, none: not narrowed). What a web view's
    /// backend checks each top-level navigation with.
    pub fn allows_webview_in(
        &self,
        url: &str,
        origin: Option<&WebOrigin>,
        hosts: Option<&WebHosts>,
    ) -> bool {
        hosts.is_none_or(|h| h.allows(url)) && self.allows_webview_with(url, origin)
    }

    /// Whether a web view's `allowOrigin` may add an origin to the hosts
    /// it may show (`webview.runtimeOrigin`): declared and granted, never
    /// by default.
    pub fn allows_runtime_origin(&self) -> bool {
        self.each(|c| c.webview.is_some() && c.webview_runtime_origin)
    }

    /// Whether a web view's ref may give its page trusted input
    /// (`sendInput`): declared and granted, never by default.
    pub fn allows_web_input(&self) -> bool {
        self.each(|c| c.webview.is_some() && c.webview_input)
    }

    /// Whether a web view's page may capture `media` (`getUserMedia`):
    /// declared and granted, never by default. The system still asks the
    /// user.
    pub fn allows_web_media(&self, media: WebMedia) -> bool {
        self.each(|c| c.webview.is_some() && c.webview_media.contains(&media))
    }

    /// Whether the app may open a window of `kind` with `attributes` (its
    /// own, before its kind's defaults) while `open` windows besides the
    /// main one are open; the message of the refusal otherwise (the call
    /// fails with `ERR_ACCESS_DENIED`, permission `windows`).
    pub fn check_window(
        &self,
        kind: crate::desktop::WindowKind,
        attributes: &crate::desktop::WindowAttributes,
        open: usize,
    ) -> Result<(), String> {
        if !self.each(|c| c.windows.is_some()) {
            return Err("windows of the app's own are not granted by capabilities.windows".into());
        }
        if !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_kind(kind))) {
            return Err(format!(
                "a window of kind `{}` is not granted by capabilities.windows{}",
                window_kind_name(kind),
                if kind == crate::desktop::WindowKind::Overlay {
                    " (overlays need `overlay: true`)"
                } else {
                    ""
                }
            ));
        }
        if !self.each(|c| {
            c.windows
                .as_ref()
                .is_some_and(|w| w.max.is_none_or(|max| open < max as usize))
        }) {
            return Err("capabilities.windows.max windows are open already".into());
        }
        let mut own = attributes.clone();
        // The kind's own level is granted with the kind.
        let level = own.level.take();
        let denied = self.deny_window_attributes(&mut own);
        if let Some(name) = denied.first() {
            return Err(format!(
                "the window attribute `{name}` is not granted by capabilities.windows"
            ));
        }
        if let Some(level) = level
            && !self.each(|c| c.windows.as_ref().is_some_and(|w| w.allows_level(level)))
        {
            return Err(format!(
                "the window level `{}` is not granted by capabilities.windows.levels",
                window_level_name(level)
            ));
        }
        Ok(())
    }

    /// Leaves out of `attributes` what the app's capabilities do not grant
    /// a window (an ungranted level, click-through without `overlay`) and
    /// returns their
    /// names, for a warning. Without a `windows` grant only the defaults
    /// remain; no window is privileged.
    pub fn deny_window_attributes(
        &self,
        attributes: &mut crate::desktop::WindowAttributes,
    ) -> Vec<&'static str> {
        let mut denied = Vec::new();
        let grant = |f: &dyn Fn(&WindowsGrant) -> bool| {
            self.each(|c| match &c.windows {
                Some(w) => f(w),
                // Without windows the main window keeps the safe defaults.
                None => false,
            })
        };
        if let Some(level) = attributes.level
            && level != crate::desktop::WindowLevel::Normal
            && !grant(&|w| w.allows_level(level))
        {
            attributes.level = None;
            denied.push("level");
        }
        if attributes.passes_pointer() && !grant(&|w| w.overlay) {
            attributes.pointer_events = None;
            denied.push("pointerEvents");
        }
        denied
    }

    /// Whether the app may set the status bar.
    pub fn allows_status_bar(&self) -> bool {
        self.each(|c| c.status_bar)
    }

    /// Whether the app may show the system's share sheet (`Share` of
    /// `nsh-extra`, which checks it).
    pub fn allows_share(&self) -> bool {
        self.each(|c| c.share)
    }

    /// Whether the app may read and write the system clipboard.
    pub fn allows_clipboard(&self) -> bool {
        self.each(|c| c.clipboard)
    }

    /// Whether the app may show the system's picker (`nsh/picker`).
    pub fn allows_picker(&self) -> bool {
        self.each(|c| c.picker)
    }

    /// Whether the app may recognize the user's speech (`Speech` of
    /// `nsh-extra`, which checks it).
    pub fn allows_speech(&self) -> bool {
        self.each(|c| c.speech)
    }

    /// Whether the app may show notifications and set its badge
    /// (`Notifications` of `nsh`).
    pub fn allows_notifications(&self) -> bool {
        self.each(|c| c.notifications)
    }

    /// Whether the app may play sound (`Sound` and `AudioPlayer` of `nsh`).
    pub fn allows_audio(&self) -> bool {
        self.each(|c| c.audio)
    }

    /// Whether the app may act on the application as a whole: the main
    /// window, the application menu, the tray, global shortcuts, quitting,
    /// restarting and launching at login (`nsh/desktop`), and the app's page
    /// in the system's settings (`nsh/mobile`'s `AppSettings`).
    pub fn allows_application(&self) -> bool {
        self.each(|c| c.application)
    }

    /// Whether `os.homedir()` may tell the user's home directory.
    pub fn allows_home_dir(&self) -> bool {
        self.each(|c| c.home_dir)
    }

    /// Whether `nsh/host` may call the embedding app's function `name`.
    pub fn allows_host(&self, name: &str) -> bool {
        self.each(|c| c.allows_host(name))
    }

    /// Whether the app may open `url` outside it (`openUrl` of
    /// `nsh/device`): its scheme is granted.
    pub fn allows_open_url(&self, url: &str) -> bool {
        let Some(scheme) = url
            .split_once(':')
            .map(|(scheme, _)| scheme.to_ascii_lowercase())
        else {
            return false;
        };
        self.each(|c| c.open_url.as_ref().is_some_and(|g| g.allows(&scheme)))
    }
}

/// `location` against `base` (absolute, scheme-relative, absolute-path or
/// relative references), as a redirect's `Location` is read: resolved as
/// WHATWG's parser resolves it, dot segments included, so a rule checks the
/// URL the next hop requests. A base that is no URL leaves the location as
/// written, which no check grants.
pub fn resolve_reference(base: &str, location: &str) -> String {
    match url::Url::parse(base).and_then(|base| base.join(location)) {
        Ok(url) => url.into(),
        Err(_) => location.to_owned(),
    }
}

/// Whether URLs `a` and `b` have the same origin (scheme, host and port,
/// a scheme's default port included), as WHATWG's parser reads them. A URL
/// it cannot read, or one with an opaque origin, shares none.
pub fn is_same_origin(a: &str, b: &str) -> bool {
    match (url::Url::parse(a), url::Url::parse(b)) {
        (Ok(a), Ok(b)) => {
            let origin = a.origin();
            origin.is_tuple() && origin == b.origin()
        }
        _ => false,
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn verbatim_windows_paths_compare_in_their_plain_form() {
        use super::without_verbatim_prefix as plain;
        assert_eq!(plain(r"\\?\C:\Users\a").as_deref(), Some(r"C:\Users\a"));
        assert_eq!(plain(r"\\?\d:\").as_deref(), Some(r"d:\"));
        assert_eq!(plain(r"\\?\C:\app\").as_deref(), Some(r"C:\app\"));
        assert_eq!(
            plain(r"\\?\UNC\server\share\a").as_deref(),
            Some(r"\\server\share\a")
        );
        // Plain paths, and verbatim ones of other kinds, stay as they are.
        for path in [
            r"C:\a",
            r"\\server\share",
            "/home/a",
            r"\\?\Volume{x}\a",
            r"\\.\C:\a",
        ] {
            assert_eq!(plain(path), None, "{path}");
        }
        // Components the plain form reads otherwise keep the verbatim form.
        for path in [
            r"\\?\C:\a\NUL",
            r"\\?\C:\a\com1.txt",
            r"\\?\C:\a\Lpt9",
            r"\\?\C:\a\b.",
            r"\\?\C:\a\b ",
            r"\\?\C:\a\..\b",
            r"\\?\C:\a\.\b",
            r"\\?\C:\a\\b",
            r"\\?\C:\a/b",
        ] {
            assert_eq!(plain(path), None, "{path}");
        }
        assert_eq!(
            plain(r"\\?\C:\a\com10\console").as_deref(),
            Some(r"C:\a\com10\console")
        );
        let long = format!(r"\\?\C:\{}", "a".repeat(260));
        assert_eq!(plain(&long), None);
    }

    #[test]
    fn anchored_roots_join_their_tail_component_by_component() {
        let app = PathBuf::from(if cfg!(windows) { r"C:\app" } else { "/app" });
        let paths = super::TrustedPaths {
            plugin_dir: Some(app.clone()),
            home_dir: None,
        };
        let root = paths.resolve_root("${pluginDir}/a//b/", &app).unwrap();
        assert_eq!(root, app.join("a").join("b"));
        let names = root.components().rev().take(2).collect::<Vec<_>>();
        assert_eq!(
            names,
            [
                Component::Normal("b".as_ref()),
                Component::Normal("a".as_ref())
            ]
        );
    }
    use super::*;

    fn caps(json: &str) -> Capabilities {
        Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap()
    }

    #[test]
    fn windows_are_granted_by_kind_level_and_count() {
        use crate::desktop::{WindowAttributes, WindowKind, WindowLevel, WindowPointerEvents};
        let none = WindowAttributes::default();
        // Without a declaration: every kind but overlays, no click-through,
        // no capture protection.
        let all = Access::all();
        assert!(all.check_window(WindowKind::Panel, &none, 10).is_ok());
        assert!(all.check_window(WindowKind::Overlay, &none, 0).is_err());
        let click_through = WindowAttributes {
            pointer_events: Some(WindowPointerEvents::None),
            ..Default::default()
        };
        assert!(
            all.check_window(WindowKind::Normal, &click_through, 0)
                .is_err()
        );
        // Through where nothing in it takes the pointer: the same grant.
        let box_none = WindowAttributes {
            pointer_events: Some(WindowPointerEvents::BoxNone),
            ..Default::default()
        };
        assert!(all.check_window(WindowKind::Popup, &box_none, 0).is_err());
        // Declared without `windows`: none.
        let declared = |json: &str| Access {
            declared: caps(json),
            granted: None,
        };
        assert!(
            declared(r#"{"process":{"exit":true}}"#)
                .check_window(WindowKind::Normal, &none, 0)
                .is_err()
        );
        let limited = declared(
            r#"{"windows":{"kinds":["normal","dialog"],"levels":["normal","floating"],"max":2}}"#,
        );
        assert!(limited.check_window(WindowKind::Dialog, &none, 1).is_ok());
        assert!(limited.check_window(WindowKind::Popup, &none, 0).is_err());
        assert!(limited.check_window(WindowKind::Normal, &none, 2).is_err());
        let above = WindowAttributes {
            level: Some(WindowLevel::AboveDock),
            ..Default::default()
        };
        assert!(limited.check_window(WindowKind::Normal, &above, 0).is_err());
        let overlay = declared(r#"{"windows":{"overlay":true}}"#);
        assert!(
            overlay
                .check_window(WindowKind::Overlay, &click_through, 0)
                .is_ok()
        );
        assert!(
            overlay
                .check_window(WindowKind::Popup, &box_none, 0)
                .is_ok()
        );
        // `set()` keeps what is granted and leaves out the rest.
        let mut asked = WindowAttributes {
            title: Some("Notes".into()),
            level: Some(WindowLevel::AboveDock),
            ..Default::default()
        };
        assert_eq!(limited.deny_window_attributes(&mut asked), ["level"]);
        assert_eq!(asked.title.as_deref(), Some("Notes"));
        assert_eq!(asked.level, None);
    }

    #[test]
    fn environment_names_match_exactly_except_on_windows() {
        let access = Access {
            declared: caps(r#"{"process":{"env":["MY_TOKEN"]}}"#),
            granted: None,
        };
        assert!(access.allows_env("MY_TOKEN"));
        assert_eq!(access.allows_env("my_token"), cfg!(windows));
        assert_eq!(super::env_names_match("Path", "PATH"), cfg!(windows));
    }

    #[test]
    fn roots_stay_within_their_anchor_and_bare_commands_have_no_drive() {
        let anchor = Path::new(if cfg!(windows) { "C:\\app" } else { "/app" });
        assert!(super::within(anchor, Path::new("data/x"), "r").is_ok());
        assert!(super::within(anchor, Path::new("/etc"), "r").is_err());
        #[cfg(windows)]
        for tail in ["C:/Windows", "\\\\srv\\share", "\\Users", "D:x"] {
            assert!(
                super::within(anchor, Path::new(tail), "r").is_err(),
                "{tail}"
            );
        }
        assert!(!super::valid_command("C:git"));
        assert!(super::valid_command("git"));
    }

    #[test]
    fn a_manifest_with_absolute_commands_and_roots_parses() {
        // The manifest of an app that also runs in a browser: there `Path::is_absolute`
        // is false for every path, so these are checked with `absolute` (`has_root`).
        let declared = caps(
            r#"{"process":{"execute":["/bin/sh","/usr/bin/open","git"]},"fs":{"read":["/Applications"]}}"#,
        );
        assert_eq!(
            declared.process.execute,
            ["/bin/sh", "/usr/bin/open", "git"]
        );
        if !cfg!(windows) {
            assert!(super::valid_command("/bin/sh"));
            assert!(super::absolute(Path::new("/Applications")));
        }
    }

    #[test]
    fn system_capabilities_are_explicit_and_intersected() {
        let declared = caps(
            r#"{"process":{"execute":["claude","codex"]},"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#,
        );
        assert_eq!(
            Capabilities::from_json(&declared.to_json()).unwrap(),
            declared
        );
        let access = Access {
            declared,
            granted: Some(caps(
                r#"{"process":{"execute":["codex"]},"fs":{"read":["${dataDir}/conversations"]}}"#,
            )),
        };
        assert!(access.allows_process("codex"));
        assert!(!access.allows_process("claude"));
        assert!(!access.allows_process("/usr/bin/codex"));
        assert!(!Access::all().allows_process("codex"));
        let root = std::env::current_dir().unwrap();
        assert!(
            access
                .authorize_file(&root.join("conversations/new.json"), &root, false)
                .is_ok()
        );
        assert!(
            access
                .authorize_file(&root.join("other.json"), &root, false)
                .is_err()
        );
        assert!(
            access
                .authorize_file(&root.join("conversations/new.json"), &root, true)
                .is_err()
        );
        assert!(Access::all().authorize_file(&root, &root, false).is_err());
        assert!(
            access
                .authorize_file(&root.join("../secret"), &root, false)
                .is_err()
        );
        for bad in [
            r#"{"process":{"execut":[]}}"#,
            r#"{"fs":{"reads":[]}}"#,
            r#"{"fs":{"read":["${dataDir}/../outside"]}}"#,
            r#"{"process":{"execute":["*"]}}"#,
        ] {
            assert!(Capabilities::from_json(&serde_json::from_str(bad).unwrap()).is_err());
        }
    }

    #[test]
    fn trusted_host_anchors_expand_without_implicit_grants() {
        let root = std::env::current_dir().unwrap();
        let anchors = TrustedPaths {
            plugin_dir: Some(root.clone()),
            home_dir: Some(root.join("native-home")),
        };
        let access = Access {
            declared: caps(
                r#"{"fs":{"read":["assets","${homeDir}/settings","${pluginDir}/content"]}}"#,
            ),
            granted: None,
        };
        for path in ["assets/file", "native-home/settings/file", "content/file"] {
            assert!(
                access
                    .authorize_file_with_paths(&root.join(path), &root, &anchors, false)
                    .is_ok()
            );
        }
        assert!(
            access
                .authorize_file(&root.join("content/file"), &root, false)
                .is_err()
        );
        assert!(
            access
                .authorize_file_with_paths(&root.join("other/file"), &root, &anchors, false)
                .is_err()
        );
        assert!(
            TrustedPaths::default()
                .resolve_root("${homeDir}/settings", &root)
                .is_err()
        );
        assert!(
            TrustedPaths::default()
                .resolve_root("assets", &root)
                .is_err()
        );
    }

    #[test]
    fn http_rules_are_one_form_whose_keys_all_narrow() {
        let allows = |rule: serde_json::Value, method: &str, url: &str| {
            Access {
                declared: Capabilities::from_json(&serde_json::json!({"network":{"http":[rule]}}))
                    .unwrap(),
                granted: None,
            }
            .allows_http(method, url)
        };
        // `{host, methods}` covers every path, scheme and port, as manifests had it.
        let plain = serde_json::json!({"host": "api.example.com", "methods": ["GET"]});
        assert!(allows(plain.clone(), "GET", "https://api.example.com/"));
        assert!(allows(
            plain.clone(),
            "GET",
            "http://api.example.com:8080/any/path"
        ));
        assert!(!allows(plain.clone(), "POST", "https://api.example.com/"));
        assert!(allows(
            serde_json::json!({"host": "api.example.com"}),
            "PUT",
            "https://api.example.com/x"
        ));
        // Paths are exact, prefixes whole segments; either one covers a path.
        let scoped = serde_json::json!({
            "host": "api.example.com", "methods": ["GET"], "scheme": "https", "port": 443,
            "paths": ["/exact"], "pathPrefixes": ["/v1"]
        });
        assert!(allows(
            scoped.clone(),
            "GET",
            "https://api.example.com/exact?q=1"
        ));
        assert!(allows(scoped.clone(), "GET", "https://api.example.com/v1"));
        assert!(allows(
            scoped.clone(),
            "GET",
            "https://api.example.com/v1/child"
        ));
        assert!(!allows(
            scoped.clone(),
            "GET",
            "https://api.example.com/v10"
        ));
        assert!(!allows(
            scoped.clone(),
            "GET",
            "https://api.example.com/exact/more"
        ));
        assert!(!allows(
            scoped.clone(),
            "GET",
            "http://api.example.com/exact"
        ));
        assert!(!allows(
            scoped.clone(),
            "GET",
            "https://api.example.com:444/exact"
        ));
        assert!(allows(scoped, "GET", "https://api.example.com:443/exact"));
        // Main's spelling still reads, and a prefix ending in `/` covers what follows it.
        let legacy = serde_json::json!({"host": "*.example.com", "schemes": ["https", "wss"], "pathPrefix": "/v1/"});
        assert!(allows(
            legacy.clone(),
            "GET",
            "https://quotes.example.com/v1/quote"
        ));
        assert!(!allows(legacy, "GET", "https://quotes.example.com/v2/"));
        // Every spelling of a key is merged, and one form is written back.
        let mixed = caps(
            r#"{"network":{"http":[{"host":"a.example.com","methods":["get"],"scheme":"https","schemes":["wss","https"],"pathPrefix":"/a","path_prefixes":["/b"],"pathPrefixes":["/a","/c"]}]}}"#,
        );
        let grant = &mixed.network.http[0];
        assert_eq!(grant.methods, ["GET"]);
        assert_eq!(grant.schemes, ["https", "wss"]);
        assert_eq!(grant.path_prefixes, ["/a", "/c", "/b"]);
        assert_eq!(
            mixed.to_json()["network"]["http"][0],
            serde_json::json!({"host":"a.example.com","methods":["GET"],"schemes":["https","wss"],"pathPrefixes":["/a","/c","/b"]})
        );
        assert_eq!(Capabilities::from_json(&mixed.to_json()).unwrap(), mixed);
        // What cannot match is an error, not a rule that grants nothing.
        for bad in [
            serde_json::json!({"host": "a.example.com", "schemes": ["ftp"]}),
            serde_json::json!({"host": "a.example.com", "port": 0}),
            serde_json::json!({"host": "a.example.com", "port": 70000}),
            serde_json::json!({"host": "a.example.com", "paths": ["relative"]}),
            serde_json::json!({"host": "a.example.com", "pathPrefixes": ["/v1/*"]}),
            serde_json::json!({"host": "a.example.com", "methods": ["*"]}),
            serde_json::json!({"host": "a.example.com", "paths": "/x", "query": true}),
            serde_json::json!({"methods": ["GET"]}),
        ] {
            assert!(
                Capabilities::from_json(&serde_json::json!({"network":{"http":[bad.clone()]}}))
                    .is_err(),
                "{bad}"
            );
        }
    }

    #[test]
    fn exit_and_environment_permissions_intersect() {
        let declared = caps(r#"{"process":{"env":["NSH_SECRET","OTHER"],"exit":true}}"#);
        assert_eq!(
            Capabilities::from_json(&declared.to_json()).unwrap(),
            declared
        );
        let access = Access {
            declared,
            granted: Some(caps(r#"{"process":{"env":["NSH_SECRET"]}}"#)),
        };
        assert!(access.allows_env("NSH_SECRET"));
        assert!(!access.allows_env("OTHER"));
        assert!(!access.allows_exit());
        assert!(!Access::all().allows_exit());
        assert!(!Access::all().allows_env("NSH_SECRET"));
        assert!(Access::all().allows_env("LANG"));
        assert_eq!(Access::all().allows_env("lang"), cfg!(windows));
        assert!(Access::all().allows_env("TZ"));
        // Identity, paths and proxy credentials need an explicit grant.
        for name in [
            "HOME",
            "USER",
            "USERNAME",
            "HOSTNAME",
            "COMPUTERNAME",
            "PATH",
            "TMPDIR",
            "XDG_RUNTIME_DIR",
            "APPDATA",
            "http_proxy",
            "HTTPS_PROXY",
            "ALL_PROXY",
            "NO_PROXY",
            "DISPLAY",
        ] {
            assert!(!Access::all().allows_env(name), "{name}");
        }
        assert!(!Access::all().allows_env("SSH_AUTH_SOCK"));
        assert!(!Access::all().allows_env("DBUS_SESSION_BUS_ADDRESS"));
        assert!(Capabilities::from_json(&serde_json::json!({"process":{"exit":"true"}})).is_err());
        assert!(
            Capabilities::from_json(&serde_json::json!({"process":{"env":["BAD=NAME"]}})).is_err()
        );
    }

    #[test]
    fn default_environment_entries_are_upper_case_names() {
        for line in include_str!("default-env").lines() {
            let name = line.split('#').next().unwrap_or_default().trim();
            assert!(
                name.is_empty()
                    || name
                        .chars()
                        .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'),
                "{line}"
            );
        }
    }

    #[test]
    fn sockets_need_exact_host_and_port_grants() {
        let declared = caps(
            r#"{"network":{"hosts":["*"],"sockets":["MQTT.example.com:8883","[::1]:9000","127.0.0.1:22"]}}"#,
        );
        assert_eq!(
            Capabilities::from_json(&declared.to_json()).unwrap(),
            declared
        );
        let access = Access {
            declared,
            granted: None,
        };
        assert!(access.allows_socket("mqtt.example.com", 8883));
        assert!(access.allows_socket("MQTT.example.com.", 8883));
        assert!(!access.allows_socket("mqtt.example.com", 1883));
        assert!(!access.allows_socket("example.com", 8883));
        assert!(!access.allows_socket("a.mqtt.example.com", 8883));
        assert!(access.allows_socket("::1", 9000));
        assert!(access.allows_socket("[::1]", 9000));
        assert!(access.allows_socket("127.0.0.1", 22));
        assert!(!access.allows_socket("127.0.0.1", 0));
        // `hosts: ["*"]` (and the unrestricted default) grant no sockets.
        assert!(!access.allows_socket("localhost", 22));
        assert!(!Access::all().allows_socket("127.0.0.1", 22));
        assert!(!Access::all().allows_socket("example.com", 443));
        let narrowed = Access {
            granted: Some(caps(r#"{"network":{"sockets":["127.0.0.1:22"]}}"#)),
            ..access
        };
        assert!(narrowed.allows_socket("127.0.0.1", 22));
        assert!(!narrowed.allows_socket("mqtt.example.com", 8883));
        for bad in [
            "*.example.com:443",
            "*:443",
            "example.com",
            "example.com:0",
            "example.com:65536",
            "example.com:*",
            ":443",
            "::1:443",
            "[]:443",
            "exa mple.com:1",
        ] {
            assert!(
                Capabilities::from_json(&serde_json::json!({"network":{"sockets":[bad]}}))
                    .unwrap_err()
                    .contains("invalid socket grant"),
                "{bad}"
            );
        }
    }

    #[test]
    fn websockets_follow_http_grants() {
        let access = Access {
            declared: caps(
                r#"{"network":{"hosts":["ws.example.com"],"http":[
                    {"host":"chat.example.com","methods":["GET"],"scheme":"https","paths":["/socket"]},
                    {"host":"legacy.example.com","schemes":["wss"]}
                ]}}"#,
            ),
            granted: None,
        };
        assert!(access.allows_websocket("ws://ws.example.com:8080/x"));
        assert!(access.allows_websocket("wss://chat.example.com/socket"));
        assert!(!access.allows_websocket("ws://chat.example.com/socket"));
        assert!(!access.allows_websocket("wss://chat.example.com/other"));
        assert!(access.allows_websocket("wss://legacy.example.com/"));
        assert!(!access.allows_websocket("ws://legacy.example.com/"));
        assert!(!access.allows_websocket("https://ws.example.com/"));
        assert!(!access.allows_socket("ws.example.com", 8080));
    }

    #[cfg(unix)]
    #[test]
    fn filesystem_symlinks_cannot_escape_granted_roots() {
        use std::os::unix::fs::symlink;
        let base = std::env::var_os("TMPDIR")
            .map(PathBuf::from)
            .unwrap_or_else(|| {
                PathBuf::from(std::env::var_os("HOME").unwrap()).join(".cache/nsh-benchs-test-tmp")
            });
        let root = base.join(format!("access-policy-{}", std::process::id()));
        std::fs::create_dir_all(root.join("allowed")).unwrap();
        std::fs::create_dir_all(root.join("outside")).unwrap();
        symlink(root.join("outside"), root.join("allowed/link")).unwrap();
        let access = Access {
            declared: caps(r#"{"fs":{"read":["${dataDir}"],"write":["${dataDir}"]}}"#),
            granted: None,
        };
        for write in [false, true] {
            assert!(
                access
                    .authorize_file(
                        &root.join("allowed/link/missing/file"),
                        &root.join("allowed"),
                        write
                    )
                    .is_err()
            );
            assert!(
                access
                    .authorize_file(&root.join("allowed/new/file"), &root.join("allowed"), write)
                    .is_ok()
            );
        }
        std::fs::remove_dir_all(root).unwrap();
    }

    #[test]
    fn the_share_sheet_is_granted_by_both_sides() {
        let declared = caps(r#"{ "share": true }"#);
        assert!(declared.share);
        assert_eq!(declared.to_json()["share"], serde_json::json!(true));
        assert!(
            Access {
                declared: declared.clone(),
                granted: None,
            }
            .allows_share()
        );
        // The embedding app grants less.
        assert!(
            !Access {
                declared,
                granted: Some(caps("{}")),
            }
            .allows_share()
        );
        // Apps without a declaration keep it.
        assert!(Access::all().allows_share());
        assert!(Capabilities::from_json(&serde_json::json!({ "share": "yes" })).is_err());
    }

    #[test]
    fn denies_unless_listed() {
        let access = Access {
            declared: caps("{}"),
            granted: None,
        };
        assert!(!access.allows_http("GET", "https://example.com/"));
        assert!(!access.allows_media("https://example.com/a.png"));
        assert!(access.allows_media("asset:/logo.png"));
        // A relative path names no file of the app's in a native app.
        assert!(!access.allows_media("logo.png"));
        // Local files are `capabilities.fs.read`'s (#1180), which this
        // declaration does not grant.
        assert!(!access.allows_media("/home/a/logo.png"));
        assert!(!access.allows_media("file:///home/a/logo.png"));
        assert!(access.allows_media("data:image/png;base64,iVBORw0KGgo="));
        assert!(!access.allows_webview("https://example.com/"));
        assert!(!access.allows_status_bar());
        assert!(!access.allows_clipboard());
        assert!(!access.allows_picker());
        assert!(!access.allows_share());
        assert!(!access.allows_speech());
        assert!(!access.allows_audio());
        assert!(!access.allows_application());
        assert!(!access.allows_home_dir());
        assert!(!access.allows_host("getUserInfo"));
        assert!(Access::all().is_unrestricted());
    }

    #[test]
    fn the_application_and_the_home_directory_are_capabilities() {
        // Undeclared: granted, as they always were.
        let all = Access::all();
        assert!(all.allows_application() && all.allows_home_dir());
        // Declared: only when listed, and the embedder may take them away.
        let access = |declared: &str, granted: Option<&str>| Access {
            declared: caps(declared),
            granted: granted.map(caps),
        };
        let listed = access(r#"{ "application": true, "homeDir": true }"#, None);
        assert!(listed.allows_application() && listed.allows_home_dir());
        let application = access(r#"{ "application": true }"#, None);
        assert!(application.allows_application() && !application.allows_home_dir());
        let narrowed = access(
            r#"{ "application": true, "homeDir": true }"#,
            Some(r#"{ "homeDir": true }"#),
        );
        assert!(!narrowed.allows_application() && narrowed.allows_home_dir());
        assert!(!access(r#"{ "application": false }"#, None).allows_application());
        assert!(Capabilities::from_json(&serde_json::json!({ "application": "yes" })).is_err());
        assert!(Capabilities::from_json(&serde_json::json!({ "homeDir": 1 })).is_err());
        // Written only when granted, read back the same.
        let both = caps(r#"{ "application": true, "homeDir": true }"#);
        assert_eq!(Capabilities::from_json(&both.to_json()).unwrap(), both);
        let none = Capabilities::default().to_json();
        assert!(none.get("application").is_none() && none.get("homeDir").is_none());
    }

    #[test]
    fn host_functions_need_an_explicit_grant() {
        // Undeclared, the other capabilities are all granted; the host's
        // functions are not.
        let all = Access::all();
        assert!(all.allows_clipboard());
        assert!(!all.allows_host("getUserInfo"));
        let access = |json: &str| Access {
            declared: caps(json),
            granted: None,
        };
        let every = access(r#"{ "host": true }"#);
        assert!(every.allows_host("getUserInfo") && every.allows_host("bridge.call"));
        assert!(!access(r#"{ "host": false }"#).allows_host("getUserInfo"));
        let listed = access(r#"{ "host": ["getUserInfo", "bridge.*"] }"#);
        assert!(listed.allows_host("getUserInfo"));
        assert!(listed.allows_host("bridge.share"));
        assert!(!listed.allows_host("getUserInfoX"));
        assert!(!listed.allows_host("bridge"));
        assert!(Capabilities::from_json(&serde_json::json!({ "host": ["a*b"] })).is_err());
        assert!(Capabilities::from_json(&serde_json::json!({ "host": [""] })).is_err());
        // The embedding app may grant less.
        let narrowed = Access {
            declared: caps(r#"{ "host": true }"#),
            granted: Some(caps(r#"{ "host": ["bridge.*"] }"#)),
        };
        assert!(narrowed.allows_host("bridge.call") && !narrowed.allows_host("getUserInfo"));
    }

    #[test]
    fn a_runtime_origin_is_exact() {
        let o = |s: &str| WebOrigin::parse(s).unwrap();
        let lan = o("http://192.168.1.5:9876");
        for url in [
            "http://192.168.1.5:9876/session-page/T/index.html",
            "http://192.168.1.5:9876",
            "HTTP://192.168.1.5:9876/x",
            "blob:http://192.168.1.5:9876/6f3c2f0e",
        ] {
            assert!(lan.contains(url), "{url}");
        }
        for url in [
            "http://192.168.1.5:9877/",
            "https://192.168.1.5:9876/",
            "http://a.192.168.1.5:9876/",
            "http://192.168.1.5:9876@evil.com/",
            "http://192.168.1.5:9876.evil.com/",
            "blob:null/6f3c2f0e",
            "file:///etc/passwd",
            "javascript:alert(1)",
            "data:text/html,hi",
            "http://192.168.1.5\\@evil.com:9876/",
        ] {
            assert!(!lan.contains(url), "{url}");
        }
        let named = o("https://Name.Example.net:443");
        assert_eq!(named.to_string(), "https://name.example.net");
        assert!(named.contains("https://name.example.net/x"));
        assert!(named.contains("https://NAME.example.net:443/x"));
        for url in [
            "https://evil.name.example.net/",
            "https://name.example.net.evil.com/",
            "http://name.example.net/",
        ] {
            assert!(!named.contains(url), "{url}");
        }
        assert_eq!(o("http://h:80/").to_string(), "http://h");
        assert_eq!(o("http://[::1]:8080").to_string(), "http://[::1]:8080");
        for bad in [
            "http://h/path",
            "http://h?q",
            "http://h#f",
            "http://u@h",
            "*",
            "http://*",
            "ftp://h",
            "h:80",
            "http://",
            "http://h:99999",
            "http://bücher.example",
        ] {
            assert!(WebOrigin::parse(bad).is_err(), "{bad}");
        }
    }

    #[test]
    fn allow_navigation_only_narrows_a_web_view() {
        let access = Access {
            declared: caps(r#"{ "webview": { "hosts": ["*"] } }"#),
            granted: None,
        };
        let hosts = WebHosts::parse(&["127.0.0.1", "*.localhost"]).unwrap();
        let ok = |url: &str| access.allows_webview_in(url, None, Some(&hosts));
        assert!(ok("http://127.0.0.1:8001/"));
        assert!(ok("http://app.localhost:3000/a"));
        assert!(ok("blob:http://127.0.0.1:8001/1234"));
        assert!(!ok("http://127.0.0.1.evil.test:8002/leaked"));
        assert!(!ok("https://example.com/"));
        assert!(!ok("http://localhost/"));
        // Other schemes stay with the app's own rules.
        assert!(ok("about:blank"));
        // It never widens what the app grants.
        let narrow = Access {
            declared: caps(r#"{ "webview": { "hosts": ["example.com"] } }"#),
            granted: None,
        };
        assert!(!narrow.allows_webview_in("http://127.0.0.1/", None, Some(&hosts)));
        assert!(narrow.allows_webview_in("https://example.com/", None, None));
        // An empty list refuses every web page.
        let none = WebHosts::default();
        assert!(!access.allows_webview_in("https://example.com/", None, Some(&none)));
        // Bad patterns do not read; the written form reads back.
        assert!(WebHosts::parse(&["http://127.0.0.1"]).is_err());
        let text = hosts.to_string();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(WebHosts::parse(&lines).unwrap(), hosts);
    }

    #[test]
    fn a_runtime_origin_needs_an_explicit_grant() {
        let access = |json: &str| Access {
            declared: caps(json),
            granted: None,
        };
        let lan = WebOrigin::parse("http://192.168.1.5:9876").unwrap();
        let page = "http://192.168.1.5:9876/index.html";
        let declared = r#"{ "webview": { "hosts": ["127.0.0.1"], "runtimeOrigin": true } }"#;
        assert!(access(declared).allows_runtime_origin());
        assert!(access(declared).allows_webview_with(page, Some(&lan)));
        assert!(!access(declared).allows_webview_with(page, None));
        assert!(access(declared).allows_webview_with("http://127.0.0.1:1/", Some(&lan)));
        // Not declared: the origin adds nothing, also for an app with every
        // host's grant (which has the page through `hosts`).
        let hosts = r#"{ "webview": { "hosts": ["127.0.0.1"] } }"#;
        assert!(!access(hosts).allows_runtime_origin());
        assert!(!access(hosts).allows_webview_with(page, Some(&lan)));
        assert!(!Access::all().allows_runtime_origin());
        assert!(Access::all().allows_webview_with(page, None));
        assert!(
            Capabilities::from_json(&serde_json::json!({ "webview": { "runtimeOrigin": 1 } }))
                .is_err()
        );
        // It round-trips, and the embedding app may withhold it.
        assert_eq!(
            Capabilities::from_json(&caps(declared).to_json()),
            Ok(caps(declared))
        );
        let narrowed = Access {
            declared: caps(declared),
            granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
        };
        assert!(!narrowed.allows_runtime_origin());
    }

    #[test]
    fn trusted_web_input_needs_an_explicit_grant() {
        // Undeclared, web views are granted; their trusted input is not.
        let all = Access::all();
        assert!(all.allows_webviews() && !all.allows_web_input());
        let access = |json: &str| Access {
            declared: caps(json),
            granted: None,
        };
        let input = r#"{ "webview": { "hosts": ["example.com"], "input": true } }"#;
        assert!(access(input).allows_web_input());
        assert!(!access(r#"{ "webview": { "hosts": ["example.com"] } }"#).allows_web_input());
        assert!(!access(r#"{ "webview": { "input": false } }"#).allows_web_input());
        assert!(
            Capabilities::from_json(&serde_json::json!({ "webview": { "input": "yes" } })).is_err()
        );
        // It round-trips, and the embedding app may withhold it.
        assert_eq!(
            Capabilities::from_json(&caps(input).to_json()),
            Ok(caps(input))
        );
        let narrowed = Access {
            declared: caps(input),
            granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
        };
        assert!(!narrowed.allows_web_input());
    }

    #[test]
    fn web_media_needs_an_explicit_grant() {
        let all = Access::all();
        assert!(!all.allows_web_media(WebMedia::Microphone));
        let access = |json: &str| Access {
            declared: caps(json),
            granted: None,
        };
        let mic = r#"{ "webview": { "hosts": ["example.com"], "media": ["microphone"] } }"#;
        assert!(access(mic).allows_web_media(WebMedia::Microphone));
        assert!(!access(mic).allows_web_media(WebMedia::Camera));
        assert!(
            Capabilities::from_json(&serde_json::json!({ "webview": { "media": ["screen"] } }))
                .is_err()
        );
        assert_eq!(Capabilities::from_json(&caps(mic).to_json()), Ok(caps(mic)));
        let narrowed = Access {
            declared: caps(mic),
            granted: Some(caps(r#"{ "webview": { "hosts": ["*"] } }"#)),
        };
        assert!(!narrowed.allows_web_media(WebMedia::Microphone));
    }

    /// A page's `URL.createObjectURL` blob URL embeds its creator's origin:
    /// a web view may show and download it when that origin is a granted
    /// host, and never a blob of a host it may not show, an opaque one, or
    /// any without a `webview` grant.
    #[test]
    fn page_owned_blob_urls_follow_the_origin_they_embed() {
        let a = Access {
            declared: caps(
                r#"{ "webview": { "hosts": ["app.example.com", "*.app.example.com"] } }"#,
            ),
            granted: None,
        };
        for url in [
            "blob:https://app.example.com/uuid",
            "blob:http://app.example.com:6711/uuid",
            "blob:https://docs.app.example.com/uuid",
            "BLOB:HTTPS://APP.EXAMPLE.COM/uuid",
        ] {
            assert!(a.allows_webview(url), "{url}");
        }
        for url in [
            "blob:https://bank.example/uuid",
            "blob:https://app.example.com.evil.example/uuid",
            "blob:https://app.example.com@bank.example/uuid",
            "blob:null/uuid",
            "blob:data:text/html,hi",
            "blob:file:///etc/passwd",
            "blob:",
            "blob:https://",
        ] {
            assert!(!a.allows_webview(url), "{url}");
        }
        // Without a `webview` grant, a blob naming a host is still refused.
        let denied = Access {
            declared: caps("{}"),
            granted: None,
        };
        assert!(!denied.allows_webview("blob:https://app.example.com/uuid"));
        // The embedding app may narrow the hosts: both must grant the origin.
        let narrowed = Access {
            granted: Some(caps(r#"{ "webview": { "hosts": ["app.example.com"] } }"#)),
            ..a.clone()
        };
        assert!(narrowed.allows_webview("blob:https://app.example.com/uuid"));
        assert!(!narrowed.allows_webview("blob:https://docs.app.example.com/uuid"));
        // The shape WebKit reports for a page at a granted loopback host.
        let local = Access {
            declared: caps(r#"{ "webview": { "hosts": ["127.0.0.1"] } }"#),
            granted: None,
        };
        assert!(
            local.allows_webview("blob:http://127.0.0.1:6711/6f3c2f0e-8a1d-4c5e-9b7a-0d2e4f6a8b1c")
        );
        // HTTP(S) pages are checked as before: the origin either matches or
        // it does not.
        assert!(a.allows_webview("https://app.example.com/page"));
        assert!(!a.allows_webview("https://bank.example/page"));
        // A blob whose embedded origin parsers read differently is covered
        // only by a grant of every host, as any ambiguous URL is.
        let ambiguous = "blob:https://app.example.com\\@bank.example/uuid";
        assert!(!a.allows_webview(ambiguous));
        let any = Access {
            declared: caps(r#"{ "webview": { "hosts": ["*"] } }"#),
            granted: None,
        };
        assert!(any.allows_webview(ambiguous));
    }

    #[test]
    fn host_function_names_and_grants_keep_to_their_charset() {
        for good in ["getUserInfo", "user.info", "a-b_c:d.E9", &"a".repeat(128)] {
            assert!(valid_host_name(good), "{good}");
        }
        for bad in [
            "",
            "user.x/../../admin",
            "a..b",
            "user x",
            "a\\b",
            "caf\u{e9}",
            "ok\u{0}",
            "a*",
            &"a".repeat(129),
        ] {
            assert!(!valid_host_name(bad), "{bad:?}");
        }
        let parses =
            |grant: &str| Capabilities::from_json(&serde_json::json!({ "host": [grant] })).is_ok();
        assert!(parses("*") && parses("user.*") && parses("user.info"));
        for bad in ["user/*", "a..*", "../*", "a b", "**"] {
            assert!(!parses(bad), "{bad}");
        }
    }

    #[test]
    fn hosts_and_finer_grants() {
        let c = caps(
            r#"{ "network": {
                "hosts": ["*.example.org"],
                "http": [{ "host": "api.example.com", "methods": ["get"], "pathPrefix": "/v1/" }]
            } }"#,
        );
        let a = Access {
            declared: c,
            granted: None,
        };
        assert!(a.allows_http("POST", "https://api.example.org/x"));
        assert!(!a.allows_http("GET", "https://example.org/"));
        assert!(!a.allows_http("GET", "https://example.org.evil.io/"));
        assert!(!a.allows_http("GET", "https://evilexample.org/"));
        assert!(a.allows_http("GET", "https://API.example.com/v1/quote"));
        assert!(!a.allows_http("POST", "https://api.example.com/v1/quote"));
        assert!(!a.allows_http("GET", "https://api.example.com/v2/"));
        assert!(!a.allows_http("GET", "file://api.example.com/v1/"));
        // User info does not fool the host check.
        assert!(!a.allows_http("GET", "https://api.example.org@evil.io/"));
        assert!(a.allows_http("GET", "https://user:pw@api.example.org:8443/"));
    }

    /// URLs that parsers read differently: WHATWG's (the web views') ends the
    /// host at a backslash, reads one in the path as `/` and drops tab, LF
    /// and CR, Foundation's `NSURL` keeps a backslash in the user info,
    /// and WHATWG's decodes a host's percent-encoding and refuses spaces in
    /// it. Granting one would let the app load a host or path it is not
    /// granted wherever another parser loads it.
    #[test]
    fn urls_that_parsers_read_as_different_hosts_are_refused() {
        let hosts = r#"["docs.example.com", "*.docs.example.com"]"#;
        let a = Access {
            declared: caps(&format!(
                r#"{{ "network": {{ "hosts": {hosts} }}, "webview": {{ "hosts": {hosts} }} }}"#
            )),
            granted: None,
        };
        for url in [
            // WHATWG: bank.example; the check read docs.example.com.
            "https://bank.example\\@docs.example.com/",
            "https://bank.example:443\\@docs.example.com/",
            "https://[::1]\\@docs.example.com/",
            // WHATWG: bank.example; the check read a subdomain.
            "https://bank.example\\.docs.example.com/",
            // Foundation's NSURL: bank.example; WHATWG: docs.example.com.
            "https://docs.example.com\\@bank.example/",
            // WHATWG: the path is `/b`; the check read `/a\..\b`.
            "https://docs.example.com/a\\..\\b",
            // WHATWG drops these or refuses the URL; the check read a subdomain.
            "https://bank.example\0.docs.example.com/",
            "https://bank.example\t.docs.example.com/",
            "https://bank.example\n.docs.example.com/",
            "https://bank.example .docs.example.com/",
            "https://bank.example[.docs.example.com/",
            "https://x]y.docs.example.com/",
            // WHATWG: bank.example.docs.example.com, decoded.
            "https://bank%2Eexample.docs.example.com/",
        ] {
            assert!(!a.allows_webview(url), "{url:?}");
            assert!(!a.allows_http("GET", url), "{url:?}");
            assert!(!a.allows_media(url), "{url:?}");
        }
        assert!(!a.allows_websocket("wss://bank.example\\@docs.example.com/"));
        // What every parser reads alike is unchanged: an escaped backslash,
        // a backslash in the query (WHATWG keeps it there), user info.
        for url in [
            "https://docs.example.com/a%5Cb",
            "https://x.docs.example.com/?q=C:\\x#a\\b",
            "https://user:pw@docs.example.com/a b",
        ] {
            assert!(a.allows_webview(url), "{url:?}");
            assert!(a.allows_http("GET", url), "{url:?}");
        }
        // Nor does it refuse what an app without capabilities loads.
        let all = Access {
            declared: Capabilities::all(),
            granted: None,
        };
        let query = url::Url::parse("wss://x.example/?q=a\\b").unwrap();
        assert!(all.allows_websocket(query.as_str()), "{query}");
        assert!(all.allows_media("https://x.example/i.png?p=a\\b"));
    }

    /// A URL that parsers read differently names no one host, port or path:
    /// a grant of every host covers it (an app without `capabilities`, `*`),
    /// a narrower grant or a rule narrowing the port or path does not, and
    /// what is no URL stays refused.
    #[test]
    fn only_grants_of_every_host_cover_ambiguous_urls() {
        let url = "https://x.example/a\\b.png";
        let all = Access {
            declared: Capabilities::all(),
            granted: None,
        };
        let any = Access {
            declared: caps(r#"{ "network": { "hosts": ["*"] }, "webview": { "hosts": ["*"] } }"#),
            granted: None,
        };
        for a in [&all, &any] {
            assert!(a.allows_http("GET", url));
            assert!(a.allows_media(url));
            assert!(a.allows_webview(url));
            assert!(!a.allows_http("GET", "ftp://x.example/a\\b"));
            assert!(!a.allows_webview("file://x.example/a\\b"));
            assert!(!a.allows_webview("not a url"));
            assert!(!a.allows_http("GET", "https://"));
        }
        let rule = |rule: &str| Access {
            declared: caps(&format!(r#"{{ "network": {{ "http": [{rule}] }} }}"#)),
            granted: None,
        };
        let methods = rule(r#"{ "host": "*", "methods": ["get"], "schemes": ["https"] }"#);
        assert!(methods.allows_http("GET", url));
        assert!(!methods.allows_http("POST", url));
        assert!(!methods.allows_http("GET", "http://x.example/a\\b.png"));
        for narrowed in [
            r#"{ "host": "*", "port": 443 }"#,
            r#"{ "host": "*", "pathPrefix": "/a" }"#,
            r#"{ "host": "*", "paths": ["/a/b.png"] }"#,
            r#"{ "host": "x.example" }"#,
        ] {
            assert!(!rule(narrowed).allows_http("GET", url), "{narrowed}");
        }
    }

    /// A URL the check grants names a granted host for WHATWG's parser too,
    /// the web views' (`url`'s): the check may refuse more, never less.
    #[test]
    fn granted_urls_are_granted_hosts_for_whatwg() {
        let pattern = |p: &str| HostPattern::new(p).unwrap();
        let granted = [pattern("docs.example.com"), pattern("*.docs.example.com")];
        let a = Access {
            declared: caps(
                r#"{ "webview": { "hosts": ["docs.example.com", "*.docs.example.com"] } }"#,
            ),
            granted: None,
        };
        for url in [
            "https://docs.example.com/a",
            "https://DOCS.Example.COM/",
            "https://docs.example.com./",
            "https://x.docs.example.com:8443/",
            "https://user:pw@docs.example.com/",
            "https://docs.example.com#@bank.example/",
            "https://docs.example.com?@bank.example/",
            "https://docs.example.com:pass@bank.example/",
            "https://docs.example.com%2F@bank.example/",
            "https://bank.example\\@docs.example.com/",
            "https://bank.example:443\\@docs.example.com/",
            "https://[::1]\\@docs.example.com/",
            "https://bank.example\\.docs.example.com/",
            "https://docs.example.com\\@bank.example/",
            "https://bank.example\0.docs.example.com/",
            "https://bank.example\t.docs.example.com/",
            "https://docs.example.com\n.bank.example/",
            "https://bank%2Eexample.docs.example.com/",
            "https://docs\u{FF0E}example\u{FF0E}com/",
            "https://d\u{043E}cs.example.com/",
            "https:\\\\docs.example.com\\",
            " https://docs.example.com/",
            "https://docs.example.com /",
            "https://bank.example .docs.example.com/",
            "https://bank.example^.docs.example.com/",
            "https://bank.example[.docs.example.com/",
            "https://x]y.docs.example.com/",
            "https://a@bank.example@docs.example.com/",
            "https://..docs.example.com/",
            "HTTPS://DOCS.EXAMPLE.COM/",
            "https://x.docs.example.com/?q=C:\\x",
        ] {
            if a.allows_webview(url) {
                let whatwg = url::Url::parse(url).unwrap_or_else(|e| panic!("{url:?}: {e}"));
                let host = whatwg.host_str().unwrap_or_default().trim_end_matches('.');
                assert!(granted.iter().any(|p| p.matches(host)), "{url:?}: {host}");
            }
        }
    }

    #[test]
    fn the_embedder_grants_at_most() {
        let a = Access {
            declared: caps(
                r#"{ "network": { "hosts": ["a.com", "b.com"] }, "statusBar": true, "clipboard": true, "picker": true, "speech": true, "audio": true }"#,
            ),
            granted: Some(caps(
                r#"{ "network": { "hosts": ["b.com"] }, "clipboard": true }"#,
            )),
        };
        assert!(a.allows_clipboard());
        assert!(!a.allows_http("GET", "https://a.com/"));
        assert!(!a.allows_picker());
        assert!(!a.allows_speech());
        assert!(!a.allows_audio());
        assert!(a.allows_http("GET", "https://b.com/"));
        assert!(!a.allows_status_bar());
    }

    #[test]
    fn typos_are_errors() {
        let bad =
            |json: &str| Capabilities::from_json(&serde_json::from_str(json).unwrap()).unwrap_err();
        assert!(bad(r#"{ "netwrok": {} }"#).contains("unknown key `netwrok`"));
        assert!(bad(r#"{ "network": { "host": [] } }"#).contains("unknown key `host`"));
        assert!(bad(r#"{ "network": { "hosts": ["exa mple.com"] } }"#).contains("invalid host"));
        let c = caps(
            r#"{ "network": { "hosts": ["a.com"], "http": [{ "host": "b.com", "methods": ["GET"] }] }, "webview": { "hosts": ["*"] } }"#,
        );
        assert_eq!(Capabilities::from_json(&c.to_json()).unwrap(), c);
    }

    /// Packages from newer signers: what this runtime does not know is never
    /// granted, and an unknown restriction drops what it restricts.
    #[test]
    fn unknown_keys_in_packages_grant_nothing() {
        let lenient =
            |json: &str| Capabilities::from_json_lenient(&serde_json::from_str(json).unwrap());
        let (c, dropped) = lenient(
            r#"{ "bluetooth": true, "clipboard": true,
                 "network": { "hosts": ["a.com"], "http": [
                     { "host": "b.com", "ports": [443] },
                     { "host": "c.com", "methods": ["GET"] }
                 ] } }"#,
        )
        .unwrap();
        assert!(c.clipboard);
        assert_eq!(c.network.hosts, [HostPattern::new("a.com").unwrap()]);
        assert_eq!(c.network.http.len(), 1);
        assert_eq!(c.network.http[0].host.as_str(), "c.com");
        assert_eq!(
            dropped,
            [
                "capabilities.bluetooth",
                "capabilities.network.http[0] (unknown key `ports`)"
            ]
        );
        let (c, dropped) =
            lenient(r#"{ "network": { "hosts": ["a.com"], "ipv6": false }, "webview": { "hosts": ["*"], "x": 1 } }"#)
                .unwrap();
        assert_eq!(c, Capabilities::default());
        assert_eq!(dropped.len(), 2);
        // A value of a form it does not know (a newer NSH's, or a typo)
        // drops its capability, alone: denied, as nothing is granted
        // unless listed.
        let (c, dropped) = lenient(
            r#"{ "statusBar": "yes", "clipboard": true,
                 "network": { "hosts": ["exa mple.com"] }, "webview": { "hosts": ["a.com"] } }"#,
        )
        .unwrap();
        assert!(!c.status_bar);
        assert!(c.clipboard);
        assert!(c.network.hosts.is_empty());
        assert_eq!(c.webview, Some(vec![HostPattern::new("a.com").unwrap()]));
        assert_eq!(dropped.len(), 2, "{dropped:?}");
        assert!(
            dropped
                .iter()
                .any(|d| d.starts_with("capabilities.statusBar ("))
        );
        assert!(
            dropped
                .iter()
                .any(|d| d.starts_with("capabilities.network ("))
        );
        // An `http` grant of another form is dropped alone.
        let (c, dropped) = lenient(
            r#"{ "network": { "hosts": ["a.com"], "http": [
                 { "host": "b.com", "port": "any" }, { "host": "c.com" } ] } }"#,
        )
        .unwrap();
        assert_eq!(c.network.hosts.len(), 1);
        assert_eq!(c.network.http.len(), 1);
        assert_eq!(c.network.http[0].host.as_str(), "c.com");
        assert_eq!(dropped.len(), 1, "{dropped:?}");
        assert!(dropped[0].starts_with("capabilities.network.http[0] ("));
        // A declaration that is no object grants nothing.
        let (c, dropped) = lenient(r#""everything""#).unwrap();
        assert_eq!(c, Capabilities::default());
        assert_eq!(dropped.len(), 1);
        // The strict parse still refuses them.
        assert!(Capabilities::from_json(&serde_json::json!({ "statusBar": "yes" })).is_err());
        // Nothing unknown: the same as the strict parse.
        let json = serde_json::json!({ "network": { "hosts": ["a.com"] }, "statusBar": true });
        let (c, dropped) = Capabilities::from_json_lenient(&json).unwrap();
        assert_eq!(c, Capabilities::from_json(&json).unwrap());
        assert!(dropped.is_empty());
    }

    #[test]
    fn media_redirects_are_checked() {
        let a = Access {
            declared: Capabilities::from_json(
                &serde_json::json!({ "network": { "hosts": ["a.com"] } }),
            )
            .unwrap(),
            granted: None,
        };
        let from = "https://a.com/x/y.png";
        assert_eq!(
            a.media_redirect(from, "/z.png").unwrap(),
            "https://a.com/z.png"
        );
        assert_eq!(
            a.media_redirect(from, "z.png").unwrap(),
            "https://a.com/x/z.png"
        );
        assert!(a.media_redirect(from, "https://b.com/z.png").is_err());
        assert!(a.media_redirect(from, "//b.com/z.png").is_err());
        assert!(a.media_redirect(from, "file:///etc/passwd").is_err());
        assert!(
            Access::default()
                .media_redirect(from, "//b.com/z.png")
                .is_ok()
        );
        assert!(
            Access::default()
                .media_redirect(from, "ftp://b.com/z.png")
                .is_err()
        );
    }

    /// An HTTP rule's paths are matched against the path WHATWG's parser
    /// (the web views', the `url` crate's) reads, as a server receives it:
    /// dot segments, percent-encoded ones too, are resolved first.
    #[test]
    fn http_paths_are_matched_as_whatwg_resolves_them() {
        let a = Access {
            declared: caps(
                r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
            ),
            granted: None,
        };
        for url in [
            "https://api.example.com/public/../private",
            "https://api.example.com/public/%2e%2e/private",
            "https://api.example.com/public/%2E%2E/private",
            "https://api.example.com/public/.%2e/private",
            "https://api.example.com/public/./../private",
        ] {
            assert!(!a.allows_http("GET", url), "{url}");
            assert!(!a.allows_media(url), "{url}");
        }
        for url in [
            "https://api.example.com/public/x",
            "https://api.example.com/private/../public/x",
            "https://api.example.com/public/./x",
        ] {
            assert!(a.allows_http("GET", url), "{url}");
        }
    }

    /// A redirect's location is resolved as WHATWG's parser resolves it,
    /// dot segments included, before the rules see it.
    #[test]
    fn redirects_resolve_dot_segments() {
        assert_eq!(
            resolve_reference("https://api.example.com/public/x", "../private"),
            "https://api.example.com/private"
        );
        assert_eq!(
            resolve_reference("https://api.example.com/public/x", "%2e%2e/private"),
            "https://api.example.com/private"
        );
        let a = Access {
            declared: caps(
                r#"{ "network": { "http": [{ "host": "api.example.com", "pathPrefix": "/public" }] } }"#,
            ),
            granted: None,
        };
        let from = "https://api.example.com/public/a.png";
        assert!(a.media_redirect(from, "b.png").is_ok());
        assert!(a.media_redirect(from, "../private.png").is_err());
        assert!(a.media_redirect(from, "/public/../private.png").is_err());
    }

    /// A media source with a scheme, or one that starts with `//` or a
    /// backslash, names a host: it is checked as WHATWG's parser reads it,
    /// not taken for the app's own file.
    #[test]
    fn media_sources_that_name_a_host_are_checked() {
        let a = Access {
            declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
            granted: None,
        };
        for uri in [
            "//bank.example/x.png",
            "\\\\bank.example\\x.png",
            "/\\bank.example/x.png",
            "https:\\\\bank.example\\x.png",
            "https:/bank.example/x.png",
            "HTTPS://bank.example/x.png",
        ] {
            assert!(!a.allows_media(uri), "{uri}");
        }
        // The app's own files and bytes it has stay its own.
        for uri in [
            "asset:/a.png",
            "data:image/png;base64,AAAA",
            "blob:https://app.example/1",
            "https://docs.example.com/x.png",
        ] {
            assert!(a.allows_media(uri), "{uri}");
        }
        // A relative path names no file of the app's in a native app
        // (`relative_paths_name_no_file_in_a_native_app`).
        assert!(!a.allows_media("img/a.png"));
        // An app without capabilities is not checked, as before.
        assert!(Access::default().allows_media("//bank.example/x.png"));
    }

    /// WHATWG's parser drops leading and trailing spaces and C0 controls and
    /// every tab and newline before it reads a URL, so a source those make
    /// into one naming a host is checked, never kept as a relative path.
    #[test]
    fn media_sources_are_read_after_whatwg_strips_them() {
        let a = Access {
            declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
            granted: None,
        };
        let page = Some("https://app.example/index.html");
        for uri in [
            "\t//bank.example/x.png",
            "\n//bank.example/x.png",
            "/\t/bank.example/x.png",
            " https://bank.example/x.png",
            "https://bank.example/x.png ",
            "ht\ttps://bank.example/x.png",
            "\u{1}https://bank.example/x.png",
        ] {
            assert_eq!(a.media_url(uri, page, None), None, "{uri:?} on the web");
            assert_eq!(
                a.media_url(uri, None, None),
                None,
                "{uri:?} in a native app"
            );
        }
        // What stays relative after stripping stays the app's own.
        assert_eq!(
            a.media_url(" icons/a.png", page, None),
            Some(Cow::Borrowed(" icons/a.png"))
        );
        // Hosts are checked as WHATWG writes them, and load as checked.
        let local = Access {
            declared: caps(r#"{ "network": { "hosts": ["127.0.0.1"] } }"#),
            granted: None,
        };
        assert_eq!(
            local.media_url("http://0x7f.1/a.png", None, None),
            Some(Cow::Owned("http://127.0.0.1/a.png".into()))
        );
        assert_eq!(a.media_url("http://0x7f.1/a.png", None, None), None);
        // Schemes ignore case, the app's own sources' too.
        for own in [
            "DATA:image/png;base64,AA",
            "Asset:/a.png",
            "BLOB:https://app.example/1",
        ] {
            assert_eq!(
                a.media_url(own, page, None),
                Some(Cow::Borrowed(own)),
                "{own}"
            );
        }
    }

    /// Spaces and C0 controls around a source, which WHATWG's parser drops,
    /// are dropped before the check, and the loader gets the serialization:
    /// a granted URL a CMS left a trailing space on loads (it did before
    /// this branch), and no loader reads the source as written. A control
    /// inside, tabs and newlines included, stays ambiguous (#979).
    #[test]
    fn whitespace_around_a_granted_url_loads_its_serialization() {
        let a = Access {
            declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
            granted: None,
        };
        let page = Some("https://app.example/index.html");
        for (uri, base) in [
            ("https://docs.example.com/x.png ", None),
            (" https://docs.example.com/x.png", None),
            ("\u{1}https://docs.example.com/x.png", None),
            ("\t//docs.example.com/x.png", page),
        ] {
            assert_eq!(
                a.media_url(uri, base, None),
                Some(Cow::Owned("https://docs.example.com/x.png".into())),
                "{uri:?}"
            );
        }
        // A host it names is still checked, and a control inside stays
        // ambiguous.
        assert_eq!(a.media_url("https://bank.example/x.png ", None, None), None);
        for inside in [
            "https://docs.example.com/x\u{1}.png",
            "https://docs.ex\tample.com/x.png",
            "ht\ntps://docs.example.com/x.png",
        ] {
            assert_eq!(a.media_url(inside, None, None), None, "{inside:?}");
        }
    }

    /// A grant's paths are read as a request sends them (WHATWG percent-
    /// encodes spaces, `{`, `}` and what is not ASCII), so a path written
    /// with them matches; one with dot segments could match nothing and is
    /// a parse error.
    #[test]
    fn grant_paths_match_as_requests_send_them() {
        let a = Access {
            declared: caps(
                r#"{ "network": { "http": [
                    { "host": "cdn.example.com", "pathPrefix": "/my photos" },
                    { "host": "cdn.example.com", "paths": ["/über.png", "/{id}.png"] }
                ] } }"#,
            ),
            granted: None,
        };
        for url in [
            "https://cdn.example.com/my photos/a.png",
            "https://cdn.example.com/my%20photos/a.png",
            "https://cdn.example.com/über.png",
            "https://cdn.example.com/{id}.png",
        ] {
            assert!(a.allows_http("GET", url), "{url}");
            assert!(a.media_url(url, None, None).is_some(), "{url}");
        }
        assert!(!a.allows_http("GET", "https://cdn.example.com/my photosx/a.png"));
        // WHATWG reads `\\` as `/` and drops tabs and newlines, so these
        // are dot segments too.
        for bad in [
            "/a/../b",
            "/./a",
            "/a/%2e%2e/b",
            "/a/.%2E",
            "/public\\..\\private",
            "/a/.\t./b",
            "/a/.\n/b",
        ] {
            let json = serde_json::json!({ "network": { "http": [{ "host": "h.example", "pathPrefix": bad }] } });
            assert!(Capabilities::from_json(&json).is_err(), "{bad}");
        }
    }

    /// A local file is held to the roots by its text first, as
    /// `fs/promises` does: a path outside them is refused with no disk work
    /// on the engine thread (a hung mount, or a Windows share it would
    /// connect to), and only one inside is resolved to see that no link
    /// leads out.
    #[cfg(unix)]
    #[test]
    fn paths_outside_the_roots_are_refused_without_disk_work() {
        let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
        let root = base.join(format!("media-text-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("allowed")).unwrap();
        std::fs::create_dir_all(root.join("elsewhere")).unwrap();
        std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
        // A link outside the root into it: its text is outside.
        std::os::unix::fs::symlink(root.join("allowed"), root.join("elsewhere/in")).unwrap();
        let allowed = root.join("allowed");
        let access = Access {
            declared: Capabilities::from_json(
                &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
            )
            .unwrap(),
            granted: None,
        };
        let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
        let resolves = || RESOLVES.with(std::cell::Cell::get);
        let before = resolves();
        for outside in [
            root.join("elsewhere/x.png"),
            root.join("elsewhere/in/a.png"),
            PathBuf::from("/Volumes/hung/x.png"),
        ] {
            assert_eq!(files.readable(&outside), None, "{}", outside.display());
        }
        assert_eq!(
            resolves(),
            before,
            "outside the roots, nothing was resolved"
        );
        // Under the root's expanded or canonical form, it is resolved.
        assert!(files.readable(&allowed.join("a.png")).is_some());
        assert!(
            files
                .readable(&canonicalize(&allowed).unwrap().join("a.png"))
                .is_some()
        );
        assert_eq!(resolves(), before + 2);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Every check of a local file resolves it again: a file granted once
    /// and then replaced by a symlink out of the root is refused (#1417's
    /// review), never answered from an earlier check.
    #[cfg(unix)]
    #[test]
    fn a_granted_file_replaced_by_a_symlink_is_refused() {
        use std::os::unix::fs::symlink;
        let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
        let root = base.join(format!("media-swap-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("allowed")).unwrap();
        let root = canonicalize(&root).unwrap();
        std::fs::write(root.join("allowed/image.png"), b"public").unwrap();
        std::fs::write(root.join("secret.png"), b"secret").unwrap();
        let allowed = root.join("allowed").to_str().unwrap().to_owned();
        let access = Access {
            declared: Capabilities::from_json(
                &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
            )
            .unwrap(),
            granted: None,
        };
        let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
        let src = format!("{allowed}/image.png");
        assert!(access.media_url(&src, None, Some(&files)).is_some());
        std::fs::remove_file(root.join("allowed/image.png")).unwrap();
        symlink(root.join("secret.png"), root.join("allowed/image.png")).unwrap();
        assert_eq!(access.media_url(&src, None, Some(&files)), None);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A bundled file (`asset:`) stays inside the app's files, as `fetch`
    /// reads one: a path that leaves them, however it is spelled, loads
    /// nothing for an app with capabilities. The loaders join the path to
    /// their directory as written, query included.
    #[test]
    fn bundled_files_stay_inside_the_app_files() {
        let a = Access {
            declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
            granted: None,
        };
        for escape in [
            "asset:/../outside.png",
            "asset:/sub/../../outside.png",
            "asset:/%2E%2e/outside.png",
            "asset:/..%2Foutside.png",
            "asset:/a%5c..%5c..%5coutside.png",
            "asset:/a.png?/../../outside.png",
            "asset:/a.png#/../../outside.png",
            "asset://Users/a/outside.png",
            "asset:/C:/outside.png",
            "asset:/./a.png",
            "asset:../outside.png",
            "ASSET:/../outside.png",
        ] {
            assert_eq!(a.media_url(escape, None, None), None, "{escape}");
            assert_eq!(
                a.media_url(escape, Some("https://app.example/"), None),
                None,
                "{escape} on the web"
            );
            assert_eq!(media_grant_advice(escape, None), ASSET_ADVICE, "{escape}");
            assert_eq!(media_capability(escape, None), "fs", "{escape}");
        }
        for inside in [
            "asset:/a.png",
            "asset:/@app/icons/a.png",
            "asset:/a.png?v=2",
            "asset:/a%20b.png",
            "asset:/sub/a..b.png",
            "ASSET:/a.png",
        ] {
            assert_eq!(
                a.media_url(inside, None, None),
                Some(Cow::Borrowed(inside)),
                "{inside}"
            );
        }
        // An app without capabilities reads what it names, as before.
        assert_eq!(
            Access::default().media_url("asset:/../outside.png", None, None),
            Some(Cow::Borrowed("asset:/../outside.png"))
        );
    }

    /// A relative path names no file of the app's in a native app: the
    /// platforms read one against the process's working directory (desktop
    /// videos, Android images) or not at all, so an app with capabilities
    /// loads nothing from it. On the web it is the page's.
    #[test]
    fn relative_paths_name_no_file_in_a_native_app() {
        let a = Access {
            declared: caps(r#"{ "network": { "hosts": ["*"] } }"#),
            granted: None,
        };
        for relative in [
            "clip.mp4",
            "./clip.mp4",
            "Users/a/secret.mp4",
            "../etc/x.png",
            " /etc/x.png",
        ] {
            assert_eq!(a.media_url(relative, None, None), None, "{relative}");
            assert_eq!(media_capability(relative, None), "fs", "{relative}");
            assert_eq!(
                media_grant_advice(relative, None),
                RELATIVE_ADVICE,
                "{relative}"
            );
            assert_eq!(
                a.media_url(relative, Some("https://app.example/"), None),
                Some(Cow::Borrowed(relative)),
                "{relative} on the web"
            );
            assert_eq!(
                Access::default().media_url(relative, None, None),
                Some(Cow::Borrowed(relative)),
                "{relative} without capabilities"
            );
        }
        // No source is no refusal.
        for empty in ["", "  "] {
            assert_eq!(a.media_url(empty, None, None), Some(Cow::Borrowed(empty)));
        }
    }

    /// A granted media file is read through its root: a link swapped in
    /// after the check does not lead the read out of it.
    #[cfg(unix)]
    #[test]
    fn media_files_open_inside_their_root() {
        use std::io::Read;
        let base = std::env::temp_dir().join(format!("media-open-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(base.join("allowed")).unwrap();
        let base = canonicalize(&base).unwrap();
        std::fs::write(base.join("allowed/a.png"), b"public").unwrap();
        std::fs::write(base.join("secret.png"), b"secret").unwrap();
        let allowed = base.join("allowed");
        let access = Access {
            declared: Capabilities::from_json(
                &serde_json::json!({ "fs": { "read": [allowed.to_str().unwrap()] } }),
            )
            .unwrap(),
            granted: None,
        };
        let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
        let path = allowed.join("a.png");
        let read = |path: &Path| {
            let mut text = String::new();
            files.open(path)?.ok()?.read_to_string(&mut text).ok()?;
            Some(text)
        };
        assert_eq!(read(&path).as_deref(), Some("public"));
        // Swapped for a link out of the root after the check.
        std::fs::remove_file(&path).unwrap();
        std::os::unix::fs::symlink(base.join("secret.png"), &path).unwrap();
        assert!(matches!(files.open(&path), Some(Err(_))));
        assert!(matches!(files.open(&base.join("secret.png")), Some(Err(_))));
        // No roots: the caller opens the path.
        assert!(MediaFiles::default().open(&path).is_none());
        // A grant narrower than the declared root: a link in the grant
        // to a file elsewhere in the declared root is refused (#1605).
        std::fs::create_dir_all(base.join("allowed/sub")).unwrap();
        std::fs::write(base.join("allowed/sub/ok.png"), b"ok").unwrap();
        std::os::unix::fs::symlink(
            base.join("allowed/a.png"),
            base.join("allowed/sub/link.png"),
        )
        .unwrap();
        std::fs::remove_file(&path).unwrap();
        std::fs::write(&path, b"public").unwrap();
        let narrowed = Access {
            declared: access.declared.clone(),
            granted: Some(
                Capabilities::from_json(&serde_json::json!({
                    "fs": { "read": [allowed.join("sub").to_str().unwrap()] }
                }))
                .unwrap(),
            ),
        };
        let files = MediaFiles::new(&narrowed, None, &TrustedPaths::default(), true);
        let mut text = String::new();
        files
            .open(&allowed.join("sub/ok.png"))
            .unwrap()
            .unwrap()
            .read_to_string(&mut text)
            .unwrap();
        assert_eq!(text, "ok");
        assert!(matches!(
            files.open(&allowed.join("sub/link.png")),
            Some(Err(_))
        ));
        assert!(matches!(files.open(&path), Some(Err(_))));
        // `file://localhost/` names the same local file, and is refused the same.
        let localhost = format!("file://localhost{}", allowed.join("sub/link.png").display());
        assert_eq!(narrowed.media_url(&localhost, None, Some(&files)), None);
        let ok = format!("file://localhost{}", allowed.join("sub/ok.png").display());
        assert!(narrowed.media_url(&ok, None, Some(&files)).is_some());
        let _ = std::fs::remove_dir_all(&base);
    }

    /// A symlink in a granted root whose target does not exist yet is
    /// refused: it names no file to resolve, and the loader would follow it
    /// out of the root once the target appears.
    #[cfg(unix)]
    #[test]
    fn a_dangling_symlink_in_a_granted_root_is_refused() {
        use std::os::unix::fs::symlink;
        let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
        let root = base.join(format!("media-dangling-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("allowed")).unwrap();
        let root = canonicalize(&root).unwrap();
        symlink(root.join("secret.png"), root.join("allowed/link.png")).unwrap();
        let allowed = root.join("allowed").to_str().unwrap().to_owned();
        let access = Access {
            declared: Capabilities::from_json(
                &serde_json::json!({ "fs": { "read": [allowed.clone()] } }),
            )
            .unwrap(),
            granted: None,
        };
        let files = MediaFiles::new(&access, None, &TrustedPaths::default(), true);
        assert_eq!(
            access.media_url(&format!("{allowed}/link.png"), None, Some(&files)),
            None
        );
        // A file that does not exist yet, and no link, is still the root's.
        let missing = format!("{allowed}/later.png");
        assert_eq!(
            access.media_url(&missing, None, Some(&files)),
            Some(Cow::Borrowed(missing.as_str()))
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A local file in a media source (an absolute path, a `file:` URL) is
    /// read under `capabilities.fs.read`, as `fs/promises` reads it, and
    /// loads as its canonical path, so a symlink in a granted root cannot
    /// lead the platform's loader out of it.
    #[cfg(unix)]
    #[test]
    fn local_media_files_need_an_fs_read_grant() {
        use std::os::unix::fs::symlink;
        let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from);
        let root = base.join(format!("media-files-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("allowed")).unwrap();
        std::fs::create_dir_all(root.join("outside")).unwrap();
        std::fs::write(root.join("allowed/a.png"), b"png").unwrap();
        std::fs::write(root.join("outside/b.png"), b"png").unwrap();
        symlink(root.join("outside"), root.join("allowed/link")).unwrap();
        // Canonical, so only the symlink below differs from its text.
        let root = canonicalize(&root).unwrap();
        let data = root.join("allowed");
        let access = Access {
            declared: caps(
                r#"{ "network": { "hosts": ["docs.example.com"] }, "fs": { "read": ["${dataDir}"] } }"#,
            ),
            granted: None,
        };
        let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
        let real = canonicalize(&data).unwrap();
        let path = |p: &Path| p.to_str().unwrap().to_owned();
        let load = |uri: &str| {
            access
                .media_url(uri, None, Some(&files))
                .map(Cow::into_owned)
        };

        let granted = path(&real.join("a.png"));
        assert_eq!(load(&path(&data.join("a.png"))), Some(granted.clone()));
        assert_eq!(
            load(&format!("file://{}", path(&data.join("a.png")))),
            Some(format!("file://{granted}"))
        );
        assert_eq!(
            load(&format!("FILE://{}", path(&data.join("a.png")))),
            Some(format!("file://{granted}"))
        );
        // `..`, percent-encoded or not, and a symlink lead out of the root.
        assert_eq!(load(&path(&data.join("../outside/b.png"))), None);
        assert_eq!(
            load(&format!("file://{}/%2e%2e/outside/b.png", path(&data))),
            None
        );
        assert_eq!(load(&path(&data.join("link/b.png"))), None);
        assert_eq!(load(&path(&root.join("outside/b.png"))), None);
        // No roots to read from: none granted, or no file system here.
        assert_eq!(
            access.media_url(&path(&data.join("a.png")), None, None),
            None
        );
        let mobile = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), false);
        assert_eq!(
            access.media_url(&path(&data.join("a.png")), None, Some(&mobile)),
            None
        );
        let network_only = Access {
            declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
            granted: None,
        };
        let none = MediaFiles::new(&network_only, Some(&data), &TrustedPaths::default(), true);
        assert_eq!(
            network_only.media_url(&path(&data.join("a.png")), None, Some(&none)),
            None
        );
        // The host's grant narrows the app's.
        let narrowed = Access {
            declared: caps(r#"{ "fs": { "read": ["${dataDir}"] } }"#),
            granted: Some(caps(r#"{ "fs": { "read": ["${dataDir}/sub"] } }"#)),
        };
        let files = MediaFiles::new(&narrowed, Some(&data), &TrustedPaths::default(), true);
        assert_eq!(
            narrowed.media_url(&path(&data.join("a.png")), None, Some(&files)),
            None
        );
        // On the web, `/x` is the page's; an app without capabilities loads
        // what it names, as before.
        let page = Some("https://app.example/index.html");
        assert_eq!(
            access.media_url("/icons/a.png", page, None),
            Some(Cow::Borrowed("/icons/a.png"))
        );
        // An app without capabilities loads local files as written, as
        // before.
        for local in [
            path(&root.join("outside/b.png")),
            format!("FILE://{}", path(&root.join("outside/b.png"))),
            "C:\\pictures\\x.png".to_owned(),
            "/x.png".to_owned(),
        ] {
            assert_eq!(
                Access::default().media_url(&local, None, None),
                Some(Cow::Borrowed(local.as_str())),
                "{local}"
            );
        }
        // A path checked again answers the same.
        let files = MediaFiles::new(&access, Some(&data), &TrustedPaths::default(), true);
        for _ in 0..2 {
            let again = |uri: &str| {
                access
                    .media_url(uri, None, Some(&files))
                    .map(Cow::into_owned)
            };
            assert_eq!(again(&path(&data.join("a.png"))), Some(granted.clone()));
            assert_eq!(again(&path(&data.join("link/b.png"))), None);
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    /// `capabilities.fs` roots gate the file system every native OS has —
    /// the desktops', iOS's, Android's; the web has none to gate.
    #[test]
    fn every_native_os_has_the_files_the_capability_gates() {
        use crate::platform::Os;
        for os in [Os::MacOs, Os::Windows, Os::Linux, Os::Ios, Os::Android] {
            assert!(native_files(os), "{os:?}");
        }
        assert!(!native_files(Os::Web));
    }

    /// A `file:` URL's path is the URL's decoded path: `%20` is a space,
    /// `file://localhost/` names no host that refuses.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn file_urls_name_their_decoded_path() {
        #[cfg(unix)]
        {
            assert_eq!(
                file_url_path("file:///tmp/a%20b.png"),
                Some(PathBuf::from("/tmp/a b.png"))
            );
            assert_eq!(
                file_url_path("file://localhost/tmp/a.png"),
                Some(PathBuf::from("/tmp/a.png"))
            );
            assert_eq!(file_url_path("file://host/tmp/a.png"), None);
        }
        #[cfg(windows)]
        {
            // A `file:` URL there names a drive: a path without one is no
            // Windows path (this is what the URL standard says, and what
            // the loaders resolve), and `localhost` is still no host to
            // refuse.
            assert_eq!(
                file_url_path("file:///C:/a%20b.png"),
                Some(PathBuf::from("C:\\a b.png"))
            );
            assert_eq!(
                file_url_path("file://localhost/C:/a.png"),
                Some(PathBuf::from("C:\\a.png"))
            );
            assert_eq!(file_url_path("file:///tmp/a.png"), None);
            assert_eq!(file_url_path("file://localhost/tmp/a.png"), None);
        }
        assert_eq!(file_url_path("not a url"), None);
        assert_eq!(file_url_path("https://a/b"), None);
    }

    /// A refused source's advice names the host it resolves to, as the
    /// check read it.
    #[test]
    fn refused_media_sources_advise_the_host_they_resolve_to() {
        let page = Some("http://localhost:8080/index.html");
        // Against the page, `//host` names the host a grant would add.
        assert_eq!(
            media_grant_advice("//127.0.0.1:9000/a.png", page),
            "add `127.0.0.1` to capabilities.network in nsh.json"
        );
        // Without one, it has no scheme to load with.
        assert_eq!(
            media_grant_advice("//127.0.0.1:9000/a.png", None),
            NO_SCHEME_ADVICE
        );
        // A backslash stays ambiguous, whatever the base.
        assert_eq!(
            media_grant_advice("//127.0.0.1\\a.png", page),
            NO_HOST_ADVICE
        );
        assert_eq!(
            media_grant_advice("https://cdn.example.com/a.png", page),
            "add `cdn.example.com` to capabilities.network in nsh.json"
        );
        // A local file is the `fs` capability's, in a native app; `/x` is
        // the page's on the web.
        assert_eq!(
            media_grant_advice("/Users/a/x.png", None),
            LOCAL_FILE_ADVICE
        );
        assert_eq!(
            media_grant_advice("file:///Users/a/x.png", page),
            LOCAL_FILE_ADVICE
        );
        // A refusal names the capability that would grant the source.
        assert_eq!(media_capability("/Users/a/x.png", None), "fs");
        assert_eq!(media_capability("C:\\pictures\\x.png", None), "fs");
        assert_eq!(media_capability("FILE:///Users/a/x.png", page), "fs");
        assert_eq!(media_capability("/icons/a.png", page), "network");
        assert_eq!(
            media_capability("https://cdn.example.com/a.png", None),
            "network"
        );
    }

    /// What a loader loads is what the check granted: a source naming a host
    /// becomes its WHATWG serialization, `//` taking the base's scheme (the
    /// page's on the web; with no base it names no URL); the app's own stay
    /// as written.
    #[test]
    fn media_sources_load_the_url_the_check_granted() {
        let a = Access {
            declared: caps(r#"{ "network": { "hosts": ["docs.example.com"] } }"#),
            granted: None,
        };
        let https = Some("https://app.example/index.html");
        let http = Some("http://127.0.0.1:8080/");
        let loads = |uri, base| a.media_url(uri, base, None).map(|u| u.into_owned());
        assert_eq!(
            loads("https://DOCS.example.com/a/../x.png", None).as_deref(),
            Some("https://docs.example.com/x.png")
        );
        assert_eq!(
            loads("//docs.example.com/x.png", https).as_deref(),
            Some("https://docs.example.com/x.png")
        );
        assert_eq!(
            loads("//docs.example.com/x.png", http).as_deref(),
            Some("http://docs.example.com/x.png")
        );
        // A backslash before the query is read differently by Foundation's
        // `NSURL` (`urls_that_parsers_read_as_different_hosts_are_refused`):
        // only a grant of every host covers it, `//`'s backslash forms too.
        assert_eq!(loads("\\\\docs.example.com\\x.png", https), None);
        assert_eq!(loads("//docs.example.com/x.png", None), None);
        assert_eq!(loads("//bank.example/x.png", https), None);
        for own in ["asset:/a.png", "img/a.png", "data:image/png;base64,AAAA"] {
            assert!(
                matches!(a.media_url(own, https, None), Some(std::borrow::Cow::Borrowed(u)) if u == own),
                "{own}"
            );
        }
        // Without capabilities, nothing is checked or rewritten.
        assert!(matches!(
            Access::default().media_url("//bank.example/x.png", None, None),
            Some(std::borrow::Cow::Borrowed("//bank.example/x.png"))
        ));
    }

    #[test]
    fn opening_urls_is_granted_by_scheme() {
        let caps = |json: serde_json::Value| Capabilities::from_json(&json).unwrap();
        let access =
            |declared: Capabilities, granted: Option<Capabilities>| Access { declared, granted };
        let any = access(caps(serde_json::json!({ "openUrl": true })), None);
        assert!(any.allows_open_url("https://a.com"));
        assert!(any.allows_open_url("tel:+15550100"));
        let some = access(
            caps(serde_json::json!({ "openUrl": { "schemes": ["HTTPS", "mailto"] } })),
            None,
        );
        assert!(some.allows_open_url("https://a.com"));
        assert!(some.allows_open_url("MAILTO:a@b.c"));
        assert!(!some.allows_open_url("tel:1"));
        // The embedding app grants less.
        let narrowed = access(
            caps(serde_json::json!({ "openUrl": true })),
            Some(caps(
                serde_json::json!({ "openUrl": { "schemes": ["https"] } }),
            )),
        );
        assert!(narrowed.allows_open_url("https://a.com"));
        assert!(!narrowed.allows_open_url("mailto:a@b.c"));
        let none = access(caps(serde_json::json!({ "openUrl": false })), None);
        assert!(!none.allows_open_url("https://a.com"));
        assert!(!access(caps(serde_json::json!({})), None).allows_open_url("https://a.com"));
        assert!(Access::default().allows_open_url("https://a.com"));
        for bad in [
            serde_json::json!({ "openUrl": "yes" }),
            serde_json::json!({ "openUrl": { "schemes": ["ht tp"] } }),
            serde_json::json!({ "openUrl": { "hosts": ["a.com"] } }),
        ] {
            assert!(Capabilities::from_json(&bad).is_err(), "{bad}");
        }
        // Round trip.
        for json in [
            serde_json::json!(true),
            serde_json::json!(false),
            serde_json::json!({ "schemes": ["https"] }),
        ] {
            let c = caps(serde_json::json!({ "openUrl": json }));
            assert_eq!(c.to_json()["openUrl"], json);
        }
    }
}