From 43a97878ce14b72f0981164f87f2e35e14151312 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 11:22:09 +0200 Subject: Adding upstream version 110.0.1. Signed-off-by: Daniel Baumann --- toolkit/mozapps/extensions/.eslintrc.js | 36 + toolkit/mozapps/extensions/AbuseReporter.jsm | 686 +++ toolkit/mozapps/extensions/AddonContentPolicy.cpp | 484 ++ toolkit/mozapps/extensions/AddonContentPolicy.h | 21 + toolkit/mozapps/extensions/AddonManager.jsm | 5301 ++++++++++++++++++++ .../extensions/AddonManagerStartup-inlines.h | 229 + toolkit/mozapps/extensions/AddonManagerStartup.cpp | 880 ++++ toolkit/mozapps/extensions/AddonManagerStartup.h | 59 + toolkit/mozapps/extensions/AddonManagerWebAPI.cpp | 169 + toolkit/mozapps/extensions/AddonManagerWebAPI.h | 32 + toolkit/mozapps/extensions/Blocklist.jsm | 1468 ++++++ .../mozapps/extensions/LightweightThemeManager.jsm | 36 + toolkit/mozapps/extensions/addonManager.js | 364 ++ toolkit/mozapps/extensions/amContentHandler.jsm | 109 + .../mozapps/extensions/amIAddonManagerStartup.idl | 82 + toolkit/mozapps/extensions/amIWebInstallPrompt.idl | 32 + toolkit/mozapps/extensions/amInstallTrigger.jsm | 281 ++ toolkit/mozapps/extensions/amWebAPI.jsm | 293 ++ toolkit/mozapps/extensions/components.conf | 45 + .../extensions/content/OpenH264-license.txt | 59 + toolkit/mozapps/extensions/content/aboutaddons.css | 891 ++++ .../mozapps/extensions/content/aboutaddons.html | 445 ++ toolkit/mozapps/extensions/content/aboutaddons.js | 4787 ++++++++++++++++++ .../extensions/content/aboutaddonsCommon.js | 277 + .../extensions/content/abuse-report-frame.html | 152 + .../extensions/content/abuse-report-panel.css | 185 + .../extensions/content/abuse-report-panel.js | 891 ++++ .../mozapps/extensions/content/abuse-reports.js | 317 ++ .../content/drag-drop-addon-installer.js | 81 + toolkit/mozapps/extensions/content/rating-star.css | 41 + toolkit/mozapps/extensions/content/shortcuts.css | 138 + toolkit/mozapps/extensions/content/shortcuts.js | 658 +++ .../mozapps/extensions/content/view-controller.js | 253 + toolkit/mozapps/extensions/default-theme/icon.svg | 7 + .../mozapps/extensions/default-theme/manifest.json | 96 + .../mozapps/extensions/default-theme/preview.svg | 46 + .../docs/AMRemoteSettings-JSONSchema.json | 41 + .../extensions/docs/AMRemoteSettings-UISchema.json | 10 + .../extensions/docs/AMRemoteSettings-overview.rst | 162 + .../mozapps/extensions/docs/AMRemoteSettings.rst | 5 + toolkit/mozapps/extensions/docs/AddonManager.rst | 4 + toolkit/mozapps/extensions/docs/SystemAddons.rst | 275 + toolkit/mozapps/extensions/docs/index.rst | 21 + toolkit/mozapps/extensions/extensions.manifest | 9 + toolkit/mozapps/extensions/gen_built_in_addons.py | 99 + .../extensions/internal/AddonRepository.jsm | 1146 +++++ .../mozapps/extensions/internal/AddonSettings.jsm | 147 + .../mozapps/extensions/internal/AddonTestUtils.jsm | 1834 +++++++ .../extensions/internal/AddonUpdateChecker.jsm | 646 +++ .../extensions/internal/GMPProvider.sys.mjs | 905 ++++ .../extensions/internal/ProductAddonChecker.jsm | 586 +++ .../internal/SitePermsAddonProvider.sys.mjs | 662 +++ .../mozapps/extensions/internal/XPIDatabase.jsm | 3770 ++++++++++++++ toolkit/mozapps/extensions/internal/XPIInstall.jsm | 4836 ++++++++++++++++++ .../mozapps/extensions/internal/XPIProvider.jsm | 3340 ++++++++++++ .../extensions/internal/crypto-utils.sys.mjs | 41 + toolkit/mozapps/extensions/internal/moz.build | 28 + .../internal/siteperms-addon-utils.sys.mjs | 72 + toolkit/mozapps/extensions/jar.mn | 26 + toolkit/mozapps/extensions/moz.build | 103 + .../mozapps/extensions/test/browser/.eslintrc.js | 14 + .../extensions/test/browser/addon_prefs.xhtml | 6 + .../addons/browser_dragdrop1/META-INF/manifest.mf | 8 + .../addons/browser_dragdrop1/META-INF/mozilla.rsa | Bin 0 -> 4210 bytes .../addons/browser_dragdrop1/META-INF/mozilla.sf | 5 + .../browser/addons/browser_dragdrop1/manifest.json | 12 + .../addons/browser_dragdrop2/META-INF/manifest.mf | 8 + .../addons/browser_dragdrop2/META-INF/mozilla.rsa | Bin 0 -> 4210 bytes .../addons/browser_dragdrop2/META-INF/mozilla.sf | 5 + .../browser/addons/browser_dragdrop2/manifest.json | 12 + .../browser_dragdrop_incompat/META-INF/manifest.mf | 8 + .../browser_dragdrop_incompat/META-INF/mozilla.rsa | Bin 0 -> 4218 bytes .../browser_dragdrop_incompat/META-INF/mozilla.sf | 5 + .../addons/browser_dragdrop_incompat/manifest.json | 13 + .../addons/browser_installssl/META-INF/manifest.mf | 8 + .../addons/browser_installssl/META-INF/mozilla.rsa | Bin 0 -> 4213 bytes .../addons/browser_installssl/META-INF/mozilla.sf | 5 + .../addons/browser_installssl/manifest.json | 12 + .../browser/addons/browser_theme/manifest.json | 22 + .../addons/options_signed/META-INF/manifest.mf | 12 + .../addons/options_signed/META-INF/mozilla.rsa | Bin 0 -> 4197 bytes .../addons/options_signed/META-INF/mozilla.sf | 4 + .../browser/addons/options_signed/manifest.json | 11 + .../browser/addons/options_signed/options.html | 9 + .../mozapps/extensions/test/browser/browser.ini | 135 + .../test/browser/browser_about_debugging_link.js | 129 + .../test/browser/browser_addon_list_reordering.js | 197 + .../extensions/test/browser/browser_bug572561.js | 96 + .../browser/browser_checkAddonCompatibility.js | 36 + .../browser/browser_colorwaycloset_aboutaddons.js | 771 +++ .../test/browser/browser_disco_taar_telemetry.js | 297 ++ .../extensions/test/browser/browser_dragdrop.js | 270 + .../browser/browser_file_xpi_no_process_switch.js | 122 + .../test/browser/browser_globalwarnings.js | 168 + .../extensions/test/browser/browser_gmpProvider.js | 390 ++ .../test/browser/browser_history_navigation.js | 616 +++ .../test/browser/browser_html_abuse_report.js | 1031 ++++ .../browser/browser_html_abuse_report_dialog.js | 178 + .../browser/browser_html_detail_permissions.js | 731 +++ .../test/browser/browser_html_detail_view.js | 1359 +++++ .../test/browser/browser_html_discover_view.js | 781 +++ .../browser/browser_html_discover_view_clientid.js | 234 + .../browser/browser_html_discover_view_prefs.js | 83 + .../test/browser/browser_html_list_view.js | 1090 ++++ .../browser_html_list_view_recommendations.js | 308 ++ .../test/browser/browser_html_message_bar.js | 185 + .../test/browser/browser_html_options_ui.js | 535 ++ .../test/browser/browser_html_options_ui_in_tab.js | 136 + .../test/browser/browser_html_pending_updates.js | 312 ++ .../test/browser/browser_html_recent_updates.js | 180 + .../test/browser/browser_html_recommendations.js | 165 + .../browser/browser_html_scroll_restoration.js | 222 + .../browser/browser_html_sitepermission_addons.js | 180 + .../test/browser/browser_html_updates.js | 829 +++ .../test/browser/browser_html_warning_messages.js | 291 ++ .../extensions/test/browser/browser_installssl.js | 378 ++ .../test/browser/browser_installtrigger_install.js | 350 ++ .../test/browser/browser_interaction_telemetry.js | 533 ++ .../test/browser/browser_manage_shortcuts.js | 322 ++ .../browser/browser_manage_shortcuts_hidden.js | 198 + .../browser/browser_manage_shortcuts_remove.js | 172 + .../browser/browser_menu_button_accessibility.js | 81 + .../browser/browser_monochromatic_aboutaddons.js | 218 + .../test/browser/browser_page_accessibility.js | 15 + .../browser/browser_page_options_install_addon.js | 128 + .../test/browser/browser_page_options_updates.js | 165 + .../test/browser/browser_permission_prompt.js | 178 + .../extensions/test/browser/browser_reinstall.js | 277 + .../test/browser/browser_search_bar_focus.js | 51 + .../browser/browser_shortcuts_duplicate_check.js | 253 + .../test/browser/browser_sidebar_categories.js | 160 + .../browser/browser_sidebar_hidden_categories.js | 214 + .../browser/browser_sidebar_restore_category.js | 76 + .../test/browser/browser_subframe_install.js | 234 + .../test/browser/browser_task_next_test.js | 17 + .../extensions/test/browser/browser_updateid.js | 87 + .../extensions/test/browser/browser_updatessl.js | 389 ++ .../extensions/test/browser/browser_updatessl.json | 17 + .../test/browser/browser_updatessl.json^headers^ | 1 + .../test/browser/browser_verify_l10n_strings.js | 62 + .../extensions/test/browser/browser_webapi.js | 125 + .../test/browser/browser_webapi_abuse_report.js | 370 ++ .../test/browser/browser_webapi_access.js | 146 + .../test/browser/browser_webapi_addon_listener.js | 124 + .../test/browser/browser_webapi_enable.js | 63 + .../test/browser/browser_webapi_install.js | 600 +++ .../browser/browser_webapi_install_disabled.js | 58 + .../test/browser/browser_webapi_theme.js | 79 + .../test/browser/browser_webapi_uninstall.js | 72 + .../extensions/test/browser/browser_webext_icon.js | 82 + .../test/browser/browser_webext_incognito.js | 631 +++ .../test/browser/discovery/api_response.json | 769 +++ .../test/browser/discovery/api_response_empty.json | 1 + .../test/browser/discovery/small-1x1.png | Bin 0 -> 82 bytes toolkit/mozapps/extensions/test/browser/head.js | 1718 +++++++ .../extensions/test/browser/head_abuse_report.js | 588 +++ .../mozapps/extensions/test/browser/head_disco.js | 125 + toolkit/mozapps/extensions/test/browser/moz.build | 31 + .../extensions/test/browser/plugin_test.html | 7 + .../mozapps/extensions/test/browser/redirect.sjs | 5 + .../mozapps/extensions/test/browser/sandboxed.html | 11 + .../test/browser/sandboxed.html^headers^ | 1 + .../test/browser/webapi_addon_listener.html | 30 + .../test/browser/webapi_checkavailable.html | 13 + .../test/browser/webapi_checkchromeframe.xhtml | 6 + .../test/browser/webapi_checkframed.html | 7 + .../test/browser/webapi_checknavigatedwindow.html | 29 + toolkit/mozapps/extensions/test/create_xpi.py | 21 + .../mozapps/extensions/test/mochitest/chrome.ini | 2 + .../extensions/test/mochitest/file_empty.html | 2 + .../extensions/test/mochitest/mochitest.ini | 6 + .../mochitest/test_blocklist_gfx_initialized.html | 31 + .../extensions/test/mochitest/test_bug887098.html | 70 + .../test/mochitest/test_default_theme.html | 33 + toolkit/mozapps/extensions/test/moz.build | 20 + .../mozapps/extensions/test/xpcshell/.eslintrc.js | 24 + .../test/xpcshell/data/bug455906_block.xml | 18 + .../test/xpcshell/data/bug455906_empty.xml | 7 + .../test/xpcshell/data/bug455906_start.xml | 30 + .../test/xpcshell/data/bug455906_warn.xml | 33 + .../extensions/test/xpcshell/data/corrupt.xpi | 1 + .../extensions/test/xpcshell/data/corruptfile.xpi | Bin 0 -> 633 bytes .../extensions/test/xpcshell/data/empty.xpi | Bin 0 -> 197 bytes .../xpcshell/data/mlbf-blocked1-unblocked2.bin | Bin 0 -> 32 bytes .../test/xpcshell/data/pluginInfoURL_block.xml | 45 + .../test/xpcshell/data/productaddons/bad.txt | 1 + .../test/xpcshell/data/productaddons/bad.xml | 3 + .../test/xpcshell/data/productaddons/bad2.xml | 3 + .../data/productaddons/content_signing_aus_ee.pem | 15 + .../content_signing_aus_ee.pem.certspec | 5 + .../data/productaddons/content_signing_int.pem | 18 + .../productaddons/content_signing_int.pem.certspec | 4 + .../test/xpcshell/data/productaddons/empty.xml | 5 + .../test/xpcshell/data/productaddons/good.xml | 11 + .../test/xpcshell/data/productaddons/missing.xml | 3 + .../test/xpcshell/data/productaddons/unsigned.xpi | Bin 0 -> 452 bytes .../data/signing_checks/langpack_signed.xpi | Bin 0 -> 4452 bytes .../data/signing_checks/langpack_unsigned.xpi | Bin 0 -> 413 bytes .../test/xpcshell/data/signing_checks/long.xpi | Bin 0 -> 4761 bytes .../xpcshell/data/signing_checks/privileged.xpi | Bin 0 -> 4659 bytes .../test/xpcshell/data/signing_checks/signed1.xpi | Bin 0 -> 4702 bytes .../test/xpcshell/data/signing_checks/signed2.xpi | Bin 0 -> 4697 bytes .../test/xpcshell/data/signing_checks/unsigned.xpi | Bin 0 -> 528 bytes .../xpcshell/data/test_AddonRepository_cache.json | 134 + .../xpcshell/data/test_AddonRepository_empty.json | 7 + .../xpcshell/data/test_AddonRepository_fail.json | 1 + .../data/test_AddonRepository_getAddonsByIDs.json | 117 + .../test/xpcshell/data/test_backgroundupdate.json | 46 + .../data/test_blocklist_metadata_filters_1.xml | 21 + .../test/xpcshell/data/test_blocklist_prefs_1.xml | 28 + .../test/xpcshell/data/test_bug393285.xml | 30 + .../data/test_bug449027_app-extensions.json | 336 ++ .../xpcshell/data/test_bug449027_app-plugins.json | 336 ++ .../test/xpcshell/data/test_bug449027_app.xml | 333 ++ .../data/test_bug449027_toolkit-extensions.json | 154 + .../data/test_bug449027_toolkit-plugins.json | 155 + .../test/xpcshell/data/test_bug449027_toolkit.xml | 208 + .../test/xpcshell/data/test_bug468528.xml | 15 + .../test/xpcshell/data/test_bug514327_1.xml | 17 + .../test/xpcshell/data/test_bug514327_2.xml | 10 + .../test/xpcshell/data/test_bug514327_3_empty.xml | 4 + .../xpcshell/data/test_bug514327_3_outdated_1.xml | 13 + .../xpcshell/data/test_bug514327_3_outdated_2.xml | 13 + .../test/xpcshell/data/test_bug655254.json | 17 + .../test/xpcshell/data/test_corrupt.json | 30 + .../xpcshell/data/test_delay_updates_complete.json | 11 + .../data/test_delay_updates_complete_legacy.json | 18 + .../xpcshell/data/test_delay_updates_defer.json | 11 + .../data/test_delay_updates_defer_legacy.json | 18 + .../xpcshell/data/test_delay_updates_ignore.json | 11 + .../data/test_delay_updates_ignore_legacy.json | 18 + .../xpcshell/data/test_delay_updates_staged.json | 32 + .../test/xpcshell/data/test_gfxBlacklist.json | 494 ++ .../xpcshell/data/test_gfxBlacklist_AllOS.json | 837 ++++ .../xpcshell/data/test_gfxBlacklist_OSVersion.json | 28 + .../test/xpcshell/data/test_install_addons.json | 31 + .../test/xpcshell/data/test_install_compat.json | 27 + .../test/xpcshell/data/test_no_update.json | 7 + .../data/test_overrideblocklist/ancient.xml | 8 + .../xpcshell/data/test_overrideblocklist/new.xml | 8 + .../xpcshell/data/test_overrideblocklist/old.xml | 8 + .../test/xpcshell/data/test_pluginBlocklistCtp.xml | 26 + .../xpcshell/data/test_pluginBlocklistCtpUndo.xml | 10 + .../test/xpcshell/data/test_softblocked1.xml | 9 + .../extensions/test/xpcshell/data/test_update.json | 137 + .../test/xpcshell/data/test_update_addons.json | 14 + .../test/xpcshell/data/test_update_compat.json | 28 + .../test/xpcshell/data/test_updatecheck.json | 269 + .../extensions/test/xpcshell/data/unsigned.xpi | Bin 0 -> 463 bytes .../test/xpcshell/data/webext-implicit-id.xpi | Bin 0 -> 4182 bytes .../extensions/test/xpcshell/head_addons.js | 1281 +++++ .../extensions/test/xpcshell/head_cert_handling.js | 33 + .../extensions/test/xpcshell/head_compat.js | 49 + .../extensions/test/xpcshell/head_sideload.js | 81 + .../extensions/test/xpcshell/head_system_addons.js | 473 ++ .../extensions/test/xpcshell/head_unpack.js | 3 + .../extensions/test/xpcshell/rs-blocklist/head.js | 54 + .../rs-blocklist/test_android_blocklist_dump.js | 57 + .../rs-blocklist/test_blocklist_addonBlockURL.js | 56 + .../rs-blocklist/test_blocklist_appversion.js | 293 ++ .../rs-blocklist/test_blocklist_clients.js | 228 + .../xpcshell/rs-blocklist/test_blocklist_gfx.js | 113 + .../test_blocklist_metadata_filters.js | 116 + .../xpcshell/rs-blocklist/test_blocklist_mlbf.js | 268 + .../rs-blocklist/test_blocklist_mlbf_dump.js | 156 + .../rs-blocklist/test_blocklist_mlbf_fetch.js | 232 + .../rs-blocklist/test_blocklist_mlbf_stashes.js | 219 + .../rs-blocklist/test_blocklist_mlbf_telemetry.js | 162 + .../rs-blocklist/test_blocklist_mlbf_update.js | 75 + .../xpcshell/rs-blocklist/test_blocklist_osabi.js | 286 ++ .../xpcshell/rs-blocklist/test_blocklist_prefs.js | 106 + .../rs-blocklist/test_blocklist_regexp_split.js | 228 + .../rs-blocklist/test_blocklist_severities.js | 504 ++ .../test_blocklist_statechange_telemetry.js | 368 ++ .../test_blocklist_targetapp_filter.js | 393 ++ .../rs-blocklist/test_blocklist_telemetry.js | 113 + .../xpcshell/rs-blocklist/test_blocklistchange.js | 1403 ++++++ .../rs-blocklist/test_blocklistchange_v2.js | 13 + .../rs-blocklist/test_gfxBlacklist_Device.js | 74 + .../rs-blocklist/test_gfxBlacklist_DriverNew.js | 68 + .../test_gfxBlacklist_Equal_DriverNew.js | 113 + .../test_gfxBlacklist_Equal_DriverOld.js | 69 + .../rs-blocklist/test_gfxBlacklist_Equal_OK.js | 69 + .../test_gfxBlacklist_GTE_DriverOld.js | 69 + .../rs-blocklist/test_gfxBlacklist_GTE_OK.js | 71 + .../test_gfxBlacklist_No_Comparison.js | 70 + .../xpcshell/rs-blocklist/test_gfxBlacklist_OK.js | 70 + .../xpcshell/rs-blocklist/test_gfxBlacklist_OS.js | 68 + .../test_gfxBlacklist_OSVersion_match.js | 71 + ...fxBlacklist_OSVersion_mismatch_DriverVersion.js | 71 + ...st_gfxBlacklist_OSVersion_mismatch_OSVersion.js | 72 + .../rs-blocklist/test_gfxBlacklist_Vendor.js | 69 + .../rs-blocklist/test_gfxBlacklist_Version.js | 189 + .../rs-blocklist/test_gfxBlacklist_prefs.js | 125 + .../test/xpcshell/rs-blocklist/test_softblocked.js | 61 + .../test/xpcshell/rs-blocklist/xpcshell.ini | 70 + .../extensions/test/xpcshell/test_AbuseReporter.js | 904 ++++ .../test/xpcshell/test_AddonRepository.js | 316 ++ .../test/xpcshell/test_AddonRepository_cache.js | 713 +++ .../xpcshell/test_AddonRepository_cache_locale.js | 217 + .../xpcshell/test_AddonRepository_langpacks.js | 135 + .../test/xpcshell/test_AddonRepository_paging.js | 91 + .../test/xpcshell/test_ProductAddonChecker.js | 292 ++ .../test_ProductAddonChecker_signatures.js | 201 + .../extensions/test/xpcshell/test_XPIStates.js | 133 + .../extensions/test/xpcshell/test_XPIcancel.js | 70 + .../extensions/test/xpcshell/test_addonStartup.js | 97 + .../test_addon_manager_telemetry_events.js | 831 +++ .../test/xpcshell/test_amo_stats_telemetry.js | 102 + .../extensions/test/xpcshell/test_aom_startup.js | 189 + .../extensions/test/xpcshell/test_bad_json.js | 39 + .../extensions/test/xpcshell/test_badschema.js | 237 + .../extensions/test/xpcshell/test_bug587088.js | 195 + .../test/xpcshell/test_builtin_location.js | 149 + .../extensions/test/xpcshell/test_cacheflush.js | 86 + .../extensions/test/xpcshell/test_childprocess.js | 20 + .../test_colorways_builtin_theme_upgrades.js | 582 +++ .../extensions/test/xpcshell/test_cookies.js | 102 + .../extensions/test/xpcshell/test_corrupt.js | 216 + .../test/xpcshell/test_crash_annotation_quoting.js | 25 + .../extensions/test/xpcshell/test_db_path.js | 64 + .../xpcshell/test_delay_update_webextension.js | 556 ++ .../extensions/test/xpcshell/test_dependencies.js | 140 + .../test/xpcshell/test_dictionary_webextension.js | 233 + .../extensions/test/xpcshell/test_distribution.js | 115 + .../test/xpcshell/test_distribution_langpack.js | 112 + .../test/xpcshell/test_embedderDisabled.js | 128 + .../mozapps/extensions/test/xpcshell/test_error.js | 78 + .../test/xpcshell/test_ext_management.js | 225 + .../extensions/test/xpcshell/test_filepointer.js | 327 ++ .../extensions/test/xpcshell/test_general.js | 49 + .../test/xpcshell/test_getInstallSourceFromHost.js | 42 + .../extensions/test/xpcshell/test_gmpProvider.js | 461 ++ .../extensions/test/xpcshell/test_harness.js | 13 + .../extensions/test/xpcshell/test_hidden.js | 251 + .../extensions/test/xpcshell/test_install.js | 1050 ++++ .../test/xpcshell/test_installOrigins.js | 537 ++ .../test/xpcshell/test_install_cancel.js | 92 + .../test/xpcshell/test_install_file_change.js | 176 + .../extensions/test/xpcshell/test_install_icons.js | 62 + .../xpcshell/test_installtrigger_deprecation.js | 374 ++ .../test/xpcshell/test_installtrigger_schemes.js | 75 + .../extensions/test/xpcshell/test_isDebuggable.js | 21 + .../extensions/test/xpcshell/test_isReady.js | 71 + .../xpcshell/test_loadManifest_isPrivileged.js | 220 + .../extensions/test/xpcshell/test_locale.js | 103 + .../test/xpcshell/test_moved_extension_metadata.js | 171 + .../extensions/test/xpcshell/test_no_addons.js | 79 + .../test/xpcshell/test_nodisable_hidden.js | 99 + .../xpcshell/test_onPropertyChanged_appDisabled.js | 55 + .../extensions/test/xpcshell/test_permissions.js | 199 + .../test/xpcshell/test_permissions_prefs.js | 99 + .../test/xpcshell/test_pref_properties.js | 221 + .../test/xpcshell/test_provider_markSafe.js | 43 + .../test/xpcshell/test_provider_shutdown.js | 97 + .../test_provider_unsafe_access_shutdown.js | 65 + .../test_provider_unsafe_access_startup.js | 59 + .../extensions/test/xpcshell/test_proxies.js | 225 + .../test/xpcshell/test_recommendations.js | 399 ++ .../test/xpcshell/test_registerchrome.js | 88 + .../extensions/test/xpcshell/test_registry.js | 166 + .../test/xpcshell/test_reinstall_disabled_addon.js | 213 + .../extensions/test/xpcshell/test_reload.js | 188 + .../extensions/test/xpcshell/test_safemode.js | 90 + .../extensions/test/xpcshell/test_schema_change.js | 160 + .../mozapps/extensions/test/xpcshell/test_seen.js | 283 ++ .../extensions/test/xpcshell/test_shutdown.js | 131 + .../test/xpcshell/test_shutdown_barriers.js | 71 + .../test/xpcshell/test_shutdown_early.js | 62 + .../test/xpcshell/test_sideload_scopes.js | 188 + .../extensions/test/xpcshell/test_sideloads.js | 117 + .../test/xpcshell/test_sideloads_after_rebuild.js | 145 + .../extensions/test/xpcshell/test_signed_inject.js | 429 ++ .../test/xpcshell/test_signed_install.js | 336 ++ .../test/xpcshell/test_signed_langpack.js | 60 + .../extensions/test/xpcshell/test_signed_long.js | 23 + .../test/xpcshell/test_signed_updatepref.js | 130 + .../extensions/test/xpcshell/test_signed_verify.js | 109 + .../test/xpcshell/test_sitePermsAddonProvider.js | 969 ++++ .../extensions/test/xpcshell/test_startup.js | 648 +++ .../test/xpcshell/test_startup_enable.js | 47 + .../test/xpcshell/test_startup_isPrivileged.js | 58 + .../extensions/test/xpcshell/test_startup_scan.js | 125 + .../test/xpcshell/test_strictcompatibility.js | 159 + .../extensions/test/xpcshell/test_syncGUID.js | 115 + .../test/xpcshell/test_system_allowed.js | 54 + .../test/xpcshell/test_system_delay_update.js | 485 ++ .../test/xpcshell/test_system_profile_location.js | 204 + .../test/xpcshell/test_system_repository.js | 68 + .../extensions/test/xpcshell/test_system_reset.js | 533 ++ .../test/xpcshell/test_system_update_blank.js | 117 + .../xpcshell/test_system_update_checkSizeHash.js | 181 + .../test/xpcshell/test_system_update_custom.js | 431 ++ .../test/xpcshell/test_system_update_empty.js | 141 + .../test_system_update_enterprisepolicy.js | 84 + .../test/xpcshell/test_system_update_fail.js | 181 + .../test_system_update_installTelemetryInfo.js | 94 + .../test/xpcshell/test_system_update_newset.js | 165 + .../xpcshell/test_system_update_overlapping.js | 180 + .../xpcshell/test_system_update_uninstall_check.js | 56 + .../test/xpcshell/test_system_update_upgrades.js | 165 + .../test/xpcshell/test_system_upgrades.js | 417 ++ .../test/xpcshell/test_systemaddomstartupprefs.js | 55 + .../extensions/test/xpcshell/test_temporary.js | 765 +++ .../test/xpcshell/test_trash_directory.js | 39 + .../mozapps/extensions/test/xpcshell/test_types.js | 117 + .../extensions/test/xpcshell/test_undouninstall.js | 584 +++ .../extensions/test/xpcshell/test_update.js | 836 +++ .../extensions/test/xpcshell/test_updateCancel.js | 139 + .../test/xpcshell/test_update_addontype.js | 75 + .../test/xpcshell/test_update_compatmode.js | 112 + .../test/xpcshell/test_update_ignorecompat.js | 100 + .../test/xpcshell/test_update_isPrivileged.js | 182 + .../xpcshell/test_update_noSystemAddonUpdate.js | 42 + .../test/xpcshell/test_update_strictcompat.js | 216 + .../extensions/test/xpcshell/test_update_theme.js | 121 + .../test/xpcshell/test_update_webextensions.js | 209 + .../extensions/test/xpcshell/test_updatecheck.js | 167 + .../test/xpcshell/test_updatecheck_errors.js | 52 + .../test/xpcshell/test_updatecheck_json.js | 379 ++ .../extensions/test/xpcshell/test_updateid.js | 82 + .../extensions/test/xpcshell/test_updateversion.js | 101 + .../extensions/test/xpcshell/test_upgrade.js | 208 + .../test/xpcshell/test_upgrade_incompatible.js | 76 + .../extensions/test/xpcshell/test_webextension.js | 672 +++ .../test/xpcshell/test_webextension_events.js | 94 + .../test/xpcshell/test_webextension_icons.js | 212 + .../test/xpcshell/test_webextension_install.js | 694 +++ .../test_webextension_install_syntax_error.js | 42 + .../test/xpcshell/test_webextension_langpack.js | 590 +++ .../test/xpcshell/test_webextension_paths.js | 47 + .../test/xpcshell/test_webextension_theme.js | 365 ++ .../extensions/test/xpcshell/xpcshell-unpack.ini | 13 + .../mozapps/extensions/test/xpcshell/xpcshell.ini | 223 + .../extensions/test/xpinstall/amosigned.xpi | Bin 0 -> 4287 bytes .../extensions/test/xpinstall/authRedirect.sjs | 21 + .../mozapps/extensions/test/xpinstall/browser.ini | 122 + .../test/xpinstall/browser_amosigned_trigger.js | 86 + .../xpinstall/browser_amosigned_trigger_iframe.js | 77 + .../test/xpinstall/browser_amosigned_url.js | 60 + .../extensions/test/xpinstall/browser_auth.js | 68 + .../extensions/test/xpinstall/browser_auth2.js | 73 + .../extensions/test/xpinstall/browser_auth3.js | 72 + .../extensions/test/xpinstall/browser_auth4.js | 71 + .../extensions/test/xpinstall/browser_badargs.js | 49 + .../extensions/test/xpinstall/browser_badargs2.js | 55 + .../extensions/test/xpinstall/browser_badhash.js | 46 + .../test/xpinstall/browser_badhashtype.js | 46 + .../xpinstall/browser_block_fullscreen_prompt.js | 125 + .../extensions/test/xpinstall/browser_bug540558.js | 31 + .../extensions/test/xpinstall/browser_bug611242.js | 31 + .../extensions/test/xpinstall/browser_bug638292.js | 51 + .../extensions/test/xpinstall/browser_bug645699.js | 69 + .../xpinstall/browser_bug645699_postDownload.js | 55 + .../extensions/test/xpinstall/browser_bug672485.js | 63 + .../test/xpinstall/browser_containers.js | 116 + .../extensions/test/xpinstall/browser_cookies.js | 42 + .../extensions/test/xpinstall/browser_cookies2.js | 64 + .../extensions/test/xpinstall/browser_cookies3.js | 68 + .../extensions/test/xpinstall/browser_cookies4.js | 68 + .../extensions/test/xpinstall/browser_corrupt.js | 53 + .../extensions/test/xpinstall/browser_datauri.js | 79 + .../test/xpinstall/browser_doorhanger_installs.js | 1666 ++++++ .../extensions/test/xpinstall/browser_empty.js | 39 + .../extensions/test/xpinstall/browser_enabled.js | 103 + .../extensions/test/xpinstall/browser_hash.js | 47 + .../extensions/test/xpinstall/browser_hash2.js | 47 + .../extensions/test/xpinstall/browser_httphash.js | 55 + .../extensions/test/xpinstall/browser_httphash2.js | 52 + .../extensions/test/xpinstall/browser_httphash3.js | 52 + .../extensions/test/xpinstall/browser_httphash4.js | 49 + .../extensions/test/xpinstall/browser_httphash5.js | 53 + .../extensions/test/xpinstall/browser_httphash6.js | 107 + .../test/xpinstall/browser_installchrome.js | 36 + .../extensions/test/xpinstall/browser_localfile.js | 42 + .../test/xpinstall/browser_localfile2.js | 60 + .../test/xpinstall/browser_localfile3.js | 42 + .../test/xpinstall/browser_localfile4.js | 55 + .../xpinstall/browser_localfile4_postDownload.js | 54 + .../extensions/test/xpinstall/browser_newwindow.js | 89 + .../extensions/test/xpinstall/browser_offline.js | 79 + .../test/xpinstall/browser_privatebrowsing.js | 133 + .../extensions/test/xpinstall/browser_relative.js | 67 + .../xpinstall/browser_required_useractivation.js | 156 + .../test/xpinstall/browser_signed_url.js | 29 + .../test/xpinstall/browser_softwareupdate.js | 36 + .../test/xpinstall/browser_trigger_redirect.js | 45 + .../test/xpinstall/browser_unsigned_trigger.js | 68 + .../xpinstall/browser_unsigned_trigger_iframe.js | 77 + .../xpinstall/browser_unsigned_trigger_xorigin.js | 58 + .../test/xpinstall/browser_unsigned_url.js | 43 + .../extensions/test/xpinstall/bug540558.html | 24 + .../extensions/test/xpinstall/bug638292.html | 17 + .../extensions/test/xpinstall/bug645699.html | 32 + .../extensions/test/xpinstall/cookieRedirect.sjs | 23 + .../mozapps/extensions/test/xpinstall/corrupt.xpi | 1 + .../mozapps/extensions/test/xpinstall/empty.xpi | Bin 0 -> 197 bytes .../mozapps/extensions/test/xpinstall/enabled.html | 25 + .../extensions/test/xpinstall/hashRedirect.sjs | 14 + toolkit/mozapps/extensions/test/xpinstall/head.js | 575 +++ .../extensions/test/xpinstall/incompatible.xpi | Bin 0 -> 428 bytes .../extensions/test/xpinstall/installchrome.html | 23 + .../extensions/test/xpinstall/installtrigger.html | 57 + .../test/xpinstall/installtrigger_frame.html | 30 + .../extensions/test/xpinstall/navigate.html | 25 + .../extensions/test/xpinstall/recommended.xpi | Bin 0 -> 7884 bytes .../mozapps/extensions/test/xpinstall/redirect.sjs | 39 + .../extensions/test/xpinstall/restartless.xpi | Bin 0 -> 4447 bytes .../extensions/test/xpinstall/slowinstall.sjs | 100 + .../test/xpinstall/startsoftwareupdate.html | 21 + .../extensions/test/xpinstall/triggerredirect.html | 37 + .../mozapps/extensions/test/xpinstall/unsigned.xpi | Bin 0 -> 312 bytes .../extensions/test/xpinstall/unsigned_mv3.xpi | Bin 0 -> 316 bytes .../test/xpinstall/webmidi_permission.xpi | Bin 0 -> 7533 bytes 514 files changed, 110376 insertions(+) create mode 100644 toolkit/mozapps/extensions/.eslintrc.js create mode 100644 toolkit/mozapps/extensions/AbuseReporter.jsm create mode 100644 toolkit/mozapps/extensions/AddonContentPolicy.cpp create mode 100644 toolkit/mozapps/extensions/AddonContentPolicy.h create mode 100644 toolkit/mozapps/extensions/AddonManager.jsm create mode 100644 toolkit/mozapps/extensions/AddonManagerStartup-inlines.h create mode 100644 toolkit/mozapps/extensions/AddonManagerStartup.cpp create mode 100644 toolkit/mozapps/extensions/AddonManagerStartup.h create mode 100644 toolkit/mozapps/extensions/AddonManagerWebAPI.cpp create mode 100644 toolkit/mozapps/extensions/AddonManagerWebAPI.h create mode 100644 toolkit/mozapps/extensions/Blocklist.jsm create mode 100644 toolkit/mozapps/extensions/LightweightThemeManager.jsm create mode 100644 toolkit/mozapps/extensions/addonManager.js create mode 100644 toolkit/mozapps/extensions/amContentHandler.jsm create mode 100644 toolkit/mozapps/extensions/amIAddonManagerStartup.idl create mode 100644 toolkit/mozapps/extensions/amIWebInstallPrompt.idl create mode 100644 toolkit/mozapps/extensions/amInstallTrigger.jsm create mode 100644 toolkit/mozapps/extensions/amWebAPI.jsm create mode 100644 toolkit/mozapps/extensions/components.conf create mode 100644 toolkit/mozapps/extensions/content/OpenH264-license.txt create mode 100644 toolkit/mozapps/extensions/content/aboutaddons.css create mode 100644 toolkit/mozapps/extensions/content/aboutaddons.html create mode 100644 toolkit/mozapps/extensions/content/aboutaddons.js create mode 100644 toolkit/mozapps/extensions/content/aboutaddonsCommon.js create mode 100644 toolkit/mozapps/extensions/content/abuse-report-frame.html create mode 100644 toolkit/mozapps/extensions/content/abuse-report-panel.css create mode 100644 toolkit/mozapps/extensions/content/abuse-report-panel.js create mode 100644 toolkit/mozapps/extensions/content/abuse-reports.js create mode 100644 toolkit/mozapps/extensions/content/drag-drop-addon-installer.js create mode 100644 toolkit/mozapps/extensions/content/rating-star.css create mode 100644 toolkit/mozapps/extensions/content/shortcuts.css create mode 100644 toolkit/mozapps/extensions/content/shortcuts.js create mode 100644 toolkit/mozapps/extensions/content/view-controller.js create mode 100644 toolkit/mozapps/extensions/default-theme/icon.svg create mode 100644 toolkit/mozapps/extensions/default-theme/manifest.json create mode 100644 toolkit/mozapps/extensions/default-theme/preview.svg create mode 100644 toolkit/mozapps/extensions/docs/AMRemoteSettings-JSONSchema.json create mode 100644 toolkit/mozapps/extensions/docs/AMRemoteSettings-UISchema.json create mode 100644 toolkit/mozapps/extensions/docs/AMRemoteSettings-overview.rst create mode 100644 toolkit/mozapps/extensions/docs/AMRemoteSettings.rst create mode 100644 toolkit/mozapps/extensions/docs/AddonManager.rst create mode 100644 toolkit/mozapps/extensions/docs/SystemAddons.rst create mode 100644 toolkit/mozapps/extensions/docs/index.rst create mode 100644 toolkit/mozapps/extensions/extensions.manifest create mode 100644 toolkit/mozapps/extensions/gen_built_in_addons.py create mode 100644 toolkit/mozapps/extensions/internal/AddonRepository.jsm create mode 100644 toolkit/mozapps/extensions/internal/AddonSettings.jsm create mode 100644 toolkit/mozapps/extensions/internal/AddonTestUtils.jsm create mode 100644 toolkit/mozapps/extensions/internal/AddonUpdateChecker.jsm create mode 100644 toolkit/mozapps/extensions/internal/GMPProvider.sys.mjs create mode 100644 toolkit/mozapps/extensions/internal/ProductAddonChecker.jsm create mode 100644 toolkit/mozapps/extensions/internal/SitePermsAddonProvider.sys.mjs create mode 100644 toolkit/mozapps/extensions/internal/XPIDatabase.jsm create mode 100644 toolkit/mozapps/extensions/internal/XPIInstall.jsm create mode 100644 toolkit/mozapps/extensions/internal/XPIProvider.jsm create mode 100644 toolkit/mozapps/extensions/internal/crypto-utils.sys.mjs create mode 100644 toolkit/mozapps/extensions/internal/moz.build create mode 100644 toolkit/mozapps/extensions/internal/siteperms-addon-utils.sys.mjs create mode 100644 toolkit/mozapps/extensions/jar.mn create mode 100644 toolkit/mozapps/extensions/moz.build create mode 100644 toolkit/mozapps/extensions/test/browser/.eslintrc.js create mode 100644 toolkit/mozapps/extensions/test/browser/addon_prefs.xhtml create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop1/META-INF/manifest.mf create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop1/META-INF/mozilla.rsa create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop1/META-INF/mozilla.sf create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop1/manifest.json create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop2/META-INF/manifest.mf create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop2/META-INF/mozilla.rsa create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop2/META-INF/mozilla.sf create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop2/manifest.json create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop_incompat/META-INF/manifest.mf create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop_incompat/META-INF/mozilla.rsa create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop_incompat/META-INF/mozilla.sf create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_dragdrop_incompat/manifest.json create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_installssl/META-INF/manifest.mf create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_installssl/META-INF/mozilla.rsa create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_installssl/META-INF/mozilla.sf create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_installssl/manifest.json create mode 100644 toolkit/mozapps/extensions/test/browser/addons/browser_theme/manifest.json create mode 100644 toolkit/mozapps/extensions/test/browser/addons/options_signed/META-INF/manifest.mf create mode 100644 toolkit/mozapps/extensions/test/browser/addons/options_signed/META-INF/mozilla.rsa create mode 100644 toolkit/mozapps/extensions/test/browser/addons/options_signed/META-INF/mozilla.sf create mode 100644 toolkit/mozapps/extensions/test/browser/addons/options_signed/manifest.json create mode 100644 toolkit/mozapps/extensions/test/browser/addons/options_signed/options.html create mode 100644 toolkit/mozapps/extensions/test/browser/browser.ini create mode 100644 toolkit/mozapps/extensions/test/browser/browser_about_debugging_link.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_addon_list_reordering.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_bug572561.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_checkAddonCompatibility.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_colorwaycloset_aboutaddons.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_disco_taar_telemetry.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_dragdrop.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_file_xpi_no_process_switch.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_globalwarnings.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_gmpProvider.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_history_navigation.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_abuse_report.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_abuse_report_dialog.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_detail_permissions.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_detail_view.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_discover_view.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_discover_view_clientid.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_discover_view_prefs.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_list_view.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_list_view_recommendations.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_message_bar.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_options_ui.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_options_ui_in_tab.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_pending_updates.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_recent_updates.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_recommendations.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_scroll_restoration.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_sitepermission_addons.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_updates.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_html_warning_messages.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_installssl.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_installtrigger_install.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_interaction_telemetry.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_manage_shortcuts.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_manage_shortcuts_hidden.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_manage_shortcuts_remove.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_menu_button_accessibility.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_monochromatic_aboutaddons.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_page_accessibility.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_page_options_install_addon.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_page_options_updates.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_permission_prompt.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_reinstall.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_search_bar_focus.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_shortcuts_duplicate_check.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_sidebar_categories.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_sidebar_hidden_categories.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_sidebar_restore_category.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_subframe_install.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_task_next_test.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_updateid.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_updatessl.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_updatessl.json create mode 100644 toolkit/mozapps/extensions/test/browser/browser_updatessl.json^headers^ create mode 100644 toolkit/mozapps/extensions/test/browser/browser_verify_l10n_strings.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_webapi.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_webapi_abuse_report.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_webapi_access.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_webapi_addon_listener.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_webapi_enable.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_webapi_install.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_webapi_install_disabled.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_webapi_theme.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_webapi_uninstall.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_webext_icon.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_webext_incognito.js create mode 100644 toolkit/mozapps/extensions/test/browser/discovery/api_response.json create mode 100644 toolkit/mozapps/extensions/test/browser/discovery/api_response_empty.json create mode 100644 toolkit/mozapps/extensions/test/browser/discovery/small-1x1.png create mode 100644 toolkit/mozapps/extensions/test/browser/head.js create mode 100644 toolkit/mozapps/extensions/test/browser/head_abuse_report.js create mode 100644 toolkit/mozapps/extensions/test/browser/head_disco.js create mode 100644 toolkit/mozapps/extensions/test/browser/moz.build create mode 100644 toolkit/mozapps/extensions/test/browser/plugin_test.html create mode 100644 toolkit/mozapps/extensions/test/browser/redirect.sjs create mode 100644 toolkit/mozapps/extensions/test/browser/sandboxed.html create mode 100644 toolkit/mozapps/extensions/test/browser/sandboxed.html^headers^ create mode 100644 toolkit/mozapps/extensions/test/browser/webapi_addon_listener.html create mode 100644 toolkit/mozapps/extensions/test/browser/webapi_checkavailable.html create mode 100644 toolkit/mozapps/extensions/test/browser/webapi_checkchromeframe.xhtml create mode 100644 toolkit/mozapps/extensions/test/browser/webapi_checkframed.html create mode 100644 toolkit/mozapps/extensions/test/browser/webapi_checknavigatedwindow.html create mode 100644 toolkit/mozapps/extensions/test/create_xpi.py create mode 100644 toolkit/mozapps/extensions/test/mochitest/chrome.ini create mode 100644 toolkit/mozapps/extensions/test/mochitest/file_empty.html create mode 100644 toolkit/mozapps/extensions/test/mochitest/mochitest.ini create mode 100644 toolkit/mozapps/extensions/test/mochitest/test_blocklist_gfx_initialized.html create mode 100644 toolkit/mozapps/extensions/test/mochitest/test_bug887098.html create mode 100644 toolkit/mozapps/extensions/test/mochitest/test_default_theme.html create mode 100644 toolkit/mozapps/extensions/test/moz.build create mode 100644 toolkit/mozapps/extensions/test/xpcshell/.eslintrc.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/bug455906_block.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/bug455906_empty.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/bug455906_start.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/bug455906_warn.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/corrupt.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/corruptfile.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/empty.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/mlbf-blocked1-unblocked2.bin create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/pluginInfoURL_block.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/productaddons/bad.txt create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/productaddons/bad.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/productaddons/bad2.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/productaddons/content_signing_aus_ee.pem create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/productaddons/content_signing_aus_ee.pem.certspec create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/productaddons/content_signing_int.pem create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/productaddons/content_signing_int.pem.certspec create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/productaddons/empty.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/productaddons/good.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/productaddons/missing.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/productaddons/unsigned.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/signing_checks/langpack_signed.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/signing_checks/langpack_unsigned.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/signing_checks/long.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/signing_checks/privileged.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/signing_checks/signed1.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/signing_checks/signed2.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/signing_checks/unsigned.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_AddonRepository_cache.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_AddonRepository_empty.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_AddonRepository_fail.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_AddonRepository_getAddonsByIDs.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_backgroundupdate.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_blocklist_metadata_filters_1.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_blocklist_prefs_1.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug393285.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug449027_app-extensions.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug449027_app-plugins.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug449027_app.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug449027_toolkit-extensions.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug449027_toolkit-plugins.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug449027_toolkit.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug468528.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug514327_1.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug514327_2.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug514327_3_empty.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug514327_3_outdated_1.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug514327_3_outdated_2.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_bug655254.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_corrupt.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_delay_updates_complete.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_delay_updates_complete_legacy.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_delay_updates_defer.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_delay_updates_defer_legacy.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_delay_updates_ignore.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_delay_updates_ignore_legacy.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_delay_updates_staged.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_gfxBlacklist.json create mode 100755 toolkit/mozapps/extensions/test/xpcshell/data/test_gfxBlacklist_AllOS.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_gfxBlacklist_OSVersion.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_install_addons.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_install_compat.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_no_update.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_overrideblocklist/ancient.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_overrideblocklist/new.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_overrideblocklist/old.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_pluginBlocklistCtp.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_pluginBlocklistCtpUndo.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_softblocked1.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_update.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_update_addons.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_update_compat.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/test_updatecheck.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/unsigned.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/webext-implicit-id.xpi create mode 100644 toolkit/mozapps/extensions/test/xpcshell/head_addons.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/head_cert_handling.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/head_compat.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/head_sideload.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/head_system_addons.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/head_unpack.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/head.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_android_blocklist_dump.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_addonBlockURL.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_appversion.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_clients.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_gfx.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_metadata_filters.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_mlbf.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_mlbf_dump.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_mlbf_fetch.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_mlbf_stashes.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_mlbf_telemetry.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_mlbf_update.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_osabi.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_prefs.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_regexp_split.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_severities.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_statechange_telemetry.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_targetapp_filter.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklist_telemetry.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklistchange.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_blocklistchange_v2.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_Device.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_DriverNew.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_Equal_DriverNew.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_Equal_DriverOld.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_Equal_OK.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_GTE_DriverOld.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_GTE_OK.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_No_Comparison.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_OK.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_OS.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_OSVersion_match.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_OSVersion_mismatch_DriverVersion.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_OSVersion_mismatch_OSVersion.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_Vendor.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_Version.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_gfxBlacklist_prefs.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/test_softblocked.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/rs-blocklist/xpcshell.ini create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_AbuseReporter.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_AddonRepository.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_AddonRepository_cache.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_AddonRepository_cache_locale.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_AddonRepository_langpacks.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_AddonRepository_paging.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_ProductAddonChecker.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_ProductAddonChecker_signatures.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_XPIStates.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_XPIcancel.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_addonStartup.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_addon_manager_telemetry_events.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_amo_stats_telemetry.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_aom_startup.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_bad_json.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_badschema.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_bug587088.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_builtin_location.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_cacheflush.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_childprocess.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_colorways_builtin_theme_upgrades.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_cookies.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_corrupt.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_crash_annotation_quoting.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_db_path.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_delay_update_webextension.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_dependencies.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_dictionary_webextension.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_distribution.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_distribution_langpack.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_embedderDisabled.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_error.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_ext_management.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_filepointer.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_general.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_getInstallSourceFromHost.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_gmpProvider.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_harness.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_hidden.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_install.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_installOrigins.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_install_cancel.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_install_file_change.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_install_icons.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_installtrigger_deprecation.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_installtrigger_schemes.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_isDebuggable.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_isReady.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_loadManifest_isPrivileged.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_locale.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_moved_extension_metadata.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_no_addons.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_nodisable_hidden.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_onPropertyChanged_appDisabled.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_permissions.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_permissions_prefs.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_pref_properties.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_provider_markSafe.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_provider_shutdown.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_provider_unsafe_access_shutdown.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_provider_unsafe_access_startup.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_proxies.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_recommendations.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_registerchrome.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_registry.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_reinstall_disabled_addon.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_reload.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_safemode.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_schema_change.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_seen.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_shutdown.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_shutdown_barriers.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_shutdown_early.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_sideload_scopes.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_sideloads.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_sideloads_after_rebuild.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_signed_inject.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_signed_install.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_signed_langpack.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_signed_long.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_signed_updatepref.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_signed_verify.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_sitePermsAddonProvider.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_startup.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_startup_enable.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_startup_isPrivileged.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_startup_scan.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_strictcompatibility.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_syncGUID.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_allowed.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_delay_update.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_profile_location.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_repository.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_reset.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_update_blank.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_update_checkSizeHash.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_update_custom.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_update_empty.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_update_enterprisepolicy.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_update_fail.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_update_installTelemetryInfo.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_update_newset.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_update_overlapping.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_update_uninstall_check.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_update_upgrades.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_system_upgrades.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_systemaddomstartupprefs.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_temporary.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_trash_directory.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_types.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_undouninstall.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_update.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_updateCancel.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_update_addontype.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_update_compatmode.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_update_ignorecompat.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_update_isPrivileged.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_update_noSystemAddonUpdate.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_update_strictcompat.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_update_theme.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_update_webextensions.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_updatecheck.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_updatecheck_errors.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_updatecheck_json.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_updateid.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_updateversion.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_upgrade.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_upgrade_incompatible.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_webextension.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_webextension_events.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_webextension_icons.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_webextension_install.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_webextension_install_syntax_error.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_webextension_langpack.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_webextension_paths.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_webextension_theme.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/xpcshell-unpack.ini create mode 100644 toolkit/mozapps/extensions/test/xpcshell/xpcshell.ini create mode 100644 toolkit/mozapps/extensions/test/xpinstall/amosigned.xpi create mode 100644 toolkit/mozapps/extensions/test/xpinstall/authRedirect.sjs create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser.ini create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_amosigned_trigger.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_amosigned_trigger_iframe.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_amosigned_url.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_auth.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_auth2.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_auth3.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_auth4.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_badargs.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_badargs2.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_badhash.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_badhashtype.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_block_fullscreen_prompt.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_bug540558.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_bug611242.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_bug638292.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_bug645699.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_bug645699_postDownload.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_bug672485.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_containers.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_cookies.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_cookies2.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_cookies3.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_cookies4.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_corrupt.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_datauri.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_doorhanger_installs.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_empty.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_enabled.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_hash.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_hash2.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_httphash.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_httphash2.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_httphash3.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_httphash4.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_httphash5.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_httphash6.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_installchrome.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_localfile.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_localfile2.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_localfile3.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_localfile4.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_localfile4_postDownload.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_newwindow.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_offline.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_privatebrowsing.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_relative.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_required_useractivation.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_signed_url.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_softwareupdate.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_trigger_redirect.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_unsigned_trigger.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_unsigned_trigger_iframe.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_unsigned_trigger_xorigin.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_unsigned_url.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/bug540558.html create mode 100644 toolkit/mozapps/extensions/test/xpinstall/bug638292.html create mode 100644 toolkit/mozapps/extensions/test/xpinstall/bug645699.html create mode 100644 toolkit/mozapps/extensions/test/xpinstall/cookieRedirect.sjs create mode 100644 toolkit/mozapps/extensions/test/xpinstall/corrupt.xpi create mode 100644 toolkit/mozapps/extensions/test/xpinstall/empty.xpi create mode 100644 toolkit/mozapps/extensions/test/xpinstall/enabled.html create mode 100644 toolkit/mozapps/extensions/test/xpinstall/hashRedirect.sjs create mode 100644 toolkit/mozapps/extensions/test/xpinstall/head.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/incompatible.xpi create mode 100644 toolkit/mozapps/extensions/test/xpinstall/installchrome.html create mode 100644 toolkit/mozapps/extensions/test/xpinstall/installtrigger.html create mode 100644 toolkit/mozapps/extensions/test/xpinstall/installtrigger_frame.html create mode 100644 toolkit/mozapps/extensions/test/xpinstall/navigate.html create mode 100644 toolkit/mozapps/extensions/test/xpinstall/recommended.xpi create mode 100644 toolkit/mozapps/extensions/test/xpinstall/redirect.sjs create mode 100644 toolkit/mozapps/extensions/test/xpinstall/restartless.xpi create mode 100644 toolkit/mozapps/extensions/test/xpinstall/slowinstall.sjs create mode 100644 toolkit/mozapps/extensions/test/xpinstall/startsoftwareupdate.html create mode 100644 toolkit/mozapps/extensions/test/xpinstall/triggerredirect.html create mode 100644 toolkit/mozapps/extensions/test/xpinstall/unsigned.xpi create mode 100644 toolkit/mozapps/extensions/test/xpinstall/unsigned_mv3.xpi create mode 100644 toolkit/mozapps/extensions/test/xpinstall/webmidi_permission.xpi (limited to 'toolkit/mozapps/extensions') diff --git a/toolkit/mozapps/extensions/.eslintrc.js b/toolkit/mozapps/extensions/.eslintrc.js new file mode 100644 index 0000000000..2e1909b8fb --- /dev/null +++ b/toolkit/mozapps/extensions/.eslintrc.js @@ -0,0 +1,36 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +module.exports = { + rules: { + // Warn about cyclomatic complexity in functions. + // XXX Bug 1326071 - This should be reduced down - probably to 20 or to + // be removed & synced with the mozilla/recommended value. + complexity: ["error", { max: 68 }], + + "no-unused-vars": [ + "error", + { + args: "none", + vars: "all", + }, + ], + }, + overrides: [ + { + files: "test/xpcshell/head*.js", + rules: { + "no-unused-vars": [ + "error", + { + args: "none", + vars: "local", + }, + ], + }, + }, + ], +}; diff --git a/toolkit/mozapps/extensions/AbuseReporter.jsm b/toolkit/mozapps/extensions/AbuseReporter.jsm new file mode 100644 index 0000000000..309d654aaf --- /dev/null +++ b/toolkit/mozapps/extensions/AbuseReporter.jsm @@ -0,0 +1,686 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +const EXPORTED_SYMBOLS = ["AbuseReporter", "AbuseReportError"]; + +const { XPCOMUtils } = ChromeUtils.importESModule( + "resource://gre/modules/XPCOMUtils.sys.mjs" +); +const { AppConstants } = ChromeUtils.importESModule( + "resource://gre/modules/AppConstants.sys.mjs" +); + +const PREF_ABUSE_REPORT_URL = "extensions.abuseReport.url"; +const PREF_AMO_DETAILS_API_URL = "extensions.abuseReport.amoDetailsURL"; + +// Name associated with the report dialog window. +const DIALOG_WINDOW_NAME = "addons-abuse-report-dialog"; + +// Maximum length of the string properties sent to the API endpoint. +const MAX_STRING_LENGTH = 255; + +// Minimum time between report submissions (in ms). +const MIN_MS_BETWEEN_SUBMITS = 30000; + +// The addon types currently supported by the integrated abuse report panel. +const SUPPORTED_ADDON_TYPES = [ + "extension", + "theme", + "sitepermission", + // TODO(Bug 1789718): Remove after the deprecated XPIProvider-based implementation is also removed. + "sitepermission-deprecated", +]; + +const lazy = {}; + +ChromeUtils.defineESModuleGetters(lazy, { + ClientID: "resource://gre/modules/ClientID.sys.mjs", +}); + +XPCOMUtils.defineLazyModuleGetters(lazy, { + AddonManager: "resource://gre/modules/AddonManager.jsm", + AMTelemetry: "resource://gre/modules/AddonManager.jsm", +}); + +XPCOMUtils.defineLazyPreferenceGetter( + lazy, + "ABUSE_REPORT_URL", + PREF_ABUSE_REPORT_URL +); + +XPCOMUtils.defineLazyPreferenceGetter( + lazy, + "AMO_DETAILS_API_URL", + PREF_AMO_DETAILS_API_URL +); + +const PRIVATE_REPORT_PROPS = Symbol("privateReportProps"); + +const ERROR_TYPES = Object.freeze([ + "ERROR_ABORTED_SUBMIT", + "ERROR_ADDON_NOTFOUND", + "ERROR_CLIENT", + "ERROR_NETWORK", + "ERROR_UNKNOWN", + "ERROR_RECENT_SUBMIT", + "ERROR_SERVER", + "ERROR_AMODETAILS_NOTFOUND", + "ERROR_AMODETAILS_FAILURE", +]); + +class AbuseReportError extends Error { + constructor(errorType, errorInfo = undefined) { + if (!ERROR_TYPES.includes(errorType)) { + throw new Error(`Unknown AbuseReportError type "${errorType}"`); + } + + let message = errorInfo ? `${errorType} - ${errorInfo}` : errorType; + + super(message); + this.name = "AbuseReportError"; + this.errorType = errorType; + this.errorInfo = errorInfo; + } +} + +/** + * Create an error info string from a fetch response object. + * + * @param {Response} response + * A fetch response object to convert into an errorInfo string. + * + * @returns {Promise} + * The errorInfo string to be included in an AbuseReportError. + */ +async function responseToErrorInfo(response) { + return JSON.stringify({ + status: response.status, + responseText: await response.text().catch(err => ""), + }); +} + +/** + * A singleton object used to create new AbuseReport instances for a given addonId + * and enforce a minium amount of time between two report submissions . + */ +const AbuseReporter = { + _lastReportTimestamp: null, + + // Error types. + updateLastReportTimestamp() { + this._lastReportTimestamp = Date.now(); + }, + + getTimeFromLastReport() { + const currentTimestamp = Date.now(); + if (this._lastReportTimestamp > currentTimestamp) { + // Reset the last report timestamp if it is in the future. + this._lastReportTimestamp = null; + } + + if (!this._lastReportTimestamp) { + return Infinity; + } + + return currentTimestamp - this._lastReportTimestamp; + }, + + isSupportedAddonType(addonType) { + return SUPPORTED_ADDON_TYPES.includes(addonType); + }, + + /** + * Create an AbuseReport instance, given the addonId and a reportEntryPoint. + * + * @param {string} addonId + * The id of the addon to create the report instance for. + * @param {object} options + * @param {string} options.reportEntryPoint + * An identifier that represent the entry point for the report flow. + * + * @returns {Promise} + * Returns a promise that resolves to an instance of the AbuseReport + * class, which represent an ongoing report. + */ + async createAbuseReport(addonId, { reportEntryPoint } = {}) { + let addon = await lazy.AddonManager.getAddonByID(addonId); + + if (!addon) { + // The addon isn't installed, query the details from the AMO API endpoint. + addon = await this.queryAMOAddonDetails(addonId, reportEntryPoint); + } + + if (!addon) { + lazy.AMTelemetry.recordReportEvent({ + addonId, + errorType: "ERROR_ADDON_NOTFOUND", + reportEntryPoint, + }); + throw new AbuseReportError("ERROR_ADDON_NOTFOUND"); + } + + const reportData = await this.getReportData(addon); + + return new AbuseReport({ + addon, + reportData, + reportEntryPoint, + }); + }, + + /** + * Retrieves the addon details from the AMO API endpoint, used to create + * abuse reports on non-installed addon-ons. + * + * For the addon details that may be translated (e.g. addon name, description etc.) + * the function will try to retrieve the string localized in the same locale used + * by Gecko (and fallback to "en-US" if that locale is unavailable). + * + * The addon creator properties are set to the first author available. + * + * @param {string} addonId + * The id of the addon to retrieve the details available on AMO. + * @param {string} reportEntryPoint + * The entry point for the report flow (to be included in the telemetry + * recorded in case of failures). + * + * @returns {Promise} + * Returns a promise that resolves to an AMOAddonDetails object, + * which has the subset of the AddonWrapper properties which are + * needed by the abuse report panel or the report data sent to + * the abuse report API endpoint), or null if it fails to + * retrieve the details from AMO. + * + * @typedef {object} AMOAddonDetails + * @prop {string} id + * @prop {string} name + * @prop {string} version + * @prop {string} description + * @prop {string} type + * @prop {string} iconURL + * @prop {string} homepageURL + * @prop {string} supportURL + * @prop {AMOAddonCreator} creator + * @prop {boolean} isRecommended + * @prop {number} signedState=AddonManager.SIGNEDSTATE_UNKNOWN + * @prop {object} installTelemetryInfo={ source: "not_installed" } + * + * @typedef {object} AMOAddonCreator + * @prop {string} name + * @prop {string} url + */ + async queryAMOAddonDetails(addonId, reportEntryPoint) { + let details; + try { + // This should be the API endpoint documented at: + // https://addons-server.readthedocs.io/en/latest/topics/api/addons.html#detail + details = await fetch(`${lazy.AMO_DETAILS_API_URL}/${addonId}`, { + credentials: "omit", + referrerPolicy: "no-referrer", + headers: { "Content-Type": "application/json" }, + }).then(async response => { + if (response.status === 200) { + return response.json(); + } + + let errorInfo = await responseToErrorInfo(response).catch( + err => undefined + ); + + if (response.status === 404) { + // Record a different telemetry event for 404 errors. + throw new AbuseReportError("ERROR_AMODETAILS_NOTFOUND", errorInfo); + } + + throw new AbuseReportError("ERROR_AMODETAILS_FAILURE", errorInfo); + }); + } catch (err) { + // Log the original error in the browser console. + Cu.reportError(err); + + lazy.AMTelemetry.recordReportEvent({ + addonId, + errorType: err.errorType || "ERROR_AMODETAILS_FAILURE", + reportEntryPoint, + }); + + return null; + } + + const locale = Services.locale.appLocaleAsBCP47; + + // Get a string value from a translated value + // (https://addons-server.readthedocs.io/en/latest/topics/api/overview.html#api-overview-translations) + const getTranslatedValue = value => { + if (typeof value === "string") { + return value; + } + return value && (value[locale] || value["en-US"]); + }; + + const getAuthorField = fieldName => + details.authors && details.authors[0] && details.authors[0][fieldName]; + + // Normalize type "statictheme" (which is the type used on the AMO API side) + // into "theme" (because it is the type we use and expect on the Firefox side + // for this addon type). + const addonType = details.type === "statictheme" ? "theme" : details.type; + + return { + id: addonId, + name: getTranslatedValue(details.name), + version: details.current_version.version, + description: getTranslatedValue(details.summary), + type: addonType, + iconURL: details.icon_url, + homepageURL: getTranslatedValue(details.homepage), + supportURL: getTranslatedValue(details.support_url), + // Set the addon creator to the first author in the AMO details. + creator: { + name: getAuthorField("name"), + url: getAuthorField("url"), + }, + isRecommended: details.is_recommended, + // Set signed state to unknown because it isn't installed. + signedState: lazy.AddonManager.SIGNEDSTATE_UNKNOWN, + // Set the installTelemetryInfo.source to "not_installed". + installTelemetryInfo: { source: "not_installed" }, + }; + }, + + /** + * Helper function that retrieves from an addon object all the data to send + * as part of the submission request, besides the `reason`, `message` which are + * going to be received from the submit method of the report object returned + * by `createAbuseReport`. + * (See https://addons-server.readthedocs.io/en/latest/topics/api/abuse.html) + * + * @param {AddonWrapper} addon + * The addon object to collect the detail from. + * + * @return {object} + * An object that contains the collected details. + */ + async getReportData(addon) { + const truncateString = text => + typeof text == "string" ? text.slice(0, MAX_STRING_LENGTH) : text; + + // Normalize addon_install_source and addon_install_method values + // as expected by the server API endpoint. Returns null if the + // value is not a string. + const normalizeValue = text => + typeof text == "string" + ? text.toLowerCase().replace(/[- :]/g, "_") + : null; + + const installInfo = addon.installTelemetryInfo || {}; + + const data = { + addon: addon.id, + addon_version: addon.version, + addon_name: truncateString(addon.name), + addon_summary: truncateString(addon.description), + addon_install_origin: + addon.sourceURI && truncateString(addon.sourceURI.spec), + install_date: addon.installDate && addon.installDate.toISOString(), + addon_install_source: normalizeValue(installInfo.source), + addon_install_source_url: + installInfo.sourceURL && truncateString(installInfo.sourceURL), + addon_install_method: normalizeValue(installInfo.method), + }; + + switch (addon.signedState) { + case lazy.AddonManager.SIGNEDSTATE_BROKEN: + data.addon_signature = "broken"; + break; + case lazy.AddonManager.SIGNEDSTATE_UNKNOWN: + data.addon_signature = "unknown"; + break; + case lazy.AddonManager.SIGNEDSTATE_MISSING: + data.addon_signature = "missing"; + break; + case lazy.AddonManager.SIGNEDSTATE_PRELIMINARY: + data.addon_signature = "preliminary"; + break; + case lazy.AddonManager.SIGNEDSTATE_SIGNED: + data.addon_signature = "signed"; + break; + case lazy.AddonManager.SIGNEDSTATE_SYSTEM: + data.addon_signature = "system"; + break; + case lazy.AddonManager.SIGNEDSTATE_PRIVILEGED: + data.addon_signature = "privileged"; + break; + default: + data.addon_signature = `unknown: ${addon.signedState}`; + } + + // Set "curated" as addon_signature on recommended addons + // (addon.isRecommended internally checks that the addon is also + // signed correctly). + if (addon.isRecommended) { + data.addon_signature = "curated"; + } + + data.client_id = await lazy.ClientID.getClientIdHash(); + + data.app = Services.appinfo.name.toLowerCase(); + data.appversion = Services.appinfo.version; + data.lang = Services.locale.appLocaleAsBCP47; + data.operating_system = AppConstants.platform; + data.operating_system_version = Services.sysinfo.getProperty("version"); + + return data; + }, + + /** + * Helper function that returns a reference to a report dialog window + * already opened (if any). + * + * @returns {Window?} + */ + getOpenDialog() { + return Services.ww.getWindowByName(DIALOG_WINDOW_NAME, null); + }, + + /** + * Helper function that opens an abuse report form in a new dialog window. + * + * @param {string} addonId + * The addonId being reported. + * @param {string} reportEntryPoint + * The entry point from which the user has triggered the abuse report + * flow. + * @param {XULElement} browser + * The browser element (if any) that is opening the report window. + * + * @return {Promise} + * Returns an AbuseReportDialog object, rejects if it fails to open + * the dialog. + * + * @typedef {object} AbuseReportDialog + * An object that represents the abuse report dialog. + * @prop {function} close + * A method that closes the report dialog (used by the caller + * to close the dialog when the user chooses to close the window + * that started the abuse report flow). + * @prop {Promise} promiseReport + * A promise resolved to an AbuseReport instance if the report should + * be submitted, or undefined if the user has cancelled the report. + * Rejects if it fails to create an AbuseReport instance or to open + * the abuse report window. + */ + async openDialog(addonId, reportEntryPoint, browser) { + const chromeWin = browser && browser.ownerGlobal; + if (!chromeWin) { + throw new Error("Abuse Reporter dialog cancelled, opener tab closed"); + } + + const dialogWin = this.getOpenDialog(); + + if (dialogWin) { + // If an abuse report dialog is already open, cancel the + // previous report flow and start a new one. + const { + deferredReport, + promiseReport, + } = dialogWin.arguments[0].wrappedJSObject; + deferredReport.resolve({ userCancelled: true }); + await promiseReport; + } + + const report = await AbuseReporter.createAbuseReport(addonId, { + reportEntryPoint, + }); + + if (!SUPPORTED_ADDON_TYPES.includes(report.addon.type)) { + throw new Error( + `Addon type "${report.addon.type}" is not currently supported by the integrated abuse reporting feature` + ); + } + + const params = Cc["@mozilla.org/array;1"].createInstance( + Ci.nsIMutableArray + ); + + const dialogInit = { + report, + openWebLink(url) { + chromeWin.openWebLinkIn(url, "tab", { + relatedToCurrent: true, + }); + }, + }; + + params.appendElement(dialogInit); + + let win; + function closeDialog() { + if (win && !win.closed) { + win.close(); + } + } + + const promiseReport = new Promise((resolve, reject) => { + dialogInit.deferredReport = { resolve, reject }; + }).then( + ({ userCancelled }) => { + closeDialog(); + return userCancelled ? undefined : report; + }, + err => { + Cu.reportError( + `Unexpected abuse report panel error: ${err} :: ${err.stack}` + ); + closeDialog(); + return Promise.reject({ + message: "Unexpected abuse report panel error", + }); + } + ); + + const promiseReportPanel = new Promise((resolve, reject) => { + dialogInit.deferredReportPanel = { resolve, reject }; + }); + + dialogInit.promiseReport = promiseReport; + dialogInit.promiseReportPanel = promiseReportPanel; + + win = Services.ww.openWindow( + chromeWin, + "chrome://mozapps/content/extensions/abuse-report-frame.html", + DIALOG_WINDOW_NAME, + // Set the dialog window options (including a reasonable initial + // window height size, eventually adjusted by the panel once it + // has been rendered its content). + "dialog,centerscreen,height=700", + params + ); + + return { + close: closeDialog, + promiseReport, + + // Properties used in tests + promiseReportPanel, + window: win, + }; + }, +}; + +/** + * Represents an ongoing abuse report. Instances of this class are created + * by the `AbuseReporter.createAbuseReport` method. + * + * This object is used by the reporting UI panel and message bars to: + * + * - get an errorType in case of a report creation error (e.g. because of a + * previously submitted report) + * - get the addon details used inside the reporting panel + * - submit the abuse report (and re-submit if a previous submission failed + * and the user choose to retry to submit it again) + * - abort an ongoing submission + * + * @param {object} options + * @param {AddonWrapper|null} options.addon + * AddonWrapper instance for the extension/theme being reported. + * (May be null if the extension has not been found). + * @param {object|null} options.reportData + * An object which contains addon and environment details to send as part of a submission + * (may be null if the report has a createErrorType). + * @param {string} options.reportEntryPoint + * A string that identify how the report has been triggered. + */ +class AbuseReport { + constructor({ addon, createErrorType, reportData, reportEntryPoint }) { + this[PRIVATE_REPORT_PROPS] = { + aborted: false, + abortController: new AbortController(), + addon, + reportData, + reportEntryPoint, + // message and reason are initially null, and then set by the panel + // using the related set method. + message: null, + reason: null, + }; + } + + recordTelemetry(errorType) { + const { addon, reportEntryPoint } = this; + lazy.AMTelemetry.recordReportEvent({ + addonId: addon.id, + addonType: addon.type, + errorType, + reportEntryPoint, + }); + } + + /** + * Submit the current report, given a reason and a message. + * + * @returns {Promise} + * Resolves once the report has been successfully submitted. + * It rejects with an AbuseReportError if the report couldn't be + * submitted for a known reason (or another Error type otherwise). + */ + async submit() { + const { + aborted, + abortController, + message, + reason, + reportData, + reportEntryPoint, + } = this[PRIVATE_REPORT_PROPS]; + + // Record telemetry event and throw an AbuseReportError. + const rejectReportError = async (errorType, { response } = {}) => { + this.recordTelemetry(errorType); + + // Leave errorInfo empty if there is no response or fails to + // be converted into an error info object. + const errorInfo = response + ? await responseToErrorInfo(response).catch(err => undefined) + : undefined; + + throw new AbuseReportError(errorType, errorInfo); + }; + + if (aborted) { + // Report aborted before being actually submitted. + return rejectReportError("ERROR_ABORTED_SUBMIT"); + } + + // Prevent submit of a new abuse report in less than MIN_MS_BETWEEN_SUBMITS. + let msFromLastReport = AbuseReporter.getTimeFromLastReport(); + if (msFromLastReport < MIN_MS_BETWEEN_SUBMITS) { + return rejectReportError("ERROR_RECENT_SUBMIT"); + } + + let response; + try { + response = await fetch(lazy.ABUSE_REPORT_URL, { + signal: abortController.signal, + method: "POST", + credentials: "omit", + referrerPolicy: "no-referrer", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + ...reportData, + report_entry_point: reportEntryPoint, + message, + reason, + }), + }); + } catch (err) { + if (err.name === "AbortError") { + return rejectReportError("ERROR_ABORTED_SUBMIT"); + } + Cu.reportError(err); + return rejectReportError("ERROR_NETWORK"); + } + + if (response.ok && response.status >= 200 && response.status < 400) { + // Ensure that the response is also a valid json format. + try { + await response.json(); + } catch (err) { + this.recordTelemetry("ERROR_UNKNOWN"); + throw err; + } + AbuseReporter.updateLastReportTimestamp(); + this.recordTelemetry(); + return undefined; + } + + if (response.status >= 400 && response.status < 500) { + return rejectReportError("ERROR_CLIENT", { response }); + } + + if (response.status >= 500 && response.status < 600) { + return rejectReportError("ERROR_SERVER", { response }); + } + + // We got an unexpected HTTP status code. + return rejectReportError("ERROR_UNKNOWN", { response }); + } + + /** + * Abort the report submission. + */ + abort() { + const { abortController } = this[PRIVATE_REPORT_PROPS]; + abortController.abort(); + this[PRIVATE_REPORT_PROPS].aborted = true; + } + + get addon() { + return this[PRIVATE_REPORT_PROPS].addon; + } + + get reportEntryPoint() { + return this[PRIVATE_REPORT_PROPS].reportEntryPoint; + } + + /** + * Set the open message (called from the panel when the user submit the report) + * + * @parm {string} message + * An optional string which contains a description for the reported issue. + */ + setMessage(message) { + this[PRIVATE_REPORT_PROPS].message = message; + } + + /** + * Set the report reason (called from the panel when the user submit the report) + * + * @parm {string} reason + * String identifier for the report reason. + */ + setReason(reason) { + this[PRIVATE_REPORT_PROPS].reason = reason; + } +} diff --git a/toolkit/mozapps/extensions/AddonContentPolicy.cpp b/toolkit/mozapps/extensions/AddonContentPolicy.cpp new file mode 100644 index 0000000000..bffe78a7ba --- /dev/null +++ b/toolkit/mozapps/extensions/AddonContentPolicy.cpp @@ -0,0 +1,484 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "AddonContentPolicy.h" + +#include "mozilla/dom/nsCSPContext.h" +#include "nsCOMPtr.h" +#include "nsComponentManagerUtils.h" +#include "nsContentPolicyUtils.h" +#include "nsContentTypeParser.h" +#include "nsContentUtils.h" +#include "nsIConsoleService.h" +#include "nsIContentSecurityPolicy.h" +#include "nsIContent.h" +#include "mozilla/Components.h" +#include "mozilla/dom/Document.h" +#include "mozilla/intl/Localization.h" +#include "nsIEffectiveTLDService.h" +#include "nsIScriptError.h" +#include "nsIStringBundle.h" +#include "nsIUUIDGenerator.h" +#include "nsIURI.h" +#include "nsNetCID.h" +#include "nsNetUtil.h" + +using namespace mozilla; +using namespace mozilla::intl; + +/* Enforces content policies for WebExtension scopes. Currently: + * + * - Prevents loading scripts with a non-default JavaScript version. + * - Checks custom content security policies for sufficiently stringent + * script-src and other script-related directives. + * - We also used to validate object-src similarly to script-src, but that was + * dropped because NPAPI plugins are no longer supported (see bug 1766881). + */ + +#define VERSIONED_JS_BLOCKED_MESSAGE \ + u"Versioned JavaScript is a non-standard, deprecated extension, and is " \ + u"not supported in WebExtension code. For alternatives, please see: " \ + u"https://developer.mozilla.org/Add-ons/WebExtensions/Tips" + +AddonContentPolicy::AddonContentPolicy() = default; + +AddonContentPolicy::~AddonContentPolicy() = default; + +NS_IMPL_ISUPPORTS(AddonContentPolicy, nsIContentPolicy, nsIAddonContentPolicy) + +static nsresult GetWindowIDFromContext(nsISupports* aContext, + uint64_t* aResult) { + NS_ENSURE_TRUE(aContext, NS_ERROR_FAILURE); + + nsCOMPtr content = do_QueryInterface(aContext); + NS_ENSURE_TRUE(content, NS_ERROR_FAILURE); + + nsCOMPtr window = content->OwnerDoc()->GetInnerWindow(); + NS_ENSURE_TRUE(window, NS_ERROR_FAILURE); + + *aResult = window->WindowID(); + return NS_OK; +} + +static nsresult LogMessage(const nsAString& aMessage, + const nsAString& aSourceName, + const nsAString& aSourceSample, + nsISupports* aContext) { + nsCOMPtr error = do_CreateInstance(NS_SCRIPTERROR_CONTRACTID); + NS_ENSURE_TRUE(error, NS_ERROR_OUT_OF_MEMORY); + + uint64_t windowID = 0; + GetWindowIDFromContext(aContext, &windowID); + + nsresult rv = error->InitWithSanitizedSource( + aMessage, aSourceName, aSourceSample, 0, 0, nsIScriptError::errorFlag, + "JavaScript", windowID); + NS_ENSURE_SUCCESS(rv, rv); + + nsCOMPtr console = + do_GetService(NS_CONSOLESERVICE_CONTRACTID); + NS_ENSURE_TRUE(console, NS_ERROR_OUT_OF_MEMORY); + + console->LogMessage(error); + return NS_OK; +} + +// Content policy enforcement: + +NS_IMETHODIMP +AddonContentPolicy::ShouldLoad(nsIURI* aContentLocation, nsILoadInfo* aLoadInfo, + const nsACString& aMimeTypeGuess, + int16_t* aShouldLoad) { + if (!aContentLocation || !aLoadInfo) { + NS_SetRequestBlockingReason( + aLoadInfo, nsILoadInfo::BLOCKING_REASON_CONTENT_POLICY_WEBEXT); + *aShouldLoad = REJECT_REQUEST; + return NS_ERROR_FAILURE; + } + + ExtContentPolicyType contentType = aLoadInfo->GetExternalContentPolicyType(); + + *aShouldLoad = nsIContentPolicy::ACCEPT; + nsCOMPtr loadingPrincipal = aLoadInfo->GetLoadingPrincipal(); + if (!loadingPrincipal) { + return NS_OK; + } + + // Only apply this policy to requests from documents loaded from + // moz-extension URLs, or to resources being loaded from moz-extension URLs. + if (!(aContentLocation->SchemeIs("moz-extension") || + loadingPrincipal->SchemeIs("moz-extension"))) { + return NS_OK; + } + + if (contentType == ExtContentPolicy::TYPE_SCRIPT) { + NS_ConvertUTF8toUTF16 typeString(aMimeTypeGuess); + nsContentTypeParser mimeParser(typeString); + + // Reject attempts to load JavaScript scripts with a non-default version. + nsAutoString mimeType, version; + if (NS_SUCCEEDED(mimeParser.GetType(mimeType)) && + nsContentUtils::IsJavascriptMIMEType(mimeType) && + NS_SUCCEEDED(mimeParser.GetParameter("version", version))) { + NS_SetRequestBlockingReason( + aLoadInfo, nsILoadInfo::BLOCKING_REASON_CONTENT_POLICY_WEBEXT); + *aShouldLoad = nsIContentPolicy::REJECT_REQUEST; + + nsCString sourceName; + loadingPrincipal->GetExposableSpec(sourceName); + NS_ConvertUTF8toUTF16 nameString(sourceName); + + nsCOMPtr context = aLoadInfo->GetLoadingContext(); + LogMessage(nsLiteralString(VERSIONED_JS_BLOCKED_MESSAGE), nameString, + typeString, context); + return NS_OK; + } + } + + return NS_OK; +} + +NS_IMETHODIMP +AddonContentPolicy::ShouldProcess(nsIURI* aContentLocation, + nsILoadInfo* aLoadInfo, + const nsACString& aMimeTypeGuess, + int16_t* aShouldProcess) { + *aShouldProcess = nsIContentPolicy::ACCEPT; + return NS_OK; +} + +// CSP Validation: + +static const char* allowedSchemes[] = {"blob", "filesystem", nullptr}; + +static const char* allowedHostSchemes[] = {"http", "https", "moz-extension", + nullptr}; + +/** + * Validates a CSP directive to ensure that it is sufficiently stringent. + * In particular, ensures that: + * + * - No remote sources are allowed other than from https: schemes + * + * - No remote sources specify host wildcards for generic domains + * (*.blogspot.com, *.com, *) + * + * - All remote sources and local extension sources specify a host + * + * - No scheme sources are allowed other than blob:, filesystem:, + * moz-extension:, and https: + * + * - No keyword sources are allowed other than 'none', 'self', 'unsafe-eval', + * and hash sources. + * + * Manifest V3 limits CSP for extension_pages, the script-src and + * worker-src directives may only be the following: + * - self + * - none + */ +class CSPValidator final : public nsCSPSrcVisitor { + public: + CSPValidator(nsAString& aURL, CSPDirective aDirective, + bool aDirectiveRequired = true, uint32_t aPermittedPolicy = 0) + : mURL(aURL), + mDirective(CSP_CSPDirectiveToString(aDirective)), + mPermittedPolicy(aPermittedPolicy), + mDirectiveRequired(aDirectiveRequired), + mFoundSelf(false) { + // Start with the default error message for a missing directive, since no + // visitors will be called if the directive isn't present. + mError.SetIsVoid(true); + } + + // Visitors + + bool visitSchemeSrc(const nsCSPSchemeSrc& src) override { + nsAutoString scheme; + src.getScheme(scheme); + + if (SchemeInList(scheme, allowedHostSchemes)) { + FormatError("csp-error-missing-host"_ns, "scheme"_ns, scheme); + return false; + } + if (!SchemeInList(scheme, allowedSchemes)) { + FormatError("csp-error-illegal-protocol"_ns, "scheme"_ns, scheme); + return false; + } + return true; + }; + + bool visitHostSrc(const nsCSPHostSrc& src) override { + nsAutoString scheme, host; + + src.getScheme(scheme); + src.getHost(host); + + if (scheme.LowerCaseEqualsLiteral("http")) { + // Allow localhost on http + if (mPermittedPolicy & nsIAddonContentPolicy::CSP_ALLOW_LOCALHOST && + HostIsLocal(host)) { + return true; + } + FormatError("csp-error-illegal-protocol"_ns, "scheme"_ns, scheme); + return false; + } + if (scheme.LowerCaseEqualsLiteral("https")) { + if (mPermittedPolicy & nsIAddonContentPolicy::CSP_ALLOW_LOCALHOST && + HostIsLocal(host)) { + return true; + } + if (!(mPermittedPolicy & nsIAddonContentPolicy::CSP_ALLOW_REMOTE)) { + FormatError("csp-error-illegal-protocol"_ns, "scheme"_ns, scheme); + return false; + } + if (!HostIsAllowed(host)) { + FormatError("csp-error-illegal-host-wildcard"_ns, "scheme"_ns, scheme); + return false; + } + } else if (scheme.LowerCaseEqualsLiteral("moz-extension")) { + // The CSP parser silently converts 'self' keywords to the origin + // URL, so we need to reconstruct the URL to see if it was present. + if (!mFoundSelf) { + nsAutoString url(u"moz-extension://"); + url.Append(host); + + mFoundSelf = url.Equals(mURL); + } + + if (host.IsEmpty() || host.EqualsLiteral("*")) { + FormatError("csp-error-missing-host"_ns, "scheme"_ns, scheme); + return false; + } + } else if (!SchemeInList(scheme, allowedSchemes)) { + FormatError("csp-error-illegal-protocol"_ns, "scheme"_ns, scheme); + return false; + } + + return true; + }; + + bool visitKeywordSrc(const nsCSPKeywordSrc& src) override { + switch (src.getKeyword()) { + case CSP_NONE: + case CSP_SELF: + return true; + case CSP_WASM_UNSAFE_EVAL: + if (mPermittedPolicy & nsIAddonContentPolicy::CSP_ALLOW_WASM) { + return true; + } + // fall through to also check CSP_ALLOW_EVAL + [[fallthrough]]; + case CSP_UNSAFE_EVAL: + if (mPermittedPolicy & nsIAddonContentPolicy::CSP_ALLOW_EVAL) { + return true; + } + // fall through and produce an illegal-keyword error. + [[fallthrough]]; + default: + FormatError( + "csp-error-illegal-keyword"_ns, "keyword"_ns, + nsDependentString(CSP_EnumToUTF16Keyword(src.getKeyword()))); + return false; + } + }; + + bool visitNonceSrc(const nsCSPNonceSrc& src) override { + FormatError("csp-error-illegal-keyword"_ns, "keyword"_ns, u"'nonce-*'"_ns); + return false; + }; + + bool visitHashSrc(const nsCSPHashSrc& src) override { return true; }; + + // Accessors + + inline nsAString& GetError() { + if (mError.IsVoid() && mDirectiveRequired) { + FormatError("csp-error-missing-directive"_ns); + } + + return mError; + }; + + inline bool FoundSelf() { return mFoundSelf; }; + + // Formatters + + inline void FormatError(const nsACString& l10nId, + const nsACString& aKey = ""_ns, + const nsAString& aValue = u""_ns) { + nsTArray resIds = {"toolkit/global/cspErrors.ftl"_ns}; + RefPtr l10n = intl::Localization::Create(resIds, true); + + auto l10nArgs = dom::Optional(); + l10nArgs.Construct(); + + auto dirArg = l10nArgs.Value().Entries().AppendElement(); + dirArg->mKey = "directive"; + dirArg->mValue.SetValue().SetAsUTF8String().Assign( + NS_ConvertUTF16toUTF8(mDirective)); + + if (!aKey.IsEmpty()) { + auto optArg = l10nArgs.Value().Entries().AppendElement(); + optArg->mKey = aKey; + optArg->mValue.SetValue().SetAsUTF8String().Assign( + NS_ConvertUTF16toUTF8(aValue)); + } + + nsAutoCString translation; + IgnoredErrorResult rv; + l10n->FormatValueSync(l10nId, l10nArgs, translation, rv); + if (rv.Failed()) { + mError.AssignLiteral("An unexpected error occurred"); + } else { + mError = NS_ConvertUTF8toUTF16(translation); + } + }; + + private: + // Validators + bool HostIsLocal(nsAString& host) { + return host.EqualsLiteral("localhost") || host.EqualsLiteral("127.0.0.1"); + } + + bool HostIsAllowed(nsAString& host) { + if (host.First() == '*') { + if (host.EqualsLiteral("*") || host[1] != '.') { + return false; + } + + host.Cut(0, 2); + + nsCOMPtr tldService = + do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID); + + if (!tldService) { + return false; + } + + NS_ConvertUTF16toUTF8 cHost(host); + nsAutoCString publicSuffix; + + nsresult rv = tldService->GetPublicSuffixFromHost(cHost, publicSuffix); + + return NS_SUCCEEDED(rv) && !cHost.Equals(publicSuffix); + } + + return true; + }; + + bool SchemeInList(nsAString& scheme, const char** schemes) { + for (; *schemes; schemes++) { + if (scheme.LowerCaseEqualsASCII(*schemes)) { + return true; + } + } + return false; + }; + + // Data members + + nsAutoString mURL; + NS_ConvertASCIItoUTF16 mDirective; + nsString mError; + + uint32_t mPermittedPolicy; + bool mDirectiveRequired; + bool mFoundSelf; +}; + +/** + * Validates a custom content security policy string for use by an add-on. + * In particular, ensures that: + * + * - That script-src (or default-src) directive is present, and meets + * the policies required by the CSPValidator class + * + * - The script-src directive includes the source 'self' + */ +NS_IMETHODIMP +AddonContentPolicy::ValidateAddonCSP(const nsAString& aPolicyString, + uint32_t aPermittedPolicy, + nsAString& aResult) { + nsresult rv; + + // Validate against a randomly-generated extension origin. + // There is no add-on-specific behavior in the CSP code, beyond the ability + // for add-ons to specify a custom policy, but the parser requires a valid + // origin in order to operate correctly. + nsAutoString url(u"moz-extension://"); + { + nsCOMPtr uuidgen = components::UUIDGenerator::Service(); + NS_ENSURE_TRUE(uuidgen, NS_ERROR_FAILURE); + + nsID id; + rv = uuidgen->GenerateUUIDInPlace(&id); + NS_ENSURE_SUCCESS(rv, rv); + + char idString[NSID_LENGTH]; + id.ToProvidedString(idString); + + MOZ_RELEASE_ASSERT(idString[0] == '{' && idString[NSID_LENGTH - 2] == '}', + "UUID generator did not return a valid UUID"); + + url.AppendASCII(idString + 1, NSID_LENGTH - 3); + } + + RefPtr principal = + BasePrincipal::CreateContentPrincipal(NS_ConvertUTF16toUTF8(url)); + + nsCOMPtr selfURI; + principal->GetURI(getter_AddRefs(selfURI)); + RefPtr csp = new nsCSPContext(); + rv = csp->SetRequestContextWithPrincipal(principal, selfURI, u""_ns, 0); + NS_ENSURE_SUCCESS(rv, rv); + csp->AppendPolicy(aPolicyString, false, false); + + const nsCSPPolicy* policy = csp->GetPolicy(0); + if (!policy) { + CSPValidator validator(url, nsIContentSecurityPolicy::SCRIPT_SRC_DIRECTIVE, + true, aPermittedPolicy); + aResult.Assign(validator.GetError()); + return NS_OK; + } + + bool haveValidDefaultSrc = false; + bool hasValidScriptSrc = false; + { + CSPDirective directive = nsIContentSecurityPolicy::DEFAULT_SRC_DIRECTIVE; + CSPValidator validator(url, directive); + + haveValidDefaultSrc = policy->visitDirectiveSrcs(directive, &validator); + } + + aResult.SetIsVoid(true); + { + CSPDirective directive = nsIContentSecurityPolicy::SCRIPT_SRC_DIRECTIVE; + CSPValidator validator(url, directive, !haveValidDefaultSrc, + aPermittedPolicy); + + if (!policy->visitDirectiveSrcs(directive, &validator)) { + aResult.Assign(validator.GetError()); + } else if (!validator.FoundSelf()) { + validator.FormatError("csp-error-missing-source"_ns, "source"_ns, + u"'self'"_ns); + aResult.Assign(validator.GetError()); + } + hasValidScriptSrc = true; + } + + if (aResult.IsVoid()) { + CSPDirective directive = nsIContentSecurityPolicy::WORKER_SRC_DIRECTIVE; + CSPValidator validator(url, directive, + !haveValidDefaultSrc && !hasValidScriptSrc, + aPermittedPolicy); + + if (!policy->visitDirectiveSrcs(directive, &validator)) { + aResult.Assign(validator.GetError()); + } + } + + return NS_OK; +} diff --git a/toolkit/mozapps/extensions/AddonContentPolicy.h b/toolkit/mozapps/extensions/AddonContentPolicy.h new file mode 100644 index 0000000000..db4c29db05 --- /dev/null +++ b/toolkit/mozapps/extensions/AddonContentPolicy.h @@ -0,0 +1,21 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nsIContentPolicy.h" +#include "nsIAddonPolicyService.h" + +class AddonContentPolicy : public nsIContentPolicy, + public nsIAddonContentPolicy { + protected: + virtual ~AddonContentPolicy(); + + public: + AddonContentPolicy(); + + NS_DECL_ISUPPORTS + NS_DECL_NSICONTENTPOLICY + NS_DECL_NSIADDONCONTENTPOLICY +}; diff --git a/toolkit/mozapps/extensions/AddonManager.jsm b/toolkit/mozapps/extensions/AddonManager.jsm new file mode 100644 index 0000000000..ecf5c907c0 --- /dev/null +++ b/toolkit/mozapps/extensions/AddonManager.jsm @@ -0,0 +1,5301 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +// Cannot use Services.appinfo here, or else xpcshell-tests will blow up, as +// most tests later register different nsIAppInfo implementations, which +// wouldn't be reflected in Services.appinfo anymore, as the lazy getter +// underlying it would have been initialized if we used it here. +if ("@mozilla.org/xre/app-info;1" in Cc) { + // eslint-disable-next-line mozilla/use-services + let runtime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime); + if (runtime.processType != Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) { + // Refuse to run in child processes. + throw new Error("You cannot use the AddonManager in child processes!"); + } +} + +const { AppConstants } = ChromeUtils.importESModule( + "resource://gre/modules/AppConstants.sys.mjs" +); + +const MOZ_COMPATIBILITY_NIGHTLY = ![ + "aurora", + "beta", + "release", + "esr", +].includes(AppConstants.MOZ_UPDATE_CHANNEL); + +const INTL_LOCALES_CHANGED = "intl:app-locales-changed"; + +const PREF_AMO_ABUSEREPORT = "extensions.abuseReport.amWebAPI.enabled"; +const PREF_BLOCKLIST_PINGCOUNTVERSION = "extensions.blocklist.pingCountVersion"; +const PREF_EM_UPDATE_ENABLED = "extensions.update.enabled"; +const PREF_EM_LAST_APP_VERSION = "extensions.lastAppVersion"; +const PREF_EM_LAST_PLATFORM_VERSION = "extensions.lastPlatformVersion"; +const PREF_EM_AUTOUPDATE_DEFAULT = "extensions.update.autoUpdateDefault"; +const PREF_EM_STRICT_COMPATIBILITY = "extensions.strictCompatibility"; +const PREF_EM_CHECK_UPDATE_SECURITY = "extensions.checkUpdateSecurity"; +const PREF_SYS_ADDON_UPDATE_ENABLED = "extensions.systemAddon.update.enabled"; +const PREF_REMOTESETTINGS_DISABLED = "extensions.remoteSettings.disabled"; + +const PREF_MIN_WEBEXT_PLATFORM_VERSION = + "extensions.webExtensionsMinPlatformVersion"; +const PREF_WEBAPI_TESTING = "extensions.webapi.testing"; +const PREF_EM_POSTDOWNLOAD_THIRD_PARTY = + "extensions.postDownloadThirdPartyPrompt"; + +const UPDATE_REQUEST_VERSION = 2; + +const BRANCH_REGEXP = /^([^\.]+\.[0-9]+[a-z]*).*/gi; +const PREF_EM_CHECK_COMPATIBILITY_BASE = "extensions.checkCompatibility"; +var PREF_EM_CHECK_COMPATIBILITY = MOZ_COMPATIBILITY_NIGHTLY + ? PREF_EM_CHECK_COMPATIBILITY_BASE + ".nightly" + : undefined; + +const WEBAPI_INSTALL_HOSTS = ["addons.mozilla.org"]; +const WEBAPI_TEST_INSTALL_HOSTS = [ + "addons.allizom.org", + "addons-dev.allizom.org", + "example.com", +]; + +const AMO_ATTRIBUTION_ALLOWED_SOURCES = ["amo", "disco"]; +const AMO_ATTRIBUTION_DATA_KEYS = [ + "utm_campaign", + "utm_content", + "utm_medium", + "utm_source", +]; +const AMO_ATTRIBUTION_DATA_MAX_LENGTH = 40; + +const { XPCOMUtils } = ChromeUtils.importESModule( + "resource://gre/modules/XPCOMUtils.sys.mjs" +); +// This global is overridden by xpcshell tests, and therefore cannot be +// a const. +var { AsyncShutdown } = ChromeUtils.importESModule( + "resource://gre/modules/AsyncShutdown.sys.mjs" +); +const { PromiseUtils } = ChromeUtils.importESModule( + "resource://gre/modules/PromiseUtils.sys.mjs" +); + +const lazy = {}; + +ChromeUtils.defineESModuleGetters(lazy, { + isGatedPermissionType: + "resource://gre/modules/addons/siteperms-addon-utils.sys.mjs", + isKnownPublicSuffix: + "resource://gre/modules/addons/siteperms-addon-utils.sys.mjs", + isPrincipalInSitePermissionsBlocklist: + "resource://gre/modules/addons/siteperms-addon-utils.sys.mjs", + TelemetryTimestamps: "resource://gre/modules/TelemetryTimestamps.sys.mjs", +}); + +XPCOMUtils.defineLazyModuleGetters(lazy, { + AddonRepository: "resource://gre/modules/addons/AddonRepository.jsm", + AbuseReporter: "resource://gre/modules/AbuseReporter.jsm", + Extension: "resource://gre/modules/Extension.jsm", + RemoteSettings: "resource://services-settings/remote-settings.js", +}); + +XPCOMUtils.defineLazyPreferenceGetter( + lazy, + "WEBEXT_POSTDOWNLOAD_THIRD_PARTY", + PREF_EM_POSTDOWNLOAD_THIRD_PARTY, + false +); + +// Initialize the WebExtension process script service as early as possible, +// since it needs to be able to track things like new frameLoader globals that +// are created before other framework code has been initialized. +Services.ppmm.loadProcessScript( + "resource://gre/modules/extensionProcessScriptLoader.js", + true +); + +const INTEGER = /^[1-9]\d*$/; + +var EXPORTED_SYMBOLS = [ + "AddonManager", + "AddonManagerPrivate", + "AMTelemetry", + "AMRemoteSettings", +]; + +const CATEGORY_PROVIDER_MODULE = "addon-provider-module"; + +const { Log } = ChromeUtils.importESModule( + "resource://gre/modules/Log.sys.mjs" +); +// Configure a logger at the parent 'addons' level to format +// messages for all the modules under addons.* +const PARENT_LOGGER_ID = "addons"; +var parentLogger = Log.repository.getLogger(PARENT_LOGGER_ID); +parentLogger.level = Log.Level.Warn; +var formatter = new Log.BasicFormatter(); +// Set parent logger (and its children) to append to +// the Javascript section of the Browser Console +parentLogger.addAppender(new Log.ConsoleAppender(formatter)); + +// Create a new logger (child of 'addons' logger) +// for use by the Addons Manager +const LOGGER_ID = "addons.manager"; +var logger = Log.repository.getLogger(LOGGER_ID); + +// Provide the ability to enable/disable logging +// messages at runtime. +// If the "extensions.logging.enabled" preference is +// missing or 'false', messages at the WARNING and higher +// severity should be logged to the JS console and standard error. +// If "extensions.logging.enabled" is set to 'true', messages +// at DEBUG and higher should go to JS console and standard error. +const PREF_LOGGING_ENABLED = "extensions.logging.enabled"; +const NS_PREFBRANCH_PREFCHANGE_TOPIC_ID = "nsPref:changed"; + +const UNNAMED_PROVIDER = ""; +function providerName(aProvider) { + return aProvider.name || UNNAMED_PROVIDER; +} + +// A reference to XPIProvider. This should only be used to access properties or +// methods that are independent of XPIProvider startup. +var gXPIProvider; + +/** + * Preference listener which listens for a change in the + * "extensions.logging.enabled" preference and changes the logging level of the + * parent 'addons' level logger accordingly. + */ +var PrefObserver = { + init() { + Services.prefs.addObserver(PREF_LOGGING_ENABLED, this); + Services.obs.addObserver(this, "xpcom-shutdown"); + this.observe(null, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID, PREF_LOGGING_ENABLED); + }, + + observe(aSubject, aTopic, aData) { + if (aTopic == "xpcom-shutdown") { + Services.prefs.removeObserver(PREF_LOGGING_ENABLED, this); + Services.obs.removeObserver(this, "xpcom-shutdown"); + } else if (aTopic == NS_PREFBRANCH_PREFCHANGE_TOPIC_ID) { + let debugLogEnabled = Services.prefs.getBoolPref( + PREF_LOGGING_ENABLED, + false + ); + if (debugLogEnabled) { + parentLogger.level = Log.Level.Debug; + } else { + parentLogger.level = Log.Level.Warn; + } + } + }, +}; + +PrefObserver.init(); + +/** + * Calls a callback method consuming any thrown exception. Any parameters after + * the callback parameter will be passed to the callback. + * + * @param aCallback + * The callback method to call + */ +function safeCall(aCallback, ...aArgs) { + try { + aCallback.apply(null, aArgs); + } catch (e) { + logger.warn("Exception calling callback", e); + } +} + +/** + * Report an exception thrown by a provider API method. + */ +function reportProviderError(aProvider, aMethod, aError) { + let method = `provider ${providerName(aProvider)}.${aMethod}`; + AddonManagerPrivate.recordException("AMI", method, aError); + logger.error("Exception calling " + method, aError); +} + +/** + * Calls a method on a provider if it exists and consumes any thrown exception. + * Any parameters after the aDefault parameter are passed to the provider's method. + * + * @param aProvider + * The provider to call + * @param aMethod + * The method name to call + * @param aDefault + * A default return value if the provider does not implement the named + * method or throws an error. + * @return the return value from the provider, or aDefault if the provider does not + * implement method or throws an error + */ +function callProvider(aProvider, aMethod, aDefault, ...aArgs) { + if (!(aMethod in aProvider)) { + return aDefault; + } + + try { + return aProvider[aMethod].apply(aProvider, aArgs); + } catch (e) { + reportProviderError(aProvider, aMethod, e); + return aDefault; + } +} + +/** + * Calls a method on a provider if it exists and consumes any thrown exception. + * Parameters after aMethod are passed to aProvider.aMethod(). + * If the provider does not implement the method, or the method throws, calls + * the callback with 'undefined'. + * + * @param aProvider + * The provider to call + * @param aMethod + * The method name to call + */ +async function promiseCallProvider(aProvider, aMethod, ...aArgs) { + if (!(aMethod in aProvider)) { + return undefined; + } + try { + return aProvider[aMethod].apply(aProvider, aArgs); + } catch (e) { + reportProviderError(aProvider, aMethod, e); + return undefined; + } +} + +/** + * Gets the currently selected locale for display. + * @return the selected locale or "en-US" if none is selected + */ +function getLocale() { + return Services.locale.requestedLocale || "en-US"; +} + +const WEB_EXPOSED_ADDON_PROPERTIES = [ + "id", + "version", + "type", + "name", + "description", + "isActive", +]; + +function webAPIForAddon(addon) { + if (!addon) { + return null; + } + + // These web-exposed Addon properties (see AddonManager.webidl) + // just come directly from an Addon object. + let result = {}; + for (let prop of WEB_EXPOSED_ADDON_PROPERTIES) { + result[prop] = addon[prop]; + } + + // These properties are computed. + result.isEnabled = !addon.userDisabled; + result.canUninstall = Boolean( + addon.permissions & AddonManager.PERM_CAN_UNINSTALL + ); + + return result; +} + +/** + * Listens for a browser changing origin and cancels the installs that were + * started by it. + */ +function BrowserListener(aBrowser, aInstallingPrincipal, aInstall) { + this.browser = aBrowser; + this.messageManager = this.browser.messageManager; + this.principal = aInstallingPrincipal; + this.install = aInstall; + + aBrowser.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION); + Services.obs.addObserver(this, "message-manager-close", true); + + aInstall.addListener(this); + + this.registered = true; +} + +BrowserListener.prototype = { + browser: null, + install: null, + registered: false, + + unregister() { + if (!this.registered) { + return; + } + this.registered = false; + + Services.obs.removeObserver(this, "message-manager-close"); + // The browser may have already been detached + if (this.browser.removeProgressListener) { + this.browser.removeProgressListener(this); + } + + this.install.removeListener(this); + this.install = null; + }, + + cancelInstall() { + try { + this.install.cancel(); + } catch (e) { + // install may have already failed or been cancelled, ignore these + } + }, + + observe(subject, topic, data) { + if (subject != this.messageManager) { + return; + } + + // The browser's message manager has closed and so the browser is + // going away, cancel the install + this.cancelInstall(); + }, + + onLocationChange(webProgress, request, location) { + if ( + this.browser.contentPrincipal && + this.principal.subsumes(this.browser.contentPrincipal) + ) { + return; + } + + // The browser has navigated to a new origin so cancel the install + this.cancelInstall(); + }, + + onDownloadCancelled(install) { + this.unregister(); + }, + + onDownloadFailed(install) { + this.unregister(); + }, + + onInstallFailed(install) { + this.unregister(); + }, + + onInstallEnded(install) { + this.unregister(); + }, + + QueryInterface: ChromeUtils.generateQI([ + "nsISupportsWeakReference", + "nsIWebProgressListener", + "nsIObserver", + ]), +}; + +/** + * This represents an author of an add-on (e.g. creator or developer) + * + * @param aName + * The name of the author + * @param aURL + * The URL of the author's profile page + */ +function AddonAuthor(aName, aURL) { + this.name = aName; + this.url = aURL; +} + +AddonAuthor.prototype = { + name: null, + url: null, + + // Returns the author's name, defaulting to the empty string + toString() { + return this.name || ""; + }, +}; + +/** + * This represents an screenshot for an add-on + * + * @param aURL + * The URL to the full version of the screenshot + * @param aWidth + * The width in pixels of the screenshot + * @param aHeight + * The height in pixels of the screenshot + * @param aThumbnailURL + * The URL to the thumbnail version of the screenshot + * @param aThumbnailWidth + * The width in pixels of the thumbnail version of the screenshot + * @param aThumbnailHeight + * The height in pixels of the thumbnail version of the screenshot + * @param aCaption + * The caption of the screenshot + */ +function AddonScreenshot( + aURL, + aWidth, + aHeight, + aThumbnailURL, + aThumbnailWidth, + aThumbnailHeight, + aCaption +) { + this.url = aURL; + if (aWidth) { + this.width = aWidth; + } + if (aHeight) { + this.height = aHeight; + } + if (aThumbnailURL) { + this.thumbnailURL = aThumbnailURL; + } + if (aThumbnailWidth) { + this.thumbnailWidth = aThumbnailWidth; + } + if (aThumbnailHeight) { + this.thumbnailHeight = aThumbnailHeight; + } + if (aCaption) { + this.caption = aCaption; + } +} + +AddonScreenshot.prototype = { + url: null, + width: null, + height: null, + thumbnailURL: null, + thumbnailWidth: null, + thumbnailHeight: null, + caption: null, + + // Returns the screenshot URL, defaulting to the empty string + toString() { + return this.url || ""; + }, +}; + +var gStarted = false; +var gStartedPromise = PromiseUtils.defer(); +var gStartupComplete = false; +var gCheckCompatibility = true; +var gStrictCompatibility = true; +var gCheckUpdateSecurityDefault = true; +var gCheckUpdateSecurity = gCheckUpdateSecurityDefault; +var gUpdateEnabled = true; +var gAutoUpdateDefault = true; +var gWebExtensionsMinPlatformVersion = ""; +var gFinalShutdownBarrier = null; +var gBeforeShutdownBarrier = null; +var gRepoShutdownState = ""; +var gShutdownInProgress = false; +var gBrowserUpdated = null; + +var AMTelemetry; +var AMRemoteSettings; + +/** + * This is the real manager, kept here rather than in AddonManager to keep its + * contents hidden from API users. + * @class + * @lends AddonManager + */ +var AddonManagerInternal = { + managerListeners: new Set(), + installListeners: new Set(), + addonListeners: new Set(), + pendingProviders: new Set(), + providers: new Set(), + providerShutdowns: new Map(), + typesByProvider: new Map(), + startupChanges: {}, + // Store telemetry details per addon provider + telemetryDetails: {}, + upgradeListeners: new Map(), + externalExtensionLoaders: new Map(), + + recordTimestamp(name, value) { + lazy.TelemetryTimestamps.add(name, value); + }, + + /** + * Start up a provider, and register its shutdown hook if it has one + * + * @param {string} aProvider - An add-on provider. + * @param {boolean} aAppChanged - Whether or not the app version has changed since last session. + * @param {string} aOldAppVersion - Previous application version, if changed. + * @param {string} aOldPlatformVersion - Previous platform version, if changed. + * + * @private + */ + _startProvider(aProvider, aAppChanged, aOldAppVersion, aOldPlatformVersion) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + logger.debug(`Starting provider: ${providerName(aProvider)}`); + callProvider( + aProvider, + "startup", + null, + aAppChanged, + aOldAppVersion, + aOldPlatformVersion + ); + if ("shutdown" in aProvider) { + let name = providerName(aProvider); + let AMProviderShutdown = () => { + // If the provider has been unregistered, it will have been removed from + // this.providers. If it hasn't been unregistered, then this is a normal + // shutdown - and we move it to this.pendingProviders in case we're + // running in a test that will start AddonManager again. + if (this.providers.has(aProvider)) { + this.providers.delete(aProvider); + this.pendingProviders.add(aProvider); + } + + return new Promise((resolve, reject) => { + logger.debug("Calling shutdown blocker for " + name); + resolve(aProvider.shutdown()); + }).catch(err => { + logger.warn("Failure during shutdown of " + name, err); + AddonManagerPrivate.recordException( + "AMI", + "Async shutdown of " + name, + err + ); + }); + }; + logger.debug("Registering shutdown blocker for " + name); + this.providerShutdowns.set(aProvider, AMProviderShutdown); + AddonManagerPrivate.finalShutdown.addBlocker(name, AMProviderShutdown); + } + + this.pendingProviders.delete(aProvider); + this.providers.add(aProvider); + logger.debug(`Provider finished startup: ${providerName(aProvider)}`); + }, + + _getProviderByName(aName) { + for (let provider of this.providers) { + if (providerName(provider) == aName) { + return provider; + } + } + return undefined; + }, + + /** + * Initializes the AddonManager, loading any known providers and initializing + * them. + */ + startup() { + try { + if (gStarted) { + return; + } + + this.recordTimestamp("AMI_startup_begin"); + + // Enable the addonsManager telemetry event category. + AMTelemetry.init(); + + // Enable the AMRemoteSettings client. + AMRemoteSettings.init(); + + // clear this for xpcshell test restarts + for (let provider in this.telemetryDetails) { + delete this.telemetryDetails[provider]; + } + + let appChanged = undefined; + + let oldAppVersion = null; + try { + oldAppVersion = Services.prefs.getCharPref(PREF_EM_LAST_APP_VERSION); + appChanged = Services.appinfo.version != oldAppVersion; + } catch (e) {} + + gBrowserUpdated = appChanged; + + let oldPlatformVersion = Services.prefs.getCharPref( + PREF_EM_LAST_PLATFORM_VERSION, + "" + ); + + if (appChanged !== false) { + logger.debug("Application has been upgraded"); + Services.prefs.setCharPref( + PREF_EM_LAST_APP_VERSION, + Services.appinfo.version + ); + Services.prefs.setCharPref( + PREF_EM_LAST_PLATFORM_VERSION, + Services.appinfo.platformVersion + ); + Services.prefs.setIntPref( + PREF_BLOCKLIST_PINGCOUNTVERSION, + appChanged === undefined ? 0 : -1 + ); + } + + if (!MOZ_COMPATIBILITY_NIGHTLY) { + PREF_EM_CHECK_COMPATIBILITY = + PREF_EM_CHECK_COMPATIBILITY_BASE + + "." + + Services.appinfo.version.replace(BRANCH_REGEXP, "$1"); + } + + gCheckCompatibility = Services.prefs.getBoolPref( + PREF_EM_CHECK_COMPATIBILITY, + gCheckCompatibility + ); + Services.prefs.addObserver(PREF_EM_CHECK_COMPATIBILITY, this); + + gStrictCompatibility = Services.prefs.getBoolPref( + PREF_EM_STRICT_COMPATIBILITY, + gStrictCompatibility + ); + Services.prefs.addObserver(PREF_EM_STRICT_COMPATIBILITY, this); + + let defaultBranch = Services.prefs.getDefaultBranch(""); + gCheckUpdateSecurityDefault = defaultBranch.getBoolPref( + PREF_EM_CHECK_UPDATE_SECURITY, + gCheckUpdateSecurityDefault + ); + + gCheckUpdateSecurity = Services.prefs.getBoolPref( + PREF_EM_CHECK_UPDATE_SECURITY, + gCheckUpdateSecurity + ); + Services.prefs.addObserver(PREF_EM_CHECK_UPDATE_SECURITY, this); + + gUpdateEnabled = Services.prefs.getBoolPref( + PREF_EM_UPDATE_ENABLED, + gUpdateEnabled + ); + Services.prefs.addObserver(PREF_EM_UPDATE_ENABLED, this); + + gAutoUpdateDefault = Services.prefs.getBoolPref( + PREF_EM_AUTOUPDATE_DEFAULT, + gAutoUpdateDefault + ); + Services.prefs.addObserver(PREF_EM_AUTOUPDATE_DEFAULT, this); + + gWebExtensionsMinPlatformVersion = Services.prefs.getCharPref( + PREF_MIN_WEBEXT_PLATFORM_VERSION, + gWebExtensionsMinPlatformVersion + ); + Services.prefs.addObserver(PREF_MIN_WEBEXT_PLATFORM_VERSION, this); + + // Watch for changes to PREF_REMOTESETTINGS_DISABLED. + Services.prefs.addObserver(PREF_REMOTESETTINGS_DISABLED, this); + + // Watch for language changes, refresh the addon cache when it changes. + Services.obs.addObserver(this, INTL_LOCALES_CHANGED); + + // Ensure all default providers have had a chance to register themselves + ({ XPIProvider: gXPIProvider } = ChromeUtils.import( + "resource://gre/modules/addons/XPIProvider.jsm" + )); + + // Load any providers registered in the category manager + for (let { entry, value: url } of Services.catMan.enumerateCategory( + CATEGORY_PROVIDER_MODULE + )) { + try { + ChromeUtils.importESModule(url); + logger.debug(`Loaded provider scope for ${url}`); + } catch (e) { + AddonManagerPrivate.recordException( + "AMI", + "provider " + url + " load failed", + e + ); + logger.error( + "Exception loading provider " + + entry + + ' from category "' + + url + + '"', + e + ); + } + } + + // Register our shutdown handler with the AsyncShutdown manager + gBeforeShutdownBarrier = new AsyncShutdown.Barrier( + "AddonManager: Waiting to start provider shutdown." + ); + gFinalShutdownBarrier = new AsyncShutdown.Barrier( + "AddonManager: Waiting for providers to shut down." + ); + AsyncShutdown.profileBeforeChange.addBlocker( + "AddonManager: shutting down.", + this.shutdownManager.bind(this), + { fetchState: this.shutdownState.bind(this) } + ); + + // Once we start calling providers we must allow all normal methods to work. + gStarted = true; + + for (let provider of this.pendingProviders) { + this._startProvider( + provider, + appChanged, + oldAppVersion, + oldPlatformVersion + ); + } + + // If this is a new profile just pretend that there were no changes + if (appChanged === undefined) { + for (let type in this.startupChanges) { + delete this.startupChanges[type]; + } + } + + gStartupComplete = true; + gStartedPromise.resolve(); + this.recordTimestamp("AMI_startup_end"); + } catch (e) { + logger.error("startup failed", e); + AddonManagerPrivate.recordException("AMI", "startup failed", e); + gStartedPromise.reject("startup failed"); + } + + logger.debug("Completed startup sequence"); + this.callManagerListeners("onStartup"); + }, + + /** + * Registers a new AddonProvider. + * + * @param {string} aProvider -The provider to register + * @param {string[]} [aTypes] - An optional array of add-on types + */ + registerProvider(aProvider, aTypes) { + if (!aProvider || typeof aProvider != "object") { + throw Components.Exception( + "aProvider must be specified", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aTypes && !Array.isArray(aTypes)) { + throw Components.Exception( + "aTypes must be an array or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + this.pendingProviders.add(aProvider); + + if (aTypes) { + this.typesByProvider.set(aProvider, new Set(aTypes)); + } + + // If we're registering after startup call this provider's startup. + if (gStarted) { + this._startProvider(aProvider); + } + }, + + /** + * Unregisters an AddonProvider. + * + * @param aProvider + * The provider to unregister + * @return Whatever the provider's 'shutdown' method returns (if anything). + * For providers that have async shutdown methods returning Promises, + * the caller should wait for that Promise to resolve. + */ + unregisterProvider(aProvider) { + if (!aProvider || typeof aProvider != "object") { + throw Components.Exception( + "aProvider must be specified", + Cr.NS_ERROR_INVALID_ARG + ); + } + + this.providers.delete(aProvider); + // The test harness will unregister XPIProvider *after* shutdown, which is + // after the provider will have been moved from providers to + // pendingProviders. + this.pendingProviders.delete(aProvider); + + this.typesByProvider.delete(aProvider); + + // If we're unregistering after startup but before shutting down, + // remove the blocker for this provider's shutdown and call it. + // If we're already shutting down, just let gFinalShutdownBarrier + // call it to avoid races. + if (gStarted && !gShutdownInProgress) { + logger.debug( + "Unregistering shutdown blocker for " + providerName(aProvider) + ); + let shutter = this.providerShutdowns.get(aProvider); + if (shutter) { + this.providerShutdowns.delete(aProvider); + gFinalShutdownBarrier.client.removeBlocker(shutter); + return shutter(); + } + } + return undefined; + }, + + /** + * Mark a provider as safe to access via AddonManager APIs, before its + * startup has completed. + * + * Normally a provider isn't marked as safe until after its (synchronous) + * startup() method has returned. Until a provider has been marked safe, + * it won't be used by any of the AddonManager APIs. markProviderSafe() + * allows a provider to mark itself as safe during its startup; this can be + * useful if the provider wants to perform tasks that block startup, which + * happen after its required initialization tasks and therefore when the + * provider is in a safe state. + * + * @param aProvider Provider object to mark safe + */ + markProviderSafe(aProvider) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!aProvider || typeof aProvider != "object") { + throw Components.Exception( + "aProvider must be specified", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (!this.pendingProviders.has(aProvider)) { + return; + } + + this.pendingProviders.delete(aProvider); + this.providers.add(aProvider); + }, + + /** + * Calls a method on all registered providers if it exists and consumes any + * thrown exception. Return values are ignored. Any parameters after the + * method parameter are passed to the provider's method. + * WARNING: Do not use for asynchronous calls; callProviders() does not + * invoke callbacks if provider methods throw synchronous exceptions. + * + * @param aMethod + * The method name to call + */ + callProviders(aMethod, ...aArgs) { + if (!aMethod || typeof aMethod != "string") { + throw Components.Exception( + "aMethod must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + let providers = [...this.providers]; + for (let provider of providers) { + try { + if (aMethod in provider) { + provider[aMethod].apply(provider, aArgs); + } + } catch (e) { + reportProviderError(provider, aMethod, e); + } + } + }, + + /** + * Report the current state of asynchronous shutdown + */ + shutdownState() { + let state = []; + for (let barrier of [gBeforeShutdownBarrier, gFinalShutdownBarrier]) { + if (barrier) { + state.push({ name: barrier.client.name, state: barrier.state }); + } + } + state.push({ + name: "AddonRepository: async shutdown", + state: gRepoShutdownState, + }); + return state; + }, + + /** + * Shuts down the addon manager and all registered providers, this must clean + * up everything in order for automated tests to fake restarts. + * @return Promise{null} that resolves when all providers and dependent modules + * have finished shutting down + */ + async shutdownManager() { + logger.debug("before shutdown"); + try { + await gBeforeShutdownBarrier.wait(); + } catch (e) { + Cu.reportError(e); + } + + logger.debug("shutdown"); + this.callManagerListeners("onShutdown"); + + if (!gStartupComplete) { + gStartedPromise.reject("shutting down"); + } + + gRepoShutdownState = "pending"; + gShutdownInProgress = true; + + // Clean up listeners + Services.prefs.removeObserver(PREF_EM_CHECK_COMPATIBILITY, this); + Services.prefs.removeObserver(PREF_EM_STRICT_COMPATIBILITY, this); + Services.prefs.removeObserver(PREF_EM_CHECK_UPDATE_SECURITY, this); + Services.prefs.removeObserver(PREF_EM_UPDATE_ENABLED, this); + Services.prefs.removeObserver(PREF_EM_AUTOUPDATE_DEFAULT, this); + Services.prefs.removeObserver(PREF_REMOTESETTINGS_DISABLED, this); + + Services.obs.removeObserver(this, INTL_LOCALES_CHANGED); + + AMRemoteSettings.shutdown(); + + let savedError = null; + // Only shut down providers if they've been started. + if (gStarted) { + try { + await gFinalShutdownBarrier.wait(); + } catch (err) { + savedError = err; + logger.error("Failure during wait for shutdown barrier", err); + AddonManagerPrivate.recordException( + "AMI", + "Async shutdown of AddonManager providers", + err + ); + } + } + gXPIProvider = null; + + // Shut down AddonRepository after providers (if any). + try { + gRepoShutdownState = "in progress"; + await lazy.AddonRepository.shutdown(); + gRepoShutdownState = "done"; + } catch (err) { + savedError = err; + logger.error("Failure during AddonRepository shutdown", err); + AddonManagerPrivate.recordException( + "AMI", + "Async shutdown of AddonRepository", + err + ); + } + + logger.debug("Async provider shutdown done"); + this.managerListeners.clear(); + this.installListeners.clear(); + this.addonListeners.clear(); + this.providerShutdowns.clear(); + for (let type in this.startupChanges) { + delete this.startupChanges[type]; + } + gStarted = false; + gStartedPromise = PromiseUtils.defer(); + gStartupComplete = false; + gFinalShutdownBarrier = null; + gBeforeShutdownBarrier = null; + gShutdownInProgress = false; + if (savedError) { + throw savedError; + } + }, + + /** + * Notified when a preference we're interested in has changed. + */ + observe(aSubject, aTopic, aData) { + switch (aTopic) { + case INTL_LOCALES_CHANGED: { + // Asynchronously fetch and update the addons cache. + lazy.AddonRepository.backgroundUpdateCheck(); + return; + } + } + + switch (aData) { + case PREF_EM_CHECK_COMPATIBILITY: { + let oldValue = gCheckCompatibility; + gCheckCompatibility = Services.prefs.getBoolPref( + PREF_EM_CHECK_COMPATIBILITY, + true + ); + + this.callManagerListeners("onCompatibilityModeChanged"); + + if (gCheckCompatibility != oldValue) { + this.updateAddonAppDisabledStates(); + } + + break; + } + case PREF_EM_STRICT_COMPATIBILITY: { + let oldValue = gStrictCompatibility; + gStrictCompatibility = Services.prefs.getBoolPref( + PREF_EM_STRICT_COMPATIBILITY, + true + ); + + this.callManagerListeners("onCompatibilityModeChanged"); + + if (gStrictCompatibility != oldValue) { + this.updateAddonAppDisabledStates(); + } + + break; + } + case PREF_EM_CHECK_UPDATE_SECURITY: { + let oldValue = gCheckUpdateSecurity; + gCheckUpdateSecurity = Services.prefs.getBoolPref( + PREF_EM_CHECK_UPDATE_SECURITY, + true + ); + + this.callManagerListeners("onCheckUpdateSecurityChanged"); + + if (gCheckUpdateSecurity != oldValue) { + this.updateAddonAppDisabledStates(); + } + + break; + } + case PREF_EM_UPDATE_ENABLED: { + gUpdateEnabled = Services.prefs.getBoolPref( + PREF_EM_UPDATE_ENABLED, + true + ); + + this.callManagerListeners("onUpdateModeChanged"); + break; + } + case PREF_EM_AUTOUPDATE_DEFAULT: { + gAutoUpdateDefault = Services.prefs.getBoolPref( + PREF_EM_AUTOUPDATE_DEFAULT, + true + ); + + this.callManagerListeners("onUpdateModeChanged"); + break; + } + case PREF_MIN_WEBEXT_PLATFORM_VERSION: { + gWebExtensionsMinPlatformVersion = Services.prefs.getCharPref( + PREF_MIN_WEBEXT_PLATFORM_VERSION + ); + break; + } + case PREF_REMOTESETTINGS_DISABLED: { + if (Services.prefs.getBoolPref(PREF_REMOTESETTINGS_DISABLED, false)) { + AMRemoteSettings.shutdown(); + } else { + AMRemoteSettings.init(); + } + break; + } + } + }, + + /** + * Replaces %...% strings in an addon url (update and updateInfo) with + * appropriate values. + * + * @param aAddon + * The Addon representing the add-on + * @param aUri + * The string representation of the URI to escape + * @param aAppVersion + * The optional application version to use for %APP_VERSION% + * @return The appropriately escaped URI. + */ + escapeAddonURI(aAddon, aUri, aAppVersion) { + if (!aAddon || typeof aAddon != "object") { + throw Components.Exception( + "aAddon must be an Addon object", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (!aUri || typeof aUri != "string") { + throw Components.Exception( + "aUri must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aAppVersion && typeof aAppVersion != "string") { + throw Components.Exception( + "aAppVersion must be a string or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + var addonStatus = + aAddon.userDisabled || aAddon.softDisabled + ? "userDisabled" + : "userEnabled"; + + if (!aAddon.isCompatible) { + addonStatus += ",incompatible"; + } + + let { blocklistState } = aAddon; + if (blocklistState == Ci.nsIBlocklistService.STATE_BLOCKED) { + addonStatus += ",blocklisted"; + } + if (blocklistState == Ci.nsIBlocklistService.STATE_SOFTBLOCKED) { + addonStatus += ",softblocked"; + } + + let params = new Map( + Object.entries({ + ITEM_ID: aAddon.id, + ITEM_VERSION: aAddon.version, + ITEM_STATUS: addonStatus, + APP_ID: Services.appinfo.ID, + APP_VERSION: aAppVersion ? aAppVersion : Services.appinfo.version, + REQ_VERSION: UPDATE_REQUEST_VERSION, + APP_OS: Services.appinfo.OS, + APP_ABI: Services.appinfo.XPCOMABI, + APP_LOCALE: getLocale(), + CURRENT_APP_VERSION: Services.appinfo.version, + }) + ); + + let uri = aUri.replace(/%([A-Z_]+)%/g, (m0, m1) => params.get(m1) || m0); + + // escape() does not properly encode + symbols in any embedded FVF strings. + return uri.replace(/\+/g, "%2B"); + }, + + _updatePromptHandler(info) { + let oldPerms = info.existingAddon.userPermissions; + if (!oldPerms) { + // Updating from a legacy add-on, just let it proceed + return Promise.resolve(); + } + + let newPerms = info.addon.userPermissions; + + let difference = lazy.Extension.comparePermissions(oldPerms, newPerms); + + // If there are no new permissions, just go ahead with the update + if (!difference.origins.length && !difference.permissions.length) { + return Promise.resolve(); + } + + return new Promise((resolve, reject) => { + let subject = { + wrappedJSObject: { + addon: info.addon, + permissions: difference, + resolve, + reject, + // Reference to the related AddonInstall object (used in AMTelemetry to + // link the recorded event to the other events from the same install flow). + install: info.install, + }, + }; + Services.obs.notifyObservers(subject, "webextension-update-permissions"); + }); + }, + + // Returns true if System Addons should be updated + systemUpdateEnabled() { + if (!Services.prefs.getBoolPref(PREF_SYS_ADDON_UPDATE_ENABLED)) { + return false; + } + if (Services.policies && !Services.policies.isAllowed("SysAddonUpdate")) { + return false; + } + return true; + }, + + /** + * Performs a background update check by starting an update for all add-ons + * that can be updated. + * @return Promise{null} Resolves when the background update check is complete + * (the resulting addon installations may still be in progress). + */ + backgroundUpdateCheck() { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + let buPromise = (async () => { + logger.debug("Background update check beginning"); + + Services.obs.notifyObservers(null, "addons-background-update-start"); + + if (this.updateEnabled) { + // Keep track of all the async add-on updates happening in parallel + let updates = []; + + let allAddons = await this.getAllAddons(); + + // Repopulate repository cache first, to ensure compatibility overrides + // are up to date before checking for addon updates. + await lazy.AddonRepository.backgroundUpdateCheck(); + + for (let addon of allAddons) { + // Check all add-ons for updates so that any compatibility updates will + // be applied + + if (!(addon.permissions & AddonManager.PERM_CAN_UPGRADE)) { + continue; + } + + updates.push( + new Promise((resolve, reject) => { + addon.findUpdates( + { + onUpdateAvailable(aAddon, aInstall) { + // Start installing updates when the add-on can be updated and + // background updates should be applied. + logger.debug("Found update for add-on ${id}", aAddon); + if (AddonManager.shouldAutoUpdate(aAddon)) { + // XXX we really should resolve when this install is done, + // not when update-available check completes, no? + logger.debug(`Starting upgrade install of ${aAddon.id}`); + aInstall.promptHandler = (...args) => + AddonManagerInternal._updatePromptHandler(...args); + aInstall.install(); + } + }, + + onUpdateFinished: aAddon => { + logger.debug("onUpdateFinished for ${id}", aAddon); + resolve(); + }, + }, + AddonManager.UPDATE_WHEN_PERIODIC_UPDATE + ); + }) + ); + } + Services.obs.notifyObservers( + null, + "addons-background-updates-found", + updates.length + ); + await Promise.all(updates); + } + + if (AddonManagerInternal.systemUpdateEnabled()) { + try { + await AddonManagerInternal._getProviderByName( + "XPIProvider" + ).updateSystemAddons(); + } catch (e) { + logger.warn("Failed to update system addons", e); + } + } + + logger.debug("Background update check complete"); + Services.obs.notifyObservers(null, "addons-background-update-complete"); + })(); + // Fork the promise chain so we can log the error and let our caller see it too. + buPromise.catch(e => logger.warn("Error in background update", e)); + return buPromise; + }, + + /** + * Adds a add-on to the list of detected changes for this startup. If + * addStartupChange is called multiple times for the same add-on in the same + * startup then only the most recent change will be remembered. + * + * @param aType + * The type of change as a string. Providers can define their own + * types of changes or use the existing defined STARTUP_CHANGE_* + * constants + * @param aID + * The ID of the add-on + */ + addStartupChange(aType, aID) { + if (!aType || typeof aType != "string") { + throw Components.Exception( + "aType must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (!aID || typeof aID != "string") { + throw Components.Exception( + "aID must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (gStartupComplete) { + return; + } + logger.debug("Registering startup change '" + aType + "' for " + aID); + + // Ensure that an ID is only listed in one type of change + for (let type in this.startupChanges) { + this.removeStartupChange(type, aID); + } + + if (!(aType in this.startupChanges)) { + this.startupChanges[aType] = []; + } + this.startupChanges[aType].push(aID); + }, + + /** + * Removes a startup change for an add-on. + * + * @param aType + * The type of change + * @param aID + * The ID of the add-on + */ + removeStartupChange(aType, aID) { + if (!aType || typeof aType != "string") { + throw Components.Exception( + "aType must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (!aID || typeof aID != "string") { + throw Components.Exception( + "aID must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (gStartupComplete) { + return; + } + + if (!(aType in this.startupChanges)) { + return; + } + + this.startupChanges[aType] = this.startupChanges[aType].filter( + aItem => aItem != aID + ); + }, + + /** + * Calls all registered AddonManagerListeners with an event. Any parameters + * after the method parameter are passed to the listener. + * + * @param aMethod + * The method on the listeners to call + */ + callManagerListeners(aMethod, ...aArgs) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!aMethod || typeof aMethod != "string") { + throw Components.Exception( + "aMethod must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + let managerListeners = new Set(this.managerListeners); + for (let listener of managerListeners) { + try { + if (aMethod in listener) { + listener[aMethod].apply(listener, aArgs); + } + } catch (e) { + logger.warn( + "AddonManagerListener threw exception when calling " + aMethod, + e + ); + } + } + }, + + /** + * Calls all registered InstallListeners with an event. Any parameters after + * the extraListeners parameter are passed to the listener. + * + * @param aMethod + * The method on the listeners to call + * @param aExtraListeners + * An optional array of extra InstallListeners to also call + * @return false if any of the listeners returned false, true otherwise + */ + callInstallListeners(aMethod, aExtraListeners, ...aArgs) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!aMethod || typeof aMethod != "string") { + throw Components.Exception( + "aMethod must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aExtraListeners && !Array.isArray(aExtraListeners)) { + throw Components.Exception( + "aExtraListeners must be an array or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + let result = true; + let listeners; + if (aExtraListeners) { + listeners = new Set( + aExtraListeners.concat(Array.from(this.installListeners)) + ); + } else { + listeners = new Set(this.installListeners); + } + + for (let listener of listeners) { + try { + if (aMethod in listener) { + if (listener[aMethod].apply(listener, aArgs) === false) { + result = false; + } + } + } catch (e) { + logger.warn( + "InstallListener threw exception when calling " + aMethod, + e + ); + } + } + return result; + }, + + /** + * Calls all registered AddonListeners with an event. Any parameters after + * the method parameter are passed to the listener. + * + * @param aMethod + * The method on the listeners to call + */ + callAddonListeners(aMethod, ...aArgs) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!aMethod || typeof aMethod != "string") { + throw Components.Exception( + "aMethod must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + let addonListeners = new Set(this.addonListeners); + for (let listener of addonListeners) { + try { + if (aMethod in listener) { + listener[aMethod].apply(listener, aArgs); + } + } catch (e) { + logger.warn("AddonListener threw exception when calling " + aMethod, e); + } + } + }, + + /** + * Notifies all providers that an add-on has been enabled when that type of + * add-on only supports a single add-on being enabled at a time. This allows + * the providers to disable theirs if necessary. + * + * @param aID + * The ID of the enabled add-on + * @param aType + * The type of the enabled add-on + * @param aPendingRestart + * A boolean indicating if the change will only take place the next + * time the application is restarted + */ + async notifyAddonChanged(aID, aType, aPendingRestart) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (aID && typeof aID != "string") { + throw Components.Exception( + "aID must be a string or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (!aType || typeof aType != "string") { + throw Components.Exception( + "aType must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + // Temporary hack until bug 520124 lands. + // We can get here during synchronous startup, at which point it's + // considered unsafe (and therefore disallowed by AddonManager.jsm) to + // access providers that haven't been initialized yet. Since this is when + // XPIProvider is starting up, XPIProvider can't access itself via APIs + // going through AddonManager.jsm. Thankfully, this is the only use + // of this API, and we know it's safe to use this API with both + // providers; so we have this hack to allow bypassing the normal + // safetey guard. + // The notifyAddonChanged/addonChanged API will be unneeded and therefore + // removed by bug 520124, so this is a temporary quick'n'dirty hack. + let providers = [...this.providers, ...this.pendingProviders]; + for (let provider of providers) { + let result = callProvider( + provider, + "addonChanged", + null, + aID, + aType, + aPendingRestart + ); + if (result) { + await result; + } + } + }, + + /** + * Notifies all providers they need to update the appDisabled property for + * their add-ons in response to an application change such as a blocklist + * update. + */ + updateAddonAppDisabledStates() { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + this.callProviders("updateAddonAppDisabledStates"); + }, + + /** + * Notifies all providers that the repository has updated its data for + * installed add-ons. + */ + updateAddonRepositoryData() { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + return (async () => { + for (let provider of this.providers) { + await promiseCallProvider(provider, "updateAddonRepositoryData"); + } + + // only tests should care about this + Services.obs.notifyObservers(null, "TEST:addon-repository-data-updated"); + })(); + }, + + /** + * Asynchronously gets an AddonInstall for a URL. + * + * @param aUrl + * The string represenation of the URL where the add-on is located + * @param {Object} [aOptions = {}] + * Additional options for this install + * @param {string} [aOptions.hash] + * An optional hash of the add-on + * @param {string} [aOptions.name] + * An optional placeholder name while the add-on is being downloaded + * @param {string|Object} [aOptions.icons] + * Optional placeholder icons while the add-on is being downloaded + * @param {string} [aOptions.version] + * An optional placeholder version while the add-on is being downloaded + * @param {XULElement} [aOptions.browser] + * An optional element for download permissions prompts. + * @param {nsIPrincipal} [aOptions.triggeringPrincipal] + * The principal which is attempting to install the add-on. + * @param {Object} [aOptions.telemetryInfo] + * An optional object which provides details about the installation source + * included in the addon manager telemetry events. + * @throws if aUrl is not specified or if an optional argument of + * an improper type is passed. + */ + async getInstallForURL(aUrl, aOptions = {}) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!aUrl || typeof aUrl != "string") { + throw Components.Exception( + "aURL must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aOptions.hash && typeof aOptions.hash != "string") { + throw Components.Exception( + "hash must be a string or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aOptions.name && typeof aOptions.name != "string") { + throw Components.Exception( + "name must be a string or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aOptions.icons) { + if (typeof aOptions.icons == "string") { + aOptions.icons = { "32": aOptions.icons }; + } else if (typeof aOptions.icons != "object") { + throw Components.Exception( + "icons must be a string, an object or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + } else { + aOptions.icons = {}; + } + + if (aOptions.version && typeof aOptions.version != "string") { + throw Components.Exception( + "version must be a string or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aOptions.browser && !Element.isInstance(aOptions.browser)) { + throw Components.Exception( + "aOptions.browser must be an Element or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + for (let provider of this.providers) { + let install = await promiseCallProvider( + provider, + "getInstallForURL", + aUrl, + aOptions + ); + if (install) { + return install; + } + } + + return null; + }, + + /** + * Asynchronously gets an AddonInstall for an nsIFile. + * + * @param aFile + * The nsIFile where the add-on is located + * @param aMimetype + * An optional mimetype hint for the add-on + * @param aTelemetryInfo + * An optional object which provides details about the installation source + * included in the addon manager telemetry events. + * @param aUseSystemLocation + * If true the addon is installed into the system profile location. + * @throws if the aFile or aCallback arguments are not specified + */ + getInstallForFile(aFile, aMimetype, aTelemetryInfo, aUseSystemLocation) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!(aFile instanceof Ci.nsIFile)) { + throw Components.Exception( + "aFile must be a nsIFile", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aMimetype && typeof aMimetype != "string") { + throw Components.Exception( + "aMimetype must be a string or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + return (async () => { + for (let provider of this.providers) { + let install = await promiseCallProvider( + provider, + "getInstallForFile", + aFile, + aTelemetryInfo, + aUseSystemLocation + ); + + if (install) { + return install; + } + } + + return null; + })(); + }, + + /** + * Get a SitePermsAddonInstall instance. + * + * @param {Element} aBrowser: The optional browser element that started the install + * @param {nsIPrincipal} aInstallingPrincipal + * @param {String} aSitePerm + * @returns {Promise} The promise will resolve with null if there + * are no provider with a getSitePermsAddonInstallForWebpage method. In practice, + * this should only be the case when SitePermsAddonProvider is not enabled, + * i.e. when dom.sitepermsaddon-provider.enabled is false. + * @throws {Components.Exception} Will throw an error if: + * - the AddonManager is not initialized + * - `aInstallingPrincipal` is not a nsIPrincipal + * - `aInstallingPrincipal` scheme is not https + * - `aInstallingPrincipal` is a public etld + * - `aInstallingPrincipal` is a plain ip address + * - `aInstallingPrincipal` is in the blocklist + * - `aSitePerm` is not a gated permission + * - `aBrowser` is not null and not an element + */ + async getSitePermsAddonInstallForWebpage( + aBrowser, + aInstallingPrincipal, + aSitePerm + ) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if ( + !aInstallingPrincipal || + !(aInstallingPrincipal instanceof Ci.nsIPrincipal) + ) { + throw Components.Exception( + "aInstallingPrincipal must be a nsIPrincipal", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aBrowser && !Element.isInstance(aBrowser)) { + throw Components.Exception( + "aBrowser must be an Element, or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (lazy.isPrincipalInSitePermissionsBlocklist(aInstallingPrincipal)) { + throw Components.Exception( + `SitePermsAddons can't be installed`, + Cr.NS_ERROR_INVALID_ARG + ); + } + + // Block install from null principal. + // /!\ We need to do this check before checking if this is a remote origin iframe, + // otherwise isThirdPartyPrincipal might throw. + if (aInstallingPrincipal.isNullPrincipal) { + throw Components.Exception( + `SitePermsAddons can't be installed from sandboxed subframes`, + Cr.NS_ERROR_INVALID_ARG + ); + } + + // Block install from remote origin iframe + if ( + aBrowser && + aBrowser.contentPrincipal.isThirdPartyPrincipal(aInstallingPrincipal) + ) { + throw Components.Exception( + `SitePermsAddons can't be installed from cross origin subframes`, + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aInstallingPrincipal.isIpAddress) { + throw Components.Exception( + `SitePermsAddons install disallowed when the host is an IP address`, + Cr.NS_ERROR_INVALID_ARG + ); + } + + // Gated APIs should probably not be available on non-secure origins, + // but let's double check here. + if (aInstallingPrincipal.scheme !== "https") { + throw Components.Exception( + `SitePermsAddons can only be installed from secure origins`, + Cr.NS_ERROR_INVALID_ARG + ); + } + + // Install origin cannot be on a known etld (e.g. github.io). + if (lazy.isKnownPublicSuffix(aInstallingPrincipal.siteOriginNoSuffix)) { + throw Components.Exception( + `SitePermsAddon can't be installed from public eTLDs ${aInstallingPrincipal.siteOriginNoSuffix}`, + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (!lazy.isGatedPermissionType(aSitePerm)) { + throw Components.Exception( + `"${aSitePerm}" is not a gated permission`, + Cr.NS_ERROR_INVALID_ARG + ); + } + + for (let provider of this.providers) { + let install = await promiseCallProvider( + provider, + "getSitePermsAddonInstallForWebpage", + aInstallingPrincipal, + aSitePerm + ); + if (install) { + return install; + } + } + + return null; + }, + + /** + * Uninstall an addon from the system profile location. + * + * @param {string} aID + * The ID of the addon to remove. + * @returns A promise that resolves when the addon is uninstalled. + */ + uninstallSystemProfileAddon(aID) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + return AddonManagerInternal._getProviderByName( + "XPIProvider" + ).uninstallSystemProfileAddon(aID); + }, + + /** + * Asynchronously gets all current AddonInstalls optionally limiting to a list + * of types. + * + * @param aTypes + * An optional array of types to retrieve. Each type is a string name + * @throws If the aCallback argument is not specified + */ + getInstallsByTypes(aTypes) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (aTypes && !Array.isArray(aTypes)) { + throw Components.Exception( + "aTypes must be an array or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + return (async () => { + let installs = []; + + for (let provider of this.providers) { + let providerInstalls = await promiseCallProvider( + provider, + "getInstallsByTypes", + aTypes + ); + + if (providerInstalls) { + installs.push(...providerInstalls); + } + } + + return installs; + })(); + }, + + /** + * Asynchronously gets all current AddonInstalls. + */ + getAllInstalls() { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + return this.getInstallsByTypes(null); + }, + + /** + * Checks whether installation is enabled for a particular mimetype. + * + * @param aMimetype + * The mimetype to check + * @return true if installation is enabled for the mimetype + */ + isInstallEnabled(aMimetype) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!aMimetype || typeof aMimetype != "string") { + throw Components.Exception( + "aMimetype must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + let providers = [...this.providers]; + for (let provider of providers) { + if ( + callProvider(provider, "supportsMimetype", false, aMimetype) && + callProvider(provider, "isInstallEnabled") + ) { + return true; + } + } + return false; + }, + + /** + * Checks whether a particular source is allowed to install add-ons of a + * given mimetype. + * + * @param aMimetype + * The mimetype of the add-on + * @param aInstallingPrincipal + * The nsIPrincipal that initiated the install + * @return true if the source is allowed to install this mimetype + */ + isInstallAllowed(aMimetype, aInstallingPrincipal) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!aMimetype || typeof aMimetype != "string") { + throw Components.Exception( + "aMimetype must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if ( + !aInstallingPrincipal || + !(aInstallingPrincipal instanceof Ci.nsIPrincipal) + ) { + throw Components.Exception( + "aInstallingPrincipal must be a nsIPrincipal", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if ( + this.isInstallAllowedByPolicy( + aInstallingPrincipal, + null, + true /* explicit */ + ) + ) { + return true; + } + + let providers = [...this.providers]; + for (let provider of providers) { + if ( + callProvider(provider, "supportsMimetype", false, aMimetype) && + callProvider(provider, "isInstallAllowed", null, aInstallingPrincipal) + ) { + return true; + } + } + return false; + }, + + /** + * Checks whether a particular source is allowed to install add-ons based + * on policy. + * + * @param aInstallingPrincipal + * The nsIPrincipal that initiated the install + * @param aInstall + * The AddonInstall to be installed + * @param explicit + * If this is set, we only return true if the source is explicitly + * blocked via policy. + * + * @return boolean + * By default, returns true if the source is blocked by policy + * or there is no policy. + * If explicit is set, only returns true of the source is + * blocked by policy, false otherwise. This is needed for + * handling inverse cases. + */ + isInstallAllowedByPolicy(aInstallingPrincipal, aInstall, explicit) { + if (Services.policies) { + let extensionSettings = Services.policies.getExtensionSettings("*"); + if (extensionSettings && extensionSettings.install_sources) { + if ( + (!aInstall || + Services.policies.allowedInstallSource(aInstall.sourceURI)) && + (!aInstallingPrincipal || + !aInstallingPrincipal.URI || + Services.policies.allowedInstallSource(aInstallingPrincipal.URI)) + ) { + return true; + } + return false; + } + } + return !explicit; + }, + + installNotifyObservers( + aTopic, + aBrowser, + aUri, + aInstall, + aInstallFn, + aCancelFn + ) { + let info = { + wrappedJSObject: { + browser: aBrowser, + originatingURI: aUri, + installs: [aInstall], + install: aInstallFn, + cancel: aCancelFn, + }, + }; + Services.obs.notifyObservers(info, aTopic); + }, + + startInstall(browser, url, install) { + this.installNotifyObservers("addon-install-started", browser, url, install); + + // Local installs may already be in a failed state in which case + // we won't get any further events, detect those cases now. + if ( + install.state == AddonManager.STATE_DOWNLOADED && + install.addon.appDisabled + ) { + install.cancel(); + this.installNotifyObservers( + "addon-install-failed", + browser, + url, + install + ); + return; + } + + let self = this; + let listener = { + onDownloadCancelled() { + install.removeListener(listener); + }, + + onDownloadFailed() { + install.removeListener(listener); + self.installNotifyObservers( + "addon-install-failed", + browser, + url, + install + ); + }, + + onDownloadEnded() { + if (install.addon.appDisabled) { + // App disabled items are not compatible and so fail to install. + install.removeListener(listener); + install.cancel(); + self.installNotifyObservers( + "addon-install-failed", + browser, + url, + install + ); + } + }, + + onInstallCancelled() { + install.removeListener(listener); + }, + + onInstallFailed() { + install.removeListener(listener); + self.installNotifyObservers( + "addon-install-failed", + browser, + url, + install + ); + }, + + onInstallEnded() { + install.removeListener(listener); + + // If installing a theme that is disabled and can be enabled + // then enable it + if ( + install.addon.type == "theme" && + !!install.addon.userDisabled && + !install.addon.appDisabled + ) { + install.addon.enable(); + } + + let needsRestart = + install.addon.pendingOperations != AddonManager.PENDING_NONE; + + if (!needsRestart) { + let subject = { + wrappedJSObject: { target: browser, addon: install.addon }, + }; + Services.obs.notifyObservers(subject, "webextension-install-notify"); + } else { + self.installNotifyObservers( + "addon-install-complete", + browser, + url, + install + ); + } + }, + }; + + install.addListener(listener); + + // Start downloading if it hasn't already begun + install.install(); + }, + + /** + * Starts installation of a SitePermsAddonInstall notifying the registered + * web install listener of a blocked or started install. + * + * @param aBrowser + * The optional browser element that started the install + * @param aInstallingPrincipal + * The nsIPrincipal that initiated the install + * @param aPermission + * The permission to install + * @returns {Promise} A promise that will resolve when the user installs the addon. + * The promise will reject if the user blocked the install, or if the addon + * can't be installed (e.g. the principal isn't supported). + * @throws {Components.Exception} Will throw an error if the AddonManager is not initialized + * or if `aInstallingPrincipal` is not a nsIPrincipal. + */ + async installSitePermsAddonFromWebpage( + aBrowser, + aInstallingPrincipal, + aPermission + ) { + const synthAddonInstall = await AddonManagerInternal.getSitePermsAddonInstallForWebpage( + aBrowser, + aInstallingPrincipal, + aPermission + ); + const promiseInstall = new Promise((resolve, reject) => { + const installListener = { + onInstallFailed() { + synthAddonInstall.removeListener(installListener); + reject(new Error("Install Failed")); + }, + + onInstallCancelled() { + synthAddonInstall.removeListener(installListener); + reject(new Error("Install Cancelled")); + }, + + onInstallEnded() { + synthAddonInstall.removeListener(installListener); + resolve(); + }, + }; + synthAddonInstall.addListener(installListener); + }); + + let startInstall = () => { + AddonManagerInternal.setupPromptHandler( + aBrowser, + aInstallingPrincipal.URI, + synthAddonInstall, + true, + "SitePermissionAddonPrompt" + ); + + AddonManagerInternal.startInstall( + aBrowser, + aInstallingPrincipal.URI, + synthAddonInstall + ); + }; + + startInstall(); + + return promiseInstall; + }, + + /** + * Starts installation of an AddonInstall notifying the registered + * web install listener of a blocked or started install. + * + * @param aMimetype + * The mimetype of the add-on being installed + * @param aBrowser + * The optional browser element that started the install + * @param aInstallingPrincipal + * The nsIPrincipal that initiated the install + * @param aInstall + * The AddonInstall to be installed + * @param [aDetails] + * Additional optional details + * @param [aDetails.hasCrossOriginAncestor] + * Boolean value set to true if any of cross-origin ancestors of the triggering frame + * (if set to true the installation will be denied). + */ + installAddonFromWebpage( + aMimetype, + aBrowser, + aInstallingPrincipal, + aInstall, + aDetails + ) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!aMimetype || typeof aMimetype != "string") { + throw Components.Exception( + "aMimetype must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aBrowser && !Element.isInstance(aBrowser)) { + throw Components.Exception( + "aSource must be an Element, or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if ( + !aInstallingPrincipal || + !(aInstallingPrincipal instanceof Ci.nsIPrincipal) + ) { + throw Components.Exception( + "aInstallingPrincipal must be a nsIPrincipal", + Cr.NS_ERROR_INVALID_ARG + ); + } + + // When a chrome in-content UI has loaded a inside to host a + // website we want to do our security checks on the inner-browser but + // notify front-end that install events came from the outer-browser (the + // main tab's browser). Check this by seeing if the browser we've been + // passed is in a content type docshell and if so get the outer-browser. + let topBrowser = aBrowser; + // GeckoView does not pass a browser. + if (aBrowser) { + let docShell = aBrowser.ownerGlobal.docShell; + if (docShell.itemType == Ci.nsIDocShellTreeItem.typeContent) { + topBrowser = docShell.chromeEventHandler; + } + } + + try { + // Use fullscreenElement to check for DOM fullscreen, while still allowing + // macOS fullscreen, which still has a browser chrome. + if (topBrowser && topBrowser.ownerDocument.fullscreenElement) { + // Addon installation and the resulting notifications should be + // blocked in DOM fullscreen for security and usability reasons. + // Installation prompts in fullscreen can trick the user into + // installing unwanted addons. + // In fullscreen the notification box does not have a clear + // visual association with its parent anymore. + aInstall.cancel(); + + this.installNotifyObservers( + "addon-install-fullscreen-blocked", + topBrowser, + aInstallingPrincipal.URI, + aInstall + ); + return; + } else if (!this.isInstallEnabled(aMimetype)) { + aInstall.cancel(); + + this.installNotifyObservers( + "addon-install-disabled", + topBrowser, + aInstallingPrincipal.URI, + aInstall + ); + return; + } else if ( + !this.isInstallAllowedByPolicy( + aInstallingPrincipal, + aInstall, + false /* explicit */ + ) + ) { + aInstall.cancel(); + + this.installNotifyObservers( + "addon-install-policy-blocked", + topBrowser, + aInstallingPrincipal.URI, + aInstall + ); + return; + } else if ( + // Block the install request if the triggering frame does have any cross-origin + // ancestor. + aDetails?.hasCrossOriginAncestor || + // Block the install if triggered by a null principal. + aInstallingPrincipal.isNullPrincipal || + (aBrowser && + (!aBrowser.contentPrincipal || + // When we attempt to handle an XPI load immediately after a + // process switch, the DocShell it's being loaded into will have + // a null principal, since it won't have been initialized yet. + // Allowing installs in this case is relatively safe, since + // there isn't much to gain by spoofing an install request from + // a null principal in any case. This exception can be removed + // once content handlers are triggered by DocumentChannel in the + // parent process. + !( + aBrowser.contentPrincipal.isNullPrincipal || + aInstallingPrincipal.subsumes(aBrowser.contentPrincipal) + ))) + ) { + aInstall.cancel(); + + this.installNotifyObservers( + "addon-install-origin-blocked", + topBrowser, + aInstallingPrincipal.URI, + aInstall + ); + return; + } + + if (aBrowser) { + // The install may start now depending on the web install listener, + // listen for the browser navigating to a new origin and cancel the + // install in that case. + new BrowserListener(aBrowser, aInstallingPrincipal, aInstall); + } + + let startInstall = source => { + AddonManagerInternal.setupPromptHandler( + aBrowser, + aInstallingPrincipal.URI, + aInstall, + true, + source + ); + + AddonManagerInternal.startInstall( + aBrowser, + aInstallingPrincipal.URI, + aInstall + ); + }; + + let installAllowed = this.isInstallAllowed( + aMimetype, + aInstallingPrincipal + ); + let installPerm = Services.perms.testPermissionFromPrincipal( + aInstallingPrincipal, + "install" + ); + + if (installAllowed) { + startInstall("AMO"); + } else if (installPerm === Ci.nsIPermissionManager.DENY_ACTION) { + // Block without prompt + aInstall.cancel(); + this.installNotifyObservers( + "addon-install-blocked-silent", + topBrowser, + aInstallingPrincipal.URI, + aInstall + ); + } else if (!lazy.WEBEXT_POSTDOWNLOAD_THIRD_PARTY) { + // Block with prompt + this.installNotifyObservers( + "addon-install-blocked", + topBrowser, + aInstallingPrincipal.URI, + aInstall, + () => startInstall("other"), + () => aInstall.cancel() + ); + } else { + // We download the addon and validate whether a 3rd party + // install prompt should be shown using e.g. recommended + // state and install_origins. + logger.info(`Addon download before validation.`); + startInstall("other"); + } + } catch (e) { + // In the event that the weblistener throws during instantiation or when + // calling onWebInstallBlocked or onWebInstallRequested the + // install should get cancelled. + logger.warn("Failure calling web installer", e); + aInstall.cancel(); + } + }, + + /** + * Starts installation of an AddonInstall created from add-ons manager + * front-end code (e.g., drag-and-drop of xpis or "Install Add-on from File" + * + * @param browser + * The browser element where the installation was initiated + * @param uri + * The URI of the page where the installation was initiated + * @param install + * The AddonInstall to be installed + */ + installAddonFromAOM(browser, uri, install) { + if (!this.isInstallAllowedByPolicy(null, install)) { + install.cancel(); + + this.installNotifyObservers( + "addon-install-policy-blocked", + browser, + install.sourceURI, + install + ); + return; + } + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + AddonManagerInternal.setupPromptHandler( + browser, + uri, + install, + true, + "local" + ); + AddonManagerInternal.startInstall(browser, uri, install); + }, + + /** + * Adds a new InstallListener if the listener is not already registered. + * + * @param aListener + * The InstallListener to add + */ + addInstallListener(aListener) { + if (!aListener || typeof aListener != "object") { + throw Components.Exception( + "aListener must be a InstallListener object", + Cr.NS_ERROR_INVALID_ARG + ); + } + + this.installListeners.add(aListener); + }, + + /** + * Removes an InstallListener if the listener is registered. + * + * @param aListener + * The InstallListener to remove + */ + removeInstallListener(aListener) { + if (!aListener || typeof aListener != "object") { + throw Components.Exception( + "aListener must be a InstallListener object", + Cr.NS_ERROR_INVALID_ARG + ); + } + + this.installListeners.delete(aListener); + }, + /** + * Adds new or overrides existing UpgradeListener. + * + * @param aInstanceID + * The instance ID of an addon to register a listener for. + * @param aCallback + * The callback to invoke when updates are available for this addon. + * @throws if there is no addon matching the instanceID + */ + addUpgradeListener(aInstanceID, aCallback) { + if (!aInstanceID || typeof aInstanceID != "symbol") { + throw Components.Exception( + "aInstanceID must be a symbol", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (!aCallback || typeof aCallback != "function") { + throw Components.Exception( + "aCallback must be a function", + Cr.NS_ERROR_INVALID_ARG + ); + } + + let addonId = this.syncGetAddonIDByInstanceID(aInstanceID); + if (!addonId) { + throw Error(`No addon matching instanceID: ${String(aInstanceID)}`); + } + logger.debug(`Registering upgrade listener for ${addonId}`); + this.upgradeListeners.set(addonId, aCallback); + }, + + /** + * Removes an UpgradeListener if the listener is registered. + * + * @param aInstanceID + * The instance ID of the addon to remove + */ + removeUpgradeListener(aInstanceID) { + if (!aInstanceID || typeof aInstanceID != "symbol") { + throw Components.Exception( + "aInstanceID must be a symbol", + Cr.NS_ERROR_INVALID_ARG + ); + } + + let addonId = this.syncGetAddonIDByInstanceID(aInstanceID); + if (!addonId) { + throw Error(`No addon for instanceID: ${aInstanceID}`); + } + if (this.upgradeListeners.has(addonId)) { + this.upgradeListeners.delete(addonId); + } else { + throw Error(`No upgrade listener registered for addon ID: ${addonId}`); + } + }, + + addExternalExtensionLoader(loader) { + this.externalExtensionLoaders.set(loader.name, loader); + }, + + /** + * Installs a temporary add-on from a local file or directory. + * + * @param aFile + * An nsIFile for the file or directory of the add-on to be + * temporarily installed. + * @returns a Promise that rejects if the add-on is not a valid restartless + * add-on or if the same ID is already temporarily installed. + */ + installTemporaryAddon(aFile) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!(aFile instanceof Ci.nsIFile)) { + throw Components.Exception( + "aFile must be a nsIFile", + Cr.NS_ERROR_INVALID_ARG + ); + } + + return AddonManagerInternal._getProviderByName( + "XPIProvider" + ).installTemporaryAddon(aFile); + }, + + /** + * Installs an add-on from a built-in location + * (ie a resource: url referencing assets shipped with the application) + * + * @param aBase + * A string containing the base URL. Must be a resource: URL. + * @returns a Promise that resolves when the addon is installed. + */ + installBuiltinAddon(aBase) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + return AddonManagerInternal._getProviderByName( + "XPIProvider" + ).installBuiltinAddon(aBase); + }, + + /** + * Like `installBuiltinAddon`, but only installs the addon at `aBase` + * if an existing built-in addon with the ID `aID` and version doesn't + * already exist. + * + * @param {string} aID + * The ID of the add-on being registered. + * @param {string} aVersion + * The version of the add-on being registered. + * @param {string} aBase + * A string containing the base URL. Must be a resource: URL. + * @returns a Promise that resolves when the addon is installed. + */ + maybeInstallBuiltinAddon(aID, aVersion, aBase) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + return AddonManagerInternal._getProviderByName( + "XPIProvider" + ).maybeInstallBuiltinAddon(aID, aVersion, aBase); + }, + + syncGetAddonIDByInstanceID(aInstanceID) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!aInstanceID || typeof aInstanceID != "symbol") { + throw Components.Exception( + "aInstanceID must be a Symbol()", + Cr.NS_ERROR_INVALID_ARG + ); + } + + return AddonManagerInternal._getProviderByName( + "XPIProvider" + ).getAddonIDByInstanceID(aInstanceID); + }, + + /** + * Gets an icon from the icon set provided by the add-on + * that is closest to the specified size. + * + * The optional window parameter will be used to determine + * the screen resolution and select a more appropriate icon. + * Calling this method with 48px on retina screens will try to + * match an icon of size 96px. + * + * @param aAddon + * An addon object, meaning: + * An object with either an icons property that is a key-value list + * of icon size and icon URL, or an object having an iconURL property. + * @param aSize + * Ideal icon size in pixels + * @param aWindow + * Optional window object for determining the correct scale. + * @return {String} The absolute URL of the icon or null if the addon doesn't have icons + */ + getPreferredIconURL(aAddon, aSize, aWindow = undefined) { + if (aWindow && aWindow.devicePixelRatio) { + aSize *= aWindow.devicePixelRatio; + } + + let icons = aAddon.icons; + + // certain addon-types only have iconURLs + if (!icons) { + icons = {}; + if (aAddon.iconURL) { + icons[32] = aAddon.iconURL; + icons[48] = aAddon.iconURL; + } + } + + // quick return if the exact size was found + if (icons[aSize]) { + return icons[aSize]; + } + + let bestSize = null; + + for (let size of Object.keys(icons)) { + if (!INTEGER.test(size)) { + throw Components.Exception( + "Invalid icon size, must be an integer", + Cr.NS_ERROR_ILLEGAL_VALUE + ); + } + + size = parseInt(size, 10); + + if (!bestSize) { + bestSize = size; + continue; + } + + if (size > aSize && bestSize > aSize) { + // If both best size and current size are larger than the wanted size then choose + // the one closest to the wanted size + bestSize = Math.min(bestSize, size); + } else { + // Otherwise choose the largest of the two so we'll prefer sizes as close to below aSize + // or above aSize + bestSize = Math.max(bestSize, size); + } + } + + return icons[bestSize] || null; + }, + + /** + * Asynchronously gets an add-on with a specific ID. + * + * @type {function} + * @param {string} aID + * The ID of the add-on to retrieve + * @returns {Promise} resolves with the found Addon or null if no such add-on exists. Never rejects. + * @throws if the aID argument is not specified + */ + getAddonByID(aID) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!aID || typeof aID != "string") { + throw Components.Exception( + "aID must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + let promises = Array.from(this.providers, p => + promiseCallProvider(p, "getAddonByID", aID) + ); + return Promise.all(promises).then(aAddons => { + return aAddons.find(a => !!a) || null; + }); + }, + + /** + * Asynchronously get an add-on with a specific Sync GUID. + * + * @param aGUID + * String GUID of add-on to retrieve + * @throws if the aGUID argument is not specified + */ + getAddonBySyncGUID(aGUID) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!aGUID || typeof aGUID != "string") { + throw Components.Exception( + "aGUID must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + return (async () => { + for (let provider of this.providers) { + let addon = await promiseCallProvider( + provider, + "getAddonBySyncGUID", + aGUID + ); + + if (addon) { + return addon; + } + } + + return null; + })(); + }, + + /** + * Asynchronously gets an array of add-ons. + * + * @param aIDs + * The array of IDs to retrieve + * @return {Promise} + * @resolves The array of found add-ons. + * @rejects Never + * @throws if the aIDs argument is not specified + */ + getAddonsByIDs(aIDs) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!Array.isArray(aIDs)) { + throw Components.Exception( + "aIDs must be an array", + Cr.NS_ERROR_INVALID_ARG + ); + } + + let promises = aIDs.map(a => AddonManagerInternal.getAddonByID(a)); + return Promise.all(promises); + }, + + /** + * Asynchronously gets add-ons of specific types. + * + * @param aTypes + * An optional array of types to retrieve. Each type is a string name + */ + getAddonsByTypes(aTypes) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (aTypes && !Array.isArray(aTypes)) { + throw Components.Exception( + "aTypes must be an array or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + return (async () => { + let addons = []; + + for (let provider of this.providers) { + let providerAddons = await promiseCallProvider( + provider, + "getAddonsByTypes", + aTypes + ); + + if (providerAddons) { + addons.push(...providerAddons); + } + } + + return addons; + })(); + }, + + /** + * Gets active add-ons of specific types. + * + * This is similar to getAddonsByTypes() but it may return a limited + * amount of information about only active addons. Consequently, it + * can be implemented by providers using only immediately available + * data as opposed to getAddonsByTypes which may require I/O). + * + * @param aTypes + * An optional array of types to retrieve. Each type is a string name + * + * @resolve {addons: Array, fullData: bool} + * fullData is true if addons contains all the data we have on those + * addons. It is false if addons only contains partial data. + */ + async getActiveAddons(aTypes) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (aTypes && !Array.isArray(aTypes)) { + throw Components.Exception( + "aTypes must be an array or null", + Cr.NS_ERROR_INVALID_ARG + ); + } + + let addons = [], + fullData = true; + + for (let provider of this.providers) { + let providerAddons, providerFullData; + if ("getActiveAddons" in provider) { + ({ + addons: providerAddons, + fullData: providerFullData, + } = await callProvider(provider, "getActiveAddons", null, aTypes)); + } else { + providerAddons = await promiseCallProvider( + provider, + "getAddonsByTypes", + aTypes + ); + providerAddons = providerAddons.filter(a => a.isActive); + providerFullData = true; + } + + if (providerAddons) { + addons.push(...providerAddons); + fullData = fullData && providerFullData; + } + } + + return { addons, fullData }; + }, + + /** + * Asynchronously gets all installed add-ons. + */ + getAllAddons() { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + return this.getAddonsByTypes(null); + }, + + /** + * Adds a new AddonManagerListener if the listener is not already registered. + * + * @param {AddonManagerListener} aListener + * The listener to add + */ + addManagerListener(aListener) { + if (!aListener || typeof aListener != "object") { + throw Components.Exception( + "aListener must be an AddonManagerListener object", + Cr.NS_ERROR_INVALID_ARG + ); + } + + this.managerListeners.add(aListener); + }, + + /** + * Removes an AddonManagerListener if the listener is registered. + * + * @param {AddonManagerListener} aListener + * The listener to remove + */ + removeManagerListener(aListener) { + if (!aListener || typeof aListener != "object") { + throw Components.Exception( + "aListener must be an AddonManagerListener object", + Cr.NS_ERROR_INVALID_ARG + ); + } + + this.managerListeners.delete(aListener); + }, + + /** + * Adds a new AddonListener if the listener is not already registered. + * + * @param {AddonManagerListener} aListener + * The AddonListener to add. + */ + addAddonListener(aListener) { + if (!aListener || typeof aListener != "object") { + throw Components.Exception( + "aListener must be an AddonListener object", + Cr.NS_ERROR_INVALID_ARG + ); + } + + this.addonListeners.add(aListener); + }, + + /** + * Removes an AddonListener if the listener is registered. + * + * @param {object} aListener + * The AddonListener to remove + */ + removeAddonListener(aListener) { + if (!aListener || typeof aListener != "object") { + throw Components.Exception( + "aListener must be an AddonListener object", + Cr.NS_ERROR_INVALID_ARG + ); + } + + this.addonListeners.delete(aListener); + }, + + /** + * @param {string} addonType + * @returns {boolean} + * Whether there is a provider that provides the given addon type. + */ + hasAddonType(addonType) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + for (let addonTypes of this.typesByProvider.values()) { + if (addonTypes.has(addonType)) { + return true; + } + } + return false; + }, + + get autoUpdateDefault() { + return gAutoUpdateDefault; + }, + + set autoUpdateDefault(aValue) { + aValue = !!aValue; + if (aValue != gAutoUpdateDefault) { + Services.prefs.setBoolPref(PREF_EM_AUTOUPDATE_DEFAULT, aValue); + } + }, + + get checkCompatibility() { + return gCheckCompatibility; + }, + + set checkCompatibility(aValue) { + aValue = !!aValue; + if (aValue != gCheckCompatibility) { + if (!aValue) { + Services.prefs.setBoolPref(PREF_EM_CHECK_COMPATIBILITY, false); + } else { + Services.prefs.clearUserPref(PREF_EM_CHECK_COMPATIBILITY); + } + } + }, + + get strictCompatibility() { + return gStrictCompatibility; + }, + + set strictCompatibility(aValue) { + aValue = !!aValue; + if (aValue != gStrictCompatibility) { + Services.prefs.setBoolPref(PREF_EM_STRICT_COMPATIBILITY, aValue); + } + }, + + get checkUpdateSecurityDefault() { + return gCheckUpdateSecurityDefault; + }, + + get checkUpdateSecurity() { + return gCheckUpdateSecurity; + }, + + set checkUpdateSecurity(aValue) { + aValue = !!aValue; + if (aValue != gCheckUpdateSecurity) { + if (aValue != gCheckUpdateSecurityDefault) { + Services.prefs.setBoolPref(PREF_EM_CHECK_UPDATE_SECURITY, aValue); + } else { + Services.prefs.clearUserPref(PREF_EM_CHECK_UPDATE_SECURITY); + } + } + }, + + get updateEnabled() { + return gUpdateEnabled; + }, + + set updateEnabled(aValue) { + aValue = !!aValue; + if (aValue != gUpdateEnabled) { + Services.prefs.setBoolPref(PREF_EM_UPDATE_ENABLED, aValue); + } + }, + + /** + * Verify whether we need to show the 3rd party install prompt. + * + * Bypass the third party install prompt if this is an install: + * - is an install from a recognized source + * - is a an addon that can bypass the panel, such as a recommended addon + * + * @param {browser} browser browser user is installing from + * @param {nsIURI} url URI for the principal of the installing source + * @param {AddonInstallWrapper} install + * @param {Object} info information such as addon wrapper + * @param {AddonWrapper} info.addon + * @param {string} source simplified string describing source of install and is + * generated based on the installing principal and checking + * against site permissions and enterprise policy. + * It may be one of "AMO", "local" or "other". + * @returns {Promise} Rejected when the installation should not proceed. + */ + _verifyThirdPartyInstall(browser, url, install, info, source) { + // If we are not post-download processing, this panel was already shown. + // Otherwise, if this is from AMO or local, bypass the prompt. + if ( + !lazy.WEBEXT_POSTDOWNLOAD_THIRD_PARTY || + ["AMO", "local"].includes(source) + ) { + return Promise.resolve(); + } + + // verify both the installing source and the xpi url are allowed. + if ( + !info.addon.validInstallOrigins({ + installFrom: url, + source: install.sourceURI, + }) + ) { + install.error = AddonManager.ERROR_INVALID_DOMAIN; + return Promise.reject(); + } + + // Some addons such as recommended addons do not result in this prompt. + if (info.addon.canBypassThirdParyInstallPrompt) { + return Promise.resolve(); + } + + return new Promise((resolve, reject) => { + this.installNotifyObservers( + "addon-install-blocked", + browser, + url, + install, + resolve, + reject + ); + }); + }, + + setupPromptHandler(browser, url, install, requireConfirm, source) { + install.promptHandler = info => + new Promise((resolve, reject) => { + this._verifyThirdPartyInstall(browser, url, install, info, source) + .then(() => { + // All installs end up in this callback when the add-on is available + // for installation. There are numerous different things that can + // happen from here though. For webextensions, if the application + // implements webextension permission prompts, those always take + // precedence. + // If this add-on is not a webextension or if the application does not + // implement permission prompts, no confirmation is displayed for + // installs created from about:addons (in which case requireConfirm + // is false). + // In the remaining cases, a confirmation prompt is displayed but the + // application may override it either by implementing the + // "@mozilla.org/addons/web-install-prompt;1" contract or by setting + // the customConfirmationUI preference and responding to the + // "addon-install-confirmation" notification. If the application + // does not implement its own prompt, use the built-in xul dialog. + if (info.addon.userPermissions) { + let subject = { + wrappedJSObject: { + target: browser, + info: Object.assign({ resolve, reject, source }, info), + }, + }; + subject.wrappedJSObject.info.permissions = + info.addon.userPermissions; + Services.obs.notifyObservers( + subject, + "webextension-permission-prompt" + ); + } else if (info.addon.sitePermissions) { + // Handle prompting for DOM permissions in SitePermission addons. + let { sitePermissions, siteOrigin } = info.addon; + let subject = { + wrappedJSObject: { + target: browser, + info: Object.assign( + { resolve, reject, source, sitePermissions, siteOrigin }, + info + ), + }, + }; + Services.obs.notifyObservers( + subject, + "webextension-permission-prompt" + ); + } else if (requireConfirm) { + // The methods below all want to call the install() or cancel() + // method on the provided AddonInstall object to either accept + // or reject the confirmation. Fit that into our promise-based + // control flow by wrapping the install object. However, + // xpInstallConfirm.xul matches the install object it is passed + // with the argument passed to an InstallListener, so give it + // access to the underlying object through the .wrapped property. + let proxy = new Proxy(install, { + get(target, property) { + if (property == "install") { + return resolve; + } else if (property == "cancel") { + return reject; + } else if (property == "wrapped") { + return target; + } + let result = target[property]; + return typeof result == "function" + ? result.bind(target) + : result; + }, + }); + + // Check for a custom installation prompt that may be provided by the + // applicaton + if ("@mozilla.org/addons/web-install-prompt;1" in Cc) { + try { + let prompt = Cc[ + "@mozilla.org/addons/web-install-prompt;1" + ].getService(Ci.amIWebInstallPrompt); + prompt.confirm(browser, url, [proxy]); + return; + } catch (e) {} + } + + this.installNotifyObservers( + "addon-install-confirmation", + browser, + url, + proxy + ); + } else { + resolve(); + } + }) + .catch(e => { + // Error is undefined if the promise was rejected. + if (e) { + Cu.reportError(`Install prompt handler error: ${e}`); + } + reject(); + }); + }); + }, + + webAPI: { + // installs maps integer ids to AddonInstall instances. + installs: new Map(), + nextInstall: 0, + + sendEvent: null, + setEventHandler(fn) { + this.sendEvent = fn; + }, + + async getAddonByID(target, id) { + return webAPIForAddon(await AddonManager.getAddonByID(id)); + }, + + // helper to copy (and convert) the properties we care about + copyProps(install, obj) { + obj.state = AddonManager.stateToString(install.state); + obj.error = AddonManager.errorToString(install.error); + obj.progress = install.progress; + obj.maxProgress = install.maxProgress; + }, + + forgetInstall(id) { + let info = this.installs.get(id); + if (!info) { + throw new Error(`forgetInstall cannot find ${id}`); + } + info.install.removeListener(info.listener); + this.installs.delete(id); + }, + + createInstall(target, options) { + // Throw an appropriate error if the given URL is not valid + // as an installation source. Return silently if it is okay. + function checkInstallUri(uri) { + if (!Services.policies.allowedInstallSource(uri)) { + // eslint-disable-next-line no-throw-literal + return { + success: false, + code: "addon-install-policy-blocked", + message: `Install from ${uri.spec} not permitted by policy`, + }; + } + + if (WEBAPI_INSTALL_HOSTS.includes(uri.host)) { + return { success: true }; + } + if ( + Services.prefs.getBoolPref(PREF_WEBAPI_TESTING, false) && + WEBAPI_TEST_INSTALL_HOSTS.includes(uri.host) + ) { + return { success: true }; + } + + // eslint-disable-next-line no-throw-literal + return { + success: false, + code: "addon-install-webapi-blocked", + message: `Install from ${uri.host} not permitted`, + }; + } + + const makeListener = (id, mm) => { + const events = [ + "onDownloadStarted", + "onDownloadProgress", + "onDownloadEnded", + "onDownloadCancelled", + "onDownloadFailed", + "onInstallStarted", + "onInstallEnded", + "onInstallCancelled", + "onInstallFailed", + ]; + + let listener = {}; + let installPromise = new Promise((resolve, reject) => { + events.forEach(event => { + listener[event] = (install, addon) => { + let data = { event, id }; + AddonManager.webAPI.copyProps(install, data); + this.sendEvent(mm, data); + if (event == "onInstallEnded") { + resolve(addon); + } else if ( + event == "onDownloadFailed" || + event == "onInstallFailed" + ) { + reject({ message: "install failed" }); + } else if ( + event == "onDownloadCancelled" || + event == "onInstallCancelled" + ) { + reject({ message: "install cancelled" }); + } else if (event == "onDownloadEnded") { + if (install.addon.appDisabled) { + // App disabled items are not compatible and so fail to install + install.cancel(); + AddonManagerInternal.installNotifyObservers( + "addon-install-failed", + target, + Services.io.newURI(options.url), + install + ); + } + } + }; + }); + }); + + // We create the promise here since this is where we're setting + // up the InstallListener, but if the install is never started, + // no handlers will be attached so make sure we terminate errors. + installPromise.catch(() => {}); + + return { listener, installPromise }; + }; + + let uri; + try { + uri = Services.io.newURI(options.url); + const { success, code, message } = checkInstallUri(uri); + if (!success) { + let info = { + wrappedJSObject: { + browser: target, + originatingURI: uri, + installs: [], + }, + }; + Cu.reportError(`${code}: ${message}`); + Services.obs.notifyObservers(info, code); + return Promise.reject({ code, message }); + } + } catch (err) { + // Reject Components.Exception errors (e.g. NS_ERROR_MALFORMED_URI) as is. + if (err instanceof Components.Exception) { + return Promise.reject({ message: err.message }); + } + return Promise.reject({ + message: "Install Failed on unexpected error", + }); + } + + return AddonManagerInternal.getInstallForURL(options.url, { + browser: target, + triggeringPrincipal: options.triggeringPrincipal, + hash: options.hash, + telemetryInfo: { + source: AddonManager.getInstallSourceFromHost(options.sourceHost), + sourceURL: options.sourceURL, + method: "amWebAPI", + }, + }).then(install => { + let requireConfirm = true; + if ( + target.contentDocument && + target.contentDocument.nodePrincipal.isSystemPrincipal + ) { + requireConfirm = false; + } + AddonManagerInternal.setupPromptHandler( + target, + null, + install, + requireConfirm, + "AMO" + ); + + let id = this.nextInstall++; + let { listener, installPromise } = makeListener( + id, + target.messageManager + ); + install.addListener(listener); + + this.installs.set(id, { + install, + target, + listener, + installPromise, + messageManager: target.messageManager, + }); + + let result = { id }; + this.copyProps(install, result); + return result; + }); + }, + + async addonUninstall(target, id) { + let addon = await AddonManager.getAddonByID(id); + if (!addon) { + return false; + } + + if (!(addon.permissions & AddonManager.PERM_CAN_UNINSTALL)) { + return Promise.reject({ message: "Addon cannot be uninstalled" }); + } + + try { + addon.uninstall(); + return true; + } catch (err) { + Cu.reportError(err); + return false; + } + }, + + async addonSetEnabled(target, id, value) { + let addon = await AddonManager.getAddonByID(id); + if (!addon) { + throw new Error(`No such addon ${id}`); + } + + if (value) { + await addon.enable(); + } else { + await addon.disable(); + } + }, + + async addonInstallDoInstall(target, id) { + let state = this.installs.get(id); + if (!state) { + throw new Error(`invalid id ${id}`); + } + + let addon = await state.install.install(); + + if (addon.type == "theme" && !addon.appDisabled) { + await addon.enable(); + } + + await new Promise(resolve => { + let subject = { + wrappedJSObject: { target, addon, callback: resolve }, + }; + Services.obs.notifyObservers(subject, "webextension-install-notify"); + }); + }, + + addonInstallCancel(target, id) { + let state = this.installs.get(id); + if (!state) { + return Promise.reject(`invalid id ${id}`); + } + return Promise.resolve(state.install.cancel()); + }, + + clearInstalls(ids) { + for (let id of ids) { + this.forgetInstall(id); + } + }, + + clearInstallsFrom(mm) { + for (let [id, info] of this.installs) { + if (info.messageManager == mm) { + this.forgetInstall(id); + } + } + }, + + async addonReportAbuse(target, id) { + if (!Services.prefs.getBoolPref(PREF_AMO_ABUSEREPORT, false)) { + return Promise.reject({ + message: "amWebAPI reportAbuse not supported", + }); + } + + let existingDialog = lazy.AbuseReporter.getOpenDialog(); + if (existingDialog) { + existingDialog.close(); + } + + const dialog = await lazy.AbuseReporter.openDialog( + id, + "amo", + target + ).catch(err => { + Cu.reportError(err); + return Promise.reject({ + message: "Error creating abuse report", + }); + }); + + return dialog.promiseReport.then( + async report => { + if (!report) { + return false; + } + + await report.submit().catch(err => { + Cu.reportError(err); + return Promise.reject({ + message: "Error submitting abuse report", + }); + }); + + return true; + }, + err => { + Cu.reportError(err); + dialog.close(); + return Promise.reject({ + message: "Error creating abuse report", + }); + } + ); + }, + }, +}; + +/** + * Should not be used outside of core Mozilla code. This is a private API for + * the startup and platform integration code to use. Refer to the methods on + * AddonManagerInternal for documentation however note that these methods are + * subject to change at any time. + */ +var AddonManagerPrivate = { + startup() { + AddonManagerInternal.startup(); + }, + + addonIsActive(addonId) { + return AddonManagerInternal._getProviderByName("XPIProvider").addonIsActive( + addonId + ); + }, + + /** + * Gets an array of add-ons which were side-loaded prior to the last + * startup, and are currently disabled. + * + * @returns {Promise>} + */ + getNewSideloads() { + return AddonManagerInternal._getProviderByName( + "XPIProvider" + ).getNewSideloads(); + }, + + get browserUpdated() { + return gBrowserUpdated; + }, + + registerProvider(aProvider, aTypes) { + AddonManagerInternal.registerProvider(aProvider, aTypes); + }, + + unregisterProvider(aProvider) { + AddonManagerInternal.unregisterProvider(aProvider); + }, + + /** + * Get a list of addon types that was passed to registerProvider for the + * provider with the given name. + * + * @param {string} aProviderName + * @returns {Array} + */ + getAddonTypesByProvider(aProviderName) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + for (let [provider, addonTypes] of AddonManagerInternal.typesByProvider) { + if (providerName(provider) === aProviderName) { + // Return an array because methods such as getAddonsByTypes expect + // aTypes to be an array. + return Array.from(addonTypes); + } + } + throw Components.Exception( + `No addonTypes found for provider: ${aProviderName}`, + Cr.NS_ERROR_INVALID_ARG + ); + }, + + markProviderSafe(aProvider) { + AddonManagerInternal.markProviderSafe(aProvider); + }, + + backgroundUpdateCheck() { + return AddonManagerInternal.backgroundUpdateCheck(); + }, + + backgroundUpdateTimerHandler() { + // Don't return the promise here, since the caller doesn't care. + AddonManagerInternal.backgroundUpdateCheck(); + }, + + addStartupChange(aType, aID) { + AddonManagerInternal.addStartupChange(aType, aID); + }, + + removeStartupChange(aType, aID) { + AddonManagerInternal.removeStartupChange(aType, aID); + }, + + notifyAddonChanged(aID, aType, aPendingRestart) { + return AddonManagerInternal.notifyAddonChanged(aID, aType, aPendingRestart); + }, + + updateAddonAppDisabledStates() { + AddonManagerInternal.updateAddonAppDisabledStates(); + }, + + updateAddonRepositoryData() { + return AddonManagerInternal.updateAddonRepositoryData(); + }, + + callInstallListeners(...aArgs) { + return AddonManagerInternal.callInstallListeners.apply( + AddonManagerInternal, + aArgs + ); + }, + + callAddonListeners(...aArgs) { + AddonManagerInternal.callAddonListeners.apply(AddonManagerInternal, aArgs); + }, + + AddonAuthor, + + AddonScreenshot, + + get BOOTSTRAP_REASONS() { + // BOOTSTRAP_REASONS is a set of constants, and may be accessed before the + // provider has fully been started. + // See https://bugzilla.mozilla.org/show_bug.cgi?id=1760146#c1 + return gXPIProvider.BOOTSTRAP_REASONS; + }, + + setAddonStartupData(addonId, startupData) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + // TODO bug 1761079: Ensure that XPIProvider is available before calling it. + gXPIProvider.setStartupData(addonId, startupData); + }, + + unregisterDictionaries(aDicts) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + // TODO bug 1761093: Use _getProviderByName instead of gXPIProvider. + gXPIProvider.unregisterDictionaries(aDicts); + }, + + recordTimestamp(name, value) { + AddonManagerInternal.recordTimestamp(name, value); + }, + + _simpleMeasures: {}, + recordSimpleMeasure(name, value) { + this._simpleMeasures[name] = value; + }, + + recordException(aModule, aContext, aException) { + let report = { + module: aModule, + context: aContext, + }; + + if (typeof aException == "number") { + report.message = Components.Exception("", aException).name; + } else { + report.message = aException.toString(); + if (aException.fileName) { + report.file = aException.fileName; + report.line = aException.lineNumber; + } + } + + this._simpleMeasures.exception = report; + }, + + getSimpleMeasures() { + return this._simpleMeasures; + }, + + getTelemetryDetails() { + return AddonManagerInternal.telemetryDetails; + }, + + setTelemetryDetails(aProvider, aDetails) { + AddonManagerInternal.telemetryDetails[aProvider] = aDetails; + }, + + // Start a timer, record a simple measure of the time interval when + // timer.done() is called + simpleTimer(aName) { + let startTime = Cu.now(); + return { + done: () => + this.recordSimpleMeasure(aName, Math.round(Cu.now() - startTime)), + }; + }, + + async recordTiming(name, task) { + let timer = this.simpleTimer(name); + try { + return await task(); + } finally { + timer.done(); + } + }, + + /** + * Helper to call update listeners when no update is available. + * + * This can be used as an implementation for Addon.findUpdates() when + * no update mechanism is available. + */ + callNoUpdateListeners(addon, listener, reason, appVersion, platformVersion) { + if ("onNoCompatibilityUpdateAvailable" in listener) { + safeCall(listener.onNoCompatibilityUpdateAvailable.bind(listener), addon); + } + if ("onNoUpdateAvailable" in listener) { + safeCall(listener.onNoUpdateAvailable.bind(listener), addon); + } + if ("onUpdateFinished" in listener) { + safeCall(listener.onUpdateFinished.bind(listener), addon); + } + }, + + get webExtensionsMinPlatformVersion() { + return gWebExtensionsMinPlatformVersion; + }, + + hasUpgradeListener(aId) { + return AddonManagerInternal.upgradeListeners.has(aId); + }, + + getUpgradeListener(aId) { + return AddonManagerInternal.upgradeListeners.get(aId); + }, + + get externalExtensionLoaders() { + return AddonManagerInternal.externalExtensionLoaders; + }, + + /** + * Predicate that returns true if we think the given extension ID + * might have been generated by XPIProvider. + */ + isTemporaryInstallID(extensionId) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + + if (!extensionId || typeof extensionId != "string") { + throw Components.Exception( + "extensionId must be a string", + Cr.NS_ERROR_INVALID_ARG + ); + } + + return AddonManagerInternal._getProviderByName( + "XPIProvider" + ).isTemporaryInstallID(extensionId); + }, + + isDBLoaded() { + let provider = AddonManagerInternal._getProviderByName("XPIProvider"); + return provider ? provider.isDBLoaded : false; + }, + + get databaseReady() { + let provider = AddonManagerInternal._getProviderByName("XPIProvider"); + return provider ? provider.databaseReady : new Promise(() => {}); + }, + + /** + * Async shutdown barrier which blocks the completion of add-on + * manager shutdown. This should generally only be used by add-on + * providers (i.e., XPIProvider) to complete their final shutdown + * tasks. + */ + get finalShutdown() { + return gFinalShutdownBarrier.client; + }, + + // Used by tests to call repo shutdown. + overrideAddonRepository(mockRepo) { + lazy.AddonRepository = mockRepo; + }, + + // Used by tests to shut down AddonManager. + overrideAsyncShutdown(mockAsyncShutdown) { + AsyncShutdown = mockAsyncShutdown; + }, +}; + +/** + * This is the public API that UI and developers should be calling. All methods + * just forward to AddonManagerInternal. + * @class + */ +var AddonManager = { + // Map used to convert the known install source hostnames into the value to set into the + // telemetry events. + _installHostSource: new Map([ + ["addons.mozilla.org", "amo"], + ["discovery.addons.mozilla.org", "disco"], + ]), + + // Constants for the AddonInstall.state property + // These will show up as AddonManager.STATE_* (eg, STATE_AVAILABLE) + _states: new Map([ + // The install is available for download. + ["STATE_AVAILABLE", 0], + // The install is being downloaded. + ["STATE_DOWNLOADING", 1], + // The install is checking the update for compatibility information. + ["STATE_CHECKING_UPDATE", 2], + // The install is downloaded and ready to install. + ["STATE_DOWNLOADED", 3], + // The download failed. + ["STATE_DOWNLOAD_FAILED", 4], + // The install may not proceed until the user accepts a prompt + ["STATE_AWAITING_PROMPT", 5], + // Any prompts are done + ["STATE_PROMPTS_DONE", 6], + // The install has been postponed. + ["STATE_POSTPONED", 7], + // The install is ready to be applied. + ["STATE_READY", 8], + // The add-on is being installed. + ["STATE_INSTALLING", 9], + // The add-on has been installed. + ["STATE_INSTALLED", 10], + // The install failed. + ["STATE_INSTALL_FAILED", 11], + // The install has been cancelled. + ["STATE_CANCELLED", 12], + ]), + + // Constants representing different types of errors while downloading an + // add-on as a preparation for installation. + // These will show up as AddonManager.ERROR_* (eg, ERROR_NETWORK_FAILURE) + // The _errors codes are translated to text for a panel in browser-addons.js. + // The text is located in browser.properties. Errors with the "Updates only:" + // prefix are not translated because the error is dumped to the console + // instead of a panel. + _errors: new Map([ + // The download failed due to network problems. + ["ERROR_NETWORK_FAILURE", -1], + // The downloaded file did not match the provided hash. + ["ERROR_INCORRECT_HASH", -2], + // The downloaded file seems to be corrupted in some way. + ["ERROR_CORRUPT_FILE", -3], + // An error occurred trying to write to the filesystem. + ["ERROR_FILE_ACCESS", -4], + // The add-on must be signed and isn't. + ["ERROR_SIGNEDSTATE_REQUIRED", -5], + // Updates only: The downloaded add-on had a different type than expected. + ["ERROR_UNEXPECTED_ADDON_TYPE", -6], + // Updates only: The addon did not have the expected ID. + ["ERROR_INCORRECT_ID", -7], + // The addon install_origins does not list the 3rd party domain. + ["ERROR_INVALID_DOMAIN", -8], + // Updates only: The downloaded add-on had a different version than expected. + ["ERROR_UNEXPECTED_ADDON_VERSION", -9], + ]), + // The update check timed out + ERROR_TIMEOUT: -1, + // There was an error while downloading the update information. + ERROR_DOWNLOAD_ERROR: -2, + // The update information was malformed in some way. + ERROR_PARSE_ERROR: -3, + // The update information was not in any known format. + ERROR_UNKNOWN_FORMAT: -4, + // The update information was not correctly signed or there was an SSL error. + ERROR_SECURITY_ERROR: -5, + // The update was cancelled + ERROR_CANCELLED: -6, + // These must be kept in sync with AddonUpdateChecker. + // No error was encountered. + UPDATE_STATUS_NO_ERROR: 0, + // The update check timed out + UPDATE_STATUS_TIMEOUT: -1, + // There was an error while downloading the update information. + UPDATE_STATUS_DOWNLOAD_ERROR: -2, + // The update information was malformed in some way. + UPDATE_STATUS_PARSE_ERROR: -3, + // The update information was not in any known format. + UPDATE_STATUS_UNKNOWN_FORMAT: -4, + // The update information was not correctly signed or there was an SSL error. + UPDATE_STATUS_SECURITY_ERROR: -5, + // The update was cancelled. + UPDATE_STATUS_CANCELLED: -6, + // Constants to indicate why an update check is being performed + // Update check has been requested by the user. + UPDATE_WHEN_USER_REQUESTED: 1, + // Update check is necessary to see if the Addon is compatibile with a new + // version of the application. + UPDATE_WHEN_NEW_APP_DETECTED: 2, + // Update check is necessary because a new application has been installed. + UPDATE_WHEN_NEW_APP_INSTALLED: 3, + // Update check is a regular background update check. + UPDATE_WHEN_PERIODIC_UPDATE: 16, + // Update check is needed to check an Addon that is being installed. + UPDATE_WHEN_ADDON_INSTALLED: 17, + + // Constants for operations in Addon.pendingOperations + // Indicates that the Addon has no pending operations. + PENDING_NONE: 0, + // Indicates that the Addon will be enabled after the application restarts. + PENDING_ENABLE: 1, + // Indicates that the Addon will be disabled after the application restarts. + PENDING_DISABLE: 2, + // Indicates that the Addon will be uninstalled after the application restarts. + PENDING_UNINSTALL: 4, + // Indicates that the Addon will be installed after the application restarts. + PENDING_INSTALL: 8, + PENDING_UPGRADE: 16, + + // Constants for operations in Addon.operationsRequiringRestart + // Indicates that restart isn't required for any operation. + OP_NEEDS_RESTART_NONE: 0, + // Indicates that restart is required for enabling the addon. + OP_NEEDS_RESTART_ENABLE: 1, + // Indicates that restart is required for disabling the addon. + OP_NEEDS_RESTART_DISABLE: 2, + // Indicates that restart is required for uninstalling the addon. + OP_NEEDS_RESTART_UNINSTALL: 4, + // Indicates that restart is required for installing the addon. + OP_NEEDS_RESTART_INSTALL: 8, + + // Constants for permissions in Addon.permissions. + // Indicates that the Addon can be uninstalled. + PERM_CAN_UNINSTALL: 1, + // Indicates that the Addon can be enabled by the user. + PERM_CAN_ENABLE: 2, + // Indicates that the Addon can be disabled by the user. + PERM_CAN_DISABLE: 4, + // Indicates that the Addon can be upgraded. + PERM_CAN_UPGRADE: 8, + // Indicates that the Addon can be set to be allowed/disallowed + // in private browsing windows. + PERM_CAN_CHANGE_PRIVATEBROWSING_ACCESS: 32, + // Indicates that internal APIs can uninstall the add-on, even if the + // front-end cannot. + PERM_API_CAN_UNINSTALL: 64, + + // General descriptions of where items are installed. + // Installed in this profile. + SCOPE_PROFILE: 1, + // Installed for all of this user's profiles. + SCOPE_USER: 2, + // Installed and owned by the application. + SCOPE_APPLICATION: 4, + // Installed for all users of the computer. + SCOPE_SYSTEM: 8, + // Installed temporarily + SCOPE_TEMPORARY: 16, + // The combination of all scopes. + SCOPE_ALL: 31, + + // Constants for Addon.applyBackgroundUpdates. + // Indicates that the Addon should not update automatically. + AUTOUPDATE_DISABLE: 0, + // Indicates that the Addon should update automatically only if + // that's the global default. + AUTOUPDATE_DEFAULT: 1, + // Indicates that the Addon should update automatically. + AUTOUPDATE_ENABLE: 2, + + // Constants for how Addon options should be shown. + // Options will be displayed in a new tab, if possible + OPTIONS_TYPE_TAB: 3, + // Similar to OPTIONS_TYPE_INLINE, but rather than generating inline + // options from a specially-formatted XUL file, the contents of the + // file are simply displayed in an inline element. + OPTIONS_TYPE_INLINE_BROWSER: 5, + + // Constants for displayed or hidden options notifications + // Options notification will be displayed + OPTIONS_NOTIFICATION_DISPLAYED: "addon-options-displayed", + // Options notification will be hidden + OPTIONS_NOTIFICATION_HIDDEN: "addon-options-hidden", + + // Constants for getStartupChanges, addStartupChange and removeStartupChange + // Add-ons that were detected as installed during startup. Doesn't include + // add-ons that were pending installation the last time the application ran. + STARTUP_CHANGE_INSTALLED: "installed", + // Add-ons that were detected as changed during startup. This includes an + // add-on moving to a different location, changing version or just having + // been detected as possibly changed. + STARTUP_CHANGE_CHANGED: "changed", + // Add-ons that were detected as uninstalled during startup. Doesn't include + // add-ons that were pending uninstallation the last time the application ran. + STARTUP_CHANGE_UNINSTALLED: "uninstalled", + // Add-ons that were detected as disabled during startup, normally because of + // an application change making an add-on incompatible. Doesn't include + // add-ons that were pending being disabled the last time the application ran. + STARTUP_CHANGE_DISABLED: "disabled", + // Add-ons that were detected as enabled during startup, normally because of + // an application change making an add-on compatible. Doesn't include + // add-ons that were pending being enabled the last time the application ran. + STARTUP_CHANGE_ENABLED: "enabled", + + // Constants for Addon.signedState. Any states that should cause an add-on + // to be unusable in builds that require signing should have negative values. + // Add-on signing is not required, e.g. because the pref is disabled. + SIGNEDSTATE_NOT_REQUIRED: undefined, + // Add-on is signed but signature verification has failed. + SIGNEDSTATE_BROKEN: -2, + // Add-on may be signed but by an certificate that doesn't chain to our + // our trusted certificate. + SIGNEDSTATE_UNKNOWN: -1, + // Add-on is unsigned. + SIGNEDSTATE_MISSING: 0, + // Add-on is preliminarily reviewed. + SIGNEDSTATE_PRELIMINARY: 1, + // Add-on is fully reviewed. + SIGNEDSTATE_SIGNED: 2, + // Add-on is system add-on. + SIGNEDSTATE_SYSTEM: 3, + // Add-on is signed with a "Mozilla Extensions" certificate + SIGNEDSTATE_PRIVILEGED: 4, + + get __AddonManagerInternal__() { + return AppConstants.DEBUG ? AddonManagerInternal : undefined; + }, + + /** Boolean indicating whether AddonManager startup has completed. */ + get isReady() { + return gStartupComplete && !gShutdownInProgress; + }, + + /** + * A promise that is resolved when the AddonManager startup has completed. + * This may be rejected if startup of the AddonManager is not successful, or + * if shutdown is started before the AddonManager has finished starting. + */ + get readyPromise() { + return gStartedPromise.promise; + }, + + /** @constructor */ + init() { + this._stateToString = new Map(); + for (let [name, value] of this._states) { + this[name] = value; + this._stateToString.set(value, name); + } + this._errorToString = new Map(); + for (let [name, value] of this._errors) { + this[name] = value; + this._errorToString.set(value, name); + } + }, + + stateToString(state) { + return this._stateToString.get(state); + }, + + errorToString(err) { + return err ? this._errorToString.get(err) : null; + }, + + getInstallSourceFromHost(host) { + if (this._installHostSource.has(host)) { + return this._installHostSource.get(host); + } + + if (WEBAPI_TEST_INSTALL_HOSTS.includes(host)) { + return "test-host"; + } + + return "unknown"; + }, + + getInstallForURL(aUrl, aOptions) { + return AddonManagerInternal.getInstallForURL(aUrl, aOptions); + }, + + getInstallForFile( + aFile, + aMimetype, + aTelemetryInfo, + aUseSystemLocation = false + ) { + return AddonManagerInternal.getInstallForFile( + aFile, + aMimetype, + aTelemetryInfo, + aUseSystemLocation + ); + }, + + uninstallSystemProfileAddon(aID) { + return AddonManagerInternal.uninstallSystemProfileAddon(aID); + }, + + stageLangpacksForAppUpdate(appVersion, platformVersion) { + return AddonManagerInternal._getProviderByName( + "XPIProvider" + ).stageLangpacksForAppUpdate(appVersion, platformVersion); + }, + + /** + * Gets an array of add-on IDs that changed during the most recent startup. + * + * @param aType + * The type of startup change to get + * @return An array of add-on IDs + */ + getStartupChanges(aType) { + if (!(aType in AddonManagerInternal.startupChanges)) { + return []; + } + return AddonManagerInternal.startupChanges[aType].slice(0); + }, + + getAddonByID(aID) { + return AddonManagerInternal.getAddonByID(aID); + }, + + getAddonBySyncGUID(aGUID) { + return AddonManagerInternal.getAddonBySyncGUID(aGUID); + }, + + getAddonsByIDs(aIDs) { + return AddonManagerInternal.getAddonsByIDs(aIDs); + }, + + getAddonsByTypes(aTypes) { + return AddonManagerInternal.getAddonsByTypes(aTypes); + }, + + getActiveAddons(aTypes) { + return AddonManagerInternal.getActiveAddons(aTypes); + }, + + getAllAddons() { + return AddonManagerInternal.getAllAddons(); + }, + + getInstallsByTypes(aTypes) { + return AddonManagerInternal.getInstallsByTypes(aTypes); + }, + + getAllInstalls() { + return AddonManagerInternal.getAllInstalls(); + }, + + isInstallEnabled(aType) { + return AddonManagerInternal.isInstallEnabled(aType); + }, + + isInstallAllowed(aType, aInstallingPrincipal) { + return AddonManagerInternal.isInstallAllowed(aType, aInstallingPrincipal); + }, + + installSitePermsAddonFromWebpage( + aBrowser, + aInstallingPrincipal, + aPermission + ) { + return AddonManagerInternal.installSitePermsAddonFromWebpage( + aBrowser, + aInstallingPrincipal, + aPermission + ); + }, + + installAddonFromWebpage( + aType, + aBrowser, + aInstallingPrincipal, + aInstall, + details + ) { + AddonManagerInternal.installAddonFromWebpage( + aType, + aBrowser, + aInstallingPrincipal, + aInstall, + details + ); + }, + + installAddonFromAOM(aBrowser, aUri, aInstall) { + AddonManagerInternal.installAddonFromAOM(aBrowser, aUri, aInstall); + }, + + installTemporaryAddon(aDirectory) { + return AddonManagerInternal.installTemporaryAddon(aDirectory); + }, + + installBuiltinAddon(aBase) { + return AddonManagerInternal.installBuiltinAddon(aBase); + }, + + maybeInstallBuiltinAddon(aID, aVersion, aBase) { + return AddonManagerInternal.maybeInstallBuiltinAddon(aID, aVersion, aBase); + }, + + addManagerListener(aListener) { + AddonManagerInternal.addManagerListener(aListener); + }, + + removeManagerListener(aListener) { + AddonManagerInternal.removeManagerListener(aListener); + }, + + addInstallListener(aListener) { + AddonManagerInternal.addInstallListener(aListener); + }, + + removeInstallListener(aListener) { + AddonManagerInternal.removeInstallListener(aListener); + }, + + getUpgradeListener(aId) { + return AddonManagerInternal.upgradeListeners.get(aId); + }, + + addUpgradeListener(aInstanceID, aCallback) { + AddonManagerInternal.addUpgradeListener(aInstanceID, aCallback); + }, + + removeUpgradeListener(aInstanceID) { + return AddonManagerInternal.removeUpgradeListener(aInstanceID); + }, + + addExternalExtensionLoader(loader) { + return AddonManagerInternal.addExternalExtensionLoader(loader); + }, + + addAddonListener(aListener) { + AddonManagerInternal.addAddonListener(aListener); + }, + + removeAddonListener(aListener) { + AddonManagerInternal.removeAddonListener(aListener); + }, + + hasAddonType(addonType) { + return AddonManagerInternal.hasAddonType(addonType); + }, + + hasProvider(name) { + if (!gStarted) { + throw Components.Exception( + "AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED + ); + } + return !!AddonManagerInternal._getProviderByName(name); + }, + + /** + * Determines whether an Addon should auto-update or not. + * + * @param aAddon + * The Addon representing the add-on + * @return true if the addon should auto-update, false otherwise. + */ + shouldAutoUpdate(aAddon) { + if (!aAddon || typeof aAddon != "object") { + throw Components.Exception( + "aAddon must be specified", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (!("applyBackgroundUpdates" in aAddon)) { + return false; + } + if (!(aAddon.permissions & AddonManager.PERM_CAN_UPGRADE)) { + return false; + } + if (aAddon.applyBackgroundUpdates == AddonManager.AUTOUPDATE_ENABLE) { + return true; + } + if (aAddon.applyBackgroundUpdates == AddonManager.AUTOUPDATE_DISABLE) { + return false; + } + return this.autoUpdateDefault; + }, + + get checkCompatibility() { + return AddonManagerInternal.checkCompatibility; + }, + + set checkCompatibility(aValue) { + AddonManagerInternal.checkCompatibility = aValue; + }, + + get strictCompatibility() { + return AddonManagerInternal.strictCompatibility; + }, + + set strictCompatibility(aValue) { + AddonManagerInternal.strictCompatibility = aValue; + }, + + get checkUpdateSecurityDefault() { + return AddonManagerInternal.checkUpdateSecurityDefault; + }, + + get checkUpdateSecurity() { + return AddonManagerInternal.checkUpdateSecurity; + }, + + set checkUpdateSecurity(aValue) { + AddonManagerInternal.checkUpdateSecurity = aValue; + }, + + get updateEnabled() { + return AddonManagerInternal.updateEnabled; + }, + + set updateEnabled(aValue) { + AddonManagerInternal.updateEnabled = aValue; + }, + + get autoUpdateDefault() { + return AddonManagerInternal.autoUpdateDefault; + }, + + set autoUpdateDefault(aValue) { + AddonManagerInternal.autoUpdateDefault = aValue; + }, + + escapeAddonURI(aAddon, aUri, aAppVersion) { + return AddonManagerInternal.escapeAddonURI(aAddon, aUri, aAppVersion); + }, + + getPreferredIconURL(aAddon, aSize, aWindow = undefined) { + return AddonManagerInternal.getPreferredIconURL(aAddon, aSize, aWindow); + }, + + get webAPI() { + return AddonManagerInternal.webAPI; + }, + + /** + * Async shutdown barrier which blocks the start of AddonManager + * shutdown. Callers should add blockers to this barrier if they need + * to complete add-on manager operations before it shuts down. + */ + get beforeShutdown() { + return gBeforeShutdownBarrier.client; + }, +}; + +/** + * Manage AddonManager settings propagated over RemoteSettings synced data. + * + * See :doc:`AMRemoteSettings Overview `. + * + * .. warning:: + * Before landing any change to ``AMRemoteSettings`` or the format expected for the + * remotely controlled settings (on the service or Firefos side), please read the + * documentation page linked above and make sure to keep the JSON Schema described + * and controlled settings groups included in that documentation page in sync with + * the one actually set on the RemoteSettings service side. + */ +AMRemoteSettings = { + RS_COLLECTION: "addons-manager-settings", + + /** + * RemoteSettings settings group map. + * + * .. note:: + * Please keep in sync the "Controlled Settings Groups" documentation from + * :doc:`AMRemoteSettings Overview ` in sync with + * the settings groups defined here. + */ + RS_ENTRIES_MAP: { + installTriggerDeprecation: [ + "extensions.InstallTriggerImpl.enabled", + "extensions.InstallTrigger.enabled", + ], + }, + + client: null, + onSync: null, + promiseStartup: null, + + init() { + try { + if (!this.promiseStartup) { + // Creating a promise to resolved when the browser startup was completed, + // used to process the existing entries (if any) after the startup is completed + // and to only to it ones. + this.promiseStartup = new Promise(resolve => { + function observer() { + resolve(); + Services.obs.removeObserver( + observer, + "browser-delayed-startup-finished" + ); + } + Services.obs.addObserver( + observer, + "browser-delayed-startup-finished" + ); + }); + } + + if (Services.prefs.getBoolPref(PREF_REMOTESETTINGS_DISABLED, false)) { + return; + } + + if (!this.client) { + this.client = lazy.RemoteSettings(this.RS_COLLECTION); + this.onSync = this.processEntries.bind(this); + this.client.on("sync", this.onSync); + // Process existing entries if any, once the browser has been fully initialized. + this.promiseStartup.then(() => this.processEntries()); + } + } catch (err) { + logger.error("Failure to initialize AddonManager RemoteSettings", err); + } + }, + + shutdown() { + try { + if (this.client) { + this.client.off("sync", this.onSync); + this.client = null; + this.onSync = null; + } + this.promiseStartup = null; + } catch (err) { + logger.error("Failure on shutdown AddonManager RemoteSettings", err); + } + }, + + /** + * Process all the settings groups that are included in the collection entry with ``"id"`` set to ``"AddonManagerSettings"`` + * (if any). + * + * .. note:: + * This method may need to be updated if the preference value type is not yet expected by this method + * (which means that it would be ignored until handled explicitly). + */ + async processEntries() { + const entries = await this.client.get({ syncIfEmpty: false }).catch(err => { + logger.error("Failure to process AddonManager RemoteSettings", err); + return []; + }); + + for (const entry of entries) { + logger.debug(`Processing AddonManager RemoteSettings "${entry.id}"`); + + for (const [groupName, prefs] of Object.entries(this.RS_ENTRIES_MAP)) { + const data = entry[groupName]; + if (!data) { + continue; + } + + for (const pref of prefs) { + // Skip the pref if it is not included in the remote settings data. + if (!(pref in data)) { + continue; + } + + try { + // Support for controlling boolean AddonManager settings. + if (typeof data[pref] == "boolean") { + logger.debug( + `Process AddonManager RemoteSettings "${entry.id}" - "${groupName}": ${pref}=${data[pref]}` + ); + Services.prefs.setBoolPref(pref, data[pref]); + } + } catch (e) { + logger.error( + `Failed to process AddonManager RemoteSettings "${entry.id}" - "${groupName}": ${pref}`, + e + ); + } + } + } + } + }, +}; + +/** + * Listens to the AddonManager install and addon events and send telemetry events. + */ +AMTelemetry = { + telemetrySetupDone: false, + + init() { + // Enable the addonsManager telemetry event category before the AddonManager + // has completed its startup, otherwise telemetry events recorded during the + // AddonManager/XPIProvider startup will not be recorded. + Services.telemetry.setEventRecordingEnabled("addonsManager", true); + }, + + // This method is called by the AddonManager, once it has been started, so that we can + // init the telemetry event category and start listening for the events related to the + // addons installation and management. + onStartup() { + if (this.telemetrySetupDone) { + return; + } + + this.telemetrySetupDone = true; + + Services.obs.addObserver(this, "addon-install-origin-blocked"); + Services.obs.addObserver(this, "addon-install-disabled"); + Services.obs.addObserver(this, "addon-install-blocked"); + + AddonManager.addInstallListener(this); + AddonManager.addAddonListener(this); + }, + + // Observer Service notification callback. + + observe(subject, topic, data) { + switch (topic) { + case "addon-install-blocked": { + const { installs } = subject.wrappedJSObject; + this.recordInstallEvent(installs[0], { step: "site_warning" }); + break; + } + case "addon-install-origin-blocked": { + const { installs } = subject.wrappedJSObject; + this.recordInstallEvent(installs[0], { step: "site_blocked" }); + break; + } + case "addon-install-disabled": { + const { installs } = subject.wrappedJSObject; + this.recordInstallEvent(installs[0], { + step: "install_disabled_warning", + }); + break; + } + } + }, + + // AddonManager install listener callbacks. + + onNewInstall(install) { + this.recordInstallEvent(install, { step: "started" }); + }, + + onInstallCancelled(install) { + this.recordInstallEvent(install, { step: "cancelled" }); + }, + + onInstallPostponed(install) { + this.recordInstallEvent(install, { step: "postponed" }); + }, + + onInstallFailed(install) { + this.recordInstallEvent(install, { step: "failed" }); + }, + + onInstallEnded(install) { + this.recordInstallEvent(install, { step: "completed" }); + // Skip install_stats events for install objects related to. + // add-on updates. + if (!install.existingAddon) { + this.recordInstallStatsEvent(install); + } + }, + + onDownloadStarted(install) { + this.recordInstallEvent(install, { step: "download_started" }); + }, + + onDownloadCancelled(install) { + this.recordInstallEvent(install, { step: "cancelled" }); + }, + + onDownloadEnded(install) { + let download_time = Math.round(Cu.now() - install.downloadStartedAt); + this.recordInstallEvent(install, { + step: "download_completed", + download_time, + }); + }, + + onDownloadFailed(install) { + let download_time = Math.round(Cu.now() - install.downloadStartedAt); + this.recordInstallEvent(install, { + step: "download_failed", + download_time, + }); + }, + + // Addon listeners callbacks. + + onUninstalled(addon) { + this.recordManageEvent(addon, "uninstall"); + }, + + onEnabled(addon) { + this.recordManageEvent(addon, "enable"); + }, + + onDisabled(addon) { + this.recordManageEvent(addon, "disable"); + }, + + // Internal helpers methods. + + /** + * Get a trimmed version of the given string if it is longer than 80 chars. + * + * @param {string} str + * The original string content. + * + * @returns {string} + * The trimmed version of the string when longer than 80 chars, or the given string + * unmodified otherwise. + */ + getTrimmedString(str) { + if (str.length <= 80) { + return str; + } + + const length = str.length; + + // Trim the string to prevent a flood of warnings messages logged internally by recordEvent, + // the trimmed version is going to be composed by the first 40 chars and the last 37 and 3 dots + // that joins the two parts, to visually indicate that the string has been trimmed. + return `${str.slice(0, 40)}...${str.slice(length - 37, length)}`; + }, + + /** + * Retrieve the addonId for the given AddonInstall instance. + * + * @param {AddonInstall} install + * The AddonInstall instance to retrieve the addonId from. + * + * @returns {string | null} + * The addonId for the given AddonInstall instance (if any). + */ + getAddonIdFromInstall(install) { + // Returns the id of the extension that is being installed, as soon as the + // addon is available in the AddonInstall instance (after being downloaded + // and validated successfully). + if (install.addon) { + return install.addon.id; + } + + // While updating an addon, the existing addon can be + // used to retrieve the addon id since the first update event. + if (install.existingAddon) { + return install.existingAddon.id; + } + + return null; + }, + + /** + * Retrieve the telemetry event's object property value for the given + * AddonInstall instance. + * + * @param {AddonInstall} install + * The AddonInstall instance to retrieve the event object from. + * + * @returns {string} + * The object for the given AddonInstall instance. + */ + getEventObjectFromInstall(install) { + let addonType; + + if (install.type) { + // The AddonInstall wrapper already provides a type (if it was known when the + // install object has been created). + addonType = install.type; + } else if (install.addon) { + // The install flow has reached a step that has an addon instance which we can + // check to know the extension type (e.g. after download for the DownloadAddonInstall). + addonType = install.addon.type; + } else if (install.existingAddon) { + // The install flow is an update and we can look the existingAddon to check which was + // the add-on type that is being installed. + addonType = install.existingAddon.type; + } + + return this.getEventObjectFromAddonType(addonType); + }, + + /** + * Retrieve the telemetry event source for the given AddonInstall instance. + * + * @param {AddonInstall} install + * The AddonInstall instance to retrieve the source from. + * + * @returns {Object | null} + * The telemetry infor ({source, method}) from the given AddonInstall instance. + */ + getInstallTelemetryInfo(install) { + if (install.installTelemetryInfo) { + return install.installTelemetryInfo; + } else if ( + install.existingAddon && + install.existingAddon.installTelemetryInfo + ) { + // Get the install source from the existing addon (e.g. for an extension update). + return install.existingAddon.installTelemetryInfo; + } + + return null; + }, + + /** + * Get the telemetry event's object property for the given addon type + * + * @param {string} addonType + * The addon type to convert into the related telemetry event object. + * + * @returns {string} + * The object for the given addon type. + */ + getEventObjectFromAddonType(addonType) { + switch (addonType) { + case undefined: + return "unknown"; + case "extension": + case "theme": + case "locale": + case "dictionary": + case "sitepermission": + return addonType; + // TODO(Bug 1789718): Remove after the deprecated XPIProvider-based implementation is also removed. + case "sitepermission-deprecated": + // Telemetry events' object maximum length is 20 chars (See https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/collection/events.html#limits) + // and the value needs to matching the "^[a-zA-Z][a-zA-Z0-9_.]*[a-zA-Z0-9]$" pattern. + return "siteperm_deprecated"; + default: + // Currently this should only include gmp-plugins ("plugin"). + return "other"; + } + }, + + convertToString(value) { + if (value == null) { + // Convert null and undefined to empty strings. + return ""; + } + switch (typeof value) { + case "string": + return value; + case "boolean": + return value ? "1" : "0"; + } + return String(value); + }, + + /** + * Return the UTM parameters found in `sourceURL` for AMO attribution data. + * + * @param {string} sourceURL + * The source URL from where the add-on has been installed. + * + * @returns {object} + * An object containing the attribution data for AMO if any. Keys + * are defined in `AMO_ATTRIBUTION_DATA_KEYS`. Values are strings. + */ + parseAttributionDataForAMO(sourceURL) { + let searchParams; + + try { + searchParams = new URL(sourceURL).searchParams; + } catch { + return {}; + } + + const utmKeys = [...searchParams.keys()].filter(key => + AMO_ATTRIBUTION_DATA_KEYS.includes(key) + ); + + return utmKeys.reduce((params, key) => { + let value = searchParams.get(key); + if (typeof value === "string") { + value = value.slice(0, AMO_ATTRIBUTION_DATA_MAX_LENGTH); + } + + return { ...params, [key]: value }; + }, {}); + }, + + /** + * Record an "install stats" event when the source is included in + * `AMO_ATTRIBUTION_ALLOWED_SOURCES`. + * + * @param {AddonInstall} install + * The AddonInstall instance to record an install_stats event for. + */ + recordInstallStatsEvent(install) { + const telemetryInfo = this.getInstallTelemetryInfo(install); + + if (!AMO_ATTRIBUTION_ALLOWED_SOURCES.includes(telemetryInfo?.source)) { + return; + } + + const method = "install_stats"; + const object = this.getEventObjectFromInstall(install); + const addonId = this.getAddonIdFromInstall(install); + + if (!addonId) { + Cu.reportError( + "Missing addonId when trying to record an install_stats event" + ); + return; + } + + let extra = { + addon_id: this.getTrimmedString(addonId), + }; + + if ( + telemetryInfo?.source === "amo" && + typeof telemetryInfo?.sourceURL === "string" + ) { + extra = { + ...extra, + ...this.parseAttributionDataForAMO(telemetryInfo.sourceURL), + }; + } + + if ( + telemetryInfo?.source === "disco" && + typeof telemetryInfo?.taarRecommended === "boolean" + ) { + extra = { + ...extra, + taar_based: this.convertToString(telemetryInfo.taarRecommended), + }; + } + + this.recordEvent({ method, object, value: install.hashedAddonId, extra }); + }, + + /** + * Convert all the telemetry event's extra_vars into strings, if needed. + * + * @param {object} extraVars + * @returns {object} The formatted extra vars. + */ + formatExtraVars({ addon, ...extraVars }) { + if (addon) { + extraVars.addonId = addon.id; + extraVars.type = addon.type; + } + + // All the extra_vars in a telemetry event have to be strings. + for (var [key, value] of Object.entries(extraVars)) { + if (value == undefined) { + delete extraVars[key]; + } else { + extraVars[key] = this.convertToString(value); + } + } + + if (extraVars.addonId) { + extraVars.addonId = this.getTrimmedString(extraVars.addonId); + } + + return extraVars; + }, + + /** + * Record an install or update event for the given AddonInstall instance. + * + * @param {AddonInstall} install + * The AddonInstall instance to record an install or update event for. + * @param {object} extraVars + * The additional extra_vars to include in the recorded event. + * @param {string} extraVars.step + * The current step in the install or update flow. + * @param {string} extraVars.download_time + * The number of ms needed to download the extension. + * @param {string} extraVars.num_strings + * The number of permission description string for the extension + * permission doorhanger. + */ + recordInstallEvent(install, extraVars) { + // Early exit if AMTelemetry's telemetry setup has not been done yet. + if (!this.telemetrySetupDone) { + return; + } + + let extra = {}; + + let telemetryInfo = this.getInstallTelemetryInfo(install); + if (telemetryInfo && typeof telemetryInfo.source === "string") { + extra.source = telemetryInfo.source; + } + + if (extra.source === "internal") { + // Do not record the telemetry event for installation sources + // that are marked as "internal". + return; + } + + // Also include the install source's method when applicable (e.g. install events with + // source "about:addons" may have "install-from-file" or "url" as their source method). + if (telemetryInfo && typeof telemetryInfo.method === "string") { + extra.method = telemetryInfo.method; + } + + let addonId = this.getAddonIdFromInstall(install); + let object = this.getEventObjectFromInstall(install); + + let installId = String(install.installId); + let eventMethod = install.existingAddon ? "update" : "install"; + + if (addonId) { + extra.addon_id = this.getTrimmedString(addonId); + } + + if (install.error) { + extra.error = AddonManager.errorToString(install.error); + } + + if ( + eventMethod === "install" && + Services.prefs.getBoolPref("extensions.install_origins.enabled", true) + ) { + // This is converted to "1" / "0". + extra.install_origins = Array.isArray(install.addon?.installOrigins); + } + + if (eventMethod === "update") { + // For "update" telemetry events, also include an extra var which determine + // if the update has been requested by the user. + extra.updated_from = install.isUserRequestedUpdate ? "user" : "app"; + } + + // All the extra vars in a telemetry event have to be strings. + extra = this.formatExtraVars({ ...extraVars, ...extra }); + + this.recordEvent({ method: eventMethod, object, value: installId, extra }); + }, + + /** + * Record a manage event for the given addon. + * + * @param {AddonWrapper} addon + * The AddonWrapper instance. + * @param {object} extraVars + * The additional extra_vars to include in the recorded event. + * @param {string} extraVars.num_strings + * The number of permission description string for the extension + * permission doorhanger. + */ + recordManageEvent(addon, method, extraVars) { + // Early exit if AMTelemetry's telemetry setup has not been done yet. + if (!this.telemetrySetupDone) { + return; + } + + let extra = {}; + + if (addon.installTelemetryInfo) { + if ("source" in addon.installTelemetryInfo) { + extra.source = addon.installTelemetryInfo.source; + } + + // Also include the install source's method when applicable (e.g. install events with + // source "about:addons" may have "install-from-file" or "url" as their source method). + if ("method" in addon.installTelemetryInfo) { + extra.method = addon.installTelemetryInfo.method; + } + } + + if (extra.source === "internal") { + // Do not record the telemetry event for installation sources + // that are marked as "internal". + return; + } + + let object = this.getEventObjectFromAddonType(addon.type); + let value = this.getTrimmedString(addon.id); + + extra = { ...extraVars, ...extra }; + + let hasExtraVars = !!Object.keys(extra).length; + extra = this.formatExtraVars(extra); + + this.recordEvent({ + method, + object, + value, + extra: hasExtraVars ? extra : null, + }); + }, + + /** + * Record an event for when a link is clicked. + * + * @param {object} opts + * @param {string} opts.object + * The object of the event, should be an identifier for where the link + * is located. The accepted values are listed in the + * addonsManager.link object of the Events.yaml file. + * @param {string} opts.value The identifier for the link destination. + * @param {object} opts.extra + * The extra data to be sent, all keys must be registered in the + * extra_keys section of addonsManager.link in Events.yaml. + */ + recordLinkEvent({ object, value, extra = null }) { + this.recordEvent({ method: "link", object, value, extra }); + }, + + /** + * Record an event for an action that took place. + * + * @param {object} opts + * @param {string} opts.object + * The object of the event, should an identifier for where the action + * took place. The accepted values are listed in the + * addonsManager.action object of the Events.yaml file. + * @param {string} opts.action The identifier for the action. + * @param {string} opts.value An optional value for the action. + * @param {object} opts.addon + * An optional object with the "id" and "type" properties, for example + * an AddonWrapper object. Passing this will set some extra properties. + * @param {string} opts.addon.id + * The add-on ID to assign to extra.addonId. + * @param {string} opts.addon.type + * The add-on type to assign to extra.type. + * @param {string} opts.view The current view, when object is aboutAddons. + * @param {object} opts.extra + * The extra data to be sent, all keys must be registered in the + * extra_keys section of addonsManager.action in Events.yaml. If + * opts.addon is passed then it will overwrite the addonId and type + * properties in this object, if they are set. + */ + recordActionEvent({ object, action, value, addon, view, extra }) { + extra = { ...extra, action, addon, view }; + if (action === "installFromRecommendation") { + extra.taar_based = !!addon.taarRecommended; + } + this.recordEvent({ + method: "action", + object, + // Treat null and undefined as null. + value: value == null ? null : this.convertToString(value), + extra: this.formatExtraVars(extra), + }); + }, + + /** + * Record an event for a view load in about:addons. + * + * @param {object} opts + * @param {string} opts.view + * The identifier for the view. The accepted values are listed in the + * object property of addonsManager.view object of the Events.yaml + * file. + * @param {AddonWrapper} opts.addon + * An optional add-on object related to the event. + * @param {string} opts.type + * An optional type for the view. If opts.addon is set it will + * overwrite this value with the type of the add-on. + * @param {boolean} opts.taarEnabled + * Set to true if taar-based discovery was enabled when the user + * did switch between about:addons views. + */ + recordViewEvent({ view, addon, type, taarEnabled }) { + this.recordEvent({ + method: "view", + object: "aboutAddons", + value: view, + extra: this.formatExtraVars({ + type, + addon, + taar_enabled: taarEnabled, + }), + }); + }, + + /** + * Record an event on abuse report submissions. + * + * @params {object} opts + * @params {string} opts.addonId + * The id of the addon being reported. + * @params {string} [opts.addonType] + * The type of the addon being reported (only present for an existing + * addonId). + * @params {string} [opts.errorType] + * The AbuseReport errorType for a submission failure. + * @params {string} opts.reportEntryPoint + * The entry point of the abuse report. + */ + recordReportEvent({ addonId, addonType, errorType, reportEntryPoint }) { + this.recordEvent({ + method: "report", + object: reportEntryPoint, + value: addonId, + extra: this.formatExtraVars({ + addon_type: addonType, + error_type: errorType, + }), + }); + }, + + recordEvent({ method, object, value, extra }) { + if (typeof value != "string") { + // The value must be a string or null, make sure it's valid so sending + // the event doesn't fail. + value = null; + } + try { + Services.telemetry.recordEvent( + "addonsManager", + method, + object, + value, + extra + ); + } catch (err) { + // If the telemetry throws just log the error so it doesn't break any + // functionality. + Cu.reportError(err); + } + }, +}; + +AddonManager.init(); + +// Setup the AMTelemetry once the AddonManager has been started. +AddonManager.addManagerListener(AMTelemetry); +Object.freeze(AddonManagerInternal); +Object.freeze(AddonManagerPrivate); +Object.freeze(AddonManager); diff --git a/toolkit/mozapps/extensions/AddonManagerStartup-inlines.h b/toolkit/mozapps/extensions/AddonManagerStartup-inlines.h new file mode 100644 index 0000000000..64211d98e7 --- /dev/null +++ b/toolkit/mozapps/extensions/AddonManagerStartup-inlines.h @@ -0,0 +1,229 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef AddonManagerStartup_inlines_h +#define AddonManagerStartup_inlines_h + +#include + +#include "js/Array.h" // JS::GetArrayLength, JS::IsArrayObject +#include "js/Exception.h" +#include "js/PropertyAndElement.h" // JS_Enumerate, JS_GetElement, JS_GetProperty, JS_GetPropertyById +#include "jsapi.h" +#include "mozilla/Maybe.h" +#include "nsJSUtils.h" + +namespace mozilla { + +class ArrayIterElem; +class PropertyIterElem; + +/***************************************************************************** + * Object iterator base classes + *****************************************************************************/ + +template +class MOZ_STACK_CLASS BaseIter { + public: + typedef T SelfType; + + PropertyType begin() const { return PropertyType(Self()); } + + PropertyType end() const { + PropertyType elem(Self()); + return elem.End(); + } + + void* Context() const { return mContext; } + + protected: + BaseIter(JSContext* cx, JS::Handle object, void* context = nullptr) + : mCx(cx), mObject(object), mContext(context) {} + + const SelfType& Self() const { return *static_cast(this); } + SelfType& Self() { return *static_cast(this); } + + JSContext* mCx; + + JS::Handle mObject; + + void* mContext; +}; + +template +class MOZ_STACK_CLASS BaseIterElem { + public: + typedef T SelfType; + + explicit BaseIterElem(const IterType& iter, uint32_t index = 0) + : mIter(iter), mIndex(index) {} + + uint32_t Length() const { return mIter.Length(); } + + JS::Value Value() { + JS::Rooted value(mIter.mCx, JS::UndefinedValue()); + + auto& self = Self(); + if (!self.GetValue(&value)) { + JS_ClearPendingException(mIter.mCx); + } + + return value; + } + + SelfType& operator*() { return Self(); } + + SelfType& operator++() { + MOZ_ASSERT(mIndex < Length()); + mIndex++; + return Self(); + } + + bool operator!=(const SelfType& other) const { + return &mIter != &other.mIter || mIndex != other.mIndex; + } + + SelfType End() const { + SelfType end(mIter); + end.mIndex = Length(); + return end; + } + + void* Context() const { return mIter.Context(); } + + protected: + const SelfType& Self() const { return *static_cast(this); } + SelfType& Self() { return *static_cast(this); } + + const IterType& mIter; + + uint32_t mIndex; +}; + +/***************************************************************************** + * Property iteration + *****************************************************************************/ + +class MOZ_STACK_CLASS PropertyIter + : public BaseIter { + friend class PropertyIterElem; + friend class BaseIterElem; + + public: + PropertyIter(JSContext* cx, JS::Handle object, + void* context = nullptr) + : BaseIter(cx, object, context), mIds(cx, JS::IdVector(cx)) { + if (!JS_Enumerate(cx, object, &mIds)) { + JS_ClearPendingException(cx); + } + } + + PropertyIter(const PropertyIter& other) + : PropertyIter(other.mCx, other.mObject, other.mContext) {} + + PropertyIter& operator=(const PropertyIter& other) { + MOZ_ASSERT(other.mObject == mObject); + mCx = other.mCx; + mContext = other.mContext; + + mIds.clear(); + if (!JS_Enumerate(mCx, mObject, &mIds)) { + JS_ClearPendingException(mCx); + } + return *this; + } + + int32_t Length() const { return mIds.length(); } + + protected: + JS::Rooted mIds; +}; + +class MOZ_STACK_CLASS PropertyIterElem + : public BaseIterElem { + friend class BaseIterElem; + + public: + using BaseIterElem::BaseIterElem; + + PropertyIterElem(const PropertyIterElem& other) + : BaseIterElem(other.mIter, other.mIndex) {} + + jsid Id() { + MOZ_ASSERT(mIndex < mIter.mIds.length()); + + return mIter.mIds[mIndex]; + } + + const nsAString& Name() { + if (mName.isNothing()) { + mName.emplace(); + mName.ref().init(mIter.mCx, Id()); + } + return mName.ref(); + } + + JSContext* Cx() { return mIter.mCx; } + + protected: + bool GetValue(JS::MutableHandle value) { + MOZ_ASSERT(mIndex < Length()); + JS::Rooted id(mIter.mCx, Id()); + + return JS_GetPropertyById(mIter.mCx, mIter.mObject, id, value); + } + + private: + Maybe mName; +}; + +/***************************************************************************** + * Array iteration + *****************************************************************************/ + +class MOZ_STACK_CLASS ArrayIter : public BaseIter { + friend class ArrayIterElem; + friend class BaseIterElem; + + public: + ArrayIter(JSContext* cx, JS::Handle object) + : BaseIter(cx, object), mLength(0) { + bool isArray; + if (!JS::IsArrayObject(cx, object, &isArray) || !isArray) { + JS_ClearPendingException(cx); + return; + } + + if (!JS::GetArrayLength(cx, object, &mLength)) { + JS_ClearPendingException(cx); + } + } + + uint32_t Length() const { return mLength; } + + private: + uint32_t mLength; +}; + +class MOZ_STACK_CLASS ArrayIterElem + : public BaseIterElem { + friend class BaseIterElem; + + public: + using BaseIterElem::BaseIterElem; + + ArrayIterElem(const ArrayIterElem& other) + : BaseIterElem(other.mIter, other.mIndex) {} + + protected: + bool GetValue(JS::MutableHandle value) { + MOZ_ASSERT(mIndex < Length()); + return JS_GetElement(mIter.mCx, mIter.mObject, mIndex, value); + } +}; + +} // namespace mozilla + +#endif // AddonManagerStartup_inlines_h diff --git a/toolkit/mozapps/extensions/AddonManagerStartup.cpp b/toolkit/mozapps/extensions/AddonManagerStartup.cpp new file mode 100644 index 0000000000..2aebf465dc --- /dev/null +++ b/toolkit/mozapps/extensions/AddonManagerStartup.cpp @@ -0,0 +1,880 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "AddonManagerStartup.h" +#include "AddonManagerStartup-inlines.h" + +#include "jsapi.h" +#include "jsfriendapi.h" +#include "js/Array.h" // JS::IsArrayObject +#include "js/ArrayBuffer.h" +#include "js/Exception.h" +#include "js/JSON.h" +#include "js/PropertyAndElement.h" // JS_GetProperty, JS_SetProperty +#include "js/TracingAPI.h" +#include "xpcpublic.h" + +#include "mozilla/AppShutdown.h" +#include "mozilla/ClearOnShutdown.h" +#include "mozilla/EndianUtils.h" +#include "mozilla/Components.h" +#include "mozilla/Compression.h" +#include "mozilla/LinkedList.h" +#include "mozilla/Preferences.h" +#include "mozilla/ResultExtensions.h" +#include "mozilla/URLPreloader.h" +#include "mozilla/Unused.h" +#include "mozilla/ErrorResult.h" +#include "mozilla/dom/ipc/StructuredCloneData.h" + +#include "nsAppDirectoryServiceDefs.h" +#include "nsAppRunner.h" +#include "nsContentUtils.h" +#include "nsChromeRegistry.h" +#include "nsIDOMWindowUtils.h" // for nsIJSRAIIHelper +#include "nsIFileURL.h" +#include "nsIIOService.h" +#include "nsIJARURI.h" +#include "nsIStringEnumerator.h" +#include "nsIZipReader.h" +#include "nsJARProtocolHandler.h" +#include "nsJSUtils.h" +#include "nsReadableUtils.h" +#include "nsXULAppAPI.h" + +#include + +namespace mozilla { + +using Compression::LZ4; +using dom::ipc::StructuredCloneData; + +AddonManagerStartup& AddonManagerStartup::GetSingleton() { + static RefPtr singleton; + if (!singleton) { + singleton = new AddonManagerStartup(); + ClearOnShutdown(&singleton); + } + return *singleton; +} + +AddonManagerStartup::AddonManagerStartup() = default; + +nsIFile* AddonManagerStartup::ProfileDir() { + if (!mProfileDir) { + nsresult rv; + + rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, + getter_AddRefs(mProfileDir)); + MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv)); + } + + return mProfileDir; +} + +NS_IMPL_ISUPPORTS(AddonManagerStartup, amIAddonManagerStartup, nsIObserver) + +/***************************************************************************** + * URI utils + *****************************************************************************/ + +static nsresult ParseJARURI(nsIJARURI* uri, nsIURI** jarFile, + nsCString& entry) { + MOZ_TRY(uri->GetJARFile(jarFile)); + MOZ_TRY(uri->GetJAREntry(entry)); + + // The entry portion of a jar: URI is required to begin with a '/', but for + // nested JAR URIs, the leading / of the outer entry is currently stripped. + // This is a bug which should be fixed in the JAR URI code, but... + if (entry.IsEmpty() || entry[0] != '/') { + entry.Insert('/', 0); + } + return NS_OK; +} + +static nsresult ParseJARURI(nsIURI* uri, nsIURI** jarFile, nsCString& entry) { + nsresult rv; + nsCOMPtr jarURI = do_QueryInterface(uri, &rv); + MOZ_TRY(rv); + + return ParseJARURI(jarURI, jarFile, entry); +} + +static Result, nsresult> GetFile(nsIURI* uri) { + nsresult rv; + nsCOMPtr fileURL = do_QueryInterface(uri, &rv); + MOZ_TRY(rv); + + nsCOMPtr file; + MOZ_TRY(fileURL->GetFile(getter_AddRefs(file))); + MOZ_ASSERT(file); + + return std::move(file); +} + +/***************************************************************************** + * File utils + *****************************************************************************/ + +static already_AddRefed CloneAndAppend(nsIFile* aFile, + const char* name) { + nsCOMPtr file; + aFile->Clone(getter_AddRefs(file)); + file->AppendNative(nsDependentCString(name)); + return file.forget(); +} + +static bool IsNormalFile(nsIFile* file) { + bool result; + return NS_SUCCEEDED(file->IsFile(&result)) && result; +} + +static const char STRUCTURED_CLONE_MAGIC[] = "mozJSSCLz40v001"; + +template +static Result DecodeLZ4(const nsACString& lz4, + const T& magicNumber) { + constexpr auto HEADER_SIZE = sizeof(magicNumber) + 4; + + // Note: We want to include the null terminator here. + nsDependentCSubstring magic(magicNumber, sizeof(magicNumber)); + + if (lz4.Length() < HEADER_SIZE || StringHead(lz4, magic.Length()) != magic) { + return Err(NS_ERROR_UNEXPECTED); + } + + auto data = lz4.BeginReading() + magic.Length(); + auto size = LittleEndian::readUint32(data); + data += 4; + + size_t dataLen = lz4.EndReading() - data; + size_t outputSize; + + nsCString result; + if (!result.SetLength(size, fallible) || + !LZ4::decompress(data, dataLen, result.BeginWriting(), size, + &outputSize)) { + return Err(NS_ERROR_UNEXPECTED); + } + + MOZ_DIAGNOSTIC_ASSERT(size == outputSize); + + return std::move(result); +} + +// Our zlib headers redefine this to MOZ_Z_compress, which breaks LZ4::compress +#undef compress + +template +static Result EncodeLZ4(const nsACString& data, + const T& magicNumber) { + // Note: We want to include the null terminator here. + nsDependentCSubstring magic(magicNumber, sizeof(magicNumber)); + + nsAutoCString result; + result.Append(magic); + + auto off = result.Length(); + if (!result.SetLength(off + 4, fallible)) { + return Err(NS_ERROR_OUT_OF_MEMORY); + } + + LittleEndian::writeUint32(result.BeginWriting() + off, data.Length()); + off += 4; + + auto size = LZ4::maxCompressedSize(data.Length()); + if (!result.SetLength(off + size, fallible)) { + return Err(NS_ERROR_OUT_OF_MEMORY); + } + + size = LZ4::compress(data.BeginReading(), data.Length(), + result.BeginWriting() + off); + + if (!result.SetLength(off + size, fallible)) { + return Err(NS_ERROR_OUT_OF_MEMORY); + } + return std::move(result); +} + +static_assert(sizeof STRUCTURED_CLONE_MAGIC % 8 == 0, + "Magic number should be an array of uint64_t"); + +/** + * Reads the contents of a LZ4-compressed file, as stored by the OS.File + * module, and returns the decompressed contents on success. + */ +static Result ReadFileLZ4(nsIFile* file) { + static const char MAGIC_NUMBER[] = "mozLz40"; + + nsCString lz4; + MOZ_TRY_VAR(lz4, URLPreloader::ReadFile(file)); + + if (lz4.IsEmpty()) { + return lz4; + } + + return DecodeLZ4(lz4, MAGIC_NUMBER); +} + +static bool ParseJSON(JSContext* cx, nsACString& jsonData, + JS::MutableHandle result) { + NS_ConvertUTF8toUTF16 str(jsonData); + jsonData.Truncate(); + + return JS_ParseJSON(cx, str.Data(), str.Length(), result); +} + +static Result, nsresult> GetJarCache() { + nsCOMPtr ios = components::IO::Service(); + NS_ENSURE_TRUE(ios, Err(NS_ERROR_FAILURE)); + + nsCOMPtr jarProto; + MOZ_TRY(ios->GetProtocolHandler("jar", getter_AddRefs(jarProto))); + + auto jar = static_cast(jarProto.get()); + MOZ_ASSERT(jar); + + nsCOMPtr zipCache = jar->JarCache(); + return std::move(zipCache); +} + +static Result GetFileLocation(nsIURI* uri) { + FileLocation location; + + nsCOMPtr fileURL = do_QueryInterface(uri); + nsCOMPtr file; + if (fileURL) { + MOZ_TRY(fileURL->GetFile(getter_AddRefs(file))); + location.Init(file); + } else { + nsCOMPtr fileURI; + nsCString entry; + MOZ_TRY(ParseJARURI(uri, getter_AddRefs(fileURI), entry)); + + MOZ_TRY_VAR(file, GetFile(fileURI)); + + location.Init(file, entry.get()); + } + + return std::move(location); +} + +/***************************************************************************** + * JSON data handling + *****************************************************************************/ + +class MOZ_STACK_CLASS WrapperBase { + protected: + WrapperBase(JSContext* cx, JSObject* object) : mCx(cx), mObject(cx, object) {} + + WrapperBase(JSContext* cx, const JS::Value& value) : mCx(cx), mObject(cx) { + if (value.isObject()) { + mObject = &value.toObject(); + } else { + mObject = JS_NewPlainObject(cx); + } + } + + protected: + JSContext* mCx; + JS::Rooted mObject; + + bool GetBool(const char* name, bool defVal = false); + + double GetNumber(const char* name, double defVal = 0); + + nsString GetString(const char* name, const char* defVal = ""); + + JSObject* GetObject(const char* name); +}; + +bool WrapperBase::GetBool(const char* name, bool defVal) { + JS::Rooted obj(mCx, mObject); + + JS::Rooted val(mCx, JS::UndefinedValue()); + if (!JS_GetProperty(mCx, obj, name, &val)) { + JS_ClearPendingException(mCx); + } + + if (val.isBoolean()) { + return val.toBoolean(); + } + return defVal; +} + +double WrapperBase::GetNumber(const char* name, double defVal) { + JS::Rooted obj(mCx, mObject); + + JS::Rooted val(mCx, JS::UndefinedValue()); + if (!JS_GetProperty(mCx, obj, name, &val)) { + JS_ClearPendingException(mCx); + } + + if (val.isNumber()) { + return val.toNumber(); + } + return defVal; +} + +nsString WrapperBase::GetString(const char* name, const char* defVal) { + JS::Rooted obj(mCx, mObject); + + JS::Rooted val(mCx, JS::UndefinedValue()); + if (!JS_GetProperty(mCx, obj, name, &val)) { + JS_ClearPendingException(mCx); + } + + nsString res; + if (val.isString()) { + AssignJSString(mCx, res, val.toString()); + } else { + res.AppendASCII(defVal); + } + return res; +} + +JSObject* WrapperBase::GetObject(const char* name) { + JS::Rooted obj(mCx, mObject); + + JS::Rooted val(mCx, JS::UndefinedValue()); + if (!JS_GetProperty(mCx, obj, name, &val)) { + JS_ClearPendingException(mCx); + } + + if (val.isObject()) { + return &val.toObject(); + } + return nullptr; +} + +class MOZ_STACK_CLASS InstallLocation : public WrapperBase { + public: + InstallLocation(JSContext* cx, const JS::Value& value); + + MOZ_IMPLICIT InstallLocation(PropertyIterElem& iter) + : InstallLocation(iter.Cx(), iter.Value()) {} + + InstallLocation(const InstallLocation& other) + : InstallLocation(other.mCx, JS::ObjectValue(*other.mObject)) {} + + void SetChanged(bool changed) { + JS::Rooted obj(mCx, mObject); + + JS::Rooted val(mCx, JS::BooleanValue(changed)); + if (!JS_SetProperty(mCx, obj, "changed", val)) { + JS_ClearPendingException(mCx); + } + } + + PropertyIter& Addons() { return mAddonsIter.ref(); } + + nsString Path() { return GetString("path"); } + + bool ShouldCheckStartupModifications() { + return GetBool("checkStartupModifications"); + } + + private: + JS::Rooted mAddonsObj; + Maybe mAddonsIter; +}; + +class MOZ_STACK_CLASS Addon : public WrapperBase { + public: + Addon(JSContext* cx, InstallLocation& location, const nsAString& id, + JSObject* object) + : WrapperBase(cx, object), mId(id), mLocation(location) {} + + MOZ_IMPLICIT Addon(PropertyIterElem& iter) + : WrapperBase(iter.Cx(), iter.Value()), + mId(iter.Name()), + mLocation(*static_cast(iter.Context())) {} + + Addon(const Addon& other) + : WrapperBase(other.mCx, other.mObject), + mId(other.mId), + mLocation(other.mLocation) {} + + const nsString& Id() { return mId; } + + nsString Path() { return GetString("path"); } + + nsString Type() { return GetString("type", "extension"); } + + bool Enabled() { return GetBool("enabled"); } + + double LastModifiedTime() { return GetNumber("lastModifiedTime"); } + + bool ShouldCheckStartupModifications() { + return Type().EqualsLiteral("locale"); + } + + Result, nsresult> FullPath(); + + Result UpdateLastModifiedTime(); + + private: + nsString mId; + InstallLocation& mLocation; +}; + +Result, nsresult> Addon::FullPath() { + nsString path = Path(); + + // First check for an absolute path, in case we have a proxy file. + nsCOMPtr file; + if (NS_SUCCEEDED(NS_NewLocalFile(path, false, getter_AddRefs(file)))) { + return std::move(file); + } + + // If not an absolute path, fall back to a relative path from the location. + MOZ_TRY(NS_NewLocalFile(mLocation.Path(), false, getter_AddRefs(file))); + + MOZ_TRY(file->AppendRelativePath(path)); + return std::move(file); +} + +Result Addon::UpdateLastModifiedTime() { + nsCOMPtr file; + MOZ_TRY_VAR(file, FullPath()); + + JS::Rooted obj(mCx, mObject); + + bool result; + if (NS_FAILED(file->Exists(&result)) || !result) { + JS::Rooted value(mCx, JS::NullValue()); + if (!JS_SetProperty(mCx, obj, "currentModifiedTime", value)) { + JS_ClearPendingException(mCx); + } + + return true; + } + + PRTime time; + + nsCOMPtr manifest = file; + if (!IsNormalFile(manifest)) { + manifest = CloneAndAppend(file, "manifest.json"); + if (!IsNormalFile(manifest)) { + return true; + } + } + + if (NS_FAILED(manifest->GetLastModifiedTime(&time))) { + return true; + } + + double lastModified = time; + JS::Rooted value(mCx, JS::NumberValue(lastModified)); + if (!JS_SetProperty(mCx, obj, "currentModifiedTime", value)) { + JS_ClearPendingException(mCx); + } + + return lastModified != LastModifiedTime(); +} + +InstallLocation::InstallLocation(JSContext* cx, const JS::Value& value) + : WrapperBase(cx, value), mAddonsObj(cx), mAddonsIter() { + mAddonsObj = GetObject("addons"); + if (!mAddonsObj) { + mAddonsObj = JS_NewPlainObject(cx); + } + mAddonsIter.emplace(cx, mAddonsObj, this); +} + +/***************************************************************************** + * XPC interfacing + *****************************************************************************/ + +nsresult AddonManagerStartup::ReadStartupData( + JSContext* cx, JS::MutableHandle locations) { + locations.set(JS::UndefinedValue()); + + nsCOMPtr file = + CloneAndAppend(ProfileDir(), "addonStartup.json.lz4"); + + nsCString data; + auto res = ReadFileLZ4(file); + if (res.isOk()) { + data = res.unwrap(); + } else if (res.inspectErr() != NS_ERROR_FILE_NOT_FOUND) { + return res.unwrapErr(); + } + + if (data.IsEmpty() || !ParseJSON(cx, data, locations)) { + return NS_OK; + } + + if (!locations.isObject()) { + return NS_ERROR_UNEXPECTED; + } + + JS::Rooted locs(cx, &locations.toObject()); + for (auto e1 : PropertyIter(cx, locs)) { + InstallLocation loc(e1); + + bool shouldCheck = loc.ShouldCheckStartupModifications(); + + for (auto e2 : loc.Addons()) { + Addon addon(e2); + + if (addon.Enabled() && + (shouldCheck || addon.ShouldCheckStartupModifications())) { + bool changed; + MOZ_TRY_VAR(changed, addon.UpdateLastModifiedTime()); + if (changed) { + loc.SetChanged(true); + } + } + } + } + + return NS_OK; +} + +nsresult AddonManagerStartup::EncodeBlob(JS::Handle value, + JSContext* cx, + JS::MutableHandle result) { + StructuredCloneData holder; + + ErrorResult rv; + holder.Write(cx, value, rv); + if (rv.Failed()) { + return rv.StealNSResult(); + } + + nsAutoCString scData; + + holder.Data().ForEachDataChunk([&](const char* aData, size_t aSize) { + scData.Append(nsDependentCSubstring(aData, aSize)); + return true; + }); + + nsCString lz4; + MOZ_TRY_VAR(lz4, EncodeLZ4(scData, STRUCTURED_CLONE_MAGIC)); + + JS::Rooted obj(cx); + MOZ_TRY(nsContentUtils::CreateArrayBuffer(cx, lz4, &obj.get())); + + result.set(JS::ObjectValue(*obj)); + return NS_OK; +} + +nsresult AddonManagerStartup::DecodeBlob(JS::Handle value, + JSContext* cx, + JS::MutableHandle result) { + NS_ENSURE_TRUE(value.isObject() && + JS::IsArrayBufferObject(&value.toObject()) && + JS::ArrayBufferHasData(&value.toObject()), + NS_ERROR_INVALID_ARG); + + StructuredCloneData holder; + + nsCString data; + { + JS::AutoCheckCannotGC nogc; + + auto obj = &value.toObject(); + bool isShared; + + size_t len = JS::GetArrayBufferByteLength(obj); + NS_ENSURE_TRUE(len <= INT32_MAX, NS_ERROR_INVALID_ARG); + nsDependentCSubstring lz4( + reinterpret_cast(JS::GetArrayBufferData(obj, &isShared, nogc)), + uint32_t(len)); + + MOZ_TRY_VAR(data, DecodeLZ4(lz4, STRUCTURED_CLONE_MAGIC)); + } + + bool ok = holder.CopyExternalData(data.get(), data.Length()); + NS_ENSURE_TRUE(ok, NS_ERROR_OUT_OF_MEMORY); + + ErrorResult rv; + holder.Read(cx, result, rv); + return rv.StealNSResult(); + ; +} + +static nsresult EnumerateZip(nsIZipReader* zip, const nsACString& pattern, + nsTArray& results) { + nsCOMPtr entries; + MOZ_TRY(zip->FindEntries(pattern, getter_AddRefs(entries))); + + bool hasMore; + while (NS_SUCCEEDED(entries->HasMore(&hasMore)) && hasMore) { + nsAutoCString name; + MOZ_TRY(entries->GetNext(name)); + + results.AppendElement(NS_ConvertUTF8toUTF16(name)); + } + + return NS_OK; +} + +nsresult AddonManagerStartup::EnumerateJAR(nsIURI* uri, + const nsACString& pattern, + nsTArray& results) { + nsCOMPtr zipCache; + MOZ_TRY_VAR(zipCache, GetJarCache()); + + nsCOMPtr zip; + nsCOMPtr file; + if (nsCOMPtr jarURI = do_QueryInterface(uri)) { + nsCOMPtr fileURI; + nsCString entry; + MOZ_TRY(ParseJARURI(jarURI, getter_AddRefs(fileURI), entry)); + + MOZ_TRY_VAR(file, GetFile(fileURI)); + MOZ_TRY( + zipCache->GetInnerZip(file, Substring(entry, 1), getter_AddRefs(zip))); + } else { + MOZ_TRY_VAR(file, GetFile(uri)); + MOZ_TRY(zipCache->GetZip(file, getter_AddRefs(zip))); + } + MOZ_ASSERT(zip); + + return EnumerateZip(zip, pattern, results); +} + +nsresult AddonManagerStartup::EnumerateJARSubtree(nsIURI* uri, + nsTArray& results) { + nsCOMPtr fileURI; + nsCString entry; + MOZ_TRY(ParseJARURI(uri, getter_AddRefs(fileURI), entry)); + + // Mangle the path into a pattern to match all child entries by escaping any + // existing pattern matching metacharacters it contains and appending "/*". + constexpr auto metaChars = "[]()?*~|$\\"_ns; + + nsCString pattern; + pattern.SetCapacity(entry.Length()); + + // The first character of the entry name is "/", which we want to skip. + for (auto chr : Span(Substring(entry, 1))) { + if (metaChars.FindChar(chr) >= 0) { + pattern.Append('\\'); + } + pattern.Append(chr); + } + if (!pattern.IsEmpty() && !StringEndsWith(pattern, "/"_ns)) { + pattern.Append('/'); + } + pattern.Append('*'); + + return EnumerateJAR(fileURI, pattern, results); +} + +nsresult AddonManagerStartup::InitializeURLPreloader() { + MOZ_RELEASE_ASSERT(xpc::IsInAutomation()); + + URLPreloader::ReInitialize(); + + return NS_OK; +} + +/****************************************************************************** + * RegisterChrome + ******************************************************************************/ + +namespace { +static bool sObserverRegistered; + +struct ContentEntry final { + explicit ContentEntry(nsTArray&& aArgs, uint8_t aFlags = 0) + : mArgs(std::move(aArgs)), mFlags(aFlags) {} + + AutoTArray mArgs; + uint8_t mFlags; +}; + +}; // anonymous namespace +}; // namespace mozilla + +MOZ_DECLARE_RELOCATE_USING_MOVE_CONSTRUCTOR(mozilla::ContentEntry); + +namespace mozilla { +namespace { + +class RegistryEntries final : public nsIJSRAIIHelper, + public LinkedListElement { + public: + NS_DECL_ISUPPORTS + NS_DECL_NSIJSRAIIHELPER + + using Override = AutoTArray; + using Locale = AutoTArray; + + RegistryEntries(FileLocation& location, nsTArray&& overrides, + nsTArray&& content, nsTArray&& locales) + : mLocation(location), + mOverrides(std::move(overrides)), + mContent(std::move(content)), + mLocales(std::move(locales)) {} + + void Register(); + + protected: + virtual ~RegistryEntries() { Unused << Destruct(); } + + private: + FileLocation mLocation; + const nsTArray mOverrides; + const nsTArray mContent; + const nsTArray mLocales; +}; + +NS_IMPL_ISUPPORTS(RegistryEntries, nsIJSRAIIHelper) + +void RegistryEntries::Register() { + RefPtr cr = nsChromeRegistry::GetSingleton(); + + nsChromeRegistry::ManifestProcessingContext context(NS_EXTENSION_LOCATION, + mLocation); + + for (auto& override : mOverrides) { + const char* args[] = {override[0].get(), override[1].get()}; + cr->ManifestOverride(context, 0, const_cast(args), 0); + } + + for (auto& content : mContent) { + const char* args[] = {content.mArgs[0].get(), content.mArgs[1].get()}; + cr->ManifestContent(context, 0, const_cast(args), content.mFlags); + } + + for (auto& locale : mLocales) { + const char* args[] = {locale[0].get(), locale[1].get(), locale[2].get()}; + cr->ManifestLocale(context, 0, const_cast(args), 0); + } +} + +NS_IMETHODIMP +RegistryEntries::Destruct() { + if (isInList()) { + remove(); + + // No point in doing I/O to check for new chrome during shutdown, return + // early in that case. + if (AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownConfirmed)) { + return NS_OK; + } + + // When we remove dynamic entries from the registry, we need to rebuild it + // in order to ensure a consistent state. See comments in Observe(). + RefPtr cr = nsChromeRegistry::GetSingleton(); + return cr->CheckForNewChrome(); + } + return NS_OK; +} + +static LinkedList& GetRegistryEntries() { + static LinkedList sEntries; + return sEntries; +} +}; // anonymous namespace + +NS_IMETHODIMP +AddonManagerStartup::RegisterChrome(nsIURI* manifestURI, + JS::Handle locations, + JSContext* cx, nsIJSRAIIHelper** result) { + auto IsArray = [cx](JS::Handle val) -> bool { + bool isArray; + return JS::IsArrayObject(cx, val, &isArray) && isArray; + }; + + NS_ENSURE_ARG_POINTER(manifestURI); + NS_ENSURE_TRUE(IsArray(locations), NS_ERROR_INVALID_ARG); + + FileLocation location; + MOZ_TRY_VAR(location, GetFileLocation(manifestURI)); + + nsTArray locales; + nsTArray content; + nsTArray overrides; + + JS::Rooted locs(cx, &locations.toObject()); + JS::Rooted arrayVal(cx); + JS::Rooted array(cx); + + for (auto elem : ArrayIter(cx, locs)) { + arrayVal = elem.Value(); + NS_ENSURE_TRUE(IsArray(arrayVal), NS_ERROR_INVALID_ARG); + + array = &arrayVal.toObject(); + + AutoTArray vals; + for (auto val : ArrayIter(cx, array)) { + nsAutoJSString str; + NS_ENSURE_TRUE(str.init(cx, val.Value()), NS_ERROR_OUT_OF_MEMORY); + + vals.AppendElement(NS_ConvertUTF16toUTF8(str)); + } + NS_ENSURE_TRUE(vals.Length() > 0, NS_ERROR_INVALID_ARG); + + nsCString type = vals[0]; + vals.RemoveElementAt(0); + + if (type.EqualsLiteral("override")) { + NS_ENSURE_TRUE(vals.Length() == 2, NS_ERROR_INVALID_ARG); + overrides.AppendElement(std::move(vals)); + } else if (type.EqualsLiteral("content")) { + if (vals.Length() == 3 && + vals[2].EqualsLiteral("contentaccessible=yes")) { + NS_ENSURE_TRUE(xpc::IsInAutomation(), NS_ERROR_INVALID_ARG); + vals.RemoveElementAt(2); + content.AppendElement(ContentEntry( + std::move(vals), nsChromeRegistry::CONTENT_ACCESSIBLE)); + } else { + NS_ENSURE_TRUE(vals.Length() == 2, NS_ERROR_INVALID_ARG); + content.AppendElement(ContentEntry(std::move(vals))); + } + } else if (type.EqualsLiteral("locale")) { + NS_ENSURE_TRUE(vals.Length() == 3, NS_ERROR_INVALID_ARG); + locales.AppendElement(std::move(vals)); + } else { + return NS_ERROR_INVALID_ARG; + } + } + + if (!sObserverRegistered) { + nsCOMPtr obs = services::GetObserverService(); + NS_ENSURE_TRUE(obs, NS_ERROR_UNEXPECTED); + obs->AddObserver(this, "chrome-manifests-loaded", false); + + sObserverRegistered = true; + } + + auto entry = MakeRefPtr( + location, std::move(overrides), std::move(content), std::move(locales)); + + entry->Register(); + GetRegistryEntries().insertBack(entry); + + entry.forget(result); + return NS_OK; +} + +NS_IMETHODIMP +AddonManagerStartup::Observe(nsISupports* subject, const char* topic, + const char16_t* data) { + // The chrome registry is maintained as a set of global resource mappings + // generated mainly from manifest files, on-the-fly, as they're parsed. + // Entries added later override entries added earlier, and no record is kept + // of the former state. + // + // As a result, if we remove a dynamically-added manifest file, or a set of + // dynamic entries, the registry needs to be rebuilt from scratch, from the + // manifests and dynamic entries that remain. The chrome registry itself + // takes care of re-parsing manifes files. This observer notification lets + // us know when we need to re-register our dynamic entries. + if (!strcmp(topic, "chrome-manifests-loaded")) { + for (auto entry : GetRegistryEntries()) { + entry->Register(); + } + } + + return NS_OK; +} + +} // namespace mozilla diff --git a/toolkit/mozapps/extensions/AddonManagerStartup.h b/toolkit/mozapps/extensions/AddonManagerStartup.h new file mode 100644 index 0000000000..a1cb5c9506 --- /dev/null +++ b/toolkit/mozapps/extensions/AddonManagerStartup.h @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef AddonManagerStartup_h +#define AddonManagerStartup_h + +#include "amIAddonManagerStartup.h" +#include "mozilla/Result.h" +#include "nsCOMArray.h" +#include "nsCOMPtr.h" +#include "nsIFile.h" +#include "nsIObserver.h" +#include "nsISupports.h" + +namespace mozilla { + +class Addon; + +class AddonManagerStartup final : public amIAddonManagerStartup, + public nsIObserver { + public: + NS_DECL_ISUPPORTS + NS_DECL_AMIADDONMANAGERSTARTUP + NS_DECL_NSIOBSERVER + + AddonManagerStartup(); + + static AddonManagerStartup& GetSingleton(); + + static already_AddRefed GetInstance() { + RefPtr inst = &GetSingleton(); + return inst.forget(); + } + + private: + nsIFile* ProfileDir(); + + nsCOMPtr mProfileDir; + + protected: + virtual ~AddonManagerStartup() = default; +}; + +} // namespace mozilla + +#define NS_ADDONMANAGERSTARTUP_CONTRACTID \ + "@mozilla.org/addons/addon-manager-startup;1" + +// {17a59a6b-92b8-42e5-bce0-ab434c7a7135 +#define NS_ADDON_MANAGER_STARTUP_CID \ + { \ + 0x17a59a6b, 0x92b8, 0x42e5, { \ + 0xbc, 0xe0, 0xab, 0x43, 0x4c, 0x7a, 0x71, 0x35 \ + } \ + } + +#endif // AddonManagerStartup_h diff --git a/toolkit/mozapps/extensions/AddonManagerWebAPI.cpp b/toolkit/mozapps/extensions/AddonManagerWebAPI.cpp new file mode 100644 index 0000000000..a249a37110 --- /dev/null +++ b/toolkit/mozapps/extensions/AddonManagerWebAPI.cpp @@ -0,0 +1,169 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "AddonManagerWebAPI.h" + +#include "mozilla/BasePrincipal.h" +#include "mozilla/dom/Navigator.h" +#include "mozilla/dom/NavigatorBinding.h" + +#include "mozilla/Preferences.h" +#include "mozilla/StaticPrefs_extensions.h" +#include "nsGlobalWindow.h" +#include "xpcpublic.h" + +#include "nsIDocShell.h" +#include "nsIScriptObjectPrincipal.h" + +namespace mozilla { +using namespace mozilla::dom; + +#ifndef MOZ_THUNDERBIRD +# define MOZ_AMO_HOSTNAME "addons.mozilla.org" +# define MOZ_AMO_STAGE_HOSTNAME "addons.allizom.org" +# define MOZ_AMO_DEV_HOSTNAME "addons-dev.allizom.org" +#else +# define MOZ_AMO_HOSTNAME "addons.thunderbird.net" +# define MOZ_AMO_STAGE_HOSTNAME "addons-stage.thunderbird.net" +# undef MOZ_AMO_DEV_HOSTNAME +#endif + +static bool IsValidHost(const nsACString& host) { + // This hidden pref allows users to disable mozAddonManager entirely if they + // want for fingerprinting resistance. Someone like Tor browser will use this + // pref. + if (StaticPrefs::privacy_resistFingerprinting_block_mozAddonManager()) { + return false; + } + + if (host.EqualsLiteral(MOZ_AMO_HOSTNAME)) { + return true; + } + + // When testing allow access to the developer sites. + if (StaticPrefs::extensions_webapi_testing()) { + if (host.LowerCaseEqualsLiteral(MOZ_AMO_STAGE_HOSTNAME) || +#ifdef MOZ_AMO_DEV_HOSTNAME + host.LowerCaseEqualsLiteral(MOZ_AMO_DEV_HOSTNAME) || +#endif + host.LowerCaseEqualsLiteral("example.com")) { + return true; + } + } + + return false; +} + +// Checks if the given uri is secure and matches one of the hosts allowed to +// access the API. +bool AddonManagerWebAPI::IsValidSite(nsIURI* uri) { + if (!uri) { + return false; + } + + if (!uri->SchemeIs("https")) { + if (!(xpc::IsInAutomation() && + StaticPrefs::extensions_webapi_testing_http())) { + return false; + } + } + + nsAutoCString host; + nsresult rv = uri->GetHost(host); + if (NS_FAILED(rv)) { + return false; + } + + return IsValidHost(host); +} + +#ifndef ANDROID +bool AddonManagerWebAPI::IsAPIEnabled(JSContext* aCx, JSObject* aGlobal) { + MOZ_DIAGNOSTIC_ASSERT(JS_IsGlobalObject(aGlobal)); + nsCOMPtr win = xpc::WindowOrNull(aGlobal); + if (!win) { + return false; + } + + // Check that the current window and all parent frames are allowed access to + // the API. + while (win) { + nsCOMPtr sop = do_QueryInterface(win); + if (!sop) { + return false; + } + + nsCOMPtr principal = sop->GetPrincipal(); + if (!principal) { + return false; + } + + // Reaching a window with a system principal means we have reached + // privileged UI of some kind so stop at this point and allow access. + if (principal->IsSystemPrincipal()) { + return true; + } + + nsCOMPtr docShell = win->GetDocShell(); + if (!docShell) { + // This window has been torn down so don't allow access to the API. + return false; + } + + if (!IsValidSite(win->GetDocumentURI())) { + return false; + } + + // Checks whether there is a parent frame of the same type. This won't cross + // mozbrowser or chrome or fission/process boundaries. + nsCOMPtr parent; + nsresult rv = docShell->GetInProcessSameTypeParent(getter_AddRefs(parent)); + if (NS_FAILED(rv)) { + return false; + } + + // No parent means we've hit a mozbrowser or chrome or process boundary. + if (!parent) { + // With Fission, a cross-origin iframe has an out-of-process parent, but + // DocShell knows nothing about it. We need to ask BrowsingContext here, + // and only allow API access if AMO is actually at the top, not framed + // by evilleagueofevil.com. + return docShell->GetBrowsingContext()->IsTopContent(); + } + + Document* doc = win->GetDoc(); + if (!doc) { + return false; + } + + doc = doc->GetInProcessParentDocument(); + if (!doc) { + // Getting here means something has been torn down so fail safe. + return false; + } + + win = doc->GetInnerWindow(); + } + + // Found a document with no inner window, don't grant access to the API. + return false; +} +#else // We don't support mozAddonManager on Android +bool AddonManagerWebAPI::IsAPIEnabled(JSContext* aCx, JSObject* aGlobal) { + return false; +} +#endif // ifndef ANDROID + +namespace dom { + +bool AddonManagerPermissions::IsHostPermitted(const GlobalObject& /*unused*/, + const nsAString& host) { + return IsValidHost(NS_ConvertUTF16toUTF8(host)); +} + +} // namespace dom + +} // namespace mozilla diff --git a/toolkit/mozapps/extensions/AddonManagerWebAPI.h b/toolkit/mozapps/extensions/AddonManagerWebAPI.h new file mode 100644 index 0000000000..4f34b366a4 --- /dev/null +++ b/toolkit/mozapps/extensions/AddonManagerWebAPI.h @@ -0,0 +1,32 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef addonmanagerwebapi_h_ +#define addonmanagerwebapi_h_ + +#include "nsPIDOMWindow.h" + +namespace mozilla { + +class AddonManagerWebAPI { + public: + static bool IsAPIEnabled(JSContext* aCx, JSObject* aGlobal); + + static bool IsValidSite(nsIURI* uri); +}; + +namespace dom { + +class AddonManagerPermissions { + public: + static bool IsHostPermitted(const GlobalObject&, const nsAString& host); +}; + +} // namespace dom + +} // namespace mozilla + +#endif // addonmanagerwebapi_h_ diff --git a/toolkit/mozapps/extensions/Blocklist.jsm b/toolkit/mozapps/extensions/Blocklist.jsm new file mode 100644 index 0000000000..6696ad42bd --- /dev/null +++ b/toolkit/mozapps/extensions/Blocklist.jsm @@ -0,0 +1,1468 @@ +/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ + +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +/* eslint "valid-jsdoc": [2, {requireReturn: false}] */ + +var EXPORTED_SYMBOLS = ["Blocklist", "BlocklistPrivate"]; + +const { XPCOMUtils } = ChromeUtils.importESModule( + "resource://gre/modules/XPCOMUtils.sys.mjs" +); +const { AppConstants } = ChromeUtils.importESModule( + "resource://gre/modules/AppConstants.sys.mjs" +); +const lazy = {}; +ChromeUtils.defineModuleGetter( + lazy, + "AddonManager", + "resource://gre/modules/AddonManager.jsm" +); +ChromeUtils.defineModuleGetter( + lazy, + "AddonManagerPrivate", + "resource://gre/modules/AddonManager.jsm" +); +ChromeUtils.defineModuleGetter( + lazy, + "RemoteSettings", + "resource://services-settings/remote-settings.js" +); +ChromeUtils.defineModuleGetter( + lazy, + "jexlFilterFunc", + "resource://services-settings/remote-settings.js" +); + +const CascadeFilter = Components.Constructor( + "@mozilla.org/cascade-filter;1", + "nsICascadeFilter", + "setFilterData" +); + +// The whole ID should be surrounded by literal (). +// IDs may contain alphanumerics, _, -, {}, @ and a literal '.' +// They may also contain backslashes (needed to escape the {} and dot) +// We filter out backslash escape sequences (like `\w`) separately +// (see kEscapeSequences). +const kIdSubRegex = + "\\([" + + "\\\\" + // note: just a backslash, but between regex and string it needs escaping. + "\\w .{}@-]+\\)"; + +// prettier-ignore +// Find regular expressions of the form: +// /^((id1)|(id2)|(id3)|...|(idN))$/ +// The outer set of parens enclosing the entire list of IDs is optional. +const kIsMultipleIds = new RegExp( + // Start with literal sequence /^( + // (the `(` is optional) + "^/\\^\\(?" + + // Then at least one ID in parens (). + kIdSubRegex + + // Followed by any number of IDs in () separated by pipes. + // Note: using a non-capturing group because we don't care about the value. + "(?:\\|" + kIdSubRegex + ")*" + + // Finally, we need to end with literal sequence )$/ + // (the leading `)` is optional like at the start) + "\\)?\\$/$" +); + +// Check for a backslash followed by anything other than a literal . or curlies +const kEscapeSequences = /\\[^.{}]/; + +// Used to remove the following 3 things: +// leading literal /^( +// plus an optional ( +// any backslash +// trailing literal )$/ +// plus an optional ) before the )$/ +const kRegExpRemovalRegExp = /^\/\^\(\(?|\\|\)\)?\$\/$/g; + +// In order to block add-ons, their type should be part of this list. There +// may be additional requirements such as requiring the add-on to be signed. +// See the uses of kXPIAddonTypes before introducing new addon types or +// providers that differ from the existing types. +XPCOMUtils.defineLazyGetter(lazy, "kXPIAddonTypes", () => { + // In practice, this result is equivalent to ALL_XPI_TYPES in XPIProvider.jsm. + // "plugin" (from GMPProvider.sys.mjs) is intentionally omitted, as we decided to + // not support blocklisting of GMP plugins in bug 1086668. + return lazy.AddonManagerPrivate.getAddonTypesByProvider("XPIProvider"); +}); + +// For a given input string matcher, produce either a string to compare with, +// a regular expression, or a set of strings to compare with. +function processMatcher(str) { + if (!str.startsWith("/")) { + return str; + } + // Process regexes matching multiple IDs into a set. + if (kIsMultipleIds.test(str) && !kEscapeSequences.test(str)) { + // Remove the regexp gunk at the start and end of the string, as well + // as all backslashes, and split by )|( to leave the list of IDs. + return new Set(str.replace(kRegExpRemovalRegExp, "").split(")|(")); + } + let lastSlash = str.lastIndexOf("/"); + let pattern = str.slice(1, lastSlash); + let flags = str.slice(lastSlash + 1); + return new RegExp(pattern, flags); +} + +// Returns true if the addonProps object passes the constraints set by matches. +// (For every non-null property in matches, the same key must exist in +// addonProps and its value must match) +function doesAddonEntryMatch(matches, addonProps) { + for (let [key, value] of Object.entries(matches)) { + if (value === null || value === undefined) { + continue; + } + if (addonProps[key]) { + // If this property matches (member of the set, matches regex, or + // an exact string match), continue to look at the other properties of + // the `matches` object. + // If not, return false immediately. + if (value.has && value.has(addonProps[key])) { + continue; + } + if (value.test && value.test(addonProps[key])) { + continue; + } + if (typeof value == "string" && value === addonProps[key]) { + continue; + } + } + // If we get here, the property doesn't match, so this entry doesn't match. + return false; + } + // If we get here, all the properties must have matched. + return true; +} + +const TOOLKIT_ID = "toolkit@mozilla.org"; +const PREF_BLOCKLIST_ITEM_URL = "extensions.blocklist.itemURL"; +const PREF_BLOCKLIST_ADDONITEM_URL = "extensions.blocklist.addonItemURL"; +const PREF_BLOCKLIST_ENABLED = "extensions.blocklist.enabled"; +const PREF_BLOCKLIST_LEVEL = "extensions.blocklist.level"; +const PREF_BLOCKLIST_USE_MLBF = "extensions.blocklist.useMLBF"; +const PREF_EM_LOGGING_ENABLED = "extensions.logging.enabled"; +const DEFAULT_SEVERITY = 3; +const DEFAULT_LEVEL = 2; +const MAX_BLOCK_LEVEL = 3; + +const BLOCKLIST_BUCKET = "blocklists"; + +const BlocklistTelemetry = { + init() { + // Used by BlocklistTelemetry.recordAddonBlockChangeTelemetry. + Services.telemetry.setEventRecordingEnabled("blocklist", true); + }, + + /** + * Record the RemoteSettings Blocklist lastModified server time into the + * "blocklist.lastModified_rs keyed scalar (or "Missing Date" when unable + * to retrieve a valid timestamp). + * + * @param {string} blocklistType + * The blocklist type that has been updated ("addons" or "addons_mlbf"); + * the "gfx" blocklist is not covered by this telemetry). + * @param {RemoteSettingsClient} remoteSettingsClient + * The RemoteSettings client to retrieve the lastModified timestamp from. + */ + async recordRSBlocklistLastModified(blocklistType, remoteSettingsClient) { + // In some tests overrides ensureInitialized and remoteSettingsClient + // can be undefined, and in that case we don't want to record any + // telemetry scalar. + if (!remoteSettingsClient) { + return; + } + + let lastModified = await remoteSettingsClient.getLastModified(); + BlocklistTelemetry.recordTimeScalar( + "lastModified_rs_" + blocklistType, + lastModified + ); + }, + + /** + * Record a timestamp in telemetry as a UTC string or "Missing Date" if the + * input is not a valid timestamp. + * + * @param {string} telemetryKey + * The part of after "blocklist.", as defined in Scalars.yaml. + * @param {number} time + * A timestamp to record. If invalid, "Missing Date" will be recorded. + */ + recordTimeScalar(telemetryKey, time) { + if (time > 0) { + // convert from timestamp in ms into UTC datetime string, so it is going + // to be record in the same format previously used by blocklist.lastModified_xml. + let dateString = new Date(time).toUTCString(); + Services.telemetry.scalarSet("blocklist." + telemetryKey, dateString); + } else { + Services.telemetry.scalarSet("blocklist." + telemetryKey, "Missing Date"); + } + }, + + /** + * Record whether an add-on is blocked and the parameters that guided the + * decision to block or unblock the add-on. + * + * @param {AddonWrapper|object} addon + * The blocked or unblocked add-on. Not necessarily installed. + * Could be an object with the id, version and blocklistState + * properties when the AddonWrapper is not available (e.g. during + * update checks). + * @param {string} reason + * The reason for recording the event, + * "addon_install", "addon_update", "addon_update_check", + * "addon_db_modified", "blocklist_update". + */ + recordAddonBlockChangeTelemetry(addon, reason) { + // Reduce the timer resolution for anonymity. + let hoursSinceInstall = -1; + if (reason === "blocklist_update" || reason === "addon_db_modified") { + hoursSinceInstall = Math.round( + (Date.now() - addon.installDate.getTime()) / 3600000 + ); + } + + const value = addon.id; + const extra = { + blocklistState: `${addon.blocklistState}`, + addon_version: addon.version, + signed_date: `${addon.signedDate?.getTime() || 0}`, + hours_since: `${hoursSinceInstall}`, + + ...ExtensionBlocklistMLBF.getBlocklistMetadataForTelemetry(), + }; + + Services.telemetry.recordEvent( + "blocklist", + "addonBlockChange", + reason, + value, + extra + ); + }, +}; + +const Utils = { + /** + * Checks whether this entry is valid for the current OS and ABI. + * If the entry has an "os" property then the current OS must appear in + * its comma separated list for it to be valid. Similarly for the + * xpcomabi property. + * + * @param {Object} item + * The blocklist item. + * @returns {bool} + * Whether the entry matches the current OS. + */ + matchesOSABI(item) { + if (item.os) { + let os = item.os.split(","); + if (!os.includes(lazy.gAppOS)) { + return false; + } + } + + if (item.xpcomabi) { + let xpcomabi = item.xpcomabi.split(","); + if (!xpcomabi.includes(lazy.gApp.XPCOMABI)) { + return false; + } + } + return true; + }, + + /** + * Checks if a version is higher than or equal to the minVersion (if provided) + * and lower than or equal to the maxVersion (if provided). + * @param {string} version + * The version to test. + * @param {string?} minVersion + * The minimum version. If null it is assumed that version is always + * larger. + * @param {string?} maxVersion + * The maximum version. If null it is assumed that version is always + * smaller. + * @returns {boolean} + * Whether the item matches the range. + */ + versionInRange(version, minVersion, maxVersion) { + if (minVersion && Services.vc.compare(version, minVersion) < 0) { + return false; + } + if (maxVersion && Services.vc.compare(version, maxVersion) > 0) { + return false; + } + return true; + }, + + /** + * Tests if this versionRange matches the item specified, and has a matching + * targetApplication id and version. + * @param {Object} versionRange + * The versionRange to check against + * @param {string} itemVersion + * The version of the actual addon/plugin to test for. + * @param {string} appVersion + * The version of the application to test for. + * @param {string} toolkitVersion + * The version of toolkit to check for. + * @returns {boolean} + * True if this version range covers the item and app/toolkit version given. + */ + versionsMatch(versionRange, itemVersion, appVersion, toolkitVersion) { + // Some platforms have no version for plugins, these don't match if there + // was a min/maxVersion provided + if (!itemVersion && (versionRange.minVersion || versionRange.maxVersion)) { + return false; + } + + // Check if the item version matches + if ( + !this.versionInRange( + itemVersion, + versionRange.minVersion, + versionRange.maxVersion + ) + ) { + return false; + } + + // Check if the application or toolkit version matches + for (let tA of versionRange.targetApplication) { + if ( + tA.guid == lazy.gAppID && + this.versionInRange(appVersion, tA.minVersion, tA.maxVersion) + ) { + return true; + } + if ( + tA.guid == TOOLKIT_ID && + this.versionInRange(toolkitVersion, tA.minVersion, tA.maxVersion) + ) { + return true; + } + } + return false; + }, + + /** + * Given a blocklist JS object entry, ensure it has a versionRange property, where + * each versionRange property has a valid severity property + * and at least 1 valid targetApplication. + * If it didn't have a valid targetApplication array before and/or it was empty, + * fill it with an entry with null min/maxVersion properties, which will match + * every version. + * + * If there *are* targetApplications, if any of them don't have a guid property, + * assign them the current app's guid. + * + * @param {Object} entry + * blocklist entry object. + */ + ensureVersionRangeIsSane(entry) { + if (!entry.versionRange.length) { + entry.versionRange.push({}); + } + for (let vr of entry.versionRange) { + if (!vr.hasOwnProperty("severity")) { + vr.severity = DEFAULT_SEVERITY; + } + if (!Array.isArray(vr.targetApplication)) { + vr.targetApplication = []; + } + if (!vr.targetApplication.length) { + vr.targetApplication.push({ minVersion: null, maxVersion: null }); + } + vr.targetApplication.forEach(tA => { + if (!tA.guid) { + tA.guid = lazy.gAppID; + } + }); + } + }, + + /** + * Create a blocklist URL for the given blockID + * @param {String} id the blockID to use + * @returns {String} the blocklist URL. + */ + _createBlocklistURL(id) { + let url = Services.urlFormatter.formatURLPref(PREF_BLOCKLIST_ITEM_URL); + return url.replace(/%blockID%/g, id); + }, +}; + +/** + * This custom filter function is used to limit the entries returned + * by `RemoteSettings("...").get()` depending on the target app information + * defined on entries. + * + * Note that this is async because `jexlFilterFunc` is async. + * + * @param {Object} entry a Remote Settings record + * @param {Object} environment the JEXL environment object. + * @returns {Object} The entry if it matches, `null` otherwise. + */ +async function targetAppFilter(entry, environment) { + // If the entry has a JEXL filter expression, it should prevail. + // The legacy target app mechanism will be kept in place for old entries. + // See https://bugzilla.mozilla.org/show_bug.cgi?id=1463377 + const { filter_expression } = entry; + if (filter_expression) { + return lazy.jexlFilterFunc(entry, environment); + } + + // Keep entries without target information. + if (!("versionRange" in entry)) { + return entry; + } + + const { versionRange } = entry; + + // Everywhere in this method, we avoid checking the minVersion, because + // we want to retain items whose minVersion is higher than the current + // app version, so that we have the items around for app updates. + + // Gfx blocklist has a specific versionRange object, which is not a list. + if (!Array.isArray(versionRange)) { + const { maxVersion = "*" } = versionRange; + const matchesRange = + Services.vc.compare(lazy.gApp.version, maxVersion) <= 0; + return matchesRange ? entry : null; + } + + // Iterate the targeted applications, at least one of them must match. + // If no target application, keep the entry. + if (!versionRange.length) { + return entry; + } + for (const vr of versionRange) { + const { targetApplication = [] } = vr; + if (!targetApplication.length) { + return entry; + } + for (const ta of targetApplication) { + const { guid } = ta; + if (!guid) { + return entry; + } + const { maxVersion = "*" } = ta; + if ( + guid == lazy.gAppID && + Services.vc.compare(lazy.gApp.version, maxVersion) <= 0 + ) { + return entry; + } + if ( + guid == "toolkit@mozilla.org" && + Services.vc.compare(Services.appinfo.platformVersion, maxVersion) <= 0 + ) { + return entry; + } + } + } + // Skip this entry. + return null; +} + +/** + * The Graphics blocklist implementation. The JSON objects for graphics blocks look + * something like: + * + * { + * "blockID": "g35", + * "os": "WINNT 6.1", + * "vendor": "0xabcd", + * "devices": [ + * "0x2783", + * "0x1234", + * ], + * "feature": " DIRECT2D ", + * "featureStatus": " BLOCKED_DRIVER_VERSION ", + * "driverVersion": " 8.52.322.2202 ", + * "driverVersionComparator": " LESS_THAN ", + * "versionRange": {"minVersion": "5.0", "maxVersion: "25.0"}, + * } + * + * The RemoteSetttings client takes care of filtering out versions that don't apply. + * The code here stores entries in memory and sends them to the gfx component in + * serialized text form, using ',', '\t' and '\n' as separators. + */ +const GfxBlocklistRS = { + _ensureInitialized() { + if (this._initialized || !gBlocklistEnabled) { + return; + } + this._initialized = true; + this._client = lazy.RemoteSettings("gfx", { + bucketName: BLOCKLIST_BUCKET, + filterFunc: targetAppFilter, + }); + this.checkForEntries = this.checkForEntries.bind(this); + this._client.on("sync", this.checkForEntries); + }, + + shutdown() { + if (this._client) { + this._client.off("sync", this.checkForEntries); + } + }, + + sync() { + this._ensureInitialized(); + return this._client.sync(); + }, + + async checkForEntries() { + this._ensureInitialized(); + if (!gBlocklistEnabled) { + return []; // return value expected by tests. + } + let entries = await this._client.get().catch(ex => Cu.reportError(ex)); + // Handle error silently. This can happen if our request to fetch data is aborted, + // e.g. by application shutdown. + if (!entries) { + return []; + } + // Trim helper (spaces, tabs, no-break spaces..) + const trim = s => + (s || "").replace(/(^[\s\uFEFF\xA0]+)|([\s\uFEFF\xA0]+$)/g, ""); + + entries = entries.map(entry => { + let props = [ + "blockID", + "driverVersion", + "driverVersionMax", + "driverVersionComparator", + "feature", + "featureStatus", + "os", + "vendor", + "devices", + ]; + let rv = {}; + for (let p of props) { + let val = entry[p]; + // Ignore falsy values or empty arrays. + if (!val || (Array.isArray(val) && !val.length)) { + continue; + } + if (typeof val == "string") { + val = trim(val); + } else if (p == "devices") { + let invalidDevices = []; + let validDevices = []; + // We serialize the array of devices as a comma-separated string, so + // we need to ensure that none of the entries contain commas, also in + // the future. + val.forEach(v => + v.includes(",") ? invalidDevices.push(v) : validDevices.push(v) + ); + for (let dev of invalidDevices) { + const e = new Error( + `Block ${entry.blockID} contains unsupported device: ${dev}` + ); + Cu.reportError(e); + } + if (!validDevices) { + continue; + } + val = validDevices; + } + rv[p] = val; + } + if (entry.versionRange) { + rv.versionRange = { + minVersion: trim(entry.versionRange.minVersion) || "0", + maxVersion: trim(entry.versionRange.maxVersion) || "*", + }; + } + return rv; + }); + if (entries.length) { + let sortedProps = [ + "blockID", + "devices", + "driverVersion", + "driverVersionComparator", + "driverVersionMax", + "feature", + "featureStatus", + "hardware", + "manufacturer", + "model", + "os", + "osversion", + "product", + "vendor", + "versionRange", + ]; + // Notify `GfxInfoBase`, by passing a string serialization. + let payload = []; + for (let gfxEntry of entries) { + let entryLines = []; + for (let key of sortedProps) { + if (gfxEntry[key]) { + let value = gfxEntry[key]; + if (Array.isArray(value)) { + value = value.join(","); + } else if (value.maxVersion) { + // Both minVersion and maxVersion are always set on each entry. + value = value.minVersion + "," + value.maxVersion; + } + entryLines.push(key + ":" + value); + } + } + payload.push(entryLines.join("\t")); + } + Services.obs.notifyObservers( + null, + "blocklist-data-gfxItems", + payload.join("\n") + ); + } + // The return value is only used by tests. + return entries; + }, +}; + +/** + * The extensions blocklist implementation. The JSON objects for extension + * blocks look something like: + * + * { + * "guid": "someguid@addons.mozilla.org", + * "prefs": ["i.am.a.pref.that.needs.resetting"], + * "schema": 1480349193877, + * "blockID": "i12345", + * "details": { + * "bug": "https://bugzilla.mozilla.org/show_bug.cgi?id=1234567", + * "who": "All Firefox users who have this add-on installed. If you wish to continue using this add-on, you can enable it in the Add-ons Manager.", + * "why": "This add-on is in violation of the Add-on Guidelines, using multiple add-on IDs and potentially doing other unwanted activities.", + * "name": "Some pretty name", + * "created": "2019-05-06T19:52:20Z" + * }, + * "enabled": true, + * "versionRange": [ + * { + * "severity": 1, + * "maxVersion": "*", + * "minVersion": "0", + * "targetApplication": [] + * } + * ], + * "id": "", + * "last_modified": 1480349215672, + * } + * + * This is a legacy format, and implements deprecated operations (bug 1620580). + * ExtensionBlocklistMLBF supersedes this implementation. + */ +const ExtensionBlocklistRS = { + async _ensureEntries() { + this.ensureInitialized(); + if (!this._entries && gBlocklistEnabled) { + await this._updateEntries(); + } + }, + + async _updateEntries() { + if (!gBlocklistEnabled) { + this._entries = []; + return; + } + this._entries = await this._client.get().catch(ex => Cu.reportError(ex)); + // Handle error silently. This can happen if our request to fetch data is aborted, + // e.g. by application shutdown. + if (!this._entries) { + this._entries = []; + return; + } + this._entries.forEach(entry => { + entry.matches = {}; + if (entry.guid) { + entry.matches.id = processMatcher(entry.guid); + } + for (let key of EXTENSION_BLOCK_FILTERS) { + if (key == "id" || !entry[key]) { + continue; + } + entry.matches[key] = processMatcher(entry[key]); + } + Utils.ensureVersionRangeIsSane(entry); + }); + + BlocklistTelemetry.recordRSBlocklistLastModified("addons", this._client); + }, + + async _filterItem(entry, environment) { + if (!(await targetAppFilter(entry, environment))) { + return null; + } + if (!Utils.matchesOSABI(entry)) { + return null; + } + // Need something to filter on - at least a guid or name (either could be a regex): + if (!entry.guid && !entry.name) { + let blockID = entry.blockID || entry.id; + Cu.reportError(new Error(`Nothing to filter add-on item ${blockID} on`)); + return null; + } + return entry; + }, + + sync() { + this.ensureInitialized(); + return this._client.sync(); + }, + + ensureInitialized() { + if (!gBlocklistEnabled || this._initialized) { + return; + } + this._initialized = true; + this._client = lazy.RemoteSettings("addons", { + bucketName: BLOCKLIST_BUCKET, + filterFunc: this._filterItem, + }); + this._onUpdate = this._onUpdate.bind(this); + this._client.on("sync", this._onUpdate); + }, + + shutdown() { + if (this._client) { + this._client.off("sync", this._onUpdate); + this._didShutdown = true; + } + }, + + // Called when the blocklist implementation is changed via a pref. + undoShutdown() { + if (this._didShutdown) { + this._client.on("sync", this._onUpdate); + this._didShutdown = false; + } + }, + + async _onUpdate() { + let oldEntries = this._entries || []; + await this.ensureInitialized(); + await this._updateEntries(); + + let addons = await lazy.AddonManager.getAddonsByTypes(lazy.kXPIAddonTypes); + for (let addon of addons) { + let oldState = addon.blocklistState; + if (addon.updateBlocklistState) { + await addon.updateBlocklistState(false); + } else if (oldEntries) { + let oldEntry = this._getEntry(addon, oldEntries); + oldState = oldEntry + ? oldEntry.state + : Ci.nsIBlocklistService.STATE_NOT_BLOCKED; + } else { + oldState = Ci.nsIBlocklistService.STATE_NOT_BLOCKED; + } + let state = addon.blocklistState; + + LOG( + "Blocklist state for " + + addon.id + + " changed from " + + oldState + + " to " + + state + ); + + // We don't want to re-warn about add-ons + if (state == oldState) { + continue; + } + + // Ensure that softDisabled is false if the add-on is not soft blocked + if (state != Ci.nsIBlocklistService.STATE_SOFTBLOCKED) { + await addon.setSoftDisabled(false); + } + + // If an add-on has dropped from hard to soft blocked just mark it as + // soft disabled and don't warn about it. + if ( + state == Ci.nsIBlocklistService.STATE_SOFTBLOCKED && + oldState == Ci.nsIBlocklistService.STATE_BLOCKED + ) { + await addon.setSoftDisabled(true); + } + + if ( + state == Ci.nsIBlocklistService.STATE_BLOCKED || + state == Ci.nsIBlocklistService.STATE_SOFTBLOCKED + ) { + // Mark it as softblocked if necessary. Note that we avoid setting + // softDisabled at the same time as userDisabled to make it clear + // which was the original cause of the add-on becoming disabled in a + // way that the user can change. + if ( + state == Ci.nsIBlocklistService.STATE_SOFTBLOCKED && + !addon.userDisabled + ) { + await addon.setSoftDisabled(true); + } + // It's a block. We must reset certain preferences. + let entry = this._getEntry(addon, this._entries); + if (entry.prefs && entry.prefs.length) { + for (let pref of entry.prefs) { + Services.prefs.clearUserPref(pref); + } + } + } + } + + lazy.AddonManagerPrivate.updateAddonAppDisabledStates(); + }, + + async getState(addon, appVersion, toolkitVersion) { + let entry = await this.getEntry(addon, appVersion, toolkitVersion); + return entry ? entry.state : Ci.nsIBlocklistService.STATE_NOT_BLOCKED; + }, + + async getEntry(addon, appVersion, toolkitVersion) { + await this._ensureEntries(); + return this._getEntry(addon, this._entries, appVersion, toolkitVersion); + }, + + _getEntry(addon, addonEntries, appVersion, toolkitVersion) { + if (!gBlocklistEnabled || !addon) { + return null; + } + + // Not all applications implement nsIXULAppInfo (e.g. xpcshell doesn't). + if (!appVersion && !lazy.gApp.version) { + return null; + } + + if (!appVersion) { + appVersion = lazy.gApp.version; + } + if (!toolkitVersion) { + toolkitVersion = lazy.gApp.platformVersion; + } + + let addonProps = {}; + for (let key of EXTENSION_BLOCK_FILTERS) { + addonProps[key] = addon[key]; + } + if (addonProps.creator) { + addonProps.creator = addonProps.creator.name; + } + + for (let entry of addonEntries) { + // First check if it matches our properties. If not, just skip to the next item. + if (!doesAddonEntryMatch(entry.matches, addonProps)) { + continue; + } + // If those match, check the app or toolkit version works: + for (let versionRange of entry.versionRange) { + if ( + Utils.versionsMatch( + versionRange, + addon.version, + appVersion, + toolkitVersion + ) + ) { + let blockID = entry.blockID || entry.id; + return { + state: + versionRange.severity >= gBlocklistLevel + ? Ci.nsIBlocklistService.STATE_BLOCKED + : Ci.nsIBlocklistService.STATE_SOFTBLOCKED, + url: Utils._createBlocklistURL(blockID), + prefs: entry.prefs || [], + }; + } + } + } + return null; + }, +}; + +/** + * The extensions blocklist implementation, the third version. + * + * The current blocklist is represented by a multi-level bloom filter (MLBF) + * (aka "Cascade Bloom Filter") that works like a set, i.e. supports a has() + * operation, except it is probabilistic. The MLBF is 100% accurate for known + * entries and unreliable for unknown entries. When the backend generates the + * MLBF, all known add-ons are recorded, including their block state. Unknown + * add-ons are identified by their signature date being newer than the MLBF's + * generation time, and they are considered to not be blocked. + * + * Legacy blocklists used to distinguish between "soft block" and "hard block", + * but the current blocklist only supports one type of block ("hard block"). + * After checking the blocklist states, any previous "soft blocked" addons will + * either be (hard) blocked or unblocked based on the blocklist. + * + * The MLBF is attached to a RemoteSettings record, as follows: + * + * { + * "generation_time": 1585692000000, + * "attachment": { ... RemoteSettings attachment ... } + * "attachment_type": "bloomfilter-base", + * } + * + * The collection can also contain stashes: + * + * { + * "stash_time": 1585692000001, + * "stash": { + * "blocked": [ "addonid:1.0", ... ], + * "unblocked": [ "addonid:1.0", ... ] + * } + * + * Stashes can be used to update the blocklist without forcing the whole MLBF + * to be downloaded again. These stashes are applied on top of the base MLBF. + */ +const ExtensionBlocklistMLBF = { + RS_ATTACHMENT_ID: "addons-mlbf.bin", + + async _fetchMLBF(record) { + // |record| may be unset. In that case, the MLBF dump is used instead + // (provided that the client has been built with it included). + let hash = record?.attachment.hash; + if (this._mlbfData && hash && this._mlbfData.cascadeHash === hash) { + // MLBF not changed, save the efforts of downloading the data again. + + // Although the MLBF has not changed, the time in the record has. This + // means that the MLBF is known to provide accurate results for add-ons + // that were signed after the previously known date (but before the newly + // given date). To ensure that add-ons in this time range are also blocked + // as expected, update the cached generationTime. + if (record.generation_time > this._mlbfData.generationTime) { + this._mlbfData.generationTime = record.generation_time; + } + return this._mlbfData; + } + const { + buffer, + record: actualRecord, + _source: rsAttachmentSource, + } = await this._client.attachments.download(record, { + attachmentId: this.RS_ATTACHMENT_ID, + fallbackToCache: true, + fallbackToDump: true, + }); + return { + cascadeHash: actualRecord.attachment.hash, + cascadeFilter: new CascadeFilter(new Uint8Array(buffer)), + // Note: generation_time is semantically distinct from last_modified. + // generation_time is compared with the signing date of the add-on, so it + // should be in sync with the signing service's clock. + // In contrast, last_modified does not have such strong requirements. + generationTime: actualRecord.generation_time, + // Used for telemetry. + rsAttachmentSource, + }; + }, + + async _updateMLBF(forceUpdate = false) { + // The update process consists of fetching the collection, followed by + // potentially multiple network requests. As long as the collection has not + // been changed, repeated update requests can be coalesced. But when the + // collection has been updated, all pending update requests should await the + // new update request instead of the previous one. + if (!forceUpdate && this._updatePromise) { + return this._updatePromise; + } + const isUpdateReplaced = () => this._updatePromise != updatePromise; + const updatePromise = (async () => { + if (!gBlocklistEnabled) { + this._mlbfData = null; + this._stashes = null; + return; + } + let records = await this._client.get(); + if (isUpdateReplaced()) { + return; + } + + let mlbfRecords = records + .filter(r => r.attachment) + // Newest attachments first. + .sort((a, b) => b.generation_time - a.generation_time); + const mlbfRecord = mlbfRecords.find( + r => r.attachment_type == "bloomfilter-base" + ); + this._stashes = records + .filter(({ stash }) => { + return ( + // Exclude non-stashes, e.g. MLBF attachments. + stash && + // Sanity check for type. + Array.isArray(stash.blocked) && + Array.isArray(stash.unblocked) + ); + }) + // Sort by stash time - newest first. + .sort((a, b) => b.stash_time - a.stash_time) + .map(({ stash, stash_time }) => ({ + blocked: new Set(stash.blocked), + unblocked: new Set(stash.unblocked), + stash_time, + })); + + let mlbf = await this._fetchMLBF(mlbfRecord); + // When a MLBF dump is packaged with the browser, mlbf will always be + // non-null at this point. + if (isUpdateReplaced()) { + return; + } + this._mlbfData = mlbf; + })() + .catch(e => { + Cu.reportError(e); + }) + .then(() => { + if (!isUpdateReplaced()) { + this._updatePromise = null; + this._recordPostUpdateTelemetry(); + } + return this._updatePromise; + }); + this._updatePromise = updatePromise; + return updatePromise; + }, + + // Update the telemetry of the blocklist. This is always called, even if + // the update request failed (e.g. due to network errors or data corruption). + _recordPostUpdateTelemetry() { + BlocklistTelemetry.recordRSBlocklistLastModified( + "addons_mlbf", + this._client + ); + Services.telemetry.scalarSet( + "blocklist.mlbf_source", + this._mlbfData?.rsAttachmentSource || "unknown" + ); + BlocklistTelemetry.recordTimeScalar( + "mlbf_generation_time", + this._mlbfData?.generationTime + ); + // stashes has conveniently already been sorted by stash_time, newest first. + let stashes = this._stashes || []; + BlocklistTelemetry.recordTimeScalar( + "mlbf_stash_time_oldest", + stashes[stashes.length - 1]?.stash_time + ); + BlocklistTelemetry.recordTimeScalar( + "mlbf_stash_time_newest", + stashes[0]?.stash_time + ); + }, + + // Used by BlocklistTelemetry.recordAddonBlockChangeTelemetry. + getBlocklistMetadataForTelemetry() { + // Blocklist telemetry can only be reported when a blocklist decision + // has been made. That implies that the blocklist has been loaded, so + // ExtensionBlocklistMLBF should have been initialized. + // (except when the blocklist is disabled, or blocklist v2 is used) + const generationTime = this._mlbfData?.generationTime ?? 0; + + // Keys to include in the blocklist.addonBlockChange telemetry event. + return { + mlbf_last_time: + // stashes are sorted, newest first. Stashes are newer than the MLBF. + `${this._stashes?.[0]?.stash_time ?? generationTime}`, + mlbf_generation: `${generationTime}`, + mlbf_source: this._mlbfData?.rsAttachmentSource ?? "unknown", + }; + }, + + ensureInitialized() { + if (!gBlocklistEnabled || this._initialized) { + return; + } + this._initialized = true; + this._client = lazy.RemoteSettings("addons-bloomfilters", { + bucketName: BLOCKLIST_BUCKET, + // Prevent the attachment for being pruned, since its ID does + // not match any record. + keepAttachmentsIds: [this.RS_ATTACHMENT_ID], + }); + this._onUpdate = this._onUpdate.bind(this); + this._client.on("sync", this._onUpdate); + }, + + shutdown() { + if (this._client) { + this._client.off("sync", this._onUpdate); + this._didShutdown = true; + } + }, + + // Called when the blocklist implementation is changed via a pref. + undoShutdown() { + if (this._didShutdown) { + this._client.on("sync", this._onUpdate); + this._didShutdown = false; + } + }, + + async _onUpdate() { + this.ensureInitialized(); + await this._updateMLBF(true); + + let addons = await lazy.AddonManager.getAddonsByTypes(lazy.kXPIAddonTypes); + for (let addon of addons) { + let oldState = addon.blocklistState; + await addon.updateBlocklistState(false); + let state = addon.blocklistState; + + LOG( + "Blocklist state for " + + addon.id + + " changed from " + + oldState + + " to " + + state + ); + + // We don't want to re-warn about add-ons + if (state == oldState) { + continue; + } + + // Ensure that softDisabled is false if the add-on is not soft blocked + // (by a previous implementation of the blocklist). + if (state != Ci.nsIBlocklistService.STATE_SOFTBLOCKED) { + await addon.setSoftDisabled(false); + } + + BlocklistTelemetry.recordAddonBlockChangeTelemetry( + addon, + "blocklist_update" + ); + } + + lazy.AddonManagerPrivate.updateAddonAppDisabledStates(); + }, + + async getState(addon) { + let state = await this.getEntry(addon); + return state ? state.state : Ci.nsIBlocklistService.STATE_NOT_BLOCKED; + }, + + async getEntry(addon) { + if (!this._stashes) { + this.ensureInitialized(); + await this._updateMLBF(false); + } else if (this._updatePromise) { + // _stashes has been initialized, but the initialization of _mlbfData is + // still pending. + await this._updatePromise; + } + + let blockKey = addon.id + ":" + addon.version; + + // _stashes will be unset if !gBlocklistEnabled. + if (this._stashes) { + // Stashes are ordered by newest first. + for (let stash of this._stashes) { + // blocked and unblocked do not have overlapping entries. + if (stash.blocked.has(blockKey)) { + return this._createBlockEntry(addon); + } + if (stash.unblocked.has(blockKey)) { + return null; + } + } + } + + // signedDate is a Date if the add-on is signed, null if not signed, + // undefined if it's an addon update descriptor instead of an addon wrapper. + let { signedDate } = addon; + if (!signedDate) { + // The MLBF does not apply to unsigned add-ons. + return null; + } + + if (!this._mlbfData) { + // This could happen in theory in any of the following cases: + // - the blocklist is disabled. + // - The RemoteSettings backend served a malformed MLBF. + // - The RemoteSettings backend is unreachable, and this client was built + // without including a dump of the MLBF. + // + // ... in other words, this is unlikely to happen in practice. + return null; + } + let { cascadeFilter, generationTime } = this._mlbfData; + if (!cascadeFilter.has(blockKey)) { + // Add-on not blocked or unknown. + return null; + } + // Add-on blocked, or unknown add-on inadvertently labeled as blocked. + + let { signedState } = addon; + if ( + signedState !== lazy.AddonManager.SIGNEDSTATE_PRELIMINARY && + signedState !== lazy.AddonManager.SIGNEDSTATE_SIGNED + ) { + // The block decision can only be relied upon for known add-ons, i.e. + // signed via AMO. Anything else is unknown and ignored: + // + // - SIGNEDSTATE_SYSTEM and SIGNEDSTATE_PRIVILEGED are signed + // independently of AMO. + // + // - SIGNEDSTATE_NOT_REQUIRED already has an early return above due to + // signedDate being unset for these kinds of add-ons. + // + // - SIGNEDSTATE_BROKEN, SIGNEDSTATE_UNKNOWN and SIGNEDSTATE_MISSING + // means that the signature cannot be relied upon. It is equivalent to + // removing the signature from the XPI file, which already causes them + // to be disabled on release builds (where MOZ_REQUIRE_SIGNING=true). + return null; + } + + if (signedDate.getTime() > generationTime) { + // The bloom filter only reports 100% accurate results for known add-ons. + // Since the add-on was unknown when the bloom filter was generated, the + // block decision is incorrect and should be treated as unblocked. + return null; + } + + if (AppConstants.NIGHTLY_BUILD && addon.type === "locale") { + // Only Mozilla can create langpacks with a valid signature. + // Langpacks for Release, Beta and ESR are submitted to AMO. + // DevEd does not support external langpacks (bug 1563923), only builtins. + // (and built-in addons are not subjected to the blocklist). + // Langpacks for Nightly are not known to AMO, so the MLBF cannot be used. + return null; + } + + return this._createBlockEntry(addon); + }, + + _createBlockEntry(addon) { + return { + state: Ci.nsIBlocklistService.STATE_BLOCKED, + url: this.createBlocklistURL(addon.id, addon.version), + }; + }, + + createBlocklistURL(id, version) { + let url = Services.urlFormatter.formatURLPref(PREF_BLOCKLIST_ADDONITEM_URL); + return url.replace(/%addonID%/g, id).replace(/%addonVersion%/g, version); + }, +}; + +const EXTENSION_BLOCK_FILTERS = [ + "id", + "name", + "creator", + "homepageURL", + "updateURL", +]; + +var gLoggingEnabled = null; +var gBlocklistEnabled = true; +var gBlocklistLevel = DEFAULT_LEVEL; + +/** + * @class nsIBlocklistPrompt + * + * nsIBlocklistPrompt is used, if available, by the default implementation of + * nsIBlocklistService to display a confirmation UI to the user before blocking + * extensions/plugins. + */ +/** + * @method prompt + * + * Prompt the user about newly blocked addons. The prompt is then resposible + * for soft-blocking any addons that need to be afterwards + * + * @param {object[]} aAddons + * An array of addons and plugins that are blocked. These are javascript + * objects with properties: + * name - the plugin or extension name, + * version - the version of the extension or plugin, + * icon - the plugin or extension icon, + * disable - can be used by the nsIBlocklistPrompt to allows users to decide + * whether a soft-blocked add-on should be disabled, + * blocked - true if the item is hard-blocked, false otherwise, + * item - the nsIPluginTag or Addon object + */ + +// It is not possible to use the one in Services since it will not successfully +// QueryInterface nsIXULAppInfo in xpcshell tests due to other code calling +// Services.appinfo before the nsIXULAppInfo is created by the tests. +XPCOMUtils.defineLazyGetter(lazy, "gApp", function() { + // eslint-disable-next-line mozilla/use-services + let appinfo = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime); + try { + appinfo.QueryInterface(Ci.nsIXULAppInfo); + } catch (ex) { + // Not all applications implement nsIXULAppInfo (e.g. xpcshell doesn't). + if ( + !(ex instanceof Components.Exception) || + ex.result != Cr.NS_NOINTERFACE + ) { + throw ex; + } + } + return appinfo; +}); + +XPCOMUtils.defineLazyGetter(lazy, "gAppID", function() { + return lazy.gApp.ID; +}); +XPCOMUtils.defineLazyGetter(lazy, "gAppOS", function() { + return lazy.gApp.OS; +}); + +/** + * Logs a string to the error console. + * @param {string} string + * The string to write to the error console.. + */ +function LOG(string) { + if (gLoggingEnabled) { + dump("*** " + string + "\n"); + Services.console.logStringMessage(string); + } +} + +let Blocklist = { + _init() { + Services.obs.addObserver(this, "xpcom-shutdown"); + gLoggingEnabled = Services.prefs.getBoolPref( + PREF_EM_LOGGING_ENABLED, + false + ); + gBlocklistEnabled = Services.prefs.getBoolPref( + PREF_BLOCKLIST_ENABLED, + true + ); + gBlocklistLevel = Math.min( + Services.prefs.getIntPref(PREF_BLOCKLIST_LEVEL, DEFAULT_LEVEL), + MAX_BLOCK_LEVEL + ); + this._chooseExtensionBlocklistImplementationFromPref(); + Services.prefs.addObserver("extensions.blocklist.", this); + Services.prefs.addObserver(PREF_EM_LOGGING_ENABLED, this); + BlocklistTelemetry.init(); + }, + isLoaded: true, + + shutdown() { + GfxBlocklistRS.shutdown(); + this.ExtensionBlocklist.shutdown(); + + Services.obs.removeObserver(this, "xpcom-shutdown"); + Services.prefs.removeObserver("extensions.blocklist.", this); + Services.prefs.removeObserver(PREF_EM_LOGGING_ENABLED, this); + }, + + observe(subject, topic, prefName) { + switch (topic) { + case "xpcom-shutdown": + this.shutdown(); + break; + case "nsPref:changed": + switch (prefName) { + case PREF_EM_LOGGING_ENABLED: + gLoggingEnabled = Services.prefs.getBoolPref( + PREF_EM_LOGGING_ENABLED, + false + ); + break; + case PREF_BLOCKLIST_ENABLED: + gBlocklistEnabled = Services.prefs.getBoolPref( + PREF_BLOCKLIST_ENABLED, + true + ); + this._blocklistUpdated(); + break; + case PREF_BLOCKLIST_LEVEL: + gBlocklistLevel = Math.min( + Services.prefs.getIntPref(PREF_BLOCKLIST_LEVEL, DEFAULT_LEVEL), + MAX_BLOCK_LEVEL + ); + this._blocklistUpdated(); + break; + case PREF_BLOCKLIST_USE_MLBF: + let oldImpl = this.ExtensionBlocklist; + this._chooseExtensionBlocklistImplementationFromPref(); + // The implementation may be unchanged when the pref is ignored. + if (oldImpl != this.ExtensionBlocklist && oldImpl._initialized) { + oldImpl.shutdown(); + this.ExtensionBlocklist.undoShutdown(); + this.ExtensionBlocklist._onUpdate(); + } // else neither has been initialized yet. Wait for it to happen. + break; + } + break; + } + }, + + loadBlocklistAsync() { + // Need to ensure we notify gfx of new stuff. + // Geckoview calls this for each new tab (bug 1730026), so ensure we only + // check for entries when first initialized. + if (!GfxBlocklistRS._initialized) { + GfxBlocklistRS.checkForEntries(); + } + this.ExtensionBlocklist.ensureInitialized(); + }, + + getAddonBlocklistState(addon, appVersion, toolkitVersion) { + // NOTE: appVersion/toolkitVersion are only used by ExtensionBlocklistRS. + return this.ExtensionBlocklist.getState(addon, appVersion, toolkitVersion); + }, + + getAddonBlocklistEntry(addon, appVersion, toolkitVersion) { + // NOTE: appVersion/toolkitVersion are only used by ExtensionBlocklistRS. + return this.ExtensionBlocklist.getEntry(addon, appVersion, toolkitVersion); + }, + + recordAddonBlockChangeTelemetry(addon, reason) { + BlocklistTelemetry.recordAddonBlockChangeTelemetry(addon, reason); + }, + + // TODO bug 1649906, bug 1639050: Remove blocklist v2. + // Allow blocklist for Android and unit tests only. + allowDeprecatedBlocklistV2: AppConstants.platform === "android", + + _chooseExtensionBlocklistImplementationFromPref() { + if ( + this.allowDeprecatedBlocklistV2 && + !Services.prefs.getBoolPref(PREF_BLOCKLIST_USE_MLBF, false) + ) { + this.ExtensionBlocklist = ExtensionBlocklistRS; + Services.telemetry.scalarSet("blocklist.mlbf_enabled", false); + } else { + this.ExtensionBlocklist = ExtensionBlocklistMLBF; + Services.telemetry.scalarSet("blocklist.mlbf_enabled", true); + } + }, + + _blocklistUpdated() { + this.ExtensionBlocklist._onUpdate(); + }, +}; + +Blocklist._init(); + +// Allow tests to reach implementation objects. +const BlocklistPrivate = { + BlocklistTelemetry, + ExtensionBlocklistMLBF, + ExtensionBlocklistRS, + GfxBlocklistRS, +}; diff --git a/toolkit/mozapps/extensions/LightweightThemeManager.jsm b/toolkit/mozapps/extensions/LightweightThemeManager.jsm new file mode 100644 index 0000000000..78c2135e61 --- /dev/null +++ b/toolkit/mozapps/extensions/LightweightThemeManager.jsm @@ -0,0 +1,36 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +var EXPORTED_SYMBOLS = ["LightweightThemeManager"]; + +// Holds optional fallback theme data that will be returned when no data for an +// active theme can be found. This the case for WebExtension Themes, for example. +var _fallbackThemeData = null; + +var LightweightThemeManager = { + set fallbackThemeData(data) { + if (data && Object.getOwnPropertyNames(data).length) { + _fallbackThemeData = Object.assign({}, data); + } else { + _fallbackThemeData = null; + } + }, + + /* + * Returns the currently active theme, taking the fallback theme into account + * if we'd be using the default theme otherwise. + * + * This will always return the original theme data and not make use of + * locally persisted resources. + */ + get currentThemeWithFallback() { + return _fallbackThemeData && _fallbackThemeData.theme; + }, + + get themeData() { + return _fallbackThemeData || { theme: null }; + }, +}; diff --git a/toolkit/mozapps/extensions/addonManager.js b/toolkit/mozapps/extensions/addonManager.js new file mode 100644 index 0000000000..d4f33ff9df --- /dev/null +++ b/toolkit/mozapps/extensions/addonManager.js @@ -0,0 +1,364 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/** + * This component serves as integration between the platform and AddonManager. + * It is responsible for initializing and shutting down the AddonManager as well + * as passing new installs from webpages to the AddonManager. + */ + +"use strict"; + +const { XPCOMUtils } = ChromeUtils.importESModule( + "resource://gre/modules/XPCOMUtils.sys.mjs" +); +const lazy = {}; +XPCOMUtils.defineLazyPreferenceGetter( + lazy, + "separatePrivilegedMozillaWebContentProcess", + "browser.tabs.remote.separatePrivilegedMozillaWebContentProcess", + false +); +XPCOMUtils.defineLazyPreferenceGetter( + lazy, + "extensionsWebAPITesting", + "extensions.webapi.testing", + false +); + +// The old XPInstall error codes +const EXECUTION_ERROR = -203; +const CANT_READ_ARCHIVE = -207; +const USER_CANCELLED = -210; +const DOWNLOAD_ERROR = -228; +const UNSUPPORTED_TYPE = -244; +const SUCCESS = 0; + +const MSG_INSTALL_ENABLED = "WebInstallerIsInstallEnabled"; +const MSG_INSTALL_ADDON = "WebInstallerInstallAddonFromWebpage"; +const MSG_INSTALL_CALLBACK = "WebInstallerInstallCallback"; + +const MSG_PROMISE_REQUEST = "WebAPIPromiseRequest"; +const MSG_PROMISE_RESULT = "WebAPIPromiseResult"; +const MSG_INSTALL_EVENT = "WebAPIInstallEvent"; +const MSG_INSTALL_CLEANUP = "WebAPICleanup"; +const MSG_ADDON_EVENT_REQ = "WebAPIAddonEventRequest"; +const MSG_ADDON_EVENT = "WebAPIAddonEvent"; + +var AddonManager, AddonManagerPrivate; +function amManager() { + ({ AddonManager, AddonManagerPrivate } = ChromeUtils.import( + "resource://gre/modules/AddonManager.jsm" + )); + + Services.mm.addMessageListener(MSG_INSTALL_ENABLED, this); + Services.mm.addMessageListener(MSG_PROMISE_REQUEST, this); + Services.mm.addMessageListener(MSG_INSTALL_CLEANUP, this); + Services.mm.addMessageListener(MSG_ADDON_EVENT_REQ, this); + + Services.ppmm.addMessageListener(MSG_INSTALL_ADDON, this); + + Services.obs.addObserver(this, "message-manager-close"); + Services.obs.addObserver(this, "message-manager-disconnect"); + + AddonManager.webAPI.setEventHandler(this.sendEvent); + + // Needed so receiveMessage can be called directly by JS callers + this.wrappedJSObject = this; +} + +amManager.prototype = { + observe(aSubject, aTopic, aData) { + switch (aTopic) { + case "addons-startup": + AddonManagerPrivate.startup(); + break; + + case "message-manager-close": + case "message-manager-disconnect": + this.childClosed(aSubject); + break; + } + }, + + installAddonFromWebpage(aPayload, aBrowser, aCallback) { + let retval = true; + + const { mimetype, triggeringPrincipal, hash, icon, name, uri } = aPayload; + + // NOTE: consider removing this call to isInstallAllowed from here, later it is going to be called + // again from inside AddonManager.installAddonFromWebpage as part of the block/allow logic. + // + // The sole purpose of the call here seems to be "clearing the optional InstallTrigger callback", + // which seems to be actually wrong if we are still proceeding to call getInstallForURL and the same + // logic used to block the install flow using the exact same method call later on. + if (!AddonManager.isInstallAllowed(mimetype, triggeringPrincipal)) { + aCallback = null; + retval = false; + } + + let telemetryInfo = { + source: AddonManager.getInstallSourceFromHost(aPayload.sourceHost), + sourceURL: aPayload.sourceURL, + }; + + if ("method" in aPayload) { + telemetryInfo.method = aPayload.method; + } + + AddonManager.getInstallForURL(uri, { + hash, + name, + icon, + browser: aBrowser, + triggeringPrincipal, + telemetryInfo, + sendCookies: true, + }).then(aInstall => { + function callCallback(status) { + try { + aCallback?.onInstallEnded(uri, status); + } catch (e) { + Cu.reportError(e); + } + } + + if (!aInstall) { + callCallback(UNSUPPORTED_TYPE); + return; + } + + if (aCallback) { + aInstall.addListener({ + onDownloadCancelled(aInstall) { + callCallback(USER_CANCELLED); + }, + + onDownloadFailed(aInstall) { + if (aInstall.error == AddonManager.ERROR_CORRUPT_FILE) { + callCallback(CANT_READ_ARCHIVE); + } else { + callCallback(DOWNLOAD_ERROR); + } + }, + + onInstallFailed(aInstall) { + callCallback(EXECUTION_ERROR); + }, + + onInstallEnded(aInstall, aStatus) { + callCallback(SUCCESS); + }, + }); + } + + AddonManager.installAddonFromWebpage( + mimetype, + aBrowser, + triggeringPrincipal, + aInstall, + { + hasCrossOriginAncestor: aPayload.hasCrossOriginAncestor, + } + ); + }); + + return retval; + }, + + notify(aTimer) { + AddonManagerPrivate.backgroundUpdateTimerHandler(); + }, + + // Maps message manager instances for content processes to the associated + // AddonListener instances. + addonListeners: new Map(), + + _addAddonListener(target) { + if (!this.addonListeners.has(target)) { + let handler = (event, id) => { + target.sendAsyncMessage(MSG_ADDON_EVENT, { event, id }); + }; + let listener = { + onEnabling: addon => handler("onEnabling", addon.id), + onEnabled: addon => handler("onEnabled", addon.id), + onDisabling: addon => handler("onDisabling", addon.id), + onDisabled: addon => handler("onDisabled", addon.id), + onInstalling: addon => handler("onInstalling", addon.id), + onInstalled: addon => handler("onInstalled", addon.id), + onUninstalling: addon => handler("onUninstalling", addon.id), + onUninstalled: addon => handler("onUninstalled", addon.id), + onOperationCancelled: addon => + handler("onOperationCancelled", addon.id), + }; + this.addonListeners.set(target, listener); + AddonManager.addAddonListener(listener); + } + }, + + _removeAddonListener(target) { + if (this.addonListeners.has(target)) { + AddonManager.removeAddonListener(this.addonListeners.get(target)); + this.addonListeners.delete(target); + } + }, + + /** + * messageManager callback function. + * + * Listens to requests from child processes for InstallTrigger + * activity, and sends back callbacks. + */ + receiveMessage(aMessage) { + let payload = aMessage.data; + + switch (aMessage.name) { + case MSG_INSTALL_ENABLED: + return AddonManager.isInstallEnabled(payload.mimetype); + + case MSG_INSTALL_ADDON: { + let browser = payload.browsingContext.top.embedderElement; + + let callback = null; + if (payload.callbackID != -1) { + let mm = browser.messageManager; + callback = { + onInstallEnded(url, status) { + mm.sendAsyncMessage(MSG_INSTALL_CALLBACK, { + callbackID: payload.callbackID, + url, + status, + }); + }, + }; + } + + return this.installAddonFromWebpage(payload, browser, callback); + } + + case MSG_PROMISE_REQUEST: { + if ( + !lazy.extensionsWebAPITesting && + lazy.separatePrivilegedMozillaWebContentProcess && + aMessage.target && + aMessage.target.remoteType != null && + aMessage.target.remoteType !== "privilegedmozilla" + ) { + return undefined; + } + + let mm = aMessage.target.messageManager; + let resolve = value => { + mm.sendAsyncMessage(MSG_PROMISE_RESULT, { + callbackID: payload.callbackID, + resolve: value, + }); + }; + let reject = value => { + mm.sendAsyncMessage(MSG_PROMISE_RESULT, { + callbackID: payload.callbackID, + reject: value, + }); + }; + + let API = AddonManager.webAPI; + if (payload.type in API) { + API[payload.type](aMessage.target, ...payload.args).then( + resolve, + reject + ); + } else { + reject("Unknown Add-on API request."); + } + break; + } + + case MSG_INSTALL_CLEANUP: { + if ( + !lazy.extensionsWebAPITesting && + lazy.separatePrivilegedMozillaWebContentProcess && + aMessage.target && + aMessage.target.remoteType != null && + aMessage.target.remoteType !== "privilegedmozilla" + ) { + return undefined; + } + + AddonManager.webAPI.clearInstalls(payload.ids); + break; + } + + case MSG_ADDON_EVENT_REQ: { + if ( + !lazy.extensionsWebAPITesting && + lazy.separatePrivilegedMozillaWebContentProcess && + aMessage.target && + aMessage.target.remoteType != null && + aMessage.target.remoteType !== "privilegedmozilla" + ) { + return undefined; + } + + let target = aMessage.target.messageManager; + if (payload.enabled) { + this._addAddonListener(target); + } else { + this._removeAddonListener(target); + } + } + } + return undefined; + }, + + childClosed(target) { + AddonManager.webAPI.clearInstallsFrom(target); + this._removeAddonListener(target); + }, + + sendEvent(mm, data) { + mm.sendAsyncMessage(MSG_INSTALL_EVENT, data); + }, + + classID: Components.ID("{4399533d-08d1-458c-a87a-235f74451cfa}"), + QueryInterface: ChromeUtils.generateQI([ + "amIAddonManager", + "nsITimerCallback", + "nsIObserver", + ]), +}; + +const BLOCKLIST_JSM = "resource://gre/modules/Blocklist.jsm"; +ChromeUtils.defineModuleGetter(lazy, "Blocklist", BLOCKLIST_JSM); + +function BlocklistService() { + this.wrappedJSObject = this; +} + +BlocklistService.prototype = { + STATE_NOT_BLOCKED: Ci.nsIBlocklistService.STATE_NOT_BLOCKED, + STATE_SOFTBLOCKED: Ci.nsIBlocklistService.STATE_SOFTBLOCKED, + STATE_BLOCKED: Ci.nsIBlocklistService.STATE_BLOCKED, + + get isLoaded() { + return Cu.isModuleLoaded(BLOCKLIST_JSM) && lazy.Blocklist.isLoaded; + }, + + observe(...args) { + return lazy.Blocklist.observe(...args); + }, + + notify() { + lazy.Blocklist.notify(); + }, + + classID: Components.ID("{66354bc9-7ed1-4692-ae1d-8da97d6b205e}"), + QueryInterface: ChromeUtils.generateQI([ + "nsIObserver", + "nsIBlocklistService", + "nsITimerCallback", + ]), +}; + +// eslint-disable-next-line no-unused-vars +var EXPORTED_SYMBOLS = ["amManager", "BlocklistService"]; diff --git a/toolkit/mozapps/extensions/amContentHandler.jsm b/toolkit/mozapps/extensions/amContentHandler.jsm new file mode 100644 index 0000000000..e5fdf8fd64 --- /dev/null +++ b/toolkit/mozapps/extensions/amContentHandler.jsm @@ -0,0 +1,109 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const XPI_CONTENT_TYPE = "application/x-xpinstall"; +const MSG_INSTALL_ADDON = "WebInstallerInstallAddonFromWebpage"; + +const { XPCOMUtils } = ChromeUtils.importESModule( + "resource://gre/modules/XPCOMUtils.sys.mjs" +); + +const lazy = {}; + +XPCOMUtils.defineLazyServiceGetters(lazy, { + ThirdPartyUtil: ["@mozilla.org/thirdpartyutil;1", "mozIThirdPartyUtil"], +}); + +function amContentHandler() {} + +amContentHandler.prototype = { + /** + * Handles a new request for an application/x-xpinstall file. + * + * @param aMimetype + * The mimetype of the file + * @param aContext + * The context passed to nsIChannel.asyncOpen + * @param aRequest + * The nsIRequest dealing with the content + */ + handleContent(aMimetype, aContext, aRequest) { + if (aMimetype != XPI_CONTENT_TYPE) { + throw Components.Exception("", Cr.NS_ERROR_WONT_HANDLE_CONTENT); + } + + if (!(aRequest instanceof Ci.nsIChannel)) { + throw Components.Exception("", Cr.NS_ERROR_WONT_HANDLE_CONTENT); + } + + let uri = aRequest.URI; + + // This check will allow a link to an xpi clicked by the user to trigger the + // addon install flow, but prevents window.open or window.location from triggering + // an addon install even when called from inside a event listener triggered by + // user input. + if ( + !aRequest.loadInfo.hasValidUserGestureActivation && + Services.prefs.getBoolPref("xpinstall.userActivation.required", true) + ) { + const error = Components.Exception( + `${uri.spec} install cancelled because of missing user gesture activation`, + Cr.NS_ERROR_WONT_HANDLE_CONTENT + ); + // Report the error in the BrowserConsole, the error thrown from here doesn't + // seem to be visible anywhere. + Cu.reportError(error); + throw error; + } + + aRequest.cancel(Cr.NS_BINDING_ABORTED); + + let { loadInfo } = aRequest; + const { triggeringPrincipal } = loadInfo; + + let browsingContext = loadInfo.targetBrowsingContext; + + let sourceHost; + let sourceURL; + + try { + sourceURL = + triggeringPrincipal.spec != "" ? triggeringPrincipal.spec : undefined; + sourceHost = triggeringPrincipal.host; + } catch (error) { + // Ignore errors when retrieving the host for the principal (e.g. data URIs return + // an NS_ERROR_FAILURE when principal.host is accessed). + } + + let install = { + uri: uri.spec, + hash: null, + name: null, + icon: null, + mimetype: XPI_CONTENT_TYPE, + triggeringPrincipal, + callbackID: -1, + method: "link", + sourceHost, + sourceURL, + browsingContext, + hasCrossOriginAncestor: lazy.ThirdPartyUtil.isThirdPartyChannel(aRequest), + }; + + Services.cpmm.sendAsyncMessage(MSG_INSTALL_ADDON, install); + }, + + classID: Components.ID("{7beb3ba8-6ec3-41b4-b67c-da89b8518922}"), + QueryInterface: ChromeUtils.generateQI(["nsIContentHandler"]), + + log(aMsg) { + let msg = "amContentHandler.js: " + (aMsg.join ? aMsg.join("") : aMsg); + Services.console.logStringMessage(msg); + dump(msg + "\n"); + }, +}; + +var EXPORTED_SYMBOLS = ["amContentHandler"]; diff --git a/toolkit/mozapps/extensions/amIAddonManagerStartup.idl b/toolkit/mozapps/extensions/amIAddonManagerStartup.idl new file mode 100644 index 0000000000..10a235a849 --- /dev/null +++ b/toolkit/mozapps/extensions/amIAddonManagerStartup.idl @@ -0,0 +1,82 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nsISupports.idl" + +interface nsIFile; +interface nsIJSRAIIHelper; +interface nsIURI; + +[scriptable, builtinclass, uuid(01dfa47b-87e4-4135-877b-586d033e1b5d)] +interface amIAddonManagerStartup : nsISupports +{ + /** + * Reads and parses startup data from the addonState.json.lz4 file, checks + * for modifications, and returns the result. + * + * Returns null for an empty or nonexistent state file, but throws for an + * invalid one. + */ + [implicit_jscontext] + jsval readStartupData(); + + /** + * Registers a set of dynamic chrome registry entries, and returns an object + * with a `destruct()` method which must be called in order to unregister + * the entries. + * + * @param manifestURI The base manifest URI for the entries. URL values are + * resolved relative to this URI. + * @param entries An array of arrays, each containing a registry entry as it + * would appar in a chrome.manifest file. Only the following entry + * types are currently accepted: + * + * - "locale" A locale package entry. Must be a 4-element array. + * - "override" A URL override entry. Must be a 3-element array. + */ + [implicit_jscontext] + nsIJSRAIIHelper registerChrome(in nsIURI manifestURI, in jsval entries); + + [implicit_jscontext] + jsval encodeBlob(in jsval value); + + [implicit_jscontext] + jsval decodeBlob(in jsval value); + + /** + * Enumerates over all entries in the JAR file at the given URI, and returns + * an array of entry paths which match the given pattern. The URI may be + * either a file: URL pointing directly to a zip file, or a jar: URI + * pointing to a zip file nested within another zip file. Only one level of + * nesting is supported. + * + * This should be used in preference to manually opening or retrieving a + * ZipReader from the zip cache, since the former causes main thread IO and + * the latter can lead to file locking issues due to unpredictable GC behavior + * keeping the cached ZipReader alive after the cache is flushed. + * + * @param uri The URI of the zip file to enumerate. + * @param pattern The pattern to match, as passed to nsIZipReader.findEntries. + */ + Array enumerateJAR(in nsIURI uri, in AUTF8String pattern); + + /** + * Similar to |enumerateJAR| above, but accepts the URI of a directory + * within a JAR file, and returns a list of all entries below it. + * + * The given URI must be a jar: URI, and its JAR file must point either to a + * file: URI, or to a singly-nested JAR within another JAR file (i.e., + * "jar:file:///thing.jar!/" or "jar:jar:file:///thing.jar!/stuff.jar!/"). + * Multiple levels of nesting are not supported. + */ + Array enumerateJARSubtree(in nsIURI uri); + + /** + * Initializes the URL Preloader. + * + * NOT FOR USE OUTSIDE OF UNIT TESTS. + */ + void initializeURLPreloader(); + +}; diff --git a/toolkit/mozapps/extensions/amIWebInstallPrompt.idl b/toolkit/mozapps/extensions/amIWebInstallPrompt.idl new file mode 100644 index 0000000000..6724303cba --- /dev/null +++ b/toolkit/mozapps/extensions/amIWebInstallPrompt.idl @@ -0,0 +1,32 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "nsISupports.idl" + +interface nsIURI; +interface nsIVariant; + +webidl Element; + +/** + * amIWebInstallPrompt is used, if available, by the default implementation of + * amIWebInstallInfo to display a confirmation UI to the user before running + * installs. + */ +[scriptable, uuid(386906f1-4d18-45bf-bc81-5dcd68e42c3b)] +interface amIWebInstallPrompt : nsISupports +{ + /** + * Get a confirmation that the user wants to start the installs. + * + * @param aBrowser + * The browser that triggered the installs + * @param aUri + * The URI of the site that triggered the installs + * @param aInstalls + * The AddonInstalls that were requested + */ + void confirm(in Element aBrowser, in nsIURI aUri, + in Array aInstalls); +}; diff --git a/toolkit/mozapps/extensions/amInstallTrigger.jsm b/toolkit/mozapps/extensions/amInstallTrigger.jsm new file mode 100644 index 0000000000..109f0330af --- /dev/null +++ b/toolkit/mozapps/extensions/amInstallTrigger.jsm @@ -0,0 +1,281 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { Preferences } = ChromeUtils.importESModule( + "resource://gre/modules/Preferences.sys.mjs" +); +const { Log } = ChromeUtils.importESModule( + "resource://gre/modules/Log.sys.mjs" +); +const { XPCOMUtils } = ChromeUtils.importESModule( + "resource://gre/modules/XPCOMUtils.sys.mjs" +); + +const lazy = {}; + +XPCOMUtils.defineLazyServiceGetters(lazy, { + ThirdPartyUtil: ["@mozilla.org/thirdpartyutil;1", "mozIThirdPartyUtil"], +}); + +const XPINSTALL_MIMETYPE = "application/x-xpinstall"; + +const MSG_INSTALL_ENABLED = "WebInstallerIsInstallEnabled"; +const MSG_INSTALL_ADDON = "WebInstallerInstallAddonFromWebpage"; +const MSG_INSTALL_CALLBACK = "WebInstallerInstallCallback"; + +const SUPPORTED_XPI_SCHEMES = ["http", "https"]; + +var log = Log.repository.getLogger("AddonManager.InstallTrigger"); +log.level = + Log.Level[ + Preferences.get("extensions.logging.enabled", false) ? "Warn" : "Trace" + ]; + +function CallbackObject(id, callback, mediator) { + this.id = id; + this.callback = callback; + this.callCallback = function(url, status) { + try { + this.callback(url, status); + } catch (e) { + log.warn("InstallTrigger callback threw an exception: " + e); + } + + mediator._callbacks.delete(id); + }; +} + +function RemoteMediator(window) { + this._windowID = window.windowGlobalChild.innerWindowId; + + this.mm = window.docShell.messageManager; + this.mm.addWeakMessageListener(MSG_INSTALL_CALLBACK, this); + + this._lastCallbackID = 0; + this._callbacks = new Map(); +} + +RemoteMediator.prototype = { + receiveMessage(message) { + if (message.name == MSG_INSTALL_CALLBACK) { + let payload = message.data; + let callbackHandler = this._callbacks.get(payload.callbackID); + if (callbackHandler) { + callbackHandler.callCallback(payload.url, payload.status); + } + } + }, + + enabled(url) { + let params = { + mimetype: XPINSTALL_MIMETYPE, + }; + return this.mm.sendSyncMessage(MSG_INSTALL_ENABLED, params)[0]; + }, + + install(install, principal, callback, window) { + let callbackID = this._addCallback(callback); + + install.mimetype = XPINSTALL_MIMETYPE; + install.triggeringPrincipal = principal; + install.callbackID = callbackID; + install.browsingContext = BrowsingContext.getFromWindow(window); + + return Services.cpmm.sendSyncMessage(MSG_INSTALL_ADDON, install)[0]; + }, + + _addCallback(callback) { + if (!callback || typeof callback != "function") { + return -1; + } + + let callbackID = this._windowID + "-" + ++this._lastCallbackID; + let callbackObject = new CallbackObject(callbackID, callback, this); + this._callbacks.set(callbackID, callbackObject); + return callbackID; + }, + + QueryInterface: ChromeUtils.generateQI(["nsISupportsWeakReference"]), +}; + +function InstallTrigger() {} + +InstallTrigger.prototype = { + // We've declared ourselves as providing the nsIDOMGlobalPropertyInitializer + // interface. This means that when the InstallTrigger property is gotten from + // the window that will createInstance this object and then call init(), + // passing the window were bound to. It will then automatically create the + // WebIDL wrapper (InstallTriggerImpl) for this object. This indirection is + // necessary because webidl does not (yet) support statics (bug 863952). See + // bug 926712 and then bug 1442360 for more details about this implementation. + init(window) { + this._window = window; + this._principal = window.document.nodePrincipal; + this._url = window.document.documentURIObject; + + this._mediator = new RemoteMediator(window); + // If we can't set up IPC (e.g., because this is a top-level window or + // something), then don't expose InstallTrigger. The Window code handles + // that, if we throw an exception here. + }, + + enabled() { + return this._mediator.enabled(this._url.spec); + }, + + updateEnabled() { + return this.enabled(); + }, + + install(installs, callback) { + if (Services.prefs.getBoolPref("xpinstall.userActivation.required", true)) { + if (!this._window.windowUtils.isHandlingUserInput) { + throw new this._window.Error( + "InstallTrigger.install can only be called from a user input handler" + ); + } + } + + let keys = Object.keys(installs); + if (keys.length > 1) { + throw new this._window.Error("Only one XPI may be installed at a time"); + } + + let item = installs[keys[0]]; + + if (typeof item === "string") { + item = { URL: item }; + } + if (!item.URL) { + throw new this._window.Error( + "Missing URL property for '" + keys[0] + "'" + ); + } + + let url = this._resolveURL(item.URL); + if (!this._checkLoadURIFromScript(url)) { + throw new this._window.Error( + "Insufficient permissions to install: " + url.spec + ); + } + + if (!SUPPORTED_XPI_SCHEMES.includes(url.scheme)) { + Cu.reportError( + `InstallTrigger call disallowed on install url with unsupported scheme: ${JSON.stringify( + { + installPrincipal: this._principal.spec, + installURL: url.spec, + } + )}` + ); + throw new this._window.Error(`Unsupported scheme`); + } + + let iconUrl = null; + if (item.IconURL) { + iconUrl = this._resolveURL(item.IconURL); + if (!this._checkLoadURIFromScript(iconUrl)) { + iconUrl = null; // If page can't load the icon, just ignore it + } + } + + const getTriggeringSource = () => { + let url; + let host; + try { + if (this._url?.schemeIs("http") || this._url?.schemeIs("https")) { + url = this._url.spec; + host = this._url.host; + } else if (this._url?.schemeIs("blob")) { + // For a blob url, we keep the blob url as the sourceURL and + // we pick the related sourceHost from either the principal + // or the precursorPrincipal (if the principal is a null principal + // and the precursor one is defined). + url = this._url.spec; + host = + this._principal.isNullPrincipal && + this._principal.precursorPrincipal + ? this._principal.precursorPrincipal.host + : this._principal.host; + } else if (!this._principal.isNullPrincipal) { + url = this._principal.exposableSpec; + host = this._principal.host; + } else if (this._principal.precursorPrincipal) { + url = this._principal.precursorPrincipal.exposableSpec; + host = this._principal.precursorPrincipal.host; + } else { + // Fallback to this._url as last resort. + url = this._url.spec; + host = this._url.host; + } + } catch (err) { + Cu.reportError(err); + } + // Fallback to an empty string if url and host are still undefined. + return { + sourceURL: url || "", + sourceHost: host || "", + }; + }; + + const { sourceHost, sourceURL } = getTriggeringSource(); + + let installData = { + uri: url.spec, + hash: item.Hash || null, + name: item.name, + icon: iconUrl ? iconUrl.spec : null, + method: "installTrigger", + sourceHost, + sourceURL, + hasCrossOriginAncestor: lazy.ThirdPartyUtil.isThirdPartyWindow( + this._window + ), + }; + + return this._mediator.install( + installData, + this._principal, + callback, + this._window + ); + }, + + startSoftwareUpdate(url, flags) { + let filename = Services.io.newURI(url).QueryInterface(Ci.nsIURL).filename; + let args = {}; + args[filename] = { URL: url }; + return this.install(args); + }, + + installChrome(type, url, skin) { + return this.startSoftwareUpdate(url); + }, + + _resolveURL(url) { + return Services.io.newURI(url, null, this._url); + }, + + _checkLoadURIFromScript(uri) { + let secman = Services.scriptSecurityManager; + try { + secman.checkLoadURIWithPrincipal( + this._principal, + uri, + secman.DISALLOW_INHERIT_PRINCIPAL + ); + return true; + } catch (e) { + return false; + } + }, + + classID: Components.ID("{9df8ef2b-94da-45c9-ab9f-132eb55fddf1}"), + contractID: "@mozilla.org/addons/installtrigger;1", + QueryInterface: ChromeUtils.generateQI(["nsIDOMGlobalPropertyInitializer"]), +}; + +var EXPORTED_SYMBOLS = ["InstallTrigger"]; diff --git a/toolkit/mozapps/extensions/amWebAPI.jsm b/toolkit/mozapps/extensions/amWebAPI.jsm new file mode 100644 index 0000000000..c78739b1bf --- /dev/null +++ b/toolkit/mozapps/extensions/amWebAPI.jsm @@ -0,0 +1,293 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { XPCOMUtils } = ChromeUtils.importESModule( + "resource://gre/modules/XPCOMUtils.sys.mjs" +); + +const lazy = {}; + +XPCOMUtils.defineLazyPreferenceGetter( + lazy, + "AMO_ABUSEREPORT", + "extensions.abuseReport.amWebAPI.enabled", + false +); + +const MSG_PROMISE_REQUEST = "WebAPIPromiseRequest"; +const MSG_PROMISE_RESULT = "WebAPIPromiseResult"; +const MSG_INSTALL_EVENT = "WebAPIInstallEvent"; +const MSG_INSTALL_CLEANUP = "WebAPICleanup"; +const MSG_ADDON_EVENT_REQ = "WebAPIAddonEventRequest"; +const MSG_ADDON_EVENT = "WebAPIAddonEvent"; + +class APIBroker { + constructor(mm) { + this.mm = mm; + + this._promises = new Map(); + + // _installMap maps integer ids to DOM AddonInstall instances + this._installMap = new Map(); + + this.mm.addMessageListener(MSG_PROMISE_RESULT, this); + this.mm.addMessageListener(MSG_INSTALL_EVENT, this); + + this._eventListener = null; + } + + receiveMessage(message) { + let payload = message.data; + + switch (message.name) { + case MSG_PROMISE_RESULT: { + if (!this._promises.has(payload.callbackID)) { + return; + } + + let resolve = this._promises.get(payload.callbackID); + this._promises.delete(payload.callbackID); + resolve(payload); + break; + } + + case MSG_INSTALL_EVENT: { + let install = this._installMap.get(payload.id); + if (!install) { + let err = new Error( + `Got install event for unknown install ${payload.id}` + ); + Cu.reportError(err); + return; + } + install._dispatch(payload); + break; + } + + case MSG_ADDON_EVENT: { + if (this._eventListener) { + this._eventListener(payload); + } + } + } + } + + sendRequest(type, ...args) { + return new Promise(resolve => { + let callbackID = APIBroker._nextID++; + + this._promises.set(callbackID, resolve); + this.mm.sendAsyncMessage(MSG_PROMISE_REQUEST, { type, callbackID, args }); + }); + } + + setAddonListener(callback) { + this._eventListener = callback; + if (callback) { + this.mm.addMessageListener(MSG_ADDON_EVENT, this); + this.mm.sendAsyncMessage(MSG_ADDON_EVENT_REQ, { enabled: true }); + } else { + this.mm.removeMessageListener(MSG_ADDON_EVENT, this); + this.mm.sendAsyncMessage(MSG_ADDON_EVENT_REQ, { enabled: false }); + } + } + + sendCleanup(ids) { + this.setAddonListener(null); + this.mm.sendAsyncMessage(MSG_INSTALL_CLEANUP, { ids }); + } +} + +APIBroker._nextID = 0; + +// Base class for building classes to back content-exposed interfaces. +class APIObject { + init(window, broker, properties) { + this.window = window; + this.broker = broker; + + // Copy any provided properties onto this object, webidl bindings + // will only expose to content what should be exposed. + for (let key of Object.keys(properties)) { + this[key] = properties[key]; + } + } + + /** + * Helper to implement an asychronous method visible to content, where + * the method is implemented by sending a message to the parent process + * and then wrapping the returned object or error in an appropriate object. + * This helper method ensures that: + * - Returned Promise objects are from the content window + * - Rejected Promises have Error objects from the content window + * - Only non-internal errors are exposed to the caller + * + * @param {string} apiRequest The command to invoke in the parent process. + * @param {array} apiArgs The arguments to include with the + * request to the parent process. + * @param {function} resultConvert If provided, a function called with the + * result from the parent process as an + * argument. Used to convert the result + * into something appropriate for content. + * @returns {Promise} A Promise suitable for passing directly to content. + */ + _apiTask(apiRequest, apiArgs, resultConverter) { + let win = this.window; + let broker = this.broker; + return new win.Promise((resolve, reject) => { + (async function() { + let result = await broker.sendRequest(apiRequest, ...apiArgs); + if ("reject" in result) { + let err = new win.Error(result.reject.message); + // We don't currently put any other properties onto Errors + // generated by mozAddonManager. If/when we do, they will + // need to get copied here. + reject(err); + return; + } + + let obj = result.resolve; + if (resultConverter) { + obj = resultConverter(obj); + } + resolve(obj); + })().catch(err => { + Cu.reportError(err); + reject(new win.Error("Unexpected internal error")); + }); + }); + } +} + +class Addon extends APIObject { + constructor(...args) { + super(); + this.init(...args); + } + + uninstall() { + return this._apiTask("addonUninstall", [this.id]); + } + + setEnabled(value) { + return this._apiTask("addonSetEnabled", [this.id, value]); + } +} + +class AddonInstall extends APIObject { + constructor(window, broker, properties) { + super(); + this.init(window, broker, properties); + + broker._installMap.set(properties.id, this); + } + + _dispatch(data) { + // The message for the event includes updated copies of all install + // properties. Use the usual "let webidl filter visible properties" trick. + for (let key of Object.keys(data)) { + this[key] = data[key]; + } + + let event = new this.window.Event(data.event); + this.__DOM_IMPL__.dispatchEvent(event); + } + + install() { + return this._apiTask("addonInstallDoInstall", [this.id]); + } + + cancel() { + return this._apiTask("addonInstallCancel", [this.id]); + } +} + +class WebAPI extends APIObject { + constructor() { + super(); + this.allInstalls = []; + this.listenerCount = 0; + } + + init(window) { + let mm = window.docShell.messageManager; + let broker = new APIBroker(mm); + + super.init(window, broker, {}); + + window.addEventListener("unload", event => { + this.broker.sendCleanup(this.allInstalls); + }); + } + + getAddonByID(id) { + return this._apiTask("getAddonByID", [id], addonInfo => { + if (!addonInfo) { + return null; + } + let addon = new Addon(this.window, this.broker, addonInfo); + return this.window.Addon._create(this.window, addon); + }); + } + + createInstall(options) { + if (!Services.prefs.getBoolPref("xpinstall.enabled", true)) { + throw new this.window.Error("Software installation is disabled."); + } + + const triggeringPrincipal = this.window.document.nodePrincipal; + + let installOptions = { + ...options, + triggeringPrincipal, + // Provide the host from which the amWebAPI is being called + // (so that we can detect if the API is being used from the disco pane, + // AMO, testpilot or another unknown webpage). + sourceHost: this.window.location?.host, + sourceURL: this.window.location?.href, + }; + return this._apiTask("createInstall", [installOptions], installInfo => { + if (!installInfo) { + return null; + } + let install = new AddonInstall(this.window, this.broker, installInfo); + this.allInstalls.push(installInfo.id); + return this.window.AddonInstall._create(this.window, install); + }); + } + + reportAbuse(id) { + return this._apiTask("addonReportAbuse", [id]); + } + + get abuseReportPanelEnabled() { + return lazy.AMO_ABUSEREPORT; + } + + eventListenerAdded(type) { + if (this.listenerCount == 0) { + this.broker.setAddonListener(data => { + let event = new this.window.AddonEvent(data.event, data); + this.__DOM_IMPL__.dispatchEvent(event); + }); + } + this.listenerCount++; + } + + eventListenerRemoved(type) { + this.listenerCount--; + if (this.listenerCount == 0) { + this.broker.setAddonListener(null); + } + } +} +WebAPI.prototype.QueryInterface = ChromeUtils.generateQI([ + "nsIDOMGlobalPropertyInitializer", +]); +WebAPI.prototype.classID = Components.ID( + "{8866d8e3-4ea5-48b7-a891-13ba0ac15235}" +); +var EXPORTED_SYMBOLS = ["WebAPI"]; diff --git a/toolkit/mozapps/extensions/components.conf b/toolkit/mozapps/extensions/components.conf new file mode 100644 index 0000000000..25595f70cb --- /dev/null +++ b/toolkit/mozapps/extensions/components.conf @@ -0,0 +1,45 @@ +# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*- +# vim: set filetype=python: +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +Classes = [ + { + 'js_name': 'blocklist', + 'cid': '{66354bc9-7ed1-4692-ae1d-8da97d6b205e}', + 'contract_ids': ['@mozilla.org/extensions/blocklist;1'], + 'jsm': 'resource://gre/modules/addonManager.js', + 'constructor': 'BlocklistService', + 'interfaces': ['nsIBlocklistService'], + 'processes': ProcessSelector.MAIN_PROCESS_ONLY, + }, + { + 'cid': '{4399533d-08d1-458c-a87a-235f74451cfa}', + 'contract_ids': ['@mozilla.org/addons/integration;1'], + 'jsm': 'resource://gre/modules/addonManager.js', + 'constructor': 'amManager', + }, + { + 'cid': '{9df8ef2b-94da-45c9-ab9f-132eb55fddf1}', + 'contract_ids': ['@mozilla.org/addons/installtrigger;1'], + 'jsm': 'resource://gre/modules/amInstallTrigger.jsm', + 'constructor': 'InstallTrigger', + }, +] + +if buildconfig.substs['MOZ_WIDGET_TOOLKIT'] != 'android': + Classes += [ + { + 'cid': '{7beb3ba8-6ec3-41b4-b67c-da89b8518922}', + 'contract_ids': ['@mozilla.org/uriloader/content-handler;1?type=application/x-xpinstall'], + 'jsm': 'resource://gre/modules/amContentHandler.jsm', + 'constructor': 'amContentHandler', + }, + { + 'cid': '{8866d8e3-4ea5-48b7-a891-13ba0ac15235}', + 'contract_ids': ['@mozilla.org/addon-web-api/manager;1'], + 'jsm': 'resource://gre/modules/amWebAPI.jsm', + 'constructor': 'WebAPI', + }, + ] diff --git a/toolkit/mozapps/extensions/content/OpenH264-license.txt b/toolkit/mozapps/extensions/content/OpenH264-license.txt new file mode 100644 index 0000000000..ad37989b8c --- /dev/null +++ b/toolkit/mozapps/extensions/content/OpenH264-license.txt @@ -0,0 +1,59 @@ +------------------------------------------------------- +About The Cisco-Provided Binary of OpenH264 Video Codec +------------------------------------------------------- + +Cisco provides this program under the terms of the BSD license. + +Additionally, this binary is licensed under Cisco’s AVC/H.264 Patent Portfolio License from MPEG LA, at no cost to you, provided that the requirements and conditions shown below in the AVC/H.264 Patent Portfolio sections are met. + +As with all AVC/H.264 codecs, you may also obtain your own patent license from MPEG LA or from the individual patent owners, or proceed at your own risk. Your rights from Cisco under the BSD license are not affected by this choice. + +For more information on the OpenH264 binary licensing, please see the OpenH264 FAQ found at http://www.openh264.org/faq.html#binary + +A corresponding source code to this binary program is available under the same BSD terms, which can be found at http://www.openh264.org + +----------- +BSD License +----------- + +Copyright © 2014 Cisco Systems, 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 THE COPYRIGHT HOLDERS AND 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 THE COPYRIGHT HOLDER OR 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. + +----------------------------------------- +AVC/H.264 Patent Portfolio License Notice +----------------------------------------- + +The binary form of this Software is distributed by Cisco under the AVC/H.264 Patent Portfolio License from MPEG LA, and is subject to the following requirements, which may or may not be applicable to your use of this software: + +THIS PRODUCT IS LICENSED UNDER THE AVC PATENT PORTFOLIO LICENSE FOR THE PERSONAL USE OF A CONSUMER OR OTHER USES IN WHICH IT DOES NOT RECEIVE REMUNERATION TO (i) ENCODE VIDEO IN COMPLIANCE WITH THE AVC STANDARD (“AVC VIDEO”) AND/OR (ii) DECODE AVC VIDEO THAT WAS ENCODED BY A CONSUMER ENGAGED IN A PERSONAL ACTIVITY AND/OR WAS OBTAINED FROM A VIDEO PROVIDER LICENSED TO PROVIDE AVC VIDEO. NO LICENSE IS GRANTED OR SHALL BE IMPLIED FOR ANY OTHER USE. ADDITIONAL INFORMATION MAY BE OBTAINED FROM MPEG LA, L.L.C. SEE HTTP://WWW.MPEGLA.COM + +Accordingly, please be advised that content providers and broadcasters using AVC/H.264 in their service may be required to obtain a separate use license from MPEG LA, referred to as "(b) sublicenses" in the SUMMARY OF AVC/H.264 LICENSE TERMS from MPEG LA found at http://www.openh264.org/mpegla + +--------------------------------------------- +AVC/H.264 Patent Portfolio License Conditions +--------------------------------------------- + +In addition, the Cisco-provided binary of this Software is licensed under Cisco's license from MPEG LA only if the following conditions are met: + +1. The Cisco-provided binary is separately downloaded to an end user’s device, and not integrated into or combined with third party software prior to being downloaded to the end user’s device; + +2. The end user must have the ability to control (e.g., to enable, disable, or re-enable) the use of the Cisco-provided binary; + +3. Third party software, in the location where end users can control the use of the Cisco-provided binary, must display the following text: + + "OpenH264 Video Codec provided by Cisco Systems, Inc." + +4. Any third-party software that makes use of the Cisco-provided binary must reproduce all of the above text, as well as this last condition, in the EULA and/or in another location where licensing information is to be presented to the end user. + + + + v1.0 diff --git a/toolkit/mozapps/extensions/content/aboutaddons.css b/toolkit/mozapps/extensions/content/aboutaddons.css new file mode 100644 index 0000000000..7c37afb6d9 --- /dev/null +++ b/toolkit/mozapps/extensions/content/aboutaddons.css @@ -0,0 +1,891 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +:root { + -moz-box-layout: flex; + --addon-icon-size: 32px; + --card-border-zap-gradient: linear-gradient(90deg, #9059FF 0%, #FF4AA2 52.08%, #FFBD4F 100%); + --main-margin-start: 28px; + --section-width: 664px; + --sidebar-width: var(--in-content-sidebar-width); + --z-index-sticky-container: 5; + --z-index-card-banner-text: 1; + --z-index-popup: 10; +} + +@media (max-width: 830px) { + :root { + --main-margin-start: 16px; + /* Maintain a main margin so card shadows don't overlap the sidebar. */ + --sidebar-width: calc(var(--in-content-sidebar-width) - var(--main-margin-start)); + } +} + +*|*[hidden] { + display: none !important; +} + +body { + cursor: default; + /* The page starts to look really bad lower than this. */ + min-width: 500px; +} + +#full { + display: grid; + grid-template-columns: var(--sidebar-width) 1fr; +} + +#sidebar { + position: sticky; + top: 0; + height: 100vh; + display: flex; + flex-direction: column; + margin: 0; + overflow: hidden auto; +} + +@media (prefers-reduced-motion) { + /* Setting border-inline-end on #sidebar makes it a focusable element */ + #sidebar::after { + content: ""; + width: 1px; + height: 100%; + background-color: var(--in-content-border-color); + top: 0; + inset-inline-end: 0; + position: absolute; + } +} + +#categories { + display: flex; + flex-direction: column; + padding-inline-end: 4px; /* Leave space for the button focus styles. */ +} + +.category { + display: grid; + grid-template-columns: 1fr auto; + margin-block: 0; + align-items: center; + font-weight: normal; +} + +.category[badge-count]::after { + display: inline-block; + min-width: 20px; + background-color: var(--in-content-accent-color); + color: var(--in-content-primary-button-text-color); + font-weight: bold; + /* Use a large border-radius to get semi-circles on the sides. */ + border-radius: 1000px; + padding: 2px 6px; + content: attr(badge-count); + text-align: center; + margin-inline-start: 8px; + grid-column: 2; +} + +.category[name="discover"] { + background-image: url("chrome://mozapps/skin/extensions/category-discover.svg"); +} +.category[name="locale"] { + background-image: url("chrome://mozapps/skin/extensions/category-languages.svg"); +} +.category[name="extension"] { + background-image: url("chrome://mozapps/skin/extensions/category-extensions.svg"); +} +.category[name="theme"] { + background-image: url("chrome://mozapps/skin/extensions/category-themes.svg"); +} +.category[name="plugin"] { + background-image: url("chrome://mozapps/skin/extensions/category-plugins.svg"); +} +.category[name="dictionary"] { + background-image: url("chrome://mozapps/skin/extensions/category-dictionaries.svg"); +} +.category[name="available-updates"] { + background-image: url("chrome://mozapps/skin/extensions/category-available.svg"); +} +.category[name="recent-updates"] { + background-image: url("chrome://mozapps/skin/extensions/category-recent.svg"); +} +.category[name="sitepermission"] { + background-image: url("chrome://mozapps/skin/extensions/category-sitepermission.svg"); +} + +.sticky-container { + background: var(--in-content-page-background); + width: 100%; + position: sticky; + top: 0; + z-index: var(--z-index-sticky-container); +} + +.main-search { + background: var(--in-content-page-background); + display: flex; + justify-content: flex-end; + align-items: center; + padding-inline-start: 28px; + padding-top: 20px; + padding-bottom: 30px; + max-width: var(--section-width); +} + +search-addons > search-textbox { + margin: 0; + width: 20em; + min-height: 32px; +} + +.search-label { + margin-inline-end: 8px; +} + +.main-heading { + background: var(--in-content-page-background); + display: flex; + margin-inline-start: var(--main-margin-start); + padding-bottom: 16px; + max-width: var(--section-width); +} + +.spacer { + flex-grow: 1; +} + +#updates-message { + display: flex; + align-items: center; + margin-inline-end: 8px; +} + +.back-button { + margin-inline-end: 16px; +} + +/* Plugins aren't yet disabled by safemode (bug 342333), + so don't show that warning when viewing plugins. */ +#page-header[current-param="plugin"] message-bar[warning-type="safe-mode"] { + display: none; +} + +#main { + margin-inline-start: var(--main-margin-start); + margin-bottom: 28px; + max-width: var(--section-width); +} + +global-warnings, +#abuse-reports-messages { + margin-inline-start: var(--main-margin-start); + max-width: var(--section-width); +} + +/* The margin between message bars. */ +message-bar-stack > * { + margin-bottom: 8px; +} + +/* List sections */ + +.list-section-heading { + font-size: 17px; + font-weight: 600; + margin-bottom: 16px; +} + +.list-section-subheading { + font-size: 0.9em; + font-weight: 400; + margin-block-start: 0.5em; +} + +.section { + margin-bottom: 32px; +} + +/* Add-on cards */ + +.addon.card { + margin-bottom: 16px; + transition: opacity 150ms, box-shadow 150ms; +} + +addon-list:not([type="theme"]) addon-card:not([expanded]):not([panelopen]) > .addon.card[active="false"]:not(:focus-within):not(:hover) { + opacity: 0.6; +} + +.addon.card:hover { + box-shadow: var(--card-shadow); +} + +addon-card:not([expanded]) > .addon.card:hover { + box-shadow: var(--card-shadow-hover); + cursor: pointer; +} + +addon-card[expanded] .addon.card { + padding-bottom: 0; +} + +.addon-card-collapsed { + display: flex; +} + +addon-list addon-card > .addon.card { + user-select: none; +} + +.addon-card-message, +.update-postponed-bar { + border-top-left-radius: 0; + border-top-right-radius: 0; + margin: 8px calc(var(--card-padding) * -1) calc(var(--card-padding) * -1); +} + +addon-card[expanded] .addon-card-message, +addon-card[expanded] .update-postponed-bar { + border-radius: 0; + margin-bottom: 0; +} + +addon-card[expanded] .update-postponed-bar + .addon-card-message { + /* Remove margin between the two message bars when they are both + * visible in the detail view */ + margin-top: 0px; +} + +.update-postponed-bar + .addon-card-message { + /* Prevent the small overlapping between the two message bars + * when they are both visible at the same time one after the + * other on the same addon card */ + margin-top: 12px; +} + +/* Theme preview image. */ +.card-heading-image { + /* If the width, height or aspect ratio changes, don't forget to update the + * getScreenshotUrlForAddon function in aboutaddons.js */ + width: var(--section-width); + /* Adjust height so that the image preserves the aspect ratio from AMO. + * For details, see https://bugzilla.mozilla.org/show_bug.cgi?id=1546123 */ + height: calc(var(--section-width) * 92 / 680); + object-fit: cover; +} + +.card-heading-icon { + flex-shrink: 0; + width: var(--addon-icon-size); + height: var(--addon-icon-size); + margin-inline-end: 16px; + -moz-context-properties: fill; + fill: currentColor; +} + +.card-contents { + word-break: break-word; + flex-grow: 1; + display: flex; + flex-direction: column; +} + +.addon-name-container { + /* Subtract the top line-height so the text and icon align at the top. */ + margin-top: -3px; + display: flex; + align-items: center; +} + +.addon-name { + font-size: 16px; + font-weight: 600; + line-height: 22px; + margin: 0; + margin-inline-end: 8px; +} + +.addon-name-link, +.addon-name-link:hover { + color: var(--in-content-text-color); + text-decoration: none; +} + +.addon-name-link:-moz-focusring { + /* Since the parent is overflow:hidden to ellipsize the regular outline is hidden. */ + outline-offset: -1px; + outline-width: 1px; +} + +.addon-badge { + display: inline-block; + margin-inline-end: 8px; + width: 22px; + height: 22px; + background-repeat: no-repeat; + background-position: center; + flex-shrink: 0; + border-radius: 11px; + -moz-context-properties: fill; + fill: #fff; +} + +.addon-badge-private-browsing-allowed { + background-image: url("chrome://global/skin/icons/indicator-private-browsing.svg"); +} + +.addon-badge-recommended { + background-color: var(--orange-50); + background-image: url("chrome://mozapps/skin/extensions/recommended.svg"); +} + +.addon-badge-line { + background-color: #fff; + background-image: url("chrome://mozapps/skin/extensions/line.svg"); + background-size: 16px; + border-radius: 10px; + border: 1px solid #CFCFD8; + width: 20px; + height: 20px; +} + +.addon-badge-verified { + background-color: var(--green-70); + background-image: url("chrome://global/skin/icons/check.svg"); +} + +.theme-enable-button { + min-width: auto; + height: auto; + font-size: 13px; + min-height: auto; + height: 24px; + margin: 0; + padding: 0 8px; + font-weight: normal; +} + +.addon-description { + font-size: 14px; + line-height: 20px; + color: var(--in-content-deemphasized-text); + font-weight: 400; +} + +/* Prevent the content from wrapping unless expanded. */ +addon-card:not([expanded]) .card-contents { + /* We're hiding the content when it's too long, so we need to define the + * width. As long as this is less than the width of its parent it works. */ + width: 1px; + white-space: nowrap; +} + +/* Ellipsize if the content is too long. */ +addon-card:not([expanded]) .addon-name, +addon-card:not([expanded]) .addon-description { + text-overflow: ellipsis; + overflow-x: hidden; +} + +.page-options-menu { + align-self: center; +} + +.page-options-menu > .more-options-button { + background-image: url("chrome://global/skin/icons/settings.svg"); + width: 32px; + height: 32px; +} + +/* Recommended add-ons on list views */ +.recommended-heading { + margin-bottom: 24px; + margin-top: 48px; +} + +/* Discopane extensions to the add-on card */ + +recommended-addon-card .addon-description:not(:empty) { + margin-top: 0.5em; +} + +.disco-card-head { + flex-grow: 1; + display: flex; + flex-direction: column; +} + +.disco-addon-name { + font-size: inherit; + font-weight: normal; + line-height: normal; + margin: 0; +} + +.disco-addon-author { + font-size: 12px; + font-weight: normal; +} + +.disco-description-statistics { + margin-top: 1em; + display: grid; + grid-template-columns: repeat(2, max-content); + grid-column-gap: 2em; + align-items: center; +} + +.disco-cta-button { + font-size: 14px; + flex-shrink: 0; + flex-grow: 0; + align-self: baseline; + margin-inline-end: 0; +} + +.discopane-notice { + margin: 24px 0; +} + +.discopane-notice-content { + padding-block: 6px; +} + +.discopane-notice-content > span { + flex-grow: 1; + margin-inline-end: 4px; +} + +.discopane-notice-content > button { + flex-grow: 0; + flex-shrink: 0; +} + +.view-footer { + text-align: center; +} + +.view-footer-item { + margin-top: 30px; +} + +.privacy-policy-link { + font-size: small; +} + +.theme-recommendation { + text-align: start; +} + +addon-details { + color: var(--in-content-deemphasized-text); +} + +.addon-detail-description-wrapper { + margin: 16px 0; +} + +.addon-detail-description-collapse .addon-detail-description { + max-height: 20rem; + overflow: hidden; +} + +/* Include button to beat out .button-link which is below this */ +button.addon-detail-description-toggle { + display: flex; + align-items: center; + margin-top: 8px; + font-weight: normal; + gap: 4px; +} + +.addon-detail-description-toggle::after { + content: ""; + display: block; + background-image: url("chrome://global/skin/icons/arrow-up-12.svg"); + background-repeat: no-repeat; + background-position: center; + -moz-context-properties: fill; + fill: currentColor; + width: 12px; + height: 12px; +} + +.addon-detail-description-collapse .addon-detail-description-toggle::after { + transform: scaleY(-1); +} + +.addon-detail-contribute { + display: flex; + padding: var(--card-padding); + border: 1px solid var(--in-content-box-border-color); + border-radius: 4px; + margin-bottom: var(--card-padding); + flex-direction: column; +} + +.addon-detail-contribute > label { + font-style: italic; +} + +.addon-detail-contribute-button { + -moz-context-properties: fill; + fill: currentColor; + background-image: url("chrome://global/skin/icons/heart.svg"); + background-repeat: no-repeat; + background-position: 8px; + padding-inline-start: 28px; + margin-top: var(--card-padding); + margin-bottom: 0; + align-self: flex-end; +} + +.addon-detail-contribute-button:dir(rtl) { + background-position-x: right 8px; +} + +.addon-detail-sitepermissions, +.addon-detail-row { + display: flex; + justify-content: space-between; + align-items: center; + border-top: 1px solid var(--in-content-border-color); + margin: 0 calc(var(--card-padding) * -1); + padding: var(--card-padding); + color: var(--in-content-text-color); +} + +.addon-detail-row.addon-detail-help-row { + display: block; + color: var(--in-content-deemphasized-text); + padding-top: 4px; + padding-bottom: var(--card-padding); + border: none; +} + +.addon-detail-row-has-help { + padding-bottom: 0; +} + +.addon-detail-row input[type="checkbox"] { + margin: 0; +} + +.addon-detail-actions, +.addon-detail-rating { + display: flex; +} + +.addon-detail-actions { + gap: 20px; +} + +.addon-detail-actions > label { + flex-wrap: wrap; +} + +.addon-detail-rating > a { + margin-inline-start: 8px; +} + +.more-options-button { + min-width: auto; + min-height: auto; + width: 24px; + height: 24px; + margin: 0; + margin-inline-start: 8px; + -moz-context-properties: fill; + fill: currentColor; + background-image: url("chrome://global/skin/icons/more.svg"); + background-repeat: no-repeat; + background-position: center center; + /* Get the -badged ::after element in the right spot. */ + padding: 1px; + display: flex; + justify-content: flex-end; +} + +.more-options-button-badged::after { + content: ""; + display: block; + width: 5px; + height: 5px; + border-radius: 50%; + background-color: var(--in-content-accent-color);; +} + +panel-item[action="remove"]::part(button) { + background-image: url("chrome://global/skin/icons/delete.svg"); +} + +panel-item[action="install-update"]::part(button) { + background-image: url("chrome://global/skin/icons/update-icon.svg"); +} + +panel-item[action="report"]::part(button) { + background-image: url(chrome://global/skin/icons/warning.svg); +} + +.hide-amo-link .amo-link-container { + display: none; +} + +.button-link { + min-height: auto; + background: none !important; + padding: 0; + margin: 0; + color: var(--in-content-link-color) !important; + cursor: pointer; + border: none; +} + +.button-link:hover { + color: var(--in-content-link-color-hover) !important; + text-decoration: underline; +} + +.button-link:active { + color: var(--in-content-link-color-active) !important; + text-decoration: none; +} + +.inline-options-stack { + /* If the options browser triggers an alert we need room to show it. */ + min-height: 250px; + width: 100%; + background-color: white; + margin-block: 4px; +} + +addon-permissions-list > .addon-detail-row { + border-top: none; +} + +.addon-permissions-list { + list-style-type: none; + margin: 0; + padding-inline-start: 8px; +} + +.addon-permissions-list > li { + border: none; + padding-block: 4px; + padding-inline-start: 2rem; + background-image: none; + background-position: 0 center; + background-size: 1.6rem 1.6rem; + background-repeat: no-repeat; +} + +.addon-permissions-list > li:dir(rtl) { + background-position-x: right 0; +} + +/* justify the permission toggle */ +li.permission-info > label { + display: flex; + justify-content: space-between; + align-items: center; +} + +/* using a list-style-image prevents aligning the image */ +.addon-permissions-list > li.permission-checked { + background-image: url("chrome://global/skin/icons/check.svg"); + -moz-context-properties: fill; + fill: var(--green-60); +} + +.permission-header { + font-size: 1em; +} + +.tab-group { + display: block; + margin-top: 8px; + /* Pull the buttons flush with the side of the card */ + margin-inline: calc(var(--card-padding) * -1); + border-bottom: 1px solid var(--in-content-border-color); + border-top: 1px solid var(--in-content-border-color); + font-size: 0; + line-height: 0; +} + +button.tab-button { + appearance: none; + border-inline: none; + border-block: 2px solid transparent; + border-radius: 0; + background: transparent; + font-size: 14px; + line-height: 20px; + margin: 0; + padding: 4px 16px; +} + +button.tab-button:hover { + border-top-color: var(--in-content-box-border-color); +} + +button.tab-button[selected], +button.tab-button[selected]:hover { + border-top-color: currentColor; + color: var(--in-content-accent-color); +} + +@media (prefers-contrast) { + button.tab-button[selected], + button.tab-button[selected]:hover { + color: var(--in-content-primary-button-text-color); + background-color: var(--in-content-primary-button-background); + } +} + +button.tab-button:-moz-focusring { + outline-offset: -2px; +} + +.tab-group[last-input-type="mouse"] > button.tab-button:-moz-focusring { + outline: none; + box-shadow: none; +} + +section:not(:empty) ~ #empty-addons-message { + display: none; +} + +@media (max-width: 830px) { + .category[badge-count]::after { + content: ""; + display: block; + width: 5px; + height: 5px; + border-radius: 50%; + min-width: auto; + padding: 0; + /* move the badged dot into the top-end (right in ltr, left in rtl) corner. */ + margin-top: -20px; + } +} + +/* Colorways Section */ + +.monochromatic-addon-list section { + display: flex; + flex-flow: row wrap; + justify-content: space-between; +} + +.monochromatic-addon-list .header-name, +.monochromatic-addon-list .list-section-subheading { + flex-basis: 100%; +} + +.monochromatic-addon-list addon-card .card { + box-sizing: border-box; + height: calc(100% - 16px); + overflow: clip; + width: calc((var(--section-width) / 3) - 16px); +} + +.monochromatic-addon-list addon-card .card .card-contents { + white-space: normal; +} + +/* Remove disabled add-on fade */ +.monochromatic-addon-list addon-card:not([expanded]) > .addon.card[active="false"] { + opacity: unset; +} + +.monochromatic-addon-list .addon-name-container { + align-items: start; + display: grid; + grid-template-columns: auto 1fr; + grid-template-rows: 3em 1fr; + row-gap: 16px; +} + +.monochromatic-addon-list .addon-name-container .addon-name { + grid-column-end: span 2; + overflow: hidden; + text-overflow: ellipsis; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; +} + +.monochromatic-addon-list .addon-name-container .spacer { + display: none; +} + +.permission-header > .addon-sitepermissions-host { + font-weight: bolder; +} + +.colorways-section > .list-section-heading { + margin-bottom: 0; +} + +#colorways-expiry-date-container { + display: flex; + flex-grow: 1; + flex-direction: row; +} + +#colorways-expiry-date { + display: inline-block; + background-image: var(--card-border-zap-gradient); + background-origin: border-box; + border: 1px solid transparent; + border-radius: 1.5em; +} + +#colorways-expiry-date > span { + display: inline-block; + color: var(--in-content-page-color); + background: var(--in-content-page-background); + border-radius: 1.5em; + padding: .3em 1em; +} + +#colorways-button { + flex-shrink: 0; + flex-grow: 0; + align-self: baseline; + margin-inline-end: 0; +} + +#colorways-preview-text-container { + z-index: var(--z-index-card-banner-text); + position: absolute; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + /* Make sure text fits within addon card dimensions */ + width: var(--section-width); + height: calc(var(--section-width) * 92 / 680); + margin: -16px -16px; +} + +#colorways-preview-text-container > h3, +#colorways-preview-text-container > p { + margin: 0; +} + +#colorways-preview-text-container > h3 { + font-size: 2.6em; +} + +#colorways-preview-text-container > p { + font-size: 1.1em; +} + +#colorways-preview-text-container + .card-heading-image { + background-color: var(--in-content-box-background-odd); +} diff --git a/toolkit/mozapps/extensions/content/aboutaddons.html b/toolkit/mozapps/extensions/content/aboutaddons.html new file mode 100644 index 0000000000..b84d13e2b1 --- /dev/null +++ b/toolkit/mozapps/extensions/content/aboutaddons.html @@ -0,0 +1,445 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/toolkit/mozapps/extensions/content/aboutaddons.js b/toolkit/mozapps/extensions/content/aboutaddons.js new file mode 100644 index 0000000000..be8a4f5377 --- /dev/null +++ b/toolkit/mozapps/extensions/content/aboutaddons.js @@ -0,0 +1,4787 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +/* eslint max-len: ["error", 80] */ +/* import-globals-from aboutaddonsCommon.js */ +/* import-globals-from abuse-reports.js */ +/* import-globals-from view-controller.js */ +/* global windowRoot */ + +"use strict"; + +ChromeUtils.defineESModuleGetters(this, { + BuiltInThemes: "resource:///modules/BuiltInThemes.sys.mjs", + ClientID: "resource://gre/modules/ClientID.sys.mjs", + DeferredTask: "resource://gre/modules/DeferredTask.sys.mjs", + E10SUtils: "resource://gre/modules/E10SUtils.sys.mjs", + PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.sys.mjs", +}); + +XPCOMUtils.defineLazyModuleGetters(this, { + AddonManager: "resource://gre/modules/AddonManager.jsm", + AddonRepository: "resource://gre/modules/addons/AddonRepository.jsm", + AMTelemetry: "resource://gre/modules/AddonManager.jsm", + ColorwayClosetOpener: "resource:///modules/ColorwayClosetOpener.jsm", + ExtensionCommon: "resource://gre/modules/ExtensionCommon.jsm", + ExtensionParent: "resource://gre/modules/ExtensionParent.jsm", + ExtensionPermissions: "resource://gre/modules/ExtensionPermissions.jsm", + NimbusFeatures: "resource://nimbus/ExperimentAPI.jsm", +}); + +XPCOMUtils.defineLazyGetter(this, "browserBundle", () => { + return Services.strings.createBundle( + "chrome://browser/locale/browser.properties" + ); +}); +XPCOMUtils.defineLazyGetter(this, "brandBundle", () => { + return Services.strings.createBundle( + "chrome://branding/locale/brand.properties" + ); +}); +XPCOMUtils.defineLazyGetter(this, "extensionStylesheets", () => { + const { ExtensionParent } = ChromeUtils.import( + "resource://gre/modules/ExtensionParent.jsm" + ); + return ExtensionParent.extensionStylesheets; +}); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "manifestV3enabled", + "extensions.manifestV3.enabled" +); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "SUPPORT_URL", + "app.support.baseURL", + "", + null, + val => Services.urlFormatter.formatURL(val) +); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "XPINSTALL_ENABLED", + "xpinstall.enabled", + true +); + +XPCOMUtils.defineLazyGetter(this, "COLORWAY_CLOSET_ENABLED", () => { + return !!( + NimbusFeatures.majorRelease2022.getVariable("colorwayCloset") && + BuiltInThemes.findActiveColorwayCollection() + ); +}); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "ACTIVE_THEME_ID", + "extensions.activeThemeID" +); + +const UPDATES_RECENT_TIMESPAN = 2 * 24 * 3600000; // 2 days (in milliseconds) + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "ABUSE_REPORT_ENABLED", + "extensions.abuseReport.enabled", + false +); +XPCOMUtils.defineLazyPreferenceGetter( + this, + "LIST_RECOMMENDATIONS_ENABLED", + "extensions.htmlaboutaddons.recommendations.enabled", + false +); + +const PLUGIN_ICON_URL = "chrome://global/skin/icons/plugin.svg"; +const EXTENSION_ICON_URL = + "chrome://mozapps/skin/extensions/extensionGeneric.svg"; + +const PERMISSION_MASKS = { + enable: AddonManager.PERM_CAN_ENABLE, + "always-activate": AddonManager.PERM_CAN_ENABLE, + disable: AddonManager.PERM_CAN_DISABLE, + "never-activate": AddonManager.PERM_CAN_DISABLE, + uninstall: AddonManager.PERM_CAN_UNINSTALL, + upgrade: AddonManager.PERM_CAN_UPGRADE, + "change-privatebrowsing": AddonManager.PERM_CAN_CHANGE_PRIVATEBROWSING_ACCESS, +}; + +const PREF_DISCOVERY_API_URL = "extensions.getAddons.discovery.api_url"; +const PREF_THEME_RECOMMENDATION_URL = + "extensions.recommendations.themeRecommendationUrl"; +const PREF_RECOMMENDATION_HIDE_NOTICE = "extensions.recommendations.hideNotice"; +const PREF_PRIVACY_POLICY_URL = "extensions.recommendations.privacyPolicyUrl"; +const PREF_RECOMMENDATION_ENABLED = "browser.discovery.enabled"; +const PREF_TELEMETRY_ENABLED = "datareporting.healthreport.uploadEnabled"; +const PRIVATE_BROWSING_PERM_NAME = "internal:privateBrowsingAllowed"; +const PRIVATE_BROWSING_PERMS = { + permissions: [PRIVATE_BROWSING_PERM_NAME], + origins: [], +}; + +const L10N_ID_MAPPING = { + "theme-disabled-heading": "theme-disabled-heading2", +}; + +function getL10nIdMapping(id) { + return L10N_ID_MAPPING[id] || id; +} + +function shouldSkipAnimations() { + return ( + document.body.hasAttribute("skip-animations") || + window.matchMedia("(prefers-reduced-motion: reduce)").matches + ); +} + +function callListeners(name, args, listeners) { + for (let listener of listeners) { + try { + if (name in listener) { + listener[name](...args); + } + } catch (e) { + Cu.reportError(e); + } + } +} + +function getUpdateInstall(addon) { + return ( + // Install object for a pending update. + addon.updateInstall || + // Install object for a postponed upgrade (only for extensions, + // because is the only addon type that can postpone their own + // updates). + (addon.type === "extension" && + addon.pendingUpgrade && + addon.pendingUpgrade.install) + ); +} + +function isManualUpdate(install) { + let isManual = + install.existingAddon && + !AddonManager.shouldAutoUpdate(install.existingAddon); + let isExtension = + install.existingAddon && install.existingAddon.type == "extension"; + return ( + (isManual && isInState(install, "available")) || + (isExtension && isInState(install, "postponed")) + ); +} + +const AddonManagerListenerHandler = { + listeners: new Set(), + + addListener(listener) { + this.listeners.add(listener); + }, + + removeListener(listener) { + this.listeners.delete(listener); + }, + + delegateEvent(name, args) { + callListeners(name, args, this.listeners); + }, + + startup() { + this._listener = new Proxy( + {}, + { + has: () => true, + get: (_, name) => (...args) => this.delegateEvent(name, args), + } + ); + AddonManager.addAddonListener(this._listener); + AddonManager.addInstallListener(this._listener); + AddonManager.addManagerListener(this._listener); + this._permissionHandler = (type, data) => { + if (type == "change-permissions") { + this.delegateEvent("onChangePermissions", [data]); + } + }; + ExtensionPermissions.addListener(this._permissionHandler); + }, + + shutdown() { + AddonManager.removeAddonListener(this._listener); + AddonManager.removeInstallListener(this._listener); + AddonManager.removeManagerListener(this._listener); + ExtensionPermissions.removeListener(this._permissionHandler); + }, +}; + +/** + * This object wires the AddonManager event listeners into addon-card and + * addon-details elements rather than needing to add/remove listeners all the + * time as the view changes. + */ +const AddonCardListenerHandler = new Proxy( + {}, + { + has: () => true, + get(_, name) { + return (...args) => { + let elements = []; + let addonId; + + // We expect args[0] to be of type: + // - AddonInstall, on AddonManager install events + // - AddonWrapper, on AddonManager addon events + // - undefined, on AddonManager manage events + if (args[0]) { + addonId = + args[0].addon?.id || + args[0].existingAddon?.id || + args[0].extensionId || + args[0].id; + } + + if (addonId) { + let cardSelector = `addon-card[addon-id="${addonId}"]`; + elements = document.querySelectorAll( + `${cardSelector}, ${cardSelector} addon-details` + ); + } else if (name == "onUpdateModeChanged") { + elements = document.querySelectorAll("addon-card"); + } + + callListeners(name, args, elements); + }; + }, + } +); +AddonManagerListenerHandler.addListener(AddonCardListenerHandler); + +function isAbuseReportSupported(addon) { + return ( + ABUSE_REPORT_ENABLED && + AbuseReporter.isSupportedAddonType(addon.type) && + !(addon.isBuiltin || addon.isSystem) + ); +} + +async function isAllowedInPrivateBrowsing(addon) { + // Use the Promise directly so this function stays sync for the other case. + let perms = await ExtensionPermissions.get(addon.id); + return perms.permissions.includes(PRIVATE_BROWSING_PERM_NAME); +} + +function hasPermission(addon, permission) { + return !!(addon.permissions & PERMISSION_MASKS[permission]); +} + +function isInState(install, state) { + return install.state == AddonManager["STATE_" + state.toUpperCase()]; +} + +async function getAddonMessageInfo(addon) { + const { name } = addon; + const { STATE_BLOCKED, STATE_SOFTBLOCKED } = Ci.nsIBlocklistService; + + if (addon.blocklistState === STATE_BLOCKED) { + return { + linkUrl: await addon.getBlocklistURL(), + messageId: "details-notification-blocked", + messageArgs: { name }, + type: "error", + }; + } else if (isDisabledUnsigned(addon)) { + return { + linkUrl: SUPPORT_URL + "unsigned-addons", + messageId: "details-notification-unsigned-and-disabled", + messageArgs: { name }, + type: "error", + }; + } else if ( + !addon.isCompatible && + (AddonManager.checkCompatibility || + addon.blocklistState !== STATE_SOFTBLOCKED) + ) { + return { + messageId: "details-notification-incompatible", + messageArgs: { name, version: Services.appinfo.version }, + type: "warning", + }; + } else if (!isCorrectlySigned(addon)) { + return { + linkUrl: SUPPORT_URL + "unsigned-addons", + messageId: "details-notification-unsigned", + messageArgs: { name }, + type: "warning", + }; + } else if (addon.blocklistState === STATE_SOFTBLOCKED) { + return { + linkUrl: await addon.getBlocklistURL(), + messageId: "details-notification-softblocked", + messageArgs: { name }, + type: "warning", + }; + } else if (addon.isGMPlugin && !addon.isInstalled && addon.isActive) { + return { + messageId: "details-notification-gmp-pending", + messageArgs: { name }, + type: "warning", + }; + } + return {}; +} + +function checkForUpdate(addon) { + return new Promise(resolve => { + let listener = { + onUpdateAvailable(addon, install) { + if (AddonManager.shouldAutoUpdate(addon)) { + // Make sure that an update handler is attached to all the install + // objects when updated xpis are going to be installed automatically. + attachUpdateHandler(install); + + let failed = () => { + detachUpdateHandler(install); + install.removeListener(updateListener); + resolve({ installed: false, pending: false, found: true }); + }; + let updateListener = { + onDownloadFailed: failed, + onInstallCancelled: failed, + onInstallFailed: failed, + onInstallEnded: (...args) => { + detachUpdateHandler(install); + install.removeListener(updateListener); + resolve({ installed: true, pending: false, found: true }); + }, + onInstallPostponed: (...args) => { + detachUpdateHandler(install); + install.removeListener(updateListener); + resolve({ installed: false, pending: true, found: true }); + }, + }; + install.addListener(updateListener); + install.install(); + } else { + resolve({ installed: false, pending: true, found: true }); + } + }, + onNoUpdateAvailable() { + resolve({ found: false }); + }, + }; + addon.findUpdates(listener, AddonManager.UPDATE_WHEN_USER_REQUESTED); + }); +} + +async function checkForUpdates() { + let addons = await AddonManager.getAddonsByTypes(null); + addons = addons.filter(addon => hasPermission(addon, "upgrade")); + let updates = await Promise.all(addons.map(addon => checkForUpdate(addon))); + gViewController.notifyEMUpdateCheckFinished(); + return updates.reduce( + (counts, update) => ({ + installed: counts.installed + (update.installed ? 1 : 0), + pending: counts.pending + (update.pending ? 1 : 0), + found: counts.found + (update.found ? 1 : 0), + }), + { installed: 0, pending: 0, found: 0 } + ); +} + +// Don't change how we handle this while the page is open. +const INLINE_OPTIONS_ENABLED = Services.prefs.getBoolPref( + "extensions.htmlaboutaddons.inline-options.enabled" +); +const OPTIONS_TYPE_MAP = { + [AddonManager.OPTIONS_TYPE_TAB]: "tab", + [AddonManager.OPTIONS_TYPE_INLINE_BROWSER]: INLINE_OPTIONS_ENABLED + ? "inline" + : "tab", +}; + +// Check if an add-on has the provided options type, accounting for the pref +// to disable inline options. +function getOptionsType(addon, type) { + return OPTIONS_TYPE_MAP[addon.optionsType]; +} + +// Check whether the options page can be loaded in the current browser window. +async function isAddonOptionsUIAllowed(addon) { + if (addon.type !== "extension" || !getOptionsType(addon)) { + // Themes never have options pages. + // Some plugins have preference pages, and they can always be shown. + // Extensions do not need to be checked if they do not have options pages. + return true; + } + if (!PrivateBrowsingUtils.isContentWindowPrivate(window)) { + return true; + } + if (addon.incognito === "not_allowed") { + return false; + } + // The current page is in a private browsing window, and the add-on does not + // have the permission to access private browsing windows. Block access. + return ( + // Note: This function is async because isAllowedInPrivateBrowsing is async. + isAllowedInPrivateBrowsing(addon) + ); +} + +let _templates = {}; + +/** + * Import a template from the main document. + */ +function importTemplate(name) { + if (!_templates.hasOwnProperty(name)) { + _templates[name] = document.querySelector(`template[name="${name}"]`); + } + let template = _templates[name]; + if (template) { + return document.importNode(template.content, true); + } + throw new Error(`Unknown template: ${name}`); +} + +function nl2br(text) { + let frag = document.createDocumentFragment(); + let hasAppended = false; + for (let part of text.split("\n")) { + if (hasAppended) { + frag.appendChild(document.createElement("br")); + } + frag.appendChild(new Text(part)); + hasAppended = true; + } + return frag; +} + +/** + * Select the screeenshot to display above an add-on card. + * + * @param {AddonWrapper|DiscoAddonWrapper} addon + * @returns {string|null} + * The URL of the best fitting screenshot, if any. + */ +function getScreenshotUrlForAddon(addon) { + if (addon.id == "default-theme@mozilla.org") { + return "chrome://mozapps/content/extensions/default-theme/preview.svg"; + } + const builtInThemePreview = BuiltInThemes.previewForBuiltInThemeId(addon.id); + if (builtInThemePreview) { + return builtInThemePreview; + } + + let { screenshots } = addon; + if (!screenshots || !screenshots.length) { + return null; + } + + // The image size is defined at .card-heading-image in aboutaddons.css, and + // is based on the aspect ratio for a 680x92 image. Use the image if possible, + // and otherwise fall back to the first image and hope for the best. + let screenshot = screenshots.find(s => s.width === 680 && s.height === 92); + if (!screenshot) { + console.warn(`Did not find screenshot with desired size for ${addon.id}.`); + screenshot = screenshots[0]; + } + return screenshot.url; +} + +/** + * Adds UTM parameters to a given URL, if it is an AMO URL. + * + * @param {string} contentAttribute + * Identifies the part of the UI with which the link is associated. + * @param {string} url + * @returns {string} + * The url with UTM parameters if it is an AMO URL. + * Otherwise the url in unmodified form. + */ +function formatUTMParams(contentAttribute, url) { + let parsedUrl = new URL(url); + let domain = `.${parsedUrl.hostname}`; + if ( + !domain.endsWith(".mozilla.org") && + // For testing: addons-dev.allizom.org and addons.allizom.org + !domain.endsWith(".allizom.org") + ) { + return url; + } + + parsedUrl.searchParams.set("utm_source", "firefox-browser"); + parsedUrl.searchParams.set("utm_medium", "firefox-browser"); + parsedUrl.searchParams.set("utm_content", contentAttribute); + return parsedUrl.href; +} + +// A wrapper around an item from the "results" array from AMO's discovery API. +// See https://addons-server.readthedocs.io/en/latest/topics/api/discovery.html +class DiscoAddonWrapper { + /** + * @param {object} details + * An item in the "results" array from AMO's discovery API. + */ + constructor(details) { + // Reuse AddonRepository._parseAddon to have the AMO response parsing logic + // in one place. + let repositoryAddon = AddonRepository._parseAddon(details.addon); + + // Note: Any property used by RecommendedAddonCard should appear here. + // The property names and values should have the same semantics as + // AddonWrapper, to ease the reuse of helper functions in this file. + this.id = repositoryAddon.id; + this.type = repositoryAddon.type; + this.name = repositoryAddon.name; + this.screenshots = repositoryAddon.screenshots; + this.sourceURI = repositoryAddon.sourceURI; + this.creator = repositoryAddon.creator; + this.averageRating = repositoryAddon.averageRating; + + this.dailyUsers = details.addon.average_daily_users; + + this.editorialDescription = details.description_text; + this.iconURL = details.addon.icon_url; + this.amoListingUrl = details.addon.url; + + this.taarRecommended = details.is_recommendation; + } +} + +/** + * A helper to retrieve the list of recommended add-ons via AMO's discovery API. + */ +var DiscoveryAPI = { + // Map Promises from fetching the API results with or + // without a client ID. The `false` (no client ID) case could actually + // have been fetched with a client ID. See getResults() for more info. + _resultPromises: new Map(), + + /** + * Fetch the list of recommended add-ons. The results are cached. + * + * Pending requests are coalesced, so there is only one request at any given + * time. If a request fails, the pending promises are rejected, but a new + * call will result in a new request. A succesful response is cached for the + * lifetime of the document. + * + * @param {boolean} preferClientId + * A boolean indicating a preference for using a client ID. + * This will not overwrite the user preference but will + * avoid sending a client ID if no request has been made yet. + * @returns {Promise} + */ + async getResults(preferClientId = true) { + // Allow a caller to set preferClientId to false, but not true if discovery + // is disabled. + preferClientId = preferClientId && this.clientIdDiscoveryEnabled; + + // Reuse a request for this preference first. + let resultPromise = + this._resultPromises.get(preferClientId) || + // If the client ID isn't preferred, we can still reuse a request with the + // client ID. + (!preferClientId && this._resultPromises.get(true)); + + if (resultPromise) { + return resultPromise; + } + + // Nothing is prepared for this preference, make a new request. + resultPromise = this._fetchRecommendedAddons(preferClientId).catch(e => { + // Delete the pending promise, so _fetchRecommendedAddons can be + // called again at the next property access. + this._resultPromises.delete(preferClientId); + Cu.reportError(e); + throw e; + }); + + // Store the new result for the preference. + this._resultPromises.set(preferClientId, resultPromise); + + return resultPromise; + }, + + get clientIdDiscoveryEnabled() { + // These prefs match Discovery.jsm for enabling clientId cookies. + return ( + Services.prefs.getBoolPref(PREF_RECOMMENDATION_ENABLED, false) && + Services.prefs.getBoolPref(PREF_TELEMETRY_ENABLED, false) && + !PrivateBrowsingUtils.isContentWindowPrivate(window) + ); + }, + + async _fetchRecommendedAddons(useClientId) { + let discoveryApiUrl = new URL( + Services.urlFormatter.formatURLPref(PREF_DISCOVERY_API_URL) + ); + + if (useClientId) { + let clientId = await ClientID.getClientIdHash(); + discoveryApiUrl.searchParams.set("telemetry-client-id", clientId); + } + let res = await fetch(discoveryApiUrl.href, { + credentials: "omit", + }); + if (!res.ok) { + throw new Error(`Failed to fetch recommended add-ons, ${res.status}`); + } + let { results } = await res.json(); + return results.map(details => new DiscoAddonWrapper(details)); + }, +}; + +class SupportLink extends HTMLAnchorElement { + static get observedAttributes() { + return ["support-page"]; + } + + connectedCallback() { + this.setHref(); + this.setAttribute("target", "_blank"); + } + + attributeChangedCallback(name, oldVal, newVal) { + if (name === "support-page") { + this.setHref(); + } + } + + setHref() { + let base = SUPPORT_URL + this.getAttribute("support-page"); + this.href = this.hasAttribute("utmcontent") + ? formatUTMParams(this.getAttribute("utmcontent"), base) + : base; + } +} +customElements.define("support-link", SupportLink, { extends: "a" }); + +class SearchAddons extends HTMLElement { + connectedCallback() { + if (this.childElementCount === 0) { + this.input = document.createXULElement("search-textbox"); + this.input.setAttribute("searchbutton", true); + this.input.setAttribute("maxlength", 100); + this.input.setAttribute("data-l10n-attrs", "placeholder"); + document.l10n.setAttributes(this.input, "addons-heading-search-input"); + this.append(this.input); + } + this.input.addEventListener("command", this); + document.addEventListener("keypress", this); + } + + disconnectedCallback() { + this.input.removeEventListener("command", this); + document.removeEventListener("keypress", this); + } + + focus() { + this.input.focus(); + } + + get focusKey() { + return this.getAttribute("key"); + } + + handleEvent(e) { + if (e.type === "command") { + this.searchAddons(this.value); + } else if (e.type === "keypress") { + if (e.key === "/" && !e.ctrlKey && !e.metaKey && !e.altKey) { + this.focus(); + } else if (e.key == this.focusKey) { + if (e.altKey || e.shiftKey) { + return; + } + + if (Services.appinfo.OS === "Darwin") { + if (e.metaKey && !e.ctrlKey) { + this.focus(); + } + } else if (e.ctrlKey && !e.metaKey) { + this.focus(); + } + } + } + } + + get value() { + return this.input.value; + } + + searchAddons(query) { + if (query.length === 0) { + return; + } + + let url = formatUTMParams( + "addons-manager-search", + AddonRepository.getSearchURL(query) + ); + + let browser = getBrowserElement(); + let chromewin = browser.ownerGlobal; + chromewin.openLinkIn(url, "tab", { + fromChrome: true, + triggeringPrincipal: Services.scriptSecurityManager.createNullPrincipal( + {} + ), + }); + + AMTelemetry.recordLinkEvent({ + object: "aboutAddons", + value: "search", + extra: { + type: this.closest("addon-page-header").getAttribute("type"), + view: getTelemetryViewName(this), + }, + }); + } +} +customElements.define("search-addons", SearchAddons); + +class MessageBarStackElement extends HTMLElement { + constructor() { + super(); + this._observer = null; + const shadowRoot = this.attachShadow({ mode: "open" }); + shadowRoot.append(this.constructor.template.content.cloneNode(true)); + } + + connectedCallback() { + // Close any message bar that should be allowed based on the + // maximum number of message bars. + this.closeMessageBars(); + + // Observe mutations to close older bars when new ones have been + // added. + this._observer = new MutationObserver(() => { + this._observer.disconnect(); + this.closeMessageBars(); + this._observer.observe(this, { childList: true }); + }); + this._observer.observe(this, { childList: true }); + } + + disconnectedCallback() { + this._observer.disconnect(); + this._observer = null; + } + + closeMessageBars() { + const { maxMessageBarCount } = this; + if (maxMessageBarCount > 1) { + // Remove the older message bars if the stack reached the + // maximum number of message bars allowed. + while (this.childElementCount > maxMessageBarCount) { + this.firstElementChild.remove(); + } + } + } + + get maxMessageBarCount() { + return parseInt(this.getAttribute("max-message-bar-count"), 10); + } + + static get template() { + const template = document.createElement("template"); + + const style = document.createElement("style"); + // Render the stack in the reverse order if the stack has the + // reverse attribute set. + style.textContent = ` + :host { + display: block; + } + :host([reverse]) > slot { + display: flex; + flex-direction: column-reverse; + } + `; + template.content.append(style); + template.content.append(document.createElement("slot")); + + Object.defineProperty(this, "template", { + value: template, + }); + + return template; + } +} + +customElements.define("message-bar-stack", MessageBarStackElement); + +class GlobalWarnings extends MessageBarStackElement { + constructor() { + super(); + // This won't change at runtime, but we'll want to fake it in tests. + this.inSafeMode = Services.appinfo.inSafeMode; + this.globalWarning = null; + } + + connectedCallback() { + this.refresh(); + this.addEventListener("click", this); + AddonManagerListenerHandler.addListener(this); + } + + disconnectedCallback() { + this.removeEventListener("click", this); + AddonManagerListenerHandler.removeListener(this); + } + + refresh() { + if (this.inSafeMode) { + this.setWarning("safe-mode"); + } else if ( + AddonManager.checkUpdateSecurityDefault && + !AddonManager.checkUpdateSecurity + ) { + this.setWarning("update-security", { action: true }); + } else if (!AddonManager.checkCompatibility) { + this.setWarning("check-compatibility", { action: true }); + } else { + this.removeWarning(); + } + } + + setWarning(type, opts) { + if ( + this.globalWarning && + this.globalWarning.getAttribute("warning-type") !== type + ) { + this.removeWarning(); + } + if (!this.globalWarning) { + this.globalWarning = document.createElement("message-bar"); + this.globalWarning.setAttribute("warning-type", type); + let textContainer = document.createElement("span"); + document.l10n.setAttributes(textContainer, `extensions-warning-${type}`); + this.globalWarning.appendChild(textContainer); + if (opts && opts.action) { + let button = document.createElement("button"); + document.l10n.setAttributes( + button, + `extensions-warning-${type}-button` + ); + button.setAttribute("action", type); + this.globalWarning.appendChild(button); + } + this.appendChild(this.globalWarning); + } + } + + removeWarning() { + if (this.globalWarning) { + this.globalWarning.remove(); + this.globalWarning = null; + } + } + + handleEvent(e) { + if (e.type === "click") { + switch (e.target.getAttribute("action")) { + case "update-security": + AddonManager.checkUpdateSecurity = true; + break; + case "check-compatibility": + AddonManager.checkCompatibility = true; + break; + } + } + } + + /** + * AddonManager listener events. + */ + + onCompatibilityModeChanged() { + this.refresh(); + } + + onCheckUpdateSecurityChanged() { + this.refresh(); + } +} +customElements.define("global-warnings", GlobalWarnings); + +class AddonPageHeader extends HTMLElement { + connectedCallback() { + if (this.childElementCount === 0) { + this.appendChild(importTemplate("addon-page-header")); + this.heading = this.querySelector(".header-name"); + this.backButton = this.querySelector(".back-button"); + this.pageOptionsMenuButton = this.querySelector( + '[action="page-options"]' + ); + // The addon-page-options element is outside of this element since this is + // position: sticky and that would break the positioning of the menu. + this.pageOptionsMenu = document.getElementById( + this.getAttribute("page-options-id") + ); + } + document.addEventListener("view-selected", this); + this.addEventListener("click", this); + this.addEventListener("mousedown", this); + // Use capture since the event is actually triggered on the internal + // panel-list and it doesn't bubble. + this.pageOptionsMenu.addEventListener("shown", this, true); + this.pageOptionsMenu.addEventListener("hidden", this, true); + } + + disconnectedCallback() { + document.removeEventListener("view-selected", this); + this.removeEventListener("click", this); + this.removeEventListener("mousedown", this); + this.pageOptionsMenu.removeEventListener("shown", this, true); + this.pageOptionsMenu.removeEventListener("hidden", this, true); + } + + setViewInfo({ type, param }) { + this.setAttribute("current-view", type); + this.setAttribute("current-param", param); + let viewType = type === "list" ? param : type; + this.setAttribute("type", viewType); + + this.heading.hidden = viewType === "detail"; + this.backButton.hidden = viewType !== "detail" && viewType !== "shortcuts"; + + this.backButton.disabled = !history.state?.previousView; + + if (viewType !== "detail") { + document.l10n.setAttributes(this.heading, `${viewType}-heading`); + } + } + + handleEvent(e) { + let { backButton, pageOptionsMenu, pageOptionsMenuButton } = this; + if (e.type === "click") { + switch (e.target) { + case backButton: + window.history.back(); + break; + case pageOptionsMenuButton: + if (e.mozInputSource == MouseEvent.MOZ_SOURCE_KEYBOARD) { + this.pageOptionsMenu.toggle(e); + } + break; + } + } else if ( + e.type == "mousedown" && + e.target == pageOptionsMenuButton && + e.button == 0 + ) { + this.pageOptionsMenu.toggle(e); + } else if ( + e.target == pageOptionsMenu.panel && + (e.type == "shown" || e.type == "hidden") + ) { + this.pageOptionsMenuButton.setAttribute( + "aria-expanded", + this.pageOptionsMenu.open + ); + } else if (e.target == document && e.type == "view-selected") { + const { type, param } = e.detail; + this.setViewInfo({ type, param }); + } + } +} +customElements.define("addon-page-header", AddonPageHeader); + +class AddonUpdatesMessage extends HTMLElement { + static get observedAttributes() { + return ["state"]; + } + + constructor() { + super(); + this.attachShadow({ mode: "open" }); + let style = document.createElement("style"); + style.textContent = ` + @import "chrome://global/skin/in-content/common.css"; + button { + margin: 0; + } + `; + this.message = document.createElement("span"); + this.message.hidden = true; + this.button = document.createElement("button"); + this.button.addEventListener("click", e => { + if (e.button === 0) { + gViewController.loadView("updates/available"); + } + }); + this.button.hidden = true; + this.shadowRoot.append(style, this.message, this.button); + } + + connectedCallback() { + document.l10n.connectRoot(this.shadowRoot); + document.l10n.translateFragment(this.shadowRoot); + } + + disconnectedCallback() { + document.l10n.disconnectRoot(this.shadowRoot); + } + + attributeChangedCallback(name, oldVal, newVal) { + if (name === "state" && oldVal !== newVal) { + let l10nId = `addon-updates-${newVal}`; + switch (newVal) { + case "updating": + case "installed": + case "none-found": + this.button.hidden = true; + this.message.hidden = false; + document.l10n.setAttributes(this.message, l10nId); + break; + case "manual-updates-found": + this.message.hidden = true; + this.button.hidden = false; + document.l10n.setAttributes(this.button, l10nId); + break; + } + } + } + + set state(val) { + this.setAttribute("state", val); + } +} +customElements.define("addon-updates-message", AddonUpdatesMessage); + +class AddonPageOptions extends HTMLElement { + connectedCallback() { + if (this.childElementCount === 0) { + this.render(); + } + this.addEventListener("click", this); + this.panel.addEventListener("showing", this); + AddonManagerListenerHandler.addListener(this); + } + + disconnectedCallback() { + this.removeEventListener("click", this); + this.panel.removeEventListener("showing", this); + AddonManagerListenerHandler.removeListener(this); + } + + toggle(...args) { + return this.panel.toggle(...args); + } + + get open() { + return this.panel.open; + } + + render() { + this.appendChild(importTemplate("addon-page-options")); + this.panel = this.querySelector("panel-list"); + this.installFromFile = this.querySelector('[action="install-from-file"]'); + this.toggleUpdatesEl = this.querySelector( + '[action="set-update-automatically"]' + ); + this.resetUpdatesEl = this.querySelector('[action="reset-update-states"]'); + this.onUpdateModeChanged(); + } + + async handleEvent(e) { + if (e.type === "click") { + e.target.disabled = true; + try { + await this.onClick(e); + } finally { + e.target.disabled = false; + } + } else if (e.type === "showing") { + this.installFromFile.hidden = !XPINSTALL_ENABLED; + } + } + + async onClick(e) { + switch (e.target.getAttribute("action")) { + case "check-for-updates": + await this.checkForUpdates(); + break; + case "view-recent-updates": + gViewController.loadView("updates/recent"); + break; + case "install-from-file": + if (XPINSTALL_ENABLED) { + installAddonsFromFilePicker().then(installs => { + for (let install of installs) { + this.recordActionEvent({ + action: "installFromFile", + value: install.installId, + }); + } + }); + } + break; + case "debug-addons": + this.openAboutDebugging(); + break; + case "set-update-automatically": + await this.toggleAutomaticUpdates(); + break; + case "reset-update-states": + await this.resetAutomaticUpdates(); + break; + case "manage-shortcuts": + gViewController.loadView("shortcuts/shortcuts"); + break; + } + } + + async checkForUpdates(e) { + this.recordActionEvent({ action: "checkForUpdates" }); + let message = document.getElementById("updates-message"); + message.state = "updating"; + message.hidden = false; + let { installed, pending } = await checkForUpdates(); + if (pending > 0) { + message.state = "manual-updates-found"; + } else if (installed > 0) { + message.state = "installed"; + } else { + message.state = "none-found"; + } + } + + openAboutDebugging() { + let mainWindow = window.windowRoot.ownerGlobal; + this.recordLinkEvent({ value: "about:debugging" }); + if ("switchToTabHavingURI" in mainWindow) { + let principal = Services.scriptSecurityManager.getSystemPrincipal(); + mainWindow.switchToTabHavingURI( + `about:debugging#/runtime/this-firefox`, + true, + { + ignoreFragment: "whenComparing", + triggeringPrincipal: principal, + } + ); + } + } + + automaticUpdatesEnabled() { + return AddonManager.updateEnabled && AddonManager.autoUpdateDefault; + } + + toggleAutomaticUpdates() { + if (!this.automaticUpdatesEnabled()) { + // One or both of the prefs is false, i.e. the checkbox is not + // checked. Now toggle both to true. If the user wants us to + // auto-update add-ons, we also need to auto-check for updates. + AddonManager.updateEnabled = true; + AddonManager.autoUpdateDefault = true; + } else { + // Both prefs are true, i.e. the checkbox is checked. + // Toggle the auto pref to false, but don't touch the enabled check. + AddonManager.autoUpdateDefault = false; + } + // Record telemetry for changing the update policy. + let updatePolicy = []; + if (AddonManager.autoUpdateDefault) { + updatePolicy.push("default"); + } + if (AddonManager.updateEnabled) { + updatePolicy.push("enabled"); + } + this.recordActionEvent({ + action: "setUpdatePolicy", + value: updatePolicy.join(","), + }); + } + + async resetAutomaticUpdates() { + let addons = await AddonManager.getAllAddons(); + for (let addon of addons) { + if ("applyBackgroundUpdates" in addon) { + addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DEFAULT; + } + } + this.recordActionEvent({ action: "resetUpdatePolicy" }); + } + + getTelemetryViewName() { + return getTelemetryViewName(document.getElementById("page-header")); + } + + recordActionEvent({ action, value }) { + AMTelemetry.recordActionEvent({ + object: "aboutAddons", + view: this.getTelemetryViewName(), + action, + addon: this.addon, + value, + }); + } + + recordLinkEvent({ value }) { + AMTelemetry.recordLinkEvent({ + object: "aboutAddons", + value, + extra: { + view: this.getTelemetryViewName(), + }, + }); + } + + /** + * AddonManager listener events. + */ + + onUpdateModeChanged() { + let updatesEnabled = this.automaticUpdatesEnabled(); + this.toggleUpdatesEl.checked = updatesEnabled; + let resetType = updatesEnabled ? "automatic" : "manual"; + let resetStringId = `addon-updates-reset-updates-to-${resetType}`; + document.l10n.setAttributes(this.resetUpdatesEl, resetStringId); + } +} +customElements.define("addon-page-options", AddonPageOptions); + +class CategoryButton extends HTMLButtonElement { + connectedCallback() { + if (this.childElementCount != 0) { + return; + } + + // Make sure the aria-selected attribute is set correctly. + this.selected = this.hasAttribute("selected"); + + document.l10n.setAttributes(this, `addon-category-${this.name}-title`); + + let text = document.createElement("span"); + text.classList.add("category-name"); + document.l10n.setAttributes(text, `addon-category-${this.name}`); + + this.append(text); + } + + load() { + gViewController.loadView(this.viewId); + } + + get isVisible() { + // Make a category button visible only if the related addon type is + // supported by the AddonManager Providers actually registered to + // the AddonManager. + return AddonManager.hasAddonType(this.name); + } + + get badgeCount() { + return parseInt(this.getAttribute("badge-count"), 10) || 0; + } + + set badgeCount(val) { + let count = parseInt(val, 10); + if (count) { + this.setAttribute("badge-count", count); + } else { + this.removeAttribute("badge-count"); + } + } + + get selected() { + return this.hasAttribute("selected"); + } + + set selected(val) { + this.toggleAttribute("selected", !!val); + this.setAttribute("aria-selected", !!val); + } + + get name() { + return this.getAttribute("name"); + } + + get viewId() { + return this.getAttribute("viewid"); + } + + // Just setting the hidden attribute isn't enough in case the category gets + // hidden while about:addons is closed since it could be the last active view + // which will unhide the button when it gets selected. + get defaultHidden() { + return this.hasAttribute("default-hidden"); + } +} +customElements.define("category-button", CategoryButton, { extends: "button" }); + +class DiscoverButton extends CategoryButton { + get isVisible() { + return isDiscoverEnabled(); + } +} +customElements.define("discover-button", DiscoverButton, { extends: "button" }); + +// Create the button-group element so it gets loaded. +document.createElement("button-group"); +class CategoriesBox extends customElements.get("button-group") { + constructor() { + super(); + // This will resolve when the initial category states have been set from + // our cached prefs. This is intended for use in testing to verify that we + // are caching the previous state. + this.promiseRendered = new Promise(resolve => { + this._resolveRendered = resolve; + }); + } + + handleEvent(e) { + if (e.target == document && e.type == "view-selected") { + const { type, param } = e.detail; + this.select(`addons://${type}/${param}`); + return; + } + + if (e.target == this && e.type == "button-group:key-selected") { + this.activeChild.load(); + return; + } + + if (e.type == "click") { + const button = e.target.closest("[viewid]"); + if (button) { + button.load(); + return; + } + } + + // Forward the unhandled events to the button-group custom element. + super.handleEvent(e); + } + + disconnectedCallback() { + document.removeEventListener("view-selected", this); + this.removeEventListener("button-group:key-selected", this); + this.removeEventListener("click", this); + AddonManagerListenerHandler.removeListener(this); + super.disconnectedCallback(); + } + + async initialize() { + let hiddenTypes = new Set([]); + + for (let button of this.children) { + let { defaultHidden, name } = button; + button.hidden = + !button.isVisible || (defaultHidden && this.shouldHideCategory(name)); + + if (defaultHidden && AddonManager.hasAddonType(name)) { + hiddenTypes.add(name); + } + } + + let hiddenUpdated; + if (hiddenTypes.size) { + hiddenUpdated = this.updateHiddenCategories(Array.from(hiddenTypes)); + } + + this.updateAvailableCount(); + + document.addEventListener("view-selected", this); + this.addEventListener("button-group:key-selected", this); + this.addEventListener("click", this); + AddonManagerListenerHandler.addListener(this); + + this._resolveRendered(); + await hiddenUpdated; + } + + shouldHideCategory(name) { + return Services.prefs.getBoolPref(`extensions.ui.${name}.hidden`, true); + } + + setShouldHideCategory(name, hide) { + Services.prefs.setBoolPref(`extensions.ui.${name}.hidden`, hide); + } + + getButtonByName(name) { + return this.querySelector(`[name="${name}"]`); + } + + get selectedChild() { + return this._selectedChild; + } + + set selectedChild(node) { + if (node && this.contains(node)) { + if (this._selectedChild) { + this._selectedChild.selected = false; + } + this._selectedChild = node; + this._selectedChild.selected = true; + } + } + + select(viewId) { + let button = this.querySelector(`[viewid="${viewId}"]`); + if (button) { + this.activeChild = button; + this.selectedChild = button; + button.hidden = false; + Services.prefs.setStringPref(PREF_UI_LASTCATEGORY, viewId); + } + } + + selectType(type) { + this.select(`addons://list/${type}`); + } + + onInstalled(addon) { + let button = this.getButtonByName(addon.type); + if (button) { + button.hidden = false; + this.setShouldHideCategory(addon.type, false); + } + this.updateAvailableCount(); + } + + onInstallStarted(install) { + this.onInstalled(install); + } + + onNewInstall() { + this.updateAvailableCount(); + } + + onInstallPostponed() { + this.updateAvailableCount(); + } + + onInstallCancelled() { + this.updateAvailableCount(); + } + + async updateAvailableCount() { + let installs = await AddonManager.getAllInstalls(); + var count = installs.filter(install => { + return isManualUpdate(install) && !install.installed; + }).length; + let availableButton = this.getButtonByName("available-updates"); + availableButton.hidden = !availableButton.selected && count == 0; + availableButton.badgeCount = count; + } + + async updateHiddenCategories(types) { + let hiddenTypes = new Set(types); + let getAddons = AddonManager.getAddonsByTypes(types); + let getInstalls = AddonManager.getInstallsByTypes(types); + + for (let addon of await getAddons) { + if (addon.hidden) { + continue; + } + + this.onInstalled(addon); + hiddenTypes.delete(addon.type); + + if (!hiddenTypes.size) { + return; + } + } + + for (let install of await getInstalls) { + if ( + install.existingAddon || + install.state == AddonManager.STATE_AVAILABLE + ) { + continue; + } + + this.onInstalled(install); + hiddenTypes.delete(install.type); + + if (!hiddenTypes.size) { + return; + } + } + + for (let type of hiddenTypes) { + let button = this.getButtonByName(type); + if (button.selected) { + // Cancel the load if this view should be hidden. + gViewController.resetState(); + } + this.setShouldHideCategory(type, true); + button.hidden = true; + } + } +} +customElements.define("categories-box", CategoriesBox); + +class SidebarFooter extends HTMLElement { + connectedCallback() { + let list = document.createElement("ul"); + list.classList.add("sidebar-footer-list"); + + let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); + let prefsItem = this.createItem({ + icon: "chrome://global/skin/icons/settings.svg", + createLinkElement: () => { + let link = document.createElement("a"); + link.href = "about:preferences"; + link.id = "preferencesButton"; + return link; + }, + titleL10nId: "sidebar-settings-button-title", + labelL10nId: "addons-settings-button", + onClick: e => { + e.preventDefault(); + AMTelemetry.recordLinkEvent({ + object: "aboutAddons", + value: "about:preferences", + extra: { + view: getTelemetryViewName(this), + }, + }); + windowRoot.ownerGlobal.switchToTabHavingURI("about:preferences", true, { + ignoreFragment: "whenComparing", + triggeringPrincipal: systemPrincipal, + }); + }, + }); + + let supportItem = this.createItem({ + icon: "chrome://global/skin/icons/help.svg", + createLinkElement: () => { + let link = document.createElement("a", { is: "support-link" }); + link.setAttribute("support-page", "addons-help"); + link.id = "help-button"; + return link; + }, + titleL10nId: "sidebar-help-button-title", + labelL10nId: "help-button", + onClick: e => { + AMTelemetry.recordLinkEvent({ + object: "aboutAddons", + value: "support", + extra: { + view: getTelemetryViewName(this), + }, + }); + }, + }); + + list.append(prefsItem, supportItem); + this.append(list); + } + + createItem({ onClick, titleL10nId, labelL10nId, icon, createLinkElement }) { + let listItem = document.createElement("li"); + + let link = createLinkElement(); + link.classList.add("sidebar-footer-link"); + link.addEventListener("click", onClick); + document.l10n.setAttributes(link, titleL10nId); + + let img = document.createElement("img"); + img.src = icon; + img.className = "sidebar-footer-icon"; + + let label = document.createElement("span"); + label.className = "sidebar-footer-label"; + document.l10n.setAttributes(label, labelL10nId); + + link.append(img, label); + listItem.append(link); + return listItem; + } +} +customElements.define("sidebar-footer", SidebarFooter, { extends: "footer" }); + +class AddonOptions extends HTMLElement { + connectedCallback() { + if (!this.children.length) { + this.render(); + } + } + + get panel() { + return this.querySelector("panel-list"); + } + + updateSeparatorsVisibility() { + let lastSeparator; + let elWasVisible = false; + + // Collect the panel-list children that are not already hidden. + const children = Array.from(this.panel.children).filter(el => !el.hidden); + + for (let child of children) { + if (child.localName == "hr") { + child.hidden = !elWasVisible; + if (!child.hidden) { + lastSeparator = child; + } + elWasVisible = false; + } else { + elWasVisible = true; + } + } + if (!elWasVisible && lastSeparator) { + lastSeparator.hidden = true; + } + } + + get template() { + return "addon-options"; + } + + render() { + this.appendChild(importTemplate(this.template)); + } + + setElementState(el, card, addon, updateInstall) { + switch (el.getAttribute("action")) { + case "remove": + if (hasPermission(addon, "uninstall")) { + // Regular add-on that can be uninstalled. + el.disabled = false; + el.hidden = false; + document.l10n.setAttributes(el, "remove-addon-button"); + } else if (addon.isBuiltin) { + // Likely the built-in themes, can't be removed, that's fine. + el.hidden = true; + } else { + // Likely sideloaded, mention that it can't be removed with a link. + el.hidden = false; + el.disabled = true; + if (!el.querySelector('[slot="support-link"]')) { + let link = document.createElement("a", { is: "support-link" }); + link.setAttribute("data-l10n-name", "link"); + link.setAttribute("support-page", "cant-remove-addon"); + link.setAttribute("slot", "support-link"); + el.appendChild(link); + document.l10n.setAttributes(el, "remove-addon-disabled-button"); + } + } + break; + case "report": + el.hidden = !isAbuseReportSupported(addon); + break; + case "install-update": + el.hidden = !updateInstall; + break; + case "expand": + el.hidden = card.expanded; + break; + case "preferences": + el.hidden = + getOptionsType(addon) !== "tab" && + (getOptionsType(addon) !== "inline" || card.expanded); + if (!el.hidden) { + isAddonOptionsUIAllowed(addon).then(allowed => { + el.hidden = !allowed; + }); + } + break; + } + } + + update(card, addon, updateInstall) { + for (let el of this.items) { + this.setElementState(el, card, addon, updateInstall); + } + + // Update the separators visibility based on the updated visibility + // of the actions in the panel-list. + this.updateSeparatorsVisibility(); + } + + get items() { + return this.querySelectorAll("panel-item"); + } + + get visibleItems() { + return Array.from(this.items).filter(item => !item.hidden); + } +} +customElements.define("addon-options", AddonOptions); + +class PluginOptions extends AddonOptions { + get template() { + return "plugin-options"; + } + + setElementState(el, card, addon) { + const userDisabledStates = { + "always-activate": false, + "never-activate": true, + }; + const action = el.getAttribute("action"); + if (action in userDisabledStates) { + let userDisabled = userDisabledStates[action]; + el.checked = addon.userDisabled === userDisabled; + el.disabled = !(el.checked || hasPermission(addon, action)); + } else { + super.setElementState(el, card, addon); + } + } +} +customElements.define("plugin-options", PluginOptions); + +class FiveStarRating extends HTMLElement { + static get observedAttributes() { + return ["rating"]; + } + + constructor() { + super(); + this.attachShadow({ mode: "open" }); + this.shadowRoot.append(importTemplate("five-star-rating")); + } + + set rating(v) { + this.setAttribute("rating", v); + } + + get rating() { + let v = parseFloat(this.getAttribute("rating"), 10); + if (v >= 0 && v <= 5) { + return v; + } + return 0; + } + + get ratingBuckets() { + // 0 <= x < 0.25 = empty + // 0.25 <= x < 0.75 = half + // 0.75 <= x <= 1 = full + // ... et cetera, until x <= 5. + let { rating } = this; + return [0, 1, 2, 3, 4].map(ratingStart => { + let distanceToFull = rating - ratingStart; + if (distanceToFull < 0.25) { + return "empty"; + } + if (distanceToFull < 0.75) { + return "half"; + } + return "full"; + }); + } + + connectedCallback() { + this.renderRating(); + } + + attributeChangedCallback() { + this.renderRating(); + } + + renderRating() { + let starElements = this.shadowRoot.querySelectorAll(".rating-star"); + for (let [i, part] of this.ratingBuckets.entries()) { + starElements[i].setAttribute("fill", part); + } + document.l10n.setAttributes(this, "five-star-rating", { + rating: this.rating, + }); + } +} +customElements.define("five-star-rating", FiveStarRating); + +class ProxyContextMenu extends HTMLElement { + openPopupAtScreen(...args) { + // prettier-ignore + const parentContextMenuPopup = + windowRoot.ownerGlobal.document.getElementById("contentAreaContextMenu"); + return parentContextMenuPopup.openPopupAtScreen(...args); + } +} +customElements.define("proxy-context-menu", ProxyContextMenu); + +class InlineOptionsBrowser extends HTMLElement { + constructor() { + super(); + // Force the options_ui remote browser to recompute window.mozInnerScreenX + // and window.mozInnerScreenY when the "addon details" page has been + // scrolled (See Bug 1390445 for rationale). + // Also force a repaint to fix an issue where the click location was + // getting out of sync (see bug 1548687). + this.updatePositionTask = new DeferredTask(() => { + if (this.browser && this.browser.isRemoteBrowser) { + // Select boxes can appear in the wrong spot after scrolling, this will + // clear that up. Bug 1390445. + this.browser.frameLoader.requestUpdatePosition(); + } + }, 100); + + this._embedderElement = null; + this._promiseDisconnected = new Promise( + resolve => (this._resolveDisconnected = resolve) + ); + } + + connectedCallback() { + window.addEventListener("scroll", this, true); + const { embedderElement } = top.browsingContext; + this._embedderElement = embedderElement; + embedderElement.addEventListener("FullZoomChange", this); + embedderElement.addEventListener("TextZoomChange", this); + } + + disconnectedCallback() { + this._resolveDisconnected(); + window.removeEventListener("scroll", this, true); + this._embedderElement?.removeEventListener("FullZoomChange", this); + this._embedderElement?.removeEventListener("TextZoomChange", this); + this._embedderElement = null; + } + + handleEvent(e) { + switch (e.type) { + case "scroll": + return this.updatePositionTask.arm(); + case "FullZoomChange": + case "TextZoomChange": + return this.maybeUpdateZoom(); + } + return undefined; + } + + maybeUpdateZoom() { + let bc = this.browser?.browsingContext; + let topBc = top.browsingContext; + if (!bc || !topBc) { + return; + } + // Use the same full-zoom as our top window. + bc.fullZoom = topBc.fullZoom; + bc.textZoom = topBc.textZoom; + } + + setAddon(addon) { + this.addon = addon; + } + + destroyBrowser() { + this.textContent = ""; + } + + ensureBrowserCreated() { + if (this.childElementCount === 0) { + this.render(); + } + } + + async render() { + let { addon } = this; + if (!addon) { + throw new Error("addon required to create inline options"); + } + + let browser = document.createXULElement("browser"); + browser.setAttribute("type", "content"); + browser.setAttribute("disableglobalhistory", "true"); + browser.setAttribute("messagemanagergroup", "webext-browsers"); + browser.setAttribute("id", "addon-inline-options"); + browser.setAttribute("transparent", "true"); + browser.setAttribute("forcemessagemanager", "true"); + browser.setAttribute("autocompletepopup", "PopupAutoComplete"); + + // The outer about:addons document listens for key presses to focus + // the search box when / is pressed. But if we're focused inside an + // options page, don't let those keypresses steal focus. + browser.addEventListener("keypress", event => { + event.stopPropagation(); + }); + + let { optionsURL, optionsBrowserStyle } = addon; + if (addon.isWebExtension) { + let policy = ExtensionParent.WebExtensionPolicy.getByID(addon.id); + browser.setAttribute( + "initialBrowsingContextGroupId", + policy.browsingContextGroupId + ); + } + + let readyPromise; + let remoteSubframes = window.docShell.QueryInterface(Ci.nsILoadContext) + .useRemoteSubframes; + // For now originAttributes have no effect, which will change if the + // optionsURL becomes anything but moz-extension* or we start considering + // OA for extensions. + var oa = E10SUtils.predictOriginAttributes({ browser }); + let loadRemote = E10SUtils.canLoadURIInRemoteType( + optionsURL, + remoteSubframes, + E10SUtils.EXTENSION_REMOTE_TYPE, + oa + ); + if (loadRemote) { + browser.setAttribute("remote", "true"); + browser.setAttribute("remoteType", E10SUtils.EXTENSION_REMOTE_TYPE); + + readyPromise = promiseEvent("XULFrameLoaderCreated", browser); + } else { + readyPromise = promiseEvent("load", browser, true); + } + + let stack = document.createXULElement("stack"); + stack.classList.add("inline-options-stack"); + stack.appendChild(browser); + this.appendChild(stack); + this.browser = browser; + + // Force bindings to apply synchronously. + browser.clientTop; + + await readyPromise; + + this.maybeUpdateZoom(); + + if (!browser.messageManager) { + // If the browser.messageManager is undefined, the browser element has + // been removed from the document in the meantime (e.g. due to a rapid + // sequence of addon reload), return null. + return; + } + + ExtensionParent.apiManager.emit("extension-browser-inserted", browser); + + await new Promise(resolve => { + let messageListener = { + receiveMessage({ name, data }) { + if (name === "Extension:BrowserResized") { + browser.style.height = `${data.height}px`; + } else if (name === "Extension:BrowserContentLoaded") { + resolve(); + } + }, + }; + + let mm = browser.messageManager; + + if (!mm) { + // If the browser.messageManager is undefined, the browser element has + // been removed from the document in the meantime (e.g. due to a rapid + // sequence of addon reload), return null. + resolve(); + return; + } + + mm.loadFrameScript( + "chrome://extensions/content/ext-browser-content.js", + false, + true + ); + mm.addMessageListener("Extension:BrowserContentLoaded", messageListener); + mm.addMessageListener("Extension:BrowserResized", messageListener); + + let browserOptions = { + fixedWidth: true, + isInline: true, + }; + + if (optionsBrowserStyle) { + browserOptions.stylesheets = extensionStylesheets; + } + + mm.sendAsyncMessage("Extension:InitBrowser", browserOptions); + + if (browser.isConnectedAndReady) { + this.loadURI(optionsURL); + } else { + // browser custom element does opt-in the delayConnectedCallback + // behavior (see connectedCallback in the custom element definition + // from browser-custom-element.js) and so calling browser.loadURI + // would fail if the about:addons document is not yet fully loaded. + Promise.race([ + promiseEvent("DOMContentLoaded", document), + this._promiseDisconnected, + ]).then(() => { + this.loadURI(optionsURL); + }); + } + }); + } + + loadURI(uri) { + if (!this.browser || !this.browser.isConnectedAndReady) { + throw new Error("Fail to loadURI"); + } + + this.browser.loadURI(uri, { + triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(), + }); + } +} +customElements.define("inline-options-browser", InlineOptionsBrowser); + +class UpdateReleaseNotes extends HTMLElement { + connectedCallback() { + this.addEventListener("click", this); + } + + disconnectedCallback() { + this.removeEventListener("click", this); + } + + handleEvent(e) { + // We used to strip links, but ParserUtils.parseFragment() leaves them in, + // so just make sure we open them using the null principal in a new tab. + if (e.type == "click" && e.target.localName == "a" && e.target.href) { + e.preventDefault(); + e.stopPropagation(); + windowRoot.ownerGlobal.openWebLinkIn(e.target.href, "tab"); + } + } + + async loadForUri(uri) { + // Can't load the release notes without a URL to load. + if (!uri || !uri.spec) { + this.setErrorMessage(); + this.dispatchEvent(new CustomEvent("release-notes-error")); + return; + } + + // Don't try to load for the same update a second time. + if (this.url == uri.spec) { + this.dispatchEvent(new CustomEvent("release-notes-cached")); + return; + } + + // Store the URL to skip the network if loaded again. + this.url = uri.spec; + + // Set the loading message before hitting the network. + this.setLoadingMessage(); + this.dispatchEvent(new CustomEvent("release-notes-loading")); + + try { + // loadReleaseNotes will fetch and sanitize the release notes. + let fragment = await loadReleaseNotes(uri); + this.textContent = ""; + this.appendChild(fragment); + this.dispatchEvent(new CustomEvent("release-notes-loaded")); + } catch (e) { + this.setErrorMessage(); + this.dispatchEvent(new CustomEvent("release-notes-error")); + } + } + + setMessage(id) { + this.textContent = ""; + let message = document.createElement("p"); + document.l10n.setAttributes(message, id); + this.appendChild(message); + } + + setLoadingMessage() { + this.setMessage("release-notes-loading"); + } + + setErrorMessage() { + this.setMessage("release-notes-error"); + } +} +customElements.define("update-release-notes", UpdateReleaseNotes); + +class AddonPermissionsList extends HTMLElement { + setAddon(addon) { + this.addon = addon; + this.render(); + } + + async render() { + let appName = brandBundle.GetStringFromName("brandShortName"); + + let empty = { origins: [], permissions: [] }; + let requiredPerms = { ...(this.addon.userPermissions ?? empty) }; + let optionalPerms = { ...(this.addon.optionalPermissions ?? empty) }; + let grantedPerms = await ExtensionPermissions.get(this.addon.id); + + if (manifestV3enabled) { + // If optional permissions include , extension can request and + // be granted permission for individual sites not listed in the manifest. + // Include them as well in the optional origins list. + optionalPerms.origins = [ + ...optionalPerms.origins, + ...grantedPerms.origins.filter(o => !requiredPerms.origins.includes(o)), + ]; + } + + let permissions = Extension.formatPermissionStrings( + { + permissions: requiredPerms, + optionalPermissions: optionalPerms, + appName, + }, + browserBundle, + { buildOptionalOrigins: manifestV3enabled } + ); + let optionalEntries = [ + ...Object.entries(permissions.optionalPermissions), + ...Object.entries(permissions.optionalOrigins), + ]; + + this.textContent = ""; + let frag = importTemplate("addon-permissions-list"); + + if (permissions.msgs.length) { + let section = frag.querySelector(".addon-permissions-required"); + section.hidden = false; + let list = section.querySelector(".addon-permissions-list"); + + for (let msg of permissions.msgs) { + let item = document.createElement("li"); + item.classList.add("permission-info", "permission-checked"); + item.appendChild(document.createTextNode(msg)); + list.appendChild(item); + } + } + + if (optionalEntries.length) { + let section = frag.querySelector(".addon-permissions-optional"); + section.hidden = false; + let list = section.querySelector(".addon-permissions-list"); + + for (let id = 0; id < optionalEntries.length; id++) { + let [perm, msg] = optionalEntries[id]; + + let type = "permission"; + if (permissions.optionalOrigins[perm]) { + type = "origin"; + } + let item = document.createElement("li"); + item.classList.add("permission-info"); + + let label = document.createElement("label"); + label.textContent = msg; + + let toggle = document.createElement("input"); + toggle.id = `permission-${id}`; + + label.setAttribute("for", toggle.id); + item.appendChild(label); + + toggle.setAttribute("permission-type", type); + toggle.setAttribute("type", "checkbox"); + + let checked = + grantedPerms.permissions.includes(perm) || + grantedPerms.origins.includes(perm); + + // If this is one of the "all sites" permissions + if (Extension.isAllSitesPermission(perm)) { + // mark it as checked if ANY of the "all sites" permission is granted. + checked = await AddonCard.optionalAllSitesGranted(this.addon.id); + toggle.toggleAttribute("permission-all-sites", true); + } + + toggle.checked = checked; + item.classList.toggle("permission-checked", checked); + + toggle.setAttribute("permission-key", perm); + toggle.setAttribute("action", "toggle-permission"); + toggle.classList.add("toggle-button"); + label.appendChild(toggle); + list.appendChild(item); + } + } + if (!permissions.msgs.length && !optionalEntries.length) { + let row = frag.querySelector(".addon-permissions-empty"); + row.hidden = false; + } + + this.appendChild(frag); + } +} +customElements.define("addon-permissions-list", AddonPermissionsList); + +class AddonSitePermissionsList extends HTMLElement { + setAddon(addon) { + this.addon = addon; + this.render(); + } + + async render() { + let appName = brandBundle.GetStringFromName("brandShortName"); + let permissions = Extension.formatPermissionStrings( + { + sitePermissions: this.addon.sitePermissions, + siteOrigin: this.addon.siteOrigin, + appName, + }, + browserBundle + ); + + this.textContent = ""; + let frag = importTemplate("addon-sitepermissions-list"); + + if (permissions.msgs.length) { + let section = frag.querySelector(".addon-permissions-required"); + section.hidden = false; + let list = section.querySelector(".addon-permissions-list"); + let header = section.querySelector(".permission-header"); + document.l10n.setAttributes(header, "addon-sitepermissions-required", { + hostname: new URL(this.addon.siteOrigin).hostname, + }); + + for (let msg of permissions.msgs) { + let item = document.createElement("li"); + item.classList.add("permission-info", "permission-checked"); + item.appendChild(document.createTextNode(msg)); + list.appendChild(item); + } + } + + this.appendChild(frag); + } +} +customElements.define("addon-sitepermissions-list", AddonSitePermissionsList); + +class AddonDetails extends HTMLElement { + connectedCallback() { + if (!this.children.length) { + this.render(); + } + this.deck.addEventListener("view-changed", this); + this.descriptionShowMoreButton.addEventListener("click", this); + } + + disconnectedCallback() { + this.inlineOptions.destroyBrowser(); + this.deck.removeEventListener("view-changed", this); + this.descriptionShowMoreButton.removeEventListener("click", this); + } + + handleEvent(e) { + if (e.type == "view-changed" && e.target == this.deck) { + switch (this.deck.selectedViewName) { + case "release-notes": + AMTelemetry.recordActionEvent({ + object: "aboutAddons", + view: getTelemetryViewName(this), + action: "releaseNotes", + addon: this.addon, + }); + let releaseNotes = this.querySelector("update-release-notes"); + let uri = this.releaseNotesUri; + if (uri) { + releaseNotes.loadForUri(uri); + } + break; + case "preferences": + if (getOptionsType(this.addon) == "inline") { + this.inlineOptions.ensureBrowserCreated(); + } + break; + } + + // When a details view is rendered again, the default details view is + // unconditionally shown. So if any other tab is selected, do not save + // the current scroll offset, but start at the top of the page instead. + ScrollOffsets.canRestore = this.deck.selectedViewName === "details"; + } else if ( + e.type == "click" && + e.target == this.descriptionShowMoreButton + ) { + this.toggleDescription(); + } + } + + onInstalled() { + let policy = WebExtensionPolicy.getByID(this.addon.id); + let extension = policy && policy.extension; + if (extension && extension.startupReason === "ADDON_UPGRADE") { + // Ensure the options browser is recreated when a new version starts. + this.extensionShutdown(); + this.extensionStartup(); + } + } + + onDisabled(addon) { + this.extensionShutdown(); + } + + onEnabled(addon) { + this.extensionStartup(); + } + + extensionShutdown() { + this.inlineOptions.destroyBrowser(); + } + + extensionStartup() { + if (this.deck.selectedViewName === "preferences") { + this.inlineOptions.ensureBrowserCreated(); + } + } + + toggleDescription() { + this.descriptionCollapsed = !this.descriptionCollapsed; + + this.descriptionWrapper.classList.toggle( + "addon-detail-description-collapse", + this.descriptionCollapsed + ); + + this.descriptionShowMoreButton.hidden = false; + document.l10n.setAttributes( + this.descriptionShowMoreButton, + this.descriptionCollapsed + ? "addon-detail-description-expand" + : "addon-detail-description-collapse" + ); + } + + get releaseNotesUri() { + let { releaseNotesURI } = getUpdateInstall(this.addon) || this.addon; + return releaseNotesURI; + } + + setAddon(addon) { + this.addon = addon; + } + + update() { + let { addon } = this; + + // Hide tab buttons that won't have any content. + let getButtonByName = name => + this.tabGroup.querySelector(`[name="${name}"]`); + let permsBtn = getButtonByName("permissions"); + permsBtn.hidden = addon.type != "extension"; + let notesBtn = getButtonByName("release-notes"); + notesBtn.hidden = !this.releaseNotesUri; + let prefsBtn = getButtonByName("preferences"); + prefsBtn.hidden = getOptionsType(addon) !== "inline"; + if (prefsBtn.hidden) { + if (this.deck.selectedViewName === "preferences") { + this.deck.selectedViewName = "details"; + } + } else { + isAddonOptionsUIAllowed(addon).then(allowed => { + prefsBtn.hidden = !allowed; + }); + } + + // Hide the tab group if "details" is the only visible button. + let tabGroupButtons = this.tabGroup.querySelectorAll(".tab-button"); + this.tabGroup.hidden = Array.from(tabGroupButtons).every(button => { + return button.name == "details" || button.hidden; + }); + + // Show the update check button if necessary. The button might not exist if + // the add-on doesn't support updates. + let updateButton = this.querySelector('[action="update-check"]'); + if (updateButton) { + updateButton.hidden = + this.addon.updateInstall || AddonManager.shouldAutoUpdate(this.addon); + } + + // Set the value for auto updates. + let inputs = this.querySelectorAll(".addon-detail-row-updates input"); + for (let input of inputs) { + input.checked = input.value == addon.applyBackgroundUpdates; + } + } + + renderDescription(addon) { + this.descriptionWrapper = this.querySelector( + ".addon-detail-description-wrapper" + ); + this.descriptionContents = this.querySelector(".addon-detail-description"); + this.descriptionShowMoreButton = this.querySelector( + ".addon-detail-description-toggle" + ); + + if (addon.getFullDescription) { + this.descriptionContents.appendChild(addon.getFullDescription(document)); + } else if (addon.fullDescription) { + this.descriptionContents.appendChild(nl2br(addon.fullDescription)); + } + + this.descriptionCollapsed = false; + + requestAnimationFrame(() => { + const remSize = parseFloat( + getComputedStyle(document.documentElement).fontSize + ); + const { height } = this.descriptionContents.getBoundingClientRect(); + + // collapse description if there are too many lines,i.e. height > (20 rem) + if (height > 20 * remSize) { + this.toggleDescription(); + } + }); + } + + async render() { + let { addon } = this; + if (!addon) { + throw new Error("addon-details must be initialized by setAddon"); + } + + this.textContent = ""; + this.appendChild(importTemplate("addon-details")); + + this.deck = this.querySelector("named-deck"); + this.tabGroup = this.querySelector(".tab-group"); + + // Set the add-on for the permissions section. + this.permissionsList = this.querySelector("addon-permissions-list"); + this.permissionsList.setAddon(addon); + + // Set the add-on for the sitepermissions section. + this.sitePermissionsList = this.querySelector("addon-sitepermissions-list"); + if (addon.type == "sitepermission") { + this.sitePermissionsList.setAddon(addon); + } + this.querySelector(".addon-detail-sitepermissions").hidden = + addon.type !== "sitepermission"; + + // Set the add-on for the preferences section. + this.inlineOptions = this.querySelector("inline-options-browser"); + this.inlineOptions.setAddon(addon); + + // Full description. + this.renderDescription(addon); + this.querySelector( + ".addon-detail-contribute" + ).hidden = !addon.contributionURL; + this.querySelector(".addon-detail-row-updates").hidden = !hasPermission( + addon, + "upgrade" + ); + + if (addon.type != "extension") { + // Don't show any private browsing related section for non-extension + // addon types, because not relevant or they are either always allowed + // (e.g. static themes). + // + // TODO(Bug 1799090): introduce ad-hoc UI for "sitepermission" addon type. + } else if (addon.incognito == "not_allowed") { + let pbRowNotAllowed = this.querySelector( + ".addon-detail-row-private-browsing-disallowed" + ); + pbRowNotAllowed.hidden = false; + pbRowNotAllowed.nextElementSibling.hidden = false; + } else if (!hasPermission(addon, "change-privatebrowsing")) { + let pbRowRequired = this.querySelector( + ".addon-detail-row-private-browsing-required" + ); + pbRowRequired.hidden = false; + pbRowRequired.nextElementSibling.hidden = false; + } else { + let pbRow = this.querySelector(".addon-detail-row-private-browsing"); + pbRow.hidden = false; + pbRow.nextElementSibling.hidden = false; + let isAllowed = await isAllowedInPrivateBrowsing(addon); + pbRow.querySelector(`[value="${isAllowed ? 1 : 0}"]`).checked = true; + } + + // Author. + let creatorRow = this.querySelector(".addon-detail-row-author"); + if (addon.creator) { + let link = creatorRow.querySelector("a"); + link.hidden = !addon.creator.url; + if (link.hidden) { + creatorRow.appendChild(new Text(addon.creator.name)); + } else { + link.href = formatUTMParams( + "addons-manager-user-profile-link", + addon.creator.url + ); + link.target = "_blank"; + link.textContent = addon.creator.name; + } + } else { + creatorRow.hidden = true; + } + + // Version. Don't show a version for LWTs. + let version = this.querySelector(".addon-detail-row-version"); + if (addon.version && !/@personas\.mozilla\.org/.test(addon.id)) { + version.appendChild(new Text(addon.version)); + } else { + version.hidden = true; + } + + // Last updated. + let updateDate = this.querySelector(".addon-detail-row-lastUpdated"); + if (addon.updateDate) { + let lastUpdated = addon.updateDate.toLocaleDateString(undefined, { + year: "numeric", + month: "long", + day: "numeric", + }); + updateDate.appendChild(new Text(lastUpdated)); + } else { + updateDate.hidden = true; + } + + // Homepage. + let homepageRow = this.querySelector(".addon-detail-row-homepage"); + if (addon.homepageURL) { + let homepageURL = homepageRow.querySelector("a"); + homepageURL.href = addon.homepageURL; + homepageURL.textContent = addon.homepageURL; + } else { + homepageRow.hidden = true; + } + + // Rating. + let ratingRow = this.querySelector(".addon-detail-row-rating"); + if (addon.averageRating) { + ratingRow.querySelector("five-star-rating").rating = addon.averageRating; + let reviews = ratingRow.querySelector("a"); + reviews.href = formatUTMParams( + "addons-manager-reviews-link", + addon.reviewURL + ); + document.l10n.setAttributes(reviews, "addon-detail-reviews-link", { + numberOfReviews: addon.reviewCount, + }); + } else { + ratingRow.hidden = true; + } + + this.update(); + } + + showPrefs() { + if (getOptionsType(this.addon) == "inline") { + this.deck.selectedViewName = "preferences"; + this.inlineOptions.ensureBrowserCreated(); + } + } +} +customElements.define("addon-details", AddonDetails); + +/** + * A card component for managing an add-on. It should be initialized by setting + * the add-on with `setAddon()` before being connected to the document. + * + * let card = document.createElement("addon-card"); + * card.setAddon(addon); + * document.body.appendChild(card); + */ +class AddonCard extends HTMLElement { + connectedCallback() { + // If we've already rendered we can just update, otherwise render. + if (this.children.length) { + this.update(); + } else { + this.render(); + } + this.registerListeners(); + } + + disconnectedCallback() { + this.removeListeners(); + } + + get expanded() { + return this.hasAttribute("expanded"); + } + + set expanded(val) { + if (val) { + this.setAttribute("expanded", "true"); + } else { + this.removeAttribute("expanded"); + } + } + + get updateInstall() { + return this._updateInstall; + } + + set updateInstall(install) { + this._updateInstall = install; + if (this.children.length) { + this.update(); + } + } + + get reloading() { + return this.hasAttribute("reloading"); + } + + set reloading(val) { + this.toggleAttribute("reloading", val); + } + + /** + * Set the add-on for this card. The card will be populated based on the + * add-on when it is connected to the DOM. + * + * @param {AddonWrapper} addon The add-on to use. + */ + setAddon(addon) { + this.addon = addon; + let install = getUpdateInstall(addon); + if ( + install && + (isInState(install, "available") || isInState(install, "postponed")) + ) { + this.updateInstall = install; + } else { + this.updateInstall = null; + } + if (this.children.length) { + this.render(); + } + } + + async setAddonPermission(permission, type, action) { + let { addon } = this; + let origins = [], + permissions = []; + if (!["add", "remove"].includes(action)) { + throw new Error("invalid action for permission change"); + } + if (type == "permission") { + if ( + action == "add" && + !addon.optionalPermissions.permissions.includes(permission) + ) { + throw new Error("permission missing from manifest"); + } + permissions = [permission]; + } else if (type == "origin") { + if (action === "add") { + let { origins } = addon.optionalPermissions; + let patternSet = new MatchPatternSet(origins, { ignorePath: true }); + if (!patternSet.subsumes(new MatchPattern(permission))) { + throw new Error("origin missing from manifest"); + } + } + origins = [permission]; + + // If this is one of the "all sites" permissions + if (Extension.isAllSitesPermission(permission)) { + // Grant/revoke ALL "all sites" optional permissions from the manifest. + origins = addon.optionalPermissions.origins.filter(perm => + Extension.isAllSitesPermission(perm) + ); + } + } else { + throw new Error("unknown permission type changed"); + } + let policy = WebExtensionPolicy.getByID(addon.id); + ExtensionPermissions[action]( + addon.id, + { origins, permissions }, + policy?.extension + ); + } + + async handleEvent(e) { + let { addon } = this; + let action = e.target.getAttribute("action"); + + if (e.type == "click") { + switch (action) { + case "toggle-permission": + let permission = e.target.getAttribute("permission-key"); + let type = e.target.getAttribute("permission-type"); + let fname = e.target.checked ? "add" : "remove"; + this.setAddonPermission(permission, type, fname); + break; + case "toggle-disabled": + this.recordActionEvent(addon.userDisabled ? "enable" : "disable"); + // Keep the checked state the same until the add-on's state changes. + e.target.checked = !addon.userDisabled; + if (addon.userDisabled) { + if (shouldShowPermissionsPrompt(addon)) { + await showPermissionsPrompt(addon); + } else { + await addon.enable(); + } + } else { + await addon.disable(); + } + break; + case "always-activate": + this.recordActionEvent("enable"); + addon.userDisabled = false; + break; + case "never-activate": + this.recordActionEvent("disable"); + addon.userDisabled = true; + break; + case "update-check": { + this.recordActionEvent("checkForUpdate"); + let { found } = await checkForUpdate(addon); + if (!found) { + this.sendEvent("no-update"); + } + break; + } + case "install-postponed": { + const { updateInstall } = this; + if (updateInstall && isInState(updateInstall, "postponed")) { + updateInstall.continuePostponedInstall(); + } + break; + } + case "install-update": + // Make sure that an update handler is attached to the install object + // before starting the update installation (otherwise the user would + // not be prompted for the new permissions requested if necessary), + // and also make sure that a prompt handler attached from a closed + // about:addons tab is replaced by the one attached by the currently + // active about:addons tab. + attachUpdateHandler(this.updateInstall); + this.updateInstall.install().then( + () => { + detachUpdateHandler(this.updateInstall); + // The card will update with the new add-on when it gets + // installed. + this.sendEvent("update-installed"); + }, + () => { + detachUpdateHandler(this.updateInstall); + // Update our state if the install is cancelled. + this.update(); + this.sendEvent("update-cancelled"); + } + ); + // Clear the install since it will be removed from the global list of + // available updates (whether it succeeds or fails). + this.updateInstall = null; + break; + case "contribute": + this.recordActionEvent("contribute"); + // prettier-ignore + windowRoot.ownerGlobal.openUILinkIn(addon.contributionURL, "tab", { + triggeringPrincipal: + Services.scriptSecurityManager.createNullPrincipal( + {} + ), + }); + break; + case "preferences": + if (getOptionsType(addon) == "tab") { + this.recordActionEvent("preferences", "external"); + openOptionsInTab(addon.optionsURL); + } else if (getOptionsType(addon) == "inline") { + this.recordActionEvent("preferences", "inline"); + gViewController.loadView(`detail/${this.addon.id}/preferences`); + } + break; + case "remove": + { + this.panel.hide(); + if (!hasPermission(addon, "uninstall")) { + this.sendEvent("remove-disabled"); + return; + } + let { BrowserAddonUI } = windowRoot.ownerGlobal; + let { remove, report } = await BrowserAddonUI.promptRemoveExtension( + addon + ); + let value = remove ? "accepted" : "cancelled"; + this.recordActionEvent("uninstall", value); + if (remove) { + await addon.uninstall(true); + this.sendEvent("remove"); + if (report) { + openAbuseReport({ + addonId: addon.id, + reportEntryPoint: "uninstall", + }); + } + } else { + this.sendEvent("remove-cancelled"); + } + } + break; + case "expand": + gViewController.loadView(`detail/${this.addon.id}`); + break; + case "more-options": + // Open panel on click from the keyboard. + if (e.mozInputSource == MouseEvent.MOZ_SOURCE_KEYBOARD) { + this.panel.toggle(e); + } + break; + case "report": + this.panel.hide(); + openAbuseReport({ addonId: addon.id, reportEntryPoint: "menu" }); + break; + case "link": + if (e.target.getAttribute("url")) { + windowRoot.ownerGlobal.openWebLinkIn( + e.target.getAttribute("url"), + "tab" + ); + } + break; + default: + // Handle a click on the card itself. + if ( + !this.expanded && + (e.target === this.addonNameEl || !e.target.closest("a")) + ) { + e.preventDefault(); + gViewController.loadView(`detail/${this.addon.id}`); + } else if ( + e.target.localName == "a" && + e.target.getAttribute("data-telemetry-name") + ) { + let value = e.target.getAttribute("data-telemetry-name"); + AMTelemetry.recordLinkEvent({ + object: "aboutAddons", + addon, + value, + extra: { + view: getTelemetryViewName(this), + }, + }); + } + break; + } + } else if (e.type == "change") { + let { name } = e.target; + let telemetryValue = e.target.getAttribute("data-telemetry-value"); + if (name == "autoupdate") { + this.recordActionEvent("setAddonUpdate", telemetryValue); + addon.applyBackgroundUpdates = e.target.value; + } else if (name == "private-browsing") { + this.recordActionEvent("privateBrowsingAllowed", telemetryValue); + let policy = WebExtensionPolicy.getByID(addon.id); + let extension = policy && policy.extension; + + if (e.target.value == "1") { + await ExtensionPermissions.add( + addon.id, + PRIVATE_BROWSING_PERMS, + extension + ); + } else { + await ExtensionPermissions.remove( + addon.id, + PRIVATE_BROWSING_PERMS, + extension + ); + } + // Reload the extension if it is already enabled. This ensures any + // change on the private browsing permission is properly handled. + if (addon.isActive) { + this.reloading = true; + // Reloading will trigger an enable and update the card. + addon.reload(); + } else { + // Update the card if the add-on isn't active. + this.update(); + } + } + } else if (e.type == "mousedown") { + // Open panel on mousedown when the mouse is used. + if (action == "more-options" && e.button == 0) { + this.panel.toggle(e); + } + } else if (e.type === "shown" || e.type === "hidden") { + let panelOpen = e.type === "shown"; + // The card will be dimmed if it's disabled, but when the panel is open + // that should be reverted so the menu items can be easily read. + this.toggleAttribute("panelopen", panelOpen); + this.optionsButton.setAttribute("aria-expanded", panelOpen); + } + } + + get panel() { + return this.card.querySelector("panel-list"); + } + + get postponedMessageBar() { + return this.card.querySelector(".update-postponed-bar"); + } + + registerListeners() { + this.addEventListener("change", this); + this.addEventListener("click", this); + this.addEventListener("mousedown", this); + this.panel.addEventListener("shown", this); + this.panel.addEventListener("hidden", this); + } + + removeListeners() { + this.removeEventListener("change", this); + this.removeEventListener("click", this); + this.removeEventListener("mousedown", this); + this.panel.removeEventListener("shown", this); + this.panel.removeEventListener("hidden", this); + } + + /** + * Update the card's contents based on the previously set add-on. This should + * be called if there has been a change to the add-on. + */ + update() { + let { addon, card } = this; + + card.setAttribute("active", addon.isActive); + + // Set the icon or theme preview. + let iconEl = card.querySelector(".addon-icon"); + let preview = card.querySelector(".card-heading-image"); + if (addon.type == "theme") { + iconEl.hidden = true; + let screenshotUrl = getScreenshotUrlForAddon(addon); + if (screenshotUrl) { + preview.src = screenshotUrl; + } + preview.hidden = !screenshotUrl; + } else { + preview.hidden = true; + iconEl.hidden = false; + if (addon.type == "plugin") { + iconEl.src = PLUGIN_ICON_URL; + } else { + iconEl.src = + AddonManager.getPreferredIconURL(addon, 32, window) || + EXTENSION_ICON_URL; + } + } + + // Update the name. + let name = this.addonNameEl; + let setDisabledStyle = !(addon.isActive || addon.type === "theme"); + if (!setDisabledStyle) { + name.textContent = addon.name; + name.removeAttribute("data-l10n-id"); + } else { + document.l10n.setAttributes(name, "addon-name-disabled", { + name: addon.name, + }); + } + name.title = `${addon.name} ${addon.version}`; + + let toggleDisabledButton = card.querySelector('[action="toggle-disabled"]'); + if (toggleDisabledButton) { + let toggleDisabledAction = addon.userDisabled ? "enable" : "disable"; + toggleDisabledButton.hidden = !hasPermission(addon, toggleDisabledAction); + if (addon.type === "theme") { + document.l10n.setAttributes( + toggleDisabledButton, + `${toggleDisabledAction}-addon-button` + ); + } else if ( + addon.type === "extension" || + addon.type === "sitepermission" + ) { + toggleDisabledButton.checked = !addon.userDisabled; + } + } + + // Set the items in the more options menu. + this.options.update(this, addon, this.updateInstall); + + // Badge the more options button if there's an update. + let moreOptionsButton = card.querySelector(".more-options-button"); + moreOptionsButton.classList.toggle( + "more-options-button-badged", + !!(this.updateInstall && isInState(this.updateInstall, "available")) + ); + + // Postponed update addon card message bar. + const hasPostponedInstall = + this.updateInstall && isInState(this.updateInstall, "postponed"); + this.postponedMessageBar.hidden = !hasPostponedInstall; + + // Hide the more options button if it's empty. + moreOptionsButton.hidden = this.options.visibleItems.length === 0; + + // Ensure all badges are initially hidden. + for (let node of card.querySelectorAll(".addon-badge")) { + node.hidden = true; + } + + // Set the private browsing badge visibility. + // TODO: We don't show the badge for SitePermsAddon for now, but this should + // be handled in Bug 1799090. + if (addon.incognito != "not_allowed" && addon.type == "extension") { + // Keep update synchronous, the badge can appear later. + isAllowedInPrivateBrowsing(addon).then(isAllowed => { + card.querySelector( + ".addon-badge-private-browsing-allowed" + ).hidden = !isAllowed; + }); + } + + // Show the recommended badges if needed. + // Plugins don't have recommendationStates, so ensure a default. + let states = addon.recommendationStates || []; + for (let badgeName of states) { + let badge = card.querySelector(`.addon-badge-${badgeName}`); + if (badge) { + badge.hidden = false; + } + } + + // Update description. + card.querySelector(".addon-description").textContent = addon.description; + + this.updateMessage(); + + // Update the details if they're shown. + if (this.details) { + this.details.update(); + } + + this.sendEvent("update"); + } + + async updateMessage() { + const messageBar = this.card.querySelector(".addon-card-message"); + + const { + linkUrl, + messageId, + messageArgs, + type = "", + } = await getAddonMessageInfo(this.addon); + + if (messageId) { + document.l10n.pauseObserving(); + document.l10n.setAttributes( + messageBar.querySelector("span"), + messageId, + messageArgs + ); + + const link = messageBar.querySelector("button"); + if (linkUrl) { + document.l10n.setAttributes(link, `${messageId}-link`); + link.setAttribute("url", linkUrl); + link.hidden = false; + } else { + link.hidden = true; + } + + document.l10n.resumeObserving(); + await document.l10n.translateFragment(messageBar); + messageBar.setAttribute("type", type); + messageBar.hidden = false; + } else { + messageBar.hidden = true; + } + } + + showPrefs() { + this.details.showPrefs(); + } + + expand() { + if (!this.children.length) { + this.expanded = true; + } else { + throw new Error("expand() is only supported before render()"); + } + } + + render() { + this.textContent = ""; + + let { addon } = this; + if (!addon) { + throw new Error("addon-card must be initialized with setAddon()"); + } + + this.setAttribute("addon-id", addon.id); + + this.card = importTemplate("card").firstElementChild; + let headingId = ExtensionCommon.makeWidgetId(`${addon.id}-heading`); + this.card.setAttribute("aria-labelledby", headingId); + + // Remove the toggle-disabled button(s) based on type. + if (addon.type != "theme") { + this.card.querySelector(".theme-enable-button").remove(); + } + if (addon.type != "extension" && addon.type != "sitepermission") { + this.card.querySelector(".extension-enable-button").remove(); + } + + let nameContainer = this.card.querySelector(".addon-name-container"); + let headingLevel = this.expanded ? "h1" : "h3"; + let nameHeading = document.createElement(headingLevel); + nameHeading.classList.add("addon-name"); + nameHeading.id = headingId; + if (!this.expanded) { + let name = document.createElement("a"); + name.classList.add("addon-name-link"); + name.href = `addons://detail/${addon.id}`; + nameHeading.appendChild(name); + this.addonNameEl = name; + } else { + this.addonNameEl = nameHeading; + } + nameContainer.prepend(nameHeading); + + let panelType = addon.type == "plugin" ? "plugin-options" : "addon-options"; + this.options = document.createElement(panelType); + this.options.render(); + this.card.appendChild(this.options); + this.optionsButton = this.card.querySelector(".more-options-button"); + + // Set the contents. + this.update(); + + let doneRenderPromise = Promise.resolve(); + if (this.expanded) { + if (!this.details) { + this.details = document.createElement("addon-details"); + } + this.details.setAddon(this.addon); + doneRenderPromise = this.details.render(); + + // If we're re-rendering we still need to append the details since the + // entire card was emptied at the beginning of the render. + this.card.appendChild(this.details); + } + + this.appendChild(this.card); + + if (this.expanded) { + requestAnimationFrame(() => this.optionsButton.focus()); + } + + // Return the promise of details rendering to wait on in DetailView. + return doneRenderPromise; + } + + sendEvent(name, detail) { + this.dispatchEvent(new CustomEvent(name, { detail })); + } + + recordActionEvent(action, value) { + AMTelemetry.recordActionEvent({ + object: "aboutAddons", + view: getTelemetryViewName(this), + action, + addon: this.addon, + value, + }); + } + + /** + * AddonManager listener events. + */ + + onNewInstall(install) { + this.updateInstall = install; + this.sendEvent("update-found"); + } + + onInstallEnded(install) { + this.setAddon(install.addon); + } + + onInstallPostponed(install) { + this.updateInstall = install; + this.sendEvent("update-postponed"); + } + + onDisabled(addon) { + if (!this.reloading) { + this.update(); + } + } + + onEnabled(addon) { + this.reloading = false; + this.update(); + } + + onInstalled(addon) { + // When a temporary addon is reloaded, onInstalled is triggered instead of + // onEnabled. + this.reloading = false; + this.update(); + } + + onUninstalling() { + // Dispatch a remove event, the DetailView is listening for this to get us + // back to the list view when the current add-on is removed. + this.sendEvent("remove"); + } + + onUpdateModeChanged() { + this.update(); + } + + onPropertyChanged(addon, changed) { + if (this.details && changed.includes("applyBackgroundUpdates")) { + this.details.update(); + } else if (addon.type == "plugin" && changed.includes("userDisabled")) { + this.update(); + } + } + + /* Extension Permission change listener */ + async onChangePermissions(data) { + let perms = data.added || data.removed; + let hasAllSites = false; + for (let permission of perms.permissions.concat(perms.origins)) { + if (Extension.isAllSitesPermission(permission)) { + hasAllSites = true; + continue; + } + let target = document.querySelector(`[permission-key="${permission}"]`); + let checked = !data.removed; + if (target) { + target.closest("li").classList.toggle("permission-checked", checked); + target.checked = checked; + } + } + if (hasAllSites) { + // special-case for finding the all-sites target by attribute. + let target = document.querySelector("[permission-all-sites]"); + let checked = await AddonCard.optionalAllSitesGranted(this.addon.id); + target.closest("li").classList.toggle("permission-checked", checked); + target.checked = checked; + } + } + + // Only covers optional_permissions in MV2 and all host permissions in MV3. + static async optionalAllSitesGranted(addonId) { + let granted = await ExtensionPermissions.get(addonId); + return granted.origins.some(perm => Extension.isAllSitesPermission(perm)); + } +} +customElements.define("addon-card", AddonCard); + +class ColorwayClosetCard extends HTMLElement { + connectedCallback() { + if (this.childElementCount === 0) { + this.render(); + } + + AddonManagerListenerHandler.addListener(this); + } + + disconnectedCallback() { + AddonManagerListenerHandler.removeListener(this); + } + + onEnabled(addon) { + if (addon.type !== "theme") { + return; + } + + // Listen for changes to actively selected theme. + // Update button label for Colorway Closet card, according to + // whether or not a colorway theme from the active collection is + // currently enabled. + let colorwaysButton = document.querySelector("[action='open-colorways']"); + + document.l10n.setAttributes( + colorwaysButton, + BuiltInThemes.isColorwayFromCurrentCollection?.(addon.id) + ? "theme-colorways-button-colorway-enabled" + : "theme-colorways-button" + ); + } + + render() { + let card = importTemplate("card").firstElementChild; + let heading = card.querySelector(".addon-name-container"); + // remove elipsis button + heading.textContent = ""; + heading.append(importTemplate("colorways-card-container")); + this.setCardPreviewText(card); + this.setCardContent(card); + this.append(card); + } + + setCardPreviewText(card) { + // Create new elements for card preview text + let colorwayPreviewHeading = document.createElement("h3"); + let colorwayPreviewSubHeading = document.createElement("p"); + let colorwayPreviewTextContainer = document.createElement("div"); + + const collection = BuiltInThemes.findActiveColorwayCollection?.(); + if (collection) { + const { l10nId } = collection; + document.l10n.setAttributes(colorwayPreviewHeading, l10nId.title); + document.l10n.setAttributes( + colorwayPreviewSubHeading, + `${l10nId.title}-short-description` + ); + } + + colorwayPreviewTextContainer.appendChild(colorwayPreviewHeading); + colorwayPreviewTextContainer.appendChild(colorwayPreviewSubHeading); + colorwayPreviewTextContainer.id = "colorways-preview-text-container"; + + // Insert colorway card preview text + let cardHeadingImage = card.querySelector(".card-heading-image"); + cardHeadingImage.parentNode.insertBefore( + colorwayPreviewTextContainer, + cardHeadingImage + ); + } + + setCardContent(card) { + card.querySelector(".addon-icon").hidden = true; + + const collection = BuiltInThemes.findActiveColorwayCollection?.(); + if (!collection) { + return; + } + + const preview = card.querySelector(".card-heading-image"); + const { cardImagePath, expiry } = collection; + if (cardImagePath) { + preview.src = cardImagePath; + } + + let colorwayExpiryDateSpan = card.querySelector( + "#colorways-expiry-date > span" + ); + document.l10n.setAttributes( + colorwayExpiryDateSpan, + "colorway-collection-expiry-label", + { + expiryDate: expiry.getTime(), + } + ); + + let colorwaysButton = card.querySelector("[action='open-colorways']"); + document.l10n.setAttributes( + colorwaysButton, + BuiltInThemes.isColorwayFromCurrentCollection?.(ACTIVE_THEME_ID) + ? "theme-colorways-button-colorway-enabled" + : "theme-colorways-button" + ); + + colorwaysButton.hidden = false; + colorwaysButton.onclick = () => { + ColorwayClosetOpener.openModal({ + source: "aboutaddons", + onClosed: ({ colorwayChanged }) => { + ColorwayClosetCard.hasModalOpen = false; + ColorwayClosetCard.runPendingModalClosedCallbacks(colorwayChanged); + }, + }); + ColorwayClosetCard.hasModalOpen = true; + }; + } + + static hasModalOpen = false; + static closedModalCallbacks = new Set(); + + static callOnModalClosed(fn) { + if (!this.hasModalOpen) { + try { + fn(); + } catch (err) { + Cu.reportError(err); + } + return; + } + this.closedModalCallbacks.add(fn); + } + + static async runPendingModalClosedCallbacks(colorwayChanged) { + // Just drop all pending callbacks if the current active theme didn't change + // from when the modal was initially opened to prevent the about:addons page + // to be flickering because of the pending callbacks forcing the page from + // re-rendering unnecessarily. + if (colorwayChanged) { + for (const fn of this.closedModalCallbacks) { + try { + fn(); + } catch (err) { + Cu.reportError(err); + } + } + } + this.closedModalCallbacks.clear(); + } +} +customElements.define("colorways-card", ColorwayClosetCard); + +/** + * A child element of ``. It should be initialized + * by calling `setDiscoAddon()` first. Call `setAddon(addon)` if it has been + * installed, and call `setAddon(null)` upon uninstall. + * + * let discoAddon = new DiscoAddonWrapper({ ... }); + * let card = document.createElement("recommended-addon-card"); + * card.setDiscoAddon(discoAddon); + * document.body.appendChild(card); + * + * AddonManager.getAddonsByID(discoAddon.id) + * .then(addon => card.setAddon(addon)); + */ +class RecommendedAddonCard extends HTMLElement { + /** + * @param {DiscoAddonWrapper} addon + * The details of the add-on that should be rendered in the card. + */ + setDiscoAddon(addon) { + this.addonId = addon.id; + + // Save the information so we can install. + this.discoAddon = addon; + + let card = importTemplate("card").firstElementChild; + let heading = card.querySelector(".addon-name-container"); + heading.textContent = ""; + heading.append(importTemplate("addon-name-container-in-disco-card")); + + this.setCardContent(card, addon); + if (addon.type != "theme") { + card + .querySelector(".addon-description") + .append(importTemplate("addon-description-in-disco-card")); + this.setCardDescription(card, addon); + } + this.registerButtons(card, addon); + + this.textContent = ""; + this.append(card); + + // We initially assume that the add-on is not installed. + this.setAddon(null); + } + + /** + * Fills in all static parts of the card. + * + * @param {HTMLElement} card + * The primary content of this card. + * @param {DiscoAddonWrapper} addon + */ + setCardContent(card, addon) { + // Set the icon. + if (addon.type == "theme") { + card.querySelector(".addon-icon").hidden = true; + } else { + card.querySelector(".addon-icon").src = AddonManager.getPreferredIconURL( + addon, + 32, + window + ); + } + + // Set the theme preview. + let preview = card.querySelector(".card-heading-image"); + if (addon.type == "theme") { + let screenshotUrl = getScreenshotUrlForAddon(addon); + if (screenshotUrl) { + preview.src = screenshotUrl; + preview.hidden = false; + } + } else { + preview.hidden = true; + } + + // Set the name. + card.querySelector(".disco-addon-name").textContent = addon.name; + + // Set the author name and link to AMO. + if (addon.creator) { + let authorInfo = card.querySelector(".disco-addon-author"); + document.l10n.setAttributes(authorInfo, "created-by-author", { + author: addon.creator.name, + }); + // This is intentionally a link to the add-on listing instead of the + // author page, because the add-on listing provides more relevant info. + authorInfo.querySelector("a").href = formatUTMParams( + "discopane-entry-link", + addon.amoListingUrl + ); + authorInfo.hidden = false; + } + } + + setCardDescription(card, addon) { + // Set the description. Note that this is the editorial description, not + // the add-on's original description that would normally appear on a card. + card.querySelector(".disco-description-main").textContent = + addon.editorialDescription; + + let hasStats = false; + if (addon.averageRating) { + hasStats = true; + card.querySelector("five-star-rating").rating = addon.averageRating; + } else { + card.querySelector("five-star-rating").hidden = true; + } + + if (addon.dailyUsers) { + hasStats = true; + let userCountElem = card.querySelector(".disco-user-count"); + document.l10n.setAttributes(userCountElem, "user-count", { + dailyUsers: addon.dailyUsers, + }); + } + + card.querySelector(".disco-description-statistics").hidden = !hasStats; + } + + registerButtons(card, addon) { + let installButton = card.querySelector("[action='install-addon']"); + if (addon.type == "theme") { + document.l10n.setAttributes(installButton, "install-theme-button"); + } else { + document.l10n.setAttributes(installButton, "install-extension-button"); + } + + this.addEventListener("click", this); + } + + handleEvent(event) { + let action = event.target.getAttribute("action"); + switch (action) { + case "install-addon": + AMTelemetry.recordActionEvent({ + object: "aboutAddons", + view: getTelemetryViewName(this), + action: "installFromRecommendation", + addon: this.discoAddon, + }); + this.installDiscoAddon(); + break; + case "manage-addon": + AMTelemetry.recordActionEvent({ + object: "aboutAddons", + view: getTelemetryViewName(this), + action: "manage", + addon: this.discoAddon, + }); + gViewController.loadView(`detail/${this.addonId}`); + break; + default: + if (event.target.matches(".disco-addon-author a[href]")) { + AMTelemetry.recordLinkEvent({ + object: "aboutAddons", + // Note: This is not "author" nor "homepage", because the link text + // is the author name, but the link URL the add-on's listing URL. + value: "discohome", + extra: { + view: getTelemetryViewName(this), + }, + }); + } + } + } + + async installDiscoAddon() { + let addon = this.discoAddon; + let url = addon.sourceURI.spec; + let install = await AddonManager.getInstallForURL(url, { + name: addon.name, + telemetryInfo: { + source: "disco", + taarRecommended: addon.taarRecommended, + }, + }); + // We are hosted in a in about:addons, but we can just use the + // main tab's browser since all of it is using the system principal. + let browser = window.docShell.chromeEventHandler; + AddonManager.installAddonFromWebpage( + "application/x-xpinstall", + browser, + Services.scriptSecurityManager.getSystemPrincipal(), + install + ); + } + + /** + * @param {AddonWrapper|null} addon + * The add-on that has been installed; null if it has been removed. + */ + setAddon(addon) { + let card = this.firstElementChild; + card.querySelector("[action='install-addon']").hidden = !!addon; + card.querySelector("[action='manage-addon']").hidden = !addon; + + this.dispatchEvent(new CustomEvent("disco-card-updated")); // For testing. + } +} +customElements.define("recommended-addon-card", RecommendedAddonCard); + +/** + * A list view for add-ons of a certain type. It should be initialized with the + * type of add-on to render and have section data set before being connected to + * the document. + * + * let list = document.createElement("addon-list"); + * list.type = "plugin"; + * list.setSections([{ + * headingId: "plugin-section-heading", + * filterFn: addon => !addon.isSystem, + * }]); + * document.body.appendChild(list); + */ +class AddonList extends HTMLElement { + constructor() { + super(); + this.sections = []; + this.pendingUninstallAddons = new Set(); + this._addonsToUpdate = new Set(); + this._userFocusListenersAdded = false; + } + + async connectedCallback() { + // Register the listener and get the add-ons, these operations should + // happpen as close to each other as possible. + this.registerListener(); + // Don't render again if we were rendered prior to being inserted. + if (!this.children.length) { + // Render the initial view. + this.render(); + } + } + + disconnectedCallback() { + // Remove content and stop listening until this is connected again. + this.textContent = ""; + this.removeListener(); + + // Process any pending uninstall related to this list. + for (const addon of this.pendingUninstallAddons) { + if (isPending(addon, "uninstall")) { + addon.uninstall(); + } + } + this.pendingUninstallAddons.clear(); + } + + /** + * Configure the sections in the list. + * + * @param {object[]} sections + * The options for the section. Each entry in the array should have: + * headingId: The fluent id for the section's heading. + * filterFn: A function that determines if an add-on belongs in + * the section. + */ + setSections(sections) { + this.sections = sections.map(section => Object.assign({}, section)); + } + + /** + * Set the add-on type for this list. This will be used to filter the add-ons + * that are displayed. + * + * @param {string} val The type to filter on. + */ + set type(val) { + this.setAttribute("type", val); + } + + get type() { + return this.getAttribute("type"); + } + + getSection(index) { + return this.sections[index].node; + } + + getCards(section) { + return section.querySelectorAll("addon-card"); + } + + getCard(addon) { + return this.querySelector(`addon-card[addon-id="${addon.id}"]`); + } + + getPendingUninstallBar(addon) { + return this.querySelector(`message-bar[addon-id="${addon.id}"]`); + } + + sortByFn(aAddon, bAddon) { + return aAddon.name.localeCompare(bAddon.name); + } + + async getAddons() { + if (!this.type) { + throw new Error(`type must be set to find add-ons`); + } + + // Find everything matching our type, null will find all types. + let type = this.type == "all" ? null : [this.type]; + let addons = await AddonManager.getAddonsByTypes(type); + + if (type == "theme") { + await BuiltInThemes.ensureBuiltInThemes(); + } + + // Put the add-ons into the sections, an add-on goes in the first section + // that it matches the filterFn for. It might not go in any section. + let sectionedAddons = this.sections.map(() => []); + for (let addon of addons) { + let index = this.sections.findIndex(({ filterFn }) => filterFn(addon)); + if (index != -1) { + sectionedAddons[index].push(addon); + } else if (isPending(addon, "uninstall")) { + // A second tab may be opened on "about:addons" (or Firefox may + // have crashed) while there are still "pending uninstall" add-ons. + // Ensure to list them in the pendingUninstall message-bar-stack + // when the AddonList is initially rendered. + this.pendingUninstallAddons.add(addon); + } + } + + // Sort the add-ons in each section. + for (let [index, section] of sectionedAddons.entries()) { + let sortByFn = this.sections[index].sortByFn || this.sortByFn; + section.sort(sortByFn); + } + + return sectionedAddons; + } + + createPendingUninstallStack() { + const stack = document.createElement("message-bar-stack"); + stack.setAttribute("class", "pending-uninstall"); + stack.setAttribute("reverse", ""); + return stack; + } + + addPendingUninstallBar(addon) { + const stack = this.pendingUninstallStack; + const mb = document.createElement("message-bar"); + mb.setAttribute("addon-id", addon.id); + mb.setAttribute("type", "generic"); + + const addonName = document.createElement("span"); + addonName.setAttribute("data-l10n-name", "addon-name"); + const message = document.createElement("span"); + message.append(addonName); + const undo = document.createElement("button"); + undo.setAttribute("action", "undo"); + undo.addEventListener("click", () => { + AMTelemetry.recordActionEvent({ + object: "aboutAddons", + view: getTelemetryViewName(this), + action: "undo", + addon, + }); + addon.cancelUninstall(); + }); + + document.l10n.setAttributes(message, "pending-uninstall-description", { + addon: addon.name, + }); + document.l10n.setAttributes(undo, "pending-uninstall-undo-button"); + + mb.append(message, undo); + stack.append(mb); + } + + removePendingUninstallBar(addon) { + const messagebar = this.getPendingUninstallBar(addon); + if (messagebar) { + messagebar.remove(); + } + } + + createSectionHeading(headingIndex) { + let { + headingId, + subheadingId, + sectionPreambleCustomElement, + } = this.sections[headingIndex]; + let frag = document.createDocumentFragment(); + let heading = document.createElement("h2"); + heading.classList.add("list-section-heading"); + document.l10n.setAttributes(heading, headingId); + frag.append(heading); + + if (subheadingId) { + let subheading = document.createElement("h3"); + subheading.classList.add("list-section-subheading"); + document.l10n.setAttributes(subheading, subheadingId); + // Preserve the old colorway section header styling + // while the colorway closet section is not yet ready to be enabled + if (!COLORWAY_CLOSET_ENABLED) { + heading.className = "header-name"; + } + frag.append(subheading); + } + + if (sectionPreambleCustomElement) { + frag.append(document.createElement(sectionPreambleCustomElement)); + } + + return frag; + } + + createEmptyListMessage() { + let emptyMessage = "list-empty-get-extensions-message"; + let linkPref = "extensions.getAddons.link.url"; + + if (this.sections && this.sections.length) { + if (this.sections[0].headingId == "locale-enabled-heading") { + emptyMessage = "list-empty-get-language-packs-message"; + linkPref = "browser.dictionaries.download.url"; + } else if (this.sections[0].headingId == "dictionary-enabled-heading") { + emptyMessage = "list-empty-get-dictionaries-message"; + linkPref = "browser.dictionaries.download.url"; + } + } + + let messageContainer = document.createElement("p"); + messageContainer.id = "empty-addons-message"; + let a = document.createElement("a"); + a.href = Services.urlFormatter.formatURLPref(linkPref); + a.setAttribute("target", "_blank"); + a.setAttribute("data-l10n-name", "get-extensions"); + document.l10n.setAttributes(messageContainer, emptyMessage, { + domain: a.hostname, + }); + messageContainer.appendChild(a); + return messageContainer; + } + + updateSectionIfEmpty(section) { + // We should empty out the section if there are no more cards to display, + // (unless the section is configured to stay visible and rendered even when + // there is no addon listed, e.g. the "Colorways Closet" section). + const sectionIndex = parseInt(section.getAttribute("section")); + const { shouldRenderIfEmpty } = this.sections[sectionIndex]; + if (!this.getCards(section).length && !shouldRenderIfEmpty) { + section.textContent = ""; + } + } + + insertCardInto(card, sectionIndex) { + let section = this.getSection(sectionIndex); + let sectionCards = this.getCards(section); + + const { shouldRenderIfEmpty } = this.sections[sectionIndex]; + + // If this is the first card in the section, and the section + // isn't configure to render the headers even when empty, + // we have to create the section heading first. + if (!shouldRenderIfEmpty && !sectionCards.length) { + section.appendChild(this.createSectionHeading(sectionIndex)); + } + + // Find where to insert the card. + let insertBefore = Array.from(sectionCards).find( + otherCard => this.sortByFn(card.addon, otherCard.addon) < 0 + ); + // This will append if insertBefore is null. + section.insertBefore(card, insertBefore || null); + } + + addAddon(addon) { + // Only insert add-ons of the right type. + if (addon.type != this.type && this.type != "all") { + this.sendEvent("skip-add", "type-mismatch"); + return; + } + + let insertSection = this._addonSectionIndex(addon); + + // Don't add the add-on if it doesn't go in a section. + if (insertSection == -1) { + return; + } + + // Create and insert the card. + let card = document.createElement("addon-card"); + card.setAddon(addon); + this.insertCardInto(card, insertSection); + this.sendEvent("add", { id: addon.id }); + } + + sendEvent(name, detail) { + this.dispatchEvent(new CustomEvent(name, { detail })); + } + + removeAddon(addon) { + let card = this.getCard(addon); + if (card) { + let section = card.parentNode; + card.remove(); + this.updateSectionIfEmpty(section); + this.sendEvent("remove", { id: addon.id }); + } + } + + updateAddon(addon) { + if (addon.type === "theme" && ColorwayClosetCard.hasModalOpen) { + // Queue up theme card changes while the ColorwayCloset modal is still + // open to prevent the about:addons page visible behind the colorway + // closet modal from flickering when the list is refreshed in response + // to a new colorway theme being selected in the modal dialog. + ColorwayClosetCard.callOnModalClosed(() => { + this.updateAddon(addon); + }); + } else if (!this.getCard(addon)) { + // Try to add the add-on right away. + this.addAddon(addon); + } else if (this._addonSectionIndex(addon) == -1) { + // If the theme is a colorways theme from an active collection that is + // being disabled, it is expected to not be in any section (it will be + // available in the colorway closet dialog instead). But, we still want + // to defer moving the card until the list is going to lose focus (to + // match the same behavior the user expects for any non-colorways theme + // card when the theme is disabled). + if ( + addon.type === "theme" && + BuiltInThemes.isColorwayFromCurrentCollection?.(addon.id) && + this.isUserFocused + ) { + this.updateLater(addon); + } else { + // Not a colorways theme, fallback to remove the add-on card right away. + this._updateAddon(addon); + } + } else if (this.isUserFocused) { + // Queue up a change for when the focus is cleared. + this.updateLater(addon); + } else { + // Not currently focused, make the change now. + this.withCardAnimation(() => this._updateAddon(addon)); + } + } + + updateLater(addon) { + this._addonsToUpdate.add(addon); + this._addUserFocusListeners(); + } + + _addUserFocusListeners() { + if (this._userFocusListenersAdded) { + return; + } + + this._userFocusListenersAdded = true; + this.addEventListener("mouseleave", this); + this.addEventListener("hidden", this, true); + this.addEventListener("focusout", this); + } + + _removeUserFocusListeners() { + if (!this._userFocusListenersAdded) { + return; + } + + this.removeEventListener("mouseleave", this); + this.removeEventListener("hidden", this, true); + this.removeEventListener("focusout", this); + this._userFocusListenersAdded = false; + } + + get hasMenuOpen() { + return !!this.querySelector("panel-list[open]"); + } + + get isUserFocused() { + return this.matches(":hover, :focus-within") || this.hasMenuOpen; + } + + update() { + if (this._addonsToUpdate.size) { + this.withCardAnimation(() => { + for (let addon of this._addonsToUpdate) { + this._updateAddon(addon); + } + this._addonsToUpdate = new Set(); + }); + } + } + + _getChildCoords() { + let results = new Map(); + for (let child of this.querySelectorAll("addon-card")) { + results.set(child, child.getBoundingClientRect()); + } + return results; + } + + withCardAnimation(changeFn) { + if (shouldSkipAnimations()) { + changeFn(); + return; + } + + let origChildCoords = this._getChildCoords(); + + changeFn(); + + let newChildCoords = this._getChildCoords(); + let cards = this.querySelectorAll("addon-card"); + let transitionCards = []; + for (let card of cards) { + let orig = origChildCoords.get(card); + let moved = newChildCoords.get(card); + let changeY = moved.y - (orig || moved).y; + let cardEl = card.firstElementChild; + + if (changeY != 0) { + cardEl.style.transform = `translateY(${changeY * -1}px)`; + transitionCards.push(card); + } + } + requestAnimationFrame(() => { + for (let card of transitionCards) { + card.firstElementChild.style.transition = "transform 125ms"; + } + + requestAnimationFrame(() => { + for (let card of transitionCards) { + let cardEl = card.firstElementChild; + cardEl.style.transform = ""; + cardEl.addEventListener("transitionend", function handler(e) { + if (e.target == cardEl && e.propertyName == "transform") { + cardEl.style.transition = ""; + cardEl.removeEventListener("transitionend", handler); + } + }); + } + }); + }); + } + + _addonSectionIndex(addon) { + return this.sections.findIndex(s => s.filterFn(addon)); + } + + _updateAddon(addon) { + let card = this.getCard(addon); + if (card) { + let sectionIndex = this._addonSectionIndex(addon); + if (sectionIndex != -1) { + // Move the card, if needed. This will allow an animation between + // page sections and provides clearer events for testing. + if (card.parentNode.getAttribute("section") != sectionIndex) { + let { activeElement } = document; + let refocus = card.contains(activeElement); + let oldSection = card.parentNode; + this.insertCardInto(card, sectionIndex); + this.updateSectionIfEmpty(oldSection); + if (refocus) { + activeElement.focus(); + } + this.sendEvent("move", { id: addon.id }); + } + } else { + this.removeAddon(addon); + } + } + } + + renderSection(addons, index) { + const { sectionClass, shouldRenderIfEmpty } = this.sections[index]; + + let section = document.createElement("section"); + section.setAttribute("section", index); + if (sectionClass) { + section.setAttribute("class", sectionClass); + } + + // Render the heading and add-ons if there are any. + if (shouldRenderIfEmpty || addons.length) { + section.appendChild(this.createSectionHeading(index)); + } + + for (let addon of addons) { + let card = document.createElement("addon-card"); + card.setAddon(addon); + card.render(); + section.appendChild(card); + } + + return section; + } + + async render() { + this.textContent = ""; + + let sectionedAddons = await this.getAddons(); + + let frag = document.createDocumentFragment(); + + // Render the pending uninstall message-bar-stack. + this.pendingUninstallStack = this.createPendingUninstallStack(); + for (let addon of this.pendingUninstallAddons) { + this.addPendingUninstallBar(addon); + } + frag.appendChild(this.pendingUninstallStack); + + // Render the sections. + for (let i = 0; i < sectionedAddons.length; i++) { + this.sections[i].node = this.renderSection(sectionedAddons[i], i); + frag.appendChild(this.sections[i].node); + } + + // Render the placeholder that is shown when all sections are empty. + // This call is after rendering the sections, because its visibility + // is controlled through the general sibling combinator relative to + // the sections (section ~). + let message = this.createEmptyListMessage(); + frag.appendChild(message); + + // Make sure fluent has set all the strings before we render. This will + // avoid the height changing as strings go from 0 height to having text. + await document.l10n.translateFragment(frag); + this.appendChild(frag); + } + + registerListener() { + AddonManagerListenerHandler.addListener(this); + } + + removeListener() { + AddonManagerListenerHandler.removeListener(this); + } + + handleEvent(e) { + if (!this.isUserFocused || (e.type == "mouseleave" && !this.hasMenuOpen)) { + this._removeUserFocusListeners(); + this.update(); + } + } + + /** + * AddonManager listener events. + */ + + onOperationCancelled(addon) { + if ( + this.pendingUninstallAddons.has(addon) && + !isPending(addon, "uninstall") + ) { + this.pendingUninstallAddons.delete(addon); + this.removePendingUninstallBar(addon); + } + this.updateAddon(addon); + } + + onEnabled(addon) { + this.updateAddon(addon); + } + + onDisabled(addon) { + this.updateAddon(addon); + } + + onUninstalling(addon) { + if ( + isPending(addon, "uninstall") && + (this.type === "all" || addon.type === this.type) + ) { + this.pendingUninstallAddons.add(addon); + this.addPendingUninstallBar(addon); + this.updateAddon(addon); + } + } + + onInstalled(addon) { + if (this.querySelector(`addon-card[addon-id="${addon.id}"]`)) { + return; + } + this.addAddon(addon); + } + + onUninstalled(addon) { + this.pendingUninstallAddons.delete(addon); + this.removePendingUninstallBar(addon); + this.removeAddon(addon); + } +} +customElements.define("addon-list", AddonList); + +class RecommendedAddonList extends HTMLElement { + connectedCallback() { + if (this.isConnected) { + this.loadCardsIfNeeded(); + this.updateCardsWithAddonManager(); + } + AddonManagerListenerHandler.addListener(this); + } + + disconnectedCallback() { + AddonManagerListenerHandler.removeListener(this); + } + + get type() { + return this.getAttribute("type"); + } + + /** + * Set the add-on type for this list. This will be used to filter the add-ons + * that are displayed. + * + * Must be set prior to the first render. + * + * @param {string} val The type to filter on. + */ + set type(val) { + this.setAttribute("type", val); + } + + get hideInstalled() { + return this.hasAttribute("hide-installed"); + } + + /** + * Set whether installed add-ons should be hidden from the list. If false, + * installed add-ons will be shown with a "Manage" button, otherwise they + * will be hidden. + * + * Must be set prior to the first render. + * + * @param {boolean} val Whether to show installed add-ons. + */ + set hideInstalled(val) { + this.toggleAttribute("hide-installed", val); + } + + getCardById(addonId) { + for (let card of this.children) { + if (card.addonId === addonId) { + return card; + } + } + return null; + } + + setAddonForCard(card, addon) { + card.setAddon(addon); + + let wasHidden = card.hidden; + card.hidden = this.hideInstalled && addon; + + if (wasHidden != card.hidden) { + let eventName = card.hidden ? "card-hidden" : "card-shown"; + this.dispatchEvent(new CustomEvent(eventName, { detail: { card } })); + } + } + + /** + * Whether the client ID should be preferred. This is disabled for themes + * since they don't use the telemetry data and don't show the TAAR notice. + */ + get preferClientId() { + return !this.type || this.type == "extension"; + } + + async updateCardsWithAddonManager() { + let cards = Array.from(this.children); + let addonIds = cards.map(card => card.addonId); + let addons = await AddonManager.getAddonsByIDs(addonIds); + for (let [i, card] of cards.entries()) { + let addon = addons[i]; + this.setAddonForCard(card, addon); + if (addon) { + // Already installed, move card to end. + this.append(card); + } + } + } + + async loadCardsIfNeeded() { + // Use promise as guard. Also used by tests to detect when load completes. + if (!this.cardsReady) { + this.cardsReady = this._loadCards(); + } + return this.cardsReady; + } + + async _loadCards() { + let recommendedAddons; + try { + recommendedAddons = await DiscoveryAPI.getResults(this.preferClientId); + } catch (e) { + return; + } + + let frag = document.createDocumentFragment(); + for (let addon of recommendedAddons) { + if (this.type && addon.type != this.type) { + continue; + } + let card = document.createElement("recommended-addon-card"); + card.setDiscoAddon(addon); + frag.append(card); + } + this.append(frag); + await this.updateCardsWithAddonManager(); + } + + /** + * AddonManager listener events. + */ + + onInstalled(addon) { + let card = this.getCardById(addon.id); + if (card) { + this.setAddonForCard(card, addon); + } + } + + onUninstalled(addon) { + let card = this.getCardById(addon.id); + if (card) { + this.setAddonForCard(card, null); + } + } +} +customElements.define("recommended-addon-list", RecommendedAddonList); + +class TaarMessageBar extends HTMLElement { + connectedCallback() { + this.hidden = + Services.prefs.getBoolPref(PREF_RECOMMENDATION_HIDE_NOTICE, false) || + !DiscoveryAPI.clientIdDiscoveryEnabled; + if (this.childElementCount == 0 && !this.hidden) { + this.appendChild(importTemplate("taar-notice")); + this.addEventListener("click", this); + this.messageBar = this.querySelector("message-bar"); + this.messageBar.addEventListener("message-bar:user-dismissed", this); + } + } + + handleEvent(e) { + if ( + e.type == "click" && + e.target.getAttribute("action") == "notice-learn-more" + ) { + AMTelemetry.recordLinkEvent({ + object: "aboutAddons", + value: "disconotice", + extra: { + view: getTelemetryViewName(this), + }, + }); + } else if (e.type == "message-bar:user-dismissed") { + Services.prefs.setBoolPref(PREF_RECOMMENDATION_HIDE_NOTICE, true); + } + } +} +customElements.define("taar-notice", TaarMessageBar); + +class RecommendedFooter extends HTMLElement { + connectedCallback() { + if (this.childElementCount == 0) { + this.appendChild(importTemplate("recommended-footer")); + this.querySelector( + ".privacy-policy-link" + ).href = Services.prefs.getStringPref(PREF_PRIVACY_POLICY_URL); + this.addEventListener("click", this); + } + } + + handleEvent(event) { + let action = event.target.getAttribute("action"); + switch (action) { + case "open-amo": + openAmoInTab(this); + break; + } + } +} +customElements.define("recommended-footer", RecommendedFooter, { + extends: "footer", +}); + +class RecommendedThemesFooter extends HTMLElement { + connectedCallback() { + if (this.childElementCount == 0) { + this.appendChild(importTemplate("recommended-themes-footer")); + let themeRecommendationRow = this.querySelector(".theme-recommendation"); + let themeRecommendationUrl = Services.prefs.getStringPref( + PREF_THEME_RECOMMENDATION_URL + ); + if (themeRecommendationUrl) { + themeRecommendationRow.querySelector("a").href = themeRecommendationUrl; + } + themeRecommendationRow.hidden = !themeRecommendationUrl; + this.addEventListener("click", this); + } + } + + handleEvent(event) { + let action = event.target.getAttribute("action"); + switch (action) { + case "open-amo": + openAmoInTab(this, "themes"); + break; + } + } +} +customElements.define("recommended-themes-footer", RecommendedThemesFooter, { + extends: "footer", +}); + +/** + * This element will handle showing recommendations with a + * and a