From 2aa4a82499d4becd2284cdb482213d541b8804dd Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 28 Apr 2024 16:29:10 +0200 Subject: Adding upstream version 86.0.1. Signed-off-by: Daniel Baumann --- toolkit/mozapps/extensions/.eslintrc.js | 36 + toolkit/mozapps/extensions/AbuseReporter.jsm | 672 +++ toolkit/mozapps/extensions/AddonContentPolicy.cpp | 483 ++ toolkit/mozapps/extensions/AddonContentPolicy.h | 21 + toolkit/mozapps/extensions/AddonManager.jsm | 4918 ++++++++++++++++++++ .../extensions/AddonManagerStartup-inlines.h | 226 + toolkit/mozapps/extensions/AddonManagerStartup.cpp | 876 ++++ toolkit/mozapps/extensions/AddonManagerStartup.h | 59 + toolkit/mozapps/extensions/AddonManagerWebAPI.cpp | 157 + toolkit/mozapps/extensions/AddonManagerWebAPI.h | 32 + toolkit/mozapps/extensions/Blocklist.jsm | 1898 ++++++++ .../mozapps/extensions/LightweightThemeManager.jsm | 36 + toolkit/mozapps/extensions/addonManager.js | 409 ++ toolkit/mozapps/extensions/amContentHandler.jsm | 81 + .../mozapps/extensions/amIAddonManagerStartup.idl | 83 + toolkit/mozapps/extensions/amIWebInstallPrompt.idl | 32 + toolkit/mozapps/extensions/amInstallTrigger.jsm | 205 + toolkit/mozapps/extensions/amWebAPI.jsm | 307 ++ toolkit/mozapps/extensions/components.conf | 44 + .../extensions/content/OpenH264-license.txt | 59 + toolkit/mozapps/extensions/content/aboutaddons.css | 739 +++ .../mozapps/extensions/content/aboutaddons.html | 427 ++ toolkit/mozapps/extensions/content/aboutaddons.js | 4811 +++++++++++++++++++ .../extensions/content/aboutaddonsCommon.js | 289 ++ .../extensions/content/abuse-report-frame.html | 144 + .../extensions/content/abuse-report-panel.css | 252 + .../extensions/content/abuse-report-panel.js | 865 ++++ .../mozapps/extensions/content/abuse-reports.js | 310 ++ toolkit/mozapps/extensions/content/blocklist.js | 119 + toolkit/mozapps/extensions/content/blocklist.xhtml | 51 + .../mozapps/extensions/content/default-theme.svg | 17 + .../content/drag-drop-addon-installer.js | 81 + toolkit/mozapps/extensions/content/extensions.js | 300 ++ .../mozapps/extensions/content/extensions.xhtml | 23 + .../extensions/content/firefox-alpenglow.svg | 4 + .../extensions/content/firefox-compact-dark.svg | 17 + .../extensions/content/firefox-compact-light.svg | 17 + toolkit/mozapps/extensions/content/message-bar.css | 144 + toolkit/mozapps/extensions/content/message-bar.js | 148 + toolkit/mozapps/extensions/content/named-deck.js | 380 ++ toolkit/mozapps/extensions/content/panel-item.css | 68 + toolkit/mozapps/extensions/content/panel-list.css | 58 + toolkit/mozapps/extensions/content/rating-star.css | 41 + toolkit/mozapps/extensions/content/shortcuts.css | 139 + toolkit/mozapps/extensions/content/shortcuts.js | 680 +++ toolkit/mozapps/extensions/default-theme/icon.svg | 14 + .../mozapps/extensions/default-theme/manifest.json | 42 + toolkit/mozapps/extensions/docs/AddonManager.rst | 4 + toolkit/mozapps/extensions/docs/SystemAddons.rst | 275 ++ toolkit/mozapps/extensions/docs/index.rst | 15 + toolkit/mozapps/extensions/extensions.manifest | 9 + toolkit/mozapps/extensions/gen_built_in_addons.py | 101 + .../extensions/internal/AddonRepository.jsm | 1126 +++++ .../mozapps/extensions/internal/AddonSettings.jsm | 147 + .../mozapps/extensions/internal/AddonTestUtils.jsm | 1986 ++++++++ .../extensions/internal/AddonUpdateChecker.jsm | 616 +++ toolkit/mozapps/extensions/internal/Content.js | 31 + .../mozapps/extensions/internal/GMPProvider.jsm | 891 ++++ .../mozapps/extensions/internal/PluginProvider.jsm | 535 +++ .../extensions/internal/ProductAddonChecker.jsm | 397 ++ .../mozapps/extensions/internal/XPIDatabase.jsm | 3500 ++++++++++++++ toolkit/mozapps/extensions/internal/XPIInstall.jsm | 4724 +++++++++++++++++++ .../mozapps/extensions/internal/XPIProvider.jsm | 3316 +++++++++++++ toolkit/mozapps/extensions/internal/moz.build | 26 + toolkit/mozapps/extensions/jar.mn | 38 + toolkit/mozapps/extensions/moz.build | 101 + .../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 | 115 + .../test/browser/browser_about_debugging_link.js | 129 + .../test/browser/browser_addon_list_reordering.js | 197 + .../extensions/test/browser/browser_bug523784.js | 153 + .../extensions/test/browser/browser_bug572561.js | 96 + .../browser/browser_checkAddonCompatibility.js | 36 + .../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 | 461 ++ .../test/browser/browser_history_navigation.js | 599 +++ .../test/browser/browser_html_abuse_report.js | 937 ++++ .../browser/browser_html_abuse_report_dialog.js | 178 + .../browser/browser_html_detail_permissions.js | 450 ++ .../test/browser/browser_html_detail_view.js | 1242 +++++ .../test/browser/browser_html_discover_view.js | 855 ++++ .../browser/browser_html_discover_view_clientid.js | 232 + .../browser/browser_html_discover_view_prefs.js | 83 + .../test/browser/browser_html_list_view.js | 990 ++++ .../browser_html_list_view_recommendations.js | 308 ++ .../test/browser/browser_html_message_bar.js | 185 + .../test/browser/browser_html_named_deck.js | 250 + .../test/browser/browser_html_options_ui.js | 539 +++ .../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 | 226 + .../test/browser/browser_html_updates.js | 829 ++++ .../test/browser/browser_html_warning_messages.js | 355 ++ .../extensions/test/browser/browser_installssl.js | 378 ++ .../test/browser/browser_installtrigger_install.js | 84 + .../test/browser/browser_interaction_telemetry.js | 531 +++ .../test/browser/browser_manage_shortcuts.js | 309 ++ .../browser/browser_manage_shortcuts_hidden.js | 199 + .../browser/browser_manage_shortcuts_remove.js | 173 + .../browser/browser_menu_button_accessibility.js | 81 + .../test/browser/browser_page_accessibility.js | 15 + .../browser/browser_page_options_install_addon.js | 128 + .../test/browser/browser_page_options_updates.js | 166 + .../test/browser/browser_panel_item_accesskey.js | 100 + .../browser/browser_panel_list_accessibility.js | 67 + .../test/browser/browser_permission_prompt.js | 178 + .../extensions/test/browser/browser_reinstall.js | 278 ++ .../test/browser/browser_search_bar_focus.js | 42 + .../browser/browser_shortcuts_duplicate_check.js | 151 + .../test/browser/browser_sidebar_categories.js | 163 + .../browser/browser_sidebar_hidden_categories.js | 214 + .../browser/browser_sidebar_restore_category.js | 76 + .../test/browser/browser_task_next_test.js | 17 + .../extensions/test/browser/browser_updateid.js | 87 + .../extensions/test/browser/browser_updatessl.js | 392 ++ .../extensions/test/browser/browser_updatessl.json | 17 + .../test/browser/browser_updatessl.json^headers^ | 1 + .../extensions/test/browser/browser_webapi.js | 143 + .../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 | 542 +++ .../browser/browser_webapi_install_disabled.js | 58 + .../test/browser/browser_webapi_theme.js | 80 + .../test/browser/browser_webapi_uninstall.js | 72 + .../extensions/test/browser/browser_webext_icon.js | 84 + .../test/browser/browser_webext_incognito.js | 645 +++ .../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 | 1809 +++++++ .../extensions/test/browser/head_abuse_report.js | 541 +++ toolkit/mozapps/extensions/test/browser/moz.build | 31 + .../extensions/test/browser/plugin_test.html | 7 + .../mozapps/extensions/test/browser/redirect.sjs | 5 + .../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 | 5 + .../extensions/test/mochitest/test_bug887098.html | 53 + .../test/mochitest/test_default_theme.html | 33 + toolkit/mozapps/extensions/test/moz.build | 20 + .../mozapps/extensions/test/xpcshell/.eslintrc.js | 24 + .../xpcshell/data/blocklistchange/addon_change.xml | 31 + .../data/blocklistchange/addon_update1.json | 102 + .../data/blocklistchange/addon_update2.json | 102 + .../data/blocklistchange/addon_update3.json | 102 + .../xpcshell/data/blocklistchange/app_update.xml | 62 + .../data/blocklistchange/blocklist_update1.xml | 3 + .../data/blocklistchange/blocklist_update2.xml | 26 + .../data/blocklistchange/manual_update.xml | 27 + .../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 + .../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 + .../test/xpcshell/data/test_gfxBlacklist.json | 352 ++ .../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 | 1350 ++++++ .../extensions/test/xpcshell/head_compat.js | 49 + .../extensions/test/xpcshell/head_sideload.js | 81 + .../extensions/test/xpcshell/head_system_addons.js | 469 ++ .../extensions/test/xpcshell/head_unpack.js | 3 + .../extensions/test/xpcshell/rs-blocklist/head.js | 51 + .../rs-blocklist/test_blocklist_addonBlockURL.js | 56 + .../rs-blocklist/test_blocklist_appversion.js | 293 ++ .../rs-blocklist/test_blocklist_clients.js | 233 + .../xpcshell/rs-blocklist/test_blocklist_gfx.js | 113 + .../test_blocklist_metadata_filters.js | 116 + .../xpcshell/rs-blocklist/test_blocklist_mlbf.js | 219 + .../rs-blocklist/test_blocklist_mlbf_dump.js | 97 + .../rs-blocklist/test_blocklist_mlbf_fetch.js | 207 + .../rs-blocklist/test_blocklist_mlbf_stashes.js | 252 + .../rs-blocklist/test_blocklist_mlbf_telemetry.js | 184 + .../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 | 229 + .../rs-blocklist/test_blocklist_severities.js | 504 ++ .../test_blocklist_targetapp_filter.js | 395 ++ .../rs-blocklist/test_blocklist_telemetry.js | 124 + .../xpcshell/rs-blocklist/test_blocklistchange.js | 1317 ++++++ .../rs-blocklist/test_blocklistchange_v2.js | 21 + .../rs-blocklist/test_gfxBlacklist_Device.js | 74 + .../rs-blocklist/test_gfxBlacklist_DriverNew.js | 68 + .../test_gfxBlacklist_Equal_DriverNew.js | 106 + .../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 | 69 + .../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 | 165 + .../rs-blocklist/test_gfxBlacklist_prefs.js | 125 + .../test/xpcshell/rs-blocklist/test_softblocked.js | 61 + .../test/xpcshell/rs-blocklist/xpcshell.ini | 66 + .../extensions/test/xpcshell/test_AbuseReporter.js | 903 ++++ .../test/xpcshell/test_AddonRepository.js | 316 ++ .../test/xpcshell/test_AddonRepository_cache.js | 711 +++ .../xpcshell/test_AddonRepository_langpacks.js | 135 + .../test/xpcshell/test_AddonRepository_paging.js | 91 + .../test/xpcshell/test_ProductAddonChecker.js | 292 ++ .../extensions/test/xpcshell/test_XPIStates.js | 132 + .../extensions/test/xpcshell/test_XPIcancel.js | 70 + .../extensions/test/xpcshell/test_addonStartup.js | 97 + .../test_addon_manager_telemetry_events.js | 788 ++++ .../test/xpcshell/test_amo_stats_telemetry.js | 102 + .../extensions/test/xpcshell/test_aom_startup.js | 187 + .../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 | 153 + .../extensions/test/xpcshell/test_cacheflush.js | 86 + .../extensions/test/xpcshell/test_childprocess.js | 20 + .../extensions/test/xpcshell/test_cookies.js | 102 + .../extensions/test/xpcshell/test_corrupt.js | 210 + .../test/xpcshell/test_crash_annotation_quoting.js | 25 + .../extensions/test/xpcshell/test_db_path.js | 69 + .../xpcshell/test_delay_update_webextension.js | 392 ++ .../extensions/test/xpcshell/test_dependencies.js | 140 + .../test/xpcshell/test_dictionary_webextension.js | 198 + .../extensions/test/xpcshell/test_distribution.js | 115 + .../test/xpcshell/test_duplicateplugins.js | 160 + .../test/xpcshell/test_embedderDisabled.js | 128 + .../mozapps/extensions/test/xpcshell/test_error.js | 78 + .../test/xpcshell/test_ext_management.js | 213 + .../extensions/test/xpcshell/test_filepointer.js | 327 ++ .../extensions/test/xpcshell/test_general.js | 59 + .../test/xpcshell/test_getInstallSourceFromHost.js | 42 + .../extensions/test/xpcshell/test_gmpProvider.js | 507 ++ .../extensions/test/xpcshell/test_harness.js | 13 + .../extensions/test/xpcshell/test_hidden.js | 58 + .../extensions/test/xpcshell/test_install.js | 1050 +++++ .../test/xpcshell/test_install_cancel.js | 92 + .../extensions/test/xpcshell/test_install_icons.js | 62 + .../extensions/test/xpcshell/test_isDebuggable.js | 21 + .../extensions/test/xpcshell/test_isReady.js | 71 + .../extensions/test/xpcshell/test_locale.js | 103 + .../test/xpcshell/test_moved_extension_metadata.js | 173 + .../extensions/test/xpcshell/test_no_addons.js | 81 + .../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 | 103 + .../extensions/test/xpcshell/test_pluginchange.js | 242 + .../test/xpcshell/test_pref_properties.js | 221 + .../test/xpcshell/test_provider_markSafe.js | 43 + .../test/xpcshell/test_provider_shutdown.js | 100 + .../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 | 336 ++ .../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 | 133 + .../test/xpcshell/test_shutdown_barriers.js | 71 + .../test/xpcshell/test_shutdown_early.js | 61 + .../test/xpcshell/test_sideload_scopes.js | 180 + .../extensions/test/xpcshell/test_sideloads.js | 117 + .../test/xpcshell/test_sideloads_after_rebuild.js | 137 + .../extensions/test/xpcshell/test_signed_inject.js | 429 ++ .../test/xpcshell/test_signed_install.js | 280 ++ .../test/xpcshell/test_signed_langpack.js | 60 + .../extensions/test/xpcshell/test_signed_long.js | 23 + .../test/xpcshell/test_signed_updatepref.js | 131 + .../extensions/test/xpcshell/test_signed_verify.js | 110 + .../extensions/test/xpcshell/test_startup.js | 648 +++ .../test/xpcshell/test_startup_enable.js | 47 + .../extensions/test/xpcshell/test_startup_scan.js | 125 + .../test/xpcshell/test_strictcompatibility.js | 152 + .../extensions/test/xpcshell/test_syncGUID.js | 117 + .../test/xpcshell/test_system_allowed.js | 54 + .../test/xpcshell/test_system_delay_update.js | 485 ++ .../test/xpcshell/test_system_profile_location.js | 208 + .../test/xpcshell/test_system_repository.js | 68 + .../extensions/test/xpcshell/test_system_reset.js | 535 +++ .../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 | 180 + .../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 | 415 ++ .../test/xpcshell/test_systemaddomstartupprefs.js | 55 + .../extensions/test/xpcshell/test_temporary.js | 774 +++ .../test/xpcshell/test_trash_directory.js | 39 + .../mozapps/extensions/test/xpcshell/test_types.js | 67 + .../extensions/test/xpcshell/test_undouninstall.js | 584 +++ .../extensions/test/xpcshell/test_update.js | 852 ++++ .../extensions/test/xpcshell/test_updateCancel.js | 139 + .../test/xpcshell/test_update_compatmode.js | 112 + .../test/xpcshell/test_update_ignorecompat.js | 100 + .../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 | 206 + .../extensions/test/xpcshell/test_updatecheck.js | 146 + .../test/xpcshell/test_updatecheck_errors.js | 52 + .../test/xpcshell/test_updatecheck_json.js | 379 ++ .../extensions/test/xpcshell/test_updateid.js | 80 + .../extensions/test/xpcshell/test_upgrade.js | 208 + .../test/xpcshell/test_upgrade_incompatible.js | 76 + .../extensions/test/xpcshell/test_webextension.js | 513 ++ .../test/xpcshell/test_webextension_events.js | 95 + .../test/xpcshell/test_webextension_icons.js | 212 + .../test/xpcshell/test_webextension_install.js | 665 +++ .../test_webextension_install_syntax_error.js | 42 + .../test/xpcshell/test_webextension_langpack.js | 573 +++ .../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 | 194 + .../mozapps/extensions/test/xpinstall/.eslintrc.js | 5 + .../extensions/test/xpinstall/amosigned.xpi | Bin 0 -> 4287 bytes .../extensions/test/xpinstall/authRedirect.sjs | 21 + .../mozapps/extensions/test/xpinstall/browser.ini | 90 + .../test/xpinstall/browser_amosigned_trigger.js | 83 + .../xpinstall/browser_amosigned_trigger_iframe.js | 74 + .../test/xpinstall/browser_amosigned_url.js | 47 + .../extensions/test/xpinstall/browser_auth.js | 65 + .../extensions/test/xpinstall/browser_auth2.js | 70 + .../extensions/test/xpinstall/browser_auth3.js | 69 + .../extensions/test/xpinstall/browser_auth4.js | 68 + .../extensions/test/xpinstall/browser_badargs.js | 46 + .../extensions/test/xpinstall/browser_badargs2.js | 52 + .../extensions/test/xpinstall/browser_badhash.js | 43 + .../test/xpinstall/browser_badhashtype.js | 43 + .../xpinstall/browser_block_fullscreen_prompt.js | 116 + .../extensions/test/xpinstall/browser_bug540558.js | 28 + .../extensions/test/xpinstall/browser_bug611242.js | 24 + .../extensions/test/xpinstall/browser_bug638292.js | 44 + .../extensions/test/xpinstall/browser_bug645699.js | 52 + .../xpinstall/browser_bug645699_postDownload.js | 52 + .../extensions/test/xpinstall/browser_bug672485.js | 60 + .../test/xpinstall/browser_containers.js | 113 + .../extensions/test/xpinstall/browser_cookies.js | 39 + .../extensions/test/xpinstall/browser_cookies2.js | 61 + .../extensions/test/xpinstall/browser_cookies3.js | 65 + .../extensions/test/xpinstall/browser_cookies4.js | 65 + .../extensions/test/xpinstall/browser_corrupt.js | 50 + .../extensions/test/xpinstall/browser_datauri.js | 75 + .../test/xpinstall/browser_doorhanger_installs.js | 1370 ++++++ .../extensions/test/xpinstall/browser_empty.js | 36 + .../extensions/test/xpinstall/browser_enabled.js | 30 + .../extensions/test/xpinstall/browser_enabled2.js | 38 + .../extensions/test/xpinstall/browser_enabled3.js | 60 + .../extensions/test/xpinstall/browser_hash.js | 44 + .../extensions/test/xpinstall/browser_hash2.js | 44 + .../extensions/test/xpinstall/browser_httphash.js | 52 + .../extensions/test/xpinstall/browser_httphash2.js | 49 + .../extensions/test/xpinstall/browser_httphash3.js | 49 + .../extensions/test/xpinstall/browser_httphash4.js | 46 + .../extensions/test/xpinstall/browser_httphash5.js | 50 + .../extensions/test/xpinstall/browser_httphash6.js | 104 + .../test/xpinstall/browser_installchrome.js | 33 + .../extensions/test/xpinstall/browser_localfile.js | 42 + .../test/xpinstall/browser_localfile2.js | 51 + .../test/xpinstall/browser_localfile3.js | 42 + .../test/xpinstall/browser_localfile4.js | 52 + .../xpinstall/browser_localfile4_postDownload.js | 51 + .../extensions/test/xpinstall/browser_newwindow.js | 74 + .../extensions/test/xpinstall/browser_offline.js | 68 + .../test/xpinstall/browser_privatebrowsing.js | 126 + .../extensions/test/xpinstall/browser_relative.js | 64 + .../test/xpinstall/browser_signed_trigger.js | 44 + .../test/xpinstall/browser_signed_url.js | 29 + .../test/xpinstall/browser_softwareupdate.js | 33 + .../test/xpinstall/browser_trigger_redirect.js | 42 + .../test/xpinstall/browser_unsigned_trigger.js | 65 + .../xpinstall/browser_unsigned_trigger_iframe.js | 74 + .../xpinstall/browser_unsigned_trigger_xorigin.js | 55 + .../test/xpinstall/browser_unsigned_url.js | 30 + .../extensions/test/xpinstall/browser_whitelist.js | 66 + .../extensions/test/xpinstall/bug540558.html | 24 + .../extensions/test/xpinstall/bug638292.html | 17 + .../extensions/test/xpinstall/bug645699.html | 32 + .../extensions/test/xpinstall/cookieRedirect.sjs | 24 + .../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 | 15 + toolkit/mozapps/extensions/test/xpinstall/head.js | 566 +++ .../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 | 45 + .../extensions/test/xpinstall/restartless.xpi | Bin 0 -> 4447 bytes .../extensions/test/xpinstall/slowinstall.sjs | 99 + .../test/xpinstall/startsoftwareupdate.html | 21 + .../extensions/test/xpinstall/triggerredirect.html | 37 + .../mozapps/extensions/test/xpinstall/unsigned.xpi | Bin 0 -> 286 bytes 503 files changed, 102904 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/blocklist.js create mode 100644 toolkit/mozapps/extensions/content/blocklist.xhtml create mode 100644 toolkit/mozapps/extensions/content/default-theme.svg create mode 100644 toolkit/mozapps/extensions/content/drag-drop-addon-installer.js create mode 100644 toolkit/mozapps/extensions/content/extensions.js create mode 100644 toolkit/mozapps/extensions/content/extensions.xhtml create mode 100644 toolkit/mozapps/extensions/content/firefox-alpenglow.svg create mode 100644 toolkit/mozapps/extensions/content/firefox-compact-dark.svg create mode 100644 toolkit/mozapps/extensions/content/firefox-compact-light.svg create mode 100644 toolkit/mozapps/extensions/content/message-bar.css create mode 100644 toolkit/mozapps/extensions/content/message-bar.js create mode 100644 toolkit/mozapps/extensions/content/named-deck.js create mode 100644 toolkit/mozapps/extensions/content/panel-item.css create mode 100644 toolkit/mozapps/extensions/content/panel-list.css 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/default-theme/icon.svg create mode 100644 toolkit/mozapps/extensions/default-theme/manifest.json 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/Content.js create mode 100644 toolkit/mozapps/extensions/internal/GMPProvider.jsm create mode 100644 toolkit/mozapps/extensions/internal/PluginProvider.jsm create mode 100644 toolkit/mozapps/extensions/internal/ProductAddonChecker.jsm 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/moz.build 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_bug523784.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_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_named_deck.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_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_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_panel_item_accesskey.js create mode 100644 toolkit/mozapps/extensions/test/browser/browser_panel_list_accessibility.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_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_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/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/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_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/blocklistchange/addon_change.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/blocklistchange/addon_update1.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/blocklistchange/addon_update2.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/blocklistchange/addon_update3.json create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/blocklistchange/app_update.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/blocklistchange/blocklist_update1.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/blocklistchange/blocklist_update2.xml create mode 100644 toolkit/mozapps/extensions/test/xpcshell/data/blocklistchange/manual_update.xml 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/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_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_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_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_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_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_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_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_duplicateplugins.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_install_cancel.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_install_icons.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_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_pluginchange.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_startup.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_startup_enable.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_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_compatmode.js create mode 100644 toolkit/mozapps/extensions/test/xpcshell/test_update_ignorecompat.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_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/.eslintrc.js 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_enabled2.js create mode 100644 toolkit/mozapps/extensions/test/xpinstall/browser_enabled3.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_signed_trigger.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/browser_whitelist.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 (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..d68e50cf7f --- /dev/null +++ b/toolkit/mozapps/extensions/AbuseReporter.jsm @@ -0,0 +1,672 @@ +/* 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.import( + "resource://gre/modules/XPCOMUtils.jsm" +); + +Cu.importGlobalProperties(["fetch"]); + +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"]; + +XPCOMUtils.defineLazyModuleGetters(this, { + AddonManager: "resource://gre/modules/AddonManager.jsm", + AMTelemetry: "resource://gre/modules/AddonManager.jsm", + AppConstants: "resource://gre/modules/AppConstants.jsm", + ClientID: "resource://gre/modules/ClientID.jsm", + Services: "resource://gre/modules/Services.jsm", +}); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "ABUSE_REPORT_URL", + PREF_ABUSE_REPORT_URL +); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "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; + }, + + /** + * 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 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) { + 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(`${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); + + 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: 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 AddonManager.SIGNEDSTATE_BROKEN: + data.addon_signature = "broken"; + break; + case AddonManager.SIGNEDSTATE_UNKNOWN: + data.addon_signature = "unknown"; + break; + case AddonManager.SIGNEDSTATE_MISSING: + data.addon_signature = "missing"; + break; + case AddonManager.SIGNEDSTATE_PRELIMINARY: + data.addon_signature = "preliminary"; + break; + case AddonManager.SIGNEDSTATE_SIGNED: + data.addon_signature = "signed"; + break; + case AddonManager.SIGNEDSTATE_SYSTEM: + data.addon_signature = "system"; + break; + case 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 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 { + 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; + 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(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..98b87ad128 --- /dev/null +++ b/toolkit/mozapps/extensions/AddonContentPolicy.cpp @@ -0,0 +1,483 @@ +/* -*- 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/dom/Document.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; + +/* 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 object-src directives. + */ + +#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, object-src, and + * worker-src directives may only be the following: + * - self + * - none + * - Any localhost source, (http://localhost, http://127.0.0.1, or any port + * on those domains) + */ +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), + 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); + if (aDirectiveRequired) { + FormatError("csp.error.missing-directive"); + } + } + + // Visitors + + bool visitSchemeSrc(const nsCSPSchemeSrc& src) override { + nsAutoString scheme; + src.getScheme(scheme); + + if (SchemeInList(scheme, allowedHostSchemes)) { + FormatError("csp.error.missing-host", scheme); + return false; + } + if (!SchemeInList(scheme, allowedSchemes)) { + FormatError("csp.error.illegal-protocol", 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", 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", scheme); + return false; + } + if (!HostIsAllowed(host)) { + FormatError("csp.error.illegal-host-wildcard", 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", scheme); + return false; + } + } else if (!SchemeInList(scheme, allowedSchemes)) { + FormatError("csp.error.illegal-protocol", scheme); + return false; + } + + return true; + }; + + bool visitKeywordSrc(const nsCSPKeywordSrc& src) override { + switch (src.getKeyword()) { + case CSP_NONE: + case CSP_SELF: + return true; + 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", + nsDependentString(CSP_EnumToUTF16Keyword(src.getKeyword()))); + return false; + } + }; + + bool visitNonceSrc(const nsCSPNonceSrc& src) override { + FormatError("csp.error.illegal-keyword", u"'nonce-*'"_ns); + return false; + }; + + bool visitHashSrc(const nsCSPHashSrc& src) override { return true; }; + + // Accessors + + inline nsAString& GetError() { return mError; }; + + inline bool FoundSelf() { return mFoundSelf; }; + + // Formatters + + template + inline void FormatError(const char* aName, const T... aParams) { + AutoTArray params = {mDirective, + aParams...}; + FormatErrorParams(aName, params); + }; + + 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; + }; + + // Formatters + + already_AddRefed GetStringBundle() { + nsCOMPtr sbs = + mozilla::services::GetStringBundleService(); + NS_ENSURE_TRUE(sbs, nullptr); + + nsCOMPtr stringBundle; + sbs->CreateBundle("chrome://global/locale/extensions.properties", + getter_AddRefs(stringBundle)); + + return stringBundle.forget(); + }; + + void FormatErrorParams(const char* aName, const nsTArray& aParams) { + nsresult rv = NS_ERROR_FAILURE; + + nsCOMPtr stringBundle = GetStringBundle(); + + if (stringBundle) { + rv = stringBundle->FormatStringFromName(aName, aParams, mError); + } + + if (NS_WARN_IF(NS_FAILED(rv))) { + mError.AssignLiteral("An unexpected error occurred"); + } + }; + + // Data members + + nsAutoString mURL; + NS_ConvertASCIItoUTF16 mDirective; + nsString mError; + + uint32_t mPermittedPolicy; + bool mFoundSelf; +}; + +/** + * Validates a custom content security policy string for use by an add-on. + * In particular, ensures that: + * + * - Both object-src and script-src directives are present, and meet + * 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 = services::GetUUIDGenerator(); + 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", u"'self'"_ns); + aResult.Assign(validator.GetError()); + } + hasValidScriptSrc = true; + } + + if (aResult.IsVoid()) { + CSPDirective directive = nsIContentSecurityPolicy::OBJECT_SRC_DIRECTIVE; + CSPValidator validator(url, directive, !haveValidDefaultSrc, + aPermittedPolicy); + + if (!policy->visitDirectiveSrcs(directive, &validator)) { + aResult.Assign(validator.GetError()); + } + } + + 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..726819a254 --- /dev/null +++ b/toolkit/mozapps/extensions/AddonManager.jsm @@ -0,0 +1,4918 @@ +/* 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.import( + "resource://gre/modules/AppConstants.jsm" +); + +const MOZ_COMPATIBILITY_NIGHTLY = ![ + "aurora", + "beta", + "release", + "esr", +].includes(AppConstants.MOZ_UPDATE_CHANNEL); + +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_MIN_WEBEXT_PLATFORM_VERSION = + "extensions.webExtensionsMinPlatformVersion"; +const PREF_WEBAPI_TESTING = "extensions.webapi.testing"; +const PREF_WEBEXT_PERM_PROMPTS = "extensions.webextPermissionPrompts"; +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 VALID_TYPES_REGEXP = /^[\w\-]+$/; + +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 { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +// This global is overridden by xpcshell tests, and therefore cannot be +// a const. +var { AsyncShutdown } = ChromeUtils.import( + "resource://gre/modules/AsyncShutdown.jsm" +); + +XPCOMUtils.defineLazyGlobalGetters(this, ["Element"]); + +XPCOMUtils.defineLazyModuleGetters(this, { + AddonRepository: "resource://gre/modules/addons/AddonRepository.jsm", + AbuseReporter: "resource://gre/modules/AbuseReporter.jsm", + Extension: "resource://gre/modules/Extension.jsm", +}); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "WEBEXT_PERMISSION_PROMPTS", + PREF_WEBEXT_PERM_PROMPTS, + false +); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "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"]; + +const CATEGORY_PROVIDER_MODULE = "addon-provider-module"; + +// A list of providers to load by default +const DEFAULT_PROVIDERS = ["resource://gre/modules/addons/XPIProvider.jsm"]; + +const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); +// 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; +} + +/** + * 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 || ""; + }, +}; + +/** + * A type of add-on, used by the UI to determine how to display different types + * of add-ons. + * + * @param aID + * The add-on type ID + * @param aLocaleURI + * The URI of a localized properties file to get the displayable name + * for the type from + * @param aLocaleKey + * The key for the string in the properties file. + * @param aViewType + * The optional type of view to use in the UI + * @param aUIPriority + * The priority is used by the UI to list the types in order. Lower + * values push the type higher in the list. + * @param aFlags + * An option set of flags that customize the display of the add-on in + * the UI. + */ +function AddonType( + aID, + aLocaleURI, + aLocaleKey, + aViewType, + aUIPriority, + aFlags +) { + if (!aID) { + throw Components.Exception( + "An AddonType must have an ID", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (aViewType && aUIPriority === undefined) { + throw Components.Exception( + "An AddonType with a defined view must have a set UI priority", + Cr.NS_ERROR_INVALID_ARG + ); + } + + if (!aLocaleKey) { + throw Components.Exception( + "An AddonType must have a displayable name", + Cr.NS_ERROR_INVALID_ARG + ); + } + + this.id = aID; + this.uiPriority = aUIPriority; + this.viewType = aViewType; + this.flags = aFlags; + + if (aLocaleURI) { + XPCOMUtils.defineLazyGetter(this, "name", () => { + let bundle = Services.strings.createBundle(aLocaleURI); + return bundle.GetStringFromName(aLocaleKey); + }); + } else { + this.name = aLocaleKey; + } +} + +var gStarted = false; +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; + +/** + * 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(), + typeListeners: new Set(), + pendingProviders: new Set(), + providers: new Set(), + providerShutdowns: new Map(), + types: {}, + startupChanges: {}, + // Store telemetry details per addon provider + telemetryDetails: {}, + upgradeListeners: new Map(), + externalExtensionLoaders: new Map(), + + recordTimestamp(name, value) { + this.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(); + + // 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); + + // Ensure all default providers have had a chance to register themselves + for (let url of DEFAULT_PROVIDERS) { + try { + let scope = {}; + ChromeUtils.import(url, scope); + // Sanity check - make sure the provider exports a symbol that + // has a 'startup' method + let syms = Object.keys(scope); + if (syms.length < 1 || typeof scope[syms[0]].startup != "function") { + logger.warn("Provider " + url + " has no startup()"); + AddonManagerPrivate.recordException( + "AMI", + "provider " + url, + "no startup()" + ); + } + logger.debug( + "Loaded provider scope for " + + url + + ": " + + Object.keys(scope).toSource() + ); + } catch (e) { + AddonManagerPrivate.recordException( + "AMI", + "provider " + url + " load failed", + e + ); + logger.error('Exception loading default provider "' + url + '"', e); + } + } + + // Load any providers registered in the category manager + for (let { entry, value: url } of Services.catMan.enumerateCategory( + CATEGORY_PROVIDER_MODULE + )) { + try { + ChromeUtils.import(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; + this.recordTimestamp("AMI_startup_end"); + } catch (e) { + logger.error("startup failed", e); + AddonManagerPrivate.recordException("AMI", "startup failed", e); + } + + 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) { + for (let type of aTypes) { + if (!(type.id in this.types)) { + if (!VALID_TYPES_REGEXP.test(type.id)) { + logger.warn("Ignoring invalid type " + type.id); + return; + } + + this.types[type.id] = { + type, + providers: [aProvider], + }; + + let typeListeners = new Set(this.typeListeners); + for (let listener of typeListeners) { + safeCall(() => listener.onTypeAdded(type)); + } + } else { + this.types[type.id].providers.push(aProvider); + } + } + } + + // 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); + + for (let type in this.types) { + this.types[type].providers = this.types[type].providers.filter( + p => p != aProvider + ); + if (!this.types[type].providers.length) { + let oldType = this.types[type].type; + delete this.types[type]; + + let typeListeners = new Set(this.typeListeners); + for (let listener of typeListeners) { + safeCall(() => listener.onTypeRemoved(oldType)); + } + } + } + + // 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 + * @see callProvider + */ + 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"); + + 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); + + 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 + ); + } + } + + // Shut down AddonRepository after providers (if any). + try { + gRepoShutdownState = "in progress"; + await 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.typeListeners.clear(); + this.providerShutdowns.clear(); + for (let type in this.startupChanges) { + delete this.startupChanges[type]; + } + gStarted = false; + gStartupComplete = false; + gFinalShutdownBarrier = null; + gBeforeShutdownBarrier = null; + gShutdownInProgress = false; + if (savedError) { + throw savedError; + } + }, + + /** + * Notified when a preference we're interested in has changed. + * + * @see nsIObserver + */ + observe(aSubject, aTopic, aData) { + 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; + } + } + }, + + /** + * 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 = 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 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 ( + aAddon.permissions & AddonManager.PERM_CAN_UPGRADE && + 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}`); + if (WEBEXT_PERMISSION_PROMPTS) { + aInstall.promptHandler = (...args) => + AddonManagerInternal._updatePromptHandler(...args); + } + aInstall.install(); + } + }, + + onUpdateFinished: aAddon => { + logger.debug("onUpdateFinished for ${id}", aAddon); + resolve(); + }, + }, + AddonManager.UPDATE_WHEN_PERIODIC_UPDATE + ); + }) + ); + } + 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; + })(); + }, + + /** + * 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 (WEBEXT_PERMISSION_PROMPTS && !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 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 + */ + installAddonFromWebpage(aMimetype, aBrowser, aInstallingPrincipal, aInstall) { + 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 ( + 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) + ))) || + !this.isInstallAllowedByPolicy( + aInstallingPrincipal, + aInstall, + false /* explicit */ + ) + ) { + 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 (!WEBEXT_POSTDOWNLOAD_THIRD_PARTY) { + // Block with prompt + this.installNotifyObservers( + "addon-install-blocked", + topBrowser, + aInstallingPrincipal.URI, + aInstall, + () => startInstall("other") + ); + } else { + // We download the addon and validate recommended states prior to + // showing the third party install panel. + 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-origin-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); + }, + + /** + * Adds a new TypeListener if the listener is not already registered. + * + * @param {TypeListener} aListener + * The TypeListener to add + */ + addTypeListener(aListener) { + if (!aListener || typeof aListener != "object") { + throw Components.Exception( + "aListener must be a TypeListener object", + Cr.NS_ERROR_INVALID_ARG + ); + } + + this.typeListeners.add(aListener); + }, + + /** + * Removes an TypeListener if the listener is registered. + * + * @param aListener + * The TypeListener to remove + */ + removeTypeListener(aListener) { + if (!aListener || typeof aListener != "object") { + throw Components.Exception( + "aListener must be a TypeListener object", + Cr.NS_ERROR_INVALID_ARG + ); + } + + this.typeListeners.delete(aListener); + }, + + get addonTypes() { + // A read-only wrapper around the types dictionary + return new Proxy(this.types, { + defineProperty(target, property, descriptor) { + // Not allowed to define properties + return false; + }, + + deleteProperty(target, property) { + // Not allowed to delete properties + return false; + }, + + get(target, property, receiver) { + if (!target.hasOwnProperty(property)) { + return undefined; + } + + return target[property].type; + }, + + getOwnPropertyDescriptor(target, property) { + if (!target.hasOwnProperty(property)) { + return undefined; + } + + return { + value: target[property].type, + writable: false, + // Claim configurability to maintain the proxy invariants. + configurable: true, + enumerable: true, + }; + }, + + preventExtensions(target) { + // Not allowed to prevent adding new properties + return false; + }, + + set(target, property, value, receiver) { + // Not allowed to set properties + return false; + }, + + setPrototypeOf(target, prototype) { + // Not allowed to change prototype + return false; + }, + }); + }, + + get autoUpdateDefault() { + return gAutoUpdateDefault; + }, + + set autoUpdateDefault(aValue) { + aValue = !!aValue; + if (aValue != gAutoUpdateDefault) { + Services.prefs.setBoolPref(PREF_EM_AUTOUPDATE_DEFAULT, aValue); + } + return 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); + } + } + return aValue; + }, + + get strictCompatibility() { + return gStrictCompatibility; + }, + + set strictCompatibility(aValue) { + aValue = !!aValue; + if (aValue != gStrictCompatibility) { + Services.prefs.setBoolPref(PREF_EM_STRICT_COMPATIBILITY, aValue); + } + return 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); + } + } + return aValue; + }, + + get updateEnabled() { + return gUpdateEnabled; + }, + + set updateEnabled(aValue) { + aValue = !!aValue; + if (aValue != gUpdateEnabled) { + Services.prefs.setBoolPref(PREF_EM_UPDATE_ENABLED, aValue); + } + return aValue; + }, + + _verifyThirdPartyInstall(browser, url, install, info, source) { + // If this is an install from a recognized source, or it is a recommended addon, we + // skip the third party panel. The source param was generated based on the installing + // principal and checking against site permissions and enterprise policy, so we + // can rely on that rather than re-validating against that principal. + if ( + !WEBEXT_POSTDOWNLOAD_THIRD_PARTY || + ["AMO", "local"].includes(source) || + 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) => { + let reject = () => { + this.installNotifyObservers( + "addon-install-cancelled", + browser, + url, + install + ); + _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 && WEBEXT_PERMISSION_PROMPTS) { + 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 (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 checkInstallUrl(url) { + let host = Services.io.newURI(options.url).host; + if (WEBAPI_INSTALL_HOSTS.includes(host)) { + return; + } + if ( + Services.prefs.getBoolPref(PREF_WEBAPI_TESTING) && + WEBAPI_TEST_INSTALL_HOSTS.includes(host) + ) { + return; + } + + throw new Error(`Install from ${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 }; + }; + + try { + checkInstallUrl(options.url); + } catch (err) { + return Promise.reject({ message: err.message }); + } + + 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(); + } + + if (Services.prefs.getBoolPref(PREF_WEBEXT_PERM_PROMPTS, false)) { + 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 = AbuseReporter.getOpenDialog(); + if (existingDialog) { + existingDialog.close(); + } + + const dialog = await 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); + }, + + 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) { + 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, + + AddonType, + + get BOOTSTRAP_REASONS() { + return AddonManagerInternal._getProviderByName("XPIProvider") + .BOOTSTRAP_REASONS; + }, + + 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; + }, +}; + +/** + * 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. + // These will show up as AddonManager.ERROR_* (eg, ERROR_NETWORK_FAILURE) + _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], + // The downloaded add-on had a different type than expected. + ["ERROR_UNEXPECTED_ADDON_TYPE", -6], + // The addon did not have the expected ID + ["ERROR_INCORRECT_ID", -7], + ]), + // 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 optionally enabled + // on a case-by-case basis. + PERM_CAN_ASK_TO_ACTIVATE: 16, + // 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, + + // Add-on type is expected to be displayed in the UI in a list. + VIEW_TYPE_LIST: "list", + + // Constants describing how add-on types behave. + + // If no add-ons of a type are installed, then the category for that add-on + // type should be hidden in the UI. + TYPE_UI_HIDE_EMPTY: 16, + // Indicates that this add-on type supports the ask-to-activate state. + // That is, add-ons of this type can be set to be optionally enabled + // on a case-by-case basis. + TYPE_SUPPORTS_ASK_TO_ACTIVATE: 32, + // The add-on type natively supports undo for restartless uninstalls. + // If this flag is not specified, the UI is expected to handle this via + // disabling the add-on, and performing the actual uninstall at a later time. + TYPE_SUPPORTS_UNDO_RESTARTLESS_UNINSTALL: 64, + + // 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, + + // Constants for the Addon.userDisabled property + // Indicates that the userDisabled state of this add-on is currently + // ask-to-activate. That is, it can be conditionally enabled on a + // case-by-case basis. + STATE_ASK_TO_ACTIVATE: "askToActivate", + + get __AddonManagerInternal__() { + return AppConstants.DEBUG ? AddonManagerInternal : undefined; + }, + + /** Boolean indicating whether AddonManager startup has completed. */ + get isReady() { + return gStartupComplete && !gShutdownInProgress; + }, + + /** @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); + }, + + installAddonFromWebpage(aType, aBrowser, aInstallingPrincipal, aInstall) { + AddonManagerInternal.installAddonFromWebpage( + aType, + aBrowser, + aInstallingPrincipal, + aInstall + ); + }, + + 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(types, loader) { + return AddonManagerInternal.addExternalExtensionLoader(types, loader); + }, + + addAddonListener(aListener) { + AddonManagerInternal.addAddonListener(aListener); + }, + + removeAddonListener(aListener) { + AddonManagerInternal.removeAddonListener(aListener); + }, + + addTypeListener(aListener) { + AddonManagerInternal.addTypeListener(aListener); + }, + + removeTypeListener(aListener) { + AddonManagerInternal.removeTypeListener(aListener); + }, + + get addonTypes() { + return AddonManagerInternal.addonTypes; + }, + + /** + * 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.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; + }, +}; + +/** + * 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 (e.g. the telemetry + // events for the extension migrated to the private browsing permission). + 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": + return addonType; + default: + // Currently this should only include plugins and gmp-plugins + 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), + }; + } + + 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 === "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 }; + 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. + */ + recordViewEvent({ view, addon, type }) { + this.recordEvent({ + method: "view", + object: "aboutAddons", + value: view, + extra: this.formatExtraVars({ type, addon }), + }); + }, + + /** + * 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); + +// load the timestamps module into AddonManagerInternal +ChromeUtils.import( + "resource://gre/modules/TelemetryTimestamps.jsm", + AddonManagerInternal +); +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..876b03cdbf --- /dev/null +++ b/toolkit/mozapps/extensions/AddonManagerStartup-inlines.h @@ -0,0 +1,226 @@ +/* -*- 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 "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::HandleObject 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::HandleObject 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::RootedValue 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::HandleObject 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::MutableHandleValue 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::HandleObject 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::MutableHandleValue 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..04b8321938 --- /dev/null +++ b/toolkit/mozapps/extensions/AddonManagerStartup.cpp @@ -0,0 +1,876 @@ +/* -*- 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/JSON.h" +#include "js/TracingAPI.h" +#include "xpcpublic.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/Services.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 "nsIAppStartup.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::MutableHandleValue result) { + NS_ConvertUTF8toUTF16 str(jsonData); + jsonData.Truncate(); + + return JS_ParseJSON(cx, str.Data(), str.Length(), result); +} + +static Result, nsresult> GetJarCache() { + nsCOMPtr ios = services::GetIOService(); + 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::RootedObject 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::RootedObject obj(mCx, mObject); + + JS::RootedValue 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::RootedObject obj(mCx, mObject); + + JS::RootedValue 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::RootedObject obj(mCx, mObject); + + JS::RootedValue 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::RootedObject obj(mCx, mObject); + + JS::RootedValue 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::RootedObject obj(mCx, mObject); + + JS::RootedValue 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::RootedObject 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::RootedObject obj(mCx, mObject); + + bool result; + if (NS_FAILED(file->Exists(&result)) || !result) { + JS::RootedValue 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::RootedValue 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::MutableHandleValue 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::RootedObject 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::HandleValue value, JSContext* cx, + JS::MutableHandleValue 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::RootedObject obj(cx); + MOZ_TRY(nsContentUtils::CreateArrayBuffer(cx, lz4, &obj.get())); + + result.set(JS::ObjectValue(*obj)); + return NS_OK; +} + +nsresult AddonManagerStartup::DecodeBlob(JS::HandleValue value, JSContext* cx, + JS::MutableHandleValue 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; + + nsDependentCSubstring lz4( + reinterpret_cast(JS::GetArrayBufferData(obj, &isShared, nogc)), + JS::GetArrayBufferByteLength(obj)); + + 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. + nsCOMPtr appStartup = components::AppStartup::Service(); + if (!appStartup || appStartup->GetShuttingDown()) { + 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::HandleValue locations, JSContext* cx, + nsIJSRAIIHelper** result) { + auto IsArray = [cx](JS::HandleValue 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::RootedObject locs(cx, &locations.toObject()); + JS::RootedValue arrayVal(cx); + JS::RootedObject 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..9d619bbd87 --- /dev/null +++ b/toolkit/mozapps/extensions/AddonManagerWebAPI.cpp @@ -0,0 +1,157 @@ +/* -*- 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 "nsGlobalWindow.h" +#include "xpcpublic.h" + +#include "nsIDocShell.h" +#include "nsIScriptObjectPrincipal.h" + +namespace mozilla { +using namespace mozilla::dom; + +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 (Preferences::GetBool( + "privacy.resistFingerprinting.block_mozAddonManager")) { + return false; + } + + if (host.EqualsLiteral("addons.mozilla.org")) { + return true; + } + + // When testing allow access to the developer sites. + if (Preferences::GetBool("extensions.webapi.testing", false)) { + if (host.LowerCaseEqualsLiteral("addons.allizom.org") || + host.LowerCaseEqualsLiteral("addons-dev.allizom.org") || + 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() && + Preferences::GetBool("extensions.webapi.testing.http", false))) { + 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..d8301ceb8b --- /dev/null +++ b/toolkit/mozapps/extensions/Blocklist.jsm @@ -0,0 +1,1898 @@ +/* -*- 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"]; + +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { AppConstants } = ChromeUtils.import( + "resource://gre/modules/AppConstants.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "AddonManager", + "resource://gre/modules/AddonManager.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "AddonManagerPrivate", + "resource://gre/modules/AddonManager.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "RemoteSettings", + "resource://services-settings/remote-settings.js" +); +ChromeUtils.defineModuleGetter( + this, + "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; + +// 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_SUPPRESSUI = "extensions.blocklist.suppressUI"; +const PREF_BLOCKLIST_USE_MLBF = "extensions.blocklist.useMLBF"; +const PREF_BLOCKLIST_USE_MLBF_STASHES = "extensions.blocklist.useMLBF.stashes"; +const PREF_EM_LOGGING_ENABLED = "extensions.logging.enabled"; +const URI_BLOCKLIST_DIALOG = + "chrome://mozapps/content/extensions/blocklist.xhtml"; +const DEFAULT_SEVERITY = 3; +const DEFAULT_LEVEL = 2; +const MAX_BLOCK_LEVEL = 3; +const SEVERITY_OUTDATED = 0; +const VULNERABILITYSTATUS_NONE = 0; +const VULNERABILITYSTATUS_UPDATE_AVAILABLE = 1; +const VULNERABILITYSTATUS_NO_UPDATE = 2; + +// Remote Settings blocklist constants +const PREF_BLOCKLIST_BUCKET = "services.blocklist.bucket"; +const PREF_BLOCKLIST_GFX_COLLECTION = "services.blocklist.gfx.collection"; +const PREF_BLOCKLIST_GFX_CHECKED_SECONDS = "services.blocklist.gfx.checked"; +const PREF_BLOCKLIST_GFX_SIGNER = "services.blocklist.gfx.signer"; +const PREF_BLOCKLIST_PLUGINS_COLLECTION = + "services.blocklist.plugins.collection"; +const PREF_BLOCKLIST_PLUGINS_CHECKED_SECONDS = + "services.blocklist.plugins.checked"; +const PREF_BLOCKLIST_PLUGINS_SIGNER = "services.blocklist.plugins.signer"; +// Blocklist v2 - legacy JSON format. +const PREF_BLOCKLIST_ADDONS_COLLECTION = "services.blocklist.addons.collection"; +const PREF_BLOCKLIST_ADDONS_CHECKED_SECONDS = + "services.blocklist.addons.checked"; +const PREF_BLOCKLIST_ADDONS_SIGNER = "services.blocklist.addons.signer"; +// Blocklist v3 - MLBF format. +const PREF_BLOCKLIST_ADDONS3_COLLECTION = + "services.blocklist.addons-mlbf.collection"; +const PREF_BLOCKLIST_ADDONS3_CHECKED_SECONDS = + "services.blocklist.addons-mlbf.checked"; +const PREF_BLOCKLIST_ADDONS3_SIGNER = "services.blocklist.addons-mlbf.signer"; + +const BlocklistTelemetry = { + /** + * 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 (one of "addons" or "plugins", + * 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"); + } + }, +}; + +this.BlocklistTelemetry = BlocklistTelemetry; + +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(gAppOS)) { + return false; + } + } + + if (item.xpcomabi) { + let xpcomabi = item.xpcomabi.split(","); + if (!xpcomabi.includes(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 == 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 valid severity and vulnerabilityStatus properties, + * 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 (!vr.hasOwnProperty("vulnerabilityStatus")) { + vr.vulnerabilityStatus = VULNERABILITYSTATUS_NONE; + } + + 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 = 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 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(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 == gAppID && + Services.vc.compare(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. + * + * Note: we assign to the global to allow tests to reach the object directly. + */ +this.GfxBlocklistRS = { + _ensureInitialized() { + if (this._initialized || !gBlocklistEnabled) { + return; + } + this._initialized = true; + this._client = RemoteSettings( + Services.prefs.getCharPref(PREF_BLOCKLIST_GFX_COLLECTION), + { + bucketNamePref: PREF_BLOCKLIST_BUCKET, + lastCheckTimePref: PREF_BLOCKLIST_GFX_CHECKED_SECONDS, + signerName: Services.prefs.getCharPref(PREF_BLOCKLIST_GFX_SIGNER), + 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 plugins blocklist implementation. The JSON objects for plugin blocks look + * something like: + * + * { + * "blockID":"p906", + * "details": { + * "bug":"https://bugzilla.mozilla.org/show_bug.cgi?id=1159917", + * "who":"Which users it affects", + * "why":"Why it's being blocklisted", + * "name":"Java Plugin 7 update 45 to 78 (click-to-play), Windows", + * "created":"2015-05-19T09:02:45Z" + * }, + * "enabled":true, + * "infoURL":"https://java.com/", + * "matchName":"Java\\(TM\\) Platform SE 7 U(4[5-9]|(5|6)\\d|7[0-8])(\\s[^\\d\\._U]|$)", + * "versionRange":[ + * { + * "severity":0, + * "targetApplication":[ + * { + * "guid":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}", + * "maxVersion":"57.0.*", + * "minVersion":"0" + * } + * ], + * "vulnerabilityStatus":1 + * } + * ], + * "matchFilename":"npjp2\\.dll", + * "id":"f254e5bc-12c7-7954-fe6b-8f1fdab0ae88", + * "last_modified":1519390914542, + * } + * + * Note: we assign to the global to allow tests to reach the object directly. + */ +this.PluginBlocklistRS = { + _matchProps: { + matchDescription: "description", + matchFilename: "filename", + matchName: "name", + }, + + async _ensureEntries() { + await this.ensureInitialized(); + if (!this._entries && gBlocklistEnabled) { + await this._updateEntries(); + + // Dispatch to mainthread because consumers may try to construct nsIPluginHost + // again based on this notification, while we were called from nsIPluginHost + // anyway, leading to re-entrancy. + Services.tm.dispatchToMainThread(function() { + Services.obs.notifyObservers(null, "plugin-blocklist-loaded"); + }); + } + }, + + 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 = {}; + for (let k of Object.keys(this._matchProps)) { + if (entry[k]) { + try { + entry.matches[this._matchProps[k]] = new RegExp(entry[k], "m"); + } catch (ex) { + /* Ignore invalid regexes */ + } + } + } + Utils.ensureVersionRangeIsSane(entry); + }); + + BlocklistTelemetry.recordRSBlocklistLastModified("plugins", this._client); + }, + + async _filterItem(entry, environment) { + if (!(await targetAppFilter(entry, environment))) { + return null; + } + if (!Utils.matchesOSABI(entry)) { + return null; + } + if (!entry.matchFilename && !entry.matchName && !entry.matchDescription) { + let blockID = entry.blockID || entry.id; + Cu.reportError(new Error(`Nothing to filter plugin item ${blockID}`)); + return null; + } + return entry; + }, + + sync() { + this.ensureInitialized(); + return this._client.sync(); + }, + + ensureInitialized() { + if (!gBlocklistEnabled || this._initialized) { + return; + } + this._initialized = true; + this._client = RemoteSettings( + Services.prefs.getCharPref(PREF_BLOCKLIST_PLUGINS_COLLECTION), + { + bucketNamePref: PREF_BLOCKLIST_BUCKET, + lastCheckTimePref: PREF_BLOCKLIST_PLUGINS_CHECKED_SECONDS, + signerName: Services.prefs.getCharPref(PREF_BLOCKLIST_PLUGINS_SIGNER), + 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); + } + }, + + async _onUpdate() { + let oldEntries = this._entries || []; + this.ensureInitialized(); + await this._updateEntries(); + const pluginHost = Cc["@mozilla.org/plugin/host;1"].getService( + Ci.nsIPluginHost + ); + const plugins = pluginHost.getPluginTags(); + + let blockedItems = []; + + for (let plugin of plugins) { + let oldState = this._getState(plugin, oldEntries); + let state = this._getState(plugin, this._entries); + LOG( + "Blocklist state for " + + plugin.name + + " changed from " + + oldState + + " to " + + state + ); + // We don't want to re-warn about items + if (state == oldState) { + continue; + } + + if (oldState == Ci.nsIBlocklistService.STATE_BLOCKED) { + if (state == Ci.nsIBlocklistService.STATE_SOFTBLOCKED) { + plugin.enabledState = Ci.nsIPluginTag.STATE_DISABLED; + } + } else if ( + !plugin.disabled && + state != Ci.nsIBlocklistService.STATE_NOT_BLOCKED + ) { + if ( + state != Ci.nsIBlocklistService.STATE_OUTDATED && + state != Ci.nsIBlocklistService.STATE_VULNERABLE_UPDATE_AVAILABLE && + state != Ci.nsIBlocklistService.STATE_VULNERABLE_NO_UPDATE + ) { + blockedItems.push({ + name: plugin.name, + version: plugin.version, + icon: "chrome://mozapps/skin/plugins/plugin.svg", + disable: false, + blocked: state == Ci.nsIBlocklistService.STATE_BLOCKED, + item: plugin, + url: await this.getURL(plugin), + }); + } + } + } + + if (blockedItems.length) { + this._showBlockedPluginsPrompt(blockedItems); + } else { + this._notifyUpdate(); + } + }, + + _showBlockedPluginsPrompt(blockedPlugins) { + let args = { + restart: false, + list: blockedPlugins, + }; + // This lets the dialog get the raw js object + args.wrappedJSObject = args; + + /* + Some tests run without UI, so the async code listens to a message + that can be sent programatically + */ + let applyBlocklistChanges = async () => { + Services.obs.removeObserver( + applyBlocklistChanges, + "addon-blocklist-closed" + ); + + for (let blockedData of blockedPlugins) { + if (!blockedData.disable) { + continue; + } + + // This will disable all the plugins immediately. + if (blockedData.item instanceof Ci.nsIPluginTag) { + blockedData.item.enabledState = Ci.nsIPluginTag.STATE_DISABLED; + } + } + + if (!args.restart) { + this._notifyUpdate(); + return; + } + + // We need to ensure the new blocklist state is written to disk before restarting. + // We'll notify about the blocklist update, then wait for nsIPluginHost + // to finish processing it, then restart the browser. + let pluginUpdatesFinishedPromise = new Promise(resolve => { + Services.obs.addObserver(function updatesFinished() { + Services.obs.removeObserver( + updatesFinished, + "plugin-blocklist-updates-finished" + ); + resolve(); + }, "plugin-blocklist-updates-finished"); + }); + this._notifyUpdate(); + await pluginUpdatesFinishedPromise; + + // Notify all windows that an application quit has been requested. + var cancelQuit = Cc["@mozilla.org/supports-PRBool;1"].createInstance( + Ci.nsISupportsPRBool + ); + Services.obs.notifyObservers(cancelQuit, "quit-application-requested"); + + // Something aborted the quit process. + if (cancelQuit.data) { + return; + } + + Services.startup.quit( + Ci.nsIAppStartup.eRestart | Ci.nsIAppStartup.eAttemptQuit + ); + }; + + Services.obs.addObserver(applyBlocklistChanges, "addon-blocklist-closed"); + + if (Services.prefs.getBoolPref(PREF_BLOCKLIST_SUPPRESSUI, false)) { + applyBlocklistChanges(); + return; + } + + function blocklistUnloadHandler(event) { + if (event.target.location == URI_BLOCKLIST_DIALOG) { + applyBlocklistChanges(); + blocklistWindow.removeEventListener("unload", blocklistUnloadHandler); + } + } + + let blocklistWindow = Services.ww.openWindow( + null, + URI_BLOCKLIST_DIALOG, + "", + "chrome,centerscreen,dialog,titlebar", + args + ); + if (blocklistWindow) { + blocklistWindow.addEventListener("unload", blocklistUnloadHandler); + } + }, + + _notifyUpdate() { + Services.obs.notifyObservers(null, "plugin-blocklist-updated"); + }, + + async getURL(plugin) { + await this._ensureEntries(); + let r = this._getEntry(plugin, this._entries); + if (!r) { + return null; + } + let blockEntry = r.entry; + let blockID = blockEntry.blockID || blockEntry.id; + return blockEntry.infoURL || Utils._createBlocklistURL(blockID); + }, + + async getState(plugin, appVersion, toolkitVersion) { + if (AppConstants.platform == "android") { + return Ci.nsIBlocklistService.STATE_NOT_BLOCKED; + } + await this._ensureEntries(); + return this._getState(plugin, this._entries, appVersion, toolkitVersion); + }, + + /** + * Private helper to get the blocklist entry for a plugin given a set of + * blocklist entries and versions. + * + * @param {nsIPluginTag} plugin + * The nsIPluginTag to get the blocklist state for. + * @param {object[]} pluginEntries + * The plugin blocklist entries to compare against. + * @param {string?} appVersion + * The application version to compare to, will use the current + * version if null. + * @param {string?} toolkitVersion + * The toolkit version to compare to, will use the current version if + * null. + * @returns {object?} + * {entry: blocklistEntry, version: blocklistEntryVersion}, + * or null if there is no matching entry. + */ + _getEntry(plugin, pluginEntries, appVersion, toolkitVersion) { + if (!gBlocklistEnabled) { + return null; + } + + // Not all applications implement nsIXULAppInfo (e.g. xpcshell doesn't). + if (!appVersion && !gApp.version) { + return Ci.nsIBlocklistService.STATE_NOT_BLOCKED; + } + + if (!appVersion) { + appVersion = gApp.version; + } + if (!toolkitVersion) { + toolkitVersion = gApp.platformVersion; + } + + const pluginProperties = { + description: plugin.description, + filename: plugin.filename, + name: plugin.name, + version: plugin.version, + }; + if (!pluginEntries) { + Cu.reportError( + new Error("There are no plugin entries. This should never happen.") + ); + } + for (let blockEntry of pluginEntries) { + var matchFailed = false; + for (var name in blockEntry.matches) { + let pluginProperty = pluginProperties[name]; + if ( + typeof pluginProperty != "string" || + !blockEntry.matches[name].test(pluginProperty) + ) { + matchFailed = true; + break; + } + } + + if (matchFailed) { + continue; + } + + for (let versionRange of blockEntry.versionRange) { + if ( + Utils.versionsMatch( + versionRange, + pluginProperties.version, + appVersion, + toolkitVersion + ) + ) { + return { entry: blockEntry, version: versionRange }; + } + } + } + + return null; + }, + + /** + * Private version of getState that allows the caller to pass in + * the plugin blocklist entries. + * + * @param {nsIPluginTag} plugin + * The nsIPluginTag to get the blocklist state for. + * @param {object[]} pluginEntries + * The plugin blocklist entries to compare against. + * @param {string?} appVersion + * The application version to compare to, will use the current + * version if null. + * @param {string?} toolkitVersion + * The toolkit version to compare to, will use the current version if + * null. + * @returns {integer} + * The blocklist state for the item, one of the STATE constants as + * defined in nsIBlocklistService. + */ + _getState(plugin, pluginEntries, appVersion, toolkitVersion) { + let r = this._getEntry(plugin, pluginEntries, appVersion, toolkitVersion); + if (!r) { + return Ci.nsIBlocklistService.STATE_NOT_BLOCKED; + } + + let { version: versionRange } = r; + + if (versionRange.severity >= gBlocklistLevel) { + return Ci.nsIBlocklistService.STATE_BLOCKED; + } + if (versionRange.severity == SEVERITY_OUTDATED) { + let vulnerabilityStatus = versionRange.vulnerabilityStatus; + if (vulnerabilityStatus == VULNERABILITYSTATUS_UPDATE_AVAILABLE) { + return Ci.nsIBlocklistService.STATE_VULNERABLE_UPDATE_AVAILABLE; + } + if (vulnerabilityStatus == VULNERABILITYSTATUS_NO_UPDATE) { + return Ci.nsIBlocklistService.STATE_VULNERABLE_NO_UPDATE; + } + return Ci.nsIBlocklistService.STATE_OUTDATED; + } + return Ci.nsIBlocklistService.STATE_SOFTBLOCKED; + }, +}; + +/** + * 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. + * + * Note: we assign to the global to allow tests to reach the object directly. + */ +this.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 = RemoteSettings( + Services.prefs.getCharPref(PREF_BLOCKLIST_ADDONS_COLLECTION), + { + bucketNamePref: PREF_BLOCKLIST_BUCKET, + lastCheckTimePref: PREF_BLOCKLIST_ADDONS_CHECKED_SECONDS, + signerName: Services.prefs.getCharPref(PREF_BLOCKLIST_ADDONS_SIGNER), + 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(); + + const types = ["extension", "theme", "locale", "dictionary", "service"]; + let addons = await AddonManager.getAddonsByTypes(types); + 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); + } + } + } + } + + 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 && !gApp.version) { + return null; + } + + if (!appVersion) { + appVersion = gApp.version; + } + if (!toolkitVersion) { + toolkitVersion = 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", + * } + * + * To update the blocklist, a replacement MLBF is published: + * + * { + * "generation_time": 1585692000000, + * "attachment": { ... RemoteSettings attachment ... } + * "attachment_type": "bloomfilter-full", + * } + * + * 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. + * The use of stashes is currently optional, and toggled via the + * extensions.blocklist.useMLBF.stashes preference (true = use stashes). + * + * Note: we assign to the global to allow tests to reach the object directly. + */ +this.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, + } = await this._client.attachments.download(record, { + attachmentId: this.RS_ATTACHMENT_ID, + useCache: true, + 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, + }; + }, + + 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); + let mlbfRecord; + if (this.stashesEnabled) { + 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, + })); + } else { + mlbfRecord = mlbfRecords.find( + r => + r.attachment_type == "bloomfilter-full" || + r.attachment_type == "bloomfilter-base" + ); + this._stashes = null; + } + + 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 + ); + 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 + ); + }, + + ensureInitialized() { + if (!gBlocklistEnabled || this._initialized) { + return; + } + this._initialized = true; + this._client = RemoteSettings( + Services.prefs.getCharPref(PREF_BLOCKLIST_ADDONS3_COLLECTION), + { + bucketNamePref: PREF_BLOCKLIST_BUCKET, + lastCheckTimePref: PREF_BLOCKLIST_ADDONS3_CHECKED_SECONDS, + signerName: Services.prefs.getCharPref(PREF_BLOCKLIST_ADDONS3_SIGNER), + } + ); + this._onUpdate = this._onUpdate.bind(this); + this._client.on("sync", this._onUpdate); + this.stashesEnabled = Services.prefs.getBoolPref( + PREF_BLOCKLIST_USE_MLBF_STASHES, + false + ); + Services.telemetry.scalarSet("blocklist.mlbf_stashes", this.stashesEnabled); + }, + + 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); + + // Check add-ons from XPIProvider. + const types = ["extension", "theme", "locale", "dictionary"]; + let addons = await AddonManager.getAddonsByTypes(types); + 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); + } + } + + 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._mlbfData) { + this.ensureInitialized(); + await this._updateMLBF(false); + } + + let blockKey = addon.id + ":" + addon.version; + + 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 shouldn't 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 !== AddonManager.SIGNEDSTATE_PRELIMINARY && + signedState !== 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 + */ + +// From appinfo in Services.jsm. It is not possible to use the one in +// Services.jsm 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(this, "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(this, "gAppID", function() { + return gApp.ID; +}); +XPCOMUtils.defineLazyGetter(this, "gAppOS", function() { + return 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); + + // If the stub blocklist service deferred any queries because we + // weren't loaded yet, execute them now. + for (let entry of Services.blocklist.pluginQueries.splice(0)) { + entry.resolve( + this.getPluginBlocklistState( + entry.plugin, + entry.appVersion, + entry.toolkitVersion + ) + ); + } + }, + isLoaded: true, + + shutdown() { + GfxBlocklistRS.shutdown(); + PluginBlocklistRS.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(); + if (oldImpl._initialized) { + oldImpl.shutdown(); + this.ExtensionBlocklist.undoShutdown(); + this.ExtensionBlocklist._onUpdate(); + } // else neither has been initialized yet. Wait for it to happen. + break; + case PREF_BLOCKLIST_USE_MLBF_STASHES: + ExtensionBlocklistMLBF.stashesEnabled = Services.prefs.getBoolPref( + PREF_BLOCKLIST_USE_MLBF_STASHES, + false + ); + if ( + ExtensionBlocklistMLBF._initialized && + !ExtensionBlocklistMLBF._didShutdown + ) { + Services.telemetry.scalarSet( + "blocklist.mlbf_stashes", + ExtensionBlocklistMLBF.stashesEnabled + ); + ExtensionBlocklistMLBF._onUpdate(); + } + break; + } + break; + } + }, + + loadBlocklistAsync() { + // Need to ensure we notify gfx of new stuff. + GfxBlocklistRS.checkForEntries(); + this.ExtensionBlocklist.ensureInitialized(); + PluginBlocklistRS.ensureInitialized(); + }, + + getPluginBlocklistState(plugin, appVersion, toolkitVersion) { + return PluginBlocklistRS.getState(plugin, appVersion, toolkitVersion); + }, + + getPluginBlockURL(plugin) { + return PluginBlocklistRS.getURL(plugin); + }, + + 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); + }, + + _chooseExtensionBlocklistImplementationFromPref() { + if (Services.prefs.getBoolPref(PREF_BLOCKLIST_USE_MLBF, false)) { + this.ExtensionBlocklist = ExtensionBlocklistMLBF; + Services.telemetry.scalarSet("blocklist.mlbf_enabled", true); + } else { + this.ExtensionBlocklist = ExtensionBlocklistRS; + Services.telemetry.scalarSet("blocklist.mlbf_enabled", false); + } + }, + + _blocklistUpdated() { + this.ExtensionBlocklist._onUpdate(); + PluginBlocklistRS._onUpdate(); + }, +}; + +Blocklist._init(); 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..ca82283b18 --- /dev/null +++ b/toolkit/mozapps/extensions/addonManager.js @@ -0,0 +1,409 @@ +/* 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"; + +ChromeUtils.defineModuleGetter( + this, + "AppConstants", + "resource://gre/modules/AppConstants.jsm" +); + +const { XPCOMUtils } = ChromeUtils.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +XPCOMUtils.defineLazyPreferenceGetter( + this, + "separatePrivilegedMozillaWebContentProcess", + "browser.tabs.remote.separatePrivilegedMozillaWebContentProcess", + false +); +XPCOMUtils.defineLazyPreferenceGetter( + this, + "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"; + +const CHILD_SCRIPT = "resource://gre/modules/addons/Content.js"; + +const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +var gSingleton = null; + +var AddonManager, AddonManagerPrivate; +function amManager() { + ({ AddonManager, AddonManagerPrivate } = ChromeUtils.import( + "resource://gre/modules/AddonManager.jsm" + )); + + Services.mm.loadFrameScript(CHILD_SCRIPT, true, true); + 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; + + 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) { + aCallback.onInstallEnded(uri, 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 + ); + }); + + 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 ( + !extensionsWebAPITesting && + 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 ( + !extensionsWebAPITesting && + 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 ( + !extensionsWebAPITesting && + 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}"), + _xpcom_factory: { + createInstance(aOuter, aIid) { + if (aOuter != null) { + throw Components.Exception( + "Component does not support aggregation", + Cr.NS_ERROR_NO_AGGREGATION + ); + } + + if (!gSingleton) { + gSingleton = new amManager(); + } + return gSingleton.QueryInterface(aIid); + }, + }, + QueryInterface: ChromeUtils.generateQI([ + "amIAddonManager", + "nsITimerCallback", + "nsIObserver", + ]), +}; + +const BLOCKLIST_JSM = "resource://gre/modules/Blocklist.jsm"; +ChromeUtils.defineModuleGetter(this, "Blocklist", BLOCKLIST_JSM); + +function BlocklistService() { + this.wrappedJSObject = this; + this.pluginQueries = []; +} + +BlocklistService.prototype = { + STATE_NOT_BLOCKED: Ci.nsIBlocklistService.STATE_NOT_BLOCKED, + STATE_SOFTBLOCKED: Ci.nsIBlocklistService.STATE_SOFTBLOCKED, + STATE_BLOCKED: Ci.nsIBlocklistService.STATE_BLOCKED, + STATE_OUTDATED: Ci.nsIBlocklistService.STATE_OUTDATED, + STATE_VULNERABLE_UPDATE_AVAILABLE: + Ci.nsIBlocklistService.STATE_VULNERABLE_UPDATE_AVAILABLE, + STATE_VULNERABLE_NO_UPDATE: Ci.nsIBlocklistService.STATE_VULNERABLE_NO_UPDATE, + + get isLoaded() { + return Cu.isModuleLoaded(BLOCKLIST_JSM) && Blocklist.isLoaded; + }, + + async getPluginBlocklistState(plugin, appVersion, toolkitVersion) { + if (AppConstants.platform == "android") { + return Ci.nsIBlocklistService.STATE_NOT_BLOCKED; + } + if (Cu.isModuleLoaded(BLOCKLIST_JSM)) { + return Blocklist.getPluginBlocklistState( + plugin, + appVersion, + toolkitVersion + ); + } + + // Blocklist module isn't loaded yet. Queue the query until it is. + let request = { plugin, appVersion, toolkitVersion }; + let promise = new Promise(resolve => { + request.resolve = resolve; + }); + + this.pluginQueries.push(request); + return promise; + }, + + observe(...args) { + return Blocklist.observe(...args); + }, + + notify() { + 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..b655409850 --- /dev/null +++ b/toolkit/mozapps/extensions/amContentHandler.jsm @@ -0,0 +1,81 @@ +/* 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 { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); + +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; + + 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, + }; + + 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..779b9f4cfe --- /dev/null +++ b/toolkit/mozapps/extensions/amIAddonManagerStartup.idl @@ -0,0 +1,83 @@ +/* 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..8acfa65ab3 --- /dev/null +++ b/toolkit/mozapps/extensions/amInstallTrigger.jsm @@ -0,0 +1,205 @@ +/* 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 { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm"); +const { Preferences } = ChromeUtils.import( + "resource://gre/modules/Preferences.jsm" +); +const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm"); + +const XPINSTALL_MIMETYPE = "application/x-xpinstall"; + +const MSG_INSTALL_ENABLED = "WebInstallerIsInstallEnabled"; +const MSG_INSTALL_ADDON = "WebInstallerInstallAddonFromWebpage"; +const MSG_INSTALL_CALLBACK = "WebInstallerInstallCallback"; + +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) { + 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 + ); + } + + 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 + } + } + + let installData = { + uri: url.spec, + hash: item.Hash || null, + name: item.name, + icon: iconUrl ? iconUrl.spec : null, + method: "installTrigger", + sourceHost: this._window.location?.host, + sourceURL: this._window.location?.href, + }; + + 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..b4a1b8d3e6 --- /dev/null +++ b/toolkit/mozapps/extensions/amWebAPI.jsm @@ -0,0 +1,307 @@ +/* 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.import( + "resource://gre/modules/XPCOMUtils.jsm" +); +ChromeUtils.defineModuleGetter( + this, + "Services", + "resource://gre/modules/Services.jsm" +); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "WEBEXT_PERMISSION_PROMPTS", + "extensions.webextPermissionPrompts", + false +); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "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 permissionPromptsEnabled() { + return WEBEXT_PERMISSION_PROMPTS; + } + + get abuseReportPanelEnabled() { + return 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..9d73b6d797 --- /dev/null +++ b/toolkit/mozapps/extensions/components.conf @@ -0,0 +1,44 @@ +# -*- 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', + '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..c7dbf90af6 --- /dev/null +++ b/toolkit/mozapps/extensions/content/aboutaddons.css @@ -0,0 +1,739 @@ +/* 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 { + --addon-icon-size: 32px; + --main-margin-start: 28px; + --section-width: 664px; + --sidebar-width: var(--in-content-sidebar-width); + --z-index-sticky-container: 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; +} + +.category[badge-count]::after { + display: inline-block; + min-width: 20px; + background-color: var(--blue-50); + color: #fff; + 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://global/skin/plugins/plugin.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"); +} + +.header-name { + user-select: initial; +} + +.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; +} + +.section { + margin-bottom: 32px; +} + +/* Add-on cards */ + +.addon.card { + margin-bottom: 16px; +} + +addon-card:not([expanded]) > .addon.card[active="false"] { + opacity: 0.6; + transition: opacity 150ms, box-shadow 150ms; +} + +addon-card:not([expanded])[panelopen] > .addon.card[active="false"], +addon-card:not([expanded]) > .addon.card[active="false"]:focus-within, +addon-card:not([expanded]) > .addon.card[active="false"]:hover { + opacity: 1; +} + +.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-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://browser/skin/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; +} + +.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; +} + +.disco-cta-button[action="install-addon"]::before { + content: "+"; + padding-inline-end: 4px; +} + +.discopane-notice { + margin: 24px 0; +} + +.discopane-notice-content { + align-items: center; + display: flex; + width: 100%; +} + +.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 { + margin: 16px 0; +} + +.addon-detail-contribute { + display: flex; + padding: var(--card-padding); + border: 1px solid var(--in-content-box-border-color); + border-radius: var(--panel-border-radius); + 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-row { + display: flex; + justify-content: space-between; + align-items: center; + border-top: 1px solid var(--in-content-box-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-rating { + display: flex; +} + +.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: var(--blue-50); +} + +panel-item { + -moz-context-properties: fill; + fill: currentColor; +} + +panel-item[action="remove"] { + --icon: url("chrome://global/skin/icons/delete.svg"); +} + +panel-item[action="install-update"] { + --icon: url("chrome://global/skin/icons/update-icon.svg"); +} + +panel-item[action="report"] { + --icon: url(chrome://global/skin/icons/warning.svg); +} + +panel-item-separator { + display: block; + height: 1px; + background: var(--in-content-box-border-color); + padding: 0; + margin: 6px 0; +} + +.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-box-border-color); + border-top: 1px solid var(--in-content-box-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; + color: var(--in-content-text-color); +} + +button.tab-button:hover { + background-color: var(--in-content-button-background); + border-top-color: var(--in-content-box-border-color); +} + +button.tab-button:hover:active { + background-color: var(--in-content-button-background-hover); +} + +button.tab-button[selected] { + border-top-color: var(--in-content-border-highlight); + color: var(--in-content-category-text-selected) !important; +} + +button.tab-button:-moz-focusring { + outline-offset: -2px; + -moz-outline-radius: 0; +} + +.tab-group[last-input-type="mouse"] > button.tab-button:-moz-focusring { + outline: none; + box-shadow: none; +} + +panel-list { + font-size: 13px; +} + +@media (max-width: 830px) { + .category[badge-count]::after { + content: ""; + display: block; + width: 5px; + height: 5px; + border-radius: 50%; + min-width: auto; + padding: 0; + } +} diff --git a/toolkit/mozapps/extensions/content/aboutaddons.html b/toolkit/mozapps/extensions/content/aboutaddons.html new file mode 100644 index 0000000000..5d9ebd3e50 --- /dev/null +++ b/toolkit/mozapps/extensions/content/aboutaddons.html @@ -0,0 +1,427 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/toolkit/mozapps/extensions/content/aboutaddons.js b/toolkit/mozapps/extensions/content/aboutaddons.js new file mode 100644 index 0000000000..0ad41fd91c --- /dev/null +++ b/toolkit/mozapps/extensions/content/aboutaddons.js @@ -0,0 +1,4811 @@ +/* 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] */ +/* exported hide, initialize, show */ +/* import-globals-from aboutaddonsCommon.js */ +/* import-globals-from abuse-reports.js */ +/* global MozXULElement, MessageBarStackElement, windowRoot */ + +"use strict"; + +XPCOMUtils.defineLazyModuleGetters(this, { + AddonManager: "resource://gre/modules/AddonManager.jsm", + AddonRepository: "resource://gre/modules/addons/AddonRepository.jsm", + AMTelemetry: "resource://gre/modules/AddonManager.jsm", + ClientID: "resource://gre/modules/ClientID.jsm", + DeferredTask: "resource://gre/modules/DeferredTask.jsm", + E10SUtils: "resource://gre/modules/E10SUtils.jsm", + ExtensionCommon: "resource://gre/modules/ExtensionCommon.jsm", + ExtensionParent: "resource://gre/modules/ExtensionParent.jsm", + ExtensionPermissions: "resource://gre/modules/ExtensionPermissions.jsm", + PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.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, "extBundle", function() { + return Services.strings.createBundle( + "chrome://mozapps/locale/extensions/extensions.properties" + ); +}); +XPCOMUtils.defineLazyGetter(this, "extensionStylesheets", () => { + const { ExtensionParent } = ChromeUtils.import( + "resource://gre/modules/ExtensionParent.jsm" + ); + return ExtensionParent.extensionStylesheets; +}); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "allowPrivateBrowsingByDefault", + "extensions.allowPrivateBrowsingByDefault", + true +); +XPCOMUtils.defineLazyPreferenceGetter( + this, + "SUPPORT_URL", + "app.support.baseURL", + "", + null, + val => Services.urlFormatter.formatURL(val) +); + +XPCOMUtils.defineLazyPreferenceGetter( + this, + "XPINSTALL_ENABLED", + "xpinstall.enabled", + true +); + +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/plugins/plugin.svg"; +const EXTENSION_ICON_URL = + "chrome://mozapps/skin/extensions/extensionGeneric.svg"; +const BUILTIN_THEME_PREVIEWS = new Map([ + [ + "default-theme@mozilla.org", + "chrome://mozapps/content/extensions/default-theme.svg", + ], + [ + "firefox-compact-light@mozilla.org", + "chrome://mozapps/content/extensions/firefox-compact-light.svg", + ], + [ + "firefox-compact-dark@mozilla.org", + "chrome://mozapps/content/extensions/firefox-compact-dark.svg", + ], + [ + "firefox-alpenglow@mozilla.org", + "chrome://mozapps/content/extensions/firefox-alpenglow.svg", + ], +]); + +const PERMISSION_MASKS = { + "ask-to-activate": AddonManager.PERM_CAN_ASK_TO_ACTIVATE, + 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: [], +}; + +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 && + ["extension", "theme"].includes(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 appName = brandBundle.GetStringFromName("brandShortName"); + const { + STATE_BLOCKED, + STATE_OUTDATED, + STATE_SOFTBLOCKED, + STATE_VULNERABLE_UPDATE_AVAILABLE, + STATE_VULNERABLE_NO_UPDATE, + } = Ci.nsIBlocklistService; + + const formatString = (name, args) => + extBundle.formatStringFromName( + `details.notification.${name}`, + args, + args.length + ); + const getString = name => + extBundle.GetStringFromName(`details.notification.${name}`); + + if (addon.blocklistState === STATE_BLOCKED) { + return { + linkText: getString("blocked.link"), + linkUrl: await addon.getBlocklistURL(), + message: formatString("blocked", [name]), + type: "error", + }; + } else if (isDisabledUnsigned(addon)) { + return { + linkText: getString("unsigned.link"), + linkUrl: SUPPORT_URL + "unsigned-addons", + message: formatString("unsignedAndDisabled", [name, appName]), + type: "error", + }; + } else if ( + !addon.isCompatible && + (AddonManager.checkCompatibility || + addon.blocklistState !== STATE_SOFTBLOCKED) + ) { + return { + message: formatString("incompatible", [ + name, + appName, + Services.appinfo.version, + ]), + type: "warning", + }; + } else if (!isCorrectlySigned(addon)) { + return { + linkText: getString("unsigned.link"), + linkUrl: SUPPORT_URL + "unsigned-addons", + message: formatString("unsigned", [name, appName]), + type: "warning", + }; + } else if (addon.blocklistState === STATE_SOFTBLOCKED) { + return { + linkText: getString("softblocked.link"), + linkUrl: await addon.getBlocklistURL(), + message: formatString("softblocked", [name]), + type: "warning", + }; + } else if (addon.blocklistState === STATE_OUTDATED) { + return { + linkText: getString("outdated.link"), + linkUrl: await addon.getBlocklistURL(), + message: formatString("outdated", [name]), + type: "warning", + }; + } else if (addon.blocklistState === STATE_VULNERABLE_UPDATE_AVAILABLE) { + return { + linkText: getString("vulnerableUpdatable.link"), + linkUrl: await addon.getBlocklistURL(), + message: formatString("vulnerableUpdatable", [name]), + type: "error", + }; + } else if (addon.blocklistState === STATE_VULNERABLE_NO_UPDATE) { + return { + linkText: getString("vulnerableNoUpdate.link"), + linkUrl: await addon.getBlocklistURL(), + message: formatString("vulnerableNoUpdate", [name]), + type: "error", + }; + } else if (addon.isGMPlugin && !addon.isInstalled && addon.isActive) { + return { + message: formatString("gmpPending", [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))); + Services.obs.notifyObservers(null, "EM-update-check-finished"); + 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 ( + allowPrivateBrowsingByDefault || + // Note: This function is async because isAllowedInPrivateBrowsing is async. + isAllowedInPrivateBrowsing(addon) + ); +} + +/** + * This function is set in initialize() by the parent about:addons window. It + * is a helper for gViewController.loadView(). + * + * @param {string} type The view type to load. + * @param {string} param The (optional) param for the view. + */ +let loadViewFn; + +/** + * This function is set in initialize() by the parent about:addons window. It + * is a helper for gViewController.replaceView(defaultViewId). This should be + * used to reset the view if we try to load an invalid view. + */ +let replaceWithDefaultViewFn; + +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 (BUILTIN_THEME_PREVIEWS.has(addon.id)) { + return BUILTIN_THEME_PREVIEWS.get(addon.id); + } + + 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; + } +} + +/** + * 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 PanelList extends HTMLElement { + static get observedAttributes() { + return ["open"]; + } + + constructor() { + super(); + this.attachShadow({ mode: "open" }); + // Ensure that the element is hidden even if its main stylesheet hasn't + // loaded yet. On initial load, or with cache disabled, the element could + // briefly flicker before the stylesheet is loaded without this. + let style = document.createElement("style"); + style.textContent = ` + :host(:not([open])) { + display: none; + } + `; + this.shadowRoot.appendChild(style); + this.shadowRoot.appendChild(importTemplate("panel-list")); + } + + connectedCallback() { + this.setAttribute("role", "menu"); + } + + attributeChangedCallback(name, oldVal, newVal) { + if (name == "open" && newVal != oldVal) { + if (this.open) { + this.onShow(); + } else { + this.onHide(); + } + } + } + + get open() { + return this.hasAttribute("open"); + } + + set open(val) { + this.toggleAttribute("open", val); + } + + show(triggeringEvent) { + this.triggeringEvent = triggeringEvent; + this.open = true; + } + + hide(triggeringEvent) { + let openingEvent = this.triggeringEvent; + this.triggeringEvent = triggeringEvent; + this.open = false; + // Refocus the button that opened the menu if we have one. + if (openingEvent && openingEvent.target) { + openingEvent.target.focus(); + } + } + + toggle(triggeringEvent) { + if (this.open) { + this.hide(triggeringEvent); + } else { + this.show(triggeringEvent); + } + } + + async setAlign() { + // Set the showing attribute to hide the panel until its alignment is set. + this.setAttribute("showing", "true"); + // Tell the parent node to hide any overflow in case the panel extends off + // the page before the alignment is set. + this.parentNode.style.overflow = "hidden"; + + // Wait for a layout flush, then find the bounds. + let { + anchorHeight, + anchorLeft, + anchorTop, + anchorWidth, + panelHeight, + panelWidth, + winHeight, + winScrollY, + winScrollX, + winWidth, + } = await new Promise(resolve => { + this.style.left = 0; + this.style.top = 0; + + requestAnimationFrame(() => + setTimeout(() => { + let anchorNode = + (this.triggeringEvent && this.triggeringEvent.target) || + this.parentNode; + // Use y since top is reserved. + let anchorBounds = window.windowUtils.getBoundsWithoutFlushing( + anchorNode + ); + let panelBounds = window.windowUtils.getBoundsWithoutFlushing(this); + resolve({ + anchorHeight: anchorBounds.height, + anchorLeft: anchorBounds.left, + anchorTop: anchorBounds.top, + anchorWidth: anchorBounds.width, + panelHeight: panelBounds.height, + panelWidth: panelBounds.width, + winHeight: innerHeight, + winWidth: innerWidth, + winScrollX: scrollX, + winScrollY: scrollY, + }); + }, 0) + ); + }); + + // Calculate the left/right alignment. + let align; + let leftOffset; + // The tip of the arrow is 25px from the edge of the panel, + // but 26px looks right. + let arrowOffset = 26; + let leftAlignX = anchorLeft + anchorWidth / 2 - arrowOffset; + let rightAlignX = anchorLeft + anchorWidth / 2 - panelWidth + arrowOffset; + if (Services.locale.isAppLocaleRTL) { + // Prefer aligning on the right. + align = rightAlignX < 0 ? "left" : "right"; + } else { + // Prefer aligning on the left. + align = leftAlignX + panelWidth > winWidth ? "right" : "left"; + } + leftOffset = align === "left" ? leftAlignX : rightAlignX; + + let bottomAlignY = anchorTop + anchorHeight; + let valign; + let topOffset; + if (bottomAlignY + panelHeight > winHeight) { + topOffset = anchorTop - panelHeight; + valign = "top"; + } else { + topOffset = bottomAlignY; + valign = "bottom"; + } + + // Set the alignments and show the panel. + this.setAttribute("align", align); + this.setAttribute("valign", valign); + this.parentNode.style.overflow = ""; + + this.style.left = `${leftOffset + winScrollX}px`; + this.style.top = `${topOffset + winScrollY}px`; + + this.removeAttribute("showing"); + } + + addHideListeners() { + // Hide when a panel-item is clicked in the list. + this.addEventListener("click", this); + document.addEventListener("keydown", this); + // Hide when a click is initiated outside the panel. + document.addEventListener("mousedown", this); + // Hide if focus changes and the panel isn't in focus. + document.addEventListener("focusin", this); + // Reset or focus tracking, we treat the first focusin differently. + this.focusHasChanged = false; + // Hide on resize, scroll or losing window focus. + window.addEventListener("resize", this); + window.addEventListener("scroll", this); + window.addEventListener("blur", this); + } + + removeHideListeners() { + this.removeEventListener("click", this); + document.removeEventListener("keydown", this); + document.removeEventListener("mousedown", this); + document.removeEventListener("focusin", this); + window.removeEventListener("resize", this); + window.removeEventListener("scroll", this); + window.removeEventListener("blur", this); + } + + handleEvent(e) { + // Ignore the event if it caused the panel to open. + if (e == this.triggeringEvent) { + return; + } + + switch (e.type) { + case "resize": + case "scroll": + case "blur": + this.hide(); + break; + case "click": + if (e.target.tagName == "PANEL-ITEM") { + this.hide(); + } else { + // Avoid falling through to the default click handler of the + // add-on card, which would expand the add-on card. + e.stopPropagation(); + } + break; + case "keydown": + if (e.key === "ArrowDown" || e.key === "ArrowUp" || e.key === "Tab") { + // Ignore tabbing with a modifer other than shift. + if (e.key === "Tab" && (e.altKey || e.ctrlKey || e.metaKey)) { + return; + } + + // Don't scroll the page or let the regular tab order take effect. + e.preventDefault(); + + // Keep moving to the next/previous element sibling until we find a + // panel-item that isn't hidden. + let moveForward = + e.key === "ArrowDown" || (e.key === "Tab" && !e.shiftKey); + + // If the menu is opened with the mouse, the active element might be + // somewhere else in the document. In that case we should ignore it + // to avoid walking unrelated DOM nodes. + this.focusWalker.currentNode = this.contains(document.activeElement) + ? document.activeElement + : this; + let nextItem = moveForward + ? this.focusWalker.nextNode() + : this.focusWalker.previousNode(); + + // If the next item wasn't found, try looping to the top/bottom. + if (!nextItem) { + this.focusWalker.currentNode = this; + if (moveForward) { + nextItem = this.focusWalker.firstChild(); + } else { + nextItem = this.focusWalker.lastChild(); + } + } + break; + } else if (e.key === "Escape") { + this.hide(); + } else if (!e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey) { + // Check if any of the children have an accesskey for this letter. + let item = this.querySelector( + `[accesskey="${e.key.toLowerCase()}"], + [accesskey="${e.key.toUpperCase()}"]` + ); + if (item) { + item.click(); + } + } + break; + case "mousedown": + case "focusin": + // There will be a focusin after the mousedown that opens the panel + // using the mouse. Ignore the first focusin event if it's on the + // triggering target. + if ( + this.triggeringEvent && + e.target == this.triggeringEvent.target && + !this.focusHasChanged + ) { + this.focusHasChanged = true; + // If the target isn't in the panel, hide. This will close when focus + // moves out of the panel, or there's a click started outside the + // panel. + } else if (!e.target || e.target.closest("panel-list") != this) { + this.hide(); + // Just record that there was a focusin event. + } else { + this.focusHasChanged = true; + } + break; + } + } + + /** + * A TreeWalker that can be used to focus elements. The returned element will + * be the element that has gained focus based on the requested movement + * through the tree. + * + * Example: + * + * this.focusWalker.currentNode = this; + * // Focus and get the first focusable child. + * let focused = this.focusWalker.nextNode(); + * // Focus the second focusable child. + * this.focusWalker.nextNode(); + */ + get focusWalker() { + if (!this._focusWalker) { + this._focusWalker = document.createTreeWalker( + this, + NodeFilter.SHOW_ELEMENT, + { + acceptNode: node => { + // No need to look at hidden nodes. + if (node.hidden) { + return NodeFilter.FILTER_REJECT; + } + + // Focus the node, if it worked then this is the node we want. + node.focus(); + if (node === document.activeElement) { + return NodeFilter.FILTER_ACCEPT; + } + + // Continue into child nodes if the parent couldn't be focused. + return NodeFilter.FILTER_SKIP; + }, + } + ); + } + return this._focusWalker; + } + + async onShow() { + this.sendEvent("showing"); + this.addHideListeners(); + await this.setAlign(); + + // Wait until the next paint for the alignment to be set and panel to be + // visible. + requestAnimationFrame(() => { + // Focus the first focusable panel-item. + this.focusWalker.currentNode = this; + this.focusWalker.nextNode(); + + this.sendEvent("shown"); + }); + } + + onHide() { + requestAnimationFrame(() => this.sendEvent("hidden")); + this.removeHideListeners(); + } + + sendEvent(name, detail) { + this.dispatchEvent(new CustomEvent(name, { detail })); + } +} +customElements.define("panel-list", PanelList); + +class PanelItem extends HTMLElement { + static get observedAttributes() { + return ["accesskey"]; + } + + constructor() { + super(); + this.attachShadow({ mode: "open" }); + + let style = document.createElement("link"); + style.rel = "stylesheet"; + style.href = "chrome://mozapps/content/extensions/panel-item.css"; + + this.button = document.createElement("button"); + this.button.setAttribute("role", "menuitem"); + + // Use a XUL label element to show the accesskey. + this.label = document.createXULElement("label"); + this.button.appendChild(this.label); + + let supportLinkSlot = document.createElement("slot"); + supportLinkSlot.name = "support-link"; + + let defaultSlot = document.createElement("slot"); + defaultSlot.style.display = "none"; + + this.shadowRoot.append(style, this.button, supportLinkSlot, defaultSlot); + + // When our content changes, move the text into the label. It doesn't work + // with a , unfortunately. + new MutationObserver(() => { + this.label.textContent = defaultSlot + .assignedNodes() + .map(node => node.textContent) + .join(""); + }).observe(this, { characterData: true, childList: true, subtree: true }); + } + + connectedCallback() { + this.panel = this.closest("panel-list"); + + if (this.panel) { + this.panel.addEventListener("hidden", this); + this.panel.addEventListener("shown", this); + } + } + + disconnectedCallback() { + if (this.panel) { + this.panel.removeEventListener("hidden", this); + this.panel.removeEventListener("shown", this); + this.panel = null; + } + } + + attributeChangedCallback(name, oldVal, newVal) { + if (name === "accesskey") { + // Bug 1037709 - Accesskey doesn't work in shadow DOM. + // Ideally we'd have the accesskey set in shadow DOM, and on + // attributeChangedCallback we'd just update the shadow DOM accesskey. + + // Skip this change event if we caused it. + if (this._modifyingAccessKey) { + this._modifyingAccessKey = false; + return; + } + + this.label.accessKey = newVal || ""; + + // Bug 1588156 - Accesskey is not ignored for hidden non-input elements. + // Since the accesskey won't be ignored, we need to remove it ourselves + // when the panel is closed, and move it back when it opens. + if (!this.panel || !this.panel.open) { + // When the panel isn't open, just store the key for later. + this._accessKey = newVal || null; + this._modifyingAccessKey = true; + this.accessKey = ""; + } else { + this._accessKey = null; + } + } + } + + get disabled() { + return this.button.hasAttribute("disabled"); + } + + set disabled(val) { + this.button.toggleAttribute("disabled", val); + } + + get checked() { + return this.hasAttribute("checked"); + } + + set checked(val) { + this.toggleAttribute("checked", val); + } + + focus() { + this.button.focus(); + } + + handleEvent(e) { + // Bug 1588156 - Accesskey is not ignored for hidden non-input elements. + // Since the accesskey won't be ignored, we need to remove it ourselves + // when the panel is closed, and move it back when it opens. + switch (e.type) { + case "shown": + if (this._accessKey) { + this.accessKey = this._accessKey; + this._accessKey = null; + } + break; + case "hidden": + if (this.accessKey) { + this._accessKey = this.accessKey; + this._modifyingAccessKey = true; + this.accessKey = ""; + } + break; + } + } +} +customElements.define("panel-item", PanelItem); + +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 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") + ); + } + 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() { + 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"; + + let { contentWindow } = getBrowserElement(); + this.backButton.disabled = !contentWindow.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 + ); + } + } +} +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) { + loadViewFn("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": + loadViewFn("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": + loadViewFn("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() { + loadViewFn(this.viewId); + } + + get isVisible() { + return true; + } + + 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" }); + +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; + }); + // This will resolve when the final category states have been set by + // checking the AddonManager state and showing/hiding categories. The page + // won't be "initialized" until this resolves. + this.promiseInitialized = new Promise(resolve => { + this._resolveInitialized = resolve; + }); + } + + async initialize() { + let addonTypesObjects = AddonManager.addonTypes; + let addonTypes = new Set(); + for (let type in addonTypesObjects) { + addonTypes.add(type); + } + + let hiddenTypes = new Set([]); + + for (let button of this.children) { + let { defaultHidden, name } = button; + button.hidden = + !button.isVisible || (defaultHidden && this.shouldHideCategory(name)); + + if (defaultHidden && addonTypes.has(name)) { + hiddenTypes.add(name); + } + } + + let hiddenUpdated; + if (hiddenTypes.size) { + hiddenUpdated = this.updateHiddenCategories(Array.from(hiddenTypes)); + } + + this.updateAvailableCount(); + + this.addEventListener("click", e => { + let button = e.target.closest("[viewid]"); + if (button) { + button.load(); + } + }); + this.addEventListener("button-group:key-selected", e => { + this.activeChild.load(); + }); + + AddonManagerListenerHandler.addListener(this); + + this._resolveRendered(); + await hiddenUpdated; + this._resolveInitialized(); + } + + get initialViewId() { + let viewId = Services.prefs.getStringPref(PREF_UI_LASTCATEGORY, ""); + // If the pref value is a valid top-level view then use that viewId. + if (this.getButtonByViewId(viewId)) { + return viewId; + } + // Otherwise, use the first viewId that can be shown. + for (let button of this.children) { + if (!button.defaultHidden && !button.hidden && button.isVisible) { + return button.viewId; + } + } + // If there aren't any available views then there's nothing to load. This + // shouldn't happen though since the extension list should always be valid. + throw new Error("Couldn't find initial view to load"); + } + + 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}"]`); + } + + getButtonByViewId(id) { + return this.querySelector(`[viewid="${id}"]`); + } + + 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. + replaceWithDefaultViewFn(); + } + 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 prefsItem = document.createElement("li"); + prefsItem.classList.add("sidebar-footer-item"); + let prefsLink = document.createElement("a"); + prefsLink.classList.add("sidebar-footer-link", "preferences-icon"); + prefsLink.id = "preferencesButton"; + prefsLink.href = "about:preferences"; + document.l10n.setAttributes(prefsLink, "sidebar-preferences-button-title"); + let systemPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); + prefsLink.addEventListener("click", 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 prefsText = document.createElement("span"); + prefsText.classList.add("sidebar-footer-link-text"); + document.l10n.setAttributes(prefsText, "preferences"); + prefsLink.append(prefsText); + prefsItem.append(prefsLink); + + let supportItem = document.createElement("li"); + supportItem.classList.add("sidebar-footer-item"); + let supportLink = document.createElement("a", { is: "support-link" }); + document.l10n.setAttributes(supportLink, "sidebar-help-button-title"); + supportLink.classList.add("sidebar-footer-link", "help-icon"); + supportLink.id = "help-button"; + supportLink.setAttribute("support-page", "addons-help"); + supportLink.addEventListener("click", e => { + AMTelemetry.recordLinkEvent({ + object: "aboutAddons", + value: "support", + extra: { + view: getTelemetryViewName(this), + }, + }); + }); + let supportText = document.createElement("span"); + supportText.classList.add("sidebar-footer-link-text"); + document.l10n.setAttributes(supportText, "help-button"); + supportLink.append(supportText); + supportItem.append(supportLink); + + list.append(prefsItem, supportItem); + this.append(list); + } +} +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.tagName == "PANEL-ITEM-SEPARATOR") { + 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 = { + "ask-to-activate": AddonManager.STATE_ASK_TO_ACTIVATE, + "always-activate": false, + "never-activate": true, + }; + const action = el.getAttribute("action"); + if (action in userDisabledStates) { + let userDisabled = userDisabledStates[action]; + el.checked = addon.userDisabled === userDisabled; + let resultProp = + action == "always-activate" && addon.isFlashPlugin + ? "hidden" + : "disabled"; + el[resultProp] = !(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 ContentSelectDropdown extends HTMLElement { + connectedCallback() { + if (this.children.length) { + return; + } + // This creates the menulist and menupopup elements needed for the inline + // browser to support