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
|
/*
* Copyright (C) 2024 Igalia S.L. All rights reserved.
* Copyright (C) 2024 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebExtension.h"
#if ENABLE(WK_WEB_EXTENSIONS)
#include "Logging.h"
#include "WebExtensionConstants.h"
#include "WebExtensionPermission.h"
#include "WebExtensionUtilities.h"
#include <WebCore/LocalizedStrings.h>
#include <WebCore/MIMETypeRegistry.h>
#include <WebCore/TextResourceDecoder.h>
#include <wtf/FileSystem.h>
#include <wtf/Language.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/Scope.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/StringToIntegerConversion.h>
#include <wtf/text/WTFString.h>
namespace WebKit {
using namespace WebCore;
static constexpr auto defaultLocaleManifestKey = "default_locale"_s;
static constexpr auto iconsManifestKey = "icons"_s;
#if ENABLE(WK_WEB_EXTENSIONS_ICON_VARIANTS)
static constexpr auto iconVariantsManifestKey = "icon_variants"_s;
static constexpr auto colorSchemesManifestKey = "color_schemes"_s;
static constexpr auto lightManifestKey = "light"_s;
static constexpr auto darkManifestKey = "dark"_s;
static constexpr auto anyManifestKey = "any"_s;
#endif
static constexpr auto actionManifestKey = "action"_s;
static constexpr auto browserActionManifestKey = "browser_action"_s;
static constexpr auto pageActionManifestKey = "page_action"_s;
static constexpr auto defaultIconManifestKey = "default_icon"_s;
static constexpr auto defaultTitleManifestKey = "default_title"_s;
static constexpr auto defaultPopupManifestKey = "default_popup"_s;
static constexpr auto manifestVersionManifestKey = "manifest_version"_s;
static constexpr auto nameManifestKey = "name"_s;
static constexpr auto shortNameManifestKey = "short_name"_s;
static constexpr auto versionManifestKey = "version"_s;
static constexpr auto versionNameManifestKey = "version_name"_s;
static constexpr auto descriptionManifestKey = "description"_s;
static constexpr auto contentSecurityPolicyManifestKey = "content_security_policy"_s;
static constexpr auto contentSecurityPolicyExtensionPagesManifestKey = "extension_pages"_s;
static constexpr auto contentScriptsManifestKey = "content_scripts"_s;
static constexpr auto contentScriptsMatchesManifestKey = "matches"_s;
static constexpr auto contentScriptsExcludeMatchesManifestKey = "exclude_matches"_s;
static constexpr auto contentScriptsIncludeGlobsManifestKey = "include_globs"_s;
static constexpr auto contentScriptsExcludeGlobsManifestKey = "exclude_globs"_s;
static constexpr auto contentScriptsMatchesAboutBlankManifestKey = "match_about_blank"_s;
static constexpr auto contentScriptsRunAtManifestKey = "run_at"_s;
static constexpr auto contentScriptsDocumentIdleManifestKey = "document_idle"_s;
static constexpr auto contentScriptsDocumentStartManifestKey = "document_start"_s;
static constexpr auto contentScriptsDocumentEndManifestKey = "document_end"_s;
static constexpr auto contentScriptsAllFramesManifestKey = "all_frames"_s;
static constexpr auto contentScriptsJSManifestKey = "js"_s;
static constexpr auto contentScriptsCSSManifestKey = "css"_s;
static constexpr auto contentScriptsWorldManifestKey = "world"_s;
static constexpr auto contentScriptsIsolatedManifestKey = "isolated"_s;
static constexpr auto contentScriptsMainManifestKey = "main"_s;
static constexpr auto contentScriptsCSSOriginManifestKey = "css_origin"_s;
static constexpr auto contentScriptsAuthorManifestKey = "author"_s;
static constexpr auto contentScriptsUserManifestKey = "user"_s;
static constexpr auto optionsUIManifestKey = "options_ui"_s;
static constexpr auto optionsUIPageManifestKey = "page"_s;
static constexpr auto optionsPageManifestKey = "options_page"_s;
static constexpr auto chromeURLOverridesManifestKey = "chrome_url_overrides"_s;
static constexpr auto browserURLOverridesManifestKey = "browser_url_overrides"_s;
static constexpr auto newTabManifestKey = "newtab"_s;
static constexpr auto backgroundManifestKey = "background"_s;
static constexpr auto backgroundPageManifestKey = "page"_s;
static constexpr auto backgroundServiceWorkerManifestKey = "service_worker"_s;
static constexpr auto backgroundScriptsManifestKey = "scripts"_s;
static constexpr auto backgroundPersistentManifestKey = "persistent"_s;
static constexpr auto backgroundPageTypeKey = "type"_s;
static constexpr auto backgroundPageTypeModuleValue = "module"_s;
static constexpr auto backgroundPreferredEnvironmentManifestKey = "preferred_environment"_s;
static constexpr auto backgroundDocumentManifestKey = "document"_s;
static constexpr auto generatedBackgroundPageFilename = "_generated_background_page.html"_s;
static constexpr auto generatedBackgroundServiceWorkerFilename = "_generated_service_worker.js"_s;
static constexpr auto permissionsManifestKey = "permissions"_s;
static constexpr auto optionalPermissionsManifestKey = "optional_permissions"_s;
static constexpr auto hostPermissionsManifestKey = "host_permissions"_s;
static constexpr auto optionalHostPermissionsManifestKey = "optional_host_permissions"_s;
static constexpr auto externallyConnectableManifestKey = "externally_connectable"_s;
static constexpr auto externallyConnectableMatchesManifestKey = "matches"_s;
static constexpr auto externallyConnectableIDsManifestKey = "ids"_s;
static constexpr auto devtoolsPageManifestKey = "devtools_page"_s;
static constexpr auto webAccessibleResourcesManifestKey = "web_accessible_resources"_s;
static constexpr auto webAccessibleResourcesResourcesManifestKey = "resources"_s;
static constexpr auto webAccessibleResourcesMatchesManifestKey = "matches"_s;
static constexpr auto commandsManifestKey = "commands"_s;
static constexpr auto commandsSuggestedKeyManifestKey = "suggested_key"_s;
static constexpr auto commandsDescriptionKeyManifestKey = "description"_s;
static constexpr auto declarativeNetRequestManifestKey = "declarative_net_request"_s;
static constexpr auto declarativeNetRequestRulesManifestKey = "rule_resources"_s;
static constexpr auto declarativeNetRequestRulesetIDManifestKey = "id"_s;
static constexpr auto declarativeNetRequestRuleEnabledManifestKey = "enabled"_s;
static constexpr auto declarativeNetRequestRulePathManifestKey = "path"_s;
#if ENABLE(WK_WEB_EXTENSIONS_SIDEBAR)
static constexpr auto sidebarActionManifestKey = "sidebar_action"_s;
static constexpr auto sidePanelManifestKey = "side_panel"_s;
static constexpr auto sidebarActionTitleManifestKey = "default_title"_s;
static constexpr auto sidebarActionPathManifestKey = "default_panel"_s;
static constexpr auto sidePanelPathManifestKey = "default_path"_s;
#endif // ENABLE(WK_WEB_EXTENSIONS_SIDEBAR)
static const size_t maximumNumberOfShortcutCommands = 4;
WebExtension::WebExtension(Resources&& resources)
: m_manifestJSON(JSON::Value::null())
, m_resources(WTFMove(resources))
{
}
WebExtension::~WebExtension()
{
if (m_resourcesAreTemporary && !m_resourceBaseURL.isEmpty())
FileSystem::deleteNonEmptyDirectory(m_resourceBaseURL.fileSystemPath());
}
static String convertChromeExtensionToTemporaryZipFile(const String& inputFilePath)
{
// Converts a Chrome extension file to a temporary ZIP file by checking for a valid Chrome extension signature ('Cr24')
// and copying the contents starting from the ZIP signature ('PK\x03\x04'). Returns a null string if the signatures
// are not found or any file operations fail.
auto inputFileHandle = FileSystem::openFile(inputFilePath, FileSystem::FileOpenMode::Read);
if (!FileSystem::isHandleValid(inputFileHandle))
return nullString();
auto closeFile = makeScopeExit([&] {
FileSystem::unlockAndCloseFile(inputFileHandle);
});
// Read the magic signature.
std::array<uint8_t, 4> signature;
auto bytesRead = FileSystem::readFromFile(inputFileHandle, signature);
if (bytesRead < 0 || static_cast<size_t>(bytesRead) != signature.size())
return nullString();
// Verify Chrome extension magic signature.
static std::array<uint8_t, 4> expectedSignature = { 'C', 'r', '2', '4' };
if (signature != expectedSignature)
return nullString();
// Create a temporary ZIP file.
auto [temporaryFilePath, temporaryFileHandle] = FileSystem::openTemporaryFile("WebKitExtension-"_s, ".zip"_s);
if (!FileSystem::isHandleValid(temporaryFileHandle))
return nullString();
auto closeTempFile = makeScopeExit([fileHandle = temporaryFileHandle] {
FileSystem::unlockAndCloseFile(fileHandle);
});
std::array<uint8_t, 4096> buffer;
bool signatureFound = false;
while (true) {
bytesRead = FileSystem::readFromFile(inputFileHandle, buffer);
// Error reading file.
if (bytesRead < 0)
return nullString();
// Done reading file.
if (!bytesRead)
break;
size_t bufferOffset = 0;
if (!signatureFound) {
// Not enough bytes for the signature.
if (bytesRead < 4)
return nullString();
// Search for the ZIP file magic signature in the buffer.
for (ssize_t i = 0; i < bytesRead - 3; ++i) {
if (buffer[i] == 'P' && buffer[i + 1] == 'K' && buffer[i + 2] == 0x03 && buffer[i + 3] == 0x04) {
signatureFound = true;
bufferOffset = i;
break;
}
}
// Continue until the start of the ZIP file is found.
if (!signatureFound)
continue;
}
auto bytesToWrite = std::span(buffer).subspan(bufferOffset, bytesRead - bufferOffset);
auto bytesWritten = FileSystem::writeToFile(temporaryFileHandle, bytesToWrite);
if (bytesWritten != static_cast<int64_t>(bytesToWrite.size()))
return nullString();
}
return temporaryFilePath;
}
String WebExtension::processFileAndExtractZipArchive(const String& path)
{
// Check if the file is a Chrome extension archive and extract it.
auto temporaryZipFilePath = convertChromeExtensionToTemporaryZipFile(path);
if (!temporaryZipFilePath.isNull()) {
auto temporaryDirectory = FileSystem::extractTemporaryZipArchive(temporaryZipFilePath);
FileSystem::deleteFile(temporaryZipFilePath);
return temporaryDirectory;
}
// Assume the file is already a ZIP archive and try to extract it.
return FileSystem::extractTemporaryZipArchive(path);
}
bool WebExtension::parseManifest(StringView manifestString)
{
RefPtr manifestValue = JSON::Value::parseJSON(manifestString);
if (!manifestValue) {
recordError(createError(Error::InvalidManifest));
return false;
}
RefPtr manifestObject = manifestValue->asObject();
if (!manifestObject) {
recordError(createError(Error::InvalidManifest));
return false;
}
// Set to the unlocalized manifest for now so calls to manifestParsedSuccessfully() during this will be true.
// This is needed for WebExtensionLocalization to properly get the defaultLocale() while we are mid-parse.
m_manifestJSON = *manifestObject;
if (auto defaultLocale = manifestObject->getString(defaultLocaleManifestKey); !defaultLocale.isNull()) {
auto parsedLocale = parseLocale(manifestObject->getString(defaultLocaleManifestKey));
if (!parsedLocale.languageCode.isEmpty()) {
if (supportedLocales().contains(defaultLocale))
m_defaultLocale = defaultLocale;
else
recordError(createError(Error::InvalidDefaultLocale, WEB_UI_STRING("Unable to find `default_locale` in “_locales” folder.", "Error description for missing default_locale")));
} else
recordError(createError(Error::InvalidDefaultLocale));
}
Ref localization = WebExtensionLocalization::create(*this);
m_localization = localization.copyRef();
RefPtr localizedManifestObject = localization->localizedJSONforJSON(manifestObject);
if (!localizedManifestObject) {
m_manifestJSON = JSON::Value::null();
recordError(createError(Error::InvalidManifest));
return false;
}
m_manifestJSON = localizedManifestObject.releaseNonNull();
return true;
}
RefPtr<const JSON::Object> WebExtension::manifestObject()
{
if (m_parsedManifest)
return m_manifestJSON->asObject();
m_parsedManifest = true;
RefPtr<API::Error> error;
auto manifestString = resourceStringForPath("manifest.json"_s, error);
if (error) {
recordErrorIfNeeded(error);
return nullptr;
}
if (!parseManifest(manifestString))
return nullptr;
return m_manifestJSON->asObject();
}
bool WebExtension::manifestParsedSuccessfully()
{
return !!manifestObject();
}
double WebExtension::manifestVersion()
{
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return 0;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/manifest_version
if (auto value = manifestObject->getDouble(manifestVersionManifestKey))
return *value;
return 0;
}
RefPtr<API::Data> WebExtension::serializeManifest()
{
Ref manifestJSON = m_manifestJSON;
if (!manifestJSON)
return nullptr;
return API::Data::create(manifestJSON->toJSONString().utf8().span());
}
RefPtr<API::Data> WebExtension::serializeLocalization()
{
if (!m_localization || !m_localization->localizationJSON())
return nullptr;
return API::Data::create(m_localization->localizationJSON()->toJSONString().utf8().span());
}
RefPtr<WebExtensionLocalization> WebExtension::localization()
{
if (!manifestParsedSuccessfully())
return nullptr;
return m_localization;
}
bool WebExtension::hasRequestedPermission(String permission)
{
populatePermissionsPropertiesIfNeeded();
return m_permissions.contains(permission);
}
bool WebExtension::isWebAccessibleResource(const URL& resourceURL, const URL& pageURL)
{
populateWebAccessibleResourcesIfNeeded();
auto resourcePath = resourceURL.path().toString();
// The path is expected to match without the prefix slash.
ASSERT(resourcePath.startsWith('/'));
resourcePath = resourcePath.substring(1);
for (auto& data : m_webAccessibleResources) {
// If matchPatterns is empty, these resources are allowed on any page.
bool allowed = data.matchPatterns.isEmpty();
for (Ref matchPattern : data.matchPatterns) {
if (matchPattern->matchesURL(pageURL)) {
allowed = true;
break;
}
}
if (!allowed)
continue;
for (auto& pathPattern : data.resourcePathPatterns) {
if (WebCore::matchesWildcardPattern(pathPattern, resourcePath))
return true;
}
}
return false;
}
void WebExtension::parseWebAccessibleResourcesVersion3()
{
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
if (RefPtr resourcesArray = manifestObject->getArray(webAccessibleResourcesManifestKey)) {
bool errorOccured = false;
for (Ref resource : *resourcesArray) {
if (RefPtr resourceObject = resource->asObject()) {
RefPtr pathsArray = resourceObject->getArray(webAccessibleResourcesResourcesManifestKey);
if (pathsArray) {
pathsArray = filterObjects(*pathsArray, [](auto& value) {
return !value.asString().isEmpty();
});
} else {
errorOccured = true;
continue;
}
RefPtr matchesArray = resourceObject->getArray(webAccessibleResourcesMatchesManifestKey);
if (matchesArray) {
matchesArray = filterObjects(*matchesArray, [](auto& value) {
return !value.asString().isEmpty();
});
} else {
errorOccured = true;
continue;
}
if (!pathsArray->length() || !matchesArray->length())
continue;
MatchPatternSet matchPatterns;
for (Ref match : *matchesArray) {
if (RefPtr matchPattern = WebExtensionMatchPattern::getOrCreate(match->asString())) {
if (matchPattern->isSupported())
matchPatterns.add(matchPattern.releaseNonNull());
else
errorOccured = true;
}
}
if (matchPatterns.isEmpty()) {
errorOccured = true;
continue;
}
m_webAccessibleResources.append({ WTFMove(matchPatterns), makeStringVector(*pathsArray) });
}
}
if (errorOccured)
recordError(createError(Error::InvalidWebAccessibleResources));
} else if (manifestObject->getValue(webAccessibleResourcesManifestKey))
recordError(createError(Error::InvalidWebAccessibleResources));
}
void WebExtension::parseWebAccessibleResourcesVersion2()
{
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
if (RefPtr resourcesArray = manifestObject->getArray(webAccessibleResourcesManifestKey)) {
resourcesArray = filterObjects(*resourcesArray, [](auto& value) {
return !value.asString().isEmpty();
});
m_webAccessibleResources.append({ { }, makeStringVector(*resourcesArray) });
} else if (manifestObject->getValue(webAccessibleResourcesManifestKey))
recordError(createError(Error::InvalidWebAccessibleResources));
}
void WebExtension::populateWebAccessibleResourcesIfNeeded()
{
if (m_parsedManifestWebAccessibleResources)
return;
m_parsedManifestWebAccessibleResources = true;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/web_accessible_resources
if (supportsManifestVersion(3))
parseWebAccessibleResourcesVersion3();
else
parseWebAccessibleResourcesVersion2();
}
URL WebExtension::resourceFileURLForPath(const String& originalPath)
{
ASSERT(originalPath);
String path = originalPath;
if (path.startsWith('/'))
path = path.substring(1);
if (!path.length() || m_resourceBaseURL.isEmpty())
return { };
URL result { m_resourceBaseURL, path };
if (!FileSystem::fileExists(result.fileSystemPath()))
return { };
// Don't allow escaping the base URL with "../".
auto basePath = FileSystem::realPath(m_resourceBaseURL.fileSystemPath());
auto resourcePath = FileSystem::realPath(result.fileSystemPath());
if (!resourcePath.startsWith(basePath)) {
RELEASE_LOG_ERROR(Extensions, "Resource URL path escape attempt: %s", resourcePath.utf8().data());
return { };
}
return result;
}
String WebExtension::resourceMIMETypeForPath(const String& path)
{
auto dataPrefix = "data:"_s;
if (path.startsWith(dataPrefix)) {
auto mimeTypePosition = path.find(';');
if (mimeTypePosition != notFound)
return path.substring(dataPrefix.length(), mimeTypePosition - dataPrefix.length());
return defaultMIMEType();
}
return MIMETypeRegistry::mimeTypeForPath(path);
}
String WebExtension::resourceStringForPath(const String& originalPath, RefPtr<API::Error>& outError, CacheResult cacheResult, SuppressNotFoundErrors suppressErrors)
{
ASSERT(originalPath);
String path = originalPath;
// Remove leading slash to normalize the path for lookup/storage in the cache dictionary.
if (path.startsWith('/'))
path = path.substring(1);
if (path == generatedBackgroundPageFilename || path == generatedBackgroundServiceWorkerFilename)
return generatedBackgroundContent();
if (auto entry = m_resources.find(path); entry != m_resources.end()) {
return WTF::switchOn(entry->value,
[](const Ref<API::Data>& data) {
return String::fromUTF8(data->span());
},
[](const String& string) {
return string;
});
}
RefPtr data = resourceDataForPath(path, outError, cacheResult, suppressErrors);
if (!data)
return nullString();
if (!data->size())
return emptyString();
auto mimeType = MIMETypeRegistry::mimeTypeForPath(path);
RefPtr decoder = TextResourceDecoder::create(mimeType, PAL::UTF8Encoding());
auto result = decoder->decode(data->span());
if (cacheResult == CacheResult::Yes)
m_resources.set(path, result);
return result;
}
static int toAPI(WebExtension::Error error)
{
switch (error) {
case WebExtension::Error::Unknown:
return static_cast<int>(WebExtension::APIError::Unknown);
case WebExtension::Error::ResourceNotFound:
return static_cast<int>(WebExtension::APIError::ResourceNotFound);
case WebExtension::Error::InvalidManifest:
return static_cast<int>(WebExtension::APIError::InvalidManifest);
case WebExtension::Error::UnsupportedManifestVersion:
return static_cast<int>(WebExtension::APIError::UnsupportedManifestVersion);
case WebExtension::Error::InvalidDeclarativeNetRequest:
return static_cast<int>(WebExtension::APIError::InvalidDeclarativeNetRequestEntry);
case WebExtension::Error::InvalidBackgroundPersistence:
return static_cast<int>(WebExtension::APIError::InvalidBackgroundPersistence);
case WebExtension::Error::InvalidResourceCodeSignature:
return static_cast<int>(WebExtension::APIError::InvalidResourceCodeSignature);
case WebExtension::Error::InvalidArchive:
return static_cast<int>(WebExtension::APIError::InvalidArchive);
case WebExtension::Error::InvalidAction:
case WebExtension::Error::InvalidActionIcon:
case WebExtension::Error::InvalidBackgroundContent:
case WebExtension::Error::InvalidCommands:
case WebExtension::Error::InvalidContentScripts:
case WebExtension::Error::InvalidContentSecurityPolicy:
case WebExtension::Error::InvalidDefaultLocale:
case WebExtension::Error::InvalidDescription:
case WebExtension::Error::InvalidExternallyConnectable:
case WebExtension::Error::InvalidIcon:
case WebExtension::Error::InvalidName:
case WebExtension::Error::InvalidOptionsPage:
case WebExtension::Error::InvalidURLOverrides:
case WebExtension::Error::InvalidVersion:
case WebExtension::Error::InvalidWebAccessibleResources:
return static_cast<int>(WebExtension::APIError::InvalidManifestEntry);
}
ASSERT_NOT_REACHED();
return static_cast<int>(WebExtension::APIError::Unknown);
}
Ref<API::Error> WebExtension::createError(Error error, const String& customLocalizedDescription, RefPtr<API::Error> underlyingError)
{
auto errorCode = toAPI(error);
String localizedDescription;
switch (error) {
case Error::Unknown:
localizedDescription = WEB_UI_STRING("An unknown error has occurred.", "WKWebExtensionErrorUnknown description");
break;
case Error::ResourceNotFound:
ASSERT(customLocalizedDescription);
break;
case Error::InvalidManifest:
if (underlyingError && !underlyingError->localizedDescription().isEmpty())
localizedDescription = WEB_UI_FORMAT_STRING("Unable to parse manifest: %s", "WKWebExtensionErrorInvalidManifest description, because of a JSON error", underlyingError->localizedDescription().utf8().data());
else
localizedDescription = WEB_UI_STRING("Unable to parse manifest because of an unexpected format.", "WKWebExtensionErrorInvalidManifest description");
break;
case Error::UnsupportedManifestVersion:
localizedDescription = WEB_UI_STRING("An unsupported `manifest_version` was specified.", "WKWebExtensionErrorUnsupportedManifestVersion description");
break;
case Error::InvalidAction:
if (supportsManifestVersion(3))
localizedDescription = WEB_UI_STRING("Missing or empty `action` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for action only");
else
localizedDescription = WEB_UI_STRING("Missing or empty `browser_action` or `page_action` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for browser_action or page_action");
break;
case Error::InvalidActionIcon: {
#if ENABLE(WK_WEB_EXTENSIONS_ICON_VARIANTS)
if (RefPtr actionObject = m_actionObject) {
if (actionObject->getValue(iconVariantsManifestKey)) {
if (supportsManifestVersion(3))
localizedDescription = WEB_UI_STRING("Empty or invalid `icon_variants` for the `action` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for icon_variants in action only");
else
localizedDescription = WEB_UI_STRING("Empty or invalid `icon_variants` for the `browser_action` or `page_action` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for icon_variants in browser_action or page_action");
} else {
if (supportsManifestVersion(3))
localizedDescription = WEB_UI_STRING("Empty or invalid `default_icon` for the `action` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for default_icon in action only");
else
localizedDescription = WEB_UI_STRING("Empty or invalid `default_icon` for the `browser_action` or `page_action` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for default_icon in browser_action or page_action");
}
} else
#endif
if (supportsManifestVersion(3))
localizedDescription = WEB_UI_STRING("Empty or invalid `default_icon` for the `action` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for default_icon in action only");
else
localizedDescription = WEB_UI_STRING("Empty or invalid `default_icon` for the `browser_action` or `page_action` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for default_icon in browser_action or page_action");
break;
}
case Error::InvalidBackgroundContent:
localizedDescription = WEB_UI_STRING("Empty or invalid `background` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for background");
break;
case Error::InvalidCommands:
localizedDescription = WEB_UI_STRING("Invalid `commands` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for commands");
break;
case Error::InvalidContentScripts:
localizedDescription = WEB_UI_STRING("Empty or invalid `content_scripts` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for content_scripts");
break;
case Error::InvalidContentSecurityPolicy:
localizedDescription = WEB_UI_STRING("Empty or invalid `content_security_policy` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for content_security_policy");
break;
case Error::InvalidDeclarativeNetRequest:
if (underlyingError && !underlyingError->localizedDescription().isEmpty())
localizedDescription = WEB_UI_FORMAT_STRING("Unable to parse `declarativeNetRequest` rules: %s", "WKWebExtensionErrorInvalidDeclarativeNetRequest description, because of a JSON error", underlyingError->localizedDescription().utf8().data());
else
localizedDescription = WEB_UI_STRING("Unable to parse `declarativeNetRequest` rules because of an unexpected error.", "WKWebExtensionErrorInvalidDeclarativeNetRequest description");
break;
case Error::InvalidDefaultLocale:
localizedDescription = WEB_UI_STRING("Empty or invalid `default_locale` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for default_locale");
break;
case Error::InvalidDescription:
localizedDescription = WEB_UI_STRING("Missing or empty `description` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for description");
break;
case Error::InvalidExternallyConnectable:
localizedDescription = WEB_UI_STRING("Empty or invalid `externally_connectable` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for externally_connectable");
break;
case Error::InvalidIcon:
#if ENABLE(WK_WEB_EXTENSIONS_ICON_VARIANTS)
if (manifestObject()->getValue(iconVariantsManifestKey))
localizedDescription = WEB_UI_STRING("Empty or invalid `icon_variants` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for icon_variants");
else
#endif
localizedDescription = WEB_UI_STRING("Missing or empty `icons` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for icons");
break;
case Error::InvalidName:
localizedDescription = WEB_UI_STRING("Missing or empty `name` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for name");
break;
case Error::InvalidOptionsPage:
if (manifestObject()->getValue(optionsUIManifestKey))
localizedDescription = WEB_UI_STRING("Empty or invalid `options_ui` manifest entry", "WKWebExtensionErrorInvalidManifestEntry description for options UI");
else
localizedDescription = WEB_UI_STRING("Empty or invalid `options_page` manifest entry", "WKWebExtensionErrorInvalidManifestEntry description for options page");
break;
case Error::InvalidURLOverrides:
if (manifestObject()->getValue(browserURLOverridesManifestKey))
localizedDescription = WEB_UI_STRING("Empty or invalid `browser_url_overrides` manifest entry", "WKWebExtensionErrorInvalidManifestEntry description for browser URL overrides");
else
localizedDescription = WEB_UI_STRING("Empty or invalid `chrome_url_overrides` manifest entry", "WKWebExtensionErrorInvalidManifestEntry description for chrome URL overrides");
break;
case Error::InvalidVersion:
localizedDescription = WEB_UI_STRING("Missing or empty `version` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for version");
break;
case Error::InvalidWebAccessibleResources:
localizedDescription = WEB_UI_STRING("Invalid `web_accessible_resources` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for web_accessible_resources");
break;
case Error::InvalidBackgroundPersistence:
localizedDescription = WEB_UI_STRING("Invalid `persistent` manifest entry.", "WKWebExtensionErrorInvalidBackgroundPersistence description");
break;
case Error::InvalidArchive:
localizedDescription = WEB_UI_STRING("Invalid or corrupt extension archive.", "WKWebExtensionErrorInvalidArchive description");
break;
case Error::InvalidResourceCodeSignature:
ASSERT(customLocalizedDescription);
break;
}
if (!customLocalizedDescription.isEmpty())
localizedDescription = customLocalizedDescription;
return API::Error::create({ "WKWebExtensionErrorDomain"_s, errorCode, { }, localizedDescription });
}
Vector<Ref<API::Error>> WebExtension::errors()
{
populateDisplayStringsIfNeeded();
populateActionPropertiesIfNeeded();
populateBackgroundPropertiesIfNeeded();
populateContentScriptPropertiesIfNeeded();
populatePermissionsPropertiesIfNeeded();
populatePagePropertiesIfNeeded();
populateContentSecurityPolicyStringsIfNeeded();
populateWebAccessibleResourcesIfNeeded();
populateCommandsIfNeeded();
populateDeclarativeNetRequestPropertiesIfNeeded();
populateExternallyConnectableIfNeeded();
return m_errors;
}
const Vector<String>& WebExtension::supportedLocales()
{
if (!m_supportedLocales.isEmpty())
return m_supportedLocales;
auto localesString = "_locales/"_s;
auto localeDirectoryPath = resourceFileURLForPath(localesString).fileSystemPath();
if (!localeDirectoryPath.isEmpty()) {
m_supportedLocales = FileSystem::listDirectory(localeDirectoryPath);
return m_supportedLocales;
}
// For tests that don't have a file system location, check the resource cache.
auto prefixLength = localesString.length();
for (const auto& resourceEntry : m_resources) {
auto path = resourceEntry.key;
if (!path.startsWith(localesString))
continue;
auto localeEnd = path.find('/', prefixLength);
if (localeEnd == notFound)
continue;
auto locale = path.substring(prefixLength, localeEnd - prefixLength);
if (!m_supportedLocales.contains(locale))
m_supportedLocales.append(locale);
}
return m_supportedLocales;
}
const String& WebExtension::defaultLocale()
{
if (!manifestParsedSuccessfully())
return nullString();
return m_defaultLocale;
}
String WebExtension::bestMatchLocale()
{
const auto& supportedLocales = this->supportedLocales();
if (supportedLocales.isEmpty())
return nullString();
if (supportedLocales.size() == 1)
return supportedLocales.first();
auto preferredLocale = defaultLanguage(ShouldMinimizeLanguages::No);
bool exactMatch = false;
auto bestMatchIndex = indexOfBestMatchingLanguageInList(preferredLocale, supportedLocales, exactMatch);
if (bestMatchIndex != notFound)
return supportedLocales[bestMatchIndex];
#if PLATFORM(COCOA)
auto preferredLocaleComponents = parseLocale(preferredLocale);
// On Apple platforms, the best match search uses Foundation, which skips "zh" when the preferred locale is "zh-Hant",
// likely assuming "zh" refers to simplified Chinese. However, web extensions expect the base language to be selected
// if it is supported, regardless of specific variants.
auto matchingLanguageIndex = supportedLocales.findIf([&](const auto& locale) {
return equalIgnoringASCIICase(locale, preferredLocaleComponents.languageCode);
});
if (matchingLanguageIndex != notFound)
return supportedLocales[matchingLanguageIndex];
#endif
return defaultLocale();
}
const String& WebExtension::displayName()
{
populateDisplayStringsIfNeeded();
return m_displayName;
}
const String& WebExtension::displayShortName()
{
populateDisplayStringsIfNeeded();
return m_displayShortName;
}
const String& WebExtension::displayVersion()
{
populateDisplayStringsIfNeeded();
return m_displayVersion;
}
const String& WebExtension::displayDescription()
{
populateDisplayStringsIfNeeded();
return m_displayDescription;
}
const String& WebExtension::version()
{
populateDisplayStringsIfNeeded();
return m_version;
}
void WebExtension::populateDisplayStringsIfNeeded()
{
if (m_parsedManifestDisplayStrings)
return;
m_parsedManifestDisplayStrings = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/name
m_displayName = manifestObject->getString(nameManifestKey);
m_displayShortName = manifestObject->getString(shortNameManifestKey);
if (m_displayShortName.isEmpty())
m_displayShortName = m_displayName;
if (m_displayName.isEmpty())
recordError(createError(Error::InvalidName));
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version
m_version = manifestObject->getString(versionManifestKey);
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version_name
m_displayVersion = manifestObject->getString(versionNameManifestKey);
if (m_displayVersion.isEmpty())
m_displayVersion = m_version;
if (m_version.isEmpty())
recordError(createError(Error::InvalidVersion));
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/description
m_displayDescription = manifestObject->getString(descriptionManifestKey);
if (m_displayDescription.isEmpty())
recordError(createError(Error::InvalidDescription));
}
const String& WebExtension::contentSecurityPolicy()
{
populateContentSecurityPolicyStringsIfNeeded();
return m_contentSecurityPolicy;
}
void WebExtension::populateContentSecurityPolicyStringsIfNeeded()
{
if (m_parsedManifestContentSecurityPolicyStrings)
return;
m_parsedManifestContentSecurityPolicyStrings = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy
if (supportsManifestVersion(3)) {
if (RefPtr policyObject = manifestObject->getObject(contentSecurityPolicyManifestKey)) {
m_contentSecurityPolicy = policyObject->getString(contentSecurityPolicyExtensionPagesManifestKey);
if (!m_contentSecurityPolicy && (!policyObject->size() || policyObject->getValue(contentSecurityPolicyExtensionPagesManifestKey)))
recordError(createError(Error::InvalidContentSecurityPolicy));
}
} else {
m_contentSecurityPolicy = manifestObject->getString(contentSecurityPolicyManifestKey);
if (!m_contentSecurityPolicy && manifestObject->getValue(contentSecurityPolicyManifestKey))
recordError(createError(Error::InvalidContentSecurityPolicy));
}
if (!m_contentSecurityPolicy)
m_contentSecurityPolicy = "script-src 'self'"_s;
}
bool WebExtension::hasBackgroundContent()
{
populateBackgroundPropertiesIfNeeded();
return !m_backgroundScriptPaths.isEmpty() || !m_backgroundPagePath.isEmpty() || !m_backgroundServiceWorkerPath.isEmpty();
}
bool WebExtension::backgroundContentIsPersistent()
{
populateBackgroundPropertiesIfNeeded();
return hasBackgroundContent() && m_backgroundContentIsPersistent;
}
bool WebExtension::backgroundContentUsesModules()
{
populateBackgroundPropertiesIfNeeded();
return hasBackgroundContent() && m_backgroundContentUsesModules;
}
bool WebExtension::backgroundContentIsServiceWorker()
{
populateBackgroundPropertiesIfNeeded();
return m_backgroundContentEnvironment == Environment::ServiceWorker;
}
const String& WebExtension::backgroundContentPath()
{
populateBackgroundPropertiesIfNeeded();
if (!m_backgroundServiceWorkerPath.isEmpty())
return m_backgroundServiceWorkerPath;
if (!m_backgroundScriptPaths.isEmpty()) {
if (backgroundContentIsServiceWorker()) {
static const NeverDestroyed<String> backgroundContentString = generatedBackgroundServiceWorkerFilename;
return backgroundContentString;
}
static const NeverDestroyed<String> backgroundContentString = generatedBackgroundPageFilename;
return backgroundContentString;
}
if (!m_backgroundPagePath.isEmpty())
return m_backgroundPagePath;
ASSERT_NOT_REACHED();
return nullString();
}
const String& WebExtension::generatedBackgroundContent()
{
if (!m_generatedBackgroundContent.isEmpty())
return m_generatedBackgroundContent;
populateBackgroundPropertiesIfNeeded();
if (!m_backgroundServiceWorkerPath.isEmpty() || !m_backgroundPagePath.isEmpty())
return nullString();
if (m_backgroundScriptPaths.isEmpty())
return nullString();
bool isServiceWorker = backgroundContentIsServiceWorker();
bool usesModules = backgroundContentUsesModules();
Vector<String> scripts;
for (auto& scriptPath : m_backgroundScriptPaths) {
StringBuilder format;
if (isServiceWorker) {
if (usesModules) {
format.append("import \"./"_s, scriptPath, "\";"_s);
scripts.append(format.toString());
continue;
}
format.append("importScripts(\""_s, scriptPath, "\");"_s);
scripts.append(format.toString());
continue;
}
format.append("<script"_s);
if (usesModules)
format.append(" type=\"module\""_s);
format.append(" src=\""_s, scriptPath, "\"></script>"_s);
scripts.append(format.toString());
}
StringBuilder generatedBackgroundContent;
if (!isServiceWorker)
generatedBackgroundContent.append("<!DOCTYPE html>\n<body>\n"_s);
for (auto& scriptPath : scripts)
generatedBackgroundContent.append(scriptPath, "\n"_s);
if (!isServiceWorker)
generatedBackgroundContent.append("\n</body>"_s);
m_generatedBackgroundContent = generatedBackgroundContent.toString();
return m_generatedBackgroundContent;
}
void WebExtension::populateBackgroundPropertiesIfNeeded()
{
if (m_parsedManifestBackgroundProperties)
return;
m_parsedManifestBackgroundProperties = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/background
RefPtr backgroundManifestObject = manifestObject->getObject(backgroundManifestKey);
if (!backgroundManifestObject || !backgroundManifestObject->size()) {
if (manifestObject->getValue(backgroundManifestKey))
recordError(createError(Error::InvalidBackgroundContent));
return;
}
m_backgroundPagePath = backgroundManifestObject->getString(backgroundPageManifestKey);
m_backgroundServiceWorkerPath = backgroundManifestObject->getString(backgroundServiceWorkerManifestKey);
m_backgroundContentUsesModules = (backgroundManifestObject->getString(backgroundPageTypeKey) == backgroundPageTypeModuleValue);
if (RefPtr backgroundScriptPaths = backgroundManifestObject->getArray(backgroundScriptsManifestKey)) {
backgroundScriptPaths = filterObjects(*backgroundScriptPaths, [](auto& value) {
return !value.asString().isEmpty();
});
m_backgroundScriptPaths = makeStringVector(*backgroundScriptPaths);
}
Vector<String> supportedEnvironments = { backgroundDocumentManifestKey, backgroundServiceWorkerManifestKey };
Vector<String> preferredEnvironments;
if (auto environment = backgroundManifestObject->getString(backgroundPreferredEnvironmentManifestKey); !environment.isEmpty()) {
if (supportedEnvironments.contains(environment))
preferredEnvironments.append(environment);
} else if (RefPtr environments = backgroundManifestObject->getArray(backgroundPreferredEnvironmentManifestKey); environments && environments->length()) {
Ref filteredEnvironments = filterObjects(*environments, [supportedEnvironments](auto& value) {
return supportedEnvironments.contains(value.asString());
});
for (Ref environment : filteredEnvironments.get())
preferredEnvironments.append(environment->asString());
} else if (backgroundManifestObject->getValue(backgroundPreferredEnvironmentManifestKey))
recordError(createError(Error::InvalidBackgroundContent, WEB_UI_STRING("Manifest `background` entry has an empty or invalid `preferred_environment` key.", "WKWebExtensionErrorInvalidBackgroundContent description for empty or invalid preferred environment key")));
for (auto& environment : preferredEnvironments) {
if (environment == backgroundDocumentManifestKey) {
m_backgroundContentEnvironment = Environment::Document;
m_backgroundServiceWorkerPath = nullString();
if (!m_backgroundPagePath.isEmpty()) {
// Page takes precedence over scripts and service worker.
m_backgroundScriptPaths = { };
break;
}
if (!m_backgroundScriptPaths.isEmpty()) {
// Scripts takes precedence over service worker.
break;
}
recordError(createError(Error::InvalidBackgroundContent, WEB_UI_STRING("Manifest `background` entry has missing or empty required `page` or `scripts` key for `preferred_environment` of `document`.", "WKWebExtensionErrorInvalidBackgroundContent description for missing background page or scripts keys")));
break;
}
if (environment == backgroundServiceWorkerManifestKey) {
m_backgroundContentEnvironment = Environment::ServiceWorker;
m_backgroundPagePath = nullString();
if (!m_backgroundServiceWorkerPath.isEmpty()) {
// Page takes precedence over scripts and service worker.
m_backgroundScriptPaths = { };
break;
}
if (!m_backgroundScriptPaths.isEmpty()) {
// Scripts takes precedence over service worker.
break;
}
recordError(createError(Error::InvalidBackgroundContent, WEB_UI_STRING("Manifest `background` entry has missing or empty required `service_worker` or `scripts` key for `preferred_environment` of `service_worker`.", "WKWebExtensionErrorInvalidBackgroundContent description for missing background service_worker or scripts keys")));
break;
}
}
if (!preferredEnvironments.size()) {
// Page takes precedence over service worker.
if (!m_backgroundPagePath.isEmpty())
m_backgroundServiceWorkerPath = nullString();
// Scripts takes precedence over page and service worker.
if (!m_backgroundScriptPaths.isEmpty()) {
m_backgroundServiceWorkerPath = nullString();
m_backgroundPagePath = nullString();
}
m_backgroundContentEnvironment = !m_backgroundServiceWorkerPath.isEmpty() ? Environment::ServiceWorker : Environment::Document;
if (m_backgroundScriptPaths.isEmpty() && m_backgroundPagePath.isEmpty() && m_backgroundServiceWorkerPath.isEmpty())
recordError(createError(Error::InvalidBackgroundContent, WEB_UI_STRING("Manifest `background` entry has missing or empty required `scripts`, `page`, or `service_worker` key.", "WKWebExtensionErrorInvalidBackgroundContent description for missing background required keys")));
}
auto persistentBoolean = backgroundManifestObject->getBoolean(backgroundPersistentManifestKey);
m_backgroundContentIsPersistent = persistentBoolean ? *persistentBoolean : !(supportsManifestVersion(3) || !m_backgroundServiceWorkerPath.isEmpty());
if (m_backgroundContentIsPersistent && supportsManifestVersion(3)) {
recordError(createError(Error::InvalidBackgroundPersistence, WEB_UI_STRING("Invalid `persistent` manifest entry. A `manifest_version` greater-than or equal to `3` must be non-persistent.", "WKWebExtensionErrorInvalidBackgroundPersistence description for manifest v3")));
m_backgroundContentIsPersistent = false;
}
if (m_backgroundContentIsPersistent && !m_backgroundServiceWorkerPath.isEmpty()) {
recordError(createError(Error::InvalidBackgroundPersistence, WEB_UI_STRING("Invalid `persistent` manifest entry. A `service_worker` must be non-persistent.", "WKWebExtensionErrorInvalidBackgroundPersistence description for service worker")));
m_backgroundContentIsPersistent = false;
}
if (!m_backgroundContentIsPersistent && hasRequestedPermission("webRequest"_s))
recordError(createError(Error::InvalidBackgroundPersistence, WEB_UI_STRING("Non-persistent background content cannot listen to `webRequest` events.", "WKWebExtensionErrorInvalidBackgroundPersistence description for webRequest events")));
#if PLATFORM(VISION)
if (m_backgroundContentIsPersistent)
recordError(createError(Error::InvalidBackgroundPersistence, WEB_UI_STRING("Invalid `persistent` manifest entry. A non-persistent background is required on visionOS.", "WKWebExtensionErrorInvalidBackgroundPersistence description for visionOS")));
#elif PLATFORM(IOS)
if (m_backgroundContentIsPersistent)
recordError(createError(Error::InvalidBackgroundPersistence, WEB_UI_STRING("Invalid `persistent` manifest entry. A non-persistent background is required on iOS and iPadOS.", "WKWebExtensionErrorInvalidBackgroundPersistence description for iOS")));
#endif
}
bool WebExtension::hasInspectorBackgroundPage()
{
populateInspectorPropertiesIfNeeded();
return !m_inspectorBackgroundPagePath.isEmpty();
}
const String& WebExtension::inspectorBackgroundPagePath()
{
populateInspectorPropertiesIfNeeded();
return m_inspectorBackgroundPagePath;
}
void WebExtension::populateInspectorPropertiesIfNeeded()
{
if (m_parsedManifestInspectorProperties)
return;
m_parsedManifestInspectorProperties = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/devtools_page
m_inspectorBackgroundPagePath = manifestObject->getString(devtoolsPageManifestKey);
}
bool WebExtension::hasOptionsPage()
{
populatePagePropertiesIfNeeded();
return !m_optionsPagePath.isEmpty();
}
bool WebExtension::hasOverrideNewTabPage()
{
populatePagePropertiesIfNeeded();
return !m_overrideNewTabPagePath.isEmpty();
}
const String& WebExtension::optionsPagePath()
{
populatePagePropertiesIfNeeded();
return m_optionsPagePath;
}
const String& WebExtension::overrideNewTabPagePath()
{
populatePagePropertiesIfNeeded();
return m_overrideNewTabPagePath;
}
void WebExtension::populatePagePropertiesIfNeeded()
{
if (m_parsedManifestPageProperties)
return;
m_parsedManifestPageProperties = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_ui
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/options_page
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/chrome_url_overrides
RefPtr optionsObject = manifestObject->getObject(optionsUIManifestKey);
if (optionsObject) {
m_optionsPagePath = optionsObject->getString(optionsUIPageManifestKey);
if (m_optionsPagePath.isEmpty())
recordError(createError(Error::InvalidOptionsPage));
} else {
m_optionsPagePath = manifestObject->getString(optionsPageManifestKey);
if (m_optionsPagePath.isEmpty() && manifestObject->getValue(optionsPageManifestKey))
recordError(createError(Error::InvalidOptionsPage));
}
RefPtr overridesObject = manifestObject->getObject(browserURLOverridesManifestKey);
if (!overridesObject)
overridesObject = manifestObject->getObject(chromeURLOverridesManifestKey);
if (overridesObject && overridesObject->size()) {
m_overrideNewTabPagePath = overridesObject->getString(newTabManifestKey);
if (m_overrideNewTabPagePath.isEmpty() && overridesObject->getValue(newTabManifestKey))
recordError(createError(Error::InvalidURLOverrides, WEB_UI_STRING("Empty or invalid `newtab` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for invalid new tab entry")));
} else if (overridesObject)
recordError(createError(Error::InvalidURLOverrides));
}
const Vector<WebExtension::InjectedContentData>& WebExtension::staticInjectedContents()
{
populateContentScriptPropertiesIfNeeded();
return m_staticInjectedContents;
}
bool WebExtension::hasStaticInjectedContentForURL(const URL& url)
{
populateContentScriptPropertiesIfNeeded();
for (auto& injectedContent : m_staticInjectedContents) {
// FIXME: <https://webkit.org/b/246492> Add support for exclude globs.
bool isExcluded = false;
for (auto& excludeMatchPattern : injectedContent.excludeMatchPatterns) {
if (excludeMatchPattern->matchesURL(url)) {
isExcluded = true;
break;
}
}
if (isExcluded)
continue;
// FIXME: <https://webkit.org/b/246492> Add support for include globs.
for (auto& includeMatchPattern : injectedContent.includeMatchPatterns) {
if (includeMatchPattern->matchesURL(url))
return true;
}
}
return false;
}
bool WebExtension::hasStaticInjectedContent()
{
populateContentScriptPropertiesIfNeeded();
return !m_staticInjectedContents.isEmpty();
}
Vector<String> WebExtension::InjectedContentData::expandedIncludeMatchPatternStrings() const
{
Vector<String> result;
for (auto& includeMatchPattern : includeMatchPatterns)
result.appendVector(includeMatchPattern->expandedStrings());
return result;
}
Vector<String> WebExtension::InjectedContentData::expandedExcludeMatchPatternStrings() const
{
Vector<String> result;
for (auto& excludeMatchPattern : excludeMatchPatterns)
result.appendVector(excludeMatchPattern->expandedStrings());
return result;
}
void WebExtension::populateContentScriptPropertiesIfNeeded()
{
if (m_parsedManifestContentScriptProperties)
return;
m_parsedManifestContentScriptProperties = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_scripts
RefPtr contentScriptsManifestArray = manifestObject->getArray(contentScriptsManifestKey);
if (!contentScriptsManifestArray || !contentScriptsManifestArray->length()) {
if (manifestObject->getValue(contentScriptsManifestKey))
recordError(createError(Error::InvalidContentScripts));
return;
}
auto addInjectedContentData = [this](auto& injectedContentObject) {
HashSet<Ref<WebExtensionMatchPattern>> includeMatchPatterns;
// Required. Specifies which pages the specified scripts and stylesheets will be injected into.
RefPtr matchesArray = injectedContentObject->getArray(contentScriptsMatchesManifestKey);
if (!matchesArray) {
recordError(createError(Error::InvalidContentScripts));
return;
}
for (Ref matchPatternStringValue : *matchesArray) {
auto matchPatternString = matchPatternStringValue->asString();
if (!matchPatternString)
continue;
if (RefPtr matchPattern = WebExtensionMatchPattern::getOrCreate(matchPatternString)) {
if (matchPattern->isSupported())
includeMatchPatterns.add(matchPattern.releaseNonNull());
}
}
if (includeMatchPatterns.isEmpty()) {
recordError(createError(Error::InvalidContentScripts, WEB_UI_STRING("Manifest `content_scripts` entry has no specified `matches` entry.", "WKWebExtensionErrorInvalidContentScripts description for missing matches entry")));
return;
}
// Optional. The list of JavaScript files to be injected into matching pages. These are injected in the order they appear in this array.
RefPtr scriptPaths = injectedContentObject->getArray(contentScriptsJSManifestKey);
if (!scriptPaths)
scriptPaths = JSON::Array::create();
scriptPaths = filterObjects(*scriptPaths, [](auto& value) {
return !value.asString().isEmpty();
});
// Optional. The list of CSS files to be injected into matching pages. These are injected in the order they appear in this array, before any DOM is constructed or displayed for the page.
RefPtr styleSheetPaths = injectedContentObject->getArray(contentScriptsCSSManifestKey);
if (!styleSheetPaths)
styleSheetPaths = JSON::Array::create();
styleSheetPaths = filterObjects(*styleSheetPaths, [](auto& value) {
return !value.asString().isEmpty();
});
if (!scriptPaths->length() && !styleSheetPaths->length()) {
recordError(createError(Error::InvalidContentScripts, WEB_UI_STRING("Manifest `content_scripts` entry has missing or empty 'js' and 'css' arrays.", "WKWebExtensionErrorInvalidContentScripts description for missing or empty 'js' and 'css' arrays")));
return;
}
// Optional. Whether the script should inject into an about:blank frame where the parent or opener frame matches one of the patterns declared in matches. Defaults to false.
auto matchesAboutBlank = injectedContentObject->getBoolean(contentScriptsMatchesAboutBlankManifestKey).value_or(false);
HashSet<Ref<WebExtensionMatchPattern>> excludeMatchPatterns;
// Optional. Excludes pages that this content script would otherwise be injected into.
RefPtr excludeMatchesArray = injectedContentObject->getArray(contentScriptsExcludeMatchesManifestKey);
if (!excludeMatchesArray)
excludeMatchesArray = JSON::Array::create();
for (Ref matchPatternStringValue : *excludeMatchesArray) {
auto matchPatternString = matchPatternStringValue->asString();
if (matchPatternString.isEmpty())
continue;
if (RefPtr matchPattern = WebExtensionMatchPattern::getOrCreate(matchPatternString)) {
if (matchPattern->isSupported())
excludeMatchPatterns.add(matchPattern.releaseNonNull());
}
}
// Optional. Applied after matches to include only those URLs that also match this glob.
RefPtr includeGlobPatternStrings = injectedContentObject->getArray(contentScriptsIncludeGlobsManifestKey);
if (!includeGlobPatternStrings)
includeGlobPatternStrings = JSON::Array::create();
includeGlobPatternStrings = filterObjects(*includeGlobPatternStrings, [](auto& value) {
return !!value.asString().isEmpty();
});
// Optional. Applied after matches to exclude URLs that match this glob.
RefPtr excludeGlobPatternStrings = injectedContentObject->getArray(contentScriptsExcludeGlobsManifestKey);
if (!excludeGlobPatternStrings)
excludeGlobPatternStrings = JSON::Array::create();
excludeGlobPatternStrings = filterObjects(*excludeGlobPatternStrings, [](auto& value) -> bool {
return !!value.asString().isEmpty();
});
// Optional. The "all_frames" field allows the extension to specify if JavaScript and CSS files should be injected into all frames matching the specified URL requirements or only into the
// topmost frame in a tab. Defaults to false, meaning that only the top frame is matched. If specified true, it will inject into all frames, even if the frame is not the topmost frame in
// the tab. Each frame is checked independently for URL requirements, it will not inject into child frames if the URL requirements are not met.
auto injectsIntoAllFrames = injectedContentObject->getBoolean(contentScriptsAllFramesManifestKey).value_or(false);
auto injectionTime = InjectionTime::DocumentIdle;
auto runsAtString = injectedContentObject->getString(contentScriptsRunAtManifestKey);
if (!runsAtString || runsAtString == contentScriptsDocumentIdleManifestKey)
injectionTime = InjectionTime::DocumentIdle;
else if (runsAtString == contentScriptsDocumentStartManifestKey)
injectionTime = InjectionTime::DocumentStart;
else if (runsAtString == contentScriptsDocumentEndManifestKey)
injectionTime = InjectionTime::DocumentEnd;
else
recordError(createError(Error::InvalidContentScripts, WEB_UI_STRING("Manifest `content_scripts` entry has unknown `run_at` value.", "WKWebExtensionErrorInvalidContentScripts description for unknown 'run_at' value")));
auto contentWorldType = WebExtensionContentWorldType::ContentScript;
auto worldString = injectedContentObject->getString(contentScriptsWorldManifestKey);
if (!worldString || equalIgnoringASCIICase(worldString, contentScriptsIsolatedManifestKey))
contentWorldType = WebExtensionContentWorldType::ContentScript;
else if (equalIgnoringASCIICase(worldString, contentScriptsMainManifestKey))
contentWorldType = WebExtensionContentWorldType::Main;
else
recordError(createError(Error::InvalidContentScripts, WEB_UI_STRING("Manifest `content_scripts` entry has unknown `world` value.", "WKWebExtensionErrorInvalidContentScripts description for unknown 'world' value")));
auto styleLevel = WebCore::UserStyleLevel::Author;
auto cssOriginString = injectedContentObject->getString(contentScriptsCSSOriginManifestKey);
if (!cssOriginString || equalIgnoringASCIICase(cssOriginString, contentScriptsAuthorManifestKey))
styleLevel = WebCore::UserStyleLevel::Author;
else if (equalIgnoringASCIICase(cssOriginString, contentScriptsUserManifestKey))
styleLevel = WebCore::UserStyleLevel::User;
else
recordError(createError(Error::InvalidContentScripts, WEB_UI_STRING("Manifest `content_scripts` entry has unknown `css_origin` value.", "WKWebExtensionErrorInvalidContentScripts description for unknown 'css_origin' value")));
InjectedContentData injectedContentData;
injectedContentData.includeMatchPatterns = WTFMove(includeMatchPatterns);
injectedContentData.excludeMatchPatterns = WTFMove(excludeMatchPatterns);
injectedContentData.injectionTime = injectionTime;
injectedContentData.matchesAboutBlank = matchesAboutBlank;
injectedContentData.injectsIntoAllFrames = injectsIntoAllFrames;
injectedContentData.contentWorldType = contentWorldType;
injectedContentData.styleLevel = styleLevel;
injectedContentData.scriptPaths = makeStringVector(*scriptPaths);
injectedContentData.styleSheetPaths = makeStringVector(*styleSheetPaths);
injectedContentData.includeGlobPatternStrings = makeStringVector(*includeGlobPatternStrings);
injectedContentData.excludeGlobPatternStrings = makeStringVector(*excludeGlobPatternStrings);
m_staticInjectedContents.append(WTFMove(injectedContentData));
};
for (Ref injectedContentValue : *contentScriptsManifestArray) {
if (RefPtr injectedContentObject = injectedContentValue->asObject())
addInjectedContentData(injectedContentObject);
}
}
#if ENABLE(WK_WEB_EXTENSIONS_SIDEBAR)
bool WebExtension::hasSidebarAction()
{
if (RefPtr manifestObject = this->manifestObject())
return manifestObject->getValue(sidebarActionManifestKey);
return false;
}
bool WebExtension::hasSidePanel()
{
return hasRequestedPermission(WebExtensionPermission::sidePanel());
}
bool WebExtension::hasAnySidebar()
{
return hasSidebarAction() || hasSidePanel();
}
RefPtr<WebCore::Icon> WebExtension::sidebarIcon(WebCore::FloatSize idealSize)
{
// FIXME: <https://webkit.org/b/276833> implement this
return nullptr;
}
const String& WebExtension::sidebarDocumentPath()
{
populateSidebarPropertiesIfNeeded();
return m_sidebarDocumentPath;
}
const String& WebExtension::sidebarTitle()
{
populateSidebarPropertiesIfNeeded();
return m_sidebarTitle;
}
void WebExtension::populateSidebarPropertiesIfNeeded()
{
if (m_parsedManifestSidebarProperties)
return;
m_parsedManifestSidebarProperties = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
// sidePanel documentation: https://developer.chrome.com/docs/extensions/reference/manifest#side-panel
// see "Examples" header -> "Side Panel" tab (doesn't mention `default_path` key elsewhere)
// sidebarAction documentation: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/sidebar_action
if (RefPtr sidebarActionObject = manifestObject->getObject(sidebarActionManifestKey)) {
populateSidebarActionProperties(sidebarActionObject);
return;
}
if (RefPtr sidePanelObject = manifestObject->getObject(sidePanelManifestKey))
populateSidePanelProperties(sidePanelObject);
}
void WebExtension::populateSidebarActionProperties(const JSON::Object& sidebarActionObject)
{
// FIXME: <https://webkit.org/b/276833> implement sidebar icon parsing
m_sidebarIconsCache = nullptr;
m_sidebarTitle = sidebarActionObject.getString(sidebarActionTitleManifestKey);
m_sidebarDocumentPath = sidebarActionObject.getString(sidebarActionPathManifestKey);
}
void WebExtension::populateSidePanelProperties(const JSON::Object& sidePanelObject)
{
// Since sidePanel cannot set a default title or icon from the manifest, setting these to null here is intentional.
m_sidebarIconsCache = nullptr;
m_sidebarTitle = nullString();
m_sidebarDocumentPath = sidePanelObject.getString(sidePanelPathManifestKey);
}
#endif // ENABLE(WK_WEB_EXTENSIONS_SIDEBAR)
const WebExtension::PermissionsSet& WebExtension::supportedPermissions()
{
static MainThreadNeverDestroyed<PermissionsSet> permissions = std::initializer_list<String> { WebExtensionPermission::activeTab(), WebExtensionPermission::alarms(), WebExtensionPermission::clipboardWrite(),
WebExtensionPermission::contextMenus(), WebExtensionPermission::cookies(), WebExtensionPermission::declarativeNetRequest(), WebExtensionPermission::declarativeNetRequestFeedback(),
WebExtensionPermission::declarativeNetRequestWithHostAccess(), WebExtensionPermission::menus(), WebExtensionPermission::nativeMessaging(), WebExtensionPermission::notifications(), WebExtensionPermission::scripting(),
WebExtensionPermission::storage(), WebExtensionPermission::tabs(), WebExtensionPermission::unlimitedStorage(), WebExtensionPermission::webNavigation(), WebExtensionPermission::webRequest(),
#if ENABLE(WK_WEB_EXTENSIONS_SIDEBAR)
WebExtensionPermission::sidePanel(),
#endif
};
return permissions;
}
const WebExtension::PermissionsSet& WebExtension::requestedPermissions()
{
populatePermissionsPropertiesIfNeeded();
return m_permissions;
}
const WebExtension::PermissionsSet& WebExtension::optionalPermissions()
{
populatePermissionsPropertiesIfNeeded();
return m_optionalPermissions;
}
const WebExtension::MatchPatternSet& WebExtension::requestedPermissionMatchPatterns()
{
populatePermissionsPropertiesIfNeeded();
return m_permissionMatchPatterns;
}
const WebExtension::MatchPatternSet& WebExtension::optionalPermissionMatchPatterns()
{
populatePermissionsPropertiesIfNeeded();
return m_optionalPermissionMatchPatterns;
}
const WebExtension::MatchPatternSet& WebExtension::externallyConnectableMatchPatterns()
{
populateExternallyConnectableIfNeeded();
return m_externallyConnectableMatchPatterns;
}
WebExtension::MatchPatternSet WebExtension::allRequestedMatchPatterns()
{
populatePermissionsPropertiesIfNeeded();
populateContentScriptPropertiesIfNeeded();
populateExternallyConnectableIfNeeded();
WebExtension::MatchPatternSet result;
for (Ref matchPattern : m_permissionMatchPatterns)
result.add(matchPattern);
for (Ref matchPattern : m_externallyConnectableMatchPatterns)
result.add(matchPattern);
for (auto& injectedContent : m_staticInjectedContents) {
for (Ref matchPattern : injectedContent.includeMatchPatterns)
result.add(matchPattern);
}
return result;
}
void WebExtension::populateExternallyConnectableIfNeeded()
{
if (m_parsedExternallyConnectable)
return;
m_parsedExternallyConnectable = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/externally_connectable
RefPtr externallyConnectableObject = manifestObject->getObject(externallyConnectableManifestKey);
if (!externallyConnectableObject)
return;
if (!externallyConnectableObject->size()) {
recordError(createError(Error::InvalidExternallyConnectable));
return;
}
bool shouldReportError = false;
MatchPatternSet matchPatterns;
if (RefPtr matchPatternStrings = externallyConnectableObject->getArray(externallyConnectableMatchesManifestKey)) {
for (auto matchPatternStringValue : *matchPatternStrings) {
auto matchPatternString = matchPatternStringValue->asString();
if (matchPatternString.isEmpty())
continue;
if (RefPtr matchPattern = WebExtensionMatchPattern::getOrCreate(matchPatternString)) {
if (matchPattern->matchesAllURLs() || !matchPattern->isSupported()) {
shouldReportError = true;
continue;
}
// URL patterns must contain at least a second-level domain. Top level domains and wildcards are not standalone patterns.
if (matchPattern->hostIsPublicSuffix()) {
shouldReportError = true;
continue;
}
matchPatterns.add(matchPattern.releaseNonNull());
}
}
}
m_externallyConnectableMatchPatterns = WTFMove(matchPatterns);
RefPtr extensionIDs = externallyConnectableObject->getArray(externallyConnectableIDsManifestKey);
if (extensionIDs) {
extensionIDs = filterObjects(*extensionIDs, [](auto& value) {
return !value.asString().isEmpty();
});
}
if (shouldReportError || (m_externallyConnectableMatchPatterns.isEmpty() && (!extensionIDs || (extensionIDs && !extensionIDs->length()))))
recordError(createError(Error::InvalidExternallyConnectable));
}
void WebExtension::populatePermissionsPropertiesIfNeeded()
{
if (m_parsedManifestPermissionProperties)
return;
m_parsedManifestPermissionProperties = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
bool findMatchPatternsInPermissions = !supportsManifestVersion(3);
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions
if (RefPtr permissionsManifestArray = manifestObject->getArray(permissionsManifestKey)) {
for (Ref permissionObject : *permissionsManifestArray) {
auto permission = permissionObject->asString();
if (permission.isEmpty())
continue;
if (findMatchPatternsInPermissions) {
if (RefPtr matchPattern = WebExtensionMatchPattern::getOrCreate(permission)) {
if (matchPattern->isSupported())
m_permissionMatchPatterns.add(matchPattern.releaseNonNull());
continue;
}
}
if (supportedPermissions().contains(permission))
m_permissions.add(permission);
}
}
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/host_permissions
if (!findMatchPatternsInPermissions) {
if (RefPtr hostPermissionsManifestArray = manifestObject->getArray(hostPermissionsManifestKey)) {
for (Ref permissionObject : *hostPermissionsManifestArray) {
auto permission = permissionObject->asString();
if (permission.isEmpty())
continue;
if (RefPtr matchPattern = WebExtensionMatchPattern::getOrCreate(permission)) {
if (matchPattern->isSupported())
m_permissionMatchPatterns.add(matchPattern.releaseNonNull());
}
}
}
}
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/optional_permissions
if (RefPtr optionalPermissionsManifestArray = manifestObject->getArray(optionalPermissionsManifestKey)) {
for (Ref permissionObject : *optionalPermissionsManifestArray) {
auto permission = permissionObject->asString();
if (permission.isEmpty())
continue;
if (findMatchPatternsInPermissions) {
if (RefPtr matchPattern = WebExtensionMatchPattern::getOrCreate(permission)) {
if (matchPattern->isSupported() && !m_permissionMatchPatterns.contains(*matchPattern))
m_optionalPermissionMatchPatterns.add(matchPattern.releaseNonNull());
continue;
}
}
if (!m_permissions.contains(permission) && supportedPermissions().contains(permission))
m_optionalPermissions.add(permission);
}
}
// Documentation: https://github.com/w3c/webextensions/issues/119
if (!findMatchPatternsInPermissions) {
if (RefPtr hostPermissionsManifestArray = manifestObject->getArray(optionalHostPermissionsManifestKey)) {
for (Ref permissionObject : *hostPermissionsManifestArray) {
auto permission = permissionObject->asString();
if (permission.isEmpty())
continue;
if (RefPtr matchPattern = WebExtensionMatchPattern::getOrCreate(permission)) {
if (matchPattern->isSupported() && !m_permissionMatchPatterns.contains(*matchPattern))
m_optionalPermissionMatchPatterns.add(matchPattern.releaseNonNull());
}
}
}
}
}
void WebExtension::populateActionPropertiesIfNeeded()
{
if (m_parsedManifestActionProperties)
return;
m_parsedManifestActionProperties = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/action
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_action
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/page_action
RefPtr<JSON::Object> actionObject;
if (supportsManifestVersion(3))
actionObject = manifestObject->getObject(actionManifestKey);
else {
actionObject = manifestObject->getObject(browserActionManifestKey);
if (!actionObject)
actionObject = manifestObject->getObject(pageActionManifestKey);
}
if (!actionObject)
return;
// Look for the "default_icon" as a string, which is useful for SVG icons. Only supported by Firefox currently.
if (auto defaultIconPath = actionObject->getString(defaultIconManifestKey); !defaultIconPath.isEmpty()) {
RefPtr<API::Error> resourceError;
m_defaultActionIcon = iconForPath(defaultIconPath, resourceError);
if (!m_defaultActionIcon) {
recordErrorIfNeeded(resourceError);
String localizedErrorDescription;
if (supportsManifestVersion(3))
localizedErrorDescription = WEB_UI_STRING("Failed to load image for `default_icon` in the `action` manifest entry.", "WKWebExtensionErrorInvalidActionIcon description for failing to load single image for action");
else
localizedErrorDescription = WEB_UI_STRING("Failed to load image for `default_icon` in the `browser_action` or `page_action` manifest entry.", "WKWebExtensionErrorInvalidActionIcon description for failing to load single image for browser_action or page_action");
recordError(createError(Error::InvalidActionIcon, localizedErrorDescription));
}
}
m_displayActionLabel = actionObject->getString(defaultTitleManifestKey);
m_actionPopupPath = actionObject->getString(defaultPopupManifestKey);
m_actionObject = actionObject;
}
const String& WebExtension::displayActionLabel()
{
populateActionPropertiesIfNeeded();
return m_displayActionLabel;
}
const String& WebExtension::actionPopupPath()
{
populateActionPropertiesIfNeeded();
return m_actionPopupPath;
}
bool WebExtension::hasAction()
{
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return false;
return supportsManifestVersion(3) && manifestObject->getValue(actionManifestKey);
}
bool WebExtension::hasBrowserAction()
{
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return false;
return !supportsManifestVersion(3) && manifestObject->getValue(browserActionManifestKey);
}
bool WebExtension::hasPageAction()
{
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return false;
return !supportsManifestVersion(3) && manifestObject->getValue(pageActionManifestKey);
}
RefPtr<WebCore::Icon> WebExtension::icon(WebCore::FloatSize size)
{
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return nullptr;
#if ENABLE(WK_WEB_EXTENSIONS_ICON_VARIANTS)
if (manifestObject->getValue(iconVariantsManifestKey)) {
String localizedErrorDescription = WEB_UI_STRING("Failed to load images in `icon_variants` manifest entry.", "WKWebExtensionErrorInvalidIcon description for failing to load image variants");
return bestIconVariantForManifestKey(*manifestObject, iconVariantsManifestKey, size, m_iconsCache, Error::InvalidIcon, localizedErrorDescription);
}
#endif
String localizedErrorDescription = WEB_UI_STRING("Failed to load images in `icons` manifest entry.", "WKWebExtensionErrorInvalidIcon description for failing to load images");
return bestIconForManifestKey(*manifestObject, iconsManifestKey, size, m_iconsCache, Error::InvalidIcon, localizedErrorDescription);
}
RefPtr<WebCore::Icon> WebExtension::actionIcon(WebCore::FloatSize size)
{
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return nullptr;
populateActionPropertiesIfNeeded();
if (m_defaultActionIcon)
return m_defaultActionIcon;
if (RefPtr actionObject = m_actionObject) {
#if ENABLE(WK_WEB_EXTENSIONS_ICON_VARIANTS)
if (actionObject->getValue(iconVariantsManifestKey)) {
String localizedErrorDescription = WEB_UI_STRING("Failed to load images in `icon_variants` for the `action` manifest entry.", "WKWebExtensionErrorInvalidActionIcon description for failing to load image variants for action");
if (RefPtr result = bestIconVariantForManifestKey(*actionObject, iconVariantsManifestKey, size, m_actionIconsCache, Error::InvalidActionIcon, localizedErrorDescription))
return result;
return icon(size);
}
#endif
String localizedErrorDescription;
if (supportsManifestVersion(3))
localizedErrorDescription = WEB_UI_STRING("Failed to load images in `default_icon` for the `action` manifest entry.", "WKWebExtensionErrorInvalidActionIcon description for failing to load images for action only");
else
localizedErrorDescription = WEB_UI_STRING("Failed to load images in `default_icon` for the `browser_action` or `page_action` manifest entry.", "WKWebExtensionErrorInvalidActionIcon description for failing to load images for browser_action or page_action");
if (RefPtr result = bestIconForManifestKey(*actionObject, defaultIconManifestKey, size, m_actionIconsCache, Error::InvalidActionIcon, localizedErrorDescription))
return result;
}
return icon(size);
}
size_t WebExtension::bestIconSize(const JSON::Object& iconsObject, size_t idealPixelSize)
{
if (!iconsObject.size())
return 0;
#if ENABLE(WK_WEB_EXTENSIONS_ICON_VARIANTS)
// Check if the "any" size exists (typically a vector image), and prefer it.
if (iconsObject.getValue(anyManifestKey)) {
// Return max to ensure it takes precedence over all other sizes.
return std::numeric_limits<size_t>::max();
}
#endif
// Check if the ideal size exists, if so return it.
auto idealSizeString = String::number(idealPixelSize);
if (iconsObject.getValue(idealSizeString))
return idealPixelSize;
Vector<size_t> sizeValues;
for (auto key : iconsObject.keys()) {
// Filter the values to only include numeric strings representing sizes. This will exclude non-numeric string
// values such as "any", "color_schemes", and any other strings that cannot be converted to a positive integer.
auto integerValue = parseInteger<size_t>(key);
if (integerValue && integerValue > 0)
sizeValues.append(*integerValue);
}
if (!sizeValues.size())
return 0;
// Sort the remaining keys and find the next largest size.
std::sort(sizeValues.begin(), sizeValues.end());
size_t bestSize = 0;
for (auto size : sizeValues) {
bestSize = size;
if (bestSize >= idealPixelSize)
break;
}
return bestSize;
}
String WebExtension::pathForBestImage(const JSON::Object& iconsObject, size_t idealPixelSize)
{
auto bestSize = bestIconSize(iconsObject, idealPixelSize);
if (!bestSize)
return nullString();
#if ENABLE(WK_WEB_EXTENSIONS_ICON_VARIANTS)
if (bestSize == std::numeric_limits<size_t>::max())
return iconsObject.getString(anyManifestKey);
#endif
return iconsObject.getString(String::number(bestSize));
}
RefPtr<WebCore::Icon> WebExtension::bestIconForManifestKey(const JSON::Object& object, const String& manifestKey, WebCore::FloatSize idealSize, IconsCache& cacheLocation, Error error, const String& customLocalizedDescription)
{
auto currentScales = availableScreenScales();
if (auto cachedScales = cacheLocation.getOptional("scales"_s)) {
auto scales = std::get_if<Vector<double>>(&*cachedScales);
if (!scales || *scales != currentScales)
cacheLocation.set("scales"_s, IconCacheEntry(currentScales));
} else
cacheLocation.set("scales"_s, IconCacheEntry(currentScales));
auto cacheKey = idealSize.toJSONString();
if (auto cacheResult = cacheLocation.getOptional(cacheKey))
return *std::get_if<RefPtr<WebCore::Icon>>(&*cacheResult);
RefPtr iconObject = object.getObject(manifestKey);
if (!iconObject)
return nullptr;
RefPtr result = bestIcon(iconObject, idealSize, [&](Ref<API::Error> error) {
recordError(error);
});
if (!result) {
if (iconObject->size()) {
// Record an error if the object had values, meaning the likely failure is the images were missing on disk or bad format.
recordError(createError(error, customLocalizedDescription));
} else if (!iconObject->size() || object.getValue(manifestKey)) {
// Record an error if the key had object that was empty, or the key had a value of the wrong type.
recordError(createError(error));
}
return nullptr;
}
cacheLocation.set(cacheKey, IconCacheEntry(result));
return result;
}
#if ENABLE(WK_WEB_EXTENSIONS_ICON_VARIANTS)
static OptionSet<WebExtension::ColorScheme> toColorSchemes(RefPtr<JSON::Value> value)
{
using ColorScheme = WebExtension::ColorScheme;
if (!value) {
// A null or invalid value counts as all color schemes.
return { ColorScheme::Light, ColorScheme::Dark };
}
OptionSet<ColorScheme> result;
RefPtr array = value->asArray();
if (!array)
return { ColorScheme::Light, ColorScheme::Dark };
for (Ref value : *array) {
if (value->asString() == lightManifestKey)
result.add(ColorScheme::Light);
if (value->asString() == darkManifestKey)
result.add(ColorScheme::Dark);
}
return result;
}
RefPtr<JSON::Object> WebExtension::bestIconVariantJSONObject(RefPtr<JSON::Array> variants, size_t idealPixelSize, ColorScheme idealColorScheme)
{
if (!variants || !variants->length())
return nullptr;
if (variants->length() == 1)
return variants->get(0)->asObject();
RefPtr<JSON::Object> bestVariant;
RefPtr<JSON::Object> fallbackVariant;
bool foundIdealFallbackVariant = false;
size_t bestSize = 0;
size_t fallbackSize = 0;
// Pick the first variant matching color scheme and/or size.
for (Ref variant : *variants) {
if (!variant)
continue;
RefPtr variantObject = variant->asObject();
auto colorSchemes = toColorSchemes(variantObject ? variantObject->getValue(colorSchemesManifestKey) : nullptr);
auto currentBestSize = bestIconSize(*variantObject, idealPixelSize);
if (colorSchemes.contains(idealColorScheme)) {
if (currentBestSize >= idealPixelSize) {
// Found the best variant, return it.
return variantObject;
}
if (currentBestSize > bestSize) {
// Found a larger ideal variant.
bestSize = currentBestSize;
bestVariant = variantObject;
}
} else if (!foundIdealFallbackVariant && currentBestSize >= idealPixelSize) {
// Found an ideal fallback variant, based only on size.
fallbackSize = currentBestSize;
fallbackVariant = variantObject;
foundIdealFallbackVariant = true;
} else if (!foundIdealFallbackVariant && currentBestSize > fallbackSize) {
// Found a smaller fallback variant.
fallbackSize = currentBestSize;
fallbackVariant = variantObject;
}
}
return bestVariant ?: fallbackVariant;
}
RefPtr<WebCore::Icon> WebExtension::bestIconVariantForManifestKey(const JSON::Object& object, const String& manifestKey, WebCore::FloatSize idealSize, IconsCache& cacheLocation, Error error, const String& customLocalizedDescription)
{
auto currentScales = availableScreenScales();
if (auto cachedScales = cacheLocation.getOptional("scales"_s)) {
auto scales = std::get_if<Vector<double>>(&*cachedScales);
if (!scales || *scales != currentScales)
cacheLocation.set("scales"_s, IconCacheEntry(currentScales));
} else
cacheLocation.set("scales"_s, IconCacheEntry(currentScales));
auto cacheKey = idealSize.toJSONString();
if (auto cacheResult = cacheLocation.getOptional(cacheKey))
return *std::get_if<RefPtr<WebCore::Icon>>(&*cacheResult);
RefPtr iconArray = object.getArray(manifestKey);
RefPtr result = bestIconVariant(iconArray, idealSize, [&](Ref<API::Error> error) {
recordError(error);
});
if (!result) {
if (iconArray->length()) {
// Record an error if the array had values, meaning the likely failure is the images were missing on disk or bad format.
recordError(createError(error, customLocalizedDescription));
} else if (!iconArray->length() || object.getValue(manifestKey)) {
// Record an error if the key had an array that was empty, or the key had a value of the wrong type.
recordError(createError(error));
}
return nullptr;
}
cacheLocation.set(cacheKey, IconCacheEntry(result));
return result;
}
#endif // ENABLE(WK_WEB_EXTENSIONS_ICON_VARIANTS)
const WebExtension::CommandsVector& WebExtension::commands()
{
populateCommandsIfNeeded();
return m_commands;
}
bool WebExtension::hasCommands()
{
populateCommandsIfNeeded();
return !m_commands.isEmpty();
}
using ModifierFlags = WebExtension::ModifierFlags;
static bool parseCommandShortcut(const String& shortcut, OptionSet<ModifierFlags>& modifierFlags, String& key)
{
modifierFlags = { };
key = emptyString();
// An empty shortcut is allowed.
if (shortcut.isEmpty())
return true;
static NeverDestroyed<HashMap<String, ModifierFlags>> modifierMap = HashMap<String, ModifierFlags> {
{ "Ctrl"_s, ModifierFlags::Command },
{ "Command"_s, ModifierFlags::Command },
{ "Alt"_s, ModifierFlags::Option },
{ "MacCtrl"_s, ModifierFlags::Control },
{ "Shift"_s, ModifierFlags::Shift }
};
static NeverDestroyed<HashMap<String, String>> specialKeyMap = HashMap<String, String> {
{ "Comma"_s, ","_s },
{ "Period"_s, "."_s },
{ "Space"_s, " "_s },
{ "F1"_s, String::fromUTF8("\uF704") },
{ "F2"_s, String::fromUTF8("\uF705") },
{ "F3"_s, String::fromUTF8("\uF706") },
{ "F4"_s, String::fromUTF8("\uF707") },
{ "F5"_s, String::fromUTF8("\uF708") },
{ "F6"_s, String::fromUTF8("\uF709") },
{ "F7"_s, String::fromUTF8("\uF70A") },
{ "F8"_s, String::fromUTF8("\uF70B") },
{ "F9"_s, String::fromUTF8("\uF70C") },
{ "F10"_s, String::fromUTF8("\uF70D") },
{ "F11"_s, String::fromUTF8("\uF70E") },
{ "F12"_s, String::fromUTF8("\uF70F") },
{ "Insert"_s, String::fromUTF8("\uF727") },
{ "Delete"_s, String::fromUTF8("\uF728") },
{ "Home"_s, String::fromUTF8("\uF729") },
{ "End"_s, String::fromUTF8("\uF72B") },
{ "PageUp"_s, String::fromUTF8("\uF72C") },
{ "PageDown"_s, String::fromUTF8("\uF72D") },
{ "Up"_s, String::fromUTF8("\uF700") },
{ "Down"_s, String::fromUTF8("\uF701") },
{ "Left"_s, String::fromUTF8("\uF702") },
{ "Right"_s, String::fromUTF8("\uF703") }
};
auto parts = shortcut.split('+');
// Reject shortcuts with fewer than two or more than three components.
if (parts.size() < 2 || parts.size() > 3)
return false;
key = parts.takeLast();
// Keys should not be present in the modifier map.
if (modifierMap.get().contains(key))
return false;
if (key.length() == 1) {
// Single-character keys must be alphanumeric.
if (!isASCIIAlphanumeric(key[0]))
return false;
key = key.convertToASCIILowercase();
} else {
auto entry = specialKeyMap.get().find(key);
// Non-alphanumeric keys must be in the special key map.
if (entry == specialKeyMap.get().end())
return false;
key = entry->value;
}
for (auto& part : parts) {
// Modifiers must exist in the modifier map.
if (!modifierMap.get().contains(part))
return false;
modifierFlags.add(modifierMap.get().get(part));
}
// At least one valid modifier is required.
if (!modifierFlags)
return false;
return true;
}
void WebExtension::populateCommandsIfNeeded()
{
if (m_parsedManifestCommands)
return;
m_parsedManifestCommands = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/commands
RefPtr commandsObject = manifestObject->getObject(commandsManifestKey);
if (!commandsObject && manifestObject->getValue(commandsManifestKey)) {
recordError(createError(Error::InvalidCommands));
return;
}
bool hasActionCommand = false;
if (commandsObject) {
size_t commandsWithShortcuts = 0;
std::optional<String> error;
for (auto commandIdentifier : commandsObject->keys()) {
if (commandIdentifier.isEmpty()) {
error = WEB_UI_STRING("Empty or invalid identifier in the `commands` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for invalid command identifier");
continue;
}
RefPtr commandObject = commandsObject->getObject(commandIdentifier);
if (!commandObject || !commandObject->size()) {
error = WEB_UI_STRING("Empty or invalid command in the `commands` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for invalid command");
continue;
}
CommandData commandData;
commandData.identifier = commandIdentifier;
commandData.activationKey = emptyString();
commandData.modifierFlags = { };
bool isActionCommand = false;
if (supportsManifestVersion(3) && commandData.identifier == "_execute_action"_s)
isActionCommand = true;
else if (!supportsManifestVersion(3) && (commandData.identifier == "_execute_browser_action"_s || commandData.identifier == "_execute_page_action"_s))
isActionCommand = true;
if (isActionCommand && !hasActionCommand)
hasActionCommand = true;
// Descriptions are required for standard commands, but are optional for action commands.
auto description = commandObject->getString(commandsDescriptionKeyManifestKey);
if (description.isEmpty() && !isActionCommand) {
error = WEB_UI_STRING("Empty or invalid `description` in the `commands` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for invalid command description");
continue;
}
if (isActionCommand && description.isEmpty()) {
description = displayActionLabel();
if (description.isEmpty())
description = displayShortName();
}
commandData.description = description;
if (RefPtr suggestedKeyObject = commandObject->getObject(commandsSuggestedKeyManifestKey)) {
#if PLATFORM(MAC) || PLATFORM(IOS_FAMILY)
const auto macPlatform = "mac"_s;
const auto iosPlatform = "ios"_s;
#elif PLATFORM(GTK) || PLATFORM(WPE)
const auto linuxPlatform = "linux"_s;
#endif
const auto defaultPlatform = "default"_s;
String platformShortcut;
#if PLATFORM(MAC)
platformShortcut = !suggestedKeyObject->getString(macPlatform).isEmpty() ? suggestedKeyObject->getString(macPlatform) : suggestedKeyObject->getString(iosPlatform);
#elif PLATFORM(IOS_FAMILY)
platformShortcut = !suggestedKeyObject->getString(iosPlatform).isEmpty() ? suggestedKeyObject->getString(iosPlatform) : suggestedKeyObject->getString(macPlatform);
#elif PLATFORM(GTK) || PLATFORM(WPE)
platformShortcut = suggestedKeyObject->getString(linuxPlatform);
#endif
if (platformShortcut.isEmpty())
platformShortcut = suggestedKeyObject->getString(defaultPlatform);
if (!parseCommandShortcut(platformShortcut, commandData.modifierFlags, commandData.activationKey)) {
error = WEB_UI_STRING("Invalid `suggested_key` in the `commands` manifest entry.", "WKWebExtensionErrorInvalidManifestEntry description for invalid command shortcut");
continue;
}
if (!commandData.activationKey.isEmpty() && ++commandsWithShortcuts > maximumNumberOfShortcutCommands) {
error = WEB_UI_STRING("Too many shortcuts specified for `commands`, only 4 shortcuts are allowed.", "WKWebExtensionErrorInvalidManifestEntry description for too many command shortcuts");
commandData.activationKey = emptyString();
commandData.modifierFlags = { };
}
}
m_commands.append(WTFMove(commandData));
}
if (error)
recordError(createError(Error::InvalidCommands, error.value()));
}
if (!hasActionCommand) {
String commandIdentifier;
if (hasAction())
commandIdentifier = "_execute_action"_s;
else if (hasBrowserAction())
commandIdentifier = "_execute_browser_action"_s;
else if (hasPageAction())
commandIdentifier = "_execute_page_action"_s;
if (!commandIdentifier.isEmpty())
m_commands.append({ commandIdentifier, displayActionLabel(), emptyString(), { } });
}
}
std::optional<WebExtension::DeclarativeNetRequestRulesetData> WebExtension::parseDeclarativeNetRequestRulesetObject(const JSON::Object& rulesetObject, RefPtr<API::Error>& error)
{
auto rulesetID = rulesetObject.getString(declarativeNetRequestRulesetIDManifestKey);
if (rulesetID.isEmpty()) {
error = createError(Error::InvalidDeclarativeNetRequest, WEB_UI_STRING("Empty or invalid `id` in `declarative_net_request` manifest entry.", "WKWebExtensionErrorInvalidDeclarativeNetRequestEntry description for empty or invalid id in declarative_net_request manifest entry"));
return { };
}
auto jsonPath = rulesetObject.getString(declarativeNetRequestRulePathManifestKey);
if (jsonPath.isEmpty()) {
error = createError(WebExtension::Error::InvalidDeclarativeNetRequest, WEB_UI_STRING("Empty or invalid `path` in `declarative_net_request` manifest entry.", "WKWebExtensionErrorInvalidDeclarativeNetRequestEntry description for empty or invalid path in declarative_net_request manifest entry"));
return { };
}
auto enabledBool = rulesetObject.getBoolean(declarativeNetRequestRuleEnabledManifestKey);
if (!enabledBool) {
error = createError(WebExtension::Error::InvalidDeclarativeNetRequest, WEB_UI_STRING("Missing or invalid `enabled` boolean for the `declarative_net_request` manifest entry.", "WKWebExtensionErrorInvalidDeclarativeNetRequestEntry description for missing enabled boolean"));
return { };
}
DeclarativeNetRequestRulesetData rulesetData = {
rulesetID,
*enabledBool,
jsonPath
};
return std::optional { WTFMove(rulesetData) };
}
void WebExtension::populateDeclarativeNetRequestPropertiesIfNeeded()
{
if (m_parsedManifestDeclarativeNetRequestRulesets)
return;
m_parsedManifestDeclarativeNetRequestRulesets = true;
RefPtr manifestObject = this->manifestObject();
if (!manifestObject)
return;
// Documentation: https://developer.mozilla.org/docs/Mozilla/Add-ons/WebExtensions/manifest.json/declarative_net_request
if (!supportedPermissions().contains(WebExtensionPermission::declarativeNetRequest()) && !supportedPermissions().contains(WebExtensionPermission::declarativeNetRequestWithHostAccess())) {
recordError(createError(Error::InvalidDeclarativeNetRequest, WEB_UI_STRING("Manifest has no `declarativeNetRequest` permission.", "WKWebExtensionErrorInvalidDeclarativeNetRequestEntry description for missing declarativeNetRequest permission")));
return;
}
RefPtr declarativeNetRequestManifestObject = manifestObject->getObject(declarativeNetRequestManifestKey);
if (!declarativeNetRequestManifestObject) {
if (manifestObject->getValue(declarativeNetRequestManifestKey))
recordError(createError(Error::InvalidDeclarativeNetRequest));
return;
}
RefPtr declarativeNetRequestRulesets = declarativeNetRequestManifestObject->getArray(declarativeNetRequestRulesManifestKey);
if (!declarativeNetRequestRulesets) {
if (manifestObject->getValue(declarativeNetRequestManifestKey))
recordError(createError(Error::InvalidDeclarativeNetRequest));
return;
}
if (declarativeNetRequestRulesets->length() > webExtensionDeclarativeNetRequestMaximumNumberOfStaticRulesets)
recordError(createError(Error::InvalidDeclarativeNetRequest, WEB_UI_STRING("Exceeded maximum number of `declarative_net_request` rulesets. Ignoring extra rulesets.", "WKWebExtensionErrorInvalidDeclarativeNetRequestEntry description for too many rulesets")));
size_t rulesetCount = 0, enabledRulesetCount = 0;
bool recordedTooManyRulesetsManifestError = false;
HashSet<String> seenRulesetIDs;
for (Ref value : *declarativeNetRequestRulesets) {
if (rulesetCount >= webExtensionDeclarativeNetRequestMaximumNumberOfStaticRulesets)
continue;
RefPtr object = value->asObject();
if (!object)
continue;
RefPtr<API::Error> error;
auto optionalRuleset = parseDeclarativeNetRequestRulesetObject(*object, error);
if (!optionalRuleset) {
if (error)
recordError(createError(Error::InvalidDeclarativeNetRequest, { }, error));
continue;
}
auto& ruleset = optionalRuleset.value();
if (seenRulesetIDs.contains(ruleset.rulesetID)) {
recordError(createError(Error::InvalidDeclarativeNetRequest, WEB_UI_FORMAT_STRING("`declarative_net_request` ruleset with id \"%s\" is invalid. Ruleset id must be unique.", "WKWebExtensionErrorInvalidDeclarativeNetRequestEntry description for duplicate ruleset id", ruleset.rulesetID.utf8().data())));
continue;
}
if (ruleset.enabled && ++enabledRulesetCount > webExtensionDeclarativeNetRequestMaximumNumberOfEnabledRulesets && !recordedTooManyRulesetsManifestError) {
recordError(createError(Error::InvalidDeclarativeNetRequest, WEB_UI_FORMAT_STRING("Exceeded maximum number of enabled `declarative_net_request` static rulesets. The first %lu will be applied, the remaining will be ignored.", "WKWebExtensionErrorInvalidDeclarativeNetRequestEntry description for too many enabled static rulesets", webExtensionDeclarativeNetRequestMaximumNumberOfEnabledRulesets)));
recordedTooManyRulesetsManifestError = true;
continue;
}
seenRulesetIDs.add(ruleset.rulesetID);
++rulesetCount;
m_declarativeNetRequestRulesets.append(WTFMove(ruleset));
}
}
const WebExtension::DeclarativeNetRequestRulesetVector& WebExtension::declarativeNetRequestRulesets()
{
populateDeclarativeNetRequestPropertiesIfNeeded();
return m_declarativeNetRequestRulesets;
}
std::optional<WebExtension::DeclarativeNetRequestRulesetData> WebExtension::declarativeNetRequestRuleset(const String& identifier)
{
for (auto& ruleset : declarativeNetRequestRulesets()) {
if (ruleset.rulesetID == identifier)
return ruleset;
}
return std::nullopt;
}
} // namespace WebKit
#endif // ENABLE(WK_WEB_EXTENSIONS)
|