From db6eb94ebb08907db81dd17eec58204be5c388d1 Mon Sep 17 00:00:00 2001 From: Fedor Date: Tue, 12 Mar 2019 19:34:24 +0300 Subject: [PATCH] Restore webext --- .../basilisk/base/content/tab-content.js | 11 + .../basilisk/base/content/urlbarBindings.xml | 19 + application/basilisk/base/jar.mn | 4 +- application/basilisk/components/moz.build | 3 + .../components/webextensions/.eslintrc.js | 22 + .../components/webextensions/ext-bookmarks.js | 374 + .../webextensions/ext-browserAction.js | 531 + .../webextensions/ext-c-contextMenus.js | 158 + .../components/webextensions/ext-c-omnibox.js | 32 + .../components/webextensions/ext-c-tabs.js | 35 + .../components/webextensions/ext-commands.js | 264 + .../webextensions/ext-contextMenus.js | 537 + .../webextensions/ext-desktop-runtime.js | 26 + .../components/webextensions/ext-history.js | 246 + .../components/webextensions/ext-omnibox.js | 104 + .../webextensions/ext-pageAction.js | 290 + .../components/webextensions/ext-sessions.js | 92 + .../components/webextensions/ext-tabs.js | 1093 ++ .../components/webextensions/ext-utils.js | 1239 +++ .../components/webextensions/ext-windows.js | 231 + .../webextensions/extension-mac-panel.css | 3 + .../webextensions/extension-mac.css | 11 + .../webextensions/extension-win-panel.css | 5 + .../components/webextensions/extension.css | 572 + .../components/webextensions/extension.svg | 19 + .../webextensions/extensions-browser.manifest | 31 + .../basilisk/components/webextensions/jar.mn | 29 + .../components/webextensions/moz.build | 14 + .../components/webextensions/schemas/LICENSE | 27 + .../webextensions/schemas/bookmarks.json | 568 + .../webextensions/schemas/browser_action.json | 430 + .../webextensions/schemas/commands.json | 148 + .../webextensions/schemas/context_menus.json | 424 + .../schemas/context_menus_internal.json | 78 + .../webextensions/schemas/history.json | 316 + .../components/webextensions/schemas/jar.mn | 16 + .../webextensions/schemas/moz.build | 7 + .../webextensions/schemas/omnibox.json | 248 + .../webextensions/schemas/page_action.json | 235 + .../webextensions/schemas/sessions.json | 146 + .../webextensions/schemas/tabs.json | 1295 +++ .../webextensions/schemas/windows.json | 508 + application/basilisk/configure.in | 13 + application/basilisk/confvars.sh | 1 + .../basilisk/installer/package-manifest.in | 12 + devtools/server/actors/moz.build | 2 +- devtools/server/actors/webbrowser.js | 18 + dom/webidl/AddonEvent.webidl | 12 + dom/webidl/AddonManager.webidl | 91 + dom/webidl/moz.build | 6 + .../components/blocklist/blocklist.manifest | 2 + toolkit/components/blocklist/moz.build | 1 + .../blocklist/nsBlocklistService.js | 9 + .../blocklist/nsBlocklistServiceContent.js | 113 + .../components/build/nsToolkitCompsModule.cpp | 18 + toolkit/components/moz.build | 3 + toolkit/components/webextensions/.eslintrc.js | 494 + .../components/webextensions/Extension.jsm | 902 ++ .../components/webextensions/ExtensionAPI.jsm | 81 + .../webextensions/ExtensionChild.jsm | 1058 ++ .../webextensions/ExtensionCommon.jsm | 679 ++ .../webextensions/ExtensionContent.jsm | 1050 ++ .../webextensions/ExtensionManagement.jsm | 321 + .../webextensions/ExtensionParent.jsm | 551 + .../webextensions/ExtensionStorage.jsm | 241 + .../webextensions/ExtensionTestCommon.jsm | 343 + .../webextensions/ExtensionUtils.jsm | 1216 +++ .../webextensions/ExtensionXPCShellUtils.jsm | 306 + .../webextensions/LegacyExtensionsUtils.jsm | 250 + .../webextensions/MessageChannel.jsm | 797 ++ .../webextensions/NativeMessaging.jsm | 443 + toolkit/components/webextensions/Schemas.jsm | 2143 ++++ .../components/webextensions/ext-alarms.js | 155 + .../webextensions/ext-backgroundPage.js | 147 + .../webextensions/ext-browser-content.js | 217 + .../webextensions/ext-c-backgroundPage.js | 45 + .../webextensions/ext-c-extension.js | 57 + .../components/webextensions/ext-c-runtime.js | 96 + .../components/webextensions/ext-c-storage.js | 62 + .../components/webextensions/ext-c-test.js | 188 + .../components/webextensions/ext-cookies.js | 484 + .../components/webextensions/ext-downloads.js | 799 ++ .../components/webextensions/ext-extension.js | 20 + toolkit/components/webextensions/ext-i18n.js | 34 + toolkit/components/webextensions/ext-idle.js | 94 + .../webextensions/ext-management.js | 109 + .../webextensions/ext-notifications.js | 161 + .../components/webextensions/ext-runtime.js | 134 + .../components/webextensions/ext-storage.js | 46 + .../components/webextensions/ext-topSites.js | 24 + .../webextensions/ext-webNavigation.js | 192 + .../webextensions/ext-webRequest.js | 115 + .../webextensions/extensions-toolkit.manifest | 49 + toolkit/components/webextensions/jar.mn | 26 + toolkit/components/webextensions/moz.build | 41 + .../components/webextensions/schemas/LICENSE | 27 + .../webextensions/schemas/alarms.json | 145 + .../webextensions/schemas/cookies.json | 224 + .../webextensions/schemas/downloads.json | 793 ++ .../webextensions/schemas/events.json | 322 + .../webextensions/schemas/experiments.json | 16 + .../webextensions/schemas/extension.json | 178 + .../schemas/extension_types.json | 83 + .../webextensions/schemas/i18n.json | 132 + .../webextensions/schemas/idle.json | 70 + .../components/webextensions/schemas/jar.mn | 25 + .../webextensions/schemas/management.json | 250 + .../webextensions/schemas/manifest.json | 377 + .../webextensions/schemas/moz.build | 7 + .../schemas/native_host_manifest.json | 37 + .../webextensions/schemas/notifications.json | 416 + .../webextensions/schemas/runtime.json | 590 ++ .../webextensions/schemas/storage.json | 229 + .../webextensions/schemas/test.json | 215 + .../webextensions/schemas/top_sites.json | 66 + .../webextensions/schemas/web_navigation.json | 387 + .../webextensions/schemas/web_request.json | 616 ++ .../webextensions/test/mochitest/.eslintrc.js | 35 + .../webextensions/test/mochitest/chrome.ini | 35 + .../test/mochitest/chrome_head.js | 12 + .../mochitest/file_WebNavigation_page1.html | 12 + .../mochitest/file_WebNavigation_page2.html | 7 + .../mochitest/file_WebNavigation_page3.html | 9 + .../test/mochitest/file_WebRequest_page3.html | 11 + .../test/mochitest/file_csp.html | 14 + .../test/mochitest/file_csp.html^headers^ | 1 + .../mochitest/file_ext_test_api_injection.js | 12 + .../test/mochitest/file_image_bad.png | Bin 0 -> 5401 bytes .../test/mochitest/file_image_good.png | Bin 0 -> 580 bytes .../test/mochitest/file_image_redirect.png | Bin 0 -> 5401 bytes .../test/mochitest/file_mixed.html | 13 + .../test/mochitest/file_permission_xhr.html | 55 + .../mochitest/file_privilege_escalation.html | 13 + .../test/mochitest/file_sample.html | 12 + .../test/mochitest/file_script_bad.js | 3 + .../test/mochitest/file_script_good.js | 3 + .../test/mochitest/file_script_redirect.js | 4 + .../test/mochitest/file_script_xhr.js | 5 + .../test/mochitest/file_style_bad.css | 3 + .../test/mochitest/file_style_good.css | 3 + .../test/mochitest/file_style_redirect.css | 3 + .../test/mochitest/file_teardown_test.js | 24 + .../file_webNavigation_clientRedirect.html | 9 + ...Navigation_clientRedirect_httpHeaders.html | 8 + ...n_clientRedirect_httpHeaders.html^headers^ | 1 + ...ile_webNavigation_frameClientRedirect.html | 12 + .../file_webNavigation_frameRedirect.html | 12 + .../file_webNavigation_manualSubframe.html | 12 + ...le_webNavigation_manualSubframe_page1.html | 8 + ...le_webNavigation_manualSubframe_page2.html | 7 + .../test/mochitest/file_with_about_blank.html | 10 + .../webextensions/test/mochitest/head.js | 13 + .../test/mochitest/head_cookies.js | 167 + .../test/mochitest/head_webrequest.js | 331 + .../test/mochitest/mochitest.ini | 115 + .../test/mochitest/redirection.sjs | 4 + .../test/mochitest/return_headers.sjs | 20 + ...st_chrome_ext_background_debug_global.html | 166 + .../test_chrome_ext_background_page.html | 84 + ...ontentscript_unrecognizedprop_warning.html | 80 + .../test_chrome_ext_downloads_saveAs.html | 68 + .../test_chrome_ext_eventpage_warning.html | 106 + .../test_chrome_ext_hybrid_addons.html | 141 + .../test/mochitest/test_chrome_ext_idle.html | 64 + .../test_chrome_ext_shutdown_cleanup.html | 50 + .../test_chrome_ext_storage_cleanup.html | 164 + .../test_chrome_ext_trustworthy_origin.html | 53 + ...hrome_ext_webnavigation_resolved_urls.html | 83 + ...rome_ext_webrequest_background_events.html | 96 + .../test_chrome_native_messaging_paths.html | 61 + .../test/mochitest/test_clipboard.html | 140 + .../test/mochitest/test_ext_all_apis.js | 160 + .../test_ext_background_api_injection.html | 46 + .../mochitest/test_ext_background_canvas.html | 47 + .../test_ext_background_generated_url.html | 47 + .../test_ext_background_teardown.html | 76 + .../test_ext_content_security_policy.html | 162 + .../mochitest/test_ext_contentscript.html | 116 + .../test_ext_contentscript_about_blank.html | 117 + .../test_ext_contentscript_api_injection.html | 88 + .../test_ext_contentscript_async_loading.html | 54 + .../test_ext_contentscript_context.html | 81 + .../test_ext_contentscript_create_iframe.html | 165 + .../mochitest/test_ext_contentscript_css.html | 48 + ...t_ext_contentscript_devtools_metadata.html | 81 + .../test_ext_contentscript_exporthelpers.html | 95 + .../test_ext_contentscript_incognito.html | 89 + .../test_ext_contentscript_permission.html | 59 + .../test_ext_contentscript_teardown.html | 96 + .../test/mochitest/test_ext_cookies.html | 234 + .../test_ext_cookies_containers.html | 93 + .../mochitest/test_ext_cookies_expiry.html | 72 + .../test_ext_cookies_permissions_bad.html | 112 + .../test_ext_cookies_permissions_good.html | 86 + .../test_ext_exclude_include_globs.html | 92 + .../test_ext_external_messaging.html | 111 + .../test/mochitest/test_ext_generate.html | 49 + .../test/mochitest/test_ext_geturl.html | 72 + .../test/mochitest/test_ext_i18n.html | 432 + .../test/mochitest/test_ext_i18n_css.html | 116 + .../test_ext_inIncognitoContext_window.html | 49 + .../test/mochitest/test_ext_jsversion.html | 86 + .../mochitest/test_ext_listener_proxies.html | 63 + .../mochitest/test_ext_notifications.html | 224 + .../mochitest/test_ext_permission_xhr.html | 119 + .../mochitest/test_ext_runtime_connect.html | 83 + .../mochitest/test_ext_runtime_connect2.html | 103 + .../test_ext_runtime_connect_twoway.html | 127 + .../test_ext_runtime_disconnect.html | 78 + .../test/mochitest/test_ext_runtime_id.html | 61 + .../test/mochitest/test_ext_sandbox_var.html | 60 + .../test/mochitest/test_ext_schema.html | 73 + .../test_ext_sendmessage_doublereply.html | 101 + .../test_ext_sendmessage_no_receiver.html | 83 + .../mochitest/test_ext_sendmessage_reply.html | 79 + .../test_ext_sendmessage_reply2.html | 181 + .../mochitest/test_ext_storage_content.html | 330 + .../test/mochitest/test_ext_storage_tab.html | 118 + .../test_ext_subframes_privileges.html | 202 + .../test/mochitest/test_ext_tab_teardown.html | 150 + .../test/mochitest/test_ext_test.html | 191 + .../test/mochitest/test_ext_unload_frame.html | 170 + .../test_ext_web_accessible_resources.html | 353 + .../mochitest/test_ext_webnavigation.html | 559 + .../test_ext_webnavigation_filters.html | 308 + ...test_ext_webrequest_background_events.html | 116 + .../mochitest/test_ext_webrequest_basic.html | 327 + .../test_ext_webrequest_suspend.html | 216 + .../mochitest/test_ext_webrequest_upload.html | 199 + .../test_ext_window_postMessage.html | 105 + .../mochitest/test_ext_xhr_capabilities.html | 86 + .../test/mochitest/webrequest_chromeworker.js | 8 + .../test/mochitest/webrequest_test.jsm | 22 + .../test/mochitest/webrequest_worker.js | 3 + .../webextensions/test/xpcshell/.eslintrc.js | 9 + .../test/xpcshell/data/file_download.html | 12 + .../test/xpcshell/data/file_download.txt | 1 + .../webextensions/test/xpcshell/head.js | 111 + .../test/xpcshell/head_native_messaging.js | 131 + .../webextensions/test/xpcshell/head_sync.js | 67 + .../test/xpcshell/native_messaging.ini | 13 + .../test/xpcshell/test_csp_custom_policies.js | 38 + .../test/xpcshell/test_csp_validator.js | 85 + .../test/xpcshell/test_ext_alarms.js | 210 + .../xpcshell/test_ext_alarms_does_not_fire.js | 33 + .../test/xpcshell/test_ext_alarms_periodic.js | 44 + .../test/xpcshell/test_ext_alarms_replaces.js | 44 + .../test/xpcshell/test_ext_api_permissions.js | 64 + .../test/xpcshell/test_ext_apimanager.js | 91 + ...st_ext_background_generated_load_events.js | 23 + .../test_ext_background_generated_reload.js | 24 + .../test_ext_background_global_history.js | 22 + .../test_ext_background_private_browsing.js | 40 + ...t_ext_background_runtime_connect_params.js | 72 + .../test_ext_background_sub_windows.js | 45 + .../test_ext_background_window_properties.js | 34 + .../test/xpcshell/test_ext_contexts.js | 190 + .../test/xpcshell/test_ext_downloads.js | 76 + .../xpcshell/test_ext_downloads_download.js | 354 + .../test/xpcshell/test_ext_downloads_misc.js | 862 ++ .../xpcshell/test_ext_downloads_search.js | 402 + .../test/xpcshell/test_ext_experiments.js | 175 + .../test/xpcshell/test_ext_extension.js | 55 + .../test/xpcshell/test_ext_idle.js | 202 + .../test/xpcshell/test_ext_json_parser.js | 37 + .../test_ext_legacy_extension_context.js | 168 + .../test_ext_legacy_extension_embedding.js | 188 + .../test/xpcshell/test_ext_localStorage.js | 50 + .../test/xpcshell/test_ext_management.js | 20 + .../test_ext_management_uninstall_self.js | 135 + ...st_ext_manifest_content_security_policy.js | 30 + .../xpcshell/test_ext_manifest_incognito.js | 27 + ...est_ext_manifest_minimum_chrome_version.js | 13 + .../xpcshell/test_ext_native_messaging.js | 514 + .../test_ext_native_messaging_perf.js | 128 + .../test_ext_native_messaging_unresponsive.js | 82 + .../test_ext_onmessage_removelistener.js | 30 + .../test_ext_runtime_connect_no_receiver.js | 23 + .../test_ext_runtime_getBrowserInfo.js | 26 + .../test_ext_runtime_getPlatformInfo.js | 25 + ...t_ext_runtime_onInstalled_and_onStartup.js | 337 + .../xpcshell/test_ext_runtime_sendMessage.js | 79 + .../test_ext_runtime_sendMessage_errors.js | 59 + ...est_ext_runtime_sendMessage_no_receiver.js | 54 + .../test_ext_runtime_sendMessage_self.js | 51 + .../test/xpcshell/test_ext_schemas.js | 1427 +++ .../test_ext_schemas_allowed_contexts.js | 147 + .../test_ext_schemas_api_injection.js | 102 + .../test/xpcshell/test_ext_schemas_async.js | 232 + .../test/xpcshell/test_ext_simple.js | 69 + .../test/xpcshell/test_ext_storage.js | 334 + .../test/xpcshell/test_ext_topSites.js | 85 + .../xpcshell/test_getAPILevelForWindow.js | 55 + .../test/xpcshell/test_locale_converter.js | 133 + .../test/xpcshell/test_locale_data.js | 130 + .../test/xpcshell/test_native_messaging.js | 302 + .../webextensions/test/xpcshell/xpcshell.ini | 69 + toolkit/jetpack/moz.build | 10 +- toolkit/jetpack/sdk/addon/bootstrap.js | 5 + toolkit/jetpack/sdk/webextension.js | 43 + .../chrome/mozapps/extensions/extensions.dtd | 27 + toolkit/locales/jar.mn | 2 +- toolkit/modules/moz.build | 4 +- toolkit/moz.build | 5 +- .../mozapps/extensions/content/newaddon.js | 13 + toolkit/mozapps/extensions/jar.mn | 2 +- .../webextensions/AddonContentPolicy.cpp | 478 + .../webextensions/AddonContentPolicy.h | 22 + .../mozapps/webextensions/AddonManager.jsm | 3666 +++++++ .../webextensions/AddonManagerWebAPI.cpp | 171 + .../webextensions/AddonManagerWebAPI.h | 33 + .../webextensions/AddonPathService.cpp | 258 + .../mozapps/webextensions/AddonPathService.h | 55 + .../webextensions/GMPInstallManager.jsm | 523 + .../webextensions/LightweightThemeManager.jsm | 909 ++ toolkit/mozapps/webextensions/addonManager.js | 296 + .../mozapps/webextensions/amInstallTrigger.js | 240 + toolkit/mozapps/webextensions/amWebAPI.js | 269 + .../webextensions/amWebInstallListener.js | 348 + .../mozapps/webextensions/content/about.js | 103 + toolkit/mozapps/webextensions/content/eula.js | 25 + .../webextensions/content/extensions.css | 270 + .../webextensions/content/extensions.js | 3827 +++++++ .../webextensions/content/extensions.xml | 2008 ++++ .../webextensions/content/extensions.xul | 715 ++ .../webextensions/content/newaddon.xul | 67 + .../mozapps/webextensions/content/setting.xml | 486 + .../mozapps/webextensions/content/update.js | 663 ++ .../mozapps/webextensions/content/update.xul | 194 + .../mozapps/webextensions/extensions.manifest | 18 + .../internal/APIExtensionBootstrap.js | 39 + .../webextensions/internal/AddonConstants.jsm | 31 + .../internal/AddonRepository.jsm | 1988 ++++ .../AddonRepository_SQLiteMigrator.jsm | 522 + .../webextensions/internal/GMPProvider.jsm | 699 ++ .../LightweightThemeImageOptimizer.jsm | 180 + .../webextensions/internal/PluginProvider.jsm | 600 ++ .../internal/WebExtensionBootstrap.js | 39 + .../webextensions/internal/XPIProvider.jsm | 9217 +++++++++++++++++ .../internal/XPIProviderUtils.js | 2239 ++++ .../mozapps/webextensions/internal/moz.build | 31 + toolkit/mozapps/webextensions/jar.mn | 35 + toolkit/mozapps/webextensions/moz.build | 57 + toolkit/themes/linux/mozapps/jar.mn | 18 + .../webextensions/category-available.png | Bin 0 -> 1092 bytes .../webextensions/category-discover.png | Bin 0 -> 1482 bytes .../webextensions/category-plugins.png | Bin 0 -> 1172 bytes .../mozapps/webextensions/category-recent.png | Bin 0 -> 2020 bytes .../mozapps/webextensions/category-search.png | Bin 0 -> 2600 bytes .../webextensions/category-service.png | Bin 0 -> 2063 bytes .../webextensions/dictionaryGeneric-16.png | Bin 0 -> 584 bytes .../webextensions/dictionaryGeneric.png | Bin 0 -> 1290 bytes .../webextensions/extensionGeneric-16.png | Bin 0 -> 713 bytes .../mozapps/webextensions/extensions.css | 42 + .../linux/mozapps/webextensions/heart.png | Bin 0 -> 2949 bytes .../mozapps/webextensions/localeGeneric.png | Bin 0 -> 1860 bytes .../linux/mozapps/webextensions/newaddon.css | 5 + .../mozapps/webextensions/themeGeneric-16.png | Bin 0 -> 638 bytes .../mozapps/webextensions/themeGeneric.png | Bin 0 -> 1734 bytes toolkit/themes/osx/mozapps/jar.mn | 40 + .../osx/mozapps/webextensions/about.css | 78 + .../osx/mozapps/webextensions/blocklist.css | 20 + .../osx/mozapps/webextensions/cancel.png | Bin 0 -> 115 bytes .../webextensions/category-available.png | Bin 0 -> 1671 bytes .../webextensions/category-dictionaries.png | Bin 0 -> 1769 bytes .../webextensions/category-discover.png | Bin 0 -> 1324 bytes .../webextensions/category-experiments.png | Bin 0 -> 822 bytes .../webextensions/category-plugins.png | Bin 0 -> 886 bytes .../mozapps/webextensions/category-recent.png | Bin 0 -> 1642 bytes .../mozapps/webextensions/category-search.png | Bin 0 -> 2600 bytes .../webextensions/category-service.png | Bin 0 -> 2063 bytes .../webextensions/dictionaryGeneric-16.png | Bin 0 -> 742 bytes .../webextensions/dictionaryGeneric.png | Bin 0 -> 1769 bytes .../mozapps/webextensions/discover-logo.png | Bin 0 -> 12007 bytes .../themes/osx/mozapps/webextensions/eula.css | 47 + .../webextensions/experimentGeneric.png | Bin 0 -> 822 bytes .../webextensions/extensionGeneric-16.png | Bin 0 -> 554 bytes .../osx/mozapps/webextensions/extensions.css | 51 + .../osx/mozapps/webextensions/heart.png | Bin 0 -> 2949 bytes .../mozapps/webextensions/localeGeneric.png | Bin 0 -> 2410 bytes .../osx/mozapps/webextensions/newaddon.css | 5 + .../mozapps/webextensions/rating-not-won.png | Bin 0 -> 1559 bytes .../osx/mozapps/webextensions/rating-won.png | Bin 0 -> 1662 bytes .../osx/mozapps/webextensions/search.png | Bin 0 -> 423 bytes .../mozapps/webextensions/themeGeneric-16.png | Bin 0 -> 710 bytes .../mozapps/webextensions/themeGeneric.png | Bin 0 -> 2185 bytes .../toolbarbutton-dropmarker.png | Bin 0 -> 147 bytes .../osx/mozapps/webextensions/update.css | 28 + .../webextensions/xpinstallConfirm.css | 90 + toolkit/themes/shared/non-mac.jar.inc.mn | 25 + toolkit/themes/windows/mozapps/jar.mn | 18 + .../windows/mozapps/webextensions/about.css | 91 + .../mozapps/webextensions/blocklist.css | 20 + .../windows/mozapps/webextensions/cancel.png | Bin 0 -> 115 bytes .../webextensions/category-available.png | Bin 0 -> 2235 bytes .../webextensions/category-discover.png | Bin 0 -> 1355 bytes .../webextensions/category-plugins.png | Bin 0 -> 962 bytes .../mozapps/webextensions/category-recent.png | Bin 0 -> 2251 bytes .../mozapps/webextensions/category-search.png | Bin 0 -> 2600 bytes .../webextensions/category-service.png | Bin 0 -> 2063 bytes .../webextensions/dictionaryGeneric-16.png | Bin 0 -> 733 bytes .../webextensions/dictionaryGeneric.png | Bin 0 -> 1665 bytes .../mozapps/webextensions/discover-logo.png | Bin 0 -> 12007 bytes .../windows/mozapps/webextensions/eula.css | 47 + .../webextensions/experimentGeneric.png | Bin 0 -> 822 bytes .../webextensions/extensionGeneric-16.png | Bin 0 -> 418 bytes .../mozapps/webextensions/extensions.css | 42 + .../windows/mozapps/webextensions/heart.png | Bin 0 -> 2949 bytes .../mozapps/webextensions/localeGeneric.png | Bin 0 -> 2518 bytes .../mozapps/webextensions/newaddon.css | 5 + .../mozapps/webextensions/rating-not-won.png | Bin 0 -> 1559 bytes .../mozapps/webextensions/rating-won.png | Bin 0 -> 1662 bytes .../mozapps/webextensions/themeGeneric-16.png | Bin 0 -> 837 bytes .../mozapps/webextensions/themeGeneric.png | Bin 0 -> 2094 bytes .../windows/mozapps/webextensions/update.css | 28 + .../webextensions/xpinstallConfirm.css | 101 + 416 files changed, 81535 insertions(+), 8 deletions(-) create mode 100644 application/basilisk/components/webextensions/.eslintrc.js create mode 100644 application/basilisk/components/webextensions/ext-bookmarks.js create mode 100644 application/basilisk/components/webextensions/ext-browserAction.js create mode 100644 application/basilisk/components/webextensions/ext-c-contextMenus.js create mode 100644 application/basilisk/components/webextensions/ext-c-omnibox.js create mode 100644 application/basilisk/components/webextensions/ext-c-tabs.js create mode 100644 application/basilisk/components/webextensions/ext-commands.js create mode 100644 application/basilisk/components/webextensions/ext-contextMenus.js create mode 100644 application/basilisk/components/webextensions/ext-desktop-runtime.js create mode 100644 application/basilisk/components/webextensions/ext-history.js create mode 100644 application/basilisk/components/webextensions/ext-omnibox.js create mode 100644 application/basilisk/components/webextensions/ext-pageAction.js create mode 100644 application/basilisk/components/webextensions/ext-sessions.js create mode 100644 application/basilisk/components/webextensions/ext-tabs.js create mode 100644 application/basilisk/components/webextensions/ext-utils.js create mode 100644 application/basilisk/components/webextensions/ext-windows.js create mode 100644 application/basilisk/components/webextensions/extension-mac-panel.css create mode 100644 application/basilisk/components/webextensions/extension-mac.css create mode 100644 application/basilisk/components/webextensions/extension-win-panel.css create mode 100644 application/basilisk/components/webextensions/extension.css create mode 100644 application/basilisk/components/webextensions/extension.svg create mode 100644 application/basilisk/components/webextensions/extensions-browser.manifest create mode 100644 application/basilisk/components/webextensions/jar.mn create mode 100644 application/basilisk/components/webextensions/moz.build create mode 100644 application/basilisk/components/webextensions/schemas/LICENSE create mode 100644 application/basilisk/components/webextensions/schemas/bookmarks.json create mode 100644 application/basilisk/components/webextensions/schemas/browser_action.json create mode 100644 application/basilisk/components/webextensions/schemas/commands.json create mode 100644 application/basilisk/components/webextensions/schemas/context_menus.json create mode 100644 application/basilisk/components/webextensions/schemas/context_menus_internal.json create mode 100644 application/basilisk/components/webextensions/schemas/history.json create mode 100644 application/basilisk/components/webextensions/schemas/jar.mn create mode 100644 application/basilisk/components/webextensions/schemas/moz.build create mode 100644 application/basilisk/components/webextensions/schemas/omnibox.json create mode 100644 application/basilisk/components/webextensions/schemas/page_action.json create mode 100644 application/basilisk/components/webextensions/schemas/sessions.json create mode 100644 application/basilisk/components/webextensions/schemas/tabs.json create mode 100644 application/basilisk/components/webextensions/schemas/windows.json create mode 100644 dom/webidl/AddonEvent.webidl create mode 100644 dom/webidl/AddonManager.webidl create mode 100644 toolkit/components/blocklist/nsBlocklistServiceContent.js create mode 100644 toolkit/components/webextensions/.eslintrc.js create mode 100644 toolkit/components/webextensions/Extension.jsm create mode 100644 toolkit/components/webextensions/ExtensionAPI.jsm create mode 100644 toolkit/components/webextensions/ExtensionChild.jsm create mode 100644 toolkit/components/webextensions/ExtensionCommon.jsm create mode 100644 toolkit/components/webextensions/ExtensionContent.jsm create mode 100644 toolkit/components/webextensions/ExtensionManagement.jsm create mode 100644 toolkit/components/webextensions/ExtensionParent.jsm create mode 100644 toolkit/components/webextensions/ExtensionStorage.jsm create mode 100644 toolkit/components/webextensions/ExtensionTestCommon.jsm create mode 100644 toolkit/components/webextensions/ExtensionUtils.jsm create mode 100644 toolkit/components/webextensions/ExtensionXPCShellUtils.jsm create mode 100644 toolkit/components/webextensions/LegacyExtensionsUtils.jsm create mode 100644 toolkit/components/webextensions/MessageChannel.jsm create mode 100644 toolkit/components/webextensions/NativeMessaging.jsm create mode 100644 toolkit/components/webextensions/Schemas.jsm create mode 100644 toolkit/components/webextensions/ext-alarms.js create mode 100644 toolkit/components/webextensions/ext-backgroundPage.js create mode 100644 toolkit/components/webextensions/ext-browser-content.js create mode 100644 toolkit/components/webextensions/ext-c-backgroundPage.js create mode 100644 toolkit/components/webextensions/ext-c-extension.js create mode 100644 toolkit/components/webextensions/ext-c-runtime.js create mode 100644 toolkit/components/webextensions/ext-c-storage.js create mode 100644 toolkit/components/webextensions/ext-c-test.js create mode 100644 toolkit/components/webextensions/ext-cookies.js create mode 100644 toolkit/components/webextensions/ext-downloads.js create mode 100644 toolkit/components/webextensions/ext-extension.js create mode 100644 toolkit/components/webextensions/ext-i18n.js create mode 100644 toolkit/components/webextensions/ext-idle.js create mode 100644 toolkit/components/webextensions/ext-management.js create mode 100644 toolkit/components/webextensions/ext-notifications.js create mode 100644 toolkit/components/webextensions/ext-runtime.js create mode 100644 toolkit/components/webextensions/ext-storage.js create mode 100644 toolkit/components/webextensions/ext-topSites.js create mode 100644 toolkit/components/webextensions/ext-webNavigation.js create mode 100644 toolkit/components/webextensions/ext-webRequest.js create mode 100644 toolkit/components/webextensions/extensions-toolkit.manifest create mode 100644 toolkit/components/webextensions/jar.mn create mode 100644 toolkit/components/webextensions/moz.build create mode 100644 toolkit/components/webextensions/schemas/LICENSE create mode 100644 toolkit/components/webextensions/schemas/alarms.json create mode 100644 toolkit/components/webextensions/schemas/cookies.json create mode 100644 toolkit/components/webextensions/schemas/downloads.json create mode 100644 toolkit/components/webextensions/schemas/events.json create mode 100644 toolkit/components/webextensions/schemas/experiments.json create mode 100644 toolkit/components/webextensions/schemas/extension.json create mode 100644 toolkit/components/webextensions/schemas/extension_types.json create mode 100644 toolkit/components/webextensions/schemas/i18n.json create mode 100644 toolkit/components/webextensions/schemas/idle.json create mode 100644 toolkit/components/webextensions/schemas/jar.mn create mode 100644 toolkit/components/webextensions/schemas/management.json create mode 100644 toolkit/components/webextensions/schemas/manifest.json create mode 100644 toolkit/components/webextensions/schemas/moz.build create mode 100644 toolkit/components/webextensions/schemas/native_host_manifest.json create mode 100644 toolkit/components/webextensions/schemas/notifications.json create mode 100644 toolkit/components/webextensions/schemas/runtime.json create mode 100644 toolkit/components/webextensions/schemas/storage.json create mode 100644 toolkit/components/webextensions/schemas/test.json create mode 100644 toolkit/components/webextensions/schemas/top_sites.json create mode 100644 toolkit/components/webextensions/schemas/web_navigation.json create mode 100644 toolkit/components/webextensions/schemas/web_request.json create mode 100644 toolkit/components/webextensions/test/mochitest/.eslintrc.js create mode 100644 toolkit/components/webextensions/test/mochitest/chrome.ini create mode 100644 toolkit/components/webextensions/test/mochitest/chrome_head.js create mode 100644 toolkit/components/webextensions/test/mochitest/file_WebNavigation_page1.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_WebNavigation_page2.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_WebNavigation_page3.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_WebRequest_page3.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_csp.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_csp.html^headers^ create mode 100644 toolkit/components/webextensions/test/mochitest/file_ext_test_api_injection.js create mode 100644 toolkit/components/webextensions/test/mochitest/file_image_bad.png create mode 100644 toolkit/components/webextensions/test/mochitest/file_image_good.png create mode 100644 toolkit/components/webextensions/test/mochitest/file_image_redirect.png create mode 100644 toolkit/components/webextensions/test/mochitest/file_mixed.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_permission_xhr.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_privilege_escalation.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_sample.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_script_bad.js create mode 100644 toolkit/components/webextensions/test/mochitest/file_script_good.js create mode 100644 toolkit/components/webextensions/test/mochitest/file_script_redirect.js create mode 100644 toolkit/components/webextensions/test/mochitest/file_script_xhr.js create mode 100644 toolkit/components/webextensions/test/mochitest/file_style_bad.css create mode 100644 toolkit/components/webextensions/test/mochitest/file_style_good.css create mode 100644 toolkit/components/webextensions/test/mochitest/file_style_redirect.css create mode 100644 toolkit/components/webextensions/test/mochitest/file_teardown_test.js create mode 100644 toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html^headers^ create mode 100644 toolkit/components/webextensions/test/mochitest/file_webNavigation_frameClientRedirect.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_webNavigation_frameRedirect.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page1.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page2.html create mode 100644 toolkit/components/webextensions/test/mochitest/file_with_about_blank.html create mode 100644 toolkit/components/webextensions/test/mochitest/head.js create mode 100644 toolkit/components/webextensions/test/mochitest/head_cookies.js create mode 100644 toolkit/components/webextensions/test/mochitest/head_webrequest.js create mode 100644 toolkit/components/webextensions/test/mochitest/mochitest.ini create mode 100644 toolkit/components/webextensions/test/mochitest/redirection.sjs create mode 100644 toolkit/components/webextensions/test/mochitest/return_headers.sjs create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_debug_global.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_page.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_contentscript_unrecognizedprop_warning.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_downloads_saveAs.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_eventpage_warning.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_hybrid_addons.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_idle.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_shutdown_cleanup.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_storage_cleanup.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_trustworthy_origin.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_webnavigation_resolved_urls.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_ext_webrequest_background_events.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_chrome_native_messaging_paths.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_clipboard.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_all_apis.js create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_background_api_injection.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_background_canvas.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_background_generated_url.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_background_teardown.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_content_security_policy.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript_about_blank.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript_api_injection.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript_async_loading.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript_context.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript_create_iframe.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript_css.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript_devtools_metadata.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript_exporthelpers.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript_incognito.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript_permission.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_contentscript_teardown.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_cookies.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_cookies_containers.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_cookies_expiry.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_bad.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_good.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_exclude_include_globs.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_external_messaging.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_generate.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_geturl.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_i18n.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_i18n_css.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_inIncognitoContext_window.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_jsversion.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_listener_proxies.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_notifications.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_permission_xhr.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect2.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect_twoway.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_runtime_disconnect.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_runtime_id.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_sandbox_var.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_schema.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_doublereply.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_no_receiver.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply2.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_storage_content.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_storage_tab.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_subframes_privileges.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_tab_teardown.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_test.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_unload_frame.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_web_accessible_resources.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_webnavigation.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_webnavigation_filters.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_webrequest_background_events.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_webrequest_basic.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_webrequest_suspend.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_webrequest_upload.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_window_postMessage.html create mode 100644 toolkit/components/webextensions/test/mochitest/test_ext_xhr_capabilities.html create mode 100644 toolkit/components/webextensions/test/mochitest/webrequest_chromeworker.js create mode 100644 toolkit/components/webextensions/test/mochitest/webrequest_test.jsm create mode 100644 toolkit/components/webextensions/test/mochitest/webrequest_worker.js create mode 100644 toolkit/components/webextensions/test/xpcshell/.eslintrc.js create mode 100644 toolkit/components/webextensions/test/xpcshell/data/file_download.html create mode 100644 toolkit/components/webextensions/test/xpcshell/data/file_download.txt create mode 100644 toolkit/components/webextensions/test/xpcshell/head.js create mode 100644 toolkit/components/webextensions/test/xpcshell/head_native_messaging.js create mode 100644 toolkit/components/webextensions/test/xpcshell/head_sync.js create mode 100644 toolkit/components/webextensions/test/xpcshell/native_messaging.ini create mode 100644 toolkit/components/webextensions/test/xpcshell/test_csp_custom_policies.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_csp_validator.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_alarms.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_alarms_does_not_fire.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_alarms_periodic.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_alarms_replaces.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_api_permissions.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_apimanager.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_load_events.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_reload.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_background_global_history.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_background_private_browsing.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_background_runtime_connect_params.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_background_sub_windows.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_background_window_properties.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_contexts.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_downloads.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_downloads_download.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_downloads_misc.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_downloads_search.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_experiments.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_extension.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_idle.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_json_parser.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_context.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_embedding.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_localStorage.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_management.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_management_uninstall_self.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_manifest_content_security_policy.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_manifest_incognito.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_manifest_minimum_chrome_version.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_perf.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_unresponsive.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_onmessage_removelistener.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_runtime_connect_no_receiver.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getBrowserInfo.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getPlatformInfo.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_runtime_onInstalled_and_onStartup.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_errors.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_no_receiver.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_self.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_schemas.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_schemas_allowed_contexts.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_schemas_api_injection.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_schemas_async.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_simple.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_storage.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_ext_topSites.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_getAPILevelForWindow.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_locale_converter.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_locale_data.js create mode 100644 toolkit/components/webextensions/test/xpcshell/test_native_messaging.js create mode 100644 toolkit/components/webextensions/test/xpcshell/xpcshell.ini create mode 100644 toolkit/jetpack/sdk/webextension.js create mode 100644 toolkit/mozapps/webextensions/AddonContentPolicy.cpp create mode 100644 toolkit/mozapps/webextensions/AddonContentPolicy.h create mode 100644 toolkit/mozapps/webextensions/AddonManager.jsm create mode 100644 toolkit/mozapps/webextensions/AddonManagerWebAPI.cpp create mode 100644 toolkit/mozapps/webextensions/AddonManagerWebAPI.h create mode 100644 toolkit/mozapps/webextensions/AddonPathService.cpp create mode 100644 toolkit/mozapps/webextensions/AddonPathService.h create mode 100644 toolkit/mozapps/webextensions/GMPInstallManager.jsm create mode 100644 toolkit/mozapps/webextensions/LightweightThemeManager.jsm create mode 100644 toolkit/mozapps/webextensions/addonManager.js create mode 100644 toolkit/mozapps/webextensions/amInstallTrigger.js create mode 100644 toolkit/mozapps/webextensions/amWebAPI.js create mode 100644 toolkit/mozapps/webextensions/amWebInstallListener.js create mode 100644 toolkit/mozapps/webextensions/content/about.js create mode 100644 toolkit/mozapps/webextensions/content/eula.js create mode 100644 toolkit/mozapps/webextensions/content/extensions.css create mode 100644 toolkit/mozapps/webextensions/content/extensions.js create mode 100644 toolkit/mozapps/webextensions/content/extensions.xml create mode 100644 toolkit/mozapps/webextensions/content/extensions.xul create mode 100644 toolkit/mozapps/webextensions/content/newaddon.xul create mode 100644 toolkit/mozapps/webextensions/content/setting.xml create mode 100644 toolkit/mozapps/webextensions/content/update.js create mode 100644 toolkit/mozapps/webextensions/content/update.xul create mode 100644 toolkit/mozapps/webextensions/extensions.manifest create mode 100644 toolkit/mozapps/webextensions/internal/APIExtensionBootstrap.js create mode 100644 toolkit/mozapps/webextensions/internal/AddonConstants.jsm create mode 100644 toolkit/mozapps/webextensions/internal/AddonRepository.jsm create mode 100644 toolkit/mozapps/webextensions/internal/AddonRepository_SQLiteMigrator.jsm create mode 100644 toolkit/mozapps/webextensions/internal/GMPProvider.jsm create mode 100644 toolkit/mozapps/webextensions/internal/LightweightThemeImageOptimizer.jsm create mode 100644 toolkit/mozapps/webextensions/internal/PluginProvider.jsm create mode 100644 toolkit/mozapps/webextensions/internal/WebExtensionBootstrap.js create mode 100644 toolkit/mozapps/webextensions/internal/XPIProvider.jsm create mode 100644 toolkit/mozapps/webextensions/internal/XPIProviderUtils.js create mode 100644 toolkit/mozapps/webextensions/internal/moz.build create mode 100644 toolkit/mozapps/webextensions/jar.mn create mode 100644 toolkit/mozapps/webextensions/moz.build create mode 100644 toolkit/themes/linux/mozapps/webextensions/category-available.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/category-discover.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/category-plugins.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/category-recent.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/category-search.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/category-service.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/dictionaryGeneric-16.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/dictionaryGeneric.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/extensionGeneric-16.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/extensions.css create mode 100644 toolkit/themes/linux/mozapps/webextensions/heart.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/localeGeneric.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/newaddon.css create mode 100644 toolkit/themes/linux/mozapps/webextensions/themeGeneric-16.png create mode 100644 toolkit/themes/linux/mozapps/webextensions/themeGeneric.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/about.css create mode 100644 toolkit/themes/osx/mozapps/webextensions/blocklist.css create mode 100644 toolkit/themes/osx/mozapps/webextensions/cancel.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/category-available.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/category-dictionaries.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/category-discover.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/category-experiments.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/category-plugins.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/category-recent.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/category-search.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/category-service.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/dictionaryGeneric-16.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/dictionaryGeneric.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/discover-logo.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/eula.css create mode 100644 toolkit/themes/osx/mozapps/webextensions/experimentGeneric.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/extensionGeneric-16.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/extensions.css create mode 100644 toolkit/themes/osx/mozapps/webextensions/heart.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/localeGeneric.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/newaddon.css create mode 100644 toolkit/themes/osx/mozapps/webextensions/rating-not-won.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/rating-won.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/search.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/themeGeneric-16.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/themeGeneric.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/toolbarbutton-dropmarker.png create mode 100644 toolkit/themes/osx/mozapps/webextensions/update.css create mode 100644 toolkit/themes/osx/mozapps/webextensions/xpinstallConfirm.css create mode 100644 toolkit/themes/windows/mozapps/webextensions/about.css create mode 100644 toolkit/themes/windows/mozapps/webextensions/blocklist.css create mode 100644 toolkit/themes/windows/mozapps/webextensions/cancel.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/category-available.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/category-discover.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/category-plugins.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/category-recent.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/category-search.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/category-service.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/dictionaryGeneric-16.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/dictionaryGeneric.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/discover-logo.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/eula.css create mode 100644 toolkit/themes/windows/mozapps/webextensions/experimentGeneric.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/extensionGeneric-16.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/extensions.css create mode 100644 toolkit/themes/windows/mozapps/webextensions/heart.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/localeGeneric.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/newaddon.css create mode 100644 toolkit/themes/windows/mozapps/webextensions/rating-not-won.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/rating-won.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/themeGeneric-16.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/themeGeneric.png create mode 100644 toolkit/themes/windows/mozapps/webextensions/update.css create mode 100644 toolkit/themes/windows/mozapps/webextensions/xpinstallConfirm.css diff --git a/application/basilisk/base/content/tab-content.js b/application/basilisk/base/content/tab-content.js index 7441b2140..6d053dd2b 100644 --- a/application/basilisk/base/content/tab-content.js +++ b/application/basilisk/base/content/tab-content.js @@ -9,6 +9,9 @@ var {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; Cu.import("resource://gre/modules/XPCOMUtils.jsm"); Cu.import("resource://gre/modules/Services.jsm"); +#ifdef MOZ_WEBEXTENSIONS +Cu.import("resource://gre/modules/ExtensionContent.jsm"); +#endif XPCOMUtils.defineLazyModuleGetter(this, "E10SUtils", "resource:///modules/E10SUtils.jsm"); @@ -913,6 +916,14 @@ var UserContextIdNotifier = { UserContextIdNotifier.init(); +#ifdef MOZ_WEBEXTENSIONS +ExtensionContent.init(this); +addEventListener("unload", () => { + ExtensionContent.uninit(this); + RefreshBlocker.uninit(); +}); +#endif + addMessageListener("AllowScriptsToClose", () => { content.QueryInterface(Ci.nsIInterfaceRequestor) .getInterface(Ci.nsIDOMWindowUtils) diff --git a/application/basilisk/base/content/urlbarBindings.xml b/application/basilisk/base/content/urlbarBindings.xml index b9c17818a..4c010bffb 100644 --- a/application/basilisk/base/content/urlbarBindings.xml +++ b/application/basilisk/base/content/urlbarBindings.xml @@ -56,6 +56,11 @@ file, You can obtain one at http://mozilla.org/MPL/2.0/. (Components.utils.import("resource://gre/modules/AppConstants.jsm", {})).AppConstants; +#ifdef MOZ_WEBEXTENSIONS + + (Components.utils.import("resource://gre/modules/ExtensionSearchHandler.jsm", {})).ExtensionSearchHandler; + +#endif convert(child, node)); + } + } + + return treenode; + } + + return PlacesUtils.promiseBookmarksTree(rootGuid, { + excludeItemsCallback: item => { + if (item.type == PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR) { + return true; + } + return item.annos && + item.annos.find(a => a.name == PlacesUtils.EXCLUDE_FROM_BACKUP_ANNO); + }, + }).then(root => { + if (onlyChildren) { + let children = root.children || []; + return children.map(child => convert(child, root)); + } + // It seems like the array always just contains the root node. + return [convert(root, null)]; + }).catch(e => Promise.reject({message: e.message})); +} + +function convert(result) { + let node = { + id: result.guid, + title: result.title || "", + index: result.index, + dateAdded: result.dateAdded.getTime(), + }; + + if (result.guid != PlacesUtils.bookmarks.rootGuid) { + node.parentId = result.parentGuid; + } + + if (result.type == PlacesUtils.bookmarks.TYPE_BOOKMARK) { + node.url = result.url.href; // Output is always URL object. + } else { + node.dateGroupModified = result.lastModified.getTime(); + } + + return node; +} + +let observer = { + skipTags: true, + skipDescendantsOnItemRemoval: true, + + onBeginUpdateBatch() {}, + onEndUpdateBatch() {}, + + onItemAdded(id, parentId, index, itemType, uri, title, dateAdded, guid, parentGuid, source) { + if (itemType == PlacesUtils.bookmarks.TYPE_SEPARATOR) { + return; + } + + let bookmark = { + id: guid, + parentId: parentGuid, + index, + title, + dateAdded: dateAdded / 1000, + }; + + if (itemType == PlacesUtils.bookmarks.TYPE_BOOKMARK) { + bookmark.url = uri.spec; + } else { + bookmark.dateGroupModified = bookmark.dateAdded; + } + + this.emit("created", bookmark); + }, + + onItemVisited() {}, + + onItemMoved(id, oldParentId, oldIndex, newParentId, newIndex, itemType, guid, oldParentGuid, newParentGuid, source) { + if (itemType == PlacesUtils.bookmarks.TYPE_SEPARATOR) { + return; + } + + let info = { + parentId: newParentGuid, + index: newIndex, + oldParentId: oldParentGuid, + oldIndex, + }; + this.emit("moved", {guid, info}); + }, + + onItemRemoved(id, parentId, index, itemType, uri, guid, parentGuid, source) { + if (itemType == PlacesUtils.bookmarks.TYPE_SEPARATOR) { + return; + } + + let node = { + id: guid, + parentId: parentGuid, + index, + }; + + if (itemType == PlacesUtils.bookmarks.TYPE_BOOKMARK) { + node.url = uri.spec; + } + + this.emit("removed", {guid, info: {parentId: parentGuid, index, node}}); + }, + + onItemChanged(id, prop, isAnno, val, lastMod, itemType, parentId, guid, parentGuid, oldVal, source) { + if (itemType == PlacesUtils.bookmarks.TYPE_SEPARATOR) { + return; + } + + let info = {}; + if (prop == "title") { + info.title = val; + } else if (prop == "uri") { + info.url = val; + } else { + // Not defined yet. + return; + } + + this.emit("changed", {guid, info}); + }, +}; +EventEmitter.decorate(observer); + +function decrementListeners() { + listenerCount -= 1; + if (!listenerCount) { + PlacesUtils.bookmarks.removeObserver(observer); + } +} + +function incrementListeners() { + listenerCount++; + if (listenerCount == 1) { + PlacesUtils.bookmarks.addObserver(observer, false); + } +} + +extensions.registerSchemaAPI("bookmarks", "addon_parent", context => { + return { + bookmarks: { + get: function(idOrIdList) { + let list = Array.isArray(idOrIdList) ? idOrIdList : [idOrIdList]; + + return Task.spawn(function* () { + let bookmarks = []; + for (let id of list) { + let bookmark = yield PlacesUtils.bookmarks.fetch({guid: id}); + if (!bookmark) { + throw new Error("Bookmark not found"); + } + bookmarks.push(convert(bookmark)); + } + return bookmarks; + }).catch(error => Promise.reject({message: error.message})); + }, + + getChildren: function(id) { + // TODO: We should optimize this. + return getTree(id, true); + }, + + getTree: function() { + return getTree(PlacesUtils.bookmarks.rootGuid, false); + }, + + getSubTree: function(id) { + return getTree(id, false); + }, + + search: function(query) { + return PlacesUtils.bookmarks.search(query).then(result => result.map(convert)); + }, + + getRecent: function(numberOfItems) { + return PlacesUtils.bookmarks.getRecent(numberOfItems).then(result => result.map(convert)); + }, + + create: function(bookmark) { + let info = { + title: bookmark.title || "", + }; + + // If url is NULL or missing, it will be a folder. + if (bookmark.url !== null) { + info.type = PlacesUtils.bookmarks.TYPE_BOOKMARK; + info.url = bookmark.url || ""; + } else { + info.type = PlacesUtils.bookmarks.TYPE_FOLDER; + } + + if (bookmark.index !== null) { + info.index = bookmark.index; + } + + if (bookmark.parentId !== null) { + info.parentGuid = bookmark.parentId; + } else { + info.parentGuid = PlacesUtils.bookmarks.unfiledGuid; + } + + try { + return PlacesUtils.bookmarks.insert(info).then(convert) + .catch(error => Promise.reject({message: error.message})); + } catch (e) { + return Promise.reject({message: `Invalid bookmark: ${JSON.stringify(info)}`}); + } + }, + + move: function(id, destination) { + let info = { + guid: id, + }; + + if (destination.parentId !== null) { + info.parentGuid = destination.parentId; + } + info.index = (destination.index === null) ? + PlacesUtils.bookmarks.DEFAULT_INDEX : destination.index; + + try { + return PlacesUtils.bookmarks.update(info).then(convert) + .catch(error => Promise.reject({message: error.message})); + } catch (e) { + return Promise.reject({message: `Invalid bookmark: ${JSON.stringify(info)}`}); + } + }, + + update: function(id, changes) { + let info = { + guid: id, + }; + + if (changes.title !== null) { + info.title = changes.title; + } + if (changes.url !== null) { + info.url = changes.url; + } + + try { + return PlacesUtils.bookmarks.update(info).then(convert) + .catch(error => Promise.reject({message: error.message})); + } catch (e) { + return Promise.reject({message: `Invalid bookmark: ${JSON.stringify(info)}`}); + } + }, + + remove: function(id) { + let info = { + guid: id, + }; + + // The API doesn't give you the old bookmark at the moment + try { + return PlacesUtils.bookmarks.remove(info, {preventRemovalOfNonEmptyFolders: true}).then(result => {}) + .catch(error => Promise.reject({message: error.message})); + } catch (e) { + return Promise.reject({message: `Invalid bookmark: ${JSON.stringify(info)}`}); + } + }, + + removeTree: function(id) { + let info = { + guid: id, + }; + + try { + return PlacesUtils.bookmarks.remove(info).then(result => {}) + .catch(error => Promise.reject({message: error.message})); + } catch (e) { + return Promise.reject({message: `Invalid bookmark: ${JSON.stringify(info)}`}); + } + }, + + onCreated: new SingletonEventManager(context, "bookmarks.onCreated", fire => { + let listener = (event, bookmark) => { + context.runSafe(fire, bookmark.id, bookmark); + }; + + observer.on("created", listener); + incrementListeners(); + return () => { + observer.off("created", listener); + decrementListeners(); + }; + }).api(), + + onRemoved: new SingletonEventManager(context, "bookmarks.onRemoved", fire => { + let listener = (event, data) => { + context.runSafe(fire, data.guid, data.info); + }; + + observer.on("removed", listener); + incrementListeners(); + return () => { + observer.off("removed", listener); + decrementListeners(); + }; + }).api(), + + onChanged: new SingletonEventManager(context, "bookmarks.onChanged", fire => { + let listener = (event, data) => { + context.runSafe(fire, data.guid, data.info); + }; + + observer.on("changed", listener); + incrementListeners(); + return () => { + observer.off("changed", listener); + decrementListeners(); + }; + }).api(), + + onMoved: new SingletonEventManager(context, "bookmarks.onMoved", fire => { + let listener = (event, data) => { + context.runSafe(fire, data.guid, data.info); + }; + + observer.on("moved", listener); + incrementListeners(); + return () => { + observer.off("moved", listener); + decrementListeners(); + }; + }).api(), + }, + }; +}); diff --git a/application/basilisk/components/webextensions/ext-browserAction.js b/application/basilisk/components/webextensions/ext-browserAction.js new file mode 100644 index 000000000..2c82ac701 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-browserAction.js @@ -0,0 +1,531 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +XPCOMUtils.defineLazyModuleGetter(this, "CustomizableUI", + "resource:///modules/CustomizableUI.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "clearTimeout", + "resource://gre/modules/Timer.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "setTimeout", + "resource://gre/modules/Timer.jsm"); + +XPCOMUtils.defineLazyServiceGetter(this, "DOMUtils", + "@mozilla.org/inspector/dom-utils;1", + "inIDOMUtils"); + +Cu.import("resource://devtools/shared/event-emitter.js"); +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +Cu.import("resource://gre/modules/Task.jsm"); + +var { + EventManager, + IconDetails, +} = ExtensionUtils; + +const POPUP_PRELOAD_TIMEOUT_MS = 200; + +const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; + +function isAncestorOrSelf(target, node) { + for (; node; node = node.parentNode) { + if (node === target) { + return true; + } + } + return false; +} + +// WeakMap[Extension -> BrowserAction] +var browserActionMap = new WeakMap(); + +// Responsible for the browser_action section of the manifest as well +// as the associated popup. +function BrowserAction(options, extension) { + this.extension = extension; + + let widgetId = makeWidgetId(extension.id); + this.id = `${widgetId}-browser-action`; + this.viewId = `PanelUI-webext-${widgetId}-browser-action-view`; + this.widget = null; + + this.pendingPopup = null; + this.pendingPopupTimeout = null; + + this.tabManager = TabManager.for(extension); + + this.defaults = { + enabled: true, + title: options.default_title || extension.name, + badgeText: "", + badgeBackgroundColor: null, + icon: IconDetails.normalize({path: options.default_icon}, extension), + popup: options.default_popup || "", + }; + + this.browserStyle = options.browser_style || false; + if (options.browser_style === null) { + this.extension.logger.warn("Please specify whether you want browser_style " + + "or not in your browser_action options."); + } + + this.tabContext = new TabContext(tab => Object.create(this.defaults), + extension); + + EventEmitter.decorate(this); +} + +BrowserAction.prototype = { + build() { + let widget = CustomizableUI.createWidget({ + id: this.id, + viewId: this.viewId, + type: "view", + removable: true, + label: this.defaults.title || this.extension.name, + tooltiptext: this.defaults.title || "", + defaultArea: CustomizableUI.AREA_NAVBAR, + + onBeforeCreated: document => { + let view = document.createElementNS(XUL_NS, "panelview"); + view.id = this.viewId; + view.setAttribute("flex", "1"); + + document.getElementById("PanelUI-multiView").appendChild(view); + }, + + onDestroyed: document => { + let view = document.getElementById(this.viewId); + if (view) { + this.clearPopup(); + CustomizableUI.hidePanelForNode(view); + view.remove(); + } + }, + + onCreated: node => { + node.classList.add("badged-button"); + node.classList.add("webextension-browser-action"); + node.setAttribute("constrain-size", "true"); + + node.onmousedown = event => this.handleEvent(event); + + this.updateButton(node, this.defaults); + }, + + onViewShowing: event => { + let document = event.target.ownerDocument; + let tabbrowser = document.defaultView.gBrowser; + + let tab = tabbrowser.selectedTab; + let popupURL = this.getProperty(tab, "popup"); + this.tabManager.addActiveTabPermission(tab); + + // Popups are shown only if a popup URL is defined; otherwise + // a "click" event is dispatched. This is done for compatibility with the + // Google Chrome onClicked extension API. + if (popupURL) { + try { + let popup = this.getPopup(document.defaultView, popupURL); + event.detail.addBlocker(popup.attach(event.target)); + } catch (e) { + Cu.reportError(e); + event.preventDefault(); + } + } else { + // This isn't not a hack, but it seems to provide the correct behavior + // with the fewest complications. + event.preventDefault(); + this.emit("click"); + } + }, + }); + + this.tabContext.on("tab-select", // eslint-disable-line mozilla/balanced-listeners + (evt, tab) => { this.updateWindow(tab.ownerGlobal); }); + + this.widget = widget; + }, + + /** + * Triggers this browser action for the given window, with the same effects as + * if it were clicked by a user. + * + * This has no effect if the browser action is disabled for, or not + * present in, the given window. + */ + triggerAction: Task.async(function* (window) { + let popup = ViewPopup.for(this.extension, window); + if (popup) { + popup.closePopup(); + return; + } + + let widget = this.widget.forWindow(window); + let tab = window.gBrowser.selectedTab; + + if (!widget || !this.getProperty(tab, "enabled")) { + return; + } + + // Popups are shown only if a popup URL is defined; otherwise + // a "click" event is dispatched. This is done for compatibility with the + // Google Chrome onClicked extension API. + if (this.getProperty(tab, "popup")) { + if (this.widget.areaType == CustomizableUI.TYPE_MENU_PANEL) { + yield window.PanelUI.show(); + } + + let event = new window.CustomEvent("command", {bubbles: true, cancelable: true}); + widget.node.dispatchEvent(event); + } else { + this.emit("click"); + } + }), + + handleEvent(event) { + let button = event.target; + let window = button.ownerDocument.defaultView; + + switch (event.type) { + case "mousedown": + if (event.button == 0) { + // Begin pre-loading the browser for the popup, so it's more likely to + // be ready by the time we get a complete click. + let tab = window.gBrowser.selectedTab; + let popupURL = this.getProperty(tab, "popup"); + let enabled = this.getProperty(tab, "enabled"); + + if (popupURL && enabled) { + // Add permission for the active tab so it will exist for the popup. + // Store the tab to revoke the permission during clearPopup. + if (!this.pendingPopup && !this.tabManager.hasActiveTabPermission(tab)) { + this.tabManager.addActiveTabPermission(tab); + this.tabToRevokeDuringClearPopup = tab; + } + + this.pendingPopup = this.getPopup(window, popupURL); + window.addEventListener("mouseup", this, true); + } else { + this.clearPopup(); + } + } + break; + + case "mouseup": + if (event.button == 0) { + this.clearPopupTimeout(); + // If we have a pending pre-loaded popup, cancel it after we've waited + // long enough that we can be relatively certain it won't be opening. + if (this.pendingPopup) { + let {node} = this.widget.forWindow(window); + if (isAncestorOrSelf(node, event.originalTarget)) { + this.pendingPopupTimeout = setTimeout(() => this.clearPopup(), + POPUP_PRELOAD_TIMEOUT_MS); + } else { + this.clearPopup(); + } + } + } + break; + } + }, + + /** + * Returns a potentially pre-loaded popup for the given URL in the given + * window. If a matching pre-load popup already exists, returns that. + * Otherwise, initializes a new one. + * + * If a pre-load popup exists which does not match, it is destroyed before a + * new one is created. + * + * @param {Window} window + * The browser window in which to create the popup. + * @param {string} popupURL + * The URL to load into the popup. + * @returns {ViewPopup} + */ + getPopup(window, popupURL) { + this.clearPopupTimeout(); + let {pendingPopup} = this; + this.pendingPopup = null; + + if (pendingPopup) { + if (pendingPopup.window === window && pendingPopup.popupURL === popupURL) { + return pendingPopup; + } + pendingPopup.destroy(); + } + + let fixedWidth = this.widget.areaType == CustomizableUI.TYPE_MENU_PANEL; + return new ViewPopup(this.extension, window, popupURL, this.browserStyle, fixedWidth); + }, + + /** + * Clears any pending pre-loaded popup and related timeouts. + */ + clearPopup() { + this.clearPopupTimeout(); + if (this.pendingPopup) { + if (this.tabToRevokeDuringClearPopup) { + this.tabManager.revokeActiveTabPermission(this.tabToRevokeDuringClearPopup); + this.tabToRevokeDuringClearPopup = null; + } + this.pendingPopup.destroy(); + this.pendingPopup = null; + } + }, + + /** + * Clears any pending timeouts to clear stale, pre-loaded popups. + */ + clearPopupTimeout() { + if (this.pendingPopup) { + this.pendingPopup.window.removeEventListener("mouseup", this, true); + } + + if (this.pendingPopupTimeout) { + clearTimeout(this.pendingPopupTimeout); + this.pendingPopupTimeout = null; + } + }, + + // Update the toolbar button |node| with the tab context data + // in |tabData|. + updateButton(node, tabData) { + let title = tabData.title || this.extension.name; + node.setAttribute("tooltiptext", title); + node.setAttribute("label", title); + + if (tabData.badgeText) { + node.setAttribute("badge", tabData.badgeText); + } else { + node.removeAttribute("badge"); + } + + if (tabData.enabled) { + node.removeAttribute("disabled"); + } else { + node.setAttribute("disabled", "true"); + } + + let badgeNode = node.ownerDocument.getAnonymousElementByAttribute(node, + "class", "toolbarbutton-badge"); + if (badgeNode) { + let color = tabData.badgeBackgroundColor; + if (color) { + color = `rgba(${color[0]}, ${color[1]}, ${color[2]}, ${color[3] / 255})`; + } + badgeNode.style.backgroundColor = color || ""; + } + + const LEGACY_CLASS = "toolbarbutton-legacy-addon"; + node.classList.remove(LEGACY_CLASS); + + let baseSize = 16; + let {icon, size} = IconDetails.getPreferredIcon(tabData.icon, this.extension, baseSize); + + // If the best available icon size is not divisible by 16, check if we have + // an 18px icon to fall back to, and trim off the padding instead. + if (size % 16 && !icon.endsWith(".svg")) { + let result = IconDetails.getPreferredIcon(tabData.icon, this.extension, 18); + + if (result.size % 18 == 0) { + baseSize = 18; + icon = result.icon; + node.classList.add(LEGACY_CLASS); + } + } + + // These URLs should already be properly escaped, but make doubly sure CSS + // string escape characters are escaped here, since they could lead to a + // sandbox break. + let escape = str => str.replace(/[\\\s"]/g, encodeURIComponent); + + let getIcon = size => escape(IconDetails.getPreferredIcon(tabData.icon, this.extension, size).icon); + + node.setAttribute("style", ` + --webextension-menupanel-image: url("${getIcon(32)}"); + --webextension-menupanel-image-2x: url("${getIcon(64)}"); + --webextension-toolbar-image: url("${escape(icon)}"); + --webextension-toolbar-image-2x: url("${getIcon(baseSize * 2)}"); + `); + }, + + // Update the toolbar button for a given window. + updateWindow(window) { + let widget = this.widget.forWindow(window); + if (widget) { + let tab = window.gBrowser.selectedTab; + this.updateButton(widget.node, this.tabContext.get(tab)); + } + }, + + // Update the toolbar button when the extension changes the icon, + // title, badge, etc. If it only changes a parameter for a single + // tab, |tab| will be that tab. Otherwise it will be null. + updateOnChange(tab) { + if (tab) { + if (tab.selected) { + this.updateWindow(tab.ownerGlobal); + } + } else { + for (let window of WindowListManager.browserWindows()) { + this.updateWindow(window); + } + } + }, + + // tab is allowed to be null. + // prop should be one of "icon", "title", "badgeText", "popup", or "badgeBackgroundColor". + setProperty(tab, prop, value) { + if (tab == null) { + this.defaults[prop] = value; + } else if (value != null) { + this.tabContext.get(tab)[prop] = value; + } else { + delete this.tabContext.get(tab)[prop]; + } + + this.updateOnChange(tab); + }, + + // tab is allowed to be null. + // prop should be one of "title", "badgeText", "popup", or "badgeBackgroundColor". + getProperty(tab, prop) { + if (tab == null) { + return this.defaults[prop]; + } + return this.tabContext.get(tab)[prop]; + }, + + shutdown() { + this.tabContext.shutdown(); + CustomizableUI.destroyWidget(this.id); + }, +}; + +BrowserAction.for = (extension) => { + return browserActionMap.get(extension); +}; + +global.browserActionFor = BrowserAction.for; + +/* eslint-disable mozilla/balanced-listeners */ +extensions.on("manifest_browser_action", (type, directive, extension, manifest) => { + let browserAction = new BrowserAction(manifest.browser_action, extension); + browserAction.build(); + browserActionMap.set(extension, browserAction); +}); + +extensions.on("shutdown", (type, extension) => { + if (browserActionMap.has(extension)) { + browserActionMap.get(extension).shutdown(); + browserActionMap.delete(extension); + } +}); +/* eslint-enable mozilla/balanced-listeners */ + +extensions.registerSchemaAPI("browserAction", "addon_parent", context => { + let {extension} = context; + return { + browserAction: { + onClicked: new EventManager(context, "browserAction.onClicked", fire => { + let listener = () => { + let tab = TabManager.activeTab; + fire(TabManager.convert(extension, tab)); + }; + BrowserAction.for(extension).on("click", listener); + return () => { + BrowserAction.for(extension).off("click", listener); + }; + }).api(), + + enable: function(tabId) { + let tab = tabId !== null ? TabManager.getTab(tabId, context) : null; + BrowserAction.for(extension).setProperty(tab, "enabled", true); + }, + + disable: function(tabId) { + let tab = tabId !== null ? TabManager.getTab(tabId, context) : null; + BrowserAction.for(extension).setProperty(tab, "enabled", false); + }, + + setTitle: function(details) { + let tab = details.tabId !== null ? TabManager.getTab(details.tabId, context) : null; + + let title = details.title; + // Clear the tab-specific title when given a null string. + if (tab && title == "") { + title = null; + } + BrowserAction.for(extension).setProperty(tab, "title", title); + }, + + getTitle: function(details) { + let tab = details.tabId !== null ? TabManager.getTab(details.tabId, context) : null; + + let title = BrowserAction.for(extension).getProperty(tab, "title"); + return Promise.resolve(title); + }, + + setIcon: function(details) { + let tab = details.tabId !== null ? TabManager.getTab(details.tabId, context) : null; + + let icon = IconDetails.normalize(details, extension, context); + BrowserAction.for(extension).setProperty(tab, "icon", icon); + }, + + setBadgeText: function(details) { + let tab = details.tabId !== null ? TabManager.getTab(details.tabId, context) : null; + + BrowserAction.for(extension).setProperty(tab, "badgeText", details.text); + }, + + getBadgeText: function(details) { + let tab = details.tabId !== null ? TabManager.getTab(details.tabId, context) : null; + + let text = BrowserAction.for(extension).getProperty(tab, "badgeText"); + return Promise.resolve(text); + }, + + setPopup: function(details) { + let tab = details.tabId !== null ? TabManager.getTab(details.tabId, context) : null; + + // Note: Chrome resolves arguments to setIcon relative to the calling + // context, but resolves arguments to setPopup relative to the extension + // root. + // For internal consistency, we currently resolve both relative to the + // calling context. + let url = details.popup && context.uri.resolve(details.popup); + if (url && !context.checkLoadURL(url)) { + return Promise.reject({message: `Access denied for URL ${url}`}); + } + BrowserAction.for(extension).setProperty(tab, "popup", url); + }, + + getPopup: function(details) { + let tab = details.tabId !== null ? TabManager.getTab(details.tabId, context) : null; + + let popup = BrowserAction.for(extension).getProperty(tab, "popup"); + return Promise.resolve(popup); + }, + + setBadgeBackgroundColor: function(details) { + let tab = details.tabId !== null ? TabManager.getTab(details.tabId, context) : null; + let color = details.color; + if (!Array.isArray(color)) { + let col = DOMUtils.colorToRGBA(color); + color = col && [col.r, col.g, col.b, Math.round(col.a * 255)]; + } + BrowserAction.for(extension).setProperty(tab, "badgeBackgroundColor", color); + }, + + getBadgeBackgroundColor: function(details, callback) { + let tab = details.tabId !== null ? TabManager.getTab(details.tabId, context) : null; + + let color = BrowserAction.for(extension).getProperty(tab, "badgeBackgroundColor"); + return Promise.resolve(color || [0xd9, 0, 0, 255]); + }, + }, + }; +}); diff --git a/application/basilisk/components/webextensions/ext-c-contextMenus.js b/application/basilisk/components/webextensions/ext-c-contextMenus.js new file mode 100644 index 000000000..9fde90808 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-c-contextMenus.js @@ -0,0 +1,158 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +// If id is not specified for an item we use an integer. +// This ID need only be unique within a single addon. Since all addon code that +// can use this API runs in the same process, this local variable suffices. +var gNextMenuItemID = 0; + +// Map[Extension -> Map[string or id, ContextMenusClickPropHandler]] +var gPropHandlers = new Map(); + +// The contextMenus API supports an "onclick" attribute in the create/update +// methods to register a callback. This class manages these onclick properties. +class ContextMenusClickPropHandler { + constructor(context) { + this.context = context; + // Map[string or integer -> callback] + this.onclickMap = new Map(); + this.dispatchEvent = this.dispatchEvent.bind(this); + } + + // A listener on contextMenus.onClicked that forwards the event to the only + // listener, if any. + dispatchEvent(info, tab) { + let onclick = this.onclickMap.get(info.menuItemId); + if (onclick) { + // No need for runSafe or anything because we are already being run inside + // an event handler -- the event is just being forwarded to the actual + // handler. + onclick(info, tab); + } + } + + // Sets the `onclick` handler for the given menu item. + // The `onclick` function MUST be owned by `this.context`. + setListener(id, onclick) { + if (this.onclickMap.size === 0) { + this.context.childManager.getParentEvent("contextMenus.onClicked").addListener(this.dispatchEvent); + this.context.callOnClose(this); + } + this.onclickMap.set(id, onclick); + + let propHandlerMap = gPropHandlers.get(this.context.extension); + if (!propHandlerMap) { + propHandlerMap = new Map(); + } else { + // If the current callback was created in a different context, remove it + // from the other context. + let propHandler = propHandlerMap.get(id); + if (propHandler && propHandler !== this) { + propHandler.unsetListener(id); + } + } + propHandlerMap.set(id, this); + gPropHandlers.set(this.context.extension, propHandlerMap); + } + + // Deletes the `onclick` handler for the given menu item. + // The `onclick` function MUST be owned by `this.context`. + unsetListener(id) { + if (!this.onclickMap.delete(id)) { + return; + } + if (this.onclickMap.size === 0) { + this.context.childManager.getParentEvent("contextMenus.onClicked").removeListener(this.dispatchEvent); + this.context.forgetOnClose(this); + } + let propHandlerMap = gPropHandlers.get(this.context.extension); + propHandlerMap.delete(id); + if (propHandlerMap.size === 0) { + gPropHandlers.delete(this.context.extension); + } + } + + // Deletes the `onclick` handler for the given menu item, if any, regardless + // of the context where it was created. + unsetListenerFromAnyContext(id) { + let propHandlerMap = gPropHandlers.get(this.context.extension); + let propHandler = propHandlerMap && propHandlerMap.get(id); + if (propHandler) { + propHandler.unsetListener(id); + } + } + + // Remove all `onclick` handlers of the extension. + deleteAllListenersFromExtension() { + let propHandlerMap = gPropHandlers.get(this.context.extension); + if (propHandlerMap) { + for (let [id, propHandler] of propHandlerMap) { + propHandler.unsetListener(id); + } + } + } + + // Removes all `onclick` handlers from this context. + close() { + for (let id of this.onclickMap.keys()) { + this.unsetListener(id); + } + } +} + +extensions.registerSchemaAPI("contextMenus", "addon_child", context => { + let onClickedProp = new ContextMenusClickPropHandler(context); + + return { + contextMenus: { + create(createProperties, callback) { + if (createProperties.id === null) { + createProperties.id = ++gNextMenuItemID; + } + let {onclick} = createProperties; + delete createProperties.onclick; + context.childManager.callParentAsyncFunction("contextMenus.createInternal", [ + createProperties, + ]).then(() => { + if (onclick) { + onClickedProp.setListener(createProperties.id, onclick); + } + if (callback) { + callback(); + } + }); + return createProperties.id; + }, + + update(id, updateProperties) { + let {onclick} = updateProperties; + delete updateProperties.onclick; + return context.childManager.callParentAsyncFunction("contextMenus.update", [ + id, + updateProperties, + ]).then(() => { + if (onclick) { + onClickedProp.setListener(id, onclick); + } else if (onclick === null) { + onClickedProp.unsetListenerFromAnyContext(id); + } + // else onclick is not set so it should not be changed. + }); + }, + + remove(id) { + onClickedProp.unsetListenerFromAnyContext(id); + return context.childManager.callParentAsyncFunction("contextMenus.remove", [ + id, + ]); + }, + + removeAll() { + onClickedProp.deleteAllListenersFromExtension(); + + return context.childManager.callParentAsyncFunction("contextMenus.removeAll", []); + }, + }, + }; +}); diff --git a/application/basilisk/components/webextensions/ext-c-omnibox.js b/application/basilisk/components/webextensions/ext-c-omnibox.js new file mode 100644 index 000000000..3b9b6e2f7 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-c-omnibox.js @@ -0,0 +1,32 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +var { + runSafeSyncWithoutClone, + SingletonEventManager, +} = ExtensionUtils; + +extensions.registerSchemaAPI("omnibox", "addon_child", context => { + return { + omnibox: { + onInputChanged: new SingletonEventManager(context, "omnibox.onInputChanged", fire => { + let listener = (text, id) => { + runSafeSyncWithoutClone(fire, text, suggestions => { + // TODO: Switch to using callParentFunctionNoReturn once bug 1314903 is fixed. + context.childManager.callParentAsyncFunction("omnibox_internal.addSuggestions", [ + id, + suggestions, + ]); + }); + }; + context.childManager.getParentEvent("omnibox_internal.onInputChanged").addListener(listener); + return () => { + context.childManager.getParentEvent("omnibox_internal.onInputChanged").removeListener(listener); + }; + }).api(), + }, + }; +}); diff --git a/application/basilisk/components/webextensions/ext-c-tabs.js b/application/basilisk/components/webextensions/ext-c-tabs.js new file mode 100644 index 000000000..d5ce9fbf9 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-c-tabs.js @@ -0,0 +1,35 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +extensions.registerSchemaAPI("tabs", "addon_child", context => { + return { + tabs: { + connect: function(tabId, connectInfo) { + let name = ""; + if (connectInfo && connectInfo.name !== null) { + name = connectInfo.name; + } + let recipient = { + extensionId: context.extension.id, + tabId, + }; + if (connectInfo && connectInfo.frameId !== null) { + recipient.frameId = connectInfo.frameId; + } + return context.messenger.connect(context.messageManager, name, recipient); + }, + + sendMessage: function(tabId, message, options, responseCallback) { + let recipient = { + extensionId: context.extension.id, + tabId: tabId, + }; + if (options && options.frameId !== null) { + recipient.frameId = options.frameId; + } + return context.messenger.sendMessage(context.messageManager, message, recipient, responseCallback); + }, + }, + }; +}); diff --git a/application/basilisk/components/webextensions/ext-commands.js b/application/basilisk/components/webextensions/ext-commands.js new file mode 100644 index 000000000..b6e7ab3d1 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-commands.js @@ -0,0 +1,264 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://devtools/shared/event-emitter.js"); +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +var { + EventManager, + PlatformInfo, +} = ExtensionUtils; + +const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; + +// WeakMap[Extension -> CommandList] +var commandsMap = new WeakMap(); + +function CommandList(manifest, extension) { + this.extension = extension; + this.id = makeWidgetId(extension.id); + this.windowOpenListener = null; + + // Map[{String} commandName -> {Object} commandProperties] + this.commands = this.loadCommandsFromManifest(manifest); + + // WeakMap[Window -> ] + this.keysetsMap = new WeakMap(); + + this.register(); + EventEmitter.decorate(this); +} + +CommandList.prototype = { + /** + * Registers the commands to all open windows and to any which + * are later created. + */ + register() { + for (let window of WindowListManager.browserWindows()) { + this.registerKeysToDocument(window); + } + + this.windowOpenListener = (window) => { + if (!this.keysetsMap.has(window)) { + this.registerKeysToDocument(window); + } + }; + + WindowListManager.addOpenListener(this.windowOpenListener); + }, + + /** + * Unregisters the commands from all open windows and stops commands + * from being registered to windows which are later created. + */ + unregister() { + for (let window of WindowListManager.browserWindows()) { + if (this.keysetsMap.has(window)) { + this.keysetsMap.get(window).remove(); + } + } + + WindowListManager.removeOpenListener(this.windowOpenListener); + }, + + /** + * Creates a Map from commands for each command in the manifest.commands object. + * + * @param {Object} manifest The manifest JSON object. + * @returns {Map} + */ + loadCommandsFromManifest(manifest) { + let commands = new Map(); + // For Windows, chrome.runtime expects 'win' while chrome.commands + // expects 'windows'. We can special case this for now. + let os = PlatformInfo.os == "win" ? "windows" : PlatformInfo.os; + for (let [name, command] of Object.entries(manifest.commands)) { + let suggested_key = command.suggested_key || {}; + let shortcut = suggested_key[os] || suggested_key.default; + shortcut = shortcut ? shortcut.replace(/\s+/g, "") : null; + commands.set(name, { + description: command.description, + shortcut, + }); + } + return commands; + }, + + /** + * Registers the commands to a document. + * @param {ChromeWindow} window The XUL window to insert the Keyset. + */ + registerKeysToDocument(window) { + let doc = window.document; + let keyset = doc.createElementNS(XUL_NS, "keyset"); + keyset.id = `ext-keyset-id-${this.id}`; + this.commands.forEach((command, name) => { + if (command.shortcut) { + let keyElement = this.buildKey(doc, name, command.shortcut); + keyset.appendChild(keyElement); + } + }); + doc.documentElement.appendChild(keyset); + this.keysetsMap.set(window, keyset); + }, + + /** + * Builds a XUL Key element and attaches an onCommand listener which + * emits a command event with the provided name when fired. + * + * @param {Document} doc The XUL document. + * @param {string} name The name of the command. + * @param {string} shortcut The shortcut provided in the manifest. + * @see https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/key + * + * @returns {Document} The newly created Key element. + */ + buildKey(doc, name, shortcut) { + let keyElement = this.buildKeyFromShortcut(doc, shortcut); + + // We need to have the attribute "oncommand" for the "command" listener to fire, + // and it is currently ignored when set to the empty string. + keyElement.setAttribute("oncommand", "//"); + + /* eslint-disable mozilla/balanced-listeners */ + // We remove all references to the key elements when the extension is shutdown, + // therefore the listeners for these elements will be garbage collected. + keyElement.addEventListener("command", (event) => { + if (name == "_execute_page_action") { + let win = event.target.ownerDocument.defaultView; + pageActionFor(this.extension).triggerAction(win); + } else if (name == "_execute_browser_action") { + let win = event.target.ownerDocument.defaultView; + browserActionFor(this.extension).triggerAction(win); + } else { + TabManager.for(this.extension) + .addActiveTabPermission(TabManager.activeTab); + this.emit("command", name); + } + }); + /* eslint-enable mozilla/balanced-listeners */ + + return keyElement; + }, + + /** + * Builds a XUL Key element from the provided shortcut. + * + * @param {Document} doc The XUL document. + * @param {string} shortcut The shortcut provided in the manifest. + * + * @see https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/key + * @returns {Document} The newly created Key element. + */ + buildKeyFromShortcut(doc, shortcut) { + let keyElement = doc.createElementNS(XUL_NS, "key"); + + let parts = shortcut.split("+"); + + // The key is always the last element. + let chromeKey = parts.pop(); + + // The modifiers are the remaining elements. + keyElement.setAttribute("modifiers", this.getModifiersAttribute(parts)); + + if (/^[A-Z]$/.test(chromeKey)) { + // We use the key attribute for all single digits and characters. + keyElement.setAttribute("key", chromeKey); + } else { + keyElement.setAttribute("keycode", this.getKeycodeAttribute(chromeKey)); + keyElement.setAttribute("event", "keydown"); + } + + return keyElement; + }, + + /** + * Determines the corresponding XUL keycode from the given chrome key. + * + * For example: + * + * input | output + * --------------------------------------- + * "PageUP" | "VK_PAGE_UP" + * "Delete" | "VK_DELETE" + * + * @param {string} chromeKey The chrome key (e.g. "PageUp", "Space", ...) + * @returns {string} The constructed value for the Key's 'keycode' attribute. + */ + getKeycodeAttribute(chromeKey) { + if (/[0-9]/.test(chromeKey)) { + return `VK_${chromeKey}`; + } + return `VK${chromeKey.replace(/([A-Z])/g, "_$&").toUpperCase()}`; + }, + + /** + * Determines the corresponding XUL modifiers from the chrome modifiers. + * + * For example: + * + * input | output + * --------------------------------------- + * ["Ctrl", "Shift"] | "accel shift" + * ["MacCtrl"] | "control" + * + * @param {Array} chromeModifiers The array of chrome modifiers. + * @returns {string} The constructed value for the Key's 'modifiers' attribute. + */ + getModifiersAttribute(chromeModifiers) { + let modifiersMap = { + "Alt": "alt", + "Command": "accel", + "Ctrl": "accel", + "MacCtrl": "control", + "Shift": "shift", + }; + return Array.from(chromeModifiers, modifier => { + return modifiersMap[modifier]; + }).join(" "); + }, +}; + + +/* eslint-disable mozilla/balanced-listeners */ +extensions.on("manifest_commands", (type, directive, extension, manifest) => { + commandsMap.set(extension, new CommandList(manifest, extension)); +}); + +extensions.on("shutdown", (type, extension) => { + let commandsList = commandsMap.get(extension); + if (commandsList) { + commandsList.unregister(); + commandsMap.delete(extension); + } +}); +/* eslint-enable mozilla/balanced-listeners */ + +extensions.registerSchemaAPI("commands", "addon_parent", context => { + let {extension} = context; + return { + commands: { + getAll() { + let commands = commandsMap.get(extension).commands; + return Promise.resolve(Array.from(commands, ([name, command]) => { + return ({ + name, + description: command.description, + shortcut: command.shortcut, + }); + })); + }, + onCommand: new EventManager(context, "commands.onCommand", fire => { + let listener = (eventName, commandName) => { + fire(commandName); + }; + commandsMap.get(extension).on("command", listener); + return () => { + commandsMap.get(extension).off("command", listener); + }; + }).api(), + }, + }; +}); diff --git a/application/basilisk/components/webextensions/ext-contextMenus.js b/application/basilisk/components/webextensions/ext-contextMenus.js new file mode 100644 index 000000000..b3bf8aa53 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-contextMenus.js @@ -0,0 +1,537 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +Cu.import("resource://gre/modules/MatchPattern.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +var { + EventManager, + ExtensionError, + IconDetails, +} = ExtensionUtils; + +// Map[Extension -> Map[ID -> MenuItem]] +// Note: we want to enumerate all the menu items so +// this cannot be a weak map. +var gContextMenuMap = new Map(); + +// Map[Extension -> MenuItem] +var gRootItems = new Map(); + +// If id is not specified for an item we use an integer. +var gNextMenuItemID = 0; + +// Used to assign unique names to radio groups. +var gNextRadioGroupID = 0; + +// The max length of a menu item's label. +var gMaxLabelLength = 64; + +// When a new contextMenu is opened, this function is called and +// we populate the |xulMenu| with all the items from extensions +// to be displayed. We always clear all the items again when +// popuphidden fires. +var gMenuBuilder = { + build: function(contextData) { + let xulMenu = contextData.menu; + xulMenu.addEventListener("popuphidden", this); + this.xulMenu = xulMenu; + for (let [, root] of gRootItems) { + let rootElement = this.buildElementWithChildren(root, contextData); + if (!rootElement.firstChild || !rootElement.firstChild.childNodes.length) { + // If the root has no visible children, there is no reason to show + // the root menu item itself either. + continue; + } + rootElement.setAttribute("ext-type", "top-level-menu"); + rootElement = this.removeTopLevelMenuIfNeeded(rootElement); + + // Display the extension icon on the root element. + if (root.extension.manifest.icons) { + let parentWindow = contextData.menu.ownerGlobal; + let extension = root.extension; + + let {icon} = IconDetails.getPreferredIcon(extension.manifest.icons, extension, + 16 * parentWindow.devicePixelRatio); + + // The extension icons in the manifest are not pre-resolved, since + // they're sometimes used by the add-on manager when the extension is + // not enabled, and its URLs are not resolvable. + let resolvedURL = root.extension.baseURI.resolve(icon); + + if (rootElement.localName == "menu") { + rootElement.setAttribute("class", "menu-iconic"); + } else if (rootElement.localName == "menuitem") { + rootElement.setAttribute("class", "menuitem-iconic"); + } + rootElement.setAttribute("image", resolvedURL); + } + + xulMenu.appendChild(rootElement); + this.itemsToCleanUp.add(rootElement); + } + }, + + buildElementWithChildren(item, contextData) { + let element = this.buildSingleElement(item, contextData); + let groupName; + for (let child of item.children) { + if (child.type == "radio" && !child.groupName) { + if (!groupName) { + groupName = `webext-radio-group-${gNextRadioGroupID++}`; + } + child.groupName = groupName; + } else { + groupName = null; + } + + if (child.enabledForContext(contextData)) { + let childElement = this.buildElementWithChildren(child, contextData); + // Here element must be a menu element and its first child + // is a menupopup, we have to append its children to this + // menupopup. + element.firstChild.appendChild(childElement); + } + } + + return element; + }, + + removeTopLevelMenuIfNeeded(element) { + // If there is only one visible top level element we don't need the + // root menu element for the extension. + let menuPopup = element.firstChild; + if (menuPopup && menuPopup.childNodes.length == 1) { + let onlyChild = menuPopup.firstChild; + onlyChild.remove(); + return onlyChild; + } + + return element; + }, + + buildSingleElement(item, contextData) { + let doc = contextData.menu.ownerDocument; + let element; + if (item.children.length > 0) { + element = this.createMenuElement(doc, item); + } else if (item.type == "separator") { + element = doc.createElement("menuseparator"); + } else { + element = doc.createElement("menuitem"); + } + + return this.customizeElement(element, item, contextData); + }, + + createMenuElement(doc, item) { + let element = doc.createElement("menu"); + // Menu elements need to have a menupopup child for its menu items. + let menupopup = doc.createElement("menupopup"); + element.appendChild(menupopup); + return element; + }, + + customizeElement(element, item, contextData) { + let label = item.title; + if (label) { + if (contextData.isTextSelected && label.indexOf("%s") > -1) { + let selection = contextData.selectionText; + // The rendering engine will truncate the title if it's longer than 64 characters. + // But if it makes sense let's try truncate selection text only, to handle cases like + // 'look up "%s" in MyDictionary' more elegantly. + let maxSelectionLength = gMaxLabelLength - label.length + 2; + if (maxSelectionLength > 4) { + selection = selection.substring(0, maxSelectionLength - 3) + "..."; + } + label = label.replace(/%s/g, selection); + } + + element.setAttribute("label", label); + } + + if (item.type == "checkbox") { + element.setAttribute("type", "checkbox"); + if (item.checked) { + element.setAttribute("checked", "true"); + } + } else if (item.type == "radio") { + element.setAttribute("type", "radio"); + element.setAttribute("name", item.groupName); + if (item.checked) { + element.setAttribute("checked", "true"); + } + } + + if (!item.enabled) { + element.setAttribute("disabled", "true"); + } + + element.addEventListener("command", event => { // eslint-disable-line mozilla/balanced-listeners + if (event.target !== event.currentTarget) { + return; + } + const wasChecked = item.checked; + if (item.type == "checkbox") { + item.checked = !item.checked; + } else if (item.type == "radio") { + // Deselect all radio items in the current radio group. + for (let child of item.parent.children) { + if (child.type == "radio" && child.groupName == item.groupName) { + child.checked = false; + } + } + // Select the clicked radio item. + item.checked = true; + } + + item.tabManager.addActiveTabPermission(); + + let tab = item.tabManager.convert(contextData.tab); + let info = item.getClickInfo(contextData, wasChecked); + item.extension.emit("webext-contextmenu-menuitem-click", info, tab); + }); + + return element; + }, + + handleEvent: function(event) { + if (this.xulMenu != event.target || event.type != "popuphidden") { + return; + } + + delete this.xulMenu; + let target = event.target; + target.removeEventListener("popuphidden", this); + for (let item of this.itemsToCleanUp) { + item.remove(); + } + this.itemsToCleanUp.clear(); + }, + + itemsToCleanUp: new Set(), +}; + +function contextMenuObserver(subject, topic, data) { + subject = subject.wrappedJSObject; + gMenuBuilder.build(subject); +} + +function getContexts(contextData) { + let contexts = new Set(["all"]); + + if (contextData.inFrame) { + contexts.add("frame"); + } + + if (contextData.isTextSelected) { + contexts.add("selection"); + } + + if (contextData.onLink) { + contexts.add("link"); + } + + if (contextData.onEditableArea) { + contexts.add("editable"); + } + + if (contextData.onImage) { + contexts.add("image"); + } + + if (contextData.onVideo) { + contexts.add("video"); + } + + if (contextData.onAudio) { + contexts.add("audio"); + } + + if (contexts.size == 1) { + contexts.add("page"); + } + + return contexts; +} + +function MenuItem(extension, createProperties, isRoot = false) { + this.extension = extension; + this.children = []; + this.parent = null; + this.tabManager = TabManager.for(extension); + + this.setDefaults(); + this.setProps(createProperties); + if (!this.hasOwnProperty("_id")) { + this.id = gNextMenuItemID++; + } + // If the item is not the root and has no parent + // it must be a child of the root. + if (!isRoot && !this.parent) { + this.root.addChild(this); + } +} + +MenuItem.prototype = { + setProps(createProperties) { + for (let propName in createProperties) { + if (createProperties[propName] === null) { + // Omitted optional argument. + continue; + } + this[propName] = createProperties[propName]; + } + + if (createProperties.documentUrlPatterns != null) { + this.documentUrlMatchPattern = new MatchPattern(this.documentUrlPatterns); + } + + if (createProperties.targetUrlPatterns != null) { + this.targetUrlMatchPattern = new MatchPattern(this.targetUrlPatterns); + } + }, + + setDefaults() { + this.setProps({ + type: "normal", + checked: false, + contexts: ["all"], + enabled: true, + }); + }, + + set id(id) { + if (this.hasOwnProperty("_id")) { + throw new Error("Id of a MenuItem cannot be changed"); + } + let isIdUsed = gContextMenuMap.get(this.extension).has(id); + if (isIdUsed) { + throw new Error("Id already exists"); + } + this._id = id; + }, + + get id() { + return this._id; + }, + + ensureValidParentId(parentId) { + if (parentId === undefined) { + return; + } + let menuMap = gContextMenuMap.get(this.extension); + if (!menuMap.has(parentId)) { + throw new Error("Could not find any MenuItem with id: " + parentId); + } + for (let item = menuMap.get(parentId); item; item = item.parent) { + if (item === this) { + throw new ExtensionError("MenuItem cannot be an ancestor (or self) of its new parent."); + } + } + }, + + set parentId(parentId) { + this.ensureValidParentId(parentId); + + if (this.parent) { + this.parent.detachChild(this); + } + + if (parentId === undefined) { + this.root.addChild(this); + } else { + let menuMap = gContextMenuMap.get(this.extension); + menuMap.get(parentId).addChild(this); + } + }, + + get parentId() { + return this.parent ? this.parent.id : undefined; + }, + + addChild(child) { + if (child.parent) { + throw new Error("Child MenuItem already has a parent."); + } + this.children.push(child); + child.parent = this; + }, + + detachChild(child) { + let idx = this.children.indexOf(child); + if (idx < 0) { + throw new Error("Child MenuItem not found, it cannot be removed."); + } + this.children.splice(idx, 1); + child.parent = null; + }, + + get root() { + let extension = this.extension; + if (!gRootItems.has(extension)) { + let root = new MenuItem(extension, + {title: extension.name}, + /* isRoot = */ true); + gRootItems.set(extension, root); + } + + return gRootItems.get(extension); + }, + + remove() { + if (this.parent) { + this.parent.detachChild(this); + } + let children = this.children.slice(0); + for (let child of children) { + child.remove(); + } + + let menuMap = gContextMenuMap.get(this.extension); + menuMap.delete(this.id); + if (this.root == this) { + gRootItems.delete(this.extension); + } + }, + + getClickInfo(contextData, wasChecked) { + let mediaType; + if (contextData.onVideo) { + mediaType = "video"; + } + if (contextData.onAudio) { + mediaType = "audio"; + } + if (contextData.onImage) { + mediaType = "image"; + } + + let info = { + menuItemId: this.id, + editable: contextData.onEditableArea, + }; + + function setIfDefined(argName, value) { + if (value !== undefined) { + info[argName] = value; + } + } + + setIfDefined("parentMenuItemId", this.parentId); + setIfDefined("mediaType", mediaType); + setIfDefined("linkUrl", contextData.linkUrl); + setIfDefined("srcUrl", contextData.srcUrl); + setIfDefined("pageUrl", contextData.pageUrl); + setIfDefined("frameUrl", contextData.frameUrl); + setIfDefined("selectionText", contextData.selectionText); + + if ((this.type === "checkbox") || (this.type === "radio")) { + info.checked = this.checked; + info.wasChecked = wasChecked; + } + + return info; + }, + + enabledForContext(contextData) { + let contexts = getContexts(contextData); + if (!this.contexts.some(n => contexts.has(n))) { + return false; + } + + let docPattern = this.documentUrlMatchPattern; + let pageURI = Services.io.newURI(contextData.pageUrl, null, null); + if (docPattern && !docPattern.matches(pageURI)) { + return false; + } + + let targetPattern = this.targetUrlMatchPattern; + if (targetPattern) { + let targetUrls = []; + if (contextData.onImage || contextData.onAudio || contextData.onVideo) { + // TODO: double check if srcUrl is always set when we need it + targetUrls.push(contextData.srcUrl); + } + if (contextData.onLink) { + targetUrls.push(contextData.linkUrl); + } + if (!targetUrls.some(targetUrl => targetPattern.matches(NetUtil.newURI(targetUrl)))) { + return false; + } + } + + return true; + }, +}; + +var gExtensionCount = 0; +/* eslint-disable mozilla/balanced-listeners */ +extensions.on("startup", (type, extension) => { + gContextMenuMap.set(extension, new Map()); + if (++gExtensionCount == 1) { + Services.obs.addObserver(contextMenuObserver, + "on-build-contextmenu", + false); + } +}); + +extensions.on("shutdown", (type, extension) => { + gContextMenuMap.delete(extension); + gRootItems.delete(extension); + if (--gExtensionCount == 0) { + Services.obs.removeObserver(contextMenuObserver, + "on-build-contextmenu"); + } +}); +/* eslint-enable mozilla/balanced-listeners */ + +extensions.registerSchemaAPI("contextMenus", "addon_parent", context => { + let {extension} = context; + return { + contextMenus: { + createInternal: function(createProperties) { + // Note that the id is required by the schema. If the addon did not set + // it, the implementation of contextMenus.create in the child should + // have added it. + let menuItem = new MenuItem(extension, createProperties); + gContextMenuMap.get(extension).set(menuItem.id, menuItem); + }, + + update: function(id, updateProperties) { + let menuItem = gContextMenuMap.get(extension).get(id); + if (menuItem) { + menuItem.setProps(updateProperties); + } + }, + + remove: function(id) { + let menuItem = gContextMenuMap.get(extension).get(id); + if (menuItem) { + menuItem.remove(); + } + }, + + removeAll: function() { + let root = gRootItems.get(extension); + if (root) { + root.remove(); + } + }, + + onClicked: new EventManager(context, "contextMenus.onClicked", fire => { + let listener = (event, info, tab) => { + fire(info, tab); + }; + + extension.on("webext-contextmenu-menuitem-click", listener); + return () => { + extension.off("webext-contextmenu-menuitem-click", listener); + }; + }).api(), + }, + }; +}); diff --git a/application/basilisk/components/webextensions/ext-desktop-runtime.js b/application/basilisk/components/webextensions/ext-desktop-runtime.js new file mode 100644 index 000000000..0fdb45562 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-desktop-runtime.js @@ -0,0 +1,26 @@ +"use strict"; + +/* eslint-disable mozilla/balanced-listeners */ +extensions.on("uninstall", (msg, extension) => { + if (extension.uninstallURL) { + let browser = WindowManager.topWindow.gBrowser; + browser.addTab(extension.uninstallURL, {relatedToCurrent: true}); + } +}); + +global.openOptionsPage = (extension) => { + let window = WindowManager.topWindow; + if (!window) { + return Promise.reject({message: "No browser window available"}); + } + + if (extension.manifest.options_ui.open_in_tab) { + window.switchToTabHavingURI(extension.manifest.options_ui.page, true); + return Promise.resolve(); + } + + let viewId = `addons://detail/${encodeURIComponent(extension.id)}/preferences`; + + return window.BrowserOpenAddonsMgr(viewId); +}; + diff --git a/application/basilisk/components/webextensions/ext-history.js b/application/basilisk/components/webextensions/ext-history.js new file mode 100644 index 000000000..a47df1621 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-history.js @@ -0,0 +1,246 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +const {classes: Cc, interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "EventEmitter", + "resource://devtools/shared/event-emitter.js"); +XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", + "resource://gre/modules/NetUtil.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils", + "resource://gre/modules/PlacesUtils.jsm"); + +const { + normalizeTime, + SingletonEventManager, +} = ExtensionUtils; + +let nsINavHistoryService = Ci.nsINavHistoryService; +const TRANSITION_TO_TRANSITION_TYPES_MAP = new Map([ + ["link", nsINavHistoryService.TRANSITION_LINK], + ["typed", nsINavHistoryService.TRANSITION_TYPED], + ["auto_bookmark", nsINavHistoryService.TRANSITION_BOOKMARK], + ["auto_subframe", nsINavHistoryService.TRANSITION_EMBED], + ["manual_subframe", nsINavHistoryService.TRANSITION_FRAMED_LINK], +]); + +let TRANSITION_TYPE_TO_TRANSITIONS_MAP = new Map(); +for (let [transition, transitionType] of TRANSITION_TO_TRANSITION_TYPES_MAP) { + TRANSITION_TYPE_TO_TRANSITIONS_MAP.set(transitionType, transition); +} + +function getTransitionType(transition) { + // cannot set a default value for the transition argument as the framework sets it to null + transition = transition || "link"; + let transitionType = TRANSITION_TO_TRANSITION_TYPES_MAP.get(transition); + if (!transitionType) { + throw new Error(`|${transition}| is not a supported transition for history`); + } + return transitionType; +} + +function getTransition(transitionType) { + return TRANSITION_TYPE_TO_TRANSITIONS_MAP.get(transitionType) || "link"; +} + +/* + * Converts a nsINavHistoryResultNode into a HistoryItem + * + * https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsINavHistoryResultNode + */ +function convertNodeToHistoryItem(node) { + return { + id: node.pageGuid, + url: node.uri, + title: node.title, + lastVisitTime: PlacesUtils.toDate(node.time).getTime(), + visitCount: node.accessCount, + }; +} + +/* + * Converts a nsINavHistoryResultNode into a VisitItem + * + * https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsINavHistoryResultNode + */ +function convertNodeToVisitItem(node) { + return { + id: node.pageGuid, + visitId: node.visitId, + visitTime: PlacesUtils.toDate(node.time).getTime(), + referringVisitId: node.fromVisitId, + transition: getTransition(node.visitType), + }; +} + +/* + * Converts a nsINavHistoryContainerResultNode into an array of objects + * + * https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsINavHistoryContainerResultNode + */ +function convertNavHistoryContainerResultNode(container, converter) { + let results = []; + container.containerOpen = true; + for (let i = 0; i < container.childCount; i++) { + let node = container.getChild(i); + results.push(converter(node)); + } + container.containerOpen = false; + return results; +} + +var _observer; + +function getObserver() { + if (!_observer) { + _observer = { + onDeleteURI: function(uri, guid, reason) { + this.emit("visitRemoved", {allHistory: false, urls: [uri.spec]}); + }, + onVisit: function(uri, visitId, time, sessionId, referringId, transitionType, guid, hidden, visitCount, typed) { + let data = { + id: guid, + url: uri.spec, + title: "", + lastVisitTime: time / 1000, // time from Places is microseconds, + visitCount, + typedCount: typed, + }; + this.emit("visited", data); + }, + onBeginUpdateBatch: function() {}, + onEndUpdateBatch: function() {}, + onTitleChanged: function() {}, + onClearHistory: function() { + this.emit("visitRemoved", {allHistory: true, urls: []}); + }, + onPageChanged: function() {}, + onFrecencyChanged: function() {}, + onManyFrecenciesChanged: function() {}, + onDeleteVisits: function(uri, time, guid, reason) { + this.emit("visitRemoved", {allHistory: false, urls: [uri.spec]}); + }, + }; + EventEmitter.decorate(_observer); + PlacesUtils.history.addObserver(_observer, false); + } + return _observer; +} + +extensions.registerSchemaAPI("history", "addon_parent", context => { + return { + history: { + addUrl: function(details) { + let transition, date; + try { + transition = getTransitionType(details.transition); + } catch (error) { + return Promise.reject({message: error.message}); + } + if (details.visitTime) { + date = normalizeTime(details.visitTime); + } + let pageInfo = { + title: details.title, + url: details.url, + visits: [ + { + transition, + date, + }, + ], + }; + try { + return PlacesUtils.history.insert(pageInfo).then(() => undefined); + } catch (error) { + return Promise.reject({message: error.message}); + } + }, + + deleteAll: function() { + return PlacesUtils.history.clear(); + }, + + deleteRange: function(filter) { + let newFilter = { + beginDate: normalizeTime(filter.startTime), + endDate: normalizeTime(filter.endTime), + }; + // History.removeVisitsByFilter returns a boolean, but our API should return nothing + return PlacesUtils.history.removeVisitsByFilter(newFilter).then(() => undefined); + }, + + deleteUrl: function(details) { + let url = details.url; + // History.remove returns a boolean, but our API should return nothing + return PlacesUtils.history.remove(url).then(() => undefined); + }, + + search: function(query) { + let beginTime = (query.startTime == null) ? + PlacesUtils.toPRTime(Date.now() - 24 * 60 * 60 * 1000) : + PlacesUtils.toPRTime(normalizeTime(query.startTime)); + let endTime = (query.endTime == null) ? + Number.MAX_VALUE : + PlacesUtils.toPRTime(normalizeTime(query.endTime)); + if (beginTime > endTime) { + return Promise.reject({message: "The startTime cannot be after the endTime"}); + } + + let options = PlacesUtils.history.getNewQueryOptions(); + options.sortingMode = options.SORT_BY_DATE_DESCENDING; + options.maxResults = query.maxResults || 100; + + let historyQuery = PlacesUtils.history.getNewQuery(); + historyQuery.searchTerms = query.text; + historyQuery.beginTime = beginTime; + historyQuery.endTime = endTime; + let queryResult = PlacesUtils.history.executeQuery(historyQuery, options).root; + let results = convertNavHistoryContainerResultNode(queryResult, convertNodeToHistoryItem); + return Promise.resolve(results); + }, + + getVisits: function(details) { + let url = details.url; + if (!url) { + return Promise.reject({message: "A URL must be provided for getVisits"}); + } + + let options = PlacesUtils.history.getNewQueryOptions(); + options.sortingMode = options.SORT_BY_DATE_DESCENDING; + options.resultType = options.RESULTS_AS_VISIT; + + let historyQuery = PlacesUtils.history.getNewQuery(); + historyQuery.uri = NetUtil.newURI(url); + let queryResult = PlacesUtils.history.executeQuery(historyQuery, options).root; + let results = convertNavHistoryContainerResultNode(queryResult, convertNodeToVisitItem); + return Promise.resolve(results); + }, + + onVisited: new SingletonEventManager(context, "history.onVisited", fire => { + let listener = (event, data) => { + context.runSafe(fire, data); + }; + + getObserver().on("visited", listener); + return () => { + getObserver().off("visited", listener); + }; + }).api(), + + onVisitRemoved: new SingletonEventManager(context, "history.onVisitRemoved", fire => { + let listener = (event, data) => { + context.runSafe(fire, data); + }; + + getObserver().on("visitRemoved", listener); + return () => { + getObserver().off("visitRemoved", listener); + }; + }).api(), + }, + }; +}); diff --git a/application/basilisk/components/webextensions/ext-omnibox.js b/application/basilisk/components/webextensions/ext-omnibox.js new file mode 100644 index 000000000..9b2f60ca4 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-omnibox.js @@ -0,0 +1,104 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionSearchHandler", + "resource://gre/modules/ExtensionSearchHandler.jsm"); +var { + SingletonEventManager, +} = ExtensionUtils; + +// WeakMap[extension -> keyword] +let gKeywordMap = new WeakMap(); + +/* eslint-disable mozilla/balanced-listeners */ +extensions.on("manifest_omnibox", (type, directive, extension, manifest) => { + let keyword = manifest.omnibox.keyword; + try { + // This will throw if the keyword is already registered. + ExtensionSearchHandler.registerKeyword(keyword, extension); + gKeywordMap.set(extension, keyword); + } catch (e) { + extension.manifestError(e.message); + } +}); + +extensions.on("shutdown", (type, extension) => { + let keyword = gKeywordMap.get(extension); + if (keyword) { + ExtensionSearchHandler.unregisterKeyword(keyword); + gKeywordMap.delete(extension); + } +}); +/* eslint-enable mozilla/balanced-listeners */ + +extensions.registerSchemaAPI("omnibox", "addon_parent", context => { + let {extension} = context; + return { + omnibox: { + setDefaultSuggestion(suggestion) { + let keyword = gKeywordMap.get(extension); + try { + // This will throw if the keyword failed to register. + ExtensionSearchHandler.setDefaultSuggestion(keyword, suggestion); + } catch (e) { + return Promise.reject(e.message); + } + }, + + onInputStarted: new SingletonEventManager(context, "omnibox.onInputStarted", fire => { + let listener = (eventName) => { + fire(); + }; + extension.on(ExtensionSearchHandler.MSG_INPUT_STARTED, listener); + return () => { + extension.off(ExtensionSearchHandler.MSG_INPUT_STARTED, listener); + }; + }).api(), + + onInputCancelled: new SingletonEventManager(context, "omnibox.onInputCancelled", fire => { + let listener = (eventName) => { + fire(); + }; + extension.on(ExtensionSearchHandler.MSG_INPUT_CANCELLED, listener); + return () => { + extension.off(ExtensionSearchHandler.MSG_INPUT_CANCELLED, listener); + }; + }).api(), + + onInputEntered: new SingletonEventManager(context, "omnibox.onInputEntered", fire => { + let listener = (eventName, text, disposition) => { + fire(text, disposition); + }; + extension.on(ExtensionSearchHandler.MSG_INPUT_ENTERED, listener); + return () => { + extension.off(ExtensionSearchHandler.MSG_INPUT_ENTERED, listener); + }; + }).api(), + }, + + omnibox_internal: { + addSuggestions(id, suggestions) { + let keyword = gKeywordMap.get(extension); + try { + ExtensionSearchHandler.addSuggestions(keyword, id, suggestions); + } catch (e) { + // Silently fail because the extension developer can not know for sure if the user + // has already invalidated the callback when asynchronously providing suggestions. + } + }, + + onInputChanged: new SingletonEventManager(context, "omnibox_internal.onInputChanged", fire => { + let listener = (eventName, text, id) => { + fire(text, id); + }; + extension.on(ExtensionSearchHandler.MSG_INPUT_CHANGED, listener); + return () => { + extension.off(ExtensionSearchHandler.MSG_INPUT_CHANGED, listener); + }; + }).api(), + }, + }; +}); diff --git a/application/basilisk/components/webextensions/ext-pageAction.js b/application/basilisk/components/webextensions/ext-pageAction.js new file mode 100644 index 000000000..5bf3a9c70 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-pageAction.js @@ -0,0 +1,290 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://gre/modules/Task.jsm"); +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +var { + EventManager, + IconDetails, +} = ExtensionUtils; + +// WeakMap[Extension -> PageAction] +var pageActionMap = new WeakMap(); + +// Handles URL bar icons, including the |page_action| manifest entry +// and associated API. +function PageAction(options, extension) { + this.extension = extension; + this.id = makeWidgetId(extension.id) + "-page-action"; + + this.tabManager = TabManager.for(extension); + + this.defaults = { + show: false, + title: options.default_title || extension.name, + icon: IconDetails.normalize({path: options.default_icon}, extension), + popup: options.default_popup || "", + }; + + this.browserStyle = options.browser_style || false; + if (options.browser_style === null) { + this.extension.logger.warn("Please specify whether you want browser_style " + + "or not in your page_action options."); + } + + this.tabContext = new TabContext(tab => Object.create(this.defaults), + extension); + + this.tabContext.on("location-change", this.handleLocationChange.bind(this)); // eslint-disable-line mozilla/balanced-listeners + + // WeakMap[ChromeWindow -> ] + this.buttons = new WeakMap(); + + EventEmitter.decorate(this); +} + +PageAction.prototype = { + // Returns the value of the property |prop| for the given tab, where + // |prop| is one of "show", "title", "icon", "popup". + getProperty(tab, prop) { + return this.tabContext.get(tab)[prop]; + }, + + // Sets the value of the property |prop| for the given tab to the + // given value, symmetrically to |getProperty|. + // + // If |tab| is currently selected, updates the page action button to + // reflect the new value. + setProperty(tab, prop, value) { + if (value != null) { + this.tabContext.get(tab)[prop] = value; + } else { + delete this.tabContext.get(tab)[prop]; + } + + if (tab.selected) { + this.updateButton(tab.ownerGlobal); + } + }, + + // Updates the page action button in the given window to reflect the + // properties of the currently selected tab: + // + // Updates "tooltiptext" and "aria-label" to match "title" property. + // Updates "image" to match the "icon" property. + // Shows or hides the icon, based on the "show" property. + updateButton(window) { + let tabData = this.tabContext.get(window.gBrowser.selectedTab); + + if (!(tabData.show || this.buttons.has(window))) { + // Don't bother creating a button for a window until it actually + // needs to be shown. + return; + } + + let button = this.getButton(window); + + if (tabData.show) { + // Update the title and icon only if the button is visible. + + let title = tabData.title || this.extension.name; + button.setAttribute("tooltiptext", title); + button.setAttribute("aria-label", title); + + // These URLs should already be properly escaped, but make doubly sure CSS + // string escape characters are escaped here, since they could lead to a + // sandbox break. + let escape = str => str.replace(/[\\\s"]/g, encodeURIComponent); + + let getIcon = size => escape(IconDetails.getPreferredIcon(tabData.icon, this.extension, size).icon); + + button.setAttribute("style", ` + --webextension-urlbar-image: url("${getIcon(16)}"); + --webextension-urlbar-image-2x: url("${getIcon(32)}"); + `); + + button.classList.add("webextension-page-action"); + } + + button.hidden = !tabData.show; + }, + + // Create an |image| node and add it to the |urlbar-icons| + // container in the given window. + addButton(window) { + let document = window.document; + + let button = document.createElement("image"); + button.id = this.id; + button.setAttribute("class", "urlbar-icon"); + + button.addEventListener("click", event => { // eslint-disable-line mozilla/balanced-listeners + if (event.button == 0) { + this.handleClick(window); + } + }); + + document.getElementById("urlbar-icons").appendChild(button); + + return button; + }, + + // Returns the page action button for the given window, creating it if + // it doesn't already exist. + getButton(window) { + if (!this.buttons.has(window)) { + let button = this.addButton(window); + this.buttons.set(window, button); + } + + return this.buttons.get(window); + }, + + /** + * Triggers this page action for the given window, with the same effects as + * if it were clicked by a user. + * + * This has no effect if the page action is hidden for the selected tab. + * + * @param {Window} window + */ + triggerAction(window) { + let pageAction = pageActionMap.get(this.extension); + if (pageAction.getProperty(window.gBrowser.selectedTab, "show")) { + pageAction.handleClick(window); + } + }, + + // Handles a click event on the page action button for the given + // window. + // If the page action has a |popup| property, a panel is opened to + // that URL. Otherwise, a "click" event is emitted, and dispatched to + // the any click listeners in the add-on. + handleClick(window) { + let tab = window.gBrowser.selectedTab; + let popupURL = this.tabContext.get(tab).popup; + + this.tabManager.addActiveTabPermission(tab); + + // If the widget has a popup URL defined, we open a popup, but do not + // dispatch a click event to the extension. + // If it has no popup URL defined, we dispatch a click event, but do not + // open a popup. + if (popupURL) { + new PanelPopup(this.extension, this.getButton(window), popupURL, + this.browserStyle); + } else { + this.emit("click", tab); + } + }, + + handleLocationChange(eventType, tab, fromBrowse) { + if (fromBrowse) { + this.tabContext.clear(tab); + } + this.updateButton(tab.ownerGlobal); + }, + + shutdown() { + this.tabContext.shutdown(); + + for (let window of WindowListManager.browserWindows()) { + if (this.buttons.has(window)) { + this.buttons.get(window).remove(); + } + } + }, +}; + +/* eslint-disable mozilla/balanced-listeners */ +extensions.on("manifest_page_action", (type, directive, extension, manifest) => { + let pageAction = new PageAction(manifest.page_action, extension); + pageActionMap.set(extension, pageAction); +}); + +extensions.on("shutdown", (type, extension) => { + if (pageActionMap.has(extension)) { + pageActionMap.get(extension).shutdown(); + pageActionMap.delete(extension); + } +}); +/* eslint-enable mozilla/balanced-listeners */ + +PageAction.for = extension => { + return pageActionMap.get(extension); +}; + +global.pageActionFor = PageAction.for; + +extensions.registerSchemaAPI("pageAction", "addon_parent", context => { + let {extension} = context; + return { + pageAction: { + onClicked: new EventManager(context, "pageAction.onClicked", fire => { + let listener = (evt, tab) => { + fire(TabManager.convert(extension, tab)); + }; + let pageAction = PageAction.for(extension); + + pageAction.on("click", listener); + return () => { + pageAction.off("click", listener); + }; + }).api(), + + show(tabId) { + let tab = TabManager.getTab(tabId, context); + PageAction.for(extension).setProperty(tab, "show", true); + }, + + hide(tabId) { + let tab = TabManager.getTab(tabId, context); + PageAction.for(extension).setProperty(tab, "show", false); + }, + + setTitle(details) { + let tab = TabManager.getTab(details.tabId, context); + + // Clear the tab-specific title when given a null string. + PageAction.for(extension).setProperty(tab, "title", details.title || null); + }, + + getTitle(details) { + let tab = TabManager.getTab(details.tabId, context); + + let title = PageAction.for(extension).getProperty(tab, "title"); + return Promise.resolve(title); + }, + + setIcon(details) { + let tab = TabManager.getTab(details.tabId, context); + + let icon = IconDetails.normalize(details, extension, context); + PageAction.for(extension).setProperty(tab, "icon", icon); + }, + + setPopup(details) { + let tab = TabManager.getTab(details.tabId, context); + + // Note: Chrome resolves arguments to setIcon relative to the calling + // context, but resolves arguments to setPopup relative to the extension + // root. + // For internal consistency, we currently resolve both relative to the + // calling context. + let url = details.popup && context.uri.resolve(details.popup); + if (url && !context.checkLoadURL(url)) { + return Promise.reject({message: `Access denied for URL ${url}`}); + } + PageAction.for(extension).setProperty(tab, "popup", url); + }, + + getPopup(details) { + let tab = TabManager.getTab(details.tabId, context); + + let popup = PageAction.for(extension).getProperty(tab, "popup"); + return Promise.resolve(popup); + }, + }, + }; +}); diff --git a/application/basilisk/components/webextensions/ext-sessions.js b/application/basilisk/components/webextensions/ext-sessions.js new file mode 100644 index 000000000..4c13a1ac3 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-sessions.js @@ -0,0 +1,92 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +var { + promiseObserved, +} = ExtensionUtils; + +XPCOMUtils.defineLazyModuleGetter(this, "SessionStore", + "resource:///modules/sessionstore/SessionStore.jsm"); + +function getRecentlyClosed(maxResults, extension) { + let recentlyClosed = []; + + // Get closed windows + let closedWindowData = SessionStore.getClosedWindowData(false); + for (let window of closedWindowData) { + recentlyClosed.push({ + lastModified: window.closedAt, + window: WindowManager.convertFromSessionStoreClosedData(window, extension)}); + } + + // Get closed tabs + for (let window of WindowListManager.browserWindows()) { + let closedTabData = SessionStore.getClosedTabData(window, false); + for (let tab of closedTabData) { + recentlyClosed.push({ + lastModified: tab.closedAt, + tab: TabManager.for(extension).convertFromSessionStoreClosedData(tab, window)}); + } + } + + // Sort windows and tabs + recentlyClosed.sort((a, b) => b.lastModified - a.lastModified); + return recentlyClosed.slice(0, maxResults); +} + +function createSession(restored, extension, sessionId) { + if (!restored) { + return Promise.reject({message: `Could not restore object using sessionId ${sessionId}.`}); + } + let sessionObj = {lastModified: Date.now()}; + if (restored instanceof Ci.nsIDOMChromeWindow) { + return promiseObserved("sessionstore-single-window-restored", subject => subject == restored).then(() => { + sessionObj.window = WindowManager.convert(extension, restored, {populate: true}); + return Promise.resolve([sessionObj]); + }); + } + sessionObj.tab = TabManager.for(extension).convert(restored); + return Promise.resolve([sessionObj]); +} + +extensions.registerSchemaAPI("sessions", "addon_parent", context => { + let {extension} = context; + return { + sessions: { + getRecentlyClosed: function(filter) { + let maxResults = filter.maxResults == undefined ? this.MAX_SESSION_RESULTS : filter.maxResults; + return Promise.resolve(getRecentlyClosed(maxResults, extension)); + }, + restore: function(sessionId) { + let session, closedId; + if (sessionId) { + closedId = sessionId; + session = SessionStore.undoCloseById(closedId); + } else if (SessionStore.lastClosedObjectType == "window") { + // If the most recently closed object is a window, just undo closing the most recent window. + session = SessionStore.undoCloseWindow(0); + } else { + // It is a tab, and we cannot call SessionStore.undoCloseTab without a window, + // so we must find the tab in which case we can just use its closedId. + let recentlyClosedTabs = []; + for (let window of WindowListManager.browserWindows()) { + let closedTabData = SessionStore.getClosedTabData(window, false); + for (let tab of closedTabData) { + recentlyClosedTabs.push(tab); + } + } + + // Sort the tabs. + recentlyClosedTabs.sort((a, b) => b.closedAt - a.closedAt); + + // Use the closedId of the most recently closed tab to restore it. + closedId = recentlyClosedTabs[0].closedId; + session = SessionStore.undoCloseById(closedId); + } + return createSession(session, extension, closedId); + }, + }, + }; +}); diff --git a/application/basilisk/components/webextensions/ext-tabs.js b/application/basilisk/components/webextensions/ext-tabs.js new file mode 100644 index 000000000..bb575aaab --- /dev/null +++ b/application/basilisk/components/webextensions/ext-tabs.js @@ -0,0 +1,1093 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService", + "@mozilla.org/browser/aboutnewtab-service;1", + "nsIAboutNewTabService"); + +XPCOMUtils.defineLazyModuleGetter(this, "MatchPattern", + "resource://gre/modules/MatchPattern.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PromiseUtils", + "resource://gre/modules/PromiseUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Services", + "resource://gre/modules/Services.jsm"); + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +var { + EventManager, + ignoreEvent, +} = ExtensionUtils; + +// This function is pretty tightly tied to Extension.jsm. +// Its job is to fill in the |tab| property of the sender. +function getSender(extension, target, sender) { + if ("tabId" in sender) { + // The message came from an ExtensionContext. In that case, it should + // include a tabId property (which is filled in by the page-open + // listener below). + let tab = TabManager.getTab(sender.tabId, null, null); + delete sender.tabId; + if (tab) { + sender.tab = TabManager.convert(extension, tab); + return; + } + } + if (target instanceof Ci.nsIDOMXULElement) { + // If the message was sent from a content script to a element, + // then we can just get the `tab` from `target`. + let tabbrowser = target.ownerGlobal.gBrowser; + if (tabbrowser) { + let tab = tabbrowser.getTabForBrowser(target); + + // `tab` can be `undefined`, e.g. for extension popups. This condition is + // reached if `getSender` is called for a popup without a valid `tabId`. + if (tab) { + sender.tab = TabManager.convert(extension, tab); + } + } + } +} + +// Used by Extension.jsm +global.tabGetSender = getSender; + +/* eslint-disable mozilla/balanced-listeners */ + +extensions.on("page-shutdown", (type, context) => { + if (context.viewType == "tab") { + if (context.extension.id !== context.xulBrowser.contentPrincipal.addonId) { + // Only close extension tabs. + // This check prevents about:addons from closing when it contains a + // WebExtension as an embedded inline options page. + return; + } + let {gBrowser} = context.xulBrowser.ownerGlobal; + if (gBrowser) { + let tab = gBrowser.getTabForBrowser(context.xulBrowser); + if (tab) { + gBrowser.removeTab(tab); + } + } + } +}); + +extensions.on("fill-browser-data", (type, browser, data) => { + data.tabId = browser ? TabManager.getBrowserId(browser) : -1; +}); +/* eslint-enable mozilla/balanced-listeners */ + +global.currentWindow = function(context) { + let {xulWindow} = context; + if (xulWindow && context.viewType != "background") { + return xulWindow; + } + return WindowManager.topWindow; +}; + +let tabListener = { + init() { + if (this.initialized) { + return; + } + + this.adoptedTabs = new WeakMap(); + + this.handleWindowOpen = this.handleWindowOpen.bind(this); + this.handleWindowClose = this.handleWindowClose.bind(this); + + AllWindowEvents.addListener("TabClose", this); + AllWindowEvents.addListener("TabOpen", this); + WindowListManager.addOpenListener(this.handleWindowOpen); + WindowListManager.addCloseListener(this.handleWindowClose); + + EventEmitter.decorate(this); + + this.initialized = true; + }, + + handleEvent(event) { + switch (event.type) { + case "TabOpen": + if (event.detail.adoptedTab) { + this.adoptedTabs.set(event.detail.adoptedTab, event.target); + } + + // We need to delay sending this event until the next tick, since the + // tab does not have its final index when the TabOpen event is dispatched. + Promise.resolve().then(() => { + if (event.detail.adoptedTab) { + this.emitAttached(event.originalTarget); + } else { + this.emitCreated(event.originalTarget); + } + }); + break; + + case "TabClose": + let tab = event.originalTarget; + + if (event.detail.adoptedBy) { + this.emitDetached(tab, event.detail.adoptedBy); + } else { + this.emitRemoved(tab, false); + } + break; + } + }, + + handleWindowOpen(window) { + if (window.arguments[0] instanceof window.XULElement) { + // If the first window argument is a XUL element, it means the + // window is about to adopt a tab from another window to replace its + // initial tab. + // + // Note that this event handler depends on running before the + // delayed startup code in browser.js, which is currently triggered + // by the first MozAfterPaint event. That code handles finally + // adopting the tab, and clears it from the arguments list in the + // process, so if we run later than it, we're too late. + let tab = window.arguments[0]; + this.adoptedTabs.set(tab, window.gBrowser.tabs[0]); + + // We need to be sure to fire this event after the onDetached event + // for the original tab. + let listener = (event, details) => { + if (details.tab == tab) { + this.off("tab-detached", listener); + + Promise.resolve().then(() => { + this.emitAttached(details.adoptedBy); + }); + } + }; + + this.on("tab-detached", listener); + } else { + for (let tab of window.gBrowser.tabs) { + this.emitCreated(tab); + } + } + }, + + handleWindowClose(window) { + for (let tab of window.gBrowser.tabs) { + if (this.adoptedTabs.has(tab)) { + this.emitDetached(tab, this.adoptedTabs.get(tab)); + } else { + this.emitRemoved(tab, true); + } + } + }, + + emitAttached(tab) { + let newWindowId = WindowManager.getId(tab.ownerGlobal); + let tabId = TabManager.getId(tab); + + this.emit("tab-attached", {tab, tabId, newWindowId, newPosition: tab._tPos}); + }, + + emitDetached(tab, adoptedBy) { + let oldWindowId = WindowManager.getId(tab.ownerGlobal); + let tabId = TabManager.getId(tab); + + this.emit("tab-detached", {tab, adoptedBy, tabId, oldWindowId, oldPosition: tab._tPos}); + }, + + emitCreated(tab) { + this.emit("tab-created", {tab}); + }, + + emitRemoved(tab, isWindowClosing) { + let windowId = WindowManager.getId(tab.ownerGlobal); + let tabId = TabManager.getId(tab); + + // When addons run in-process, `window.close()` is synchronous. Most other + // addon-invoked calls are asynchronous since they go through a proxy + // context via the message manager. This includes event registrations such + // as `tabs.onRemoved.addListener`. + // So, even if `window.close()` were to be called (in-process) after calling + // `tabs.onRemoved.addListener`, then the tab would be closed before the + // event listener is registered. To make sure that the event listener is + // notified, we dispatch `tabs.onRemoved` asynchronously. + Services.tm.mainThread.dispatch(() => { + this.emit("tab-removed", {tab, tabId, windowId, isWindowClosing}); + }, Ci.nsIThread.DISPATCH_NORMAL); + }, + + tabReadyInitialized: false, + tabReadyPromises: new WeakMap(), + initializingTabs: new WeakSet(), + + initTabReady() { + if (!this.tabReadyInitialized) { + AllWindowEvents.addListener("progress", this); + + this.tabReadyInitialized = true; + } + }, + + onLocationChange(browser, webProgress, request, locationURI, flags) { + if (webProgress.isTopLevel) { + let gBrowser = browser.ownerGlobal.gBrowser; + let tab = gBrowser.getTabForBrowser(browser); + + // Now we are certain that the first page in the tab was loaded. + this.initializingTabs.delete(tab); + + // browser.innerWindowID is now set, resolve the promises if any. + let deferred = this.tabReadyPromises.get(tab); + if (deferred) { + deferred.resolve(tab); + this.tabReadyPromises.delete(tab); + } + } + }, + + /** + * Returns a promise that resolves when the tab is ready. + * Tabs created via the `tabs.create` method are "ready" once the location + * changes to the requested URL. Other tabs are assumed to be ready once their + * inner window ID is known. + * + * @param {XULElement} tab The element. + * @returns {Promise} Resolves with the given tab once ready. + */ + awaitTabReady(tab) { + let deferred = this.tabReadyPromises.get(tab); + if (!deferred) { + deferred = PromiseUtils.defer(); + if (!this.initializingTabs.has(tab) && tab.linkedBrowser.innerWindowID) { + deferred.resolve(tab); + } else { + this.initTabReady(); + this.tabReadyPromises.set(tab, deferred); + } + } + return deferred.promise; + }, +}; + +/* eslint-disable mozilla/balanced-listeners */ +extensions.on("startup", () => { + tabListener.init(); +}); +/* eslint-enable mozilla/balanced-listeners */ + +extensions.registerSchemaAPI("tabs", "addon_parent", context => { + let {extension} = context; + let self = { + tabs: { + onActivated: new WindowEventManager(context, "tabs.onActivated", "TabSelect", (fire, event) => { + let tab = event.originalTarget; + let tabId = TabManager.getId(tab); + let windowId = WindowManager.getId(tab.ownerGlobal); + fire({tabId, windowId}); + }).api(), + + onCreated: new EventManager(context, "tabs.onCreated", fire => { + let listener = (eventName, event) => { + fire(TabManager.convert(extension, event.tab)); + }; + + tabListener.on("tab-created", listener); + return () => { + tabListener.off("tab-created", listener); + }; + }).api(), + + /** + * Since multiple tabs currently can't be highlighted, onHighlighted + * essentially acts an alias for self.tabs.onActivated but returns + * the tabId in an array to match the API. + * @see https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/Tabs/onHighlighted + */ + onHighlighted: new WindowEventManager(context, "tabs.onHighlighted", "TabSelect", (fire, event) => { + let tab = event.originalTarget; + let tabIds = [TabManager.getId(tab)]; + let windowId = WindowManager.getId(tab.ownerGlobal); + fire({tabIds, windowId}); + }).api(), + + onAttached: new EventManager(context, "tabs.onAttached", fire => { + let listener = (eventName, event) => { + fire(event.tabId, {newWindowId: event.newWindowId, newPosition: event.newPosition}); + }; + + tabListener.on("tab-attached", listener); + return () => { + tabListener.off("tab-attached", listener); + }; + }).api(), + + onDetached: new EventManager(context, "tabs.onDetached", fire => { + let listener = (eventName, event) => { + fire(event.tabId, {oldWindowId: event.oldWindowId, oldPosition: event.oldPosition}); + }; + + tabListener.on("tab-detached", listener); + return () => { + tabListener.off("tab-detached", listener); + }; + }).api(), + + onRemoved: new EventManager(context, "tabs.onRemoved", fire => { + let listener = (eventName, event) => { + fire(event.tabId, {windowId: event.windowId, isWindowClosing: event.isWindowClosing}); + }; + + tabListener.on("tab-removed", listener); + return () => { + tabListener.off("tab-removed", listener); + }; + }).api(), + + onReplaced: ignoreEvent(context, "tabs.onReplaced"), + + onMoved: new EventManager(context, "tabs.onMoved", fire => { + // There are certain circumstances where we need to ignore a move event. + // + // Namely, the first time the tab is moved after it's created, we need + // to report the final position as the initial position in the tab's + // onAttached or onCreated event. This is because most tabs are inserted + // in a temporary location and then moved after the TabOpen event fires, + // which generates a TabOpen event followed by a TabMove event, which + // does not match the contract of our API. + let ignoreNextMove = new WeakSet(); + + let openListener = event => { + ignoreNextMove.add(event.target); + // Remove the tab from the set on the next tick, since it will already + // have been moved by then. + Promise.resolve().then(() => { + ignoreNextMove.delete(event.target); + }); + }; + + let moveListener = event => { + let tab = event.originalTarget; + + if (ignoreNextMove.has(tab)) { + ignoreNextMove.delete(tab); + return; + } + + fire(TabManager.getId(tab), { + windowId: WindowManager.getId(tab.ownerGlobal), + fromIndex: event.detail, + toIndex: tab._tPos, + }); + }; + + AllWindowEvents.addListener("TabMove", moveListener); + AllWindowEvents.addListener("TabOpen", openListener); + return () => { + AllWindowEvents.removeListener("TabMove", moveListener); + AllWindowEvents.removeListener("TabOpen", openListener); + }; + }).api(), + + onUpdated: new EventManager(context, "tabs.onUpdated", fire => { + function sanitize(extension, changeInfo) { + let result = {}; + let nonempty = false; + for (let prop in changeInfo) { + if ((prop != "favIconUrl" && prop != "url") || extension.hasPermission("tabs")) { + nonempty = true; + result[prop] = changeInfo[prop]; + } + } + return [nonempty, result]; + } + + let fireForBrowser = (browser, changed) => { + let [needed, changeInfo] = sanitize(extension, changed); + if (needed) { + let gBrowser = browser.ownerGlobal.gBrowser; + let tabElem = gBrowser.getTabForBrowser(browser); + + let tab = TabManager.convert(extension, tabElem); + fire(tab.id, changeInfo, tab); + } + }; + + let listener = event => { + let needed = []; + if (event.type == "TabAttrModified") { + let changed = event.detail.changed; + if (changed.includes("image")) { + needed.push("favIconUrl"); + } + if (changed.includes("muted")) { + needed.push("mutedInfo"); + } + if (changed.includes("soundplaying")) { + needed.push("audible"); + } + } else if (event.type == "TabPinned") { + needed.push("pinned"); + } else if (event.type == "TabUnpinned") { + needed.push("pinned"); + } + + if (needed.length && !extension.hasPermission("tabs")) { + needed = needed.filter(attr => attr != "url" && attr != "favIconUrl"); + } + + if (needed.length) { + let tab = TabManager.convert(extension, event.originalTarget); + + let changeInfo = {}; + for (let prop of needed) { + changeInfo[prop] = tab[prop]; + } + fire(tab.id, changeInfo, tab); + } + }; + let progressListener = { + onStateChange(browser, webProgress, request, stateFlags, statusCode) { + if (!webProgress.isTopLevel) { + return; + } + + let status; + if (stateFlags & Ci.nsIWebProgressListener.STATE_IS_WINDOW) { + if (stateFlags & Ci.nsIWebProgressListener.STATE_START) { + status = "loading"; + } else if (stateFlags & Ci.nsIWebProgressListener.STATE_STOP) { + status = "complete"; + } + } else if (stateFlags & Ci.nsIWebProgressListener.STATE_STOP && + statusCode == Cr.NS_BINDING_ABORTED) { + status = "complete"; + } + + fireForBrowser(browser, {status}); + }, + + onLocationChange(browser, webProgress, request, locationURI, flags) { + if (!webProgress.isTopLevel) { + return; + } + + fireForBrowser(browser, { + status: webProgress.isLoadingDocument ? "loading" : "complete", + url: locationURI.spec, + }); + }, + }; + + AllWindowEvents.addListener("progress", progressListener); + AllWindowEvents.addListener("TabAttrModified", listener); + AllWindowEvents.addListener("TabPinned", listener); + AllWindowEvents.addListener("TabUnpinned", listener); + + return () => { + AllWindowEvents.removeListener("progress", progressListener); + AllWindowEvents.removeListener("TabAttrModified", listener); + AllWindowEvents.removeListener("TabPinned", listener); + AllWindowEvents.removeListener("TabUnpinned", listener); + }; + }).api(), + + create: function(createProperties) { + return new Promise((resolve, reject) => { + let window = createProperties.windowId !== null ? + WindowManager.getWindow(createProperties.windowId, context) : + WindowManager.topWindow; + if (!window.gBrowser) { + let obs = (finishedWindow, topic, data) => { + if (finishedWindow != window) { + return; + } + Services.obs.removeObserver(obs, "browser-delayed-startup-finished"); + resolve(window); + }; + Services.obs.addObserver(obs, "browser-delayed-startup-finished", false); + } else { + resolve(window); + } + }).then(window => { + let url; + + if (createProperties.url !== null) { + url = context.uri.resolve(createProperties.url); + + if (!context.checkLoadURL(url, {dontReportErrors: true})) { + return Promise.reject({message: `Illegal URL: ${url}`}); + } + } + + if (createProperties.cookieStoreId && !extension.hasPermission("cookies")) { + return Promise.reject({message: `No permission for cookieStoreId: ${createProperties.cookieStoreId}`}); + } + + let options = {}; + if (createProperties.cookieStoreId) { + if (!global.isValidCookieStoreId(createProperties.cookieStoreId)) { + return Promise.reject({message: `Illegal cookieStoreId: ${createProperties.cookieStoreId}`}); + } + + let privateWindow = PrivateBrowsingUtils.isBrowserPrivate(window.gBrowser); + if (privateWindow && !global.isPrivateCookieStoreId(createProperties.cookieStoreId)) { + return Promise.reject({message: `Illegal to set non-private cookieStorageId in a private window`}); + } + + if (!privateWindow && global.isPrivateCookieStoreId(createProperties.cookieStoreId)) { + return Promise.reject({message: `Illegal to set private cookieStorageId in a non-private window`}); + } + + if (global.isContainerCookieStoreId(createProperties.cookieStoreId)) { + let containerId = global.getContainerForCookieStoreId(createProperties.cookieStoreId); + if (!containerId) { + return Promise.reject({message: `No cookie store exists with ID ${createProperties.cookieStoreId}`}); + } + + options.userContextId = containerId; + } + } + + tabListener.initTabReady(); + let tab = window.gBrowser.addTab(url || window.BROWSER_NEW_TAB_URL, options); + + let active = true; + if (createProperties.active !== null) { + active = createProperties.active; + } + if (active) { + window.gBrowser.selectedTab = tab; + } + + if (createProperties.index !== null) { + window.gBrowser.moveTabTo(tab, createProperties.index); + } + + if (createProperties.pinned) { + window.gBrowser.pinTab(tab); + } + + if (createProperties.url && !createProperties.url.startsWith("about:")) { + // We can't wait for a location change event for about:newtab, + // since it may be pre-rendered, in which case its initial + // location change event has already fired. + + // Mark the tab as initializing, so that operations like + // `executeScript` wait until the requested URL is loaded in + // the tab before dispatching messages to the inner window + // that contains the URL we're attempting to load. + tabListener.initializingTabs.add(tab); + } + + return TabManager.convert(extension, tab); + }); + }, + + remove: function(tabs) { + if (!Array.isArray(tabs)) { + tabs = [tabs]; + } + + for (let tabId of tabs) { + let tab = TabManager.getTab(tabId, context); + tab.ownerGlobal.gBrowser.removeTab(tab); + } + + return Promise.resolve(); + }, + + update: function(tabId, updateProperties) { + let tab = tabId !== null ? TabManager.getTab(tabId, context) : TabManager.activeTab; + + let tabbrowser = tab.ownerGlobal.gBrowser; + + if (updateProperties.url !== null) { + let url = context.uri.resolve(updateProperties.url); + + if (!context.checkLoadURL(url, {dontReportErrors: true})) { + return Promise.reject({message: `Illegal URL: ${url}`}); + } + + tab.linkedBrowser.loadURI(url); + } + + if (updateProperties.active !== null) { + if (updateProperties.active) { + tabbrowser.selectedTab = tab; + } else { + // Not sure what to do here? Which tab should we select? + } + } + if (updateProperties.muted !== null) { + if (tab.muted != updateProperties.muted) { + tab.toggleMuteAudio(extension.uuid); + } + } + if (updateProperties.pinned !== null) { + if (updateProperties.pinned) { + tabbrowser.pinTab(tab); + } else { + tabbrowser.unpinTab(tab); + } + } + // FIXME: highlighted/selected, openerTabId + + return Promise.resolve(TabManager.convert(extension, tab)); + }, + + reload: function(tabId, reloadProperties) { + let tab = tabId !== null ? TabManager.getTab(tabId, context) : TabManager.activeTab; + + let flags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE; + if (reloadProperties && reloadProperties.bypassCache) { + flags |= Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE; + } + tab.linkedBrowser.reloadWithFlags(flags); + + return Promise.resolve(); + }, + + get: function(tabId) { + let tab = TabManager.getTab(tabId, context); + + return Promise.resolve(TabManager.convert(extension, tab)); + }, + + getCurrent() { + let tab; + if (context.tabId) { + tab = TabManager.convert(extension, TabManager.getTab(context.tabId, context)); + } + return Promise.resolve(tab); + }, + + query: function(queryInfo) { + let pattern = null; + if (queryInfo.url !== null) { + if (!extension.hasPermission("tabs")) { + return Promise.reject({message: 'The "tabs" permission is required to use the query API with the "url" parameter'}); + } + + pattern = new MatchPattern(queryInfo.url); + } + + function matches(tab) { + let props = ["active", "pinned", "highlighted", "status", "title", "index"]; + for (let prop of props) { + if (queryInfo[prop] !== null && queryInfo[prop] != tab[prop]) { + return false; + } + } + + if (queryInfo.audible !== null) { + if (queryInfo.audible != tab.audible) { + return false; + } + } + + if (queryInfo.muted !== null) { + if (queryInfo.muted != tab.mutedInfo.muted) { + return false; + } + } + + if (queryInfo.cookieStoreId !== null && + tab.cookieStoreId != queryInfo.cookieStoreId) { + return false; + } + + if (pattern && !pattern.matches(Services.io.newURI(tab.url, null, null))) { + return false; + } + + return true; + } + + let result = []; + for (let window of WindowListManager.browserWindows()) { + let lastFocused = window === WindowManager.topWindow; + if (queryInfo.lastFocusedWindow !== null && queryInfo.lastFocusedWindow !== lastFocused) { + continue; + } + + let windowType = WindowManager.windowType(window); + if (queryInfo.windowType !== null && queryInfo.windowType !== windowType) { + continue; + } + + if (queryInfo.windowId !== null) { + if (queryInfo.windowId === WindowManager.WINDOW_ID_CURRENT) { + if (currentWindow(context) !== window) { + continue; + } + } else if (queryInfo.windowId !== WindowManager.getId(window)) { + continue; + } + } + + if (queryInfo.currentWindow !== null) { + let eq = window === currentWindow(context); + if (queryInfo.currentWindow != eq) { + continue; + } + } + + let tabs = TabManager.for(extension).getTabs(window); + for (let tab of tabs) { + if (matches(tab)) { + result.push(tab); + } + } + } + return Promise.resolve(result); + }, + + captureVisibleTab: function(windowId, options) { + if (!extension.hasPermission("")) { + return Promise.reject({message: "The permission is required to use the captureVisibleTab API"}); + } + + let window = windowId == null ? + WindowManager.topWindow : + WindowManager.getWindow(windowId, context); + + let tab = window.gBrowser.selectedTab; + return tabListener.awaitTabReady(tab).then(() => { + let browser = tab.linkedBrowser; + let recipient = { + innerWindowID: browser.innerWindowID, + }; + + if (!options) { + options = {}; + } + if (options.format == null) { + options.format = "png"; + } + if (options.quality == null) { + options.quality = 92; + } + + let message = { + options, + width: browser.clientWidth, + height: browser.clientHeight, + }; + + return context.sendMessage(browser.messageManager, "Extension:Capture", + message, {recipient}); + }); + }, + + detectLanguage: function(tabId) { + let tab = tabId !== null ? TabManager.getTab(tabId, context) : TabManager.activeTab; + + return tabListener.awaitTabReady(tab).then(() => { + let browser = tab.linkedBrowser; + let recipient = {innerWindowID: browser.innerWindowID}; + + return context.sendMessage(browser.messageManager, "Extension:DetectLanguage", + {}, {recipient}); + }); + }, + + // Used to executeScript, insertCSS and removeCSS. + _execute: function(tabId, details, kind, method) { + let tab = tabId !== null ? TabManager.getTab(tabId, context) : TabManager.activeTab; + + let options = { + js: [], + css: [], + remove_css: method == "removeCSS", + }; + + // We require a `code` or a `file` property, but we can't accept both. + if ((details.code === null) == (details.file === null)) { + return Promise.reject({message: `${method} requires either a 'code' or a 'file' property, but not both`}); + } + + if (details.frameId !== null && details.allFrames) { + return Promise.reject({message: `'frameId' and 'allFrames' are mutually exclusive`}); + } + + if (TabManager.for(extension).hasActiveTabPermission(tab)) { + // If we have the "activeTab" permission for this tab, ignore + // the host whitelist. + options.matchesHost = [""]; + } else { + options.matchesHost = extension.whiteListedHosts.serialize(); + } + + if (details.code !== null) { + options[kind + "Code"] = details.code; + } + if (details.file !== null) { + let url = context.uri.resolve(details.file); + if (!extension.isExtensionURL(url)) { + return Promise.reject({message: "Files to be injected must be within the extension"}); + } + options[kind].push(url); + } + if (details.allFrames) { + options.all_frames = details.allFrames; + } + if (details.frameId !== null) { + options.frame_id = details.frameId; + } + if (details.matchAboutBlank) { + options.match_about_blank = details.matchAboutBlank; + } + if (details.runAt !== null) { + options.run_at = details.runAt; + } else { + options.run_at = "document_idle"; + } + + return tabListener.awaitTabReady(tab).then(() => { + let browser = tab.linkedBrowser; + let recipient = { + innerWindowID: browser.innerWindowID, + }; + + return context.sendMessage(browser.messageManager, "Extension:Execute", {options}, {recipient}); + }); + }, + + executeScript: function(tabId, details) { + return self.tabs._execute(tabId, details, "js", "executeScript"); + }, + + insertCSS: function(tabId, details) { + return self.tabs._execute(tabId, details, "css", "insertCSS").then(() => {}); + }, + + removeCSS: function(tabId, details) { + return self.tabs._execute(tabId, details, "css", "removeCSS").then(() => {}); + }, + + move: function(tabIds, moveProperties) { + let index = moveProperties.index; + let tabsMoved = []; + if (!Array.isArray(tabIds)) { + tabIds = [tabIds]; + } + + let destinationWindow = null; + if (moveProperties.windowId !== null) { + destinationWindow = WindowManager.getWindow(moveProperties.windowId, context); + // Fail on an invalid window. + if (!destinationWindow) { + return Promise.reject({message: `Invalid window ID: ${moveProperties.windowId}`}); + } + } + + /* + Indexes are maintained on a per window basis so that a call to + move([tabA, tabB], {index: 0}) + -> tabA to 0, tabB to 1 if tabA and tabB are in the same window + move([tabA, tabB], {index: 0}) + -> tabA to 0, tabB to 0 if tabA and tabB are in different windows + */ + let indexMap = new Map(); + + let tabs = tabIds.map(tabId => TabManager.getTab(tabId, context)); + for (let tab of tabs) { + // If the window is not specified, use the window from the tab. + let window = destinationWindow || tab.ownerGlobal; + let gBrowser = window.gBrowser; + + let insertionPoint = indexMap.get(window) || index; + // If the index is -1 it should go to the end of the tabs. + if (insertionPoint == -1) { + insertionPoint = gBrowser.tabs.length; + } + + // We can only move pinned tabs to a point within, or just after, + // the current set of pinned tabs. Unpinned tabs, likewise, can only + // be moved to a position after the current set of pinned tabs. + // Attempts to move a tab to an illegal position are ignored. + let numPinned = gBrowser._numPinnedTabs; + let ok = tab.pinned ? insertionPoint <= numPinned : insertionPoint >= numPinned; + if (!ok) { + continue; + } + + indexMap.set(window, insertionPoint + 1); + + if (tab.ownerGlobal != window) { + // If the window we are moving the tab in is different, then move the tab + // to the new window. + tab = gBrowser.adoptTab(tab, insertionPoint, false); + } else { + // If the window we are moving is the same, just move the tab. + gBrowser.moveTabTo(tab, insertionPoint); + } + tabsMoved.push(tab); + } + + return Promise.resolve(tabsMoved.map(tab => TabManager.convert(extension, tab))); + }, + + duplicate: function(tabId) { + let tab = TabManager.getTab(tabId, context); + + let gBrowser = tab.ownerGlobal.gBrowser; + let newTab = gBrowser.duplicateTab(tab); + + return new Promise(resolve => { + // We need to use SSTabRestoring because any attributes set before + // are ignored. SSTabRestored is too late and results in a jump in + // the UI. See http://bit.ly/session-store-api for more information. + newTab.addEventListener("SSTabRestoring", function listener() { + // As the tab is restoring, move it to the correct position. + newTab.removeEventListener("SSTabRestoring", listener); + // Pinned tabs that are duplicated are inserted + // after the existing pinned tab and pinned. + if (tab.pinned) { + gBrowser.pinTab(newTab); + } + gBrowser.moveTabTo(newTab, tab._tPos + 1); + }); + + newTab.addEventListener("SSTabRestored", function listener() { + // Once it has been restored, select it and return the promise. + newTab.removeEventListener("SSTabRestored", listener); + gBrowser.selectedTab = newTab; + return resolve(TabManager.convert(extension, newTab)); + }); + }); + }, + + getZoom(tabId) { + let tab = tabId ? TabManager.getTab(tabId, context) : TabManager.activeTab; + + let {ZoomManager} = tab.ownerGlobal; + let zoom = ZoomManager.getZoomForBrowser(tab.linkedBrowser); + + return Promise.resolve(zoom); + }, + + setZoom(tabId, zoom) { + let tab = tabId ? TabManager.getTab(tabId, context) : TabManager.activeTab; + + let {FullZoom, ZoomManager} = tab.ownerGlobal; + + if (zoom === 0) { + // A value of zero means use the default zoom factor. + return FullZoom.reset(tab.linkedBrowser); + } else if (zoom >= ZoomManager.MIN && zoom <= ZoomManager.MAX) { + FullZoom.setZoom(zoom, tab.linkedBrowser); + } else { + return Promise.reject({ + message: `Zoom value ${zoom} out of range (must be between ${ZoomManager.MIN} and ${ZoomManager.MAX})`, + }); + } + + return Promise.resolve(); + }, + + _getZoomSettings(tabId) { + let tab = tabId ? TabManager.getTab(tabId, context) : TabManager.activeTab; + + let {FullZoom} = tab.ownerGlobal; + + return { + mode: "automatic", + scope: FullZoom.siteSpecific ? "per-origin" : "per-tab", + defaultZoomFactor: 1, + }; + }, + + getZoomSettings(tabId) { + return Promise.resolve(this._getZoomSettings(tabId)); + }, + + setZoomSettings(tabId, settings) { + let tab = tabId ? TabManager.getTab(tabId, context) : TabManager.activeTab; + + let currentSettings = this._getZoomSettings(tab.id); + + if (!Object.keys(settings).every(key => settings[key] === currentSettings[key])) { + return Promise.reject(`Unsupported zoom settings: ${JSON.stringify(settings)}`); + } + return Promise.resolve(); + }, + + onZoomChange: new EventManager(context, "tabs.onZoomChange", fire => { + let getZoomLevel = browser => { + let {ZoomManager} = browser.ownerGlobal; + + return ZoomManager.getZoomForBrowser(browser); + }; + + // Stores the last known zoom level for each tab's browser. + // WeakMap[ -> number] + let zoomLevels = new WeakMap(); + + // Store the zoom level for all existing tabs. + for (let window of WindowListManager.browserWindows()) { + for (let tab of window.gBrowser.tabs) { + let browser = tab.linkedBrowser; + zoomLevels.set(browser, getZoomLevel(browser)); + } + } + + let tabCreated = (eventName, event) => { + let browser = event.tab.linkedBrowser; + zoomLevels.set(browser, getZoomLevel(browser)); + }; + + + let zoomListener = event => { + let browser = event.originalTarget; + + // For non-remote browsers, this event is dispatched on the document + // rather than on the . + if (browser instanceof Ci.nsIDOMDocument) { + browser = browser.defaultView.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell) + .chromeEventHandler; + } + + let {gBrowser} = browser.ownerGlobal; + let tab = gBrowser.getTabForBrowser(browser); + if (!tab) { + // We only care about zoom events in the top-level browser of a tab. + return; + } + + let oldZoomFactor = zoomLevels.get(browser); + let newZoomFactor = getZoomLevel(browser); + + if (oldZoomFactor != newZoomFactor) { + zoomLevels.set(browser, newZoomFactor); + + let tabId = TabManager.getId(tab); + fire({ + tabId, + oldZoomFactor, + newZoomFactor, + zoomSettings: self.tabs._getZoomSettings(tabId), + }); + } + }; + + tabListener.on("tab-attached", tabCreated); + tabListener.on("tab-created", tabCreated); + + AllWindowEvents.addListener("FullZoomChange", zoomListener); + AllWindowEvents.addListener("TextZoomChange", zoomListener); + return () => { + tabListener.off("tab-attached", tabCreated); + tabListener.off("tab-created", tabCreated); + + AllWindowEvents.removeListener("FullZoomChange", zoomListener); + AllWindowEvents.removeListener("TextZoomChange", zoomListener); + }; + }).api(), + }, + }; + return self; +}); diff --git a/application/basilisk/components/webextensions/ext-utils.js b/application/basilisk/components/webextensions/ext-utils.js new file mode 100644 index 000000000..75b2f4bd4 --- /dev/null +++ b/application/basilisk/components/webextensions/ext-utils.js @@ -0,0 +1,1239 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +XPCOMUtils.defineLazyModuleGetter(this, "CustomizableUI", + "resource:///modules/CustomizableUI.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", + "resource://gre/modules/NetUtil.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Task", + "resource://gre/modules/Task.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "setTimeout", + "resource://gre/modules/Timer.jsm"); + +XPCOMUtils.defineLazyServiceGetter(this, "styleSheetService", + "@mozilla.org/content/style-sheet-service;1", + "nsIStyleSheetService"); + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +Cu.import("resource://gre/modules/AppConstants.jsm"); + +const POPUP_LOAD_TIMEOUT_MS = 200; + +const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; + +var { + DefaultWeakMap, + EventManager, + promiseEvent, +} = ExtensionUtils; + +// This file provides some useful code for the |tabs| and |windows| +// modules. All of the code is installed on |global|, which is a scope +// shared among the different ext-*.js scripts. + +global.makeWidgetId = id => { + id = id.toLowerCase(); + // FIXME: This allows for collisions. + return id.replace(/[^a-z0-9_-]/g, "_"); +}; + +function promisePopupShown(popup) { + return new Promise(resolve => { + if (popup.state == "open") { + resolve(); + } else { + popup.addEventListener("popupshown", function onPopupShown(event) { + popup.removeEventListener("popupshown", onPopupShown); + resolve(); + }); + } + }); +} + +XPCOMUtils.defineLazyGetter(this, "popupStylesheets", () => { + let stylesheets = ["chrome://browser/content/extension.css"]; + + if (AppConstants.platform === "macosx") { + stylesheets.push("chrome://browser/content/extension-mac.css"); + } + return stylesheets; +}); + +XPCOMUtils.defineLazyGetter(this, "standaloneStylesheets", () => { + let stylesheets = []; + + if (AppConstants.platform === "macosx") { + stylesheets.push("chrome://browser/content/extension-mac-panel.css"); + } + if (AppConstants.platform === "win") { + stylesheets.push("chrome://browser/content/extension-win-panel.css"); + } + return stylesheets; +}); + +class BasePopup { + constructor(extension, viewNode, popupURL, browserStyle, fixedWidth = false) { + this.extension = extension; + this.popupURL = popupURL; + this.viewNode = viewNode; + this.browserStyle = browserStyle; + this.window = viewNode.ownerGlobal; + this.destroyed = false; + this.fixedWidth = fixedWidth; + + extension.callOnClose(this); + + this.contentReady = new Promise(resolve => { + this._resolveContentReady = resolve; + }); + + this.viewNode.addEventListener(this.DESTROY_EVENT, this); + + let doc = viewNode.ownerDocument; + let arrowContent = doc.getAnonymousElementByAttribute(this.panel, "class", "panel-arrowcontent"); + this.borderColor = doc.defaultView.getComputedStyle(arrowContent).borderTopColor; + + this.browser = null; + this.browserLoaded = new Promise((resolve, reject) => { + this.browserLoadedDeferred = {resolve, reject}; + }); + this.browserReady = this.createBrowser(viewNode, popupURL); + + BasePopup.instances.get(this.window).set(extension, this); + } + + static for(extension, window) { + return BasePopup.instances.get(window).get(extension); + } + + close() { + this.closePopup(); + } + + destroy() { + this.extension.forgetOnClose(this); + + this.destroyed = true; + this.browserLoadedDeferred.reject(new Error("Popup destroyed")); + return this.browserReady.then(() => { + this.destroyBrowser(this.browser); + this.browser.remove(); + + this.viewNode.removeEventListener(this.DESTROY_EVENT, this); + this.viewNode.style.maxHeight = ""; + + if (this.panel) { + this.panel.style.removeProperty("--arrowpanel-background"); + this.panel.style.removeProperty("--panel-arrow-image-vertical"); + } + + BasePopup.instances.get(this.window).delete(this.extension); + + this.browser = null; + this.viewNode = null; + }); + } + + destroyBrowser(browser) { + let mm = browser.messageManager; + // If the browser has already been removed from the document, because the + // popup was closed externally, there will be no message manager here. + if (mm) { + mm.removeMessageListener("DOMTitleChanged", this); + mm.removeMessageListener("Extension:BrowserBackgroundChanged", this); + mm.removeMessageListener("Extension:BrowserContentLoaded", this); + mm.removeMessageListener("Extension:BrowserResized", this); + mm.removeMessageListener("Extension:DOMWindowClose", this); + } + } + + // Returns the name of the event fired on `viewNode` when the popup is being + // destroyed. This must be implemented by every subclass. + get DESTROY_EVENT() { + throw new Error("Not implemented"); + } + + get STYLESHEETS() { + let sheets = []; + + if (this.browserStyle) { + sheets.push(...popupStylesheets); + } + if (!this.fixedWidth) { + sheets.push(...standaloneStylesheets); + } + + return sheets; + } + + get panel() { + let panel = this.viewNode; + while (panel && panel.localName != "panel") { + panel = panel.parentNode; + } + return panel; + } + + receiveMessage({name, data}) { + switch (name) { + case "DOMTitleChanged": + this.viewNode.setAttribute("aria-label", this.browser.contentTitle); + break; + + case "Extension:BrowserBackgroundChanged": + this.setBackground(data.background); + break; + + case "Extension:BrowserContentLoaded": + this.browserLoadedDeferred.resolve(); + break; + + case "Extension:BrowserResized": + this._resolveContentReady(); + if (this.ignoreResizes) { + this.dimensions = data; + } else { + this.resizeBrowser(data); + } + break; + + case "Extension:DOMWindowClose": + this.closePopup(); + break; + } + } + + handleEvent(event) { + switch (event.type) { + case this.DESTROY_EVENT: + this.destroy(); + break; + } + } + + createBrowser(viewNode, popupURL = null) { + let document = viewNode.ownerDocument; + this.browser = document.createElementNS(XUL_NS, "browser"); + this.browser.setAttribute("type", "content"); + this.browser.setAttribute("disableglobalhistory", "true"); + this.browser.setAttribute("transparent", "true"); + this.browser.setAttribute("class", "webextension-popup-browser"); + this.browser.setAttribute("tooltip", "aHTMLTooltip"); + + // We only need flex sizing for the sake of the slide-in sub-views of the + // main menu panel, so that the browser occupies the full width of the view, + // and also takes up any extra height that's available to it. + this.browser.setAttribute("flex", "1"); + + // Note: When using noautohide panels, the popup manager will add width and + // height attributes to the panel, breaking our resize code, if the browser + // starts out smaller than 30px by 10px. This isn't an issue now, but it + // will be if and when we popup debugging. + + viewNode.appendChild(this.browser); + + extensions.emit("extension-browser-inserted", this.browser); + let windowId = WindowManager.getId(this.browser.ownerGlobal); + this.browser.messageManager.sendAsyncMessage("Extension:InitExtensionView", { + viewType: "popup", + windowId, + }); + // TODO(robwu): Rework this to use the Extension:ExtensionViewLoaded message + // to detect loads and so on. And definitely move this content logic inside + // a file in the child process. + + let initBrowser = browser => { + let mm = browser.messageManager; + mm.addMessageListener("DOMTitleChanged", this); + mm.addMessageListener("Extension:BrowserBackgroundChanged", this); + mm.addMessageListener("Extension:BrowserContentLoaded", this); + mm.addMessageListener("Extension:BrowserResized", this); + mm.addMessageListener("Extension:DOMWindowClose", this, true); + }; + + if (!popupURL) { + initBrowser(this.browser); + return this.browser; + } + + return promiseEvent(this.browser, "load").then(() => { + initBrowser(this.browser); + + let mm = this.browser.messageManager; + + mm.loadFrameScript( + "chrome://extensions/content/ext-browser-content.js", false); + + mm.sendAsyncMessage("Extension:InitBrowser", { + allowScriptsToClose: true, + fixedWidth: this.fixedWidth, + maxWidth: 800, + maxHeight: 600, + stylesheets: this.STYLESHEETS, + }); + + this.browser.setAttribute("src", popupURL); + }); + } + + resizeBrowser({width, height, detail}) { + if (this.fixedWidth) { + // Figure out how much extra space we have on the side of the panel + // opposite the arrow. + let side = this.panel.getAttribute("side") == "top" ? "bottom" : "top"; + let maxHeight = this.viewHeight + this.extraHeight[side]; + + height = Math.min(height, maxHeight); + this.browser.style.height = `${height}px`; + + // Set a maximum height on the element to our preferred + // maximum height, so that the PanelUI resizing code can make an accurate + // calculation. If we don't do this, the flex sizing logic will prevent us + // from ever reporting a preferred size smaller than the height currently + // available to us in the panel. + height = Math.max(height, this.viewHeight); + this.viewNode.style.maxHeight = `${height}px`; + } else { + this.browser.style.width = `${width}px`; + this.browser.style.height = `${height}px`; + } + + let event = new this.window.CustomEvent("WebExtPopupResized", {detail}); + this.browser.dispatchEvent(event); + } + + setBackground(background) { + let panelBackground = ""; + let panelArrow = ""; + + if (background) { + let borderColor = this.borderColor || background; + + panelBackground = background; + panelArrow = `url("data:image/svg+xml,${encodeURIComponent(` + + + + + `)}")`; + } + + this.panel.style.setProperty("--arrowpanel-background", panelBackground); + this.panel.style.setProperty("--panel-arrow-image-vertical", panelArrow); + this.background = background; + } +} + +/** + * A map of active popups for a given browser window. + * + * WeakMap[window -> WeakMap[Extension -> BasePopup]] + */ +BasePopup.instances = new DefaultWeakMap(() => new WeakMap()); + +class PanelPopup extends BasePopup { + constructor(extension, imageNode, popupURL, browserStyle) { + let document = imageNode.ownerDocument; + + let panel = document.createElement("panel"); + panel.setAttribute("id", makeWidgetId(extension.id) + "-panel"); + panel.setAttribute("class", "browser-extension-panel"); + panel.setAttribute("tabspecific", "true"); + panel.setAttribute("type", "arrow"); + panel.setAttribute("role", "group"); + + document.getElementById("mainPopupSet").appendChild(panel); + + super(extension, panel, popupURL, browserStyle); + + this.contentReady.then(() => { + panel.openPopup(imageNode, "bottomcenter topright", 0, 0, false, false); + + let event = new this.window.CustomEvent("WebExtPopupLoaded", { + bubbles: true, + detail: {extension}, + }); + this.browser.dispatchEvent(event); + }); + } + + get DESTROY_EVENT() { + return "popuphidden"; + } + + destroy() { + super.destroy(); + this.viewNode.remove(); + } + + closePopup() { + promisePopupShown(this.viewNode).then(() => { + // Make sure we're not already destroyed. + if (this.viewNode) { + this.viewNode.hidePopup(); + } + }); + } +} + +class ViewPopup extends BasePopup { + constructor(extension, window, popupURL, browserStyle, fixedWidth) { + let document = window.document; + + // Create a temporary panel to hold the browser while it pre-loads its + // content. This panel will never be shown, but the browser's docShell will + // be swapped with the browser in the real panel when it's ready. + let panel = document.createElement("panel"); + panel.setAttribute("type", "arrow"); + document.getElementById("mainPopupSet").appendChild(panel); + + super(extension, panel, popupURL, browserStyle, fixedWidth); + + this.ignoreResizes = true; + + this.attached = false; + this.tempPanel = panel; + + this.browser.classList.add("webextension-preload-browser"); + } + + /** + * Attaches the pre-loaded browser to the given view node, and reserves a + * promise which resolves when the browser is ready. + * + * @param {Element} viewNode + * The node to attach the browser to. + * @returns {Promise} + * Resolves when the browser is ready. Resolves to `false` if the + * browser was destroyed before it was fully loaded, and the popup + * should be closed, or `true` otherwise. + */ + attach(viewNode) { + return Task.spawn(function* () { + this.viewNode = viewNode; + this.viewNode.addEventListener(this.DESTROY_EVENT, this); + + // Wait until the browser element is fully initialized, and give it at least + // a short grace period to finish loading its initial content, if necessary. + // + // In practice, the browser that was created by the mousdown handler should + // nearly always be ready by this point. + yield Promise.all([ + this.browserReady, + Promise.race([ + // This promise may be rejected if the popup calls window.close() + // before it has fully loaded. + this.browserLoaded.catch(() => {}), + new Promise(resolve => setTimeout(resolve, POPUP_LOAD_TIMEOUT_MS)), + ]), + ]); + + if (!this.destroyed && !this.panel) { + this.destroy(); + } + + if (this.destroyed) { + return false; + } + + this.attached = true; + + // Store the initial height of the view, so that we never resize menu panel + // sub-views smaller than the initial height of the menu. + this.viewHeight = this.viewNode.boxObject.height; + + // Calculate the extra height available on the screen above and below the + // menu panel. Use that to calculate the how much the sub-view may grow. + let popupRect = this.panel.getBoundingClientRect(); + + this.setBackground(this.background); + + let win = this.window; + let popupBottom = win.mozInnerScreenY + popupRect.bottom; + let popupTop = win.mozInnerScreenY + popupRect.top; + + let screenBottom = win.screen.availTop + win.screen.availHeight; + this.extraHeight = { + bottom: Math.max(0, screenBottom - popupBottom), + top: Math.max(0, popupTop - win.screen.availTop), + }; + + // Create a new browser in the real popup. + let browser = this.browser; + this.createBrowser(this.viewNode); + + this.browser.swapDocShells(browser); + this.destroyBrowser(browser); + + this.ignoreResizes = false; + if (this.dimensions) { + this.resizeBrowser(this.dimensions); + } + + this.tempPanel.remove(); + this.tempPanel = null; + + let event = new this.window.CustomEvent("WebExtPopupLoaded", { + bubbles: true, + detail: {extension: this.extension}, + }); + this.browser.dispatchEvent(event); + + return true; + }.bind(this)); + } + + destroy() { + return super.destroy().then(() => { + if (this.tempPanel) { + this.tempPanel.remove(); + this.tempPanel = null; + } + }); + } + + get DESTROY_EVENT() { + return "ViewHiding"; + } + + closePopup() { + if (this.attached) { + CustomizableUI.hidePanelForNode(this.viewNode); + } else { + this.destroy(); + } + } +} + +Object.assign(global, {PanelPopup, ViewPopup}); + +// Manages tab-specific context data, and dispatching tab select events +// across all windows. +global.TabContext = function TabContext(getDefaults, extension) { + this.extension = extension; + this.getDefaults = getDefaults; + + this.tabData = new WeakMap(); + this.lastLocation = new WeakMap(); + + AllWindowEvents.addListener("progress", this); + AllWindowEvents.addListener("TabSelect", this); + + EventEmitter.decorate(this); +}; + +TabContext.prototype = { + get(tab) { + if (!this.tabData.has(tab)) { + this.tabData.set(tab, this.getDefaults(tab)); + } + + return this.tabData.get(tab); + }, + + clear(tab) { + this.tabData.delete(tab); + }, + + handleEvent(event) { + if (event.type == "TabSelect") { + let tab = event.target; + this.emit("tab-select", tab); + this.emit("location-change", tab); + } + }, + + onStateChange(browser, webProgress, request, stateFlags, statusCode) { + let flags = Ci.nsIWebProgressListener; + + if (!(~stateFlags & (flags.STATE_IS_WINDOW | flags.STATE_START) || + this.lastLocation.has(browser))) { + this.lastLocation.set(browser, request.URI); + } + }, + + onLocationChange(browser, webProgress, request, locationURI, flags) { + let gBrowser = browser.ownerGlobal.gBrowser; + let lastLocation = this.lastLocation.get(browser); + if (browser === gBrowser.selectedBrowser && + !(lastLocation && lastLocation.equalsExceptRef(browser.currentURI))) { + let tab = gBrowser.getTabForBrowser(browser); + this.emit("location-change", tab, true); + } + this.lastLocation.set(browser, browser.currentURI); + }, + + shutdown() { + AllWindowEvents.removeListener("progress", this); + AllWindowEvents.removeListener("TabSelect", this); + }, +}; + +// Manages tab mappings and permissions for a specific extension. +function ExtensionTabManager(extension) { + this.extension = extension; + + // A mapping of tab objects to the inner window ID the extension currently has + // the active tab permission for. The active permission for a given tab is + // valid only for the inner window that was active when the permission was + // granted. If the tab navigates, the inner window ID changes, and the + // permission automatically becomes stale. + // + // WeakMap[tab => inner-window-id] + this.hasTabPermissionFor = new WeakMap(); +} + +ExtensionTabManager.prototype = { + addActiveTabPermission(tab = TabManager.activeTab) { + if (this.extension.hasPermission("activeTab")) { + // Note that, unlike Chrome, we don't currently clear this permission with + // the tab navigates. If the inner window is revived from BFCache before + // we've granted this permission to a new inner window, the extension + // maintains its permissions for it. + this.hasTabPermissionFor.set(tab, tab.linkedBrowser.innerWindowID); + } + }, + + revokeActiveTabPermission(tab = TabManager.activeTab) { + this.hasTabPermissionFor.delete(tab); + }, + + // Returns true if the extension has the "activeTab" permission for this tab. + // This is somewhat more permissive than the generic "tabs" permission, as + // checked by |hasTabPermission|, in that it also allows programmatic script + // injection without an explicit host permission. + hasActiveTabPermission(tab) { + // This check is redundant with addTabPermission, but cheap. + if (this.extension.hasPermission("activeTab")) { + return (this.hasTabPermissionFor.has(tab) && + this.hasTabPermissionFor.get(tab) === tab.linkedBrowser.innerWindowID); + } + return false; + }, + + hasTabPermission(tab) { + return this.extension.hasPermission("tabs") || this.hasActiveTabPermission(tab); + }, + + convert(tab) { + let window = tab.ownerGlobal; + let browser = tab.linkedBrowser; + + let mutedInfo = {muted: tab.muted}; + if (tab.muteReason === null) { + mutedInfo.reason = "user"; + } else if (tab.muteReason) { + mutedInfo.reason = "extension"; + mutedInfo.extensionId = tab.muteReason; + } + + let result = { + id: TabManager.getId(tab), + index: tab._tPos, + windowId: WindowManager.getId(window), + selected: tab.selected, + highlighted: tab.selected, + active: tab.selected, + pinned: tab.pinned, + status: TabManager.getStatus(tab), + incognito: WindowManager.isBrowserPrivate(browser), + width: browser.frameLoader.lazyWidth || browser.clientWidth, + height: browser.frameLoader.lazyHeight || browser.clientHeight, + audible: tab.soundPlaying, + mutedInfo, + }; + if (this.extension.hasPermission("cookies")) { + result.cookieStoreId = getCookieStoreIdForTab(result, tab); + } + + if (this.hasTabPermission(tab)) { + result.url = browser.currentURI.spec; + let title = browser.contentTitle || tab.label; + if (title) { + result.title = title; + } + let icon = window.gBrowser.getIcon(tab); + if (icon) { + result.favIconUrl = icon; + } + } + + return result; + }, + + // Converts tabs returned from SessionStore.getClosedTabData and + // SessionStore.getClosedWindowData into API tab objects + convertFromSessionStoreClosedData(tab, window) { + let result = { + sessionId: String(tab.closedId), + index: tab.pos ? tab.pos : 0, + windowId: WindowManager.getId(window), + selected: false, + highlighted: false, + active: false, + pinned: false, + incognito: Boolean(tab.state && tab.state.isPrivate), + }; + + if (this.hasTabPermission(tab)) { + let entries = tab.state ? tab.state.entries : tab.entries; + result.url = entries[0].url; + result.title = entries[0].title; + if (tab.image) { + result.favIconUrl = tab.image; + } + } + + return result; + }, + + getTabs(window) { + return Array.from(window.gBrowser.tabs) + .filter(tab => !tab.closing) + .map(tab => this.convert(tab)); + }, +}; + +// Sends the tab and windowId upon request. This is primarily used to support +// the synchronous `browser.extension.getViews` API. +let onGetTabAndWindowId = { + receiveMessage({name, target, sync}) { + let {gBrowser} = target.ownerGlobal; + let tab = gBrowser && gBrowser.getTabForBrowser(target); + if (tab) { + let reply = { + tabId: TabManager.getId(tab), + windowId: WindowManager.getId(tab.ownerGlobal), + }; + if (sync) { + return reply; + } + target.messageManager.sendAsyncMessage("Extension:SetTabAndWindowId", reply); + } + }, +}; +/* eslint-disable mozilla/balanced-listeners */ +Services.mm.addMessageListener("Extension:GetTabAndWindowId", onGetTabAndWindowId); +/* eslint-enable mozilla/balanced-listeners */ + + +// Manages global mappings between XUL tabs and extension tab IDs. +global.TabManager = { + _tabs: new WeakMap(), + _nextId: 1, + _initialized: false, + + // We begin listening for TabOpen and TabClose events once we've started + // assigning IDs to tabs, so that we can remap the IDs of tabs which are moved + // between windows. + initListener() { + if (this._initialized) { + return; + } + + AllWindowEvents.addListener("TabOpen", this); + AllWindowEvents.addListener("TabClose", this); + WindowListManager.addOpenListener(this.handleWindowOpen.bind(this)); + + this._initialized = true; + }, + + handleEvent(event) { + if (event.type == "TabOpen") { + let {adoptedTab} = event.detail; + if (adoptedTab) { + // This tab is being created to adopt a tab from a different window. + // Copy the ID from the old tab to the new. + let tab = event.target; + this._tabs.set(tab, this.getId(adoptedTab)); + + tab.linkedBrowser.messageManager.sendAsyncMessage("Extension:SetTabAndWindowId", { + windowId: WindowManager.getId(tab.ownerGlobal), + }); + } + } else if (event.type == "TabClose") { + let {adoptedBy} = event.detail; + if (adoptedBy) { + // This tab is being closed because it was adopted by a new window. + // Copy its ID to the new tab, in case it was created as the first tab + // of a new window, and did not have an `adoptedTab` detail when it was + // opened. + this._tabs.set(adoptedBy, this.getId(event.target)); + + adoptedBy.linkedBrowser.messageManager.sendAsyncMessage("Extension:SetTabAndWindowId", { + windowId: WindowManager.getId(adoptedBy), + }); + } + } + }, + + handleWindowOpen(window) { + if (window.arguments && window.arguments[0] instanceof window.XULElement) { + // If the first window argument is a XUL element, it means the + // window is about to adopt a tab from another window to replace its + // initial tab. + let adoptedTab = window.arguments[0]; + + this._tabs.set(window.gBrowser.tabs[0], this.getId(adoptedTab)); + } + }, + + getId(tab) { + if (this._tabs.has(tab)) { + return this._tabs.get(tab); + } + this.initListener(); + + let id = this._nextId++; + this._tabs.set(tab, id); + return id; + }, + + getBrowserId(browser) { + let gBrowser = browser.ownerGlobal.gBrowser; + // Some non-browser windows have gBrowser but not + // getTabForBrowser! + if (gBrowser && gBrowser.getTabForBrowser) { + let tab = gBrowser.getTabForBrowser(browser); + if (tab) { + return this.getId(tab); + } + } + return -1; + }, + + /** + * Returns the XUL element associated with the given tab ID. If no tab + * with the given ID exists, and no default value is provided, an error is + * raised, belonging to the scope of the given context. + * + * @param {integer} tabId + * The ID of the tab to retrieve. + * @param {ExtensionContext} context + * The context of the caller. + * This value may be omitted if `default_` is not `undefined`. + * @param {*} default_ + * The value to return if no tab exists with the given ID. + * @returns {Element} + * A XUL element. + */ + getTab(tabId, context, default_ = undefined) { + // FIXME: Speed this up without leaking memory somehow. + for (let window of WindowListManager.browserWindows()) { + if (!window.gBrowser) { + continue; + } + for (let tab of window.gBrowser.tabs) { + if (this.getId(tab) == tabId) { + return tab; + } + } + } + if (default_ !== undefined) { + return default_; + } + throw new context.cloneScope.Error(`Invalid tab ID: ${tabId}`); + }, + + get activeTab() { + let window = WindowManager.topWindow; + if (window && window.gBrowser) { + return window.gBrowser.selectedTab; + } + return null; + }, + + getStatus(tab) { + return tab.getAttribute("busy") == "true" ? "loading" : "complete"; + }, + + convert(extension, tab) { + return TabManager.for(extension).convert(tab); + }, +}; + +// WeakMap[Extension -> ExtensionTabManager] +let tabManagers = new WeakMap(); + +// Returns the extension-specific tab manager for the given extension, or +// creates one if it doesn't already exist. +TabManager.for = function(extension) { + if (!tabManagers.has(extension)) { + tabManagers.set(extension, new ExtensionTabManager(extension)); + } + return tabManagers.get(extension); +}; + +/* eslint-disable mozilla/balanced-listeners */ +extensions.on("shutdown", (type, extension) => { + tabManagers.delete(extension); +}); +/* eslint-enable mozilla/balanced-listeners */ + +function memoize(fn) { + let weakMap = new DefaultWeakMap(fn); + return weakMap.get.bind(weakMap); +} + +// Manages mapping between XUL windows and extension window IDs. +global.WindowManager = { + _windows: new WeakMap(), + _nextId: 0, + + // Note: These must match the values in windows.json. + WINDOW_ID_NONE: -1, + WINDOW_ID_CURRENT: -2, + + get topWindow() { + return Services.wm.getMostRecentWindow("navigator:browser"); + }, + + windowType(window) { + // TODO: Make this work. + + let {chromeFlags} = window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell) + .treeOwner.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIXULWindow); + + if (chromeFlags & Ci.nsIWebBrowserChrome.CHROME_OPENAS_DIALOG) { + return "popup"; + } + + return "normal"; + }, + + updateGeometry(window, options) { + if (options.left !== null || options.top !== null) { + let left = options.left !== null ? options.left : window.screenX; + let top = options.top !== null ? options.top : window.screenY; + window.moveTo(left, top); + } + + if (options.width !== null || options.height !== null) { + let width = options.width !== null ? options.width : window.outerWidth; + let height = options.height !== null ? options.height : window.outerHeight; + window.resizeTo(width, height); + } + }, + + isBrowserPrivate: memoize(browser => { + return PrivateBrowsingUtils.isBrowserPrivate(browser); + }), + + getId(window) { + if (this._windows.has(window)) { + return this._windows.get(window); + } + let id = this._nextId++; + this._windows.set(window, id); + return id; + }, + + getWindow(id, context) { + if (id == this.WINDOW_ID_CURRENT) { + return currentWindow(context); + } + + for (let window of WindowListManager.browserWindows(true)) { + if (this.getId(window) == id) { + return window; + } + } + return null; + }, + + getState(window) { + const STATES = { + [window.STATE_MAXIMIZED]: "maximized", + [window.STATE_MINIMIZED]: "minimized", + [window.STATE_NORMAL]: "normal", + }; + let state = STATES[window.windowState]; + if (window.fullScreen) { + state = "fullscreen"; + } + return state; + }, + + setState(window, state) { + if (state != "fullscreen" && window.fullScreen) { + window.fullScreen = false; + } + + switch (state) { + case "maximized": + window.maximize(); + break; + + case "minimized": + case "docked": + window.minimize(); + break; + + case "normal": + // Restore sometimes returns the window to its previous state, rather + // than to the "normal" state, so it may need to be called anywhere from + // zero to two times. + window.restore(); + if (window.windowState != window.STATE_NORMAL) { + window.restore(); + } + if (window.windowState != window.STATE_NORMAL) { + // And on OS-X, where normal vs. maximized is basically a heuristic, + // we need to cheat. + window.sizeToContent(); + } + break; + + case "fullscreen": + window.fullScreen = true; + break; + + default: + throw new Error(`Unexpected window state: ${state}`); + } + }, + + convert(extension, window, getInfo) { + let xulWindow = window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell) + .treeOwner.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIXULWindow); + + let result = { + id: this.getId(window), + focused: window.document.hasFocus(), + top: window.screenY, + left: window.screenX, + width: window.outerWidth, + height: window.outerHeight, + incognito: PrivateBrowsingUtils.isWindowPrivate(window), + type: this.windowType(window), + state: this.getState(window), + alwaysOnTop: xulWindow.zLevel >= Ci.nsIXULWindow.raisedZ, + }; + + if (getInfo && getInfo.populate) { + result.tabs = TabManager.for(extension).getTabs(window); + } + + return result; + }, + + // Converts windows returned from SessionStore.getClosedWindowData + // into API window objects + convertFromSessionStoreClosedData(window, extension) { + let result = { + sessionId: String(window.closedId), + focused: false, + incognito: false, + type: "normal", // this is always "normal" for a closed window + state: this.getState(window), + alwaysOnTop: false, + }; + + if (window.tabs.length) { + result.tabs = []; + window.tabs.forEach((tab, index) => { + result.tabs.push(TabManager.for(extension).convertFromSessionStoreClosedData(tab, window, index)); + }); + } + + return result; + }, +}; + +// Manages listeners for window opening and closing. A window is +// considered open when the "load" event fires on it. A window is +// closed when a "domwindowclosed" notification fires for it. +global.WindowListManager = { + _openListeners: new Set(), + _closeListeners: new Set(), + + // Returns an iterator for all browser windows. Unless |includeIncomplete| is + // true, only fully-loaded windows are returned. + * browserWindows(includeIncomplete = false) { + // The window type parameter is only available once the window's document + // element has been created. This means that, when looking for incomplete + // browser windows, we need to ignore the type entirely for windows which + // haven't finished loading, since we would otherwise skip browser windows + // in their early loading stages. + // This is particularly important given that the "domwindowcreated" event + // fires for browser windows when they're in that in-between state, and just + // before we register our own "domwindowcreated" listener. + + let e = Services.wm.getEnumerator(""); + while (e.hasMoreElements()) { + let window = e.getNext(); + + let ok = includeIncomplete; + if (window.document.readyState == "complete") { + ok = window.document.documentElement.getAttribute("windowtype") == "navigator:browser"; + } + + if (ok) { + yield window; + } + } + }, + + addOpenListener(listener) { + if (this._openListeners.size == 0 && this._closeListeners.size == 0) { + Services.ww.registerNotification(this); + } + this._openListeners.add(listener); + + for (let window of this.browserWindows(true)) { + if (window.document.readyState != "complete") { + window.addEventListener("load", this); + } + } + }, + + removeOpenListener(listener) { + this._openListeners.delete(listener); + if (this._openListeners.size == 0 && this._closeListeners.size == 0) { + Services.ww.unregisterNotification(this); + } + }, + + addCloseListener(listener) { + if (this._openListeners.size == 0 && this._closeListeners.size == 0) { + Services.ww.registerNotification(this); + } + this._closeListeners.add(listener); + }, + + removeCloseListener(listener) { + this._closeListeners.delete(listener); + if (this._openListeners.size == 0 && this._closeListeners.size == 0) { + Services.ww.unregisterNotification(this); + } + }, + + handleEvent(event) { + event.currentTarget.removeEventListener(event.type, this); + let window = event.target.defaultView; + if (window.document.documentElement.getAttribute("windowtype") != "navigator:browser") { + return; + } + + for (let listener of this._openListeners) { + listener(window); + } + }, + + observe(window, topic, data) { + if (topic == "domwindowclosed") { + if (window.document.documentElement.getAttribute("windowtype") != "navigator:browser") { + return; + } + + window.removeEventListener("load", this); + for (let listener of this._closeListeners) { + listener(window); + } + } else { + window.addEventListener("load", this); + } + }, +}; + +// Provides a facility to listen for DOM events across all XUL windows. +global.AllWindowEvents = { + _listeners: new Map(), + + // If |type| is a normal event type, invoke |listener| each time + // that event fires in any open window. If |type| is "progress", add + // a web progress listener that covers all open windows. + addListener(type, listener) { + if (type == "domwindowopened") { + return WindowListManager.addOpenListener(listener); + } else if (type == "domwindowclosed") { + return WindowListManager.addCloseListener(listener); + } + + if (this._listeners.size == 0) { + WindowListManager.addOpenListener(this.openListener); + } + + if (!this._listeners.has(type)) { + this._listeners.set(type, new Set()); + } + let list = this._listeners.get(type); + list.add(listener); + + // Register listener on all existing windows. + for (let window of WindowListManager.browserWindows()) { + this.addWindowListener(window, type, listener); + } + }, + + removeListener(eventType, listener) { + if (eventType == "domwindowopened") { + return WindowListManager.removeOpenListener(listener); + } else if (eventType == "domwindowclosed") { + return WindowListManager.removeCloseListener(listener); + } + + let listeners = this._listeners.get(eventType); + listeners.delete(listener); + if (listeners.size == 0) { + this._listeners.delete(eventType); + if (this._listeners.size == 0) { + WindowListManager.removeOpenListener(this.openListener); + } + } + + // Unregister listener from all existing windows. + let useCapture = eventType === "focus" || eventType === "blur"; + for (let window of WindowListManager.browserWindows()) { + if (eventType == "progress") { + window.gBrowser.removeTabsProgressListener(listener); + } else { + window.removeEventListener(eventType, listener, useCapture); + } + } + }, + + /* eslint-disable mozilla/balanced-listeners */ + addWindowListener(window, eventType, listener) { + let useCapture = eventType === "focus" || eventType === "blur"; + + if (eventType == "progress") { + window.gBrowser.addTabsProgressListener(listener); + } else { + window.addEventListener(eventType, listener, useCapture); + } + }, + /* eslint-enable mozilla/balanced-listeners */ + + // Runs whenever the "load" event fires for a new window. + openListener(window) { + for (let [eventType, listeners] of AllWindowEvents._listeners) { + for (let listener of listeners) { + this.addWindowListener(window, eventType, listener); + } + } + }, +}; + +AllWindowEvents.openListener = AllWindowEvents.openListener.bind(AllWindowEvents); + +// Subclass of EventManager where we just need to call +// add/removeEventListener on each XUL window. +global.WindowEventManager = function(context, name, event, listener) { + EventManager.call(this, context, name, fire => { + let listener2 = (...args) => listener(fire, ...args); + AllWindowEvents.addListener(event, listener2); + return () => { + AllWindowEvents.removeListener(event, listener2); + }; + }); +}; + +WindowEventManager.prototype = Object.create(EventManager.prototype); diff --git a/application/basilisk/components/webextensions/ext-windows.js b/application/basilisk/components/webextensions/ext-windows.js new file mode 100644 index 000000000..5956ae15b --- /dev/null +++ b/application/basilisk/components/webextensions/ext-windows.js @@ -0,0 +1,231 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +XPCOMUtils.defineLazyServiceGetter(this, "aboutNewTabService", + "@mozilla.org/browser/aboutnewtab-service;1", + "nsIAboutNewTabService"); +XPCOMUtils.defineLazyModuleGetter(this, "AppConstants", + "resource://gre/modules/AppConstants.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm"); + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +var { + EventManager, + promiseObserved, +} = ExtensionUtils; + +function onXULFrameLoaderCreated({target}) { + target.messageManager.sendAsyncMessage("AllowScriptsToClose", {}); +} + +extensions.registerSchemaAPI("windows", "addon_parent", context => { + let {extension} = context; + return { + windows: { + onCreated: + new WindowEventManager(context, "windows.onCreated", "domwindowopened", (fire, window) => { + fire(WindowManager.convert(extension, window)); + }).api(), + + onRemoved: + new WindowEventManager(context, "windows.onRemoved", "domwindowclosed", (fire, window) => { + fire(WindowManager.getId(window)); + }).api(), + + onFocusChanged: new EventManager(context, "windows.onFocusChanged", fire => { + // Keep track of the last windowId used to fire an onFocusChanged event + let lastOnFocusChangedWindowId; + + let listener = event => { + // Wait a tick to avoid firing a superfluous WINDOW_ID_NONE + // event when switching focus between two Firefox windows. + Promise.resolve().then(() => { + let window = Services.focus.activeWindow; + let windowId = window ? WindowManager.getId(window) : WindowManager.WINDOW_ID_NONE; + if (windowId !== lastOnFocusChangedWindowId) { + fire(windowId); + lastOnFocusChangedWindowId = windowId; + } + }); + }; + AllWindowEvents.addListener("focus", listener); + AllWindowEvents.addListener("blur", listener); + return () => { + AllWindowEvents.removeListener("focus", listener); + AllWindowEvents.removeListener("blur", listener); + }; + }).api(), + + get: function(windowId, getInfo) { + let window = WindowManager.getWindow(windowId, context); + return Promise.resolve(WindowManager.convert(extension, window, getInfo)); + }, + + getCurrent: function(getInfo) { + let window = currentWindow(context); + return Promise.resolve(WindowManager.convert(extension, window, getInfo)); + }, + + getLastFocused: function(getInfo) { + let window = WindowManager.topWindow; + return Promise.resolve(WindowManager.convert(extension, window, getInfo)); + }, + + getAll: function(getInfo) { + let windows = Array.from(WindowListManager.browserWindows(), + window => WindowManager.convert(extension, window, getInfo)); + return Promise.resolve(windows); + }, + + create: function(createData) { + let needResize = (createData.left !== null || createData.top !== null || + createData.width !== null || createData.height !== null); + + if (needResize) { + if (createData.state !== null && createData.state != "normal") { + return Promise.reject({message: `"state": "${createData.state}" may not be combined with "left", "top", "width", or "height"`}); + } + createData.state = "normal"; + } + + function mkstr(s) { + let result = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString); + result.data = s; + return result; + } + + let args = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray); + + if (createData.tabId !== null) { + if (createData.url !== null) { + return Promise.reject({message: "`tabId` may not be used in conjunction with `url`"}); + } + + if (createData.allowScriptsToClose) { + return Promise.reject({message: "`tabId` may not be used in conjunction with `allowScriptsToClose`"}); + } + + let tab = TabManager.getTab(createData.tabId, context); + + // Private browsing tabs can only be moved to private browsing + // windows. + let incognito = PrivateBrowsingUtils.isBrowserPrivate(tab.linkedBrowser); + if (createData.incognito !== null && createData.incognito != incognito) { + return Promise.reject({message: "`incognito` property must match the incognito state of tab"}); + } + createData.incognito = incognito; + + args.appendElement(tab, /* weak = */ false); + } else if (createData.url !== null) { + if (Array.isArray(createData.url)) { + let array = Cc["@mozilla.org/array;1"].createInstance(Ci.nsIMutableArray); + for (let url of createData.url) { + array.appendElement(mkstr(url), /* weak = */ false); + } + args.appendElement(array, /* weak = */ false); + } else { + args.appendElement(mkstr(createData.url), /* weak = */ false); + } + } else { + args.appendElement(mkstr(aboutNewTabService.newTabURL), /* weak = */ false); + } + + let features = ["chrome"]; + + if (createData.type === null || createData.type == "normal") { + features.push("dialog=no", "all"); + } else { + // All other types create "popup"-type windows by default. + features.push("dialog", "resizable", "minimizable", "centerscreen", "titlebar", "close"); + } + + if (createData.incognito !== null) { + if (createData.incognito) { + features.push("private"); + } else { + features.push("non-private"); + } + } + + let {allowScriptsToClose, url} = createData; + if (allowScriptsToClose === null) { + allowScriptsToClose = typeof url === "string" && url.startsWith("moz-extension://"); + } + + let window = Services.ww.openWindow(null, "chrome://browser/content/browser.xul", "_blank", + features.join(","), args); + + WindowManager.updateGeometry(window, createData); + + // TODO: focused, type + + return new Promise(resolve => { + window.addEventListener("load", function listener() { + window.removeEventListener("load", listener); + if (["maximized", "normal"].includes(createData.state)) { + window.document.documentElement.setAttribute("sizemode", createData.state); + } + resolve(promiseObserved("browser-delayed-startup-finished", win => win == window)); + }); + }).then(() => { + // Some states only work after delayed-startup-finished + if (["minimized", "fullscreen", "docked"].includes(createData.state)) { + WindowManager.setState(window, createData.state); + } + if (allowScriptsToClose) { + for (let {linkedBrowser} of window.gBrowser.tabs) { + onXULFrameLoaderCreated({target: linkedBrowser}); + linkedBrowser.addEventListener( // eslint-disable-line mozilla/balanced-listeners + "XULFrameLoaderCreated", onXULFrameLoaderCreated); + } + } + return WindowManager.convert(extension, window, {populate: true}); + }); + }, + + update: function(windowId, updateInfo) { + if (updateInfo.state !== null && updateInfo.state != "normal") { + if (updateInfo.left !== null || updateInfo.top !== null || + updateInfo.width !== null || updateInfo.height !== null) { + return Promise.reject({message: `"state": "${updateInfo.state}" may not be combined with "left", "top", "width", or "height"`}); + } + } + + let window = WindowManager.getWindow(windowId, context); + if (updateInfo.focused) { + Services.focus.activeWindow = window; + } + + if (updateInfo.state !== null) { + WindowManager.setState(window, updateInfo.state); + } + + if (updateInfo.drawAttention) { + // Bug 1257497 - Firefox can't cancel attention actions. + window.getAttention(); + } + + WindowManager.updateGeometry(window, updateInfo); + + // TODO: All the other properties, focused=false... + + return Promise.resolve(WindowManager.convert(extension, window)); + }, + + remove: function(windowId) { + let window = WindowManager.getWindow(windowId, context); + window.close(); + + return new Promise(resolve => { + let listener = () => { + AllWindowEvents.removeListener("domwindowclosed", listener); + resolve(); + }; + AllWindowEvents.addListener("domwindowclosed", listener); + }); + }, + }, + }; +}); diff --git a/application/basilisk/components/webextensions/extension-mac-panel.css b/application/basilisk/components/webextensions/extension-mac-panel.css new file mode 100644 index 000000000..2e9ed6bdb --- /dev/null +++ b/application/basilisk/components/webextensions/extension-mac-panel.css @@ -0,0 +1,3 @@ +body { + border-radius: 3.5px; +} diff --git a/application/basilisk/components/webextensions/extension-mac.css b/application/basilisk/components/webextensions/extension-mac.css new file mode 100644 index 000000000..49cd3b359 --- /dev/null +++ b/application/basilisk/components/webextensions/extension-mac.css @@ -0,0 +1,11 @@ +button, +select, +input[type="checkbox"] + label::before { + border-radius: 4px; +} + +.panel-section-footer { + border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; + overflow: hidden; +} diff --git a/application/basilisk/components/webextensions/extension-win-panel.css b/application/basilisk/components/webextensions/extension-win-panel.css new file mode 100644 index 000000000..9da6da14c --- /dev/null +++ b/application/basilisk/components/webextensions/extension-win-panel.css @@ -0,0 +1,5 @@ +@media (-moz-os-version: windows-win7) { + body { + border-radius: 4px; + } +} diff --git a/application/basilisk/components/webextensions/extension.css b/application/basilisk/components/webextensions/extension.css new file mode 100644 index 000000000..6b59033e3 --- /dev/null +++ b/application/basilisk/components/webextensions/extension.css @@ -0,0 +1,572 @@ +/* stylelint-disable property-no-vendor-prefix */ +/* stylelint-disable property-no-vendor-prefix */ +/* Base */ +button, +select, +option, +input { + -moz-appearance: none; +} + +/* Variables */ +html, +body { + background: transparent; + box-sizing: border-box; + color: #222426; + cursor: default; + display: flex; + flex-direction: column; + font: caption; + margin: 0; + padding: 0; + -moz-user-select: none; +} + +body * { + box-sizing: border-box; + text-align: start; +} + +/* stylelint-disable property-no-vendor-prefix */ +/* Buttons */ +button, +select { + background-color: #fbfbfb; + border: 1px solid #b1b1b1; + box-shadow: 0 0 0 0 transparent; + font: caption; + height: 24px; + outline: 0 !important; + padding: 0 8px 0; + transition-duration: 250ms; + transition-property: box-shadow, border; +} + +select { + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDE2IDE2Ij4KICA8cGF0aCBkPSJNOCwxMkwzLDcsNCw2bDQsNCw0LTQsMSwxWiIgZmlsbD0iIzZBNkE2QSIgLz4KPC9zdmc+Cg==); + background-position: calc(100% - 4px) center; + background-repeat: no-repeat; + padding-inline-end: 24px; + text-overflow: ellipsis; +} + +label { + font: caption; +} + +button::-moz-focus-inner { + border: 0; + outline: 0; +} + +/* Dropdowns */ +select { + background-color: #fbfbfb; + border: 1px solid #b1b1b1; + box-shadow: 0 0 0 0 transparent; + font: caption; + height: 24px; + outline: 0 !important; + padding: 0 8px 0; + transition-duration: 250ms; + transition-property: box-shadow, border; +} + +select { + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDE2IDE2Ij4KICA8cGF0aCBkPSJNOCwxMkwzLDcsNCw2bDQsNCw0LTQsMSwxWiIgZmlsbD0iIzZBNkE2QSIgLz4KPC9zdmc+Cg==); + background-position: calc(100% - 4px) center; + background-repeat: no-repeat; + padding-inline-end: 24px; + text-overflow: ellipsis; +} + +select:-moz-focusring { + color: transparent; + text-shadow: 0 0 0 #000; +} + +select:-moz-focusring * { + color: #000; + text-shadow: none; +} + +button.hover, +select.hover { + background-color: #ebebeb; + border: 1px solid #b1b1b1; +} + +button.pressed, +select.pressed { + background-color: #d4d4d4; + border: 1px solid #858585; +} + +button.disabled, +select.disabled { + color: #999; + opacity: .5; +} + +button.focused, +select.focused { + border-color: #fff; + box-shadow: 0 0 0 2px rgba(97, 181, 255, 0.75); +} + +button.default { + background-color: #0996f8; + border-color: #0670cc; + color: #fff; +} + +button.default.hover { + background-color: #0670cc; + border-color: #005bab; +} + +button.default.pressed { + background-color: #005bab; + border-color: #004480; +} + +button.default.focused { + border-color: #fff; +} + +/* Radio Buttons */ +.radioItem { + margin-bottom: 6px; + text-align: left; +} + +input[type="radio"] { + display: none; +} + +input[type="radio"] + label { + -moz-user-select: none; +} + +input[type="radio"] + label::before { + background-color: #fff; + background-position: center; + border: 1px solid #b1b1b1; + border-radius: 50%; + content: ""; + display: inline-block; + height: 16px; + margin-right: 6px; + vertical-align: text-top; + width: 16px; +} + +input[type="radio"]:hover + label::before, +.radioItem.hover input[type="radio"]:not(active) + label::before { + background-color: #fbfbfb; + border-color: #b1b1b1; +} + +input[type="radio"]:hover:active + label::before, +.radioItem.pressed input[type="radio"]:not(active) + label::before { + background-color: #ebebeb; + border-color: #858585; +} + +input[type="radio"]:checked + label::before { + background-color: #0996f8; + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDE2IDE2Ij4KICA8Y2lyY2xlIGN4PSI4IiBjeT0iOCIgcj0iNCIgZmlsbD0iI2ZmZiIgLz4KPC9zdmc+Cg==); + border-color: #0670cc; +} + +input[type="radio"]:checked:hover + label::before, +.radioItem.hover input[type="radio"]:checked:not(active) + label::before { + background-color: #0670cc; + border-color: #005bab; +} + +input[type="radio"]:checked:hover:active + label::before, +.radioItem.pressed input[type="radio"]:checked:not(active) + label::before { + background-color: #005bab; + border-color: #004480; +} + +.radioItem.disabled input[type="radio"] + label, +.radioItem.disabled input[type="radio"]:hover + label, +.radioItem.disabled input[type="radio"]:hover:active + label { + color: #999; + opacity: .5; +} + +.radioItem.focused input[type="radio"] + label::before { + border-color: #0996f8; + box-shadow: 0 0 0 2px rgba(97, 181, 255, 0.75); +} + +.radioItem.focused input[type="radio"]:checked + label::before { + border-color: #fff; +} + +/* Checkboxes */ +.checkboxItem { + margin-bottom: 6px; + text-align: left; +} + +input[type="checkbox"] { + display: none; +} + +input[type="checkbox"] + label { + -moz-user-select: none; +} + +input[type="checkbox"] + label::before { + background-color: #fff; + background-position: center; + border: 1px solid #b1b1b1; + content: ""; + display: inline-block; + height: 16px; + margin-right: 6px; + vertical-align: text-top; + width: 16px; +} + +input[type="checkbox"]:hover + label::before, +.checkboxItem.hover input[type="checkbox"]:not(active) + label::before { + background-color: #fbfbfb; + border-color: #b1b1b1; +} + +input[type="checkbox"]:hover:active + label::before, +.checkboxItem.pressed input[type="checkbox"]:not(active) + label::before { + background-color: #ebebeb; + border-color: #858585; +} + +input[type="checkbox"]:checked + label::before { + background-color: #0996f8; + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDE2IDE2Ij4KICA8cGF0aCBkPSJNNy43LDEyLjkgQzcuNCwxMy4zIDYuOCwxMy40IDYuNCwxMyBMMy4yLDkuOCBDMi44LDkuNCAyLjgsOC42IDMuMiw4LjIgQzMuNiw3LjggNC40LDcuOCA0LjgsOC4yIEw2LjksMTAuMyBMMTEuMSw0LjQgQzExLjUsMy45IDEyLjIsMy44IDEyLjcsNC4xIEMxMy4yLDQuNSAxMy4zLDUuMiAxMyw1LjcgTDcuNywxMi45IEw3LjcsMTIuOSBaIiBmaWxsPSIjZmZmIiAvPgo8L3N2Zz4K); + border-color: #0670cc; +} + +input[type="checkbox"]:checked:hover + label::before, +.checkboxItem.hover input[type="checkbox"]:checked:not(active) + label::before { + background-color: #0670cc; + border-color: #005bab; +} + +input[type="checkbox"]:checked:hover:active + label::before, +.checkboxItem.pressed input[type="checkbox"]:checked:not(active) + label::before { + background-color: #005bab; + border-color: #004480; +} + +.checkboxItem.disabled input[type="checkbox"] + label, +.checkboxItem.disabled input[type="checkbox"]:hover + label, +.checkboxItem.disabled input[type="checkbox"]:hover:active + label { + color: #999; + opacity: .5; +} + +.checkboxItem.focused input[type="checkbox"] + label::before { + border-color: #0996f8; + box-shadow: 0 0 0 2px rgba(97, 181, 255, 0.75); +} + +.checkboxItem.focused input[type="checkbox"]:checked + label::before { + border-color: #fff; +} + +/* Expander Button */ +button.expander { + background-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDE2IDE2Ij4KICA8cGF0aCBkPSJNOCwxMkwzLDcsNCw2bDQsNCw0LTQsMSwxWiIgZmlsbD0iIzZBNkE2QSIgLz4KPC9zdmc+Cg==); + background-position: center; + background-repeat: no-repeat; + height: 24px; + padding: 0; + width: 24px; +} + +/* Interactive States */ +button:hover:not(.pressed):not(.disabled):not(.focused), +select:hover:not(.pressed):not(.disabled):not(.focused) { + background-color: #ebebeb; + border: 1px solid #b1b1b1; +} + +button:hover:active:not(.hover):not(.disabled):not(.focused), +select:hover:active:not(.hover):not(.disabled):not(.focused) { + background-color: #d4d4d4; + border: 1px solid #858585; +} + +button.default:hover:not(.pressed):not(.disabled):not(.focused) { + background-color: #0670cc; + border-color: #005bab; +} + +button.default:hover:active:not(.hover):not(.disabled):not(.focused) { + background-color: #005bab; + border-color: #004480; +} + +button:focus:not(.disabled) { + border-color: #fff !important; + box-shadow: 0 0 0 2px rgba(97, 181, 255, 0.75); +} + +/* Fields */ +input[type="text"], +textarea { + background-color: #fff; + border: 1px solid #b1b1b1; + box-shadow: 0 0 0 0 rgba(97, 181, 255, 0); + font: caption; + padding: 0 6px 0; + transition-duration: 250ms; + transition-property: box-shadow; +} + +input[type="text"] { + height: 24px; +} + +input[type="text"].hover, +textarea.hover { + border: 1px solid #858585; +} + +input[type="text"].disabled, +textarea.disabled { + color: #999; + opacity: .5; +} + +input[type="text"].focused, +textarea.focused { + border-color: #0996f8; + box-shadow: 0 0 0 2px rgba(97, 181, 255, 0.75); +} + +/* Interactive States */ +input[type="text"]:not(disabled):hover, +textarea:not(disabled):hover { + border: 1px solid #858585; +} + +input[type="text"]:focus, +input[type="text"]:focus:hover, +textarea:focus, +textarea:focus:hover { + border-color: #0996f8; + box-shadow: 0 0 0 2px rgba(97, 181, 255, 0.75); +} + +/* stylelint-disable property-no-vendor-prefix */ +.panel-section { + display: flex; + flex-direction: row; +} + +.panel-section-separator { + background-color: rgba(0, 0, 0, 0.15); + min-height: 1px; +} + +/* Panel Section - Header */ +.panel-section-header { + border-bottom: 1px solid rgba(0, 0, 0, 0.15); + padding: 16px; +} + +.panel-section-header > .icon-section-header { + background-position: center center; + background-repeat: no-repeat; + height: 32px; + margin-right: 16px; + position: relative; + width: 32px; +} + +.panel-section-header > .text-section-header { + align-self: center; + font-size: 1.385em; + font-weight: lighter; +} + +/* Panel Section - List */ +.panel-section-list { + flex-direction: column; + padding: 4px 0; +} + +.panel-list-item { + align-items: center; + display: flex; + flex-direction: row; + height: 24px; + padding: 0 16px; +} + +.panel-list-item:not(.disabled):hover { + background-color: rgba(0, 0, 0, 0.06); + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + border-top: 1px solid rgba(0, 0, 0, 0.1); +} + +.panel-list-item:not(.disabled):hover:active { + background-color: rgba(0, 0, 0, 0.1); +} + +.panel-list-item.disabled { + color: #999; +} + +.panel-list-item > .icon { + flex-grow: 0; + flex-shrink: 0; +} + +.panel-list-item > .text { + flex-grow: 10; +} + +.panel-list-item > .text-shortcut { + color: #808080; + font-family: "Lucida Grande", caption; + font-size: .847em; + justify-content: flex-end; +} + +.panel-section-list .panel-section-separator { + margin: 4px 0; +} + +/* Panel Section - Form Elements */ +.panel-section-formElements { + display: flex; + flex-direction: column; + padding: 16px; +} + +.panel-formElements-item { + align-items: center; + display: flex; + flex-direction: row; + margin-bottom: 12px; +} + +.panel-formElements-item:last-child { + margin-bottom: 0; +} + +.panel-formElements-item label { + flex-shrink: 0; + margin-right: 6px; + text-align: right; +} + +.panel-formElements-item input[type="text"], +.panel-formElements-item select { + flex-grow: 1; +} + +/* Panel Section - Footer */ +.panel-section-footer { + background-color: rgba(0, 0, 0, 0.06); + border-top: 1px solid rgba(0, 0, 0, 0.15); + color: #1a1a1a; + display: flex; + flex-direction: row; + height: 41px; + margin-top: -1px; + padding: 0; +} + +.panel-section-footer-button { + flex: 1 1 auto; + height: 100%; + margin: 0 -1px; + padding: 12px; + text-align: center; +} + +.panel-section-footer-button > .text-shortcut { + color: #808080; + font-family: "Lucida Grande", caption; + font-size: .847em; +} + +.panel-section-footer-button:hover { + background-color: rgba(0, 0, 0, 0.06); +} + +.panel-section-footer-button:hover:active { + background-color: rgba(0, 0, 0, 0.1); +} + +.panel-section-footer-button.default { + background-color: #0996f8; + box-shadow: 0 1px 0 #0670cc inset; + color: #fff; +} + +.panel-section-footer-button.default:hover { + background-color: #0670cc; + box-shadow: 0 1px 0 #005bab inset; +} + +.panel-section-footer-button.default:hover:active { + background-color: #005bab; + box-shadow: 0 1px 0 #004480 inset; +} + +.panel-section-footer-separator { + background-color: rgba(0, 0, 0, 0.1); + width: 1px; + z-index: 99; +} + +/* Panel Section - Tabs */ +.panel-section-tabs { + color: #1a1a1a; + display: flex; + flex-direction: row; + height: 41px; + margin-bottom: -1px; + padding: 0; +} + +.panel-section-tabs-button { + flex: 1 1 auto; + height: 100%; + margin: 0 -1px; + padding: 12px; + text-align: center; +} + +.panel-section-tabs-button:hover { + background-color: rgba(0, 0, 0, 0.06); +} + +.panel-section-tabs-button:hover:active { + background-color: rgba(0, 0, 0, 0.1); +} + +.panel-section-tabs-button.selected { + box-shadow: 0 -1px 0 #0670cc inset, 0 -4px 0 #0996f8 inset; + color: #0996f8; +} + +.panel-section-tabs-button.selected:hover { + color: #0670cc; +} + +.panel-section-tabs-separator { + background-color: rgba(0, 0, 0, 0.1); + width: 1px; + z-index: 99; +} diff --git a/application/basilisk/components/webextensions/extension.svg b/application/basilisk/components/webextensions/extension.svg new file mode 100644 index 000000000..a16455253 --- /dev/null +++ b/application/basilisk/components/webextensions/extension.svg @@ -0,0 +1,19 @@ + + + + + + + + + + + + diff --git a/application/basilisk/components/webextensions/extensions-browser.manifest b/application/basilisk/components/webextensions/extensions-browser.manifest new file mode 100644 index 000000000..ed5cca813 --- /dev/null +++ b/application/basilisk/components/webextensions/extensions-browser.manifest @@ -0,0 +1,31 @@ +# scripts +category webextension-scripts bookmarks chrome://browser/content/ext-bookmarks.js +category webextension-scripts browserAction chrome://browser/content/ext-browserAction.js +category webextension-scripts commands chrome://browser/content/ext-commands.js +category webextension-scripts contextMenus chrome://browser/content/ext-contextMenus.js +category webextension-scripts desktop-runtime chrome://browser/content/ext-desktop-runtime.js +category webextension-scripts history chrome://browser/content/ext-history.js +category webextension-scripts omnibox chrome://browser/content/ext-omnibox.js +category webextension-scripts pageAction chrome://browser/content/ext-pageAction.js +category webextension-scripts sessions chrome://browser/content/ext-sessions.js +category webextension-scripts tabs chrome://browser/content/ext-tabs.js +category webextension-scripts utils chrome://browser/content/ext-utils.js +category webextension-scripts windows chrome://browser/content/ext-windows.js + +# scripts that must run in the same process as addon code. +category webextension-scripts-addon contextMenus chrome://browser/content/ext-c-contextMenus.js +category webextension-scripts-addon omnibox chrome://browser/content/ext-c-omnibox.js +category webextension-scripts-addon tabs chrome://browser/content/ext-c-tabs.js + +# schemas +category webextension-schemas bookmarks chrome://browser/content/schemas/bookmarks.json +category webextension-schemas browser_action chrome://browser/content/schemas/browser_action.json +category webextension-schemas commands chrome://browser/content/schemas/commands.json +category webextension-schemas context_menus chrome://browser/content/schemas/context_menus.json +category webextension-schemas context_menus_internal chrome://browser/content/schemas/context_menus_internal.json +category webextension-schemas history chrome://browser/content/schemas/history.json +category webextension-schemas omnibox chrome://browser/content/schemas/omnibox.json +category webextension-schemas page_action chrome://browser/content/schemas/page_action.json +category webextension-schemas sessions chrome://browser/content/schemas/sessions.json +category webextension-schemas tabs chrome://browser/content/schemas/tabs.json +category webextension-schemas windows chrome://browser/content/schemas/windows.json diff --git a/application/basilisk/components/webextensions/jar.mn b/application/basilisk/components/webextensions/jar.mn new file mode 100644 index 000000000..a7b506ec4 --- /dev/null +++ b/application/basilisk/components/webextensions/jar.mn @@ -0,0 +1,29 @@ +# 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/. + +browser.jar: + content/browser/extension.css +#ifdef XP_MACOSX + content/browser/extension-mac.css + content/browser/extension-mac-panel.css +#endif +#ifdef XP_WIN + content/browser/extension-win-panel.css +#endif + content/browser/extension.svg + content/browser/ext-bookmarks.js + content/browser/ext-browserAction.js + content/browser/ext-commands.js + content/browser/ext-contextMenus.js + content/browser/ext-desktop-runtime.js + content/browser/ext-history.js + content/browser/ext-omnibox.js + content/browser/ext-pageAction.js + content/browser/ext-sessions.js + content/browser/ext-tabs.js + content/browser/ext-utils.js + content/browser/ext-windows.js + content/browser/ext-c-contextMenus.js + content/browser/ext-c-omnibox.js + content/browser/ext-c-tabs.js diff --git a/application/basilisk/components/webextensions/moz.build b/application/basilisk/components/webextensions/moz.build new file mode 100644 index 000000000..116e90415 --- /dev/null +++ b/application/basilisk/components/webextensions/moz.build @@ -0,0 +1,14 @@ +# -*- 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/. + +JAR_MANIFESTS += ['jar.mn'] + +EXTRA_COMPONENTS += [ + 'extensions-browser.manifest', +] + +DIRS += ['schemas'] + diff --git a/application/basilisk/components/webextensions/schemas/LICENSE b/application/basilisk/components/webextensions/schemas/LICENSE new file mode 100644 index 000000000..9314092fd --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/LICENSE @@ -0,0 +1,27 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// 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 +// OWNER 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. diff --git a/application/basilisk/components/webextensions/schemas/bookmarks.json b/application/basilisk/components/webextensions/schemas/bookmarks.json new file mode 100644 index 000000000..fb74c633e --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/bookmarks.json @@ -0,0 +1,568 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "bookmarks" + ] + }] + } + ] + }, + { + "namespace": "bookmarks", + "description": "Use the browser.bookmarks API to create, organize, and otherwise manipulate bookmarks. Also see $(topic:override)[Override Pages], which you can use to create a custom Bookmark Manager page.", + "permissions": ["bookmarks"], + "types": [ + { + "id": "BookmarkTreeNodeUnmodifiable", + "type": "string", + "enum": ["managed"], + "description": "Indicates the reason why this node is unmodifiable. The managed value indicates that this node was configured by the system administrator or by the custodian of a supervised user. Omitted if the node can be modified by the user and the extension (default)." + }, + { + "id": "BookmarkTreeNode", + "type": "object", + "description": "A node (either a bookmark or a folder) in the bookmark tree. Child nodes are ordered within their parent folder.", + "properties": { + "id": { + "type": "string", + "description": "The unique identifier for the node. IDs are unique within the current profile, and they remain valid even after the browser is restarted." + }, + "parentId": { + "type": "string", + "optional": true, + "description": "The id of the parent folder. Omitted for the root node." + }, + "index": { + "type": "integer", + "optional": true, + "description": "The 0-based position of this node within its parent folder." + }, + "url": { + "type": "string", + "optional": true, + "description": "The URL navigated to when a user clicks the bookmark. Omitted for folders." + }, + "title": { + "type": "string", + "description": "The text displayed for the node." + }, + "dateAdded": { + "type": "number", + "optional": true, + "description": "When this node was created, in milliseconds since the epoch (new Date(dateAdded))." + }, + "dateGroupModified": { + "type": "number", + "optional": true, + "description": "When the contents of this folder last changed, in milliseconds since the epoch." + }, + "unmodifiable": { + "$ref": "BookmarkTreeNodeUnmodifiable", + "optional": true, + "description": "Indicates the reason why this node is unmodifiable. The managed value indicates that this node was configured by the system administrator or by the custodian of a supervised user. Omitted if the node can be modified by the user and the extension (default)." + }, + "children": { + "type": "array", + "optional": true, + "items": { "$ref": "BookmarkTreeNode" }, + "description": "An ordered list of children of this node." + } + } + }, + { + "id": "CreateDetails", + "description": "Object passed to the create() function.", + "type": "object", + "properties": { + "parentId": { + "type": "string", + "optional": true, + "description": "Defaults to the Other Bookmarks folder." + }, + "index": { + "type": "integer", + "minimum": 0, + "optional": true + }, + "title": { + "type": "string", + "optional": true + }, + "url": { + "type": "string", + "optional": true + } + } + } + ], + "functions": [ + { + "name": "get", + "type": "function", + "description": "Retrieves the specified BookmarkTreeNode(s).", + "async": "callback", + "parameters": [ + { + "name": "idOrIdList", + "description": "A single string-valued id, or an array of string-valued ids", + "choices": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1 + } + ] + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "results", + "type": "array", + "items": { "$ref": "BookmarkTreeNode" } + } + ] + } + ] + }, + { + "name": "getChildren", + "type": "function", + "description": "Retrieves the children of the specified BookmarkTreeNode id.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "id" + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "results", + "type": "array", + "items": { "$ref": "BookmarkTreeNode"} + } + ] + } + ] + }, + { + "name": "getRecent", + "type": "function", + "description": "Retrieves the recently added bookmarks.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "minimum": 1, + "name": "numberOfItems", + "description": "The maximum number of items to return." + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "results", + "type": "array", + "items": { "$ref": "BookmarkTreeNode" } + } + ] + } + ] + }, + { + "name": "getTree", + "type": "function", + "description": "Retrieves the entire Bookmarks hierarchy.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "results", + "type": "array", + "items": { "$ref": "BookmarkTreeNode" } + } + ] + } + ] + }, + { + "name": "getSubTree", + "type": "function", + "description": "Retrieves part of the Bookmarks hierarchy, starting at the specified node.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "id", + "description": "The ID of the root of the subtree to retrieve." + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "results", + "type": "array", + "items": { "$ref": "BookmarkTreeNode" } + } + ] + } + ] + }, + { + "name": "search", + "type": "function", + "description": "Searches for BookmarkTreeNodes matching the given query. Queries specified with an object produce BookmarkTreeNodes matching all specified properties.", + "async": "callback", + "parameters": [ + { + "name": "query", + "description": "Either a string of words and quoted phrases that are matched against bookmark URLs and titles, or an object. If an object, the properties query, url, and title may be specified and bookmarks matching all specified properties will be produced.", + "choices": [ + { + "type": "string", + "description": "A string of words and quoted phrases that are matched against bookmark URLs and titles." + }, + { + "type": "object", + "description": "An object specifying properties and values to match when searching. Produces bookmarks matching all properties.", + "properties": { + "query": { + "type": "string", + "optional": true, + "description": "A string of words and quoted phrases that are matched against bookmark URLs and titles." + }, + "url": { + "type": "string", + "format": "url", + "optional": true, + "description": "The URL of the bookmark; matches verbatim. Note that folders have no URL." + }, + "title": { + "type": "string", + "optional": true, + "description": "The title of the bookmark; matches verbatim." + } + } + } + ] + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "results", + "type": "array", + "items": { "$ref": "BookmarkTreeNode" } + } + ] + } + ] + }, + { + "name": "create", + "type": "function", + "description": "Creates a bookmark or folder under the specified parentId. If url is NULL or missing, it will be a folder.", + "async": "callback", + "parameters": [ + { + "$ref": "CreateDetails", + "name": "bookmark" + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "result", + "$ref": "BookmarkTreeNode" + } + ] + } + ] + }, + { + "name": "move", + "type": "function", + "description": "Moves the specified BookmarkTreeNode to the provided location.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "id" + }, + { + "type": "object", + "name": "destination", + "properties": { + "parentId": { + "type": "string", + "optional": true + }, + "index": { + "type": "integer", + "minimum": 0, + "optional": true + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "result", + "$ref": "BookmarkTreeNode" + } + ] + } + ] + }, + { + "name": "update", + "type": "function", + "description": "Updates the properties of a bookmark or folder. Specify only the properties that you want to change; unspecified properties will be left unchanged. Note: Currently, only 'title' and 'url' are supported.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "id" + }, + { + "type": "object", + "name": "changes", + "properties": { + "title": { + "type": "string", + "optional": true + }, + "url": { + "type": "string", + "optional": true + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "result", + "$ref": "BookmarkTreeNode" + } + ] + } + ] + }, + { + "name": "remove", + "type": "function", + "description": "Removes a bookmark or an empty bookmark folder.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "id" + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "removeTree", + "type": "function", + "description": "Recursively removes a bookmark folder.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "id" + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "import", + "unsupported": true, + "type": "function", + "description": "Imports bookmarks from an html bookmark file", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "export", + "unsupported": true, + "type": "function", + "description": "Exports bookmarks to an html bookmark file", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + } + ], + "events": [ + { + "name": "onCreated", + "type": "function", + "description": "Fired when a bookmark or folder is created.", + "parameters": [ + { + "type": "string", + "name": "id" + }, + { + "$ref": "BookmarkTreeNode", + "name": "bookmark" + } + ] + }, + { + "name": "onRemoved", + "type": "function", + "description": "Fired when a bookmark or folder is removed. When a folder is removed recursively, a single notification is fired for the folder, and none for its contents.", + "parameters": [ + { + "type": "string", + "name": "id" + }, + { + "type": "object", + "name": "removeInfo", + "properties": { + "parentId": { "type": "string" }, + "index": { "type": "integer" }, + "node": { "$ref": "BookmarkTreeNode" } + } + } + ] + }, + { + "name": "onChanged", + "type": "function", + "description": "Fired when a bookmark or folder changes. Note: Currently, only title and url changes trigger this.", + "parameters": [ + { + "type": "string", + "name": "id" + }, + { + "type": "object", + "name": "changeInfo", + "properties": { + "title": { "type": "string" }, + "url": { + "type": "string", + "optional": true + } + } + } + ] + }, + { + "name": "onMoved", + "type": "function", + "description": "Fired when a bookmark or folder is moved to a different parent folder.", + "parameters": [ + { + "type": "string", + "name": "id" + }, + { + "type": "object", + "name": "moveInfo", + "properties": { + "parentId": { "type": "string" }, + "index": { "type": "integer" }, + "oldParentId": { "type": "string" }, + "oldIndex": { "type": "integer" } + } + } + ] + }, + { + "name": "onChildrenReordered", + "unsupported": true, + "type": "function", + "description": "Fired when the children of a folder have changed their order due to the order being sorted in the UI. This is not called as a result of a move().", + "parameters": [ + { + "type": "string", + "name": "id" + }, + { + "type": "object", + "name": "reorderInfo", + "properties": { + "childIds": { + "type": "array", + "items": { "type": "string" } + } + } + } + ] + }, + { + "name": "onImportBegan", + "unsupported": true, + "type": "function", + "description": "Fired when a bookmark import session is begun. Expensive observers should ignore onCreated updates until onImportEnded is fired. Observers should still handle other notifications immediately.", + "parameters": [] + }, + { + "name": "onImportEnded", + "unsupported": true, + "type": "function", + "description": "Fired when a bookmark import session is ended.", + "parameters": [] + } + ] + } +] diff --git a/application/basilisk/components/webextensions/schemas/browser_action.json b/application/basilisk/components/webextensions/schemas/browser_action.json new file mode 100644 index 000000000..1a7da956a --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/browser_action.json @@ -0,0 +1,430 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "WebExtensionManifest", + "properties": { + "browser_action": { + "type": "object", + "additionalProperties": { "$ref": "UnrecognizedProperty" }, + "properties": { + "default_title": { + "type": "string", + "optional": true, + "preprocess": "localize" + }, + "default_icon": { + "$ref": "IconPath", + "optional": true + }, + "default_popup": { + "type": "string", + "format": "relativeUrl", + "optional": true, + "preprocess": "localize" + }, + "browser_style": { + "type": "boolean", + "optional": true + } + }, + "optional": true + } + } + } + ] + }, + { + "namespace": "browserAction", + "description": "Use browser actions to put icons in the main browser toolbar, to the right of the address bar. In addition to its icon, a browser action can also have a tooltip, a badge, and a popup.", + "permissions": ["manifest:browser_action"], + "types": [ + { + "id": "ColorArray", + "type": "array", + "items": { + "type": "integer", + "minimum": 0, + "maximum": 255 + }, + "minItems": 4, + "maxItems": 4 + }, + { + "id": "ImageDataType", + "type": "object", + "isInstanceOf": "ImageData", + "additionalProperties": { "type": "any" }, + "postprocess": "convertImageDataToURL", + "description": "Pixel data for an image. Must be an ImageData object (for example, from a canvas element)." + } + ], + "functions": [ + { + "name": "setTitle", + "type": "function", + "description": "Sets the title of the browser action. This shows up in the tooltip.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "title": { + "type": "string", + "description": "The string the browser action should display when moused over." + }, + "tabId": { + "type": "integer", + "optional": true, + "description": "Limits the change to when a particular tab is selected. Automatically resets when the tab is closed." + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "getTitle", + "type": "function", + "description": "Gets the title of the browser action.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "tabId": { + "type": "integer", + "optional": true, + "description": "Specify the tab to get the title from. If no tab is specified, the non-tab-specific title is returned." + } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "result", + "type": "string" + } + ] + } + ] + }, + { + "name": "setIcon", + "type": "function", + "description": "Sets the icon for the browser action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element, or as dictionary of either one of those. Either the path or the imageData property must be specified.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "imageData": { + "choices": [ + { "$ref": "ImageDataType" }, + { + "type": "object", + "additionalProperties": {"$ref": "ImageDataType"} + } + ], + "optional": true, + "description": "Either an ImageData object or a dictionary {size -> ImageData} representing icon to be set. If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density. If the number of image pixels that fit into one screen space unit equals scale, then image with size scale * 19 will be selected. Initially only scales 1 and 2 will be supported. At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'19': foo}'" + }, + "path": { + "choices": [ + { "type": "string" }, + { + "type": "object", + "additionalProperties": {"type": "string"} + } + ], + "optional": true, + "description": "Either a relative image path or a dictionary {size -> relative image path} pointing to icon to be set. If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density. If the number of image pixels that fit into one screen space unit equals scale, then image with size scale * 19 will be selected. Initially only scales 1 and 2 will be supported. At least one image must be specified. Note that 'details.path = foo' is equivalent to 'details.imageData = {'19': foo}'" + }, + "tabId": { + "type": "integer", + "optional": true, + "description": "Limits the change to when a particular tab is selected. Automatically resets when the tab is closed." + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "setPopup", + "type": "function", + "description": "Sets the html document to be opened as a popup when the user clicks on the browser action's icon.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "tabId": { + "type": "integer", + "optional": true, + "minimum": 0, + "description": "Limits the change to when a particular tab is selected. Automatically resets when the tab is closed." + }, + "popup": { + "type": "string", + "description": "The html file to show in a popup. If set to the empty string (''), no popup is shown." + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "getPopup", + "type": "function", + "description": "Gets the html document set as the popup for this browser action.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "tabId": { + "type": "integer", + "optional": true, + "description": "Specify the tab to get the popup from. If no tab is specified, the non-tab-specific popup is returned." + } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "result", + "type": "string" + } + ] + } + ] + }, + { + "name": "setBadgeText", + "type": "function", + "description": "Sets the badge text for the browser action. The badge is displayed on top of the icon.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "text": { + "type": "string", + "description": "Any number of characters can be passed, but only about four can fit in the space." + }, + "tabId": { + "type": "integer", + "optional": true, + "description": "Limits the change to when a particular tab is selected. Automatically resets when the tab is closed." + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "getBadgeText", + "type": "function", + "description": "Gets the badge text of the browser action. If no tab is specified, the non-tab-specific badge text is returned.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "tabId": { + "type": "integer", + "optional": true, + "description": "Specify the tab to get the badge text from. If no tab is specified, the non-tab-specific badge text is returned." + } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "result", + "type": "string" + } + ] + } + ] + }, + { + "name": "setBadgeBackgroundColor", + "type": "function", + "description": "Sets the background color for the badge.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "color": { + "description": "An array of four integers in the range [0,255] that make up the RGBA color of the badge. For example, opaque red is [255, 0, 0, 255]. Can also be a string with a CSS value, with opaque red being #FF0000 or #F00.", + "choices": [ + {"type": "string"}, + {"$ref": "ColorArray"} + ] + }, + "tabId": { + "type": "integer", + "optional": true, + "description": "Limits the change to when a particular tab is selected. Automatically resets when the tab is closed." + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "getBadgeBackgroundColor", + "type": "function", + "description": "Gets the background color of the browser action.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "tabId": { + "type": "integer", + "optional": true, + "description": "Specify the tab to get the badge background color from. If no tab is specified, the non-tab-specific badge background color is returned." + } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "result", + "$ref": "ColorArray" + } + ] + } + ] + }, + { + "name": "enable", + "type": "function", + "description": "Enables the browser action for a tab. By default, browser actions are enabled.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "optional": true, + "name": "tabId", + "minimum": 0, + "description": "The id of the tab for which you want to modify the browser action." + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "disable", + "type": "function", + "description": "Disables the browser action for a tab.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "optional": true, + "name": "tabId", + "minimum": 0, + "description": "The id of the tab for which you want to modify the browser action." + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "openPopup", + "type": "function", + "description": "Opens the extension popup window in the active window but does not grant tab permissions.", + "unsupported": true, + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "popupView", + "type": "object", + "optional": true, + "description": "JavaScript 'window' object for the popup window if it was succesfully opened.", + "additionalProperties": { "type": "any" } + } + ] + } + ] + } + ], + "events": [ + { + "name": "onClicked", + "type": "function", + "description": "Fired when a browser action icon is clicked. This event will not fire if the browser action has a popup.", + "parameters": [ + { + "name": "tab", + "$ref": "tabs.Tab" + } + ] + } + ] + } +] diff --git a/application/basilisk/components/webextensions/schemas/commands.json b/application/basilisk/components/webextensions/schemas/commands.json new file mode 100644 index 000000000..a1632088e --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/commands.json @@ -0,0 +1,148 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "id": "KeyName", + "choices": [ + { + "type": "string", + "pattern": "^\\s*(Alt|Ctrl|Command|MacCtrl)\\s*\\+\\s*(Shift\\s*\\+\\s*)?([A-Z0-9]|Comma|Period|Home|End|PageUp|PageDown|Space|Insert|Delete|Up|Down|Left|Right)\\s*$" + }, + { + "type": "string", + "pattern": "^(MediaNextTrack|MediaPlayPause|MediaPrevTrack|MediaStop)$" + } + ] + }, + { + "$extend": "WebExtensionManifest", + "properties": { + "commands": { + "type": "object", + "optional": true, + "additionalProperties": { + "type": "object", + "additionalProperties": { "$ref": "UnrecognizedProperty" }, + "properties": { + "suggested_key": { + "type": "object", + "optional": true, + "properties": { + "default": { + "$ref": "KeyName", + "optional": true + }, + "mac": { + "$ref": "KeyName", + "optional": true + }, + "linux": { + "$ref": "KeyName", + "optional": true + }, + "windows": { + "$ref": "KeyName", + "optional": true + }, + "chromeos": { + "type": "string", + "optional": true + }, + "android": { + "type": "string", + "optional": true + }, + "ios": { + "type": "string", + "optional": true + }, + "additionalProperties": { + "type": "string", + "deprecated": "Unknown platform name", + "optional": true + } + } + }, + "description": { + "type": "string", + "optional": true + } + } + } + } + } + } + ] + }, + { + "namespace": "commands", + "description": "Use the commands API to add keyboard shortcuts that trigger actions in your extension, for example, an action to open the browser action or send a command to the xtension.", + "permissions": ["manifest:commands"], + "types": [ + { + "id": "Command", + "type": "object", + "properties": { + "name": { + "type": "string", + "optional": true, + "description": "The name of the Extension Command" + }, + "description": { + "type": "string", + "optional": true, + "description": "The Extension Command description" + }, + "shortcut": { + "type": "string", + "optional": true, + "description": "The shortcut active for this command, or blank if not active." + } + } + } + ], + "events": [ + { + "name": "onCommand", + "description": "Fired when a registered command is activated using a keyboard shortcut.", + "type": "function", + "parameters": [ + { + "name": "command", + "type": "string" + } + ] + } + ], + "functions": [ + { + "name": "getAll", + "type": "function", + "async": "callback", + "description": "Returns all the registered extension commands for this extension and their shortcut (if active).", + "parameters": [ + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "commands", + "type": "array", + "items": { + "$ref": "Command" + } + } + ], + "description": "Called to return the registered commands." + } + ] + } + ] + } +] diff --git a/application/basilisk/components/webextensions/schemas/context_menus.json b/application/basilisk/components/webextensions/schemas/context_menus.json new file mode 100644 index 000000000..b31af51f3 --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/context_menus.json @@ -0,0 +1,424 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "contextMenus" + ] + }] + } + ] + }, + { + "namespace": "contextMenus", + "description": "Use the browser.contextMenus API to add items to the browser's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages.", + "permissions": ["contextMenus"], + "properties": { + "ACTION_MENU_TOP_LEVEL_LIMIT": { + "value": 6, + "description": "The maximum number of top level extension items that can be added to an extension action context menu. Any items beyond this limit will be ignored." + } + }, + "types": [ + { + "id": "ContextType", + "type": "string", + "enum": ["all", "page", "frame", "selection", "link", "editable", "image", "video", "audio", "launcher", "browser_action", "page_action"], + "description": "The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other contexts except for 'launcher'. The 'launcher' context is only supported by apps and is used to add menu items to the context menu that appears when clicking on the app icon in the launcher/taskbar/dock/etc. Different platforms might put limitations on what is actually supported in a launcher context menu." + }, + { + "id": "ItemType", + "type": "string", + "enum": ["normal", "checkbox", "radio", "separator"], + "description": "The type of menu item." + }, + { + "id": "OnClickData", + "type": "object", + "description": "Information sent when a context menu item is clicked.", + "properties": { + "menuItemId": { + "choices": [ + { "type": "integer" }, + { "type": "string" } + ], + "description": "The ID of the menu item that was clicked." + }, + "parentMenuItemId": { + "choices": [ + { "type": "integer" }, + { "type": "string" } + ], + "optional": true, + "description": "The parent ID, if any, for the item clicked." + }, + "mediaType": { + "type": "string", + "optional": true, + "description": "One of 'image', 'video', or 'audio' if the context menu was activated on one of these types of elements." + }, + "linkUrl": { + "type": "string", + "optional": true, + "description": "If the element is a link, the URL it points to." + }, + "srcUrl": { + "type": "string", + "optional": true, + "description": "Will be present for elements with a 'src' URL." + }, + "pageUrl": { + "type": "string", + "optional": true, + "description": "The URL of the page where the menu item was clicked. This property is not set if the click occured in a context where there is no current page, such as in a launcher context menu." + }, + "frameUrl": { + "type": "string", + "optional": true, + "description": " The URL of the frame of the element where the context menu was clicked, if it was in a frame." + }, + "selectionText": { + "type": "string", + "optional": true, + "description": "The text for the context selection, if any." + }, + "editable": { + "type": "boolean", + "description": "A flag indicating whether the element is editable (text input, textarea, etc.)." + }, + "wasChecked": { + "type": "boolean", + "optional": true, + "description": "A flag indicating the state of a checkbox or radio item before it was clicked." + }, + "checked": { + "type": "boolean", + "optional": true, + "description": "A flag indicating the state of a checkbox or radio item after it is clicked." + } + } + } + ], + "functions": [ + { + "name": "create", + "type": "function", + "description": "Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in $(ref:runtime.lastError)).", + "returns": { + "choices": [ + { "type": "integer" }, + { "type": "string" } + ], + "description": "The ID of the newly created item." + }, + "parameters": [ + { + "type": "object", + "name": "createProperties", + "properties": { + "type": { + "$ref": "ItemType", + "optional": true, + "description": "The type of menu item. Defaults to 'normal' if not specified." + }, + "id": { + "type": "string", + "optional": true, + "description": "The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension." + }, + "title": { + "type": "string", + "optional": true, + "description": "The text to be displayed in the item; this is required unless type is 'separator'. When the context is 'selection', you can use %s within the string to show the selected text. For example, if this parameter's value is \"Translate '%s' to Pig Latin\" and the user selects the word \"cool\", the context menu item for the selection is \"Translate 'cool' to Pig Latin\"." + }, + "checked": { + "type": "boolean", + "optional": true, + "description": "The initial state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items." + }, + "contexts": { + "type": "array", + "items": { + "$ref": "ContextType" + }, + "minItems": 1, + "optional": true, + "description": "List of contexts this menu item will appear in. Defaults to ['page'] if not specified." + }, + "onclick": { + "type": "function", + "optional": true, + "description": "A function that will be called back when the menu item is clicked. Event pages cannot use this; instead, they should register a listener for $(ref:contextMenus.onClicked).", + "parameters": [ + { + "name": "info", + "$ref": "contextMenusInternal.OnClickData", + "description": "Information about the item clicked and the context where the click happened." + }, + { + "name": "tab", + "$ref": "tabs.Tab", + "description": "The details of the tab where the click took place. Note: this parameter only present for extensions." + } + ] + }, + "parentId": { + "choices": [ + { "type": "integer" }, + { "type": "string" } + ], + "optional": true, + "description": "The ID of a parent menu item; this makes the item a child of a previously added item." + }, + "documentUrlPatterns": { + "type": "array", + "items": {"type": "string"}, + "optional": true, + "description": "Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see $(topic:match_patterns)[Match Patterns]." + }, + "targetUrlPatterns": { + "type": "array", + "items": {"type": "string"}, + "optional": true, + "description": "Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags." + }, + "enabled": { + "type": "boolean", + "optional": true, + "description": "Whether this context menu item is enabled or disabled. Defaults to true." + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "description": "Called when the item has been created in the browser. If there were any problems creating the item, details will be available in $(ref:runtime.lastError).", + "parameters": [] + } + ] + }, + { + "name": "createInternal", + "type": "function", + "allowedContexts": ["addon_parent_only"], + "async": "callback", + "description": "Identical to contextMenus.create, except: the 'id' field is required and allows an integer, 'onclick' is not allowed, and the method is async (and the return value is not a menu item ID).", + "parameters": [ + { + "type": "object", + "name": "createProperties", + "properties": { + "type": { + "$ref": "ItemType", + "optional": true + }, + "id": { + "choices": [ + { "type": "integer" }, + { "type": "string" } + ] + }, + "title": { + "type": "string", + "optional": true + }, + "checked": { + "type": "boolean", + "optional": true + }, + "contexts": { + "type": "array", + "items": { + "$ref": "ContextType" + }, + "minItems": 1, + "optional": true + }, + "parentId": { + "choices": [ + { "type": "integer" }, + { "type": "string" } + ], + "optional": true + }, + "documentUrlPatterns": { + "type": "array", + "items": {"type": "string"}, + "optional": true + }, + "targetUrlPatterns": { + "type": "array", + "items": {"type": "string"}, + "optional": true + }, + "enabled": { + "type": "boolean", + "optional": true + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "update", + "type": "function", + "description": "Updates a previously created context menu item.", + "async": "callback", + "parameters": [ + { + "choices": [ + { "type": "integer" }, + { "type": "string" } + ], + "name": "id", + "description": "The ID of the item to update." + }, + { + "type": "object", + "name": "updateProperties", + "description": "The properties to update. Accepts the same values as the create function.", + "properties": { + "type": { + "$ref": "ItemType", + "optional": true + }, + "title": { + "type": "string", + "optional": true + }, + "checked": { + "type": "boolean", + "optional": true + }, + "contexts": { + "type": "array", + "items": { + "$ref": "ContextType" + }, + "minItems": 1, + "optional": true + }, + "onclick": { + "type": "function", + "optional": "omit-key-if-missing", + "parameters": [ + { + "name": "info", + "$ref": "contextMenusInternal.OnClickData" + }, + { + "name": "tab", + "$ref": "tabs.Tab", + "description": "The details of the tab where the click took place. Note: this parameter only present for extensions." + } + ] + }, + "parentId": { + "choices": [ + { "type": "integer" }, + { "type": "string" } + ], + "optional": true, + "description": "Note: You cannot change an item to be a child of one of its own descendants." + }, + "documentUrlPatterns": { + "type": "array", + "items": {"type": "string"}, + "optional": true + }, + "targetUrlPatterns": { + "type": "array", + "items": {"type": "string"}, + "optional": true + }, + "enabled": { + "type": "boolean", + "optional": true + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [], + "description": "Called when the context menu has been updated." + } + ] + }, + { + "name": "remove", + "type": "function", + "description": "Removes a context menu item.", + "async": "callback", + "parameters": [ + { + "choices": [ + { "type": "integer" }, + { "type": "string" } + ], + "name": "menuItemId", + "description": "The ID of the context menu item to remove." + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [], + "description": "Called when the context menu has been removed." + } + ] + }, + { + "name": "removeAll", + "type": "function", + "description": "Removes all context menu items added by this extension.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [], + "description": "Called when removal is complete." + } + ] + } + ], + "events": [ + { + "name": "onClicked", + "type": "function", + "description": "Fired when a context menu item is clicked.", + "parameters": [ + { + "name": "info", + "$ref": "OnClickData", + "description": "Information about the item clicked and the context where the click happened." + }, + { + "name": "tab", + "$ref": "tabs.Tab", + "description": "The details of the tab where the click took place. If the click did not take place in a tab, this parameter will be missing.", + "optional": true + } + ] + } + ] + } +] diff --git a/application/basilisk/components/webextensions/schemas/context_menus_internal.json b/application/basilisk/components/webextensions/schemas/context_menus_internal.json new file mode 100644 index 000000000..c3cb7aff0 --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/context_menus_internal.json @@ -0,0 +1,78 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "contextMenusInternal", + "description": "Use the browser.contextMenus API to add items to the browser's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages.", + "types": [ + { + "id": "OnClickData", + "type": "object", + "description": "Information sent when a context menu item is clicked.", + "properties": { + "menuItemId": { + "choices": [ + { "type": "integer" }, + { "type": "string" } + ], + "description": "The ID of the menu item that was clicked." + }, + "parentMenuItemId": { + "choices": [ + { "type": "integer" }, + { "type": "string" } + ], + "optional": true, + "description": "The parent ID, if any, for the item clicked." + }, + "mediaType": { + "type": "string", + "optional": true, + "description": "One of 'image', 'video', or 'audio' if the context menu was activated on one of these types of elements." + }, + "linkUrl": { + "type": "string", + "optional": true, + "description": "If the element is a link, the URL it points to." + }, + "srcUrl": { + "type": "string", + "optional": true, + "description": "Will be present for elements with a 'src' URL." + }, + "pageUrl": { + "type": "string", + "optional": true, + "description": "The URL of the page where the menu item was clicked. This property is not set if the click occured in a context where there is no current page, such as in a launcher context menu." + }, + "frameUrl": { + "type": "string", + "optional": true, + "description": " The URL of the frame of the element where the context menu was clicked, if it was in a frame." + }, + "selectionText": { + "type": "string", + "optional": true, + "description": "The text for the context selection, if any." + }, + "editable": { + "type": "boolean", + "description": "A flag indicating whether the element is editable (text input, textarea, etc.)." + }, + "wasChecked": { + "type": "boolean", + "optional": true, + "description": "A flag indicating the state of a checkbox or radio item before it was clicked." + }, + "checked": { + "type": "boolean", + "optional": true, + "description": "A flag indicating the state of a checkbox or radio item after it is clicked." + } + } + } + ] + } +] diff --git a/application/basilisk/components/webextensions/schemas/history.json b/application/basilisk/components/webextensions/schemas/history.json new file mode 100644 index 000000000..e05569e38 --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/history.json @@ -0,0 +1,316 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "history" + ] + }] + } + ] + }, + { + "namespace": "history", + "description": "Use the browser.history API to interact with the browser's record of visited pages. You can add, remove, and query for URLs in the browser's history. To override the history page with your own version, see $(topic:override)[Override Pages].", + "permissions": ["history"], + "types": [ + { + "id": "TransitionType", + "type": "string", + "enum": ["link", "typed", "auto_bookmark", "auto_subframe", "manual_subframe", "generated", "auto_toplevel", "form_submit", "reload", "keyword", "keyword_generated"], + "description": "The $(topic:transition-types)[transition type] for this visit from its referrer." + }, + { + "id": "HistoryItem", + "type": "object", + "description": "An object encapsulating one result of a history query.", + "properties": { + "id": { + "type": "string", + "description": "The unique identifier for the item." + }, + "url": { + "type": "string", + "optional": true, + "description": "The URL navigated to by a user." + }, + "title": { + "type": "string", + "optional": true, + "description": "The title of the page when it was last loaded." + }, + "lastVisitTime": { + "type": "number", + "optional": true, + "description": "When this page was last loaded, represented in milliseconds since the epoch." + }, + "visitCount": { + "type": "integer", + "optional": true, + "description": "The number of times the user has navigated to this page." + }, + "typedCount": { + "type": "integer", + "optional": true, + "description": "The number of times the user has navigated to this page by typing in the address." + } + } + }, + { + "id": "VisitItem", + "type": "object", + "description": "An object encapsulating one visit to a URL.", + "properties": { + "id": { + "type": "string", + "description": "The unique identifier for the item." + }, + "visitId": { + "type": "string", + "description": "The unique identifier for this visit." + }, + "visitTime": { + "type": "number", + "optional": true, + "description": "When this visit occurred, represented in milliseconds since the epoch." + }, + "referringVisitId": { + "type": "string", + "description": "The visit ID of the referrer." + }, + "transition": { + "$ref": "TransitionType", + "description": "The $(topic:transition-types)[transition type] for this visit from its referrer." + } + } + } + ], + "functions": [ + { + "name": "search", + "type": "function", + "description": "Searches the history for the last visit time of each page matching the query.", + "async": "callback", + "parameters": [ + { + "name": "query", + "type": "object", + "properties": { + "text": { + "type": "string", + "description": "A free-text query to the history service. Leave empty to retrieve all pages." + }, + "startTime": { + "$ref": "extensionTypes.Date", + "optional": true, + "description": "Limit results to those visited after this date. If not specified, this defaults to 24 hours in the past." + }, + "endTime": { + "$ref": "extensionTypes.Date", + "optional": true, + "description": "Limit results to those visited before this date." + }, + "maxResults": { + "type": "integer", + "optional": true, + "minimum": 1, + "description": "The maximum number of results to retrieve. Defaults to 100." + } + } + }, + { + "name": "callback", + "type": "function", + "parameters": [ + { + "name": "results", + "type": "array", + "items": { + "$ref": "HistoryItem" + } + } + ] + } + ] + }, + { + "name": "getVisits", + "type": "function", + "description": "Retrieves information about visits to a URL.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The URL for which to retrieve visit information. It must be in the format as returned from a call to history.search." + } + } + }, + { + "name": "callback", + "type": "function", + "parameters": [ + { + "name": "results", + "type": "array", + "items": { + "$ref": "VisitItem" + } + } + ] + } + ] + }, + { + "name": "addUrl", + "type": "function", + "description": "Adds a URL to the history with a default visitTime of the current time and a default $(topic:transition-types)[transition type] of \"link\".", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The URL to add. Must be a valid URL that can be added to history." + }, + "title": { + "type": "string", + "optional": true, + "description": "The title of the page." + }, + "transition": { + "$ref": "TransitionType", + "optional": true, + "description": "The $(topic:transition-types)[transition type] for this visit from its referrer." + }, + "visitTime": { + "$ref": "extensionTypes.Date", + "optional": true, + "description": "The date when this visit occurred." + } + } + }, + { + "name": "callback", + "type": "function", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "deleteUrl", + "type": "function", + "description": "Removes all occurrences of the given URL from the history.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The URL to remove." + } + } + }, + { + "name": "callback", + "type": "function", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "deleteRange", + "type": "function", + "description": "Removes all items within the specified date range from the history. Pages will not be removed from the history unless all visits fall within the range.", + "async": "callback", + "parameters": [ + { + "name": "range", + "type": "object", + "properties": { + "startTime": { + "$ref": "extensionTypes.Date", + "description": "Items added to history after this date." + }, + "endTime": { + "$ref": "extensionTypes.Date", + "description": "Items added to history before this date." + } + } + }, + { + "name": "callback", + "type": "function", + "parameters": [] + } + ] + }, + { + "name": "deleteAll", + "type": "function", + "description": "Deletes all items from the history.", + "async": "callback", + "parameters": [ + { + "name": "callback", + "type": "function", + "parameters": [] + } + ] + } + ], + "events": [ + { + "name": "onVisited", + "type": "function", + "description": "Fired when a URL is visited, providing the HistoryItem data for that URL. This event fires before the page has loaded.", + "parameters": [ + { + "name": "result", + "$ref": "HistoryItem" + } + ] + }, + { + "name": "onVisitRemoved", + "type": "function", + "description": "Fired when one or more URLs are removed from the history service. When all visits have been removed the URL is purged from history.", + "parameters": [ + { + "name": "removed", + "type": "object", + "properties": { + "allHistory": { + "type": "boolean", + "description": "True if all history was removed. If true, then urls will be empty." + }, + "urls": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + ] + } + ] + } +] diff --git a/application/basilisk/components/webextensions/schemas/jar.mn b/application/basilisk/components/webextensions/schemas/jar.mn new file mode 100644 index 000000000..c9fc9a808 --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/jar.mn @@ -0,0 +1,16 @@ +# 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/. + +browser.jar: + content/browser/schemas/bookmarks.json + content/browser/schemas/browser_action.json + content/browser/schemas/commands.json + content/browser/schemas/context_menus.json + content/browser/schemas/context_menus_internal.json + content/browser/schemas/history.json + content/browser/schemas/omnibox.json + content/browser/schemas/page_action.json + content/browser/schemas/sessions.json + content/browser/schemas/tabs.json + content/browser/schemas/windows.json diff --git a/application/basilisk/components/webextensions/schemas/moz.build b/application/basilisk/components/webextensions/schemas/moz.build new file mode 100644 index 000000000..aac3a838c --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/moz.build @@ -0,0 +1,7 @@ +# -*- 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/. + +JAR_MANIFESTS += ['jar.mn'] diff --git a/application/basilisk/components/webextensions/schemas/omnibox.json b/application/basilisk/components/webextensions/schemas/omnibox.json new file mode 100644 index 000000000..34428fab7 --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/omnibox.json @@ -0,0 +1,248 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "WebExtensionManifest", + "properties": { + "omnibox": { + "type": "object", + "additionalProperties": { "$ref": "UnrecognizedProperty" }, + "properties": { + "keyword": { + "type": "string", + "pattern": "^[^?\\s:]([^\\s:]*[^/\\s:])?$" + } + }, + "optional": true + } + } + } + ] + }, + { + "namespace": "omnibox", + "description": "The omnibox API allows you to register a keyword with Firefox's address bar.", + "permissions": ["manifest:omnibox"], + "types": [ + { + "id": "DescriptionStyleType", + "type": "string", + "description": "The style type.", + "enum": ["url", "match", "dim"] + }, + { + "id": "OnInputEnteredDisposition", + "type": "string", + "enum": ["currentTab", "newForegroundTab", "newBackgroundTab"], + "description": "The window disposition for the omnibox query. This is the recommended context to display results. For example, if the omnibox command is to navigate to a certain URL, a disposition of 'newForegroundTab' means the navigation should take place in a new selected tab." + }, + { + "id": "SuggestResult", + "type": "object", + "description": "A suggest result.", + "properties": { + "content": { + "type": "string", + "minLength": 1, + "description": "The text that is put into the URL bar, and that is sent to the extension when the user chooses this entry." + }, + "description": { + "type": "string", + "minLength": 1, + "description": "The text that is displayed in the URL dropdown. Can contain XML-style markup for styling. The supported tags are 'url' (for a literal URL), 'match' (for highlighting text that matched what the user's query), and 'dim' (for dim helper text). The styles can be nested, eg. dimmed match. You must escape the five predefined entities to display them as text: stackoverflow.com/a/1091953/89484 " + }, + "descriptionStyles": { + "optional": true, + "unsupported": true, + "type": "array", + "description": "An array of style ranges for the description, as provided by the extension.", + "items": { + "type": "object", + "description": "The style ranges for the description, as provided by the extension.", + "properties": { + "offset": { "type": "integer" }, + "type": { "description": "The style type", "$ref": "DescriptionStyleType"}, + "length": { "type": "integer", "optional": true } + } + } + }, + "descriptionStylesRaw": { + "optional": true, + "unsupported": true, + "type": "array", + "description": "An array of style ranges for the description, as provided by ToValue().", + "items": { + "type": "object", + "description": "The style ranges for the description, as provided by ToValue().", + "properties": { + "offset": { "type": "integer" }, + "type": { "type": "integer" } + } + } + } + } + }, + { + "id": "DefaultSuggestResult", + "type": "object", + "description": "A suggest result.", + "properties": { + "description": { + "type": "string", + "minLength": 1, + "description": "The text that is displayed in the URL dropdown." + }, + "descriptionStyles": { + "optional": true, + "unsupported": true, + "type": "array", + "description": "An array of style ranges for the description, as provided by the extension.", + "items": { + "type": "object", + "description": "The style ranges for the description, as provided by the extension.", + "properties": { + "offset": { "type": "integer" }, + "type": { "description": "The style type", "$ref": "DescriptionStyleType"}, + "length": { "type": "integer", "optional": true } + } + } + }, + "descriptionStylesRaw": { + "optional": true, + "unsupported": true, + "type": "array", + "description": "An array of style ranges for the description, as provided by ToValue().", + "items": { + "type": "object", + "description": "The style ranges for the description, as provided by ToValue().", + "properties": { + "offset": { "type": "integer" }, + "type": { "type": "integer" } + } + } + } + } + } + ], + "functions": [ + { + "name": "setDefaultSuggestion", + "type": "function", + "description": "Sets the description and styling for the default suggestion. The default suggestion is the text that is displayed in the first suggestion row underneath the URL bar.", + "parameters": [ + { + "name": "suggestion", + "$ref": "DefaultSuggestResult", + "description": "A partial SuggestResult object, without the 'content' parameter." + } + ] + } + ], + "events": [ + { + "name": "onInputStarted", + "type": "function", + "description": "User has started a keyword input session by typing the extension's keyword. This is guaranteed to be sent exactly once per input session, and before any onInputChanged events.", + "parameters": [] + }, + { + "name": "onInputChanged", + "type": "function", + "description": "User has changed what is typed into the omnibox.", + "parameters": [ + { + "type": "string", + "name": "text" + }, + { + "name": "suggest", + "type": "function", + "description": "A callback passed to the onInputChanged event used for sending suggestions back to the browser.", + "parameters": [ + { + "name": "suggestResults", + "type": "array", + "description": "Array of suggest results", + "items": { + "$ref": "SuggestResult" + } + } + ] + } + ] + }, + { + "name": "onInputEntered", + "type": "function", + "description": "User has accepted what is typed into the omnibox.", + "parameters": [ + { + "type": "string", + "name": "text" + }, + { + "name": "disposition", + "$ref": "OnInputEnteredDisposition" + } + ] + }, + { + "name": "onInputCancelled", + "type": "function", + "description": "User has ended the keyword input session without accepting the input.", + "parameters": [] + } + ] + }, + { + "namespace": "omnibox_internal", + "description": "The internal namespace used by the omnibox API.", + "defaultContexts": ["addon_parent_only"], + "functions": [ + { + "name": "addSuggestions", + "type": "function", + "async": "callback", + "description": "Internal function used by omnibox.onInputChanged for adding search suggestions", + "parameters": [ + { + "name": "id", + "type": "integer", + "description": "The ID of the callback received by onInputChangedInternal" + }, + { + "name": "suggestResults", + "type": "array", + "description": "Array of suggest results", + "items": { + "$ref": "omnibox.SuggestResult" + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + } + ], + "events": [ + { + "name": "onInputChanged", + "type": "function", + "description": "Identical to omnibox.onInputChanged except no 'suggest' callback is provided.", + "parameters": [ + { + "type": "string", + "name": "text" + } + ] + } + ] + } +] \ No newline at end of file diff --git a/application/basilisk/components/webextensions/schemas/page_action.json b/application/basilisk/components/webextensions/schemas/page_action.json new file mode 100644 index 000000000..126378ca5 --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/page_action.json @@ -0,0 +1,235 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "WebExtensionManifest", + "properties": { + "page_action": { + "type": "object", + "additionalProperties": { "$ref": "UnrecognizedProperty" }, + "properties": { + "default_title": { + "type": "string", + "optional": true, + "preprocess": "localize" + }, + "default_icon": { + "$ref": "IconPath", + "optional": true + }, + "default_popup": { + "type": "string", + "format": "relativeUrl", + "optional": true, + "preprocess": "localize" + }, + "browser_style": { + "type": "boolean", + "optional": true + } + }, + "optional": true + } + } + } + ] + }, + { + "namespace": "pageAction", + "description": "Use the browser.pageAction API to put icons inside the address bar. Page actions represent actions that can be taken on the current page, but that aren't applicable to all pages.", + "permissions": ["manifest:page_action"], + "types": [ + { + "id": "ImageDataType", + "type": "object", + "isInstanceOf": "ImageData", + "additionalProperties": { "type": "any" }, + "postprocess": "convertImageDataToURL", + "description": "Pixel data for an image. Must be an ImageData object (for example, from a canvas element)." + } + ], + "functions": [ + { + "name": "show", + "type": "function", + "async": "callback", + "description": "Shows the page action. The page action is shown whenever the tab is selected.", + "parameters": [ + {"type": "integer", "name": "tabId", "minimum": 0, "description": "The id of the tab for which you want to modify the page action."}, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "hide", + "type": "function", + "async": "callback", + "description": "Hides the page action.", + "parameters": [ + {"type": "integer", "name": "tabId", "minimum": 0, "description": "The id of the tab for which you want to modify the page action."}, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "setTitle", + "type": "function", + "description": "Sets the title of the page action. This is displayed in a tooltip over the page action.", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "tabId": {"type": "integer", "minimum": 0, "description": "The id of the tab for which you want to modify the page action."}, + "title": {"type": "string", "description": "The tooltip string."} + } + } + ] + }, + { + "name": "getTitle", + "type": "function", + "description": "Gets the title of the page action.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "tabId": { + "type": "integer", + "description": "Specify the tab to get the title from." + } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "result", + "type": "string" + } + ] + } + ] + }, + { + "name": "setIcon", + "type": "function", + "description": "Sets the icon for the page action. The icon can be specified either as the path to an image file or as the pixel data from a canvas element, or as dictionary of either one of those. Either the path or the imageData property must be specified.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "tabId": {"type": "integer", "minimum": 0, "description": "The id of the tab for which you want to modify the page action."}, + "imageData": { + "choices": [ + { "$ref": "ImageDataType" }, + { + "type": "object", + "additionalProperties": {"$ref": "ImageDataType"} + } + ], + "optional": true, + "description": "Either an ImageData object or a dictionary {size -> ImageData} representing icon to be set. If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density. If the number of image pixels that fit into one screen space unit equals scale, then image with size scale * 19 will be selected. Initially only scales 1 and 2 will be supported. At least one image must be specified. Note that 'details.imageData = foo' is equivalent to 'details.imageData = {'19': foo}'" + }, + "path": { + "choices": [ + { "type": "string" }, + { + "type": "object", + "additionalProperties": {"type": "string"} + } + ], + "optional": true, + "description": "Either a relative image path or a dictionary {size -> relative image path} pointing to icon to be set. If the icon is specified as a dictionary, the actual image to be used is chosen depending on screen's pixel density. If the number of image pixels that fit into one screen space unit equals scale, then image with size scale * 19 will be selected. Initially only scales 1 and 2 will be supported. At least one image must be specified. Note that 'details.path = foo' is equivalent to 'details.imageData = {'19': foo}'" + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "setPopup", + "type": "function", + "async": true, + "description": "Sets the html document to be opened as a popup when the user clicks on the page action's icon.", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "tabId": {"type": "integer", "minimum": 0, "description": "The id of the tab for which you want to modify the page action."}, + "popup": { + "type": "string", + "description": "The html file to show in a popup. If set to the empty string (''), no popup is shown." + } + } + } + ] + }, + { + "name": "getPopup", + "type": "function", + "description": "Gets the html document set as the popup for this page action.", + "async": "callback", + "parameters": [ + { + "name": "details", + "type": "object", + "properties": { + "tabId": { + "type": "integer", + "description": "Specify the tab to get the popup from." + } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "result", + "type": "string" + } + ] + } + ] + } + ], + "events": [ + { + "name": "onClicked", + "type": "function", + "description": "Fired when a page action icon is clicked. This event will not fire if the page action has a popup.", + "parameters": [ + { + "name": "tab", + "$ref": "tabs.Tab" + } + ] + } + ] + } +] diff --git a/application/basilisk/components/webextensions/schemas/sessions.json b/application/basilisk/components/webextensions/schemas/sessions.json new file mode 100644 index 000000000..690bb8ebc --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/sessions.json @@ -0,0 +1,146 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "sessions" + ] + }] + } + ] + }, + { + "namespace": "sessions", + "description": "Use the chrome.sessions API to query and restore tabs and windows from a browsing session.", + "permissions": ["sessions"], + "types": [ + { + "id": "Filter", + "type": "object", + "properties": { + "maxResults": { + "type": "integer", + "minimum": 0, + "maximum": 25, + "optional": true, + "description": "The maximum number of entries to be fetched in the requested list. Omit this parameter to fetch the maximum number of entries ($(ref:sessions.MAX_SESSION_RESULTS))." + } + } + }, + { + "id": "Session", + "type": "object", + "properties": { + "lastModified": {"type": "integer", "description": "The time when the window or tab was closed or modified, represented in milliseconds since the epoch."}, + "tab": {"$ref": "tabs.Tab", "optional": true, "description": "The $(ref:tabs.Tab), if this entry describes a tab. Either this or $(ref:sessions.Session.window) will be set."}, + "window": {"$ref": "windows.Window", "optional": true, "description": "The $(ref:windows.Window), if this entry describes a window. Either this or $(ref:sessions.Session.tab) will be set."} + } + }, + { + "id": "Device", + "type": "object", + "properties": { + "info": {"type": "string"}, + "deviceName": {"type": "string", "description": "The name of the foreign device."}, + "sessions": {"type": "array", "items": {"$ref": "Session"}, "description": "A list of open window sessions for the foreign device, sorted from most recently to least recently modified session."} + } + } + ], + "functions": [ + { + "name": "getRecentlyClosed", + "type": "function", + "description": "Gets the list of recently closed tabs and/or windows.", + "async": "callback", + "parameters": [ + { + "$ref": "Filter", + "name": "filter", + "optional": true, + "default": {} + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "sessions", "type": "array", "items": { "$ref": "Session" }, "description": "The list of closed entries in reverse order that they were closed (the most recently closed tab or window will be at index 0). The entries may contain either tabs or windows." + } + ] + } + ] + }, + { + "name": "getDevices", + "unsupported": true, + "type": "function", + "description": "Retrieves all devices with synced sessions.", + "async": "callback", + "parameters": [ + { + "$ref": "Filter", + "name": "filter", + "optional": true + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "devices", "type": "array", "items": { "$ref": "Device" }, "description": "The list of $(ref:sessions.Device) objects for each synced session, sorted in order from device with most recently modified session to device with least recently modified session. $(ref:tabs.Tab) objects are sorted by recency in the $(ref:windows.Window) of the $(ref:sessions.Session) objects." + } + ] + } + ] + }, + { + "name": "restore", + "type": "function", + "description": "Reopens a $(ref:windows.Window) or $(ref:tabs.Tab), with an optional callback to run when the entry has been restored.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "sessionId", + "optional": true, + "description": "The $(ref:windows.Window.sessionId), or $(ref:tabs.Tab.sessionId) to restore. If this parameter is not specified, the most recently closed session is restored." + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "$ref": "Session", + "name": "restoredSession", + "description": "A $(ref:sessions.Session) containing the restored $(ref:windows.Window) or $(ref:tabs.Tab) object." + } + ] + } + ] + } + ], + "events": [ + { + "name": "onChanged", + "unsupported": true, + "description": "Fired when recently closed tabs and/or windows are changed. This event does not monitor synced sessions changes.", + "type": "function" + } + ], + "properties": { + "MAX_SESSION_RESULTS": { + "value": 25, + "description": "The maximum number of $(ref:sessions.Session) that will be included in a requested list." + } + } + } +] diff --git a/application/basilisk/components/webextensions/schemas/tabs.json b/application/basilisk/components/webextensions/schemas/tabs.json new file mode 100644 index 000000000..23ce33a4b --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/tabs.json @@ -0,0 +1,1295 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "activeTab", + "tabs" + ] + }] + } + ] + }, + { + "namespace": "tabs", + "description": "Use the browser.tabs API to interact with the browser's tab system. You can use this API to create, modify, and rearrange tabs in the browser.", + "types": [ + { "id": "MutedInfoReason", + "type": "string", + "description": "An event that caused a muted state change.", + "enum": [ + {"name": "user", "description": "A user input action has set/overridden the muted state."}, + {"name": "capture", "description": "Tab capture started, forcing a muted state change."}, + {"name": "extension", "description": "An extension, identified by the extensionId field, set the muted state."} + ] + }, + { + "id": "MutedInfo", + "type": "object", + "description": "Tab muted state and the reason for the last state change.", + "properties": { + "muted": { + "type": "boolean", + "description": "Whether the tab is prevented from playing sound (but hasn't necessarily recently produced sound). Equivalent to whether the muted audio indicator is showing." + }, + "reason": { + "$ref": "MutedInfoReason", + "optional": true, + "description": "The reason the tab was muted or unmuted. Not set if the tab's mute state has never been changed." + }, + "extensionId": { + "type": "string", + "optional": true, + "description": "The ID of the extension that changed the muted state. Not set if an extension was not the reason the muted state last changed." + } + } + }, + { + "id": "Tab", + "type": "object", + "properties": { + "id": {"type": "integer", "minimum": -1, "optional": true, "description": "The ID of the tab. Tab IDs are unique within a browser session. Under some circumstances a Tab may not be assigned an ID, for example when querying foreign tabs using the $(ref:sessions) API, in which case a session ID may be present. Tab ID can also be set to $(ref:tabs.TAB_ID_NONE) for apps and devtools windows."}, + "index": {"type": "integer", "minimum": -1, "description": "The zero-based index of the tab within its window."}, + "windowId": {"type": "integer", "minimum": 0, "description": "The ID of the window the tab is contained within."}, + "openerTabId": {"unsupported": true, "type": "integer", "minimum": 0, "optional": true, "description": "The ID of the tab that opened this tab, if any. This property is only present if the opener tab still exists."}, + "selected": {"type": "boolean", "description": "Whether the tab is selected.", "deprecated": "Please use $(ref:tabs.Tab.highlighted).", "unsupported": true}, + "highlighted": {"type": "boolean", "description": "Whether the tab is highlighted."}, + "active": {"type": "boolean", "description": "Whether the tab is active in its window. (Does not necessarily mean the window is focused.)"}, + "pinned": {"type": "boolean", "description": "Whether the tab is pinned."}, + "audible": {"type": "boolean", "optional": true, "description": "Whether the tab has produced sound over the past couple of seconds (but it might not be heard if also muted). Equivalent to whether the speaker audio indicator is showing."}, + "mutedInfo": {"$ref": "MutedInfo", "optional": true, "description": "Current tab muted state and the reason for the last state change."}, + "url": {"type": "string", "optional": true, "permissions": ["tabs"], "description": "The URL the tab is displaying. This property is only present if the extension's manifest includes the \"tabs\" permission."}, + "title": {"type": "string", "optional": true, "permissions": ["tabs"], "description": "The title of the tab. This property is only present if the extension's manifest includes the \"tabs\" permission."}, + "favIconUrl": {"type": "string", "optional": true, "permissions": ["tabs"], "description": "The URL of the tab's favicon. This property is only present if the extension's manifest includes the \"tabs\" permission. It may also be an empty string if the tab is loading."}, + "status": {"type": "string", "optional": true, "description": "Either loading or complete."}, + "incognito": {"type": "boolean", "description": "Whether the tab is in an incognito window."}, + "width": {"type": "integer", "optional": true, "description": "The width of the tab in pixels."}, + "height": {"type": "integer", "optional": true, "description": "The height of the tab in pixels."}, + "sessionId": {"unsupported": true, "type": "string", "optional": true, "description": "The session ID used to uniquely identify a Tab obtained from the $(ref:sessions) API."}, + "cookieStoreId": {"type": "string", "description": "The CookieStoreId used for the tab."} + } + }, + { + "id": "ZoomSettingsMode", + "type": "string", + "description": "Defines how zoom changes are handled, i.e. which entity is responsible for the actual scaling of the page; defaults to automatic.", + "enum": [ + { + "name": "automatic", + "description": "Zoom changes are handled automatically by the browser." + }, + { + "name": "manual", + "description": "Overrides the automatic handling of zoom changes. The onZoomChange event will still be dispatched, and it is the responsibility of the extension to listen for this event and manually scale the page. This mode does not support per-origin zooming, and will thus ignore the scope zoom setting and assume per-tab." + }, + { + "name": "disabled", + "description": "Disables all zooming in the tab. The tab will revert to the default zoom level, and all attempted zoom changes will be ignored." + } + ] + }, + { + "id": "ZoomSettingsScope", + "type": "string", + "description": "Defines whether zoom changes will persist for the page's origin, or only take effect in this tab; defaults to per-origin when in automatic mode, and per-tab otherwise.", + "enum": [ + { + "name": "per-origin", + "description": "Zoom changes will persist in the zoomed page's origin, i.e. all other tabs navigated to that same origin will be zoomed as well. Moreover, per-origin zoom changes are saved with the origin, meaning that when navigating to other pages in the same origin, they will all be zoomed to the same zoom factor. The per-origin scope is only available in the automatic mode." + }, + { + "name": "per-tab", + "description": "Zoom changes only take effect in this tab, and zoom changes in other tabs will not affect the zooming of this tab. Also, per-tab zoom changes are reset on navigation; navigating a tab will always load pages with their per-origin zoom factors." + } + ] + }, + { + "id": "ZoomSettings", + "type": "object", + "description": "Defines how zoom changes in a tab are handled and at what scope.", + "properties": { + "mode": { + "$ref": "ZoomSettingsMode", + "description": "Defines how zoom changes are handled, i.e. which entity is responsible for the actual scaling of the page; defaults to automatic.", + "optional": true + }, + "scope": { + "$ref": "ZoomSettingsScope", + "description": "Defines whether zoom changes will persist for the page's origin, or only take effect in this tab; defaults to per-origin when in automatic mode, and per-tab otherwise.", + "optional": true + }, + "defaultZoomFactor": { + "type": "number", + "optional": true, + "description": "Used to return the default zoom level for the current tab in calls to tabs.getZoomSettings." + } + } + }, + { + "id": "TabStatus", + "type": "string", + "enum": ["loading", "complete"], + "description": "Whether the tabs have completed loading." + }, + { + "id": "WindowType", + "type": "string", + "enum": ["normal", "popup", "panel", "app", "devtools"], + "description": "The type of window." + } + ], + "properties": { + "TAB_ID_NONE": { + "value": -1, + "description": "An ID which represents the absence of a browser tab." + } + }, + "functions": [ + { + "name": "get", + "type": "function", + "description": "Retrieves details about the specified tab.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0 + }, + { + "type": "function", + "name": "callback", + "parameters": [ + {"name": "tab", "$ref": "Tab"} + ] + } + ] + }, + { + "name": "getCurrent", + "type": "function", + "description": "Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "tab", + "$ref": "Tab", + "optional": true + } + ] + } + ] + }, + { + "name": "connect", + "type": "function", + "description": "Connects to the content script(s) in the specified tab. The $(ref:runtime.onConnect) event is fired in each content script running in the specified tab for the current extension. For more details, see $(topic:messaging)[Content Script Messaging].", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0 + }, + { + "type": "object", + "name": "connectInfo", + "properties": { + "name": { "type": "string", "optional": true, "description": "Will be passed into onConnect for content scripts that are listening for the connection event." }, + "frameId": { + "type": "integer", + "optional": true, + "minimum": 0, + "description": "Open a port to a specific $(topic:frame_ids)[frame] identified by frameId instead of all frames in the tab." + } + }, + "optional": true + } + ], + "returns": { + "$ref": "runtime.Port", + "description": "A port that can be used to communicate with the content scripts running in the specified tab. The port's $(ref:runtime.Port) event is fired if the tab closes or does not exist. " + } + }, + { + "name": "sendRequest", + "deprecated": "Please use $(ref:runtime.sendMessage).", + "unsupported": true, + "type": "function", + "description": "Sends a single request to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The $(ref:extension.onRequest) event is fired in each content script running in the specified tab for the current extension.", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0 + }, + { + "type": "any", + "name": "request" + }, + { + "type": "function", + "name": "responseCallback", + "optional": true, + "parameters": [ + { + "name": "response", + "type": "any", + "description": "The JSON response object sent by the handler of the request. If an error occurs while connecting to the specified tab, the callback will be called with no arguments and $(ref:runtime.lastError) will be set to the error message." + } + ] + } + ] + }, + { + "name": "sendMessage", + "type": "function", + "description": "Sends a single message to the content script(s) in the specified tab, with an optional callback to run when a response is sent back. The $(ref:runtime.onMessage) event is fired in each content script running in the specified tab for the current extension.", + "async": "responseCallback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0 + }, + { + "type": "any", + "name": "message" + }, + { + "type": "object", + "name": "options", + "properties": { + "frameId": { + "type": "integer", + "optional": true, + "minimum": 0, + "description": "Send a message to a specific $(topic:frame_ids)[frame] identified by frameId instead of all frames in the tab." + } + }, + "optional": true + }, + { + "type": "function", + "name": "responseCallback", + "optional": true, + "parameters": [ + { + "name": "response", + "type": "any", + "description": "The JSON response object sent by the handler of the message. If an error occurs while connecting to the specified tab, the callback will be called with no arguments and $(ref:runtime.lastError) will be set to the error message." + } + ] + } + ] + }, + { + "name": "getSelected", + "deprecated": "Please use $(ref:tabs.query) {active: true}.", + "unsupported": true, + "type": "function", + "description": "Gets the tab that is selected in the specified window.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "windowId", + "minimum": -2, + "optional": true, + "description": "Defaults to the $(topic:current-window)[current window]." + }, + { + "type": "function", + "name": "callback", + "parameters": [ + {"name": "tab", "$ref": "Tab"} + ] + } + ] + }, + { + "name": "getAllInWindow", + "deprecated": "Please use $(ref:tabs.query) {windowId: windowId}.", + "unsupported": true, + "type": "function", + "description": "Gets details about all tabs in the specified window.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "windowId", + "minimum": -2, + "optional": true, + "description": "Defaults to the $(topic:current-window)[current window]." + }, + { + "type": "function", + "name": "callback", + "parameters": [ + {"name": "tabs", "type": "array", "items": { "$ref": "Tab" } } + ] + } + ] + }, + { + "name": "create", + "type": "function", + "description": "Creates a new tab.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "createProperties", + "properties": { + "windowId": { + "type": "integer", + "minimum": -2, + "optional": true, + "description": "The window to create the new tab in. Defaults to the $(topic:current-window)[current window]." + }, + "index": { + "type": "integer", + "minimum": 0, + "optional": true, + "description": "The position the tab should take in the window. The provided value will be clamped to between zero and the number of tabs in the window." + }, + "url": { + "type": "string", + "optional": true, + "description": "The URL to navigate the tab to initially. Fully-qualified URLs must include a scheme (i.e. 'http://www.google.com', not 'www.google.com'). Relative URLs will be relative to the current page within the extension. Defaults to the New Tab Page." + }, + "active": { + "type": "boolean", + "optional": true, + "description": "Whether the tab should become the active tab in the window. Does not affect whether the window is focused (see $(ref:windows.update)). Defaults to true." + }, + "selected": { + "deprecated": "Please use active.", + "unsupported": true, + "type": "boolean", + "optional": true, + "description": "Whether the tab should become the selected tab in the window. Defaults to true" + }, + "pinned": { + "type": "boolean", + "optional": true, + "description": "Whether the tab should be pinned. Defaults to false" + }, + "openerTabId": { + "unsupported": true, + "type": "integer", + "minimum": 0, + "optional": true, + "description": "The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as the newly created tab." + }, + "cookieStoreId": { + "type": "string", + "optional": true, + "description": "The CookieStoreId for the tab that opened this tab." + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "tab", + "$ref": "Tab", + "description": "Details about the created tab. Will contain the ID of the new tab." + } + ] + } + ] + }, + { + "name": "duplicate", + "type": "function", + "description": "Duplicates a tab.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0, + "description": "The ID of the tab which is to be duplicated." + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "tab", + "optional": true, + "description": "Details about the duplicated tab. The $(ref:tabs.Tab) object doesn't contain url, title and favIconUrl if the \"tabs\" permission has not been requested.", + "$ref": "Tab" + } + ] + } + ] + }, + { + "name": "query", + "type": "function", + "description": "Gets all tabs that have the specified properties, or all tabs if no properties are specified.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "queryInfo", + "properties": { + "active": { + "type": "boolean", + "optional": true, + "description": "Whether the tabs are active in their windows." + }, + "pinned": { + "type": "boolean", + "optional": true, + "description": "Whether the tabs are pinned." + }, + "audible": { + "type": "boolean", + "optional": true, + "description": "Whether the tabs are audible." + }, + "muted": { + "type": "boolean", + "optional": true, + "description": "Whether the tabs are muted." + }, + "highlighted": { + "type": "boolean", + "optional": true, + "description": "Whether the tabs are highlighted." + }, + "currentWindow": { + "type": "boolean", + "optional": true, + "description": "Whether the tabs are in the $(topic:current-window)[current window]." + }, + "lastFocusedWindow": { + "type": "boolean", + "optional": true, + "description": "Whether the tabs are in the last focused window." + }, + "status": { + "$ref": "TabStatus", + "optional": true, + "description": "Whether the tabs have completed loading." + }, + "title": { + "type": "string", + "optional": true, + "description": "Match page titles against a pattern." + }, + "url": { + "choices": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ], + "optional": true, + "description": "Match tabs against one or more $(topic:match_patterns)[URL patterns]. Note that fragment identifiers are not matched." + }, + "windowId": { + "type": "integer", + "optional": true, + "minimum": -2, + "description": "The ID of the parent window, or $(ref:windows.WINDOW_ID_CURRENT) for the $(topic:current-window)[current window]." + }, + "windowType": { + "$ref": "WindowType", + "optional": true, + "description": "The type of window the tabs are in." + }, + "index": { + "type": "integer", + "optional": true, + "minimum": 0, + "description": "The position of the tabs within their windows." + }, + "cookieStoreId": { + "type": "string", + "optional": true, + "description": "The CookieStoreId used for the tab." + } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "result", + "type": "array", + "items": { + "$ref": "Tab" + } + } + ] + } + ] + }, + { + "name": "highlight", + "type": "function", + "description": "Highlights the given tabs.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "highlightInfo", + "properties": { + "windowId": { + "type": "integer", + "optional": true, + "description": "The window that contains the tabs.", + "minimum": -2 + }, + "tabs": { + "description": "One or more tab indices to highlight.", + "choices": [ + {"type": "array", "items": {"type": "integer", "minimum": 0}}, + {"type": "integer"} + ] + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "window", + "$ref": "windows.Window", + "description": "Contains details about the window whose tabs were highlighted." + } + ] + } + ] + }, + { + "name": "update", + "type": "function", + "description": "Modifies the properties of a tab. Properties that are not specified in updateProperties are not modified.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0, + "optional": true, + "description": "Defaults to the selected tab of the $(topic:current-window)[current window]." + }, + { + "type": "object", + "name": "updateProperties", + "properties": { + "url": { + "type": "string", + "optional": true, + "description": "A URL to navigate the tab to." + }, + "active": { + "type": "boolean", + "optional": true, + "description": "Whether the tab should be active. Does not affect whether the window is focused (see $(ref:windows.update))." + }, + "highlighted": { + "unsupported": true, + "type": "boolean", + "optional": true, + "description": "Adds or removes the tab from the current selection." + }, + "selected": { + "unsupported": true, + "deprecated": "Please use highlighted.", + "type": "boolean", + "optional": true, + "description": "Whether the tab should be selected." + }, + "pinned": { + "type": "boolean", + "optional": true, + "description": "Whether the tab should be pinned." + }, + "muted": { + "type": "boolean", + "optional": true, + "description": "Whether the tab should be muted." + }, + "openerTabId": { + "unsupported": true, + "type": "integer", + "minimum": 0, + "optional": true, + "description": "The ID of the tab that opened this tab. If specified, the opener tab must be in the same window as this tab." + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "tab", + "$ref": "Tab", + "optional": true, + "description": "Details about the updated tab. The $(ref:tabs.Tab) object doesn't contain url, title and favIconUrl if the \"tabs\" permission has not been requested." + } + ] + } + ] + }, + { + "name": "move", + "type": "function", + "description": "Moves one or more tabs to a new position within its window, or to a new window. Note that tabs can only be moved to and from normal (window.type === \"normal\") windows.", + "async": "callback", + "parameters": [ + { + "name": "tabIds", + "description": "The tab or list of tabs to move.", + "choices": [ + {"type": "integer", "minimum": 0}, + {"type": "array", "items": {"type": "integer", "minimum": 0}} + ] + }, + { + "type": "object", + "name": "moveProperties", + "properties": { + "windowId": { + "type": "integer", + "minimum": -2, + "optional": true, + "description": "Defaults to the window the tab is currently in." + }, + "index": { + "type": "integer", + "minimum": -1, + "description": "The position to move the window to. -1 will place the tab at the end of the window." + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "tabs", + "description": "Details about the moved tabs.", + "choices": [ + {"$ref": "Tab"}, + {"type": "array", "items": {"$ref": "Tab"}} + ] + } + ] + } + ] + }, + { + "name": "reload", + "type": "function", + "description": "Reload a tab.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0, + "optional": true, + "description": "The ID of the tab to reload; defaults to the selected tab of the current window." + }, + { + "type": "object", + "name": "reloadProperties", + "optional": true, + "properties": { + "bypassCache": { + "type": "boolean", + "optional": true, + "description": "Whether using any local cache. Default is false." + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "remove", + "type": "function", + "description": "Closes one or more tabs.", + "async": "callback", + "parameters": [ + { + "name": "tabIds", + "description": "The tab or list of tabs to close.", + "choices": [ + {"type": "integer", "minimum": 0}, + {"type": "array", "items": {"type": "integer", "minimum": 0}} + ] + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "detectLanguage", + "type": "function", + "description": "Detects the primary language of the content in a tab.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0, + "optional": true, + "description": "Defaults to the active tab of the $(topic:current-window)[current window]." + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "type": "string", + "name": "language", + "description": "An ISO language code such as en or fr. For a complete list of languages supported by this method, see kLanguageInfoTable. The 2nd to 4th columns will be checked and the first non-NULL value will be returned except for Simplified Chinese for which zh-CN will be returned. For an unknown language, und will be returned." + } + ] + } + ] + }, + { + "name": "captureVisibleTab", + "type": "function", + "description": "Captures the visible area of the currently active tab in the specified window. You must have $(topic:declare_permissions)[<all_urls>] permission to use this method.", + "permissions": [""], + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "windowId", + "minimum": -2, + "optional": true, + "description": "The target window. Defaults to the $(topic:current-window)[current window]." + }, + { + "$ref": "extensionTypes.ImageDetails", + "name": "options", + "optional": true + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "type": "string", + "name": "dataUrl", + "description": "A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display." + } + ] + } + ] + }, + { + "name": "executeScript", + "type": "function", + "description": "Injects JavaScript code into a page. For details, see the $(topic:content_scripts)[programmatic injection] section of the content scripts doc.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0, + "optional": true, + "description": "The ID of the tab in which to run the script; defaults to the active tab of the current window." + }, + { + "$ref": "extensionTypes.InjectDetails", + "name": "details", + "description": "Details of the script to run." + }, + { + "type": "function", + "name": "callback", + "optional": true, + "description": "Called after all the JavaScript has been executed.", + "parameters": [ + { + "name": "result", + "optional": true, + "type": "array", + "items": {"type": "any"}, + "description": "The result of the script in every injected frame." + } + ] + } + ] + }, + { + "name": "insertCSS", + "type": "function", + "description": "Injects CSS into a page. For details, see the $(topic:content_scripts)[programmatic injection] section of the content scripts doc.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0, + "optional": true, + "description": "The ID of the tab in which to insert the CSS; defaults to the active tab of the current window." + }, + { + "$ref": "extensionTypes.InjectDetails", + "name": "details", + "description": "Details of the CSS text to insert." + }, + { + "type": "function", + "name": "callback", + "optional": true, + "description": "Called when all the CSS has been inserted.", + "parameters": [] + } + ] + }, + { + "name": "removeCSS", + "type": "function", + "description": "Removes injected CSS from a page. For details, see the $(topic:content_scripts)[programmatic injection] section of the content scripts doc.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0, + "optional": true, + "description": "The ID of the tab from which to remove the injected CSS; defaults to the active tab of the current window." + }, + { + "$ref": "extensionTypes.InjectDetails", + "name": "details", + "description": "Details of the CSS text to remove." + }, + { + "type": "function", + "name": "callback", + "optional": true, + "description": "Called when all the CSS has been removed.", + "parameters": [] + } + ] + }, + { + "name": "setZoom", + "type": "function", + "description": "Zooms a specified tab.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0, + "optional": true, + "description": "The ID of the tab to zoom; defaults to the active tab of the current window." + }, + { + "type": "number", + "name": "zoomFactor", + "description": "The new zoom factor. Use a value of 0 here to set the tab to its current default zoom factor. Values greater than zero specify a (possibly non-default) zoom factor for the tab." + }, + { + "type": "function", + "name": "callback", + "optional": true, + "description": "Called after the zoom factor has been changed.", + "parameters": [] + } + ] + }, + { + "name": "getZoom", + "type": "function", + "description": "Gets the current zoom factor of a specified tab.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0, + "optional": true, + "description": "The ID of the tab to get the current zoom factor from; defaults to the active tab of the current window." + }, + { + "type": "function", + "name": "callback", + "description": "Called with the tab's current zoom factor after it has been fetched.", + "parameters": [ + { + "type": "number", + "name": "zoomFactor", + "description": "The tab's current zoom factor." + } + ] + } + ] + }, + { + "name": "setZoomSettings", + "type": "function", + "description": "Sets the zoom settings for a specified tab, which define how zoom changes are handled. These settings are reset to defaults upon navigating the tab.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "optional": true, + "minimum": 0, + "description": "The ID of the tab to change the zoom settings for; defaults to the active tab of the current window." + }, + { + "$ref": "ZoomSettings", + "name": "zoomSettings", + "description": "Defines how zoom changes are handled and at what scope." + }, + { + "type": "function", + "name": "callback", + "optional": true, + "description": "Called after the zoom settings have been changed.", + "parameters": [] + } + ] + }, + { + "name": "getZoomSettings", + "type": "function", + "description": "Gets the current zoom settings of a specified tab.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "optional": true, + "minimum": 0, + "description": "The ID of the tab to get the current zoom settings from; defaults to the active tab of the current window." + }, + { + "type": "function", + "name": "callback", + "description": "Called with the tab's current zoom settings.", + "parameters": [ + { + "$ref": "ZoomSettings", + "name": "zoomSettings", + "description": "The tab's current zoom settings." + } + ] + } + ] + } + ], + "events": [ + { + "name": "onCreated", + "type": "function", + "description": "Fired when a tab is created. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events to be notified when a URL is set.", + "parameters": [ + { + "$ref": "Tab", + "name": "tab", + "description": "Details of the tab that was created." + } + ] + }, + { + "name": "onUpdated", + "type": "function", + "description": "Fired when a tab is updated.", + "parameters": [ + {"type": "integer", "name": "tabId", "minimum": 0}, + { + "type": "object", + "name": "changeInfo", + "description": "Lists the changes to the state of the tab that was updated.", + "properties": { + "status": { + "type": "string", + "optional": true, + "description": "The status of the tab. Can be either loading or complete." + }, + "url": { + "type": "string", + "optional": true, + "description": "The tab's URL if it has changed." + }, + "pinned": { + "type": "boolean", + "optional": true, + "description": "The tab's new pinned state." + }, + "audible": { + "type": "boolean", + "optional": true, + "description": "The tab's new audible state." + }, + "mutedInfo": { + "$ref": "MutedInfo", + "optional": true, + "description": "The tab's new muted state and the reason for the change." + }, + "favIconUrl": { + "type": "string", + "optional": true, + "description": "The tab's new favicon URL." + } + } + }, + { + "$ref": "Tab", + "name": "tab", + "description": "Gives the state of the tab that was updated." + } + ] + }, + { + "name": "onMoved", + "type": "function", + "description": "Fired when a tab is moved within a window. Only one move event is fired, representing the tab the user directly moved. Move events are not fired for the other tabs that must move in response. This event is not fired when a tab is moved between windows. For that, see $(ref:tabs.onDetached).", + "parameters": [ + {"type": "integer", "name": "tabId", "minimum": 0}, + { + "type": "object", + "name": "moveInfo", + "properties": { + "windowId": {"type": "integer", "minimum": 0}, + "fromIndex": {"type": "integer", "minimum": 0}, + "toIndex": {"type": "integer", "minimum": 0} + } + } + ] + }, + { + "name": "onSelectionChanged", + "deprecated": "Please use $(ref:tabs.onActivated).", + "unsupported": true, + "type": "function", + "description": "Fires when the selected tab in a window changes.", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0, + "description": "The ID of the tab that has become active." + }, + { + "type": "object", + "name": "selectInfo", + "properties": { + "windowId": { + "type": "integer", + "minimum": 0, + "description": "The ID of the window the selected tab changed inside of." + } + } + } + ] + }, + { + "name": "onActiveChanged", + "deprecated": "Please use $(ref:tabs.onActivated).", + "unsupported": true, + "type": "function", + "description": "Fires when the selected tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to $(ref:tabs.onUpdated) events to be notified when a URL is set.", + "parameters": [ + { + "type": "integer", + "name": "tabId", + "minimum": 0, + "description": "The ID of the tab that has become active." + }, + { + "type": "object", + "name": "selectInfo", + "properties": { + "windowId": { + "type": "integer", + "minimum": 0, + "description": "The ID of the window the selected tab changed inside of." + } + } + } + ] + }, + { + "name": "onActivated", + "type": "function", + "description": "Fires when the active tab in a window changes. Note that the tab's URL may not be set at the time this event fired, but you can listen to onUpdated events to be notified when a URL is set.", + "parameters": [ + { + "type": "object", + "name": "activeInfo", + "properties": { + "tabId": { + "type": "integer", + "minimum": 0, + "description": "The ID of the tab that has become active." + }, + "windowId": { + "type": "integer", + "minimum": 0, + "description": "The ID of the window the active tab changed inside of." + } + } + } + ] + }, + { + "name": "onHighlightChanged", + "deprecated": "Please use $(ref:tabs.onHighlighted).", + "unsupported": true, + "type": "function", + "description": "Fired when the highlighted or selected tabs in a window changes.", + "parameters": [ + { + "type": "object", + "name": "selectInfo", + "properties": { + "windowId": { + "type": "integer", + "minimum": 0, + "description": "The window whose tabs changed." + }, + "tabIds": { + "type": "array", + "items": {"type": "integer", "minimum": 0}, + "description": "All highlighted tabs in the window." + } + } + } + ] + }, + { + "name": "onHighlighted", + "type": "function", + "description": "Fired when the highlighted or selected tabs in a window changes.", + "parameters": [ + { + "type": "object", + "name": "highlightInfo", + "properties": { + "windowId": { + "type": "integer", + "minimum": 0, + "description": "The window whose tabs changed." + }, + "tabIds": { + "type": "array", + "items": {"type": "integer", "minimum": 0}, + "description": "All highlighted tabs in the window." + } + } + } + ] + }, + { + "name": "onDetached", + "type": "function", + "description": "Fired when a tab is detached from a window, for example because it is being moved between windows.", + "parameters": [ + {"type": "integer", "name": "tabId", "minimum": 0}, + { + "type": "object", + "name": "detachInfo", + "properties": { + "oldWindowId": {"type": "integer", "minimum": 0}, + "oldPosition": {"type": "integer", "minimum": 0} + } + } + ] + }, + { + "name": "onAttached", + "type": "function", + "description": "Fired when a tab is attached to a window, for example because it was moved between windows.", + "parameters": [ + {"type": "integer", "name": "tabId", "minimum": 0}, + { + "type": "object", + "name": "attachInfo", + "properties": { + "newWindowId": {"type": "integer", "minimum": 0}, + "newPosition": {"type": "integer", "minimum": 0} + } + } + ] + }, + { + "name": "onRemoved", + "type": "function", + "description": "Fired when a tab is closed.", + "parameters": [ + {"type": "integer", "name": "tabId", "minimum": 0}, + { + "type": "object", + "name": "removeInfo", + "properties": { + "windowId": {"type": "integer", "minimum": 0, "description": "The window whose tab is closed." }, + "isWindowClosing": {"type": "boolean", "description": "True when the tab is being closed because its window is being closed." } + } + } + ] + }, + { + "name": "onReplaced", + "type": "function", + "description": "Fired when a tab is replaced with another tab due to prerendering or instant.", + "parameters": [ + {"type": "integer", "name": "addedTabId", "minimum": 0}, + {"type": "integer", "name": "removedTabId", "minimum": 0} + ] + }, + { + "name": "onZoomChange", + "type": "function", + "description": "Fired when a tab is zoomed.", + "parameters": [{ + "type": "object", + "name": "ZoomChangeInfo", + "properties": { + "tabId": {"type": "integer", "minimum": 0}, + "oldZoomFactor": {"type": "number"}, + "newZoomFactor": {"type": "number"}, + "zoomSettings": {"$ref": "ZoomSettings"} + } + }] + } + ] + } +] diff --git a/application/basilisk/components/webextensions/schemas/windows.json b/application/basilisk/components/webextensions/schemas/windows.json new file mode 100644 index 000000000..8453358b5 --- /dev/null +++ b/application/basilisk/components/webextensions/schemas/windows.json @@ -0,0 +1,508 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "windows", + "description": "Use the browser.windows API to interact with browser windows. You can use this API to create, modify, and rearrange windows in the browser.", + "types": [ + { + "id": "WindowType", + "type": "string", + "description": "The type of browser window this is. Under some circumstances a Window may not be assigned type property, for example when querying closed windows from the $(ref:sessions) API.", + "enum": ["normal", "popup", "panel", "app", "devtools"] + }, + { + "id": "WindowState", + "type": "string", + "description": "The state of this browser window. Under some circumstances a Window may not be assigned state property, for example when querying closed windows from the $(ref:sessions) API.", + "enum": ["normal", "minimized", "maximized", "fullscreen", "docked"] + }, + { + "id": "Window", + "type": "object", + "properties": { + "id": { + "type": "integer", + "optional": true, + "minimum": 0, + "description": "The ID of the window. Window IDs are unique within a browser session. Under some circumstances a Window may not be assigned an ID, for example when querying windows using the $(ref:sessions) API, in which case a session ID may be present." + }, + "focused": { + "type": "boolean", + "description": "Whether the window is currently the focused window." + }, + "top": { + "type": "integer", + "optional": true, + "description": "The offset of the window from the top edge of the screen in pixels. Under some circumstances a Window may not be assigned top property, for example when querying closed windows from the $(ref:sessions) API." + }, + "left": { + "type": "integer", + "optional": true, + "description": "The offset of the window from the left edge of the screen in pixels. Under some circumstances a Window may not be assigned left property, for example when querying closed windows from the $(ref:sessions) API." + }, + "width": { + "type": "integer", + "optional": true, + "description": "The width of the window, including the frame, in pixels. Under some circumstances a Window may not be assigned width property, for example when querying closed windows from the $(ref:sessions) API." + }, + "height": { + "type": "integer", + "optional": true, + "description": "The height of the window, including the frame, in pixels. Under some circumstances a Window may not be assigned height property, for example when querying closed windows from the $(ref:sessions) API." + }, + "tabs": { + "type": "array", + "items": { "$ref": "tabs.Tab" }, + "optional": true, + "description": "Array of $(ref:tabs.Tab) objects representing the current tabs in the window." + }, + "incognito": { + "type": "boolean", + "description": "Whether the window is incognito." + }, + "type": { + "$ref": "WindowType", + "optional": true, + "description": "The type of browser window this is." + }, + "state": { + "$ref": "WindowState", + "optional": true, + "description": "The state of this browser window." + }, + "alwaysOnTop": { + "type": "boolean", + "description": "Whether the window is set to be always on top." + }, + "sessionId": { + "type": "string", + "optional": true, + "description": "The session ID used to uniquely identify a Window obtained from the $(ref:sessions) API." + } + } + }, + { + "id": "CreateType", + "type": "string", + "description": "Specifies what type of browser window to create. The 'panel' and 'detached_panel' types create a popup unless the '--enable-panels' flag is set.", + "enum": ["normal", "popup", "panel", "detached_panel"] + } + ], + "properties": { + "WINDOW_ID_NONE": { + "value": -1, + "description": "The windowId value that represents the absence of a browser window." + }, + "WINDOW_ID_CURRENT": { + "value": -2, + "description": "The windowId value that represents the $(topic:current-window)[current window]." + } + }, + "functions": [ + { + "name": "get", + "type": "function", + "description": "Gets details about a window.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "windowId", + "minimum": -2 + }, + { + "type": "object", + "name": "getInfo", + "optional": true, + "description": "", + "properties": { + "populate": { + "type": "boolean", + "optional": true, + "description": "If true, the $(ref:windows.Window) object will have a tabs property that contains a list of the $(ref:tabs.Tab) objects. The Tab objects only contain the url, title and favIconUrl properties if the extension's manifest file includes the \"tabs\" permission." + }, + "windowTypes": { + "type": "array", + "items": { + "$ref": "WindowType" + }, + "optional": true, + "description": "If set, the $(ref:windows.Window) returned will be filtered based on its type. If unset the default filter is set to ['app', 'normal', 'panel', 'popup'], with 'app' and 'panel' window types limited to the extension's own windows." + } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "window", + "$ref": "Window" + } + ] + } + ] + }, + { + "name": "getCurrent", + "type": "function", + "description": "Gets the $(topic:current-window)[current window].", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "getInfo", + "optional": true, + "description": "", + "properties": { + "populate": { + "type": "boolean", + "optional": true, + "description": "If true, the $(ref:windows.Window) object will have a tabs property that contains a list of the $(ref:tabs.Tab) objects. The Tab objects only contain the url, title and favIconUrl properties if the extension's manifest file includes the \"tabs\" permission." + }, + "windowTypes": { + "type": "array", + "items": { "$ref": "WindowType" }, + "optional": true, + "description": "If set, the $(ref:windows.Window) returned will be filtered based on its type. If unset the default filter is set to ['app', 'normal', 'panel', 'popup'], with 'app' and 'panel' window types limited to the extension's own windows." + } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "window", + "$ref": "Window" + } + ] + } + ] + }, + { + "name": "getLastFocused", + "type": "function", + "description": "Gets the window that was most recently focused — typically the window 'on top'.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "getInfo", + "optional": true, + "description": "", + "properties": { + "populate": { + "type": "boolean", + "optional": true, + "description": "If true, the $(ref:windows.Window) object will have a tabs property that contains a list of the $(ref:tabs.Tab) objects. The Tab objects only contain the url, title and favIconUrl properties if the extension's manifest file includes the \"tabs\" permission." + }, + "windowTypes": { + "type": "array", + "items": { "$ref": "WindowType" }, + "optional": true, + "description": "If set, the $(ref:windows.Window) returned will be filtered based on its type. If unset the default filter is set to ['app', 'normal', 'panel', 'popup'], with 'app' and 'panel' window types limited to the extension's own windows." + } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "window", + "$ref": "Window" + } + ] + } + ] + }, + { + "name": "getAll", + "type": "function", + "description": "Gets all windows.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "getInfo", + "optional": true, + "description": "", + "properties": { + "populate": { + "type": "boolean", + "optional": true, + "description": "If true, each $(ref:windows.Window) object will have a tabs property that contains a list of the $(ref:tabs.Tab) objects for that window. The Tab objects only contain the url, title and favIconUrl properties if the extension's manifest file includes the \"tabs\" permission." + }, + "windowTypes": { + "type": "array", + "items": { "$ref": "WindowType" }, + "optional": true, + "description": "If set, the $(ref:windows.Window) returned will be filtered based on its type. If unset the default filter is set to ['app', 'normal', 'panel', 'popup'], with 'app' and 'panel' window types limited to the extension's own windows." + } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "windows", + "type": "array", + "items": { "$ref": "Window" } + } + ] + } + ] + }, + { + "name": "create", + "type": "function", + "description": "Creates (opens) a new browser with any optional sizing, position or default URL provided.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "createData", + "optional": true, + "default": {}, + "properties": { + "url": { + "description": "A URL or array of URLs to open as tabs in the window. Fully-qualified URLs must include a scheme (i.e. 'http://www.google.com', not 'www.google.com'). Relative URLs will be relative to the current page within the extension. Defaults to the New Tab Page.", + "optional": true, + "choices": [ + { "type": "string", "format": "relativeUrl" }, + { + "type": "array", + "items": { "type": "string", "format": "relativeUrl" } + } + ] + }, + "tabId": { + "type": "integer", + "minimum": 0, + "optional": true, + "description": "The id of the tab for which you want to adopt to the new window." + }, + "left": { + "type": "integer", + "optional": true, + "description": "The number of pixels to position the new window from the left edge of the screen. If not specified, the new window is offset naturally from the last focused window. This value is ignored for panels." + }, + "top": { + "type": "integer", + "optional": true, + "description": "The number of pixels to position the new window from the top edge of the screen. If not specified, the new window is offset naturally from the last focused window. This value is ignored for panels." + }, + "width": { + "type": "integer", + "minimum": 0, + "optional": true, + "description": "The width in pixels of the new window, including the frame. If not specified defaults to a natural width." + }, + "height": { + "type": "integer", + "minimum": 0, + "optional": true, + "description": "The height in pixels of the new window, including the frame. If not specified defaults to a natural height." + }, + "focused": { + "unsupported": true, + "type": "boolean", + "optional": true, + "description": "If true, opens an active window. If false, opens an inactive window." + }, + "incognito": { + "type": "boolean", + "optional": true, + "description": "Whether the new window should be an incognito window." + }, + "type": { + "$ref": "CreateType", + "optional": true, + "description": "Specifies what type of browser window to create. The 'panel' and 'detached_panel' types create a popup unless the '--enable-panels' flag is set." + }, + "state": { + "$ref": "WindowState", + "optional": true, + "description": "The initial state of the window. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined with 'left', 'top', 'width' or 'height'." + }, + "allowScriptsToClose": { + "type": "boolean", + "optional": true, + "description": "Allow scripts to close the window." + } + }, + "optional": true + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "window", + "$ref": "Window", + "description": "Contains details about the created window.", + "optional": true + } + ] + } + ] + }, + { + "name": "update", + "type": "function", + "description": "Updates the properties of a window. Specify only the properties that you want to change; unspecified properties will be left unchanged.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "windowId", + "minimum": -2 + }, + { + "type": "object", + "name": "updateInfo", + "properties": { + "left": { + "type": "integer", + "optional": true, + "description": "The offset from the left edge of the screen to move the window to in pixels. This value is ignored for panels." + }, + "top": { + "type": "integer", + "optional": true, + "description": "The offset from the top edge of the screen to move the window to in pixels. This value is ignored for panels." + }, + "width": { + "type": "integer", + "minimum": 0, + "optional": true, + "description": "The width to resize the window to in pixels. This value is ignored for panels." + }, + "height": { + "type": "integer", + "minimum": 0, + "optional": true, + "description": "The height to resize the window to in pixels. This value is ignored for panels." + }, + "focused": { + "type": "boolean", + "optional": true, + "description": "If true, brings the window to the front. If false, brings the next window in the z-order to the front." + }, + "drawAttention": { + "type": "boolean", + "optional": true, + "description": "If true, causes the window to be displayed in a manner that draws the user's attention to the window, without changing the focused window. The effect lasts until the user changes focus to the window. This option has no effect if the window already has focus. Set to false to cancel a previous draw attention request." + }, + "state": { + "$ref": "WindowState", + "optional": true, + "description": "The new state of the window. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined with 'left', 'top', 'width' or 'height'." + } + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "window", + "$ref": "Window" + } + ] + } + ] + }, + { + "name": "remove", + "type": "function", + "description": "Removes (closes) a window, and all the tabs inside it.", + "async": "callback", + "parameters": [ + { + "type": "integer", + "name": "windowId", + "minimum": 0 + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + } + ], + "events": [ + { + "name": "onCreated", + "type": "function", + "description": "Fired when a window is created.", + "filters": [ + { + "name": "windowTypes", + "type": "array", + "items": { "$ref": "WindowType" }, + "description": "Conditions that the window's type being created must satisfy. By default it will satisfy ['app', 'normal', 'panel', 'popup'], with 'app' and 'panel' window types limited to the extension's own windows." + } + ], + "parameters": [ + { + "$ref": "Window", + "name": "window", + "description": "Details of the window that was created." + } + ] + }, + { + "name": "onRemoved", + "type": "function", + "description": "Fired when a window is removed (closed).", + "filters": [ + { + "name": "windowTypes", + "type": "array", + "items": { "$ref": "WindowType" }, + "description": "Conditions that the window's type being removed must satisfy. By default it will satisfy ['app', 'normal', 'panel', 'popup'], with 'app' and 'panel' window types limited to the extension's own windows." + } + ], + "parameters": [ + { + "type": "integer", + "name": "windowId", + "minimum": 0, + "description": "ID of the removed window." + } + ] + }, + { + "name": "onFocusChanged", + "type": "function", + "description": "Fired when the currently focused window changes. Will be $(ref:windows.WINDOW_ID_NONE) if all browser windows have lost focus. Note: On some Linux window managers, WINDOW_ID_NONE will always be sent immediately preceding a switch from one browser window to another.", + "filters": [ + { + "name": "windowTypes", + "type": "array", + "items": { "$ref": "WindowType" }, + "description": "Conditions that the window's type being removed must satisfy. By default it will satisfy ['app', 'normal', 'panel', 'popup'], with 'app' and 'panel' window types limited to the extension's own windows." + } + ], + "parameters": [ + { + "type": "integer", + "name": "windowId", + "minimum": -1, + "description": "ID of the newly focused window." + } + ] + } + ] + } +] diff --git a/application/basilisk/configure.in b/application/basilisk/configure.in index 4e7a06390..8527d218c 100644 --- a/application/basilisk/configure.in +++ b/application/basilisk/configure.in @@ -16,3 +16,16 @@ AC_SUBST(MC_BASILISK) dnl Optional parts of the build. +dnl ======================================================== +dnl = Disable WebExtensions +dnl ======================================================== +MOZ_ARG_DISABLE_BOOL(webextensions, +[ --disable-webextensions Disable WebExtensions], + MOZ_WEBEXTENSIONS=, + MOZ_WEBEXTENSIONS=1) + +if test -n "$MOZ_WEBEXTENSIONS"; then + AC_DEFINE(MOZ_WEBEXTENSIONS) +fi + +AC_SUBST(MOZ_WEBEXTENSIONS) \ No newline at end of file diff --git a/application/basilisk/confvars.sh b/application/basilisk/confvars.sh index 2df7e826a..da12a03d0 100644 --- a/application/basilisk/confvars.sh +++ b/application/basilisk/confvars.sh @@ -51,6 +51,7 @@ MOZ_APP_STATIC_INI=1 MOZ_WEBGL_CONFORMANT=1 MOZ_JSDOWNLOADS=1 MOZ_WEBRTC=1 +MOZ_WEBEXTENSIONS=1 MOZ_DEVTOOLS=1 MOZ_SERVICES_COMMON=1 MOZ_SERVICES_SYNC=1 diff --git a/application/basilisk/installer/package-manifest.in b/application/basilisk/installer/package-manifest.in index fa3d55f9f..8318a610a 100644 --- a/application/basilisk/installer/package-manifest.in +++ b/application/basilisk/installer/package-manifest.in @@ -397,9 +397,15 @@ @RESPATH@/components/addonManager.js @RESPATH@/components/amContentHandler.js @RESPATH@/components/amInstallTrigger.js +#ifdef MOZ_WEBEXTENSIONS +@RESPATH@/components/amWebAPI.js +#endif @RESPATH@/components/amWebInstallListener.js @RESPATH@/components/nsBlocklistService.js @RESPATH@/components/blocklist.manifest +#ifdef MOZ_WEBEXTENSIONS +@RESPATH@/components/nsBlocklistServiceContent.js +#endif #ifdef MOZ_UPDATER @RESPATH@/components/nsUpdateService.manifest @RESPATH@/components/nsUpdateService.js @@ -548,6 +554,12 @@ @RESPATH@/components/TestInterfaceJSMaplike.js #endif +#ifdef MOZ_WEBEXTENSIONS +; [Extensions] +@RESPATH@/components/extensions-toolkit.manifest +@RESPATH@/browser/components/extensions-browser.manifest +#endif + ; Modules @RESPATH@/browser/modules/* @RESPATH@/modules/* diff --git a/devtools/server/actors/moz.build b/devtools/server/actors/moz.build index 085d003cf..ddefc3e9e 100644 --- a/devtools/server/actors/moz.build +++ b/devtools/server/actors/moz.build @@ -67,6 +67,6 @@ DevToolsModules( 'worker.js', ) -FINAL_TARGET_FILES.chrome.devtools.modules.devtools.server.actors += [ +FINAL_TARGET_PP_FILES.chrome.devtools.modules.devtools.server.actors += [ 'webbrowser.js', ] \ No newline at end of file diff --git a/devtools/server/actors/webbrowser.js b/devtools/server/actors/webbrowser.js index e7981e163..dffe49b91 100644 --- a/devtools/server/actors/webbrowser.js +++ b/devtools/server/actors/webbrowser.js @@ -30,6 +30,9 @@ loader.lazyRequireGetter(this, "WorkerActorList", "devtools/server/actors/worker loader.lazyRequireGetter(this, "ServiceWorkerRegistrationActorList", "devtools/server/actors/worker", true); loader.lazyRequireGetter(this, "ProcessActorList", "devtools/server/actors/process", true); loader.lazyImporter(this, "AddonManager", "resource://gre/modules/AddonManager.jsm"); +#ifdef MOZ_WEBEXTENSIONS +loader.lazyImporter(this, "ExtensionContent", "resource://gre/modules/ExtensionContent.jsm"); +#endif // Assumptions on events module: // events needs to be dispatched synchronously, @@ -981,6 +984,21 @@ TabActor.prototype = { return null; }, +#ifdef MOZ_WEBEXTENSIONS + /** + * Getter for the WebExtensions ContentScript globals related to the + * current tab content's DOM window. + */ + get webextensionsContentScriptGlobals() { + // Ignore xpcshell runtime which spawn TabActors without a window. + if (this.window) { + return ExtensionContent.getContentScriptGlobalsForWindow(this.window); + } + + return []; + }, +#endif + /** * Getter for the list of all content DOM windows in this tabActor * @return {Array} diff --git a/dom/webidl/AddonEvent.webidl b/dom/webidl/AddonEvent.webidl new file mode 100644 index 000000000..235f81ec2 --- /dev/null +++ b/dom/webidl/AddonEvent.webidl @@ -0,0 +1,12 @@ +[ Func="mozilla::AddonManagerWebAPI::IsAPIEnabled", + Constructor(DOMString type, AddonEventInit eventInitDict)] +interface AddonEvent : Event { + readonly attribute DOMString id; + readonly attribute boolean needsRestart; +}; + +dictionary AddonEventInit : EventInit { + required DOMString id; + required boolean needsRestart; +}; + diff --git a/dom/webidl/AddonManager.webidl b/dom/webidl/AddonManager.webidl new file mode 100644 index 000000000..02c7953e6 --- /dev/null +++ b/dom/webidl/AddonManager.webidl @@ -0,0 +1,91 @@ +/* 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/. + */ + +/* We need a JSImplementation but cannot get one without a contract ID. + Since Addon and AddonInstall are only ever created from JS they don't need + real contract IDs. */ +[ChromeOnly, JSImplementation="dummy"] +interface Addon { + // The add-on's ID. + readonly attribute DOMString id; + // The add-on's version. + readonly attribute DOMString version; + // The add-on's type (extension, theme, etc.). + readonly attribute DOMString type; + // The add-on's name in the current locale. + readonly attribute DOMString name; + // The add-on's description in the current locale. + readonly attribute DOMString description; + // If the user has enabled this add-on, note that it still may not be running + // depending on whether enabling requires a restart or if the add-on is + // incompatible in some way. + readonly attribute boolean isEnabled; + // If the add-on is currently active in the browser. + readonly attribute boolean isActive; + // If the add-on may be uninstalled + readonly attribute boolean canUninstall; + + Promise uninstall(); + Promise setEnabled(boolean value); +}; + +[ChromeOnly, JSImplementation="dummy"] +interface AddonInstall : EventTarget { + // One of the STATE_* symbols from AddonManager.jsm + readonly attribute DOMString state; + // One of the ERROR_* symbols from AddonManager.jsm, or null + readonly attribute DOMString? error; + // How many bytes have been downloaded + readonly attribute long long progress; + // How many total bytes will need to be downloaded or -1 if unknown + readonly attribute long long maxProgress; + + Promise install(); + Promise cancel(); +}; + +dictionary addonInstallOptions { + required DOMString url; + // If a non-empty string is passed for "hash", it is used to verify the + // checksum of the downloaded XPI before installing. If is omitted or if + // it is null or empty string, no checksum verification is performed. + DOMString? hash = null; +}; + +[HeaderFile="mozilla/AddonManagerWebAPI.h", + Func="mozilla::AddonManagerWebAPI::IsAPIEnabled", + NavigatorProperty="mozAddonManager", + JSImplementation="@mozilla.org/addon-web-api/manager;1"] +interface AddonManager : EventTarget { + /** + * Gets information about an add-on + * + * @param id + * The ID of the add-on to test for. + * @return A promise. It will resolve to an Addon if the add-on is installed. + */ + Promise getAddonByID(DOMString id); + + /** + * Creates an AddonInstall object for a given URL. + * + * @param options + * Only one supported option: 'url', the URL of the addon to install. + * @return A promise that resolves to an instance of AddonInstall. + */ + Promise createInstall(optional addonInstallOptions options); + + /* Hooks for managing event listeners */ + [ChromeOnly] + void eventListenerWasAdded(DOMString type); + [ChromeOnly] + void eventListenerWasRemoved(DOMString type); +}; + +[ChromeOnly,Exposed=System,HeaderFile="mozilla/AddonManagerWebAPI.h"] +interface AddonManagerPermissions { + static boolean isHostPermitted(DOMString host); +}; + diff --git a/dom/webidl/moz.build b/dom/webidl/moz.build index aae7e479c..06fea2f20 100644 --- a/dom/webidl/moz.build +++ b/dom/webidl/moz.build @@ -591,6 +591,9 @@ WEBIDL_FILES = [ 'XULElement.webidl', ] +if CONFIG['MOZ_WEBEXTENSIONS']: + WEBIDL_FILES += ['AddonManager.webidl'] + if CONFIG['MOZ_AUDIO_CHANNEL_MANAGER']: WEBIDL_FILES += [ 'AudioChannelManager.webidl', @@ -719,6 +722,9 @@ GENERATED_EVENTS_WEBIDL_FILES = [ 'WebGLContextEvent.webidl', ] +if CONFIG['MOZ_WEBEXTENSIONS']: + GENERATED_EVENTS_WEBIDL_FILES += ['AddonEvent.webidl'] + if CONFIG['MOZ_WEBRTC']: GENERATED_EVENTS_WEBIDL_FILES += [ 'RTCDataChannelEvent.webidl', diff --git a/toolkit/components/blocklist/blocklist.manifest b/toolkit/components/blocklist/blocklist.manifest index 6b63d6072..c770b4e7d 100644 --- a/toolkit/components/blocklist/blocklist.manifest +++ b/toolkit/components/blocklist/blocklist.manifest @@ -1,5 +1,7 @@ component {66354bc9-7ed1-4692-ae1d-8da97d6b205e} nsBlocklistService.js process=main contract @mozilla.org/extensions/blocklist;1 {66354bc9-7ed1-4692-ae1d-8da97d6b205e} process=main category profile-after-change nsBlocklistService @mozilla.org/extensions/blocklist;1 process=main +component {e0a106ed-6ad4-47a4-b6af-2f1c8aa4712d} nsBlocklistServiceContent.js process=content +contract @mozilla.org/extensions/blocklist;1 {e0a106ed-6ad4-47a4-b6af-2f1c8aa4712d} process=content category update-timer nsBlocklistService @mozilla.org/extensions/blocklist;1,getService,blocklist-background-update-timer,extensions.blocklist.interval,86400 \ No newline at end of file diff --git a/toolkit/components/blocklist/moz.build b/toolkit/components/blocklist/moz.build index 0016e74c2..3dc3be5ba 100644 --- a/toolkit/components/blocklist/moz.build +++ b/toolkit/components/blocklist/moz.build @@ -6,6 +6,7 @@ EXTRA_COMPONENTS += [ 'blocklist.manifest', + 'nsBlocklistServiceContent.js', ] EXTRA_PP_COMPONENTS += [ diff --git a/toolkit/components/blocklist/nsBlocklistService.js b/toolkit/components/blocklist/nsBlocklistService.js index 1cd2ed806..891346b72 100644 --- a/toolkit/components/blocklist/nsBlocklistService.js +++ b/toolkit/components/blocklist/nsBlocklistService.js @@ -24,8 +24,13 @@ try { XPCOMUtils.defineLazyModuleGetter(this, "FileUtils", "resource://gre/modules/FileUtils.jsm"); +#ifdef MOZ_WEBEXTENSIONS +XPCOMUtils.defineLazyModuleGetter(this, "UpdateUtils", + "resource://gre/modules/UpdateUtils.jsm"); +#else XPCOMUtils.defineLazyModuleGetter(this, "UpdateChannel", "resource://gre/modules/UpdateChannel.jsm"); +#endif XPCOMUtils.defineLazyModuleGetter(this, "OS", "resource://gre/modules/osfile.jsm"); XPCOMUtils.defineLazyModuleGetter(this, "ServiceRequest", @@ -566,7 +571,11 @@ Blocklist.prototype = { dsURI = dsURI.replace(/%BUILD_TARGET%/g, gApp.OS + "_" + gABI); dsURI = dsURI.replace(/%OS_VERSION%/g, gOSVersion); dsURI = dsURI.replace(/%LOCALE%/g, getLocale()); +#ifdef MOZ_WEBEXTENSIONS + dsURI = dsURI.replace(/%CHANNEL%/g, UpdateUtils.UpdateChannel); +#else dsURI = dsURI.replace(/%CHANNEL%/g, UpdateChannel.get()); +#endif dsURI = dsURI.replace(/%PLATFORM_VERSION%/g, gApp.platformVersion); dsURI = dsURI.replace(/%DISTRIBUTION%/g, getDistributionPrefValue(PREF_APP_DISTRIBUTION)); diff --git a/toolkit/components/blocklist/nsBlocklistServiceContent.js b/toolkit/components/blocklist/nsBlocklistServiceContent.js new file mode 100644 index 000000000..1752924b5 --- /dev/null +++ b/toolkit/components/blocklist/nsBlocklistServiceContent.js @@ -0,0 +1,113 @@ +/* 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 Cc = Components.classes; +const Ci = Components.interfaces; +const Cr = Components.results; + +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); +Components.utils.import("resource://gre/modules/Services.jsm"); + +const kMissingAPIMessage = "Unsupported blocklist call in the child process." + +/* + * A lightweight blocklist proxy for the content process that traps plugin + * related blocklist checks and forwards them to the parent. This interface is + * primarily designed to insure overlays work.. it does not control plugin + * or addon loading. + */ + +function Blocklist() { + this.init(); +} + +Blocklist.prototype = { + classID: Components.ID("{e0a106ed-6ad4-47a4-b6af-2f1c8aa4712d}"), + + QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, + Ci.nsIBlocklistService]), + + init: function() { + Services.cpmm.addMessageListener("Blocklist:blocklistInvalidated", this); + Services.obs.addObserver(this, "xpcom-shutdown", false); + }, + + uninit: function() { + Services.cpmm.removeMessageListener("Blocklist:blocklistInvalidated", this); + Services.obs.removeObserver(this, "xpcom-shutdown", false); + }, + + observe: function(aSubject, aTopic, aData) { + switch (aTopic) { + case "xpcom-shutdown": + this.uninit(); + break; + } + }, + + // Message manager message handlers + receiveMessage: function(aMsg) { + switch (aMsg.name) { + case "Blocklist:blocklistInvalidated": + Services.obs.notifyObservers(null, "blocklist-updated", null); + Services.cpmm.sendAsyncMessage("Blocklist:content-blocklist-updated"); + break; + default: + throw new Error("Unknown blocklist message received from content: " + aMsg.name); + } + }, + + /* + * A helper that queries key data from a plugin or addon object + * and generates a simple data wrapper suitable for ipc. We hand + * these directly to the nsBlockListService in the parent which + * doesn't query for much.. allowing us to get away with this. + */ + flattenObject: function(aTag) { + // Based on debugging the nsBlocklistService, these are the props the + // parent side will check on our objects. + let props = ["name", "description", "filename", "version"]; + let dataWrapper = {}; + for (let prop of props) { + dataWrapper[prop] = aTag[prop]; + } + return dataWrapper; + }, + + // We support the addon methods here for completeness, but content currently + // only calls getPluginBlocklistState. + + isAddonBlocklisted: function(aAddon, aAppVersion, aToolkitVersion) { + return true; + }, + + getAddonBlocklistState: function(aAddon, aAppVersion, aToolkitVersion) { + return Components.interfaces.nsIBlocklistService.STATE_BLOCKED; + }, + + // There are a few callers in layout that rely on this. + getPluginBlocklistState: function(aPluginTag, aAppVersion, aToolkitVersion) { + return Services.cpmm.sendSyncMessage("Blocklist:getPluginBlocklistState", { + addonData: this.flattenObject(aPluginTag), + appVersion: aAppVersion, + toolkitVersion: aToolkitVersion + })[0]; + }, + + getAddonBlocklistURL: function(aAddon, aAppVersion, aToolkitVersion) { + throw new Error(kMissingAPIMessage); + }, + + getPluginBlocklistURL: function(aPluginTag) { + throw new Error(kMissingAPIMessage); + }, + + getPluginInfoURL: function(aPluginTag) { + throw new Error(kMissingAPIMessage); + } +}; + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([Blocklist]); diff --git a/toolkit/components/build/nsToolkitCompsModule.cpp b/toolkit/components/build/nsToolkitCompsModule.cpp index a4293c6f9..33c604c4e 100644 --- a/toolkit/components/build/nsToolkitCompsModule.cpp +++ b/toolkit/components/build/nsToolkitCompsModule.cpp @@ -39,6 +39,9 @@ #include "nsBrowserStatusFilter.h" #include "mozilla/FinalizationWitnessService.h" #include "mozilla/NativeOSFileInternals.h" +#ifdef MOZ_WEBEXTENSIONS +#include "mozilla/AddonContentPolicy.h" +#endif #include "mozilla/AddonPathService.h" #if defined(XP_WIN) @@ -129,6 +132,9 @@ NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(FinalizationWitnessService, Init) NS_GENERIC_FACTORY_CONSTRUCTOR(NativeOSFileInternalsService) NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(NativeFileWatcherService, Init) +#ifdef MOZ_WEBEXTENSIONS +NS_GENERIC_FACTORY_CONSTRUCTOR(AddonContentPolicy) +#endif NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(AddonPathService, AddonPathService::GetInstance) NS_DEFINE_NAMED_CID(NS_TOOLKIT_APPSTARTUP_CID); @@ -165,6 +171,9 @@ NS_DEFINE_NAMED_CID(NS_UPDATEPROCESSOR_CID); #endif NS_DEFINE_NAMED_CID(FINALIZATIONWITNESSSERVICE_CID); NS_DEFINE_NAMED_CID(NATIVE_OSFILE_INTERNALS_SERVICE_CID); +#ifdef MOZ_WEBEXTENSIONS +NS_DEFINE_NAMED_CID(NS_ADDONCONTENTPOLICY_CID); +#endif NS_DEFINE_NAMED_CID(NS_ADDON_PATH_SERVICE_CID); NS_DEFINE_NAMED_CID(NATIVE_FILEWATCHER_SERVICE_CID); @@ -202,6 +211,9 @@ static const Module::CIDEntry kToolkitCIDs[] = { #endif { &kFINALIZATIONWITNESSSERVICE_CID, false, nullptr, FinalizationWitnessServiceConstructor }, { &kNATIVE_OSFILE_INTERNALS_SERVICE_CID, false, nullptr, NativeOSFileInternalsServiceConstructor }, +#ifdef MOZ_WEBEXTENSIONS + { &kNS_ADDONCONTENTPOLICY_CID, false, nullptr, AddonContentPolicyConstructor }, +#endif { &kNS_ADDON_PATH_SERVICE_CID, false, nullptr, AddonPathServiceConstructor }, { &kNATIVE_FILEWATCHER_SERVICE_CID, false, nullptr, NativeFileWatcherServiceConstructor }, { nullptr } @@ -241,12 +253,18 @@ static const Module::ContractIDEntry kToolkitContracts[] = { #endif { FINALIZATIONWITNESSSERVICE_CONTRACTID, &kFINALIZATIONWITNESSSERVICE_CID }, { NATIVE_OSFILE_INTERNALS_SERVICE_CONTRACTID, &kNATIVE_OSFILE_INTERNALS_SERVICE_CID }, +#ifdef MOZ_WEBEXTENSIONS + { NS_ADDONCONTENTPOLICY_CONTRACTID, &kNS_ADDONCONTENTPOLICY_CID }, +#endif { NS_ADDONPATHSERVICE_CONTRACTID, &kNS_ADDON_PATH_SERVICE_CID }, { NATIVE_FILEWATCHER_SERVICE_CONTRACTID, &kNATIVE_FILEWATCHER_SERVICE_CID }, { nullptr } }; static const mozilla::Module::CategoryEntry kToolkitCategories[] = { +#ifdef MOZ_WEBEXTENSIONS + { "content-policy", NS_ADDONCONTENTPOLICY_CONTRACTID, NS_ADDONCONTENTPOLICY_CONTRACTID }, +#endif { nullptr } }; diff --git a/toolkit/components/moz.build b/toolkit/components/moz.build index 7173ca4e7..953e6c6e3 100644 --- a/toolkit/components/moz.build +++ b/toolkit/components/moz.build @@ -66,6 +66,9 @@ DIRS += [ 'xulstore' ] +if CONFIG['MOZ_WEBEXTENSIONS']: + DIRS += ['webextensions'] + DIRS += ['mozintl'] if not CONFIG['MOZ_FENNEC']: diff --git a/toolkit/components/webextensions/.eslintrc.js b/toolkit/components/webextensions/.eslintrc.js new file mode 100644 index 000000000..70f91ab6d --- /dev/null +++ b/toolkit/components/webextensions/.eslintrc.js @@ -0,0 +1,494 @@ +"use strict"; + +module.exports = { // eslint-disable-line no-undef + "extends": "../../.eslintrc.js", + + "parserOptions": { + "ecmaVersion": 8, + }, + + "globals": { + "Cc": true, + "Ci": true, + "Components": true, + "Cr": true, + "Cu": true, + "dump": true, + "TextDecoder": false, + "TextEncoder": false, + // Specific to WebExtensions: + "Extension": true, + "ExtensionManagement": true, + "extensions": true, + "global": true, + "NetUtil": true, + "openOptionsPage": true, + "require": false, + "runSafe": true, + "runSafeSync": true, + "runSafeSyncWithoutClone": true, + "Services": true, + "TabManager": true, + "WindowListManager": true, + "XPCOMUtils": true, + }, + + "rules": { + // Rules from the mozilla plugin + "mozilla/balanced-listeners": "error", + "mozilla/no-aArgs": "error", + "mozilla/no-cpows-in-tests": "warn", + "mozilla/var-only-at-top-level": "warn", + + "valid-jsdoc": ["error", { + "prefer": { + "return": "returns", + }, + "preferType": { + "Boolean": "boolean", + "Number": "number", + "String": "string", + "bool": "boolean", + }, + "requireParamDescription": false, + "requireReturn": false, + "requireReturnDescription": false, + }], + + // Braces only needed for multi-line arrow function blocks + // "arrow-body-style": ["error", "as-needed"], + + // Require spacing around => + "arrow-spacing": "error", + + // Always require spacing around a single line block + "block-spacing": "warn", + + // Forbid spaces inside the square brackets of array literals. + "array-bracket-spacing": ["error", "never"], + + // Forbid spaces inside the curly brackets of object literals. + "object-curly-spacing": ["error", "never"], + + // No space padding in parentheses + "space-in-parens": ["error", "never"], + + // Enforce one true brace style (opening brace on the same line) and avoid + // start and end braces on the same line. + "brace-style": ["error", "1tbs", {"allowSingleLine": true}], + + // No space before always a space after a comma + "comma-spacing": ["error", {"before": false, "after": true}], + + // Commas at the end of the line not the start + "comma-style": "error", + + // Don't require spaces around computed properties + "computed-property-spacing": ["error", "never"], + + // Functions are not required to consistently return something or nothing + "consistent-return": "off", + + // Require braces around blocks that start a new line + "curly": ["error", "all"], + + // Always require a trailing EOL + "eol-last": "error", + + // Require function* name() + "generator-star-spacing": ["error", {"before": false, "after": true}], + + // Two space indent + "indent": ["error", 2, {"SwitchCase": 1}], + + // Space after colon not before in property declarations + "key-spacing": ["error", {"beforeColon": false, "afterColon": true, "mode": "minimum"}], + + // Require spaces before and after finally, catch, etc. + "keyword-spacing": "error", + + // Unix linebreaks + "linebreak-style": ["error", "unix"], + + // Always require parenthesis for new calls + "new-parens": "error", + + // Use [] instead of Array() + "no-array-constructor": "error", + + // No duplicate arguments in function declarations + "no-dupe-args": "error", + + // No duplicate keys in object declarations + "no-dupe-keys": "error", + + // No duplicate cases in switch statements + "no-duplicate-case": "error", + + // If an if block ends with a return no need for an else block + // "no-else-return": "error", + + // Disallow empty statements. This will report an error for: + // try { something(); } catch (e) {} + // but will not report it for: + // try { something(); } catch (e) { /* Silencing the error because ...*/ } + // which is a valid use case. + "no-empty": "error", + + // No empty character classes in regex + "no-empty-character-class": "error", + + // Disallow empty destructuring + "no-empty-pattern": "error", + + // No assiging to exception variable + "no-ex-assign": "error", + + // No using !! where casting to boolean is already happening + "no-extra-boolean-cast": "warn", + + // No double semicolon + "no-extra-semi": "error", + + // No overwriting defined functions + "no-func-assign": "error", + + // No invalid regular expresions + "no-invalid-regexp": "error", + + // No odd whitespace characters + "no-irregular-whitespace": "error", + + // No single if block inside an else block + "no-lonely-if": "warn", + + // No mixing spaces and tabs in indent + "no-mixed-spaces-and-tabs": ["error", "smart-tabs"], + + // Disallow use of multiple spaces (sometimes used to align const values, + // array or object items, etc.). It's hard to maintain and doesn't add that + // much benefit. + "no-multi-spaces": "warn", + + // No reassigning native JS objects + "no-native-reassign": "error", + + // Nested ternary statements are confusing + "no-nested-ternary": "error", + + // Use {} instead of new Object() + "no-new-object": "error", + + // No Math() or JSON() + "no-obj-calls": "error", + + // No octal literals + "no-octal": "error", + + // No redeclaring variables + "no-redeclare": "error", + + // No unnecessary comparisons + "no-self-compare": "error", + + // No spaces between function name and parentheses + "no-spaced-func": "warn", + + // No trailing whitespace + "no-trailing-spaces": "error", + + // Error on newline where a semicolon is needed + "no-unexpected-multiline": "error", + + // No unreachable statements + "no-unreachable": "error", + + // No expressions where a statement is expected + "no-unused-expressions": "error", + + // No declaring variables that are never used + "no-unused-vars": ["error", {"args": "none", "varsIgnorePattern": "^(Cc|Ci|Cr|Cu|EXPORTED_SYMBOLS)$"}], + + // No using variables before defined + "no-use-before-define": "error", + + // No using with + "no-with": "error", + + // Always require semicolon at end of statement + "semi": ["error", "always"], + + // Require space before blocks + "space-before-blocks": "error", + + // Never use spaces before function parentheses + "space-before-function-paren": ["error", {"anonymous": "never", "named": "never"}], + + // Require spaces around operators, except for a|0. + "space-infix-ops": ["error", {"int32Hint": true}], + + // ++ and -- should not need spacing + "space-unary-ops": ["warn", {"nonwords": false, "words": true, "overrides": {"typeof": false}}], + + // No comparisons to NaN + "use-isnan": "error", + + // Only check typeof against valid results + "valid-typeof": "error", + + // Disallow using variables outside the blocks they are defined (especially + // since only let and const are used, see "no-var"). + "block-scoped-var": "error", + + // Allow trailing commas for easy list extension. Having them does not + // impair readability, but also not required either. + "comma-dangle": ["error", "always-multiline"], + + // Warn about cyclomatic complexity in functions. + "complexity": "warn", + + // Don't warn for inconsistent naming when capturing this (not so important + // with auto-binding fat arrow functions). + // "consistent-this": ["error", "self"], + + // Don't require a default case in switch statements. Avoid being forced to + // add a bogus default when you know all possible cases are handled. + "default-case": "off", + + // Enforce dots on the next line with property name. + "dot-location": ["error", "property"], + + // Encourage the use of dot notation whenever possible. + "dot-notation": "error", + + // Allow using == instead of ===, in the interest of landing something since + // the devtools codebase is split on convention here. + "eqeqeq": "off", + + // Don't require function expressions to have a name. + // This makes the code more verbose and hard to read. Our engine already + // does a fantastic job assigning a name to the function, which includes + // the enclosing function name, and worst case you have a line number that + // you can just look up. + "func-names": "off", + + // Allow use of function declarations and expressions. + "func-style": "off", + + // Don't enforce the maximum depth that blocks can be nested. The complexity + // rule is a better rule to check this. + "max-depth": "off", + + // Maximum length of a line. + // Disabled because we exceed this in too many places. + "max-len": [0, 80], + + // Maximum depth callbacks can be nested. + "max-nested-callbacks": ["error", 4], + + // Don't limit the number of parameters that can be used in a function. + "max-params": "off", + + // Don't limit the maximum number of statement allowed in a function. We + // already have the complexity rule that's a better measurement. + "max-statements": "off", + + // Don't require a capital letter for constructors, only check if all new + // operators are followed by a capital letter. Don't warn when capitalized + // functions are used without the new operator. + "new-cap": ["off", {"capIsNew": false}], + + // Allow use of bitwise operators. + "no-bitwise": "off", + + // Disallow use of arguments.caller or arguments.callee. + "no-caller": "error", + + // Disallow the catch clause parameter name being the same as a variable in + // the outer scope, to avoid confusion. + "no-catch-shadow": "off", + + // Disallow assignment in conditional expressions. + "no-cond-assign": "error", + + // Disallow using the console API. + "no-console": "error", + + // Allow using constant expressions in conditions like while (true) + "no-constant-condition": "off", + + // Allow use of the continue statement. + "no-continue": "off", + + // Disallow control characters in regular expressions. + "no-control-regex": "error", + + // Disallow use of debugger. + "no-debugger": "error", + + // Disallow deletion of variables (deleting properties is fine). + "no-delete-var": "error", + + // Allow division operators explicitly at beginning of regular expression. + "no-div-regex": "off", + + // Disallow use of eval(). We have other APIs to evaluate code in content. + "no-eval": "error", + + // Disallow adding to native types + "no-extend-native": "error", + + // Disallow unnecessary function binding. + "no-extra-bind": "error", + + // Allow unnecessary parentheses, as they may make the code more readable. + "no-extra-parens": "off", + + // Disallow fallthrough of case statements, except if there is a comment. + "no-fallthrough": "error", + + // Allow the use of leading or trailing decimal points in numeric literals. + "no-floating-decimal": "off", + + // Allow comments inline after code. + "no-inline-comments": "off", + + // Disallow use of labels for anything other then loops and switches. + "no-labels": ["error", {"allowLoop": true}], + + // Disallow use of multiline strings (use template strings instead). + "no-multi-str": "warn", + + // Disallow multiple empty lines. + "no-multiple-empty-lines": [1, {"max": 2}], + + // Allow reassignment of function parameters. + "no-param-reassign": "off", + + // Allow string concatenation with __dirname and __filename (not a node env). + "no-path-concat": "off", + + // Allow use of unary operators, ++ and --. + "no-plusplus": "off", + + // Allow using process.env (not a node environment). + "no-process-env": "off", + + // Allow using process.exit (not a node environment). + "no-process-exit": "off", + + // Disallow usage of __proto__ property. + "no-proto": "error", + + // Disallow multiple spaces in a regular expression literal. + "no-regex-spaces": "error", + + // Allow reserved words being used as object literal keys. + "no-reserved-keys": "off", + + // Don't restrict usage of specified node modules (not a node environment). + "no-restricted-modules": "off", + + // Disallow use of assignment in return statement. It is preferable for a + // single line of code to have only one easily predictable effect. + "no-return-assign": "error", + + // Don't warn about declaration of variables already declared in the outer scope. + "no-shadow": "off", + + // Disallow shadowing of names such as arguments. + "no-shadow-restricted-names": "error", + + // Allow use of synchronous methods (not a node environment). + "no-sync": "off", + + // Allow the use of ternary operators. + "no-ternary": "off", + + // Disallow throwing literals (eg. throw "error" instead of + // throw new Error("error")). + "no-throw-literal": "error", + + // Disallow use of undeclared variables unless mentioned in a /* global */ + // block. Note that globals from head.js are automatically imported in tests + // by the import-headjs-globals rule form the mozilla eslint plugin. + "no-undef": "error", + + // Allow dangling underscores in identifiers (for privates). + "no-underscore-dangle": "off", + + // Allow use of undefined variable. + "no-undefined": "off", + + // Disallow the use of Boolean literals in conditional expressions. + "no-unneeded-ternary": "error", + + // We use var-only-at-top-level instead of no-var as we allow top level + // vars. + "no-var": "off", + + // Allow using TODO/FIXME comments. + "no-warning-comments": "off", + + // Don't require method and property shorthand syntax for object literals. + // We use this in the code a lot, but not consistently, and this seems more + // like something to check at code review time. + "object-shorthand": "off", + + // Allow more than one variable declaration per function. + "one-var": "off", + + // Disallow padding within blocks. + "padded-blocks": ["warn", "never"], + + // Don't require quotes around object literal property names. + "quote-props": "off", + + // Double quotes should be used. + "quotes": ["warn", "double", {"avoidEscape": true, "allowTemplateLiterals": true}], + + // Require use of the second argument for parseInt(). + "radix": "error", + + // Enforce spacing after semicolons. + "semi-spacing": ["error", {"before": false, "after": true}], + + // Don't require to sort variables within the same declaration block. + // Anyway, one-var is disabled. + "sort-vars": "off", + + // Require a space immediately following the // in a line comment. + "spaced-comment": ["error", "always"], + + // Require "use strict" to be defined globally in the script. + "strict": ["error", "global"], + + // Allow vars to be declared anywhere in the scope. + "vars-on-top": "off", + + // Don't require immediate function invocation to be wrapped in parentheses. + "wrap-iife": "off", + + // Don't require regex literals to be wrapped in parentheses (which + // supposedly prevent them from being mistaken for division operators). + "wrap-regex": "off", + + // Disallow Yoda conditions (where literal value comes first). + "yoda": "error", + + // disallow use of eval()-like methods + "no-implied-eval": "error", + + // Disallow function or variable declarations in nested blocks + "no-inner-declarations": "error", + + // Disallow usage of __iterator__ property + "no-iterator": "error", + + // Disallow labels that share a name with a variable + "no-label-var": "error", + + // Disallow creating new instances of String, Number, and Boolean + "no-new-wrappers": "error", + }, +}; diff --git a/toolkit/components/webextensions/Extension.jsm b/toolkit/components/webextensions/Extension.jsm new file mode 100644 index 000000000..3468f2594 --- /dev/null +++ b/toolkit/components/webextensions/Extension.jsm @@ -0,0 +1,902 @@ +/* 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"; + +this.EXPORTED_SYMBOLS = ["Extension", "ExtensionData"]; + +/* globals Extension ExtensionData */ + +/* + * This file is the main entry point for extensions. When an extension + * loads, its bootstrap.js file creates a Extension instance + * and calls .startup() on it. It calls .shutdown() when the extension + * unloads. Extension manages any extension-specific state in + * the chrome process. + */ + +const Ci = Components.interfaces; +const Cc = Components.classes; +const Cu = Components.utils; +const Cr = Components.results; + +Cu.importGlobalProperties(["TextEncoder"]); + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "AddonManager", + "resource://gre/modules/AddonManager.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "AppConstants", + "resource://gre/modules/AppConstants.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionAPIs", + "resource://gre/modules/ExtensionAPI.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionStorage", + "resource://gre/modules/ExtensionStorage.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionTestCommon", + "resource://testing-common/ExtensionTestCommon.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Locale", + "resource://gre/modules/Locale.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Log", + "resource://gre/modules/Log.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "MatchGlobs", + "resource://gre/modules/MatchPattern.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "MatchPattern", + "resource://gre/modules/MatchPattern.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel", + "resource://gre/modules/MessageChannel.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", + "resource://gre/modules/NetUtil.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "OS", + "resource://gre/modules/osfile.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Preferences", + "resource://gre/modules/Preferences.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "require", + "resource://devtools/shared/Loader.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Schemas", + "resource://gre/modules/Schemas.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Task", + "resource://gre/modules/Task.jsm"); + +Cu.import("resource://gre/modules/ExtensionContent.jsm"); +Cu.import("resource://gre/modules/ExtensionManagement.jsm"); +Cu.import("resource://gre/modules/ExtensionParent.jsm"); +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +XPCOMUtils.defineLazyServiceGetter(this, "uuidGen", + "@mozilla.org/uuid-generator;1", + "nsIUUIDGenerator"); + +var { + GlobalManager, + ParentAPIManager, + apiManager: Management, +} = ExtensionParent; + +const { + EventEmitter, + LocaleData, + getUniqueId, +} = ExtensionUtils; + +XPCOMUtils.defineLazyGetter(this, "console", ExtensionUtils.getConsole); + +const LOGGER_ID_BASE = "addons.webextension."; +const UUID_MAP_PREF = "extensions.webextensions.uuids"; +const LEAVE_STORAGE_PREF = "extensions.webextensions.keepStorageOnUninstall"; +const LEAVE_UUID_PREF = "extensions.webextensions.keepUuidOnUninstall"; + +const COMMENT_REGEXP = new RegExp(String.raw` + ^ + ( + (?: + [^"\n] | + " (?:[^"\\\n] | \\.)* " + )*? + ) + + //.* + `.replace(/\s+/g, ""), "gm"); + +// All moz-extension URIs use a machine-specific UUID rather than the +// extension's own ID in the host component. This makes it more +// difficult for web pages to detect whether a user has a given add-on +// installed (by trying to load a moz-extension URI referring to a +// web_accessible_resource from the extension). UUIDMap.get() +// returns the UUID for a given add-on ID. +var UUIDMap = { + _read() { + let pref = Preferences.get(UUID_MAP_PREF, "{}"); + try { + return JSON.parse(pref); + } catch (e) { + Cu.reportError(`Error parsing ${UUID_MAP_PREF}.`); + return {}; + } + }, + + _write(map) { + Preferences.set(UUID_MAP_PREF, JSON.stringify(map)); + }, + + get(id, create = true) { + let map = this._read(); + + if (id in map) { + return map[id]; + } + + let uuid = null; + if (create) { + uuid = uuidGen.generateUUID().number; + uuid = uuid.slice(1, -1); // Strip { and } off the UUID. + + map[id] = uuid; + this._write(map); + } + return uuid; + }, + + remove(id) { + let map = this._read(); + delete map[id]; + this._write(map); + }, +}; + +// This is the old interface that UUIDMap replaced, to be removed when +// the references listed in bug 1291399 are updated. +/* exported getExtensionUUID */ +function getExtensionUUID(id) { + return UUIDMap.get(id, true); +} + +// For extensions that have called setUninstallURL(), send an event +// so the browser can display the URL. +var UninstallObserver = { + initialized: false, + + init() { + if (!this.initialized) { + AddonManager.addAddonListener(this); + XPCOMUtils.defineLazyPreferenceGetter(this, "leaveStorage", LEAVE_STORAGE_PREF, false); + XPCOMUtils.defineLazyPreferenceGetter(this, "leaveUuid", LEAVE_UUID_PREF, false); + this.initialized = true; + } + }, + + onUninstalling(addon) { + let extension = GlobalManager.extensionMap.get(addon.id); + if (extension) { + // Let any other interested listeners respond + // (e.g., display the uninstall URL) + Management.emit("uninstall", extension); + } + }, + + onUninstalled(addon) { + let uuid = UUIDMap.get(addon.id, false); + if (!uuid) { + return; + } + + if (!this.leaveStorage) { + // Clear browser.local.storage + ExtensionStorage.clear(addon.id); + + // Clear any IndexedDB storage created by the extension + let baseURI = NetUtil.newURI(`moz-extension://${uuid}/`); + let principal = Services.scriptSecurityManager.createCodebasePrincipal( + baseURI, {addonId: addon.id} + ); + Services.qms.clearStoragesForPrincipal(principal); + + // Clear localStorage created by the extension + let attrs = JSON.stringify({addonId: addon.id}); + Services.obs.notifyObservers(null, "clear-origin-attributes-data", attrs); + } + + if (!this.leaveUuid) { + // Clear the entry in the UUID map + UUIDMap.remove(addon.id); + } + }, +}; + +UninstallObserver.init(); + +// Represents the data contained in an extension, contained either +// in a directory or a zip file, which may or may not be installed. +// This class implements the functionality of the Extension class, +// primarily related to manifest parsing and localization, which is +// useful prior to extension installation or initialization. +// +// No functionality of this class is guaranteed to work before +// |readManifest| has been called, and completed. +this.ExtensionData = class { + constructor(rootURI) { + this.rootURI = rootURI; + + this.manifest = null; + this.id = null; + this.uuid = null; + this.localeData = null; + this._promiseLocales = null; + + this.apiNames = new Set(); + this.dependencies = new Set(); + this.permissions = new Set(); + + this.errors = []; + } + + get builtinMessages() { + return null; + } + + get logger() { + let id = this.id || ""; + return Log.repository.getLogger(LOGGER_ID_BASE + id); + } + + // Report an error about the extension's manifest file. + manifestError(message) { + this.packagingError(`Reading manifest: ${message}`); + } + + // Report an error about the extension's general packaging. + packagingError(message) { + this.errors.push(message); + this.logger.error(`Loading extension '${this.id}': ${message}`); + } + + /** + * Returns the moz-extension: URL for the given path within this + * extension. + * + * Must not be called unless either the `id` or `uuid` property has + * already been set. + * + * @param {string} path The path portion of the URL. + * @returns {string} + */ + getURL(path = "") { + if (!(this.id || this.uuid)) { + throw new Error("getURL may not be called before an `id` or `uuid` has been set"); + } + if (!this.uuid) { + this.uuid = UUIDMap.get(this.id); + } + return `moz-extension://${this.uuid}/${path}`; + } + + readDirectory(path) { + return Task.spawn(function* () { + if (this.rootURI instanceof Ci.nsIFileURL) { + let uri = NetUtil.newURI(this.rootURI.resolve("./" + path)); + let fullPath = uri.QueryInterface(Ci.nsIFileURL).file.path; + + let iter = new OS.File.DirectoryIterator(fullPath); + let results = []; + + try { + yield iter.forEach(entry => { + results.push(entry); + }); + } catch (e) { + // Always return a list, even if the directory does not exist (or is + // not a directory) for symmetry with the ZipReader behavior. + } + iter.close(); + + return results; + } + + // FIXME: We need a way to do this without main thread IO. + + let uri = this.rootURI.QueryInterface(Ci.nsIJARURI); + + let file = uri.JARFile.QueryInterface(Ci.nsIFileURL).file; + let zipReader = Cc["@mozilla.org/libjar/zip-reader;1"].createInstance(Ci.nsIZipReader); + zipReader.open(file); + try { + let results = []; + + // Normalize the directory path. + path = `${uri.JAREntry}/${path}`; + path = path.replace(/\/\/+/g, "/").replace(/^\/|\/$/g, "") + "/"; + + // Escape pattern metacharacters. + let pattern = path.replace(/[[\]()?*~|$\\]/g, "\\$&"); + + let enumerator = zipReader.findEntries(pattern + "*"); + while (enumerator.hasMore()) { + let name = enumerator.getNext(); + if (!name.startsWith(path)) { + throw new Error("Unexpected ZipReader entry"); + } + + // The enumerator returns the full path of all entries. + // Trim off the leading path, and filter out entries from + // subdirectories. + name = name.slice(path.length); + if (name && !/\/./.test(name)) { + results.push({ + name: name.replace("/", ""), + isDir: name.endsWith("/"), + }); + } + } + + return results; + } finally { + zipReader.close(); + } + }.bind(this)); + } + + readJSON(path) { + return new Promise((resolve, reject) => { + let uri = this.rootURI.resolve(`./${path}`); + + NetUtil.asyncFetch({uri, loadUsingSystemPrincipal: true}, (inputStream, status) => { + if (!Components.isSuccessCode(status)) { + // Convert status code to a string + let e = Components.Exception("", status); + reject(new Error(`Error while loading '${uri}' (${e.name})`)); + return; + } + try { + let text = NetUtil.readInputStreamToString(inputStream, inputStream.available(), + {charset: "utf-8"}); + + text = text.replace(COMMENT_REGEXP, "$1"); + + resolve(JSON.parse(text)); + } catch (e) { + reject(e); + } + }); + }); + } + + // Reads the extension's |manifest.json| file, and stores its + // parsed contents in |this.manifest|. + readManifest() { + return Promise.all([ + this.readJSON("manifest.json"), + Management.lazyInit(), + ]).then(([manifest]) => { + this.manifest = manifest; + this.rawManifest = manifest; + + if (manifest && manifest.default_locale) { + return this.initLocale(); + } + }).then(() => { + let context = { + url: this.baseURI && this.baseURI.spec, + + principal: this.principal, + + logError: error => { + this.logger.warn(`Loading extension '${this.id}': Reading manifest: ${error}`); + }, + + preprocessors: {}, + }; + + if (this.localeData) { + context.preprocessors.localize = (value, context) => this.localize(value); + } + + let normalized = Schemas.normalize(this.manifest, "manifest.WebExtensionManifest", context); + if (normalized.error) { + this.manifestError(normalized.error); + } else { + this.manifest = normalized.value; + } + + try { + // Do not override the add-on id that has been already assigned. + if (!this.id && this.manifest.applications.gecko.id) { + this.id = this.manifest.applications.gecko.id; + } + } catch (e) { + // Errors are handled by the type checks above. + } + + let permissions = this.manifest.permissions || []; + + let whitelist = []; + for (let perm of permissions) { + this.permissions.add(perm); + + let match = /^(\w+)(?:\.(\w+)(?:\.\w+)*)?$/.exec(perm); + if (!match) { + whitelist.push(perm); + } else if (match[1] == "experiments" && match[2]) { + this.apiNames.add(match[2]); + } + } + this.whiteListedHosts = new MatchPattern(whitelist); + + for (let api of this.apiNames) { + this.dependencies.add(`${api}@experiments.addons.mozilla.org`); + } + + return this.manifest; + }); + } + + localizeMessage(...args) { + return this.localeData.localizeMessage(...args); + } + + localize(...args) { + return this.localeData.localize(...args); + } + + // If a "default_locale" is specified in that manifest, returns it + // as a Gecko-compatible locale string. Otherwise, returns null. + get defaultLocale() { + if (this.manifest.default_locale != null) { + return this.normalizeLocaleCode(this.manifest.default_locale); + } + + return null; + } + + // Normalizes a Chrome-compatible locale code to the appropriate + // Gecko-compatible variant. Currently, this means simply + // replacing underscores with hyphens. + normalizeLocaleCode(locale) { + return String.replace(locale, /_/g, "-"); + } + + // Reads the locale file for the given Gecko-compatible locale code, and + // stores its parsed contents in |this.localeMessages.get(locale)|. + readLocaleFile(locale) { + return Task.spawn(function* () { + let locales = yield this.promiseLocales(); + let dir = locales.get(locale) || locale; + let file = `_locales/${dir}/messages.json`; + + try { + let messages = yield this.readJSON(file); + return this.localeData.addLocale(locale, messages, this); + } catch (e) { + this.packagingError(`Loading locale file ${file}: ${e}`); + return new Map(); + } + }.bind(this)); + } + + // Reads the list of locales available in the extension, and returns a + // Promise which resolves to a Map upon completion. + // Each map key is a Gecko-compatible locale code, and each value is the + // "_locales" subdirectory containing that locale: + // + // Map(gecko-locale-code -> locale-directory-name) + promiseLocales() { + if (!this._promiseLocales) { + this._promiseLocales = Task.spawn(function* () { + let locales = new Map(); + + let entries = yield this.readDirectory("_locales"); + for (let file of entries) { + if (file.isDir) { + let locale = this.normalizeLocaleCode(file.name); + locales.set(locale, file.name); + } + } + + this.localeData = new LocaleData({ + defaultLocale: this.defaultLocale, + locales, + builtinMessages: this.builtinMessages, + }); + + return locales; + }.bind(this)); + } + + return this._promiseLocales; + } + + // Reads the locale messages for all locales, and returns a promise which + // resolves to a Map of locale messages upon completion. Each key in the map + // is a Gecko-compatible locale code, and each value is a locale data object + // as returned by |readLocaleFile|. + initAllLocales() { + return Task.spawn(function* () { + let locales = yield this.promiseLocales(); + + yield Promise.all(Array.from(locales.keys(), + locale => this.readLocaleFile(locale))); + + let defaultLocale = this.defaultLocale; + if (defaultLocale) { + if (!locales.has(defaultLocale)) { + this.manifestError('Value for "default_locale" property must correspond to ' + + 'a directory in "_locales/". Not found: ' + + JSON.stringify(`_locales/${this.manifest.default_locale}/`)); + } + } else if (locales.size) { + this.manifestError('The "default_locale" property is required when a ' + + '"_locales/" directory is present.'); + } + + return this.localeData.messages; + }.bind(this)); + } + + // Reads the locale file for the given Gecko-compatible locale code, or the + // default locale if no locale code is given, and sets it as the currently + // selected locale on success. + // + // Pre-loads the default locale for fallback message processing, regardless + // of the locale specified. + // + // If no locales are unavailable, resolves to |null|. + initLocale(locale = this.defaultLocale) { + return Task.spawn(function* () { + if (locale == null) { + return null; + } + + let promises = [this.readLocaleFile(locale)]; + + let {defaultLocale} = this; + if (locale != defaultLocale && !this.localeData.has(defaultLocale)) { + promises.push(this.readLocaleFile(defaultLocale)); + } + + let results = yield Promise.all(promises); + + this.localeData.selectedLocale = locale; + return results[0]; + }.bind(this)); + } +}; + +let _browserUpdated = false; + +const PROXIED_EVENTS = new Set(["test-harness-message"]); + +// We create one instance of this class per extension. |addonData| +// comes directly from bootstrap.js when initializing. +this.Extension = class extends ExtensionData { + constructor(addonData, startupReason) { + super(addonData.resourceURI); + + this.uuid = UUIDMap.get(addonData.id); + this.instanceId = getUniqueId(); + + this.MESSAGE_EMIT_EVENT = `Extension:EmitEvent:${this.instanceId}`; + Services.ppmm.addMessageListener(this.MESSAGE_EMIT_EVENT, this); + + if (addonData.cleanupFile) { + Services.obs.addObserver(this, "xpcom-shutdown", false); + this.cleanupFile = addonData.cleanupFile || null; + delete addonData.cleanupFile; + } + + this.addonData = addonData; + this.startupReason = startupReason; + + this.id = addonData.id; + this.baseURI = NetUtil.newURI(this.getURL("")).QueryInterface(Ci.nsIURL); + this.principal = this.createPrincipal(); + + this.onStartup = null; + + this.hasShutdown = false; + this.onShutdown = new Set(); + + this.uninstallURL = null; + + this.apis = []; + this.whiteListedHosts = null; + this.webAccessibleResources = null; + + this.emitter = new EventEmitter(); + } + + static set browserUpdated(updated) { + _browserUpdated = updated; + } + + static get browserUpdated() { + return _browserUpdated; + } + + static generateXPI(data) { + return ExtensionTestCommon.generateXPI(data); + } + + static generateZipFile(files, baseName = "generated-extension.xpi") { + return ExtensionTestCommon.generateZipFile(files, baseName); + } + + static generate(data) { + return ExtensionTestCommon.generate(data); + } + + on(hook, f) { + return this.emitter.on(hook, f); + } + + off(hook, f) { + return this.emitter.off(hook, f); + } + + emit(event, ...args) { + if (PROXIED_EVENTS.has(event)) { + Services.ppmm.broadcastAsyncMessage(this.MESSAGE_EMIT_EVENT, {event, args}); + } + + return this.emitter.emit(event, ...args); + } + + receiveMessage({name, data}) { + if (name === this.MESSAGE_EMIT_EVENT) { + this.emitter.emit(data.event, ...data.args); + } + } + + testMessage(...args) { + this.emit("test-harness-message", ...args); + } + + createPrincipal(uri = this.baseURI) { + return Services.scriptSecurityManager.createCodebasePrincipal( + uri, {addonId: this.id}); + } + + // Checks that the given URL is a child of our baseURI. + isExtensionURL(url) { + let uri = Services.io.newURI(url, null, null); + + let common = this.baseURI.getCommonBaseSpec(uri); + return common == this.baseURI.spec; + } + + readManifest() { + return super.readManifest().then(manifest => { + if (AppConstants.RELEASE_OR_BETA) { + return manifest; + } + + // Load Experiments APIs that this extension depends on. + return Promise.all( + Array.from(this.apiNames, api => ExtensionAPIs.load(api)) + ).then(apis => { + for (let API of apis) { + this.apis.push(new API(this)); + } + + return manifest; + }); + }); + } + + // Representation of the extension to send to content + // processes. This should include anything the content process might + // need. + serialize() { + return { + id: this.id, + uuid: this.uuid, + instanceId: this.instanceId, + manifest: this.manifest, + resourceURL: this.addonData.resourceURI.spec, + baseURL: this.baseURI.spec, + content_scripts: this.manifest.content_scripts || [], // eslint-disable-line camelcase + webAccessibleResources: this.webAccessibleResources.serialize(), + whiteListedHosts: this.whiteListedHosts.serialize(), + localeData: this.localeData.serialize(), + permissions: this.permissions, + principal: this.principal, + }; + } + + broadcast(msg, data) { + return new Promise(resolve => { + let count = Services.ppmm.childCount; + Services.ppmm.addMessageListener(msg + "Complete", function listener() { + count--; + if (count == 0) { + Services.ppmm.removeMessageListener(msg + "Complete", listener); + resolve(); + } + }); + Services.ppmm.broadcastAsyncMessage(msg, data); + }); + } + + runManifest(manifest) { + // Strip leading slashes from web_accessible_resources. + let strippedWebAccessibleResources = []; + if (manifest.web_accessible_resources) { + strippedWebAccessibleResources = manifest.web_accessible_resources.map(path => path.replace(/^\/+/, "")); + } + + this.webAccessibleResources = new MatchGlobs(strippedWebAccessibleResources); + + let promises = []; + for (let directive in manifest) { + if (manifest[directive] !== null) { + promises.push(Management.emit(`manifest_${directive}`, directive, this, manifest)); + } + } + + let data = Services.ppmm.initialProcessData; + if (!data["Extension:Extensions"]) { + data["Extension:Extensions"] = []; + } + let serial = this.serialize(); + data["Extension:Extensions"].push(serial); + + return this.broadcast("Extension:Startup", serial).then(() => { + return Promise.all(promises); + }); + } + + callOnClose(obj) { + this.onShutdown.add(obj); + } + + forgetOnClose(obj) { + this.onShutdown.delete(obj); + } + + get builtinMessages() { + return new Map([ + ["@@extension_id", this.uuid], + ]); + } + + // Reads the locale file for the given Gecko-compatible locale code, or if + // no locale is given, the available locale closest to the UI locale. + // Sets the currently selected locale on success. + initLocale(locale = undefined) { + // Ugh. + let super_ = super.initLocale.bind(this); + + return Task.spawn(function* () { + if (locale === undefined) { + let locales = yield this.promiseLocales(); + + let localeList = Array.from(locales.keys(), locale => { + return {name: locale, locales: [locale]}; + }); + + let match = Locale.findClosestLocale(localeList); + locale = match ? match.name : this.defaultLocale; + } + + return super_(locale); + }.bind(this)); + } + + startup() { + let started = false; + return this.readManifest().then(() => { + ExtensionManagement.startupExtension(this.uuid, this.addonData.resourceURI, this); + started = true; + + if (!this.hasShutdown) { + return this.initLocale(); + } + }).then(() => { + if (this.errors.length) { + return Promise.reject({errors: this.errors}); + } + + if (this.hasShutdown) { + return; + } + + GlobalManager.init(this); + + // The "startup" Management event sent on the extension instance itself + // is emitted just before the Management "startup" event, + // and it is used to run code that needs to be executed before + // any of the "startup" listeners. + this.emit("startup", this); + Management.emit("startup", this); + + return this.runManifest(this.manifest); + }).then(() => { + Management.emit("ready", this); + }).catch(e => { + dump(`Extension error: ${e.message} ${e.filename || e.fileName}:${e.lineNumber} :: ${e.stack || new Error().stack}\n`); + Cu.reportError(e); + + if (started) { + ExtensionManagement.shutdownExtension(this.uuid); + } + + this.cleanupGeneratedFile(); + + throw e; + }); + } + + cleanupGeneratedFile() { + if (!this.cleanupFile) { + return; + } + + let file = this.cleanupFile; + this.cleanupFile = null; + + Services.obs.removeObserver(this, "xpcom-shutdown"); + + this.broadcast("Extension:FlushJarCache", {path: file.path}).then(() => { + // We can't delete this file until everyone using it has + // closed it (because Windows is dumb). So we wait for all the + // child processes (including the parent) to flush their JAR + // caches. These caches may keep the file open. + file.remove(false); + }); + } + + shutdown() { + this.hasShutdown = true; + + Services.ppmm.removeMessageListener(this.MESSAGE_EMIT_EVENT, this); + + if (!this.manifest) { + ExtensionManagement.shutdownExtension(this.uuid); + + this.cleanupGeneratedFile(); + return; + } + + GlobalManager.uninit(this); + + for (let obj of this.onShutdown) { + obj.close(); + } + + for (let api of this.apis) { + api.destroy(); + } + + ParentAPIManager.shutdownExtension(this.id); + + Management.emit("shutdown", this); + + Services.ppmm.broadcastAsyncMessage("Extension:Shutdown", {id: this.id}); + + MessageChannel.abortResponses({extensionId: this.id}); + + ExtensionManagement.shutdownExtension(this.uuid); + + this.cleanupGeneratedFile(); + } + + observe(subject, topic, data) { + if (topic == "xpcom-shutdown") { + this.cleanupGeneratedFile(); + } + } + + hasPermission(perm) { + let match = /^manifest:(.*)/.exec(perm); + if (match) { + return this.manifest[match[1]] != null; + } + + return this.permissions.has(perm); + } + + get name() { + return this.manifest.name; + } +}; diff --git a/toolkit/components/webextensions/ExtensionAPI.jsm b/toolkit/components/webextensions/ExtensionAPI.jsm new file mode 100644 index 000000000..54dab8e3b --- /dev/null +++ b/toolkit/components/webextensions/ExtensionAPI.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"; + +this.EXPORTED_SYMBOLS = ["ExtensionAPI", "ExtensionAPIs"]; + +/* exported ExtensionAPIs */ + +const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; + +Cu.import("resource://gre/modules/ExtensionManagement.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "EventEmitter", + "resource://devtools/shared/event-emitter.js"); +XPCOMUtils.defineLazyModuleGetter(this, "Schemas", + "resource://gre/modules/Schemas.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Task", + "resource://gre/modules/Task.jsm"); + +const global = this; + +class ExtensionAPI { + constructor(extension) { + this.extension = extension; + } + + destroy() { + } + + getAPI(context) { + throw new Error("Not Implemented"); + } +} + +var ExtensionAPIs = { + apis: ExtensionManagement.APIs.apis, + + load(apiName) { + let api = this.apis.get(apiName); + + if (api.loadPromise) { + return api.loadPromise; + } + + let {script, schema} = api; + + let addonId = `${apiName}@experiments.addons.mozilla.org`; + api.sandbox = Cu.Sandbox(global, { + wantXrays: false, + sandboxName: script, + addonId, + metadata: {addonID: addonId}, + }); + + api.sandbox.ExtensionAPI = ExtensionAPI; + + Services.scriptloader.loadSubScript(script, api.sandbox, "UTF-8"); + + api.loadPromise = Schemas.load(schema).then(() => { + return Cu.evalInSandbox("API", api.sandbox); + }); + + return api.loadPromise; + }, + + unload(apiName) { + let api = this.apis.get(apiName); + + let {schema} = api; + + Schemas.unload(schema); + Cu.nukeSandbox(api.sandbox); + + api.sandbox = null; + api.loadPromise = null; + }, +}; diff --git a/toolkit/components/webextensions/ExtensionChild.jsm b/toolkit/components/webextensions/ExtensionChild.jsm new file mode 100644 index 000000000..5dc4e2277 --- /dev/null +++ b/toolkit/components/webextensions/ExtensionChild.jsm @@ -0,0 +1,1058 @@ +/* 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"; + +this.EXPORTED_SYMBOLS = ["ExtensionChild"]; + +/* + * This file handles addon logic that is independent of the chrome process. + * When addons run out-of-process, this is the main entry point. + * Its primary function is managing addon globals. + * + * Don't put contentscript logic here, use ExtensionContent.jsm instead. + */ + +const Ci = Components.interfaces; +const Cc = Components.classes; +const Cu = Components.utils; +const Cr = Components.results; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel", + "resource://gre/modules/MessageChannel.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "NativeApp", + "resource://gre/modules/NativeMessaging.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PromiseUtils", + "resource://gre/modules/PromiseUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Schemas", + "resource://gre/modules/Schemas.jsm"); + +const CATEGORY_EXTENSION_SCRIPTS_ADDON = "webextension-scripts-addon"; + +Cu.import("resource://gre/modules/ExtensionCommon.jsm"); +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +const { + DefaultMap, + EventManager, + SingletonEventManager, + SpreadArgs, + defineLazyGetter, + getInnerWindowID, + getMessageManager, + getUniqueId, + injectAPI, +} = ExtensionUtils; + +const { + BaseContext, + LocalAPIImplementation, + SchemaAPIInterface, + SchemaAPIManager, +} = ExtensionCommon; + +var ExtensionChild; + +/** + * Abstraction for a Port object in the extension API. + * + * @param {BaseContext} context The context that owns this port. + * @param {nsIMessageSender} senderMM The message manager to send messages to. + * @param {Array} receiverMMs Message managers to + * listen on. + * @param {string} name Arbitrary port name as defined by the addon. + * @param {string} id An ID that uniquely identifies this port's channel. + * @param {object} sender The `port.sender` property. + * @param {object} recipient The recipient of messages sent from this port. + */ +class Port { + constructor(context, senderMM, receiverMMs, name, id, sender, recipient) { + this.context = context; + this.senderMM = senderMM; + this.receiverMMs = receiverMMs; + this.name = name; + this.id = id; + this.sender = sender; + this.recipient = recipient; + this.disconnected = false; + this.disconnectListeners = new Set(); + this.unregisterMessageFuncs = new Set(); + + // Common options for onMessage and onDisconnect. + this.handlerBase = { + messageFilterStrict: {portId: id}, + + filterMessage: (sender, recipient) => { + return sender.contextId !== this.context.contextId; + }, + }; + + this.disconnectHandler = Object.assign({ + receiveMessage: ({data}) => this.disconnectByOtherEnd(data), + }, this.handlerBase); + + MessageChannel.addListener(this.receiverMMs, "Extension:Port:Disconnect", this.disconnectHandler); + + this.context.callOnClose(this); + } + + api() { + let portObj = Cu.createObjectIn(this.context.cloneScope); + + let portError = null; + let publicAPI = { + name: this.name, + + disconnect: () => { + this.disconnect(); + }, + + postMessage: json => { + this.postMessage(json); + }, + + onDisconnect: new EventManager(this.context, "Port.onDisconnect", fire => { + return this.registerOnDisconnect(error => { + portError = error && this.context.normalizeError(error); + fire.withoutClone(portObj); + }); + }).api(), + + onMessage: new EventManager(this.context, "Port.onMessage", fire => { + return this.registerOnMessage(msg => { + msg = Cu.cloneInto(msg, this.context.cloneScope); + fire.withoutClone(msg, portObj); + }); + }).api(), + + get error() { + return portError; + }, + }; + + if (this.sender) { + publicAPI.sender = this.sender; + } + + injectAPI(publicAPI, portObj); + return portObj; + } + + postMessage(json) { + if (this.disconnected) { + throw new this.context.cloneScope.Error("Attempt to postMessage on disconnected port"); + } + + this._sendMessage("Extension:Port:PostMessage", json); + } + + /** + * Register a callback that is called when the port is disconnected by the + * *other* end. The callback is automatically unregistered when the port or + * context is closed. + * + * @param {function} callback Called when the other end disconnects the port. + * If the disconnect is caused by an error, the first parameter is an + * object with a "message" string property that describes the cause. + * @returns {function} Function to unregister the listener. + */ + registerOnDisconnect(callback) { + let listener = error => { + if (this.context.active && !this.disconnected) { + callback(error); + } + }; + this.disconnectListeners.add(listener); + return () => { + this.disconnectListeners.delete(listener); + }; + } + + /** + * Register a callback that is called when a message is received. The callback + * is automatically unregistered when the port or context is closed. + * + * @param {function} callback Called when a message is received. + * @returns {function} Function to unregister the listener. + */ + registerOnMessage(callback) { + let handler = Object.assign({ + receiveMessage: ({data}) => { + if (this.context.active && !this.disconnected) { + callback(data); + } + }, + }, this.handlerBase); + + let unregister = () => { + this.unregisterMessageFuncs.delete(unregister); + MessageChannel.removeListener(this.receiverMMs, "Extension:Port:PostMessage", handler); + }; + MessageChannel.addListener(this.receiverMMs, "Extension:Port:PostMessage", handler); + this.unregisterMessageFuncs.add(unregister); + return unregister; + } + + _sendMessage(message, data) { + let options = { + recipient: Object.assign({}, this.recipient, {portId: this.id}), + responseType: MessageChannel.RESPONSE_NONE, + }; + + return this.context.sendMessage(this.senderMM, message, data, options); + } + + handleDisconnection() { + MessageChannel.removeListener(this.receiverMMs, "Extension:Port:Disconnect", this.disconnectHandler); + for (let unregister of this.unregisterMessageFuncs) { + unregister(); + } + this.context.forgetOnClose(this); + this.disconnected = true; + } + + /** + * Disconnect the port from the other end (which may not even exist). + * + * @param {Error|{message: string}} [error] The reason for disconnecting, + * if it is an abnormal disconnect. + */ + disconnectByOtherEnd(error = null) { + if (this.disconnected) { + return; + } + + for (let listener of this.disconnectListeners) { + listener(error); + } + + this.handleDisconnection(); + } + + /** + * Disconnect the port from this end. + * + * @param {Error|{message: string}} [error] The reason for disconnecting, + * if it is an abnormal disconnect. + */ + disconnect(error = null) { + if (this.disconnected) { + // disconnect() may be called without side effects even after the port is + // closed - https://developer.chrome.com/extensions/runtime#type-Port + return; + } + this.handleDisconnection(); + if (error) { + error = {message: this.context.normalizeError(error).message}; + } + this._sendMessage("Extension:Port:Disconnect", error); + } + + close() { + this.disconnect(); + } +} + +class NativePort extends Port { + postMessage(data) { + data = NativeApp.encodeMessage(this.context, data); + + return super.postMessage(data); + } +} + +/** + * Each extension context gets its own Messenger object. It handles the + * basics of sendMessage, onMessage, connect and onConnect. + * + * @param {BaseContext} context The context to which this Messenger is tied. + * @param {Array} messageManagers + * The message managers used to receive messages (e.g. onMessage/onConnect + * requests). + * @param {object} sender Describes this sender to the recipient. This object + * is extended further by BaseContext's sendMessage method and appears as + * the `sender` object to `onConnect` and `onMessage`. + * Do not set the `extensionId`, `contextId` or `tab` properties. The former + * two are added by BaseContext's sendMessage, while `sender.tab` is set by + * the ProxyMessenger in the main process. + * @param {object} filter A recipient filter to apply to incoming messages from + * the broker. Messages are only handled by this Messenger if all key-value + * pairs match the `recipient` as specified by the sender of the message. + * In other words, this filter defines the required fields of `recipient`. + * @param {object} [optionalFilter] An additional filter to apply to incoming + * messages. Unlike `filter`, the keys from `optionalFilter` are allowed to + * be omitted from `recipient`. Only keys that are present in both + * `optionalFilter` and `recipient` are applied to filter incoming messages. + */ +class Messenger { + constructor(context, messageManagers, sender, filter, optionalFilter) { + this.context = context; + this.messageManagers = messageManagers; + this.sender = sender; + this.filter = filter; + this.optionalFilter = optionalFilter; + } + + _sendMessage(messageManager, message, data, recipient) { + let options = { + recipient, + sender: this.sender, + responseType: MessageChannel.RESPONSE_FIRST, + }; + + return this.context.sendMessage(messageManager, message, data, options); + } + + sendMessage(messageManager, msg, recipient, responseCallback) { + let promise = this._sendMessage(messageManager, "Extension:Message", msg, recipient) + .catch(error => { + if (error.result == MessageChannel.RESULT_NO_HANDLER) { + return Promise.reject({message: "Could not establish connection. Receiving end does not exist."}); + } else if (error.result != MessageChannel.RESULT_NO_RESPONSE) { + return Promise.reject({message: error.message}); + } + }); + + return this.context.wrapPromise(promise, responseCallback); + } + + sendNativeMessage(messageManager, msg, recipient, responseCallback) { + msg = NativeApp.encodeMessage(this.context, msg); + return this.sendMessage(messageManager, msg, recipient, responseCallback); + } + + _onMessage(name, filter) { + return new SingletonEventManager(this.context, name, callback => { + let listener = { + messageFilterPermissive: this.optionalFilter, + messageFilterStrict: this.filter, + + filterMessage: (sender, recipient) => { + // Ignore the message if it was sent by this Messenger. + return (sender.contextId !== this.context.contextId && + filter(sender, recipient)); + }, + + receiveMessage: ({target, data: message, sender, recipient}) => { + if (!this.context.active) { + return; + } + + let sendResponse; + let response = undefined; + let promise = new Promise(resolve => { + sendResponse = value => { + resolve(value); + response = promise; + }; + }); + + message = Cu.cloneInto(message, this.context.cloneScope); + sender = Cu.cloneInto(sender, this.context.cloneScope); + sendResponse = Cu.exportFunction(sendResponse, this.context.cloneScope); + + // Note: We intentionally do not use runSafe here so that any + // errors are propagated to the message sender. + let result = callback(message, sender, sendResponse); + if (result instanceof this.context.cloneScope.Promise) { + return result; + } else if (result === true) { + return promise; + } + return response; + }, + }; + + MessageChannel.addListener(this.messageManagers, "Extension:Message", listener); + return () => { + MessageChannel.removeListener(this.messageManagers, "Extension:Message", listener); + }; + }).api(); + } + + onMessage(name) { + return this._onMessage(name, sender => sender.id === this.sender.id); + } + + onMessageExternal(name) { + return this._onMessage(name, sender => sender.id !== this.sender.id); + } + + _connect(messageManager, port, recipient) { + let msg = { + name: port.name, + portId: port.id, + }; + + this._sendMessage(messageManager, "Extension:Connect", msg, recipient).catch(error => { + if (error.result === MessageChannel.RESULT_NO_HANDLER) { + error = {message: "Could not establish connection. Receiving end does not exist."}; + } else if (error.result === MessageChannel.RESULT_DISCONNECTED) { + error = null; + } + port.disconnectByOtherEnd(error); + }); + + return port.api(); + } + + connect(messageManager, name, recipient) { + let portId = getUniqueId(); + + let port = new Port(this.context, messageManager, this.messageManagers, name, portId, null, recipient); + + return this._connect(messageManager, port, recipient); + } + + connectNative(messageManager, name, recipient) { + let portId = getUniqueId(); + + let port = new NativePort(this.context, messageManager, this.messageManagers, name, portId, null, recipient); + + return this._connect(messageManager, port, recipient); + } + + _onConnect(name, filter) { + return new SingletonEventManager(this.context, name, callback => { + let listener = { + messageFilterPermissive: this.optionalFilter, + messageFilterStrict: this.filter, + + filterMessage: (sender, recipient) => { + // Ignore the port if it was created by this Messenger. + return (sender.contextId !== this.context.contextId && + filter(sender, recipient)); + }, + + receiveMessage: ({target, data: message, sender}) => { + let {name, portId} = message; + let mm = getMessageManager(target); + let recipient = Object.assign({}, sender); + if (recipient.tab) { + recipient.tabId = recipient.tab.id; + delete recipient.tab; + } + let port = new Port(this.context, mm, this.messageManagers, name, portId, sender, recipient); + this.context.runSafeWithoutClone(callback, port.api()); + return true; + }, + }; + + MessageChannel.addListener(this.messageManagers, "Extension:Connect", listener); + return () => { + MessageChannel.removeListener(this.messageManagers, "Extension:Connect", listener); + }; + }).api(); + } + + onConnect(name) { + return this._onConnect(name, sender => sender.id === this.sender.id); + } + + onConnectExternal(name) { + return this._onConnect(name, sender => sender.id !== this.sender.id); + } +} + +var apiManager = new class extends SchemaAPIManager { + constructor() { + super("addon"); + this.initialized = false; + } + + generateAPIs(...args) { + if (!this.initialized) { + this.initialized = true; + for (let [/* name */, value] of XPCOMUtils.enumerateCategoryEntries(CATEGORY_EXTENSION_SCRIPTS_ADDON)) { + this.loadScript(value); + } + } + return super.generateAPIs(...args); + } + + registerSchemaAPI(namespace, envType, getAPI) { + if (envType == "addon_child") { + super.registerSchemaAPI(namespace, envType, getAPI); + } + } +}(); + +/** + * An object that runs an remote implementation of an API. + */ +class ProxyAPIImplementation extends SchemaAPIInterface { + /** + * @param {string} namespace The full path to the namespace that contains the + * `name` member. This may contain dots, e.g. "storage.local". + * @param {string} name The name of the method or property. + * @param {ChildAPIManager} childApiManager The owner of this implementation. + */ + constructor(namespace, name, childApiManager) { + super(); + this.path = `${namespace}.${name}`; + this.childApiManager = childApiManager; + } + + callFunctionNoReturn(args) { + this.childApiManager.callParentFunctionNoReturn(this.path, args); + } + + callAsyncFunction(args, callback) { + return this.childApiManager.callParentAsyncFunction(this.path, args, callback); + } + + addListener(listener, args) { + let map = this.childApiManager.listeners.get(this.path); + + if (map.listeners.has(listener)) { + // TODO: Called with different args? + return; + } + + let id = getUniqueId(); + + map.ids.set(id, listener); + map.listeners.set(listener, id); + + this.childApiManager.messageManager.sendAsyncMessage("API:AddListener", { + childId: this.childApiManager.id, + listenerId: id, + path: this.path, + args, + }); + } + + removeListener(listener) { + let map = this.childApiManager.listeners.get(this.path); + + if (!map.listeners.has(listener)) { + return; + } + + let id = map.listeners.get(listener); + map.listeners.delete(listener); + map.ids.delete(id); + + this.childApiManager.messageManager.sendAsyncMessage("API:RemoveListener", { + childId: this.childApiManager.id, + listenerId: id, + path: this.path, + }); + } + + hasListener(listener) { + let map = this.childApiManager.listeners.get(this.path); + return map.listeners.has(listener); + } +} + +// We create one instance of this class for every extension context that +// needs to use remote APIs. It uses the message manager to communicate +// with the ParentAPIManager singleton in ExtensionParent.jsm. It +// handles asynchronous function calls as well as event listeners. +class ChildAPIManager { + constructor(context, messageManager, localApis, contextData) { + this.context = context; + this.messageManager = messageManager; + this.url = contextData.url; + + // The root namespace of all locally implemented APIs. If an extension calls + // an API that does not exist in this object, then the implementation is + // delegated to the ParentAPIManager. + this.localApis = localApis; + + this.id = `${context.extension.id}.${context.contextId}`; + + MessageChannel.addListener(messageManager, "API:RunListener", this); + messageManager.addMessageListener("API:CallResult", this); + + this.messageFilterStrict = {childId: this.id}; + + this.listeners = new DefaultMap(() => ({ + ids: new Map(), + listeners: new Map(), + })); + + // Map[callId -> Deferred] + this.callPromises = new Map(); + + let params = { + childId: this.id, + extensionId: context.extension.id, + principal: context.principal, + }; + Object.assign(params, contextData); + + this.messageManager.sendAsyncMessage("API:CreateProxyContext", params); + } + + receiveMessage({name, messageName, data}) { + if (data.childId != this.id) { + return; + } + + switch (name || messageName) { + case "API:RunListener": + let map = this.listeners.get(data.path); + let listener = map.ids.get(data.listenerId); + + if (listener) { + return this.context.runSafe(listener, ...data.args); + } + + Cu.reportError(`Unknown listener at childId=${data.childId} path=${data.path} listenerId=${data.listenerId}\n`); + break; + + case "API:CallResult": + let deferred = this.callPromises.get(data.callId); + if ("error" in data) { + deferred.reject(data.error); + } else { + deferred.resolve(new SpreadArgs(data.result)); + } + this.callPromises.delete(data.callId); + break; + } + } + + /** + * Call a function in the parent process and ignores its return value. + * + * @param {string} path The full name of the method, e.g. "tabs.create". + * @param {Array} args The parameters for the function. + */ + callParentFunctionNoReturn(path, args) { + this.messageManager.sendAsyncMessage("API:Call", { + childId: this.id, + path, + args, + }); + } + + /** + * Calls a function in the parent process and returns its result + * asynchronously. + * + * @param {string} path The full name of the method, e.g. "tabs.create". + * @param {Array} args The parameters for the function. + * @param {function(*)} [callback] The callback to be called when the function + * completes. + * @returns {Promise|undefined} Must be void if `callback` is set, and a + * promise otherwise. The promise is resolved when the function completes. + */ + callParentAsyncFunction(path, args, callback) { + let callId = getUniqueId(); + let deferred = PromiseUtils.defer(); + this.callPromises.set(callId, deferred); + + this.messageManager.sendAsyncMessage("API:Call", { + childId: this.id, + callId, + path, + args, + }); + + return this.context.wrapPromise(deferred.promise, callback); + } + + /** + * Create a proxy for an event in the parent process. The returned event + * object shares its internal state with other instances. For instance, if + * `removeListener` is used on a listener that was added on another object + * through `addListener`, then the event is unregistered. + * + * @param {string} path The full name of the event, e.g. "tabs.onCreated". + * @returns {object} An object with the addListener, removeListener and + * hasListener methods. See SchemaAPIInterface for documentation. + */ + getParentEvent(path) { + path = path.split("."); + + let name = path.pop(); + let namespace = path.join("."); + + let impl = new ProxyAPIImplementation(namespace, name, this); + return { + addListener: (listener, ...args) => impl.addListener(listener, args), + removeListener: (listener) => impl.removeListener(listener), + hasListener: (listener) => impl.hasListener(listener), + }; + } + + close() { + this.messageManager.sendAsyncMessage("API:CloseProxyContext", {childId: this.id}); + } + + get cloneScope() { + return this.context.cloneScope; + } + + get principal() { + return this.context.principal; + } + + shouldInject(namespace, name, allowedContexts) { + // Do not generate content script APIs, unless explicitly allowed. + if (this.context.envType === "content_child" && + !allowedContexts.includes("content")) { + return false; + } + if (allowedContexts.includes("addon_parent_only")) { + return false; + } + return true; + } + + getImplementation(namespace, name) { + let obj = namespace.split(".").reduce( + (object, prop) => object && object[prop], + this.localApis); + + if (obj && name in obj) { + return new LocalAPIImplementation(obj, name, this.context); + } + + return this.getFallbackImplementation(namespace, name); + } + + getFallbackImplementation(namespace, name) { + // No local API found, defer implementation to the parent. + return new ProxyAPIImplementation(namespace, name, this); + } + + hasPermission(permission) { + return this.context.extension.hasPermission(permission); + } +} + +class ExtensionPageContextChild extends BaseContext { + /** + * This ExtensionPageContextChild represents a privileged addon + * execution environment that has full access to the WebExtensions + * APIs (provided that the correct permissions have been requested). + * + * This is the child side of the ExtensionPageContextParent class + * defined in ExtensionParent.jsm. + * + * @param {BrowserExtensionContent} extension This context's owner. + * @param {object} params + * @param {nsIDOMWindow} params.contentWindow The window where the addon runs. + * @param {string} params.viewType One of "background", "popup" or "tab". + * "background" and "tab" are used by `browser.extension.getViews`. + * "popup" is only used internally to identify page action and browser + * action popups and options_ui pages. + * @param {number} [params.tabId] This tab's ID, used if viewType is "tab". + */ + constructor(extension, params) { + super("addon_child", extension); + if (Services.appinfo.processType != Services.appinfo.PROCESS_TYPE_DEFAULT) { + // This check is temporary. It should be removed once the proxy creation + // is asynchronous. + throw new Error("ExtensionPageContextChild cannot be created in child processes"); + } + + let {viewType, uri, contentWindow, tabId} = params; + this.viewType = viewType; + this.uri = uri || extension.baseURI; + + this.setContentWindow(contentWindow); + + // This is the MessageSender property passed to extension. + // It can be augmented by the "page-open" hook. + let sender = {id: extension.id}; + if (viewType == "tab") { + sender.tabId = tabId; + this.tabId = tabId; + } + if (uri) { + sender.url = uri.spec; + } + this.sender = sender; + + Schemas.exportLazyGetter(contentWindow, "browser", () => { + let browserObj = Cu.createObjectIn(contentWindow); + Schemas.inject(browserObj, this.childManager); + return browserObj; + }); + + Schemas.exportLazyGetter(contentWindow, "chrome", () => { + let chromeApiWrapper = Object.create(this.childManager); + chromeApiWrapper.isChromeCompat = true; + + let chromeObj = Cu.createObjectIn(contentWindow); + Schemas.inject(chromeObj, chromeApiWrapper); + return chromeObj; + }); + + this.extension.views.add(this); + } + + get cloneScope() { + return this.contentWindow; + } + + get principal() { + return this.contentWindow.document.nodePrincipal; + } + + get windowId() { + if (this.viewType == "tab" || this.viewType == "popup") { + let globalView = ExtensionChild.contentGlobals.get(this.messageManager); + return globalView ? globalView.windowId : -1; + } + } + + // Called when the extension shuts down. + shutdown() { + this.unload(); + } + + // This method is called when an extension page navigates away or + // its tab is closed. + unload() { + // Note that without this guard, we end up running unload code + // multiple times for tab pages closed by the "page-unload" handlers + // triggered below. + if (this.unloaded) { + return; + } + + if (this.contentWindow) { + this.contentWindow.close(); + } + + super.unload(); + this.extension.views.delete(this); + } +} + +defineLazyGetter(ExtensionPageContextChild.prototype, "messenger", function() { + let filter = {extensionId: this.extension.id}; + let optionalFilter = {}; + // Addon-generated messages (not necessarily from the same process as the + // addon itself) are sent to the main process, which forwards them via the + // parent process message manager. Specific replies can be sent to the frame + // message manager. + return new Messenger(this, [Services.cpmm, this.messageManager], this.sender, + filter, optionalFilter); +}); + +defineLazyGetter(ExtensionPageContextChild.prototype, "childManager", function() { + let localApis = {}; + apiManager.generateAPIs(this, localApis); + + if (this.viewType == "background") { + apiManager.global.initializeBackgroundPage(this.contentWindow); + } + + let childManager = new ChildAPIManager(this, this.messageManager, localApis, { + envType: "addon_parent", + viewType: this.viewType, + url: this.uri.spec, + incognito: this.incognito, + }); + + this.callOnClose(childManager); + + return childManager; +}); + +// All subframes in a tab, background page, popup, etc. have the same view type. +// This class keeps track of such global state. +// Note that this is created even for non-extension tabs because at present we +// do not have a way to distinguish regular tabs from extension tabs at the +// initialization of a frame script. +class ContentGlobal { + /** + * @param {nsIContentFrameMessageManager} global The frame script's global. + */ + constructor(global) { + this.global = global; + // Unless specified otherwise assume that the extension page is in a tab, + // because the majority of all class instances are going to be a tab. Any + // special views (background page, extension popup) will immediately send an + // Extension:InitExtensionView message to change the viewType. + this.viewType = "tab"; + this.tabId = -1; + this.windowId = -1; + this.initialized = false; + this.global.addMessageListener("Extension:InitExtensionView", this); + this.global.addMessageListener("Extension:SetTabAndWindowId", this); + + this.initialDocuments = new WeakSet(); + } + + uninit() { + this.global.removeMessageListener("Extension:InitExtensionView", this); + this.global.removeMessageListener("Extension:SetTabAndWindowId", this); + this.global.removeEventListener("DOMContentLoaded", this); + } + + ensureInitialized() { + if (!this.initialized) { + // Request tab and window ID in case "Extension:InitExtensionView" is not + // sent (e.g. when `viewType` is "tab"). + let reply = this.global.sendSyncMessage("Extension:GetTabAndWindowId"); + this.handleSetTabAndWindowId(reply[0] || {}); + } + return this; + } + + receiveMessage({name, data}) { + switch (name) { + case "Extension:InitExtensionView": + // The view type is initialized once and then fixed. + this.global.removeMessageListener("Extension:InitExtensionView", this); + let {viewType, url} = data; + this.viewType = viewType; + this.global.addEventListener("DOMContentLoaded", this); + if (url) { + // TODO(robwu): Remove this check. It is only here because the popup + // implementation does not always load a URL at the initialization, + // and the logic is too complex to fix at once. + let {document} = this.global.content; + this.initialDocuments.add(document); + document.location.replace(url); + } + /* Falls through to allow these properties to be initialized at once */ + case "Extension:SetTabAndWindowId": + this.handleSetTabAndWindowId(data); + break; + } + } + + handleSetTabAndWindowId(data) { + let {tabId, windowId} = data; + if (tabId) { + // Tab IDs are not expected to change. + if (this.tabId !== -1 && tabId !== this.tabId) { + throw new Error("Attempted to change a tabId after it was set"); + } + this.tabId = tabId; + } + if (windowId !== undefined) { + // Window IDs may change if a tab is moved to a different location. + // Note: This is the ID of the browser window for the extension API. + // Do not confuse it with the innerWindowID of DOMWindows! + this.windowId = windowId; + } + this.initialized = true; + } + + // "DOMContentLoaded" event. + handleEvent(event) { + let {document} = this.global.content; + if (event.target === document) { + // If the document was still being loaded at the time of navigation, then + // the DOMContentLoaded event is fired for the old document. Ignore it. + if (this.initialDocuments.has(document)) { + this.initialDocuments.delete(document); + return; + } + this.global.removeEventListener("DOMContentLoaded", this); + this.global.sendAsyncMessage("Extension:ExtensionViewLoaded"); + } + } +} + +ExtensionChild = { + // Map + contentGlobals: new Map(), + + // Map + extensionContexts: new Map(), + + initOnce() { + // This initializes the default message handler for messages targeted at + // an addon process, in case the addon process receives a message before + // its Messenger has been instantiated. For example, if a content script + // sends a message while there is no background page. + MessageChannel.setupMessageManagers([Services.cpmm]); + }, + + init(global) { + this.contentGlobals.set(global, new ContentGlobal(global)); + }, + + uninit(global) { + this.contentGlobals.get(global).uninit(); + this.contentGlobals.delete(global); + }, + + /** + * Create a privileged context at document-element-inserted. + * + * @param {BrowserExtensionContent} extension + * The extension for which the context should be created. + * @param {nsIDOMWindow} contentWindow The global of the page. + */ + createExtensionContext(extension, contentWindow) { + let windowId = getInnerWindowID(contentWindow); + let context = this.extensionContexts.get(windowId); + if (context) { + if (context.extension !== extension) { + // Oops. This should never happen. + Cu.reportError("A different extension context already exists in this frame!"); + } else { + // This should not happen either. + Cu.reportError("The extension context was already initialized in this frame."); + } + return; + } + + let mm = contentWindow + .QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell) + .QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIContentFrameMessageManager); + let {viewType, tabId} = this.contentGlobals.get(mm).ensureInitialized(); + + let uri = contentWindow.document.documentURIObject; + + context = new ExtensionPageContextChild(extension, {viewType, contentWindow, uri, tabId}); + this.extensionContexts.set(windowId, context); + }, + + /** + * Close the ExtensionPageContextChild belonging to the given window, if any. + * + * @param {number} windowId The inner window ID of the destroyed context. + */ + destroyExtensionContext(windowId) { + let context = this.extensionContexts.get(windowId); + if (context) { + context.unload(); + this.extensionContexts.delete(windowId); + } + }, + + shutdownExtension(extensionId) { + for (let [windowId, context] of this.extensionContexts) { + if (context.extension.id == extensionId) { + context.shutdown(); + this.extensionContexts.delete(windowId); + } + } + }, +}; + +// TODO(robwu): Change this condition when addons move to a separate process. +if (Services.appinfo.processType != Services.appinfo.PROCESS_TYPE_DEFAULT) { + Object.keys(ExtensionChild).forEach(function(key) { + if (typeof ExtensionChild[key] == "function") { + // :/ + ExtensionChild[key] = () => {}; + } + }); +} + +Object.assign(ExtensionChild, { + ChildAPIManager, + Messenger, + Port, +}); + diff --git a/toolkit/components/webextensions/ExtensionCommon.jsm b/toolkit/components/webextensions/ExtensionCommon.jsm new file mode 100644 index 000000000..9ec84b5c7 --- /dev/null +++ b/toolkit/components/webextensions/ExtensionCommon.jsm @@ -0,0 +1,679 @@ +/* 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"; + +/** + * This module contains utilities and base classes for logic which is + * common between the parent and child process, and in particular + * between ExtensionParent.jsm and ExtensionChild.jsm. + */ + +const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; + +/* exported ExtensionCommon */ + +this.EXPORTED_SYMBOLS = ["ExtensionCommon"]; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel", + "resource://gre/modules/MessageChannel.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Schemas", + "resource://gre/modules/Schemas.jsm"); + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +var { + EventEmitter, + ExtensionError, + SpreadArgs, + getConsole, + getInnerWindowID, + getUniqueId, + runSafeSync, + runSafeSyncWithoutClone, + instanceOf, +} = ExtensionUtils; + +XPCOMUtils.defineLazyGetter(this, "console", getConsole); + +class BaseContext { + constructor(envType, extension) { + this.envType = envType; + this.onClose = new Set(); + this.checkedLastError = false; + this._lastError = null; + this.contextId = getUniqueId(); + this.unloaded = false; + this.extension = extension; + this.jsonSandbox = null; + this.active = true; + this.incognito = null; + this.messageManager = null; + this.docShell = null; + this.contentWindow = null; + this.innerWindowID = 0; + } + + setContentWindow(contentWindow) { + let {document} = contentWindow; + let docShell = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell); + + this.innerWindowID = getInnerWindowID(contentWindow); + this.messageManager = docShell.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIContentFrameMessageManager); + + if (this.incognito == null) { + this.incognito = PrivateBrowsingUtils.isContentWindowPrivate(contentWindow); + } + + MessageChannel.setupMessageManagers([this.messageManager]); + + let onPageShow = event => { + if (!event || event.target === document) { + this.docShell = docShell; + this.contentWindow = contentWindow; + this.active = true; + } + }; + let onPageHide = event => { + if (!event || event.target === document) { + // Put this off until the next tick. + Promise.resolve().then(() => { + this.docShell = null; + this.contentWindow = null; + this.active = false; + }); + } + }; + + onPageShow(); + contentWindow.addEventListener("pagehide", onPageHide, true); + contentWindow.addEventListener("pageshow", onPageShow, true); + this.callOnClose({ + close: () => { + onPageHide(); + if (this.active) { + contentWindow.removeEventListener("pagehide", onPageHide, true); + contentWindow.removeEventListener("pageshow", onPageShow, true); + } + }, + }); + } + + get cloneScope() { + throw new Error("Not implemented"); + } + + get principal() { + throw new Error("Not implemented"); + } + + runSafe(...args) { + if (this.unloaded) { + Cu.reportError("context.runSafe called after context unloaded"); + } else if (!this.active) { + Cu.reportError("context.runSafe called while context is inactive"); + } else { + return runSafeSync(this, ...args); + } + } + + runSafeWithoutClone(...args) { + if (this.unloaded) { + Cu.reportError("context.runSafeWithoutClone called after context unloaded"); + } else if (!this.active) { + Cu.reportError("context.runSafeWithoutClone called while context is inactive"); + } else { + return runSafeSyncWithoutClone(...args); + } + } + + checkLoadURL(url, options = {}) { + let ssm = Services.scriptSecurityManager; + + let flags = ssm.STANDARD; + if (!options.allowScript) { + flags |= ssm.DISALLOW_SCRIPT; + } + if (!options.allowInheritsPrincipal) { + flags |= ssm.DISALLOW_INHERIT_PRINCIPAL; + } + if (options.dontReportErrors) { + flags |= ssm.DONT_REPORT_ERRORS; + } + + try { + ssm.checkLoadURIStrWithPrincipal(this.principal, url, flags); + } catch (e) { + return false; + } + return true; + } + + /** + * Safely call JSON.stringify() on an object that comes from an + * extension. + * + * @param {array} args Arguments for JSON.stringify() + * @returns {string} The stringified representation of obj + */ + jsonStringify(...args) { + if (!this.jsonSandbox) { + this.jsonSandbox = Cu.Sandbox(this.principal, { + sameZoneAs: this.cloneScope, + wantXrays: false, + }); + } + + return Cu.waiveXrays(this.jsonSandbox.JSON).stringify(...args); + } + + callOnClose(obj) { + this.onClose.add(obj); + } + + forgetOnClose(obj) { + this.onClose.delete(obj); + } + + /** + * A wrapper around MessageChannel.sendMessage which adds the extension ID + * to the recipient object, and ensures replies are not processed after the + * context has been unloaded. + * + * @param {nsIMessageManager} target + * @param {string} messageName + * @param {object} data + * @param {object} [options] + * @param {object} [options.sender] + * @param {object} [options.recipient] + * + * @returns {Promise} + */ + sendMessage(target, messageName, data, options = {}) { + options.recipient = Object.assign({extensionId: this.extension.id}, options.recipient); + options.sender = options.sender || {}; + + options.sender.extensionId = this.extension.id; + options.sender.contextId = this.contextId; + + return MessageChannel.sendMessage(target, messageName, data, options); + } + + get lastError() { + this.checkedLastError = true; + return this._lastError; + } + + set lastError(val) { + this.checkedLastError = false; + this._lastError = val; + } + + /** + * Normalizes the given error object for use by the target scope. If + * the target is an error object which belongs to that scope, it is + * returned as-is. If it is an ordinary object with a `message` + * property, it is converted into an error belonging to the target + * scope. If it is an Error object which does *not* belong to the + * clone scope, it is reported, and converted to an unexpected + * exception error. + * + * @param {Error|object} error + * @returns {Error} + */ + normalizeError(error) { + if (error instanceof this.cloneScope.Error) { + return error; + } + let message; + if (instanceOf(error, "Object") || error instanceof ExtensionError) { + message = error.message; + } else if (typeof error == "object" && + this.principal.subsumes(Cu.getObjectPrincipal(error))) { + message = error.message; + } else { + Cu.reportError(error); + } + message = message || "An unexpected error occurred"; + return new this.cloneScope.Error(message); + } + + /** + * Sets the value of `.lastError` to `error`, calls the given + * callback, and reports an error if the value has not been checked + * when the callback returns. + * + * @param {object} error An object with a `message` property. May + * optionally be an `Error` object belonging to the target scope. + * @param {function} callback The callback to call. + * @returns {*} The return value of callback. + */ + withLastError(error, callback) { + this.lastError = this.normalizeError(error); + try { + return callback(); + } finally { + if (!this.checkedLastError) { + Cu.reportError(`Unchecked lastError value: ${this.lastError}`); + } + this.lastError = null; + } + } + + /** + * Wraps the given promise so it can be safely returned to extension + * code in this context. + * + * If `callback` is provided, however, it is used as a completion + * function for the promise, and no promise is returned. In this case, + * the callback is called when the promise resolves or rejects. In the + * latter case, `lastError` is set to the rejection value, and the + * callback function must check `browser.runtime.lastError` or + * `extension.runtime.lastError` in order to prevent it being reported + * to the console. + * + * @param {Promise} promise The promise with which to wrap the + * callback. May resolve to a `SpreadArgs` instance, in which case + * each element will be used as a separate argument. + * + * Unless the promise object belongs to the cloneScope global, its + * resolution value is cloned into cloneScope prior to calling the + * `callback` function or resolving the wrapped promise. + * + * @param {function} [callback] The callback function to wrap + * + * @returns {Promise|undefined} If callback is null, a promise object + * belonging to the target scope. Otherwise, undefined. + */ + wrapPromise(promise, callback = null) { + let runSafe = this.runSafe.bind(this); + if (promise instanceof this.cloneScope.Promise) { + runSafe = this.runSafeWithoutClone.bind(this); + } + + if (callback) { + promise.then( + args => { + if (this.unloaded) { + dump(`Promise resolved after context unloaded\n`); + } else if (!this.active) { + dump(`Promise resolved while context is inactive\n`); + } else if (args instanceof SpreadArgs) { + runSafe(callback, ...args); + } else { + runSafe(callback, args); + } + }, + error => { + this.withLastError(error, () => { + if (this.unloaded) { + dump(`Promise rejected after context unloaded\n`); + } else if (!this.active) { + dump(`Promise rejected while context is inactive\n`); + } else { + this.runSafeWithoutClone(callback); + } + }); + }); + } else { + return new this.cloneScope.Promise((resolve, reject) => { + promise.then( + value => { + if (this.unloaded) { + dump(`Promise resolved after context unloaded\n`); + } else if (!this.active) { + dump(`Promise resolved while context is inactive\n`); + } else if (value instanceof SpreadArgs) { + runSafe(resolve, value.length == 1 ? value[0] : value); + } else { + runSafe(resolve, value); + } + }, + value => { + if (this.unloaded) { + dump(`Promise rejected after context unloaded: ${value && value.message}\n`); + } else if (!this.active) { + dump(`Promise rejected while context is inactive: ${value && value.message}\n`); + } else { + this.runSafeWithoutClone(reject, this.normalizeError(value)); + } + }); + }); + } + } + + unload() { + this.unloaded = true; + + MessageChannel.abortResponses({ + extensionId: this.extension.id, + contextId: this.contextId, + }); + + for (let obj of this.onClose) { + obj.close(); + } + } + + /** + * A simple proxy for unload(), for use with callOnClose(). + */ + close() { + this.unload(); + } +} + +/** + * An object that runs the implementation of a schema API. Instantiations of + * this interfaces are used by Schemas.jsm. + * + * @interface + */ +class SchemaAPIInterface { + /** + * Calls this as a function that returns its return value. + * + * @abstract + * @param {Array} args The parameters for the function. + * @returns {*} The return value of the invoked function. + */ + callFunction(args) { + throw new Error("Not implemented"); + } + + /** + * Calls this as a function and ignores its return value. + * + * @abstract + * @param {Array} args The parameters for the function. + */ + callFunctionNoReturn(args) { + throw new Error("Not implemented"); + } + + /** + * Calls this as a function that completes asynchronously. + * + * @abstract + * @param {Array} args The parameters for the function. + * @param {function(*)} [callback] The callback to be called when the function + * completes. + * @returns {Promise|undefined} Must be void if `callback` is set, and a + * promise otherwise. The promise is resolved when the function completes. + */ + callAsyncFunction(args, callback) { + throw new Error("Not implemented"); + } + + /** + * Retrieves the value of this as a property. + * + * @abstract + * @returns {*} The value of the property. + */ + getProperty() { + throw new Error("Not implemented"); + } + + /** + * Assigns the value to this as property. + * + * @abstract + * @param {string} value The new value of the property. + */ + setProperty(value) { + throw new Error("Not implemented"); + } + + /** + * Registers a `listener` to this as an event. + * + * @abstract + * @param {function} listener The callback to be called when the event fires. + * @param {Array} args Extra parameters for EventManager.addListener. + * @see EventManager.addListener + */ + addListener(listener, args) { + throw new Error("Not implemented"); + } + + /** + * Checks whether `listener` is listening to this as an event. + * + * @abstract + * @param {function} listener The event listener. + * @returns {boolean} Whether `listener` is registered with this as an event. + * @see EventManager.hasListener + */ + hasListener(listener) { + throw new Error("Not implemented"); + } + + /** + * Unregisters `listener` from this as an event. + * + * @abstract + * @param {function} listener The event listener. + * @see EventManager.removeListener + */ + removeListener(listener) { + throw new Error("Not implemented"); + } +} + +/** + * An object that runs a locally implemented API. + */ +class LocalAPIImplementation extends SchemaAPIInterface { + /** + * Constructs an implementation of the `name` method or property of `pathObj`. + * + * @param {object} pathObj The object containing the member with name `name`. + * @param {string} name The name of the implemented member. + * @param {BaseContext} context The context in which the schema is injected. + */ + constructor(pathObj, name, context) { + super(); + this.pathObj = pathObj; + this.name = name; + this.context = context; + } + + callFunction(args) { + return this.pathObj[this.name](...args); + } + + callFunctionNoReturn(args) { + this.pathObj[this.name](...args); + } + + callAsyncFunction(args, callback) { + let promise; + try { + promise = this.pathObj[this.name](...args) || Promise.resolve(); + } catch (e) { + promise = Promise.reject(e); + } + return this.context.wrapPromise(promise, callback); + } + + getProperty() { + return this.pathObj[this.name]; + } + + setProperty(value) { + this.pathObj[this.name] = value; + } + + addListener(listener, args) { + try { + this.pathObj[this.name].addListener.call(null, listener, ...args); + } catch (e) { + throw this.context.normalizeError(e); + } + } + + hasListener(listener) { + return this.pathObj[this.name].hasListener.call(null, listener); + } + + removeListener(listener) { + this.pathObj[this.name].removeListener.call(null, listener); + } +} + +/** + * This object loads the ext-*.js scripts that define the extension API. + * + * This class instance is shared with the scripts that it loads, so that the + * ext-*.js scripts and the instantiator can communicate with each other. + */ +class SchemaAPIManager extends EventEmitter { + /** + * @param {string} processType + * "main" - The main, one and only chrome browser process. + * "addon" - An addon process. + * "content" - A content process. + */ + constructor(processType) { + super(); + this.processType = processType; + this.global = this._createExtGlobal(); + this._scriptScopes = []; + this._schemaApis = { + addon_parent: [], + addon_child: [], + content_parent: [], + content_child: [], + }; + } + + /** + * Create a global object that is used as the shared global for all ext-*.js + * scripts that are loaded via `loadScript`. + * + * @returns {object} A sandbox that is used as the global by `loadScript`. + */ + _createExtGlobal() { + let global = Cu.Sandbox(Services.scriptSecurityManager.getSystemPrincipal(), { + wantXrays: false, + sandboxName: `Namespace of ext-*.js scripts for ${this.processType}`, + }); + + Object.assign(global, {global, Cc, Ci, Cu, Cr, XPCOMUtils, extensions: this}); + + XPCOMUtils.defineLazyGetter(global, "console", getConsole); + + XPCOMUtils.defineLazyModuleGetter(global, "require", + "resource://devtools/shared/Loader.jsm"); + + return global; + } + + /** + * Load an ext-*.js script. The script runs in its own scope, if it wishes to + * share state with another script it can assign to the `global` variable. If + * it wishes to communicate with this API manager, use `extensions`. + * + * @param {string} scriptUrl The URL of the ext-*.js script. + */ + loadScript(scriptUrl) { + // Create the object in the context of the sandbox so that the script runs + // in the sandbox's context instead of here. + let scope = Cu.createObjectIn(this.global); + + Services.scriptloader.loadSubScript(scriptUrl, scope, "UTF-8"); + + // Save the scope to avoid it being garbage collected. + this._scriptScopes.push(scope); + } + + /** + * Called by an ext-*.js script to register an API. + * + * @param {string} namespace The API namespace. + * Intended to match the namespace of the generated API, but not used at + * the moment - see bugzil.la/1295774. + * @param {string} envType Restricts the API to contexts that run in the + * given environment. Must be one of the following: + * - "addon_parent" - addon APIs that runs in the main process. + * - "addon_child" - addon APIs that runs in an addon process. + * - "content_parent" - content script APIs that runs in the main process. + * - "content_child" - content script APIs that runs in a content process. + * @param {function(BaseContext)} getAPI A function that returns an object + * that will be merged with |chrome| and |browser|. The next example adds + * the create, update and remove methods to the tabs API. + * + * registerSchemaAPI("tabs", "addon_parent", (context) => ({ + * tabs: { create, update }, + * })); + * registerSchemaAPI("tabs", "addon_parent", (context) => ({ + * tabs: { remove }, + * })); + */ + registerSchemaAPI(namespace, envType, getAPI) { + this._schemaApis[envType].push({namespace, getAPI}); + } + + /** + * Exports all registered scripts to `obj`. + * + * @param {BaseContext} context The context for which the API bindings are + * generated. + * @param {object} obj The destination of the API. + */ + generateAPIs(context, obj) { + let apis = this._schemaApis[context.envType]; + if (!apis) { + Cu.reportError(`No APIs have been registered for ${context.envType}`); + return; + } + SchemaAPIManager.generateAPIs(context, apis, obj); + } + + /** + * Mash together all the APIs from `apis` into `obj`. + * + * @param {BaseContext} context The context for which the API bindings are + * generated. + * @param {Array} apis A list of objects, see `registerSchemaAPI`. + * @param {object} obj The destination of the API. + */ + static generateAPIs(context, apis, obj) { + // Recursively copy properties from source to dest. + function copy(dest, source) { + for (let prop in source) { + let desc = Object.getOwnPropertyDescriptor(source, prop); + if (typeof(desc.value) == "object") { + if (!(prop in dest)) { + dest[prop] = {}; + } + copy(dest[prop], source[prop]); + } else { + Object.defineProperty(dest, prop, desc); + } + } + } + + for (let api of apis) { + if (Schemas.checkPermissions(api.namespace, context.extension)) { + api = api.getAPI(context); + copy(obj, api); + } + } + } +} + +const ExtensionCommon = { + BaseContext, + LocalAPIImplementation, + SchemaAPIInterface, + SchemaAPIManager, +}; diff --git a/toolkit/components/webextensions/ExtensionContent.jsm b/toolkit/components/webextensions/ExtensionContent.jsm new file mode 100644 index 000000000..5f9b88f35 --- /dev/null +++ b/toolkit/components/webextensions/ExtensionContent.jsm @@ -0,0 +1,1050 @@ +/* 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"; + +this.EXPORTED_SYMBOLS = ["ExtensionContent"]; + +/* globals ExtensionContent */ + +/* + * This file handles the content process side of extensions. It mainly + * takes care of content script injection, content script APIs, and + * messaging. + * + * This file is also the initial entry point for addon processes. + * ExtensionChild.jsm is responsible for functionality specific to addon + * processes. + */ + +const Ci = Components.interfaces; +const Cc = Components.classes; +const Cu = Components.utils; +const Cr = Components.results; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/AppConstants.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement", + "resource://gre/modules/ExtensionManagement.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "LanguageDetector", + "resource:///modules/translation/LanguageDetector.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "MatchPattern", + "resource://gre/modules/MatchPattern.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "MatchGlobs", + "resource://gre/modules/MatchPattern.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel", + "resource://gre/modules/MessageChannel.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PromiseUtils", + "resource://gre/modules/PromiseUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Schemas", + "resource://gre/modules/Schemas.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "WebNavigationFrames", + "resource://gre/modules/WebNavigationFrames.jsm"); + +Cu.import("resource://gre/modules/ExtensionChild.jsm"); +Cu.import("resource://gre/modules/ExtensionCommon.jsm"); +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +const { + EventEmitter, + LocaleData, + defineLazyGetter, + flushJarCache, + getInnerWindowID, + promiseDocumentReady, + runSafeSyncWithoutClone, +} = ExtensionUtils; + +const { + BaseContext, + SchemaAPIManager, +} = ExtensionCommon; + +const { + ChildAPIManager, + Messenger, +} = ExtensionChild; + +XPCOMUtils.defineLazyGetter(this, "console", ExtensionUtils.getConsole); + +const CATEGORY_EXTENSION_SCRIPTS_CONTENT = "webextension-scripts-content"; + +function isWhenBeforeOrSame(when1, when2) { + let table = {"document_start": 0, + "document_end": 1, + "document_idle": 2}; + return table[when1] <= table[when2]; +} + +var apiManager = new class extends SchemaAPIManager { + constructor() { + super("content"); + this.initialized = false; + } + + generateAPIs(...args) { + if (!this.initialized) { + this.initialized = true; + for (let [/* name */, value] of XPCOMUtils.enumerateCategoryEntries(CATEGORY_EXTENSION_SCRIPTS_CONTENT)) { + this.loadScript(value); + } + } + return super.generateAPIs(...args); + } + + registerSchemaAPI(namespace, envType, getAPI) { + if (envType == "content_child") { + super.registerSchemaAPI(namespace, envType, getAPI); + } + } +}(); + +// Represents a content script. +function Script(extension, options, deferred = PromiseUtils.defer()) { + this.extension = extension; + this.options = options; + this.run_at = this.options.run_at; + this.js = this.options.js || []; + this.css = this.options.css || []; + this.remove_css = this.options.remove_css; + this.match_about_blank = this.options.match_about_blank; + + this.deferred = deferred; + + this.matches_ = new MatchPattern(this.options.matches); + this.exclude_matches_ = new MatchPattern(this.options.exclude_matches || null); + // TODO: MatchPattern should pre-mangle host-only patterns so that we + // don't need to call a separate match function. + this.matches_host_ = new MatchPattern(this.options.matchesHost || null); + this.include_globs_ = new MatchGlobs(this.options.include_globs); + this.exclude_globs_ = new MatchGlobs(this.options.exclude_globs); + + this.requiresCleanup = !this.remove_css && (this.css.length > 0 || options.cssCode); +} + +Script.prototype = { + get cssURLs() { + // We can handle CSS urls (css) and CSS code (cssCode). + let urls = []; + for (let url of this.css) { + urls.push(this.extension.baseURI.resolve(url)); + } + + if (this.options.cssCode) { + let url = "data:text/css;charset=utf-8," + encodeURIComponent(this.options.cssCode); + urls.push(url); + } + + return urls; + }, + + matches(window) { + let uri = window.document.documentURIObject; + let principal = window.document.nodePrincipal; + + // If mozAddonManager is present on this page, don't allow + // content scripts. + if (window.navigator.mozAddonManager !== undefined) { + return false; + } + + if (this.match_about_blank && ["about:blank", "about:srcdoc"].includes(uri.spec)) { + // When matching about:blank/srcdoc documents, the checks below + // need to be performed against the "owner" document's URI. + uri = principal.URI; + } + + // Documents from data: URIs also inherit the principal. + if (Services.netUtils.URIChainHasFlags(uri, Ci.nsIProtocolHandler.URI_INHERITS_SECURITY_CONTEXT)) { + if (!this.match_about_blank) { + return false; + } + uri = principal.URI; + } + + if (!(this.matches_.matches(uri) || this.matches_host_.matchesIgnoringPath(uri))) { + return false; + } + + if (this.exclude_matches_.matches(uri)) { + return false; + } + + if (this.options.include_globs != null) { + if (!this.include_globs_.matches(uri.spec)) { + return false; + } + } + + if (this.exclude_globs_.matches(uri.spec)) { + return false; + } + + if (this.options.frame_id != null) { + if (WebNavigationFrames.getFrameId(window) != this.options.frame_id) { + return false; + } + } else if (!this.options.all_frames && window.top != window) { + return false; + } + + return true; + }, + + cleanup(window) { + if (!this.remove_css) { + let winUtils = window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils); + + for (let url of this.cssURLs) { + runSafeSyncWithoutClone(winUtils.removeSheetUsingURIString, url, winUtils.AUTHOR_SHEET); + } + } + }, + + /** + * Tries to inject this script into the given window and sandbox, if + * there are pending operations for the window's current load state. + * + * @param {Window} window + * The DOM Window to inject the scripts and CSS into. + * @param {Sandbox} sandbox + * A Sandbox inheriting from `window` in which to evaluate the + * injected scripts. + * @param {function} shouldRun + * A function which, when passed the document load state that a + * script is expected to run at, returns `true` if we should + * currently be injecting scripts for that load state. + * + * For initial injection of a script, this function should + * return true if the document is currently in or has already + * passed through the given state. For injections triggered by + * document state changes, it should only return true if the + * given state exactly matches the state that triggered the + * change. + * @param {string} when + * The document's current load state, or if triggered by a + * document state change, the new document state that triggered + * the injection. + */ + tryInject(window, sandbox, shouldRun, when) { + if (shouldRun("document_start")) { + let {cssURLs} = this; + if (cssURLs.length > 0) { + let winUtils = window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils); + + let method = this.remove_css ? winUtils.removeSheetUsingURIString : winUtils.loadSheetUsingURIString; + for (let url of cssURLs) { + runSafeSyncWithoutClone(method, url, winUtils.AUTHOR_SHEET); + } + + this.deferred.resolve(); + } + } + + let result; + let scheduled = this.run_at || "document_idle"; + if (shouldRun(scheduled)) { + for (let [i, url] of this.js.entries()) { + let options = { + target: sandbox, + charset: "UTF-8", + // Inject the last script asynchronously unless we're expected to + // inject before any page scripts have run, and we haven't already + // missed that boat. + async: (i === this.js.length - 1) && + (this.run_at !== "document_start" || when !== "document_start"), + }; + try { + result = Services.scriptloader.loadSubScriptWithOptions(url, options); + } catch (e) { + Cu.reportError(e); + this.deferred.reject(e); + } + } + + if (this.options.jsCode) { + try { + result = Cu.evalInSandbox(this.options.jsCode, sandbox, "latest"); + } catch (e) { + Cu.reportError(e); + this.deferred.reject(e); + } + } + + this.deferred.resolve(result); + } + }, +}; + +function getWindowMessageManager(contentWindow) { + let ir = contentWindow.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell) + .QueryInterface(Ci.nsIInterfaceRequestor); + try { + return ir.getInterface(Ci.nsIContentFrameMessageManager); + } catch (e) { + // Some windows don't support this interface (hidden window). + return null; + } +} + +var DocumentManager; +var ExtensionManager; + +/** + * An execution context for semi-privileged extension content scripts. + * + * This is the child side of the ContentScriptContextParent class + * defined in ExtensionParent.jsm. + */ +class ContentScriptContextChild extends BaseContext { + constructor(extension, contentWindow, contextOptions = {}) { + super("content_child", extension); + + let {isExtensionPage} = contextOptions; + + this.isExtensionPage = isExtensionPage; + + this.setContentWindow(contentWindow); + + let frameId = WebNavigationFrames.getFrameId(contentWindow); + this.frameId = frameId; + + this.scripts = []; + + let contentPrincipal = contentWindow.document.nodePrincipal; + let ssm = Services.scriptSecurityManager; + + // copy origin attributes from the content window origin attributes to + // preserve the user context id. overwrite the addonId. + let attrs = contentPrincipal.originAttributes; + attrs.addonId = this.extension.id; + let extensionPrincipal = ssm.createCodebasePrincipal(this.extension.baseURI, attrs); + + let principal; + if (ssm.isSystemPrincipal(contentPrincipal)) { + // Make sure we don't hand out the system principal by accident. + // also make sure that the null principal has the right origin attributes + principal = ssm.createNullPrincipal(attrs); + } else { + principal = [contentPrincipal, extensionPrincipal]; + } + + if (isExtensionPage) { + if (ExtensionManagement.getAddonIdForWindow(this.contentWindow) != this.extension.id) { + throw new Error("Invalid target window for this extension context"); + } + // This is an iframe with content script API enabled and its principal should be the + // contentWindow itself. (we create a sandbox with the contentWindow as principal and with X-rays disabled + // because it enables us to create the APIs object in this sandbox object and then copying it + // into the iframe's window, see Bug 1214658 for rationale) + this.sandbox = Cu.Sandbox(contentWindow, { + sandboxName: `Web-Accessible Extension Page ${this.extension.id}`, + sandboxPrototype: contentWindow, + sameZoneAs: contentWindow, + wantXrays: false, + isWebExtensionContentScript: true, + }); + } else { + // This metadata is required by the Developer Tools, in order for + // the content script to be associated with both the extension and + // the tab holding the content page. + let metadata = { + "inner-window-id": this.innerWindowID, + addonId: attrs.addonId, + }; + + this.sandbox = Cu.Sandbox(principal, { + metadata, + sandboxName: `Content Script ${this.extension.id}`, + sandboxPrototype: contentWindow, + sameZoneAs: contentWindow, + wantXrays: true, + isWebExtensionContentScript: true, + wantExportHelpers: true, + wantGlobalProperties: ["XMLHttpRequest", "fetch"], + originAttributes: attrs, + }); + + Cu.evalInSandbox(` + window.JSON = JSON; + window.XMLHttpRequest = XMLHttpRequest; + window.fetch = fetch; + `, this.sandbox); + } + + Object.defineProperty(this, "principal", { + value: Cu.getObjectPrincipal(this.sandbox), + enumerable: true, + configurable: true, + }); + + this.url = contentWindow.location.href; + + defineLazyGetter(this, "chromeObj", () => { + let chromeObj = Cu.createObjectIn(this.sandbox); + + Schemas.inject(chromeObj, this.childManager); + return chromeObj; + }); + + Schemas.exportLazyGetter(this.sandbox, "browser", () => this.chromeObj); + Schemas.exportLazyGetter(this.sandbox, "chrome", () => this.chromeObj); + + // This is an iframe with content script API enabled (bug 1214658) + if (isExtensionPage) { + Schemas.exportLazyGetter(this.contentWindow, + "browser", () => this.chromeObj); + Schemas.exportLazyGetter(this.contentWindow, + "chrome", () => this.chromeObj); + } + } + + get cloneScope() { + return this.sandbox; + } + + execute(script, shouldRun, when) { + script.tryInject(this.contentWindow, this.sandbox, shouldRun, when); + } + + addScript(script, when) { + let state = DocumentManager.getWindowState(this.contentWindow); + this.execute(script, scheduled => isWhenBeforeOrSame(scheduled, state), when); + + // Save the script in case it has pending operations in later load + // states, but only if we're before document_idle, or require cleanup. + if (state != "document_idle" || script.requiresCleanup) { + this.scripts.push(script); + } + } + + triggerScripts(documentState) { + for (let script of this.scripts) { + this.execute(script, scheduled => scheduled == documentState, documentState); + } + if (documentState == "document_idle") { + // Don't bother saving scripts after document_idle. + this.scripts = this.scripts.filter(script => script.requiresCleanup); + } + } + + close() { + super.unload(); + + if (this.contentWindow) { + for (let script of this.scripts) { + if (script.requiresCleanup) { + script.cleanup(this.contentWindow); + } + } + + // Overwrite the content script APIs with an empty object if the APIs objects are still + // defined in the content window (bug 1214658). + if (this.isExtensionPage) { + Cu.createObjectIn(this.contentWindow, {defineAs: "browser"}); + Cu.createObjectIn(this.contentWindow, {defineAs: "chrome"}); + } + } + Cu.nukeSandbox(this.sandbox); + this.sandbox = null; + } +} + +defineLazyGetter(ContentScriptContextChild.prototype, "messenger", function() { + // The |sender| parameter is passed directly to the extension. + let sender = {id: this.extension.id, frameId: this.frameId, url: this.url}; + let filter = {extensionId: this.extension.id}; + let optionalFilter = {frameId: this.frameId}; + + return new Messenger(this, [this.messageManager], sender, filter, optionalFilter); +}); + +defineLazyGetter(ContentScriptContextChild.prototype, "childManager", function() { + let localApis = {}; + apiManager.generateAPIs(this, localApis); + + let childManager = new ChildAPIManager(this, this.messageManager, localApis, { + envType: "content_parent", + url: this.url, + }); + + this.callOnClose(childManager); + + return childManager; +}); + +// Responsible for creating ExtensionContexts and injecting content +// scripts into them when new documents are created. +DocumentManager = { + extensionCount: 0, + + // Map[windowId -> Map[extensionId -> ContentScriptContextChild]] + contentScriptWindows: new Map(), + + // Map[windowId -> ContentScriptContextChild] + extensionPageWindows: new Map(), + + init() { + Services.obs.addObserver(this, "content-document-global-created", false); + Services.obs.addObserver(this, "document-element-inserted", false); + Services.obs.addObserver(this, "inner-window-destroyed", false); + }, + + uninit() { + Services.obs.removeObserver(this, "content-document-global-created"); + Services.obs.removeObserver(this, "document-element-inserted"); + Services.obs.removeObserver(this, "inner-window-destroyed"); + }, + + getWindowState(contentWindow) { + let readyState = contentWindow.document.readyState; + if (readyState == "complete") { + return "document_idle"; + } + if (readyState == "interactive") { + return "document_end"; + } + return "document_start"; + }, + + loadInto(window) { + // Enable the content script APIs should be available in subframes' window + // if it is recognized as a valid addon id (see Bug 1214658 for rationale). + const { + NO_PRIVILEGES, + CONTENTSCRIPT_PRIVILEGES, + FULL_PRIVILEGES, + } = ExtensionManagement.API_LEVELS; + let extensionId = ExtensionManagement.getAddonIdForWindow(window); + let apiLevel = ExtensionManagement.getAPILevelForWindow(window, extensionId); + + if (apiLevel != NO_PRIVILEGES) { + let extension = ExtensionManager.get(extensionId); + if (extension) { + if (apiLevel == CONTENTSCRIPT_PRIVILEGES) { + DocumentManager.getExtensionPageContext(extension, window); + } else if (apiLevel == FULL_PRIVILEGES) { + ExtensionChild.createExtensionContext(extension, window); + } + } + } + }, + + observe: function(subject, topic, data) { + // For some types of documents (about:blank), we only see the first + // notification, for others (data: URIs) we only observe the second. + if (topic == "content-document-global-created" || topic == "document-element-inserted") { + let document = subject; + let window = document && document.defaultView; + + if (topic == "content-document-global-created") { + window = subject; + document = window && window.document; + } + + if (!document || !document.location || !window) { + return; + } + + // Make sure we only load into frames that ExtensionContent.init + // was called on (i.e., not frames for social or sidebars). + let mm = getWindowMessageManager(window); + if (!mm || !ExtensionContent.globals.has(mm)) { + return; + } + + // Load on document-element-inserted, except for about:blank which doesn't + // see it, and needs special late handling on DOMContentLoaded event. + if (topic === "document-element-inserted") { + this.loadInto(window); + this.trigger("document_start", window); + } + + /* eslint-disable mozilla/balanced-listeners */ + window.addEventListener("DOMContentLoaded", this, true); + window.addEventListener("load", this, true); + /* eslint-enable mozilla/balanced-listeners */ + } else if (topic == "inner-window-destroyed") { + let windowId = subject.QueryInterface(Ci.nsISupportsPRUint64).data; + + MessageChannel.abortResponses({innerWindowID: windowId}); + + // Close any existent content-script context for the destroyed window. + if (this.contentScriptWindows.has(windowId)) { + let extensions = this.contentScriptWindows.get(windowId); + for (let [, context] of extensions) { + context.close(); + } + + this.contentScriptWindows.delete(windowId); + } + + // Close any existent iframe extension page context for the destroyed window. + if (this.extensionPageWindows.has(windowId)) { + let context = this.extensionPageWindows.get(windowId); + context.close(); + this.extensionPageWindows.delete(windowId); + } + + ExtensionChild.destroyExtensionContext(windowId); + } + }, + + handleEvent: function(event) { + let window = event.currentTarget; + if (event.target != window.document) { + // We use capturing listeners so we have precedence over content script + // listeners, but only care about events targeted to the element we're + // listening on. + return; + } + window.removeEventListener(event.type, this, true); + + // Need to check if we're still on the right page? Greasemonkey does this. + + if (event.type == "DOMContentLoaded") { + // By this time, we can be sure if this is an explicit about:blank + // document, and if it needs special late loading and fake trigger. + if (window.location.href === "about:blank") { + this.loadInto(window); + this.trigger("document_start", window); + } + this.trigger("document_end", window); + } else if (event.type == "load") { + this.trigger("document_idle", window); + } + }, + + // Used to executeScript, insertCSS and removeCSS. + executeScript(global, extensionId, options) { + let extension = ExtensionManager.get(extensionId); + + let executeInWin = (window) => { + let deferred = PromiseUtils.defer(); + let script = new Script(extension, options, deferred); + + if (script.matches(window)) { + let context = this.getContentScriptContext(extension, window); + context.addScript(script); + return deferred.promise; + } + return null; + }; + + let promises = Array.from(this.enumerateWindows(global.docShell), executeInWin) + .filter(promise => promise); + + if (!promises.length) { + let details = {}; + for (let key of ["all_frames", "frame_id", "matches_about_blank", "matchesHost"]) { + if (key in options) { + details[key] = options[key]; + } + } + + return Promise.reject({message: `No window matching ${JSON.stringify(details)}`}); + } + if (!options.all_frames && promises.length > 1) { + return Promise.reject({message: `Internal error: Script matched multiple windows`}); + } + return Promise.all(promises); + }, + + enumerateWindows: function* (docShell) { + let window = docShell.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindow); + yield window; + + for (let i = 0; i < docShell.childCount; i++) { + let child = docShell.getChildAt(i).QueryInterface(Ci.nsIDocShell); + yield* this.enumerateWindows(child); + } + }, + + getContentScriptGlobalsForWindow(window) { + let winId = getInnerWindowID(window); + let extensions = this.contentScriptWindows.get(winId); + + if (extensions) { + return Array.from(extensions.values(), ctx => ctx.sandbox); + } + + return []; + }, + + getContentScriptContext(extension, window) { + let winId = getInnerWindowID(window); + if (!this.contentScriptWindows.has(winId)) { + this.contentScriptWindows.set(winId, new Map()); + } + + let extensions = this.contentScriptWindows.get(winId); + if (!extensions.has(extension.id)) { + let context = new ContentScriptContextChild(extension, window); + extensions.set(extension.id, context); + } + + return extensions.get(extension.id); + }, + + getExtensionPageContext(extension, window) { + let winId = getInnerWindowID(window); + + let context = this.extensionPageWindows.get(winId); + if (!context) { + let context = new ContentScriptContextChild(extension, window, {isExtensionPage: true}); + this.extensionPageWindows.set(winId, context); + } + + return context; + }, + + startupExtension(extensionId) { + if (this.extensionCount == 0) { + this.init(); + } + this.extensionCount++; + + let extension = ExtensionManager.get(extensionId); + for (let global of ExtensionContent.globals.keys()) { + // Note that we miss windows in the bfcache here. In theory we + // could execute content scripts on a pageshow event for that + // window, but that seems extreme. + for (let window of this.enumerateWindows(global.docShell)) { + for (let script of extension.scripts) { + if (script.matches(window)) { + let context = this.getContentScriptContext(extension, window); + context.addScript(script); + } + } + } + } + }, + + shutdownExtension(extensionId) { + // Clean up content-script contexts on extension shutdown. + for (let [, extensions] of this.contentScriptWindows) { + let context = extensions.get(extensionId); + if (context) { + context.close(); + extensions.delete(extensionId); + } + } + + // Clean up iframe extension page contexts on extension shutdown. + for (let [winId, context] of this.extensionPageWindows) { + if (context.extension.id == extensionId) { + context.close(); + this.extensionPageWindows.delete(winId); + } + } + + ExtensionChild.shutdownExtension(extensionId); + + MessageChannel.abortResponses({extensionId}); + + this.extensionCount--; + if (this.extensionCount == 0) { + this.uninit(); + } + }, + + trigger(when, window) { + if (when === "document_start") { + for (let extension of ExtensionManager.extensions.values()) { + for (let script of extension.scripts) { + if (script.matches(window)) { + let context = this.getContentScriptContext(extension, window); + context.addScript(script, when); + } + } + } + } else { + let contexts = this.contentScriptWindows.get(getInnerWindowID(window)) || new Map(); + for (let context of contexts.values()) { + context.triggerScripts(when); + } + } + }, +}; + +// Represents a browser extension in the content process. +class BrowserExtensionContent extends EventEmitter { + constructor(data) { + super(); + + this.id = data.id; + this.uuid = data.uuid; + this.data = data; + this.instanceId = data.instanceId; + + this.MESSAGE_EMIT_EVENT = `Extension:EmitEvent:${this.instanceId}`; + Services.cpmm.addMessageListener(this.MESSAGE_EMIT_EVENT, this); + + this.scripts = data.content_scripts.map(scriptData => new Script(this, scriptData)); + this.webAccessibleResources = new MatchGlobs(data.webAccessibleResources); + this.whiteListedHosts = new MatchPattern(data.whiteListedHosts); + this.permissions = data.permissions; + this.principal = data.principal; + + this.localeData = new LocaleData(data.localeData); + + this.manifest = data.manifest; + this.baseURI = Services.io.newURI(data.baseURL, null, null); + + // Only used in addon processes. + this.views = new Set(); + + let uri = Services.io.newURI(data.resourceURL, null, null); + + if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { + // Extension.jsm takes care of this in the parent. + ExtensionManagement.startupExtension(this.uuid, uri, this); + } + } + + shutdown() { + Services.cpmm.removeMessageListener(this.MESSAGE_EMIT_EVENT, this); + + if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { + ExtensionManagement.shutdownExtension(this.uuid); + } + } + + emit(event, ...args) { + Services.cpmm.sendAsyncMessage(this.MESSAGE_EMIT_EVENT, {event, args}); + + super.emit(event, ...args); + } + + receiveMessage({name, data}) { + if (name === this.MESSAGE_EMIT_EVENT) { + super.emit(data.event, ...data.args); + } + } + + localizeMessage(...args) { + return this.localeData.localizeMessage(...args); + } + + localize(...args) { + return this.localeData.localize(...args); + } + + hasPermission(perm) { + let match = /^manifest:(.*)/.exec(perm); + if (match) { + return this.manifest[match[1]] != null; + } + return this.permissions.has(perm); + } +} + +ExtensionManager = { + // Map[extensionId, BrowserExtensionContent] + extensions: new Map(), + + init() { + Schemas.init(); + ExtensionChild.initOnce(); + + Services.cpmm.addMessageListener("Extension:Startup", this); + Services.cpmm.addMessageListener("Extension:Shutdown", this); + Services.cpmm.addMessageListener("Extension:FlushJarCache", this); + + if (Services.cpmm.initialProcessData && "Extension:Extensions" in Services.cpmm.initialProcessData) { + let extensions = Services.cpmm.initialProcessData["Extension:Extensions"]; + for (let data of extensions) { + this.extensions.set(data.id, new BrowserExtensionContent(data)); + DocumentManager.startupExtension(data.id); + } + } + }, + + get(extensionId) { + return this.extensions.get(extensionId); + }, + + receiveMessage({name, data}) { + let extension; + switch (name) { + case "Extension:Startup": { + extension = new BrowserExtensionContent(data); + + this.extensions.set(data.id, extension); + + DocumentManager.startupExtension(data.id); + + Services.cpmm.sendAsyncMessage("Extension:StartupComplete"); + break; + } + + case "Extension:Shutdown": { + extension = this.extensions.get(data.id); + extension.shutdown(); + + DocumentManager.shutdownExtension(data.id); + + this.extensions.delete(data.id); + break; + } + + case "Extension:FlushJarCache": { + let nsIFile = Components.Constructor("@mozilla.org/file/local;1", "nsIFile", + "initWithPath"); + let file = new nsIFile(data.path); + flushJarCache(file); + Services.cpmm.sendAsyncMessage("Extension:FlushJarCacheComplete"); + break; + } + } + }, +}; + +class ExtensionGlobal { + constructor(global) { + this.global = global; + + MessageChannel.addListener(global, "Extension:Capture", this); + MessageChannel.addListener(global, "Extension:DetectLanguage", this); + MessageChannel.addListener(global, "Extension:Execute", this); + MessageChannel.addListener(global, "WebNavigation:GetFrame", this); + MessageChannel.addListener(global, "WebNavigation:GetAllFrames", this); + + this.windowId = global.content + .QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils) + .outerWindowID; + + global.sendAsyncMessage("Extension:TopWindowID", {windowId: this.windowId}); + } + + uninit() { + this.global.sendAsyncMessage("Extension:RemoveTopWindowID", {windowId: this.windowId}); + } + + get messageFilterStrict() { + return { + innerWindowID: getInnerWindowID(this.global.content), + }; + } + + receiveMessage({target, messageName, recipient, data}) { + switch (messageName) { + case "Extension:Capture": + return this.handleExtensionCapture(data.width, data.height, data.options); + case "Extension:DetectLanguage": + return this.handleDetectLanguage(target); + case "Extension:Execute": + return this.handleExtensionExecute(target, recipient.extensionId, data.options); + case "WebNavigation:GetFrame": + return this.handleWebNavigationGetFrame(data.options); + case "WebNavigation:GetAllFrames": + return this.handleWebNavigationGetAllFrames(); + } + } + + handleExtensionCapture(width, height, options) { + let win = this.global.content; + + const XHTML_NS = "http://www.w3.org/1999/xhtml"; + let canvas = win.document.createElementNS(XHTML_NS, "canvas"); + canvas.width = width; + canvas.height = height; + canvas.mozOpaque = true; + + let ctx = canvas.getContext("2d"); + + // We need to scale the image to the visible size of the browser, + // in order for the result to appear as the user sees it when + // settings like full zoom come into play. + ctx.scale(canvas.width / win.innerWidth, canvas.height / win.innerHeight); + + ctx.drawWindow(win, win.scrollX, win.scrollY, win.innerWidth, win.innerHeight, "#fff"); + + return canvas.toDataURL(`image/${options.format}`, options.quality / 100); + } + + handleDetectLanguage(target) { + let doc = target.content.document; + + return promiseDocumentReady(doc).then(() => { + let elem = doc.documentElement; + + let language = (elem.getAttribute("xml:lang") || elem.getAttribute("lang") || + doc.contentLanguage || null); + + // We only want the last element of the TLD here. + // Only country codes have any effect on the results, but other + // values cause no harm. + let tld = doc.location.hostname.match(/[a-z]*$/)[0]; + + // The CLD2 library used by the language detector is capable of + // analyzing raw HTML. Unfortunately, that takes much more memory, + // and since it's hosted by emscripten, and therefore can't shrink + // its heap after it's grown, it has a performance cost. + // So we send plain text instead. + let encoder = Cc["@mozilla.org/layout/documentEncoder;1?type=text/plain"].createInstance(Ci.nsIDocumentEncoder); + encoder.init(doc, "text/plain", encoder.SkipInvisibleContent); + let text = encoder.encodeToStringWithMaxLength(60 * 1024); + + let encoding = doc.characterSet; + + return LanguageDetector.detectLanguage({language, tld, text, encoding}) + .then(result => result.language === "un" ? "und" : result.language); + }); + } + + // Used to executeScript, insertCSS and removeCSS. + handleExtensionExecute(target, extensionId, options) { + return DocumentManager.executeScript(target, extensionId, options).then(result => { + try { + // Make sure we can structured-clone the result value before + // we try to send it back over the message manager. + Cu.cloneInto(result, target); + } catch (e) { + return Promise.reject({message: "Script returned non-structured-clonable data"}); + } + return result; + }); + } + + handleWebNavigationGetFrame({frameId}) { + return WebNavigationFrames.getFrame(this.global.docShell, frameId); + } + + handleWebNavigationGetAllFrames() { + return WebNavigationFrames.getAllFrames(this.global.docShell); + } +} + +this.ExtensionContent = { + globals: new Map(), + + init(global) { + this.globals.set(global, new ExtensionGlobal(global)); + ExtensionChild.init(global); + }, + + uninit(global) { + ExtensionChild.uninit(global); + this.globals.get(global).uninit(); + this.globals.delete(global); + }, + + // This helper is exported to be integrated in the devtools RDP actors, + // that can use it to retrieve the existent WebExtensions ContentScripts + // of a target window and be able to show the ContentScripts source in the + // DevTools Debugger panel. + getContentScriptGlobalsForWindow(window) { + return DocumentManager.getContentScriptGlobalsForWindow(window); + }, +}; + +ExtensionManager.init(); diff --git a/toolkit/components/webextensions/ExtensionManagement.jsm b/toolkit/components/webextensions/ExtensionManagement.jsm new file mode 100644 index 000000000..324c5b71b --- /dev/null +++ b/toolkit/components/webextensions/ExtensionManagement.jsm @@ -0,0 +1,321 @@ +/* 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"; + +this.EXPORTED_SYMBOLS = ["ExtensionManagement"]; + +const Ci = Components.interfaces; +const Cc = Components.classes; +const Cu = Components.utils; +const Cr = Components.results; + +Cu.import("resource://gre/modules/AppConstants.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionUtils", + "resource://gre/modules/ExtensionUtils.jsm"); + +XPCOMUtils.defineLazyGetter(this, "console", () => ExtensionUtils.getConsole()); + +XPCOMUtils.defineLazyGetter(this, "UUIDMap", () => { + let {UUIDMap} = Cu.import("resource://gre/modules/Extension.jsm", {}); + return UUIDMap; +}); + +/* + * This file should be kept short and simple since it's loaded even + * when no extensions are running. + */ + +// Keep track of frame IDs for content windows. Mostly we can just use +// the outer window ID as the frame ID. However, the API specifies +// that top-level windows have a frame ID of 0. So we need to keep +// track of which windows are top-level. This code listens to messages +// from ExtensionContent to do that. +var Frames = { + // Window IDs of top-level content windows. + topWindowIds: new Set(), + + init() { + if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { + return; + } + + Services.mm.addMessageListener("Extension:TopWindowID", this); + Services.mm.addMessageListener("Extension:RemoveTopWindowID", this, true); + }, + + isTopWindowId(windowId) { + return this.topWindowIds.has(windowId); + }, + + // Convert an outer window ID to a frame ID. An outer window ID of 0 + // is invalid. + getId(windowId) { + if (this.isTopWindowId(windowId)) { + return 0; + } + if (windowId == 0) { + return -1; + } + return windowId; + }, + + // Convert an outer window ID for a parent window to a frame + // ID. Outer window IDs follow the same convention that + // |window.top.parent === window.top|. The API works differently, + // giving a frame ID of -1 for the the parent of a top-level + // window. This function handles the conversion. + getParentId(parentWindowId, windowId) { + if (parentWindowId == windowId) { + // We have a top-level window. + return -1; + } + + // Not a top-level window. Just return the ID as normal. + return this.getId(parentWindowId); + }, + + receiveMessage({name, data}) { + switch (name) { + case "Extension:TopWindowID": + // FIXME: Need to handle the case where the content process + // crashes. Right now we leak its top window IDs. + this.topWindowIds.add(data.windowId); + break; + + case "Extension:RemoveTopWindowID": + this.topWindowIds.delete(data.windowId); + break; + } + }, +}; +Frames.init(); + +var APIs = { + apis: new Map(), + + register(namespace, schema, script) { + if (this.apis.has(namespace)) { + throw new Error(`API namespace already exists: ${namespace}`); + } + + this.apis.set(namespace, {schema, script}); + }, + + unregister(namespace) { + if (!this.apis.has(namespace)) { + throw new Error(`API namespace does not exist: ${namespace}`); + } + + this.apis.delete(namespace); + }, +}; + +function getURLForExtension(id, path = "") { + let uuid = UUIDMap.get(id, false); + if (!uuid) { + Cu.reportError(`Called getURLForExtension on unmapped extension ${id}`); + return null; + } + return `moz-extension://${uuid}/${path}`; +} + +// This object manages various platform-level issues related to +// moz-extension:// URIs. It lives here so that it can be used in both +// the parent and child processes. +// +// moz-extension URIs have the form moz-extension://uuid/path. Each +// extension has its own UUID, unique to the machine it's installed +// on. This is easier and more secure than using the extension ID, +// since it makes it slightly harder to fingerprint for extensions if +// each user uses different URIs for the extension. +var Service = { + initialized: false, + + // Map[uuid -> extension]. + // extension can be an Extension (parent process) or BrowserExtensionContent (child process). + uuidMap: new Map(), + + init() { + let aps = Cc["@mozilla.org/addons/policy-service;1"].getService(Ci.nsIAddonPolicyService); + aps = aps.wrappedJSObject; + this.aps = aps; + aps.setExtensionURILoadCallback(this.extensionURILoadableByAnyone.bind(this)); + aps.setExtensionURIToAddonIdCallback(this.extensionURIToAddonID.bind(this)); + }, + + // Called when a new extension is loaded. + startupExtension(uuid, uri, extension) { + if (!this.initialized) { + this.initialized = true; + this.init(); + } + + // Create the moz-extension://uuid mapping. + let handler = Services.io.getProtocolHandler("moz-extension"); + handler.QueryInterface(Ci.nsISubstitutingProtocolHandler); + handler.setSubstitution(uuid, uri); + + this.uuidMap.set(uuid, extension); + this.aps.setAddonHasPermissionCallback(extension.id, extension.hasPermission.bind(extension)); + this.aps.setAddonLoadURICallback(extension.id, this.checkAddonMayLoad.bind(this, extension)); + this.aps.setAddonLocalizeCallback(extension.id, extension.localize.bind(extension)); + this.aps.setAddonCSP(extension.id, extension.manifest.content_security_policy); + this.aps.setBackgroundPageUrlCallback(uuid, this.generateBackgroundPageUrl.bind(this, extension)); + }, + + // Called when an extension is unloaded. + shutdownExtension(uuid) { + let extension = this.uuidMap.get(uuid); + this.uuidMap.delete(uuid); + this.aps.setAddonHasPermissionCallback(extension.id, null); + this.aps.setAddonLoadURICallback(extension.id, null); + this.aps.setAddonLocalizeCallback(extension.id, null); + this.aps.setAddonCSP(extension.id, null); + this.aps.setBackgroundPageUrlCallback(uuid, null); + + let handler = Services.io.getProtocolHandler("moz-extension"); + handler.QueryInterface(Ci.nsISubstitutingProtocolHandler); + handler.setSubstitution(uuid, null); + }, + + // Return true if the given URI can be loaded from arbitrary web + // content. The manifest.json |web_accessible_resources| directive + // determines this. + extensionURILoadableByAnyone(uri) { + let uuid = uri.host; + let extension = this.uuidMap.get(uuid); + if (!extension || !extension.webAccessibleResources) { + return false; + } + + let path = uri.QueryInterface(Ci.nsIURL).filePath; + if (path.length > 0 && path[0] == "/") { + path = path.substr(1); + } + return extension.webAccessibleResources.matches(path); + }, + + // Checks whether a given extension can load this URI (typically via + // an XML HTTP request). The manifest.json |permissions| directive + // determines this. + checkAddonMayLoad(extension, uri) { + return extension.whiteListedHosts.matchesIgnoringPath(uri); + }, + + generateBackgroundPageUrl(extension) { + let background_scripts = extension.manifest.background && + extension.manifest.background.scripts; + if (!background_scripts) { + return; + } + let html = "\n\n"; + for (let script of background_scripts) { + script = script.replace(/"/g, """); + html += `\n`; + } + html += "\n\n"; + return "data:text/html;charset=utf-8," + encodeURIComponent(html); + }, + + // Finds the add-on ID associated with a given moz-extension:// URI. + // This is used to set the addonId on the originAttributes for the + // nsIPrincipal attached to the URI. + extensionURIToAddonID(uri) { + let uuid = uri.host; + let extension = this.uuidMap.get(uuid); + return extension ? extension.id : undefined; + }, +}; + +// API Levels Helpers + +// Find the add-on associated with this document via the +// principal's originAttributes. This value is computed by +// extensionURIToAddonID, which ensures that we don't inject our +// API into webAccessibleResources or remote web pages. +function getAddonIdForWindow(window) { + return Cu.getObjectPrincipal(window).originAttributes.addonId; +} + +const API_LEVELS = Object.freeze({ + NO_PRIVILEGES: 0, + CONTENTSCRIPT_PRIVILEGES: 1, + FULL_PRIVILEGES: 2, +}); + +// Finds the API Level ("FULL_PRIVILEGES", "CONTENTSCRIPT_PRIVILEGES", "NO_PRIVILEGES") +// with a given a window object. +function getAPILevelForWindow(window, addonId) { + const {NO_PRIVILEGES, CONTENTSCRIPT_PRIVILEGES, FULL_PRIVILEGES} = API_LEVELS; + + // Non WebExtension URLs and WebExtension URLs from a different extension + // has no access to APIs. + if (!addonId || getAddonIdForWindow(window) != addonId) { + return NO_PRIVILEGES; + } + + // Extension pages running in the content process always defaults to + // "content script API level privileges". + if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { + return CONTENTSCRIPT_PRIVILEGES; + } + + let docShell = window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell); + + // Handling of ExtensionPages running inside sub-frames. + if (docShell.sameTypeParent) { + let parentWindow = docShell.sameTypeParent.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindow); + + // The option page iframe embedded in the about:addons tab should have + // full API level privileges. (see Bug 1256282 for rationale) + let parentDocument = parentWindow.document; + let parentIsSystemPrincipal = Services.scriptSecurityManager + .isSystemPrincipal(parentDocument.nodePrincipal); + if (parentDocument.location.href == "about:addons" && parentIsSystemPrincipal) { + return FULL_PRIVILEGES; + } + + // The addon iframes embedded in a addon page from with the same addonId + // should have the same privileges of the sameTypeParent. + // (see Bug 1258347 for rationale) + let parentSameAddonPrivileges = getAPILevelForWindow(parentWindow, addonId); + if (parentSameAddonPrivileges > NO_PRIVILEGES) { + return parentSameAddonPrivileges; + } + + // In all the other cases, WebExtension URLs loaded into sub-frame UI + // will have "content script API level privileges". + // (see Bug 1214658 for rationale) + return CONTENTSCRIPT_PRIVILEGES; + } + + // WebExtension URLs loaded into top frames UI could have full API level privileges. + return FULL_PRIVILEGES; +} + +this.ExtensionManagement = { + startupExtension: Service.startupExtension.bind(Service), + shutdownExtension: Service.shutdownExtension.bind(Service), + + registerAPI: APIs.register.bind(APIs), + unregisterAPI: APIs.unregister.bind(APIs), + + getFrameId: Frames.getId.bind(Frames), + getParentFrameId: Frames.getParentId.bind(Frames), + + getURLForExtension, + + // exported API Level Helpers + getAddonIdForWindow, + getAPILevelForWindow, + API_LEVELS, + + APIs, +}; diff --git a/toolkit/components/webextensions/ExtensionParent.jsm b/toolkit/components/webextensions/ExtensionParent.jsm new file mode 100644 index 000000000..b88500d1e --- /dev/null +++ b/toolkit/components/webextensions/ExtensionParent.jsm @@ -0,0 +1,551 @@ +/* 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"; + +/** + * This module contains code for managing APIs that need to run in the + * parent process, and handles the parent side of operations that need + * to be proxied from ExtensionChild.jsm. + */ + +const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; + +/* exported ExtensionParent */ + +this.EXPORTED_SYMBOLS = ["ExtensionParent"]; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "AddonManager", + "resource://gre/modules/AddonManager.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "AppConstants", + "resource://gre/modules/AppConstants.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel", + "resource://gre/modules/MessageChannel.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "NativeApp", + "resource://gre/modules/NativeMessaging.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", + "resource://gre/modules/NetUtil.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Schemas", + "resource://gre/modules/Schemas.jsm"); + +Cu.import("resource://gre/modules/ExtensionCommon.jsm"); +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +var { + BaseContext, + SchemaAPIManager, +} = ExtensionCommon; + +var { + MessageManagerProxy, + SpreadArgs, + defineLazyGetter, + findPathInObject, +} = ExtensionUtils; + +const BASE_SCHEMA = "chrome://extensions/content/schemas/manifest.json"; +const CATEGORY_EXTENSION_SCHEMAS = "webextension-schemas"; +const CATEGORY_EXTENSION_SCRIPTS = "webextension-scripts"; + +let schemaURLs = new Set(); + +if (!AppConstants.RELEASE_OR_BETA) { + schemaURLs.add("chrome://extensions/content/schemas/experiments.json"); +} + +let GlobalManager; +let ParentAPIManager; +let ProxyMessenger; + +// This object loads the ext-*.js scripts that define the extension API. +let apiManager = new class extends SchemaAPIManager { + constructor() { + super("main"); + this.initialized = null; + } + + // Loads all the ext-*.js scripts currently registered. + lazyInit() { + if (this.initialized) { + return this.initialized; + } + + // Load order matters here. The base manifest defines types which are + // extended by other schemas, so needs to be loaded first. + let promise = Schemas.load(BASE_SCHEMA).then(() => { + let promises = []; + for (let [/* name */, url] of XPCOMUtils.enumerateCategoryEntries(CATEGORY_EXTENSION_SCHEMAS)) { + promises.push(Schemas.load(url)); + } + for (let url of schemaURLs) { + promises.push(Schemas.load(url)); + } + return Promise.all(promises); + }); + + for (let [/* name */, value] of XPCOMUtils.enumerateCategoryEntries(CATEGORY_EXTENSION_SCRIPTS)) { + this.loadScript(value); + } + + this.initialized = promise; + return this.initialized; + } + + registerSchemaAPI(namespace, envType, getAPI) { + if (envType == "addon_parent" || envType == "content_parent") { + super.registerSchemaAPI(namespace, envType, getAPI); + } + } +}(); + +// Subscribes to messages related to the extension messaging API and forwards it +// to the relevant message manager. The "sender" field for the `onMessage` and +// `onConnect` events are updated if needed. +ProxyMessenger = { + _initialized: false, + init() { + if (this._initialized) { + return; + } + this._initialized = true; + + // TODO(robwu): When addons move to a separate process, we should use the + // parent process manager(s) of the addon process(es) instead of the + // in-process one. + let pipmm = Services.ppmm.getChildAt(0); + // Listen on the global frame message manager because content scripts send + // and receive extension messages via their frame. + // Listen on the parent process message manager because `runtime.connect` + // and `runtime.sendMessage` requests must be delivered to all frames in an + // addon process (by the API contract). + // And legacy addons are not associated with a frame, so that is another + // reason for having a parent process manager here. + let messageManagers = [Services.mm, pipmm]; + + MessageChannel.addListener(messageManagers, "Extension:Connect", this); + MessageChannel.addListener(messageManagers, "Extension:Message", this); + MessageChannel.addListener(messageManagers, "Extension:Port:Disconnect", this); + MessageChannel.addListener(messageManagers, "Extension:Port:PostMessage", this); + }, + + receiveMessage({target, messageName, channelId, sender, recipient, data, responseType}) { + if (recipient.toNativeApp) { + let {childId, toNativeApp} = recipient; + if (messageName == "Extension:Message") { + let context = ParentAPIManager.getContextById(childId); + return new NativeApp(context, toNativeApp).sendMessage(data); + } + if (messageName == "Extension:Connect") { + let context = ParentAPIManager.getContextById(childId); + NativeApp.onConnectNative(context, target.messageManager, data.portId, sender, toNativeApp); + return true; + } + // "Extension:Port:Disconnect" and "Extension:Port:PostMessage" for + // native messages are handled by NativeApp. + return; + } + let extension = GlobalManager.extensionMap.get(sender.extensionId); + let receiverMM = this._getMessageManagerForRecipient(recipient); + if (!extension || !receiverMM) { + return Promise.reject({ + result: MessageChannel.RESULT_NO_HANDLER, + message: "No matching message handler for the given recipient.", + }); + } + + if ((messageName == "Extension:Message" || + messageName == "Extension:Connect") && + apiManager.global.tabGetSender) { + // From ext-tabs.js, undefined on Android. + apiManager.global.tabGetSender(extension, target, sender); + } + return MessageChannel.sendMessage(receiverMM, messageName, data, { + sender, + recipient, + responseType, + }); + }, + + /** + * @param {object} recipient An object that was passed to + * `MessageChannel.sendMessage`. + * @returns {object|null} The message manager matching the recipient if found. + */ + _getMessageManagerForRecipient(recipient) { + let {extensionId, tabId} = recipient; + // tabs.sendMessage / tabs.connect + if (tabId) { + // `tabId` being set implies that the tabs API is supported, so we don't + // need to check whether `TabManager` exists. + let tab = apiManager.global.TabManager.getTab(tabId, null, null); + return tab && tab.linkedBrowser.messageManager; + } + + // runtime.sendMessage / runtime.connect + if (extensionId) { + // TODO(robwu): map the extensionId to the addon parent process's message + // manager when they run in a separate process. + return Services.ppmm.getChildAt(0); + } + + return null; + }, +}; + +// Responsible for loading extension APIs into the right globals. +GlobalManager = { + // Map[extension ID -> Extension]. Determines which extension is + // responsible for content under a particular extension ID. + extensionMap: new Map(), + initialized: false, + + init(extension) { + if (this.extensionMap.size == 0) { + ProxyMessenger.init(); + apiManager.on("extension-browser-inserted", this._onExtensionBrowser); + this.initialized = true; + } + + this.extensionMap.set(extension.id, extension); + }, + + uninit(extension) { + this.extensionMap.delete(extension.id); + + if (this.extensionMap.size == 0 && this.initialized) { + apiManager.off("extension-browser-inserted", this._onExtensionBrowser); + this.initialized = false; + } + }, + + _onExtensionBrowser(type, browser) { + browser.messageManager.loadFrameScript(`data:, + Components.utils.import("resource://gre/modules/ExtensionContent.jsm"); + ExtensionContent.init(this); + addEventListener("unload", function() { + ExtensionContent.uninit(this); + }); + `, false); + }, + + getExtension(extensionId) { + return this.extensionMap.get(extensionId); + }, + + injectInObject(context, isChromeCompat, dest) { + apiManager.generateAPIs(context, dest); + SchemaAPIManager.generateAPIs(context, context.extension.apis, dest); + }, +}; + +/** + * The proxied parent side of a context in ExtensionChild.jsm, for the + * parent side of a proxied API. + */ +class ProxyContextParent extends BaseContext { + constructor(envType, extension, params, xulBrowser, principal) { + super(envType, extension); + + this.uri = NetUtil.newURI(params.url); + + this.incognito = params.incognito; + + // This message manager is used by ParentAPIManager to send messages and to + // close the ProxyContext if the underlying message manager closes. This + // message manager object may change when `xulBrowser` swaps docshells, e.g. + // when a tab is moved to a different window. + this.messageManagerProxy = new MessageManagerProxy(xulBrowser); + + Object.defineProperty(this, "principal", { + value: principal, enumerable: true, configurable: true, + }); + + this.listenerProxies = new Map(); + + apiManager.emit("proxy-context-load", this); + } + + get cloneScope() { + return this.sandbox; + } + + get xulBrowser() { + return this.messageManagerProxy.eventTarget; + } + + get parentMessageManager() { + return this.messageManagerProxy.messageManager; + } + + shutdown() { + this.unload(); + } + + unload() { + if (this.unloaded) { + return; + } + this.messageManagerProxy.dispose(); + super.unload(); + apiManager.emit("proxy-context-unload", this); + } +} + +defineLazyGetter(ProxyContextParent.prototype, "apiObj", function() { + let obj = {}; + GlobalManager.injectInObject(this, false, obj); + return obj; +}); + +defineLazyGetter(ProxyContextParent.prototype, "sandbox", function() { + return Cu.Sandbox(this.principal); +}); + +/** + * The parent side of proxied API context for extension content script + * running in ExtensionContent.jsm. + */ +class ContentScriptContextParent extends ProxyContextParent { +} + +/** + * The parent side of proxied API context for extension page, such as a + * background script, a tab page, or a popup, running in + * ExtensionChild.jsm. + */ +class ExtensionPageContextParent extends ProxyContextParent { + constructor(envType, extension, params, xulBrowser) { + super(envType, extension, params, xulBrowser, extension.principal); + + this.viewType = params.viewType; + } + + // The window that contains this context. This may change due to moving tabs. + get xulWindow() { + return this.xulBrowser.ownerGlobal; + } + + get windowId() { + if (!apiManager.global.WindowManager || this.viewType == "background") { + return; + } + // viewType popup or tab: + return apiManager.global.WindowManager.getId(this.xulWindow); + } + + get tabId() { + if (!apiManager.global.TabManager) { + return; // Not yet supported on Android. + } + let {gBrowser} = this.xulBrowser.ownerGlobal; + let tab = gBrowser && gBrowser.getTabForBrowser(this.xulBrowser); + return tab && apiManager.global.TabManager.getId(tab); + } + + onBrowserChange(browser) { + super.onBrowserChange(browser); + this.xulBrowser = browser; + } + + shutdown() { + apiManager.emit("page-shutdown", this); + super.shutdown(); + } +} + +ParentAPIManager = { + proxyContexts: new Map(), + + init() { + Services.obs.addObserver(this, "message-manager-close", false); + + Services.mm.addMessageListener("API:CreateProxyContext", this); + Services.mm.addMessageListener("API:CloseProxyContext", this, true); + Services.mm.addMessageListener("API:Call", this); + Services.mm.addMessageListener("API:AddListener", this); + Services.mm.addMessageListener("API:RemoveListener", this); + }, + + observe(subject, topic, data) { + if (topic === "message-manager-close") { + let mm = subject; + for (let [childId, context] of this.proxyContexts) { + if (context.parentMessageManager === mm) { + this.closeProxyContext(childId); + } + } + } + }, + + shutdownExtension(extensionId) { + for (let [childId, context] of this.proxyContexts) { + if (context.extension.id == extensionId) { + context.shutdown(); + this.proxyContexts.delete(childId); + } + } + }, + + receiveMessage({name, data, target}) { + switch (name) { + case "API:CreateProxyContext": + this.createProxyContext(data, target); + break; + + case "API:CloseProxyContext": + this.closeProxyContext(data.childId); + break; + + case "API:Call": + this.call(data, target); + break; + + case "API:AddListener": + this.addListener(data, target); + break; + + case "API:RemoveListener": + this.removeListener(data); + break; + } + }, + + createProxyContext(data, target) { + let {envType, extensionId, childId, principal} = data; + if (this.proxyContexts.has(childId)) { + throw new Error("A WebExtension context with the given ID already exists!"); + } + + let extension = GlobalManager.getExtension(extensionId); + if (!extension) { + throw new Error(`No WebExtension found with ID ${extensionId}`); + } + + let context; + if (envType == "addon_parent") { + // Privileged addon contexts can only be loaded in documents whose main + // frame is also the same addon. + if (principal.URI.prePath !== extension.baseURI.prePath || + !target.contentPrincipal.subsumes(principal)) { + throw new Error(`Refused to create privileged WebExtension context for ${principal.URI.spec}`); + } + context = new ExtensionPageContextParent(envType, extension, data, target); + } else if (envType == "content_parent") { + context = new ContentScriptContextParent(envType, extension, data, target, principal); + } else { + throw new Error(`Invalid WebExtension context envType: ${envType}`); + } + this.proxyContexts.set(childId, context); + }, + + closeProxyContext(childId) { + let context = this.proxyContexts.get(childId); + if (context) { + context.unload(); + this.proxyContexts.delete(childId); + } + }, + + call(data, target) { + let context = this.getContextById(data.childId); + if (context.parentMessageManager !== target.messageManager) { + throw new Error("Got message on unexpected message manager"); + } + + let reply = result => { + if (!context.parentMessageManager) { + Cu.reportError("Cannot send function call result: other side closed connection"); + return; + } + + context.parentMessageManager.sendAsyncMessage( + "API:CallResult", + Object.assign({ + childId: data.childId, + callId: data.callId, + }, result)); + }; + + try { + let args = Cu.cloneInto(data.args, context.sandbox); + let result = findPathInObject(context.apiObj, data.path)(...args); + + if (data.callId) { + result = result || Promise.resolve(); + + result.then(result => { + result = result instanceof SpreadArgs ? [...result] : [result]; + + reply({result}); + }, error => { + error = context.normalizeError(error); + reply({error: {message: error.message}}); + }); + } + } catch (e) { + if (data.callId) { + let error = context.normalizeError(e); + reply({error: {message: error.message}}); + } else { + Cu.reportError(e); + } + } + }, + + addListener(data, target) { + let context = this.getContextById(data.childId); + if (context.parentMessageManager !== target.messageManager) { + throw new Error("Got message on unexpected message manager"); + } + + let {childId} = data; + + function listener(...listenerArgs) { + return context.sendMessage( + context.parentMessageManager, + "API:RunListener", + { + childId, + listenerId: data.listenerId, + path: data.path, + args: listenerArgs, + }, + { + recipient: {childId}, + }); + } + + context.listenerProxies.set(data.listenerId, listener); + + let args = Cu.cloneInto(data.args, context.sandbox); + findPathInObject(context.apiObj, data.path).addListener(listener, ...args); + }, + + removeListener(data) { + let context = this.getContextById(data.childId); + let listener = context.listenerProxies.get(data.listenerId); + findPathInObject(context.apiObj, data.path).removeListener(listener); + }, + + getContextById(childId) { + let context = this.proxyContexts.get(childId); + if (!context) { + let error = new Error("WebExtension context not found!"); + Cu.reportError(error); + throw error; + } + return context; + }, +}; + +ParentAPIManager.init(); + + +const ExtensionParent = { + GlobalManager, + ParentAPIManager, + apiManager, +}; diff --git a/toolkit/components/webextensions/ExtensionStorage.jsm b/toolkit/components/webextensions/ExtensionStorage.jsm new file mode 100644 index 000000000..0b0ffb000 --- /dev/null +++ b/toolkit/components/webextensions/ExtensionStorage.jsm @@ -0,0 +1,241 @@ +/* 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"; + +this.EXPORTED_SYMBOLS = ["ExtensionStorage"]; + +const Ci = Components.interfaces; +const Cc = Components.classes; +const Cu = Components.utils; +const Cr = Components.results; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "OS", + "resource://gre/modules/osfile.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown", + "resource://gre/modules/AsyncShutdown.jsm"); + +function jsonReplacer(key, value) { + switch (typeof(value)) { + // Serialize primitive types as-is. + case "string": + case "number": + case "boolean": + return value; + + case "object": + if (value === null) { + return value; + } + + switch (Cu.getClassName(value, true)) { + // Serialize arrays and ordinary objects as-is. + case "Array": + case "Object": + return value; + + // Serialize Date objects and regular expressions as their + // string representations. + case "Date": + case "RegExp": + return String(value); + } + break; + } + + if (!key) { + // If this is the root object, and we can't serialize it, serialize + // the value to an empty object. + return {}; + } + + // Everything else, omit entirely. + return undefined; +} + +this.ExtensionStorage = { + cache: new Map(), + listeners: new Map(), + + /** + * Sanitizes the given value, and returns a JSON-compatible + * representation of it, based on the privileges of the given global. + * + * @param {value} value + * The value to sanitize. + * @param {Context} context + * The extension context in which to sanitize the value + * @returns {value} + * The sanitized value. + */ + sanitize(value, context) { + let json = context.jsonStringify(value, jsonReplacer); + return JSON.parse(json); + }, + + getExtensionDir(extensionId) { + return OS.Path.join(this.extensionDir, extensionId); + }, + + getStorageFile(extensionId) { + return OS.Path.join(this.extensionDir, extensionId, "storage.js"); + }, + + read(extensionId) { + if (this.cache.has(extensionId)) { + return this.cache.get(extensionId); + } + + let path = this.getStorageFile(extensionId); + let decoder = new TextDecoder(); + let promise = OS.File.read(path); + promise = promise.then(array => { + return JSON.parse(decoder.decode(array)); + }).catch((error) => { + if (!error.becauseNoSuchFile) { + Cu.reportError("Unable to parse JSON data for extension storage."); + } + return {}; + }); + this.cache.set(extensionId, promise); + return promise; + }, + + write(extensionId) { + let promise = this.read(extensionId).then(extData => { + let encoder = new TextEncoder(); + let array = encoder.encode(JSON.stringify(extData)); + let path = this.getStorageFile(extensionId); + OS.File.makeDir(this.getExtensionDir(extensionId), { + ignoreExisting: true, + from: OS.Constants.Path.profileDir, + }); + let promise = OS.File.writeAtomic(path, array); + return promise; + }).catch(() => { + // Make sure this promise is never rejected. + Cu.reportError("Unable to write JSON data for extension storage."); + }); + + AsyncShutdown.profileBeforeChange.addBlocker( + "ExtensionStorage: Finish writing extension data", + promise); + + return promise.then(() => { + AsyncShutdown.profileBeforeChange.removeBlocker(promise); + }); + }, + + set(extensionId, items, context) { + return this.read(extensionId).then(extData => { + let changes = {}; + for (let prop in items) { + let item = this.sanitize(items[prop], context); + changes[prop] = {oldValue: extData[prop], newValue: item}; + extData[prop] = item; + } + + this.notifyListeners(extensionId, changes); + + return this.write(extensionId); + }); + }, + + remove(extensionId, items) { + return this.read(extensionId).then(extData => { + let changes = {}; + for (let prop of [].concat(items)) { + changes[prop] = {oldValue: extData[prop]}; + delete extData[prop]; + } + + this.notifyListeners(extensionId, changes); + + return this.write(extensionId); + }); + }, + + clear(extensionId) { + return this.read(extensionId).then(extData => { + let changes = {}; + for (let prop of Object.keys(extData)) { + changes[prop] = {oldValue: extData[prop]}; + delete extData[prop]; + } + + this.notifyListeners(extensionId, changes); + + return this.write(extensionId); + }); + }, + + get(extensionId, keys) { + return this.read(extensionId).then(extData => { + let result = {}; + if (keys === null) { + Object.assign(result, extData); + } else if (typeof(keys) == "object" && !Array.isArray(keys)) { + for (let prop in keys) { + if (prop in extData) { + result[prop] = extData[prop]; + } else { + result[prop] = keys[prop]; + } + } + } else { + for (let prop of [].concat(keys)) { + if (prop in extData) { + result[prop] = extData[prop]; + } + } + } + + return result; + }); + }, + + addOnChangedListener(extensionId, listener) { + let listeners = this.listeners.get(extensionId) || new Set(); + listeners.add(listener); + this.listeners.set(extensionId, listeners); + }, + + removeOnChangedListener(extensionId, listener) { + let listeners = this.listeners.get(extensionId); + listeners.delete(listener); + }, + + notifyListeners(extensionId, changes) { + let listeners = this.listeners.get(extensionId); + if (listeners) { + for (let listener of listeners) { + listener(changes); + } + } + }, + + init() { + if (Services.appinfo.processType != Services.appinfo.PROCESS_TYPE_DEFAULT) { + return; + } + Services.obs.addObserver(this, "extension-invalidate-storage-cache", false); + Services.obs.addObserver(this, "xpcom-shutdown", false); + }, + + observe(subject, topic, data) { + if (topic == "xpcom-shutdown") { + Services.obs.removeObserver(this, "extension-invalidate-storage-cache"); + Services.obs.removeObserver(this, "xpcom-shutdown"); + } else if (topic == "extension-invalidate-storage-cache") { + this.cache.clear(); + } + }, +}; + +XPCOMUtils.defineLazyGetter(ExtensionStorage, "extensionDir", + () => OS.Path.join(OS.Constants.Path.profileDir, "browser-extension-data")); + +ExtensionStorage.init(); diff --git a/toolkit/components/webextensions/ExtensionTestCommon.jsm b/toolkit/components/webextensions/ExtensionTestCommon.jsm new file mode 100644 index 000000000..02453ddfd --- /dev/null +++ b/toolkit/components/webextensions/ExtensionTestCommon.jsm @@ -0,0 +1,343 @@ +/* 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"; + +/** + * This module contains extension testing helper logic which is common + * between all test suites. + */ + +/* exported ExtensionTestCommon, MockExtension */ + +this.EXPORTED_SYMBOLS = ["ExtensionTestCommon", "MockExtension"]; + +const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; + +Cu.importGlobalProperties(["TextEncoder"]); + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "AddonManager", + "resource://gre/modules/AddonManager.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "AppConstants", + "resource://gre/modules/AppConstants.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Extension", + "resource://gre/modules/Extension.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionParent", + "resource://gre/modules/ExtensionParent.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "FileUtils", + "resource://gre/modules/FileUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "OS", + "resource://gre/modules/osfile.jsm"); + +XPCOMUtils.defineLazyGetter(this, "apiManager", + () => ExtensionParent.apiManager); + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +XPCOMUtils.defineLazyServiceGetter(this, "uuidGen", + "@mozilla.org/uuid-generator;1", + "nsIUUIDGenerator"); + +const { + flushJarCache, + instanceOf, +} = ExtensionUtils; + +XPCOMUtils.defineLazyGetter(this, "console", ExtensionUtils.getConsole); + + +/** + * A skeleton Extension-like object, used for testing, which installs an + * add-on via the add-on manager when startup() is called, and + * uninstalles it on shutdown(). + * + * @param {string} id + * @param {nsIFile} file + * @param {nsIURI} rootURI + * @param {string} installType + */ +class MockExtension { + constructor(file, rootURI, installType) { + this.id = null; + this.file = file; + this.rootURI = rootURI; + this.installType = installType; + this.addon = null; + + let promiseEvent = eventName => new Promise(resolve => { + let onstartup = (msg, extension) => { + if (this.addon && extension.id == this.addon.id) { + apiManager.off(eventName, onstartup); + + this.id = extension.id; + this._extension = extension; + resolve(extension); + } + }; + apiManager.on(eventName, onstartup); + }); + + this._extension = null; + this._extensionPromise = promiseEvent("startup"); + this._readyPromise = promiseEvent("ready"); + } + + testMessage(...args) { + return this._extension.testMessage(...args); + } + + on(...args) { + this._extensionPromise.then(extension => { + extension.on(...args); + }); + } + + off(...args) { + this._extensionPromise.then(extension => { + extension.off(...args); + }); + } + + startup() { + if (this.installType == "temporary") { + return AddonManager.installTemporaryAddon(this.file).then(addon => { + this.addon = addon; + return this._readyPromise; + }); + } else if (this.installType == "permanent") { + return new Promise((resolve, reject) => { + AddonManager.getInstallForFile(this.file, install => { + let listener = { + onInstallFailed: reject, + onInstallEnded: (install, newAddon) => { + this.addon = newAddon; + resolve(this._readyPromise); + }, + }; + + install.addListener(listener); + install.install(); + }); + }); + } + throw new Error("installType must be one of: temporary, permanent"); + } + + shutdown() { + this.addon.uninstall(); + return this.cleanupGeneratedFile(); + } + + cleanupGeneratedFile() { + flushJarCache(this.file); + return OS.File.remove(this.file.path); + } +} + +class ExtensionTestCommon { + /** + * This code is designed to make it easy to test a WebExtension + * without creating a bunch of files. Everything is contained in a + * single JSON blob. + * + * Properties: + * "background": "" + * A script to be loaded as the background script. + * The "background" section of the "manifest" property is overwritten + * if this is provided. + * "manifest": {...} + * Contents of manifest.json + * "files": {"filename1": "contents1", ...} + * Data to be included as files. Can be referenced from the manifest. + * If a manifest file is provided here, it takes precedence over + * a generated one. Always use "/" as a directory separator. + * Directories should appear here only implicitly (as a prefix + * to file names) + * + * To make things easier, the value of "background" and "files"[] can + * be a function, which is converted to source that is run. + * + * The generated extension is stored in the system temporary directory, + * and an nsIFile object pointing to it is returned. + * + * @param {object} data + * @returns {nsIFile} + */ + static generateXPI(data) { + let manifest = data.manifest; + if (!manifest) { + manifest = {}; + } + + let files = data.files; + if (!files) { + files = {}; + } + + function provide(obj, keys, value, override = false) { + if (keys.length == 1) { + if (!(keys[0] in obj) || override) { + obj[keys[0]] = value; + } + } else { + if (!(keys[0] in obj)) { + obj[keys[0]] = {}; + } + provide(obj[keys[0]], keys.slice(1), value, override); + } + } + + provide(manifest, ["name"], "Generated extension"); + provide(manifest, ["manifest_version"], 2); + provide(manifest, ["version"], "1.0"); + + if (data.background) { + let bgScript = uuidGen.generateUUID().number + ".js"; + + provide(manifest, ["background", "scripts"], [bgScript], true); + files[bgScript] = data.background; + } + + provide(files, ["manifest.json"], manifest); + + if (data.embedded) { + // Package this as a webextension embedded inside a legacy + // extension. + + let xpiFiles = { + "install.rdf": ` + + + + + + + + + + `, + + "bootstrap.js": ` + function install() {} + function uninstall() {} + function shutdown() {} + + function startup(data) { + data.webExtension.startup(); + } + `, + }; + + for (let [path, data] of Object.entries(files)) { + xpiFiles[`webextension/${path}`] = data; + } + + files = xpiFiles; + } + + return this.generateZipFile(files); + } + + static generateZipFile(files, baseName = "generated-extension.xpi") { + let ZipWriter = Components.Constructor("@mozilla.org/zipwriter;1", "nsIZipWriter"); + let zipW = new ZipWriter(); + + let file = FileUtils.getFile("TmpD", [baseName]); + file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE); + + const MODE_WRONLY = 0x02; + const MODE_TRUNCATE = 0x20; + zipW.open(file, MODE_WRONLY | MODE_TRUNCATE); + + // Needs to be in microseconds for some reason. + let time = Date.now() * 1000; + + function generateFile(filename) { + let components = filename.split("/"); + let path = ""; + for (let component of components.slice(0, -1)) { + path += component + "/"; + if (!zipW.hasEntry(path)) { + zipW.addEntryDirectory(path, time, false); + } + } + } + + for (let filename in files) { + let script = files[filename]; + if (typeof(script) == "function") { + script = "(" + script.toString() + ")()"; + } else if (instanceOf(script, "Object") || instanceOf(script, "Array")) { + script = JSON.stringify(script); + } + + if (!instanceOf(script, "ArrayBuffer")) { + script = new TextEncoder("utf-8").encode(script).buffer; + } + + let stream = Cc["@mozilla.org/io/arraybuffer-input-stream;1"].createInstance(Ci.nsIArrayBufferInputStream); + stream.setData(script, 0, script.byteLength); + + generateFile(filename); + zipW.addEntryStream(filename, time, 0, stream, false); + } + + zipW.close(); + + return file; + } + + /** + * Generates a new extension using |Extension.generateXPI|, and initializes a + * new |Extension| instance which will execute it. + * + * @param {object} data + * @returns {Extension} + */ + static generate(data) { + let file = this.generateXPI(data); + + flushJarCache(file); + Services.ppmm.broadcastAsyncMessage("Extension:FlushJarCache", {path: file.path}); + + let fileURI = Services.io.newFileURI(file); + let jarURI = Services.io.newURI("jar:" + fileURI.spec + "!/", null, null); + + // This may be "temporary" or "permanent". + if (data.useAddonManager) { + return new MockExtension(file, jarURI, data.useAddonManager); + } + + let id; + if (data.manifest) { + if (data.manifest.applications && data.manifest.applications.gecko) { + id = data.manifest.applications.gecko.id; + } else if (data.manifest.browser_specific_settings && data.manifest.browser_specific_settings.gecko) { + id = data.manifest.browser_specific_settings.gecko.id; + } + } + if (!id) { + id = uuidGen.generateUUID().number; + } + + return new Extension({ + id, + resourceURI: jarURI, + cleanupFile: file, + }); + } +} diff --git a/toolkit/components/webextensions/ExtensionUtils.jsm b/toolkit/components/webextensions/ExtensionUtils.jsm new file mode 100644 index 000000000..04e767cb5 --- /dev/null +++ b/toolkit/components/webextensions/ExtensionUtils.jsm @@ -0,0 +1,1216 @@ +/* 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"; + +this.EXPORTED_SYMBOLS = ["ExtensionUtils"]; + +const Ci = Components.interfaces; +const Cc = Components.classes; +const Cu = Components.utils; +const Cr = Components.results; + +const INTEGER = /^[1-9]\d*$/; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "AddonManager", + "resource://gre/modules/AddonManager.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "AppConstants", + "resource://gre/modules/AppConstants.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ConsoleAPI", + "resource://gre/modules/Console.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "LanguageDetector", + "resource:///modules/translation/LanguageDetector.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Locale", + "resource://gre/modules/Locale.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "MessageChannel", + "resource://gre/modules/MessageChannel.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", + "resource://gre/modules/NetUtil.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Preferences", + "resource://gre/modules/Preferences.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Schemas", + "resource://gre/modules/Schemas.jsm"); + +XPCOMUtils.defineLazyServiceGetter(this, "styleSheetService", + "@mozilla.org/content/style-sheet-service;1", + "nsIStyleSheetService"); + +function getConsole() { + return new ConsoleAPI({ + maxLogLevelPref: "extensions.webextensions.log.level", + prefix: "WebExtensions", + }); +} + +XPCOMUtils.defineLazyGetter(this, "console", getConsole); + +let nextId = 0; +const {uniqueProcessID} = Services.appinfo; + +function getUniqueId() { + return `${nextId++}-${uniqueProcessID}`; +} + +/** + * An Error subclass for which complete error messages are always passed + * to extensions, rather than being interpreted as an unknown error. + */ +class ExtensionError extends Error {} + +function filterStack(error) { + return String(error.stack).replace(/(^.*(Task\.jsm|Promise-backend\.js).*\n)+/gm, "\n"); +} + +// Run a function and report exceptions. +function runSafeSyncWithoutClone(f, ...args) { + try { + return f(...args); + } catch (e) { + dump(`Extension error: ${e} ${e.fileName} ${e.lineNumber}\n[[Exception stack\n${filterStack(e)}Current stack\n${filterStack(Error())}]]\n`); + Cu.reportError(e); + } +} + +// Run a function and report exceptions. +function runSafeWithoutClone(f, ...args) { + if (typeof(f) != "function") { + dump(`Extension error: expected function\n${filterStack(Error())}`); + return; + } + + Promise.resolve().then(() => { + runSafeSyncWithoutClone(f, ...args); + }); +} + +// Run a function, cloning arguments into context.cloneScope, and +// report exceptions. |f| is expected to be in context.cloneScope. +function runSafeSync(context, f, ...args) { + if (context.unloaded) { + Cu.reportError("runSafeSync called after context unloaded"); + return; + } + + try { + args = Cu.cloneInto(args, context.cloneScope); + } catch (e) { + Cu.reportError(e); + dump(`runSafe failure: cloning into ${context.cloneScope}: ${e}\n\n${filterStack(Error())}`); + } + return runSafeSyncWithoutClone(f, ...args); +} + +// Run a function, cloning arguments into context.cloneScope, and +// report exceptions. |f| is expected to be in context.cloneScope. +function runSafe(context, f, ...args) { + try { + args = Cu.cloneInto(args, context.cloneScope); + } catch (e) { + Cu.reportError(e); + dump(`runSafe failure: cloning into ${context.cloneScope}: ${e}\n\n${filterStack(Error())}`); + } + if (context.unloaded) { + dump(`runSafe failure: context is already unloaded ${filterStack(new Error())}\n`); + return undefined; + } + return runSafeWithoutClone(f, ...args); +} + +function getInnerWindowID(window) { + return window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils) + .currentInnerWindowID; +} + +// Return true if the given value is an instance of the given +// native type. +function instanceOf(value, type) { + return {}.toString.call(value) == `[object ${type}]`; +} + +// Extend the object |obj| with the property descriptors of each object in +// |args|. +function extend(obj, ...args) { + for (let arg of args) { + let props = [...Object.getOwnPropertyNames(arg), + ...Object.getOwnPropertySymbols(arg)]; + for (let prop of props) { + let descriptor = Object.getOwnPropertyDescriptor(arg, prop); + Object.defineProperty(obj, prop, descriptor); + } + } + + return obj; +} + +/** + * Similar to a WeakMap, but creates a new key with the given + * constructor if one is not present. + */ +class DefaultWeakMap extends WeakMap { + constructor(defaultConstructor, init) { + super(init); + this.defaultConstructor = defaultConstructor; + } + + get(key) { + if (!this.has(key)) { + this.set(key, this.defaultConstructor(key)); + } + return super.get(key); + } +} + +class DefaultMap extends Map { + constructor(defaultConstructor, init) { + super(init); + this.defaultConstructor = defaultConstructor; + } + + get(key) { + if (!this.has(key)) { + this.set(key, this.defaultConstructor(key)); + } + return super.get(key); + } +} + +class SpreadArgs extends Array { + constructor(args) { + super(); + this.push(...args); + } +} + +// Manages icon details for toolbar buttons in the |pageAction| and +// |browserAction| APIs. +let IconDetails = { + // Normalizes the various acceptable input formats into an object + // with icon size as key and icon URL as value. + // + // If a context is specified (function is called from an extension): + // Throws an error if an invalid icon size was provided or the + // extension is not allowed to load the specified resources. + // + // If no context is specified, instead of throwing an error, this + // function simply logs a warning message. + normalize(details, extension, context = null) { + let result = {}; + + try { + if (details.imageData) { + let imageData = details.imageData; + + if (typeof imageData == "string") { + imageData = {"19": imageData}; + } + + for (let size of Object.keys(imageData)) { + if (!INTEGER.test(size)) { + throw new ExtensionError(`Invalid icon size ${size}, must be an integer`); + } + result[size] = imageData[size]; + } + } + + if (details.path) { + let path = details.path; + if (typeof path != "object") { + path = {"19": path}; + } + + let baseURI = context ? context.uri : extension.baseURI; + + for (let size of Object.keys(path)) { + if (!INTEGER.test(size)) { + throw new ExtensionError(`Invalid icon size ${size}, must be an integer`); + } + + let url = baseURI.resolve(path[size]); + + // The Chrome documentation specifies these parameters as + // relative paths. We currently accept absolute URLs as well, + // which means we need to check that the extension is allowed + // to load them. This will throw an error if it's not allowed. + try { + Services.scriptSecurityManager.checkLoadURIStrWithPrincipal( + extension.principal, url, + Services.scriptSecurityManager.DISALLOW_SCRIPT); + } catch (e) { + throw new ExtensionError(`Illegal URL ${url}`); + } + + result[size] = url; + } + } + } catch (e) { + // Function is called from extension code, delegate error. + if (context) { + throw e; + } + // If there's no context, it's because we're handling this + // as a manifest directive. Log a warning rather than + // raising an error. + extension.manifestError(`Invalid icon data: ${e}`); + } + + return result; + }, + + // Returns the appropriate icon URL for the given icons object and the + // screen resolution of the given window. + getPreferredIcon(icons, extension = null, size = 16) { + const DEFAULT = "chrome://browser/content/extension.svg"; + + let bestSize = null; + if (icons[size]) { + bestSize = size; + } else if (icons[2 * size]) { + bestSize = 2 * size; + } else { + let sizes = Object.keys(icons) + .map(key => parseInt(key, 10)) + .sort((a, b) => a - b); + + bestSize = sizes.find(candidate => candidate > size) || sizes.pop(); + } + + if (bestSize) { + return {size: bestSize, icon: icons[bestSize]}; + } + + return {size, icon: DEFAULT}; + }, + + convertImageURLToDataURL(imageURL, contentWindow, browserWindow, size = 18) { + return new Promise((resolve, reject) => { + let image = new contentWindow.Image(); + image.onload = function() { + let canvas = contentWindow.document.createElement("canvas"); + let ctx = canvas.getContext("2d"); + let dSize = size * browserWindow.devicePixelRatio; + + // Scales the image while maintaing width to height ratio. + // If the width and height differ, the image is centered using the + // smaller of the two dimensions. + let dWidth, dHeight, dx, dy; + if (this.width > this.height) { + dWidth = dSize; + dHeight = image.height * (dSize / image.width); + dx = 0; + dy = (dSize - dHeight) / 2; + } else { + dWidth = image.width * (dSize / image.height); + dHeight = dSize; + dx = (dSize - dWidth) / 2; + dy = 0; + } + + ctx.drawImage(this, 0, 0, this.width, this.height, dx, dy, dWidth, dHeight); + resolve(canvas.toDataURL("image/png")); + }; + image.onerror = reject; + image.src = imageURL; + }); + }, +}; + +const LISTENERS = Symbol("listeners"); + +class EventEmitter { + constructor() { + this[LISTENERS] = new Map(); + } + + /** + * Adds the given function as a listener for the given event. + * + * The listener function may optionally return a Promise which + * resolves when it has completed all operations which event + * dispatchers may need to block on. + * + * @param {string} event + * The name of the event to listen for. + * @param {function(string, ...any)} listener + * The listener to call when events are emitted. + */ + on(event, listener) { + if (!this[LISTENERS].has(event)) { + this[LISTENERS].set(event, new Set()); + } + + this[LISTENERS].get(event).add(listener); + } + + /** + * Removes the given function as a listener for the given event. + * + * @param {string} event + * The name of the event to stop listening for. + * @param {function(string, ...any)} listener + * The listener function to remove. + */ + off(event, listener) { + if (this[LISTENERS].has(event)) { + let set = this[LISTENERS].get(event); + + set.delete(listener); + if (!set.size) { + this[LISTENERS].delete(event); + } + } + } + + /** + * Triggers all listeners for the given event, and returns a promise + * which resolves when all listeners have been called, and any + * promises they have returned have likewise resolved. + * + * @param {string} event + * The name of the event to emit. + * @param {any} args + * Arbitrary arguments to pass to the listener functions, after + * the event name. + * @returns {Promise} + */ + emit(event, ...args) { + let listeners = this[LISTENERS].get(event) || new Set(); + + let promises = Array.from(listeners, listener => { + return runSafeSyncWithoutClone(listener, event, ...args); + }); + + return Promise.all(promises); + } +} + +function LocaleData(data) { + this.defaultLocale = data.defaultLocale; + this.selectedLocale = data.selectedLocale; + this.locales = data.locales || new Map(); + this.warnedMissingKeys = new Set(); + + // Map(locale-name -> Map(message-key -> localized-string)) + // + // Contains a key for each loaded locale, each of which is a + // Map of message keys to their localized strings. + this.messages = data.messages || new Map(); + + if (data.builtinMessages) { + this.messages.set(this.BUILTIN, data.builtinMessages); + } +} + + +LocaleData.prototype = { + // Representation of the object to send to content processes. This + // should include anything the content process might need. + serialize() { + return { + defaultLocale: this.defaultLocale, + selectedLocale: this.selectedLocale, + messages: this.messages, + locales: this.locales, + }; + }, + + BUILTIN: "@@BUILTIN_MESSAGES", + + has(locale) { + return this.messages.has(locale); + }, + + // https://developer.chrome.com/extensions/i18n + localizeMessage(message, substitutions = [], options = {}) { + let defaultOptions = { + locale: this.selectedLocale, + defaultValue: "", + cloneScope: null, + }; + + options = Object.assign(defaultOptions, options); + + let locales = new Set([this.BUILTIN, options.locale, this.defaultLocale] + .filter(locale => this.messages.has(locale))); + + // Message names are case-insensitive, so normalize them to lower-case. + message = message.toLowerCase(); + for (let locale of locales) { + let messages = this.messages.get(locale); + if (messages.has(message)) { + let str = messages.get(message); + + if (!Array.isArray(substitutions)) { + substitutions = [substitutions]; + } + + let replacer = (matched, index, dollarSigns) => { + if (index) { + // This is not quite Chrome-compatible. Chrome consumes any number + // of digits following the $, but only accepts 9 substitutions. We + // accept any number of substitutions. + index = parseInt(index, 10) - 1; + return index in substitutions ? substitutions[index] : ""; + } + // For any series of contiguous `$`s, the first is dropped, and + // the rest remain in the output string. + return dollarSigns; + }; + return str.replace(/\$(?:([1-9]\d*)|(\$+))/g, replacer); + } + } + + // Check for certain pre-defined messages. + if (message == "@@ui_locale") { + return this.uiLocale; + } else if (message.startsWith("@@bidi_")) { + let registry = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIXULChromeRegistry); + let rtl = registry.isLocaleRTL("global"); + + if (message == "@@bidi_dir") { + return rtl ? "rtl" : "ltr"; + } else if (message == "@@bidi_reversed_dir") { + return rtl ? "ltr" : "rtl"; + } else if (message == "@@bidi_start_edge") { + return rtl ? "right" : "left"; + } else if (message == "@@bidi_end_edge") { + return rtl ? "left" : "right"; + } + } + + if (!this.warnedMissingKeys.has(message)) { + let error = `Unknown localization message ${message}`; + if (options.cloneScope) { + error = new options.cloneScope.Error(error); + } + Cu.reportError(error); + this.warnedMissingKeys.add(message); + } + return options.defaultValue; + }, + + // Localize a string, replacing all |__MSG_(.*)__| tokens with the + // matching string from the current locale, as determined by + // |this.selectedLocale|. + // + // This may not be called before calling either |initLocale| or + // |initAllLocales|. + localize(str, locale = this.selectedLocale) { + if (!str) { + return str; + } + + return str.replace(/__MSG_([A-Za-z0-9@_]+?)__/g, (matched, message) => { + return this.localizeMessage(message, [], {locale, defaultValue: matched}); + }); + }, + + // Validates the contents of a locale JSON file, normalizes the + // messages into a Map of message key -> localized string pairs. + addLocale(locale, messages, extension) { + let result = new Map(); + + // Chrome does not document the semantics of its localization + // system very well. It handles replacements by pre-processing + // messages, replacing |$[a-zA-Z0-9@_]+$| tokens with the value of their + // replacements. Later, it processes the resulting string for + // |$[0-9]| replacements. + // + // Again, it does not document this, but it accepts any number + // of sequential |$|s, and replaces them with that number minus + // 1. It also accepts |$| followed by any number of sequential + // digits, but refuses to process a localized string which + // provides more than 9 substitutions. + if (!instanceOf(messages, "Object")) { + extension.packagingError(`Invalid locale data for ${locale}`); + return result; + } + + for (let key of Object.keys(messages)) { + let msg = messages[key]; + + if (!instanceOf(msg, "Object") || typeof(msg.message) != "string") { + extension.packagingError(`Invalid locale message data for ${locale}, message ${JSON.stringify(key)}`); + continue; + } + + // Substitutions are case-insensitive, so normalize all of their names + // to lower-case. + let placeholders = new Map(); + if (instanceOf(msg.placeholders, "Object")) { + for (let key of Object.keys(msg.placeholders)) { + placeholders.set(key.toLowerCase(), msg.placeholders[key]); + } + } + + let replacer = (match, name) => { + let replacement = placeholders.get(name.toLowerCase()); + if (instanceOf(replacement, "Object") && "content" in replacement) { + return replacement.content; + } + return ""; + }; + + let value = msg.message.replace(/\$([A-Za-z0-9@_]+)\$/g, replacer); + + // Message names are also case-insensitive, so normalize them to lower-case. + result.set(key.toLowerCase(), value); + } + + this.messages.set(locale, result); + return result; + }, + + get acceptLanguages() { + let result = Preferences.get("intl.accept_languages", "", Ci.nsIPrefLocalizedString); + return result.split(/\s*,\s*/g); + }, + + + get uiLocale() { + // Return the browser locale, but convert it to a Chrome-style + // locale code. + return Locale.getLocale().replace(/-/g, "_"); + }, +}; + +// This is a generic class for managing event listeners. Example usage: +// +// new EventManager(context, "api.subAPI", fire => { +// let listener = (...) => { +// // Fire any listeners registered with addListener. +// fire(arg1, arg2); +// }; +// // Register the listener. +// SomehowRegisterListener(listener); +// return () => { +// // Return a way to unregister the listener. +// SomehowUnregisterListener(listener); +// }; +// }).api() +// +// The result is an object with addListener, removeListener, and +// hasListener methods. |context| is an add-on scope (either an +// ExtensionContext in the chrome process or ExtensionContext in a +// content process). |name| is for debugging. |register| is a function +// to register the listener. |register| is only called once, even if +// multiple listeners are registered. |register| should return an +// unregister function that will unregister the listener. +function EventManager(context, name, register) { + this.context = context; + this.name = name; + this.register = register; + this.unregister = null; + this.callbacks = new Set(); +} + +EventManager.prototype = { + addListener(callback) { + if (typeof(callback) != "function") { + dump(`Expected function\n${Error().stack}`); + return; + } + if (this.context.unloaded) { + dump(`Cannot add listener to ${this.name} after context unloaded`); + return; + } + + if (!this.callbacks.size) { + this.context.callOnClose(this); + + let fireFunc = this.fire.bind(this); + let fireWithoutClone = this.fireWithoutClone.bind(this); + fireFunc.withoutClone = fireWithoutClone; + this.unregister = this.register(fireFunc); + } + this.callbacks.add(callback); + }, + + removeListener(callback) { + if (!this.callbacks.size) { + return; + } + + this.callbacks.delete(callback); + if (this.callbacks.size == 0) { + this.unregister(); + this.unregister = null; + + this.context.forgetOnClose(this); + } + }, + + hasListener(callback) { + return this.callbacks.has(callback); + }, + + fire(...args) { + this._fireCommon("runSafe", args); + }, + + fireWithoutClone(...args) { + this._fireCommon("runSafeWithoutClone", args); + }, + + _fireCommon(runSafeMethod, args) { + for (let callback of this.callbacks) { + Promise.resolve(callback).then(callback => { + if (this.context.unloaded) { + dump(`${this.name} event fired after context unloaded.\n`); + } else if (!this.context.active) { + dump(`${this.name} event fired while context is inactive.\n`); + } else if (this.callbacks.has(callback)) { + this.context[runSafeMethod](callback, ...args); + } + }); + } + }, + + close() { + if (this.callbacks.size) { + this.unregister(); + } + this.callbacks.clear(); + this.register = null; + this.unregister = null; + }, + + api() { + return { + addListener: callback => this.addListener(callback), + removeListener: callback => this.removeListener(callback), + hasListener: callback => this.hasListener(callback), + }; + }, +}; + +// Similar to EventManager, but it doesn't try to consolidate event +// notifications. Each addListener call causes us to register once. It +// allows extra arguments to be passed to addListener. +function SingletonEventManager(context, name, register) { + this.context = context; + this.name = name; + this.register = register; + this.unregister = new Map(); +} + +SingletonEventManager.prototype = { + addListener(callback, ...args) { + let wrappedCallback = (...args) => { + if (this.context.unloaded) { + dump(`${this.name} event fired after context unloaded.\n`); + } else if (this.unregister.has(callback)) { + return callback(...args); + } + }; + + let unregister = this.register(wrappedCallback, ...args); + this.unregister.set(callback, unregister); + this.context.callOnClose(this); + }, + + removeListener(callback) { + if (!this.unregister.has(callback)) { + return; + } + + let unregister = this.unregister.get(callback); + this.unregister.delete(callback); + unregister(); + }, + + hasListener(callback) { + return this.unregister.has(callback); + }, + + close() { + for (let unregister of this.unregister.values()) { + unregister(); + } + }, + + api() { + return { + addListener: (...args) => this.addListener(...args), + removeListener: (...args) => this.removeListener(...args), + hasListener: (...args) => this.hasListener(...args), + }; + }, +}; + +// Simple API for event listeners where events never fire. +function ignoreEvent(context, name) { + return { + addListener: function(callback) { + let id = context.extension.id; + let frame = Components.stack.caller; + let msg = `In add-on ${id}, attempting to use listener "${name}", which is unimplemented.`; + let scriptError = Cc["@mozilla.org/scripterror;1"] + .createInstance(Ci.nsIScriptError); + scriptError.init(msg, frame.filename, null, frame.lineNumber, + frame.columnNumber, Ci.nsIScriptError.warningFlag, + "content javascript"); + let consoleService = Cc["@mozilla.org/consoleservice;1"] + .getService(Ci.nsIConsoleService); + consoleService.logMessage(scriptError); + }, + removeListener: function(callback) {}, + hasListener: function(callback) {}, + }; +} + +// Copy an API object from |source| into the scope |dest|. +function injectAPI(source, dest) { + for (let prop in source) { + // Skip names prefixed with '_'. + if (prop[0] == "_") { + continue; + } + + let desc = Object.getOwnPropertyDescriptor(source, prop); + if (typeof(desc.value) == "function") { + Cu.exportFunction(desc.value, dest, {defineAs: prop}); + } else if (typeof(desc.value) == "object") { + let obj = Cu.createObjectIn(dest, {defineAs: prop}); + injectAPI(desc.value, obj); + } else { + Object.defineProperty(dest, prop, desc); + } + } +} + +/** + * Returns a Promise which resolves when the given document's DOM has + * fully loaded. + * + * @param {Document} doc The document to await the load of. + * @returns {Promise} + */ +function promiseDocumentReady(doc) { + if (doc.readyState == "interactive" || doc.readyState == "complete") { + return Promise.resolve(doc); + } + + return new Promise(resolve => { + doc.addEventListener("DOMContentLoaded", function onReady(event) { + if (event.target === event.currentTarget) { + doc.removeEventListener("DOMContentLoaded", onReady, true); + resolve(doc); + } + }, true); + }); +} + +/** + * Returns a Promise which resolves when the given document is fully + * loaded. + * + * @param {Document} doc The document to await the load of. + * @returns {Promise} + */ +function promiseDocumentLoaded(doc) { + if (doc.readyState == "complete") { + return Promise.resolve(doc); + } + + return new Promise(resolve => { + doc.defaultView.addEventListener("load", function onReady(event) { + doc.defaultView.removeEventListener("load", onReady); + resolve(doc); + }); + }); +} + +/** + * Returns a Promise which resolves when the given event is dispatched to the + * given element. + * + * @param {Element} element + * The element on which to listen. + * @param {string} eventName + * The event to listen for. + * @param {boolean} [useCapture = true] + * If true, listen for the even in the capturing rather than + * bubbling phase. + * @param {Event} [test] + * An optional test function which, when called with the + * observer's subject and data, should return true if this is the + * expected event, false otherwise. + * @returns {Promise} + */ +function promiseEvent(element, eventName, useCapture = true, test = event => true) { + return new Promise(resolve => { + function listener(event) { + if (test(event)) { + element.removeEventListener(eventName, listener, useCapture); + resolve(event); + } + } + element.addEventListener(eventName, listener, useCapture); + }); +} + +/** + * Returns a Promise which resolves the given observer topic has been + * observed. + * + * @param {string} topic + * The topic to observe. + * @param {function(nsISupports, string)} [test] + * An optional test function which, when called with the + * observer's subject and data, should return true if this is the + * expected notification, false otherwise. + * @returns {Promise} + */ +function promiseObserved(topic, test = () => true) { + return new Promise(resolve => { + let observer = (subject, topic, data) => { + if (test(subject, data)) { + Services.obs.removeObserver(observer, topic); + resolve({subject, data}); + } + }; + Services.obs.addObserver(observer, topic, false); + }); +} + +function getMessageManager(target) { + if (target instanceof Ci.nsIFrameLoaderOwner) { + return target.QueryInterface(Ci.nsIFrameLoaderOwner).frameLoader.messageManager; + } + return target.QueryInterface(Ci.nsIMessageSender); +} + +function flushJarCache(jarFile) { + Services.obs.notifyObservers(jarFile, "flush-cache-entry", null); +} + +const PlatformInfo = Object.freeze({ + os: (function() { + let os = AppConstants.platform; + if (os == "macosx") { + os = "mac"; + } + return os; + })(), + arch: (function() { + let abi = Services.appinfo.XPCOMABI; + let [arch] = abi.split("-"); + if (arch == "x86") { + arch = "x86-32"; + } else if (arch == "x86_64") { + arch = "x86-64"; + } + return arch; + })(), +}); + +function detectLanguage(text) { + return LanguageDetector.detectLanguage(text).then(result => ({ + isReliable: result.confident, + languages: result.languages.map(lang => { + return { + language: lang.languageCode, + percentage: lang.percent, + }; + }), + })); +} + +/** + * Convert any of several different representations of a date/time to a Date object. + * Accepts several formats: + * a Date object, an ISO8601 string, or a number of milliseconds since the epoch as + * either a number or a string. + * + * @param {Date|string|number} date + * The date to convert. + * @returns {Date} + * A Date object + */ +function normalizeTime(date) { + // Of all the formats we accept the "number of milliseconds since the epoch as a string" + // is an outlier, everything else can just be passed directly to the Date constructor. + return new Date((typeof date == "string" && /^\d+$/.test(date)) + ? parseInt(date, 10) : date); +} + +const stylesheetMap = new DefaultMap(url => { + let uri = NetUtil.newURI(url); + return styleSheetService.preloadSheet(uri, styleSheetService.AGENT_SHEET); +}); + +/** + * Defines a lazy getter for the given property on the given object. The + * first time the property is accessed, the return value of the getter + * is defined on the current `this` object with the given property name. + * Importantly, this means that a lazy getter defined on an object + * prototype will be invoked separately for each object instance that + * it's accessed on. + * + * @param {object} object + * The prototype object on which to define the getter. + * @param {string|Symbol} prop + * The property name for which to define the getter. + * @param {function} getter + * The function to call in order to generate the final property + * value. + */ +function defineLazyGetter(object, prop, getter) { + let redefine = (obj, value) => { + Object.defineProperty(obj, prop, { + enumerable: true, + configurable: true, + writable: true, + value, + }); + return value; + }; + + Object.defineProperty(object, prop, { + enumerable: true, + configurable: true, + + get() { + return redefine(this, getter.call(this)); + }, + + set(value) { + redefine(this, value); + }, + }); +} + +function findPathInObject(obj, path, printErrors = true) { + let parent; + for (let elt of path.split(".")) { + if (!obj || !(elt in obj)) { + if (printErrors) { + let appname = Services.appinfo.name; + Cu.reportError(`WebExtension API ${path} not found (it may be unimplemented by ${appname}).`); + } + return null; + } + + parent = obj; + obj = obj[elt]; + } + + if (typeof obj === "function") { + return obj.bind(parent); + } + return obj; +} + +/** + * Acts as a proxy for a message manager or message manager owner, and + * tracks docShell swaps so that messages are always sent to the same + * receiver, even if it is moved to a different . + * + * @param {nsIMessageSender|Element} target + * The target message manager on which to send messages, or the + * element which owns it. + */ +class MessageManagerProxy { + constructor(target) { + this.listeners = new DefaultMap(() => new Map()); + + if (target instanceof Ci.nsIMessageSender) { + Object.defineProperty(this, "messageManager", { + value: target, + configurable: true, + writable: true, + }); + } else { + this.addListeners(target); + } + } + + /** + * Disposes of the proxy object, removes event listeners, and drops + * all references to the underlying message manager. + * + * Must be called before the last reference to the proxy is dropped, + * unless the underlying message manager or is also being + * destroyed. + */ + dispose() { + if (this.eventTarget) { + this.removeListeners(this.eventTarget); + this.eventTarget = null; + } else { + this.messageManager = null; + } + } + + /** + * Returns true if the given target is the same as, or owns, the given + * message manager. + * + * @param {nsIMessageSender|MessageManagerProxy|Element} target + * The message manager, MessageManagerProxy, or + * element agaisnt which to match. + * @param {nsIMessageSender} messageManager + * The message manager against which to match `target`. + * + * @returns {boolean} + * True if `messageManager` is the same object as `target`, or + * `target` is a MessageManagerProxy or element that + * is tied to it. + */ + static matches(target, messageManager) { + return target === messageManager || target.messageManager === messageManager; + } + + /** + * @property {nsIMessageSender|null} messageManager + * The message manager that is currently being proxied. This + * may change during the life of the proxy object, so should + * not be stored elsewhere. + */ + get messageManager() { + return this.eventTarget && this.eventTarget.messageManager; + } + + /** + * Sends a message on the proxied message manager. + * + * @param {array} args + * Arguments to be passed verbatim to the underlying + * sendAsyncMessage method. + * @returns {undefined} + */ + sendAsyncMessage(...args) { + if (this.messageManager) { + return this.messageManager.sendAsyncMessage(...args); + } + /* globals uneval */ + Cu.reportError(`Cannot send message: Other side disconnected: ${uneval(args)}`); + } + + /** + * Adds a message listener to the current message manager, and + * transfers it to the new message manager after a docShell swap. + * + * @param {string} message + * The name of the message to listen for. + * @param {nsIMessageListener} listener + * The listener to add. + * @param {boolean} [listenWhenClosed = false] + * If true, the listener will receive messages which were sent + * after the remote side of the listener began closing. + */ + addMessageListener(message, listener, listenWhenClosed = false) { + this.messageManager.addMessageListener(message, listener, listenWhenClosed); + this.listeners.get(message).set(listener, listenWhenClosed); + } + + /** + * Adds a message listener from the current message manager. + * + * @param {string} message + * The name of the message to stop listening for. + * @param {nsIMessageListener} listener + * The listener to remove. + */ + removeMessageListener(message, listener) { + this.messageManager.removeMessageListener(message, listener); + + let listeners = this.listeners.get(message); + listeners.delete(listener); + if (!listeners.size) { + this.listeners.delete(message); + } + } + + /** + * @private + * Iterates over all of the currently registered message listeners. + */ + * iterListeners() { + for (let [message, listeners] of this.listeners) { + for (let [listener, listenWhenClosed] of listeners) { + yield {message, listener, listenWhenClosed}; + } + } + } + + /** + * @private + * Adds docShell swap listeners to the message manager owner. + * + * @param {Element} target + * The target element. + */ + addListeners(target) { + target.addEventListener("SwapDocShells", this); + + for (let {message, listener, listenWhenClosed} of this.iterListeners()) { + target.addMessageListener(message, listener, listenWhenClosed); + } + + this.eventTarget = target; + } + + /** + * @private + * Removes docShell swap listeners to the message manager owner. + * + * @param {Element} target + * The target element. + */ + removeListeners(target) { + target.removeEventListener("SwapDocShells", this); + + for (let {message, listener} of this.iterListeners()) { + target.removeMessageListener(message, listener); + } + } + + handleEvent(event) { + if (event.type == "SwapDocShells") { + this.removeListeners(this.eventTarget); + this.addListeners(event.detail); + } + } +} + +this.ExtensionUtils = { + defineLazyGetter, + detectLanguage, + extend, + findPathInObject, + flushJarCache, + getConsole, + getInnerWindowID, + getMessageManager, + getUniqueId, + ignoreEvent, + injectAPI, + instanceOf, + normalizeTime, + promiseDocumentLoaded, + promiseDocumentReady, + promiseEvent, + promiseObserved, + runSafe, + runSafeSync, + runSafeSyncWithoutClone, + runSafeWithoutClone, + stylesheetMap, + DefaultMap, + DefaultWeakMap, + EventEmitter, + EventManager, + ExtensionError, + IconDetails, + LocaleData, + MessageManagerProxy, + PlatformInfo, + SingletonEventManager, + SpreadArgs, +}; diff --git a/toolkit/components/webextensions/ExtensionXPCShellUtils.jsm b/toolkit/components/webextensions/ExtensionXPCShellUtils.jsm new file mode 100644 index 000000000..339709a19 --- /dev/null +++ b/toolkit/components/webextensions/ExtensionXPCShellUtils.jsm @@ -0,0 +1,306 @@ +/* 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"; + +this.EXPORTED_SYMBOLS = ["ExtensionTestUtils"]; + +const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; + +Components.utils.import("resource://gre/modules/Task.jsm"); +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "Extension", + "resource://gre/modules/Extension.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "FileUtils", + "resource://gre/modules/FileUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Schemas", + "resource://gre/modules/Schemas.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Services", + "resource://gre/modules/Services.jsm"); + +XPCOMUtils.defineLazyGetter(this, "Management", () => { + const {Management} = Cu.import("resource://gre/modules/Extension.jsm", {}); + return Management; +}); + +/* exported ExtensionTestUtils */ + +let BASE_MANIFEST = Object.freeze({ + "applications": Object.freeze({ + "gecko": Object.freeze({ + "id": "test@web.ext", + }), + }), + + "manifest_version": 2, + + "name": "name", + "version": "0", +}); + +class ExtensionWrapper { + constructor(extension, testScope) { + this.extension = extension; + this.testScope = testScope; + + this.state = "uninitialized"; + + this.testResolve = null; + this.testDone = new Promise(resolve => { this.testResolve = resolve; }); + + this.messageHandler = new Map(); + this.messageAwaiter = new Map(); + + this.messageQueue = new Set(); + + this.attachListeners(); + + this.testScope.do_register_cleanup(() => { + if (this.messageQueue.size) { + let names = Array.from(this.messageQueue, ([msg]) => msg); + this.testScope.equal(JSON.stringify(names), "[]", "message queue is empty"); + } + if (this.messageAwaiter.size) { + let names = Array.from(this.messageAwaiter.keys()); + this.testScope.equal(JSON.stringify(names), "[]", "no tasks awaiting on messages"); + } + }); + + this.testScope.do_register_cleanup(() => { + if (this.state == "pending" || this.state == "running") { + this.testScope.equal(this.state, "unloaded", "Extension left running at test shutdown"); + return this.unload(); + } else if (extension.state == "unloading") { + this.testScope.equal(this.state, "unloaded", "Extension not fully unloaded at test shutdown"); + } + }); + + this.testScope.do_print(`Extension loaded`); + } + + attachListeners() { + /* eslint-disable mozilla/balanced-listeners */ + this.extension.on("test-eq", (kind, pass, msg, expected, actual) => { + this.testScope.ok(pass, `${msg} - Expected: ${expected}, Actual: ${actual}`); + }); + this.extension.on("test-log", (kind, pass, msg) => { + this.testScope.do_print(msg); + }); + this.extension.on("test-result", (kind, pass, msg) => { + this.testScope.ok(pass, msg); + }); + this.extension.on("test-done", (kind, pass, msg, expected, actual) => { + this.testScope.ok(pass, msg); + this.testResolve(msg); + }); + + this.extension.on("test-message", (kind, msg, ...args) => { + let handler = this.messageHandler.get(msg); + if (handler) { + handler(...args); + } else { + this.messageQueue.add([msg, ...args]); + this.checkMessages(); + } + }); + /* eslint-enable mozilla/balanced-listeners */ + } + + startup() { + if (this.state != "uninitialized") { + throw new Error("Extension already started"); + } + this.state = "pending"; + + return this.extension.startup().then( + result => { + this.state = "running"; + + return result; + }, + error => { + this.state = "failed"; + + return Promise.reject(error); + }); + } + + unload() { + if (this.state != "running") { + throw new Error("Extension not running"); + } + this.state = "unloading"; + + this.extension.shutdown(); + + this.state = "unloaded"; + + return Promise.resolve(); + } + + /* + * This method marks the extension unloading without actually calling + * shutdown, since shutting down a MockExtension causes it to be uninstalled. + * + * Normally you shouldn't need to use this unless you need to test something + * that requires a restart, such as updates. + */ + markUnloaded() { + if (this.state != "running") { + throw new Error("Extension not running"); + } + this.state = "unloaded"; + + return Promise.resolve(); + } + + sendMessage(...args) { + this.extension.testMessage(...args); + } + + awaitFinish(msg) { + return this.testDone.then(actual => { + if (msg) { + this.testScope.equal(actual, msg, "test result correct"); + } + return actual; + }); + } + + checkMessages() { + for (let message of this.messageQueue) { + let [msg, ...args] = message; + + let listener = this.messageAwaiter.get(msg); + if (listener) { + this.messageQueue.delete(message); + this.messageAwaiter.delete(msg); + + listener.resolve(...args); + return; + } + } + } + + checkDuplicateListeners(msg) { + if (this.messageHandler.has(msg) || this.messageAwaiter.has(msg)) { + throw new Error("only one message handler allowed"); + } + } + + awaitMessage(msg) { + return new Promise(resolve => { + this.checkDuplicateListeners(msg); + + this.messageAwaiter.set(msg, {resolve}); + this.checkMessages(); + }); + } + + onMessage(msg, callback) { + this.checkDuplicateListeners(msg); + this.messageHandler.set(msg, callback); + } +} + +var ExtensionTestUtils = { + BASE_MANIFEST, + + normalizeManifest: Task.async(function* (manifest, baseManifest = BASE_MANIFEST) { + yield Management.lazyInit(); + + let errors = []; + let context = { + url: null, + + logError: error => { + errors.push(error); + }, + + preprocessors: {}, + }; + + manifest = Object.assign({}, baseManifest, manifest); + + let normalized = Schemas.normalize(manifest, "manifest.WebExtensionManifest", context); + normalized.errors = errors; + + return normalized; + }), + + currentScope: null, + + profileDir: null, + + init(scope) { + this.currentScope = scope; + + this.profileDir = scope.do_get_profile(); + + // We need to load at least one frame script into every message + // manager to ensure that the scriptable wrapper for its global gets + // created before we try to access it externally. If we don't, we + // fail sanity checks on debug builds the first time we try to + // create a wrapper, because we should never have a global without a + // cached wrapper. + Services.mm.loadFrameScript("data:text/javascript,//", true); + + + let tmpD = this.profileDir.clone(); + tmpD.append("tmp"); + tmpD.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); + + let dirProvider = { + getFile(prop, persistent) { + persistent.value = false; + if (prop == "TmpD") { + return tmpD.clone(); + } + return null; + }, + + QueryInterface: XPCOMUtils.generateQI([Ci.nsIDirectoryServiceProvider]), + }; + Services.dirsvc.registerProvider(dirProvider); + + + scope.do_register_cleanup(() => { + tmpD.remove(true); + Services.dirsvc.unregisterProvider(dirProvider); + + this.currentScope = null; + }); + }, + + addonManagerStarted: false, + + mockAppInfo() { + const {updateAppInfo} = Cu.import("resource://testing-common/AppInfo.jsm", {}); + updateAppInfo({ + ID: "xpcshell@tests.mozilla.org", + name: "XPCShell", + version: "48", + platformVersion: "48", + }); + }, + + startAddonManager() { + if (this.addonManagerStarted) { + return; + } + this.addonManagerStarted = true; + this.mockAppInfo(); + + let manager = Cc["@mozilla.org/addons/integration;1"].getService(Ci.nsIObserver) + .QueryInterface(Ci.nsITimerCallback); + manager.observe(null, "addons-startup", null); + }, + + loadExtension(data) { + let extension = Extension.generate(data); + + return new ExtensionWrapper(extension, this.currentScope); + }, +}; diff --git a/toolkit/components/webextensions/LegacyExtensionsUtils.jsm b/toolkit/components/webextensions/LegacyExtensionsUtils.jsm new file mode 100644 index 000000000..e8d276fe9 --- /dev/null +++ b/toolkit/components/webextensions/LegacyExtensionsUtils.jsm @@ -0,0 +1,250 @@ +/* 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"; + +this.EXPORTED_SYMBOLS = ["LegacyExtensionsUtils"]; + +/* exported LegacyExtensionsUtils, LegacyExtensionContext */ + +/** + * This file exports helpers for Legacy Extensions that want to embed a webextensions + * and exchange messages with the embedded WebExtension. + */ + +const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "Extension", + "resource://gre/modules/Extension.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Services", + "resource://gre/modules/Services.jsm"); + +Cu.import("resource://gre/modules/ExtensionChild.jsm"); +Cu.import("resource://gre/modules/ExtensionCommon.jsm"); + +var { + BaseContext, +} = ExtensionCommon; + +var { + Messenger, +} = ExtensionChild; + +/** + * Instances created from this class provide to a legacy extension + * a simple API to exchange messages with a webextension. + */ +var LegacyExtensionContext = class extends BaseContext { + /** + * Create a new LegacyExtensionContext given a target Extension instance. + * + * @param {Extension} targetExtension + * The webextension instance associated with this context. This will be the + * instance of the newly created embedded webextension when this class is + * used through the EmbeddedWebExtensionsUtils. + */ + constructor(targetExtension) { + super("legacy_extension", targetExtension); + + // Legacy Extensions (xul overlays, bootstrap restartless and Addon SDK) + // runs with a systemPrincipal. + let addonPrincipal = Services.scriptSecurityManager.getSystemPrincipal(); + Object.defineProperty( + this, "principal", + {value: addonPrincipal, enumerable: true, configurable: true} + ); + + let cloneScope = Cu.Sandbox(this.principal, {}); + Cu.setSandboxMetadata(cloneScope, {addonId: targetExtension.id}); + Object.defineProperty( + this, "cloneScope", + {value: cloneScope, enumerable: true, configurable: true, writable: true} + ); + + let sender = {id: targetExtension.id}; + let filter = {extensionId: targetExtension.id}; + // Legacy addons live in the main process. Messages from other addons are + // Messages from WebExtensions are sent to the main process and forwarded via + // the parent process manager to the legacy extension. + this.messenger = new Messenger(this, [Services.cpmm], sender, filter); + + this.api = { + browser: { + runtime: { + onConnect: this.messenger.onConnect("runtime.onConnect"), + onMessage: this.messenger.onMessage("runtime.onMessage"), + }, + }, + }; + } + + /** + * This method is called when the extension shuts down or is unloaded, + * and it nukes the cloneScope sandbox, if any. + */ + unload() { + if (this.unloaded) { + throw new Error("Error trying to unload LegacyExtensionContext twice."); + } + super.unload(); + Cu.nukeSandbox(this.cloneScope); + this.cloneScope = null; + } +}; + +var EmbeddedExtensionManager; + +/** + * Instances of this class are used internally by the exported EmbeddedWebExtensionsUtils + * to manage the embedded webextension instance and the related LegacyExtensionContext + * instance used to exchange messages with it. + */ +class EmbeddedExtension { + /** + * Create a new EmbeddedExtension given the add-on id and the base resource URI of the + * container add-on (the webextension resources will be loaded from the "webextension/" + * subdir of the base resource URI for the legacy extension add-on). + * + * @param {Object} containerAddonParams + * An object with the following properties: + * @param {string} containerAddonParams.id + * The Add-on id of the Legacy Extension which will contain the embedded webextension. + * @param {nsIURI} containerAddonParams.resourceURI + * The nsIURI of the Legacy Extension container add-on. + */ + constructor({id, resourceURI}) { + this.addonId = id; + this.resourceURI = resourceURI; + + // Setup status flag. + this.started = false; + } + + /** + * Start the embedded webextension. + * + * @returns {Promise} A promise which resolve to the API exposed to the + * legacy context. + */ + startup() { + if (this.started) { + return Promise.reject(new Error("This embedded extension has already been started")); + } + + // Setup the startup promise. + this.startupPromise = new Promise((resolve, reject) => { + let embeddedExtensionURI = Services.io.newURI("webextension/", null, this.resourceURI); + + // This is the instance of the WebExtension embedded in the hybrid add-on. + this.extension = new Extension({ + id: this.addonId, + resourceURI: embeddedExtensionURI, + }); + + // This callback is register to the "startup" event, emitted by the Extension instance + // after the extension manifest.json has been loaded without any errors, but before + // starting any of the defined contexts (which give the legacy part a chance to subscribe + // runtime.onMessage/onConnect listener before the background page has been loaded). + const onBeforeStarted = () => { + this.extension.off("startup", onBeforeStarted); + + // Resolve the startup promise and reset the startupError. + this.started = true; + this.startupPromise = null; + + // Create the legacy extension context, the legacy container addon + // needs to use it before the embedded webextension startup, + // because it is supposed to be used during the legacy container startup + // to subscribe its message listeners (which are supposed to be able to + // receive any message that the embedded part can try to send to it + // during its startup). + this.context = new LegacyExtensionContext(this.extension); + + // Destroy the LegacyExtensionContext cloneScope when + // the embedded webextensions is unloaded. + this.extension.callOnClose({ + close: () => { + this.context.unload(); + }, + }); + + // resolve startupPromise to execute any pending shutdown that has been + // chained to it. + resolve(this.context.api); + }; + + this.extension.on("startup", onBeforeStarted); + + // Run ambedded extension startup and catch any error during embedded extension + // startup. + this.extension.startup().catch((err) => { + this.started = false; + this.startupPromise = null; + this.extension.off("startup", onBeforeStarted); + + reject(err); + }); + }); + + return this.startupPromise; + } + + /** + * Shuts down the embedded webextension. + * + * @returns {Promise} a promise that is resolved when the shutdown has been done + */ + shutdown() { + EmbeddedExtensionManager.untrackEmbeddedExtension(this); + + // If there is a pending startup, wait to be completed and then shutdown. + if (this.startupPromise) { + return this.startupPromise.then(() => { + this.extension.shutdown(); + }); + } + + // Run shutdown now if the embedded webextension has been correctly started + if (this.extension && this.started && !this.extension.hasShutdown) { + this.extension.shutdown(); + } + + return Promise.resolve(); + } +} + +// Keep track on the created EmbeddedExtension instances and destroy +// them when their container addon is going to be disabled or uninstalled. +EmbeddedExtensionManager = { + // Map of the existent EmbeddedExtensions instances by addon id. + embeddedExtensionsByAddonId: new Map(), + + untrackEmbeddedExtension(embeddedExtensionInstance) { + // Remove this instance from the tracked embedded extensions + let id = embeddedExtensionInstance.addonId; + if (this.embeddedExtensionsByAddonId.get(id) == embeddedExtensionInstance) { + this.embeddedExtensionsByAddonId.delete(id); + } + }, + + getEmbeddedExtensionFor({id, resourceURI}) { + let embeddedExtension = this.embeddedExtensionsByAddonId.get(id); + + if (!embeddedExtension) { + embeddedExtension = new EmbeddedExtension({id, resourceURI}); + // Keep track of the embedded extension instance. + this.embeddedExtensionsByAddonId.set(id, embeddedExtension); + } + + return embeddedExtension; + }, +}; + +this.LegacyExtensionsUtils = { + getEmbeddedExtensionFor: (addon) => { + return EmbeddedExtensionManager.getEmbeddedExtensionFor(addon); + }, +}; diff --git a/toolkit/components/webextensions/MessageChannel.jsm b/toolkit/components/webextensions/MessageChannel.jsm new file mode 100644 index 000000000..c5b326405 --- /dev/null +++ b/toolkit/components/webextensions/MessageChannel.jsm @@ -0,0 +1,797 @@ +/* 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"; + +/** + * This module provides wrappers around standard message managers to + * simplify bidirectional communication. It currently allows a caller to + * send a message to a single listener, and receive a reply. If there + * are no matching listeners, or the message manager disconnects before + * a reply is received, the caller is returned an error. + * + * The listener end may specify filters for the messages it wishes to + * receive, and the sender end likewise may specify recipient tags to + * match the filters. + * + * The message handler on the listener side may return its response + * value directly, or may return a promise, the resolution or rejection + * of which will be returned instead. The sender end likewise receives a + * promise which resolves or rejects to the listener's response. + * + * + * A basic setup works something like this: + * + * A content script adds a message listener to its global + * nsIContentFrameMessageManager, with an appropriate set of filters: + * + * { + * init(messageManager, window, extensionID) { + * this.window = window; + * + * MessageChannel.addListener( + * messageManager, "ContentScript:TouchContent", + * this); + * + * this.messageFilterStrict = { + * innerWindowID: getInnerWindowID(window), + * extensionID: extensionID, + * }; + * + * this.messageFilterPermissive = { + * outerWindowID: getOuterWindowID(window), + * }; + * }, + * + * receiveMessage({ target, messageName, sender, recipient, data }) { + * if (messageName == "ContentScript:TouchContent") { + * return new Promise(resolve => { + * this.touchWindow(data.touchWith, result => { + * resolve({ touchResult: result }); + * }); + * }); + * } + * }, + * }; + * + * A script in the parent process sends a message to the content process + * via a tab message manager, including recipient tags to match its + * filter, and an optional sender tag to identify itself: + * + * let data = { touchWith: "pencil" }; + * let sender = { extensionID, contextID }; + * let recipient = { innerWindowID: tab.linkedBrowser.innerWindowID, extensionID }; + * + * MessageChannel.sendMessage( + * tab.linkedBrowser.messageManager, "ContentScript:TouchContent", + * data, {recipient, sender} + * ).then(result => { + * alert(result.touchResult); + * }); + * + * Since the lifetimes of message senders and receivers may not always + * match, either side of the message channel may cancel pending + * responses which match its sender or recipient tags. + * + * For the above client, this might be done from an + * inner-window-destroyed observer, when its target scope is destroyed: + * + * observe(subject, topic, data) { + * if (topic == "inner-window-destroyed") { + * let innerWindowID = subject.QueryInterface(Ci.nsISupportsPRUint64).data; + * + * MessageChannel.abortResponses({ innerWindowID }); + * } + * }, + * + * From the parent, it may be done when its context is being destroyed: + * + * onDestroy() { + * MessageChannel.abortResponses({ + * extensionID: this.extensionID, + * contextID: this.contextID, + * }); + * }, + * + */ + +this.EXPORTED_SYMBOLS = ["MessageChannel"]; + +/* globals MessageChannel */ + +const Ci = Components.interfaces; +const Cc = Components.classes; +const Cu = Components.utils; +const Cr = Components.results; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionUtils", + "resource://gre/modules/ExtensionUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PromiseUtils", + "resource://gre/modules/PromiseUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Task", + "resource://gre/modules/Task.jsm"); + +XPCOMUtils.defineLazyGetter(this, "MessageManagerProxy", + () => ExtensionUtils.MessageManagerProxy); + +/** + * Handles the mapping and dispatching of messages to their registered + * handlers. There is one broker per message manager and class of + * messages. Each class of messages is mapped to one native message + * name, e.g., "MessageChannel:Message", and is dispatched to handlers + * based on an internal message name, e.g., "Extension:ExecuteScript". + */ +class FilteringMessageManager { + /** + * @param {string} messageName + * The name of the native message this broker listens for. + * @param {function} callback + * A function which is called for each message after it has been + * mapped to its handler. The function receives two arguments: + * + * result: + * An object containing either a `handler` or an `error` property. + * If no error occurs, `handler` will be a matching handler that + * was registered by `addHandler`. Otherwise, the `error` property + * will contain an object describing the error. + * + * data: + * An object describing the message, as defined in + * `MessageChannel.addListener`. + * @param {nsIMessageListenerManager} messageManager + */ + constructor(messageName, callback, messageManager) { + this.messageName = messageName; + this.callback = callback; + this.messageManager = messageManager; + + this.messageManager.addMessageListener(this.messageName, this, true); + + this.handlers = new Map(); + } + + /** + * Receives a message from our message manager, maps it to a handler, and + * passes the result to our message callback. + */ + receiveMessage({data, target}) { + let handlers = Array.from(this.getHandlers(data.messageName, data.sender, data.recipient)); + + data.target = target; + this.callback(handlers, data); + } + + /** + * Iterates over all handlers for the given message name. If `recipient` + * is provided, only iterates over handlers whose filters match it. + * + * @param {string|number} messageName + * The message for which to return handlers. + * @param {object} sender + * The sender data on which to filter handlers. + * @param {object} recipient + * The recipient data on which to filter handlers. + */ + * getHandlers(messageName, sender, recipient) { + let handlers = this.handlers.get(messageName) || new Set(); + for (let handler of handlers) { + if (MessageChannel.matchesFilter(handler.messageFilterStrict || {}, recipient) && + MessageChannel.matchesFilter(handler.messageFilterPermissive || {}, recipient, false) && + (!handler.filterMessage || handler.filterMessage(sender, recipient))) { + yield handler; + } + } + } + + /** + * Registers a handler for the given message. + * + * @param {string} messageName + * The internal message name for which to register the handler. + * @param {object} handler + * An opaque handler object. The object may have a + * `messageFilterStrict` and/or a `messageFilterPermissive` + * property and/or a `filterMessage` method on which to filter messages. + * + * Final dispatching is handled by the message callback passed to + * the constructor. + */ + addHandler(messageName, handler) { + if (!this.handlers.has(messageName)) { + this.handlers.set(messageName, new Set()); + } + + this.handlers.get(messageName).add(handler); + } + + /** + * Unregisters a handler for the given message. + * + * @param {string} messageName + * The internal message name for which to unregister the handler. + * @param {object} handler + * The handler object to unregister. + */ + removeHandler(messageName, handler) { + this.handlers.get(messageName).delete(handler); + } +} + +/** + * Manages mappings of message managers to their corresponding message + * brokers. Brokers are lazily created for each message manager the + * first time they are accessed. In the case of content frame message + * managers, they are also automatically destroyed when the frame + * unload event fires. + */ +class FilteringMessageManagerMap extends Map { + // Unfortunately, we can't use a WeakMap for this, because message + // managers do not support preserved wrappers. + + /** + * @param {string} messageName + * The native message name passed to `FilteringMessageManager` constructors. + * @param {function} callback + * The message callback function passed to + * `FilteringMessageManager` constructors. + */ + constructor(messageName, callback) { + super(); + + this.messageName = messageName; + this.callback = callback; + } + + /** + * Returns, and possibly creates, a message broker for the given + * message manager. + * + * @param {nsIMessageListenerManager} target + * The message manager for which to return a broker. + * + * @returns {FilteringMessageManager} + */ + get(target) { + if (this.has(target)) { + return super.get(target); + } + + let broker = new FilteringMessageManager(this.messageName, this.callback, target); + this.set(target, broker); + + if (target instanceof Ci.nsIDOMEventTarget) { + let onUnload = event => { + target.removeEventListener("unload", onUnload); + this.delete(target); + }; + target.addEventListener("unload", onUnload); + } + + return broker; + } +} + +const MESSAGE_MESSAGE = "MessageChannel:Message"; +const MESSAGE_RESPONSE = "MessageChannel:Response"; + +this.MessageChannel = { + init() { + Services.obs.addObserver(this, "message-manager-close", false); + Services.obs.addObserver(this, "message-manager-disconnect", false); + + this.messageManagers = new FilteringMessageManagerMap( + MESSAGE_MESSAGE, this._handleMessage.bind(this)); + + this.responseManagers = new FilteringMessageManagerMap( + MESSAGE_RESPONSE, this._handleResponse.bind(this)); + + /** + * Contains a list of pending responses, either waiting to be + * received or waiting to be sent. @see _addPendingResponse + */ + this.pendingResponses = new Set(); + }, + + RESULT_SUCCESS: 0, + RESULT_DISCONNECTED: 1, + RESULT_NO_HANDLER: 2, + RESULT_MULTIPLE_HANDLERS: 3, + RESULT_ERROR: 4, + RESULT_NO_RESPONSE: 5, + + REASON_DISCONNECTED: { + result: this.RESULT_DISCONNECTED, + message: "Message manager disconnected", + }, + + /** + * Specifies that only a single listener matching the specified + * recipient tag may be listening for the given message, at the other + * end of the target message manager. + * + * If no matching listeners exist, a RESULT_NO_HANDLER error will be + * returned. If multiple matching listeners exist, a + * RESULT_MULTIPLE_HANDLERS error will be returned. + */ + RESPONSE_SINGLE: 0, + + /** + * If multiple message managers matching the specified recipient tag + * are listening for a message, all listeners are notified, but only + * the first response or error is returned. + * + * Only handlers which return a value other than `undefined` are + * considered to have responded. Returning a Promise which evaluates + * to `undefined` is interpreted as an explicit response. + * + * If no matching listeners exist, a RESULT_NO_HANDLER error will be + * returned. If no listeners return a response, a RESULT_NO_RESPONSE + * error will be returned. + */ + RESPONSE_FIRST: 1, + + /** + * If multiple message managers matching the specified recipient tag + * are listening for a message, all listeners are notified, and all + * responses are returned as an array, once all listeners have + * replied. + */ + RESPONSE_ALL: 2, + + /** + * Fire-and-forget: The sender of this message does not expect a reply. + */ + RESPONSE_NONE: 3, + + /** + * Initializes message handlers for the given message managers if needed. + * + * @param {Array} messageManagers + */ + setupMessageManagers(messageManagers) { + for (let mm of messageManagers) { + // This call initializes a FilteringMessageManager for |mm| if needed. + // The FilteringMessageManager must be created to make sure that senders + // of messages that expect a reply, such as MessageChannel:Message, do + // actually receive a default reply even if there are no explicit message + // handlers. + this.messageManagers.get(mm); + } + }, + + /** + * Returns true if the properties of the `data` object match those in + * the `filter` object. Matching is done on a strict equality basis, + * and the behavior varies depending on the value of the `strict` + * parameter. + * + * @param {object} filter + * The filter object to match against. + * @param {object} data + * The data object being matched. + * @param {boolean} [strict=false] + * If true, all properties in the `filter` object have a + * corresponding property in `data` with the same value. If + * false, properties present in both objects must have the same + * value. + * @returns {boolean} True if the objects match. + */ + matchesFilter(filter, data, strict = true) { + if (strict) { + return Object.keys(filter).every(key => { + return key in data && data[key] === filter[key]; + }); + } + return Object.keys(filter).every(key => { + return !(key in data) || data[key] === filter[key]; + }); + }, + + /** + * Adds a message listener to the given message manager. + * + * @param {nsIMessageListenerManager|Array} targets + * The message managers on which to listen. + * @param {string|number} messageName + * The name of the message to listen for. + * @param {MessageReceiver} handler + * The handler to dispatch to. Must be an object with the following + * properties: + * + * receiveMessage: + * A method which is called for each message received by the + * listener. The method takes one argument, an object, with the + * following properties: + * + * messageName: + * The internal message name, as passed to `sendMessage`. + * + * target: + * The message manager which received this message. + * + * channelId: + * The internal ID of the transaction, used to map responses to + * the original sender. + * + * sender: + * An object describing the sender, as passed to `sendMessage`. + * + * recipient: + * An object describing the recipient, as passed to + * `sendMessage`. + * + * data: + * The contents of the message, as passed to `sendMessage`. + * + * The method may return any structured-clone-compatible + * object, which will be returned as a response to the message + * sender. It may also instead return a `Promise`, the + * resolution or rejection value of which will likewise be + * returned to the message sender. + * + * messageFilterStrict: + * An object containing arbitrary properties on which to filter + * received messages. Messages will only be dispatched to this + * object if the `recipient` object passed to `sendMessage` + * matches this filter, as determined by `matchesFilter` with + * `strict=true`. + * + * messageFilterPermissive: + * An object containing arbitrary properties on which to filter + * received messages. Messages will only be dispatched to this + * object if the `recipient` object passed to `sendMessage` + * matches this filter, as determined by `matchesFilter` with + * `strict=false`. + * + * filterMessage: + * An optional function that prevents the handler from handling a + * message by returning `false`. See `getHandlers` for the parameters. + */ + addListener(targets, messageName, handler) { + for (let target of [].concat(targets)) { + this.messageManagers.get(target).addHandler(messageName, handler); + } + }, + + /** + * Removes a message listener from the given message manager. + * + * @param {nsIMessageListenerManager|Array} targets + * The message managers on which to stop listening. + * @param {string|number} messageName + * The name of the message to stop listening for. + * @param {MessageReceiver} handler + * The handler to stop dispatching to. + */ + removeListener(targets, messageName, handler) { + for (let target of [].concat(targets)) { + if (this.messageManagers.has(target)) { + this.messageManagers.get(target).removeHandler(messageName, handler); + } + } + }, + + /** + * Sends a message via the given message manager. Returns a promise which + * resolves or rejects with the return value of the message receiver. + * + * The promise also rejects if there is no matching listener, or the other + * side of the message manager disconnects before the response is received. + * + * @param {nsIMessageSender} target + * The message manager on which to send the message. + * @param {string} messageName + * The name of the message to send, as passed to `addListener`. + * @param {object} data + * A structured-clone-compatible object to send to the message + * recipient. + * @param {object} [options] + * An object containing any of the following properties: + * @param {object} [options.recipient] + * A structured-clone-compatible object to identify the message + * recipient. The object must match the `messageFilterStrict` and + * `messageFilterPermissive` filters defined by recipients in order + * for the message to be received. + * @param {object} [options.sender] + * A structured-clone-compatible object to identify the message + * sender. This object may also be used to avoid delivering the + * message to the sender, and as a filter to prematurely + * abort responses when the sender is being destroyed. + * @see `abortResponses`. + * @param {integer} [options.responseType=RESPONSE_SINGLE] + * Specifies the type of response expected. See the `RESPONSE_*` + * contents for details. + * @returns {Promise} + */ + sendMessage(target, messageName, data, options = {}) { + let sender = options.sender || {}; + let recipient = options.recipient || {}; + let responseType = options.responseType || this.RESPONSE_SINGLE; + + let channelId = ExtensionUtils.getUniqueId(); + let message = {messageName, channelId, sender, recipient, data, responseType}; + + if (responseType == this.RESPONSE_NONE) { + try { + target.sendAsyncMessage(MESSAGE_MESSAGE, message); + } catch (e) { + // Caller is not expecting a reply, so dump the error to the console. + Cu.reportError(e); + return Promise.reject(e); + } + return Promise.resolve(); // Not expecting any reply. + } + + let deferred = PromiseUtils.defer(); + deferred.sender = recipient; + deferred.messageManager = target; + + this._addPendingResponse(deferred); + + // The channel ID is used as the message name when routing responses. + // Add a message listener to the response broker, and remove it once + // we've gotten (or canceled) a response. + let broker = this.responseManagers.get(target); + broker.addHandler(channelId, deferred); + + let cleanup = () => { + broker.removeHandler(channelId, deferred); + }; + deferred.promise.then(cleanup, cleanup); + + try { + target.sendAsyncMessage(MESSAGE_MESSAGE, message); + } catch (e) { + deferred.reject(e); + } + return deferred.promise; + }, + + _callHandlers(handlers, data) { + let responseType = data.responseType; + + // At least one handler is required for all response types but + // RESPONSE_ALL. + if (handlers.length == 0 && responseType != this.RESPONSE_ALL) { + return Promise.reject({result: MessageChannel.RESULT_NO_HANDLER, + message: "No matching message handler"}); + } + + if (responseType == this.RESPONSE_SINGLE) { + if (handlers.length > 1) { + return Promise.reject({result: MessageChannel.RESULT_MULTIPLE_HANDLERS, + message: `Multiple matching handlers for ${data.messageName}`}); + } + + // Note: We use `new Promise` rather than `Promise.resolve` here + // so that errors from the handler are trapped and converted into + // rejected promises. + return new Promise(resolve => { + resolve(handlers[0].receiveMessage(data)); + }); + } + + let responses = handlers.map(handler => { + try { + return handler.receiveMessage(data); + } catch (e) { + return Promise.reject(e); + } + }); + responses = responses.filter(response => response !== undefined); + + switch (responseType) { + case this.RESPONSE_FIRST: + if (responses.length == 0) { + return Promise.reject({result: MessageChannel.RESULT_NO_RESPONSE, + message: "No handler returned a response"}); + } + + return Promise.race(responses); + + case this.RESPONSE_ALL: + return Promise.all(responses); + } + return Promise.reject({message: "Invalid response type"}); + }, + + /** + * Handles dispatching message callbacks from the message brokers to their + * appropriate `MessageReceivers`, and routing the responses back to the + * original senders. + * + * Each handler object is a `MessageReceiver` object as passed to + * `addListener`. + * + * @param {Array} handlers + * @param {object} data + * @param {nsIMessageSender|{messageManager:nsIMessageSender}} data.target + */ + _handleMessage(handlers, data) { + if (data.responseType == this.RESPONSE_NONE) { + handlers.forEach(handler => { + // The sender expects no reply, so dump any errors to the console. + new Promise(resolve => { + resolve(handler.receiveMessage(data)); + }).catch(e => { + Cu.reportError(e.stack ? `${e}\n${e.stack}` : e.message || e); + }); + }); + // Note: Unhandled messages are silently dropped. + return; + } + + let target = new MessageManagerProxy(data.target); + + let deferred = { + sender: data.sender, + messageManager: target, + }; + deferred.promise = new Promise((resolve, reject) => { + deferred.reject = reject; + + this._callHandlers(handlers, data).then(resolve, reject); + }).then( + value => { + let response = { + result: this.RESULT_SUCCESS, + messageName: data.channelId, + recipient: {}, + value, + }; + + target.sendAsyncMessage(MESSAGE_RESPONSE, response); + }, + error => { + let response = { + result: this.RESULT_ERROR, + messageName: data.channelId, + recipient: {}, + error: {}, + }; + + if (error && typeof(error) == "object") { + if (error.result) { + response.result = error.result; + } + // Error objects are not structured-clonable, so just copy + // over the important properties. + for (let key of ["fileName", "filename", "lineNumber", + "columnNumber", "message", "stack", "result"]) { + if (key in error) { + response.error[key] = error[key]; + } + } + } + + target.sendAsyncMessage(MESSAGE_RESPONSE, response); + }).catch(e => { + Cu.reportError(e); + }).then(() => { + target.dispose(); + }); + + this._addPendingResponse(deferred); + }, + + /** + * Handles message callbacks from the response brokers. + * + * Each handler object is a deferred object created by `sendMessage`, and + * should be resolved or rejected based on the contents of the response. + * + * @param {Array} handlers + * @param {object} data + * @param {nsIMessageSender|{messageManager:nsIMessageSender}} data.target + */ + _handleResponse(handlers, data) { + // If we have an error at this point, we have handler to report it to, + // so just log it. + if (handlers.length == 0) { + Cu.reportError(`No matching message response handler for ${data.messageName}`); + } else if (handlers.length > 1) { + Cu.reportError(`Multiple matching response handlers for ${data.messageName}`); + } else if (data.result === this.RESULT_SUCCESS) { + handlers[0].resolve(data.value); + } else { + handlers[0].reject(data.error); + } + }, + + /** + * Adds a pending response to the the `pendingResponses` list. + * + * The response object must be a deferred promise with the following + * properties: + * + * promise: + * The promise object which resolves or rejects when the response + * is no longer pending. + * + * reject: + * A function which, when called, causes the `promise` object to be + * rejected. + * + * sender: + * A sender object, as passed to `sendMessage. + * + * messageManager: + * The message manager the response will be sent or received on. + * + * When the promise resolves or rejects, it will be removed from the + * list. + * + * These values are used to clear pending responses when execution + * contexts are destroyed. + * + * @param {Deferred} deferred + */ + _addPendingResponse(deferred) { + let cleanup = () => { + this.pendingResponses.delete(deferred); + }; + this.pendingResponses.add(deferred); + deferred.promise.then(cleanup, cleanup); + }, + + /** + * Aborts any pending message responses to senders matching the given + * filter. + * + * @param {object} sender + * The object on which to filter senders, as determined by + * `matchesFilter`. + * @param {object} [reason] + * An optional object describing the reason the response was aborted. + * Will be passed to the promise rejection handler of all aborted + * responses. + */ + abortResponses(sender, reason = this.REASON_DISCONNECTED) { + for (let response of this.pendingResponses) { + if (this.matchesFilter(sender, response.sender)) { + response.reject(reason); + } + } + }, + + /** + * Aborts any pending message responses to the broker for the given + * message manager. + * + * @param {nsIMessageListenerManager} target + * The message manager for which to abort brokers. + * @param {object} reason + * An object describing the reason the responses were aborted. + * Will be passed to the promise rejection handler of all aborted + * responses. + */ + abortMessageManager(target, reason) { + for (let response of this.pendingResponses) { + if (MessageManagerProxy.matches(response.messageManager, target)) { + response.reject(reason); + } + } + }, + + observe(subject, topic, data) { + switch (topic) { + case "message-manager-close": + case "message-manager-disconnect": + try { + if (this.responseManagers.has(subject)) { + this.abortMessageManager(subject, this.REASON_DISCONNECTED); + } + } finally { + this.responseManagers.delete(subject); + this.messageManagers.delete(subject); + } + break; + } + }, +}; + +MessageChannel.init(); diff --git a/toolkit/components/webextensions/NativeMessaging.jsm b/toolkit/components/webextensions/NativeMessaging.jsm new file mode 100644 index 000000000..3d8658a3f --- /dev/null +++ b/toolkit/components/webextensions/NativeMessaging.jsm @@ -0,0 +1,443 @@ +/* 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"; + +this.EXPORTED_SYMBOLS = ["HostManifestManager", "NativeApp"]; +/* globals NativeApp */ + +const {classes: Cc, interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +const {EventEmitter} = Cu.import("resource://devtools/shared/event-emitter.js", {}); + +XPCOMUtils.defineLazyModuleGetter(this, "AppConstants", + "resource://gre/modules/AppConstants.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "AsyncShutdown", + "resource://gre/modules/AsyncShutdown.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionChild", + "resource://gre/modules/ExtensionChild.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "OS", + "resource://gre/modules/osfile.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Schemas", + "resource://gre/modules/Schemas.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Services", + "resource://gre/modules/Services.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Subprocess", + "resource://gre/modules/Subprocess.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Task", + "resource://gre/modules/Task.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "clearTimeout", + "resource://gre/modules/Timer.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "setTimeout", + "resource://gre/modules/Timer.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "WindowsRegistry", + "resource://gre/modules/WindowsRegistry.jsm"); + +const HOST_MANIFEST_SCHEMA = "chrome://extensions/content/schemas/native_host_manifest.json"; +const VALID_APPLICATION = /^\w+(\.\w+)*$/; + +// For a graceful shutdown (i.e., when the extension is unloaded or when it +// explicitly calls disconnect() on a native port), how long we give the native +// application to exit before we start trying to kill it. (in milliseconds) +const GRACEFUL_SHUTDOWN_TIME = 3000; + +// Hard limits on maximum message size that can be read/written +// These are defined in the native messaging documentation, note that +// the write limit is imposed by the "wire protocol" in which message +// boundaries are defined by preceding each message with its length as +// 4-byte unsigned integer so this is the largest value that can be +// represented. Good luck generating a serialized message that large, +// the practical write limit is likely to be dictated by available memory. +const MAX_READ = 1024 * 1024; +const MAX_WRITE = 0xffffffff; + +// Preferences that can lower the message size limits above, +// used for testing the limits. +const PREF_MAX_READ = "webextensions.native-messaging.max-input-message-bytes"; +const PREF_MAX_WRITE = "webextensions.native-messaging.max-output-message-bytes"; + +const REGPATH = "Software\\Mozilla\\NativeMessagingHosts"; + +this.HostManifestManager = { + _initializePromise: null, + _lookup: null, + + init() { + if (!this._initializePromise) { + let platform = AppConstants.platform; + if (platform == "win") { + this._lookup = this._winLookup; + } else if (platform == "macosx" || platform == "linux") { + let dirs = [ + Services.dirsvc.get("XREUserNativeMessaging", Ci.nsIFile).path, + Services.dirsvc.get("XRESysNativeMessaging", Ci.nsIFile).path, + ]; + this._lookup = (application, context) => this._tryPaths(application, dirs, context); + } else { + throw new Error(`Native messaging is not supported on ${AppConstants.platform}`); + } + this._initializePromise = Schemas.load(HOST_MANIFEST_SCHEMA); + } + return this._initializePromise; + }, + + _winLookup(application, context) { + const REGISTRY = Ci.nsIWindowsRegKey; + let regPath = `${REGPATH}\\${application}`; + let path = WindowsRegistry.readRegKey(REGISTRY.ROOT_KEY_CURRENT_USER, + regPath, "", REGISTRY.WOW64_64); + if (!path) { + path = WindowsRegistry.readRegKey(Ci.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE, + regPath, "", REGISTRY.WOW64_64); + } + if (!path) { + return null; + } + return this._tryPath(path, application, context) + .then(manifest => manifest ? {path, manifest} : null); + }, + + _tryPath(path, application, context) { + return Promise.resolve() + .then(() => OS.File.read(path, {encoding: "utf-8"})) + .then(data => { + let manifest; + try { + manifest = JSON.parse(data); + } catch (ex) { + let msg = `Error parsing native host manifest ${path}: ${ex.message}`; + Cu.reportError(msg); + return null; + } + + let normalized = Schemas.normalize(manifest, "manifest.NativeHostManifest", context); + if (normalized.error) { + Cu.reportError(normalized.error); + return null; + } + manifest = normalized.value; + if (manifest.name != application) { + let msg = `Native host manifest ${path} has name property ${manifest.name} (expected ${application})`; + Cu.reportError(msg); + return null; + } + return normalized.value; + }).catch(ex => { + if (ex instanceof OS.File.Error && ex.becauseNoSuchFile) { + return null; + } + throw ex; + }); + }, + + _tryPaths: Task.async(function* (application, dirs, context) { + for (let dir of dirs) { + let path = OS.Path.join(dir, `${application}.json`); + let manifest = yield this._tryPath(path, application, context); + if (manifest) { + return {path, manifest}; + } + } + return null; + }), + + /** + * Search for a valid native host manifest for the given application name. + * The directories searched and rules for manifest validation are all + * detailed in the native messaging documentation. + * + * @param {string} application The name of the applciation to search for. + * @param {object} context A context object as expected by Schemas.normalize. + * @returns {object} The contents of the validated manifest, or null if + * no valid manifest can be found for this application. + */ + lookupApplication(application, context) { + if (!VALID_APPLICATION.test(application)) { + throw new Error(`Invalid application "${application}"`); + } + return this.init().then(() => this._lookup(application, context)); + }, +}; + +this.NativeApp = class extends EventEmitter { + /** + * @param {BaseContext} context The context that initiated the native app. + * @param {string} application The identifier of the native app. + */ + constructor(context, application) { + super(); + + this.context = context; + this.name = application; + + // We want a close() notification when the window is destroyed. + this.context.callOnClose(this); + + this.proc = null; + this.readPromise = null; + this.sendQueue = []; + this.writePromise = null; + this.sentDisconnect = false; + + this.startupPromise = HostManifestManager.lookupApplication(application, context) + .then(hostInfo => { + // Put the two errors together to not leak information about whether a native + // application is installed to addons that do not have the right permission. + if (!hostInfo || !hostInfo.manifest.allowed_extensions.includes(context.extension.id)) { + throw new context.cloneScope.Error(`This extension does not have permission to use native application ${application} (or the application is not installed)`); + } + + let command = hostInfo.manifest.path; + if (AppConstants.platform == "win") { + // OS.Path.join() ignores anything before the last absolute path + // it sees, so if command is already absolute, it remains unchanged + // here. If it is relative, we get the proper absolute path here. + command = OS.Path.join(OS.Path.dirname(hostInfo.path), command); + } + + let subprocessOpts = { + command: command, + arguments: [hostInfo.path], + workdir: OS.Path.dirname(command), + stderr: "pipe", + }; + return Subprocess.call(subprocessOpts); + }).then(proc => { + this.startupPromise = null; + this.proc = proc; + this._startRead(); + this._startWrite(); + this._startStderrRead(); + }).catch(err => { + this.startupPromise = null; + Cu.reportError(err instanceof Error ? err : err.message); + this._cleanup(err); + }); + } + + /** + * Open a connection to a native messaging host. + * + * @param {BaseContext} context The context associated with the port. + * @param {nsIMessageSender} messageManager The message manager used to send + * and receive messages from the port's creator. + * @param {string} portId A unique internal ID that identifies the port. + * @param {object} sender The object describing the creator of the connection + * request. + * @param {string} application The name of the native messaging host. + */ + static onConnectNative(context, messageManager, portId, sender, application) { + let app = new NativeApp(context, application); + let port = new ExtensionChild.Port(context, messageManager, [Services.mm], "", portId, sender, sender); + app.once("disconnect", (what, err) => port.disconnect(err)); + + /* eslint-disable mozilla/balanced-listeners */ + app.on("message", (what, msg) => port.postMessage(msg)); + /* eslint-enable mozilla/balanced-listeners */ + + port.registerOnMessage(msg => app.send(msg)); + port.registerOnDisconnect(msg => app.close()); + } + + /** + * @param {BaseContext} context The scope from where `message` originates. + * @param {*} message A message from the extension, meant for a native app. + * @returns {ArrayBuffer} An ArrayBuffer that can be sent to the native app. + */ + static encodeMessage(context, message) { + message = context.jsonStringify(message); + let buffer = new TextEncoder().encode(message).buffer; + if (buffer.byteLength > NativeApp.maxWrite) { + throw new context.cloneScope.Error("Write too big"); + } + return buffer; + } + + // A port is definitely "alive" if this.proc is non-null. But we have + // to provide a live port object immediately when connecting so we also + // need to consider a port alive if proc is null but the startupPromise + // is still pending. + get _isDisconnected() { + return (!this.proc && !this.startupPromise); + } + + _startRead() { + if (this.readPromise) { + throw new Error("Entered _startRead() while readPromise is non-null"); + } + this.readPromise = this.proc.stdout.readUint32() + .then(len => { + if (len > NativeApp.maxRead) { + throw new this.context.cloneScope.Error(`Native application tried to send a message of ${len} bytes, which exceeds the limit of ${NativeApp.maxRead} bytes.`); + } + return this.proc.stdout.readJSON(len); + }).then(msg => { + this.emit("message", msg); + this.readPromise = null; + this._startRead(); + }).catch(err => { + if (err.errorCode != Subprocess.ERROR_END_OF_FILE) { + Cu.reportError(err instanceof Error ? err : err.message); + } + this._cleanup(err); + }); + } + + _startWrite() { + if (this.sendQueue.length == 0) { + return; + } + + if (this.writePromise) { + throw new Error("Entered _startWrite() while writePromise is non-null"); + } + + let buffer = this.sendQueue.shift(); + let uintArray = Uint32Array.of(buffer.byteLength); + + this.writePromise = Promise.all([ + this.proc.stdin.write(uintArray.buffer), + this.proc.stdin.write(buffer), + ]).then(() => { + this.writePromise = null; + this._startWrite(); + }).catch(err => { + Cu.reportError(err.message); + this._cleanup(err); + }); + } + + _startStderrRead() { + let proc = this.proc; + let app = this.name; + Task.spawn(function* () { + let partial = ""; + while (true) { + let data = yield proc.stderr.readString(); + if (data.length == 0) { + // We have hit EOF, just stop reading + if (partial) { + Services.console.logStringMessage(`stderr output from native app ${app}: ${partial}`); + } + break; + } + + let lines = data.split(/\r?\n/); + lines[0] = partial + lines[0]; + partial = lines.pop(); + + for (let line of lines) { + Services.console.logStringMessage(`stderr output from native app ${app}: ${line}`); + } + } + }); + } + + send(msg) { + if (this._isDisconnected) { + throw new this.context.cloneScope.Error("Attempt to postMessage on disconnected port"); + } + if (Cu.getClassName(msg, true) != "ArrayBuffer") { + // This error cannot be triggered by extensions; it indicates an error in + // our implementation. + throw new Error("The message to the native messaging host is not an ArrayBuffer"); + } + + let buffer = msg; + + if (buffer.byteLength > NativeApp.maxWrite) { + throw new this.context.cloneScope.Error("Write too big"); + } + + this.sendQueue.push(buffer); + if (!this.startupPromise && !this.writePromise) { + this._startWrite(); + } + } + + // Shut down the native application and also signal to the extension + // that the connect has been disconnected. + _cleanup(err) { + this.context.forgetOnClose(this); + + let doCleanup = () => { + // Set a timer to kill the process gracefully after one timeout + // interval and kill it forcefully after two intervals. + let timer = setTimeout(() => { + this.proc.kill(GRACEFUL_SHUTDOWN_TIME); + }, GRACEFUL_SHUTDOWN_TIME); + + let promise = Promise.all([ + this.proc.stdin.close() + .catch(err => { + if (err.errorCode != Subprocess.ERROR_END_OF_FILE) { + throw err; + } + }), + this.proc.wait(), + ]).then(() => { + this.proc = null; + clearTimeout(timer); + }); + + AsyncShutdown.profileBeforeChange.addBlocker( + `Native Messaging: Wait for application ${this.name} to exit`, + promise); + + promise.then(() => { + AsyncShutdown.profileBeforeChange.removeBlocker(promise); + }); + + return promise; + }; + + if (this.proc) { + doCleanup(); + } else if (this.startupPromise) { + this.startupPromise.then(doCleanup); + } + + if (!this.sentDisconnect) { + this.sentDisconnect = true; + if (err && err.errorCode == Subprocess.ERROR_END_OF_FILE) { + err = null; + } + this.emit("disconnect", err); + } + } + + // Called from Context when the extension is shut down. + close() { + this._cleanup(); + } + + sendMessage(msg) { + let responsePromise = new Promise((resolve, reject) => { + this.once("message", (what, msg) => { resolve(msg); }); + this.once("disconnect", (what, err) => { reject(err); }); + }); + + let result = this.startupPromise.then(() => { + this.send(msg); + return responsePromise; + }); + + result.then(() => { + this._cleanup(); + }, () => { + // Prevent the response promise from being reported as an + // unchecked rejection if the startup promise fails. + responsePromise.catch(() => {}); + + this._cleanup(); + }); + + return result; + } +}; + +XPCOMUtils.defineLazyPreferenceGetter(NativeApp, "maxRead", PREF_MAX_READ, MAX_READ); +XPCOMUtils.defineLazyPreferenceGetter(NativeApp, "maxWrite", PREF_MAX_WRITE, MAX_WRITE); diff --git a/toolkit/components/webextensions/Schemas.jsm b/toolkit/components/webextensions/Schemas.jsm new file mode 100644 index 000000000..159211c79 --- /dev/null +++ b/toolkit/components/webextensions/Schemas.jsm @@ -0,0 +1,2143 @@ +/* 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 Ci = Components.interfaces; +const Cc = Components.classes; +const Cu = Components.utils; +const Cr = Components.results; + +const global = this; + +Cu.importGlobalProperties(["URL"]); + +Cu.import("resource://gre/modules/NetUtil.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +var { + DefaultMap, + instanceOf, +} = ExtensionUtils; + +class DeepMap extends DefaultMap { + constructor() { + super(() => new DeepMap()); + } + + getPath(...keys) { + return keys.reduce((map, prop) => map.get(prop), this); + } +} + +XPCOMUtils.defineLazyServiceGetter(this, "contentPolicyService", + "@mozilla.org/addons/content-policy;1", + "nsIAddonContentPolicy"); + +this.EXPORTED_SYMBOLS = ["Schemas"]; + +/* globals Schemas, URL */ + +function readJSON(url) { + return new Promise((resolve, reject) => { + NetUtil.asyncFetch({uri: url, loadUsingSystemPrincipal: true}, (inputStream, status) => { + if (!Components.isSuccessCode(status)) { + // Convert status code to a string + let e = Components.Exception("", status); + reject(new Error(`Error while loading '${url}' (${e.name})`)); + return; + } + try { + let text = NetUtil.readInputStreamToString(inputStream, inputStream.available()); + + // Chrome JSON files include a license comment that we need to + // strip off for this to be valid JSON. As a hack, we just + // look for the first '[' character, which signals the start + // of the JSON content. + let index = text.indexOf("["); + text = text.slice(index); + + resolve(JSON.parse(text)); + } catch (e) { + reject(e); + } + }); + }); +} + +/** + * Defines a lazy getter for the given property on the given object. Any + * security wrappers are waived on the object before the property is + * defined, and the getter and setter methods are wrapped for the target + * scope. + * + * The given getter function is guaranteed to be called only once, even + * if the target scope retrieves the wrapped getter from the property + * descriptor and calls it directly. + * + * @param {object} object + * The object on which to define the getter. + * @param {string|Symbol} prop + * The property name for which to define the getter. + * @param {function} getter + * The function to call in order to generate the final property + * value. + */ +function exportLazyGetter(object, prop, getter) { + object = Cu.waiveXrays(object); + + let redefine = value => { + if (value === undefined) { + delete object[prop]; + } else { + Object.defineProperty(object, prop, { + enumerable: true, + configurable: true, + writable: true, + value, + }); + } + + getter = null; + + return value; + }; + + Object.defineProperty(object, prop, { + enumerable: true, + configurable: true, + + get: Cu.exportFunction(function() { + return redefine(getter.call(this)); + }, object), + + set: Cu.exportFunction(value => { + redefine(value); + }, object), + }); +} + +const POSTPROCESSORS = { + convertImageDataToURL(imageData, context) { + let document = context.cloneScope.document; + let canvas = document.createElementNS("http://www.w3.org/1999/xhtml", "canvas"); + canvas.width = imageData.width; + canvas.height = imageData.height; + canvas.getContext("2d").putImageData(imageData, 0, 0); + + return canvas.toDataURL("image/png"); + }, +}; + +// Parses a regular expression, with support for the Python extended +// syntax that allows setting flags by including the string (?im) +function parsePattern(pattern) { + let flags = ""; + let match = /^\(\?([im]*)\)(.*)/.exec(pattern); + if (match) { + [, flags, pattern] = match; + } + return new RegExp(pattern, flags); +} + +function getValueBaseType(value) { + let t = typeof(value); + if (t == "object") { + if (value === null) { + return "null"; + } else if (Array.isArray(value)) { + return "array"; + } else if (Object.prototype.toString.call(value) == "[object ArrayBuffer]") { + return "binary"; + } + } else if (t == "number") { + if (value % 1 == 0) { + return "integer"; + } + } + return t; +} + +// Methods of Context that are used by Schemas.normalize. These methods can be +// overridden at the construction of Context. +const CONTEXT_FOR_VALIDATION = [ + "checkLoadURL", + "hasPermission", + "logError", +]; + +// Methods of Context that are used by Schemas.inject. +// Callers of Schemas.inject should implement all of these methods. +const CONTEXT_FOR_INJECTION = [ + ...CONTEXT_FOR_VALIDATION, + "shouldInject", + "getImplementation", +]; + +/** + * A context for schema validation and error reporting. This class is only used + * internally within Schemas. + */ +class Context { + /** + * @param {object} params Provides the implementation of this class. + * @param {Array} overridableMethods + */ + constructor(params, overridableMethods = CONTEXT_FOR_VALIDATION) { + this.params = params; + + this.path = []; + this.preprocessors = { + localize(value, context) { + return value; + }, + }; + this.postprocessors = POSTPROCESSORS; + this.isChromeCompat = false; + + this.currentChoices = new Set(); + this.choicePathIndex = 0; + + for (let method of overridableMethods) { + if (method in params) { + this[method] = params[method].bind(params); + } + } + + let props = ["preprocessors", "isChromeCompat"]; + for (let prop of props) { + if (prop in params) { + if (prop in this && typeof this[prop] == "object") { + Object.assign(this[prop], params[prop]); + } else { + this[prop] = params[prop]; + } + } + } + } + + get choicePath() { + let path = this.path.slice(this.choicePathIndex); + return path.join("."); + } + + get cloneScope() { + return this.params.cloneScope; + } + + get url() { + return this.params.url; + } + + get principal() { + return this.params.principal || Services.scriptSecurityManager.createNullPrincipal({}); + } + + /** + * Checks whether `url` may be loaded by the extension in this context. + * + * @param {string} url The URL that the extension wished to load. + * @returns {boolean} Whether the context may load `url`. + */ + checkLoadURL(url) { + let ssm = Services.scriptSecurityManager; + try { + ssm.checkLoadURIStrWithPrincipal(this.principal, url, + ssm.DISALLOW_INHERIT_PRINCIPAL); + } catch (e) { + return false; + } + return true; + } + + /** + * Checks whether this context has the given permission. + * + * @param {string} permission + * The name of the permission to check. + * + * @returns {boolean} True if the context has the given permission. + */ + hasPermission(permission) { + return false; + } + + /** + * Returns an error result object with the given message, for return + * by Type normalization functions. + * + * If the context has a `currentTarget` value, this is prepended to + * the message to indicate the location of the error. + * + * @param {string} errorMessage + * The error message which will be displayed when this is the + * only possible matching schema. + * @param {string} choicesMessage + * The message describing the valid what constitutes a valid + * value for this schema, which will be displayed when multiple + * schema choices are available and none match. + * + * A caller may pass `null` to prevent a choice from being + * added, but this should *only* be done from code processing a + * choices type. + * @returns {object} + */ + error(errorMessage, choicesMessage = undefined) { + if (choicesMessage !== null) { + let {choicePath} = this; + if (choicePath) { + choicesMessage = `.${choicePath} must ${choicesMessage}`; + } + + this.currentChoices.add(choicesMessage); + } + + if (this.currentTarget) { + return {error: `Error processing ${this.currentTarget}: ${errorMessage}`}; + } + return {error: errorMessage}; + } + + /** + * Creates an `Error` object belonging to the current unprivileged + * scope. If there is no unprivileged scope associated with this + * context, the message is returned as a string. + * + * If the context has a `currentTarget` value, this is prepended to + * the message, in the same way as for the `error` method. + * + * @param {string} message + * @returns {Error} + */ + makeError(message) { + let {error} = this.error(message); + if (this.cloneScope) { + return new this.cloneScope.Error(error); + } + return error; + } + + /** + * Logs the given error to the console. May be overridden to enable + * custom logging. + * + * @param {Error|string} error + */ + logError(error) { + Cu.reportError(error); + } + + /** + * Returns the name of the value currently being normalized. For a + * nested object, this is usually approximately equivalent to the + * JavaScript property accessor for that property. Given: + * + * { foo: { bar: [{ baz: x }] } } + * + * When processing the value for `x`, the currentTarget is + * 'foo.bar.0.baz' + */ + get currentTarget() { + return this.path.join("."); + } + + /** + * Executes the given callback, and returns an array of choice strings + * passed to {@see #error} during its execution. + * + * @param {function} callback + * @returns {object} + * An object with a `result` property containing the return + * value of the callback, and a `choice` property containing + * an array of choices. + */ + withChoices(callback) { + let {currentChoices, choicePathIndex} = this; + + let choices = new Set(); + this.currentChoices = choices; + this.choicePathIndex = this.path.length; + + try { + let result = callback(); + + return {result, choices: Array.from(choices)}; + } finally { + this.currentChoices = currentChoices; + this.choicePathIndex = choicePathIndex; + + choices = Array.from(choices); + if (choices.length == 1) { + currentChoices.add(choices[0]); + } else if (choices.length) { + let n = choices.length - 1; + choices[n] = `or ${choices[n]}`; + + this.error(null, `must either [${choices.join(", ")}]`); + } + } + } + + /** + * Appends the given component to the `currentTarget` path to indicate + * that it is being processed, calls the given callback function, and + * then restores the original path. + * + * This is used to identify the path of the property being processed + * when reporting type errors. + * + * @param {string} component + * @param {function} callback + * @returns {*} + */ + withPath(component, callback) { + this.path.push(component); + try { + return callback(); + } finally { + this.path.pop(); + } + } +} + +/** + * Holds methods that run the actual implementation of the extension APIs. These + * methods are only called if the extension API invocation matches the signature + * as defined in the schema. Otherwise an error is reported to the context. + */ +class InjectionContext extends Context { + constructor(params) { + super(params, CONTEXT_FOR_INJECTION); + } + + /** + * Check whether the API should be injected. + * + * @abstract + * @param {string} namespace The namespace of the API. This may contain dots, + * e.g. in the case of "devtools.inspectedWindow". + * @param {string} [name] The name of the property in the namespace. + * `null` if we are checking whether the namespace should be injected. + * @param {Array} allowedContexts A list of additional contexts in which + * this API should be available. May include any of: + * "main" - The main chrome browser process. + * "addon" - An addon process. + * "content" - A content process. + * @returns {boolean} Whether the API should be injected. + */ + shouldInject(namespace, name, allowedContexts) { + throw new Error("Not implemented"); + } + + /** + * Generate the implementation for `namespace`.`name`. + * + * @abstract + * @param {string} namespace The full path to the namespace of the API, minus + * the name of the method or property. E.g. "storage.local". + * @param {string} name The name of the method, property or event. + * @returns {SchemaAPIInterface} The implementation of the API. + */ + getImplementation(namespace, name) { + throw new Error("Not implemented"); + } +} + +/** + * The methods in this singleton represent the "format" specifier for + * JSON Schema string types. + * + * Each method either returns a normalized version of the original + * value, or throws an error if the value is not valid for the given + * format. + */ +const FORMATS = { + url(string, context) { + let url = new URL(string).href; + + if (!context.checkLoadURL(url)) { + throw new Error(`Access denied for URL ${url}`); + } + return url; + }, + + relativeUrl(string, context) { + if (!context.url) { + // If there's no context URL, return relative URLs unresolved, and + // skip security checks for them. + try { + new URL(string); + } catch (e) { + return string; + } + } + + let url = new URL(string, context.url).href; + + if (!context.checkLoadURL(url)) { + throw new Error(`Access denied for URL ${url}`); + } + return url; + }, + + strictRelativeUrl(string, context) { + // Do not accept a string which resolves as an absolute URL, or any + // protocol-relative URL. + if (!string.startsWith("//")) { + try { + new URL(string); + } catch (e) { + return FORMATS.relativeUrl(string, context); + } + } + + throw new SyntaxError(`String ${JSON.stringify(string)} must be a relative URL`); + }, + + contentSecurityPolicy(string, context) { + let error = contentPolicyService.validateAddonCSP(string); + if (error != null) { + throw new SyntaxError(error); + } + return string; + }, + + date(string, context) { + // A valid ISO 8601 timestamp. + const PATTERN = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d{3})?(Z|([-+]\d{2}:?\d{2})))?$/; + if (!PATTERN.test(string)) { + throw new Error(`Invalid date string ${string}`); + } + // Our pattern just checks the format, we could still have invalid + // values (e.g., month=99 or month=02 and day=31). Let the Date + // constructor do the dirty work of validating. + if (isNaN(new Date(string))) { + throw new Error(`Invalid date string ${string}`); + } + return string; + }, +}; + +// Schema files contain namespaces, and each namespace contains types, +// properties, functions, and events. An Entry is a base class for +// types, properties, functions, and events. +class Entry { + constructor(schema = {}) { + /** + * If set to any value which evaluates as true, this entry is + * deprecated, and any access to it will result in a deprecation + * warning being logged to the browser console. + * + * If the value is a string, it will be appended to the deprecation + * message. If it contains the substring "${value}", it will be + * replaced with a string representation of the value being + * processed. + * + * If the value is any other truthy value, a generic deprecation + * message will be emitted. + */ + this.deprecated = false; + if ("deprecated" in schema) { + this.deprecated = schema.deprecated; + } + + /** + * @property {string} [preprocessor] + * If set to a string value, and a preprocessor of the same is + * defined in the validation context, it will be applied to this + * value prior to any normalization. + */ + this.preprocessor = schema.preprocess || null; + + /** + * @property {string} [postprocessor] + * If set to a string value, and a postprocessor of the same is + * defined in the validation context, it will be applied to this + * value after any normalization. + */ + this.postprocessor = schema.postprocess || null; + + /** + * @property {Array} allowedContexts A list of allowed contexts + * to consider before generating the API. + * These are not parsed by the schema, but passed to `shouldInject`. + */ + this.allowedContexts = schema.allowedContexts || []; + } + + /** + * Preprocess the given value with the preprocessor declared in + * `preprocessor`. + * + * @param {*} value + * @param {Context} context + * @returns {*} + */ + preprocess(value, context) { + if (this.preprocessor) { + return context.preprocessors[this.preprocessor](value, context); + } + return value; + } + + /** + * Postprocess the given result with the postprocessor declared in + * `postprocessor`. + * + * @param {object} result + * @param {Context} context + * @returns {object} + */ + postprocess(result, context) { + if (result.error || !this.postprocessor) { + return result; + } + + let value = context.postprocessors[this.postprocessor](result.value, context); + return {value}; + } + + /** + * Logs a deprecation warning for this entry, based on the value of + * its `deprecated` property. + * + * @param {Context} context + * @param {value} [value] + */ + logDeprecation(context, value = null) { + let message = "This property is deprecated"; + if (typeof(this.deprecated) == "string") { + message = this.deprecated; + if (message.includes("${value}")) { + try { + value = JSON.stringify(value); + } catch (e) { + value = String(value); + } + message = message.replace(/\$\{value\}/g, () => value); + } + } + + context.logError(context.makeError(message)); + } + + /** + * Checks whether the entry is deprecated and, if so, logs a + * deprecation message. + * + * @param {Context} context + * @param {value} [value] + */ + checkDeprecated(context, value = null) { + if (this.deprecated) { + this.logDeprecation(context, value); + } + } + + /** + * Injects JS values for the entry into the extension API + * namespace. The default implementation is to do nothing. + * `context` is used to call the actual implementation + * of a given function or event. + * + * @param {Array} path The API path, e.g. `["storage", "local"]`. + * @param {string} name The method name, e.g. "get". + * @param {object} dest The object where `path`.`name` should be stored. + * @param {InjectionContext} context + */ + inject(path, name, dest, context) { + } +} + +// Corresponds either to a type declared in the "types" section of the +// schema or else to any type object used throughout the schema. +class Type extends Entry { + /** + * @property {Array} EXTRA_PROPERTIES + * An array of extra properties which may be present for + * schemas of this type. + */ + static get EXTRA_PROPERTIES() { + return ["description", "deprecated", "preprocess", "postprocess", "allowedContexts"]; + } + + /** + * Parses the given schema object and returns an instance of this + * class which corresponds to its properties. + * + * @param {object} schema + * A JSON schema object which corresponds to a definition of + * this type. + * @param {Array} path + * The path to this schema object from the root schema, + * corresponding to the property names and array indices + * traversed during parsing in order to arrive at this schema + * object. + * @param {Array} [extraProperties] + * An array of extra property names which are valid for this + * schema in the current context. + * @returns {Type} + * An instance of this type which corresponds to the given + * schema object. + * @static + */ + static parseSchema(schema, path, extraProperties = []) { + this.checkSchemaProperties(schema, path, extraProperties); + + return new this(schema); + } + + /** + * Checks that all of the properties present in the given schema + * object are valid properties for this type, and throws if invalid. + * + * @param {object} schema + * A JSON schema object. + * @param {Array} path + * The path to this schema object from the root schema, + * corresponding to the property names and array indices + * traversed during parsing in order to arrive at this schema + * object. + * @param {Array} [extra] + * An array of extra property names which are valid for this + * schema in the current context. + * @throws {Error} + * An error describing the first invalid property found in the + * schema object. + */ + static checkSchemaProperties(schema, path, extra = []) { + let allowedSet = new Set([...this.EXTRA_PROPERTIES, ...extra]); + + for (let prop of Object.keys(schema)) { + if (!allowedSet.has(prop)) { + throw new Error(`Internal error: Namespace ${path.join(".")} has invalid type property "${prop}" in type "${schema.id || JSON.stringify(schema)}"`); + } + } + } + + // Takes a value, checks that it has the correct type, and returns a + // "normalized" version of the value. The normalized version will + // include "nulls" in place of omitted optional properties. The + // result of this function is either {error: "Some type error"} or + // {value: }. + normalize(value, context) { + return context.error("invalid type"); + } + + // Unlike normalize, this function does a shallow check to see if + // |baseType| (one of the possible getValueBaseType results) is + // valid for this type. It returns true or false. It's used to fill + // in optional arguments to functions before actually type checking + + checkBaseType(baseType) { + return false; + } + + // Helper method that simply relies on checkBaseType to implement + // normalize. Subclasses can choose to use it or not. + normalizeBase(type, value, context) { + if (this.checkBaseType(getValueBaseType(value))) { + this.checkDeprecated(context, value); + return {value: this.preprocess(value, context)}; + } + + let choice; + if (/^[aeiou]/.test(type)) { + choice = `be an ${type} value`; + } else { + choice = `be a ${type} value`; + } + + return context.error(`Expected ${type} instead of ${JSON.stringify(value)}`, + choice); + } +} + +// Type that allows any value. +class AnyType extends Type { + normalize(value, context) { + this.checkDeprecated(context, value); + return this.postprocess({value}, context); + } + + checkBaseType(baseType) { + return true; + } +} + +// An untagged union type. +class ChoiceType extends Type { + static get EXTRA_PROPERTIES() { + return ["choices", ...super.EXTRA_PROPERTIES]; + } + + static parseSchema(schema, path, extraProperties = []) { + this.checkSchemaProperties(schema, path, extraProperties); + + let choices = schema.choices.map(t => Schemas.parseSchema(t, path)); + return new this(schema, choices); + } + + constructor(schema, choices) { + super(schema); + this.choices = choices; + } + + extend(type) { + this.choices.push(...type.choices); + + return this; + } + + normalize(value, context) { + this.checkDeprecated(context, value); + + let error; + let {choices, result} = context.withChoices(() => { + for (let choice of this.choices) { + let r = choice.normalize(value, context); + if (!r.error) { + return r; + } + + error = r; + } + }); + + if (result) { + return result; + } + if (choices.length <= 1) { + return error; + } + + let n = choices.length - 1; + choices[n] = `or ${choices[n]}`; + + let message = `Value must either: ${choices.join(", ")}`; + + return context.error(message, null); + } + + checkBaseType(baseType) { + return this.choices.some(t => t.checkBaseType(baseType)); + } +} + +// This is a reference to another type--essentially a typedef. +class RefType extends Type { + static get EXTRA_PROPERTIES() { + return ["$ref", ...super.EXTRA_PROPERTIES]; + } + + static parseSchema(schema, path, extraProperties = []) { + this.checkSchemaProperties(schema, path, extraProperties); + + let ref = schema.$ref; + let ns = path[0]; + if (ref.includes(".")) { + [ns, ref] = ref.split("."); + } + return new this(schema, ns, ref); + } + + // For a reference to a type named T declared in namespace NS, + // namespaceName will be NS and reference will be T. + constructor(schema, namespaceName, reference) { + super(schema); + this.namespaceName = namespaceName; + this.reference = reference; + } + + get targetType() { + let ns = Schemas.namespaces.get(this.namespaceName); + let type = ns.get(this.reference); + if (!type) { + throw new Error(`Internal error: Type ${this.reference} not found`); + } + return type; + } + + normalize(value, context) { + this.checkDeprecated(context, value); + return this.targetType.normalize(value, context); + } + + checkBaseType(baseType) { + return this.targetType.checkBaseType(baseType); + } +} + +class StringType extends Type { + static get EXTRA_PROPERTIES() { + return ["enum", "minLength", "maxLength", "pattern", "format", + ...super.EXTRA_PROPERTIES]; + } + + static parseSchema(schema, path, extraProperties = []) { + this.checkSchemaProperties(schema, path, extraProperties); + + let enumeration = schema.enum || null; + if (enumeration) { + // The "enum" property is either a list of strings that are + // valid values or else a list of {name, description} objects, + // where the .name values are the valid values. + enumeration = enumeration.map(e => { + if (typeof(e) == "object") { + return e.name; + } + return e; + }); + } + + let pattern = null; + if (schema.pattern) { + try { + pattern = parsePattern(schema.pattern); + } catch (e) { + throw new Error(`Internal error: Invalid pattern ${JSON.stringify(schema.pattern)}`); + } + } + + let format = null; + if (schema.format) { + if (!(schema.format in FORMATS)) { + throw new Error(`Internal error: Invalid string format ${schema.format}`); + } + format = FORMATS[schema.format]; + } + return new this(schema, enumeration, + schema.minLength || 0, + schema.maxLength || Infinity, + pattern, + format); + } + + constructor(schema, enumeration, minLength, maxLength, pattern, format) { + super(schema); + this.enumeration = enumeration; + this.minLength = minLength; + this.maxLength = maxLength; + this.pattern = pattern; + this.format = format; + } + + normalize(value, context) { + let r = this.normalizeBase("string", value, context); + if (r.error) { + return r; + } + value = r.value; + + if (this.enumeration) { + if (this.enumeration.includes(value)) { + return this.postprocess({value}, context); + } + + let choices = this.enumeration.map(JSON.stringify).join(", "); + + return context.error(`Invalid enumeration value ${JSON.stringify(value)}`, + `be one of [${choices}]`); + } + + if (value.length < this.minLength) { + return context.error(`String ${JSON.stringify(value)} is too short (must be ${this.minLength})`, + `be longer than ${this.minLength}`); + } + if (value.length > this.maxLength) { + return context.error(`String ${JSON.stringify(value)} is too long (must be ${this.maxLength})`, + `be shorter than ${this.maxLength}`); + } + + if (this.pattern && !this.pattern.test(value)) { + return context.error(`String ${JSON.stringify(value)} must match ${this.pattern}`, + `match the pattern ${this.pattern.toSource()}`); + } + + if (this.format) { + try { + r.value = this.format(r.value, context); + } catch (e) { + return context.error(String(e), `match the format "${this.format.name}"`); + } + } + + return r; + } + + checkBaseType(baseType) { + return baseType == "string"; + } + + inject(path, name, dest, context) { + if (this.enumeration) { + exportLazyGetter(dest, name, () => { + let obj = Cu.createObjectIn(dest); + for (let e of this.enumeration) { + obj[e.toUpperCase()] = e; + } + return obj; + }); + } + } +} + +let SubModuleType; +class ObjectType extends Type { + static get EXTRA_PROPERTIES() { + return ["properties", "patternProperties", ...super.EXTRA_PROPERTIES]; + } + + static parseSchema(schema, path, extraProperties = []) { + if ("functions" in schema) { + return SubModuleType.parseSchema(schema, path, extraProperties); + } + + if (!("$extend" in schema)) { + // Only allow extending "properties" and "patternProperties". + extraProperties = ["additionalProperties", "isInstanceOf", ...extraProperties]; + } + this.checkSchemaProperties(schema, path, extraProperties); + + let parseProperty = (schema, extraProps = []) => { + return { + type: Schemas.parseSchema(schema, path, + ["unsupported", "onError", "permissions", ...extraProps]), + optional: schema.optional || false, + unsupported: schema.unsupported || false, + onError: schema.onError || null, + }; + }; + + // Parse explicit "properties" object. + let properties = Object.create(null); + for (let propName of Object.keys(schema.properties || {})) { + properties[propName] = parseProperty(schema.properties[propName], ["optional"]); + } + + // Parse regexp properties from "patternProperties" object. + let patternProperties = []; + for (let propName of Object.keys(schema.patternProperties || {})) { + let pattern; + try { + pattern = parsePattern(propName); + } catch (e) { + throw new Error(`Internal error: Invalid property pattern ${JSON.stringify(propName)}`); + } + + patternProperties.push({ + pattern, + type: parseProperty(schema.patternProperties[propName]), + }); + } + + // Parse "additionalProperties" schema. + let additionalProperties = null; + if (schema.additionalProperties) { + let type = schema.additionalProperties; + if (type === true) { + type = {"type": "any"}; + } + + additionalProperties = Schemas.parseSchema(type, path); + } + + return new this(schema, properties, additionalProperties, patternProperties, schema.isInstanceOf || null); + } + + constructor(schema, properties, additionalProperties, patternProperties, isInstanceOf) { + super(schema); + this.properties = properties; + this.additionalProperties = additionalProperties; + this.patternProperties = patternProperties; + this.isInstanceOf = isInstanceOf; + } + + extend(type) { + for (let key of Object.keys(type.properties)) { + if (key in this.properties) { + throw new Error(`InternalError: Attempt to extend an object with conflicting property "${key}"`); + } + this.properties[key] = type.properties[key]; + } + + this.patternProperties.push(...type.patternProperties); + + return this; + } + + checkBaseType(baseType) { + return baseType == "object"; + } + + /** + * Extracts the enumerable properties of the given object, including + * function properties which would normally be omitted by X-ray + * wrappers. + * + * @param {object} value + * @param {Context} context + * The current parse context. + * @returns {object} + * An object with an `error` or `value` property. + */ + extractProperties(value, context) { + // |value| should be a JS Xray wrapping an object in the + // extension compartment. This works well except when we need to + // access callable properties on |value| since JS Xrays don't + // support those. To work around the problem, we verify that + // |value| is a plain JS object (i.e., not anything scary like a + // Proxy). Then we copy the properties out of it into a normal + // object using a waiver wrapper. + + let klass = Cu.getClassName(value, true); + if (klass != "Object") { + throw context.error(`Expected a plain JavaScript object, got a ${klass}`, + `be a plain JavaScript object`); + } + + let properties = Object.create(null); + + let waived = Cu.waiveXrays(value); + for (let prop of Object.getOwnPropertyNames(waived)) { + let desc = Object.getOwnPropertyDescriptor(waived, prop); + if (desc.get || desc.set) { + throw context.error("Objects cannot have getters or setters on properties", + "contain no getter or setter properties"); + } + // Chrome ignores non-enumerable properties. + if (desc.enumerable) { + properties[prop] = Cu.unwaiveXrays(desc.value); + } + } + + return properties; + } + + checkProperty(context, prop, propType, result, properties, remainingProps) { + let {type, optional, unsupported, onError} = propType; + let error = null; + + if (unsupported) { + if (prop in properties) { + error = context.error(`Property "${prop}" is unsupported by Firefox`, + `not contain an unsupported "${prop}" property`); + } + } else if (prop in properties) { + if (optional && (properties[prop] === null || properties[prop] === undefined)) { + result[prop] = null; + } else { + let r = context.withPath(prop, () => type.normalize(properties[prop], context)); + if (r.error) { + error = r; + } else { + result[prop] = r.value; + properties[prop] = r.value; + } + } + remainingProps.delete(prop); + } else if (!optional) { + error = context.error(`Property "${prop}" is required`, + `contain the required "${prop}" property`); + } else if (optional !== "omit-key-if-missing") { + result[prop] = null; + } + + if (error) { + if (onError == "warn") { + context.logError(error.error); + } else if (onError != "ignore") { + throw error; + } + + result[prop] = null; + } + } + + normalize(value, context) { + try { + let v = this.normalizeBase("object", value, context); + if (v.error) { + return v; + } + value = v.value; + + if (this.isInstanceOf) { + if (Object.keys(this.properties).length || + this.patternProperties.length || + !(this.additionalProperties instanceof AnyType)) { + throw new Error("InternalError: isInstanceOf can only be used with objects that are otherwise unrestricted"); + } + + if (!instanceOf(value, this.isInstanceOf)) { + return context.error(`Object must be an instance of ${this.isInstanceOf}`, + `be an instance of ${this.isInstanceOf}`); + } + + // This is kind of a hack, but we can't normalize things that + // aren't JSON, so we just return them. + return this.postprocess({value}, context); + } + + let properties = this.extractProperties(value, context); + let remainingProps = new Set(Object.keys(properties)); + + let result = {}; + for (let prop of Object.keys(this.properties)) { + this.checkProperty(context, prop, this.properties[prop], result, + properties, remainingProps); + } + + for (let prop of Object.keys(properties)) { + for (let {pattern, type} of this.patternProperties) { + if (pattern.test(prop)) { + this.checkProperty(context, prop, type, result, + properties, remainingProps); + } + } + } + + if (this.additionalProperties) { + for (let prop of remainingProps) { + let type = this.additionalProperties; + let r = context.withPath(prop, () => type.normalize(properties[prop], context)); + if (r.error) { + return r; + } + result[prop] = r.value; + } + } else if (remainingProps.size == 1) { + return context.error(`Unexpected property "${[...remainingProps]}"`, + `not contain an unexpected "${[...remainingProps]}" property`); + } else if (remainingProps.size) { + let props = [...remainingProps].sort().join(", "); + return context.error(`Unexpected properties: ${props}`, + `not contain the unexpected properties [${props}]`); + } + + return this.postprocess({value: result}, context); + } catch (e) { + if (e.error) { + return e; + } + throw e; + } + } +} + +// This type is just a placeholder to be referred to by +// SubModuleProperty. No value is ever expected to have this type. +SubModuleType = class SubModuleType extends Type { + static get EXTRA_PROPERTIES() { + return ["functions", "events", "properties", ...super.EXTRA_PROPERTIES]; + } + + static parseSchema(schema, path, extraProperties = []) { + this.checkSchemaProperties(schema, path, extraProperties); + + // The path we pass in here is only used for error messages. + path = [...path, schema.id]; + let functions = schema.functions.map(fun => Schemas.parseFunction(path, fun)); + + return new this(functions); + } + + constructor(functions) { + super(); + this.functions = functions; + } +}; + +class NumberType extends Type { + normalize(value, context) { + let r = this.normalizeBase("number", value, context); + if (r.error) { + return r; + } + + if (isNaN(r.value) || !Number.isFinite(r.value)) { + return context.error("NaN and infinity are not valid", + "be a finite number"); + } + + return r; + } + + checkBaseType(baseType) { + return baseType == "number" || baseType == "integer"; + } +} + +class IntegerType extends Type { + static get EXTRA_PROPERTIES() { + return ["minimum", "maximum", ...super.EXTRA_PROPERTIES]; + } + + static parseSchema(schema, path, extraProperties = []) { + this.checkSchemaProperties(schema, path, extraProperties); + + return new this(schema, schema.minimum || -Infinity, schema.maximum || Infinity); + } + + constructor(schema, minimum, maximum) { + super(schema); + this.minimum = minimum; + this.maximum = maximum; + } + + normalize(value, context) { + let r = this.normalizeBase("integer", value, context); + if (r.error) { + return r; + } + value = r.value; + + // Ensure it's between -2**31 and 2**31-1 + if (!Number.isSafeInteger(value)) { + return context.error("Integer is out of range", + "be a valid 32 bit signed integer"); + } + + if (value < this.minimum) { + return context.error(`Integer ${value} is too small (must be at least ${this.minimum})`, + `be at least ${this.minimum}`); + } + if (value > this.maximum) { + return context.error(`Integer ${value} is too big (must be at most ${this.maximum})`, + `be no greater than ${this.maximum}`); + } + + return this.postprocess(r, context); + } + + checkBaseType(baseType) { + return baseType == "integer"; + } +} + +class BooleanType extends Type { + normalize(value, context) { + return this.normalizeBase("boolean", value, context); + } + + checkBaseType(baseType) { + return baseType == "boolean"; + } +} + +class ArrayType extends Type { + static get EXTRA_PROPERTIES() { + return ["items", "minItems", "maxItems", ...super.EXTRA_PROPERTIES]; + } + + static parseSchema(schema, path, extraProperties = []) { + this.checkSchemaProperties(schema, path, extraProperties); + + let items = Schemas.parseSchema(schema.items, path); + + return new this(schema, items, schema.minItems || 0, schema.maxItems || Infinity); + } + + constructor(schema, itemType, minItems, maxItems) { + super(schema); + this.itemType = itemType; + this.minItems = minItems; + this.maxItems = maxItems; + } + + normalize(value, context) { + let v = this.normalizeBase("array", value, context); + if (v.error) { + return v; + } + value = v.value; + + let result = []; + for (let [i, element] of value.entries()) { + element = context.withPath(String(i), () => this.itemType.normalize(element, context)); + if (element.error) { + return element; + } + result.push(element.value); + } + + if (result.length < this.minItems) { + return context.error(`Array requires at least ${this.minItems} items; you have ${result.length}`, + `have at least ${this.minItems} items`); + } + + if (result.length > this.maxItems) { + return context.error(`Array requires at most ${this.maxItems} items; you have ${result.length}`, + `have at most ${this.maxItems} items`); + } + + return this.postprocess({value: result}, context); + } + + checkBaseType(baseType) { + return baseType == "array"; + } +} + +class FunctionType extends Type { + static get EXTRA_PROPERTIES() { + return ["parameters", "async", "returns", ...super.EXTRA_PROPERTIES]; + } + + static parseSchema(schema, path, extraProperties = []) { + this.checkSchemaProperties(schema, path, extraProperties); + + let isAsync = !!schema.async; + let isExpectingCallback = typeof schema.async === "string"; + let parameters = null; + if ("parameters" in schema) { + parameters = []; + for (let param of schema.parameters) { + // Callbacks default to optional for now, because of promise + // handling. + let isCallback = isAsync && param.name == schema.async; + if (isCallback) { + isExpectingCallback = false; + } + + parameters.push({ + type: Schemas.parseSchema(param, path, ["name", "optional", "default"]), + name: param.name, + optional: param.optional == null ? isCallback : param.optional, + default: param.default == undefined ? null : param.default, + }); + } + } + if (isExpectingCallback) { + throw new Error(`Internal error: Expected a callback parameter with name ${schema.async}`); + } + + let hasAsyncCallback = false; + if (isAsync) { + hasAsyncCallback = (parameters && + parameters.length && + parameters[parameters.length - 1].name == schema.async); + + if (schema.returns) { + throw new Error("Internal error: Async functions must not have return values."); + } + if (schema.allowAmbiguousOptionalArguments && !hasAsyncCallback) { + throw new Error("Internal error: Async functions with ambiguous arguments must declare the callback as the last parameter"); + } + } + + return new this(schema, parameters, isAsync, hasAsyncCallback); + } + + constructor(schema, parameters, isAsync, hasAsyncCallback) { + super(schema); + this.parameters = parameters; + this.isAsync = isAsync; + this.hasAsyncCallback = hasAsyncCallback; + } + + normalize(value, context) { + return this.normalizeBase("function", value, context); + } + + checkBaseType(baseType) { + return baseType == "function"; + } +} + +// Represents a "property" defined in a schema namespace with a +// particular value. Essentially this is a constant. +class ValueProperty extends Entry { + constructor(schema, name, value) { + super(schema); + this.name = name; + this.value = value; + } + + inject(path, name, dest, context) { + dest[name] = this.value; + } +} + +// Represents a "property" defined in a schema namespace that is not a +// constant. +class TypeProperty extends Entry { + constructor(schema, namespaceName, name, type, writable) { + super(schema); + this.namespaceName = namespaceName; + this.name = name; + this.type = type; + this.writable = writable; + } + + throwError(context, msg) { + throw context.makeError(`${msg} for ${this.namespaceName}.${this.name}.`); + } + + inject(path, name, dest, context) { + if (this.unsupported) { + return; + } + + let apiImpl = context.getImplementation(path.join("."), name); + + let getStub = () => { + this.checkDeprecated(context); + return apiImpl.getProperty(); + }; + + let desc = { + configurable: false, + enumerable: true, + + get: Cu.exportFunction(getStub, dest), + }; + + if (this.writable) { + let setStub = (value) => { + let normalized = this.type.normalize(value, context); + if (normalized.error) { + this.throwError(context, normalized.error); + } + + apiImpl.setProperty(normalized.value); + }; + + desc.set = Cu.exportFunction(setStub, dest); + } + + Object.defineProperty(dest, name, desc); + } +} + +class SubModuleProperty extends Entry { + // A SubModuleProperty represents a tree of objects and properties + // to expose to an extension. Currently we support only a limited + // form of sub-module properties, where "$ref" points to a + // SubModuleType containing a list of functions and "properties" is + // a list of additional simple properties. + // + // name: Name of the property stuff is being added to. + // namespaceName: Namespace in which the property lives. + // reference: Name of the type defining the functions to add to the property. + // properties: Additional properties to add to the module (unsupported). + constructor(schema, name, namespaceName, reference, properties) { + super(schema); + this.name = name; + this.namespaceName = namespaceName; + this.reference = reference; + this.properties = properties; + } + + inject(path, name, dest, context) { + exportLazyGetter(dest, name, () => { + let obj = Cu.createObjectIn(dest); + + let ns = Schemas.namespaces.get(this.namespaceName); + let type = ns.get(this.reference); + if (!type && this.reference.includes(".")) { + let [namespaceName, ref] = this.reference.split("."); + ns = Schemas.namespaces.get(namespaceName); + type = ns.get(ref); + } + if (!type || !(type instanceof SubModuleType)) { + throw new Error(`Internal error: ${this.namespaceName}.${this.reference} is not a sub-module`); + } + + let functions = type.functions; + for (let fun of functions) { + let subpath = path.concat(name); + let namespace = subpath.join("."); + let allowedContexts = fun.allowedContexts.length ? fun.allowedContexts : ns.defaultContexts; + if (context.shouldInject(namespace, fun.name, allowedContexts)) { + fun.inject(subpath, fun.name, obj, context); + } + } + + // TODO: Inject this.properties. + + return obj; + }); + } +} + +// This class is a base class for FunctionEntrys and Events. It takes +// care of validating parameter lists (i.e., handling of optional +// parameters and parameter type checking). +class CallEntry extends Entry { + constructor(schema, path, name, parameters, allowAmbiguousOptionalArguments) { + super(schema); + this.path = path; + this.name = name; + this.parameters = parameters; + this.allowAmbiguousOptionalArguments = allowAmbiguousOptionalArguments; + } + + throwError(context, msg) { + throw context.makeError(`${msg} for ${this.path.join(".")}.${this.name}.`); + } + + checkParameters(args, context) { + let fixedArgs = []; + + // First we create a new array, fixedArgs, that is the same as + // |args| but with default values in place of omitted optional parameters. + let check = (parameterIndex, argIndex) => { + if (parameterIndex == this.parameters.length) { + if (argIndex == args.length) { + return true; + } + return false; + } + + let parameter = this.parameters[parameterIndex]; + if (parameter.optional) { + // Try skipping it. + fixedArgs[parameterIndex] = parameter.default; + if (check(parameterIndex + 1, argIndex)) { + return true; + } + } + + if (argIndex == args.length) { + return false; + } + + let arg = args[argIndex]; + if (!parameter.type.checkBaseType(getValueBaseType(arg))) { + // For Chrome compatibility, use the default value if null or undefined + // is explicitly passed but is not a valid argument in this position. + if (parameter.optional && (arg === null || arg === undefined)) { + fixedArgs[parameterIndex] = Cu.cloneInto(parameter.default, global); + } else { + return false; + } + } else { + fixedArgs[parameterIndex] = arg; + } + + return check(parameterIndex + 1, argIndex + 1); + }; + + if (this.allowAmbiguousOptionalArguments) { + // When this option is set, it's up to the implementation to + // parse arguments. + // The last argument for asynchronous methods is either a function or null. + // This is specifically done for runtime.sendMessage. + if (this.hasAsyncCallback && typeof(args[args.length - 1]) != "function") { + args.push(null); + } + return args; + } + let success = check(0, 0); + if (!success) { + this.throwError(context, "Incorrect argument types"); + } + + // Now we normalize (and fully type check) all non-omitted arguments. + fixedArgs = fixedArgs.map((arg, parameterIndex) => { + if (arg === null) { + return null; + } + let parameter = this.parameters[parameterIndex]; + let r = parameter.type.normalize(arg, context); + if (r.error) { + this.throwError(context, `Type error for parameter ${parameter.name} (${r.error})`); + } + return r.value; + }); + + return fixedArgs; + } +} + +// Represents a "function" defined in a schema namespace. +class FunctionEntry extends CallEntry { + constructor(schema, path, name, type, unsupported, allowAmbiguousOptionalArguments, returns, permissions) { + super(schema, path, name, type.parameters, allowAmbiguousOptionalArguments); + this.unsupported = unsupported; + this.returns = returns; + this.permissions = permissions; + + this.isAsync = type.isAsync; + this.hasAsyncCallback = type.hasAsyncCallback; + } + + inject(path, name, dest, context) { + if (this.unsupported) { + return; + } + + if (this.permissions && !this.permissions.some(perm => context.hasPermission(perm))) { + return; + } + + exportLazyGetter(dest, name, () => { + let apiImpl = context.getImplementation(path.join("."), name); + + let stub; + if (this.isAsync) { + stub = (...args) => { + this.checkDeprecated(context); + let actuals = this.checkParameters(args, context); + let callback = null; + if (this.hasAsyncCallback) { + callback = actuals.pop(); + } + if (callback === null && context.isChromeCompat) { + // We pass an empty stub function as a default callback for + // the `chrome` API, so promise objects are not returned, + // and lastError values are reported immediately. + callback = () => {}; + } + return apiImpl.callAsyncFunction(actuals, callback); + }; + } else if (!this.returns) { + stub = (...args) => { + this.checkDeprecated(context); + let actuals = this.checkParameters(args, context); + return apiImpl.callFunctionNoReturn(actuals); + }; + } else { + stub = (...args) => { + this.checkDeprecated(context); + let actuals = this.checkParameters(args, context); + return apiImpl.callFunction(actuals); + }; + } + return Cu.exportFunction(stub, dest); + }); + } +} + +// Represents an "event" defined in a schema namespace. +class Event extends CallEntry { + constructor(schema, path, name, type, extraParameters, unsupported, permissions) { + super(schema, path, name, extraParameters); + this.type = type; + this.unsupported = unsupported; + this.permissions = permissions; + } + + checkListener(listener, context) { + let r = this.type.normalize(listener, context); + if (r.error) { + this.throwError(context, "Invalid listener"); + } + return r.value; + } + + inject(path, name, dest, context) { + if (this.unsupported) { + return; + } + + if (this.permissions && !this.permissions.some(perm => context.hasPermission(perm))) { + return; + } + + exportLazyGetter(dest, name, () => { + let apiImpl = context.getImplementation(path.join("."), name); + + let addStub = (listener, ...args) => { + listener = this.checkListener(listener, context); + let actuals = this.checkParameters(args, context); + apiImpl.addListener(listener, actuals); + }; + + let removeStub = (listener) => { + listener = this.checkListener(listener, context); + apiImpl.removeListener(listener); + }; + + let hasStub = (listener) => { + listener = this.checkListener(listener, context); + return apiImpl.hasListener(listener); + }; + + let obj = Cu.createObjectIn(dest); + + Cu.exportFunction(addStub, obj, {defineAs: "addListener"}); + Cu.exportFunction(removeStub, obj, {defineAs: "removeListener"}); + Cu.exportFunction(hasStub, obj, {defineAs: "hasListener"}); + + return obj; + }); + } +} + +const TYPES = Object.freeze(Object.assign(Object.create(null), { + any: AnyType, + array: ArrayType, + boolean: BooleanType, + function: FunctionType, + integer: IntegerType, + number: NumberType, + object: ObjectType, + string: StringType, +})); + +this.Schemas = { + initialized: false, + + // Maps a schema URL to the JSON contained in that schema file. This + // is useful for sending the JSON across processes. + schemaJSON: new Map(), + + // Map[ -> Map[ -> Entry]] + // This keeps track of all the schemas that have been loaded so far. + namespaces: new Map(), + + register(namespaceName, symbol, value) { + let ns = this.namespaces.get(namespaceName); + if (!ns) { + ns = new Map(); + ns.name = namespaceName; + ns.permissions = null; + ns.allowedContexts = []; + ns.defaultContexts = []; + this.namespaces.set(namespaceName, ns); + } + ns.set(symbol, value); + }, + + parseSchema(schema, path, extraProperties = []) { + let allowedProperties = new Set(extraProperties); + + if ("choices" in schema) { + return ChoiceType.parseSchema(schema, path, allowedProperties); + } else if ("$ref" in schema) { + return RefType.parseSchema(schema, path, allowedProperties); + } + + if (!("type" in schema)) { + throw new Error(`Unexpected value for type: ${JSON.stringify(schema)}`); + } + + allowedProperties.add("type"); + + let type = TYPES[schema.type]; + if (!type) { + throw new Error(`Unexpected type ${schema.type}`); + } + return type.parseSchema(schema, path, allowedProperties); + }, + + parseFunction(path, fun) { + let f = new FunctionEntry(fun, path, fun.name, + this.parseSchema(fun, path, + ["name", "unsupported", "returns", + "permissions", + "allowAmbiguousOptionalArguments"]), + fun.unsupported || false, + fun.allowAmbiguousOptionalArguments || false, + fun.returns || null, + fun.permissions || null); + return f; + }, + + loadType(namespaceName, type) { + if ("$extend" in type) { + this.extendType(namespaceName, type); + } else { + this.register(namespaceName, type.id, this.parseSchema(type, [namespaceName], ["id"])); + } + }, + + extendType(namespaceName, type) { + let ns = Schemas.namespaces.get(namespaceName); + let targetType = ns && ns.get(type.$extend); + + // Only allow extending object and choices types for now. + if (targetType instanceof ObjectType) { + type.type = "object"; + } else if (!targetType) { + throw new Error(`Internal error: Attempt to extend a nonexistant type ${type.$extend}`); + } else if (!(targetType instanceof ChoiceType)) { + throw new Error(`Internal error: Attempt to extend a non-extensible type ${type.$extend}`); + } + + let parsed = this.parseSchema(type, [namespaceName], ["$extend"]); + if (parsed.constructor !== targetType.constructor) { + throw new Error(`Internal error: Bad attempt to extend ${type.$extend}`); + } + + targetType.extend(parsed); + }, + + loadProperty(namespaceName, name, prop) { + if ("$ref" in prop) { + if (!prop.unsupported) { + this.register(namespaceName, name, new SubModuleProperty(prop, name, namespaceName, prop.$ref, + prop.properties || {})); + } + } else if ("value" in prop) { + this.register(namespaceName, name, new ValueProperty(prop, name, prop.value)); + } else { + // We ignore the "optional" attribute on properties since we + // don't inject anything here anyway. + let type = this.parseSchema(prop, [namespaceName], ["optional", "writable"]); + this.register(namespaceName, name, new TypeProperty(prop, namespaceName, name, type, prop.writable || false)); + } + }, + + loadFunction(namespaceName, fun) { + let f = this.parseFunction([namespaceName], fun); + this.register(namespaceName, fun.name, f); + }, + + loadEvent(namespaceName, event) { + let extras = event.extraParameters || []; + extras = extras.map(param => { + return { + type: this.parseSchema(param, [namespaceName], ["name", "optional", "default"]), + name: param.name, + optional: param.optional || false, + default: param.default == undefined ? null : param.default, + }; + }); + + // We ignore these properties for now. + /* eslint-disable no-unused-vars */ + let returns = event.returns; + let filters = event.filters; + /* eslint-enable no-unused-vars */ + + let type = this.parseSchema(event, [namespaceName], + ["name", "unsupported", "permissions", + "extraParameters", "returns", "filters"]); + + let e = new Event(event, [namespaceName], event.name, type, extras, + event.unsupported || false, + event.permissions || null); + this.register(namespaceName, event.name, e); + }, + + init() { + if (this.initialized) { + return; + } + this.initialized = true; + + if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) { + let data = Services.cpmm.initialProcessData; + let schemas = data["Extension:Schemas"]; + if (schemas) { + this.schemaJSON = schemas; + } + Services.cpmm.addMessageListener("Schema:Add", this); + } + + this.flushSchemas(); + }, + + receiveMessage(msg) { + switch (msg.name) { + case "Schema:Add": + this.schemaJSON.set(msg.data.url, msg.data.schema); + this.flushSchemas(); + break; + + case "Schema:Delete": + this.schemaJSON.delete(msg.data.url); + this.flushSchemas(); + break; + } + }, + + flushSchemas() { + XPCOMUtils.defineLazyGetter(this, "namespaces", + () => this.parseSchemas()); + }, + + parseSchemas() { + Object.defineProperty(this, "namespaces", { + enumerable: true, + configurable: true, + value: new Map(), + }); + + for (let json of this.schemaJSON.values()) { + try { + this.loadSchema(json); + } catch (e) { + Cu.reportError(e); + } + } + + return this.namespaces; + }, + + loadSchema(json) { + for (let namespace of json) { + let name = namespace.namespace; + + let types = namespace.types || []; + for (let type of types) { + this.loadType(name, type); + } + + let properties = namespace.properties || {}; + for (let propertyName of Object.keys(properties)) { + this.loadProperty(name, propertyName, properties[propertyName]); + } + + let functions = namespace.functions || []; + for (let fun of functions) { + this.loadFunction(name, fun); + } + + let events = namespace.events || []; + for (let event of events) { + this.loadEvent(name, event); + } + + let ns = this.namespaces.get(name); + ns.permissions = namespace.permissions || null; + ns.allowedContexts = namespace.allowedContexts || []; + ns.defaultContexts = namespace.defaultContexts || []; + } + }, + + load(url) { + if (Services.appinfo.processType != Services.appinfo.PROCESS_TYPE_CONTENT) { + return readJSON(url).then(json => { + this.schemaJSON.set(url, json); + + let data = Services.ppmm.initialProcessData; + data["Extension:Schemas"] = this.schemaJSON; + + Services.ppmm.broadcastAsyncMessage("Schema:Add", {url, schema: json}); + + this.flushSchemas(); + }); + } + }, + + unload(url) { + this.schemaJSON.delete(url); + + let data = Services.ppmm.initialProcessData; + data["Extension:Schemas"] = this.schemaJSON; + + Services.ppmm.broadcastAsyncMessage("Schema:Delete", {url}); + + this.flushSchemas(); + }, + + /** + * Checks whether a given object has the necessary permissions to + * expose the given namespace. + * + * @param {string} namespace + * The top-level namespace to check permissions for. + * @param {object} wrapperFuncs + * Wrapper functions for the given context. + * @param {function} wrapperFuncs.hasPermission + * A function which, when given a string argument, returns true + * if the context has the given permission. + * @returns {boolean} + * True if the context has permission for the given namespace. + */ + checkPermissions(namespace, wrapperFuncs) { + let ns = this.namespaces.get(namespace); + if (ns && ns.permissions) { + return ns.permissions.some(perm => wrapperFuncs.hasPermission(perm)); + } + return true; + }, + + exportLazyGetter, + + /** + * Inject registered extension APIs into `dest`. + * + * @param {object} dest The root namespace for the APIs. + * This object is usually exposed to extensions as "chrome" or "browser". + * @param {object} wrapperFuncs An implementation of the InjectionContext + * interface, which runs the actual functionality of the generated API. + */ + inject(dest, wrapperFuncs) { + let context = new InjectionContext(wrapperFuncs); + + let createNamespace = ns => { + let obj = Cu.createObjectIn(dest); + + for (let [name, entry] of ns) { + let allowedContexts = entry.allowedContexts; + if (!allowedContexts.length) { + allowedContexts = ns.defaultContexts; + } + + if (context.shouldInject(ns.name, name, allowedContexts)) { + entry.inject([ns.name], name, obj, context); + } + } + + // Remove the namespace object if it is empty + if (Object.keys(obj).length) { + return obj; + } + }; + + let createNestedNamespaces = (parent, namespaces) => { + for (let [prop, namespace] of namespaces) { + if (namespace instanceof DeepMap) { + exportLazyGetter(parent, prop, () => { + let obj = Cu.createObjectIn(parent); + createNestedNamespaces(obj, namespace); + return obj; + }); + } else { + exportLazyGetter(parent, prop, + () => createNamespace(namespace)); + } + } + }; + + let nestedNamespaces = new DeepMap(); + for (let ns of this.namespaces.values()) { + if (ns.permissions && !ns.permissions.some(perm => context.hasPermission(perm))) { + continue; + } + + if (!wrapperFuncs.shouldInject(ns.name, null, ns.allowedContexts)) { + continue; + } + + if (ns.name.includes(".")) { + let path = ns.name.split("."); + let leafName = path.pop(); + + let parent = nestedNamespaces.getPath(...path); + + parent.set(leafName, ns); + } else { + exportLazyGetter(dest, ns.name, + () => createNamespace(ns)); + } + } + + createNestedNamespaces(dest, nestedNamespaces); + }, + + /** + * Normalize `obj` according to the loaded schema for `typeName`. + * + * @param {object} obj The object to normalize against the schema. + * @param {string} typeName The name in the format namespace.propertyname + * @param {object} context An implementation of Context. Any validation errors + * are reported to the given context. + * @returns {object} The normalized object. + */ + normalize(obj, typeName, context) { + let [namespaceName, prop] = typeName.split("."); + let ns = this.namespaces.get(namespaceName); + let type = ns.get(prop); + + return type.normalize(obj, new Context(context)); + }, +}; diff --git a/toolkit/components/webextensions/ext-alarms.js b/toolkit/components/webextensions/ext-alarms.js new file mode 100644 index 000000000..2171e7dba --- /dev/null +++ b/toolkit/components/webextensions/ext-alarms.js @@ -0,0 +1,155 @@ +"use strict"; + +var {classes: Cc, interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +var { + EventManager, +} = ExtensionUtils; + +// WeakMap[Extension -> Map[name -> Alarm]] +var alarmsMap = new WeakMap(); + +// WeakMap[Extension -> Set[callback]] +var alarmCallbacksMap = new WeakMap(); + +// Manages an alarm created by the extension (alarms API). +function Alarm(extension, name, alarmInfo) { + this.extension = extension; + this.name = name; + this.when = alarmInfo.when; + this.delayInMinutes = alarmInfo.delayInMinutes; + this.periodInMinutes = alarmInfo.periodInMinutes; + this.canceled = false; + + let delay, scheduledTime; + if (this.when) { + scheduledTime = this.when; + delay = this.when - Date.now(); + } else { + if (!this.delayInMinutes) { + this.delayInMinutes = this.periodInMinutes; + } + delay = this.delayInMinutes * 60 * 1000; + scheduledTime = Date.now() + delay; + } + + this.scheduledTime = scheduledTime; + + let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); + timer.init(this, delay, Ci.nsITimer.TYPE_ONE_SHOT); + this.timer = timer; +} + +Alarm.prototype = { + clear() { + this.timer.cancel(); + alarmsMap.get(this.extension).delete(this.name); + this.canceled = true; + }, + + observe(subject, topic, data) { + if (this.canceled) { + return; + } + + for (let callback of alarmCallbacksMap.get(this.extension)) { + callback(this); + } + + if (!this.periodInMinutes) { + this.clear(); + return; + } + + let delay = this.periodInMinutes * 60 * 1000; + this.scheduledTime = Date.now() + delay; + this.timer.init(this, delay, Ci.nsITimer.TYPE_ONE_SHOT); + }, + + get data() { + return { + name: this.name, + scheduledTime: this.scheduledTime, + periodInMinutes: this.periodInMinutes, + }; + }, +}; + +/* eslint-disable mozilla/balanced-listeners */ +extensions.on("startup", (type, extension) => { + alarmsMap.set(extension, new Map()); + alarmCallbacksMap.set(extension, new Set()); +}); + +extensions.on("shutdown", (type, extension) => { + if (alarmsMap.has(extension)) { + for (let alarm of alarmsMap.get(extension).values()) { + alarm.clear(); + } + alarmsMap.delete(extension); + alarmCallbacksMap.delete(extension); + } +}); +/* eslint-enable mozilla/balanced-listeners */ + +extensions.registerSchemaAPI("alarms", "addon_parent", context => { + let {extension} = context; + return { + alarms: { + create: function(name, alarmInfo) { + name = name || ""; + let alarms = alarmsMap.get(extension); + if (alarms.has(name)) { + alarms.get(name).clear(); + } + let alarm = new Alarm(extension, name, alarmInfo); + alarms.set(alarm.name, alarm); + }, + + get: function(name) { + name = name || ""; + let alarms = alarmsMap.get(extension); + if (alarms.has(name)) { + return Promise.resolve(alarms.get(name).data); + } + return Promise.resolve(); + }, + + getAll: function() { + let result = Array.from(alarmsMap.get(extension).values(), alarm => alarm.data); + return Promise.resolve(result); + }, + + clear: function(name) { + name = name || ""; + let alarms = alarmsMap.get(extension); + if (alarms.has(name)) { + alarms.get(name).clear(); + return Promise.resolve(true); + } + return Promise.resolve(false); + }, + + clearAll: function() { + let cleared = false; + for (let alarm of alarmsMap.get(extension).values()) { + alarm.clear(); + cleared = true; + } + return Promise.resolve(cleared); + }, + + onAlarm: new EventManager(context, "alarms.onAlarm", fire => { + let callback = alarm => { + fire(alarm.data); + }; + + alarmCallbacksMap.get(extension).add(callback); + return () => { + alarmCallbacksMap.get(extension).delete(callback); + }; + }).api(), + }, + }; +}); diff --git a/toolkit/components/webextensions/ext-backgroundPage.js b/toolkit/components/webextensions/ext-backgroundPage.js new file mode 100644 index 000000000..fce6100ca --- /dev/null +++ b/toolkit/components/webextensions/ext-backgroundPage.js @@ -0,0 +1,147 @@ +"use strict"; + +var {interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/Task.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "AddonManager", + "resource://gre/modules/AddonManager.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm"); + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +const { + promiseDocumentLoaded, + promiseObserved, +} = ExtensionUtils; + +const XUL_URL = "data:application/vnd.mozilla.xul+xml;charset=utf-8," + encodeURI( + ` + `); + +// WeakMap[Extension -> BackgroundPage] +var backgroundPagesMap = new WeakMap(); + +// Responsible for the background_page section of the manifest. +function BackgroundPage(options, extension) { + this.extension = extension; + this.page = options.page || null; + this.isGenerated = !!options.scripts; + this.windowlessBrowser = null; + this.webNav = null; +} + +BackgroundPage.prototype = { + build: Task.async(function* () { + let windowlessBrowser = Services.appShell.createWindowlessBrowser(true); + this.windowlessBrowser = windowlessBrowser; + + let url; + if (this.page) { + url = this.extension.baseURI.resolve(this.page); + } else if (this.isGenerated) { + url = this.extension.baseURI.resolve("_generated_background_page.html"); + } + + if (!this.extension.isExtensionURL(url)) { + this.extension.manifestError("Background page must be a file within the extension"); + url = this.extension.baseURI.resolve("_blank.html"); + } + + let system = Services.scriptSecurityManager.getSystemPrincipal(); + + // The windowless browser is a thin wrapper around a docShell that keeps + // its related resources alive. It implements nsIWebNavigation and + // forwards its methods to the underlying docShell, but cannot act as a + // docShell itself. Calling `getInterface(nsIDocShell)` gives us the + // underlying docShell, and `QueryInterface(nsIWebNavigation)` gives us + // access to the webNav methods that are already available on the + // windowless browser, but contrary to appearances, they are not the same + // object. + let chromeShell = windowlessBrowser.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell) + .QueryInterface(Ci.nsIWebNavigation); + + if (PrivateBrowsingUtils.permanentPrivateBrowsing) { + let attrs = chromeShell.getOriginAttributes(); + attrs.privateBrowsingId = 1; + chromeShell.setOriginAttributes(attrs); + } + + chromeShell.useGlobalHistory = false; + chromeShell.createAboutBlankContentViewer(system); + chromeShell.loadURI(XUL_URL, 0, null, null, null); + + + yield promiseObserved("chrome-document-global-created", + win => win.document == chromeShell.document); + + let chromeDoc = yield promiseDocumentLoaded(chromeShell.document); + + let browser = chromeDoc.createElement("browser"); + browser.setAttribute("type", "content"); + browser.setAttribute("disableglobalhistory", "true"); + chromeDoc.documentElement.appendChild(browser); + + extensions.emit("extension-browser-inserted", browser); + browser.messageManager.sendAsyncMessage("Extension:InitExtensionView", { + viewType: "background", + url, + }); + + yield new Promise(resolve => { + browser.messageManager.addMessageListener("Extension:ExtensionViewLoaded", function onLoad() { + browser.messageManager.removeMessageListener("Extension:ExtensionViewLoaded", onLoad); + resolve(); + }); + }); + + // TODO(robwu): This is not webext-oop compatible. + this.webNav = browser.docShell.QueryInterface(Ci.nsIWebNavigation); + let window = this.webNav.document.defaultView; + + + // Set the add-on's main debugger global, for use in the debugger + // console. + if (this.extension.addonData.instanceID) { + AddonManager.getAddonByInstanceID(this.extension.addonData.instanceID) + .then(addon => addon.setDebugGlobal(window)); + } + + this.extension.emit("startup"); + }), + + shutdown() { + if (this.extension.addonData.instanceID) { + AddonManager.getAddonByInstanceID(this.extension.addonData.instanceID) + .then(addon => addon.setDebugGlobal(null)); + } + + // Navigate away from the background page to invalidate any + // setTimeouts or other callbacks. + if (this.webNav) { + this.webNav.loadURI("about:blank", 0, null, null, null); + this.webNav = null; + } + + this.windowlessBrowser.loadURI("about:blank", 0, null, null, null); + this.windowlessBrowser.close(); + this.windowlessBrowser = null; + }, +}; + +/* eslint-disable mozilla/balanced-listeners */ +extensions.on("manifest_background", (type, directive, extension, manifest) => { + let bgPage = new BackgroundPage(manifest.background, extension); + backgroundPagesMap.set(extension, bgPage); + return bgPage.build(); +}); + +extensions.on("shutdown", (type, extension) => { + if (backgroundPagesMap.has(extension)) { + backgroundPagesMap.get(extension).shutdown(); + backgroundPagesMap.delete(extension); + } +}); +/* eslint-enable mozilla/balanced-listeners */ diff --git a/toolkit/components/webextensions/ext-browser-content.js b/toolkit/components/webextensions/ext-browser-content.js new file mode 100644 index 000000000..e14ca50d6 --- /dev/null +++ b/toolkit/components/webextensions/ext-browser-content.js @@ -0,0 +1,217 @@ +/* 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 {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "clearTimeout", + "resource://gre/modules/Timer.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", + "resource://gre/modules/NetUtil.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "require", + "resource://devtools/shared/Loader.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "setTimeout", + "resource://gre/modules/Timer.jsm"); + +XPCOMUtils.defineLazyGetter(this, "colorUtils", () => { + return require("devtools/shared/css/color").colorUtils; +}); + +const { + stylesheetMap, +} = ExtensionUtils; + +/* globals addMessageListener, content, docShell, sendAsyncMessage */ + +// Minimum time between two resizes. +const RESIZE_TIMEOUT = 100; + +const BrowserListener = { + init({allowScriptsToClose, fixedWidth, maxHeight, maxWidth, stylesheets}) { + this.fixedWidth = fixedWidth; + this.stylesheets = stylesheets || []; + + this.maxWidth = maxWidth; + this.maxHeight = maxHeight; + + this.oldBackground = null; + + if (allowScriptsToClose) { + content.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils) + .allowScriptsToClose(); + } + + addEventListener("DOMWindowCreated", this, true); + addEventListener("load", this, true); + addEventListener("DOMContentLoaded", this, true); + addEventListener("DOMWindowClose", this, true); + addEventListener("MozScrolledAreaChanged", this, true); + }, + + destroy() { + removeEventListener("DOMWindowCreated", this, true); + removeEventListener("load", this, true); + removeEventListener("DOMContentLoaded", this, true); + removeEventListener("DOMWindowClose", this, true); + removeEventListener("MozScrolledAreaChanged", this, true); + }, + + receiveMessage({name, data}) { + if (name === "Extension:InitBrowser") { + this.init(data); + } + }, + + handleEvent(event) { + switch (event.type) { + case "DOMWindowCreated": + if (event.target === content.document) { + let winUtils = content.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindowUtils); + + for (let url of this.stylesheets) { + winUtils.addSheet(stylesheetMap.get(url), winUtils.AGENT_SHEET); + } + } + break; + + case "DOMWindowClose": + if (event.target === content) { + event.preventDefault(); + + sendAsyncMessage("Extension:DOMWindowClose"); + } + break; + + case "DOMContentLoaded": + if (event.target === content.document) { + sendAsyncMessage("Extension:BrowserContentLoaded", {url: content.location.href}); + this.handleDOMChange(true); + } + break; + + case "load": + if (event.target.contentWindow === content) { + // For about:addons inline , we currently receive a load + // event on the element, but no load or DOMContentLoaded + // events from the content window. + sendAsyncMessage("Extension:BrowserContentLoaded", {url: content.location.href}); + } else if (event.target !== content.document) { + break; + } + + // We use a capturing listener, so we get this event earlier than any + // load listeners in the content page. Resizing after a timeout ensures + // that we calculate the size after the entire event cycle has completed + // (unless someone spins the event loop, anyway), and hopefully after + // the content has made any modifications. + Promise.resolve().then(() => { + this.handleDOMChange(true); + }); + + // Mutation observer to make sure the panel shrinks when the content does. + new content.MutationObserver(this.handleDOMChange.bind(this)).observe( + content.document.documentElement, { + attributes: true, + characterData: true, + childList: true, + subtree: true, + }); + break; + + case "MozScrolledAreaChanged": + this.handleDOMChange(); + break; + } + }, + + // Resizes the browser to match the preferred size of the content (debounced). + handleDOMChange(ignoreThrottling = false) { + if (ignoreThrottling && this.resizeTimeout) { + clearTimeout(this.resizeTimeout); + this.resizeTimeout = null; + } + + if (this.resizeTimeout == null) { + this.resizeTimeout = setTimeout(() => { + try { + if (content) { + this._handleDOMChange("delayed"); + } + } finally { + this.resizeTimeout = null; + } + }, RESIZE_TIMEOUT); + + this._handleDOMChange(); + } + }, + + _handleDOMChange(detail) { + let doc = content.document; + + let body = doc.body; + if (!body || doc.compatMode === "BackCompat") { + // In quirks mode, the root element is used as the scroll frame, and the + // body lies about its scroll geometry, and returns the values for the + // root instead. + body = doc.documentElement; + } + + + let result; + if (this.fixedWidth) { + // If we're in a fixed-width area (namely a slide-in subview of the main + // menu panel), we need to calculate the view height based on the + // preferred height of the content document's root scrollable element at the + // current width, rather than the complete preferred dimensions of the + // content window. + + // Compensate for any offsets (margin, padding, ...) between the scroll + // area of the body and the outer height of the document. + let getHeight = elem => elem.getBoundingClientRect(elem).height; + let bodyPadding = getHeight(doc.documentElement) - getHeight(body); + + let height = Math.ceil(body.scrollHeight + bodyPadding); + + result = {height, detail}; + } else { + let background = doc.defaultView.getComputedStyle(body).backgroundColor; + let bgColor = colorUtils.colorToRGBA(background); + if (bgColor.a !== 1) { + // Ignore non-opaque backgrounds. + background = null; + } + + if (background !== this.oldBackground) { + sendAsyncMessage("Extension:BrowserBackgroundChanged", {background}); + } + this.oldBackground = background; + + + // Adjust the size of the browser based on its content's preferred size. + let {contentViewer} = docShell; + let ratio = content.devicePixelRatio; + + let w = {}, h = {}; + contentViewer.getContentSizeConstrained(this.maxWidth * ratio, + this.maxHeight * ratio, + w, h); + + let width = Math.ceil(w.value / ratio); + let height = Math.ceil(h.value / ratio); + + result = {width, height, detail}; + } + + sendAsyncMessage("Extension:BrowserResized", result); + }, +}; + +addMessageListener("Extension:InitBrowser", BrowserListener); diff --git a/toolkit/components/webextensions/ext-c-backgroundPage.js b/toolkit/components/webextensions/ext-c-backgroundPage.js new file mode 100644 index 000000000..ca446ce79 --- /dev/null +++ b/toolkit/components/webextensions/ext-c-backgroundPage.js @@ -0,0 +1,45 @@ +"use strict"; + +global.initializeBackgroundPage = (contentWindow) => { + // Override the `alert()` method inside background windows; + // we alias it to console.log(). + // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1203394 + let alertDisplayedWarning = false; + let alertOverwrite = text => { + if (!alertDisplayedWarning) { + require("devtools/client/framework/devtools-browser"); + + let {HUDService} = require("devtools/client/webconsole/hudservice"); + HUDService.openBrowserConsoleOrFocus(); + + contentWindow.console.warn("alert() is not supported in background windows; please use console.log instead."); + + alertDisplayedWarning = true; + } + + contentWindow.console.log(text); + }; + Cu.exportFunction(alertOverwrite, contentWindow, {defineAs: "alert"}); +}; + +extensions.registerSchemaAPI("extension", "addon_child", context => { + function getBackgroundPage() { + for (let view of context.extension.views) { + if (view.viewType == "background" && context.principal.subsumes(view.principal)) { + return view.contentWindow; + } + } + return null; + } + return { + extension: { + getBackgroundPage, + }, + + runtime: { + getBackgroundPage() { + return context.cloneScope.Promise.resolve(getBackgroundPage()); + }, + }, + }; +}); diff --git a/toolkit/components/webextensions/ext-c-extension.js b/toolkit/components/webextensions/ext-c-extension.js new file mode 100644 index 000000000..669309bea --- /dev/null +++ b/toolkit/components/webextensions/ext-c-extension.js @@ -0,0 +1,57 @@ +"use strict"; + +XPCOMUtils.defineLazyModuleGetter(this, "PrivateBrowsingUtils", + "resource://gre/modules/PrivateBrowsingUtils.jsm"); + +function extensionApiFactory(context) { + return { + extension: { + getURL(url) { + return context.extension.baseURI.resolve(url); + }, + + get lastError() { + return context.lastError; + }, + + get inIncognitoContext() { + return context.incognito; + }, + }, + }; +} + +extensions.registerSchemaAPI("extension", "addon_child", extensionApiFactory); +extensions.registerSchemaAPI("extension", "content_child", extensionApiFactory); +extensions.registerSchemaAPI("extension", "addon_child", context => { + return { + extension: { + getViews: function(fetchProperties) { + let result = Cu.cloneInto([], context.cloneScope); + + for (let view of context.extension.views) { + if (!view.active) { + continue; + } + if (!context.principal.subsumes(view.principal)) { + continue; + } + + if (fetchProperties !== null) { + if (fetchProperties.type !== null && view.viewType != fetchProperties.type) { + continue; + } + + if (fetchProperties.windowId !== null && view.windowId != fetchProperties.windowId) { + continue; + } + } + + result.push(view.contentWindow); + } + + return result; + }, + }, + }; +}); diff --git a/toolkit/components/webextensions/ext-c-runtime.js b/toolkit/components/webextensions/ext-c-runtime.js new file mode 100644 index 000000000..1dcac35da --- /dev/null +++ b/toolkit/components/webextensions/ext-c-runtime.js @@ -0,0 +1,96 @@ +"use strict"; + +function runtimeApiFactory(context) { + let {extension} = context; + + return { + runtime: { + onConnect: context.messenger.onConnect("runtime.onConnect"), + + onMessage: context.messenger.onMessage("runtime.onMessage"), + + onConnectExternal: context.messenger.onConnectExternal("runtime.onConnectExternal"), + + onMessageExternal: context.messenger.onMessageExternal("runtime.onMessageExternal"), + + connect: function(extensionId, connectInfo) { + let name = connectInfo !== null && connectInfo.name || ""; + extensionId = extensionId || extension.id; + let recipient = {extensionId}; + + return context.messenger.connect(context.messageManager, name, recipient); + }, + + sendMessage: function(...args) { + let options; // eslint-disable-line no-unused-vars + let extensionId, message, responseCallback; + if (typeof args[args.length - 1] == "function") { + responseCallback = args.pop(); + } + if (!args.length) { + return Promise.reject({message: "runtime.sendMessage's message argument is missing"}); + } else if (args.length == 1) { + message = args[0]; + } else if (args.length == 2) { + if (typeof args[0] == "string" && args[0]) { + [extensionId, message] = args; + } else { + [message, options] = args; + } + } else if (args.length == 3) { + [extensionId, message, options] = args; + } else if (args.length == 4 && !responseCallback) { + return Promise.reject({message: "runtime.sendMessage's last argument is not a function"}); + } else { + return Promise.reject({message: "runtime.sendMessage received too many arguments"}); + } + + if (extensionId != null && typeof extensionId != "string") { + return Promise.reject({message: "runtime.sendMessage's extensionId argument is invalid"}); + } + if (options != null && typeof options != "object") { + return Promise.reject({message: "runtime.sendMessage's options argument is invalid"}); + } + + extensionId = extensionId || extension.id; + let recipient = {extensionId}; + + return context.messenger.sendMessage(context.messageManager, message, recipient, responseCallback); + }, + + connectNative(application) { + let recipient = { + childId: context.childManager.id, + toNativeApp: application, + }; + + return context.messenger.connectNative(context.messageManager, "", recipient); + }, + + sendNativeMessage(application, message) { + let recipient = { + childId: context.childManager.id, + toNativeApp: application, + }; + return context.messenger.sendNativeMessage(context.messageManager, message, recipient); + }, + + get lastError() { + return context.lastError; + }, + + getManifest() { + return Cu.cloneInto(extension.manifest, context.cloneScope); + }, + + id: extension.id, + + getURL: function(url) { + return extension.baseURI.resolve(url); + }, + }, + }; +} + +extensions.registerSchemaAPI("runtime", "addon_child", runtimeApiFactory); +extensions.registerSchemaAPI("runtime", "content_child", runtimeApiFactory); diff --git a/toolkit/components/webextensions/ext-c-storage.js b/toolkit/components/webextensions/ext-c-storage.js new file mode 100644 index 000000000..e8d53058f --- /dev/null +++ b/toolkit/components/webextensions/ext-c-storage.js @@ -0,0 +1,62 @@ +"use strict"; + +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionStorage", + "resource://gre/modules/ExtensionStorage.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); + +function storageApiFactory(context) { + function sanitize(items) { + // The schema validator already takes care of arrays (which are only allowed + // to contain strings). Strings and null are safe values. + if (typeof items != "object" || items === null || Array.isArray(items)) { + return items; + } + // If we got here, then `items` is an object generated by `ObjectType`'s + // `normalize` method from Schemas.jsm. The object returned by `normalize` + // lives in this compartment, while the values live in compartment of + // `context.contentWindow`. The `sanitize` method runs with the principal + // of `context`, so we cannot just use `ExtensionStorage.sanitize` because + // it is not allowed to access properties of `items`. + // So we enumerate all properties and sanitize each value individually. + let sanitized = {}; + for (let [key, value] of Object.entries(items)) { + sanitized[key] = ExtensionStorage.sanitize(value, context); + } + return sanitized; + } + return { + storage: { + local: { + get: function(keys) { + keys = sanitize(keys); + return context.childManager.callParentAsyncFunction("storage.local.get", [ + keys, + ]); + }, + set: function(items) { + items = sanitize(items); + return context.childManager.callParentAsyncFunction("storage.local.set", [ + items, + ]); + }, + }, + + sync: { + get: function(keys) { + keys = sanitize(keys); + return context.childManager.callParentAsyncFunction("storage.sync.get", [ + keys, + ]); + }, + set: function(items) { + items = sanitize(items); + return context.childManager.callParentAsyncFunction("storage.sync.set", [ + items, + ]); + }, + }, + }, + }; +} +extensions.registerSchemaAPI("storage", "addon_child", storageApiFactory); +extensions.registerSchemaAPI("storage", "content_child", storageApiFactory); diff --git a/toolkit/components/webextensions/ext-c-test.js b/toolkit/components/webextensions/ext-c-test.js new file mode 100644 index 000000000..b0c92f79f --- /dev/null +++ b/toolkit/components/webextensions/ext-c-test.js @@ -0,0 +1,188 @@ +"use strict"; + +Components.utils.import("resource://gre/modules/ExtensionUtils.jsm"); +var { + SingletonEventManager, +} = ExtensionUtils; + +/** + * Checks whether the given error matches the given expectations. + * + * @param {*} error + * The error to check. + * @param {string|RegExp|function|null} expectedError + * The expectation to check against. If this parameter is: + * + * - a string, the error message must exactly equal the string. + * - a regular expression, it must match the error message. + * - a function, it is called with the error object and its + * return value is returned. + * - null, the function always returns true. + * @param {BaseContext} context + * + * @returns {boolean} + * True if the error matches the expected error. + */ +function errorMatches(error, expectedError, context) { + if (expectedError === null) { + return true; + } + + if (typeof expectedError === "function") { + return context.runSafeWithoutClone(expectedError, error); + } + + if (typeof error !== "object" || error == null || + typeof error.message !== "string") { + return false; + } + + if (typeof expectedError === "string") { + return error.message === expectedError; + } + + try { + return expectedError.test(error.message); + } catch (e) { + Cu.reportError(e); + } + + return false; +} + +/** + * Calls .toSource() on the given value, but handles null, undefined, + * and errors. + * + * @param {*} value + * @returns {string} + */ +function toSource(value) { + if (value === null) { + return "null"; + } + if (value === undefined) { + return "undefined"; + } + if (typeof value === "string") { + return JSON.stringify(value); + } + + try { + return String(value.toSource()); + } catch (e) { + return ""; + } +} + +function makeTestAPI(context) { + const {extension} = context; + + function getStack() { + return new context.cloneScope.Error().stack.replace(/^/gm, " "); + } + + function assertTrue(value, msg) { + extension.emit("test-result", Boolean(value), String(msg), getStack()); + } + + return { + test: { + sendMessage(...args) { + extension.emit("test-message", ...args); + }, + + notifyPass(msg) { + extension.emit("test-done", true, msg, getStack()); + }, + + notifyFail(msg) { + extension.emit("test-done", false, msg, getStack()); + }, + + log(msg) { + extension.emit("test-log", true, msg, getStack()); + }, + + fail(msg) { + assertTrue(false, msg); + }, + + succeed(msg) { + assertTrue(true, msg); + }, + + assertTrue(value, msg) { + assertTrue(value, msg); + }, + + assertFalse(value, msg) { + assertTrue(!value, msg); + }, + + assertEq(expected, actual, msg) { + let equal = expected === actual; + + expected = String(expected); + actual = String(actual); + + if (!equal && expected === actual) { + actual += " (different)"; + } + extension.emit("test-eq", equal, String(msg), expected, actual, getStack()); + }, + + assertRejects(promise, expectedError, msg) { + // Wrap in a native promise for consistency. + promise = Promise.resolve(promise); + + if (msg) { + msg = `: ${msg}`; + } + + return promise.then(result => { + assertTrue(false, `Promise resolved, expected rejection${msg}`); + }, error => { + let errorMessage = toSource(error && error.message); + + assertTrue(errorMatches(error, expectedError, context), + `Promise rejected, expecting rejection to match ${toSource(expectedError)}, ` + + `got ${errorMessage}${msg}`); + }); + }, + + assertThrows(func, expectedError, msg) { + if (msg) { + msg = `: ${msg}`; + } + + try { + func(); + + assertTrue(false, `Function did not throw, expected error${msg}`); + } catch (error) { + let errorMessage = toSource(error && error.message); + + assertTrue(errorMatches(error, expectedError, context), + `Function threw, expecting error to match ${toSource(expectedError)}` + + `got ${errorMessage}${msg}`); + } + }, + + onMessage: new SingletonEventManager(context, "test.onMessage", fire => { + let handler = (event, ...args) => { + context.runSafe(fire, ...args); + }; + + extension.on("test-harness-message", handler); + return () => { + extension.off("test-harness-message", handler); + }; + }).api(), + }, + }; +} + +extensions.registerSchemaAPI("test", "addon_child", makeTestAPI); +extensions.registerSchemaAPI("test", "content_child", makeTestAPI); + diff --git a/toolkit/components/webextensions/ext-cookies.js b/toolkit/components/webextensions/ext-cookies.js new file mode 100644 index 000000000..d0a703421 --- /dev/null +++ b/toolkit/components/webextensions/ext-cookies.js @@ -0,0 +1,484 @@ +"use strict"; + +const {interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +Cu.import("resource://gre/modules/NetUtil.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "ContextualIdentityService", + "resource://gre/modules/ContextualIdentityService.jsm"); + +var { + EventManager, +} = ExtensionUtils; + +var DEFAULT_STORE = "firefox-default"; +var PRIVATE_STORE = "firefox-private"; +var CONTAINER_STORE = "firefox-container-"; + +global.getCookieStoreIdForTab = function(data, tab) { + if (data.incognito) { + return PRIVATE_STORE; + } + + if (tab.userContextId) { + return CONTAINER_STORE + tab.userContextId; + } + + return DEFAULT_STORE; +}; + +global.isPrivateCookieStoreId = function(storeId) { + return storeId == PRIVATE_STORE; +}; + +global.isDefaultCookieStoreId = function(storeId) { + return storeId == DEFAULT_STORE; +}; + +global.isContainerCookieStoreId = function(storeId) { + return storeId !== null && storeId.startsWith(CONTAINER_STORE); +}; + +global.getContainerForCookieStoreId = function(storeId) { + if (!global.isContainerCookieStoreId(storeId)) { + return null; + } + + let containerId = storeId.substring(CONTAINER_STORE.length); + if (ContextualIdentityService.getIdentityFromId(containerId)) { + return parseInt(containerId, 10); + } + + return null; +}; + +global.isValidCookieStoreId = function(storeId) { + return global.isDefaultCookieStoreId(storeId) || + global.isPrivateCookieStoreId(storeId) || + global.isContainerCookieStoreId(storeId); +}; + +function convert({cookie, isPrivate}) { + let result = { + name: cookie.name, + value: cookie.value, + domain: cookie.host, + hostOnly: !cookie.isDomain, + path: cookie.path, + secure: cookie.isSecure, + httpOnly: cookie.isHttpOnly, + session: cookie.isSession, + }; + + if (!cookie.isSession) { + result.expirationDate = cookie.expiry; + } + + if (cookie.originAttributes.userContextId) { + result.storeId = CONTAINER_STORE + cookie.originAttributes.userContextId; + } else if (cookie.originAttributes.privateBrowsingId || isPrivate) { + result.storeId = PRIVATE_STORE; + } else { + result.storeId = DEFAULT_STORE; + } + + return result; +} + +function isSubdomain(otherDomain, baseDomain) { + return otherDomain == baseDomain || otherDomain.endsWith("." + baseDomain); +} + +// Checks that the given extension has permission to set the given cookie for +// the given URI. +function checkSetCookiePermissions(extension, uri, cookie) { + // Permission checks: + // + // - If the extension does not have permissions for the specified + // URL, it cannot set cookies for it. + // + // - If the specified URL could not set the given cookie, neither can + // the extension. + // + // Ideally, we would just have the cookie service make the latter + // determination, but that turns out to be quite complicated. At the + // moment, it requires constructing a cookie string and creating a + // dummy channel, both of which can be problematic. It also triggers + // a whole set of additional permission and preference checks, which + // may or may not be desirable. + // + // So instead, we do a similar set of checks here. Exactly what + // cookies a given URL should be able to set is not well-documented, + // and is not standardized in any standard that anyone actually + // follows. So instead, we follow the rules used by the cookie + // service. + // + // See source/netwerk/cookie/nsCookieService.cpp, in particular + // CheckDomain() and SetCookieInternal(). + + if (uri.scheme != "http" && uri.scheme != "https") { + return false; + } + + if (!extension.whiteListedHosts.matchesIgnoringPath(uri)) { + return false; + } + + if (!cookie.host) { + // If no explicit host is specified, this becomes a host-only cookie. + cookie.host = uri.host; + return true; + } + + // A leading "." is not expected, but is tolerated if it's not the only + // character in the host. If there is one, start by stripping it off. We'll + // add a new one on success. + if (cookie.host.length > 1) { + cookie.host = cookie.host.replace(/^\./, ""); + } + cookie.host = cookie.host.toLowerCase(); + + if (cookie.host != uri.host) { + // Not an exact match, so check for a valid subdomain. + let baseDomain; + try { + baseDomain = Services.eTLD.getBaseDomain(uri); + } catch (e) { + if (e.result == Cr.NS_ERROR_HOST_IS_IP_ADDRESS || + e.result == Cr.NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS) { + // The cookie service uses these to determine whether the domain + // requires an exact match. We already know we don't have an exact + // match, so return false. In all other cases, re-raise the error. + return false; + } + throw e; + } + + // The cookie domain must be a subdomain of the base domain. This prevents + // us from setting cookies for domains like ".co.uk". + // The domain of the requesting URL must likewise be a subdomain of the + // cookie domain. This prevents us from setting cookies for entirely + // unrelated domains. + if (!isSubdomain(cookie.host, baseDomain) || + !isSubdomain(uri.host, cookie.host)) { + return false; + } + + // RFC2109 suggests that we may only add cookies for sub-domains 1-level + // below us, but enforcing that would break the web, so we don't. + } + + // An explicit domain was passed, so add a leading "." to make this a + // domain cookie. + cookie.host = "." + cookie.host; + + // We don't do any significant checking of path permissions. RFC2109 + // suggests we only allow sites to add cookies for sub-paths, similar to + // same origin policy enforcement, but no-one implements this. + + return true; +} + +function* query(detailsIn, props, context) { + // Different callers want to filter on different properties. |props| + // tells us which ones they're interested in. + let details = {}; + props.forEach(property => { + if (detailsIn[property] !== null) { + details[property] = detailsIn[property]; + } + }); + + if ("domain" in details) { + details.domain = details.domain.toLowerCase().replace(/^\./, ""); + } + + let userContextId = 0; + let isPrivate = context.incognito; + if (details.storeId) { + if (!global.isValidCookieStoreId(details.storeId)) { + return; + } + + if (global.isDefaultCookieStoreId(details.storeId)) { + isPrivate = false; + } else if (global.isPrivateCookieStoreId(details.storeId)) { + isPrivate = true; + } else if (global.isContainerCookieStoreId(details.storeId)) { + isPrivate = false; + userContextId = global.getContainerForCookieStoreId(details.storeId); + if (!userContextId) { + return; + } + } + } + + let storeId = DEFAULT_STORE; + if (isPrivate) { + storeId = PRIVATE_STORE; + } else if ("storeId" in details) { + storeId = details.storeId; + } + + // We can use getCookiesFromHost for faster searching. + let enumerator; + let uri; + if ("url" in details) { + try { + uri = NetUtil.newURI(details.url).QueryInterface(Ci.nsIURL); + Services.cookies.usePrivateMode(isPrivate, () => { + enumerator = Services.cookies.getCookiesFromHost(uri.host, {userContextId}); + }); + } catch (ex) { + // This often happens for about: URLs + return; + } + } else if ("domain" in details) { + Services.cookies.usePrivateMode(isPrivate, () => { + enumerator = Services.cookies.getCookiesFromHost(details.domain, {userContextId}); + }); + } else { + Services.cookies.usePrivateMode(isPrivate, () => { + enumerator = Services.cookies.enumerator; + }); + } + + // Based on nsCookieService::GetCookieStringInternal + function matches(cookie) { + function domainMatches(host) { + return cookie.rawHost == host || (cookie.isDomain && host.endsWith(cookie.host)); + } + + function pathMatches(path) { + let cookiePath = cookie.path.replace(/\/$/, ""); + + if (!path.startsWith(cookiePath)) { + return false; + } + + // path == cookiePath, but without the redundant string compare. + if (path.length == cookiePath.length) { + return true; + } + + // URL path is a substring of the cookie path, so it matches if, and + // only if, the next character is a path delimiter. + let pathDelimiters = ["/", "?", "#", ";"]; + return pathDelimiters.includes(path[cookiePath.length]); + } + + // "Restricts the retrieved cookies to those that would match the given URL." + if (uri) { + if (!domainMatches(uri.host)) { + return false; + } + + if (cookie.isSecure && uri.scheme != "https") { + return false; + } + + if (!pathMatches(uri.path)) { + return false; + } + } + + if ("name" in details && details.name != cookie.name) { + return false; + } + + if (userContextId != cookie.originAttributes.userContextId) { + return false; + } + + // "Restricts the retrieved cookies to those whose domains match or are subdomains of this one." + if ("domain" in details && !isSubdomain(cookie.rawHost, details.domain)) { + return false; + } + + // "Restricts the retrieved cookies to those whose path exactly matches this string."" + if ("path" in details && details.path != cookie.path) { + return false; + } + + if ("secure" in details && details.secure != cookie.isSecure) { + return false; + } + + if ("session" in details && details.session != cookie.isSession) { + return false; + } + + // Check that the extension has permissions for this host. + if (!context.extension.whiteListedHosts.matchesCookie(cookie)) { + return false; + } + + return true; + } + + while (enumerator.hasMoreElements()) { + let cookie = enumerator.getNext().QueryInterface(Ci.nsICookie2); + if (matches(cookie)) { + yield {cookie, isPrivate, storeId}; + } + } +} + +extensions.registerSchemaAPI("cookies", "addon_parent", context => { + let {extension} = context; + let self = { + cookies: { + get: function(details) { + // FIXME: We don't sort by length of path and creation time. + for (let cookie of query(details, ["url", "name", "storeId"], context)) { + return Promise.resolve(convert(cookie)); + } + + // Found no match. + return Promise.resolve(null); + }, + + getAll: function(details) { + let allowed = ["url", "name", "domain", "path", "secure", "session", "storeId"]; + let result = Array.from(query(details, allowed, context), convert); + + return Promise.resolve(result); + }, + + set: function(details) { + let uri = NetUtil.newURI(details.url).QueryInterface(Ci.nsIURL); + + let path; + if (details.path !== null) { + path = details.path; + } else { + // This interface essentially emulates the behavior of the + // Set-Cookie header. In the case of an omitted path, the cookie + // service uses the directory path of the requesting URL, ignoring + // any filename or query parameters. + path = uri.directory; + } + + let name = details.name !== null ? details.name : ""; + let value = details.value !== null ? details.value : ""; + let secure = details.secure !== null ? details.secure : false; + let httpOnly = details.httpOnly !== null ? details.httpOnly : false; + let isSession = details.expirationDate === null; + let expiry = isSession ? Number.MAX_SAFE_INTEGER : details.expirationDate; + let isPrivate = context.incognito; + let userContextId = 0; + if (global.isDefaultCookieStoreId(details.storeId)) { + isPrivate = false; + } else if (global.isPrivateCookieStoreId(details.storeId)) { + isPrivate = true; + } else if (global.isContainerCookieStoreId(details.storeId)) { + let containerId = global.getContainerForCookieStoreId(details.storeId); + if (containerId === null) { + return Promise.reject({message: `Illegal storeId: ${details.storeId}`}); + } + isPrivate = false; + userContextId = containerId; + } else if (details.storeId !== null) { + return Promise.reject({message: "Unknown storeId"}); + } + + let cookieAttrs = {host: details.domain, path: path, isSecure: secure}; + if (!checkSetCookiePermissions(extension, uri, cookieAttrs)) { + return Promise.reject({message: `Permission denied to set cookie ${JSON.stringify(details)}`}); + } + + // The permission check may have modified the domain, so use + // the new value instead. + Services.cookies.usePrivateMode(isPrivate, () => { + Services.cookies.add(cookieAttrs.host, path, name, value, + secure, httpOnly, isSession, expiry, {userContextId}); + }); + + return self.cookies.get(details); + }, + + remove: function(details) { + for (let {cookie, isPrivate, storeId} of query(details, ["url", "name", "storeId"], context)) { + Services.cookies.usePrivateMode(isPrivate, () => { + Services.cookies.remove(cookie.host, cookie.name, cookie.path, false, cookie.originAttributes); + }); + + // Todo: could there be multiple per subdomain? + return Promise.resolve({ + url: details.url, + name: details.name, + storeId, + }); + } + + return Promise.resolve(null); + }, + + getAllCookieStores: function() { + let data = {}; + for (let window of WindowListManager.browserWindows()) { + let tabs = TabManager.for(extension).getTabs(window); + for (let tab of tabs) { + if (!(tab.cookieStoreId in data)) { + data[tab.cookieStoreId] = []; + } + data[tab.cookieStoreId].push(tab); + } + } + + let result = []; + for (let key in data) { + result.push({id: key, tabIds: data[key], incognito: key == PRIVATE_STORE}); + } + return Promise.resolve(result); + }, + + onChanged: new EventManager(context, "cookies.onChanged", fire => { + let observer = (subject, topic, data) => { + let notify = (removed, cookie, cause) => { + cookie.QueryInterface(Ci.nsICookie2); + + if (extension.whiteListedHosts.matchesCookie(cookie)) { + fire({removed, cookie: convert({cookie, isPrivate: topic == "private-cookie-changed"}), cause}); + } + }; + + // We do our best effort here to map the incompatible states. + switch (data) { + case "deleted": + notify(true, subject, "explicit"); + break; + case "added": + notify(false, subject, "explicit"); + break; + case "changed": + notify(true, subject, "overwrite"); + notify(false, subject, "explicit"); + break; + case "batch-deleted": + subject.QueryInterface(Ci.nsIArray); + for (let i = 0; i < subject.length; i++) { + let cookie = subject.queryElementAt(i, Ci.nsICookie2); + if (!cookie.isSession && cookie.expiry * 1000 <= Date.now()) { + notify(true, cookie, "expired"); + } else { + notify(true, cookie, "evicted"); + } + } + break; + } + }; + + Services.obs.addObserver(observer, "cookie-changed", false); + Services.obs.addObserver(observer, "private-cookie-changed", false); + return () => { + Services.obs.removeObserver(observer, "cookie-changed"); + Services.obs.removeObserver(observer, "private-cookie-changed"); + }; + }).api(), + }, + }; + + return self; +}); diff --git a/toolkit/components/webextensions/ext-downloads.js b/toolkit/components/webextensions/ext-downloads.js new file mode 100644 index 000000000..132814ae4 --- /dev/null +++ b/toolkit/components/webextensions/ext-downloads.js @@ -0,0 +1,799 @@ +"use strict"; + +var {classes: Cc, interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "Downloads", + "resource://gre/modules/Downloads.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "DownloadPaths", + "resource://gre/modules/DownloadPaths.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "OS", + "resource://gre/modules/osfile.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "FileUtils", + "resource://gre/modules/FileUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", + "resource://gre/modules/NetUtil.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "EventEmitter", + "resource://devtools/shared/event-emitter.js"); + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +const { + ignoreEvent, + normalizeTime, + runSafeSync, + SingletonEventManager, + PlatformInfo, +} = ExtensionUtils; + +const DOWNLOAD_ITEM_FIELDS = ["id", "url", "referrer", "filename", "incognito", + "danger", "mime", "startTime", "endTime", + "estimatedEndTime", "state", + "paused", "canResume", "error", + "bytesReceived", "totalBytes", + "fileSize", "exists", + "byExtensionId", "byExtensionName"]; + +// Fields that we generate onChanged events for. +const DOWNLOAD_ITEM_CHANGE_FIELDS = ["endTime", "state", "paused", "canResume", + "error", "exists"]; + +// From https://fetch.spec.whatwg.org/#forbidden-header-name +const FORBIDDEN_HEADERS = ["ACCEPT-CHARSET", "ACCEPT-ENCODING", + "ACCESS-CONTROL-REQUEST-HEADERS", "ACCESS-CONTROL-REQUEST-METHOD", + "CONNECTION", "CONTENT-LENGTH", "COOKIE", "COOKIE2", "DATE", "DNT", + "EXPECT", "HOST", "KEEP-ALIVE", "ORIGIN", "REFERER", "TE", "TRAILER", + "TRANSFER-ENCODING", "UPGRADE", "VIA"]; + +const FORBIDDEN_PREFIXES = /^PROXY-|^SEC-/i; + +class DownloadItem { + constructor(id, download, extension) { + this.id = id; + this.download = download; + this.extension = extension; + this.prechange = {}; + } + + get url() { return this.download.source.url; } + get referrer() { return this.download.source.referrer; } + get filename() { return this.download.target.path; } + get incognito() { return this.download.source.isPrivate; } + get danger() { return "safe"; } // TODO + get mime() { return this.download.contentType; } + get startTime() { return this.download.startTime; } + get endTime() { return null; } // TODO + get estimatedEndTime() { return null; } // TODO + get state() { + if (this.download.succeeded) { + return "complete"; + } + if (this.download.canceled) { + return "interrupted"; + } + return "in_progress"; + } + get paused() { + return this.download.canceled && this.download.hasPartialData && !this.download.error; + } + get canResume() { + return (this.download.stopped || this.download.canceled) && + this.download.hasPartialData && !this.download.error; + } + get error() { + if (!this.download.stopped || this.download.succeeded) { + return null; + } + // TODO store this instead of calculating it + + if (this.download.error) { + if (this.download.error.becauseSourceFailed) { + return "NETWORK_FAILED"; // TODO + } + if (this.download.error.becauseTargetFailed) { + return "FILE_FAILED"; // TODO + } + return "CRASH"; + } + return "USER_CANCELED"; + } + get bytesReceived() { + return this.download.currentBytes; + } + get totalBytes() { + return this.download.hasProgress ? this.download.totalBytes : -1; + } + get fileSize() { + // todo: this is supposed to be post-compression + return this.download.succeeded ? this.download.target.size : -1; + } + get exists() { return this.download.target.exists; } + get byExtensionId() { return this.extension ? this.extension.id : undefined; } + get byExtensionName() { return this.extension ? this.extension.name : undefined; } + + /** + * Create a cloneable version of this object by pulling all the + * fields into simple properties (instead of getters). + * + * @returns {object} A DownloadItem with flat properties, + * suitable for cloning. + */ + serialize() { + let obj = {}; + for (let field of DOWNLOAD_ITEM_FIELDS) { + obj[field] = this[field]; + } + if (obj.startTime) { + obj.startTime = obj.startTime.toISOString(); + } + return obj; + } + + // When a change event fires, handlers can look at how an individual + // field changed by comparing item.fieldname with item.prechange.fieldname. + // After all handlers have been invoked, this gets called to store the + // current values of all fields ahead of the next event. + _change() { + for (let field of DOWNLOAD_ITEM_CHANGE_FIELDS) { + this.prechange[field] = this[field]; + } + } +} + + +// DownloadMap maps back and forth betwen the numeric identifiers used in +// the downloads WebExtension API and a Download object from the Downloads jsm. +// todo: make id and extension info persistent (bug 1247794) +const DownloadMap = { + currentId: 0, + loadPromise: null, + + // Maps numeric id -> DownloadItem + byId: new Map(), + + // Maps Download object -> DownloadItem + byDownload: new WeakMap(), + + lazyInit() { + if (this.loadPromise == null) { + EventEmitter.decorate(this); + this.loadPromise = Downloads.getList(Downloads.ALL).then(list => { + let self = this; + return list.addView({ + onDownloadAdded(download) { + const item = self.newFromDownload(download, null); + self.emit("create", item); + }, + + onDownloadRemoved(download) { + const item = self.byDownload.get(download); + if (item != null) { + self.emit("erase", item); + self.byDownload.delete(download); + self.byId.delete(item.id); + } + }, + + onDownloadChanged(download) { + const item = self.byDownload.get(download); + if (item == null) { + Cu.reportError("Got onDownloadChanged for unknown download object"); + } else { + // We get the first one of these when the download is started. + // In this case, don't emit anything, just initialize prechange. + if (Object.keys(item.prechange).length > 0) { + self.emit("change", item); + } + item._change(); + } + }, + }).then(() => list.getAll()) + .then(downloads => { + downloads.forEach(download => { + this.newFromDownload(download, null); + }); + }) + .then(() => list); + }); + } + return this.loadPromise; + }, + + getDownloadList() { + return this.lazyInit(); + }, + + getAll() { + return this.lazyInit().then(() => this.byId.values()); + }, + + fromId(id) { + const download = this.byId.get(id); + if (!download) { + throw new Error(`Invalid download id ${id}`); + } + return download; + }, + + newFromDownload(download, extension) { + if (this.byDownload.has(download)) { + return this.byDownload.get(download); + } + + const id = ++this.currentId; + let item = new DownloadItem(id, download, extension); + this.byId.set(id, item); + this.byDownload.set(download, item); + return item; + }, + + erase(item) { + // This will need to get more complicated for bug 1255507 but for now we + // only work with downloads in the DownloadList from getAll() + return this.getDownloadList().then(list => { + list.remove(item.download); + }); + }, +}; + +// Create a callable function that filters a DownloadItem based on a +// query object of the type passed to search() or erase(). +function downloadQuery(query) { + let queryTerms = []; + let queryNegativeTerms = []; + if (query.query != null) { + for (let term of query.query) { + if (term[0] == "-") { + queryNegativeTerms.push(term.slice(1).toLowerCase()); + } else { + queryTerms.push(term.toLowerCase()); + } + } + } + + function normalizeDownloadTime(arg, before) { + if (arg == null) { + return before ? Number.MAX_VALUE : 0; + } + return normalizeTime(arg).getTime(); + } + + const startedBefore = normalizeDownloadTime(query.startedBefore, true); + const startedAfter = normalizeDownloadTime(query.startedAfter, false); + // const endedBefore = normalizeDownloadTime(query.endedBefore, true); + // const endedAfter = normalizeDownloadTime(query.endedAfter, false); + + const totalBytesGreater = query.totalBytesGreater || 0; + const totalBytesLess = (query.totalBytesLess != null) + ? query.totalBytesLess : Number.MAX_VALUE; + + // Handle options for which we can have a regular expression and/or + // an explicit value to match. + function makeMatch(regex, value, field) { + if (value == null && regex == null) { + return input => true; + } + + let re; + try { + re = new RegExp(regex || "", "i"); + } catch (err) { + throw new Error(`Invalid ${field}Regex: ${err.message}`); + } + if (value == null) { + return input => re.test(input); + } + + value = value.toLowerCase(); + if (re.test(value)) { + return input => (value == input); + } + return input => false; + } + + const matchFilename = makeMatch(query.filenameRegex, query.filename, "filename"); + const matchUrl = makeMatch(query.urlRegex, query.url, "url"); + + return function(item) { + const url = item.url.toLowerCase(); + const filename = item.filename.toLowerCase(); + + if (!queryTerms.every(term => url.includes(term) || filename.includes(term))) { + return false; + } + + if (queryNegativeTerms.some(term => url.includes(term) || filename.includes(term))) { + return false; + } + + if (!matchFilename(filename) || !matchUrl(url)) { + return false; + } + + if (!item.startTime) { + if (query.startedBefore != null || query.startedAfter != null) { + return false; + } + } else if (item.startTime > startedBefore || item.startTime < startedAfter) { + return false; + } + + // todo endedBefore, endedAfter + + if (item.totalBytes == -1) { + if (query.totalBytesGreater != null || query.totalBytesLess != null) { + return false; + } + } else if (item.totalBytes <= totalBytesGreater || item.totalBytes >= totalBytesLess) { + return false; + } + + // todo: include danger + const SIMPLE_ITEMS = ["id", "mime", "startTime", "endTime", "state", + "paused", "error", + "bytesReceived", "totalBytes", "fileSize", "exists"]; + for (let field of SIMPLE_ITEMS) { + if (query[field] != null && item[field] != query[field]) { + return false; + } + } + + return true; + }; +} + +function queryHelper(query) { + let matchFn; + try { + matchFn = downloadQuery(query); + } catch (err) { + return Promise.reject({message: err.message}); + } + + let compareFn; + if (query.orderBy != null) { + const fields = query.orderBy.map(field => field[0] == "-" + ? {reverse: true, name: field.slice(1)} + : {reverse: false, name: field}); + + for (let field of fields) { + if (!DOWNLOAD_ITEM_FIELDS.includes(field.name)) { + return Promise.reject({message: `Invalid orderBy field ${field.name}`}); + } + } + + compareFn = (dl1, dl2) => { + for (let field of fields) { + const val1 = dl1[field.name]; + const val2 = dl2[field.name]; + + if (val1 < val2) { + return field.reverse ? 1 : -1; + } else if (val1 > val2) { + return field.reverse ? -1 : 1; + } + } + return 0; + }; + } + + return DownloadMap.getAll().then(downloads => { + if (compareFn) { + downloads = Array.from(downloads); + downloads.sort(compareFn); + } + let results = []; + for (let download of downloads) { + if (query.limit && results.length >= query.limit) { + break; + } + if (matchFn(download)) { + results.push(download); + } + } + return results; + }); +} + +extensions.registerSchemaAPI("downloads", "addon_parent", context => { + let {extension} = context; + return { + downloads: { + download(options) { + let {filename} = options; + if (filename && PlatformInfo.os === "win") { + // cross platform javascript code uses "/" + filename = filename.replace(/\//g, "\\"); + } + + if (filename != null) { + if (filename.length == 0) { + return Promise.reject({message: "filename must not be empty"}); + } + + let path = OS.Path.split(filename); + if (path.absolute) { + return Promise.reject({message: "filename must not be an absolute path"}); + } + + if (path.components.some(component => component == "..")) { + return Promise.reject({message: "filename must not contain back-references (..)"}); + } + } + + if (options.conflictAction == "prompt") { + // TODO + return Promise.reject({message: "conflictAction prompt not yet implemented"}); + } + + if (options.headers) { + for (let {name} of options.headers) { + if (FORBIDDEN_HEADERS.includes(name.toUpperCase()) || name.match(FORBIDDEN_PREFIXES)) { + return Promise.reject({message: "Forbidden request header name"}); + } + } + } + + // Handle method, headers and body options. + function adjustChannel(channel) { + if (channel instanceof Ci.nsIHttpChannel) { + const method = options.method || "GET"; + channel.requestMethod = method; + + if (options.headers) { + for (let {name, value} of options.headers) { + channel.setRequestHeader(name, value, false); + } + } + + if (options.body != null) { + const stream = Cc["@mozilla.org/io/string-input-stream;1"] + .createInstance(Ci.nsIStringInputStream); + stream.setData(options.body, options.body.length); + + channel.QueryInterface(Ci.nsIUploadChannel2); + channel.explicitSetUploadStream(stream, null, -1, method, false); + } + } + return Promise.resolve(); + } + + function createTarget(downloadsDir) { + let target; + if (filename) { + target = OS.Path.join(downloadsDir, filename); + } else { + let uri = NetUtil.newURI(options.url); + + let remote = "download"; + if (uri instanceof Ci.nsIURL) { + remote = uri.fileName; + } + target = OS.Path.join(downloadsDir, remote); + } + + // Create any needed subdirectories if required by filename. + const dir = OS.Path.dirname(target); + return OS.File.makeDir(dir, {from: downloadsDir}).then(() => { + return OS.File.exists(target); + }).then(exists => { + // This has a race, something else could come along and create + // the file between this test and them time the download code + // creates the target file. But we can't easily fix it without + // modifying DownloadCore so we live with it for now. + if (exists) { + switch (options.conflictAction) { + case "uniquify": + default: + target = DownloadPaths.createNiceUniqueFile(new FileUtils.File(target)).path; + break; + + case "overwrite": + break; + } + } + }).then(() => { + if (!options.saveAs) { + return Promise.resolve(target); + } + + // Setup the file picker Save As dialog. + const picker = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker); + const window = Services.wm.getMostRecentWindow("navigator:browser"); + picker.init(window, null, Ci.nsIFilePicker.modeSave); + picker.displayDirectory = new FileUtils.File(dir); + picker.appendFilters(Ci.nsIFilePicker.filterAll); + picker.defaultString = OS.Path.basename(target); + + // Open the dialog and resolve/reject with the result. + return new Promise((resolve, reject) => { + picker.open(result => { + if (result === Ci.nsIFilePicker.returnCancel) { + reject({message: "Download canceled by the user"}); + } else { + resolve(picker.file.path); + } + }); + }); + }); + } + + let download; + return Downloads.getPreferredDownloadsDirectory() + .then(downloadsDir => createTarget(downloadsDir)) + .then(target => { + const source = { + url: options.url, + }; + + if (options.method || options.headers || options.body) { + source.adjustChannel = adjustChannel; + } + + return Downloads.createDownload({ + source, + target: { + path: target, + partFilePath: target + ".part", + }, + }); + }).then(dl => { + download = dl; + return DownloadMap.getDownloadList(); + }).then(list => { + list.add(download); + + // This is necessary to make pause/resume work. + download.tryToKeepPartialData = true; + download.start(); + + const item = DownloadMap.newFromDownload(download, extension); + return item.id; + }); + }, + + removeFile(id) { + return DownloadMap.lazyInit().then(() => { + let item; + try { + item = DownloadMap.fromId(id); + } catch (err) { + return Promise.reject({message: `Invalid download id ${id}`}); + } + if (item.state !== "complete") { + return Promise.reject({message: `Cannot remove incomplete download id ${id}`}); + } + return OS.File.remove(item.filename, {ignoreAbsent: false}).catch((err) => { + return Promise.reject({message: `Could not remove download id ${item.id} because the file doesn't exist`}); + }); + }); + }, + + search(query) { + return queryHelper(query) + .then(items => items.map(item => item.serialize())); + }, + + pause(id) { + return DownloadMap.lazyInit().then(() => { + let item; + try { + item = DownloadMap.fromId(id); + } catch (err) { + return Promise.reject({message: `Invalid download id ${id}`}); + } + if (item.state != "in_progress") { + return Promise.reject({message: `Download ${id} cannot be paused since it is in state ${item.state}`}); + } + + return item.download.cancel(); + }); + }, + + resume(id) { + return DownloadMap.lazyInit().then(() => { + let item; + try { + item = DownloadMap.fromId(id); + } catch (err) { + return Promise.reject({message: `Invalid download id ${id}`}); + } + if (!item.canResume) { + return Promise.reject({message: `Download ${id} cannot be resumed`}); + } + + return item.download.start(); + }); + }, + + cancel(id) { + return DownloadMap.lazyInit().then(() => { + let item; + try { + item = DownloadMap.fromId(id); + } catch (err) { + return Promise.reject({message: `Invalid download id ${id}`}); + } + if (item.download.succeeded) { + return Promise.reject({message: `Download ${id} is already complete`}); + } + return item.download.finalize(true); + }); + }, + + showDefaultFolder() { + Downloads.getPreferredDownloadsDirectory().then(dir => { + let dirobj = new FileUtils.File(dir); + if (dirobj.isDirectory()) { + dirobj.launch(); + } else { + throw new Error(`Download directory ${dirobj.path} is not actually a directory`); + } + }).catch(Cu.reportError); + }, + + erase(query) { + return queryHelper(query).then(items => { + let results = []; + let promises = []; + for (let item of items) { + promises.push(DownloadMap.erase(item)); + results.push(item.id); + } + return Promise.all(promises).then(() => results); + }); + }, + + open(downloadId) { + return DownloadMap.lazyInit().then(() => { + let download = DownloadMap.fromId(downloadId).download; + if (download.succeeded) { + return download.launch(); + } + return Promise.reject({message: "Download has not completed."}); + }).catch((error) => { + return Promise.reject({message: error.message}); + }); + }, + + show(downloadId) { + return DownloadMap.lazyInit().then(() => { + let download = DownloadMap.fromId(downloadId); + return download.download.showContainingDirectory(); + }).then(() => { + return true; + }).catch(error => { + return Promise.reject({message: error.message}); + }); + }, + + getFileIcon(downloadId, options) { + return DownloadMap.lazyInit().then(() => { + let size = options && options.size ? options.size : 32; + let download = DownloadMap.fromId(downloadId).download; + let pathPrefix = ""; + let path; + + if (download.succeeded) { + let file = FileUtils.File(download.target.path); + path = Services.io.newFileURI(file).spec; + } else { + path = OS.Path.basename(download.target.path); + pathPrefix = "//"; + } + + return new Promise((resolve, reject) => { + let chromeWebNav = Services.appShell.createWindowlessBrowser(true); + chromeWebNav + .QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell) + .createAboutBlankContentViewer(Services.scriptSecurityManager.getSystemPrincipal()); + + let img = chromeWebNav.document.createElement("img"); + img.width = size; + img.height = size; + + let handleLoad; + let handleError; + const cleanup = () => { + img.removeEventListener("load", handleLoad); + img.removeEventListener("error", handleError); + chromeWebNav.close(); + chromeWebNav = null; + }; + + handleLoad = () => { + let canvas = chromeWebNav.document.createElement("canvas"); + canvas.width = size; + canvas.height = size; + let context = canvas.getContext("2d"); + context.drawImage(img, 0, 0, size, size); + let dataURL = canvas.toDataURL("image/png"); + cleanup(); + resolve(dataURL); + }; + + handleError = (error) => { + Cu.reportError(error); + cleanup(); + reject(new Error("An unexpected error occurred")); + }; + + img.addEventListener("load", handleLoad); + img.addEventListener("error", handleError); + img.src = `moz-icon:${pathPrefix}${path}?size=${size}`; + }); + }).catch((error) => { + return Promise.reject({message: error.message}); + }); + }, + + // When we do setShelfEnabled(), check for additional "downloads.shelf" permission. + // i.e.: + // setShelfEnabled(enabled) { + // if (!extension.hasPermission("downloads.shelf")) { + // throw new context.cloneScope.Error("Permission denied because 'downloads.shelf' permission is missing."); + // } + // ... + // } + + onChanged: new SingletonEventManager(context, "downloads.onChanged", fire => { + const handler = (what, item) => { + let changes = {}; + const noundef = val => (val === undefined) ? null : val; + DOWNLOAD_ITEM_CHANGE_FIELDS.forEach(fld => { + if (item[fld] != item.prechange[fld]) { + changes[fld] = { + previous: noundef(item.prechange[fld]), + current: noundef(item[fld]), + }; + } + }); + if (Object.keys(changes).length > 0) { + changes.id = item.id; + runSafeSync(context, fire, changes); + } + }; + + let registerPromise = DownloadMap.getDownloadList().then(() => { + DownloadMap.on("change", handler); + }); + return () => { + registerPromise.then(() => { + DownloadMap.off("change", handler); + }); + }; + }).api(), + + onCreated: new SingletonEventManager(context, "downloads.onCreated", fire => { + const handler = (what, item) => { + runSafeSync(context, fire, item.serialize()); + }; + let registerPromise = DownloadMap.getDownloadList().then(() => { + DownloadMap.on("create", handler); + }); + return () => { + registerPromise.then(() => { + DownloadMap.off("create", handler); + }); + }; + }).api(), + + onErased: new SingletonEventManager(context, "downloads.onErased", fire => { + const handler = (what, item) => { + runSafeSync(context, fire, item.id); + }; + let registerPromise = DownloadMap.getDownloadList().then(() => { + DownloadMap.on("erase", handler); + }); + return () => { + registerPromise.then(() => { + DownloadMap.off("erase", handler); + }); + }; + }).api(), + + onDeterminingFilename: ignoreEvent(context, "downloads.onDeterminingFilename"), + }, + }; +}); diff --git a/toolkit/components/webextensions/ext-extension.js b/toolkit/components/webextensions/ext-extension.js new file mode 100644 index 000000000..c4bdc8b63 --- /dev/null +++ b/toolkit/components/webextensions/ext-extension.js @@ -0,0 +1,20 @@ +"use strict"; + +extensions.registerSchemaAPI("extension", "addon_parent", context => { + return { + extension: { + get lastError() { + return context.lastError; + }, + + isAllowedIncognitoAccess() { + return Promise.resolve(true); + }, + + isAllowedFileSchemeAccess() { + return Promise.resolve(false); + }, + }, + }; +}); + diff --git a/toolkit/components/webextensions/ext-i18n.js b/toolkit/components/webextensions/ext-i18n.js new file mode 100644 index 000000000..bb4bde4bd --- /dev/null +++ b/toolkit/components/webextensions/ext-i18n.js @@ -0,0 +1,34 @@ +"use strict"; + +var {classes: Cc, interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +var { + detectLanguage, +} = ExtensionUtils; + +function i18nApiFactory(context) { + let {extension} = context; + return { + i18n: { + getMessage: function(messageName, substitutions) { + return extension.localizeMessage(messageName, substitutions, {cloneScope: context.cloneScope}); + }, + + getAcceptLanguages: function() { + let result = extension.localeData.acceptLanguages; + return Promise.resolve(result); + }, + + getUILanguage: function() { + return extension.localeData.uiLocale; + }, + + detectLanguage: function(text) { + return detectLanguage(text); + }, + }, + }; +} +extensions.registerSchemaAPI("i18n", "addon_child", i18nApiFactory); +extensions.registerSchemaAPI("i18n", "content_child", i18nApiFactory); diff --git a/toolkit/components/webextensions/ext-idle.js b/toolkit/components/webextensions/ext-idle.js new file mode 100644 index 000000000..c5be4b600 --- /dev/null +++ b/toolkit/components/webextensions/ext-idle.js @@ -0,0 +1,94 @@ +"use strict"; + +const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "EventEmitter", + "resource://devtools/shared/event-emitter.js"); +XPCOMUtils.defineLazyServiceGetter(this, "idleService", + "@mozilla.org/widget/idleservice;1", + "nsIIdleService"); +const { + SingletonEventManager, +} = ExtensionUtils; + +// WeakMap[Extension -> Object] +var observersMap = new WeakMap(); + +function getObserverInfo(extension, context) { + let observerInfo = observersMap.get(extension); + if (!observerInfo) { + observerInfo = { + observer: null, + detectionInterval: 60, + }; + observersMap.set(extension, observerInfo); + context.callOnClose({ + close: () => { + let {observer, detectionInterval} = observersMap.get(extension); + if (observer) { + idleService.removeIdleObserver(observer, detectionInterval); + } + observersMap.delete(extension); + }, + }); + } + return observerInfo; +} + +function getObserver(extension, context) { + let observerInfo = getObserverInfo(extension, context); + let {observer, detectionInterval} = observerInfo; + if (!observer) { + observer = { + observe: function(subject, topic, data) { + if (topic == "idle" || topic == "active") { + this.emit("stateChanged", topic); + } + }, + }; + EventEmitter.decorate(observer); + idleService.addIdleObserver(observer, detectionInterval); + observerInfo.observer = observer; + observerInfo.detectionInterval = detectionInterval; + } + return observer; +} + +function setDetectionInterval(extension, context, newInterval) { + let observerInfo = getObserverInfo(extension, context); + let {observer, detectionInterval} = observerInfo; + if (observer) { + idleService.removeIdleObserver(observer, detectionInterval); + idleService.addIdleObserver(observer, newInterval); + } + observerInfo.detectionInterval = newInterval; +} + +extensions.registerSchemaAPI("idle", "addon_parent", context => { + let {extension} = context; + return { + idle: { + queryState: function(detectionIntervalInSeconds) { + if (idleService.idleTime < detectionIntervalInSeconds * 1000) { + return Promise.resolve("active"); + } + return Promise.resolve("idle"); + }, + setDetectionInterval: function(detectionIntervalInSeconds) { + setDetectionInterval(extension, context, detectionIntervalInSeconds); + }, + onStateChanged: new SingletonEventManager(context, "idle.onStateChanged", fire => { + let listener = (event, data) => { + context.runSafe(fire, data); + }; + + getObserver(extension, context).on("stateChanged", listener); + return () => { + getObserver(extension, context).off("stateChanged", listener); + }; + }).api(), + }, + }; +}); diff --git a/toolkit/components/webextensions/ext-management.js b/toolkit/components/webextensions/ext-management.js new file mode 100644 index 000000000..59a7959d7 --- /dev/null +++ b/toolkit/components/webextensions/ext-management.js @@ -0,0 +1,109 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; + +XPCOMUtils.defineLazyGetter(this, "strBundle", function() { + const stringSvc = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService); + return stringSvc.createBundle("chrome://global/locale/extensions.properties"); +}); +XPCOMUtils.defineLazyModuleGetter(this, "AddonManager", + "resource://gre/modules/AddonManager.jsm"); +XPCOMUtils.defineLazyServiceGetter(this, "promptService", + "@mozilla.org/embedcomp/prompt-service;1", + "nsIPromptService"); + +function _(key, ...args) { + if (args.length) { + return strBundle.formatStringFromName(key, args, args.length); + } + return strBundle.GetStringFromName(key); +} + +function installType(addon) { + if (addon.temporarilyInstalled) { + return "development"; + } else if (addon.foreignInstall) { + return "sideload"; + } else if (addon.isSystem) { + return "other"; + } + return "normal"; +} + +extensions.registerSchemaAPI("management", "addon_parent", context => { + let {extension} = context; + return { + management: { + getSelf: function() { + return new Promise((resolve, reject) => AddonManager.getAddonByID(extension.id, addon => { + try { + let m = extension.manifest; + let extInfo = { + id: extension.id, + name: addon.name, + shortName: m.short_name || "", + description: addon.description || "", + version: addon.version, + mayDisable: !!(addon.permissions & AddonManager.PERM_CAN_DISABLE), + enabled: addon.isActive, + optionsUrl: addon.optionsURL || "", + permissions: Array.from(extension.permissions).filter(perm => { + return !extension.whiteListedHosts.pat.includes(perm); + }), + hostPermissions: extension.whiteListedHosts.pat, + installType: installType(addon), + }; + if (addon.homepageURL) { + extInfo.homepageUrl = addon.homepageURL; + } + if (addon.updateURL) { + extInfo.updateUrl = addon.updateURL; + } + if (m.icons) { + extInfo.icons = Object.keys(m.icons).map(key => { + return {size: Number(key), url: m.icons[key]}; + }); + } + + resolve(extInfo); + } catch (err) { + reject(err); + } + })); + }, + + uninstallSelf: function(options) { + return new Promise((resolve, reject) => { + if (options && options.showConfirmDialog) { + let message = _("uninstall.confirmation.message", extension.name); + if (options.dialogMessage) { + message = `${options.dialogMessage}\n${message}`; + } + let title = _("uninstall.confirmation.title", extension.name); + let buttonFlags = promptService.BUTTON_POS_0 * promptService.BUTTON_TITLE_IS_STRING + + promptService.BUTTON_POS_1 * promptService.BUTTON_TITLE_IS_STRING; + let button0Title = _("uninstall.confirmation.button-0.label"); + let button1Title = _("uninstall.confirmation.button-1.label"); + let response = promptService.confirmEx(null, title, message, buttonFlags, button0Title, button1Title, null, null, {value: 0}); + if (response == 1) { + return reject({message: "User cancelled uninstall of extension"}); + } + } + AddonManager.getAddonByID(extension.id, addon => { + let canUninstall = Boolean(addon.permissions & AddonManager.PERM_CAN_UNINSTALL); + if (!canUninstall) { + return reject({message: "The add-on cannot be uninstalled"}); + } + try { + addon.uninstall(); + } catch (err) { + return reject(err); + } + }); + }); + }, + }, + }; +}); diff --git a/toolkit/components/webextensions/ext-notifications.js b/toolkit/components/webextensions/ext-notifications.js new file mode 100644 index 000000000..1df96a2ac --- /dev/null +++ b/toolkit/components/webextensions/ext-notifications.js @@ -0,0 +1,161 @@ +"use strict"; + +var {classes: Cc, interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "EventEmitter", + "resource://devtools/shared/event-emitter.js"); + +var { + EventManager, + ignoreEvent, +} = ExtensionUtils; + +// WeakMap[Extension -> Map[id -> Notification]] +var notificationsMap = new WeakMap(); + +// Manages a notification popup (notifications API) created by the extension. +function Notification(extension, id, options) { + this.extension = extension; + this.id = id; + this.options = options; + + let imageURL; + if (options.iconUrl) { + imageURL = this.extension.baseURI.resolve(options.iconUrl); + } + + try { + let svc = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService); + svc.showAlertNotification(imageURL, + options.title, + options.message, + true, // textClickable + this.id, + this, + this.id); + } catch (e) { + // This will fail if alerts aren't available on the system. + } +} + +Notification.prototype = { + clear() { + try { + let svc = Cc["@mozilla.org/alerts-service;1"].getService(Ci.nsIAlertsService); + svc.closeAlert(this.id); + } catch (e) { + // This will fail if the OS doesn't support this function. + } + notificationsMap.get(this.extension).delete(this.id); + }, + + observe(subject, topic, data) { + let notifications = notificationsMap.get(this.extension); + + let emitAndDelete = event => { + notifications.emit(event, data); + notifications.delete(this.id); + }; + + // Don't try to emit events if the extension has been unloaded + if (!notifications) { + return; + } + + if (topic === "alertclickcallback") { + emitAndDelete("clicked"); + } + if (topic === "alertfinished") { + emitAndDelete("closed"); + } + }, +}; + +/* eslint-disable mozilla/balanced-listeners */ +extensions.on("startup", (type, extension) => { + let map = new Map(); + EventEmitter.decorate(map); + notificationsMap.set(extension, map); +}); + +extensions.on("shutdown", (type, extension) => { + if (notificationsMap.has(extension)) { + for (let notification of notificationsMap.get(extension).values()) { + notification.clear(); + } + notificationsMap.delete(extension); + } +}); +/* eslint-enable mozilla/balanced-listeners */ + +var nextId = 0; + +extensions.registerSchemaAPI("notifications", "addon_parent", context => { + let {extension} = context; + return { + notifications: { + create: function(notificationId, options) { + if (!notificationId) { + notificationId = String(nextId++); + } + + let notifications = notificationsMap.get(extension); + if (notifications.has(notificationId)) { + notifications.get(notificationId).clear(); + } + + // FIXME: Lots of options still aren't supported, especially + // buttons. + let notification = new Notification(extension, notificationId, options); + notificationsMap.get(extension).set(notificationId, notification); + + return Promise.resolve(notificationId); + }, + + clear: function(notificationId) { + let notifications = notificationsMap.get(extension); + if (notifications.has(notificationId)) { + notifications.get(notificationId).clear(); + return Promise.resolve(true); + } + return Promise.resolve(false); + }, + + getAll: function() { + let result = {}; + notificationsMap.get(extension).forEach((value, key) => { + result[key] = value.options; + }); + return Promise.resolve(result); + }, + + onClosed: new EventManager(context, "notifications.onClosed", fire => { + let listener = (event, notificationId) => { + // FIXME: Support the byUser argument. + fire(notificationId, true); + }; + + notificationsMap.get(extension).on("closed", listener); + return () => { + notificationsMap.get(extension).off("closed", listener); + }; + }).api(), + + onClicked: new EventManager(context, "notifications.onClicked", fire => { + let listener = (event, notificationId) => { + fire(notificationId, true); + }; + + notificationsMap.get(extension).on("clicked", listener); + return () => { + notificationsMap.get(extension).off("clicked", listener); + }; + }).api(), + + // Intend to implement this later: https://bugzilla.mozilla.org/show_bug.cgi?id=1190681 + onButtonClicked: ignoreEvent(context, "notifications.onButtonClicked"), + }, + }; +}); diff --git a/toolkit/components/webextensions/ext-runtime.js b/toolkit/components/webextensions/ext-runtime.js new file mode 100644 index 000000000..aed3ffd4b --- /dev/null +++ b/toolkit/components/webextensions/ext-runtime.js @@ -0,0 +1,134 @@ +"use strict"; + +var {classes: Cc, interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "AddonManager", + "resource://gre/modules/AddonManager.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Extension", + "resource://gre/modules/Extension.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement", + "resource://gre/modules/ExtensionManagement.jsm"); + +var { + SingletonEventManager, +} = ExtensionUtils; + +extensions.registerSchemaAPI("runtime", "addon_parent", context => { + let {extension} = context; + return { + runtime: { + onStartup: new SingletonEventManager(context, "runtime.onStartup", fire => { + if (context.incognito) { + // This event should not fire if we are operating in a private profile. + return () => {}; + } + let listener = () => { + if (extension.startupReason === "APP_STARTUP") { + fire(); + } + }; + extension.on("startup", listener); + return () => { + extension.off("startup", listener); + }; + }).api(), + + onInstalled: new SingletonEventManager(context, "runtime.onInstalled", fire => { + let listener = () => { + switch (extension.startupReason) { + case "APP_STARTUP": + if (Extension.browserUpdated) { + fire({reason: "browser_update"}); + } + break; + case "ADDON_INSTALL": + fire({reason: "install"}); + break; + case "ADDON_UPGRADE": + fire({reason: "update"}); + break; + } + }; + extension.on("startup", listener); + return () => { + extension.off("startup", listener); + }; + }).api(), + + onUpdateAvailable: new SingletonEventManager(context, "runtime.onUpdateAvailable", fire => { + let instanceID = extension.addonData.instanceID; + AddonManager.addUpgradeListener(instanceID, upgrade => { + extension.upgrade = upgrade; + let details = { + version: upgrade.version, + }; + context.runSafe(fire, details); + }); + return () => { + AddonManager.removeUpgradeListener(instanceID); + }; + }).api(), + + reload: () => { + if (extension.upgrade) { + // If there is a pending update, install it now. + extension.upgrade.install(); + } else { + // Otherwise, reload the current extension. + AddonManager.getAddonByID(extension.id, addon => { + addon.reload(); + }); + } + }, + + get lastError() { + // TODO(robwu): Figure out how to make sure that errors in the parent + // process are propagated to the child process. + // lastError should not be accessed from the parent. + return context.lastError; + }, + + getBrowserInfo: function() { + const {name, vendor, version, appBuildID} = Services.appinfo; + const info = {name, vendor, version, buildID: appBuildID}; + return Promise.resolve(info); + }, + + getPlatformInfo: function() { + return Promise.resolve(ExtensionUtils.PlatformInfo); + }, + + openOptionsPage: function() { + if (!extension.manifest.options_ui) { + return Promise.reject({message: "No `options_ui` declared"}); + } + + return openOptionsPage(extension).then(() => {}); + }, + + setUninstallURL: function(url) { + if (url.length == 0) { + return Promise.resolve(); + } + + let uri; + try { + uri = NetUtil.newURI(url); + } catch (e) { + return Promise.reject({message: `Invalid URL: ${JSON.stringify(url)}`}); + } + + if (uri.scheme != "http" && uri.scheme != "https") { + return Promise.reject({message: "url must have the scheme http or https"}); + } + + extension.uninstallURL = url; + return Promise.resolve(); + }, + }, + }; +}); diff --git a/toolkit/components/webextensions/ext-storage.js b/toolkit/components/webextensions/ext-storage.js new file mode 100644 index 000000000..b1e22c46c --- /dev/null +++ b/toolkit/components/webextensions/ext-storage.js @@ -0,0 +1,46 @@ +"use strict"; + +var {classes: Cc, interfaces: Ci, utils: Cu} = Components; + +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionStorage", + "resource://gre/modules/ExtensionStorage.jsm"); + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +var { + EventManager, +} = ExtensionUtils; + +function storageApiFactory(context) { + let {extension} = context; + return { + storage: { + local: { + get: function(spec) { + return ExtensionStorage.get(extension.id, spec); + }, + set: function(items) { + return ExtensionStorage.set(extension.id, items, context); + }, + remove: function(keys) { + return ExtensionStorage.remove(extension.id, keys); + }, + clear: function() { + return ExtensionStorage.clear(extension.id); + }, + }, + + onChanged: new EventManager(context, "storage.onChanged", fire => { + let listenerLocal = changes => { + fire(changes, "local"); + }; + + ExtensionStorage.addOnChangedListener(extension.id, listenerLocal); + return () => { + ExtensionStorage.removeOnChangedListener(extension.id, listenerLocal); + }; + }).api(), + }, + }; +} +extensions.registerSchemaAPI("storage", "addon_parent", storageApiFactory); +extensions.registerSchemaAPI("storage", "content_parent", storageApiFactory); diff --git a/toolkit/components/webextensions/ext-topSites.js b/toolkit/components/webextensions/ext-topSites.js new file mode 100644 index 000000000..a66ac85d9 --- /dev/null +++ b/toolkit/components/webextensions/ext-topSites.js @@ -0,0 +1,24 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +XPCOMUtils.defineLazyModuleGetter(this, "NewTabUtils", + "resource://gre/modules/NewTabUtils.jsm"); + +extensions.registerSchemaAPI("topSites", "addon_parent", context => { + return { + topSites: { + get: function() { + let urls = NewTabUtils.links.getLinks() + .filter(link => !!link) + .map(link => { + return { + url: link.url, + title: link.title, + }; + }); + return Promise.resolve(urls); + }, + }, + }; +}); diff --git a/toolkit/components/webextensions/ext-webNavigation.js b/toolkit/components/webextensions/ext-webNavigation.js new file mode 100644 index 000000000..904f3a4a7 --- /dev/null +++ b/toolkit/components/webextensions/ext-webNavigation.js @@ -0,0 +1,192 @@ +"use strict"; + +var {classes: Cc, interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement", + "resource://gre/modules/ExtensionManagement.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "MatchURLFilters", + "resource://gre/modules/MatchPattern.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "WebNavigation", + "resource://gre/modules/WebNavigation.jsm"); + +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +var { + SingletonEventManager, + ignoreEvent, +} = ExtensionUtils; + +const defaultTransitionTypes = { + topFrame: "link", + subFrame: "auto_subframe", +}; + +const frameTransitions = { + anyFrame: { + qualifiers: ["server_redirect", "client_redirect", "forward_back"], + }, + topFrame: { + types: ["reload", "form_submit"], + }, +}; + +const tabTransitions = { + topFrame: { + qualifiers: ["from_address_bar"], + types: ["auto_bookmark", "typed", "keyword", "generated", "link"], + }, + subFrame: { + types: ["manual_subframe"], + }, +}; + +function isTopLevelFrame({frameId, parentFrameId}) { + return frameId == 0 && parentFrameId == -1; +} + +function fillTransitionProperties(eventName, src, dst) { + if (eventName == "onCommitted" || eventName == "onHistoryStateUpdated") { + let frameTransitionData = src.frameTransitionData || {}; + let tabTransitionData = src.tabTransitionData || {}; + + let transitionType, transitionQualifiers = []; + + // Fill transition properties for any frame. + for (let qualifier of frameTransitions.anyFrame.qualifiers) { + if (frameTransitionData[qualifier]) { + transitionQualifiers.push(qualifier); + } + } + + if (isTopLevelFrame(dst)) { + for (let type of frameTransitions.topFrame.types) { + if (frameTransitionData[type]) { + transitionType = type; + } + } + + for (let qualifier of tabTransitions.topFrame.qualifiers) { + if (tabTransitionData[qualifier]) { + transitionQualifiers.push(qualifier); + } + } + + for (let type of tabTransitions.topFrame.types) { + if (tabTransitionData[type]) { + transitionType = type; + } + } + + // If transitionType is not defined, defaults it to "link". + if (!transitionType) { + transitionType = defaultTransitionTypes.topFrame; + } + } else { + // If it is sub-frame, transitionType defaults it to "auto_subframe", + // "manual_subframe" is set only in case of a recent user interaction. + transitionType = tabTransitionData.link ? + "manual_subframe" : defaultTransitionTypes.subFrame; + } + + // Fill the transition properties in the webNavigation event object. + dst.transitionType = transitionType; + dst.transitionQualifiers = transitionQualifiers; + } +} + +// Similar to WebRequestEventManager but for WebNavigation. +function WebNavigationEventManager(context, eventName) { + let name = `webNavigation.${eventName}`; + let register = (callback, urlFilters) => { + // Don't create a MatchURLFilters instance if the listener does not include any filter. + let filters = urlFilters ? + new MatchURLFilters(urlFilters.url) : null; + + let listener = data => { + if (!data.browser) { + return; + } + + let data2 = { + url: data.url, + timeStamp: Date.now(), + frameId: ExtensionManagement.getFrameId(data.windowId), + parentFrameId: ExtensionManagement.getParentFrameId(data.parentWindowId, data.windowId), + }; + + if (eventName == "onErrorOccurred") { + data2.error = data.error; + } + + // Fills in tabId typically. + extensions.emit("fill-browser-data", data.browser, data2); + if (data2.tabId < 0) { + return; + } + + fillTransitionProperties(eventName, data, data2); + + context.runSafe(callback, data2); + }; + + WebNavigation[eventName].addListener(listener, filters); + return () => { + WebNavigation[eventName].removeListener(listener); + }; + }; + + return SingletonEventManager.call(this, context, name, register); +} + +WebNavigationEventManager.prototype = Object.create(SingletonEventManager.prototype); + +function convertGetFrameResult(tabId, data) { + return { + errorOccurred: data.errorOccurred, + url: data.url, + tabId, + frameId: ExtensionManagement.getFrameId(data.windowId), + parentFrameId: ExtensionManagement.getParentFrameId(data.parentWindowId, data.windowId), + }; +} + +extensions.registerSchemaAPI("webNavigation", "addon_parent", context => { + return { + webNavigation: { + onTabReplaced: ignoreEvent(context, "webNavigation.onTabReplaced"), + onBeforeNavigate: new WebNavigationEventManager(context, "onBeforeNavigate").api(), + onCommitted: new WebNavigationEventManager(context, "onCommitted").api(), + onDOMContentLoaded: new WebNavigationEventManager(context, "onDOMContentLoaded").api(), + onCompleted: new WebNavigationEventManager(context, "onCompleted").api(), + onErrorOccurred: new WebNavigationEventManager(context, "onErrorOccurred").api(), + onReferenceFragmentUpdated: new WebNavigationEventManager(context, "onReferenceFragmentUpdated").api(), + onHistoryStateUpdated: new WebNavigationEventManager(context, "onHistoryStateUpdated").api(), + onCreatedNavigationTarget: ignoreEvent(context, "webNavigation.onCreatedNavigationTarget"), + getAllFrames(details) { + let tab = TabManager.getTab(details.tabId, context); + + let {innerWindowID, messageManager} = tab.linkedBrowser; + let recipient = {innerWindowID}; + + return context.sendMessage(messageManager, "WebNavigation:GetAllFrames", {}, {recipient}) + .then((results) => results.map(convertGetFrameResult.bind(null, details.tabId))); + }, + getFrame(details) { + let tab = TabManager.getTab(details.tabId, context); + + let recipient = { + innerWindowID: tab.linkedBrowser.innerWindowID, + }; + + let mm = tab.linkedBrowser.messageManager; + return context.sendMessage(mm, "WebNavigation:GetFrame", {options: details}, {recipient}) + .then((result) => { + return result ? + convertGetFrameResult(details.tabId, result) : + Promise.reject({message: `No frame found with frameId: ${details.frameId}`}); + }); + }, + }, + }; +}); diff --git a/toolkit/components/webextensions/ext-webRequest.js b/toolkit/components/webextensions/ext-webRequest.js new file mode 100644 index 000000000..f92330131 --- /dev/null +++ b/toolkit/components/webextensions/ext-webRequest.js @@ -0,0 +1,115 @@ +"use strict"; + +var {classes: Cc, interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "MatchPattern", + "resource://gre/modules/MatchPattern.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "WebRequest", + "resource://gre/modules/WebRequest.jsm"); + +Cu.import("resource://gre/modules/ExtensionManagement.jsm"); +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); +var { + SingletonEventManager, +} = ExtensionUtils; + +// EventManager-like class specifically for WebRequest. Inherits from +// SingletonEventManager. Takes care of converting |details| parameter +// when invoking listeners. +function WebRequestEventManager(context, eventName) { + let name = `webRequest.${eventName}`; + let register = (callback, filter, info) => { + let listener = data => { + // Prevent listening in on requests originating from system principal to + // prevent tinkering with OCSP, app and addon updates, etc. + if (data.isSystemPrincipal) { + return; + } + + let data2 = { + requestId: data.requestId, + url: data.url, + originUrl: data.originUrl, + method: data.method, + type: data.type, + timeStamp: Date.now(), + frameId: data.type == "main_frame" ? 0 : ExtensionManagement.getFrameId(data.windowId), + parentFrameId: ExtensionManagement.getParentFrameId(data.parentWindowId, data.windowId), + }; + + const maybeCached = ["onResponseStarted", "onBeforeRedirect", "onCompleted", "onErrorOccurred"]; + if (maybeCached.includes(eventName)) { + data2.fromCache = !!data.fromCache; + } + + if ("ip" in data) { + data2.ip = data.ip; + } + + extensions.emit("fill-browser-data", data.browser, data2); + + let optional = ["requestHeaders", "responseHeaders", "statusCode", "statusLine", "error", "redirectUrl", + "requestBody"]; + for (let opt of optional) { + if (opt in data) { + data2[opt] = data[opt]; + } + } + + return context.runSafe(callback, data2); + }; + + let filter2 = {}; + filter2.urls = new MatchPattern(filter.urls); + if (filter.types) { + filter2.types = filter.types; + } + if (filter.tabId) { + filter2.tabId = filter.tabId; + } + if (filter.windowId) { + filter2.windowId = filter.windowId; + } + + let info2 = []; + if (info) { + for (let desc of info) { + if (desc == "blocking" && !context.extension.hasPermission("webRequestBlocking")) { + Cu.reportError("Using webRequest.addListener with the blocking option " + + "requires the 'webRequestBlocking' permission."); + } else { + info2.push(desc); + } + } + } + + WebRequest[eventName].addListener(listener, filter2, info2); + return () => { + WebRequest[eventName].removeListener(listener); + }; + }; + + return SingletonEventManager.call(this, context, name, register); +} + +WebRequestEventManager.prototype = Object.create(SingletonEventManager.prototype); + +extensions.registerSchemaAPI("webRequest", "addon_parent", context => { + return { + webRequest: { + onBeforeRequest: new WebRequestEventManager(context, "onBeforeRequest").api(), + onBeforeSendHeaders: new WebRequestEventManager(context, "onBeforeSendHeaders").api(), + onSendHeaders: new WebRequestEventManager(context, "onSendHeaders").api(), + onHeadersReceived: new WebRequestEventManager(context, "onHeadersReceived").api(), + onBeforeRedirect: new WebRequestEventManager(context, "onBeforeRedirect").api(), + onResponseStarted: new WebRequestEventManager(context, "onResponseStarted").api(), + onErrorOccurred: new WebRequestEventManager(context, "onErrorOccurred").api(), + onCompleted: new WebRequestEventManager(context, "onCompleted").api(), + handlerBehaviorChanged: function() { + // TODO: Flush all caches. + }, + }, + }; +}); diff --git a/toolkit/components/webextensions/extensions-toolkit.manifest b/toolkit/components/webextensions/extensions-toolkit.manifest new file mode 100644 index 000000000..4ec65a984 --- /dev/null +++ b/toolkit/components/webextensions/extensions-toolkit.manifest @@ -0,0 +1,49 @@ +# scripts +category webextension-scripts alarms chrome://extensions/content/ext-alarms.js +category webextension-scripts backgroundPage chrome://extensions/content/ext-backgroundPage.js +category webextension-scripts cookies chrome://extensions/content/ext-cookies.js +category webextension-scripts downloads chrome://extensions/content/ext-downloads.js +category webextension-scripts management chrome://extensions/content/ext-management.js +category webextension-scripts notifications chrome://extensions/content/ext-notifications.js +category webextension-scripts i18n chrome://extensions/content/ext-i18n.js +category webextension-scripts idle chrome://extensions/content/ext-idle.js +category webextension-scripts webRequest chrome://extensions/content/ext-webRequest.js +category webextension-scripts webNavigation chrome://extensions/content/ext-webNavigation.js +category webextension-scripts runtime chrome://extensions/content/ext-runtime.js +category webextension-scripts extension chrome://extensions/content/ext-extension.js +category webextension-scripts storage chrome://extensions/content/ext-storage.js +category webextension-scripts topSites chrome://extensions/content/ext-topSites.js + +# scripts specific for content process. +category webextension-scripts-content extension chrome://extensions/content/ext-c-extension.js +category webextension-scripts-content i18n chrome://extensions/content/ext-i18n.js +category webextension-scripts-content runtime chrome://extensions/content/ext-c-runtime.js +category webextension-scripts-content test chrome://extensions/content/ext-c-test.js +category webextension-scripts-content storage chrome://extensions/content/ext-c-storage.js + +# scripts that must run in the same process as addon code. +category webextension-scripts-addon backgroundPage chrome://extensions/content/ext-c-backgroundPage.js +category webextension-scripts-addon extension chrome://extensions/content/ext-c-extension.js +category webextension-scripts-addon i18n chrome://extensions/content/ext-i18n.js +category webextension-scripts-addon runtime chrome://extensions/content/ext-c-runtime.js +category webextension-scripts-addon test chrome://extensions/content/ext-c-test.js +category webextension-scripts-addon storage chrome://extensions/content/ext-c-storage.js + +# schemas +category webextension-schemas alarms chrome://extensions/content/schemas/alarms.json +category webextension-schemas cookies chrome://extensions/content/schemas/cookies.json +category webextension-schemas downloads chrome://extensions/content/schemas/downloads.json +category webextension-schemas events chrome://extensions/content/schemas/events.json +category webextension-schemas extension chrome://extensions/content/schemas/extension.json +category webextension-schemas extension_types chrome://extensions/content/schemas/extension_types.json +category webextension-schemas i18n chrome://extensions/content/schemas/i18n.json +category webextension-schemas idle chrome://extensions/content/schemas/idle.json +category webextension-schemas management chrome://extensions/content/schemas/management.json +category webextension-schemas native_host_manifest chrome://extensions/content/schemas/native_host_manifest.json +category webextension-schemas notifications chrome://extensions/content/schemas/notifications.json +category webextension-schemas runtime chrome://extensions/content/schemas/runtime.json +category webextension-schemas storage chrome://extensions/content/schemas/storage.json +category webextension-schemas test chrome://extensions/content/schemas/test.json +category webextension-schemas top_sites chrome://extensions/content/schemas/top_sites.json +category webextension-schemas web_navigation chrome://extensions/content/schemas/web_navigation.json +category webextension-schemas web_request chrome://extensions/content/schemas/web_request.json diff --git a/toolkit/components/webextensions/jar.mn b/toolkit/components/webextensions/jar.mn new file mode 100644 index 000000000..6d343e1b7 --- /dev/null +++ b/toolkit/components/webextensions/jar.mn @@ -0,0 +1,26 @@ +# 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/. + +toolkit.jar: +% content extensions %content/extensions/ + content/extensions/ext-alarms.js + content/extensions/ext-backgroundPage.js + content/extensions/ext-browser-content.js + content/extensions/ext-cookies.js + content/extensions/ext-downloads.js + content/extensions/ext-management.js + content/extensions/ext-notifications.js + content/extensions/ext-i18n.js + content/extensions/ext-idle.js + content/extensions/ext-webRequest.js + content/extensions/ext-webNavigation.js + content/extensions/ext-runtime.js + content/extensions/ext-extension.js + content/extensions/ext-storage.js + content/extensions/ext-topSites.js + content/extensions/ext-c-backgroundPage.js + content/extensions/ext-c-extension.js + content/extensions/ext-c-runtime.js + content/extensions/ext-c-storage.js + content/extensions/ext-c-test.js diff --git a/toolkit/components/webextensions/moz.build b/toolkit/components/webextensions/moz.build new file mode 100644 index 000000000..f32f526f9 --- /dev/null +++ b/toolkit/components/webextensions/moz.build @@ -0,0 +1,41 @@ +# -*- 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/. + +EXTRA_JS_MODULES += [ + 'Extension.jsm', + 'ExtensionAPI.jsm', + 'ExtensionChild.jsm', + 'ExtensionCommon.jsm', + 'ExtensionContent.jsm', + 'ExtensionManagement.jsm', + 'ExtensionParent.jsm', + 'ExtensionStorage.jsm', + 'ExtensionUtils.jsm', + 'LegacyExtensionsUtils.jsm', + 'MessageChannel.jsm', + 'NativeMessaging.jsm', + 'Schemas.jsm', +] + +EXTRA_COMPONENTS += [ + 'extensions-toolkit.manifest', +] + +TESTING_JS_MODULES += [ + 'ExtensionTestCommon.jsm', + 'ExtensionXPCShellUtils.jsm', +] + +DIRS += ['schemas'] + +JAR_MANIFESTS += ['jar.mn'] + +MOCHITEST_MANIFESTS += ['test/mochitest/mochitest.ini'] +MOCHITEST_CHROME_MANIFESTS += ['test/mochitest/chrome.ini'] +XPCSHELL_TESTS_MANIFESTS += [ + 'test/xpcshell/native_messaging.ini', + 'test/xpcshell/xpcshell.ini', +] diff --git a/toolkit/components/webextensions/schemas/LICENSE b/toolkit/components/webextensions/schemas/LICENSE new file mode 100644 index 000000000..9314092fd --- /dev/null +++ b/toolkit/components/webextensions/schemas/LICENSE @@ -0,0 +1,27 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// 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 +// OWNER 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. diff --git a/toolkit/components/webextensions/schemas/alarms.json b/toolkit/components/webextensions/schemas/alarms.json new file mode 100644 index 000000000..2a72a2842 --- /dev/null +++ b/toolkit/components/webextensions/schemas/alarms.json @@ -0,0 +1,145 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "alarms", + "permissions": ["alarms"], + "types": [ + { + "id": "Alarm", + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Name of this alarm." + }, + "scheduledTime": { + "type": "number", + "description": "Time when the alarm is scheduled to fire, in milliseconds past the epoch." + }, + "periodInMinutes": { + "type": "number", + "optional": true, + "description": "When present, signals that the alarm triggers periodically after so many minutes." + } + } + } + ], + "functions": [ + { + "name": "create", + "type": "function", + "description": "Creates an alarm. After the delay is expired, the onAlarm event is fired. If there is another alarm with the same name (or no name if none is specified), it will be cancelled and replaced by this alarm.", + "parameters": [ + { + "type": "string", + "name": "name", + "optional": true, + "description": "Optional name to identify this alarm. Defaults to the empty string." + }, + { + "type": "object", + "name": "alarmInfo", + "description": "Details about the alarm. The alarm first fires either at 'when' milliseconds past the epoch (if 'when' is provided), after 'delayInMinutes' minutes from the current time (if 'delayInMinutes' is provided instead), or after 'periodInMinutes' minutes from the current time (if only 'periodInMinutes' is provided). Users should never provide both 'when' and 'delayInMinutes'. If 'periodInMinutes' is provided, then the alarm recurs repeatedly after that many minutes.", + "properties": { + "when": {"type": "number", "optional": true, + "description": "Time when the alarm is scheduled to first fire, in milliseconds past the epoch."}, + "delayInMinutes": {"type": "number", "optional": true, + "description": "Number of minutes from the current time after which the alarm should first fire."}, + "periodInMinutes": {"type": "number", "optional": true, + "description": "Number of minutes after which the alarm should recur repeatedly."} + } + } + ] + }, + { + "name": "get", + "type": "function", + "description": "Retrieves details about the specified alarm.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "name", + "optional": true, + "description": "The name of the alarm to get. Defaults to the empty string." + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { "name": "alarm", "$ref": "Alarm" } + ] + } + ] + }, + { + "name": "getAll", + "type": "function", + "description": "Gets an array of all the alarms.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { "name": "alarms", "type": "array", "items": { "$ref": "Alarm" } } + ] + } + ] + }, + { + "name": "clear", + "type": "function", + "description": "Clears the alarm with the given name.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "name", + "optional": true, + "description": "The name of the alarm to clear. Defaults to the empty string." + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { "name": "wasCleared", "type": "boolean", "description": "Whether an alarm of the given name was found to clear." } + ] + } + ] + }, + { + "name": "clearAll", + "type": "function", + "description": "Clears all alarms.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { "name": "wasCleared", "type": "boolean", "description": "Whether any alarm was found to clear." } + ] + } + ] + } + ], + "events": [ + { + "name": "onAlarm", + "type": "function", + "description": "Fired when an alarm has expired. Useful for transient background pages.", + "parameters": [ + { + "name": "name", + "$ref": "Alarm", + "description": "The alarm that has expired." + } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/cookies.json b/toolkit/components/webextensions/schemas/cookies.json new file mode 100644 index 000000000..a7de6eb42 --- /dev/null +++ b/toolkit/components/webextensions/schemas/cookies.json @@ -0,0 +1,224 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "cookies" + ] + }] + } + ] + }, + { + "namespace": "cookies", + "description": "Use the browser.cookies API to query and modify cookies, and to be notified when they change.", + "permissions": ["cookies"], + "types": [ + { + "id": "Cookie", + "type": "object", + "description": "Represents information about an HTTP cookie.", + "properties": { + "name": {"type": "string", "description": "The name of the cookie."}, + "value": {"type": "string", "description": "The value of the cookie."}, + "domain": {"type": "string", "description": "The domain of the cookie (e.g. \"www.google.com\", \"example.com\")."}, + "hostOnly": {"type": "boolean", "description": "True if the cookie is a host-only cookie (i.e. a request's host must exactly match the domain of the cookie)."}, + "path": {"type": "string", "description": "The path of the cookie."}, + "secure": {"type": "boolean", "description": "True if the cookie is marked as Secure (i.e. its scope is limited to secure channels, typically HTTPS)."}, + "httpOnly": {"type": "boolean", "description": "True if the cookie is marked as HttpOnly (i.e. the cookie is inaccessible to client-side scripts)."}, + "session": {"type": "boolean", "description": "True if the cookie is a session cookie, as opposed to a persistent cookie with an expiration date."}, + "expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. Not provided for session cookies."}, + "storeId": {"type": "string", "description": "The ID of the cookie store containing this cookie, as provided in getAllCookieStores()."} + } + }, + { + "id": "CookieStore", + "type": "object", + "description": "Represents a cookie store in the browser. An incognito mode window, for instance, uses a separate cookie store from a non-incognito window.", + "properties": { + "id": {"type": "string", "description": "The unique identifier for the cookie store."}, + "tabIds": {"type": "array", "items": {"type": "integer"}, "description": "Identifiers of all the browser tabs that share this cookie store."} + } + }, + { + "id": "OnChangedCause", + "type": "string", + "enum": ["evicted", "expired", "explicit", "expired_overwrite", "overwrite"], + "description": "The underlying reason behind the cookie's change. If a cookie was inserted, or removed via an explicit call to $(ref:cookies.remove), \"cause\" will be \"explicit\". If a cookie was automatically removed due to expiry, \"cause\" will be \"expired\". If a cookie was removed due to being overwritten with an already-expired expiration date, \"cause\" will be set to \"expired_overwrite\". If a cookie was automatically removed due to garbage collection, \"cause\" will be \"evicted\". If a cookie was automatically removed due to a \"set\" call that overwrote it, \"cause\" will be \"overwrite\". Plan your response accordingly." + } + ], + "functions": [ + { + "name": "get", + "type": "function", + "description": "Retrieves information about a single cookie. If more than one cookie of the same name exists for the given URL, the one with the longest path will be returned. For cookies with the same path length, the cookie with the earliest creation time will be returned.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "details", + "description": "Details to identify the cookie being retrieved.", + "properties": { + "url": {"type": "string", "description": "The URL with which the cookie to retrieve is associated. This argument may be a full URL, in which case any data following the URL path (e.g. the query string) is simply ignored. If host permissions for this URL are not specified in the manifest file, the API call will fail."}, + "name": {"type": "string", "description": "The name of the cookie to retrieve."}, + "storeId": {"type": "string", "optional": true, "description": "The ID of the cookie store in which to look for the cookie. By default, the current execution context's cookie store will be used."} + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie. This parameter is null if no such cookie was found." + } + ] + } + ] + }, + { + "name": "getAll", + "type": "function", + "description": "Retrieves all cookies from a single cookie store that match the given information. The cookies returned will be sorted, with those with the longest path first. If multiple cookies have the same path length, those with the earliest creation time will be first.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "details", + "description": "Information to filter the cookies being retrieved.", + "properties": { + "url": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those that would match the given URL."}, + "name": {"type": "string", "optional": true, "description": "Filters the cookies by name."}, + "domain": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those whose domains match or are subdomains of this one."}, + "path": {"type": "string", "optional": true, "description": "Restricts the retrieved cookies to those whose path exactly matches this string."}, + "secure": {"type": "boolean", "optional": true, "description": "Filters the cookies by their Secure property."}, + "session": {"type": "boolean", "optional": true, "description": "Filters out session vs. persistent cookies."}, + "storeId": {"type": "string", "optional": true, "description": "The cookie store to retrieve cookies from. If omitted, the current execution context's cookie store will be used."} + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "cookies", "type": "array", "items": {"$ref": "Cookie"}, "description": "All the existing, unexpired cookies that match the given cookie info." + } + ] + } + ] + }, + { + "name": "set", + "type": "function", + "description": "Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "details", + "description": "Details about the cookie being set.", + "properties": { + "url": {"type": "string", "description": "The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail."}, + "name": {"type": "string", "optional": true, "description": "The name of the cookie. Empty by default if omitted."}, + "value": {"type": "string", "optional": true, "description": "The value of the cookie. Empty by default if omitted."}, + "domain": {"type": "string", "optional": true, "description": "The domain of the cookie. If omitted, the cookie becomes a host-only cookie."}, + "path": {"type": "string", "optional": true, "description": "The path of the cookie. Defaults to the path portion of the url parameter."}, + "secure": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as Secure. Defaults to false."}, + "httpOnly": {"type": "boolean", "optional": true, "description": "Whether the cookie should be marked as HttpOnly. Defaults to false."}, + "expirationDate": {"type": "number", "optional": true, "description": "The expiration date of the cookie as the number of seconds since the UNIX epoch. If omitted, the cookie becomes a session cookie."}, + "storeId": {"type": "string", "optional": true, "description": "The ID of the cookie store in which to set the cookie. By default, the cookie is set in the current execution context's cookie store."} + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie that's been set. If setting failed for any reason, this will be \"null\", and $(ref:runtime.lastError) will be set." + } + ] + } + ] + }, + { + "name": "remove", + "type": "function", + "description": "Deletes a cookie by name.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "details", + "description": "Information to identify the cookie to remove.", + "properties": { + "url": {"type": "string", "description": "The URL associated with the cookie. If host permissions for this URL are not specified in the manifest file, the API call will fail."}, + "name": {"type": "string", "description": "The name of the cookie to remove."}, + "storeId": {"type": "string", "optional": true, "description": "The ID of the cookie store to look in for the cookie. If unspecified, the cookie is looked for by default in the current execution context's cookie store."} + } + }, + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "details", + "type": "object", + "description": "Contains details about the cookie that's been removed. If removal failed for any reason, this will be \"null\", and $(ref:runtime.lastError) will be set.", + "optional": true, + "properties": { + "url": {"type": "string", "description": "The URL associated with the cookie that's been removed."}, + "name": {"type": "string", "description": "The name of the cookie that's been removed."}, + "storeId": {"type": "string", "description": "The ID of the cookie store from which the cookie was removed."} + } + } + ] + } + ] + }, + { + "name": "getAllCookieStores", + "type": "function", + "description": "Lists all existing cookie stores.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "cookieStores", "type": "array", "items": {"$ref": "CookieStore"}, "description": "All the existing cookie stores." + } + ] + } + ] + } + ], + "events": [ + { + "name": "onChanged", + "type": "function", + "description": "Fired when a cookie is set or removed. As a special case, note that updating a cookie's properties is implemented as a two step process: the cookie to be updated is first removed entirely, generating a notification with \"cause\" of \"overwrite\" . Afterwards, a new cookie is written with the updated values, generating a second notification with \"cause\" \"explicit\".", + "parameters": [ + { + "type": "object", + "name": "changeInfo", + "properties": { + "removed": {"type": "boolean", "description": "True if a cookie was removed."}, + "cookie": {"$ref": "Cookie", "description": "Information about the cookie that was set or removed."}, + "cause": {"$ref": "OnChangedCause", "description": "The underlying reason behind the cookie's change."} + } + } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/downloads.json b/toolkit/components/webextensions/schemas/downloads.json new file mode 100644 index 000000000..dcd43e4e1 --- /dev/null +++ b/toolkit/components/webextensions/schemas/downloads.json @@ -0,0 +1,793 @@ +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "downloads", + "downloads.open", + "downloads.shelf" + ] + }] + } + ] + }, + { + "namespace": "downloads", + "permissions": ["downloads"], + "types": [ + { + "id": "FilenameConflictAction", + "type": "string", + "enum": [ + "uniquify", + "overwrite", + "prompt" + ] + }, + { + "id": "InterruptReason", + "type": "string", + "enum": [ + "FILE_FAILED", + "FILE_ACCESS_DENIED", + "FILE_NO_SPACE", + "FILE_NAME_TOO_LONG", + "FILE_TOO_LARGE", + "FILE_VIRUS_INFECTED", + "FILE_TRANSIENT_ERROR", + "FILE_BLOCKED", + "FILE_SECURITY_CHECK_FAILED", + "FILE_TOO_SHORT", + "NETWORK_FAILED", + "NETWORK_TIMEOUT", + "NETWORK_DISCONNECTED", + "NETWORK_SERVER_DOWN", + "NETWORK_INVALID_REQUEST", + "SERVER_FAILED", + "SERVER_NO_RANGE", + "SERVER_BAD_CONTENT", + "SERVER_UNAUTHORIZED", + "SERVER_CERT_PROBLEM", + "SERVER_FORBIDDEN", + "USER_CANCELED", + "USER_SHUTDOWN", + "CRASH" + ] + }, + { + "id": "DangerType", + "type": "string", + "enum": [ + "file", + "url", + "content", + "uncommon", + "host", + "unwanted", + "safe", + "accepted" + ], + "description": "
file
The download's filename is suspicious.
url
The download's URL is known to be malicious.
content
The downloaded file is known to be malicious.
uncommon
The download's URL is not commonly downloaded and could be dangerous.
safe
The download presents no known danger to the user's computer.
These string constants will never change, however the set of DangerTypes may change." + }, + { + "id": "State", + "type": "string", + "enum": [ + "in_progress", + "interrupted", + "complete" + ], + "description": "
in_progress
The download is currently receiving data from the server.
interrupted
An error broke the connection with the file host.
complete
The download completed successfully.
These string constants will never change, however the set of States may change." + }, + { + "id": "DownloadItem", + "type": "object", + "properties": { + "id": { + "description": "An identifier that is persistent across browser sessions.", + "type": "integer" + }, + "url": { + "description": "Absolute URL.", + "type": "string" + }, + "referrer": { + "type": "string" + }, + "filename": { + "description": "Absolute local path.", + "type": "string" + }, + "incognito": { + "description": "False if this download is recorded in the history, true if it is not recorded.", + "type": "boolean" + }, + "danger": { + "$ref": "DangerType", + "description": "Indication of whether this download is thought to be safe or known to be suspicious." + }, + "mime": { + "description": "The file's MIME type.", + "type": "string" + }, + "startTime": { + "description": "Number of milliseconds between the unix epoch and when this download began.", + "type": "string" + }, + "endTime": { + "description": "Number of milliseconds between the unix epoch and when this download ended.", + "optional": true, + "type": "string" + }, + "estimatedEndTime": { + "type": "string", + "optional": true + }, + "state": { + "$ref": "State", + "description": "Indicates whether the download is progressing, interrupted, or complete." + }, + "paused": { + "description": "True if the download has stopped reading data from the host, but kept the connection open.", + "type": "boolean" + }, + "canResume": { + "type": "boolean" + }, + "error": { + "description": "Number indicating why a download was interrupted.", + "optional": true, + "$ref": "InterruptReason" + }, + "bytesReceived": { + "description": "Number of bytes received so far from the host, without considering file compression.", + "type": "number" + }, + "totalBytes": { + "description": "Number of bytes in the whole file, without considering file compression, or -1 if unknown.", + "type": "number" + }, + "fileSize": { + "description": "Number of bytes in the whole file post-decompression, or -1 if unknown.", + "type": "number" + }, + "exists": { + "type": "boolean" + }, + "byExtensionId": { + "type": "string", + "optional": true + }, + "byExtensionName": { + "type": "string", + "optional": true + } + } + }, + { + "id": "StringDelta", + "type": "object", + "properties": { + "current": { + "optional": true, + "type": "string" + }, + "previous": { + "optional": true, + "type": "string" + } + } + }, + { + "id": "DoubleDelta", + "type": "object", + "properties": { + "current": { + "optional": true, + "type": "number" + }, + "previous": { + "optional": true, + "type": "number" + } + } + }, + { + "id": "BooleanDelta", + "type": "object", + "properties": { + "current": { + "optional": true, + "type": "boolean" + }, + "previous": { + "optional": true, + "type": "boolean" + } + } + }, + { + "id": "DownloadTime", + "description": "A time specified as a Date object, a number or string representing milliseconds since the epoch, or an ISO 8601 string", + "choices": [ + { + "type": "string", + "pattern": "^[1-9]\\d*$" + }, + { + "$ref": "extensionTypes.Date" + } + ] + }, + { + "id": "DownloadQuery", + "description": "Parameters that combine to specify a predicate that can be used to select a set of downloads. Used for example in search() and erase()", + "type": "object", + "properties": { + "query": { + "description": "This array of search terms limits results to DownloadItems whose filename or url contain all of the search terms that do not begin with a dash '-' and none of the search terms that do begin with a dash.", + "optional": true, + "type": "array", + "items": { "type": "string" } + }, + "startedBefore": { + "description": "Limits results to downloads that started before the given ms since the epoch.", + "optional": true, + "$ref": "DownloadTime" + }, + "startedAfter": { + "description": "Limits results to downloads that started after the given ms since the epoch.", + "optional": true, + "$ref": "DownloadTime" + }, + "endedBefore": { + "description": "Limits results to downloads that ended before the given ms since the epoch.", + "optional": true, + "$ref": "DownloadTime" + }, + "endedAfter": { + "description": "Limits results to downloads that ended after the given ms since the epoch.", + "optional": true, + "$ref": "DownloadTime" + }, + "totalBytesGreater": { + "description": "Limits results to downloads whose totalBytes is greater than the given integer.", + "optional": true, + "type": "number" + }, + "totalBytesLess": { + "description": "Limits results to downloads whose totalBytes is less than the given integer.", + "optional": true, + "type": "number" + }, + "filenameRegex": { + "description": "Limits results to DownloadItems whose filename matches the given regular expression.", + "optional": true, + "type": "string" + }, + "urlRegex": { + "description": "Limits results to DownloadItems whose url matches the given regular expression.", + "optional": true, + "type": "string" + }, + "limit": { + "description": "Setting this integer limits the number of results. Otherwise, all matching DownloadItems will be returned.", + "optional": true, + "type": "integer" + }, + "orderBy": { + "description": "Setting elements of this array to DownloadItem properties in order to sort the search results. For example, setting orderBy='startTime' sorts the DownloadItems by their start time in ascending order. To specify descending order, prefix orderBy with a hyphen: '-startTime'.", + "optional": true, + "type": "array", + "items": { "type": "string" } + }, + "id": { + "type": "integer", + "optional": true + }, + "url": { + "description": "Absolute URL.", + "optional": true, + "type": "string" + }, + "filename": { + "description": "Absolute local path.", + "optional": true, + "type": "string" + }, + "danger": { + "$ref": "DangerType", + "description": "Indication of whether this download is thought to be safe or known to be suspicious.", + "optional": true + }, + "mime": { + "description": "The file's MIME type.", + "optional": true, + "type": "string" + }, + "startTime": { + "optional": true, + "type": "string" + }, + "endTime": { + "optional": true, + "type": "string" + }, + "state": { + "$ref": "State", + "description": "Indicates whether the download is progressing, interrupted, or complete.", + "optional": true + }, + "paused": { + "description": "True if the download has stopped reading data from the host, but kept the connection open.", + "optional": true, + "type": "boolean" + }, + "error": { + "description": "Why a download was interrupted.", + "optional": true, + "$ref": "InterruptReason" + }, + "bytesReceived": { + "description": "Number of bytes received so far from the host, without considering file compression.", + "optional": true, + "type": "number" + }, + "totalBytes": { + "description": "Number of bytes in the whole file, without considering file compression, or -1 if unknown.", + "optional": true, + "type": "number" + }, + "fileSize": { + "description": "Number of bytes in the whole file post-decompression, or -1 if unknown.", + "optional": true, + "type": "number" + }, + "exists": { + "type": "boolean", + "optional": true + } + } + } + ], + "functions": [ + { + "name": "download", + "type": "function", + "async": "callback", + "description": "Download a URL. If the URL uses the HTTP[S] protocol, then the request will include all cookies currently set for its hostname. If both filename and saveAs are specified, then the Save As dialog will be displayed, pre-populated with the specified filename. If the download started successfully, callback will be called with the new DownloadItem's downloadId. If there was an error starting the download, then callback will be called with downloadId=undefined and chrome.extension.lastError will contain a descriptive string. The error strings are not guaranteed to remain backwards compatible between releases. You must not parse it.", + "parameters": [ + { + "description": "What to download and how.", + "name": "options", + "type": "object", + "properties": { + "url": { + "description": "The URL to download.", + "type": "string", + "format": "url" + }, + "filename": { + "description": "A file path relative to the Downloads directory to contain the downloaded file.", + "optional": true, + "type": "string" + }, + "conflictAction": { + "$ref": "FilenameConflictAction", + "optional": true + }, + "saveAs": { + "description": "Use a file-chooser to allow the user to select a filename.", + "optional": true, + "type": "boolean" + }, + "method": { + "description": "The HTTP method to use if the URL uses the HTTP[S] protocol.", + "enum": [ + "GET", + "POST" + ], + "optional": true, + "type": "string" + }, + "headers": { + "optional": true, + "type": "array", + "description": "Extra HTTP headers to send with the request if the URL uses the HTTP[s] protocol. Each header is represented as a dictionary containing the keys name and either value or binaryValue, restricted to those allowed by XMLHttpRequest.", + "items": { + "type": "object", + "properties": { + "name": { + "description": "Name of the HTTP header.", + "type": "string" + }, + "value": { + "description": "Value of the HTTP header.", + "type": "string" + } + } + } + }, + "body": { + "description": "Post body.", + "optional": true, + "type": "string" + } + } + }, + { + "name": "callback", + "type": "function", + "optional": true, + "parameters": [ + { + "name": "downloadId", + "type": "integer" + } + ] + } + ] + }, + { + "name": "search", + "type": "function", + "async": "callback", + "description": "Find DownloadItems. Set query to the empty object to get all DownloadItems. To get a specific DownloadItem, set only the id field.", + "parameters": [ + { + "name": "query", + "$ref": "DownloadQuery" + }, + { + "name": "callback", + "type": "function", + "parameters": [ + { + "items": { + "$ref": "DownloadItem" + }, + "name": "results", + "type": "array" + } + ] + } + ] + }, + { + "name": "pause", + "type": "function", + "async": "callback", + "description": "Pause the download. If the request was successful the download is in a paused state. Otherwise chrome.extension.lastError contains an error message. The request will fail if the download is not active.", + "parameters": [ + { + "description": "The id of the download to pause.", + "name": "downloadId", + "type": "integer" + }, + { + "name": "callback", + "optional": true, + "parameters": [], + "type": "function" + } + ] + }, + { + "name": "resume", + "type": "function", + "async": "callback", + "description": "Resume a paused download. If the request was successful the download is in progress and unpaused. Otherwise chrome.extension.lastError contains an error message. The request will fail if the download is not active.", + "parameters": [ + { + "description": "The id of the download to resume.", + "name": "downloadId", + "type": "integer" + }, + { + "name": "callback", + "optional": true, + "parameters": [], + "type": "function" + } + ] + }, + { + "name": "cancel", + "type": "function", + "async": "callback", + "description": "Cancel a download. When callback is run, the download is cancelled, completed, interrupted or doesn't exist anymore.", + "parameters": [ + { + "description": "The id of the download to cancel.", + "name": "downloadId", + "type": "integer" + }, + { + "name": "callback", + "optional": true, + "parameters": [], + "type": "function" + } + ] + }, + { + "name": "getFileIcon", + "type": "function", + "async": "callback", + "description": "Retrieve an icon for the specified download. For new downloads, file icons are available after the onCreated event has been received. The image returned by this function while a download is in progress may be different from the image returned after the download is complete. Icon retrieval is done by querying the underlying operating system or toolkit depending on the platform. The icon that is returned will therefore depend on a number of factors including state of the download, platform, registered file types and visual theme. If a file icon cannot be determined, chrome.extension.lastError will contain an error message.", + "parameters": [ + { + "description": "The identifier for the download.", + "name": "downloadId", + "type": "integer" + }, + { + "name": "options", + "optional": true, + "properties": { + "size": { + "description": "The size of the icon. The returned icon will be square with dimensions size * size pixels. The default size for the icon is 32x32 pixels.", + "optional": true, + "minimum": 1, + "maximum": 127, + "type": "integer" + } + }, + "type": "object" + }, + { + "name": "callback", + "parameters": [ + { + "name": "iconURL", + "optional": true, + "type": "string" + } + ], + "type": "function" + } + ] + }, + { + "name": "open", + "type": "function", + "async": "callback", + "description": "Open the downloaded file.", + "permissions": ["downloads.open"], + "parameters": [ + { + "name": "downloadId", + "type": "integer" + }, + { + "name": "callback", + "type": "function", + "optional": true, + "parameters": [] + } + ] + }, + { + "name": "show", + "type": "function", + "description": "Show the downloaded file in its folder in a file manager.", + "async": "callback", + "parameters": [ + { + "name": "downloadId", + "type": "integer" + }, + { + "name": "callback", + "type": "function", + "optional": true, + "parameters": [ + { + "name": "success", + "type": "boolean" + } + ] + } + ] + }, + { + "name": "showDefaultFolder", + "type": "function", + "parameters": [] + }, + { + "name": "erase", + "type": "function", + "async": "callback", + "description": "Erase matching DownloadItems from history", + "parameters": [ + { + "name": "query", + "$ref": "DownloadQuery" + }, + { + "name": "callback", + "type": "function", + "optional": true, + "parameters": [ + { + "items": { + "type": "integer" + }, + "name": "erasedIds", + "type": "array" + } + ] + } + ] + }, + { + "name": "removeFile", + "async": "callback", + "type": "function", + "parameters": [ + { + "name": "downloadId", + "type": "integer" + }, + { + "name": "callback", + "type": "function", + "optional": true, + "parameters": [ ] + } + ] + }, + { + "description": "Prompt the user to either accept or cancel a dangerous download. acceptDanger() does not automatically accept dangerous downloads.", + "name": "acceptDanger", + "unsupported": true, + "parameters": [ + { + "name": "downloadId", + "type": "integer" + }, + { + "name": "callback", + "type": "function", + "optional": true, + "parameters": [ ] + } + ], + "type": "function" + }, + { + "description": "Initiate dragging the file to another application.", + "name": "drag", + "unsupported": true, + "parameters": [ + { + "name": "downloadId", + "type": "integer" + } + ], + "type": "function" + }, + { + "name": "setShelfEnabled", + "type": "function", + "unsupported": true, + "parameters": [ + { + "name": "enabled", + "type": "boolean" + } + ] + } + ], + "events": [ + { + "description": "This event fires with the DownloadItem object when a download begins.", + "name": "onCreated", + "parameters": [ + { + "$ref": "DownloadItem", + "name": "downloadItem" + } + ], + "type": "function" + }, + { + "description": "Fires with the downloadId when a download is erased from history.", + "name": "onErased", + "parameters": [ + { + "name": "downloadId", + "description": "The id of the DownloadItem that was erased.", + "type": "integer" + } + ], + "type": "function" + }, + { + "name": "onChanged", + "description": "When any of a DownloadItem's properties except bytesReceived changes, this event fires with the downloadId and an object containing the properties that changed.", + "parameters": [ + { + "name": "downloadDelta", + "type": "object", + "properties": { + "id": { + "description": "The id of the DownloadItem that changed.", + "type": "integer" + }, + "url": { + "description": "Describes a change in a DownloadItem's url.", + "optional": true, + "$ref": "StringDelta" + }, + "filename": { + "description": "Describes a change in a DownloadItem's filename.", + "optional": true, + "$ref": "StringDelta" + }, + "danger": { + "description": "Describes a change in a DownloadItem's danger.", + "optional": true, + "$ref": "StringDelta" + }, + "mime": { + "description": "Describes a change in a DownloadItem's mime.", + "optional": true, + "$ref": "StringDelta" + }, + "startTime": { + "description": "Describes a change in a DownloadItem's startTime.", + "optional": true, + "$ref": "StringDelta" + }, + "endTime": { + "description": "Describes a change in a DownloadItem's endTime.", + "optional": true, + "$ref": "StringDelta" + }, + "state": { + "description": "Describes a change in a DownloadItem's state.", + "optional": true, + "$ref": "StringDelta" + }, + "canResume": { + "optional": true, + "$ref": "BooleanDelta" + }, + "paused": { + "description": "Describes a change in a DownloadItem's paused.", + "optional": true, + "$ref": "BooleanDelta" + }, + "error": { + "description": "Describes a change in a DownloadItem's error.", + "optional": true, + "$ref": "StringDelta" + }, + "totalBytes": { + "description": "Describes a change in a DownloadItem's totalBytes.", + "optional": true, + "$ref": "DoubleDelta" + }, + "fileSize": { + "description": "Describes a change in a DownloadItem's fileSize.", + "optional": true, + "$ref": "DoubleDelta" + }, + "exists": { + "optional": true, + "$ref": "BooleanDelta" + } + } + } + ], + "type": "function" + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/events.json b/toolkit/components/webextensions/schemas/events.json new file mode 100644 index 000000000..ea3cbb5d2 --- /dev/null +++ b/toolkit/components/webextensions/schemas/events.json @@ -0,0 +1,322 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "events", + "description": "The chrome.events namespace contains common types used by APIs dispatching events to notify you when something interesting happens.", + "types": [ + { + "id": "Rule", + "type": "object", + "description": "Description of a declarative rule for handling events.", + "properties": { + "id": { + "type": "string", + "optional": true, + "description": "Optional identifier that allows referencing this rule." + }, + "tags": { + "type": "array", + "items": {"type": "string"}, + "optional": true, + "description": "Tags can be used to annotate rules and perform operations on sets of rules." + }, + "conditions": { + "type": "array", + "items": {"type": "any"}, + "description": "List of conditions that can trigger the actions." + }, + "actions": { + "type": "array", + "items": {"type": "any"}, + "description": "List of actions that are triggered if one of the condtions is fulfilled." + }, + "priority": { + "type": "integer", + "optional": true, + "description": "Optional priority of this rule. Defaults to 100." + } + } + }, + { + "id": "Event", + "type": "object", + "description": "An object which allows the addition and removal of listeners for a Chrome event.", + "functions": [ + { + "name": "addListener", + "type": "function", + "description": "Registers an event listener callback to an event.", + "parameters": [ + { + "name": "callback", + "type": "function", + "description": "Called when an event occurs. The parameters of this function depend on the type of event." + } + ] + }, + { + "name": "removeListener", + "type": "function", + "description": "Deregisters an event listener callback from an event.", + "parameters": [ + { + "name": "callback", + "type": "function", + "description": "Listener that shall be unregistered." + } + ] + }, + { + "name": "hasListener", + "type": "function", + "parameters": [ + { + "name": "callback", + "type": "function", + "description": "Listener whose registration status shall be tested." + } + ], + "returns": { + "type": "boolean", + "description": "True if callback is registered to the event." + } + }, + { + "name": "hasListeners", + "type": "function", + "parameters": [], + "returns": { + "type": "boolean", + "description": "True if any event listeners are registered to the event." + } + }, + { + "name": "addRules", + "unsupported": true, + "type": "function", + "description": "Registers rules to handle events.", + "parameters": [ + { + "name": "eventName", + "type": "string", + "description": "Name of the event this function affects." + }, + { + "name": "webViewInstanceId", + "type": "integer", + "description": "If provided, this is an integer that uniquely identfies the associated with this function call." + }, + { + "name": "rules", + "type": "array", + "items": {"$ref": "Rule"}, + "description": "Rules to be registered. These do not replace previously registered rules." + }, + { + "name": "callback", + "optional": true, + "type": "function", + "parameters": [ + { + "name": "rules", + "type": "array", + "items": {"$ref": "Rule"}, + "description": "Rules that were registered, the optional parameters are filled with values." + } + ], + "description": "Called with registered rules." + } + ] + }, + { + "name": "getRules", + "unsupported": true, + "type": "function", + "description": "Returns currently registered rules.", + "parameters": [ + { + "name": "eventName", + "type": "string", + "description": "Name of the event this function affects." + }, + { + "name": "webViewInstanceId", + "type": "integer", + "description": "If provided, this is an integer that uniquely identfies the associated with this function call." + }, + { + "name": "ruleIdentifiers", + "optional": true, + "type": "array", + "items": {"type": "string"}, + "description": "If an array is passed, only rules with identifiers contained in this array are returned." + }, + { + "name": "callback", + "type": "function", + "parameters": [ + { + "name": "rules", + "type": "array", + "items": {"$ref": "Rule"}, + "description": "Rules that were registered, the optional parameters are filled with values." + } + ], + "description": "Called with registered rules." + } + ] + }, + { + "name": "removeRules", + "unsupported": true, + "type": "function", + "description": "Unregisters currently registered rules.", + "parameters": [ + { + "name": "eventName", + "type": "string", + "description": "Name of the event this function affects." + }, + { + "name": "webViewInstanceId", + "type": "integer", + "description": "If provided, this is an integer that uniquely identfies the associated with this function call." + }, + { + "name": "ruleIdentifiers", + "optional": true, + "type": "array", + "items": {"type": "string"}, + "description": "If an array is passed, only rules with identifiers contained in this array are unregistered." + }, + { + "name": "callback", + "optional": true, + "type": "function", + "parameters": [], + "description": "Called when rules were unregistered." + } + ] + } + ] + }, + { + "id": "UrlFilter", + "type": "object", + "description": "Filters URLs for various criteria. See event filtering. All criteria are case sensitive.", + "properties": { + "hostContains": { + "type": "string", + "description": "Matches if the host name of the URL contains a specified string. To test whether a host name component has a prefix 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot is added at the beginning of the host name. Similarly, hostContains can be used to match against component suffix ('foo.') and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last components need to be done separately using hostSuffix, because no implicit dot is added at the end of the host name.", + "optional": true + }, + "hostEquals": { + "type": "string", + "description": "Matches if the host name of the URL is equal to a specified string.", + "optional": true + }, + "hostPrefix": { + "type": "string", + "description": "Matches if the host name of the URL starts with a specified string.", + "optional": true + }, + "hostSuffix": { + "type": "string", + "description": "Matches if the host name of the URL ends with a specified string.", + "optional": true + }, + "pathContains": { + "type": "string", + "description": "Matches if the path segment of the URL contains a specified string.", + "optional": true + }, + "pathEquals": { + "type": "string", + "description": "Matches if the path segment of the URL is equal to a specified string.", + "optional": true + }, + "pathPrefix": { + "type": "string", + "description": "Matches if the path segment of the URL starts with a specified string.", + "optional": true + }, + "pathSuffix": { + "type": "string", + "description": "Matches if the path segment of the URL ends with a specified string.", + "optional": true + }, + "queryContains": { + "type": "string", + "description": "Matches if the query segment of the URL contains a specified string.", + "optional": true + }, + "queryEquals": { + "type": "string", + "description": "Matches if the query segment of the URL is equal to a specified string.", + "optional": true + }, + "queryPrefix": { + "type": "string", + "description": "Matches if the query segment of the URL starts with a specified string.", + "optional": true + }, + "querySuffix": { + "type": "string", + "description": "Matches if the query segment of the URL ends with a specified string.", + "optional": true + }, + "urlContains": { + "type": "string", + "description": "Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number.", + "optional": true + }, + "urlEquals": { + "type": "string", + "description": "Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number.", + "optional": true + }, + "urlMatches": { + "type": "string", + "description": "Matches if the URL (without fragment identifier) matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax.", + "optional": true + }, + "originAndPathMatches": { + "type": "string", + "description": "Matches if the URL without query segment and fragment identifier matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax.", + "optional": true + }, + "urlPrefix": { + "type": "string", + "description": "Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number.", + "optional": true + }, + "urlSuffix": { + "type": "string", + "description": "Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number.", + "optional": true + }, + "schemes": { + "type": "array", + "description": "Matches if the scheme of the URL is equal to any of the schemes specified in the array.", + "optional": true, + "items": { "type": "string" } + }, + "ports": { + "type": "array", + "description": "Matches if the port of the URL is contained in any of the specified port lists. For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200.", + "optional": true, + "items": { + "choices": [ + {"type": "integer", "description": "A specific port."}, + {"type": "array", "minItems": 2, "maxItems": 2, "items": {"type": "integer"}, "description": "A pair of integers identiying the start and end (both inclusive) of a port range."} + ] + } + } + } + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/experiments.json b/toolkit/components/webextensions/schemas/experiments.json new file mode 100644 index 000000000..c687173a9 --- /dev/null +++ b/toolkit/components/webextensions/schemas/experiments.json @@ -0,0 +1,16 @@ +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [ + { + "type": "string", + "pattern": "^experiments(\\.\\w+)+$" + } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/extension.json b/toolkit/components/webextensions/schemas/extension.json new file mode 100644 index 000000000..5a1b6c935 --- /dev/null +++ b/toolkit/components/webextensions/schemas/extension.json @@ -0,0 +1,178 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "extension", + "allowedContexts": ["content"], + "description": "The browser.extension API has utilities that can be used by any extension page. It includes support for exchanging messages between an extension and its content scripts or between extensions, as described in detail in $(topic:messaging)[Message Passing].", + "properties": { + "lastError": { + "type": "object", + "optional": true, + "allowedContexts": ["content"], + "description": "Set for the lifetime of a callback if an ansychronous extension api has resulted in an error. If no error has occured lastError will be undefined.", + "properties": { + "message": { "type": "string", "description": "Description of the error that has taken place." } + }, + "additionalProperties": { + "type": "any" + } + }, + "inIncognitoContext": { + "type": "boolean", + "optional": true, + "allowedContexts": ["content"], + "description": "True for content scripts running inside incognito tabs, and for extension pages running inside an incognito process. The latter only applies to extensions with 'split' incognito_behavior." + } + }, + "types": [ + { + "id": "ViewType", + "type": "string", + "enum": ["tab", "notification", "popup"], + "description": "The type of extension view." + } + ], + "functions": [ + { + "name": "getURL", + "type": "function", + "allowedContexts": ["content"], + "description": "Converts a relative path within an extension install directory to a fully-qualified URL.", + "parameters": [ + { + "type": "string", + "name": "path", + "description": "A path to a resource within an extension expressed relative to its install directory." + } + ], + "returns": { + "type": "string", + "description": "The fully-qualified URL to the resource." + } + }, + { + "name": "getViews", + "type": "function", + "description": "Returns an array of the JavaScript 'window' objects for each of the pages running inside the current extension.", + "parameters": [ + { + "type": "object", + "name": "fetchProperties", + "optional": true, + "properties": { + "type": { + "$ref": "ViewType", + "optional": true, + "description": "The type of view to get. If omitted, returns all views (including background pages and tabs). Valid values: 'tab', 'notification', 'popup'." + }, + "windowId": { + "type": "integer", + "optional": true, + "description": "The window to restrict the search to. If omitted, returns all views." + } + } + } + ], + "returns": { + "type": "array", + "description": "Array of global objects", + "items": { + "name": "viewGlobals", + "type": "object", + "isInstanceOf": "Window", + "additionalProperties": { "type": "any" } + } + } + }, + { + "name": "getBackgroundPage", + "type": "function", + "description": "Returns the JavaScript 'window' object for the background page running inside the current extension. Returns null if the extension has no background page.", + "parameters": [], + "returns": { + "type": "object", + "optional": true, + "name": "backgroundPageGlobal", + "isInstanceOf": "Window", + "additionalProperties": { "type": "any" } + } + }, + { + "name": "isAllowedIncognitoAccess", + "type": "function", + "description": "Retrieves the state of the extension's access to Incognito-mode (as determined by the user-controlled 'Allowed in Incognito' checkbox.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "isAllowedAccess", + "type": "boolean", + "description": "True if the extension has access to Incognito mode, false otherwise." + } + ] + } + ] + }, + { + "name": "isAllowedFileSchemeAccess", + "type": "function", + "description": "Retrieves the state of the extension's access to the 'file://' scheme (as determined by the user-controlled 'Allow access to File URLs' checkbox.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "isAllowedAccess", + "type": "boolean", + "description": "True if the extension can access the 'file://' scheme, false otherwise." + } + ] + } + ] + }, + { + "name": "setUpdateUrlData", + "unsupported": true, + "type": "function", + "description": "Sets the value of the ap CGI parameter used in the extension's update URL. This value is ignored for extensions that are hosted in the browser vendor's store.", + "parameters": [ + {"type": "string", "name": "data", "maxLength": 1024} + ] + } + ], + "events": [ + { + "name": "onRequest", + "unsupported": true, + "deprecated": "Please use $(ref:runtime.onMessage).", + "type": "function", + "description": "Fired when a request is sent from either an extension process or a content script.", + "parameters": [ + {"name": "request", "type": "any", "optional": true, "description": "The request sent by the calling script."}, + {"name": "sender", "$ref": "runtime.MessageSender" }, + {"name": "sendResponse", "type": "function", "description": "Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. If you have more than one onRequest listener in the same document, then only one may send a response." } + ] + }, + { + "name": "onRequestExternal", + "unsupported": true, + "deprecated": "Please use $(ref:runtime.onMessageExternal).", + "type": "function", + "description": "Fired when a request is sent from another extension.", + "parameters": [ + {"name": "request", "type": "any", "optional": true, "description": "The request sent by the calling script."}, + {"name": "sender", "$ref": "runtime.MessageSender" }, + {"name": "sendResponse", "type": "function", "description": "Function to call when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response." } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/extension_types.json b/toolkit/components/webextensions/schemas/extension_types.json new file mode 100644 index 000000000..1a88e4e60 --- /dev/null +++ b/toolkit/components/webextensions/schemas/extension_types.json @@ -0,0 +1,83 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "extensionTypes", + "description": "The browser.extensionTypes API contains type declarations for WebExtensions.", + "types": [ + { + "id": "ImageFormat", + "type": "string", + "enum": ["jpeg", "png"], + "description": "The format of an image." + }, + { + "id": "ImageDetails", + "type": "object", + "description": "Details about the format and quality of an image.", + "properties": { + "format": { + "$ref": "ImageFormat", + "optional": true, + "description": "The format of the resulting image. Default is \"jpeg\"." + }, + "quality": { + "type": "integer", + "optional": true, + "minimum": 0, + "maximum": 100, + "description": "When format is \"jpeg\", controls the quality of the resulting image. This value is ignored for PNG images. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease." + } + } + }, + { + "id": "RunAt", + "type": "string", + "enum": ["document_start", "document_end", "document_idle"], + "description": "The soonest that the JavaScript or CSS will be injected into the tab." + }, + { + "id": "InjectDetails", + "type": "object", + "description": "Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time.", + "properties": { + "code": {"type": "string", "optional": true, "description": "JavaScript or CSS code to inject.

Warning:
Be careful using the code parameter. Incorrect use of it may open your extension to cross site scripting attacks."}, + "file": {"type": "string", "optional": true, "description": "JavaScript or CSS file to inject."}, + "allFrames": {"type": "boolean", "optional": true, "description": "If allFrames is true, implies that the JavaScript or CSS should be injected into all frames of current page. By default, it's false and is only injected into the top frame."}, + "matchAboutBlank": {"type": "boolean", "optional": true, "description": "If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is false."}, + "frameId": { + "type": "integer", + "minimum": 0, + "optional": true, + "description": "The ID of the frame to inject the script into. This may not be used in combination with allFrames." + }, + "runAt": { + "$ref": "RunAt", + "optional": true, + "description": "The soonest that the JavaScript or CSS will be injected into the tab. Defaults to \"document_idle\"." + } + } + }, + { + "id": "Date", + "choices": [ + { + "type": "string", + "format": "date" + }, + { + "type": "integer", + "minimum": 0 + }, + { + "type": "object", + "isInstanceOf": "Date", + "additionalProperties": { "type": "any" } + } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/i18n.json b/toolkit/components/webextensions/schemas/i18n.json new file mode 100644 index 000000000..12dc45dfc --- /dev/null +++ b/toolkit/components/webextensions/schemas/i18n.json @@ -0,0 +1,132 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "WebExtensionManifest", + "properties": { + "default_locale": { + "type": "string", + "optional": "true" + } + } + } + ] + }, + { + "namespace": "i18n", + "allowedContexts": ["content"], + "defaultContexts": ["content"], + "description": "Use the browser.i18n infrastructure to implement internationalization across your whole app or extension.", + "types": [ + { + "id": "LanguageCode", + "type": "string", + "description": "An ISO language code such as en or fr. For a complete list of languages supported by this method, see kLanguageInfoTable. For an unknown language, und will be returned, which means that [percentage] of the text is unknown to CLD" + } + ], + "functions": [ + { + "name": "getAcceptLanguages", + "type": "function", + "description": "Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the locale, use $(ref:i18n.getUILanguage).", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + {"name": "languages", "type": "array", "items": {"$ref": "LanguageCode"}, "description": "Array of LanguageCode"} + ] + } + ] + }, + { + "name": "getMessage", + "type": "function", + "description": "Gets the localized string for the specified message. If the message is missing, this method returns an empty string (''). If the format of the getMessage() call is wrong — for example, messageName is not a string or the substitutions array has more than 9 elements — this method returns undefined.", + "parameters": [ + { + "type": "string", + "name": "messageName", + "description": "The name of the message, as specified in the $(topic:i18n-messages)[messages.json] file." + }, + { + "type": "any", + "name": "substitutions", + "optional": true, + "description": "Substitution strings, if the message requires any." + } + ], + "returns": { + "type": "string", + "description": "Message localized for current locale." + } + }, + { + "name": "getUILanguage", + "type": "function", + "description": "Gets the browser UI language of the browser. This is different from $(ref:i18n.getAcceptLanguages) which returns the preferred user languages.", + "parameters": [], + "returns": { + "type": "string", + "description": "The browser UI language code such as en-US or fr-FR." + } + }, + { + "name": "detectLanguage", + "type": "function", + "description": "Detects the language of the provided text using CLD.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "text", + "description": "User input string to be translated." + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "type": "object", + "name": "result", + "description": "LanguageDetectionResult object that holds detected langugae reliability and array of DetectedLanguage", + "properties": { + "isReliable": { "type": "boolean", "description": "CLD detected language reliability" }, + "languages": + { + "type": "array", + "description": "array of detectedLanguage", + "items": + { + "type": "object", + "description": "DetectedLanguage object that holds detected ISO language code and its percentage in the input string", + "properties": + { + "language": + { + "$ref": "LanguageCode" + }, + "percentage": + { + "type": "integer", + "description": "The percentage of the detected language" + } + } + } + } + } + } + ] + } + ] + } + ], + "events": [] + } +] diff --git a/toolkit/components/webextensions/schemas/idle.json b/toolkit/components/webextensions/schemas/idle.json new file mode 100644 index 000000000..e0b3b951e --- /dev/null +++ b/toolkit/components/webextensions/schemas/idle.json @@ -0,0 +1,70 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "idle", + "description": "Use the browser.idle API to detect when the machine's idle state changes.", + "permissions": ["idle"], + "types": [ + { + "id": "IdleState", + "type": "string", + "enum": ["active", "idle"] + } + ], + "functions": [ + { + "name": "queryState", + "type": "function", + "description": "Returns \"idle\" if the user has not generated any input for a specified number of seconds, or \"active\" otherwise.", + "async": "callback", + "parameters": [ + { + "name": "detectionIntervalInSeconds", + "type": "integer", + "minimum": 15, + "description": "The system is considered idle if detectionIntervalInSeconds seconds have elapsed since the last user input detected." + }, + { + "name": "callback", + "type": "function", + "parameters": [ + { + "name": "newState", + "$ref": "IdleState" + } + ] + } + ] + }, + { + "name": "setDetectionInterval", + "type": "function", + "description": "Sets the interval, in seconds, used to determine when the system is in an idle state for onStateChanged events. The default interval is 60 seconds.", + "parameters": [ + { + "name": "intervalInSeconds", + "type": "integer", + "minimum": 15, + "description": "Threshold, in seconds, used to determine when the system is in an idle state." + } + ] + } + ], + "events": [ + { + "name": "onStateChanged", + "type": "function", + "description": "Fired when the system changes to an active or idle state. The event fires with \"idle\" if the the user has not generated any input for a specified number of seconds, and \"active\" when the user generates input on an idle system.", + "parameters": [ + { + "name": "newState", + "$ref": "IdleState" + } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/jar.mn b/toolkit/components/webextensions/schemas/jar.mn new file mode 100644 index 000000000..0bdf35b0d --- /dev/null +++ b/toolkit/components/webextensions/schemas/jar.mn @@ -0,0 +1,25 @@ +# 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/. + +toolkit.jar: +% content extensions %content/extensions/ + content/extensions/schemas/alarms.json + content/extensions/schemas/cookies.json + content/extensions/schemas/downloads.json + content/extensions/schemas/events.json + content/extensions/schemas/experiments.json + content/extensions/schemas/extension.json + content/extensions/schemas/extension_types.json + content/extensions/schemas/i18n.json + content/extensions/schemas/idle.json + content/extensions/schemas/management.json + content/extensions/schemas/manifest.json + content/extensions/schemas/native_host_manifest.json + content/extensions/schemas/notifications.json + content/extensions/schemas/runtime.json + content/extensions/schemas/storage.json + content/extensions/schemas/test.json + content/extensions/schemas/top_sites.json + content/extensions/schemas/web_navigation.json + content/extensions/schemas/web_request.json diff --git a/toolkit/components/webextensions/schemas/management.json b/toolkit/components/webextensions/schemas/management.json new file mode 100644 index 000000000..413ff1d0d --- /dev/null +++ b/toolkit/components/webextensions/schemas/management.json @@ -0,0 +1,250 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "management" + ] + }] + } + ] + }, + { + "namespace":"management", + "description": "The browser.management API provides ways to manage the list of extensions that are installed and running.", + "types": [ + { + "id": "IconInfo", + "description": "Information about an icon belonging to an extension.", + "type": "object", + "properties": { + "size": { + "type": "integer", + "description": "A number representing the width and height of the icon. Likely values include (but are not limited to) 128, 48, 24, and 16." + }, + "url": { + "type": "string", + "description": "The URL for this icon image. To display a grayscale version of the icon (to indicate that an extension is disabled, for example), append ?grayscale=true to the URL." + } + } + }, + { + "id": "ExtensionDisabledReason", + "description": "A reason the item is disabled.", + "type": "string", + "enum": ["unknown", "permissions_increase"] + }, + { + "id": "ExtensionType", + "description": "The type of this extension. Will always be 'extension'.", + "type": "string", + "enum": ["extension"] + }, + { + "id": "ExtensionInstallType", + "description": "How the extension was installed. One of
development: The extension was loaded unpacked in developer mode,
normal: The extension was installed normally via an .xpi file,
sideload: The extension was installed by other software on the machine,
other: The extension was installed by other means.", + "type": "string", + "enum": ["development", "normal", "sideload", "other"] + }, + { + "id": "ExtensionInfo", + "description": "Information about an installed extension.", + "type": "object", + "properties": { + "id": { + "description": "The extension's unique identifier.", + "type": "string" + }, + "name": { + "description": "The name of this extension.", + "type": "string" + }, + "shortName": { + "description": "A short version of the name of this extension.", + "type": "string" + }, + "description": { + "description": "The description of this extension.", + "type": "string" + }, + "version": { + "description": "The version of this extension.", + "type": "string" + }, + "versionName": { + "description": "The version name of this extension if the manifest specified one.", + "type": "string", + "optional": true + }, + "mayDisable": { + "description": "Whether this extension can be disabled or uninstalled by the user.", + "type": "boolean" + }, + "enabled": { + "description": "Whether it is currently enabled or disabled.", + "type": "boolean" + }, + "disabledReason": { + "description": "A reason the item is disabled.", + "$ref": "ExtensionDisabledReason", + "optional": true + }, + "type": { + "description": "The type of this extension. Will always return 'extension'.", + "$ref": "ExtensionType" + }, + "homepageUrl": { + "description": "The URL of the homepage of this extension.", + "type": "string", + "optional": true + }, + "updateUrl": { + "description": "The update URL of this extension.", + "type": "string", + "optional": true + }, + "optionsUrl": { + "description": "The url for the item's options page, if it has one.", + "type": "string" + }, + "icons": { + "description": "A list of icon information. Note that this just reflects what was declared in the manifest, and the actual image at that url may be larger or smaller than what was declared, so you might consider using explicit width and height attributes on img tags referencing these images. See the manifest documentation on icons for more details.", + "type": "array", + "optional": true, + "items": { + "$ref": "IconInfo" + } + }, + "permissions": { + "description": "Returns a list of API based permissions.", + "type": "array", + "items" : { + "type": "string" + } + }, + "hostPermissions": { + "description": "Returns a list of host based permissions.", + "type": "array", + "items" : { + "type": "string" + } + }, + "installType": { + "description": "How the extension was installed.", + "$ref": "ExtensionInstallType" + } + } + } + ], + "functions": [ + { + "name": "getAll", + "type": "function", + "permissions": ["management"], + "unsupported": true, + "description": "Returns a list of information about installed extensions.", + "async": "callback", + "parameters": [ + { + "name": "callback", + "type": "function", + "optional": true, + "parameters": [ + { + "type": "array", + "name": "result", + "items": { + "$ref": "ExtensionInfo" + } + } + ] + } + ] + }, + { + "name": "get", + "type": "function", + "permissions": ["management"], + "unsupported": true, + "description": "Returns information about the installed extension that has the given ID.", + "async": "callback", + "parameters": [ + { + "name": "id", + "$ref": "manifest.ExtensionID", + "description": "The ID from an item of $(ref:management.ExtensionInfo)." + }, + { + "name": "callback", + "type": "function", + "optional": true, + "parameters": [ + { + "name": "result", + "$ref": "ExtensionInfo" + } + ] + } + ] + }, + { + "name": "getSelf", + "type": "function", + "description": "Returns information about the calling extension. Note: This function can be used without requesting the 'management' permission in the manifest.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [ + { + "name": "result", + "$ref": "ExtensionInfo" + } + ] + } + ] + }, + { + "name": "uninstallSelf", + "type": "function", + "description": "Uninstalls the calling extension. Note: This function can be used without requesting the 'management' permission in the manifest.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "options", + "optional": true, + "properties": { + "showConfirmDialog": { + "type": "boolean", + "optional": true, + "description": "Whether or not a confirm-uninstall dialog should prompt the user. Defaults to false." + }, + "dialogMessage": { + "type": "string", + "optional": true, + "description": "The message to display to a user when being asked to confirm removal of the extension." + } + } + }, + { + "name": "callback", + "type": "function", + "optional": true, + "parameters": [] + } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/manifest.json b/toolkit/components/webextensions/schemas/manifest.json new file mode 100644 index 000000000..09e6b56fb --- /dev/null +++ b/toolkit/components/webextensions/schemas/manifest.json @@ -0,0 +1,377 @@ +[ + { + "namespace": "manifest", + "types": [ + { + "id": "WebExtensionManifest", + "type": "object", + "description": "Represents a WebExtension manifest.json file", + "properties": { + "manifest_version": { + "type": "integer", + "minimum": 2, + "maximum": 2 + }, + + "minimum_chrome_version":{ + "type": "string", + "optional": true + }, + + "applications": { + "type": "object", + "optional": true, + "properties": { + "gecko": { + "$ref": "FirefoxSpecificProperties", + "optional": true + } + } + }, + + "browser_specific_settings": { + "type": "object", + "optional": true, + "properties": { + "gecko": { + "$ref": "FirefoxSpecificProperties", + "optional": true + } + } + }, + + "name": { + "type": "string", + "optional": false, + "preprocess": "localize" + }, + + "short_name": { + "type": "string", + "optional": true, + "preprocess": "localize" + }, + + "description": { + "type": "string", + "optional": true, + "preprocess": "localize" + }, + + "author": { + "type": "string", + "optional": true, + "preprocess": "localize", + "onError": "warn" + }, + + "version": { + "type": "string", + "optional": false + }, + + "homepage_url": { + "type": "string", + "format": "url", + "optional": true, + "preprocess": "localize" + }, + + "icons": { + "type": "object", + "optional": true, + "patternProperties": { + "^[1-9]\\d*$": { "type": "string" } + } + }, + + "incognito": { + "type": "string", + "enum": ["spanning"], + "optional": true, + "onError": "warn" + }, + + "background": { + "choices": [ + { + "type": "object", + "properties": { + "page": { "$ref": "ExtensionURL" }, + "persistent": { + "optional": true, + "$ref": "PersistentBackgroundProperty" + } + }, + "additionalProperties": { "$ref": "UnrecognizedProperty" } + }, + { + "type": "object", + "properties": { + "scripts": { + "type": "array", + "items": { "$ref": "ExtensionURL" } + }, + "persistent": { + "optional": true, + "$ref": "PersistentBackgroundProperty" + } + }, + "additionalProperties": { "$ref": "UnrecognizedProperty" } + } + ], + "optional": true + }, + + "options_ui": { + "type": "object", + + "optional": true, + + "properties": { + "page": { "$ref": "ExtensionURL" }, + "browser_style": { + "type": "boolean", + "optional": true + }, + "chrome_style": { + "type": "boolean", + "optional": true + }, + "open_in_tab": { + "type": "boolean", + "optional": true + } + }, + + "additionalProperties": { + "type": "any", + "deprecated": "An unexpected property was found in the WebExtension manifest" + } + }, + + "content_scripts": { + "type": "array", + "optional": true, + "items": { "$ref": "ContentScript" } + }, + + "content_security_policy": { + "type": "string", + "optional": true, + "format": "contentSecurityPolicy", + "onError": "warn" + }, + + "permissions": { + "type": "array", + "items": { + "choices": [ + { "$ref": "Permission" }, + { + "type": "string", + "deprecated": "Unknown permission ${value}" + } + ] + }, + "optional": true + }, + + "web_accessible_resources": { + "type": "array", + "items": { "type": "string" }, + "optional": true + }, + + "developer": { + "type": "object", + "optional": true, + "properties": { + "name": { + "type": "string", + "optional": true, + "preprocess": "localize" + }, + "url": { + "type": "string", + "optional": true, + "preprocess": "localize" + } + } + } + + }, + + "additionalProperties": { "$ref": "UnrecognizedProperty" } + }, + { + "id": "Permission", + "choices": [ + { + "type": "string", + "enum": [ + "alarms", + "clipboardWrite", + "idle", + "notifications", + "storage" + ] + }, + { "$ref": "MatchPattern" } + ] + }, + { + "id": "ExtensionURL", + "type": "string", + "format": "strictRelativeUrl" + }, + { + "id": "ExtensionID", + "choices": [ + { + "type": "string", + "pattern": "(?i)^\\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\}$" + }, + { + "type": "string", + "pattern": "(?i)^[a-z0-9-._]*@[a-z0-9-._]+$" + } + ] + }, + { + "id": "FirefoxSpecificProperties", + "type": "object", + "properties": { + "id": { + "$ref": "ExtensionID", + "optional": true + }, + + "update_url": { + "type": "string", + "format": "url", + "optional": true + }, + + "strict_min_version": { + "type": "string", + "optional": true + }, + + "strict_max_version": { + "type": "string", + "optional": true + } + } + }, + { + "id": "MatchPattern", + "choices": [ + { + "type": "string", + "enum": [""] + }, + { + "type": "string", + "pattern": "^(https?|file|ftp|\\*)://(\\*|\\*\\.[^*/]+|[^*/]+)/.*$" + }, + { + "type": "string", + "pattern": "^file:///.*$" + } + ] + }, + { + "id": "ContentScript", + "type": "object", + "description": "Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. Based on InjectDetails, but using underscore rather than camel case naming conventions.", + "additionalProperties": { "$ref": "UnrecognizedProperty" }, + "properties": { + "matches": { + "type": "array", + "optional": false, + "minItems": 1, + "items": { "$ref": "MatchPattern" } + }, + "exclude_matches": { + "type": "array", + "optional": true, + "minItems": 1, + "items": { "$ref": "MatchPattern" } + }, + "include_globs": { + "type": "array", + "optional": true, + "items": { "type": "string" } + }, + "exclude_globs": { + "type": "array", + "optional": true, + "items": { "type": "string" } + }, + "css": { + "type": "array", + "optional": true, + "description": "The list of CSS files to inject", + "items": { "$ref": "ExtensionURL" } + }, + "js": { + "type": "array", + "optional": true, + "description": "The list of CSS files to inject", + "items": { "$ref": "ExtensionURL" } + }, + "all_frames": {"type": "boolean", "optional": true, "description": "If allFrames is true, implies that the JavaScript or CSS should be injected into all frames of current page. By default, it's false and is only injected into the top frame."}, + "match_about_blank": {"type": "boolean", "optional": true, "description": "If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is false."}, + "run_at": { + "$ref": "extensionTypes.RunAt", + "optional": true, + "description": "The soonest that the JavaScript or CSS will be injected into the tab. Defaults to \"document_idle\"." + } + } + }, + { + "id": "IconPath", + "choices": [ + { + "type": "object", + "patternProperties": { + "^[1-9]\\d*$": { "$ref": "ExtensionURL" } + }, + "additionalProperties": false + }, + { "$ref": "ExtensionURL" } + ] + }, + { + "id": "IconImageData", + "choices": [ + { + "type": "object", + "patternProperties": { + "^[1-9]\\d*$": { "$ref": "ImageData" } + }, + "additionalProperties": false + }, + { "$ref": "ImageData" } + ] + }, + { + "id": "ImageData", + "type": "object", + "isInstanceOf": "ImageData", + "postprocess": "convertImageDataToURL" + }, + { + "id": "UnrecognizedProperty", + "type": "any", + "deprecated": "An unexpected property was found in the WebExtension manifest." + }, + { + "id": "PersistentBackgroundProperty", + "type": "boolean", + "deprecated": "Event pages are not currently supported. This will run as a persistent background page." + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/moz.build b/toolkit/components/webextensions/schemas/moz.build new file mode 100644 index 000000000..aac3a838c --- /dev/null +++ b/toolkit/components/webextensions/schemas/moz.build @@ -0,0 +1,7 @@ +# -*- 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/. + +JAR_MANIFESTS += ['jar.mn'] diff --git a/toolkit/components/webextensions/schemas/native_host_manifest.json b/toolkit/components/webextensions/schemas/native_host_manifest.json new file mode 100644 index 000000000..4ad2ea7f1 --- /dev/null +++ b/toolkit/components/webextensions/schemas/native_host_manifest.json @@ -0,0 +1,37 @@ +[ + { + "namespace": "manifest", + "types": [ + { + "id": "NativeHostManifest", + "type": "object", + "description": "Represents a native host manifest file", + "properties": { + "name": { + "type": "string", + "pattern": "^\\w+(\\.\\w+)*$" + }, + "description": { + "type": "string" + }, + "path": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "stdio" + ] + }, + "allowed_extensions": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "manifest.ExtensionID" + } + } + } + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/notifications.json b/toolkit/components/webextensions/schemas/notifications.json new file mode 100644 index 000000000..12878e8c8 --- /dev/null +++ b/toolkit/components/webextensions/schemas/notifications.json @@ -0,0 +1,416 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "notifications", + "permissions": ["notifications"], + "types": [ + { + "id": "TemplateType", + "type": "string", + "enum": [ + "basic", + "image", + "list", + "progress" + ] + }, + { + "id": "PermissionLevel", + "type": "string", + "enum": [ + "granted", + "denied" + ] + }, + { + "id": "NotificationItem", + "type": "object", + "properties": { + "title": { + "description": "Title of one item of a list notification.", + "type": "string" + }, + "message": { + "description": "Additional details about this item.", + "type": "string" + } + } + }, + { + "id": "CreateNotificationOptions", + "type": "object", + "properties": { + "type": { + "description": "Which type of notification to display.", + "$ref": "TemplateType" + }, + "iconUrl": { + "optional": true, + "description": "A URL to the sender's avatar, app icon, or a thumbnail for image notifications.", + "type": "string" + }, + "appIconMaskUrl": { + "optional": true, + "description": "A URL to the app icon mask.", + "type": "string" + }, + "title": { + "description": "Title of the notification (e.g. sender name for email).", + "type": "string" + }, + "message": { + "description": "Main notification content.", + "type": "string" + }, + "contextMessage": { + "optional": true, + "description": "Alternate notification content with a lower-weight font.", + "type": "string" + }, + "priority": { + "optional": true, + "description": "Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default.", + "type": "integer", + "minimum": -2, + "maximum": 2 + }, + "eventTime": { + "optional": true, + "description": "A timestamp associated with the notification, in milliseconds past the epoch.", + "type": "number" + }, + "buttons": { + "unsupported": true, + "optional": true, + "description": "Text and icons for up to two notification action buttons.", + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "iconUrl": { + "optional": true, + "type": "string" + } + } + } + }, + "imageUrl": { + "optional": true, + "description": "A URL to the image thumbnail for image-type notifications.", + "type": "string" + }, + "items": { + "optional": true, + "description": "Items for multi-item notifications.", + "type": "array", + "items": { "$ref": "NotificationItem" } + }, + "progress": { + "optional": true, + "description": "Current progress ranges from 0 to 100.", + "type": "integer", + "minimum": 0, + "maximum": 100 + }, + "isClickable": { + "optional": true, + "description": "Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification.", + "type": "boolean" + } + } + }, + { + "id": "UpdateNotificationOptions", + "type": "object", + "properties": { + "type": { + "optional": true, + "description": "Which type of notification to display.", + "$ref": "TemplateType" + }, + "iconUrl": { + "optional": true, + "description": "A URL to the sender's avatar, app icon, or a thumbnail for image notifications.", + "type": "string" + }, + "appIconMaskUrl": { + "optional": true, + "description": "A URL to the app icon mask.", + "type": "string" + }, + "title": { + "optional": true, + "description": "Title of the notification (e.g. sender name for email).", + "type": "string" + }, + "message": { + "optional": true, + "description": "Main notification content.", + "type": "string" + }, + "contextMessage": { + "optional": true, + "description": "Alternate notification content with a lower-weight font.", + "type": "string" + }, + "priority": { + "optional": true, + "description": "Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default.", + "type": "integer", + "minimum": -2, + "maximum": 2 + }, + "eventTime": { + "optional": true, + "description": "A timestamp associated with the notification, in milliseconds past the epoch.", + "type": "number" + }, + "buttons": { + "unsupported": true, + "optional": true, + "description": "Text and icons for up to two notification action buttons.", + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "iconUrl": { + "optional": true, + "type": "string" + } + } + } + }, + "imageUrl": { + "optional": true, + "description": "A URL to the image thumbnail for image-type notifications.", + "type": "string" + }, + "items": { + "optional": true, + "description": "Items for multi-item notifications.", + "type": "array", + "items": { "$ref": "NotificationItem" } + }, + "progress": { + "optional": true, + "description": "Current progress ranges from 0 to 100.", + "type": "integer", + "minimum": 0, + "maximum": 100 + }, + "isClickable": { + "optional": true, + "description": "Whether to show UI indicating that the app will visibly respond to clicks on the body of a notification.", + "type": "boolean" + } + } + } + ], + "functions": [ + { + "name": "create", + "type": "function", + "description": "Creates and displays a notification.", + "async": "callback", + "parameters": [ + { + "optional": true, + "type": "string", + "name": "notificationId", + "description": "Identifier of the notification. If it is empty, this method generates an id. If it matches an existing notification, this method first clears that notification before proceeding with the create operation." + }, + { + "$ref": "CreateNotificationOptions", + "name": "options", + "description": "Contents of the notification." + }, + { + "optional": true, + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "notificationId", + "type": "string", + "description": "The notification id (either supplied or generated) that represents the created notification." + } + ] + } + ] + }, + { + "name": "update", + "unsupported": true, + "type": "function", + "description": "Updates an existing notification.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "notificationId", + "description": "The id of the notification to be updated." + }, + { + "$ref": "UpdateNotificationOptions", + "name": "options", + "description": "Contents of the notification to update to." + }, + { + "optional": true, + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "wasUpdated", + "type": "boolean", + "description": "Indicates whether a matching notification existed." + } + ] + } + ] + }, + { + "name": "clear", + "type": "function", + "description": "Clears an existing notification.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "notificationId", + "description": "The id of the notification to be updated." + }, + { + "optional": true, + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "wasCleared", + "type": "boolean", + "description": "Indicates whether a matching notification existed." + } + ] + } + ] + }, + { + "name": "getAll", + "type": "function", + "description": "Retrieves all the notifications.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "notifications", + "type": "object", + "description": "The set of notifications currently in the system." + } + ] + } + ] + }, + { + "name": "getPermissionLevel", + "unsupported": true, + "type": "function", + "description": "Retrieves whether the user has enabled notifications from this app or extension.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "level", + "$ref": "PermissionLevel", + "description": "The current permission level." + } + ] + } + ] + } + ], + "events": [ + { + "name": "onClosed", + "type": "function", + "description": "Fired when the notification closed, either by the system or by user action.", + "parameters": [ + { + "type": "string", + "name": "notificationId", + "description": "The notificationId of the closed notification." + }, + { + "type": "boolean", + "name": "byUser", + "description": "True if the notification was closed by the user." + } + ] + }, + { + "name": "onClicked", + "type": "function", + "description": "Fired when the user clicked in a non-button area of the notification.", + "parameters": [ + { + "type": "string", + "name": "notificationId", + "description": "The notificationId of the clicked notification." + } + ] + }, + { + "name": "onButtonClicked", + "type": "function", + "description": "Fired when the user pressed a button in the notification.", + "parameters": [ + { + "type": "string", + "name": "notificationId", + "description": "The notificationId of the clicked notification." + }, + { + "type": "number", + "name": "buttonIndex", + "description": "The index of the button clicked by the user." + } + ] + }, + { + "name": "onPermissionLevelChanged", + "unsupported": true, + "type": "function", + "description": "Fired when the user changes the permission level.", + "parameters": [ + { + "$ref": "PermissionLevel", + "name": "level", + "description": "The new permission level." + } + ] + }, + { + "name": "onShowSettings", + "unsupported": true, + "type": "function", + "description": "Fired when the user clicked on a link for the app's notification settings.", + "parameters": [ + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/runtime.json b/toolkit/components/webextensions/schemas/runtime.json new file mode 100644 index 000000000..575df7d27 --- /dev/null +++ b/toolkit/components/webextensions/schemas/runtime.json @@ -0,0 +1,590 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "nativeMessaging" + ] + }] + } + ] + }, + { + "namespace": "runtime", + "allowedContexts": ["content"], + "description": "Use the browser.runtime API to retrieve the background page, return details about the manifest, and listen for and respond to events in the app or extension lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs.", + "types": [ + { + "id": "Port", + "type": "object", + "allowedContexts": ["content"], + "description": "An object which allows two way communication with other pages.", + "properties": { + "name": {"type": "string"}, + "disconnect": { "type": "function" }, + "onDisconnect": { "$ref": "events.Event" }, + "onMessage": { "$ref": "events.Event" }, + "postMessage": {"type": "function"}, + "sender": { + "$ref": "MessageSender", + "optional": true, + "description": "This property will only be present on ports passed to onConnect/onConnectExternal listeners." + } + }, + "additionalProperties": { "type": "any"} + }, + { + "id": "MessageSender", + "type": "object", + "allowedContexts": ["content"], + "description": "An object containing information about the script context that sent a message or request.", + "properties": { + "tab": {"$ref": "tabs.Tab", "optional": true, "description": "The $(ref:tabs.Tab) which opened the connection, if any. This property will only be present when the connection was opened from a tab (including content scripts), and only if the receiver is an extension, not an app."}, + "frameId": {"type": "integer", "optional": true, "description": "The $(topic:frame_ids)[frame] that opened the connection. 0 for top-level frames, positive for child frames. This will only be set when tab is set."}, + "id": {"type": "string", "optional": true, "description": "The ID of the extension or app that opened the connection, if any."}, + "url": {"type": "string", "optional": true, "description": "The URL of the page or frame that opened the connection. If the sender is in an iframe, it will be iframe's URL not the URL of the page which hosts it."}, + "tlsChannelId": {"unsupported": true, "type": "string", "optional": true, "description": "The TLS channel ID of the page or frame that opened the connection, if requested by the extension or app, and if available."} + } + }, + { + "id": "PlatformOs", + "type": "string", + "allowedContexts": ["content"], + "description": "The operating system the browser is running on.", + "enum": ["mac", "win", "android", "cros", "linux", "openbsd"] + }, + { + "id": "PlatformArch", + "type": "string", + "enum": ["arm", "x86-32", "x86-64"], + "allowedContexts": ["content"], + "description": "The machine's processor architecture." + }, + { + "id": "PlatformInfo", + "type": "object", + "allowedContexts": ["content"], + "description": "An object containing information about the current platform.", + "properties": { + "os": { + "$ref": "PlatformOs", + "description": "The operating system the browser is running on." + }, + "arch": { + "$ref": "PlatformArch", + "description": "The machine's processor architecture." + }, + "nacl_arch" : { + "unsupported": true, + "description": "The native client architecture. This may be different from arch on some platforms.", + "$ref": "PlatformNaclArch" + } + } + }, + { + "id": "BrowserInfo", + "type": "object", + "description": "An object containing information about the current browser.", + "properties": { + "name": { + "type": "string", + "description": "The name of the browser, for example 'Firefox'." + }, + "vendor": { + "type": "string", + "description": "The name of the browser vendor, for example 'Mozilla'." + }, + "version": { + "type": "string", + "description": "The browser's version, for example '42.0.0' or '0.8.1pre'." + }, + "buildID": { + "type": "string", + "description": "The browser's build ID/date, for example '20160101'." + } + } + }, + { + "id": "RequestUpdateCheckStatus", + "type": "string", + "enum": ["throttled", "no_update", "update_available"], + "allowedContexts": ["content"], + "description": "Result of the update check." + }, + { + "id": "OnInstalledReason", + "type": "string", + "enum": ["install", "update", "browser_update"], + "allowedContexts": ["content"], + "description": "The reason that this event is being dispatched." + }, + { + "id": "OnRestartRequiredReason", + "type": "string", + "allowedContexts": ["content"], + "description": "The reason that the event is being dispatched. 'app_update' is used when the restart is needed because the application is updated to a newer version. 'os_update' is used when the restart is needed because the browser/OS is updated to a newer version. 'periodic' is used when the system runs for more than the permitted uptime set in the enterprise policy.", + "enum": ["app_update", "os_update", "periodic"] + } + ], + "properties": { + "lastError": { + "type": "object", + "optional": true, + "allowedContexts": ["content"], + "description": "This will be defined during an API method callback if there was an error", + "properties": { + "message": { + "optional": true, + "type": "string", + "description": "Details about the error which occurred." + } + }, + "additionalProperties": { + "type": "any" + } + }, + "id": { + "type": "string", + "allowedContexts": ["content"], + "description": "The ID of the extension/app." + } + }, + "functions": [ + { + "name": "getBackgroundPage", + "type": "function", + "description": "Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. If the background page is an event page, the system will ensure it is loaded before calling the callback. If there is no background page, an error is set.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "backgroundPage", + "optional": true, + "type": "object", + "isInstanceOf": "Window", + "additionalProperties": { "type": "any" }, + "description": "The JavaScript 'window' object for the background page." + } + ] + } + ] + }, + { + "name": "openOptionsPage", + "type": "function", + "description": "

Open your Extension's options page, if possible.

The precise behavior may depend on your manifest's $(topic:optionsV2)[options_ui] or $(topic:options)[options_page] key, or what the browser happens to support at the time.

If your Extension does not declare an options page, or the browser failed to create one for some other reason, the callback will set $(ref:lastError).

", + "async": "callback", + "parameters": [{ + "type": "function", + "name": "callback", + "parameters": [], + "optional": true + }] + }, + { + "name": "getManifest", + "allowedContexts": ["content"], + "description": "Returns details about the app or extension from the manifest. The object returned is a serialization of the full $(topic:manifest)[manifest file].", + "type": "function", + "parameters": [], + "returns": { + "type": "object", + "properties": {}, + "additionalProperties": { "type": "any" }, + "description": "The manifest details." + } + }, + { + "name": "getURL", + "type": "function", + "allowedContexts": ["content"], + "description": "Converts a relative path within an app/extension install directory to a fully-qualified URL.", + "parameters": [ + { + "type": "string", + "name": "path", + "description": "A path to a resource within an app/extension expressed relative to its install directory." + } + ], + "returns": { + "type": "string", + "description": "The fully-qualified URL to the resource." + } + }, + { + "name": "setUninstallURL", + "type": "function", + "description": "Sets the URL to be visited upon uninstallation. This may be used to clean up server-side data, do analytics, and implement surveys. Maximum 255 characters.", + "async": "callback", + "parameters": [ + { + "type": "string", + "name": "url", + "maxLength": 255, + "description": "URL to be opened after the extension is uninstalled. This URL must have an http: or https: scheme. Set an empty string to not open a new tab upon uninstallation." + }, + { + "type": "function", + "name": "callback", + "optional": true, + "description": "Called when the uninstall URL is set. If the given URL is invalid, $(ref:runtime.lastError) will be set.", + "parameters": [] + } + ] + }, + { + "name": "reload", + "description": "Reloads the app or extension.", + "type": "function", + "parameters": [] + }, + { + "name": "requestUpdateCheck", + "unsupported": true, + "type": "function", + "description": "Requests an update check for this app/extension.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "status", + "$ref": "RequestUpdateCheckStatus", + "description": "Result of the update check." + }, + { + "name": "details", + "type": "object", + "optional": true, + "properties": { + "version": { + "type": "string", + "description": "The version of the available update." + } + }, + "description": "If an update is available, this contains more information about the available update." + } + ] + } + ] + }, + { + "name": "restart", + "unsupported": true, + "description": "Restart the device when the app runs in kiosk mode. Otherwise, it's no-op.", + "type": "function", + "parameters": [] + }, + { + "name": "connect", + "type": "function", + "allowedContexts": ["content"], + "description": "Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and $(topic:manifest/externally_connectable)[web messaging]. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via $(ref:tabs.connect).", + "parameters": [ + {"type": "string", "name": "extensionId", "optional": true, "description": "The ID of the extension or app to connect to. If omitted, a connection will be attempted with your own extension. Required if sending messages from a web page for $(topic:manifest/externally_connectable)[web messaging]."}, + { + "type": "object", + "name": "connectInfo", + "properties": { + "name": { "type": "string", "optional": true, "description": "Will be passed into onConnect for processes that are listening for the connection event." }, + "includeTlsChannelId": { "type": "boolean", "optional": true, "description": "Whether the TLS channel ID will be passed into onConnectExternal for processes that are listening for the connection event." } + }, + "optional": true + } + ], + "returns": { + "$ref": "Port", + "description": "Port through which messages can be sent and received. The port's $(ref:runtime.Port onDisconnect) event is fired if the extension/app does not exist. " + } + }, + { + "name": "connectNative", + "type": "function", + "description": "Connects to a native application in the host machine.", + "permissions": ["nativeMessaging"], + "parameters": [ + { + "type": "string", + "name": "application", + "description": "The name of the registered application to connect to." + } + ], + "returns": { + "$ref": "Port", + "description": "Port through which messages can be sent and received with the application" + } + }, + { + "name": "sendMessage", + "type": "function", + "allowAmbiguousOptionalArguments": true, + "allowedContexts": ["content"], + "description": "Sends a single message to event listeners within your extension/app or a different extension/app. Similar to $(ref:runtime.connect) but only sends a single message, with an optional response. If sending to your extension, the $(ref:runtime.onMessage) event will be fired in each page, or $(ref:runtime.onMessageExternal), if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use $(ref:tabs.sendMessage).", + "async": "responseCallback", + "parameters": [ + {"type": "string", "name": "extensionId", "optional": true, "description": "The ID of the extension/app to send the message to. If omitted, the message will be sent to your own extension/app. Required if sending messages from a web page for $(topic:manifest/externally_connectable)[web messaging]."}, + { "type": "any", "name": "message" }, + { + "type": "object", + "name": "options", + "properties": { + "includeTlsChannelId": { "type": "boolean", "optional": true, "description": "Whether the TLS channel ID will be passed into onMessageExternal for processes that are listening for the connection event." } + }, + "optional": true + }, + { + "type": "function", + "name": "responseCallback", + "optional": true, + "parameters": [ + { + "name": "response", + "type": "any", + "description": "The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and $(ref:runtime.lastError) will be set to the error message." + } + ] + } + ] + }, + { + "name": "sendNativeMessage", + "type": "function", + "description": "Send a single message to a native application.", + "permissions": ["nativeMessaging"], + "async": "responseCallback", + "parameters": [ + { + "name": "application", + "description": "The name of the native messaging host.", + "type": "string" + }, + { + "name": "message", + "description": "The message that will be passed to the native messaging host.", + "type": "any" + }, + { + "type": "function", + "name": "responseCallback", + "optional": true, + "parameters": [ + { + "name": "response", + "type": "any", + "description": "The response message sent by the native messaging host. If an error occurs while connecting to the native messaging host, the callback will be called with no arguments and $(ref:runtime.lastError) will be set to the error message." + } + ] + } + ] + }, + { + "name": "getBrowserInfo", + "type": "function", + "description": "Returns information about the current browser.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "description": "Called with results", + "parameters": [ + { + "name": "browserInfo", + "$ref": "BrowserInfo" + } + ] + } + ] + }, + { + "name": "getPlatformInfo", + "type": "function", + "description": "Returns information about the current platform.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "description": "Called with results", + "parameters": [ + { + "name": "platformInfo", + "$ref": "PlatformInfo" + } + ] + } + ] + }, + { + "name": "getPackageDirectoryEntry", + "unsupported": true, + "type": "function", + "description": "Returns a DirectoryEntry for the package directory.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "directoryEntry", + "type": "object", + "additionalProperties": { "type": "any" }, + "isInstanceOf": "DirectoryEntry" + } + ] + } + ] + } + ], + "events": [ + { + "name": "onStartup", + "type": "function", + "description": "Fired when a profile that has this extension installed first starts up. This event is not fired for incognito profiles." + }, + { + "name": "onInstalled", + "type": "function", + "description": "Fired when the extension is first installed, when the extension is updated to a new version, and when the browser is updated to a new version.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "reason": { + "$ref": "OnInstalledReason", + "description": "The reason that this event is being dispatched." + }, + "previousVersion": { + "type": "string", + "optional": true, + "unsupported": true, + "description": "Indicates the previous version of the extension, which has just been updated. This is present only if 'reason' is 'update'." + }, + "id": { + "type": "string", + "optional": true, + "unsupported": true, + "description": "Indicates the ID of the imported shared module extension which updated. This is present only if 'reason' is 'shared_module_update'." + } + } + } + ] + }, + { + "name": "onSuspend", + "unsupported": true, + "type": "function", + "description": "Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete. If more activity for the event page occurs before it gets unloaded the onSuspendCanceled event will be sent and the page won't be unloaded. " + }, + { + "name": "onSuspendCanceled", + "unsupported": true, + "type": "function", + "description": "Sent after onSuspend to indicate that the app won't be unloaded after all." + }, + { + "name": "onUpdateAvailable", + "type": "function", + "description": "Fired when an update is available, but isn't installed immediately because the app is currently running. If you do nothing, the update will be installed the next time the background page gets unloaded, if you want it to be installed sooner you can explicitly call $(ref:runtime.reload). If your extension is using a persistent background page, the background page of course never gets unloaded, so unless you call $(ref:runtime.reload) manually in response to this event the update will not get installed until the next time the browser itself restarts. If no handlers are listening for this event, and your extension has a persistent background page, it behaves as if $(ref:runtime.reload) is called in response to this event.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "version": { + "type": "string", + "description": "The version number of the available update." + } + }, + "additionalProperties": { "type": "any" }, + "description": "The manifest details of the available update." + } + ] + }, + { + "name": "onBrowserUpdateAvailable", + "unsupported": true, + "type": "function", + "description": "Fired when an update for the browser is available, but isn't installed immediately because a browser restart is required.", + "deprecated": "Please use $(ref:runtime.onRestartRequired).", + "parameters": [] + }, + { + "name": "onConnect", + "type": "function", + "allowedContexts": ["content"], + "description": "Fired when a connection is made from either an extension process or a content script.", + "parameters": [ + {"$ref": "Port", "name": "port"} + ] + }, + { + "name": "onConnectExternal", + "type": "function", + "description": "Fired when a connection is made from another extension.", + "parameters": [ + {"$ref": "Port", "name": "port"} + ] + }, + { + "name": "onMessage", + "type": "function", + "allowedContexts": ["content"], + "description": "Fired when a message is sent from either an extension process or a content script.", + "parameters": [ + {"name": "message", "type": "any", "optional": true, "description": "The message sent by the calling script."}, + {"name": "sender", "$ref": "MessageSender" }, + {"name": "sendResponse", "type": "function", "description": "Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one onMessage listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called)." } + ], + "returns": { + "type": "boolean", + "optional": true, + "description": "Return true from the event listener if you wish to call sendResponse after the event listener returns." + } + }, + { + "name": "onMessageExternal", + "type": "function", + "description": "Fired when a message is sent from another extension/app. Cannot be used in a content script.", + "parameters": [ + {"name": "message", "type": "any", "optional": true, "description": "The message sent by the calling script."}, + {"name": "sender", "$ref": "MessageSender" }, + {"name": "sendResponse", "type": "function", "description": "Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one onMessage listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called)." } + ], + "returns": { + "type": "boolean", + "optional": true, + "description": "Return true from the event listener if you wish to call sendResponse after the event listener returns." + } + }, + { + "name": "onRestartRequired", + "unsupported": true, + "type": "function", + "description": "Fired when an app or the device that it runs on needs to be restarted. The app should close all its windows at its earliest convenient time to let the restart to happen. If the app does nothing, a restart will be enforced after a 24-hour grace period has passed. Currently, this event is only fired for Chrome OS kiosk apps.", + "parameters": [ + { + "$ref": "OnRestartRequiredReason", + "name": "reason", + "description": "The reason that the event is being dispatched." + } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/storage.json b/toolkit/components/webextensions/schemas/storage.json new file mode 100644 index 000000000..a54a20942 --- /dev/null +++ b/toolkit/components/webextensions/schemas/storage.json @@ -0,0 +1,229 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "storage", + "allowedContexts": ["content"], + "defaultContexts": ["content"], + "description": "Use the browser.storage API to store, retrieve, and track changes to user data.", + "permissions": ["storage"], + "types": [ + { + "id": "StorageChange", + "type": "object", + "properties": { + "oldValue": { + "type": "any", + "description": "The old value of the item, if there was an old value.", + "optional": true + }, + "newValue": { + "type": "any", + "description": "The new value of the item, if there is a new value.", + "optional": true + } + } + }, + { + "id": "StorageArea", + "type": "object", + "functions": [ + { + "name": "get", + "type": "function", + "description": "Gets one or more items from storage.", + "async": "callback", + "parameters": [ + { + "name": "keys", + "choices": [ + { "type": "string" }, + { "type": "array", "items": { "type": "string" } }, + { + "type": "object", + "description": "Storage items to return in the callback, where the values are replaced with those from storage if they exist.", + "additionalProperties": { "type": "any" } + } + ], + "description": "A single key to get, list of keys to get, or a dictionary specifying default values (see description of the object). An empty list or object will return an empty result object. Pass in null to get the entire contents of storage.", + "optional": true + }, + { + "name": "callback", + "type": "function", + "description": "Callback with storage items, or on failure (in which case $(ref:runtime.lastError) will be set).", + "parameters": [ + { + "name": "items", + "type": "object", + "additionalProperties": { "type": "any" }, + "description": "Object with items in their key-value mappings." + } + ] + } + ] + }, + { + "name": "getBytesInUse", + "unsupported": true, + "type": "function", + "description": "Gets the amount of space (in bytes) being used by one or more items.", + "async": "callback", + "parameters": [ + { + "name": "keys", + "choices": [ + { "type": "string" }, + { "type": "array", "items": { "type": "string" } } + ], + "description": "A single key or list of keys to get the total usage for. An empty list will return 0. Pass in null to get the total usage of all of storage.", + "optional": true + }, + { + "name": "callback", + "type": "function", + "description": "Callback with the amount of space being used by storage, or on failure (in which case $(ref:runtime.lastError) will be set).", + "parameters": [ + { + "name": "bytesInUse", + "type": "integer", + "description": "Amount of space being used in storage, in bytes." + } + ] + } + ] + }, + { + "name": "set", + "type": "function", + "description": "Sets multiple items.", + "async": "callback", + "parameters": [ + { + "name": "items", + "type": "object", + "additionalProperties": { "type": "any" }, + "description": "

An object which gives each key/value pair to update storage with. Any other key/value pairs in storage will not be affected.

Primitive values such as numbers will serialize as expected. Values with a typeof \"object\" and \"function\" will typically serialize to {}, with the exception of Array (serializes as expected), Date, and Regex (serialize using their String representation).

" + }, + { + "name": "callback", + "type": "function", + "description": "Callback on success, or on failure (in which case $(ref:runtime.lastError) will be set).", + "parameters": [], + "optional": true + } + ] + }, + { + "name": "remove", + "type": "function", + "description": "Removes one or more items from storage.", + "async": "callback", + "parameters": [ + { + "name": "keys", + "choices": [ + {"type": "string"}, + {"type": "array", "items": {"type": "string"}} + ], + "description": "A single key or a list of keys for items to remove." + }, + { + "name": "callback", + "type": "function", + "description": "Callback on success, or on failure (in which case $(ref:runtime.lastError) will be set).", + "parameters": [], + "optional": true + } + ] + }, + { + "name": "clear", + "type": "function", + "description": "Removes all items from storage.", + "async": "callback", + "parameters": [ + { + "name": "callback", + "type": "function", + "description": "Callback on success, or on failure (in which case $(ref:runtime.lastError) will be set).", + "parameters": [], + "optional": true + } + ] + } + ] + } + ], + "events": [ + { + "name": "onChanged", + "type": "function", + "description": "Fired when one or more items change.", + "parameters": [ + { + "name": "changes", + "type": "object", + "additionalProperties": { "$ref": "StorageChange" }, + "description": "Object mapping each key that changed to its corresponding $(ref:storage.StorageChange) for that item." + }, + { + "name": "areaName", + "type": "string", + "description": "The name of the storage area (\"sync\", \"local\" or \"managed\") the changes are for." + } + ] + } + ], + "properties": { + "sync": { + "$ref": "StorageArea", + "description": "Items in the sync storage area are synced by the browser.", + "properties": { + "QUOTA_BYTES": { + "value": 102400, + "description": "The maximum total amount (in bytes) of data that can be stored in sync storage, as measured by the JSON stringification of every value plus every key's length. Updates that would cause this limit to be exceeded fail immediately and set $(ref:runtime.lastError)." + }, + "QUOTA_BYTES_PER_ITEM": { + "value": 8192, + "description": "The maximum size (in bytes) of each individual item in sync storage, as measured by the JSON stringification of its value plus its key length. Updates containing items larger than this limit will fail immediately and set $(ref:runtime.lastError)." + }, + "MAX_ITEMS": { + "value": 512, + "description": "The maximum number of items that can be stored in sync storage. Updates that would cause this limit to be exceeded will fail immediately and set $(ref:runtime.lastError)." + }, + "MAX_WRITE_OPERATIONS_PER_HOUR": { + "value": 1800, + "description": "

The maximum number of set, remove, or clear operations that can be performed each hour. This is 1 every 2 seconds, a lower ceiling than the short term higher writes-per-minute limit.

Updates that would cause this limit to be exceeded fail immediately and set $(ref:runtime.lastError).

" + }, + "MAX_WRITE_OPERATIONS_PER_MINUTE": { + "value": 120, + "description": "

The maximum number of set, remove, or clear operations that can be performed each minute. This is 2 per second, providing higher throughput than writes-per-hour over a shorter period of time.

Updates that would cause this limit to be exceeded fail immediately and set $(ref:runtime.lastError).

" + }, + "MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE": { + "value": 1000000, + "deprecated": "The storage.sync API no longer has a sustained write operation quota.", + "description": "" + } + } + }, + "local": { + "$ref": "StorageArea", + "description": "Items in the local storage area are local to each machine.", + "properties": { + "QUOTA_BYTES": { + "value": 5242880, + "description": "The maximum amount (in bytes) of data that can be stored in local storage, as measured by the JSON stringification of every value plus every key's length. This value will be ignored if the extension has the unlimitedStorage permission. Updates that would cause this limit to be exceeded fail immediately and set $(ref:runtime.lastError)." + } + } + }, + "managed": { + "unsupported": true, + "$ref": "StorageArea", + "description": "Items in the managed storage area are set by the domain administrator, and are read-only for the extension; trying to modify this namespace results in an error." + } + } + } +] diff --git a/toolkit/components/webextensions/schemas/test.json b/toolkit/components/webextensions/schemas/test.json new file mode 100644 index 000000000..25a62a96b --- /dev/null +++ b/toolkit/components/webextensions/schemas/test.json @@ -0,0 +1,215 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "test", + "allowedContexts": ["content"], + "defaultContexts": ["content"], + "description": "none", + "functions": [ + { + "name": "notifyFail", + "type": "function", + "description": "Notifies the browser process that test code running in the extension failed. This is only used for internal unit testing.", + "parameters": [ + {"type": "string", "name": "message"} + ] + }, + { + "name": "notifyPass", + "type": "function", + "description": "Notifies the browser process that test code running in the extension passed. This is only used for internal unit testing.", + "parameters": [ + {"type": "string", "name": "message", "optional": true} + ] + }, + { + "name": "log", + "type": "function", + "description": "Logs a message during internal unit testing.", + "parameters": [ + {"type": "string", "name": "message"} + ] + }, + { + "name": "sendMessage", + "type": "function", + "description": "Sends a string message to the browser process, generating a Notification that C++ test code can wait for.", + "allowAmbiguousOptionalArguments": true, + "parameters": [ + {"type": "any", "name": "arg1", "optional": true}, + {"type": "any", "name": "arg2", "optional": true} + ] + }, + { + "name": "fail", + "type": "function", + "parameters": [ + {"type": "any", "name": "message", "optional": true} + ] + }, + { + "name": "succeed", + "type": "function", + "parameters": [ + {"type": "any", "name": "message", "optional": true} + ] + }, + { + "name": "assertTrue", + "type": "function", + "allowAmbiguousOptionalArguments": true, + "parameters": [ + {"name": "test", "type": "any", "optional": true}, + {"type": "string", "name": "message", "optional": true} + ] + }, + { + "name": "assertFalse", + "type": "function", + "allowAmbiguousOptionalArguments": true, + "parameters": [ + {"name": "test", "type": "any", "optional": true}, + {"type": "string", "name": "message", "optional": true} + ] + }, + { + "name": "assertBool", + "type": "function", + "unsupported": true, + "parameters": [ + { + "name": "test", + "choices": [ + {"type": "string"}, + {"type": "boolean"} + ] + }, + {"type": "boolean", "name": "expected"}, + {"type": "string", "name": "message", "optional": true} + ] + }, + { + "name": "checkDeepEq", + "type": "function", + "unsupported": true, + "allowAmbiguousOptionalArguments": true, + "parameters": [ + {"type": "any", "name": "expected"}, + {"type": "any", "name": "actual"} + ] + }, + { + "name": "assertEq", + "type": "function", + "allowAmbiguousOptionalArguments": true, + "parameters": [ + {"type": "any", "name": "expected", "optional": true}, + {"type": "any", "name": "actual", "optional": true}, + {"type": "string", "name": "message", "optional": true} + ] + }, + { + "name": "assertNoLastError", + "type": "function", + "unsupported": true, + "parameters": [] + }, + { + "name": "assertLastError", + "type": "function", + "unsupported": true, + "parameters": [ + {"type": "string", "name": "expectedError"} + ] + }, + { + "name": "assertRejects", + "type": "function", + "async": true, + "parameters": [ + { + "name": "promise", + "$ref": "Promise" + }, + { + "name": "expectedError", + "$ref": "ExpectedError", + "optional": true + }, + { + "name": "message", + "type": "string", + "optional": true + } + ] + }, + { + "name": "assertThrows", + "type": "function", + "parameters": [ + { + "name": "func", + "type": "function" + }, + { + "name": "expectedError", + "$ref": "ExpectedError", + "optional": true + }, + { + "name": "message", + "type": "string", + "optional": true + } + ] + } + ], + "types": [ + { + "id": "ExpectedError", + "choices": [ + {"type": "string"}, + {"type": "object", "isInstanceOf": "RegExp", "additionalProperties": true}, + {"type": "function"} + ] + }, + { + "id": "Promise", + "choices": [ + { + "type": "object", + "properties": { + "then": {"type": "function"} + }, + "additionalProperties": true + }, + { + "type": "object", + "isInstanceOf": "Promise", + "additionalProperties": true + } + ] + } + ], + "events": [ + { + "name": "onMessage", + "type": "function", + "description": "Used to test sending messages to extensions.", + "parameters": [ + { + "type": "string", + "name": "message" + }, + { + "type": "any", + "name": "argument" + } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/top_sites.json b/toolkit/components/webextensions/schemas/top_sites.json new file mode 100644 index 000000000..fbfbc4b62 --- /dev/null +++ b/toolkit/components/webextensions/schemas/top_sites.json @@ -0,0 +1,66 @@ +/* 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/. */ + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "topSites" + ] + }] + } + ] + }, + { + "namespace": "topSites", + "description": "Use the chrome.topSites API to access the top sites that are displayed on the new tab page. ", + "permissions": ["topSites"], + "types": [ + { + "id": "MostVisitedURL", + "type": "object", + "description": "An object encapsulating a most visited URL, such as the URLs on the new tab page.", + "properties": { + "url": { + "type": "string", + "description": "The most visited URL." + }, + "title": { + "type": "string", + "optional": true, + "description": "The title of the page." + } + } + } + ], + "functions": [ + { + "name": "get", + "type": "function", + "description": "Gets a list of top sites.", + "async": "callback", + "parameters": [ + { + "name": "callback", + "type": "function", + "parameters": [ + { + "name": "results", + "type": "array", + "items": { + "$ref": "MostVisitedURL" + } + } + ] + } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/web_navigation.json b/toolkit/components/webextensions/schemas/web_navigation.json new file mode 100644 index 000000000..1e13b181a --- /dev/null +++ b/toolkit/components/webextensions/schemas/web_navigation.json @@ -0,0 +1,387 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "webNavigation" + ] + }] + } + ] + }, + { + "namespace": "webNavigation", + "description": "Use the browser.webNavigation API to receive notifications about the status of navigation requests in-flight.", + "permissions": ["webNavigation"], + "types": [ + { + "id": "TransitionType", + "type": "string", + "enum": ["link", "typed", "auto_bookmark", "auto_subframe", "manual_subframe", "generated", "start_page", "form_submit", "reload", "keyword", "keyword_generated"], + "description": "Cause of the navigation. The same transition types as defined in the history API are used. These are the same transition types as defined in the $(topic:transition_types)[history API] except with \"start_page\" in place of \"auto_toplevel\" (for backwards compatibility)." + }, + { + "id": "TransitionQualifier", + "type": "string", + "enum": ["client_redirect", "server_redirect", "forward_back", "from_address_bar"] + }, + { + "id": "EventUrlFilters", + "type": "object", + "properties": { + "url": { + "type": "array", + "minItems": 1, + "items": { "$ref": "events.UrlFilter" } + } + } + } + ], + "functions": [ + { + "name": "getFrame", + "type": "function", + "description": "Retrieves information about the given frame. A frame refers to an <iframe> or a <frame> of a web page and is identified by a tab ID and a frame ID.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "details", + "description": "Information about the frame to retrieve information about.", + "properties": { + "tabId": { "type": "integer", "minimum": 0, "description": "The ID of the tab in which the frame is." }, + "processId": {"optional": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."}, + "frameId": { "type": "integer", "minimum": 0, "description": "The ID of the frame in the given tab." } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "type": "object", + "name": "details", + "optional": true, + "description": "Information about the requested frame, null if the specified frame ID and/or tab ID are invalid.", + "properties": { + "errorOccurred": { + "unsupported": true, + "type": "boolean", + "description": "True if the last navigation in this frame was interrupted by an error, i.e. the onErrorOccurred event fired." + }, + "url": { + "type": "string", + "description": "The URL currently associated with this frame, if the frame identified by the frameId existed at one point in the given tab. The fact that an URL is associated with a given frameId does not imply that the corresponding frame still exists." + }, + "parentFrameId": { + "type": "integer", + "description": "ID of frame that wraps the frame. Set to -1 of no parent frame exists." + } + } + } + ] + } + ] + }, + { + "name": "getAllFrames", + "type": "function", + "description": "Retrieves information about all frames of a given tab.", + "async": "callback", + "parameters": [ + { + "type": "object", + "name": "details", + "description": "Information about the tab to retrieve all frames from.", + "properties": { + "tabId": { "type": "integer", "minimum": 0, "description": "The ID of the tab." } + } + }, + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "details", + "type": "array", + "description": "A list of frames in the given tab, null if the specified tab ID is invalid.", + "optional": true, + "items": { + "type": "object", + "properties": { + "errorOccurred": { + "unsupported": true, + "type": "boolean", + "description": "True if the last navigation in this frame was interrupted by an error, i.e. the onErrorOccurred event fired." + }, + "processId": { + "unsupported": true, + "type": "integer", + "description": "The ID of the process runs the renderer for this tab." + }, + "frameId": { + "type": "integer", + "description": "The ID of the frame. 0 indicates that this is the main frame; a positive value indicates the ID of a subframe." + }, + "parentFrameId": { + "type": "integer", + "description": "ID of frame that wraps the frame. Set to -1 of no parent frame exists." + }, + "url": { + "type": "string", + "description": "The URL currently associated with this frame." + } + } + } + } + ] + } + ] + } + ], + "events": [ + { + "name": "onBeforeNavigate", + "type": "function", + "description": "Fired when a navigation is about to occur.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation is about to occur."}, + "url": {"type": "string"}, + "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."}, + "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique for a given tab and process."}, + "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame. Set to -1 of no parent frame exists."}, + "timeStamp": {"type": "number", "description": "The time when the browser was about to start the navigation, in milliseconds since the epoch."} + } + } + ], + "extraParameters": [ + { + "name": "filters", + "optional": true, + "$ref": "EventUrlFilters", + "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event." + } + ] + }, + { + "name": "onCommitted", + "type": "function", + "description": "Fired when a navigation is committed. The document (and the resources it refers to, such as images and subframes) might still be downloading, but at least part of the document has been received from the server and the browser has decided to switch to the new document.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."}, + "url": {"type": "string"}, + "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."}, + "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."}, + "transitionType": {"unsupported": true, "$ref": "TransitionType", "description": "Cause of the navigation."}, + "transitionQualifiers": {"unsupported": true, "type": "array", "description": "A list of transition qualifiers.", "items": {"$ref": "TransitionQualifier"}}, + "timeStamp": {"type": "number", "description": "The time when the navigation was committed, in milliseconds since the epoch."} + } + } + ], + "extraParameters": [ + { + "name": "filters", + "optional": true, + "$ref": "EventUrlFilters", + "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event." + } + ] + }, + { + "name": "onDOMContentLoaded", + "type": "function", + "description": "Fired when the page's DOM is fully constructed, but the referenced resources may not finish loading.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."}, + "url": {"type": "string"}, + "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."}, + "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."}, + "timeStamp": {"type": "number", "description": "The time when the page's DOM was fully constructed, in milliseconds since the epoch."} + } + } + ], + "extraParameters": [ + { + "name": "filters", + "optional": true, + "$ref": "EventUrlFilters", + "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event." + } + ] + }, + { + "name": "onCompleted", + "type": "function", + "description": "Fired when a document, including the resources it refers to, is completely loaded and initialized.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."}, + "url": {"type": "string"}, + "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."}, + "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."}, + "timeStamp": {"type": "number", "description": "The time when the document finished loading, in milliseconds since the epoch."} + } + } + ], + "extraParameters": [ + { + "name": "filters", + "optional": true, + "$ref": "EventUrlFilters", + "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event." + } + ] + }, + { + "name": "onErrorOccurred", + "type": "function", + "description": "Fired when an error occurs and the navigation is aborted. This can happen if either a network error occurred, or the user aborted the navigation.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."}, + "url": {"type": "string"}, + "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."}, + "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."}, + "error": {"unsupported": true, "type": "string", "description": "The error description."}, + "timeStamp": {"type": "number", "description": "The time when the error occurred, in milliseconds since the epoch."} + } + } + ], + "extraParameters": [ + { + "name": "filters", + "optional": true, + "$ref": "EventUrlFilters", + "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event." + } + ] + }, + { + "name": "onCreatedNavigationTarget", + "unsupported": true, + "type": "function", + "description": "Fired when a new window, or a new tab in an existing window, is created to host a navigation.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "sourceTabId": {"type": "integer", "description": "The ID of the tab in which the navigation is triggered."}, + "sourceProcessId": {"type": "integer", "description": "The ID of the process runs the renderer for the source tab."}, + "sourceFrameId": {"type": "integer", "description": "The ID of the frame with sourceTabId in which the navigation is triggered. 0 indicates the main frame."}, + "url": {"type": "string", "description": "The URL to be opened in the new window."}, + "tabId": {"type": "integer", "description": "The ID of the tab in which the url is opened"}, + "timeStamp": {"type": "number", "description": "The time when the browser was about to create a new view, in milliseconds since the epoch."} + } + } + ], + "extraParameters": [ + { + "name": "filters", + "optional": true, + "$ref": "EventUrlFilters", + "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event." + } + ] + }, + { + "name": "onReferenceFragmentUpdated", + "type": "function", + "description": "Fired when the reference fragment of a frame was updated. All future events for that frame will use the updated URL.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."}, + "url": {"type": "string"}, + "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."}, + "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."}, + "transitionType": {"unsupported": true, "$ref": "TransitionType", "description": "Cause of the navigation."}, + "transitionQualifiers": {"unsupported": true, "type": "array", "description": "A list of transition qualifiers.", "items": {"$ref": "TransitionQualifier"}}, + "timeStamp": {"type": "number", "description": "The time when the navigation was committed, in milliseconds since the epoch."} + } + } + ], + "extraParameters": [ + { + "name": "filters", + "optional": true, + "$ref": "EventUrlFilters", + "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event." + } + ] + }, + { + "name": "onTabReplaced", + "type": "function", + "description": "Fired when the contents of the tab is replaced by a different (usually previously pre-rendered) tab.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "replacedTabId": {"type": "integer", "description": "The ID of the tab that was replaced."}, + "tabId": {"type": "integer", "description": "The ID of the tab that replaced the old tab."}, + "timeStamp": {"type": "number", "description": "The time when the replacement happened, in milliseconds since the epoch."} + } + } + ] + }, + { + "name": "onHistoryStateUpdated", + "type": "function", + "description": "Fired when the frame's history was updated to a new URL. All future events for that frame will use the updated URL.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "tabId": {"type": "integer", "description": "The ID of the tab in which the navigation occurs."}, + "url": {"type": "string"}, + "processId": {"unsupported": true, "type": "integer", "description": "The ID of the process runs the renderer for this tab."}, + "frameId": {"type": "integer", "description": "0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab."}, + "transitionType": {"unsupported": true, "$ref": "TransitionType", "description": "Cause of the navigation."}, + "transitionQualifiers": {"unsupported": true, "type": "array", "description": "A list of transition qualifiers.", "items": {"$ref": "TransitionQualifier"}}, + "timeStamp": {"type": "number", "description": "The time when the navigation was committed, in milliseconds since the epoch."} + } + } + ], + "extraParameters": [ + { + "name": "filters", + "optional": true, + "$ref": "EventUrlFilters", + "description": "Conditions that the URL being navigated to must satisfy. The 'schemes' and 'ports' fields of UrlFilter are ignored for this event." + } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/schemas/web_request.json b/toolkit/components/webextensions/schemas/web_request.json new file mode 100644 index 000000000..4035aea6e --- /dev/null +++ b/toolkit/components/webextensions/schemas/web_request.json @@ -0,0 +1,616 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +[ + { + "namespace": "manifest", + "types": [ + { + "$extend": "Permission", + "choices": [{ + "type": "string", + "enum": [ + "webRequest", + "webRequestBlocking" + ] + }] + } + ] + }, + { + "namespace": "webRequest", + "description": "Use the browser.webRequest API to observe and analyze traffic and to intercept, block, or modify requests in-flight.", + "permissions": ["webRequest"], + "properties": { + "MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES": { + "value": 20, + "description": "The maximum number of times that handlerBehaviorChanged can be called per 10 minute sustained interval. handlerBehaviorChanged is an expensive function call that shouldn't be called often." + } + }, + "types": [ + { + "id": "ResourceType", + "type": "string", + "enum": [ + "main_frame", + "sub_frame", + "stylesheet", + "script", + "image", + "object", + "xmlhttprequest", + "xbl", + "xslt", + "ping", + "beacon", + "xml_dtd", + "font", + "media", + "websocket", + "csp_report", + "imageset", + "web_manifest", + "other" + ] + }, + { + "id": "OnBeforeRequestOptions", + "type": "string", + "enum": ["blocking", "requestBody"] + }, + { + "id": "OnBeforeSendHeadersOptions", + "type": "string", + "enum": ["requestHeaders", "blocking"] + }, + { + "id": "OnSendHeadersOptions", + "type": "string", + "enum": ["requestHeaders"] + }, + { + "id": "OnHeadersReceivedOptions", + "type": "string", + "enum": ["blocking", "responseHeaders"] + }, + { + "id": "OnAuthRequiredOptions", + "type": "string", + "enum": ["responseHeaders", "blocking", "asyncBlocking"] + }, + { + "id": "OnResponseStartedOptions", + "type": "string", + "enum": ["responseHeaders"] + }, + { + "id": "OnBeforeRedirectOptions", + "type": "string", + "enum": ["responseHeaders"] + }, + { + "id": "OnCompletedOptions", + "type": "string", + "enum": ["responseHeaders"] + }, + { + "id": "RequestFilter", + "type": "object", + "description": "An object describing filters to apply to webRequest events.", + "properties": { + "urls": { + "type": "array", + "description": "A list of URLs or URL patterns. Requests that cannot match any of the URLs will be filtered out.", + "items": { "type": "string" } + }, + "types": { + "type": "array", + "optional": true, + "description": "A list of request types. Requests that cannot match any of the types will be filtered out.", + "items": { "$ref": "ResourceType" } + }, + "tabId": { "type": "integer", "optional": true }, + "windowId": { "type": "integer", "optional": true } + } + }, + { + "id": "HttpHeaders", + "type": "array", + "description": "An array of HTTP headers. Each header is represented as a dictionary containing the keys name and either value or binaryValue.", + "items": { + "type": "object", + "properties": { + "name": {"type": "string", "description": "Name of the HTTP header."}, + "value": {"type": "string", "optional": true, "description": "Value of the HTTP header if it can be represented by UTF-8."}, + "binaryValue": { + "type": "array", + "optional": true, + "description": "Value of the HTTP header if it cannot be represented by UTF-8, stored as individual byte values (0..255).", + "items": {"type": "integer"} + } + } + } + }, + { + "id": "BlockingResponse", + "type": "object", + "description": "Returns value for event handlers that have the 'blocking' extraInfoSpec applied. Allows the event handler to modify network requests.", + "properties": { + "cancel": { + "type": "boolean", + "optional": true, + "description": "If true, the request is cancelled. Used in onBeforeRequest, this prevents the request from being sent." + }, + "redirectUrl": { + "type": "string", + "optional": true, + "description": "Only used as a response to the onBeforeRequest and onHeadersReceived events. If set, the original request is prevented from being sent/completed and is instead redirected to the given URL. Redirections to non-HTTP schemes such as data: are allowed. Redirects initiated by a redirect action use the original request method for the redirect, with one exception: If the redirect is initiated at the onHeadersReceived stage, then the redirect will be issued using the GET method." + }, + "requestHeaders": { + "$ref": "HttpHeaders", + "optional": true, + "description": "Only used as a response to the onBeforeSendHeaders event. If set, the request is made with these request headers instead." + }, + "responseHeaders": { + "$ref": "HttpHeaders", + "optional": true, + "description": "Only used as a response to the onHeadersReceived event. If set, the server is assumed to have responded with these response headers instead. Only return responseHeaders if you really want to modify the headers in order to limit the number of conflicts (only one extension may modify responseHeaders for each request)." + }, + "authCredentials": { + "type": "object", + "description": "Only used as a response to the onAuthRequired event. If set, the request is made using the supplied credentials.", + "optional": true, + "properties": { + "username": {"type": "string"}, + "password": {"type": "string"} + } + } + } + }, + { + "id": "UploadData", + "type": "object", + "properties": { + "bytes": { + "type": "any", + "optional": true, + "description": "An ArrayBuffer with a copy of the data." + }, + "file": { + "type": "string", + "optional": true, + "description": "A string with the file's path and name." + } + }, + "description": "Contains data uploaded in a URL request." + } + ], + "functions": [ + { + "name": "handlerBehaviorChanged", + "type": "function", + "description": "Needs to be called when the behavior of the webRequest handlers has changed to prevent incorrect handling due to caching. This function call is expensive. Don't call it often.", + "async": "callback", + "parameters": [ + { + "type": "function", + "name": "callback", + "optional": true, + "parameters": [] + } + ] + } + ], + "events": [ + { + "name": "onBeforeRequest", + "type": "function", + "description": "Fired when a request is about to occur.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."}, + "url": {"type": "string"}, + "method": {"type": "string", "description": "Standard HTTP method."}, + "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."}, + "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."}, + "requestBody": { + "type": "object", + "optional": true, + "description": "Contains the HTTP request body data. Only provided if extraInfoSpec contains 'requestBody'.", + "properties": { + "error": {"type": "string", "optional": true, "description": "Errors when obtaining request body data."}, + "formData": { + "type": "object", + "optional": true, + "description": "If the request method is POST and the body is a sequence of key-value pairs encoded in UTF8, encoded as either multipart/form-data, or application/x-www-form-urlencoded, this dictionary is present and for each key contains the list of all values for that key. If the data is of another media type, or if it is malformed, the dictionary is not present. An example value of this dictionary is {'key': ['value1', 'value2']}.", + "properties": {}, + "additionalProperties": { + "type": "array", + "items": { "type": "string" } + } + }, + "raw" : { + "type": "array", + "optional": true, + "items": {"$ref": "UploadData"}, + "description": "If the request method is PUT or POST, and the body is not already parsed in formData, then the unparsed request body elements are contained in this array." + } + } + }, + "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."}, + "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."}, + "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."} + } + } + ], + "extraParameters": [ + { + "$ref": "RequestFilter", + "name": "filter", + "description": "A set of filters that restricts the events that will be sent to this listener." + }, + { + "type": "array", + "optional": true, + "name": "extraInfoSpec", + "description": "Array of extra information that should be passed to the listener function.", + "items": { + "$ref": "OnBeforeRequestOptions" + } + } + ], + "returns": { + "$ref": "BlockingResponse", + "description": "If \"blocking\" is specified in the \"extraInfoSpec\" parameter, the event listener should return an object of this type.", + "optional": true + } + }, + { + "name": "onBeforeSendHeaders", + "type": "function", + "description": "Fired before sending an HTTP request, once the request headers are available. This may occur after a TCP connection is made to the server, but before any HTTP data is sent. ", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."}, + "url": {"type": "string"}, + "method": {"type": "string", "description": "Standard HTTP method."}, + "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."}, + "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."}, + "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."}, + "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."}, + "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."}, + "requestHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP request headers that are going to be sent out with this request."} + } + } + ], + "extraParameters": [ + { + "$ref": "RequestFilter", + "name": "filter", + "description": "A set of filters that restricts the events that will be sent to this listener." + }, + { + "type": "array", + "optional": true, + "name": "extraInfoSpec", + "description": "Array of extra information that should be passed to the listener function.", + "items": { + "$ref": "OnBeforeSendHeadersOptions" + } + } + ], + "returns": { + "$ref": "BlockingResponse", + "description": "If \"blocking\" is specified in the \"extraInfoSpec\" parameter, the event listener should return an object of this type.", + "optional": true + } + }, + { + "name": "onSendHeaders", + "type": "function", + "description": "Fired just before a request is going to be sent to the server (modifications of previous onBeforeSendHeaders callbacks are visible by the time onSendHeaders is fired).", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."}, + "url": {"type": "string"}, + "method": {"type": "string", "description": "Standard HTTP method."}, + "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."}, + "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."}, + "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."}, + "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."}, + "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."}, + "requestHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP request headers that have been sent out with this request."} + } + } + ], + "extraParameters": [ + { + "$ref": "RequestFilter", + "name": "filter", + "description": "A set of filters that restricts the events that will be sent to this listener." + }, + { + "type": "array", + "optional": true, + "name": "extraInfoSpec", + "description": "Array of extra information that should be passed to the listener function.", + "items": { + "$ref": "OnSendHeadersOptions" + } + } + ] + }, + { + "name": "onHeadersReceived", + "type": "function", + "description": "Fired when HTTP response headers of a request have been received.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."}, + "url": {"type": "string"}, + "method": {"type": "string", "description": "Standard HTTP method."}, + "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."}, + "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."}, + "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."}, + "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."}, + "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."}, + "statusLine": {"type": "string", "description": "HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line)."}, + "responseHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP response headers that have been received with this response."}, + "statusCode": {"type": "integer", "description": "Standard HTTP status code returned by the server."} + } + } + ], + "extraParameters": [ + { + "$ref": "RequestFilter", + "name": "filter", + "description": "A set of filters that restricts the events that will be sent to this listener." + }, + { + "type": "array", + "optional": true, + "name": "extraInfoSpec", + "description": "Array of extra information that should be passed to the listener function.", + "items": { + "$ref": "OnHeadersReceivedOptions" + } + } + ], + "returns": { + "$ref": "BlockingResponse", + "description": "If \"blocking\" is specified in the \"extraInfoSpec\" parameter, the event listener should return an object of this type.", + "optional": true + } + }, + { + "name": "onAuthRequired", + "unsupported": true, + "type": "function", + "description": "Fired when an authentication failure is received. The listener has three options: it can provide authentication credentials, it can cancel the request and display the error page, or it can take no action on the challenge. If bad user credentials are provided, this may be called multiple times for the same request.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."}, + "url": {"type": "string"}, + "method": {"type": "string", "description": "Standard HTTP method."}, + "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."}, + "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."}, + "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."}, + "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."}, + "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."}, + "scheme": {"type": "string", "description": "The authentication scheme, e.g. Basic or Digest."}, + "realm": {"type": "string", "description": "The authentication realm provided by the server, if there is one.", "optional": true}, + "challenger": {"type": "object", "description": "The server requesting authentication.", "properties": {"host": {"type": "string"}, "port": {"type": "integer"}}}, + "isProxy": {"type": "boolean", "description": "True for Proxy-Authenticate, false for WWW-Authenticate."}, + "responseHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP response headers that were received along with this response."}, + "statusLine": {"type": "string", "description": "HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers."}, + "statusCode": {"type": "integer", "description": "Standard HTTP status code returned by the server."} + } + }, + { + "type": "function", + "optional": true, + "name": "callback", + "parameters": [ + {"name": "response", "$ref": "BlockingResponse"} + ] + } + ], + "extraParameters": [ + { + "$ref": "RequestFilter", + "name": "filter", + "description": "A set of filters that restricts the events that will be sent to this listener." + }, + { + "type": "array", + "optional": true, + "name": "extraInfoSpec", + "description": "Array of extra information that should be passed to the listener function.", + "items": { + "$ref": "OnAuthRequiredOptions" + } + } + ], + "returns": { + "$ref": "BlockingResponse", + "description": "If \"blocking\" is specified in the \"extraInfoSpec\" parameter, the event listener should return an object of this type.", + "optional": true + } + }, + { + "name": "onResponseStarted", + "type": "function", + "description": "Fired when the first byte of the response body is received. For HTTP requests, this means that the status line and response headers are available.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."}, + "url": {"type": "string"}, + "method": {"type": "string", "description": "Standard HTTP method."}, + "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."}, + "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."}, + "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."}, + "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."}, + "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."}, + "ip": {"type": "string", "optional": true, "description": "The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address."}, + "fromCache": {"type": "boolean", "description": "Indicates if this response was fetched from disk cache."}, + "statusCode": {"type": "integer", "description": "Standard HTTP status code returned by the server."}, + "responseHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP response headers that were received along with this response."}, + "statusLine": {"type": "string", "description": "HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers."} + } + } + ], + "extraParameters": [ + { + "$ref": "RequestFilter", + "name": "filter", + "description": "A set of filters that restricts the events that will be sent to this listener." + }, + { + "type": "array", + "optional": true, + "name": "extraInfoSpec", + "description": "Array of extra information that should be passed to the listener function.", + "items": { + "$ref": "OnResponseStartedOptions" + } + } + ] + }, + { + "name": "onBeforeRedirect", + "type": "function", + "description": "Fired when a server-initiated redirect is about to occur.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."}, + "url": {"type": "string"}, + "method": {"type": "string", "description": "Standard HTTP method."}, + "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."}, + "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."}, + "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."}, + "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."}, + "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."}, + "ip": {"type": "string", "optional": true, "description": "The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address."}, + "fromCache": {"type": "boolean", "description": "Indicates if this response was fetched from disk cache."}, + "statusCode": {"type": "integer", "description": "Standard HTTP status code returned by the server."}, + "redirectUrl": {"type": "string", "description": "The new URL."}, + "responseHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP response headers that were received along with this redirect."}, + "statusLine": {"type": "string", "description": "HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers."} + } + } + ], + "extraParameters": [ + { + "$ref": "RequestFilter", + "name": "filter", + "description": "A set of filters that restricts the events that will be sent to this listener." + }, + { + "type": "array", + "optional": true, + "name": "extraInfoSpec", + "description": "Array of extra information that should be passed to the listener function.", + "items": { + "$ref": "OnBeforeRedirectOptions" + } + } + ] + }, + { + "name": "onCompleted", + "type": "function", + "description": "Fired when a request is completed.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."}, + "url": {"type": "string"}, + "method": {"type": "string", "description": "Standard HTTP method."}, + "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."}, + "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."}, + "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."}, + "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."}, + "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."}, + "ip": {"type": "string", "optional": true, "description": "The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address."}, + "fromCache": {"type": "boolean", "description": "Indicates if this response was fetched from disk cache."}, + "statusCode": {"type": "integer", "description": "Standard HTTP status code returned by the server."}, + "responseHeaders": {"$ref": "HttpHeaders", "optional": true, "description": "The HTTP response headers that were received along with this response."}, + "statusLine": {"type": "string", "description": "HTTP status line of the response or the 'HTTP/0.9 200 OK' string for HTTP/0.9 responses (i.e., responses that lack a status line) or an empty string if there are no headers."} + } + } + ], + "extraParameters": [ + { + "$ref": "RequestFilter", + "name": "filter", + "description": "A set of filters that restricts the events that will be sent to this listener." + }, + { + "type": "array", + "optional": true, + "name": "extraInfoSpec", + "description": "Array of extra information that should be passed to the listener function.", + "items": { + "$ref": "OnCompletedOptions" + } + } + ] + }, + { + "name": "onErrorOccurred", + "type": "function", + "description": "Fired when an error occurs.", + "parameters": [ + { + "type": "object", + "name": "details", + "properties": { + "requestId": {"type": "string", "description": "The ID of the request. Request IDs are unique within a browser session. As a result, they could be used to relate different events of the same request."}, + "url": {"type": "string"}, + "method": {"type": "string", "description": "Standard HTTP method."}, + "frameId": {"type": "integer", "description": "The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab."}, + "parentFrameId": {"type": "integer", "description": "ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists."}, + "tabId": {"type": "integer", "description": "The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab."}, + "type": {"$ref": "ResourceType", "description": "How the requested resource will be used."}, + "timeStamp": {"type": "number", "description": "The time when this signal is triggered, in milliseconds since the epoch."}, + "ip": {"type": "string", "optional": true, "description": "The server IP address that the request was actually sent to. Note that it may be a literal IPv6 address."}, + "fromCache": {"type": "boolean", "description": "Indicates if this response was fetched from disk cache."}, + "error": {"type": "string", "description": "The error description. This string is not guaranteed to remain backwards compatible between releases. You must not parse and act based upon its content."} + } + } + ], + "extraParameters": [ + { + "$ref": "RequestFilter", + "name": "filter", + "description": "A set of filters that restricts the events that will be sent to this listener." + } + ] + } + ] + } +] diff --git a/toolkit/components/webextensions/test/mochitest/.eslintrc.js b/toolkit/components/webextensions/test/mochitest/.eslintrc.js new file mode 100644 index 000000000..53938410b --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/.eslintrc.js @@ -0,0 +1,35 @@ +"use strict"; + +module.exports = { // eslint-disable-line no-undef + "extends": "../../../../../testing/mochitest/mochitest.eslintrc.js", + + "env": { + "webextensions": true, + }, + + "globals": { + "ChromeWorker": false, + "onmessage": true, + "sendAsyncMessage": false, + + "waitForLoad": true, + "promiseConsoleOutput": true, + + "ExtensionTestUtils": false, + "NetUtil": true, + "webrequest_test": false, + "XPCOMUtils": true, + + // head_webrequest.js symbols + "addStylesheet": true, + "addLink": true, + "addImage": true, + "addScript": true, + "addFrame": true, + "makeExtension": false, + }, + + "rules": { + "no-shadow": 0, + }, +}; diff --git a/toolkit/components/webextensions/test/mochitest/chrome.ini b/toolkit/components/webextensions/test/mochitest/chrome.ini new file mode 100644 index 000000000..26585cad7 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/chrome.ini @@ -0,0 +1,35 @@ +[DEFAULT] +support-files = + chrome_head.js + head.js + head_cookies.js + file_sample.html + webrequest_chromeworker.js + webrequest_test.jsm +tags = webextensions + +[test_chrome_ext_background_debug_global.html] +skip-if = (os == 'android') # android doesn't have devtools +[test_chrome_ext_background_page.html] +skip-if = (toolkit == 'android') # android doesn't have devtools +[test_chrome_ext_eventpage_warning.html] +[test_chrome_ext_contentscript_unrecognizedprop_warning.html] +skip-if = (os == 'android') # browser.tabs is undefined. Bug 1258975 on android. +[test_chrome_ext_hybrid_addons.html] +[test_chrome_ext_trustworthy_origin.html] +[test_chrome_ext_webnavigation_resolved_urls.html] +skip-if = (os == 'android') # browser.tabs is undefined. Bug 1258975 on android. +[test_chrome_ext_shutdown_cleanup.html] +[test_chrome_native_messaging_paths.html] +skip-if = os != "mac" && os != "linux" +[test_ext_cookies_expiry.html] +[test_ext_cookies_permissions_bad.html] +[test_ext_cookies_permissions_good.html] +[test_ext_cookies_containers.html] +[test_ext_jsversion.html] +[test_ext_schema.html] +[test_chrome_ext_storage_cleanup.html] +[test_chrome_ext_idle.html] +[test_chrome_ext_downloads_saveAs.html] +[test_chrome_ext_webrequest_background_events.html] +skip-if = os == 'android' # webrequest api unsupported (bug 1258975). diff --git a/toolkit/components/webextensions/test/mochitest/chrome_head.js b/toolkit/components/webextensions/test/mochitest/chrome_head.js new file mode 100644 index 000000000..da2f53a02 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/chrome_head.js @@ -0,0 +1,12 @@ +"use strict"; + +const { + classes: Cc, + interfaces: Ci, + utils: Cu, + results: Cr, +} = Components; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/NetUtil.jsm"); + diff --git a/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page1.html b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page1.html new file mode 100644 index 000000000..663ebc611 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page1.html @@ -0,0 +1,12 @@ + + + + + + + +
+
+ + + diff --git a/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page2.html b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page2.html new file mode 100644 index 000000000..cc1acc83d --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page2.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page3.html b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page3.html new file mode 100644 index 000000000..a0a26a2e9 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_WebNavigation_page3.html @@ -0,0 +1,9 @@ + + + + + +click me + + + diff --git a/toolkit/components/webextensions/test/mochitest/file_WebRequest_page3.html b/toolkit/components/webextensions/test/mochitest/file_WebRequest_page3.html new file mode 100644 index 000000000..5807dd439 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_WebRequest_page3.html @@ -0,0 +1,11 @@ + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/file_csp.html b/toolkit/components/webextensions/test/mochitest/file_csp.html new file mode 100644 index 000000000..206e44390 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_csp.html @@ -0,0 +1,14 @@ + + + + + + + + +
Sample text
+ + + + + diff --git a/toolkit/components/webextensions/test/mochitest/file_csp.html^headers^ b/toolkit/components/webextensions/test/mochitest/file_csp.html^headers^ new file mode 100644 index 000000000..4c6fa3c26 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_csp.html^headers^ @@ -0,0 +1 @@ +Content-Security-Policy: default-src 'self' diff --git a/toolkit/components/webextensions/test/mochitest/file_ext_test_api_injection.js b/toolkit/components/webextensions/test/mochitest/file_ext_test_api_injection.js new file mode 100644 index 000000000..06dfae65e --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_ext_test_api_injection.js @@ -0,0 +1,12 @@ +"use strict"; + +var {interfaces: Ci} = Components; + +Components.utils.import("resource://gre/modules/Services.jsm"); + +Services.console.registerListener(function listener(message) { + if (/WebExt Privilege Escalation/.test(message.message)) { + Services.console.unregisterListener(listener); + sendAsyncMessage("console-message", {message: message.message}); + } +}); diff --git a/toolkit/components/webextensions/test/mochitest/file_image_bad.png b/toolkit/components/webextensions/test/mochitest/file_image_bad.png new file mode 100644 index 0000000000000000000000000000000000000000..4c3be508477eb19cd08ddf4d0f568a06a4ec7a45 GIT binary patch literal 5401 zcmWldUu+x6eaC+@`zOm484PJsC8-t|9#_g9EgeW%V$=3zmhv&HlYCg&JcYK?fZCH> zQI>!tErOyzfgwc+v@92ES*J+nG+3T>4sGiWmMsf;q;2Y|Q*2bHvt0Y`wQ0GBTWAAU3Q{d~T2#d`M#0X41yKw#KBeb)P){PRb_-uq7+3jpD7hEE%Xe@4>d z3IghX>W2RBPtU7!c`G)Sjij1+H(u|LjJ(m~irW?n|SlBi|gv0JGOwku*mI3k6cIJ&jWx*DTzvbX`0$xLJg%qm@B&>G%? z@_dwj-Qb7Ppr>VAW`;fG zi+7(h$&TdE`}sZpe~!bA>)F<%FqBL=i`H{ea?gJws_utU`Sh%BDhIDF3`GM8Gw;f3 zVot^T;}BcPPvQ%H%XnqfK;RWpP^UD|H;<)mVkyS}b0z#YCn5@Pa?0 zC&RKSKaA+&mK8&(raa6K;4i}GI6eYuk_-)-?9rKO{GhXbokCpCvez{BM6r=%Z3ms2 zloqu4?BlpK8~SZ9JcP965>~eJb*TW+#7<*Q+CM$W`xn+FDM#+ZNE5&T!eGHdAzn__ zPRf)=5o)wt_faiQhAdFD%1kFzW~(&>sI6kFhxqFiZPmAlCMgWG=6q!&TDzw&Fgz}A zkGki_=CZC+TIOsSM0g%r3YO0) z%xwi*|F*_-m%#NrN@182Kd0fGGB6}Tr^-h) zG?nY^8-qQ*Lt%}LCO%iDc$_tobk!K8GAH;*Cb>B6Wb{=i%B1_`B>2~HGJ%xJjM&4) z*J)LL!3Kr0@T@hD%c$}JMgFXLf);>I;~1FI(2 zF7^V+h%44LdH5C`nqA;D%V@clb4r<=0b$;*U!*7nLQT3`ndEDSerEtGgmG)}J^Ea} zRGFdT;o07&3^jp0>$Fe3$WL^>qqJ|I>_HnyRTAQ%L*&~;wtWsL4%>s|QlfB^f2E&@ z8dl6CGbb(%vh9ITIS}lxeRGI&2_Hpb)i*uVM4(e&J+ktdc?zeZF#FM0a1qrUc;UQK zuuebYgG)1PYVKf~N zUw^9^n7Sx6dhhetqNbl};{)?Z`FvK9=+%$+EMa#bxBV}(n5^WTXZn}2uj#LzX`7Fu zSN7W9kh9D1Nn#DkW59-PyQS(QHsnrOc|hxhE<)pik&7yqTQ##wPr5b3(VIAy=$ z@f))8;h605pDcXEyN$V94@=}0+5UL)Xr(6Yah0R5qIb{Z^;vRFLlgj6v?(ewRt~byElMH@83MQ`(kB%1W~S!hIIH?@tG`d5e#N@%PxYQ%=6d?{HQ09V(?wzso6#iKye_Ah}fv7b^qm z4#X((Z4S~*Pp$e1{2jc#6h^KXWG=jKahrP4P)Pt=fZVA_4evE5lh9nN~SUyaw_BO}nj0F~st9g9i_PA3OqPbHh^8NBkbCg^dfGN!Tx0P)(q@V+HRn8}(CIGG=d%P&@lh`Z;@4-} z;j_JUpVGUH!{p?5_v+njkBVVYNpNcviRnb%*?~uAa`VyLHh;om22xt2-7~5AuSDu+ z3}jb-gr4bZ9BR4Odb>7r-y=ivlZ<_`1z~SW3u*c}>rb6aK3BuNp4mOQ63X>27Qm{2y|6Qz zF2jk(;YB2y9cncF(d_BhEAHqA0T%6NG6h+Lx>zaVvZo8ze|f;gOsyY}DBi!1&KEDZ z)gp`PqV0(TbRpF~sZX{;?NmLuU5)zpIlddD!T$njx>GT>JWXM}wFk#dQb)&pW>L%6 zk!WiU8xdlgK@->9JQz>hxG)&6N zF*&1@1K$so{Vs%czMk8ld5aU?eY~rtsV_$tgW^EPp^b6+@r9m?@}#P=cuA%8pwm&r z;TlfSb#q7;A+u@}CxwG?#@8uKjWGV8Z$;jeQe1RS>oik6t;0y${GMVCHP~x;flrbX zF5ZEqg=}J19Tr04&wGK3_B{s@w9C3=7fXZIGLvMUD~3L`*+>;Oq?p?unjDH-LV-NR z?ZsIhO^?u+&PUH|$8@kQWl>#0w*$HdPuaJh$t@I-AT3Ccl34K5!g^ zb4I+qR8gC-i*-KcxX&0kqU0$z{eugp<%t)QYp@$X+Eu3;-V(!!$mnfg>$xpFDMVO| zDk=K3-tWz_Z{NR-o9icUa=cE|AF(5)APu%Dg^x!>3xP{Wn(|UI;Z*b52qAQo!`wMnlN$r6Q2BATieg`-gM4U?X;(2}Iekze$< zSs`{svNn7}N3$oUA+`Bvw>Z?&n{Z4BW!qFBh25Z1ml)d`+z-RhtZ#;V`OSFDR;Nz7 z=dJvMZtfm(wX~ML;9Qa-ZhTtN_=nd;4b9D%ryiT;tag(fu?voPM0DXT(jVeQ9BZ5x zj%k~--r?mOw-0E{=xE_^yT64QTUG`=b;QCZQuPxWa)*wTxDX~{LNgx3H1vtI-x+O% zJR5br<|7z;bhkd3yEZn>?5J4tB8SC>^dD^nQ)bk>MZ}}gX_&0{?M=fm$GC9G@Cri2 zkwr8^drG*y+84l!ub{F%r>NhT%BT-$nPcxahg%S8kf)^c98f1~ObH27C}!h~@rl9YCF)C8qwE^0tRtx|k@?LtKCfIYPxnDY z{~sc1wP>w-ua_#%NpAHMG*R)1m9{0@!^T5uBv>9Jjpaym$Jl@ke9Oyk``guomkP0n zDyoxVf1{(^?>%WgP@0o_{D=4C%F*&U`c@{M1-U_|MVs)yMD( z%AL{rgmqiVd0k=}GMdlLvucicWDe{35(Kn-lkVc-?}E!UXTtsf^&ww*bpb?%hEU^Z z^cJY7fh3b9go33U?Y4JLPjwb=w!wtV_jn*CfZ)ZBOpxx{+BK==%1`^`E7(l1q0N zzz&47C&#ZjG<>6zRo7+GTDd+WtXt1u&*7FXzHY5t5)C_545dSTY~#B(=o;${;?Z4A z%viheYBXlNo;>I==5@dL zU6Pvyabe7g*zsNMVz(Z;>#Rzgr1$~EXqpkQ+$wTgL@%0AkN;0 zyJ&%i2}6{0DD#K)G49(rgXS=7jscJvI__x|ULfDupElyJ;>x8lzrCH1?L;A&i#7cP z@9sqvU4KIk!4AhhGfrTfVNks*w(=h=d2U%gVy`8jzklHueB*YtM|G-7F zViI{xasv(Il3LkJx>b$5pI36Aa8^g?*ng-?@9gaSt*os4-<6T^zln*-e<1(Y>eZ{a-@A8D7MlS80mJ}u z0SKQtbH>fs*!aH-1H=C_K)ecw?*efe5W7I}s#U9Y!PLVrKmdV>nKNfT1{(H16si$K zmjm&CV+al6D=8`c7X*o+82}JK4A3z64>JJB_`e(E3S)?2X{|^lf1sei(+1UtAY{Ww#jt?wfcn3@ zy!=0d5|Evi_8%aC7~Z{m#}1AKK|~<_M{=g1px}QcP=ErR57Iaj7$e5OumVLr$n^jL z1djz!sJcLHd57c@W2lWFi_p^m2m=HVoB>kgf@C|$pqa*ykjAAMgaHBwo)>`0c=vmt z+g3yQpuk*x7A(#H^u|wInF%0(FiZq_r2`t3pnwGh6fWCA7$ATcDb3CR0R{jJCzQv) SYsoAC0000 zQI>!tErOyzfgwc+v@92ES*J+nG+3T>4sGiWmMsf;q;2Y|Q*2bHvt0Y`wQ0GBTWAAU3Q{d~T2#d`M#0X41yKw#KBeb)P){PRb_-uq7+3jpD7hEE%Xe@4>d z3IghX>W2RBPtU7!c`G)Sjij1+H(u|LjJ(m~irW?n|SlBi|gv0JGOwku*mI3k6cIJ&jWx*DTzvbX`0$xLJg%qm@B&>G%? z@_dwj-Qb7Ppr>VAW`;fG zi+7(h$&TdE`}sZpe~!bA>)F<%FqBL=i`H{ea?gJws_utU`Sh%BDhIDF3`GM8Gw;f3 zVot^T;}BcPPvQ%H%XnqfK;RWpP^UD|H;<)mVkyS}b0z#YCn5@Pa?0 zC&RKSKaA+&mK8&(raa6K;4i}GI6eYuk_-)-?9rKO{GhXbokCpCvez{BM6r=%Z3ms2 zloqu4?BlpK8~SZ9JcP965>~eJb*TW+#7<*Q+CM$W`xn+FDM#+ZNE5&T!eGHdAzn__ zPRf)=5o)wt_faiQhAdFD%1kFzW~(&>sI6kFhxqFiZPmAlCMgWG=6q!&TDzw&Fgz}A zkGki_=CZC+TIOsSM0g%r3YO0) z%xwi*|F*_-m%#NrN@182Kd0fGGB6}Tr^-h) zG?nY^8-qQ*Lt%}LCO%iDc$_tobk!K8GAH;*Cb>B6Wb{=i%B1_`B>2~HGJ%xJjM&4) z*J)LL!3Kr0@T@hD%c$}JMgFXLf);>I;~1FI(2 zF7^V+h%44LdH5C`nqA;D%V@clb4r<=0b$;*U!*7nLQT3`ndEDSerEtGgmG)}J^Ea} zRGFdT;o07&3^jp0>$Fe3$WL^>qqJ|I>_HnyRTAQ%L*&~;wtWsL4%>s|QlfB^f2E&@ z8dl6CGbb(%vh9ITIS}lxeRGI&2_Hpb)i*uVM4(e&J+ktdc?zeZF#FM0a1qrUc;UQK zuuebYgG)1PYVKf~N zUw^9^n7Sx6dhhetqNbl};{)?Z`FvK9=+%$+EMa#bxBV}(n5^WTXZn}2uj#LzX`7Fu zSN7W9kh9D1Nn#DkW59-PyQS(QHsnrOc|hxhE<)pik&7yqTQ##wPr5b3(VIAy=$ z@f))8;h605pDcXEyN$V94@=}0+5UL)Xr(6Yah0R5qIb{Z^;vRFLlgj6v?(ewRt~byElMH@83MQ`(kB%1W~S!hIIH?@tG`d5e#N@%PxYQ%=6d?{HQ09V(?wzso6#iKye_Ah}fv7b^qm z4#X((Z4S~*Pp$e1{2jc#6h^KXWG=jKahrP4P)Pt=fZVA_4evE5lh9nN~SUyaw_BO}nj0F~st9g9i_PA3OqPbHh^8NBkbCg^dfGN!Tx0P)(q@V+HRn8}(CIGG=d%P&@lh`Z;@4-} z;j_JUpVGUH!{p?5_v+njkBVVYNpNcviRnb%*?~uAa`VyLHh;om22xt2-7~5AuSDu+ z3}jb-gr4bZ9BR4Odb>7r-y=ivlZ<_`1z~SW3u*c}>rb6aK3BuNp4mOQ63X>27Qm{2y|6Qz zF2jk(;YB2y9cncF(d_BhEAHqA0T%6NG6h+Lx>zaVvZo8ze|f;gOsyY}DBi!1&KEDZ z)gp`PqV0(TbRpF~sZX{;?NmLuU5)zpIlddD!T$njx>GT>JWXM}wFk#dQb)&pW>L%6 zk!WiU8xdlgK@->9JQz>hxG)&6N zF*&1@1K$so{Vs%czMk8ld5aU?eY~rtsV_$tgW^EPp^b6+@r9m?@}#P=cuA%8pwm&r z;TlfSb#q7;A+u@}CxwG?#@8uKjWGV8Z$;jeQe1RS>oik6t;0y${GMVCHP~x;flrbX zF5ZEqg=}J19Tr04&wGK3_B{s@w9C3=7fXZIGLvMUD~3L`*+>;Oq?p?unjDH-LV-NR z?ZsIhO^?u+&PUH|$8@kQWl>#0w*$HdPuaJh$t@I-AT3Ccl34K5!g^ zb4I+qR8gC-i*-KcxX&0kqU0$z{eugp<%t)QYp@$X+Eu3;-V(!!$mnfg>$xpFDMVO| zDk=K3-tWz_Z{NR-o9icUa=cE|AF(5)APu%Dg^x!>3xP{Wn(|UI;Z*b52qAQo!`wMnlN$r6Q2BATieg`-gM4U?X;(2}Iekze$< zSs`{svNn7}N3$oUA+`Bvw>Z?&n{Z4BW!qFBh25Z1ml)d`+z-RhtZ#;V`OSFDR;Nz7 z=dJvMZtfm(wX~ML;9Qa-ZhTtN_=nd;4b9D%ryiT;tag(fu?voPM0DXT(jVeQ9BZ5x zj%k~--r?mOw-0E{=xE_^yT64QTUG`=b;QCZQuPxWa)*wTxDX~{LNgx3H1vtI-x+O% zJR5br<|7z;bhkd3yEZn>?5J4tB8SC>^dD^nQ)bk>MZ}}gX_&0{?M=fm$GC9G@Cri2 zkwr8^drG*y+84l!ub{F%r>NhT%BT-$nPcxahg%S8kf)^c98f1~ObH27C}!h~@rl9YCF)C8qwE^0tRtx|k@?LtKCfIYPxnDY z{~sc1wP>w-ua_#%NpAHMG*R)1m9{0@!^T5uBv>9Jjpaym$Jl@ke9Oyk``guomkP0n zDyoxVf1{(^?>%WgP@0o_{D=4C%F*&U`c@{M1-U_|MVs)yMD( z%AL{rgmqiVd0k=}GMdlLvucicWDe{35(Kn-lkVc-?}E!UXTtsf^&ww*bpb?%hEU^Z z^cJY7fh3b9go33U?Y4JLPjwb=w!wtV_jn*CfZ)ZBOpxx{+BK==%1`^`E7(l1q0N zzz&47C&#ZjG<>6zRo7+GTDd+WtXt1u&*7FXzHY5t5)C_545dSTY~#B(=o;${;?Z4A z%viheYBXlNo;>I==5@dL zU6Pvyabe7g*zsNMVz(Z;>#Rzgr1$~EXqpkQ+$wTgL@%0AkN;0 zyJ&%i2}6{0DD#K)G49(rgXS=7jscJvI__x|ULfDupElyJ;>x8lzrCH1?L;A&i#7cP z@9sqvU4KIk!4AhhGfrTfVNks*w(=h=d2U%gVy`8jzklHueB*YtM|G-7F zViI{xasv(Il3LkJx>b$5pI36Aa8^g?*ng- + + + + + + + +
Sample text
+ + + + diff --git a/toolkit/components/webextensions/test/mochitest/file_permission_xhr.html b/toolkit/components/webextensions/test/mochitest/file_permission_xhr.html new file mode 100644 index 000000000..22a55f90d --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_permission_xhr.html @@ -0,0 +1,55 @@ + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/file_privilege_escalation.html b/toolkit/components/webextensions/test/mochitest/file_privilege_escalation.html new file mode 100644 index 000000000..258f7058d --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_privilege_escalation.html @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/file_sample.html b/toolkit/components/webextensions/test/mochitest/file_sample.html new file mode 100644 index 000000000..a20e49a1f --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_sample.html @@ -0,0 +1,12 @@ + + + + + + + + +
Sample text
+ + + diff --git a/toolkit/components/webextensions/test/mochitest/file_script_bad.js b/toolkit/components/webextensions/test/mochitest/file_script_bad.js new file mode 100644 index 000000000..c425122c7 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_script_bad.js @@ -0,0 +1,3 @@ +"use strict"; + +window.failure = true; diff --git a/toolkit/components/webextensions/test/mochitest/file_script_good.js b/toolkit/components/webextensions/test/mochitest/file_script_good.js new file mode 100644 index 000000000..1848edf68 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_script_good.js @@ -0,0 +1,3 @@ +"use strict"; + +window.success = window.success ? window.success + 1 : 1; diff --git a/toolkit/components/webextensions/test/mochitest/file_script_redirect.js b/toolkit/components/webextensions/test/mochitest/file_script_redirect.js new file mode 100644 index 000000000..c89a196c2 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_script_redirect.js @@ -0,0 +1,4 @@ +"use strict"; + +window.failure = true; + diff --git a/toolkit/components/webextensions/test/mochitest/file_script_xhr.js b/toolkit/components/webextensions/test/mochitest/file_script_xhr.js new file mode 100644 index 000000000..07f80eb2e --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_script_xhr.js @@ -0,0 +1,5 @@ +"use strict"; + +var request = new XMLHttpRequest(); +request.open("get", "http://mochi.test:8888/tests/toolkit/components/extensions/test/mochitest/xhr_resource", false); +request.send(); diff --git a/toolkit/components/webextensions/test/mochitest/file_style_bad.css b/toolkit/components/webextensions/test/mochitest/file_style_bad.css new file mode 100644 index 000000000..8dbc8dc7a --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_style_bad.css @@ -0,0 +1,3 @@ +#test { + color: green !important; +} diff --git a/toolkit/components/webextensions/test/mochitest/file_style_good.css b/toolkit/components/webextensions/test/mochitest/file_style_good.css new file mode 100644 index 000000000..46f9774b5 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_style_good.css @@ -0,0 +1,3 @@ +#test { + color: red; +} diff --git a/toolkit/components/webextensions/test/mochitest/file_style_redirect.css b/toolkit/components/webextensions/test/mochitest/file_style_redirect.css new file mode 100644 index 000000000..8dbc8dc7a --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_style_redirect.css @@ -0,0 +1,3 @@ +#test { + color: green !important; +} diff --git a/toolkit/components/webextensions/test/mochitest/file_teardown_test.js b/toolkit/components/webextensions/test/mochitest/file_teardown_test.js new file mode 100644 index 000000000..7246012ad --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_teardown_test.js @@ -0,0 +1,24 @@ +"use strict"; + +/* globals addMessageListener */ +let {Management} = Components.utils.import("resource://gre/modules/Extension.jsm", {}); +let events = []; +function record(type, extensionContext) { + let eventType = type == "proxy-context-load" ? "load" : "unload"; + let url = extensionContext.uri.spec; + let extensionId = extensionContext.extension.id; + events.push({eventType, url, extensionId}); +} + +Management.on("proxy-context-load", record); +Management.on("proxy-context-unload", record); +addMessageListener("cleanup", () => { + Management.off("proxy-context-load", record); + Management.off("proxy-context-unload", record); +}); + +addMessageListener("get-context-events", extensionId => { + sendAsyncMessage("context-events", events); + events = []; +}); +sendAsyncMessage("chromescript-startup"); diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect.html new file mode 100644 index 000000000..cba3043f7 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect.html @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html new file mode 100644 index 000000000..c5b436979 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html^headers^ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html^headers^ new file mode 100644 index 000000000..574a392a1 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_clientRedirect_httpHeaders.html^headers^ @@ -0,0 +1 @@ +Refresh: 1;url=dummy_page.html diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameClientRedirect.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameClientRedirect.html new file mode 100644 index 000000000..d360bcbb1 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameClientRedirect.html @@ -0,0 +1,12 @@ + + + + + + + +
+
+ + + diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameRedirect.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameRedirect.html new file mode 100644 index 000000000..06dbd4374 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_frameRedirect.html @@ -0,0 +1,12 @@ + + + + + + + +
+
+ + + diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe.html new file mode 100644 index 000000000..307990714 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe.html @@ -0,0 +1,12 @@ + + + + + + + +
+
+ + + diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page1.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page1.html new file mode 100644 index 000000000..55bb7aa6a --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page1.html @@ -0,0 +1,8 @@ + + + + +

page1

+ page2 + + diff --git a/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page2.html b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page2.html new file mode 100644 index 000000000..8f589f8bb --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_webNavigation_manualSubframe_page2.html @@ -0,0 +1,7 @@ + + + + +

page2

+ + diff --git a/toolkit/components/webextensions/test/mochitest/file_with_about_blank.html b/toolkit/components/webextensions/test/mochitest/file_with_about_blank.html new file mode 100644 index 000000000..af51c2e52 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/file_with_about_blank.html @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/head.js b/toolkit/components/webextensions/test/mochitest/head.js new file mode 100644 index 000000000..1b1a29472 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/head.js @@ -0,0 +1,13 @@ +"use strict"; + +/* exported waitForLoad */ + +function waitForLoad(win) { + return new Promise(resolve => { + win.addEventListener("load", function listener() { + win.removeEventListener("load", listener, true); + resolve(); + }, true); + }); +} + diff --git a/toolkit/components/webextensions/test/mochitest/head_cookies.js b/toolkit/components/webextensions/test/mochitest/head_cookies.js new file mode 100644 index 000000000..9f6966551 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/head_cookies.js @@ -0,0 +1,167 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +/* exported testCookies */ + +function* testCookies(options) { + // Changing the options object is a bit of a hack, but it allows us to easily + // pass an expiration date to the background script. + options.expiry = Date.now() / 1000 + 3600; + + async function background(backgroundOptions) { + // Ask the parent scope to change some cookies we may or may not have + // permission for. + let awaitChanges = new Promise(resolve => { + browser.test.onMessage.addListener(msg => { + browser.test.assertEq("cookies-changed", msg, "browser.test.onMessage"); + resolve(); + }); + }); + + let changed = []; + browser.cookies.onChanged.addListener(event => { + changed.push(`${event.cookie.name}:${event.cause}`); + }); + browser.test.sendMessage("change-cookies"); + + + // Try to access some cookies in various ways. + let {url, domain, secure} = backgroundOptions; + + let failures = 0; + let tallyFailure = error => { + failures++; + }; + + try { + await awaitChanges; + + let cookie = await browser.cookies.get({url, name: "foo"}); + browser.test.assertEq(backgroundOptions.shouldPass, cookie != null, "should pass == get cookie"); + + let cookies = await browser.cookies.getAll({domain}); + if (backgroundOptions.shouldPass) { + browser.test.assertEq(2, cookies.length, "expected number of cookies"); + } else { + browser.test.assertEq(0, cookies.length, "expected number of cookies"); + } + + await Promise.all([ + browser.cookies.set({url, domain, secure, name: "foo", "value": "baz", expirationDate: backgroundOptions.expiry}).catch(tallyFailure), + browser.cookies.set({url, domain, secure, name: "bar", "value": "quux", expirationDate: backgroundOptions.expiry}).catch(tallyFailure), + browser.cookies.remove({url, name: "deleted"}), + ]); + + if (backgroundOptions.shouldPass) { + // The order of eviction events isn't guaranteed, so just check that + // it's there somewhere. + let evicted = changed.indexOf("evicted:evicted"); + if (evicted < 0) { + browser.test.fail("got no eviction event"); + } else { + browser.test.succeed("got eviction event"); + changed.splice(evicted, 1); + } + + browser.test.assertEq("x:explicit,x:overwrite,x:explicit,x:explicit,foo:overwrite,foo:explicit,bar:explicit,deleted:explicit", + changed.join(","), "expected changes"); + } else { + browser.test.assertEq("", changed.join(","), "expected no changes"); + } + + if (!(backgroundOptions.shouldPass || backgroundOptions.shouldWrite)) { + browser.test.assertEq(2, failures, "Expected failures"); + } else { + browser.test.assertEq(0, failures, "Expected no failures"); + } + + browser.test.notifyPass("cookie-permissions"); + } catch (error) { + browser.test.fail(`Error: ${error} :: ${error.stack}`); + browser.test.notifyFail("cookie-permissions"); + } + } + + let extension = ExtensionTestUtils.loadExtension({ + manifest: { + "permissions": options.permissions, + }, + + background: `(${background})(${JSON.stringify(options)})`, + }); + + + let cookieSvc = SpecialPowers.Services.cookies; + + let domain = options.domain.replace(/^\.?/, "."); + + // This will be evicted after we add a fourth cookie. + cookieSvc.add(domain, "/", "evicted", "bar", options.secure, false, false, options.expiry); + // This will be modified by the background script. + cookieSvc.add(domain, "/", "foo", "bar", options.secure, false, false, options.expiry); + // This will be deleted by the background script. + cookieSvc.add(domain, "/", "deleted", "bar", options.secure, false, false, options.expiry); + + + yield extension.startup(); + + yield extension.awaitMessage("change-cookies"); + cookieSvc.add(domain, "/", "x", "y", options.secure, false, false, options.expiry); + cookieSvc.add(domain, "/", "x", "z", options.secure, false, false, options.expiry); + cookieSvc.remove(domain, "x", "/", false, {}); + extension.sendMessage("cookies-changed"); + + yield extension.awaitFinish("cookie-permissions"); + yield extension.unload(); + + + function getCookies(host) { + let cookies = []; + let enum_ = cookieSvc.getCookiesFromHost(host, {}); + while (enum_.hasMoreElements()) { + cookies.push(enum_.getNext().QueryInterface(SpecialPowers.Ci.nsICookie2)); + } + return cookies.sort((a, b) => String.localeCompare(a.name, b.name)); + } + + let cookies = getCookies(options.domain); + info(`Cookies: ${cookies.map(c => `${c.name}=${c.value}`)}`); + + if (options.shouldPass) { + is(cookies.length, 2, "expected two cookies for host"); + + is(cookies[0].name, "bar", "correct cookie name"); + is(cookies[0].value, "quux", "correct cookie value"); + + is(cookies[1].name, "foo", "correct cookie name"); + is(cookies[1].value, "baz", "correct cookie value"); + } else if (options.shouldWrite) { + // Note: |shouldWrite| applies only when |shouldPass| is false. + // This is necessary because, unfortunately, websites (and therefore web + // extensions) are allowed to write some cookies which they're not allowed + // to read. + is(cookies.length, 3, "expected three cookies for host"); + + is(cookies[0].name, "bar", "correct cookie name"); + is(cookies[0].value, "quux", "correct cookie value"); + + is(cookies[1].name, "deleted", "correct cookie name"); + + is(cookies[2].name, "foo", "correct cookie name"); + is(cookies[2].value, "baz", "correct cookie value"); + } else { + is(cookies.length, 2, "expected two cookies for host"); + + is(cookies[0].name, "deleted", "correct second cookie name"); + + is(cookies[1].name, "foo", "correct cookie name"); + is(cookies[1].value, "bar", "correct cookie value"); + } + + for (let cookie of cookies) { + cookieSvc.remove(cookie.host, cookie.name, "/", false, {}); + } + // Make sure we don't silently poison subsequent tests if something goes wrong. + is(getCookies(options.domain).length, 0, "cookies cleared"); +} diff --git a/toolkit/components/webextensions/test/mochitest/head_webrequest.js b/toolkit/components/webextensions/test/mochitest/head_webrequest.js new file mode 100644 index 000000000..96924e505 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/head_webrequest.js @@ -0,0 +1,331 @@ +"use strict"; + +let commonEvents = { + "onBeforeRequest": [{urls: [""]}, ["blocking"]], + "onBeforeSendHeaders": [{urls: [""]}, ["blocking", "requestHeaders"]], + "onSendHeaders": [{urls: [""]}, ["requestHeaders"]], + "onBeforeRedirect": [{urls: [""]}], + "onHeadersReceived": [{urls: [""]}, ["blocking", "responseHeaders"]], + "onResponseStarted": [{urls: [""]}], + "onCompleted": [{urls: [""]}, ["responseHeaders"]], + "onErrorOccurred": [{urls: [""]}], +}; + +function background(events) { + let expect; + let ignore; + let defaultOrigin; + + browser.test.onMessage.addListener((msg, expected) => { + if (msg !== "set-expected") { + return; + } + expect = expected.expect; + defaultOrigin = expected.origin; + ignore = expected.ignore; + let promises = []; + // Initialize some stuff we'll need in the tests. + for (let entry of Object.values(expect)) { + // a place for the test infrastructure to store some state. + entry.test = {}; + // Each entry in expected gets a Promise that will be resolved in the + // last event for that entry. This will either be onCompleted, or the + // last entry if an events list was provided. + promises.push(new Promise(resolve => { entry.test.resolve = resolve; })); + // If events was left undefined, we're expecting all normal events we're + // listening for, exclude onBeforeRedirect and onErrorOccurred + if (entry.events === undefined) { + entry.events = Object.keys(events).filter(name => name != "onErrorOccurred" && name != "onBeforeRedirect"); + } + if (entry.optional_events === undefined) { + entry.optional_events = []; + } + } + // When every expected entry has finished our test is done. + Promise.all(promises).then(() => { + browser.test.sendMessage("done"); + }); + browser.test.sendMessage("continue"); + }); + + // Retrieve the per-file/test expected values. + function getExpected(details) { + let url = new URL(details.url); + let filename; + if (url.protocol == "data:") { + // pathname is everything after protocol. + filename = url.pathname; + } else { + filename = url.pathname.split("/").pop(); + } + if (ignore && ignore.includes(filename)) { + return; + } + let expected = expect[filename]; + if (!expected) { + browser.test.fail(`unexpected request ${filename}`); + return; + } + // Save filename for redirect verification. + expected.test.filename = filename; + return expected; + } + + // Process any test header modifications that can happen in request or response phases. + // If a test includes headers, it needs a complete header object, no undefined + // objects even if empty: + // request: { + // add: {"HeaderName": "value",}, + // modify: {"HeaderName": "value",}, + // remove: ["HeaderName",], + // }, + // response: { + // add: {"HeaderName": "value",}, + // modify: {"HeaderName": "value",}, + // remove: ["HeaderName",], + // }, + function processHeaders(phase, expected, details) { + // This should only happen once per phase [request|response]. + browser.test.assertFalse(!!expected.test[phase], `First processing of headers for ${phase}`); + expected.test[phase] = true; + + let headers = details[`${phase}Headers`]; + browser.test.assertTrue(Array.isArray(headers), `${phase}Headers array present`); + + let {add, modify, remove} = expected.headers[phase]; + + for (let name in add) { + browser.test.assertTrue(!headers.find(h => h.name === name), `header ${name} to be added not present yet in ${phase}Headers`); + let header = {name: name}; + if (name.endsWith("-binary")) { + header.binaryValue = Array.from(add[name], c => c.charCodeAt(0)); + } else { + header.value = add[name]; + } + headers.push(header); + } + + let modifiedAny = false; + for (let header of headers) { + if (header.name.toLowerCase() in modify) { + header.value = modify[header.name.toLowerCase()]; + modifiedAny = true; + } + } + browser.test.assertTrue(modifiedAny, `at least one ${phase}Headers element to modify`); + + let deletedAny = false; + for (let j = headers.length; j-- > 0;) { + if (remove.includes(headers[j].name.toLowerCase())) { + headers.splice(j, 1); + deletedAny = true; + } + } + browser.test.assertTrue(deletedAny, `at least one ${phase}Headers element to delete`); + + return headers; + } + + // phase is request or response. + function checkHeaders(phase, expected, details) { + if (!/^https?:/.test(details.url)) { + return; + } + + let headers = details[`${phase}Headers`]; + browser.test.assertTrue(Array.isArray(headers), `valid ${phase}Headers array`); + + let {add, modify, remove} = expected.headers[phase]; + for (let name in add) { + let value = headers.find(h => h.name.toLowerCase() === name.toLowerCase()).value; + browser.test.assertEq(value, add[name], `header ${name} correctly injected in ${phase}Headers`); + } + + for (let name in modify) { + let value = headers.find(h => h.name.toLowerCase() === name.toLowerCase()).value; + browser.test.assertEq(value, modify[name], `header ${name} matches modified value`); + } + + for (let name of remove) { + let found = headers.find(h => h.name.toLowerCase() === name.toLowerCase()); + browser.test.assertFalse(!!found, `deleted header ${name} still found in ${phase}Headers`); + } + } + + function getListener(name) { + return details => { + let result = {}; + browser.test.log(`${name} ${details.requestId} ${details.url}`); + let expected = getExpected(details); + if (!expected) { + return result; + } + let expectedEvent = expected.events[0] == name; + if (expectedEvent) { + expected.events.shift(); + } else { + expectedEvent = expected.optional_events[0] == name; + if (expectedEvent) { + expected.optional_events.shift(); + } + } + browser.test.assertTrue(expectedEvent, `received ${name}`); + browser.test.assertEq(expected.type, details.type, "resource type is correct"); + browser.test.assertEq(expected.origin || defaultOrigin, details.originUrl, "origin is correct"); + + if (name == "onBeforeRequest") { + // Save some values to test request consistency in later events. + browser.test.assertTrue(details.tabId !== undefined, `tabId ${details.tabId}`); + browser.test.assertTrue(details.requestId !== undefined, `requestId ${details.requestId}`); + // Validate requestId if it's already set, this happens with redirects. + if (expected.test.requestId !== undefined) { + browser.test.assertEq("string", typeof expected.test.requestId, `requestid ${expected.test.requestId} is string`); + browser.test.assertEq("string", typeof details.requestId, `requestid ${details.requestId} is string`); + browser.test.assertEq("number", typeof parseInt(details.requestId, 10), "parsed requestid is number"); + browser.test.assertNotEq(expected.test.requestId, details.requestId, + `last requestId ${expected.test.requestId} different from this one ${details.requestId}`); + } else { + // Save any values we want to validate in later events. + expected.test.requestId = details.requestId; + expected.test.tabId = details.tabId; + } + // Tests we don't need to do every event. + browser.test.assertTrue(details.type.toUpperCase() in browser.webRequest.ResourceType, `valid resource type ${details.type}`); + if (details.type == "main_frame") { + browser.test.assertEq(0, details.frameId, "frameId is zero when type is main_frame bug 1329299"); + } + } else { + // On events after onBeforeRequest, check the previous values. + browser.test.assertEq(expected.test.requestId, details.requestId, "correct requestId"); + browser.test.assertEq(expected.test.tabId, details.tabId, "correct tabId"); + } + if (name == "onBeforeSendHeaders") { + if (expected.headers && expected.headers.request) { + result.requestHeaders = processHeaders("request", expected, details); + } + if (expected.redirect) { + browser.test.log(`${name} redirect request`); + result.redirectUrl = details.url.replace(expected.test.filename, expected.redirect); + } + } + if (name == "onSendHeaders") { + if (expected.headers && expected.headers.request) { + checkHeaders("request", expected, details); + } + } + if (name == "onHeadersReceived") { + browser.test.assertEq(expected.status || 200, details.statusCode, + `expected HTTP status received for ${details.url}`); + if (expected.headers && expected.headers.response) { + result.responseHeaders = processHeaders("response", expected, details); + } + } + if (name == "onCompleted") { + // If we have already completed a GET request for this url, + // and it was found, we expect for the response to come fromCache. + // expected.cached may be undefined, force boolean. + let expectCached = !!expected.cached && details.method === "GET" && details.statusCode != 404; + browser.test.assertEq(expectCached, details.fromCache, "fromCache is correct"); + // We can only tell IPs for non-cached HTTP requests. + if (!details.fromCache && /^https?:/.test(details.url)) { + browser.test.assertEq("127.0.0.1", details.ip, `correct ip for ${details.url}`); + } + if (expected.headers && expected.headers.response) { + checkHeaders("response", expected, details); + } + } + + if (expected.cancel && expected.cancel == name) { + browser.test.log(`${name} cancel request`); + browser.test.sendMessage("cancelled"); + result.cancel = true; + } + // If we've used up all the events for this test, resolve the promise. + // If something wrong happens and more events come through, there will be + // failures. + if (expected.events.length <= 0) { + expected.test.resolve(); + } + return result; + }; + } + + for (let [name, args] of Object.entries(events)) { + browser.test.log(`adding listener for ${name}`); + try { + browser.webRequest[name].addListener(getListener(name), ...args); + } catch (e) { + browser.test.assertTrue(/\brequestBody\b/.test(e.message), + "Request body is unsupported"); + + // RequestBody is disabled in release builds. + if (!/\brequestBody\b/.test(e.message)) { + throw e; + } + + args.splice(args.indexOf("requestBody"), 1); + browser.webRequest[name].addListener(getListener(name), ...args); + } + } +} + +/* exported makeExtension */ + +function makeExtension(events = commonEvents) { + return ExtensionTestUtils.loadExtension({ + manifest: { + permissions: [ + "webRequest", + "webRequestBlocking", + "", + ], + }, + background: `(${background})(${JSON.stringify(events)})`, + }); +} + +/* exported addStylesheet */ + +function addStylesheet(file) { + let link = document.createElement("link"); + link.setAttribute("rel", "stylesheet"); + link.setAttribute("href", file); + document.body.appendChild(link); +} + +/* exported addLink */ + +function addLink(file) { + let a = document.createElement("a"); + a.setAttribute("href", file); + a.setAttribute("target", "_blank"); + document.body.appendChild(a); + return a; +} + +/* exported addImage */ + +function addImage(file) { + let img = document.createElement("img"); + img.setAttribute("src", file); + document.body.appendChild(img); +} + +/* exported addScript */ + +function addScript(file) { + let script = document.createElement("script"); + script.setAttribute("type", "text/javascript"); + script.setAttribute("src", file); + document.getElementsByTagName("head").item(0).appendChild(script); +} + +/* exported addFrame */ + +function addFrame(file) { + let frame = document.createElement("iframe"); + frame.setAttribute("width", "200"); + frame.setAttribute("height", "200"); + frame.setAttribute("src", file); + document.body.appendChild(frame); +} diff --git a/toolkit/components/webextensions/test/mochitest/mochitest.ini b/toolkit/components/webextensions/test/mochitest/mochitest.ini new file mode 100644 index 000000000..1f61060ad --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/mochitest.ini @@ -0,0 +1,115 @@ +[DEFAULT] +support-files = + head.js + file_mixed.html + head_webrequest.js + file_csp.html + file_csp.html^headers^ + file_WebRequest_page3.html + file_webNavigation_clientRedirect.html + file_webNavigation_clientRedirect_httpHeaders.html + file_webNavigation_clientRedirect_httpHeaders.html^headers^ + file_webNavigation_frameClientRedirect.html + file_webNavigation_frameRedirect.html + file_webNavigation_manualSubframe.html + file_webNavigation_manualSubframe_page1.html + file_webNavigation_manualSubframe_page2.html + file_WebNavigation_page1.html + file_WebNavigation_page2.html + file_WebNavigation_page3.html + file_with_about_blank.html + file_image_good.png + file_image_bad.png + file_image_redirect.png + file_style_good.css + file_style_bad.css + file_style_redirect.css + file_script_good.js + file_script_bad.js + file_script_redirect.js + file_script_xhr.js + file_sample.html + redirection.sjs + file_privilege_escalation.html + file_ext_test_api_injection.js + file_permission_xhr.html + file_teardown_test.js + return_headers.sjs + webrequest_worker.js +tags = webextensions + +[test_clipboard.html] +# skip-if = # disabled test case with_permission_allow_copy, see inline comment. +[test_ext_inIncognitoContext_window.html] +skip-if = os == 'android' # Android does not currently support windows. +[test_ext_geturl.html] +[test_ext_background_canvas.html] +[test_ext_content_security_policy.html] +[test_ext_contentscript.html] +[test_ext_contentscript_api_injection.html] +[test_ext_contentscript_async_loading.html] +[test_ext_contentscript_context.html] +[test_ext_contentscript_create_iframe.html] +[test_ext_contentscript_devtools_metadata.html] +[test_ext_contentscript_exporthelpers.html] +[test_ext_contentscript_css.html] +[test_ext_contentscript_about_blank.html] +[test_ext_contentscript_permission.html] +skip-if = os == 'android' # Android does not support tabs API. Bug 1260250 +[test_ext_contentscript_teardown.html] +skip-if = (os == 'android') # Android does not support tabs API. Bug 1260250 +[test_ext_exclude_include_globs.html] +[test_ext_external_messaging.html] +[test_ext_i18n_css.html] +[test_ext_generate.html] +[test_ext_notifications.html] +[test_ext_permission_xhr.html] +[test_ext_runtime_connect.html] +skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975). +[test_ext_runtime_connect_twoway.html] +skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975). +[test_ext_runtime_connect2.html] +skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975). +[test_ext_runtime_disconnect.html] +[test_ext_runtime_id.html] +[test_ext_sandbox_var.html] +[test_ext_sendmessage_reply.html] +skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975). +[test_ext_sendmessage_reply2.html] +skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975). +[test_ext_sendmessage_doublereply.html] +skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975). +[test_ext_sendmessage_no_receiver.html] +[test_ext_storage_content.html] +[test_ext_storage_tab.html] +skip-if = os == 'android' # Android does not currently support tabs. +[test_ext_test.html] +[test_ext_cookies.html] +skip-if = os == 'android' # Bug 1258975 on android. +[test_ext_background_api_injection.html] +[test_ext_background_generated_url.html] +[test_ext_background_teardown.html] +[test_ext_tab_teardown.html] +skip-if = (os == 'android') # Android does not support tabs API. Bug 1260250 +[test_ext_unload_frame.html] +[test_ext_i18n.html] +skip-if = (os == 'android') # Bug 1258975 on android. +[test_ext_listener_proxies.html] +[test_ext_web_accessible_resources.html] +skip-if = (os == 'android') # Bug 1258975 on android. +[test_ext_webrequest_background_events.html] +skip-if = os == 'android' # webrequest api unsupported (bug 1258975). +[test_ext_webrequest_basic.html] +skip-if = os == 'android' # webrequest api unsupported (bug 1258975). +[test_ext_webrequest_suspend.html] +skip-if = os == 'android' # webrequest api unsupported (bug 1258975). +[test_ext_webrequest_upload.html] +skip-if = release_or_beta || os == 'android' # webrequest api unsupported (bug 1258975). +[test_ext_webnavigation.html] +skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975). +[test_ext_webnavigation_filters.html] +skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975). +[test_ext_window_postMessage.html] +[test_ext_subframes_privileges.html] +skip-if = os == 'android' # port.sender.tab is undefined on Android (bug 1258975). +[test_ext_xhr_capabilities.html] diff --git a/toolkit/components/webextensions/test/mochitest/redirection.sjs b/toolkit/components/webextensions/test/mochitest/redirection.sjs new file mode 100644 index 000000000..370ecd213 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/redirection.sjs @@ -0,0 +1,4 @@ +function handleRequest(aRequest, aResponse) { + aResponse.setStatusLine(aRequest.httpVersion, 302); + aResponse.setHeader("Location", "./dummy_page.html"); +} diff --git a/toolkit/components/webextensions/test/mochitest/return_headers.sjs b/toolkit/components/webextensions/test/mochitest/return_headers.sjs new file mode 100644 index 000000000..54e2e5fb4 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/return_headers.sjs @@ -0,0 +1,20 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set ft=javascript sts=2 sw=2 et tw=80: */ +"use strict"; + +/* exported handleRequest */ + +function handleRequest(request, response) { + response.setHeader("Content-Type", "text/plain", false); + + let headers = {}; + // Why on earth is this a nsISimpleEnumerator... + let enumerator = request.headers; + while (enumerator.hasMoreElements()) { + let header = enumerator.getNext().data; + headers[header.toLowerCase()] = request.getHeader(header); + } + + response.write(JSON.stringify(headers)); +} + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_debug_global.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_debug_global.html new file mode 100644 index 000000000..0edf5ea86 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_debug_global.html @@ -0,0 +1,166 @@ + + + + WebExtension test + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_page.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_page.html new file mode 100644 index 000000000..471c5339d --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_background_page.html @@ -0,0 +1,84 @@ + + + + WebExtension test + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_contentscript_unrecognizedprop_warning.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_contentscript_unrecognizedprop_warning.html new file mode 100644 index 000000000..e08121a8f --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_contentscript_unrecognizedprop_warning.html @@ -0,0 +1,80 @@ + + + + Test for content script unrecognized property on manifest + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_downloads_saveAs.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_downloads_saveAs.html new file mode 100644 index 000000000..c1aaae035 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_downloads_saveAs.html @@ -0,0 +1,68 @@ + + + + Test downloads.download() saveAs option + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_eventpage_warning.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_eventpage_warning.html new file mode 100644 index 000000000..ecea8237e --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_eventpage_warning.html @@ -0,0 +1,106 @@ + + + + Test for WebExtension EventPage Warning + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_hybrid_addons.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_hybrid_addons.html new file mode 100644 index 000000000..a74c551f0 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_hybrid_addons.html @@ -0,0 +1,141 @@ + + + + Test for hybrid addons: SDK or bootstrap.js + embedded WebExtension + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_idle.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_idle.html new file mode 100644 index 000000000..3c3063e67 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_idle.html @@ -0,0 +1,64 @@ + + + + WebExtension test + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_shutdown_cleanup.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_shutdown_cleanup.html new file mode 100644 index 000000000..e3098e6b1 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_shutdown_cleanup.html @@ -0,0 +1,50 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_storage_cleanup.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_storage_cleanup.html new file mode 100644 index 000000000..010769500 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_storage_cleanup.html @@ -0,0 +1,164 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_trustworthy_origin.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_trustworthy_origin.html new file mode 100644 index 000000000..573c08806 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_trustworthy_origin.html @@ -0,0 +1,53 @@ + + + + WebExtension test + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webnavigation_resolved_urls.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webnavigation_resolved_urls.html new file mode 100644 index 000000000..768eb31fd --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webnavigation_resolved_urls.html @@ -0,0 +1,83 @@ + + + + Test for simple WebExtension + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webrequest_background_events.html b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webrequest_background_events.html new file mode 100644 index 000000000..a13c4d475 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_ext_webrequest_background_events.html @@ -0,0 +1,96 @@ + + + + Test for simple WebExtension + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_chrome_native_messaging_paths.html b/toolkit/components/webextensions/test/mochitest/test_chrome_native_messaging_paths.html new file mode 100644 index 000000000..29a148063 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_chrome_native_messaging_paths.html @@ -0,0 +1,61 @@ + + + + WebExtension test + + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_clipboard.html b/toolkit/components/webextensions/test/mochitest/test_clipboard.html new file mode 100644 index 000000000..900ee5f10 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_clipboard.html @@ -0,0 +1,140 @@ + + + + clipboard permission test + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_all_apis.js b/toolkit/components/webextensions/test/mochitest/test_ext_all_apis.js new file mode 100644 index 000000000..25d04b36b --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_all_apis.js @@ -0,0 +1,160 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +// Tests whether not too many APIs are visible by default. +// This file is used by test_ext_all_apis.html in browser/ and mobile/android/, +// which may modify the following variables to add or remove expected APIs. +/* globals expectedContentApisTargetSpecific */ +/* globals expectedBackgroundApisTargetSpecific */ + +// Generates a list of expectations. +function generateExpectations(list) { + return list.reduce((allApis, path) => { + return allApis.concat(`browser.${path}`, `chrome.${path}`); + }, []).sort(); +} + +let expectedCommonApis = [ + "extension.getURL", + "extension.inIncognitoContext", + "extension.lastError", + "i18n.detectLanguage", + "i18n.getAcceptLanguages", + "i18n.getMessage", + "i18n.getUILanguage", + "runtime.OnInstalledReason", + "runtime.OnRestartRequiredReason", + "runtime.PlatformArch", + "runtime.PlatformOs", + "runtime.RequestUpdateCheckStatus", + "runtime.getManifest", + "runtime.connect", + "runtime.getURL", + "runtime.id", + "runtime.lastError", + "runtime.onConnect", + "runtime.onMessage", + "runtime.sendMessage", + // If you want to add a new powerful test API, please see bug 1287233. + "test.assertEq", + "test.assertFalse", + "test.assertRejects", + "test.assertThrows", + "test.assertTrue", + "test.fail", + "test.log", + "test.notifyFail", + "test.notifyPass", + "test.onMessage", + "test.sendMessage", + "test.succeed", +]; + +let expectedContentApis = [ + ...expectedCommonApis, + ...expectedContentApisTargetSpecific, +]; + +let expectedBackgroundApis = [ + ...expectedCommonApis, + ...expectedBackgroundApisTargetSpecific, + "extension.ViewType", + "extension.getBackgroundPage", + "extension.getViews", + "extension.isAllowedFileSchemeAccess", + "extension.isAllowedIncognitoAccess", + // Note: extensionTypes is not visible in Chrome. + "extensionTypes.ImageFormat", + "extensionTypes.RunAt", + "management.ExtensionDisabledReason", + "management.ExtensionInstallType", + "management.ExtensionType", + "management.getSelf", + "management.uninstallSelf", + "runtime.getBackgroundPage", + "runtime.getBrowserInfo", + "runtime.getPlatformInfo", + "runtime.onConnectExternal", + "runtime.onInstalled", + "runtime.onMessageExternal", + "runtime.onStartup", + "runtime.onUpdateAvailable", + "runtime.openOptionsPage", + "runtime.reload", + "runtime.setUninstallURL", +]; + +function sendAllApis() { + function isEvent(key, val) { + if (!/^on[A-Z]/.test(key)) { + return false; + } + let eventKeys = []; + for (let prop in val) { + eventKeys.push(prop); + } + eventKeys = eventKeys.sort().join(); + return eventKeys === "addListener,hasListener,removeListener"; + } + function mayRecurse(key, val) { + if (Object.keys(val).filter(k => !/^[A-Z\-0-9_]+$/.test(k)).length === 0) { + // Don't recurse on constants and empty objects. + return false; + } + return !isEvent(key, val); + } + + let results = []; + function diveDeeper(path, obj) { + for (let key in obj) { + let val = obj[key]; + if (typeof val == "object" && val !== null && mayRecurse(key, val)) { + diveDeeper(`${path}.${key}`, val); + } else if (val !== undefined) { + results.push(`${path}.${key}`); + } + } + } + diveDeeper("browser", browser); + diveDeeper("chrome", chrome); + browser.test.sendMessage("allApis", results.sort()); +} + +add_task(function* test_enumerate_content_script_apis() { + let extensionData = { + manifest: { + content_scripts: [{ + matches: ["http://mochi.test/*/file_sample.html"], + js: ["contentscript.js"], + run_at: "document_start", + }], + }, + files: { + "contentscript.js": sendAllApis, + }, + }; + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + + let win = window.open("file_sample.html"); + let actualApis = yield extension.awaitMessage("allApis"); + win.close(); + let expectedApis = generateExpectations(expectedContentApis); + isDeeply(actualApis, expectedApis, "content script APIs"); + + yield extension.unload(); +}); + +add_task(function* test_enumerate_background_script_apis() { + let extensionData = { + background: sendAllApis, + }; + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + let actualApis = yield extension.awaitMessage("allApis"); + let expectedApis = generateExpectations(expectedBackgroundApis); + isDeeply(actualApis, expectedApis, "background script APIs"); + + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_background_api_injection.html b/toolkit/components/webextensions/test/mochitest/test_ext_background_api_injection.html new file mode 100644 index 000000000..f43a59f81 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_background_api_injection.html @@ -0,0 +1,46 @@ + + + + Test for privilege escalation into content pages + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_background_canvas.html b/toolkit/components/webextensions/test/mochitest/test_ext_background_canvas.html new file mode 100644 index 000000000..bff7190cb --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_background_canvas.html @@ -0,0 +1,47 @@ + + + + Test for background page canvas rendering + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_background_generated_url.html b/toolkit/components/webextensions/test/mochitest/test_ext_background_generated_url.html new file mode 100644 index 000000000..f4fcf3d34 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_background_generated_url.html @@ -0,0 +1,47 @@ + + + + Test _generated_background_page.html + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_background_teardown.html b/toolkit/components/webextensions/test/mochitest/test_ext_background_teardown.html new file mode 100644 index 000000000..bb6b2e970 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_background_teardown.html @@ -0,0 +1,76 @@ + + + + Test for background script teardown + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_content_security_policy.html b/toolkit/components/webextensions/test/mochitest/test_ext_content_security_policy.html new file mode 100644 index 000000000..a36f29563 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_content_security_policy.html @@ -0,0 +1,162 @@ + + + + WebExtension CSP test + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript.html new file mode 100644 index 000000000..39f1bfabd --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript.html @@ -0,0 +1,116 @@ + + + + Test for content script + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_about_blank.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_about_blank.html new file mode 100644 index 000000000..3766678e7 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_about_blank.html @@ -0,0 +1,117 @@ + + + + Test content script match_about_blank option + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_api_injection.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_api_injection.html new file mode 100644 index 000000000..abf3d349f --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_api_injection.html @@ -0,0 +1,88 @@ + + + + Test for privilege escalation into iframe with content script APIs + + + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_async_loading.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_async_loading.html new file mode 100644 index 000000000..d78f7ce02 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_async_loading.html @@ -0,0 +1,54 @@ + + + + Test content script async loading + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_context.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_context.html new file mode 100644 index 000000000..97b1645dd --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_context.html @@ -0,0 +1,81 @@ + + + + Test for content script contexts + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_create_iframe.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_create_iframe.html new file mode 100644 index 000000000..8aac3e213 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_create_iframe.html @@ -0,0 +1,165 @@ + + + + Test for content script + + + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_css.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_css.html new file mode 100644 index 000000000..5630a1d68 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_css.html @@ -0,0 +1,48 @@ + + + + Test for content script + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_devtools_metadata.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_devtools_metadata.html new file mode 100644 index 000000000..137a3cda4 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_devtools_metadata.html @@ -0,0 +1,81 @@ + + + + Test for Sandbox metadata on WebExtensions ContentScripts + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_exporthelpers.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_exporthelpers.html new file mode 100644 index 000000000..f3414901d --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_exporthelpers.html @@ -0,0 +1,95 @@ + + + + Test for content script + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_incognito.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_incognito.html new file mode 100644 index 000000000..a2f38dce6 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_incognito.html @@ -0,0 +1,89 @@ + + + + Test for content script private browsing ID + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_permission.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_permission.html new file mode 100644 index 000000000..eaf815092 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_permission.html @@ -0,0 +1,59 @@ + + + + Test for content script + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_teardown.html b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_teardown.html new file mode 100644 index 000000000..33a8c4ccc --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_contentscript_teardown.html @@ -0,0 +1,96 @@ + + + + Test for content script teardown + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_cookies.html b/toolkit/components/webextensions/test/mochitest/test_ext_cookies.html new file mode 100644 index 000000000..d414a4e46 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_cookies.html @@ -0,0 +1,234 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_cookies_containers.html b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_containers.html new file mode 100644 index 000000000..bc4994eec --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_containers.html @@ -0,0 +1,93 @@ + + + + WebExtension test + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_cookies_expiry.html b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_expiry.html new file mode 100644 index 000000000..3927d9e94 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_expiry.html @@ -0,0 +1,72 @@ + + + + WebExtension test + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_bad.html b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_bad.html new file mode 100644 index 000000000..15a62855a --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_bad.html @@ -0,0 +1,112 @@ + + + + WebExtension test + + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_good.html b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_good.html new file mode 100644 index 000000000..31e83188c --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_cookies_permissions_good.html @@ -0,0 +1,86 @@ + + + + WebExtension test + + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_exclude_include_globs.html b/toolkit/components/webextensions/test/mochitest/test_ext_exclude_include_globs.html new file mode 100644 index 000000000..640522b40 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_exclude_include_globs.html @@ -0,0 +1,92 @@ + + + + Test for content script + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_external_messaging.html b/toolkit/components/webextensions/test/mochitest/test_ext_external_messaging.html new file mode 100644 index 000000000..dfc1f9427 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_external_messaging.html @@ -0,0 +1,111 @@ + + + + WebExtension external messaging + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_generate.html b/toolkit/components/webextensions/test/mochitest/test_ext_generate.html new file mode 100644 index 000000000..cfafcbad9 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_generate.html @@ -0,0 +1,49 @@ + + + + Test for generating WebExtensions + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_geturl.html b/toolkit/components/webextensions/test/mochitest/test_ext_geturl.html new file mode 100644 index 000000000..6e39c2f5d --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_geturl.html @@ -0,0 +1,72 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_i18n.html b/toolkit/components/webextensions/test/mochitest/test_ext_i18n.html new file mode 100644 index 000000000..1f7330bbb --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_i18n.html @@ -0,0 +1,432 @@ + + + + + Test for WebExtension localization APIs + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_i18n_css.html b/toolkit/components/webextensions/test/mochitest/test_ext_i18n_css.html new file mode 100644 index 000000000..7c6a8eeaa --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_i18n_css.html @@ -0,0 +1,116 @@ + + + + Test for content script + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_inIncognitoContext_window.html b/toolkit/components/webextensions/test/mochitest/test_ext_inIncognitoContext_window.html new file mode 100644 index 000000000..675cbb298 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_inIncognitoContext_window.html @@ -0,0 +1,49 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_jsversion.html b/toolkit/components/webextensions/test/mochitest/test_ext_jsversion.html new file mode 100644 index 000000000..da0c355e0 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_jsversion.html @@ -0,0 +1,86 @@ + + + + Test for simple WebExtension + + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_listener_proxies.html b/toolkit/components/webextensions/test/mochitest/test_ext_listener_proxies.html new file mode 100644 index 000000000..ca8db873e --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_listener_proxies.html @@ -0,0 +1,63 @@ + + + + Test for content script + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_notifications.html b/toolkit/components/webextensions/test/mochitest/test_ext_notifications.html new file mode 100644 index 000000000..d1b798cf9 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_notifications.html @@ -0,0 +1,224 @@ + + + + Test for notifications + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_permission_xhr.html b/toolkit/components/webextensions/test/mochitest/test_ext_permission_xhr.html new file mode 100644 index 000000000..07967d5d0 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_permission_xhr.html @@ -0,0 +1,119 @@ + + + + WebExtension Test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect.html b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect.html new file mode 100644 index 000000000..60351eaee --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect.html @@ -0,0 +1,83 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect2.html b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect2.html new file mode 100644 index 000000000..dce12b21b --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect2.html @@ -0,0 +1,103 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect_twoway.html b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect_twoway.html new file mode 100644 index 000000000..e84134eff --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_connect_twoway.html @@ -0,0 +1,127 @@ + + + + WebExtension test + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_runtime_disconnect.html b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_disconnect.html new file mode 100644 index 000000000..5764d0a3c --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_disconnect.html @@ -0,0 +1,78 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_runtime_id.html b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_id.html new file mode 100644 index 000000000..4cdefda41 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_runtime_id.html @@ -0,0 +1,61 @@ + + + + + Test for browser.runtime.id + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_sandbox_var.html b/toolkit/components/webextensions/test/mochitest/test_ext_sandbox_var.html new file mode 100644 index 000000000..426a71ac6 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_sandbox_var.html @@ -0,0 +1,60 @@ + + + + Test for content script + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_schema.html b/toolkit/components/webextensions/test/mochitest/test_ext_schema.html new file mode 100644 index 000000000..8a0e11c56 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_schema.html @@ -0,0 +1,73 @@ + + + + Test for schema API creation + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_doublereply.html b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_doublereply.html new file mode 100644 index 000000000..a3ef37cad --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_doublereply.html @@ -0,0 +1,101 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_no_receiver.html b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_no_receiver.html new file mode 100644 index 000000000..96af6558e --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_no_receiver.html @@ -0,0 +1,83 @@ + + + + WebExtension test + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply.html b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply.html new file mode 100644 index 000000000..a4ac708b2 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply.html @@ -0,0 +1,79 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply2.html b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply2.html new file mode 100644 index 000000000..5c350be2f --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_sendmessage_reply2.html @@ -0,0 +1,181 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_storage_content.html b/toolkit/components/webextensions/test/mochitest/test_ext_storage_content.html new file mode 100644 index 000000000..09a33814a --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_storage_content.html @@ -0,0 +1,330 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_storage_tab.html b/toolkit/components/webextensions/test/mochitest/test_ext_storage_tab.html new file mode 100644 index 000000000..32d8e6af0 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_storage_tab.html @@ -0,0 +1,118 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_subframes_privileges.html b/toolkit/components/webextensions/test/mochitest/test_ext_subframes_privileges.html new file mode 100644 index 000000000..1f3a9a3c9 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_subframes_privileges.html @@ -0,0 +1,202 @@ + + + + WebExtension test + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_tab_teardown.html b/toolkit/components/webextensions/test/mochitest/test_ext_tab_teardown.html new file mode 100644 index 000000000..dc351e48a --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_tab_teardown.html @@ -0,0 +1,150 @@ + + + + Test for extension tab teardown + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_test.html b/toolkit/components/webextensions/test/mochitest/test_ext_test.html new file mode 100644 index 000000000..fef31e0e2 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_test.html @@ -0,0 +1,191 @@ + + + + Testing test + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_unload_frame.html b/toolkit/components/webextensions/test/mochitest/test_ext_unload_frame.html new file mode 100644 index 000000000..5572de281 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_unload_frame.html @@ -0,0 +1,170 @@ + + + + WebExtensions test + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_web_accessible_resources.html b/toolkit/components/webextensions/test/mochitest/test_ext_web_accessible_resources.html new file mode 100644 index 000000000..fa3228739 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_web_accessible_resources.html @@ -0,0 +1,353 @@ + + + + Test the web_accessible_resources manifest directive + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation.html b/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation.html new file mode 100644 index 000000000..2287fd9b1 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation.html @@ -0,0 +1,559 @@ + + + + Test for simple WebExtension + + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation_filters.html b/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation_filters.html new file mode 100644 index 000000000..a0de5e9e5 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_webnavigation_filters.html @@ -0,0 +1,308 @@ + + + + Test for simple WebExtension + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_background_events.html b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_background_events.html new file mode 100644 index 000000000..78efeab35 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_background_events.html @@ -0,0 +1,116 @@ + + + + Test for simple WebExtension + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_basic.html b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_basic.html new file mode 100644 index 000000000..ef77fee3b --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_basic.html @@ -0,0 +1,327 @@ + + + + + + + + + + + + + + +
Sample text
+ + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_suspend.html b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_suspend.html new file mode 100644 index 000000000..c8423ec7c --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_suspend.html @@ -0,0 +1,216 @@ + + + + Test for simple WebExtension + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_upload.html b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_upload.html new file mode 100644 index 000000000..998ab9800 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_webrequest_upload.html @@ -0,0 +1,199 @@ + + + + + + + + + + + + + +
+ + + + +
+ +
+ + + +
+ + +
+ + +
+ + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_window_postMessage.html b/toolkit/components/webextensions/test/mochitest/test_ext_window_postMessage.html new file mode 100644 index 000000000..7d49d55ba --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_window_postMessage.html @@ -0,0 +1,105 @@ + + + + Test for content script + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/test_ext_xhr_capabilities.html b/toolkit/components/webextensions/test/mochitest/test_ext_xhr_capabilities.html new file mode 100644 index 000000000..1afdadb9f --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/test_ext_xhr_capabilities.html @@ -0,0 +1,86 @@ + + + + Test XHR capabilities + + + + + + + + + + + + diff --git a/toolkit/components/webextensions/test/mochitest/webrequest_chromeworker.js b/toolkit/components/webextensions/test/mochitest/webrequest_chromeworker.js new file mode 100644 index 000000000..ccfb2ac1f --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/webrequest_chromeworker.js @@ -0,0 +1,8 @@ +"use strict"; + +onmessage = function(event) { + fetch("https://example.com/example.txt").then(() => { + postMessage("Done!"); + }); +}; + diff --git a/toolkit/components/webextensions/test/mochitest/webrequest_test.jsm b/toolkit/components/webextensions/test/mochitest/webrequest_test.jsm new file mode 100644 index 000000000..bfb148301 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/webrequest_test.jsm @@ -0,0 +1,22 @@ +"use strict"; + +this.EXPORTED_SYMBOLS = ["webrequest_test"]; + +Components.utils.importGlobalProperties(["fetch", "XMLHttpRequest"]); + +this.webrequest_test = { + testFetch(url) { + return fetch(url); + }, + + testXHR(url) { + return new Promise(resolve => { + let xhr = new XMLHttpRequest(); + xhr.open("HEAD", url); + xhr.onload = () => { + resolve(); + }; + xhr.send(); + }); + }, +}; diff --git a/toolkit/components/webextensions/test/mochitest/webrequest_worker.js b/toolkit/components/webextensions/test/mochitest/webrequest_worker.js new file mode 100644 index 000000000..dcffd0857 --- /dev/null +++ b/toolkit/components/webextensions/test/mochitest/webrequest_worker.js @@ -0,0 +1,3 @@ +"use strict"; + +fetch("https://example.com/example.txt"); diff --git a/toolkit/components/webextensions/test/xpcshell/.eslintrc.js b/toolkit/components/webextensions/test/xpcshell/.eslintrc.js new file mode 100644 index 000000000..3758537ef --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/.eslintrc.js @@ -0,0 +1,9 @@ +"use strict"; + +module.exports = { // eslint-disable-line no-undef + "extends": "../../../../../testing/xpcshell/xpcshell.eslintrc.js", + + "globals": { + "browser": false, + }, +}; diff --git a/toolkit/components/webextensions/test/xpcshell/data/file_download.html b/toolkit/components/webextensions/test/xpcshell/data/file_download.html new file mode 100644 index 000000000..d970c6325 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/data/file_download.html @@ -0,0 +1,12 @@ + + + + + + + + +
Download HTML File
+ + + diff --git a/toolkit/components/webextensions/test/xpcshell/data/file_download.txt b/toolkit/components/webextensions/test/xpcshell/data/file_download.txt new file mode 100644 index 000000000..6293c7af7 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/data/file_download.txt @@ -0,0 +1 @@ +This is a sample file used in download tests. diff --git a/toolkit/components/webextensions/test/xpcshell/head.js b/toolkit/components/webextensions/test/xpcshell/head.js new file mode 100644 index 000000000..9e22be6da --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/head.js @@ -0,0 +1,111 @@ +"use strict"; + +const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; + +/* exported createHttpServer, promiseConsoleOutput, cleanupDir */ + +Components.utils.import("resource://gre/modules/Task.jsm"); +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); +Components.utils.import("resource://gre/modules/Timer.jsm"); +Components.utils.import("resource://testing-common/AddonTestUtils.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "AppConstants", + "resource://gre/modules/AppConstants.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Extension", + "resource://gre/modules/Extension.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionData", + "resource://gre/modules/Extension.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionManagement", + "resource://gre/modules/ExtensionManagement.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ExtensionTestUtils", + "resource://testing-common/ExtensionXPCShellUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "FileUtils", + "resource://gre/modules/FileUtils.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "HttpServer", + "resource://testing-common/httpd.js"); +XPCOMUtils.defineLazyModuleGetter(this, "NetUtil", + "resource://gre/modules/NetUtil.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Schemas", + "resource://gre/modules/Schemas.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Services", + "resource://gre/modules/Services.jsm"); + +ExtensionTestUtils.init(this); + +/** + * Creates a new HttpServer for testing, and begins listening on the + * specified port. Automatically shuts down the server when the test + * unit ends. + * + * @param {integer} [port] + * The port to listen on. If omitted, listen on a random + * port. The latter is the preferred behavior. + * + * @returns {HttpServer} + */ +function createHttpServer(port = -1) { + let server = new HttpServer(); + server.start(port); + + do_register_cleanup(() => { + return new Promise(resolve => { + server.stop(resolve); + }); + }); + + return server; +} + +var promiseConsoleOutput = Task.async(function* (task) { + const DONE = `=== console listener ${Math.random()} done ===`; + + let listener; + let messages = []; + let awaitListener = new Promise(resolve => { + listener = msg => { + if (msg == DONE) { + resolve(); + } else { + void (msg instanceof Ci.nsIConsoleMessage); + messages.push(msg); + } + }; + }); + + Services.console.registerListener(listener); + try { + let result = yield task(); + + Services.console.logStringMessage(DONE); + yield awaitListener; + + return {messages, result}; + } finally { + Services.console.unregisterListener(listener); + } +}); + +// Attempt to remove a directory. If the Windows OS is still using the +// file sometimes remove() will fail. So try repeatedly until we can +// remove it or we give up. +function cleanupDir(dir) { + let count = 0; + return new Promise((resolve, reject) => { + function tryToRemoveDir() { + count += 1; + try { + dir.remove(true); + } catch (e) { + // ignore + } + if (!dir.exists()) { + return resolve(); + } + if (count >= 25) { + return reject(`Failed to cleanup directory: ${dir}`); + } + setTimeout(tryToRemoveDir, 100); + } + tryToRemoveDir(); + }); +} diff --git a/toolkit/components/webextensions/test/xpcshell/head_native_messaging.js b/toolkit/components/webextensions/test/xpcshell/head_native_messaging.js new file mode 100644 index 000000000..f7c619b76 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/head_native_messaging.js @@ -0,0 +1,131 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +/* globals AppConstants, FileUtils */ +/* exported getSubprocessCount, setupHosts, waitForSubprocessExit */ + +XPCOMUtils.defineLazyModuleGetter(this, "MockRegistry", + "resource://testing-common/MockRegistry.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "OS", + "resource://gre/modules/osfile.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "setTimeout", + "resource://gre/modules/Timer.jsm"); + +let {Subprocess, SubprocessImpl} = Cu.import("resource://gre/modules/Subprocess.jsm"); + + +// It's important that we use a space in this directory name to make sure we +// correctly handle executing batch files with spaces in their path. +let tmpDir = FileUtils.getDir("TmpD", ["Native Messaging"]); +tmpDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); + +do_register_cleanup(() => { + tmpDir.remove(true); +}); + +function getPath(filename) { + return OS.Path.join(tmpDir.path, filename); +} + +const ID = "native@tests.mozilla.org"; + + +function* setupHosts(scripts) { + const PERMS = {unixMode: 0o755}; + + const env = Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); + const pythonPath = yield Subprocess.pathSearch(env.get("PYTHON")); + + function* writeManifest(script, scriptPath, path) { + let body = `#!${pythonPath} -u\n${script.script}`; + + yield OS.File.writeAtomic(scriptPath, body); + yield OS.File.setPermissions(scriptPath, PERMS); + + let manifest = { + name: script.name, + description: script.description, + path, + type: "stdio", + allowed_extensions: [ID], + }; + + let manifestPath = getPath(`${script.name}.json`); + yield OS.File.writeAtomic(manifestPath, JSON.stringify(manifest)); + + return manifestPath; + } + + switch (AppConstants.platform) { + case "macosx": + case "linux": + let dirProvider = { + getFile(property) { + if (property == "XREUserNativeMessaging") { + return tmpDir.clone(); + } else if (property == "XRESysNativeMessaging") { + return tmpDir.clone(); + } + return null; + }, + }; + + Services.dirsvc.registerProvider(dirProvider); + do_register_cleanup(() => { + Services.dirsvc.unregisterProvider(dirProvider); + }); + + for (let script of scripts) { + let path = getPath(`${script.name}.py`); + + yield writeManifest(script, path, path); + } + break; + + case "win": + const REGKEY = String.raw`Software\Mozilla\NativeMessagingHosts`; + + let registry = new MockRegistry(); + do_register_cleanup(() => { + registry.shutdown(); + }); + + for (let script of scripts) { + // It's important that we use a space in this filename. See directory + // name comment above. + let batPath = getPath(`batch ${script.name}.bat`); + let scriptPath = getPath(`${script.name}.py`); + + let batBody = `@ECHO OFF\n${pythonPath} -u "${scriptPath}" %*\n`; + yield OS.File.writeAtomic(batPath, batBody); + + // Create absolute and relative path versions of the entry. + for (let [name, path] of [[script.name, batPath], + [`relative.${script.name}`, OS.Path.basename(batPath)]]) { + script.name = name; + let manifestPath = yield writeManifest(script, scriptPath, path); + + registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, + `${REGKEY}\\${script.name}`, "", manifestPath); + } + } + break; + + default: + ok(false, `Native messaging is not supported on ${AppConstants.platform}`); + } +} + + +function getSubprocessCount() { + return SubprocessImpl.Process.getWorker().call("getProcesses", []) + .then(result => result.size); +} +function waitForSubprocessExit() { + return SubprocessImpl.Process.getWorker().call("waitForNoProcesses", []).then(() => { + // Return to the main event loop to give IO handlers enough time to consume + // their remaining buffered input. + return new Promise(resolve => setTimeout(resolve, 0)); + }); +} diff --git a/toolkit/components/webextensions/test/xpcshell/head_sync.js b/toolkit/components/webextensions/test/xpcshell/head_sync.js new file mode 100644 index 000000000..9b66b78e7 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/head_sync.js @@ -0,0 +1,67 @@ +/* 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"; + +/* exported withSyncContext */ + +Components.utils.import("resource://gre/modules/Services.jsm", this); +Components.utils.import("resource://gre/modules/ExtensionCommon.jsm", this); + +var { + BaseContext, +} = ExtensionCommon; + +class Context extends BaseContext { + constructor(principal) { + super(); + Object.defineProperty(this, "principal", { + value: principal, + configurable: true, + }); + this.sandbox = Components.utils.Sandbox(principal, {wantXrays: false}); + this.extension = {id: "test@web.extension"}; + } + + get cloneScope() { + return this.sandbox; + } +} + +/** + * Call the given function with a newly-constructed context. + * Unload the context on the way out. + * + * @param {function} f the function to call + */ +function* withContext(f) { + const ssm = Services.scriptSecurityManager; + const PRINCIPAL1 = ssm.createCodebasePrincipalFromOrigin("http://www.example.org"); + const context = new Context(PRINCIPAL1); + try { + yield* f(context); + } finally { + yield context.unload(); + } +} + +/** + * Like withContext(), but also turn on the "storage.sync" pref for + * the duration of the function. + * Calls to this function can be replaced with calls to withContext + * once the pref becomes on by default. + * + * @param {function} f the function to call + */ +function* withSyncContext(f) { + const STORAGE_SYNC_PREF = "webextensions.storage.sync.enabled"; + let prefs = Services.prefs; + + try { + prefs.setBoolPref(STORAGE_SYNC_PREF, true); + yield* withContext(f); + } finally { + prefs.clearUserPref(STORAGE_SYNC_PREF); + } +} diff --git a/toolkit/components/webextensions/test/xpcshell/native_messaging.ini b/toolkit/components/webextensions/test/xpcshell/native_messaging.ini new file mode 100644 index 000000000..d0e1da163 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/native_messaging.ini @@ -0,0 +1,13 @@ +[DEFAULT] +head = head.js head_native_messaging.js +tail = +firefox-appdir = browser +skip-if = appname == "thunderbird" || os == "android" +subprocess = true +support-files = + data/** +tags = webextensions + +[test_ext_native_messaging.js] +[test_ext_native_messaging_perf.js] +[test_ext_native_messaging_unresponsive.js] diff --git a/toolkit/components/webextensions/test/xpcshell/test_csp_custom_policies.js b/toolkit/components/webextensions/test/xpcshell/test_csp_custom_policies.js new file mode 100644 index 000000000..b6213baac --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_csp_custom_policies.js @@ -0,0 +1,38 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://gre/modules/Preferences.jsm"); + +const ADDON_ID = "test@web.extension"; + +const aps = Cc["@mozilla.org/addons/policy-service;1"] + .getService(Ci.nsIAddonPolicyService).wrappedJSObject; + +do_register_cleanup(() => { + aps.setAddonCSP(ADDON_ID, null); +}); + +add_task(function* test_addon_csp() { + equal(aps.baseCSP, Preferences.get("extensions.webextensions.base-content-security-policy"), + "Expected base CSP value"); + + equal(aps.defaultCSP, Preferences.get("extensions.webextensions.default-content-security-policy"), + "Expected default CSP value"); + + equal(aps.getAddonCSP(ADDON_ID), aps.defaultCSP, + "CSP for unknown add-on ID should be the default CSP"); + + + const CUSTOM_POLICY = "script-src: 'self' https://xpcshell.test.custom.csp; object-src: 'none'"; + + aps.setAddonCSP(ADDON_ID, CUSTOM_POLICY); + + equal(aps.getAddonCSP(ADDON_ID), CUSTOM_POLICY, "CSP should point to add-on's custom policy"); + + + aps.setAddonCSP(ADDON_ID, null); + + equal(aps.getAddonCSP(ADDON_ID), aps.defaultCSP, + "CSP should revert to default when set to null"); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_csp_validator.js b/toolkit/components/webextensions/test/xpcshell/test_csp_validator.js new file mode 100644 index 000000000..59a7322bc --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_csp_validator.js @@ -0,0 +1,85 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +const cps = Cc["@mozilla.org/addons/content-policy;1"].getService(Ci.nsIAddonContentPolicy); + +add_task(function* test_csp_validator() { + let checkPolicy = (policy, expectedResult, message = null) => { + do_print(`Checking policy: ${policy}`); + + let result = cps.validateAddonCSP(policy); + equal(result, expectedResult); + }; + + checkPolicy("script-src 'self'; object-src 'self';", + null); + + let hash = "'sha256-NjZhMDQ1YjQ1MjEwMmM1OWQ4NDBlYzA5N2Q1OWQ5NDY3ZTEzYTNmMzRmNjQ5NGU1MzlmZmQzMmMxYmIzNWYxOCAgLQo='"; + + checkPolicy(`script-src 'self' https://com https://*.example.com moz-extension://09abcdef blob: filesystem: ${hash} 'unsafe-eval'; ` + + `object-src 'self' https://com https://*.example.com moz-extension://09abcdef blob: filesystem: ${hash}`, + null); + + checkPolicy("", + "Policy is missing a required \u2018script-src\u2019 directive"); + + checkPolicy("object-src 'none';", + "Policy is missing a required \u2018script-src\u2019 directive"); + + + checkPolicy("default-src 'self'", null, + "A valid default-src should count as a valid script-src or object-src"); + + checkPolicy("default-src 'self'; script-src 'self'", null, + "A valid default-src should count as a valid script-src or object-src"); + + checkPolicy("default-src 'self'; object-src 'self'", null, + "A valid default-src should count as a valid script-src or object-src"); + + + checkPolicy("default-src 'self'; script-src http://example.com", + "\u2018script-src\u2019 directive contains a forbidden http: protocol source", + "A valid default-src should not allow an invalid script-src directive"); + + checkPolicy("default-src 'self'; object-src http://example.com", + "\u2018object-src\u2019 directive contains a forbidden http: protocol source", + "A valid default-src should not allow an invalid object-src directive"); + + + checkPolicy("script-src 'self';", + "Policy is missing a required \u2018object-src\u2019 directive"); + + checkPolicy("script-src 'none'; object-src 'none'", + "\u2018script-src\u2019 must include the source 'self'"); + + checkPolicy("script-src 'self'; object-src 'none';", + null); + + checkPolicy("script-src 'self' 'unsafe-inline'; object-src 'self';", + "\u2018script-src\u2019 directive contains a forbidden 'unsafe-inline' keyword"); + + + let directives = ["script-src", "object-src"]; + + for (let [directive, other] of [directives, directives.slice().reverse()]) { + for (let src of ["https://*", "https://*.blogspot.com", "https://*"]) { + checkPolicy(`${directive} 'self' ${src}; ${other} 'self';`, + `https: wildcard sources in \u2018${directive}\u2019 directives must include at least one non-generic sub-domain (e.g., *.example.com rather than *.com)`); + } + + checkPolicy(`${directive} 'self' https:; ${other} 'self';`, + `https: protocol requires a host in \u2018${directive}\u2019 directives`); + + checkPolicy(`${directive} 'self' http://example.com; ${other} 'self';`, + `\u2018${directive}\u2019 directive contains a forbidden http: protocol source`); + + for (let protocol of ["http", "ftp", "meh"]) { + checkPolicy(`${directive} 'self' ${protocol}:; ${other} 'self';`, + `\u2018${directive}\u2019 directive contains a forbidden ${protocol}: protocol source`); + } + + checkPolicy(`${directive} 'self' 'nonce-01234'; ${other} 'self';`, + `\u2018${directive}\u2019 directive contains a forbidden 'nonce-*' keyword`); + } +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_alarms.js b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms.js new file mode 100644 index 000000000..936c984c6 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms.js @@ -0,0 +1,210 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_alarm_without_permissions() { + function backgroundScript() { + browser.test.assertTrue(!browser.alarms, + "alarm API is not available when the alarm permission is not required"); + browser.test.notifyPass("alarms_permission"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background: `(${backgroundScript})()`, + manifest: { + permissions: [], + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("alarms_permission"); + yield extension.unload(); +}); + + +add_task(function* test_alarm_fires() { + function backgroundScript() { + let ALARM_NAME = "test_ext_alarms"; + let timer; + + browser.alarms.onAlarm.addListener(alarm => { + browser.test.assertEq(ALARM_NAME, alarm.name, "alarm has the correct name"); + clearTimeout(timer); + browser.test.notifyPass("alarm-fires"); + }); + + browser.alarms.create(ALARM_NAME, {delayInMinutes: 0.02}); + + timer = setTimeout(async () => { + browser.test.fail("alarm fired within expected time"); + let wasCleared = await browser.alarms.clear(ALARM_NAME); + browser.test.assertTrue(wasCleared, "alarm was cleared"); + browser.test.notifyFail("alarm-fires"); + }, 10000); + } + + let extension = ExtensionTestUtils.loadExtension({ + background: `(${backgroundScript})()`, + manifest: { + permissions: ["alarms"], + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("alarm-fires"); + yield extension.unload(); +}); + + +add_task(function* test_alarm_fires_with_when() { + function backgroundScript() { + let ALARM_NAME = "test_ext_alarms"; + let timer; + + browser.alarms.onAlarm.addListener(alarm => { + browser.test.assertEq(ALARM_NAME, alarm.name, "alarm has the expected name"); + clearTimeout(timer); + browser.test.notifyPass("alarm-when"); + }); + + browser.alarms.create(ALARM_NAME, {when: Date.now() + 1000}); + + timer = setTimeout(async () => { + browser.test.fail("alarm fired within expected time"); + let wasCleared = await browser.alarms.clear(ALARM_NAME); + browser.test.assertTrue(wasCleared, "alarm was cleared"); + browser.test.notifyFail("alarm-when"); + }, 10000); + } + + let extension = ExtensionTestUtils.loadExtension({ + background: `(${backgroundScript})()`, + manifest: { + permissions: ["alarms"], + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("alarm-when"); + yield extension.unload(); +}); + + +add_task(function* test_alarm_clear_non_matching_name() { + async function backgroundScript() { + let ALARM_NAME = "test_ext_alarms"; + + browser.alarms.create(ALARM_NAME, {when: Date.now() + 2000}); + + let wasCleared = await browser.alarms.clear(ALARM_NAME + "1"); + browser.test.assertFalse(wasCleared, "alarm was not cleared"); + + let alarms = await browser.alarms.getAll(); + browser.test.assertEq(1, alarms.length, "alarm was not removed"); + browser.test.notifyPass("alarm-clear"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background: `(${backgroundScript})()`, + manifest: { + permissions: ["alarms"], + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("alarm-clear"); + yield extension.unload(); +}); + + +add_task(function* test_alarm_get_and_clear_single_argument() { + async function backgroundScript() { + browser.alarms.create({when: Date.now() + 2000}); + + let alarm = await browser.alarms.get(); + browser.test.assertEq("", alarm.name, "expected alarm returned"); + + let wasCleared = await browser.alarms.clear(); + browser.test.assertTrue(wasCleared, "alarm was cleared"); + + let alarms = await browser.alarms.getAll(); + browser.test.assertEq(0, alarms.length, "alarm was removed"); + + browser.test.notifyPass("alarm-single-arg"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background: `(${backgroundScript})()`, + manifest: { + permissions: ["alarms"], + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("alarm-single-arg"); + yield extension.unload(); +}); + + +add_task(function* test_get_get_all_clear_all_alarms() { + async function backgroundScript() { + const ALARM_NAME = "test_alarm"; + + let suffixes = [0, 1, 2]; + + for (let suffix of suffixes) { + browser.alarms.create(ALARM_NAME + suffix, {when: Date.now() + (suffix + 1) * 10000}); + } + + let alarms = await browser.alarms.getAll(); + browser.test.assertEq(suffixes.length, alarms.length, "expected number of alarms were found"); + alarms.forEach((alarm, index) => { + browser.test.assertEq(ALARM_NAME + index, alarm.name, "alarm has the expected name"); + }); + + + for (let suffix of suffixes) { + let alarm = await browser.alarms.get(ALARM_NAME + suffix); + browser.test.assertEq(ALARM_NAME + suffix, alarm.name, "alarm has the expected name"); + browser.test.sendMessage(`get-${suffix}`); + } + + let wasCleared = await browser.alarms.clear(ALARM_NAME + suffixes[0]); + browser.test.assertTrue(wasCleared, "alarm was cleared"); + + alarms = await browser.alarms.getAll(); + browser.test.assertEq(2, alarms.length, "alarm was removed"); + + let alarm = await browser.alarms.get(ALARM_NAME + suffixes[0]); + browser.test.assertEq(undefined, alarm, "non-existent alarm is undefined"); + browser.test.sendMessage(`get-invalid`); + + wasCleared = await browser.alarms.clearAll(); + browser.test.assertTrue(wasCleared, "alarms were cleared"); + + alarms = await browser.alarms.getAll(); + browser.test.assertEq(0, alarms.length, "no alarms exist"); + browser.test.sendMessage("clearAll"); + browser.test.sendMessage("clear"); + browser.test.sendMessage("getAll"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background: `(${backgroundScript})()`, + manifest: { + permissions: ["alarms"], + }, + }); + + yield Promise.all([ + extension.startup(), + extension.awaitMessage("getAll"), + extension.awaitMessage("get-0"), + extension.awaitMessage("get-1"), + extension.awaitMessage("get-2"), + extension.awaitMessage("clear"), + extension.awaitMessage("get-invalid"), + extension.awaitMessage("clearAll"), + ]); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_does_not_fire.js b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_does_not_fire.js new file mode 100644 index 000000000..11407b108 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_does_not_fire.js @@ -0,0 +1,33 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_cleared_alarm_does_not_fire() { + async function backgroundScript() { + let ALARM_NAME = "test_ext_alarms"; + + browser.alarms.onAlarm.addListener(alarm => { + browser.test.fail("cleared alarm does not fire"); + browser.test.notifyFail("alarm-cleared"); + }); + browser.alarms.create(ALARM_NAME, {when: Date.now() + 1000}); + + let wasCleared = await browser.alarms.clear(ALARM_NAME); + browser.test.assertTrue(wasCleared, "alarm was cleared"); + + await new Promise(resolve => setTimeout(resolve, 2000)); + + browser.test.notifyPass("alarm-cleared"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background: `(${backgroundScript})()`, + manifest: { + permissions: ["alarms"], + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("alarm-cleared"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_periodic.js b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_periodic.js new file mode 100644 index 000000000..6bcdf4e33 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_periodic.js @@ -0,0 +1,44 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_periodic_alarm_fires() { + function backgroundScript() { + const ALARM_NAME = "test_ext_alarms"; + let count = 0; + let timer; + + browser.alarms.onAlarm.addListener(async alarm => { + browser.test.assertEq(alarm.name, ALARM_NAME, "alarm has the expected name"); + if (count++ === 3) { + clearTimeout(timer); + let wasCleared = await browser.alarms.clear(ALARM_NAME); + browser.test.assertTrue(wasCleared, "alarm was cleared"); + + browser.test.notifyPass("alarm-periodic"); + } + }); + + browser.alarms.create(ALARM_NAME, {periodInMinutes: 0.02}); + + timer = setTimeout(async () => { + browser.test.fail("alarm fired expected number of times"); + + let wasCleared = await browser.alarms.clear(ALARM_NAME); + browser.test.assertTrue(wasCleared, "alarm was cleared"); + + browser.test.notifyFail("alarm-periodic"); + }, 30000); + } + + let extension = ExtensionTestUtils.loadExtension({ + background: `(${backgroundScript})()`, + manifest: { + permissions: ["alarms"], + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("alarm-periodic"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_replaces.js b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_replaces.js new file mode 100644 index 000000000..96f61acb5 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_alarms_replaces.js @@ -0,0 +1,44 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + + +add_task(function* test_duplicate_alarm_name_replaces_alarm() { + function backgroundScript() { + let count = 0; + + browser.alarms.onAlarm.addListener(async alarm => { + if (alarm.name === "master alarm") { + browser.alarms.create("child alarm", {delayInMinutes: 0.05}); + let results = await browser.alarms.getAll(); + + browser.test.assertEq(2, results.length, "exactly two alarms exist"); + browser.test.assertEq("master alarm", results[0].name, "first alarm has the expected name"); + browser.test.assertEq("child alarm", results[1].name, "second alarm has the expected name"); + + if (count++ === 3) { + await browser.alarms.clear("master alarm"); + await browser.alarms.clear("child alarm"); + + browser.test.notifyPass("alarm-duplicate"); + } + } else { + browser.test.fail("duplicate named alarm replaced existing alarm"); + browser.test.notifyFail("alarm-duplicate"); + } + }); + + browser.alarms.create("master alarm", {delayInMinutes: 0.025, periodInMinutes: 0.025}); + } + + let extension = ExtensionTestUtils.loadExtension({ + background: `(${backgroundScript})()`, + manifest: { + permissions: ["alarms"], + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("alarm-duplicate"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_api_permissions.js b/toolkit/components/webextensions/test/xpcshell/test_ext_api_permissions.js new file mode 100644 index 000000000..d653d0e7a --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_api_permissions.js @@ -0,0 +1,64 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +let {Management} = Cu.import("resource://gre/modules/Extension.jsm", {}); +function getNextContext() { + return new Promise(resolve => { + Management.on("proxy-context-load", function listener(type, context) { + Management.off("proxy-context-load", listener); + resolve(context); + }); + }); +} + +add_task(function* test_storage_api_without_permissions() { + let extension = ExtensionTestUtils.loadExtension({ + background() { + // Force API initialization. + void browser.storage; + }, + + manifest: { + permissions: [], + }, + }); + + let contextPromise = getNextContext(); + yield extension.startup(); + + let context = yield contextPromise; + + // Force API initialization. + void context.apiObj; + + ok(!("storage" in context.apiObj), + "The storage API should not be initialized"); + + yield extension.unload(); +}); + +add_task(function* test_storage_api_with_permissions() { + let extension = ExtensionTestUtils.loadExtension({ + background() { + void browser.storage; + }, + + manifest: { + permissions: ["storage"], + }, + }); + + let contextPromise = getNextContext(); + yield extension.startup(); + + let context = yield contextPromise; + + // Force API initialization. + void context.apiObj; + + equal(typeof context.apiObj.storage, "object", + "The storage API should be initialized"); + + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_apimanager.js b/toolkit/components/webextensions/test/xpcshell/test_ext_apimanager.js new file mode 100644 index 000000000..3f6672a11 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_apimanager.js @@ -0,0 +1,91 @@ +/* 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"; + +Cu.import("resource://gre/modules/ExtensionCommon.jsm"); + +const { + SchemaAPIManager, +} = ExtensionCommon; + +this.unknownvar = "Some module-global var"; + +var gUniqueId = 0; + +// SchemaAPIManager's loadScript uses loadSubScript to load a script. This +// requires a local (resource://) URL. So create such a temporary URL for +// testing. +function toLocalURI(code) { + let dataUrl = `data:charset=utf-8,${encodeURIComponent(code)}`; + let uniqueResPart = `need-a-local-uri-for-subscript-loading-${++gUniqueId}`; + Services.io.getProtocolHandler("resource") + .QueryInterface(Ci.nsIResProtocolHandler) + .setSubstitution(uniqueResPart, Services.io.newURI(dataUrl, null, null)); + return `resource://${uniqueResPart}`; +} + +add_task(function* test_global_isolation() { + let manA = new SchemaAPIManager("procA"); + let manB = new SchemaAPIManager("procB"); + + // The "global" variable should be persistent and shared. + manA.loadScript(toLocalURI`global.globalVar = 1;`); + do_check_eq(manA.global.globalVar, 1); + do_check_eq(manA.global.unknownvar, undefined); + manA.loadScript(toLocalURI`global.canSeeGlobal = global.globalVar;`); + do_check_eq(manA.global.canSeeGlobal, 1); + + // Each loadScript call should have their own scope, and global is shared. + manA.loadScript(toLocalURI`this.aVar = 1; global.thisScopeVar = aVar`); + do_check_eq(manA.global.aVar, undefined); + do_check_eq(manA.global.thisScopeVar, 1); + manA.loadScript(toLocalURI`global.differentScopeVar = this.aVar;`); + do_check_eq(manA.global.differentScopeVar, undefined); + manA.loadScript(toLocalURI`global.cantSeeOtherScope = typeof aVar;`); + do_check_eq(manA.global.cantSeeOtherScope, "undefined"); + + manB.loadScript(toLocalURI`global.tryReadOtherGlobal = global.tryagain;`); + do_check_eq(manA.global.tryReadOtherGlobal, undefined); + + // Cu.import without second argument exports to the caller's global. Let's + // verify that it does not leak to the SchemaAPIManager's global. + do_check_eq(typeof ExtensionUtils, "undefined"); // Sanity check #1. + manA.loadScript(toLocalURI`global.hasExtUtils = typeof ExtensionUtils;`); + do_check_eq(manA.global.hasExtUtils, "undefined"); // Sanity check #2 + + Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + do_check_eq(typeof ExtensionUtils, "object"); // Sanity check #3. + + manA.loadScript(toLocalURI`global.hasExtUtils = typeof ExtensionUtils;`); + do_check_eq(manA.global.hasExtUtils, "undefined"); + manB.loadScript(toLocalURI`global.hasExtUtils = typeof ExtensionUtils;`); + do_check_eq(manB.global.hasExtUtils, "undefined"); + + // Confirm that Cu.import does not leak between SchemaAPIManager globals. + manA.loadScript(toLocalURI` + Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + global.hasExtUtils = typeof ExtensionUtils; + `); + do_check_eq(manA.global.hasExtUtils, "object"); // Sanity check. + manB.loadScript(toLocalURI`global.hasExtUtils = typeof ExtensionUtils;`); + do_check_eq(manB.global.hasExtUtils, "undefined"); + + // Prototype modifications should be isolated. + manA.loadScript(toLocalURI` + Object.prototype.modifiedByA = "Prrft"; + global.fromA = {}; + `); + manA.loadScript(toLocalURI` + global.fromAagain = {}; + `); + manB.loadScript(toLocalURI` + global.fromB = {}; + `); + do_check_eq(manA.global.modifiedByA, "Prrft"); + do_check_eq(manA.global.fromA.modifiedByA, "Prrft"); + do_check_eq(manA.global.fromAagain.modifiedByA, "Prrft"); + do_check_eq(manB.global.modifiedByA, undefined); + do_check_eq(manB.global.fromB.modifiedByA, undefined); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_load_events.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_load_events.js new file mode 100644 index 000000000..26282fcb9 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_load_events.js @@ -0,0 +1,23 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +/* eslint-disable mozilla/balanced-listeners */ + +add_task(function* test_DOMContentLoaded_in_generated_background_page() { + let extension = ExtensionTestUtils.loadExtension({ + background() { + function reportListener(event) { + browser.test.sendMessage("eventname", event.type); + } + document.addEventListener("DOMContentLoaded", reportListener); + window.addEventListener("load", reportListener); + }, + }); + + yield extension.startup(); + equal("DOMContentLoaded", yield extension.awaitMessage("eventname")); + equal("load", yield extension.awaitMessage("eventname")); + + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_reload.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_reload.js new file mode 100644 index 000000000..4bf59b798 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_generated_reload.js @@ -0,0 +1,24 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_reload_generated_background_page() { + let extension = ExtensionTestUtils.loadExtension({ + background() { + if (location.hash !== "#firstrun") { + browser.test.sendMessage("first run"); + location.hash = "#firstrun"; + browser.test.assertEq("#firstrun", location.hash); + location.reload(); + } else { + browser.test.notifyPass("second run"); + } + }, + }); + + yield extension.startup(); + yield extension.awaitMessage("first run"); + yield extension.awaitFinish("second run"); + + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_global_history.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_global_history.js new file mode 100644 index 000000000..092a9f5b3 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_global_history.js @@ -0,0 +1,22 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://testing-common/PlacesTestUtils.jsm"); + +add_task(function* test_global_history() { + let extension = ExtensionTestUtils.loadExtension({ + background() { + browser.test.sendMessage("background-loaded", location.href); + }, + }); + + yield extension.startup(); + + let backgroundURL = yield extension.awaitMessage("background-loaded"); + + yield extension.unload(); + + let exists = yield PlacesTestUtils.isPageInDB(backgroundURL); + ok(!exists, "Background URL should not be in history database"); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_private_browsing.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_private_browsing.js new file mode 100644 index 000000000..8e8b5e0b0 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_private_browsing.js @@ -0,0 +1,40 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://gre/modules/Preferences.jsm"); + +function* testBackgroundPage(expected) { + let extension = ExtensionTestUtils.loadExtension({ + async background() { + browser.test.assertEq(window, browser.extension.getBackgroundPage(), + "Caller should be able to access itself as a background page"); + browser.test.assertEq(window, await browser.runtime.getBackgroundPage(), + "Caller should be able to access itself as a background page"); + + browser.test.sendMessage("incognito", browser.extension.inIncognitoContext); + }, + }); + + yield extension.startup(); + + let incognito = yield extension.awaitMessage("incognito"); + equal(incognito, expected.incognito, "Expected incognito value"); + + yield extension.unload(); +} + +add_task(function* test_background_incognito() { + do_print("Test background page incognito value with permanent private browsing disabled"); + + yield testBackgroundPage({incognito: false}); + + do_print("Test background page incognito value with permanent private browsing enabled"); + + Preferences.set("browser.privatebrowsing.autostart", true); + do_register_cleanup(() => { + Preferences.reset("browser.privatebrowsing.autostart"); + }); + + yield testBackgroundPage({incognito: true}); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_runtime_connect_params.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_runtime_connect_params.js new file mode 100644 index 000000000..426833edd --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_runtime_connect_params.js @@ -0,0 +1,72 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +function backgroundScript() { + let received_ports_number = 0; + + const expected_received_ports_number = 1; + + function countReceivedPorts(port) { + received_ports_number++; + + if (port.name == "check-results") { + browser.runtime.onConnect.removeListener(countReceivedPorts); + + browser.test.assertEq(expected_received_ports_number, received_ports_number, "invalid connect should not create a port"); + + browser.test.notifyPass("runtime.connect invalid params"); + } + } + + browser.runtime.onConnect.addListener(countReceivedPorts); + + let childFrame = document.createElement("iframe"); + childFrame.src = "extensionpage.html"; + document.body.appendChild(childFrame); +} + +function senderScript() { + let detected_invalid_connect_params = 0; + + const invalid_connect_params = [ + // too many params + ["fake-extensions-id", {name: "fake-conn-name"}, "unexpected third params"], + // invalid params format + [{}, {}], + ["fake-extensions-id", "invalid-connect-info-format"], + ]; + const expected_detected_invalid_connect_params = invalid_connect_params.length; + + function assertInvalidConnectParamsException(params) { + try { + browser.runtime.connect(...params); + } catch (e) { + detected_invalid_connect_params++; + browser.test.assertTrue(e.toString().indexOf("Incorrect argument types for runtime.connect.") >= 0, "exception message is correct"); + } + } + for (let params of invalid_connect_params) { + assertInvalidConnectParamsException(params); + } + browser.test.assertEq(expected_detected_invalid_connect_params, detected_invalid_connect_params, "all invalid runtime.connect params detected"); + + browser.runtime.connect(browser.runtime.id, {name: "check-results"}); +} + +let extensionData = { + background: backgroundScript, + files: { + "senderScript.js": senderScript, + "extensionpage.html": ``, + }, +}; + +add_task(function* test_backgroundRuntimeConnectParams() { + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + + yield extension.awaitFinish("runtime.connect invalid params"); + + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_sub_windows.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_sub_windows.js new file mode 100644 index 000000000..c5f2f1332 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_sub_windows.js @@ -0,0 +1,45 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* testBackgroundWindow() { + let extension = ExtensionTestUtils.loadExtension({ + background() { + browser.test.log("background script executed"); + + browser.test.sendMessage("background-script-load"); + + let img = document.createElement("img"); + img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; + document.body.appendChild(img); + + img.onload = () => { + browser.test.log("image loaded"); + + let iframe = document.createElement("iframe"); + iframe.src = "about:blank?1"; + + iframe.onload = () => { + browser.test.log("iframe loaded"); + setTimeout(() => { + browser.test.notifyPass("background sub-window test done"); + }, 0); + }; + document.body.appendChild(iframe); + }; + }, + }); + + let loadCount = 0; + extension.onMessage("background-script-load", () => { + loadCount++; + }); + + yield extension.startup(); + + yield extension.awaitFinish("background sub-window test done"); + + equal(loadCount, 1, "background script loaded only once"); + + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_background_window_properties.js b/toolkit/components/webextensions/test/xpcshell/test_ext_background_window_properties.js new file mode 100644 index 000000000..948e2913e --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_background_window_properties.js @@ -0,0 +1,34 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* testBackgroundWindowProperties() { + let extension = ExtensionTestUtils.loadExtension({ + background() { + let expectedValues = { + screenX: 0, + screenY: 0, + outerWidth: 0, + outerHeight: 0, + }; + + for (let k in window) { + try { + if (k in expectedValues) { + browser.test.assertEq(expectedValues[k], window[k], + `should return the expected value for window property: ${k}`); + } else { + void window[k]; + } + } catch (e) { + browser.test.assertEq(null, e, `unexpected exception accessing window property: ${k}`); + } + } + + browser.test.notifyPass("background.testWindowProperties.done"); + }, + }); + yield extension.startup(); + yield extension.awaitFinish("background.testWindowProperties.done"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_contexts.js b/toolkit/components/webextensions/test/xpcshell/test_ext_contexts.js new file mode 100644 index 000000000..56a14e189 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_contexts.js @@ -0,0 +1,190 @@ +"use strict"; + +const global = this; + +Cu.import("resource://gre/modules/Timer.jsm"); + +Cu.import("resource://gre/modules/ExtensionCommon.jsm"); +Cu.import("resource://gre/modules/ExtensionUtils.jsm"); + +var { + BaseContext, +} = ExtensionCommon; + +var { + EventManager, + SingletonEventManager, +} = ExtensionUtils; + +class StubContext extends BaseContext { + constructor() { + let fakeExtension = {id: "test@web.extension"}; + super("testEnv", fakeExtension); + this.sandbox = Cu.Sandbox(global); + } + + get cloneScope() { + return this.sandbox; + } +} + + +add_task(function* test_post_unload_promises() { + let context = new StubContext(); + + let fail = result => { + ok(false, `Unexpected callback: ${result}`); + }; + + // Make sure promises resolve normally prior to unload. + let promises = [ + context.wrapPromise(Promise.resolve()), + context.wrapPromise(Promise.reject({message: ""})).catch(() => {}), + ]; + + yield Promise.all(promises); + + // Make sure promises that resolve after unload do not trigger + // resolution handlers. + + context.wrapPromise(Promise.resolve("resolved")) + .then(fail); + + context.wrapPromise(Promise.reject({message: "rejected"})) + .then(fail, fail); + + context.unload(); + + // The `setTimeout` ensures that we return to the event loop after + // promise resolution, which means we're guaranteed to return after + // any micro-tasks that get enqueued by the resolution handlers above. + yield new Promise(resolve => setTimeout(resolve, 0)); +}); + + +add_task(function* test_post_unload_listeners() { + let context = new StubContext(); + + let fireEvent; + let onEvent = new EventManager(context, "onEvent", fire => { + fireEvent = fire; + return () => {}; + }); + + let fireSingleton; + let onSingleton = new SingletonEventManager(context, "onSingleton", callback => { + fireSingleton = () => { + Promise.resolve().then(callback); + }; + return () => {}; + }); + + let fail = event => { + ok(false, `Unexpected event: ${event}`); + }; + + // Check that event listeners aren't called after they've been removed. + onEvent.addListener(fail); + onSingleton.addListener(fail); + + let promises = [ + new Promise(resolve => onEvent.addListener(resolve)), + new Promise(resolve => onSingleton.addListener(resolve)), + ]; + + fireEvent("onEvent"); + fireSingleton("onSingleton"); + + // Both `fireEvent` calls are dispatched asynchronously, so they won't + // have fired by this point. The `fail` listeners that we remove now + // should not be called, even though the events have already been + // enqueued. + onEvent.removeListener(fail); + onSingleton.removeListener(fail); + + // Wait for the remaining listeners to be called, which should always + // happen after the `fail` listeners would normally be called. + yield Promise.all(promises); + + // Check that event listeners aren't called after the context has + // unloaded. + onEvent.addListener(fail); + onSingleton.addListener(fail); + + // The EventManager `fire` callback always dispatches events + // asynchronously, so we need to test that any pending event callbacks + // aren't fired after the context unloads. We also need to test that + // any `fire` calls that happen *after* the context is unloaded also + // do not trigger callbacks. + fireEvent("onEvent"); + Promise.resolve("onEvent").then(fireEvent); + + fireSingleton("onSingleton"); + Promise.resolve("onSingleton").then(fireSingleton); + + context.unload(); + + // The `setTimeout` ensures that we return to the event loop after + // promise resolution, which means we're guaranteed to return after + // any micro-tasks that get enqueued by the resolution handlers above. + yield new Promise(resolve => setTimeout(resolve, 0)); +}); + +class Context extends BaseContext { + constructor(principal) { + let fakeExtension = {id: "test@web.extension"}; + super("testEnv", fakeExtension); + Object.defineProperty(this, "principal", { + value: principal, + configurable: true, + }); + this.sandbox = Cu.Sandbox(principal, {wantXrays: false}); + } + + get cloneScope() { + return this.sandbox; + } +} + +let ssm = Services.scriptSecurityManager; +const PRINCIPAL1 = ssm.createCodebasePrincipalFromOrigin("http://www.example.org"); +const PRINCIPAL2 = ssm.createCodebasePrincipalFromOrigin("http://www.somethingelse.org"); + +// Test that toJSON() works in the json sandbox +add_task(function* test_stringify_toJSON() { + let context = new Context(PRINCIPAL1); + let obj = Cu.evalInSandbox("({hidden: true, toJSON() { return {visible: true}; } })", context.sandbox); + + let stringified = context.jsonStringify(obj); + let expected = JSON.stringify({visible: true}); + equal(stringified, expected, "Stringified object with toJSON() method is as expected"); +}); + +// Test that stringifying in inaccessible property throws +add_task(function* test_stringify_inaccessible() { + let context = new Context(PRINCIPAL1); + let sandbox = context.sandbox; + let sandbox2 = Cu.Sandbox(PRINCIPAL2); + + Cu.waiveXrays(sandbox).subobj = Cu.evalInSandbox("({ subobject: true })", sandbox2); + let obj = Cu.evalInSandbox("({ local: true, nested: subobj })", sandbox); + Assert.throws(() => { + context.jsonStringify(obj); + }); +}); + +add_task(function* test_stringify_accessible() { + // Test that an accessible property from another global is included + let principal = Cu.getObjectPrincipal(Cu.Sandbox([PRINCIPAL1, PRINCIPAL2])); + let context = new Context(principal); + let sandbox = context.sandbox; + let sandbox2 = Cu.Sandbox(PRINCIPAL2); + + Cu.waiveXrays(sandbox).subobj = Cu.evalInSandbox("({ subobject: true })", sandbox2); + let obj = Cu.evalInSandbox("({ local: true, nested: subobj })", sandbox); + let stringified = context.jsonStringify(obj); + + let expected = JSON.stringify({local: true, nested: {subobject: true}}); + equal(stringified, expected, "Stringified object with accessible property is as expected"); +}); + diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_downloads.js b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads.js new file mode 100644 index 000000000..058b9b18c --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads.js @@ -0,0 +1,76 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_downloads_api_namespace_and_permissions() { + function backgroundScript() { + browser.test.assertTrue(!!browser.downloads, "`downloads` API is present."); + browser.test.assertTrue(!!browser.downloads.FilenameConflictAction, + "`downloads.FilenameConflictAction` enum is present."); + browser.test.assertTrue(!!browser.downloads.InterruptReason, + "`downloads.InterruptReason` enum is present."); + browser.test.assertTrue(!!browser.downloads.DangerType, + "`downloads.DangerType` enum is present."); + browser.test.assertTrue(!!browser.downloads.State, + "`downloads.State` enum is present."); + browser.test.notifyPass("downloads tests"); + } + + let extensionData = { + background: backgroundScript, + manifest: { + permissions: ["downloads", "downloads.open", "downloads.shelf"], + }, + }; + + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + yield extension.awaitFinish("downloads tests"); + yield extension.unload(); +}); + +add_task(function* test_downloads_open_permission() { + function backgroundScript() { + browser.test.assertFalse("open" in browser.downloads, + "`downloads.open` permission is required."); + browser.test.notifyPass("downloads tests"); + } + + let extensionData = { + background: backgroundScript, + manifest: { + permissions: ["downloads"], + }, + }; + + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + yield extension.awaitFinish("downloads tests"); + yield extension.unload(); +}); + +add_task(function* test_downloads_open() { + async function backgroundScript() { + await browser.test.assertRejects( + browser.downloads.open(10), + "Invalid download id 10", + "The error is informative."); + + browser.test.notifyPass("downloads tests"); + + // TODO: Once downloads.{pause,cancel,resume} lands (bug 1245602) test that this gives a good + // error when called with an incompleted download. + } + + let extensionData = { + background: backgroundScript, + manifest: { + permissions: ["downloads", "downloads.open"], + }, + }; + + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + yield extension.awaitFinish("downloads tests"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_download.js b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_download.js new file mode 100644 index 000000000..37ddd4d7c --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_download.js @@ -0,0 +1,354 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +/* global OS */ + +Cu.import("resource://gre/modules/osfile.jsm"); +Cu.import("resource://gre/modules/Downloads.jsm"); + +const gServer = createHttpServer(); +gServer.registerDirectory("/data/", do_get_file("data")); + +const WINDOWS = AppConstants.platform == "win"; + +const BASE = `http://localhost:${gServer.identity.primaryPort}/data`; +const FILE_NAME = "file_download.txt"; +const FILE_URL = BASE + "/" + FILE_NAME; +const FILE_NAME_UNIQUE = "file_download(1).txt"; +const FILE_LEN = 46; + +let downloadDir; + +function setup() { + downloadDir = FileUtils.getDir("TmpD", ["downloads"]); + downloadDir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); + do_print(`Using download directory ${downloadDir.path}`); + + Services.prefs.setIntPref("browser.download.folderList", 2); + Services.prefs.setComplexValue("browser.download.dir", Ci.nsIFile, downloadDir); + + do_register_cleanup(() => { + Services.prefs.clearUserPref("browser.download.folderList"); + Services.prefs.clearUserPref("browser.download.dir"); + + let entries = downloadDir.directoryEntries; + while (entries.hasMoreElements()) { + let entry = entries.getNext().QueryInterface(Ci.nsIFile); + ok(false, `Leftover file ${entry.path} in download directory`); + entry.remove(false); + } + + downloadDir.remove(false); + }); +} + +function backgroundScript() { + let blobUrl; + browser.test.onMessage.addListener(async (msg, ...args) => { + if (msg == "download.request") { + let options = args[0]; + + if (options.blobme) { + let blob = new Blob(options.blobme); + delete options.blobme; + blobUrl = options.url = window.URL.createObjectURL(blob); + } + + try { + let id = await browser.downloads.download(options); + browser.test.sendMessage("download.done", {status: "success", id}); + } catch (error) { + browser.test.sendMessage("download.done", {status: "error", errmsg: error.message}); + } + } else if (msg == "killTheBlob") { + window.URL.revokeObjectURL(blobUrl); + blobUrl = null; + } + }); + + browser.test.sendMessage("ready"); +} + +// This function is a bit of a sledgehammer, it looks at every download +// the browser knows about and waits for all active downloads to complete. +// But we only start one at a time and only do a handful in total, so +// this lets us test download() without depending on anything else. +async function waitForDownloads() { + let list = await Downloads.getList(Downloads.ALL); + let downloads = await list.getAll(); + + let inprogress = downloads.filter(dl => !dl.stopped); + return Promise.all(inprogress.map(dl => dl.whenSucceeded())); +} + +// Create a file in the downloads directory. +function touch(filename) { + let file = downloadDir.clone(); + file.append(filename); + file.create(Ci.nsIFile.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE); +} + +// Remove a file in the downloads directory. +function remove(filename, recursive = false) { + let file = downloadDir.clone(); + file.append(filename); + file.remove(recursive); +} + +add_task(function* test_downloads() { + setup(); + + let extension = ExtensionTestUtils.loadExtension({ + background: `(${backgroundScript})()`, + manifest: { + permissions: ["downloads"], + }, + }); + + function download(options) { + extension.sendMessage("download.request", options); + return extension.awaitMessage("download.done"); + } + + async function testDownload(options, localFile, expectedSize, description) { + let msg = await download(options); + equal(msg.status, "success", `downloads.download() works with ${description}`); + + await waitForDownloads(); + + let localPath = downloadDir.clone(); + let parts = Array.isArray(localFile) ? localFile : [localFile]; + + parts.map(p => localPath.append(p)); + equal(localPath.fileSize, expectedSize, "Downloaded file has expected size"); + localPath.remove(false); + } + + yield extension.startup(); + yield extension.awaitMessage("ready"); + do_print("extension started"); + + // Call download() with just the url property. + yield testDownload({url: FILE_URL}, FILE_NAME, FILE_LEN, "just source"); + + // Call download() with a filename property. + yield testDownload({ + url: FILE_URL, + filename: "newpath.txt", + }, "newpath.txt", FILE_LEN, "source and filename"); + + // Call download() with a filename with subdirs. + yield testDownload({ + url: FILE_URL, + filename: "sub/dir/file", + }, ["sub", "dir", "file"], FILE_LEN, "source and filename with subdirs"); + + // Call download() with a filename with existing subdirs. + yield testDownload({ + url: FILE_URL, + filename: "sub/dir/file2", + }, ["sub", "dir", "file2"], FILE_LEN, "source and filename with existing subdirs"); + + // Only run Windows path separator test on Windows. + if (WINDOWS) { + // Call download() with a filename with Windows path separator. + yield testDownload({ + url: FILE_URL, + filename: "sub\\dir\\file3", + }, ["sub", "dir", "file3"], FILE_LEN, "filename with Windows path separator"); + } + remove("sub", true); + + // Call download(), filename with subdir, skipping parts. + yield testDownload({ + url: FILE_URL, + filename: "skip//part", + }, ["skip", "part"], FILE_LEN, "source, filename, with subdir, skipping parts"); + remove("skip", true); + + // Check conflictAction of "uniquify". + touch(FILE_NAME); + yield testDownload({ + url: FILE_URL, + conflictAction: "uniquify", + }, FILE_NAME_UNIQUE, FILE_LEN, "conflictAction=uniquify"); + // todo check that preexisting file was not modified? + remove(FILE_NAME); + + // Check conflictAction of "overwrite". + touch(FILE_NAME); + yield testDownload({ + url: FILE_URL, + conflictAction: "overwrite", + }, FILE_NAME, FILE_LEN, "conflictAction=overwrite"); + + // Try to download in invalid url + yield download({url: "this is not a valid URL"}).then(msg => { + equal(msg.status, "error", "downloads.download() fails with invalid url"); + ok(/not a valid URL/.test(msg.errmsg), "error message for invalid url is correct"); + }); + + // Try to download to an empty path. + yield download({ + url: FILE_URL, + filename: "", + }).then(msg => { + equal(msg.status, "error", "downloads.download() fails with empty filename"); + equal(msg.errmsg, "filename must not be empty", "error message for empty filename is correct"); + }); + + // Try to download to an absolute path. + const absolutePath = OS.Path.join(WINDOWS ? "\\tmp" : "/tmp", "file_download.txt"); + yield download({ + url: FILE_URL, + filename: absolutePath, + }).then(msg => { + equal(msg.status, "error", "downloads.download() fails with absolute filename"); + equal(msg.errmsg, "filename must not be an absolute path", `error message for absolute path (${absolutePath}) is correct`); + }); + + if (WINDOWS) { + yield download({ + url: FILE_URL, + filename: "C:\\file_download.txt", + }).then(msg => { + equal(msg.status, "error", "downloads.download() fails with absolute filename"); + equal(msg.errmsg, "filename must not be an absolute path", "error message for absolute path with drive letter is correct"); + }); + } + + // Try to download to a relative path containing .. + yield download({ + url: FILE_URL, + filename: OS.Path.join("..", "file_download.txt"), + }).then(msg => { + equal(msg.status, "error", "downloads.download() fails with back-references"); + equal(msg.errmsg, "filename must not contain back-references (..)", "error message for back-references is correct"); + }); + + // Try to download to a long relative path containing .. + yield download({ + url: FILE_URL, + filename: OS.Path.join("foo", "..", "..", "file_download.txt"), + }).then(msg => { + equal(msg.status, "error", "downloads.download() fails with back-references"); + equal(msg.errmsg, "filename must not contain back-references (..)", "error message for back-references is correct"); + }); + + // Try to download a blob url + const BLOB_STRING = "Hello, world"; + yield testDownload({ + blobme: [BLOB_STRING], + filename: FILE_NAME, + }, FILE_NAME, BLOB_STRING.length, "blob url"); + extension.sendMessage("killTheBlob"); + + // Try to download a blob url without a given filename + yield testDownload({ + blobme: [BLOB_STRING], + }, "download", BLOB_STRING.length, "blob url with no filename"); + extension.sendMessage("killTheBlob"); + + yield extension.unload(); +}); + +add_task(function* test_download_post() { + const server = createHttpServer(); + const url = `http://localhost:${server.identity.primaryPort}/post-log`; + + let received; + server.registerPathHandler("/post-log", request => { + received = request; + }); + + // Confirm received vs. expected values. + function confirm(method, headers = {}, body) { + equal(received.method, method, "method is correct"); + + for (let name in headers) { + ok(received.hasHeader(name), `header ${name} received`); + equal(received.getHeader(name), headers[name], `header ${name} is correct`); + } + + if (body) { + const str = NetUtil.readInputStreamToString(received.bodyInputStream, + received.bodyInputStream.available()); + equal(str, body, "body is correct"); + } + } + + function background() { + browser.test.onMessage.addListener(async options => { + try { + await browser.downloads.download(options); + } catch (err) { + browser.test.sendMessage("done", {err: err.message}); + } + }); + browser.downloads.onChanged.addListener(({state}) => { + if (state && state.current === "complete") { + browser.test.sendMessage("done", {ok: true}); + } + }); + } + + const manifest = {permissions: ["downloads"]}; + const extension = ExtensionTestUtils.loadExtension({background, manifest}); + yield extension.startup(); + + function download(options) { + options.url = url; + options.conflictAction = "overwrite"; + + extension.sendMessage(options); + return extension.awaitMessage("done"); + } + + // Test method option. + let result = yield download({}); + ok(result.ok, "download works without the method option, defaults to GET"); + confirm("GET"); + + result = yield download({method: "PUT"}); + ok(!result.ok, "download rejected with PUT method"); + ok(/method: Invalid enumeration/.test(result.err), "descriptive error message"); + + result = yield download({method: "POST"}); + ok(result.ok, "download works with POST method"); + confirm("POST"); + + // Test body option values. + result = yield download({body: []}); + ok(!result.ok, "download rejected because of non-string body"); + ok(/body: Expected string/.test(result.err), "descriptive error message"); + + result = yield download({method: "POST", body: "of work"}); + ok(result.ok, "download works with POST method and body"); + confirm("POST", {"Content-Length": 7}, "of work"); + + // Test custom headers. + result = yield download({headers: [{name: "X-Custom"}]}); + ok(!result.ok, "download rejected because of missing header value"); + ok(/"value" is required/.test(result.err), "descriptive error message"); + + result = yield download({headers: [{name: "X-Custom", value: "13"}]}); + ok(result.ok, "download works with a custom header"); + confirm("GET", {"X-Custom": "13"}); + + // Test forbidden headers. + result = yield download({headers: [{name: "DNT", value: "1"}]}); + ok(!result.ok, "download rejected because of forbidden header name DNT"); + ok(/Forbidden request header/.test(result.err), "descriptive error message"); + + result = yield download({headers: [{name: "Proxy-Connection", value: "keep"}]}); + ok(!result.ok, "download rejected because of forbidden header name prefix Proxy-"); + ok(/Forbidden request header/.test(result.err), "descriptive error message"); + + result = yield download({headers: [{name: "Sec-ret", value: "13"}]}); + ok(!result.ok, "download rejected because of forbidden header name prefix Sec-"); + ok(/Forbidden request header/.test(result.err), "descriptive error message"); + + remove("post-log"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_misc.js b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_misc.js new file mode 100644 index 000000000..d08aab666 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_misc.js @@ -0,0 +1,862 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://gre/modules/Downloads.jsm"); + +const server = createHttpServer(); +server.registerDirectory("/data/", do_get_file("data")); + +const ROOT = `http://localhost:${server.identity.primaryPort}`; +const BASE = `${ROOT}/data`; +const TXT_FILE = "file_download.txt"; +const TXT_URL = BASE + "/" + TXT_FILE; + +// Keep these in sync with code in interruptible.sjs +const INT_PARTIAL_LEN = 15; +const INT_TOTAL_LEN = 31; + +const TEST_DATA = "This is 31 bytes of sample data"; +const TOTAL_LEN = TEST_DATA.length; +const PARTIAL_LEN = 15; + +// A handler to let us systematically test pausing/resuming/canceling +// of downloads. This target represents a small text file but a simple +// GET will stall after sending part of the data, to give the test code +// a chance to pause or do other operations on an in-progress download. +// A resumed download (ie, a GET with a Range: header) will allow the +// download to complete. +function handleRequest(request, response) { + response.setHeader("Content-Type", "text/plain", false); + + if (request.hasHeader("Range")) { + let start, end; + let matches = request.getHeader("Range") + .match(/^\s*bytes=(\d+)?-(\d+)?\s*$/); + if (matches != null) { + start = matches[1] ? parseInt(matches[1], 10) : 0; + end = matches[2] ? parseInt(matches[2], 10) : (TOTAL_LEN - 1); + } + + if (end == undefined || end >= TOTAL_LEN) { + response.setStatusLine(request.httpVersion, 416, "Requested Range Not Satisfiable"); + response.setHeader("Content-Range", `*/${TOTAL_LEN}`, false); + response.finish(); + return; + } + + response.setStatusLine(request.httpVersion, 206, "Partial Content"); + response.setHeader("Content-Range", `${start}-${end}/${TOTAL_LEN}`, false); + response.write(TEST_DATA.slice(start, end + 1)); + } else { + response.processAsync(); + response.setHeader("Content-Length", `${TOTAL_LEN}`, false); + response.write(TEST_DATA.slice(0, PARTIAL_LEN)); + } + + do_register_cleanup(() => { + try { + response.finish(); + } catch (e) { + // This will throw, but we don't care at this point. + } + }); +} + +server.registerPathHandler("/interruptible.html", handleRequest); + +let interruptibleCount = 0; +function getInterruptibleUrl() { + let n = interruptibleCount++; + return `${ROOT}/interruptible.html?count=${n}`; +} + +function backgroundScript() { + let events = new Set(); + let eventWaiter = null; + + browser.downloads.onCreated.addListener(data => { + events.add({type: "onCreated", data}); + if (eventWaiter) { + eventWaiter(); + } + }); + + browser.downloads.onChanged.addListener(data => { + events.add({type: "onChanged", data}); + if (eventWaiter) { + eventWaiter(); + } + }); + + browser.downloads.onErased.addListener(data => { + events.add({type: "onErased", data}); + if (eventWaiter) { + eventWaiter(); + } + }); + + // Returns a promise that will resolve when the given list of expected + // events have all been seen. By default, succeeds only if the exact list + // of expected events is seen in the given order. options.exact can be + // set to false to allow other events and options.inorder can be set to + // false to allow the events to arrive in any order. + function waitForEvents(expected, options = {}) { + function compare(a, b) { + if (typeof b == "object" && b != null) { + if (typeof a != "object") { + return false; + } + return Object.keys(b).every(fld => compare(a[fld], b[fld])); + } + return (a == b); + } + + const exact = ("exact" in options) ? options.exact : true; + const inorder = ("inorder" in options) ? options.inorder : true; + return new Promise((resolve, reject) => { + function check() { + function fail(msg) { + browser.test.fail(msg); + reject(new Error(msg)); + } + if (events.size < expected.length) { + return; + } + if (exact && expected.length < events.size) { + fail(`Got ${events.size} events but only expected ${expected.length}`); + return; + } + + let remaining = new Set(events); + if (inorder) { + for (let event of events) { + if (compare(event, expected[0])) { + expected.shift(); + remaining.delete(event); + } + } + } else { + expected = expected.filter(val => { + for (let remainingEvent of remaining) { + if (compare(remainingEvent, val)) { + remaining.delete(remainingEvent); + return false; + } + } + return true; + }); + } + + // Events that did occur have been removed from expected so if + // expected is empty, we're done. If we didn't see all the + // expected events and we're not looking for an exact match, + // then we just may not have seen the event yet, so return without + // failing and check() will be called again when a new event arrives. + if (expected.length == 0) { + events = remaining; + eventWaiter = null; + resolve(); + } else if (exact) { + fail(`Mismatched event: expecting ${JSON.stringify(expected[0])} but got ${JSON.stringify(Array.from(remaining)[0])}`); + } + } + eventWaiter = check; + check(); + }); + } + + browser.test.onMessage.addListener(async (msg, ...args) => { + let match = msg.match(/(\w+).request$/); + if (!match) { + return; + } + + let what = match[1]; + if (what == "waitForEvents") { + try { + await waitForEvents(...args); + browser.test.sendMessage("waitForEvents.done", {status: "success"}); + } catch (error) { + browser.test.sendMessage("waitForEvents.done", {status: "error", errmsg: error.message}); + } + } else if (what == "clearEvents") { + events = new Set(); + browser.test.sendMessage("clearEvents.done", {status: "success"}); + } else { + try { + let result = await browser.downloads[what](...args); + browser.test.sendMessage(`${what}.done`, {status: "success", result}); + } catch (error) { + browser.test.sendMessage(`${what}.done`, {status: "error", errmsg: error.message}); + } + } + }); + + browser.test.sendMessage("ready"); +} + +let downloadDir; +let extension; + +async function clearDownloads(callback) { + let list = await Downloads.getList(Downloads.ALL); + let downloads = await list.getAll(); + + await Promise.all(downloads.map(download => list.remove(download))); + + return downloads; +} + +function runInExtension(what, ...args) { + extension.sendMessage(`${what}.request`, ...args); + return extension.awaitMessage(`${what}.done`); +} + +// This is pretty simplistic, it looks for a progress update for a +// download of the given url in which the total bytes are exactly equal +// to the given value. Unless you know exactly how data will arrive from +// the server (eg see interruptible.sjs), it probably isn't very useful. +async function waitForProgress(url, bytes) { + let list = await Downloads.getList(Downloads.ALL); + + return new Promise(resolve => { + const view = { + onDownloadChanged(download) { + if (download.source.url == url && download.currentBytes == bytes) { + list.removeView(view); + resolve(); + } + }, + }; + list.addView(view); + }); +} + +add_task(function* setup() { + const nsIFile = Ci.nsIFile; + downloadDir = FileUtils.getDir("TmpD", ["downloads"]); + downloadDir.createUnique(nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); + do_print(`downloadDir ${downloadDir.path}`); + + Services.prefs.setIntPref("browser.download.folderList", 2); + Services.prefs.setComplexValue("browser.download.dir", nsIFile, downloadDir); + + do_register_cleanup(() => { + Services.prefs.clearUserPref("browser.download.folderList"); + Services.prefs.clearUserPref("browser.download.dir"); + downloadDir.remove(true); + + return clearDownloads(); + }); + + yield clearDownloads().then(downloads => { + do_print(`removed ${downloads.length} pre-existing downloads from history`); + }); + + extension = ExtensionTestUtils.loadExtension({ + background: backgroundScript, + manifest: { + permissions: ["downloads"], + }, + }); + + yield extension.startup(); + yield extension.awaitMessage("ready"); +}); + +add_task(function* test_events() { + let msg = yield runInExtension("download", {url: TXT_URL}); + equal(msg.status, "success", "download() succeeded"); + const id = msg.result; + + msg = yield runInExtension("waitForEvents", [ + {type: "onCreated", data: {id, url: TXT_URL}}, + { + type: "onChanged", + data: { + id, + state: { + previous: "in_progress", + current: "complete", + }, + }, + }, + ]); + equal(msg.status, "success", "got onCreated and onChanged events"); +}); + +add_task(function* test_cancel() { + let url = getInterruptibleUrl(); + do_print(url); + let msg = yield runInExtension("download", {url}); + equal(msg.status, "success", "download() succeeded"); + const id = msg.result; + + let progressPromise = waitForProgress(url, INT_PARTIAL_LEN); + + msg = yield runInExtension("waitForEvents", [ + {type: "onCreated", data: {id}}, + ]); + equal(msg.status, "success", "got created and changed events"); + + yield progressPromise; + do_print(`download reached ${INT_PARTIAL_LEN} bytes`); + + msg = yield runInExtension("cancel", id); + equal(msg.status, "success", "cancel() succeeded"); + + // This sequence of events is bogus (bug 1256243) + msg = yield runInExtension("waitForEvents", [ + { + type: "onChanged", + data: { + state: { + previous: "in_progress", + current: "interrupted", + }, + paused: { + previous: false, + current: true, + }, + }, + }, { + type: "onChanged", + data: { + id, + error: { + previous: null, + current: "USER_CANCELED", + }, + }, + }, { + type: "onChanged", + data: { + id, + paused: { + previous: true, + current: false, + }, + }, + }, + ]); + equal(msg.status, "success", "got onChanged events corresponding to cancel()"); + + msg = yield runInExtension("search", {error: "USER_CANCELED"}); + equal(msg.status, "success", "search() succeeded"); + equal(msg.result.length, 1, "search() found 1 download"); + equal(msg.result[0].id, id, "download.id is correct"); + equal(msg.result[0].state, "interrupted", "download.state is correct"); + equal(msg.result[0].paused, false, "download.paused is correct"); + equal(msg.result[0].canResume, false, "download.canResume is correct"); + equal(msg.result[0].error, "USER_CANCELED", "download.error is correct"); + equal(msg.result[0].totalBytes, INT_TOTAL_LEN, "download.totalBytes is correct"); + equal(msg.result[0].exists, false, "download.exists is correct"); + + msg = yield runInExtension("pause", id); + equal(msg.status, "error", "cannot pause a canceled download"); + + msg = yield runInExtension("resume", id); + equal(msg.status, "error", "cannot resume a canceled download"); +}); + +add_task(function* test_pauseresume() { + let url = getInterruptibleUrl(); + let msg = yield runInExtension("download", {url}); + equal(msg.status, "success", "download() succeeded"); + const id = msg.result; + + let progressPromise = waitForProgress(url, INT_PARTIAL_LEN); + + msg = yield runInExtension("waitForEvents", [ + {type: "onCreated", data: {id}}, + ]); + equal(msg.status, "success", "got created and changed events"); + + yield progressPromise; + do_print(`download reached ${INT_PARTIAL_LEN} bytes`); + + msg = yield runInExtension("pause", id); + equal(msg.status, "success", "pause() succeeded"); + + msg = yield runInExtension("waitForEvents", [ + { + type: "onChanged", + data: { + id, + state: { + previous: "in_progress", + current: "interrupted", + }, + paused: { + previous: false, + current: true, + }, + canResume: { + previous: false, + current: true, + }, + }, + }, { + type: "onChanged", + data: { + id, + error: { + previous: null, + current: "USER_CANCELED", + }, + }, + }]); + equal(msg.status, "success", "got onChanged event corresponding to pause"); + + msg = yield runInExtension("search", {paused: true}); + equal(msg.status, "success", "search() succeeded"); + equal(msg.result.length, 1, "search() found 1 download"); + equal(msg.result[0].id, id, "download.id is correct"); + equal(msg.result[0].state, "interrupted", "download.state is correct"); + equal(msg.result[0].paused, true, "download.paused is correct"); + equal(msg.result[0].canResume, true, "download.canResume is correct"); + equal(msg.result[0].error, "USER_CANCELED", "download.error is correct"); + equal(msg.result[0].bytesReceived, INT_PARTIAL_LEN, "download.bytesReceived is correct"); + equal(msg.result[0].totalBytes, INT_TOTAL_LEN, "download.totalBytes is correct"); + equal(msg.result[0].exists, false, "download.exists is correct"); + + msg = yield runInExtension("search", {error: "USER_CANCELED"}); + equal(msg.status, "success", "search() succeeded"); + let found = msg.result.filter(item => item.id == id); + equal(found.length, 1, "search() by error found the paused download"); + + msg = yield runInExtension("pause", id); + equal(msg.status, "error", "cannot pause an already paused download"); + + msg = yield runInExtension("resume", id); + equal(msg.status, "success", "resume() succeeded"); + + msg = yield runInExtension("waitForEvents", [ + { + type: "onChanged", + data: { + id, + state: { + previous: "interrupted", + current: "in_progress", + }, + paused: { + previous: true, + current: false, + }, + canResume: { + previous: true, + current: false, + }, + error: { + previous: "USER_CANCELED", + current: null, + }, + }, + }, + { + type: "onChanged", + data: { + id, + state: { + previous: "in_progress", + current: "complete", + }, + }, + }, + ]); + equal(msg.status, "success", "got onChanged events for resume and complete"); + + msg = yield runInExtension("search", {id}); + equal(msg.status, "success", "search() succeeded"); + equal(msg.result.length, 1, "search() found 1 download"); + equal(msg.result[0].state, "complete", "download.state is correct"); + equal(msg.result[0].paused, false, "download.paused is correct"); + equal(msg.result[0].canResume, false, "download.canResume is correct"); + equal(msg.result[0].error, null, "download.error is correct"); + equal(msg.result[0].bytesReceived, INT_TOTAL_LEN, "download.bytesReceived is correct"); + equal(msg.result[0].totalBytes, INT_TOTAL_LEN, "download.totalBytes is correct"); + equal(msg.result[0].exists, true, "download.exists is correct"); + + msg = yield runInExtension("pause", id); + equal(msg.status, "error", "cannot pause a completed download"); + + msg = yield runInExtension("resume", id); + equal(msg.status, "error", "cannot resume a completed download"); +}); + +add_task(function* test_pausecancel() { + let url = getInterruptibleUrl(); + let msg = yield runInExtension("download", {url}); + equal(msg.status, "success", "download() succeeded"); + const id = msg.result; + + let progressPromise = waitForProgress(url, INT_PARTIAL_LEN); + + msg = yield runInExtension("waitForEvents", [ + {type: "onCreated", data: {id}}, + ]); + equal(msg.status, "success", "got created and changed events"); + + yield progressPromise; + do_print(`download reached ${INT_PARTIAL_LEN} bytes`); + + msg = yield runInExtension("pause", id); + equal(msg.status, "success", "pause() succeeded"); + + msg = yield runInExtension("waitForEvents", [ + { + type: "onChanged", + data: { + id, + state: { + previous: "in_progress", + current: "interrupted", + }, + paused: { + previous: false, + current: true, + }, + canResume: { + previous: false, + current: true, + }, + }, + }, { + type: "onChanged", + data: { + id, + error: { + previous: null, + current: "USER_CANCELED", + }, + }, + }]); + equal(msg.status, "success", "got onChanged event corresponding to pause"); + + msg = yield runInExtension("search", {paused: true}); + equal(msg.status, "success", "search() succeeded"); + equal(msg.result.length, 1, "search() found 1 download"); + equal(msg.result[0].id, id, "download.id is correct"); + equal(msg.result[0].state, "interrupted", "download.state is correct"); + equal(msg.result[0].paused, true, "download.paused is correct"); + equal(msg.result[0].canResume, true, "download.canResume is correct"); + equal(msg.result[0].error, "USER_CANCELED", "download.error is correct"); + equal(msg.result[0].bytesReceived, INT_PARTIAL_LEN, "download.bytesReceived is correct"); + equal(msg.result[0].totalBytes, INT_TOTAL_LEN, "download.totalBytes is correct"); + equal(msg.result[0].exists, false, "download.exists is correct"); + + msg = yield runInExtension("search", {error: "USER_CANCELED"}); + equal(msg.status, "success", "search() succeeded"); + let found = msg.result.filter(item => item.id == id); + equal(found.length, 1, "search() by error found the paused download"); + + msg = yield runInExtension("cancel", id); + equal(msg.status, "success", "cancel() succeeded"); + + msg = yield runInExtension("waitForEvents", [ + { + type: "onChanged", + data: { + id, + paused: { + previous: true, + current: false, + }, + canResume: { + previous: true, + current: false, + }, + }, + }, + ]); + equal(msg.status, "success", "got onChanged event for cancel"); + + msg = yield runInExtension("search", {id}); + equal(msg.status, "success", "search() succeeded"); + equal(msg.result.length, 1, "search() found 1 download"); + equal(msg.result[0].state, "interrupted", "download.state is correct"); + equal(msg.result[0].paused, false, "download.paused is correct"); + equal(msg.result[0].canResume, false, "download.canResume is correct"); + equal(msg.result[0].error, "USER_CANCELED", "download.error is correct"); + equal(msg.result[0].totalBytes, INT_TOTAL_LEN, "download.totalBytes is correct"); + equal(msg.result[0].exists, false, "download.exists is correct"); +}); + +add_task(function* test_pause_resume_cancel_badargs() { + let BAD_ID = 1000; + + let msg = yield runInExtension("pause", BAD_ID); + equal(msg.status, "error", "pause() failed with a bad download id"); + ok(/Invalid download id/.test(msg.errmsg), "error message is descriptive"); + + msg = yield runInExtension("resume", BAD_ID); + equal(msg.status, "error", "resume() failed with a bad download id"); + ok(/Invalid download id/.test(msg.errmsg), "error message is descriptive"); + + msg = yield runInExtension("cancel", BAD_ID); + equal(msg.status, "error", "cancel() failed with a bad download id"); + ok(/Invalid download id/.test(msg.errmsg), "error message is descriptive"); +}); + +add_task(function* test_file_removal() { + let msg = yield runInExtension("download", {url: TXT_URL}); + equal(msg.status, "success", "download() succeeded"); + const id = msg.result; + + msg = yield runInExtension("waitForEvents", [ + {type: "onCreated", data: {id, url: TXT_URL}}, + { + type: "onChanged", + data: { + id, + state: { + previous: "in_progress", + current: "complete", + }, + }, + }, + ]); + + equal(msg.status, "success", "got onCreated and onChanged events"); + + msg = yield runInExtension("removeFile", id); + equal(msg.status, "success", "removeFile() succeeded"); + + msg = yield runInExtension("removeFile", id); + equal(msg.status, "error", "removeFile() fails since the file was already removed."); + ok(/file doesn't exist/.test(msg.errmsg), "removeFile() failed on removed file."); + + msg = yield runInExtension("removeFile", 1000); + ok(/Invalid download id/.test(msg.errmsg), "removeFile() failed due to non-existent id"); +}); + +add_task(function* test_removal_of_incomplete_download() { + let url = getInterruptibleUrl(); + let msg = yield runInExtension("download", {url}); + equal(msg.status, "success", "download() succeeded"); + const id = msg.result; + + let progressPromise = waitForProgress(url, INT_PARTIAL_LEN); + + msg = yield runInExtension("waitForEvents", [ + {type: "onCreated", data: {id}}, + ]); + equal(msg.status, "success", "got created and changed events"); + + yield progressPromise; + do_print(`download reached ${INT_PARTIAL_LEN} bytes`); + + msg = yield runInExtension("pause", id); + equal(msg.status, "success", "pause() succeeded"); + + msg = yield runInExtension("waitForEvents", [ + { + type: "onChanged", + data: { + id, + state: { + previous: "in_progress", + current: "interrupted", + }, + paused: { + previous: false, + current: true, + }, + canResume: { + previous: false, + current: true, + }, + }, + }, { + type: "onChanged", + data: { + id, + error: { + previous: null, + current: "USER_CANCELED", + }, + }, + }]); + equal(msg.status, "success", "got onChanged event corresponding to pause"); + + msg = yield runInExtension("removeFile", id); + equal(msg.status, "error", "removeFile() on paused download failed"); + + ok(/Cannot remove incomplete download/.test(msg.errmsg), "removeFile() failed due to download being incomplete"); + + msg = yield runInExtension("resume", id); + equal(msg.status, "success", "resume() succeeded"); + + msg = yield runInExtension("waitForEvents", [ + { + type: "onChanged", + data: { + id, + state: { + previous: "interrupted", + current: "in_progress", + }, + paused: { + previous: true, + current: false, + }, + canResume: { + previous: true, + current: false, + }, + error: { + previous: "USER_CANCELED", + current: null, + }, + }, + }, + { + type: "onChanged", + data: { + id, + state: { + previous: "in_progress", + current: "complete", + }, + }, + }, + ]); + equal(msg.status, "success", "got onChanged events for resume and complete"); + + msg = yield runInExtension("removeFile", id); + equal(msg.status, "success", "removeFile() succeeded following completion of resumed download."); +}); + +// Test erase(). We don't do elaborate testing of the query handling +// since it uses the exact same engine as search() which is tested +// more thoroughly in test_chrome_ext_downloads_search.html +add_task(function* test_erase() { + yield clearDownloads(); + + yield runInExtension("clearEvents"); + + function* download() { + let msg = yield runInExtension("download", {url: TXT_URL}); + equal(msg.status, "success", "download succeeded"); + let id = msg.result; + + msg = yield runInExtension("waitForEvents", [{ + type: "onChanged", data: {id, state: {current: "complete"}}, + }], {exact: false}); + equal(msg.status, "success", "download finished"); + + return id; + } + + let ids = {}; + ids.dl1 = yield download(); + ids.dl2 = yield download(); + ids.dl3 = yield download(); + + let msg = yield runInExtension("search", {}); + equal(msg.status, "success", "search succeded"); + equal(msg.result.length, 3, "search found 3 downloads"); + + msg = yield runInExtension("clearEvents"); + + msg = yield runInExtension("erase", {id: ids.dl1}); + equal(msg.status, "success", "erase by id succeeded"); + + msg = yield runInExtension("waitForEvents", [ + {type: "onErased", data: ids.dl1}, + ]); + equal(msg.status, "success", "received onErased event"); + + msg = yield runInExtension("search", {}); + equal(msg.status, "success", "search succeded"); + equal(msg.result.length, 2, "search found 2 downloads"); + + msg = yield runInExtension("erase", {}); + equal(msg.status, "success", "erase everything succeeded"); + + msg = yield runInExtension("waitForEvents", [ + {type: "onErased", data: ids.dl2}, + {type: "onErased", data: ids.dl3}, + ], {inorder: false}); + equal(msg.status, "success", "received 2 onErased events"); + + msg = yield runInExtension("search", {}); + equal(msg.status, "success", "search succeded"); + equal(msg.result.length, 0, "search found 0 downloads"); +}); + +function loadImage(img, data) { + return new Promise((resolve) => { + img.src = data; + img.onload = resolve; + }); +} + +add_task(function* test_getFileIcon() { + let webNav = Services.appShell.createWindowlessBrowser(false); + let docShell = webNav.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell); + + let system = Services.scriptSecurityManager.getSystemPrincipal(); + docShell.createAboutBlankContentViewer(system); + + let img = webNav.document.createElement("img"); + + let msg = yield runInExtension("download", {url: TXT_URL}); + equal(msg.status, "success", "download() succeeded"); + const id = msg.result; + + msg = yield runInExtension("getFileIcon", id); + equal(msg.status, "success", "getFileIcon() succeeded"); + yield loadImage(img, msg.result); + equal(img.height, 32, "returns an icon with the right height"); + equal(img.width, 32, "returns an icon with the right width"); + + msg = yield runInExtension("waitForEvents", [ + {type: "onCreated", data: {id, url: TXT_URL}}, + {type: "onChanged"}, + ]); + equal(msg.status, "success", "got events"); + + msg = yield runInExtension("getFileIcon", id); + equal(msg.status, "success", "getFileIcon() succeeded"); + yield loadImage(img, msg.result); + equal(img.height, 32, "returns an icon with the right height after download"); + equal(img.width, 32, "returns an icon with the right width after download"); + + msg = yield runInExtension("getFileIcon", id + 100); + equal(msg.status, "error", "getFileIcon() failed"); + ok(msg.errmsg.includes("Invalid download id"), "download id is invalid"); + + msg = yield runInExtension("getFileIcon", id, {size: 127}); + equal(msg.status, "success", "getFileIcon() succeeded"); + yield loadImage(img, msg.result); + equal(img.height, 127, "returns an icon with the right custom height"); + equal(img.width, 127, "returns an icon with the right custom width"); + + msg = yield runInExtension("getFileIcon", id, {size: 1}); + equal(msg.status, "success", "getFileIcon() succeeded"); + yield loadImage(img, msg.result); + equal(img.height, 1, "returns an icon with the right custom height"); + equal(img.width, 1, "returns an icon with the right custom width"); + + msg = yield runInExtension("getFileIcon", id, {size: "foo"}); + equal(msg.status, "error", "getFileIcon() fails"); + ok(msg.errmsg.includes("Error processing size"), "size is not a number"); + + msg = yield runInExtension("getFileIcon", id, {size: 0}); + equal(msg.status, "error", "getFileIcon() fails"); + ok(msg.errmsg.includes("Error processing size"), "size is too small"); + + msg = yield runInExtension("getFileIcon", id, {size: 128}); + equal(msg.status, "error", "getFileIcon() fails"); + ok(msg.errmsg.includes("Error processing size"), "size is too big"); + + webNav.close(); +}); + +add_task(function* cleanup() { + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_search.js b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_search.js new file mode 100644 index 000000000..4caa82456 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_downloads_search.js @@ -0,0 +1,402 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://gre/modules/Downloads.jsm"); + +const server = createHttpServer(); +server.registerDirectory("/data/", do_get_file("data")); + +const BASE = `http://localhost:${server.identity.primaryPort}/data`; +const TXT_FILE = "file_download.txt"; +const TXT_URL = BASE + "/" + TXT_FILE; +const TXT_LEN = 46; +const HTML_FILE = "file_download.html"; +const HTML_URL = BASE + "/" + HTML_FILE; +const HTML_LEN = 117; +const BIG_LEN = 1000; // something bigger both TXT_LEN and HTML_LEN + +function backgroundScript() { + let complete = new Map(); + + function waitForComplete(id) { + if (complete.has(id)) { + return complete.get(id).promise; + } + + let promise = new Promise(resolve => { + complete.set(id, {resolve}); + }); + complete.get(id).promise = promise; + return promise; + } + + browser.downloads.onChanged.addListener(change => { + if (change.state && change.state.current == "complete") { + // Make sure we have a promise. + waitForComplete(change.id); + complete.get(change.id).resolve(); + } + }); + + browser.test.onMessage.addListener(async (msg, ...args) => { + if (msg == "download.request") { + try { + let id = await browser.downloads.download(args[0]); + browser.test.sendMessage("download.done", {status: "success", id}); + } catch (error) { + browser.test.sendMessage("download.done", {status: "error", errmsg: error.message}); + } + } else if (msg == "search.request") { + try { + let downloads = await browser.downloads.search(args[0]); + browser.test.sendMessage("search.done", {status: "success", downloads}); + } catch (error) { + browser.test.sendMessage("search.done", {status: "error", errmsg: error.message}); + } + } else if (msg == "waitForComplete.request") { + await waitForComplete(args[0]); + browser.test.sendMessage("waitForComplete.done"); + } + }); + + browser.test.sendMessage("ready"); +} + +async function clearDownloads(callback) { + let list = await Downloads.getList(Downloads.ALL); + let downloads = await list.getAll(); + + await Promise.all(downloads.map(download => list.remove(download))); + + return downloads; +} + +add_task(function* test_search() { + const nsIFile = Ci.nsIFile; + let downloadDir = FileUtils.getDir("TmpD", ["downloads"]); + downloadDir.createUnique(nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); + do_print(`downloadDir ${downloadDir.path}`); + + function downloadPath(filename) { + let path = downloadDir.clone(); + path.append(filename); + return path.path; + } + + Services.prefs.setIntPref("browser.download.folderList", 2); + Services.prefs.setComplexValue("browser.download.dir", nsIFile, downloadDir); + + do_register_cleanup(async () => { + Services.prefs.clearUserPref("browser.download.folderList"); + Services.prefs.clearUserPref("browser.download.dir"); + await cleanupDir(downloadDir); + await clearDownloads(); + }); + + yield clearDownloads().then(downloads => { + do_print(`removed ${downloads.length} pre-existing downloads from history`); + }); + + let extension = ExtensionTestUtils.loadExtension({ + background: backgroundScript, + manifest: { + permissions: ["downloads"], + }, + }); + + async function download(options) { + extension.sendMessage("download.request", options); + let result = await extension.awaitMessage("download.done"); + + if (result.status == "success") { + do_print(`wait for onChanged event to indicate ${result.id} is complete`); + extension.sendMessage("waitForComplete.request", result.id); + + await extension.awaitMessage("waitForComplete.done"); + } + + return result; + } + + function search(query) { + extension.sendMessage("search.request", query); + return extension.awaitMessage("search.done"); + } + + yield extension.startup(); + yield extension.awaitMessage("ready"); + + // Do some downloads... + const time1 = new Date(); + + let downloadIds = {}; + let msg = yield download({url: TXT_URL}); + equal(msg.status, "success", "download() succeeded"); + downloadIds.txt1 = msg.id; + + const TXT_FILE2 = "NewFile.txt"; + msg = yield download({url: TXT_URL, filename: TXT_FILE2}); + equal(msg.status, "success", "download() succeeded"); + downloadIds.txt2 = msg.id; + + const time2 = new Date(); + + msg = yield download({url: HTML_URL}); + equal(msg.status, "success", "download() succeeded"); + downloadIds.html1 = msg.id; + + const HTML_FILE2 = "renamed.html"; + msg = yield download({url: HTML_URL, filename: HTML_FILE2}); + equal(msg.status, "success", "download() succeeded"); + downloadIds.html2 = msg.id; + + const time3 = new Date(); + + // Search for each individual download and check + // the corresponding DownloadItem. + function* checkDownloadItem(id, expect) { + let item = yield search({id}); + equal(item.status, "success", "search() succeeded"); + equal(item.downloads.length, 1, "search() found exactly 1 download"); + + Object.keys(expect).forEach(function(field) { + equal(item.downloads[0][field], expect[field], `DownloadItem.${field} is correct"`); + }); + } + yield checkDownloadItem(downloadIds.txt1, { + url: TXT_URL, + filename: downloadPath(TXT_FILE), + mime: "text/plain", + state: "complete", + bytesReceived: TXT_LEN, + totalBytes: TXT_LEN, + fileSize: TXT_LEN, + exists: true, + }); + + yield checkDownloadItem(downloadIds.txt2, { + url: TXT_URL, + filename: downloadPath(TXT_FILE2), + mime: "text/plain", + state: "complete", + bytesReceived: TXT_LEN, + totalBytes: TXT_LEN, + fileSize: TXT_LEN, + exists: true, + }); + + yield checkDownloadItem(downloadIds.html1, { + url: HTML_URL, + filename: downloadPath(HTML_FILE), + mime: "text/html", + state: "complete", + bytesReceived: HTML_LEN, + totalBytes: HTML_LEN, + fileSize: HTML_LEN, + exists: true, + }); + + yield checkDownloadItem(downloadIds.html2, { + url: HTML_URL, + filename: downloadPath(HTML_FILE2), + mime: "text/html", + state: "complete", + bytesReceived: HTML_LEN, + totalBytes: HTML_LEN, + fileSize: HTML_LEN, + exists: true, + }); + + function* checkSearch(query, expected, description, exact) { + let item = yield search(query); + equal(item.status, "success", "search() succeeded"); + equal(item.downloads.length, expected.length, `search() for ${description} found exactly ${expected.length} downloads`); + + let receivedIds = item.downloads.map(i => i.id); + if (exact) { + receivedIds.forEach((id, idx) => { + equal(id, downloadIds[expected[idx]], `search() for ${description} returned ${expected[idx]} in position ${idx}`); + }); + } else { + Object.keys(downloadIds).forEach(key => { + const id = downloadIds[key]; + const thisExpected = expected.includes(key); + equal(receivedIds.includes(id), thisExpected, + `search() for ${description} ${thisExpected ? "includes" : "does not include"} ${key}`); + }); + } + } + + // Check that search with an invalid id returns nothing. + // NB: for now ids are not persistent and we start numbering them at 1 + // so a sufficiently large number will be unused. + const INVALID_ID = 1000; + yield checkSearch({id: INVALID_ID}, [], "invalid id"); + + // Check that search on url works. + yield checkSearch({url: TXT_URL}, ["txt1", "txt2"], "url"); + + // Check that regexp on url works. + const HTML_REGEX = "[downlad]{8}\.html+$"; + yield checkSearch({urlRegex: HTML_REGEX}, ["html1", "html2"], "url regexp"); + + // Check that compatible url+regexp works + yield checkSearch({url: HTML_URL, urlRegex: HTML_REGEX}, ["html1", "html2"], "compatible url+urlRegex"); + + // Check that incompatible url+regexp works + yield checkSearch({url: TXT_URL, urlRegex: HTML_REGEX}, [], "incompatible url+urlRegex"); + + // Check that search on filename works. + yield checkSearch({filename: downloadPath(TXT_FILE)}, ["txt1"], "filename"); + + // Check that regexp on filename works. + yield checkSearch({filenameRegex: HTML_REGEX}, ["html1"], "filename regex"); + + // Check that compatible filename+regexp works + yield checkSearch({filename: downloadPath(HTML_FILE), filenameRegex: HTML_REGEX}, ["html1"], "compatible filename+filename regex"); + + // Check that incompatible filename+regexp works + yield checkSearch({filename: downloadPath(TXT_FILE), filenameRegex: HTML_REGEX}, [], "incompatible filename+filename regex"); + + // Check that simple positive search terms work. + yield checkSearch({query: ["file_download"]}, ["txt1", "txt2", "html1", "html2"], + "term file_download"); + yield checkSearch({query: ["NewFile"]}, ["txt2"], "term NewFile"); + + // Check that positive search terms work case-insensitive. + yield checkSearch({query: ["nEwfILe"]}, ["txt2"], "term nEwfiLe"); + + // Check that negative search terms work. + yield checkSearch({query: ["-txt"]}, ["html1", "html2"], "term -txt"); + + // Check that positive and negative search terms together work. + yield checkSearch({query: ["html", "-renamed"]}, ["html1"], "postive and negative terms"); + + function* checkSearchWithDate(query, expected, description) { + const fields = Object.keys(query); + if (fields.length != 1 || !(query[fields[0]] instanceof Date)) { + throw new Error("checkSearchWithDate expects exactly one Date field"); + } + const field = fields[0]; + const date = query[field]; + + let newquery = {}; + + // Check as a Date + newquery[field] = date; + yield checkSearch(newquery, expected, `${description} as Date`); + + // Check as numeric milliseconds + newquery[field] = date.valueOf(); + yield checkSearch(newquery, expected, `${description} as numeric ms`); + + // Check as stringified milliseconds + newquery[field] = date.valueOf().toString(); + yield checkSearch(newquery, expected, `${description} as string ms`); + + // Check as ISO string + newquery[field] = date.toISOString(); + yield checkSearch(newquery, expected, `${description} as iso string`); + } + + // Check startedBefore + yield checkSearchWithDate({startedBefore: time1}, [], "before time1"); + yield checkSearchWithDate({startedBefore: time2}, ["txt1", "txt2"], "before time2"); + yield checkSearchWithDate({startedBefore: time3}, ["txt1", "txt2", "html1", "html2"], "before time3"); + + // Check startedAfter + yield checkSearchWithDate({startedAfter: time1}, ["txt1", "txt2", "html1", "html2"], "after time1"); + yield checkSearchWithDate({startedAfter: time2}, ["html1", "html2"], "after time2"); + yield checkSearchWithDate({startedAfter: time3}, [], "after time3"); + + // Check simple search on totalBytes + yield checkSearch({totalBytes: TXT_LEN}, ["txt1", "txt2"], "totalBytes"); + yield checkSearch({totalBytes: HTML_LEN}, ["html1", "html2"], "totalBytes"); + + // Check simple test on totalBytes{Greater,Less} + // (NB: TXT_LEN < HTML_LEN < BIG_LEN) + yield checkSearch({totalBytesGreater: 0}, ["txt1", "txt2", "html1", "html2"], "totalBytesGreater than 0"); + yield checkSearch({totalBytesGreater: TXT_LEN}, ["html1", "html2"], `totalBytesGreater than ${TXT_LEN}`); + yield checkSearch({totalBytesGreater: HTML_LEN}, [], `totalBytesGreater than ${HTML_LEN}`); + yield checkSearch({totalBytesLess: TXT_LEN}, [], `totalBytesLess than ${TXT_LEN}`); + yield checkSearch({totalBytesLess: HTML_LEN}, ["txt1", "txt2"], `totalBytesLess than ${HTML_LEN}`); + yield checkSearch({totalBytesLess: BIG_LEN}, ["txt1", "txt2", "html1", "html2"], `totalBytesLess than ${BIG_LEN}`); + + // Check good combinations of totalBytes*. + yield checkSearch({totalBytes: HTML_LEN, totalBytesGreater: TXT_LEN}, ["html1", "html2"], "totalBytes and totalBytesGreater"); + yield checkSearch({totalBytes: TXT_LEN, totalBytesLess: HTML_LEN}, ["txt1", "txt2"], "totalBytes and totalBytesGreater"); + yield checkSearch({totalBytes: HTML_LEN, totalBytesLess: BIG_LEN, totalBytesGreater: 0}, ["html1", "html2"], "totalBytes and totalBytesLess and totalBytesGreater"); + + // Check bad combination of totalBytes*. + yield checkSearch({totalBytesLess: TXT_LEN, totalBytesGreater: HTML_LEN}, [], "bad totalBytesLess, totalBytesGreater combination"); + yield checkSearch({totalBytes: TXT_LEN, totalBytesGreater: HTML_LEN}, [], "bad totalBytes, totalBytesGreater combination"); + yield checkSearch({totalBytes: HTML_LEN, totalBytesLess: TXT_LEN}, [], "bad totalBytes, totalBytesLess combination"); + + // Check mime. + yield checkSearch({mime: "text/plain"}, ["txt1", "txt2"], "mime text/plain"); + yield checkSearch({mime: "text/html"}, ["html1", "html2"], "mime text/htmlplain"); + yield checkSearch({mime: "video/webm"}, [], "mime video/webm"); + + // Check fileSize. + yield checkSearch({fileSize: TXT_LEN}, ["txt1", "txt2"], "fileSize"); + yield checkSearch({fileSize: HTML_LEN}, ["html1", "html2"], "fileSize"); + + // Fields like bytesReceived, paused, state, exists are meaningful + // for downloads that are in progress but have not yet completed. + // todo: add tests for these when we have better support for in-progress + // downloads (e.g., after pause(), resume() and cancel() are implemented) + + // Check multiple query properties. + // We could make this testing arbitrarily complicated... + // We already tested combining fields with obvious interactions above + // (e.g., filename and filenameRegex or startTime and startedBefore/After) + // so now just throw as many fields as we can at a single search and + // make sure a simple case still works. + yield checkSearch({ + url: TXT_URL, + urlRegex: "download", + filename: downloadPath(TXT_FILE), + filenameRegex: "download", + query: ["download"], + startedAfter: time1.valueOf().toString(), + startedBefore: time2.valueOf().toString(), + totalBytes: TXT_LEN, + totalBytesGreater: 0, + totalBytesLess: BIG_LEN, + mime: "text/plain", + fileSize: TXT_LEN, + }, ["txt1"], "many properties"); + + // Check simple orderBy (forward and backward). + yield checkSearch({orderBy: ["startTime"]}, ["txt1", "txt2", "html1", "html2"], "orderBy startTime", true); + yield checkSearch({orderBy: ["-startTime"]}, ["html2", "html1", "txt2", "txt1"], "orderBy -startTime", true); + + // Check orderBy with multiple fields. + // NB: TXT_URL and HTML_URL differ only in extension and .html precedes .txt + yield checkSearch({orderBy: ["url", "-startTime"]}, ["html2", "html1", "txt2", "txt1"], "orderBy with multiple fields", true); + + // Check orderBy with limit. + yield checkSearch({orderBy: ["url"], limit: 1}, ["html1"], "orderBy with limit", true); + + // Check bad arguments. + function* checkBadSearch(query, pattern, description) { + let item = yield search(query); + equal(item.status, "error", "search() failed"); + ok(pattern.test(item.errmsg), `error message for ${description} was correct (${item.errmsg}).`); + } + + yield checkBadSearch("myquery", /Incorrect argument type/, "query is not an object"); + yield checkBadSearch({bogus: "boo"}, /Unexpected property/, "query contains an unknown field"); + yield checkBadSearch({query: "query string"}, /Expected array/, "query.query is a string"); + yield checkBadSearch({startedBefore: "i am not a time"}, /Type error/, "query.startedBefore is not a valid time"); + yield checkBadSearch({startedAfter: "i am not a time"}, /Type error/, "query.startedAfter is not a valid time"); + yield checkBadSearch({endedBefore: "i am not a time"}, /Type error/, "query.endedBefore is not a valid time"); + yield checkBadSearch({endedAfter: "i am not a time"}, /Type error/, "query.endedAfter is not a valid time"); + yield checkBadSearch({urlRegex: "["}, /Invalid urlRegex/, "query.urlRegexp is not a valid regular expression"); + yield checkBadSearch({filenameRegex: "["}, /Invalid filenameRegex/, "query.filenameRegexp is not a valid regular expression"); + yield checkBadSearch({orderBy: "startTime"}, /Expected array/, "query.orderBy is not an array"); + yield checkBadSearch({orderBy: ["bogus"]}, /Invalid orderBy field/, "query.orderBy references a non-existent field"); + + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_experiments.js b/toolkit/components/webextensions/test/xpcshell/test_ext_experiments.js new file mode 100644 index 000000000..bc6bfcd68 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_experiments.js @@ -0,0 +1,175 @@ +"use strict"; + +/* globals browser */ + +XPCOMUtils.defineLazyModuleGetter(this, "AddonManager", + "resource://gre/modules/AddonManager.jsm"); + +function promiseAddonStartup() { + const {Management} = Cu.import("resource://gre/modules/Extension.jsm"); + + return new Promise(resolve => { + let listener = (evt, extension) => { + Management.off("startup", listener); + resolve(extension); + }; + + Management.on("startup", listener); + }); +} + +add_task(function* setup() { + yield ExtensionTestUtils.startAddonManager(); +}); + +add_task(function* test_experiments_api() { + let apiAddonFile = Extension.generateZipFile({ + "install.rdf": ` + + + + + + + + + `, + + "api.js": String.raw` + Components.utils.import("resource://gre/modules/Services.jsm"); + + Services.obs.notifyObservers(null, "webext-api-loaded", ""); + + class API extends ExtensionAPI { + getAPI(context) { + return { + meh: { + hello(text) { + Services.obs.notifyObservers(null, "webext-api-hello", text); + } + } + } + } + } + `, + + "schema.json": [ + { + "namespace": "meh", + "description": "All full of meh.", + "permissions": ["experiments.meh"], + "functions": [ + { + "name": "hello", + "type": "function", + "description": "Hates you. This is all.", + "parameters": [ + {"type": "string", "name": "text"}, + ], + }, + ], + }, + ], + }); + + let addonFile = Extension.generateXPI({ + manifest: { + applications: {gecko: {id: "meh@web.extension"}}, + permissions: ["experiments.meh"], + }, + + background() { + // The test code below checks that hello() is called at the right + // time with the string "Here I am". Verify that the api schema is + // being correctly interpreted by calling hello() with bad arguments + // and only calling hello() with the magic string if the call with + // bad arguments throws. + try { + browser.meh.hello("I should not see this", "since two arguments are bad"); + } catch (err) { + browser.meh.hello("Here I am"); + } + }, + }); + + let boringAddonFile = Extension.generateXPI({ + manifest: { + applications: {gecko: {id: "boring@web.extension"}}, + }, + background() { + if (browser.meh) { + browser.meh.hello("Here I should not be"); + } + }, + }); + + do_register_cleanup(() => { + for (let file of [apiAddonFile, addonFile, boringAddonFile]) { + Services.obs.notifyObservers(file, "flush-cache-entry", null); + file.remove(false); + } + }); + + + let resolveHello; + let observer = (subject, topic, data) => { + if (topic == "webext-api-loaded") { + ok(!!resolveHello, "Should not see API loaded until dependent extension loads"); + } else if (topic == "webext-api-hello") { + resolveHello(data); + } + }; + + Services.obs.addObserver(observer, "webext-api-loaded", false); + Services.obs.addObserver(observer, "webext-api-hello", false); + do_register_cleanup(() => { + Services.obs.removeObserver(observer, "webext-api-loaded"); + Services.obs.removeObserver(observer, "webext-api-hello"); + }); + + + // Install API add-on. + let apiAddon = yield AddonManager.installTemporaryAddon(apiAddonFile); + + let {APIs} = Cu.import("resource://gre/modules/ExtensionManagement.jsm", {}); + ok(APIs.apis.has("meh"), "Should have meh API."); + + + // Install boring WebExtension add-on. + let boringAddon = yield AddonManager.installTemporaryAddon(boringAddonFile); + yield promiseAddonStartup(); + + + // Install interesting WebExtension add-on. + let promise = new Promise(resolve => { + resolveHello = resolve; + }); + + let addon = yield AddonManager.installTemporaryAddon(addonFile); + yield promiseAddonStartup(); + + let hello = yield promise; + equal(hello, "Here I am", "Should get hello from add-on"); + + // Cleanup. + apiAddon.uninstall(); + + boringAddon.userDisabled = true; + yield new Promise(do_execute_soon); + + equal(addon.appDisabled, true, "Add-on should be app-disabled after its dependency is removed."); + + addon.uninstall(); + boringAddon.uninstall(); +}); + diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_extension.js b/toolkit/components/webextensions/test/xpcshell/test_ext_extension.js new file mode 100644 index 000000000..f18845f6a --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_extension.js @@ -0,0 +1,55 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_is_allowed_incognito_access() { + async function background() { + let allowed = await browser.extension.isAllowedIncognitoAccess(); + + browser.test.assertEq(true, allowed, "isAllowedIncognitoAccess is true"); + browser.test.notifyPass("isAllowedIncognitoAccess"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: {}, + }); + + yield extension.startup(); + yield extension.awaitFinish("isAllowedIncognitoAccess"); + yield extension.unload(); +}); + +add_task(function* test_in_incognito_context_false() { + function background() { + browser.test.assertEq(false, browser.extension.inIncognitoContext, "inIncognitoContext returned false"); + browser.test.notifyPass("inIncognitoContext"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: {}, + }); + + yield extension.startup(); + yield extension.awaitFinish("inIncognitoContext"); + yield extension.unload(); +}); + +add_task(function* test_is_allowed_file_scheme_access() { + async function background() { + let allowed = await browser.extension.isAllowedFileSchemeAccess(); + + browser.test.assertEq(false, allowed, "isAllowedFileSchemeAccess is false"); + browser.test.notifyPass("isAllowedFileSchemeAccess"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: {}, + }); + + yield extension.startup(); + yield extension.awaitFinish("isAllowedFileSchemeAccess"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_idle.js b/toolkit/components/webextensions/test/xpcshell/test_ext_idle.js new file mode 100644 index 000000000..89bcac217 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_idle.js @@ -0,0 +1,202 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://testing-common/MockRegistrar.jsm"); + +let idleService = { + _observers: new Set(), + _activity: { + addCalls: [], + removeCalls: [], + observerFires: [], + }, + _reset: function() { + this._observers.clear(); + this._activity.addCalls = []; + this._activity.removeCalls = []; + this._activity.observerFires = []; + }, + _fireObservers: function(state) { + for (let observer of this._observers.values()) { + observer.observe(observer, state, null); + this._activity.observerFires.push(state); + } + }, + QueryInterface: XPCOMUtils.generateQI([Ci.nsIIdleService]), + idleTime: 19999, + addIdleObserver: function(observer, time) { + this._observers.add(observer); + this._activity.addCalls.push(time); + }, + removeIdleObserver: function(observer, time) { + this._observers.delete(observer); + this._activity.removeCalls.push(time); + }, +}; + +function checkActivity(expectedActivity) { + let {expectedAdd, expectedRemove, expectedFires} = expectedActivity; + let {addCalls, removeCalls, observerFires} = idleService._activity; + equal(expectedAdd.length, addCalls.length, "idleService.addIdleObserver was called the expected number of times"); + equal(expectedRemove.length, removeCalls.length, "idleService.removeIdleObserver was called the expected number of times"); + equal(expectedFires.length, observerFires.length, "idle observer was fired the expected number of times"); + deepEqual(addCalls, expectedAdd, "expected interval passed to idleService.addIdleObserver"); + deepEqual(removeCalls, expectedRemove, "expected interval passed to idleService.removeIdleObserver"); + deepEqual(observerFires, expectedFires, "expected topic passed to idle observer"); +} + +add_task(function* setup() { + let fakeIdleService = MockRegistrar.register("@mozilla.org/widget/idleservice;1", idleService); + do_register_cleanup(() => { + MockRegistrar.unregister(fakeIdleService); + }); +}); + +add_task(function* testQueryStateActive() { + function background() { + browser.idle.queryState(20).then(status => { + browser.test.assertEq("active", status, "Idle status is active"); + browser.test.notifyPass("idle"); + }, + err => { + browser.test.fail(`Error: ${err} :: ${err.stack}`); + browser.test.notifyFail("idle"); + }); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + permissions: ["idle"], + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("idle"); + yield extension.unload(); +}); + +add_task(function* testQueryStateIdle() { + function background() { + browser.idle.queryState(15).then(status => { + browser.test.assertEq("idle", status, "Idle status is idle"); + browser.test.notifyPass("idle"); + }, + err => { + browser.test.fail(`Error: ${err} :: ${err.stack}`); + browser.test.notifyFail("idle"); + }); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + permissions: ["idle"], + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("idle"); + yield extension.unload(); +}); + +add_task(function* testOnlySetDetectionInterval() { + function background() { + browser.idle.setDetectionInterval(99); + browser.test.sendMessage("detectionIntervalSet"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + permissions: ["idle"], + }, + }); + + idleService._reset(); + yield extension.startup(); + yield extension.awaitMessage("detectionIntervalSet"); + idleService._fireObservers("idle"); + checkActivity({expectedAdd: [], expectedRemove: [], expectedFires: []}); + yield extension.unload(); +}); + +add_task(function* testSetDetectionIntervalBeforeAddingListener() { + function background() { + browser.idle.setDetectionInterval(99); + browser.idle.onStateChanged.addListener(newState => { + browser.test.assertEq("idle", newState, "listener fired with the expected state"); + browser.test.sendMessage("listenerFired"); + }); + browser.test.sendMessage("listenerAdded"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + permissions: ["idle"], + }, + }); + + idleService._reset(); + yield extension.startup(); + yield extension.awaitMessage("listenerAdded"); + idleService._fireObservers("idle"); + yield extension.awaitMessage("listenerFired"); + checkActivity({expectedAdd: [99], expectedRemove: [], expectedFires: ["idle"]}); + yield extension.unload(); +}); + +add_task(function* testSetDetectionIntervalAfterAddingListener() { + function background() { + browser.idle.onStateChanged.addListener(newState => { + browser.test.assertEq("idle", newState, "listener fired with the expected state"); + browser.test.sendMessage("listenerFired"); + }); + browser.idle.setDetectionInterval(99); + browser.test.sendMessage("detectionIntervalSet"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + permissions: ["idle"], + }, + }); + + idleService._reset(); + yield extension.startup(); + yield extension.awaitMessage("detectionIntervalSet"); + idleService._fireObservers("idle"); + yield extension.awaitMessage("listenerFired"); + checkActivity({expectedAdd: [60, 99], expectedRemove: [60], expectedFires: ["idle"]}); + yield extension.unload(); +}); + +add_task(function* testOnlyAddingListener() { + function background() { + browser.idle.onStateChanged.addListener(newState => { + browser.test.assertEq("active", newState, "listener fired with the expected state"); + browser.test.sendMessage("listenerFired"); + }); + browser.test.sendMessage("listenerAdded"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + permissions: ["idle"], + }, + }); + + idleService._reset(); + yield extension.startup(); + yield extension.awaitMessage("listenerAdded"); + idleService._fireObservers("active"); + yield extension.awaitMessage("listenerFired"); + // check that "idle-daily" topic does not cause a listener to fire + idleService._fireObservers("idle-daily"); + checkActivity({expectedAdd: [60], expectedRemove: [], expectedFires: ["active", "idle-daily"]}); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_json_parser.js b/toolkit/components/webextensions/test/xpcshell/test_ext_json_parser.js new file mode 100644 index 000000000..652f41315 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_json_parser.js @@ -0,0 +1,37 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_json_parser() { + const ID = "json@test.web.extension"; + + let xpi = Extension.generateXPI({ + files: { + "manifest.json": String.raw`{ + // This is a manifest. + "applications": {"gecko": {"id": "${ID}"}}, + "name": "This \" is // not a comment", + "version": "0.1\\" // , "description": "This is not a description" + }`, + }, + }); + + let expectedManifest = { + "applications": {"gecko": {"id": ID}}, + "name": "This \" is // not a comment", + "version": "0.1\\", + }; + + let fileURI = Services.io.newFileURI(xpi); + let uri = NetUtil.newURI(`jar:${fileURI.spec}!/`); + + let extension = new ExtensionData(uri); + + yield extension.readManifest(); + + Assert.deepEqual(extension.rawManifest, expectedManifest, + "Manifest with correctly-filtered comments"); + + Services.obs.notifyObservers(xpi, "flush-cache-entry", null); + xpi.remove(false); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_context.js b/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_context.js new file mode 100644 index 000000000..770851472 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_context.js @@ -0,0 +1,168 @@ +"use strict"; + +/* globals browser */ + +Cu.import("resource://gre/modules/Extension.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); + +const {LegacyExtensionContext} = Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm"); + +/** + * This test case ensures that LegacyExtensionContext instances: + * - expose the expected API object and can join the messaging + * of a webextension given its addon id + * - the exposed API object can receive a port related to a `runtime.connect` + * Port created in the webextension's background page + * - the received Port instance can exchange messages with the background page + * - the received Port receive a disconnect event when the webextension is + * shutting down + */ +add_task(function* test_legacy_extension_context() { + function background() { + let bgURL = window.location.href; + + let extensionInfo = { + bgURL, + // Extract the assigned uuid from the background page url. + uuid: window.location.hostname, + }; + + browser.test.sendMessage("webextension-ready", extensionInfo); + + let port; + + browser.test.onMessage.addListener(async msg => { + if (msg == "do-send-message") { + let reply = await browser.runtime.sendMessage("webextension -> legacy_extension message"); + + browser.test.assertEq("legacy_extension -> webextension reply", reply, + "Got the expected message from the LegacyExtensionContext"); + browser.test.sendMessage("got-reply-message"); + } else if (msg == "do-connect") { + port = browser.runtime.connect(); + + port.onMessage.addListener(portMsg => { + browser.test.assertEq("legacy_extension -> webextension port message", portMsg, + "Got the expected message from the LegacyExtensionContext"); + port.postMessage("webextension -> legacy_extension port message"); + }); + } else if (msg == "do-disconnect") { + port.disconnect(); + } + }); + } + + let extensionData = { + background, + }; + + let extension = Extension.generate(extensionData); + + let waitForExtensionInfo = new Promise((resolve, reject) => { + extension.on("test-message", function testMessageListener(kind, msg, ...args) { + if (msg != "webextension-ready") { + reject(new Error(`Got an unexpected test-message: ${msg}`)); + } else { + extension.off("test-message", testMessageListener); + resolve(args[0]); + } + }); + }); + + // Connect to the target extension as an external context + // using the given custom sender info. + let legacyContext; + + extension.on("startup", function onStartup() { + extension.off("startup", onStartup); + legacyContext = new LegacyExtensionContext(extension); + extension.callOnClose({ + close: () => legacyContext.unload(), + }); + }); + + yield extension.startup(); + + let extensionInfo = yield waitForExtensionInfo; + + equal(legacyContext.envType, "legacy_extension", + "LegacyExtensionContext instance has the expected type"); + + ok(legacyContext.api, "Got the expected API object"); + ok(legacyContext.api.browser, "Got the expected browser property"); + + let waitMessage = new Promise(resolve => { + const {browser} = legacyContext.api; + browser.runtime.onMessage.addListener((singleMsg, msgSender) => { + resolve({singleMsg, msgSender}); + + // Send a reply to the sender. + return Promise.resolve("legacy_extension -> webextension reply"); + }); + }); + + extension.testMessage("do-send-message"); + + let {singleMsg, msgSender} = yield waitMessage; + equal(singleMsg, "webextension -> legacy_extension message", + "Got the expected message"); + ok(msgSender, "Got a message sender object"); + + equal(msgSender.id, extension.id, "The sender has the expected id property"); + equal(msgSender.url, extensionInfo.bgURL, "The sender has the expected url property"); + + // Wait confirmation that the reply has been received. + yield new Promise((resolve, reject) => { + extension.on("test-message", function testMessageListener(kind, msg, ...args) { + if (msg != "got-reply-message") { + reject(new Error(`Got an unexpected test-message: ${msg}`)); + } else { + extension.off("test-message", testMessageListener); + resolve(); + } + }); + }); + + let waitConnectPort = new Promise(resolve => { + let {browser} = legacyContext.api; + browser.runtime.onConnect.addListener(port => { + resolve(port); + }); + }); + + extension.testMessage("do-connect"); + + let port = yield waitConnectPort; + + ok(port, "Got the Port API object"); + ok(port.sender, "The port has a sender property"); + equal(port.sender.id, extension.id, + "The port sender has the expected id property"); + equal(port.sender.url, extensionInfo.bgURL, + "The port sender has the expected url property"); + + let waitPortMessage = new Promise(resolve => { + port.onMessage.addListener((msg) => { + resolve(msg); + }); + }); + + port.postMessage("legacy_extension -> webextension port message"); + + let msg = yield waitPortMessage; + + equal(msg, "webextension -> legacy_extension port message", + "LegacyExtensionContext received the expected message from the webextension"); + + let waitForDisconnect = new Promise(resolve => { + port.onDisconnect.addListener(resolve); + }); + + extension.testMessage("do-disconnect"); + + yield waitForDisconnect; + + do_print("Got the disconnect event on unload"); + + yield extension.shutdown(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_embedding.js b/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_embedding.js new file mode 100644 index 000000000..ea5d78524 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_legacy_extension_embedding.js @@ -0,0 +1,188 @@ +"use strict"; + +/* globals browser */ + +Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm"); + +// Import EmbeddedExtensionManager to be able to check that the +// tacked instances are cleared after the embedded extension shutdown. +const { + EmbeddedExtensionManager, +} = Cu.import("resource://gre/modules/LegacyExtensionsUtils.jsm", {}); + +/** + * This test case ensures that the LegacyExtensionsUtils.EmbeddedExtension: + * - load the embedded webextension resources from a "/webextension/" dir + * inside the XPI. + * - EmbeddedExtension.prototype.api returns an API object which exposes + * a working `runtime.onConnect` event object (e.g. the API can receive a port + * when the embedded webextension is started and it can exchange messages + * with the background page). + * - EmbeddedExtension.prototype.startup/shutdown methods manage the embedded + * webextension lifecycle as expected. + */ +add_task(function* test_embedded_webextension_utils() { + function backgroundScript() { + let port = browser.runtime.connect(); + + port.onMessage.addListener((msg) => { + if (msg == "legacy_extension -> webextension") { + port.postMessage("webextension -> legacy_extension"); + port.disconnect(); + } + }); + } + + const id = "@test.embedded.web.extension"; + + // Extensions.generateXPI is used here (and in the other hybrid addons tests in this same + // test dir) to be able to generate an xpi with the directory layout that we expect from + // an hybrid legacy+webextension addon (where all the embedded webextension resources are + // loaded from a 'webextension/' directory). + let fakeHybridAddonFile = Extension.generateZipFile({ + "webextension/manifest.json": { + applications: {gecko: {id}}, + name: "embedded webextension name", + manifest_version: 2, + version: "1.0", + background: { + scripts: ["bg.js"], + }, + }, + "webextension/bg.js": `new ${backgroundScript}`, + }); + + // Remove the generated xpi file and flush the its jar cache + // on cleanup. + do_register_cleanup(() => { + Services.obs.notifyObservers(fakeHybridAddonFile, "flush-cache-entry", null); + fakeHybridAddonFile.remove(false); + }); + + let fileURI = Services.io.newFileURI(fakeHybridAddonFile); + let resourceURI = Services.io.newURI(`jar:${fileURI.spec}!/`, null, null); + + let embeddedExtension = LegacyExtensionsUtils.getEmbeddedExtensionFor({ + id, resourceURI, + }); + + ok(embeddedExtension, "Got the embeddedExtension object"); + + equal(EmbeddedExtensionManager.embeddedExtensionsByAddonId.size, 1, + "Got the expected number of tracked embedded extension instances"); + + do_print("waiting embeddedExtension.startup"); + let embeddedExtensionAPI = yield embeddedExtension.startup(); + ok(embeddedExtensionAPI, "Got the embeddedExtensionAPI object"); + + let waitConnectPort = new Promise(resolve => { + let {browser} = embeddedExtensionAPI; + browser.runtime.onConnect.addListener(port => { + resolve(port); + }); + }); + + let port = yield waitConnectPort; + + ok(port, "Got the Port API object"); + + let waitPortMessage = new Promise(resolve => { + port.onMessage.addListener((msg) => { + resolve(msg); + }); + }); + + port.postMessage("legacy_extension -> webextension"); + + let msg = yield waitPortMessage; + + equal(msg, "webextension -> legacy_extension", + "LegacyExtensionContext received the expected message from the webextension"); + + let waitForDisconnect = new Promise(resolve => { + port.onDisconnect.addListener(resolve); + }); + + do_print("Wait for the disconnect port event"); + yield waitForDisconnect; + do_print("Got the disconnect port event"); + + yield embeddedExtension.shutdown(); + + equal(EmbeddedExtensionManager.embeddedExtensionsByAddonId.size, 0, + "EmbeddedExtension instances has been untracked from the EmbeddedExtensionManager"); +}); + +function* createManifestErrorTestCase(id, xpi, expectedError) { + // Remove the generated xpi file and flush the its jar cache + // on cleanup. + do_register_cleanup(() => { + Services.obs.notifyObservers(xpi, "flush-cache-entry", null); + xpi.remove(false); + }); + + let fileURI = Services.io.newFileURI(xpi); + let resourceURI = Services.io.newURI(`jar:${fileURI.spec}!/`, null, null); + + let embeddedExtension = LegacyExtensionsUtils.getEmbeddedExtensionFor({ + id, resourceURI, + }); + + yield Assert.rejects(embeddedExtension.startup(), expectedError, + "embedded extension startup rejected"); + + // Shutdown a "never-started" addon with an embedded webextension should not + // raise any exception, and if it does this test will fail. + yield embeddedExtension.shutdown(); +} + +add_task(function* test_startup_error_empty_manifest() { + const id = "empty-manifest@test.embedded.web.extension"; + const files = { + "webextension/manifest.json": ``, + }; + const expectedError = "(NS_BASE_STREAM_CLOSED)"; + + let fakeHybridAddonFile = Extension.generateZipFile(files); + + yield createManifestErrorTestCase(id, fakeHybridAddonFile, expectedError); +}); + +add_task(function* test_startup_error_invalid_json_manifest() { + const id = "invalid-json-manifest@test.embedded.web.extension"; + const files = { + "webextension/manifest.json": `{ "name": }`, + }; + const expectedError = "JSON.parse:"; + + let fakeHybridAddonFile = Extension.generateZipFile(files); + + yield createManifestErrorTestCase(id, fakeHybridAddonFile, expectedError); +}); + +add_task(function* test_startup_error_blocking_validation_errors() { + const id = "blocking-manifest-validation-error@test.embedded.web.extension"; + const files = { + "webextension/manifest.json": { + name: "embedded webextension name", + manifest_version: 2, + version: "1.0", + background: { + scripts: {}, + }, + }, + }; + + function expectedError(actual) { + if (actual.errors && actual.errors.length == 1 && + actual.errors[0].startsWith("Reading manifest:")) { + return true; + } + + return false; + } + + let fakeHybridAddonFile = Extension.generateZipFile(files); + + yield createManifestErrorTestCase(id, fakeHybridAddonFile, expectedError); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_localStorage.js b/toolkit/components/webextensions/test/xpcshell/test_ext_localStorage.js new file mode 100644 index 000000000..0f0b41085 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_localStorage.js @@ -0,0 +1,50 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +function backgroundScript() { + let hasRun = localStorage.getItem("has-run"); + let result; + if (!hasRun) { + localStorage.setItem("has-run", "yup"); + localStorage.setItem("test-item", "item1"); + result = "item1"; + } else { + let data = localStorage.getItem("test-item"); + if (data == "item1") { + localStorage.setItem("test-item", "item2"); + result = "item2"; + } else if (data == "item2") { + localStorage.removeItem("test-item"); + result = "deleted"; + } else if (!data) { + localStorage.clear(); + result = "cleared"; + } + } + browser.test.sendMessage("result", result); + browser.test.notifyPass("localStorage"); +} + +const ID = "test-webextension@mozilla.com"; +let extensionData = { + manifest: {applications: {gecko: {id: ID}}}, + background: backgroundScript, +}; + +add_task(function* test_localStorage() { + const RESULTS = ["item1", "item2", "deleted", "cleared", "item1"]; + + for (let expected of RESULTS) { + let extension = ExtensionTestUtils.loadExtension(extensionData); + + yield extension.startup(); + + let actual = yield extension.awaitMessage("result"); + + yield extension.awaitFinish("localStorage"); + yield extension.unload(); + + equal(actual, expected, "got expected localStorage data"); + } +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_management.js b/toolkit/components/webextensions/test/xpcshell/test_ext_management.js new file mode 100644 index 000000000..b19554a57 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_management.js @@ -0,0 +1,20 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_management_schema() { + function background() { + browser.test.assertTrue(browser.management, "browser.management API exists"); + browser.test.notifyPass("management-schema"); + } + + let extension = ExtensionTestUtils.loadExtension({ + manifest: { + permissions: ["management"], + }, + background: `(${background})()`, + }); + yield extension.startup(); + yield extension.awaitFinish("management-schema"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_management_uninstall_self.js b/toolkit/components/webextensions/test/xpcshell/test_ext_management_uninstall_self.js new file mode 100644 index 000000000..7d80a9c23 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_management_uninstall_self.js @@ -0,0 +1,135 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +Cu.import("resource://gre/modules/AddonManager.jsm"); +Cu.import("resource://testing-common/AddonTestUtils.jsm"); +Cu.import("resource://testing-common/MockRegistrar.jsm"); + +const {promiseAddonByID} = AddonTestUtils; +const id = "uninstall_self_test@tests.mozilla.com"; + +const manifest = { + applications: { + gecko: { + id, + }, + }, + name: "test extension name", + version: "1.0", +}; + +const waitForUninstalled = () => new Promise(resolve => { + const listener = { + onUninstalled: (addon) => { + equal(addon.id, id, "The expected add-on has been uninstalled"); + AddonManager.getAddonByID(addon.id, checkedAddon => { + equal(checkedAddon, null, "Add-on no longer exists"); + AddonManager.removeAddonListener(listener); + resolve(); + }); + }, + }; + AddonManager.addAddonListener(listener); +}); + +let promptService = { + _response: null, + QueryInterface: XPCOMUtils.generateQI([Ci.nsIPromptService]), + confirmEx: function(...args) { + this._confirmExArgs = args; + return this._response; + }, +}; + +add_task(function* setup() { + let fakePromptService = MockRegistrar.register("@mozilla.org/embedcomp/prompt-service;1", promptService); + do_register_cleanup(() => { + MockRegistrar.unregister(fakePromptService); + }); + yield ExtensionTestUtils.startAddonManager(); +}); + +add_task(function* test_management_uninstall_no_prompt() { + function background() { + browser.test.onMessage.addListener(msg => { + browser.management.uninstallSelf(); + }); + } + + let extension = ExtensionTestUtils.loadExtension({ + manifest, + background, + useAddonManager: "temporary", + }); + + yield extension.startup(); + let addon = yield promiseAddonByID(id); + notEqual(addon, null, "Add-on is installed"); + extension.sendMessage("uninstall"); + yield waitForUninstalled(); + yield extension.markUnloaded(); + Services.obs.notifyObservers(extension.extension.file, "flush-cache-entry", null); +}); + +add_task(function* test_management_uninstall_prompt_uninstall() { + promptService._response = 0; + + function background() { + browser.test.onMessage.addListener(msg => { + browser.management.uninstallSelf({showConfirmDialog: true}); + }); + } + + let extension = ExtensionTestUtils.loadExtension({ + manifest, + background, + useAddonManager: "temporary", + }); + + yield extension.startup(); + let addon = yield promiseAddonByID(id); + notEqual(addon, null, "Add-on is installed"); + extension.sendMessage("uninstall"); + yield waitForUninstalled(); + yield extension.markUnloaded(); + + // Test localization strings + equal(promptService._confirmExArgs[1], `Uninstall ${manifest.name}`); + equal(promptService._confirmExArgs[2], + `The extension “${manifest.name}†is requesting to be uninstalled. What would you like to do?`); + equal(promptService._confirmExArgs[4], "Uninstall"); + equal(promptService._confirmExArgs[5], "Keep Installed"); + Services.obs.notifyObservers(extension.extension.file, "flush-cache-entry", null); +}); + +add_task(function* test_management_uninstall_prompt_keep() { + promptService._response = 1; + + function background() { + browser.test.onMessage.addListener(async msg => { + await browser.test.assertRejects( + browser.management.uninstallSelf({showConfirmDialog: true}), + "User cancelled uninstall of extension", + "Expected rejection when user declines uninstall"); + + browser.test.sendMessage("uninstall-rejected"); + }); + } + + let extension = ExtensionTestUtils.loadExtension({ + manifest, + background, + useAddonManager: "temporary", + }); + + yield extension.startup(); + let addon = yield promiseAddonByID(id); + notEqual(addon, null, "Add-on is installed"); + extension.sendMessage("uninstall"); + yield extension.awaitMessage("uninstall-rejected"); + addon = yield promiseAddonByID(id); + notEqual(addon, null, "Add-on remains installed"); + yield extension.unload(); + Services.obs.notifyObservers(extension.extension.file, "flush-cache-entry", null); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_content_security_policy.js b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_content_security_policy.js new file mode 100644 index 000000000..2b0084980 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_content_security_policy.js @@ -0,0 +1,30 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + + +add_task(function* test_manifest_csp() { + let normalized = yield ExtensionTestUtils.normalizeManifest({ + "content_security_policy": "script-src 'self'; object-src 'none'", + }); + + equal(normalized.error, undefined, "Should not have an error"); + equal(normalized.errors.length, 0, "Should not have warnings"); + equal(normalized.value.content_security_policy, + "script-src 'self'; object-src 'none'", + "Should have the expected poilcy string"); + + + normalized = yield ExtensionTestUtils.normalizeManifest({ + "content_security_policy": "object-src 'none'", + }); + + equal(normalized.error, undefined, "Should not have an error"); + + Assert.deepEqual(normalized.errors, + ["Error processing content_security_policy: SyntaxError: Policy is missing a required \u2018script-src\u2019 directive"], + "Should have the expected warning"); + + equal(normalized.value.content_security_policy, null, + "Invalid policy string should be omitted"); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_incognito.js b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_incognito.js new file mode 100644 index 000000000..94649692e --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_incognito.js @@ -0,0 +1,27 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + + +add_task(function* test_manifest_incognito() { + let normalized = yield ExtensionTestUtils.normalizeManifest({ + "incognito": "spanning", + }); + + equal(normalized.error, undefined, "Should not have an error"); + equal(normalized.errors.length, 0, "Should not have warnings"); + equal(normalized.value.incognito, + "spanning", + "Should have the expected incognito string"); + + normalized = yield ExtensionTestUtils.normalizeManifest({ + "incognito": "split", + }); + + equal(normalized.error, undefined, "Should not have an error"); + Assert.deepEqual(normalized.errors, + ['Error processing incognito: Invalid enumeration value "split"'], + "Should have the expected warning"); + equal(normalized.value.incognito, null, + "Invalid incognito string should be omitted"); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_minimum_chrome_version.js b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_minimum_chrome_version.js new file mode 100644 index 000000000..fad5661bb --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_manifest_minimum_chrome_version.js @@ -0,0 +1,13 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + + +add_task(function* test_manifest_minimum_chrome_version() { + let normalized = yield ExtensionTestUtils.normalizeManifest({ + "minimum_chrome_version": "42", + }); + + equal(normalized.error, undefined, "Should not have an error"); + equal(normalized.errors.length, 0, "Should not have warnings"); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging.js b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging.js new file mode 100644 index 000000000..5a6b628f5 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging.js @@ -0,0 +1,514 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +/* globals chrome */ + +const PREF_MAX_READ = "webextensions.native-messaging.max-input-message-bytes"; +const PREF_MAX_WRITE = "webextensions.native-messaging.max-output-message-bytes"; + +const ECHO_BODY = String.raw` + import struct + import sys + + while True: + rawlen = sys.stdin.read(4) + if len(rawlen) == 0: + sys.exit(0) + msglen = struct.unpack('@I', rawlen)[0] + msg = sys.stdin.read(msglen) + + sys.stdout.write(struct.pack('@I', msglen)) + sys.stdout.write(msg) +`; + +const INFO_BODY = String.raw` + import json + import os + import struct + import sys + + msg = json.dumps({"args": sys.argv, "cwd": os.getcwd()}) + sys.stdout.write(struct.pack('@I', len(msg))) + sys.stdout.write(msg) + sys.exit(0) +`; + +const STDERR_LINES = ["hello stderr", "this should be a separate line"]; +let STDERR_MSG = STDERR_LINES.join("\\n"); + +const STDERR_BODY = String.raw` + import sys + sys.stderr.write("${STDERR_MSG}") +`; + +const SCRIPTS = [ + { + name: "echo", + description: "a native app that echoes back messages it receives", + script: ECHO_BODY.replace(/^ {2}/gm, ""), + }, + { + name: "info", + description: "a native app that gives some info about how it was started", + script: INFO_BODY.replace(/^ {2}/gm, ""), + }, + { + name: "stderr", + description: "a native app that writes to stderr and then exits", + script: STDERR_BODY.replace(/^ {2}/gm, ""), + }, +]; + +add_task(function* setup() { + yield setupHosts(SCRIPTS); +}); + +// Test the basic operation of native messaging with a simple +// script that echoes back whatever message is sent to it. +add_task(function* test_happy_path() { + function background() { + let port = browser.runtime.connectNative("echo"); + port.onMessage.addListener(msg => { + browser.test.sendMessage("message", msg); + }); + browser.test.onMessage.addListener((what, payload) => { + if (what == "send") { + if (payload._json) { + let json = payload._json; + payload.toJSON = () => json; + delete payload._json; + } + port.postMessage(payload); + } + }); + browser.test.sendMessage("ready"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + applications: {gecko: {id: ID}}, + permissions: ["nativeMessaging"], + }, + }); + + yield extension.startup(); + yield extension.awaitMessage("ready"); + const tests = [ + { + data: "this is a string", + what: "simple string", + }, + { + data: "Это юникода", + what: "unicode string", + }, + { + data: {test: "hello"}, + what: "simple object", + }, + { + data: { + what: "An object with a few properties", + number: 123, + bool: true, + nested: {what: "another object"}, + }, + what: "object with several properties", + }, + + { + data: { + ignoreme: true, + _json: {data: "i have a tojson method"}, + }, + expected: {data: "i have a tojson method"}, + what: "object with toJSON() method", + }, + ]; + for (let test of tests) { + extension.sendMessage("send", test.data); + let response = yield extension.awaitMessage("message"); + let expected = test.expected || test.data; + deepEqual(response, expected, `Echoed a message of type ${test.what}`); + } + + let procCount = yield getSubprocessCount(); + equal(procCount, 1, "subprocess is still running"); + let exitPromise = waitForSubprocessExit(); + yield extension.unload(); + yield exitPromise; +}); + +if (AppConstants.platform == "win") { + // "relative.echo" has a relative path in the host manifest. + add_task(function* test_relative_path() { + function background() { + let port = browser.runtime.connectNative("relative.echo"); + let MSG = "test relative echo path"; + port.onMessage.addListener(msg => { + browser.test.assertEq(MSG, msg, "Got expected message back"); + browser.test.sendMessage("done"); + }); + port.postMessage(MSG); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + applications: {gecko: {id: ID}}, + permissions: ["nativeMessaging"], + }, + }); + + yield extension.startup(); + yield extension.awaitMessage("done"); + + let procCount = yield getSubprocessCount(); + equal(procCount, 1, "subprocess is still running"); + let exitPromise = waitForSubprocessExit(); + yield extension.unload(); + yield exitPromise; + }); +} + +// Test sendNativeMessage() +add_task(function* test_sendNativeMessage() { + async function background() { + let MSG = {test: "hello world"}; + + // Check error handling + await browser.test.assertRejects( + browser.runtime.sendNativeMessage("nonexistent", MSG), + /Attempt to postMessage on disconnected port/, + "sendNativeMessage() to a nonexistent app failed"); + + // Check regular message exchange + let reply = await browser.runtime.sendNativeMessage("echo", MSG); + + let expected = JSON.stringify(MSG); + let received = JSON.stringify(reply); + browser.test.assertEq(expected, received, "Received echoed native message"); + + browser.test.sendMessage("finished"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + applications: {gecko: {id: ID}}, + permissions: ["nativeMessaging"], + }, + }); + + yield extension.startup(); + yield extension.awaitMessage("finished"); + + // With sendNativeMessage(), the subprocess should be disconnected + // after exchanging a single message. + yield waitForSubprocessExit(); + + yield extension.unload(); +}); + +// Test calling Port.disconnect() +add_task(function* test_disconnect() { + function background() { + let port = browser.runtime.connectNative("echo"); + port.onMessage.addListener((msg, msgPort) => { + browser.test.assertEq(port, msgPort, "onMessage handler should receive the port as the second argument"); + browser.test.sendMessage("message", msg); + }); + port.onDisconnect.addListener(msgPort => { + browser.test.fail("onDisconnect should not be called for disconnect()"); + }); + browser.test.onMessage.addListener((what, payload) => { + if (what == "send") { + if (payload._json) { + let json = payload._json; + payload.toJSON = () => json; + delete payload._json; + } + port.postMessage(payload); + } else if (what == "disconnect") { + try { + port.disconnect(); + browser.test.sendMessage("disconnect-result", {success: true}); + } catch (err) { + browser.test.sendMessage("disconnect-result", { + success: false, + errmsg: err.message, + }); + } + } + }); + browser.test.sendMessage("ready"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + applications: {gecko: {id: ID}}, + permissions: ["nativeMessaging"], + }, + }); + + yield extension.startup(); + yield extension.awaitMessage("ready"); + + extension.sendMessage("send", "test"); + let response = yield extension.awaitMessage("message"); + equal(response, "test", "Echoed a string"); + + let procCount = yield getSubprocessCount(); + equal(procCount, 1, "subprocess is running"); + + extension.sendMessage("disconnect"); + response = yield extension.awaitMessage("disconnect-result"); + equal(response.success, true, "disconnect succeeded"); + + do_print("waiting for subprocess to exit"); + yield waitForSubprocessExit(); + procCount = yield getSubprocessCount(); + equal(procCount, 0, "subprocess is no longer running"); + + extension.sendMessage("disconnect"); + response = yield extension.awaitMessage("disconnect-result"); + equal(response.success, true, "second call to disconnect silently ignored"); + + yield extension.unload(); +}); + +// Test the limit on message size for writing +add_task(function* test_write_limit() { + Services.prefs.setIntPref(PREF_MAX_WRITE, 10); + function clearPref() { + Services.prefs.clearUserPref(PREF_MAX_WRITE); + } + do_register_cleanup(clearPref); + + function background() { + const PAYLOAD = "0123456789A"; + let port = browser.runtime.connectNative("echo"); + try { + port.postMessage(PAYLOAD); + browser.test.sendMessage("result", null); + } catch (ex) { + browser.test.sendMessage("result", ex.message); + } + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + applications: {gecko: {id: ID}}, + permissions: ["nativeMessaging"], + }, + }); + + yield extension.startup(); + + let errmsg = yield extension.awaitMessage("result"); + notEqual(errmsg, null, "native postMessage() failed for overly large message"); + + yield extension.unload(); + yield waitForSubprocessExit(); + + clearPref(); +}); + +// Test the limit on message size for reading +add_task(function* test_read_limit() { + Services.prefs.setIntPref(PREF_MAX_READ, 10); + function clearPref() { + Services.prefs.clearUserPref(PREF_MAX_READ); + } + do_register_cleanup(clearPref); + + function background() { + const PAYLOAD = "0123456789A"; + let port = browser.runtime.connectNative("echo"); + port.onDisconnect.addListener(msgPort => { + browser.test.assertEq(port, msgPort, "onDisconnect handler should receive the port as the first argument"); + browser.test.assertEq("Native application tried to send a message of 13 bytes, which exceeds the limit of 10 bytes.", port.error && port.error.message); + browser.test.sendMessage("result", "disconnected"); + }); + port.onMessage.addListener(msg => { + browser.test.sendMessage("result", "message"); + }); + port.postMessage(PAYLOAD); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + applications: {gecko: {id: ID}}, + permissions: ["nativeMessaging"], + }, + }); + + yield extension.startup(); + + let result = yield extension.awaitMessage("result"); + equal(result, "disconnected", "native port disconnected on receiving large message"); + + yield extension.unload(); + yield waitForSubprocessExit(); + + clearPref(); +}); + +// Test that an extension without the nativeMessaging permission cannot +// use native messaging. +add_task(function* test_ext_permission() { + function background() { + browser.test.assertFalse("connectNative" in chrome.runtime, "chrome.runtime.connectNative does not exist without nativeMessaging permission"); + browser.test.assertFalse("connectNative" in browser.runtime, "browser.runtime.connectNative does not exist without nativeMessaging permission"); + browser.test.assertFalse("sendNativeMessage" in chrome.runtime, "chrome.runtime.sendNativeMessage does not exist without nativeMessaging permission"); + browser.test.assertFalse("sendNativeMessage" in browser.runtime, "browser.runtime.sendNativeMessage does not exist without nativeMessaging permission"); + browser.test.sendMessage("finished"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: {}, + }); + + yield extension.startup(); + yield extension.awaitMessage("finished"); + yield extension.unload(); +}); + +// Test that an extension that is not listed in allowed_extensions for +// a native application cannot use that application. +add_task(function* test_app_permission() { + function background() { + let port = browser.runtime.connectNative("echo"); + port.onDisconnect.addListener(msgPort => { + browser.test.assertEq(port, msgPort, "onDisconnect handler should receive the port as the first argument"); + browser.test.assertEq("This extension does not have permission to use native application echo (or the application is not installed)", port.error && port.error.message); + browser.test.sendMessage("result", "disconnected"); + }); + port.onMessage.addListener(msg => { + browser.test.sendMessage("result", "message"); + }); + port.postMessage({test: "test"}); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + permissions: ["nativeMessaging"], + }, + }, "somethingelse@tests.mozilla.org"); + + yield extension.startup(); + + let result = yield extension.awaitMessage("result"); + equal(result, "disconnected", "connectNative() failed without native app permission"); + + yield extension.unload(); + + let procCount = yield getSubprocessCount(); + equal(procCount, 0, "No child process was started"); +}); + +// Test that the command-line arguments and working directory for the +// native application are as expected. +add_task(function* test_child_process() { + function background() { + let port = browser.runtime.connectNative("info"); + port.onMessage.addListener(msg => { + browser.test.sendMessage("result", msg); + }); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + applications: {gecko: {id: ID}}, + permissions: ["nativeMessaging"], + }, + }); + + yield extension.startup(); + + let msg = yield extension.awaitMessage("result"); + equal(msg.args.length, 2, "Received one command line argument"); + equal(msg.args[1], getPath("info.json"), "Command line argument is the path to the native host manifest"); + equal(msg.cwd.replace(/^\/private\//, "/"), tmpDir.path, + "Working directory is the directory containing the native appliation"); + + let exitPromise = waitForSubprocessExit(); + yield extension.unload(); + yield exitPromise; +}); + +add_task(function* test_stderr() { + function background() { + let port = browser.runtime.connectNative("stderr"); + port.onDisconnect.addListener(msgPort => { + browser.test.assertEq(port, msgPort, "onDisconnect handler should receive the port as the first argument"); + browser.test.assertEq(null, port.error, "Normal application exit is not an error"); + browser.test.sendMessage("finished"); + }); + } + + let {messages} = yield promiseConsoleOutput(function* () { + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + applications: {gecko: {id: ID}}, + permissions: ["nativeMessaging"], + }, + }); + + yield extension.startup(); + yield extension.awaitMessage("finished"); + yield extension.unload(); + + yield waitForSubprocessExit(); + }); + + let lines = STDERR_LINES.map(line => messages.findIndex(msg => msg.message.includes(line))); + notEqual(lines[0], -1, "Saw first line of stderr output on the console"); + notEqual(lines[1], -1, "Saw second line of stderr output on the console"); + notEqual(lines[0], lines[1], "Stderr output lines are separated in the console"); +}); + +// Test that calling connectNative() multiple times works +// (bug 1313980 was a previous regression in this area) +add_task(function* test_multiple_connects() { + async function background() { + function once() { + return new Promise(resolve => { + let MSG = "hello"; + let port = browser.runtime.connectNative("echo"); + + port.onMessage.addListener(msg => { + browser.test.assertEq(MSG, msg, "Got expected message back"); + port.disconnect(); + resolve(); + }); + port.postMessage(MSG); + }); + } + + await once(); + await once(); + browser.test.notifyPass("multiple-connect"); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + applications: {gecko: {id: ID}}, + permissions: ["nativeMessaging"], + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("multiple-connect"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_perf.js b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_perf.js new file mode 100644 index 000000000..693f67dde --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_perf.js @@ -0,0 +1,128 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +XPCOMUtils.defineLazyModuleGetter(this, "MockRegistry", + "resource://testing-common/MockRegistry.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "OS", + "resource://gre/modules/osfile.jsm"); + +Cu.import("resource://gre/modules/Subprocess.jsm"); + +const MAX_ROUND_TRIP_TIME_MS = AppConstants.DEBUG || AppConstants.ASAN ? 36 : 18; +const MAX_RETRIES = 5; + + +const ECHO_BODY = String.raw` + import struct + import sys + + while True: + rawlen = sys.stdin.read(4) + if len(rawlen) == 0: + sys.exit(0) + + msglen = struct.unpack('@I', rawlen)[0] + msg = sys.stdin.read(msglen) + + sys.stdout.write(struct.pack('@I', msglen)) + sys.stdout.write(msg) +`; + +const SCRIPTS = [ + { + name: "echo", + description: "A native app that echoes back messages it receives", + script: ECHO_BODY.replace(/^ {2}/gm, ""), + }, +]; + +add_task(function* setup() { + yield setupHosts(SCRIPTS); +}); + +add_task(function* test_round_trip_perf() { + let extension = ExtensionTestUtils.loadExtension({ + background() { + browser.test.onMessage.addListener(msg => { + if (msg != "run-tests") { + return; + } + + let port = browser.runtime.connectNative("echo"); + + function next() { + port.postMessage({ + "Lorem": { + "ipsum": { + "dolor": [ + "sit amet", + "consectetur adipiscing elit", + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", + ], + "Ut enim": [ + "ad minim veniam", + "quis nostrud exercitation ullamco", + "laboris nisi ut aliquip ex ea commodo consequat.", + ], + "Duis": [ + "aute irure dolor in reprehenderit in", + "voluptate velit esse cillum dolore eu", + "fugiat nulla pariatur.", + ], + "Excepteur": [ + "sint occaecat cupidatat non proident", + "sunt in culpa qui officia deserunt", + "mollit anim id est laborum.", + ], + }, + }, + }); + } + + const COUNT = 1000; + let now; + function finish() { + let roundTripTime = (Date.now() - now) / COUNT; + + port.disconnect(); + browser.test.sendMessage("result", roundTripTime); + } + + let count = 0; + port.onMessage.addListener(() => { + if (count == 0) { + // Skip the first round, since it includes the time it takes + // the app to start up. + now = Date.now(); + } + + if (count++ <= COUNT) { + next(); + } else { + finish(); + } + }); + + next(); + }); + }, + manifest: { + applications: {gecko: {id: ID}}, + permissions: ["nativeMessaging"], + }, + }); + + yield extension.startup(); + + let roundTripTime = Infinity; + for (let i = 0; i < MAX_RETRIES && roundTripTime > MAX_ROUND_TRIP_TIME_MS; i++) { + extension.sendMessage("run-tests"); + roundTripTime = yield extension.awaitMessage("result"); + } + + yield extension.unload(); + + ok(roundTripTime <= MAX_ROUND_TRIP_TIME_MS, + `Expected round trip time (${roundTripTime}ms) to be less than ${MAX_ROUND_TRIP_TIME_MS}ms`); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_unresponsive.js b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_unresponsive.js new file mode 100644 index 000000000..a75a1d49d --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_native_messaging_unresponsive.js @@ -0,0 +1,82 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +const WONTDIE_BODY = String.raw` + import signal + import struct + import sys + import time + + signal.signal(signal.SIGTERM, signal.SIG_IGN) + + def spin(): + while True: + try: + signal.pause() + except AttributeError: + time.sleep(5) + + while True: + rawlen = sys.stdin.read(4) + if len(rawlen) == 0: + spin() + + msglen = struct.unpack('@I', rawlen)[0] + msg = sys.stdin.read(msglen) + + sys.stdout.write(struct.pack('@I', msglen)) + sys.stdout.write(msg) +`; + +const SCRIPTS = [ + { + name: "wontdie", + description: "a native app that does not exit when stdin closes or on SIGTERM", + script: WONTDIE_BODY.replace(/^ {2}/gm, ""), + }, +]; + +add_task(function* setup() { + yield setupHosts(SCRIPTS); +}); + + +// Test that an unresponsive native application still gets killed eventually +add_task(function* test_unresponsive_native_app() { + // XXX expose GRACEFUL_SHUTDOWN_TIME as a pref and reduce it + // just for this test? + + function background() { + let port = browser.runtime.connectNative("wontdie"); + + const MSG = "echo me"; + // bounce a message to make sure the process actually starts + port.onMessage.addListener(msg => { + browser.test.assertEq(msg, MSG, "Received echoed message"); + browser.test.sendMessage("ready"); + }); + port.postMessage(MSG); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + manifest: { + applications: {gecko: {id: ID}}, + permissions: ["nativeMessaging"], + }, + }); + + yield extension.startup(); + yield extension.awaitMessage("ready"); + + let procCount = yield getSubprocessCount(); + equal(procCount, 1, "subprocess is running"); + + let exitPromise = waitForSubprocessExit(); + yield extension.unload(); + yield exitPromise; + + procCount = yield getSubprocessCount(); + equal(procCount, 0, "subprocess was succesfully killed"); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_onmessage_removelistener.js b/toolkit/components/webextensions/test/xpcshell/test_ext_onmessage_removelistener.js new file mode 100644 index 000000000..6f8b553fc --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_onmessage_removelistener.js @@ -0,0 +1,30 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +function backgroundScript() { + function listener() { + browser.test.notifyFail("listener should not be invoked"); + } + + browser.runtime.onMessage.addListener(listener); + browser.runtime.onMessage.removeListener(listener); + browser.runtime.sendMessage("hello"); + + // Make sure that, if we somehow fail to remove the listener, then we'll run + // the listener before the test is marked as passing. + setTimeout(function() { + browser.test.notifyPass("onmessage_removelistener"); + }, 0); +} + +let extensionData = { + background: backgroundScript, +}; + +add_task(function* test_contentscript() { + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + yield extension.awaitFinish("onmessage_removelistener"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_connect_no_receiver.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_connect_no_receiver.js new file mode 100644 index 000000000..2a1342cde --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_connect_no_receiver.js @@ -0,0 +1,23 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_connect_without_listener() { + function background() { + let port = browser.runtime.connect(); + port.onDisconnect.addListener(() => { + browser.test.assertEq("Could not establish connection. Receiving end does not exist.", port.error && port.error.message); + browser.test.notifyPass("port.onDisconnect was called"); + }); + } + let extensionData = { + background, + }; + + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + + yield extension.awaitFinish("port.onDisconnect was called"); + + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getBrowserInfo.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getBrowserInfo.js new file mode 100644 index 000000000..a280206fa --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getBrowserInfo.js @@ -0,0 +1,26 @@ +/* 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"; + +add_task(function* setup() { + ExtensionTestUtils.mockAppInfo(); +}); + +add_task(function* test_getBrowserInfo() { + async function background() { + let info = await browser.runtime.getBrowserInfo(); + + browser.test.assertEq(info.name, "XPCShell", "name is valid"); + browser.test.assertEq(info.vendor, "Mozilla", "vendor is Mozilla"); + browser.test.assertEq(info.version, "48", "version is correct"); + browser.test.assertEq(info.buildID, "20160315", "buildID is correct"); + + browser.test.notifyPass("runtime.getBrowserInfo"); + } + + const extension = ExtensionTestUtils.loadExtension({background}); + yield extension.startup(); + yield extension.awaitFinish("runtime.getBrowserInfo"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getPlatformInfo.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getPlatformInfo.js new file mode 100644 index 000000000..29bad0c10 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_getPlatformInfo.js @@ -0,0 +1,25 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +function backgroundScript() { + browser.runtime.getPlatformInfo(info => { + let validOSs = ["mac", "win", "android", "cros", "linux", "openbsd"]; + let validArchs = ["arm", "x86-32", "x86-64"]; + + browser.test.assertTrue(validOSs.indexOf(info.os) != -1, "OS is valid"); + browser.test.assertTrue(validArchs.indexOf(info.arch) != -1, "Architecture is valid"); + browser.test.notifyPass("runtime.getPlatformInfo"); + }); +} + +let extensionData = { + background: backgroundScript, +}; + +add_task(function* test_contentscript() { + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + yield extension.awaitFinish("runtime.getPlatformInfo"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_onInstalled_and_onStartup.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_onInstalled_and_onStartup.js new file mode 100644 index 000000000..fa6461412 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_onInstalled_and_onStartup.js @@ -0,0 +1,337 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +XPCOMUtils.defineLazyGetter(this, "Management", () => { + const {Management} = Cu.import("resource://gre/modules/Extension.jsm", {}); + return Management; +}); + +const { + createAppInfo, + createTempWebExtensionFile, + promiseAddonByID, + promiseAddonEvent, + promiseCompleteAllInstalls, + promiseFindAddonUpdates, + promiseRestartManager, + promiseShutdownManager, + promiseStartupManager, +} = AddonTestUtils; + +AddonTestUtils.init(this); + +// Allow for unsigned addons. +AddonTestUtils.overrideCertDB(); + +createAppInfo("xpcshell@tests.mozilla.org", "XPCShell", "1", "42"); + +function awaitEvent(eventName) { + return new Promise(resolve => { + let listener = (_eventName, ...args) => { + if (_eventName === eventName) { + Management.off(eventName, listener); + resolve(...args); + } + }; + + Management.on(eventName, listener); + }); +} + +function background() { + let onInstalledDetails = null; + let onStartupFired = false; + + browser.runtime.onInstalled.addListener(details => { + onInstalledDetails = details; + }); + + browser.runtime.onStartup.addListener(() => { + onStartupFired = true; + }); + + browser.test.onMessage.addListener(message => { + if (message === "get-on-installed-details") { + onInstalledDetails = onInstalledDetails || {fired: false}; + browser.test.sendMessage("on-installed-details", onInstalledDetails); + } else if (message === "did-on-startup-fire") { + browser.test.sendMessage("on-startup-fired", onStartupFired); + } else if (message === "reload-extension") { + browser.runtime.reload(); + } + }); + + browser.runtime.onUpdateAvailable.addListener(details => { + browser.test.sendMessage("reloading"); + browser.runtime.reload(); + }); +} + +function* expectEvents(extension, {onStartupFired, onInstalledFired, onInstalledReason}) { + extension.sendMessage("get-on-installed-details"); + let details = yield extension.awaitMessage("on-installed-details"); + if (onInstalledFired) { + equal(details.reason, onInstalledReason, "runtime.onInstalled fired with the correct reason"); + } else { + equal(details.fired, onInstalledFired, "runtime.onInstalled should not have fired"); + } + + extension.sendMessage("did-on-startup-fire"); + let fired = yield extension.awaitMessage("on-startup-fired"); + equal(fired, onStartupFired, `Expected runtime.onStartup to ${onStartupFired ? "" : "not "} fire`); +} + +add_task(function* test_should_fire_on_addon_update() { + const EXTENSION_ID = "test_runtime_on_installed_addon_update@tests.mozilla.org"; + + const PREF_EM_CHECK_UPDATE_SECURITY = "extensions.checkUpdateSecurity"; + + // The test extension uses an insecure update url. + Services.prefs.setBoolPref(PREF_EM_CHECK_UPDATE_SECURITY, false); + + const testServer = createHttpServer(); + const port = testServer.identity.primaryPort; + + let extension = ExtensionTestUtils.loadExtension({ + useAddonManager: "permanent", + manifest: { + "version": "1.0", + "applications": { + "gecko": { + "id": EXTENSION_ID, + "update_url": `http://localhost:${port}/test_update.json`, + }, + }, + }, + background, + }); + + testServer.registerPathHandler("/test_update.json", (request, response) => { + response.write(`{ + "addons": { + "${EXTENSION_ID}": { + "updates": [ + { + "version": "2.0", + "update_link": "http://localhost:${port}/addons/test_runtime_on_installed-2.0.xpi" + } + ] + } + } + }`); + }); + + let webExtensionFile = createTempWebExtensionFile({ + manifest: { + version: "2.0", + applications: { + gecko: { + id: EXTENSION_ID, + }, + }, + }, + background, + }); + + testServer.registerFile("/addons/test_runtime_on_installed-2.0.xpi", webExtensionFile); + + yield promiseStartupManager(); + + yield extension.startup(); + + yield expectEvents(extension, { + onStartupFired: false, + onInstalledFired: true, + onInstalledReason: "install", + }); + + let addon = yield promiseAddonByID(EXTENSION_ID); + equal(addon.version, "1.0", "The installed addon has the correct version"); + + let update = yield promiseFindAddonUpdates(addon); + let install = update.updateAvailable; + + let promiseInstalled = promiseAddonEvent("onInstalled"); + yield promiseCompleteAllInstalls([install]); + + yield extension.awaitMessage("reloading"); + + let startupPromise = awaitEvent("ready"); + + let [updated_addon] = yield promiseInstalled; + equal(updated_addon.version, "2.0", "The updated addon has the correct version"); + + extension.extension = yield startupPromise; + extension.attachListeners(); + + yield expectEvents(extension, { + onStartupFired: false, + onInstalledFired: true, + onInstalledReason: "update", + }); + + yield extension.unload(); + + yield updated_addon.uninstall(); + yield promiseShutdownManager(); +}); + +add_task(function* test_should_fire_on_browser_update() { + const EXTENSION_ID = "test_runtime_on_installed_browser_update@tests.mozilla.org"; + + yield promiseStartupManager(); + + let extension = ExtensionTestUtils.loadExtension({ + useAddonManager: "permanent", + manifest: { + "version": "1.0", + "applications": { + "gecko": { + "id": EXTENSION_ID, + }, + }, + }, + background, + }); + + yield extension.startup(); + + yield expectEvents(extension, { + onStartupFired: false, + onInstalledFired: true, + onInstalledReason: "install", + }); + + let startupPromise = awaitEvent("ready"); + yield promiseRestartManager("1"); + extension.extension = yield startupPromise; + extension.attachListeners(); + + yield expectEvents(extension, { + onStartupFired: true, + onInstalledFired: false, + }); + + // Update the browser. + startupPromise = awaitEvent("ready"); + yield promiseRestartManager("2"); + extension.extension = yield startupPromise; + extension.attachListeners(); + + yield expectEvents(extension, { + onStartupFired: true, + onInstalledFired: true, + onInstalledReason: "browser_update", + }); + + // Restart the browser. + startupPromise = awaitEvent("ready"); + yield promiseRestartManager("2"); + extension.extension = yield startupPromise; + extension.attachListeners(); + + yield expectEvents(extension, { + onStartupFired: true, + onInstalledFired: false, + }); + + // Update the browser again. + startupPromise = awaitEvent("ready"); + yield promiseRestartManager("3"); + extension.extension = yield startupPromise; + extension.attachListeners(); + + yield expectEvents(extension, { + onStartupFired: true, + onInstalledFired: true, + onInstalledReason: "browser_update", + }); + + yield extension.unload(); + + yield promiseShutdownManager(); +}); + +add_task(function* test_should_not_fire_on_reload() { + const EXTENSION_ID = "test_runtime_on_installed_reload@tests.mozilla.org"; + + yield promiseStartupManager(); + + let extension = ExtensionTestUtils.loadExtension({ + useAddonManager: "permanent", + manifest: { + "version": "1.0", + "applications": { + "gecko": { + "id": EXTENSION_ID, + }, + }, + }, + background, + }); + + yield extension.startup(); + + yield expectEvents(extension, { + onStartupFired: false, + onInstalledFired: true, + onInstalledReason: "install", + }); + + let startupPromise = awaitEvent("ready"); + extension.sendMessage("reload-extension"); + extension.extension = yield startupPromise; + extension.attachListeners(); + + yield expectEvents(extension, { + onStartupFired: false, + onInstalledFired: false, + }); + + yield extension.unload(); + yield promiseShutdownManager(); +}); + +add_task(function* test_should_not_fire_on_restart() { + const EXTENSION_ID = "test_runtime_on_installed_restart@tests.mozilla.org"; + + yield promiseStartupManager(); + + let extension = ExtensionTestUtils.loadExtension({ + useAddonManager: "permanent", + manifest: { + "version": "1.0", + "applications": { + "gecko": { + "id": EXTENSION_ID, + }, + }, + }, + background, + }); + + yield extension.startup(); + + yield expectEvents(extension, { + onStartupFired: false, + onInstalledFired: true, + onInstalledReason: "install", + }); + + let addon = yield promiseAddonByID(EXTENSION_ID); + addon.userDisabled = true; + + let startupPromise = awaitEvent("ready"); + addon.userDisabled = false; + extension.extension = yield startupPromise; + extension.attachListeners(); + + yield expectEvents(extension, { + onStartupFired: false, + onInstalledFired: false, + }); + + yield extension.markUnloaded(); + yield promiseShutdownManager(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage.js new file mode 100644 index 000000000..fec8e13dd --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage.js @@ -0,0 +1,79 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* tabsSendMessageReply() { + function background() { + browser.runtime.onMessage.addListener((msg, sender, respond) => { + if (msg == "respond-now") { + respond(msg); + } else if (msg == "respond-soon") { + setTimeout(() => { respond(msg); }, 0); + return true; + } else if (msg == "respond-promise") { + return Promise.resolve(msg); + } else if (msg == "respond-never") { + return; + } else if (msg == "respond-error") { + return Promise.reject(new Error(msg)); + } else if (msg == "throw-error") { + throw new Error(msg); + } + }); + + browser.runtime.onMessage.addListener((msg, sender, respond) => { + if (msg == "respond-now") { + respond("hello"); + } else if (msg == "respond-now-2") { + respond(msg); + } + }); + + let childFrame = document.createElement("iframe"); + childFrame.src = "extensionpage.html"; + document.body.appendChild(childFrame); + } + + function senderScript() { + Promise.all([ + browser.runtime.sendMessage("respond-now"), + browser.runtime.sendMessage("respond-now-2"), + new Promise(resolve => browser.runtime.sendMessage("respond-soon", resolve)), + browser.runtime.sendMessage("respond-promise"), + browser.runtime.sendMessage("respond-never"), + new Promise(resolve => { + browser.runtime.sendMessage("respond-never", response => { resolve(response); }); + }), + + browser.runtime.sendMessage("respond-error").catch(error => Promise.resolve({error})), + browser.runtime.sendMessage("throw-error").catch(error => Promise.resolve({error})), + ]).then(([respondNow, respondNow2, respondSoon, respondPromise, respondNever, respondNever2, respondError, throwError]) => { + browser.test.assertEq("respond-now", respondNow, "Got the expected immediate response"); + browser.test.assertEq("respond-now-2", respondNow2, "Got the expected immediate response from the second listener"); + browser.test.assertEq("respond-soon", respondSoon, "Got the expected delayed response"); + browser.test.assertEq("respond-promise", respondPromise, "Got the expected promise response"); + browser.test.assertEq(undefined, respondNever, "Got the expected no-response resolution"); + browser.test.assertEq(undefined, respondNever2, "Got the expected no-response resolution"); + + browser.test.assertEq("respond-error", respondError.error.message, "Got the expected error response"); + browser.test.assertEq("throw-error", throwError.error.message, "Got the expected thrown error response"); + + browser.test.notifyPass("sendMessage"); + }).catch(e => { + browser.test.fail(`Error: ${e} :: ${e.stack}`); + browser.test.notifyFail("sendMessage"); + }); + } + + let extension = ExtensionTestUtils.loadExtension({ + background, + files: { + "senderScript.js": senderScript, + "extensionpage.html": ``, + }, + }); + + yield extension.startup(); + yield extension.awaitFinish("sendMessage"); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_errors.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_errors.js new file mode 100644 index 000000000..f1a8d5a36 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_errors.js @@ -0,0 +1,59 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_sendMessage_error() { + async function background() { + let circ = {}; + circ.circ = circ; + let testCases = [ + // [arguments, expected error string], + [[], "runtime.sendMessage's message argument is missing"], + [[null, null, null, null], "runtime.sendMessage's last argument is not a function"], + [[null, null, 1], "runtime.sendMessage's options argument is invalid"], + [[1, null, null], "runtime.sendMessage's extensionId argument is invalid"], + [[null, null, null, null, null], "runtime.sendMessage received too many arguments"], + + // Even when the parameters are accepted, we still expect an error + // because there is no onMessage listener. + [[null, null, null], "Could not establish connection. Receiving end does not exist."], + + // Structural cloning doesn't work with DOM but we fall back + // JSON serialization, so we don't expect another error. + [[null, location, null], "Could not establish connection. Receiving end does not exist."], + + // Structured cloning supports cyclic self-references. + [[null, [circ, location], null], "cyclic object value"], + // JSON serialization does not support cyclic references. + [[null, circ, null], "Could not establish connection. Receiving end does not exist."], + // (the last two tests shows whether sendMessage is implemented as structured cloning). + ]; + + // Repeat all tests with the undefined value instead of null. + for (let [args, expectedError] of testCases.slice()) { + args = args.map(arg => arg === null ? undefined : arg); + testCases.push([args, expectedError]); + } + + for (let [args, expectedError] of testCases) { + let description = `runtime.sendMessage(${args.map(String).join(", ")})`; + + await browser.test.assertRejects( + browser.runtime.sendMessage(...args), + expectedError, + `expected error message for ${description}`); + } + + browser.test.notifyPass("sendMessage parameter validation"); + } + let extensionData = { + background, + }; + + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + + yield extension.awaitFinish("sendMessage parameter validation"); + + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_no_receiver.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_no_receiver.js new file mode 100644 index 000000000..f906333d2 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_no_receiver.js @@ -0,0 +1,54 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_sendMessage_without_listener() { + async function background() { + await browser.test.assertRejects( + browser.runtime.sendMessage("msg"), + "Could not establish connection. Receiving end does not exist.", + "sendMessage callback was invoked"); + + browser.test.notifyPass("sendMessage callback was invoked"); + } + let extensionData = { + background, + }; + + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + + yield extension.awaitFinish("sendMessage callback was invoked"); + + yield extension.unload(); +}); + +add_task(function* test_chrome_sendMessage_without_listener() { + function background() { + /* globals chrome */ + browser.test.assertEq(null, chrome.runtime.lastError, "no lastError before call"); + let retval = chrome.runtime.sendMessage("msg"); + browser.test.assertEq(null, chrome.runtime.lastError, "no lastError after call"); + browser.test.assertEq(undefined, retval, "return value of chrome.runtime.sendMessage without callback"); + + let isAsyncCall = false; + retval = chrome.runtime.sendMessage("msg", reply => { + browser.test.assertEq(undefined, reply, "no reply"); + browser.test.assertTrue(isAsyncCall, "chrome.runtime.sendMessage's callback must be called asynchronously"); + browser.test.assertEq(undefined, retval, "return value of chrome.runtime.sendMessage with callback"); + browser.test.assertEq("Could not establish connection. Receiving end does not exist.", chrome.runtime.lastError.message); + browser.test.notifyPass("finished chrome.runtime.sendMessage"); + }); + isAsyncCall = true; + } + let extensionData = { + background, + }; + + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + + yield extension.awaitFinish("finished chrome.runtime.sendMessage"); + + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_self.js b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_self.js new file mode 100644 index 000000000..e4f5e951f --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_runtime_sendMessage_self.js @@ -0,0 +1,51 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ + +"use strict"; + +add_task(function* test_sendMessage_to_self_should_not_trigger_onMessage() { + async function background() { + browser.runtime.onMessage.addListener(msg => { + browser.test.assertEq("msg from child", msg); + browser.test.notifyPass("sendMessage did not call same-frame onMessage"); + }); + + browser.test.onMessage.addListener(msg => { + browser.test.assertEq("sendMessage with a listener in another frame", msg); + browser.runtime.sendMessage("should only reach another frame"); + }); + + await browser.test.assertRejects( + browser.runtime.sendMessage("should not trigger same-frame onMessage"), + "Could not establish connection. Receiving end does not exist."); + + let anotherFrame = document.createElement("iframe"); + anotherFrame.src = browser.extension.getURL("extensionpage.html"); + document.body.appendChild(anotherFrame); + } + + function lastScript() { + browser.runtime.onMessage.addListener(msg => { + browser.test.assertEq("should only reach another frame", msg); + browser.runtime.sendMessage("msg from child"); + }); + browser.test.sendMessage("sendMessage callback called"); + } + + let extensionData = { + background, + files: { + "lastScript.js": lastScript, + "extensionpage.html": ``, + }, + }; + + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + + yield extension.awaitMessage("sendMessage callback called"); + extension.sendMessage("sendMessage with a listener in another frame"); + yield extension.awaitFinish("sendMessage did not call same-frame onMessage"); + + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_schemas.js b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas.js new file mode 100644 index 000000000..d838be5b5 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas.js @@ -0,0 +1,1427 @@ +"use strict"; + +Components.utils.import("resource://gre/modules/Schemas.jsm"); +Components.utils.import("resource://gre/modules/BrowserUtils.jsm"); +Components.utils.import("resource://gre/modules/ExtensionCommon.jsm"); + +let {LocalAPIImplementation, SchemaAPIInterface} = ExtensionCommon; + +let json = [ + {namespace: "testing", + + properties: { + PROP1: {value: 20}, + prop2: {type: "string"}, + prop3: { + $ref: "submodule", + }, + prop4: { + $ref: "submodule", + unsupported: true, + }, + }, + + types: [ + { + id: "type1", + type: "string", + "enum": ["value1", "value2", "value3"], + }, + + { + id: "type2", + type: "object", + properties: { + prop1: {type: "integer"}, + prop2: {type: "array", items: {"$ref": "type1"}}, + }, + }, + + { + id: "basetype1", + type: "object", + properties: { + prop1: {type: "string"}, + }, + }, + + { + id: "basetype2", + choices: [ + {type: "integer"}, + ], + }, + + { + $extend: "basetype1", + properties: { + prop2: {type: "string"}, + }, + }, + + { + $extend: "basetype2", + choices: [ + {type: "string"}, + ], + }, + + { + id: "submodule", + type: "object", + functions: [ + { + name: "sub_foo", + type: "function", + parameters: [], + returns: "integer", + }, + ], + }, + ], + + functions: [ + { + name: "foo", + type: "function", + parameters: [ + {name: "arg1", type: "integer", optional: true, default: 99}, + {name: "arg2", type: "boolean", optional: true}, + ], + }, + + { + name: "bar", + type: "function", + parameters: [ + {name: "arg1", type: "integer", optional: true}, + {name: "arg2", type: "boolean"}, + ], + }, + + { + name: "baz", + type: "function", + parameters: [ + {name: "arg1", type: "object", properties: { + prop1: {type: "string"}, + prop2: {type: "integer", optional: true}, + prop3: {type: "integer", unsupported: true}, + }}, + ], + }, + + { + name: "qux", + type: "function", + parameters: [ + {name: "arg1", "$ref": "type1"}, + ], + }, + + { + name: "quack", + type: "function", + parameters: [ + {name: "arg1", "$ref": "type2"}, + ], + }, + + { + name: "quora", + type: "function", + parameters: [ + {name: "arg1", type: "function"}, + ], + }, + + { + name: "quileute", + type: "function", + parameters: [ + {name: "arg1", type: "integer", optional: true}, + {name: "arg2", type: "integer"}, + ], + }, + + { + name: "queets", + type: "function", + unsupported: true, + parameters: [], + }, + + { + name: "quintuplets", + type: "function", + parameters: [ + {name: "obj", type: "object", properties: [], additionalProperties: {type: "integer"}}, + ], + }, + + { + name: "quasar", + type: "function", + parameters: [ + {name: "abc", type: "object", properties: { + func: {type: "function", parameters: [ + {name: "x", type: "integer"}, + ]}, + }}, + ], + }, + + { + name: "quosimodo", + type: "function", + parameters: [ + {name: "xyz", type: "object", additionalProperties: {type: "any"}}, + ], + }, + + { + name: "patternprop", + type: "function", + parameters: [ + { + name: "obj", + type: "object", + properties: {"prop1": {type: "string", pattern: "^\\d+$"}}, + patternProperties: { + "(?i)^prop\\d+$": {type: "string"}, + "^foo\\d+$": {type: "string"}, + }, + }, + ], + }, + + { + name: "pattern", + type: "function", + parameters: [ + {name: "arg", type: "string", pattern: "(?i)^[0-9a-f]+$"}, + ], + }, + + { + name: "format", + type: "function", + parameters: [ + { + name: "arg", + type: "object", + properties: { + url: {type: "string", "format": "url", "optional": true}, + relativeUrl: {type: "string", "format": "relativeUrl", "optional": true}, + strictRelativeUrl: {type: "string", "format": "strictRelativeUrl", "optional": true}, + }, + }, + ], + }, + + { + name: "formatDate", + type: "function", + parameters: [ + { + name: "arg", + type: "object", + properties: { + date: {type: "string", format: "date", optional: true}, + }, + }, + ], + }, + + { + name: "deep", + type: "function", + parameters: [ + { + name: "arg", + type: "object", + properties: { + foo: { + type: "object", + properties: { + bar: { + type: "array", + items: { + type: "object", + properties: { + baz: { + type: "object", + properties: { + required: {type: "integer"}, + optional: {type: "string", optional: true}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + ], + }, + + { + name: "errors", + type: "function", + parameters: [ + { + name: "arg", + type: "object", + properties: { + warn: { + type: "string", + pattern: "^\\d+$", + optional: true, + onError: "warn", + }, + ignore: { + type: "string", + pattern: "^\\d+$", + optional: true, + onError: "ignore", + }, + default: { + type: "string", + pattern: "^\\d+$", + optional: true, + }, + }, + }, + ], + }, + + { + name: "localize", + type: "function", + parameters: [ + { + name: "arg", + type: "object", + properties: { + foo: {type: "string", "preprocess": "localize", "optional": true}, + bar: {type: "string", "optional": true}, + url: {type: "string", "preprocess": "localize", "format": "url", "optional": true}, + }, + }, + ], + }, + + { + name: "extended1", + type: "function", + parameters: [ + {name: "val", $ref: "basetype1"}, + ], + }, + + { + name: "extended2", + type: "function", + parameters: [ + {name: "val", $ref: "basetype2"}, + ], + }, + ], + + events: [ + { + name: "onFoo", + type: "function", + }, + + { + name: "onBar", + type: "function", + extraParameters: [{ + name: "filter", + type: "integer", + optional: true, + default: 1, + }], + }, + ], + }, + { + namespace: "foreign", + properties: { + foreignRef: {$ref: "testing.submodule"}, + }, + }, + { + namespace: "inject", + properties: { + PROP1: {value: "should inject"}, + }, + }, + { + namespace: "do-not-inject", + properties: { + PROP1: {value: "should not inject"}, + }, + }, +]; + +let tallied = null; + +function tally(kind, ns, name, args) { + tallied = [kind, ns, name, args]; +} + +function verify(...args) { + do_check_eq(JSON.stringify(tallied), JSON.stringify(args)); + tallied = null; +} + +let talliedErrors = []; + +function checkErrors(errors) { + do_check_eq(talliedErrors.length, errors.length, "Got expected number of errors"); + for (let [i, error] of errors.entries()) { + do_check_true(i in talliedErrors && talliedErrors[i].includes(error), + `${JSON.stringify(error)} is a substring of error ${JSON.stringify(talliedErrors[i])}`); + } + + talliedErrors.length = 0; +} + +let permissions = new Set(); + +class TallyingAPIImplementation extends SchemaAPIInterface { + constructor(namespace, name) { + super(); + this.namespace = namespace; + this.name = name; + } + + callFunction(args) { + tally("call", this.namespace, this.name, args); + } + + callFunctionNoReturn(args) { + tally("call", this.namespace, this.name, args); + } + + getProperty() { + tally("get", this.namespace, this.name); + } + + setProperty(value) { + tally("set", this.namespace, this.name, value); + } + + addListener(listener, args) { + tally("addListener", this.namespace, this.name, [listener, args]); + } + + removeListener(listener) { + tally("removeListener", this.namespace, this.name, [listener]); + } + + hasListener(listener) { + tally("hasListener", this.namespace, this.name, [listener]); + } +} + +let wrapper = { + url: "moz-extension://b66e3509-cdb3-44f6-8eb8-c8b39b3a1d27/", + + checkLoadURL(url) { + return !url.startsWith("chrome:"); + }, + + preprocessors: { + localize(value, context) { + return value.replace(/__MSG_(.*?)__/g, (m0, m1) => `${m1.toUpperCase()}`); + }, + }, + + logError(message) { + talliedErrors.push(message); + }, + + hasPermission(permission) { + return permissions.has(permission); + }, + + shouldInject(ns) { + return ns != "do-not-inject"; + }, + + getImplementation(namespace, name) { + return new TallyingAPIImplementation(namespace, name); + }, +}; + +add_task(function* () { + let url = "data:," + JSON.stringify(json); + yield Schemas.load(url); + + let root = {}; + tallied = null; + Schemas.inject(root, wrapper); + do_check_eq(tallied, null); + + do_check_eq(root.testing.PROP1, 20, "simple value property"); + do_check_eq(root.testing.type1.VALUE1, "value1", "enum type"); + do_check_eq(root.testing.type1.VALUE2, "value2", "enum type"); + + do_check_eq("inject" in root, true, "namespace 'inject' should be injected"); + do_check_eq("do-not-inject" in root, false, "namespace 'do-not-inject' should not be injected"); + + root.testing.foo(11, true); + verify("call", "testing", "foo", [11, true]); + + root.testing.foo(true); + verify("call", "testing", "foo", [99, true]); + + root.testing.foo(null, true); + verify("call", "testing", "foo", [99, true]); + + root.testing.foo(undefined, true); + verify("call", "testing", "foo", [99, true]); + + root.testing.foo(11); + verify("call", "testing", "foo", [11, null]); + + Assert.throws(() => root.testing.bar(11), + /Incorrect argument types/, + "should throw without required arg"); + + Assert.throws(() => root.testing.bar(11, true, 10), + /Incorrect argument types/, + "should throw with too many arguments"); + + root.testing.bar(true); + verify("call", "testing", "bar", [null, true]); + + root.testing.baz({prop1: "hello", prop2: 22}); + verify("call", "testing", "baz", [{prop1: "hello", prop2: 22}]); + + root.testing.baz({prop1: "hello"}); + verify("call", "testing", "baz", [{prop1: "hello", prop2: null}]); + + root.testing.baz({prop1: "hello", prop2: null}); + verify("call", "testing", "baz", [{prop1: "hello", prop2: null}]); + + Assert.throws(() => root.testing.baz({prop2: 12}), + /Property "prop1" is required/, + "should throw without required property"); + + Assert.throws(() => root.testing.baz({prop1: "hi", prop3: 12}), + /Property "prop3" is unsupported by Firefox/, + "should throw with unsupported property"); + + Assert.throws(() => root.testing.baz({prop1: "hi", prop4: 12}), + /Unexpected property "prop4"/, + "should throw with unexpected property"); + + Assert.throws(() => root.testing.baz({prop1: 12}), + /Expected string instead of 12/, + "should throw with wrong type"); + + root.testing.qux("value2"); + verify("call", "testing", "qux", ["value2"]); + + Assert.throws(() => root.testing.qux("value4"), + /Invalid enumeration value "value4"/, + "should throw for invalid enum value"); + + root.testing.quack({prop1: 12, prop2: ["value1", "value3"]}); + verify("call", "testing", "quack", [{prop1: 12, prop2: ["value1", "value3"]}]); + + Assert.throws(() => root.testing.quack({prop1: 12, prop2: ["value1", "value3", "value4"]}), + /Invalid enumeration value "value4"/, + "should throw for invalid array type"); + + function f() {} + root.testing.quora(f); + do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["call", "testing", "quora"])); + do_check_eq(tallied[3][0], f); + tallied = null; + + let g = () => 0; + root.testing.quora(g); + do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["call", "testing", "quora"])); + do_check_eq(tallied[3][0], g); + tallied = null; + + root.testing.quileute(10); + verify("call", "testing", "quileute", [null, 10]); + + Assert.throws(() => root.testing.queets(), + /queets is not a function/, + "should throw for unsupported functions"); + + root.testing.quintuplets({a: 10, b: 20, c: 30}); + verify("call", "testing", "quintuplets", [{a: 10, b: 20, c: 30}]); + + Assert.throws(() => root.testing.quintuplets({a: 10, b: 20, c: 30, d: "hi"}), + /Expected integer instead of "hi"/, + "should throw for wrong additionalProperties type"); + + root.testing.quasar({func: f}); + do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["call", "testing", "quasar"])); + do_check_eq(tallied[3][0].func, f); + tallied = null; + + root.testing.quosimodo({a: 10, b: 20, c: 30}); + verify("call", "testing", "quosimodo", [{a: 10, b: 20, c: 30}]); + tallied = null; + + Assert.throws(() => root.testing.quosimodo(10), + /Incorrect argument types/, + "should throw for wrong type"); + + root.testing.patternprop({prop1: "12", prop2: "42", Prop3: "43", foo1: "x"}); + verify("call", "testing", "patternprop", [{prop1: "12", prop2: "42", Prop3: "43", foo1: "x"}]); + tallied = null; + + root.testing.patternprop({prop1: "12"}); + verify("call", "testing", "patternprop", [{prop1: "12"}]); + tallied = null; + + Assert.throws(() => root.testing.patternprop({prop1: "12", foo1: null}), + /Expected string instead of null/, + "should throw for wrong property type"); + + Assert.throws(() => root.testing.patternprop({prop1: "xx", prop2: "yy"}), + /String "xx" must match \/\^\\d\+\$\//, + "should throw for wrong property type"); + + Assert.throws(() => root.testing.patternprop({prop1: "12", prop2: 42}), + /Expected string instead of 42/, + "should throw for wrong property type"); + + Assert.throws(() => root.testing.patternprop({prop1: "12", prop2: null}), + /Expected string instead of null/, + "should throw for wrong property type"); + + Assert.throws(() => root.testing.patternprop({prop1: "12", propx: "42"}), + /Unexpected property "propx"/, + "should throw for unexpected property"); + + Assert.throws(() => root.testing.patternprop({prop1: "12", Foo1: "x"}), + /Unexpected property "Foo1"/, + "should throw for unexpected property"); + + root.testing.pattern("DEADbeef"); + verify("call", "testing", "pattern", ["DEADbeef"]); + tallied = null; + + Assert.throws(() => root.testing.pattern("DEADcow"), + /String "DEADcow" must match \/\^\[0-9a-f\]\+\$\/i/, + "should throw for non-match"); + + root.testing.format({url: "http://foo/bar", + relativeUrl: "http://foo/bar"}); + verify("call", "testing", "format", [{url: "http://foo/bar", + relativeUrl: "http://foo/bar", + strictRelativeUrl: null}]); + tallied = null; + + root.testing.format({relativeUrl: "foo.html", strictRelativeUrl: "foo.html"}); + verify("call", "testing", "format", [{url: null, + relativeUrl: `${wrapper.url}foo.html`, + strictRelativeUrl: `${wrapper.url}foo.html`}]); + tallied = null; + + for (let format of ["url", "relativeUrl"]) { + Assert.throws(() => root.testing.format({[format]: "chrome://foo/content/"}), + /Access denied/, + "should throw for access denied"); + } + + for (let urlString of ["//foo.html", "http://foo/bar.html"]) { + Assert.throws(() => root.testing.format({strictRelativeUrl: urlString}), + /must be a relative URL/, + "should throw for non-relative URL"); + } + + const dates = [ + "2016-03-04", + "2016-03-04T08:00:00Z", + "2016-03-04T08:00:00.000Z", + "2016-03-04T08:00:00-08:00", + "2016-03-04T08:00:00.000-08:00", + "2016-03-04T08:00:00+08:00", + "2016-03-04T08:00:00.000+08:00", + "2016-03-04T08:00:00+0800", + "2016-03-04T08:00:00-0800", + ]; + dates.forEach(str => { + root.testing.formatDate({date: str}); + verify("call", "testing", "formatDate", [{date: str}]); + }); + + // Make sure that a trivial change to a valid date invalidates it. + dates.forEach(str => { + Assert.throws(() => root.testing.formatDate({date: "0" + str}), + /Invalid date string/, + "should throw for invalid iso date string"); + Assert.throws(() => root.testing.formatDate({date: str + "0"}), + /Invalid date string/, + "should throw for invalid iso date string"); + }); + + const badDates = [ + "I do not look anything like a date string", + "2016-99-99", + "2016-03-04T25:00:00Z", + ]; + badDates.forEach(str => { + Assert.throws(() => root.testing.formatDate({date: str}), + /Invalid date string/, + "should throw for invalid iso date string"); + }); + + root.testing.deep({foo: {bar: [{baz: {required: 12, optional: "42"}}]}}); + verify("call", "testing", "deep", [{foo: {bar: [{baz: {required: 12, optional: "42"}}]}}]); + tallied = null; + + Assert.throws(() => root.testing.deep({foo: {bar: [{baz: {optional: "42"}}]}}), + /Type error for parameter arg \(Error processing foo\.bar\.0\.baz: Property "required" is required\) for testing\.deep/, + "should throw with the correct object path"); + + Assert.throws(() => root.testing.deep({foo: {bar: [{baz: {required: 12, optional: 42}}]}}), + /Type error for parameter arg \(Error processing foo\.bar\.0\.baz\.optional: Expected string instead of 42\) for testing\.deep/, + "should throw with the correct object path"); + + + talliedErrors.length = 0; + + root.testing.errors({warn: "0123", ignore: "0123", default: "0123"}); + verify("call", "testing", "errors", [{warn: "0123", ignore: "0123", default: "0123"}]); + checkErrors([]); + + root.testing.errors({warn: "0123", ignore: "x123", default: "0123"}); + verify("call", "testing", "errors", [{warn: "0123", ignore: null, default: "0123"}]); + checkErrors([]); + + root.testing.errors({warn: "x123", ignore: "0123", default: "0123"}); + verify("call", "testing", "errors", [{warn: null, ignore: "0123", default: "0123"}]); + checkErrors([ + 'String "x123" must match /^\\d+$/', + ]); + + + root.testing.onFoo.addListener(f); + do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["addListener", "testing", "onFoo"])); + do_check_eq(tallied[3][0], f); + do_check_eq(JSON.stringify(tallied[3][1]), JSON.stringify([])); + tallied = null; + + root.testing.onFoo.removeListener(f); + do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["removeListener", "testing", "onFoo"])); + do_check_eq(tallied[3][0], f); + tallied = null; + + root.testing.onFoo.hasListener(f); + do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["hasListener", "testing", "onFoo"])); + do_check_eq(tallied[3][0], f); + tallied = null; + + Assert.throws(() => root.testing.onFoo.addListener(10), + /Invalid listener/, + "addListener with non-function should throw"); + + root.testing.onBar.addListener(f, 10); + do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["addListener", "testing", "onBar"])); + do_check_eq(tallied[3][0], f); + do_check_eq(JSON.stringify(tallied[3][1]), JSON.stringify([10])); + tallied = null; + + root.testing.onBar.addListener(f); + do_check_eq(JSON.stringify(tallied.slice(0, -1)), JSON.stringify(["addListener", "testing", "onBar"])); + do_check_eq(tallied[3][0], f); + do_check_eq(JSON.stringify(tallied[3][1]), JSON.stringify([1])); + tallied = null; + + Assert.throws(() => root.testing.onBar.addListener(f, "hi"), + /Incorrect argument types/, + "addListener with wrong extra parameter should throw"); + + let target = {prop1: 12, prop2: ["value1", "value3"]}; + let proxy = new Proxy(target, {}); + Assert.throws(() => root.testing.quack(proxy), + /Expected a plain JavaScript object, got a Proxy/, + "should throw when passing a Proxy"); + + if (Symbol.toStringTag) { + let stringTarget = {prop1: 12, prop2: ["value1", "value3"]}; + stringTarget[Symbol.toStringTag] = () => "[object Object]"; + let stringProxy = new Proxy(stringTarget, {}); + Assert.throws(() => root.testing.quack(stringProxy), + /Expected a plain JavaScript object, got a Proxy/, + "should throw when passing a Proxy"); + } + + + root.testing.localize({foo: "__MSG_foo__", bar: "__MSG_foo__", url: "__MSG_http://example.com/__"}); + verify("call", "testing", "localize", [{foo: "FOO", bar: "__MSG_foo__", url: "http://example.com/"}]); + tallied = null; + + + Assert.throws(() => root.testing.localize({url: "__MSG_/foo/bar__"}), + /\/FOO\/BAR is not a valid URL\./, + "should throw for invalid URL"); + + + root.testing.extended1({prop1: "foo", prop2: "bar"}); + verify("call", "testing", "extended1", [{prop1: "foo", prop2: "bar"}]); + tallied = null; + + Assert.throws(() => root.testing.extended1({prop1: "foo", prop2: 12}), + /Expected string instead of 12/, + "should throw for wrong property type"); + + Assert.throws(() => root.testing.extended1({prop1: "foo"}), + /Property "prop2" is required/, + "should throw for missing property"); + + Assert.throws(() => root.testing.extended1({prop1: "foo", prop2: "bar", prop3: "xxx"}), + /Unexpected property "prop3"/, + "should throw for extra property"); + + + root.testing.extended2("foo"); + verify("call", "testing", "extended2", ["foo"]); + tallied = null; + + root.testing.extended2(12); + verify("call", "testing", "extended2", [12]); + tallied = null; + + Assert.throws(() => root.testing.extended2(true), + /Incorrect argument types/, + "should throw for wrong argument type"); + + root.testing.prop3.sub_foo(); + verify("call", "testing.prop3", "sub_foo", []); + tallied = null; + + Assert.throws(() => root.testing.prop4.sub_foo(), + /root.testing.prop4 is undefined/, + "should throw for unsupported submodule"); + + root.foreign.foreignRef.sub_foo(); + verify("call", "foreign.foreignRef", "sub_foo", []); + tallied = null; +}); + +let deprecatedJson = [ + {namespace: "deprecated", + + properties: { + accessor: { + type: "string", + writable: true, + deprecated: "This is not the property you are looking for", + }, + }, + + types: [ + { + "id": "Type", + "type": "string", + }, + ], + + functions: [ + { + name: "property", + type: "function", + parameters: [ + { + name: "arg", + type: "object", + properties: { + foo: { + type: "string", + }, + }, + additionalProperties: { + type: "any", + deprecated: "Unknown property", + }, + }, + ], + }, + + { + name: "value", + type: "function", + parameters: [ + { + name: "arg", + choices: [ + { + type: "integer", + }, + { + type: "string", + deprecated: "Please use an integer, not ${value}", + }, + ], + }, + ], + }, + + { + name: "choices", + type: "function", + parameters: [ + { + name: "arg", + deprecated: "You have no choices", + choices: [ + { + type: "integer", + }, + ], + }, + ], + }, + + { + name: "ref", + type: "function", + parameters: [ + { + name: "arg", + choices: [ + { + $ref: "Type", + deprecated: "Deprecated alias", + }, + ], + }, + ], + }, + + { + name: "method", + type: "function", + deprecated: "Do not call this method", + parameters: [ + ], + }, + ], + + events: [ + { + name: "onDeprecated", + type: "function", + deprecated: "This event does not work", + }, + ], + }, +]; + +add_task(function* testDeprecation() { + let url = "data:," + JSON.stringify(deprecatedJson); + yield Schemas.load(url); + + let root = {}; + Schemas.inject(root, wrapper); + + talliedErrors.length = 0; + + + root.deprecated.property({foo: "bar", xxx: "any", yyy: "property"}); + verify("call", "deprecated", "property", [{foo: "bar", xxx: "any", yyy: "property"}]); + checkErrors([ + "Error processing xxx: Unknown property", + "Error processing yyy: Unknown property", + ]); + + root.deprecated.value(12); + verify("call", "deprecated", "value", [12]); + checkErrors([]); + + root.deprecated.value("12"); + verify("call", "deprecated", "value", ["12"]); + checkErrors(["Please use an integer, not \"12\""]); + + root.deprecated.choices(12); + verify("call", "deprecated", "choices", [12]); + checkErrors(["You have no choices"]); + + root.deprecated.ref("12"); + verify("call", "deprecated", "ref", ["12"]); + checkErrors(["Deprecated alias"]); + + root.deprecated.method(); + verify("call", "deprecated", "method", []); + checkErrors(["Do not call this method"]); + + + void root.deprecated.accessor; + verify("get", "deprecated", "accessor", null); + checkErrors(["This is not the property you are looking for"]); + + root.deprecated.accessor = "x"; + verify("set", "deprecated", "accessor", "x"); + checkErrors(["This is not the property you are looking for"]); + + + root.deprecated.onDeprecated.addListener(() => {}); + checkErrors(["This event does not work"]); + + root.deprecated.onDeprecated.removeListener(() => {}); + checkErrors(["This event does not work"]); + + root.deprecated.onDeprecated.hasListener(() => {}); + checkErrors(["This event does not work"]); +}); + + +let choicesJson = [ + {namespace: "choices", + + types: [ + ], + + functions: [ + { + name: "meh", + type: "function", + parameters: [ + { + name: "arg", + choices: [ + { + type: "string", + enum: ["foo", "bar", "baz"], + }, + { + type: "string", + pattern: "florg.*meh", + }, + { + type: "integer", + minimum: 12, + maximum: 42, + }, + ], + }, + ], + }, + + { + name: "foo", + type: "function", + parameters: [ + { + name: "arg", + choices: [ + { + type: "object", + properties: { + blurg: { + type: "string", + unsupported: true, + optional: true, + }, + }, + additionalProperties: { + type: "string", + }, + }, + { + type: "string", + }, + { + type: "array", + minItems: 2, + maxItems: 3, + items: { + type: "integer", + }, + }, + ], + }, + ], + }, + + { + name: "bar", + type: "function", + parameters: [ + { + name: "arg", + choices: [ + { + type: "object", + properties: { + baz: { + type: "string", + }, + }, + }, + { + type: "array", + items: { + type: "integer", + }, + }, + ], + }, + ], + }, + ]}, +]; + +add_task(function* testChoices() { + let url = "data:," + JSON.stringify(choicesJson); + yield Schemas.load(url); + + let root = {}; + Schemas.inject(root, wrapper); + + talliedErrors.length = 0; + + Assert.throws(() => root.choices.meh("frog"), + /Value must either: be one of \["foo", "bar", "baz"\], match the pattern \/florg\.\*meh\/, or be an integer value/); + + Assert.throws(() => root.choices.meh(4), + /be a string value, or be at least 12/); + + Assert.throws(() => root.choices.meh(43), + /be a string value, or be no greater than 42/); + + + Assert.throws(() => root.choices.foo([]), + /be an object value, be a string value, or have at least 2 items/); + + Assert.throws(() => root.choices.foo([1, 2, 3, 4]), + /be an object value, be a string value, or have at most 3 items/); + + Assert.throws(() => root.choices.foo({foo: 12}), + /.foo must be a string value, be a string value, or be an array value/); + + Assert.throws(() => root.choices.foo({blurg: "foo"}), + /not contain an unsupported "blurg" property, be a string value, or be an array value/); + + + Assert.throws(() => root.choices.bar({}), + /contain the required "baz" property, or be an array value/); + + Assert.throws(() => root.choices.bar({baz: "x", quux: "y"}), + /not contain an unexpected "quux" property, or be an array value/); + + Assert.throws(() => root.choices.bar({baz: "x", quux: "y", foo: "z"}), + /not contain the unexpected properties \[foo, quux\], or be an array value/); +}); + + +let permissionsJson = [ + {namespace: "noPerms", + + types: [], + + functions: [ + { + name: "noPerms", + type: "function", + parameters: [], + }, + + { + name: "fooPerm", + type: "function", + permissions: ["foo"], + parameters: [], + }, + ]}, + + {namespace: "fooPerm", + + permissions: ["foo"], + + types: [], + + functions: [ + { + name: "noPerms", + type: "function", + parameters: [], + }, + + { + name: "fooBarPerm", + type: "function", + permissions: ["foo.bar"], + parameters: [], + }, + ]}, +]; + +add_task(function* testPermissions() { + let url = "data:," + JSON.stringify(permissionsJson); + yield Schemas.load(url); + + let root = {}; + Schemas.inject(root, wrapper); + + equal(typeof root.noPerms, "object", "noPerms namespace should exist"); + equal(typeof root.noPerms.noPerms, "function", "noPerms.noPerms method should exist"); + + ok(!("fooPerm" in root.noPerms), "noPerms.fooPerm should not method exist"); + + ok(!("fooPerm" in root), "fooPerm namespace should not exist"); + + + do_print('Add "foo" permission'); + permissions.add("foo"); + + root = {}; + Schemas.inject(root, wrapper); + + equal(typeof root.noPerms, "object", "noPerms namespace should exist"); + equal(typeof root.noPerms.noPerms, "function", "noPerms.noPerms method should exist"); + equal(typeof root.noPerms.fooPerm, "function", "noPerms.fooPerm method should exist"); + + equal(typeof root.fooPerm, "object", "fooPerm namespace should exist"); + equal(typeof root.fooPerm.noPerms, "function", "noPerms.noPerms method should exist"); + + ok(!("fooBarPerm" in root.fooPerm), "fooPerm.fooBarPerm method should not exist"); + + + do_print('Add "foo.bar" permission'); + permissions.add("foo.bar"); + + root = {}; + Schemas.inject(root, wrapper); + + equal(typeof root.noPerms, "object", "noPerms namespace should exist"); + equal(typeof root.noPerms.noPerms, "function", "noPerms.noPerms method should exist"); + equal(typeof root.noPerms.fooPerm, "function", "noPerms.fooPerm method should exist"); + + equal(typeof root.fooPerm, "object", "fooPerm namespace should exist"); + equal(typeof root.fooPerm.noPerms, "function", "noPerms.noPerms method should exist"); + equal(typeof root.fooPerm.fooBarPerm, "function", "noPerms.fooBarPerm method should exist"); +}); + +let nestedNamespaceJson = [ + { + "namespace": "nested.namespace", + "types": [ + { + "id": "CustomType", + "type": "object", + "events": [ + { + "name": "onEvent", + }, + ], + "properties": { + "url": { + "type": "string", + }, + }, + "functions": [ + { + "name": "functionOnCustomType", + "type": "function", + "parameters": [ + { + "name": "title", + "type": "string", + }, + ], + }, + ], + }, + ], + "properties": { + "instanceOfCustomType": { + "$ref": "CustomType", + }, + }, + "functions": [ + { + "name": "create", + "type": "function", + "parameters": [ + { + "name": "title", + "type": "string", + }, + ], + }, + ], + }, +]; + +add_task(function* testNestedNamespace() { + let url = "data:," + JSON.stringify(nestedNamespaceJson); + + yield Schemas.load(url); + + let root = {}; + Schemas.inject(root, wrapper); + + talliedErrors.length = 0; + + ok(root.nested, "The root object contains the first namespace level"); + ok(root.nested.namespace, "The first level object contains the second namespace level"); + + ok(root.nested.namespace.create, "Got the expected function in the nested namespace"); + do_check_eq(typeof root.nested.namespace.create, "function", + "The property is a function as expected"); + + let {instanceOfCustomType} = root.nested.namespace; + + ok(instanceOfCustomType, + "Got the expected instance of the CustomType defined in the schema"); + ok(instanceOfCustomType.functionOnCustomType, + "Got the expected method in the CustomType instance"); + + // TODO: test support events and properties in a SubModuleType defined in the schema, + // once implemented, e.g.: + // + // ok(instanceOfCustomType.url, + // "Got the expected property defined in the CustomType instance) + // + // ok(instanceOfCustomType.onEvent && + // instanceOfCustomType.onEvent.addListener && + // typeof instanceOfCustomType.onEvent.addListener == "function", + // "Got the expected event defined in the CustomType instance"); +}); + +add_task(function* testLocalAPIImplementation() { + let countGet2 = 0; + let countProp3 = 0; + let countProp3SubFoo = 0; + + let testingApiObj = { + get PROP1() { + // PROP1 is a schema-defined constant. + throw new Error("Unexpected get PROP1"); + }, + get prop2() { + ++countGet2; + return "prop2 val"; + }, + get prop3() { + throw new Error("Unexpected get prop3"); + }, + set prop3(v) { + // prop3 is a submodule, defined as a function, so the API should not pass + // through assignment to prop3. + throw new Error("Unexpected set prop3"); + }, + }; + let submoduleApiObj = { + get sub_foo() { + ++countProp3; + return () => { + return ++countProp3SubFoo; + }; + }, + }; + + let localWrapper = { + shouldInject(ns) { + return ns == "testing" || ns == "testing.prop3"; + }, + getImplementation(ns, name) { + do_check_true(ns == "testing" || ns == "testing.prop3"); + if (ns == "testing.prop3" && name == "sub_foo") { + // It is fine to use `null` here because we don't call async functions. + return new LocalAPIImplementation(submoduleApiObj, name, null); + } + // It is fine to use `null` here because we don't call async functions. + return new LocalAPIImplementation(testingApiObj, name, null); + }, + }; + + let root = {}; + Schemas.inject(root, localWrapper); + do_check_eq(countGet2, 0); + do_check_eq(countProp3, 0); + do_check_eq(countProp3SubFoo, 0); + + do_check_eq(root.testing.PROP1, 20); + + do_check_eq(root.testing.prop2, "prop2 val"); + do_check_eq(countGet2, 1); + + do_check_eq(root.testing.prop2, "prop2 val"); + do_check_eq(countGet2, 2); + + do_print(JSON.stringify(root.testing)); + do_check_eq(root.testing.prop3.sub_foo(), 1); + do_check_eq(countProp3, 1); + do_check_eq(countProp3SubFoo, 1); + + do_check_eq(root.testing.prop3.sub_foo(), 2); + do_check_eq(countProp3, 2); + do_check_eq(countProp3SubFoo, 2); + + root.testing.prop3.sub_foo = () => { return "overwritten"; }; + do_check_eq(root.testing.prop3.sub_foo(), "overwritten"); + + root.testing.prop3 = {sub_foo() { return "overwritten again"; }}; + do_check_eq(root.testing.prop3.sub_foo(), "overwritten again"); + do_check_eq(countProp3SubFoo, 2); +}); + + +let defaultsJson = [ + {namespace: "defaultsJson", + + types: [], + + functions: [ + { + name: "defaultFoo", + type: "function", + parameters: [ + {name: "arg", type: "object", optional: true, properties: { + prop1: {type: "integer", optional: true}, + }, default: {prop1: 1}}, + ], + returns: { + type: "object", + }, + }, + ]}, +]; + +add_task(function* testDefaults() { + let url = "data:," + JSON.stringify(defaultsJson); + yield Schemas.load(url); + + let testingApiObj = { + defaultFoo: function(arg) { + if (Object.keys(arg) != "prop1") { + throw new Error(`Received the expected default object, default: ${JSON.stringify(arg)}`); + } + arg.newProp = 1; + return arg; + }, + }; + + let localWrapper = { + shouldInject(ns) { + return true; + }, + getImplementation(ns, name) { + return new LocalAPIImplementation(testingApiObj, name, null); + }, + }; + + let root = {}; + Schemas.inject(root, localWrapper); + + deepEqual(root.defaultsJson.defaultFoo(), {prop1: 1, newProp: 1}); + deepEqual(root.defaultsJson.defaultFoo({prop1: 2}), {prop1: 2, newProp: 1}); + deepEqual(root.defaultsJson.defaultFoo(), {prop1: 1, newProp: 1}); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_allowed_contexts.js b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_allowed_contexts.js new file mode 100644 index 000000000..606459764 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_allowed_contexts.js @@ -0,0 +1,147 @@ +"use strict"; + +Components.utils.import("resource://gre/modules/Schemas.jsm"); + +let schemaJson = [ + { + namespace: "noAllowedContexts", + properties: { + prop1: {type: "object"}, + prop2: {type: "object", allowedContexts: ["test_zero", "test_one"]}, + prop3: {type: "number", value: 1}, + prop4: {type: "number", value: 1, allowedContexts: ["numeric_one"]}, + }, + }, + { + namespace: "defaultContexts", + defaultContexts: ["test_two"], + properties: { + prop1: {type: "object"}, + prop2: {type: "object", allowedContexts: ["test_three"]}, + prop3: {type: "number", value: 1}, + prop4: {type: "number", value: 1, allowedContexts: ["numeric_two"]}, + }, + }, + { + namespace: "withAllowedContexts", + allowedContexts: ["test_four"], + properties: { + prop1: {type: "object"}, + prop2: {type: "object", allowedContexts: ["test_five"]}, + prop3: {type: "number", value: 1}, + prop4: {type: "number", value: 1, allowedContexts: ["numeric_three"]}, + }, + }, + { + namespace: "withAllowedContextsAndDefault", + allowedContexts: ["test_six"], + defaultContexts: ["test_seven"], + properties: { + prop1: {type: "object"}, + prop2: {type: "object", allowedContexts: ["test_eight"]}, + prop3: {type: "number", value: 1}, + prop4: {type: "number", value: 1, allowedContexts: ["numeric_four"]}, + }, + }, + { + namespace: "with_submodule", + defaultContexts: ["test_nine"], + types: [{ + id: "subtype", + type: "object", + functions: [{ + name: "noAllowedContexts", + type: "function", + parameters: [], + }, { + name: "allowedContexts", + allowedContexts: ["test_ten"], + type: "function", + parameters: [], + }], + }], + properties: { + prop1: {$ref: "subtype"}, + prop2: {$ref: "subtype", allowedContexts: ["test_eleven"]}, + }, + }, +]; +add_task(function* testRestrictions() { + let url = "data:," + JSON.stringify(schemaJson); + yield Schemas.load(url); + let results = {}; + let localWrapper = { + shouldInject(ns, name, allowedContexts) { + name = name === null ? ns : ns + "." + name; + results[name] = allowedContexts.join(","); + return true; + }, + getImplementation() { + // The actual implementation is not significant for this test. + // Let's take this opportunity to see if schema generation is free of + // exceptions even when somehow getImplementation does not return an + // implementation. + }, + }; + + let root = {}; + Schemas.inject(root, localWrapper); + + function verify(path, expected) { + let obj = root; + for (let thing of path.split(".")) { + try { + obj = obj[thing]; + } catch (e) { + // Blech. + } + } + + let result = results[path]; + equal(result, expected); + } + + verify("noAllowedContexts", ""); + verify("noAllowedContexts.prop1", ""); + verify("noAllowedContexts.prop2", "test_zero,test_one"); + verify("noAllowedContexts.prop3", ""); + verify("noAllowedContexts.prop4", "numeric_one"); + + verify("defaultContexts", ""); + verify("defaultContexts.prop1", "test_two"); + verify("defaultContexts.prop2", "test_three"); + verify("defaultContexts.prop3", "test_two"); + verify("defaultContexts.prop4", "numeric_two"); + + verify("withAllowedContexts", "test_four"); + verify("withAllowedContexts.prop1", ""); + verify("withAllowedContexts.prop2", "test_five"); + verify("withAllowedContexts.prop3", ""); + verify("withAllowedContexts.prop4", "numeric_three"); + + verify("withAllowedContextsAndDefault", "test_six"); + verify("withAllowedContextsAndDefault.prop1", "test_seven"); + verify("withAllowedContextsAndDefault.prop2", "test_eight"); + verify("withAllowedContextsAndDefault.prop3", "test_seven"); + verify("withAllowedContextsAndDefault.prop4", "numeric_four"); + + verify("with_submodule", ""); + verify("with_submodule.prop1", "test_nine"); + verify("with_submodule.prop1.noAllowedContexts", "test_nine"); + verify("with_submodule.prop1.allowedContexts", "test_ten"); + verify("with_submodule.prop2", "test_eleven"); + // Note: test_nine inherits allowed contexts from the namespace, not from + // submodule. There is no "defaultContexts" for submodule types to not + // complicate things. + verify("with_submodule.prop1.noAllowedContexts", "test_nine"); + verify("with_submodule.prop1.allowedContexts", "test_ten"); + + // This is a constant, so it does not matter that getImplementation does not + // return an implementation since the API injector should take care of it. + equal(root.noAllowedContexts.prop3, 1); + + Assert.throws(() => root.noAllowedContexts.prop1, + /undefined/, + "Should throw when the implementation is absent."); +}); + diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_api_injection.js b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_api_injection.js new file mode 100644 index 000000000..36d88d722 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_api_injection.js @@ -0,0 +1,102 @@ +"use strict"; + +Components.utils.import("resource://gre/modules/ExtensionCommon.jsm"); +Components.utils.import("resource://gre/modules/Schemas.jsm"); + +let { + BaseContext, + SchemaAPIManager, +} = ExtensionCommon; + +let nestedNamespaceJson = [ + { + "namespace": "backgroundAPI.testnamespace", + "functions": [ + { + "name": "create", + "type": "function", + "parameters": [ + { + "name": "title", + "type": "string", + }, + ], + "returns": { + "type": "string", + }, + }, + ], + }, + { + "namespace": "noBackgroundAPI.testnamespace", + "functions": [ + { + "name": "create", + "type": "function", + "parameters": [ + { + "name": "title", + "type": "string", + }, + ], + }, + ], + }, +]; + +let global = this; +class StubContext extends BaseContext { + constructor() { + let fakeExtension = {id: "test@web.extension"}; + super("addon_child", fakeExtension); + this.sandbox = Cu.Sandbox(global); + this.viewType = "background"; + } + + get cloneScope() { + return this.sandbox; + } +} + +add_task(function* testSchemaAPIInjection() { + let url = "data:," + JSON.stringify(nestedNamespaceJson); + + // Load the schema of the fake APIs. + yield Schemas.load(url); + + let apiManager = new SchemaAPIManager("addon"); + + // Register an API that will skip the background page. + apiManager.registerSchemaAPI("noBackgroundAPI.testnamespace", "addon_child", context => { + // This API should not be available in this context, return null so that + // the schema wrapper is removed as well. + return null; + }); + + // Register an API that will skip any but the background page. + apiManager.registerSchemaAPI("backgroundAPI.testnamespace", "addon_child", context => { + if (context.viewType === "background") { + return { + backgroundAPI: { + testnamespace: { + create(title) { + return title; + }, + }, + }, + }; + } + + // This API should not be available in this context, return null so that + // the schema wrapper is removed as well. + return null; + }); + + let context = new StubContext(); + let browserObj = {}; + apiManager.generateAPIs(context, browserObj); + + do_check_eq(browserObj.noBackgroundAPI, undefined); + const res = browserObj.backgroundAPI.testnamespace.create("param-value"); + do_check_eq(res, "param-value"); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_async.js b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_async.js new file mode 100644 index 000000000..6397d1f96 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_schemas_async.js @@ -0,0 +1,232 @@ +"use strict"; + +Components.utils.import("resource://gre/modules/ExtensionCommon.jsm"); +Components.utils.import("resource://gre/modules/Schemas.jsm"); + +let {BaseContext, LocalAPIImplementation} = ExtensionCommon; + +let schemaJson = [ + { + namespace: "testnamespace", + functions: [{ + name: "one_required", + type: "function", + parameters: [{ + name: "first", + type: "function", + parameters: [], + }], + }, { + name: "one_optional", + type: "function", + parameters: [{ + name: "first", + type: "function", + parameters: [], + optional: true, + }], + }, { + name: "async_required", + type: "function", + async: "first", + parameters: [{ + name: "first", + type: "function", + parameters: [], + }], + }, { + name: "async_optional", + type: "function", + async: "first", + parameters: [{ + name: "first", + type: "function", + parameters: [], + optional: true, + }], + }], + }, +]; + +const global = this; +class StubContext extends BaseContext { + constructor() { + let fakeExtension = {id: "test@web.extension"}; + super("testEnv", fakeExtension); + this.sandbox = Cu.Sandbox(global); + } + + get cloneScope() { + return this.sandbox; + } + + get principal() { + return Cu.getObjectPrincipal(this.sandbox); + } +} + +let context; + +function generateAPIs(extraWrapper, apiObj) { + context = new StubContext(); + let localWrapper = { + shouldInject() { + return true; + }, + getImplementation(namespace, name) { + return new LocalAPIImplementation(apiObj, name, context); + }, + }; + Object.assign(localWrapper, extraWrapper); + + let root = {}; + Schemas.inject(root, localWrapper); + return root.testnamespace; +} + +add_task(function* testParameterValidation() { + yield Schemas.load("data:," + JSON.stringify(schemaJson)); + + let testnamespace; + function assertThrows(name, ...args) { + Assert.throws(() => testnamespace[name](...args), + /Incorrect argument types/, + `Expected testnamespace.${name}(${args.map(String).join(", ")}) to throw.`); + } + function assertNoThrows(name, ...args) { + try { + testnamespace[name](...args); + } catch (e) { + do_print(`testnamespace.${name}(${args.map(String).join(", ")}) unexpectedly threw.`); + throw new Error(e); + } + } + let cb = () => {}; + + for (let isChromeCompat of [true, false]) { + do_print(`Testing API validation with isChromeCompat=${isChromeCompat}`); + testnamespace = generateAPIs({ + isChromeCompat, + }, { + one_required() {}, + one_optional() {}, + async_required() {}, + async_optional() {}, + }); + + assertThrows("one_required"); + assertThrows("one_required", null); + assertNoThrows("one_required", cb); + assertThrows("one_required", cb, null); + assertThrows("one_required", cb, cb); + + assertNoThrows("one_optional"); + assertNoThrows("one_optional", null); + assertNoThrows("one_optional", cb); + assertThrows("one_optional", cb, null); + assertThrows("one_optional", cb, cb); + + // Schema-based validation happens before an async method is called, so + // errors should be thrown synchronously. + + // The parameter was declared as required, but there was also an "async" + // attribute with the same value as the parameter name, so the callback + // parameter is actually optional. + assertNoThrows("async_required"); + assertNoThrows("async_required", null); + assertNoThrows("async_required", cb); + assertThrows("async_required", cb, null); + assertThrows("async_required", cb, cb); + + assertNoThrows("async_optional"); + assertNoThrows("async_optional", null); + assertNoThrows("async_optional", cb); + assertThrows("async_optional", cb, null); + assertThrows("async_optional", cb, cb); + } +}); + +add_task(function* testAsyncResults() { + yield Schemas.load("data:," + JSON.stringify(schemaJson)); + function* runWithCallback(func) { + do_print(`Calling testnamespace.${func.name}, expecting callback with result`); + return yield new Promise(resolve => { + let result = "uninitialized value"; + let returnValue = func(reply => { + result = reply; + resolve(result); + }); + // When a callback is given, the return value must be missing. + do_check_eq(returnValue, undefined); + // Callback must be called asynchronously. + do_check_eq(result, "uninitialized value"); + }); + } + + function* runFailCallback(func) { + do_print(`Calling testnamespace.${func.name}, expecting callback with error`); + return yield new Promise(resolve => { + func(reply => { + do_check_eq(reply, undefined); + resolve(context.lastError.message); // eslint-disable-line no-undef + }); + }); + } + + for (let isChromeCompat of [true, false]) { + do_print(`Testing API invocation with isChromeCompat=${isChromeCompat}`); + let testnamespace = generateAPIs({ + isChromeCompat, + }, { + async_required(cb) { + do_check_eq(cb, undefined); + return Promise.resolve(1); + }, + async_optional(cb) { + do_check_eq(cb, undefined); + return Promise.resolve(2); + }, + }); + if (!isChromeCompat) { // No promises for chrome. + do_print("testnamespace.async_required should be a Promise"); + let promise = testnamespace.async_required(); + do_check_true(promise instanceof context.cloneScope.Promise); + do_check_eq(yield promise, 1); + + do_print("testnamespace.async_optional should be a Promise"); + promise = testnamespace.async_optional(); + do_check_true(promise instanceof context.cloneScope.Promise); + do_check_eq(yield promise, 2); + } + + do_check_eq(yield* runWithCallback(testnamespace.async_required), 1); + do_check_eq(yield* runWithCallback(testnamespace.async_optional), 2); + + let otherSandbox = Cu.Sandbox(null, {}); + let errorFactories = [ + msg => { throw new context.cloneScope.Error(msg); }, + msg => context.cloneScope.Promise.reject({message: msg}), + msg => Cu.evalInSandbox(`throw new Error("${msg}")`, otherSandbox), + msg => Cu.evalInSandbox(`Promise.reject({message: "${msg}"})`, otherSandbox), + ]; + for (let makeError of errorFactories) { + do_print(`Testing callback/promise with error caused by: ${makeError}`); + testnamespace = generateAPIs({ + isChromeCompat, + }, { + async_required() { return makeError("ONE"); }, + async_optional() { return makeError("TWO"); }, + }); + + if (!isChromeCompat) { // No promises for chrome. + yield Assert.rejects(testnamespace.async_required(), /ONE/, + "should reject testnamespace.async_required()").catch(() => {}); + yield Assert.rejects(testnamespace.async_optional(), /TWO/, + "should reject testnamespace.async_optional()").catch(() => {}); + } + + do_check_eq(yield* runFailCallback(testnamespace.async_required), "ONE"); + do_check_eq(yield* runFailCallback(testnamespace.async_optional), "TWO"); + } + } +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_simple.js b/toolkit/components/webextensions/test/xpcshell/test_ext_simple.js new file mode 100644 index 000000000..91b10354c --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_simple.js @@ -0,0 +1,69 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +add_task(function* test_simple() { + let extensionData = { + manifest: { + "name": "Simple extension test", + "version": "1.0", + "manifest_version": 2, + "description": "", + }, + }; + + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + yield extension.unload(); +}); + +add_task(function* test_background() { + function background() { + browser.test.log("running background script"); + + browser.test.onMessage.addListener((x, y) => { + browser.test.assertEq(x, 10, "x is 10"); + browser.test.assertEq(y, 20, "y is 20"); + + browser.test.notifyPass("background test passed"); + }); + + browser.test.sendMessage("running", 1); + } + + let extensionData = { + background, + manifest: { + "name": "Simple extension test", + "version": "1.0", + "manifest_version": 2, + "description": "", + }, + }; + + let extension = ExtensionTestUtils.loadExtension(extensionData); + + let [, x] = yield Promise.all([extension.startup(), extension.awaitMessage("running")]); + equal(x, 1, "got correct value from extension"); + + extension.sendMessage(10, 20); + yield extension.awaitFinish(); + yield extension.unload(); +}); + +add_task(function* test_extensionTypes() { + let extensionData = { + background: function() { + browser.test.assertEq(typeof browser.extensionTypes, "object", "browser.extensionTypes exists"); + browser.test.assertEq(typeof browser.extensionTypes.RunAt, "object", "browser.extensionTypes.RunAt exists"); + browser.test.notifyPass("extentionTypes test passed"); + }, + }; + + let extension = ExtensionTestUtils.loadExtension(extensionData); + + yield extension.startup(); + yield extension.awaitFinish(); + yield extension.unload(); +}); + diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_storage.js b/toolkit/components/webextensions/test/xpcshell/test_ext_storage.js new file mode 100644 index 000000000..df46dfb63 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_storage.js @@ -0,0 +1,334 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +const STORAGE_SYNC_PREF = "webextensions.storage.sync.enabled"; +Cu.import("resource://gre/modules/Preferences.jsm"); + +/** + * Utility function to ensure that all supported APIs for getting are + * tested. + * + * @param {string} areaName + * either "local" or "sync" according to what we want to test + * @param {string} prop + * "key" to look up using the storage API + * @param {Object} value + * "value" to compare against + */ +async function checkGetImpl(areaName, prop, value) { + let storage = browser.storage[areaName]; + + let data = await storage.get(null); + browser.test.assertEq(value, data[prop], `null getter worked for ${prop} in ${areaName}`); + + data = await storage.get(prop); + browser.test.assertEq(value, data[prop], `string getter worked for ${prop} in ${areaName}`); + + data = await storage.get([prop]); + browser.test.assertEq(value, data[prop], `array getter worked for ${prop} in ${areaName}`); + + data = await storage.get({[prop]: undefined}); + browser.test.assertEq(value, data[prop], `object getter worked for ${prop} in ${areaName}`); +} + +add_task(function* test_local_cache_invalidation() { + function background(checkGet) { + browser.test.onMessage.addListener(async msg => { + if (msg === "set-initial") { + await browser.storage.local.set({"test-prop1": "value1", "test-prop2": "value2"}); + browser.test.sendMessage("set-initial-done"); + } else if (msg === "check") { + await checkGet("local", "test-prop1", "value1"); + await checkGet("local", "test-prop2", "value2"); + browser.test.sendMessage("check-done"); + } + }); + + browser.test.sendMessage("ready"); + } + + let extension = ExtensionTestUtils.loadExtension({ + manifest: { + permissions: ["storage"], + }, + background: `(${background})(${checkGetImpl})`, + }); + + yield extension.startup(); + yield extension.awaitMessage("ready"); + + extension.sendMessage("set-initial"); + yield extension.awaitMessage("set-initial-done"); + + Services.obs.notifyObservers(null, "extension-invalidate-storage-cache", ""); + + extension.sendMessage("check"); + yield extension.awaitMessage("check-done"); + + yield extension.unload(); +}); + +add_task(function* test_config_flag_needed() { + function background() { + let promises = []; + let apiTests = [ + {method: "get", args: ["foo"]}, + {method: "set", args: [{foo: "bar"}]}, + {method: "remove", args: ["foo"]}, + {method: "clear", args: []}, + ]; + apiTests.forEach(testDef => { + promises.push(browser.test.assertRejects( + browser.storage.sync[testDef.method](...testDef.args), + "Please set webextensions.storage.sync.enabled to true in about:config", + `storage.sync.${testDef.method} is behind a flag`)); + }); + + Promise.all(promises).then(() => browser.test.notifyPass("flag needed")); + } + + ok(!Preferences.get(STORAGE_SYNC_PREF)); + let extension = ExtensionTestUtils.loadExtension({ + manifest: { + permissions: ["storage"], + }, + background: `(${background})(${checkGetImpl})`, + }); + + yield extension.startup(); + yield extension.awaitFinish("flag needed"); + yield extension.unload(); +}); + +add_task(function* test_reloading_extensions_works() { + // Just some random extension ID that we can re-use + const extensionId = "my-extension-id@1"; + + function loadExtension() { + function background() { + browser.storage.sync.set({"a": "b"}).then(() => { + browser.test.notifyPass("set-works"); + }); + } + + return ExtensionTestUtils.loadExtension({ + manifest: { + permissions: ["storage"], + }, + background: `(${background})()`, + }, extensionId); + } + + Preferences.set(STORAGE_SYNC_PREF, true); + + let extension1 = loadExtension(); + + yield extension1.startup(); + yield extension1.awaitFinish("set-works"); + yield extension1.unload(); + + let extension2 = loadExtension(); + + yield extension2.startup(); + yield extension2.awaitFinish("set-works"); + yield extension2.unload(); + + Preferences.reset(STORAGE_SYNC_PREF); +}); + +do_register_cleanup(() => { + Preferences.reset(STORAGE_SYNC_PREF); +}); + +add_task(function* test_backgroundScript() { + async function backgroundScript(checkGet) { + let globalChanges, gResolve; + function clearGlobalChanges() { + globalChanges = new Promise(resolve => { gResolve = resolve; }); + } + clearGlobalChanges(); + let expectedAreaName; + + browser.storage.onChanged.addListener((changes, areaName) => { + browser.test.assertEq(expectedAreaName, areaName, + "Expected area name received by listener"); + gResolve(changes); + }); + + async function checkChanges(areaName, changes, message) { + function checkSub(obj1, obj2) { + for (let prop in obj1) { + browser.test.assertTrue(obj1[prop] !== undefined, + `checkChanges ${areaName} ${prop} is missing (${message})`); + browser.test.assertTrue(obj2[prop] !== undefined, + `checkChanges ${areaName} ${prop} is missing (${message})`); + browser.test.assertEq(obj1[prop].oldValue, obj2[prop].oldValue, + `checkChanges ${areaName} ${prop} old (${message})`); + browser.test.assertEq(obj1[prop].newValue, obj2[prop].newValue, + `checkChanges ${areaName} ${prop} new (${message})`); + } + } + + const recentChanges = await globalChanges; + checkSub(changes, recentChanges); + checkSub(recentChanges, changes); + clearGlobalChanges(); + } + + /* eslint-disable dot-notation */ + async function runTests(areaName) { + expectedAreaName = areaName; + let storage = browser.storage[areaName]; + // Set some data and then test getters. + try { + await storage.set({"test-prop1": "value1", "test-prop2": "value2"}); + await checkChanges(areaName, + {"test-prop1": {newValue: "value1"}, "test-prop2": {newValue: "value2"}}, + "set (a)"); + + await checkGet(areaName, "test-prop1", "value1"); + await checkGet(areaName, "test-prop2", "value2"); + + let data = await storage.get({"test-prop1": undefined, "test-prop2": undefined, "other": "default"}); + browser.test.assertEq("value1", data["test-prop1"], "prop1 correct (a)"); + browser.test.assertEq("value2", data["test-prop2"], "prop2 correct (a)"); + browser.test.assertEq("default", data["other"], "other correct"); + + data = await storage.get(["test-prop1", "test-prop2", "other"]); + browser.test.assertEq("value1", data["test-prop1"], "prop1 correct (b)"); + browser.test.assertEq("value2", data["test-prop2"], "prop2 correct (b)"); + browser.test.assertFalse("other" in data, "other correct"); + + // Remove data in various ways. + await storage.remove("test-prop1"); + await checkChanges(areaName, {"test-prop1": {oldValue: "value1"}}, "remove string"); + + data = await storage.get(["test-prop1", "test-prop2"]); + browser.test.assertFalse("test-prop1" in data, "prop1 absent (remove string)"); + browser.test.assertTrue("test-prop2" in data, "prop2 present (remove string)"); + + await storage.set({"test-prop1": "value1"}); + await checkChanges(areaName, {"test-prop1": {newValue: "value1"}}, "set (c)"); + + data = await storage.get(["test-prop1", "test-prop2"]); + browser.test.assertEq(data["test-prop1"], "value1", "prop1 correct (c)"); + browser.test.assertEq(data["test-prop2"], "value2", "prop2 correct (c)"); + + await storage.remove(["test-prop1", "test-prop2"]); + await checkChanges(areaName, + {"test-prop1": {oldValue: "value1"}, "test-prop2": {oldValue: "value2"}}, + "remove array"); + + data = await storage.get(["test-prop1", "test-prop2"]); + browser.test.assertFalse("test-prop1" in data, "prop1 absent (remove array)"); + browser.test.assertFalse("test-prop2" in data, "prop2 absent (remove array)"); + + // test storage.clear + await storage.set({"test-prop1": "value1", "test-prop2": "value2"}); + // Make sure that set() handler happened before we clear the + // promise again. + await globalChanges; + + clearGlobalChanges(); + await storage.clear(); + + await checkChanges(areaName, + {"test-prop1": {oldValue: "value1"}, "test-prop2": {oldValue: "value2"}}, + "clear"); + data = await storage.get(["test-prop1", "test-prop2"]); + browser.test.assertFalse("test-prop1" in data, "prop1 absent (clear)"); + browser.test.assertFalse("test-prop2" in data, "prop2 absent (clear)"); + + // Make sure we can store complex JSON data. + // known previous values + await storage.set({"test-prop1": "value1", "test-prop2": "value2"}); + + // Make sure the set() handler landed. + await globalChanges; + + clearGlobalChanges(); + await storage.set({ + "test-prop1": { + str: "hello", + bool: true, + null: null, + undef: undefined, + obj: {}, + arr: [1, 2], + date: new Date(0), + regexp: /regexp/, + func: function func() {}, + window, + }, + }); + + await storage.set({"test-prop2": function func() {}}); + const recentChanges = await globalChanges; + + browser.test.assertEq("value1", recentChanges["test-prop1"].oldValue, "oldValue correct"); + browser.test.assertEq("object", typeof(recentChanges["test-prop1"].newValue), "newValue is obj"); + clearGlobalChanges(); + + data = await storage.get({"test-prop1": undefined, "test-prop2": undefined}); + let obj = data["test-prop1"]; + + browser.test.assertEq("hello", obj.str, "string part correct"); + browser.test.assertEq(true, obj.bool, "bool part correct"); + browser.test.assertEq(null, obj.null, "null part correct"); + browser.test.assertEq(undefined, obj.undef, "undefined part correct"); + browser.test.assertEq(undefined, obj.func, "function part correct"); + browser.test.assertEq(undefined, obj.window, "window part correct"); + browser.test.assertEq("1970-01-01T00:00:00.000Z", obj.date, "date part correct"); + browser.test.assertEq("/regexp/", obj.regexp, "regexp part correct"); + browser.test.assertEq("object", typeof(obj.obj), "object part correct"); + browser.test.assertTrue(Array.isArray(obj.arr), "array part present"); + browser.test.assertEq(1, obj.arr[0], "arr[0] part correct"); + browser.test.assertEq(2, obj.arr[1], "arr[1] part correct"); + browser.test.assertEq(2, obj.arr.length, "arr.length part correct"); + + obj = data["test-prop2"]; + + browser.test.assertEq("[object Object]", {}.toString.call(obj), "function serialized as a plain object"); + browser.test.assertEq(0, Object.keys(obj).length, "function serialized as an empty object"); + } catch (e) { + browser.test.fail(`Error: ${e} :: ${e.stack}`); + browser.test.notifyFail("storage"); + } + } + + browser.test.onMessage.addListener(msg => { + let promise; + if (msg === "test-local") { + promise = runTests("local"); + } else if (msg === "test-sync") { + promise = runTests("sync"); + } + promise.then(() => browser.test.sendMessage("test-finished")); + }); + + browser.test.sendMessage("ready"); + } + + let extensionData = { + background: `(${backgroundScript})(${checkGetImpl})`, + manifest: { + permissions: ["storage"], + }, + }; + + Preferences.set(STORAGE_SYNC_PREF, true); + + let extension = ExtensionTestUtils.loadExtension(extensionData); + yield extension.startup(); + yield extension.awaitMessage("ready"); + + extension.sendMessage("test-local"); + yield extension.awaitMessage("test-finished"); + + extension.sendMessage("test-sync"); + yield extension.awaitMessage("test-finished"); + + Preferences.reset(STORAGE_SYNC_PREF); + yield extension.unload(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_ext_topSites.js b/toolkit/components/webextensions/test/xpcshell/test_ext_topSites.js new file mode 100644 index 000000000..eb3f552ed --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_ext_topSites.js @@ -0,0 +1,85 @@ +"use strict"; + +Cu.import("resource://gre/modules/NewTabUtils.jsm"); + + +function TestProvider(getLinksFn) { + this.getLinks = getLinksFn; + this._observers = new Set(); +} + +TestProvider.prototype = { + addObserver: function(observer) { + this._observers.add(observer); + }, + notifyLinkChanged: function(link, index = -1, deleted = false) { + this._notifyObservers("onLinkChanged", link, index, deleted); + }, + notifyManyLinksChanged: function() { + this._notifyObservers("onManyLinksChanged"); + }, + _notifyObservers: function(observerMethodName, ...args) { + args.unshift(this); + for (let obs of this._observers) { + if (obs[observerMethodName]) { + obs[observerMethodName].apply(NewTabUtils.links, args); + } + } + }, +}; + +function makeLinks(links) { + // Important: To avoid test failures due to clock jitter on Windows XP, call + // Date.now() once here, not each time through the loop. + let frecency = 0; + let now = Date.now() * 1000; + let places = []; + links.map((link, i) => { + places.push({ + url: link.url, + title: link.title, + lastVisitDate: now - i, + frecency: frecency++, + }); + }); + return places; +} + +add_task(function* test_topSites() { + let expect = [{url: "http://example.com/", title: "site#-1"}, + {url: "http://example0.com/", title: "site#0"}, + {url: "http://example1.com/", title: "site#1"}, + {url: "http://example2.com/", title: "site#2"}, + {url: "http://example3.com/", title: "site#3"}]; + + let extension = ExtensionTestUtils.loadExtension({ + manifest: { + "permissions": [ + "topSites", + ], + }, + background() { + browser.topSites.get(result => { + browser.test.sendMessage("done", result); + }); + }, + }); + + + let expectedLinks = makeLinks(expect); + let provider = new TestProvider(done => done(expectedLinks)); + + NewTabUtils.initWithoutProviders(); + NewTabUtils.links.addProvider(provider); + + yield NewTabUtils.links.populateCache(); + + yield extension.startup(); + + let result = yield extension.awaitMessage("done"); + Assert.deepEqual(expect, result, "got topSites"); + + yield extension.unload(); + + NewTabUtils.links.removeProvider(provider); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_getAPILevelForWindow.js b/toolkit/components/webextensions/test/xpcshell/test_getAPILevelForWindow.js new file mode 100644 index 000000000..68741a6cc --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_getAPILevelForWindow.js @@ -0,0 +1,55 @@ +"use strict"; + +Cu.import("resource://gre/modules/ExtensionManagement.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); + +function createWindowWithAddonId(addonId) { + let baseURI = Services.io.newURI("about:blank", null, null); + let originAttributes = {addonId}; + let principal = Services.scriptSecurityManager + .createCodebasePrincipal(baseURI, originAttributes); + let chromeNav = Services.appShell.createWindowlessBrowser(true); + let interfaceRequestor = chromeNav.QueryInterface(Ci.nsIInterfaceRequestor); + let docShell = interfaceRequestor.getInterface(Ci.nsIDocShell); + docShell.createAboutBlankContentViewer(principal); + + return {chromeNav, window: docShell.contentViewer.DOMDocument.defaultView}; +} + +add_task(function* test_eventpages() { + const {getAPILevelForWindow, getAddonIdForWindow} = ExtensionManagement; + const {NO_PRIVILEGES, FULL_PRIVILEGES} = ExtensionManagement.API_LEVELS; + const FAKE_ADDON_ID = "fakeAddonId"; + const OTHER_ADDON_ID = "otherFakeAddonId"; + const EMPTY_ADDON_ID = ""; + + let fakeAddonId = createWindowWithAddonId(FAKE_ADDON_ID); + equal(getAddonIdForWindow(fakeAddonId.window), FAKE_ADDON_ID, + "the window has the expected addonId"); + + let apiLevel = getAPILevelForWindow(fakeAddonId.window, FAKE_ADDON_ID); + equal(apiLevel, FULL_PRIVILEGES, + "apiLevel for the window with the right addonId should be FULL_PRIVILEGES"); + + apiLevel = getAPILevelForWindow(fakeAddonId.window, OTHER_ADDON_ID); + equal(apiLevel, NO_PRIVILEGES, + "apiLevel for the window with a different addonId should be NO_PRIVILEGES"); + + fakeAddonId.chromeNav.close(); + + // NOTE: check that window with an empty addon Id (which are window that are + // not Extensions pages) always get no WebExtensions APIs. + let emptyAddonId = createWindowWithAddonId(EMPTY_ADDON_ID); + equal(getAddonIdForWindow(emptyAddonId.window), EMPTY_ADDON_ID, + "the window has the expected addonId"); + + apiLevel = getAPILevelForWindow(emptyAddonId.window, EMPTY_ADDON_ID); + equal(apiLevel, NO_PRIVILEGES, + "apiLevel for empty addonId should be NO_PRIVILEGES"); + + apiLevel = getAPILevelForWindow(emptyAddonId.window, OTHER_ADDON_ID); + equal(apiLevel, NO_PRIVILEGES, + "apiLevel for an 'empty addonId' window should be always NO_PRIVILEGES"); + + emptyAddonId.chromeNav.close(); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_locale_converter.js b/toolkit/components/webextensions/test/xpcshell/test_locale_converter.js new file mode 100644 index 000000000..c8b1ee92b --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_locale_converter.js @@ -0,0 +1,133 @@ +"use strict"; + +const convService = Cc["@mozilla.org/streamConverters;1"] + .getService(Ci.nsIStreamConverterService); + +const UUID = "72b61ee3-aceb-476c-be1b-0822b036c9f1"; +const ADDON_ID = "test@web.extension"; +const URI = NetUtil.newURI(`moz-extension://${UUID}/file.css`); + +const FROM_TYPE = "application/vnd.mozilla.webext.unlocalized"; +const TO_TYPE = "text/css"; + + +function StringStream(string) { + let stream = Cc["@mozilla.org/io/string-input-stream;1"] + .createInstance(Ci.nsIStringInputStream); + + stream.data = string; + return stream; +} + + +// Initialize the policy service with a stub localizer for our +// add-on ID. +add_task(function* init() { + const aps = Cc["@mozilla.org/addons/policy-service;1"] + .getService(Ci.nsIAddonPolicyService).wrappedJSObject; + + let oldCallback = aps.setExtensionURIToAddonIdCallback(uri => { + if (uri.host == UUID) { + return ADDON_ID; + } + }); + + aps.setAddonLocalizeCallback(ADDON_ID, string => { + return string.replace(/__MSG_(.*?)__/g, ""); + }); + + do_register_cleanup(() => { + aps.setExtensionURIToAddonIdCallback(oldCallback); + aps.setAddonLocalizeCallback(ADDON_ID, null); + }); +}); + + +// Test that the synchronous converter works as expected with a +// simple string. +add_task(function* testSynchronousConvert() { + let stream = StringStream("Foo __MSG_xxx__ bar __MSG_yyy__ baz"); + + let resultStream = convService.convert(stream, FROM_TYPE, TO_TYPE, URI); + + let result = NetUtil.readInputStreamToString(resultStream, resultStream.available()); + + equal(result, "Foo bar baz"); +}); + + +// Test that the asynchronous converter works as expected with input +// split into multiple chunks, and a boundary in the middle of a +// replacement token. +add_task(function* testAsyncConvert() { + let listener; + let awaitResult = new Promise((resolve, reject) => { + listener = { + QueryInterface: XPCOMUtils.generateQI([Ci.nsIStreamListener]), + + onDataAvailable(request, context, inputStream, offset, count) { + this.resultParts.push(NetUtil.readInputStreamToString(inputStream, count)); + }, + + onStartRequest() { + ok(!("resultParts" in this)); + this.resultParts = []; + }, + + onStopRequest(request, context, statusCode) { + if (!Components.isSuccessCode(statusCode)) { + reject(new Error(statusCode)); + } + + resolve(this.resultParts.join("\n")); + }, + }; + }); + + let parts = ["Foo __MSG_x", "xx__ bar __MSG_yyy__ baz"]; + + let converter = convService.asyncConvertData(FROM_TYPE, TO_TYPE, listener, URI); + converter.onStartRequest(null, null); + + for (let part of parts) { + converter.onDataAvailable(null, null, StringStream(part), 0, part.length); + } + + converter.onStopRequest(null, null, Cr.NS_OK); + + + let result = yield awaitResult; + equal(result, "Foo bar baz"); +}); + + +// Test that attempting to initialize a converter with the URI of a +// nonexistent WebExtension fails. +add_task(function* testInvalidUUID() { + let uri = NetUtil.newURI("moz-extension://eb4f3be8-41c9-4970-aa6d-b84d1ecc02b2/file.css"); + let stream = StringStream("Foo __MSG_xxx__ bar __MSG_yyy__ baz"); + + // Assert.throws raise a TypeError exception when the expected param + // is an arrow function. (See Bug 1237961 for rationale) + let expectInvalidContextException = function(e) { + return e.result === Cr.NS_ERROR_INVALID_ARG && /Invalid context/.test(e); + }; + + Assert.throws(() => { + convService.convert(stream, FROM_TYPE, TO_TYPE, uri); + }, expectInvalidContextException); + + Assert.throws(() => { + let listener = {QueryInterface: XPCOMUtils.generateQI([Ci.nsIStreamListener])}; + + convService.asyncConvertData(FROM_TYPE, TO_TYPE, listener, uri); + }, expectInvalidContextException); +}); + + +// Test that an empty stream does not throw an NS_ERROR_ILLEGAL_VALUE. +add_task(function* testEmptyStream() { + let stream = StringStream(""); + let resultStream = convService.convert(stream, FROM_TYPE, TO_TYPE, URI); + equal(resultStream.data, ""); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_locale_data.js b/toolkit/components/webextensions/test/xpcshell/test_locale_data.js new file mode 100644 index 000000000..c3cd44e57 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_locale_data.js @@ -0,0 +1,130 @@ +"use strict"; + +Cu.import("resource://gre/modules/Extension.jsm"); + +/* globals ExtensionData */ + +const uuidGenerator = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator); + +function* generateAddon(data) { + let id = uuidGenerator.generateUUID().number; + + data = Object.assign({embedded: true}, data); + data.manifest = Object.assign({applications: {gecko: {id}}}, data.manifest); + + let xpi = Extension.generateXPI(data); + do_register_cleanup(() => { + Services.obs.notifyObservers(xpi, "flush-cache-entry", null); + xpi.remove(false); + }); + + let fileURI = Services.io.newFileURI(xpi); + let jarURI = NetUtil.newURI(`jar:${fileURI.spec}!/webextension/`); + + let extension = new ExtensionData(jarURI); + yield extension.readManifest(); + + return extension; +} + +add_task(function* testMissingDefaultLocale() { + let extension = yield generateAddon({ + "files": { + "_locales/en_US/messages.json": {}, + }, + }); + + equal(extension.errors.length, 0, "No errors reported"); + + yield extension.initAllLocales(); + + equal(extension.errors.length, 1, "One error reported"); + + do_print(`Got error: ${extension.errors[0]}`); + + ok(extension.errors[0].includes('"default_locale" property is required'), + "Got missing default_locale error"); +}); + + +add_task(function* testInvalidDefaultLocale() { + let extension = yield generateAddon({ + "manifest": { + "default_locale": "en", + }, + + "files": { + "_locales/en_US/messages.json": {}, + }, + }); + + equal(extension.errors.length, 1, "One error reported"); + + do_print(`Got error: ${extension.errors[0]}`); + + ok(extension.errors[0].includes("Loading locale file _locales/en/messages.json"), + "Got invalid default_locale error"); + + yield extension.initAllLocales(); + + equal(extension.errors.length, 2, "Two errors reported"); + + do_print(`Got error: ${extension.errors[1]}`); + + ok(extension.errors[1].includes('"default_locale" property must correspond'), + "Got invalid default_locale error"); +}); + + +add_task(function* testUnexpectedDefaultLocale() { + let extension = yield generateAddon({ + "manifest": { + "default_locale": "en_US", + }, + }); + + equal(extension.errors.length, 1, "One error reported"); + + do_print(`Got error: ${extension.errors[0]}`); + + ok(extension.errors[0].includes("Loading locale file _locales/en-US/messages.json"), + "Got invalid default_locale error"); + + yield extension.initAllLocales(); + + equal(extension.errors.length, 2, "One error reported"); + + do_print(`Got error: ${extension.errors[1]}`); + + ok(extension.errors[1].includes('"default_locale" property must correspond'), + "Got unexpected default_locale error"); +}); + + +add_task(function* testInvalidSyntax() { + let extension = yield generateAddon({ + "manifest": { + "default_locale": "en_US", + }, + + "files": { + "_locales/en_US/messages.json": '{foo: {message: "bar", description: "baz"}}', + }, + }); + + equal(extension.errors.length, 1, "No errors reported"); + + do_print(`Got error: ${extension.errors[0]}`); + + ok(extension.errors[0].includes("Loading locale file _locales\/en_US\/messages\.json: SyntaxError"), + "Got syntax error"); + + yield extension.initAllLocales(); + + equal(extension.errors.length, 2, "One error reported"); + + do_print(`Got error: ${extension.errors[1]}`); + + ok(extension.errors[1].includes("Loading locale file _locales\/en_US\/messages\.json: SyntaxError"), + "Got syntax error"); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/test_native_messaging.js b/toolkit/components/webextensions/test/xpcshell/test_native_messaging.js new file mode 100644 index 000000000..1fcb7799e --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/test_native_messaging.js @@ -0,0 +1,302 @@ +"use strict"; + +/* global OS, HostManifestManager, NativeApp */ +Cu.import("resource://gre/modules/AppConstants.jsm"); +Cu.import("resource://gre/modules/AsyncShutdown.jsm"); +Cu.import("resource://gre/modules/ExtensionCommon.jsm"); +Cu.import("resource://gre/modules/FileUtils.jsm"); +Cu.import("resource://gre/modules/Schemas.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +const {Subprocess, SubprocessImpl} = Cu.import("resource://gre/modules/Subprocess.jsm"); +Cu.import("resource://gre/modules/NativeMessaging.jsm"); +Cu.import("resource://gre/modules/osfile.jsm"); + +let registry = null; +if (AppConstants.platform == "win") { + Cu.import("resource://testing-common/MockRegistry.jsm"); + registry = new MockRegistry(); + do_register_cleanup(() => { + registry.shutdown(); + }); +} + +const REGPATH = "Software\\Mozilla\\NativeMessagingHosts"; + +const BASE_SCHEMA = "chrome://extensions/content/schemas/manifest.json"; + +let dir = FileUtils.getDir("TmpD", ["NativeMessaging"]); +dir.createUnique(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); + +let userDir = dir.clone(); +userDir.append("user"); +userDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); + +let globalDir = dir.clone(); +globalDir.append("global"); +globalDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); + +let dirProvider = { + getFile(property) { + if (property == "XREUserNativeMessaging") { + return userDir.clone(); + } else if (property == "XRESysNativeMessaging") { + return globalDir.clone(); + } + return null; + }, +}; + +Services.dirsvc.registerProvider(dirProvider); + +do_register_cleanup(() => { + Services.dirsvc.unregisterProvider(dirProvider); + dir.remove(true); +}); + +function writeManifest(path, manifest) { + if (typeof manifest != "string") { + manifest = JSON.stringify(manifest); + } + return OS.File.writeAtomic(path, manifest); +} + +let PYTHON; +add_task(function* setup() { + yield Schemas.load(BASE_SCHEMA); + + PYTHON = yield Subprocess.pathSearch("python2.7"); + if (PYTHON == null) { + PYTHON = yield Subprocess.pathSearch("python"); + } + notEqual(PYTHON, null, "Found a suitable python interpreter"); +}); + +let global = this; + +// Test of HostManifestManager.lookupApplication() begin here... +let context = { + url: null, + jsonStringify(...args) { return JSON.stringify(...args); }, + cloneScope: global, + logError() {}, + preprocessors: {}, + callOnClose: () => {}, + forgetOnClose: () => {}, +}; + +class MockContext extends ExtensionCommon.BaseContext { + constructor(extensionId) { + let fakeExtension = {id: extensionId}; + super("testEnv", fakeExtension); + this.sandbox = Cu.Sandbox(global); + } + + get cloneScope() { + return global; + } + + get principal() { + return Cu.getObjectPrincipal(this.sandbox); + } +} + +let templateManifest = { + name: "test", + description: "this is only a test", + path: "/bin/cat", + type: "stdio", + allowed_extensions: ["extension@tests.mozilla.org"], +}; + +add_task(function* test_nonexistent_manifest() { + let result = yield HostManifestManager.lookupApplication("test", context); + equal(result, null, "lookupApplication returns null for non-existent application"); +}); + +const USER_TEST_JSON = OS.Path.join(userDir.path, "test.json"); + +add_task(function* test_good_manifest() { + yield writeManifest(USER_TEST_JSON, templateManifest); + if (registry) { + registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, + `${REGPATH}\\test`, "", USER_TEST_JSON); + } + + let result = yield HostManifestManager.lookupApplication("test", context); + notEqual(result, null, "lookupApplication finds a good manifest"); + equal(result.path, USER_TEST_JSON, "lookupApplication returns the correct path"); + deepEqual(result.manifest, templateManifest, "lookupApplication returns the manifest contents"); +}); + +add_task(function* test_invalid_json() { + yield writeManifest(USER_TEST_JSON, "this is not valid json"); + let result = yield HostManifestManager.lookupApplication("test", context); + equal(result, null, "lookupApplication ignores bad json"); +}); + +add_task(function* test_invalid_name() { + let manifest = Object.assign({}, templateManifest); + manifest.name = "../test"; + yield writeManifest(USER_TEST_JSON, manifest); + let result = yield HostManifestManager.lookupApplication("test", context); + equal(result, null, "lookupApplication ignores an invalid name"); +}); + +add_task(function* test_name_mismatch() { + let manifest = Object.assign({}, templateManifest); + manifest.name = "not test"; + yield writeManifest(USER_TEST_JSON, manifest); + let result = yield HostManifestManager.lookupApplication("test", context); + let what = (AppConstants.platform == "win") ? "registry key" : "json filename"; + equal(result, null, `lookupApplication ignores mistmatch between ${what} and name property`); +}); + +add_task(function* test_missing_props() { + const PROPS = [ + "name", + "description", + "path", + "type", + "allowed_extensions", + ]; + for (let prop of PROPS) { + let manifest = Object.assign({}, templateManifest); + delete manifest[prop]; + + yield writeManifest(USER_TEST_JSON, manifest); + let result = yield HostManifestManager.lookupApplication("test", context); + equal(result, null, `lookupApplication ignores missing ${prop}`); + } +}); + +add_task(function* test_invalid_type() { + let manifest = Object.assign({}, templateManifest); + manifest.type = "bogus"; + yield writeManifest(USER_TEST_JSON, manifest); + let result = yield HostManifestManager.lookupApplication("test", context); + equal(result, null, "lookupApplication ignores invalid type"); +}); + +add_task(function* test_no_allowed_extensions() { + let manifest = Object.assign({}, templateManifest); + manifest.allowed_extensions = []; + yield writeManifest(USER_TEST_JSON, manifest); + let result = yield HostManifestManager.lookupApplication("test", context); + equal(result, null, "lookupApplication ignores manifest with no allowed_extensions"); +}); + +const GLOBAL_TEST_JSON = OS.Path.join(globalDir.path, "test.json"); +let globalManifest = Object.assign({}, templateManifest); +globalManifest.description = "This manifest is from the systemwide directory"; + +add_task(function* good_manifest_system_dir() { + yield OS.File.remove(USER_TEST_JSON); + yield writeManifest(GLOBAL_TEST_JSON, globalManifest); + if (registry) { + registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, + `${REGPATH}\\test`, "", null); + registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_LOCAL_MACHINE, + `${REGPATH}\\test`, "", GLOBAL_TEST_JSON); + } + + let where = (AppConstants.platform == "win") ? "registry location" : "directory"; + let result = yield HostManifestManager.lookupApplication("test", context); + notEqual(result, null, `lookupApplication finds a manifest in the system-wide ${where}`); + equal(result.path, GLOBAL_TEST_JSON, `lookupApplication returns path in the system-wide ${where}`); + deepEqual(result.manifest, globalManifest, `lookupApplication returns manifest contents from the system-wide ${where}`); +}); + +add_task(function* test_user_dir_precedence() { + yield writeManifest(USER_TEST_JSON, templateManifest); + if (registry) { + registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, + `${REGPATH}\\test`, "", USER_TEST_JSON); + } + // global test.json and LOCAL_MACHINE registry key on windows are + // still present from the previous test + + let result = yield HostManifestManager.lookupApplication("test", context); + notEqual(result, null, "lookupApplication finds a manifest when entries exist in both user-specific and system-wide locations"); + equal(result.path, USER_TEST_JSON, "lookupApplication returns the user-specific path when user-specific and system-wide entries both exist"); + deepEqual(result.manifest, templateManifest, "lookupApplication returns user-specific manifest contents with user-specific and system-wide entries both exist"); +}); + +// Test shutdown handling in NativeApp +add_task(function* test_native_app_shutdown() { + const SCRIPT = String.raw` +import signal +import struct +import sys + +signal.signal(signal.SIGTERM, signal.SIG_IGN) + +while True: + rawlen = sys.stdin.read(4) + if len(rawlen) == 0: + signal.pause() + msglen = struct.unpack('@I', rawlen)[0] + msg = sys.stdin.read(msglen) + + sys.stdout.write(struct.pack('@I', msglen)) + sys.stdout.write(msg) + `; + + let scriptPath = OS.Path.join(userDir.path, "wontdie.py"); + let manifestPath = OS.Path.join(userDir.path, "wontdie.json"); + + const ID = "native@tests.mozilla.org"; + let manifest = { + name: "wontdie", + description: "test async shutdown of native apps", + type: "stdio", + allowed_extensions: [ID], + }; + + if (AppConstants.platform == "win") { + yield OS.File.writeAtomic(scriptPath, SCRIPT); + + let batPath = OS.Path.join(userDir.path, "wontdie.bat"); + let batBody = `@ECHO OFF\n${PYTHON} -u "${scriptPath}" %*\n`; + yield OS.File.writeAtomic(batPath, batBody); + yield OS.File.setPermissions(batPath, {unixMode: 0o755}); + + manifest.path = batPath; + yield writeManifest(manifestPath, manifest); + + registry.setValue(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER, + `${REGPATH}\\wontdie`, "", manifestPath); + } else { + yield OS.File.writeAtomic(scriptPath, `#!${PYTHON} -u\n${SCRIPT}`); + yield OS.File.setPermissions(scriptPath, {unixMode: 0o755}); + manifest.path = scriptPath; + yield writeManifest(manifestPath, manifest); + } + + let mockContext = new MockContext(ID); + let app = new NativeApp(mockContext, "wontdie"); + + // send a message and wait for the reply to make sure the app is running + let MSG = "test"; + let recvPromise = new Promise(resolve => { + let listener = (what, msg) => { + equal(msg, MSG, "Received test message"); + app.off("message", listener); + resolve(); + }; + app.on("message", listener); + }); + + let buffer = NativeApp.encodeMessage(mockContext, MSG); + app.send(buffer); + yield recvPromise; + + app._cleanup(); + + do_print("waiting for async shutdown"); + Services.prefs.setBoolPref("toolkit.asyncshutdown.testing", true); + AsyncShutdown.profileBeforeChange._trigger(); + Services.prefs.clearUserPref("toolkit.asyncshutdown.testing"); + + let procs = yield SubprocessImpl.Process.getWorker().call("getProcesses", []); + equal(procs.size, 0, "native process exited"); +}); diff --git a/toolkit/components/webextensions/test/xpcshell/xpcshell.ini b/toolkit/components/webextensions/test/xpcshell/xpcshell.ini new file mode 100644 index 000000000..d2c6fd5d0 --- /dev/null +++ b/toolkit/components/webextensions/test/xpcshell/xpcshell.ini @@ -0,0 +1,69 @@ +[DEFAULT] +head = head.js +tail = +firefox-appdir = browser +skip-if = appname == "thunderbird" +support-files = + data/** head_sync.js +tags = webextensions + +[test_csp_custom_policies.js] +[test_csp_validator.js] +[test_ext_alarms.js] +[test_ext_alarms_does_not_fire.js] +[test_ext_alarms_periodic.js] +[test_ext_alarms_replaces.js] +[test_ext_apimanager.js] +[test_ext_api_permissions.js] +[test_ext_background_generated_load_events.js] +[test_ext_background_generated_reload.js] +[test_ext_background_global_history.js] +skip-if = os == "android" # Android does not use Places for history. +[test_ext_background_private_browsing.js] +[test_ext_background_runtime_connect_params.js] +[test_ext_background_sub_windows.js] +[test_ext_background_window_properties.js] +skip-if = os == "android" +[test_ext_contexts.js] +[test_ext_downloads.js] +[test_ext_downloads_download.js] +skip-if = os == "android" +[test_ext_downloads_misc.js] +skip-if = os == "android" +[test_ext_downloads_search.js] +skip-if = os == "android" +[test_ext_experiments.js] +skip-if = release_or_beta +[test_ext_extension.js] +[test_ext_idle.js] +[test_ext_json_parser.js] +[test_ext_localStorage.js] +[test_ext_management.js] +[test_ext_management_uninstall_self.js] +[test_ext_manifest_content_security_policy.js] +[test_ext_manifest_incognito.js] +[test_ext_manifest_minimum_chrome_version.js] +[test_ext_onmessage_removelistener.js] +[test_ext_runtime_connect_no_receiver.js] +[test_ext_runtime_getBrowserInfo.js] +[test_ext_runtime_getPlatformInfo.js] +[test_ext_runtime_onInstalled_and_onStartup.js] +[test_ext_runtime_sendMessage.js] +[test_ext_runtime_sendMessage_errors.js] +[test_ext_runtime_sendMessage_no_receiver.js] +[test_ext_runtime_sendMessage_self.js] +[test_ext_schemas.js] +[test_ext_schemas_api_injection.js] +[test_ext_schemas_async.js] +[test_ext_schemas_allowed_contexts.js] +[test_ext_simple.js] +[test_ext_storage.js] +[test_ext_topSites.js] +skip-if = os == "android" +[test_getAPILevelForWindow.js] +[test_ext_legacy_extension_context.js] +[test_ext_legacy_extension_embedding.js] +[test_locale_converter.js] +[test_locale_data.js] +[test_native_messaging.js] +skip-if = os == "android" diff --git a/toolkit/jetpack/moz.build b/toolkit/jetpack/moz.build index 6d27f8a3f..22be010d6 100644 --- a/toolkit/jetpack/moz.build +++ b/toolkit/jetpack/moz.build @@ -127,6 +127,11 @@ EXTRA_JS_MODULES.commonjs += [ 'test.js', ] +if CONFIG['MOZ_WEBEXTENSIONS']: + EXTRA_JS_MODULES.commonjs.sdk += [ + 'sdk/webextension.js', + ] + EXTRA_JS_MODULES.commonjs.dev += [ 'dev/debuggee.js', 'dev/frame-script.js', @@ -223,7 +228,6 @@ EXTRA_PP_JS_MODULES.commonjs.sdk += [ ] EXTRA_JS_MODULES.commonjs.sdk.addon += [ - 'sdk/addon/bootstrap.js', 'sdk/addon/events.js', 'sdk/addon/host.js', 'sdk/addon/installer.js', @@ -232,6 +236,10 @@ EXTRA_JS_MODULES.commonjs.sdk.addon += [ 'sdk/addon/window.js', ] +EXTRA_PP_JS_MODULES.commonjs.sdk.addon += [ + 'sdk/addon/bootstrap.js', +] + EXTRA_JS_MODULES.commonjs.sdk.browser += [ 'sdk/browser/events.js', ] diff --git a/toolkit/jetpack/sdk/addon/bootstrap.js b/toolkit/jetpack/sdk/addon/bootstrap.js index a6055bd10..6c5827f1e 100644 --- a/toolkit/jetpack/sdk/addon/bootstrap.js +++ b/toolkit/jetpack/sdk/addon/bootstrap.js @@ -134,6 +134,11 @@ Bootstrap.prototype = { const main = command === "test" ? "sdk/test/runner" : null; const prefsURI = `${baseURI}defaults/preferences/prefs.js`; +#ifdef MOZ_WEBEXTENSIONS + // Init the 'sdk/webextension' module from the bootstrap addon parameter. + require("sdk/webextension").initFromBootstrapAddonParam(addon); +#endif + const { startup } = require("sdk/addon/runner"); startup(reason, {loader, main, prefsURI}); }.bind(this)).catch(error => { diff --git a/toolkit/jetpack/sdk/webextension.js b/toolkit/jetpack/sdk/webextension.js new file mode 100644 index 000000000..d1c4385e2 --- /dev/null +++ b/toolkit/jetpack/sdk/webextension.js @@ -0,0 +1,43 @@ +/* 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.metadata = { + "stability": "experimental" +}; + +let webExtension; +let waitForWebExtensionAPI; + +module.exports = { + initFromBootstrapAddonParam(data) { + if (webExtension) { + throw new Error("'sdk/webextension' module has been already initialized"); + } + + webExtension = data.webExtension; + }, + + startup() { + if (!webExtension) { + return Promise.reject(new Error( + "'sdk/webextension' module is currently disabled. " + + "('hasEmbeddedWebExtension' option is missing or set to false)" + )); + } + + // NOTE: calling `startup` more than once raises an "Embedded Extension already started" + // error, but given that SDK addons are going to have access to the startup method through + // an SDK module that can be required in any part of the addon, it will be nicer if any + // additional startup calls return the startup promise instead of raising an exception, + // so that the SDK addon can access the API object in the other addon modules without the + // need to manually pass this promise around. + if (!waitForWebExtensionAPI) { + waitForWebExtensionAPI = webExtension.startup(); + } + + return waitForWebExtensionAPI; + } +}; diff --git a/toolkit/locales/en-US/chrome/mozapps/extensions/extensions.dtd b/toolkit/locales/en-US/chrome/mozapps/extensions/extensions.dtd index febc18dfd..b5086032c 100644 --- a/toolkit/locales/en-US/chrome/mozapps/extensions/extensions.dtd +++ b/toolkit/locales/en-US/chrome/mozapps/extensions/extensions.dtd @@ -24,6 +24,13 @@ +#ifdef MOZ_WEBEXTENSIONS + + + + +#endif + @@ -235,3 +242,23 @@ + +#ifdef MOZ_WEBEXTENSIONS + + + + + + + + + + + + + +#endif diff --git a/toolkit/locales/jar.mn b/toolkit/locales/jar.mn index 99c16de1d..e92e10599 100644 --- a/toolkit/locales/jar.mn +++ b/toolkit/locales/jar.mn @@ -107,7 +107,7 @@ locale/@AB_CD@/mozapps/downloads/settingsChange.dtd (%chrome/mozapps/downloads/settingsChange.dtd) locale/@AB_CD@/mozapps/downloads/downloads.dtd (%chrome/mozapps/downloads/downloads.dtd) locale/@AB_CD@/mozapps/downloads/downloads.properties (%chrome/mozapps/downloads/downloads.properties) - locale/@AB_CD@/mozapps/extensions/extensions.dtd (%chrome/mozapps/extensions/extensions.dtd) +* locale/@AB_CD@/mozapps/extensions/extensions.dtd (%chrome/mozapps/extensions/extensions.dtd) locale/@AB_CD@/mozapps/extensions/extensions.properties (%chrome/mozapps/extensions/extensions.properties) locale/@AB_CD@/mozapps/extensions/blocklist.dtd (%chrome/mozapps/extensions/blocklist.dtd) locale/@AB_CD@/mozapps/extensions/about.dtd (%chrome/mozapps/extensions/about.dtd) diff --git a/toolkit/modules/moz.build b/toolkit/modules/moz.build index e0acdb19e..948d8d2c9 100644 --- a/toolkit/modules/moz.build +++ b/toolkit/modules/moz.build @@ -103,9 +103,11 @@ EXTRA_JS_MODULES.sessionstore += ['sessionstore/Utils.jsm'] EXTRA_PP_JS_MODULES += [ 'NewTabUtils.jsm', 'Troubleshoot.jsm', - 'UpdateChannel.jsm', ] +if not CONFIG['MOZ_WEBEXTENSIONS']: + EXTRA_PP_JS_MODULES += ['UpdateChannel.jsm'] + if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('windows', 'cocoa'): DEFINES['CAN_DRAW_IN_TITLEBAR'] = 1 diff --git a/toolkit/moz.build b/toolkit/moz.build index 158e760dc..3951700b9 100644 --- a/toolkit/moz.build +++ b/toolkit/moz.build @@ -22,7 +22,10 @@ DIRS += [ if CONFIG['MOZ_JETPACK']: DIRS += ['jetpack'] -DIRS += ['mozapps/extensions'] +if CONFIG['MOZ_WEBEXTENSIONS']: + DIRS += ['mozapps/webextensions'] +else: + DIRS += ['mozapps/extensions'] if CONFIG['MOZ_UPDATER'] and CONFIG['MOZ_WIDGET_TOOLKIT'] != 'android': DIRS += ['mozapps/update'] diff --git a/toolkit/mozapps/extensions/content/newaddon.js b/toolkit/mozapps/extensions/content/newaddon.js index aab556a62..79978a698 100644 --- a/toolkit/mozapps/extensions/content/newaddon.js +++ b/toolkit/mozapps/extensions/content/newaddon.js @@ -43,6 +43,9 @@ function initialize() { // been seen or it cannot be enabled then this UI is useless, just close it. // This shouldn't normally happen unless session restore restores the tab. if (!aAddon || !aAddon.userDisabled || +#ifdef MOZ_WEBEXTENSIONS + aAddon.seen || +#endif !(aAddon.permissions & AddonManager.PERM_CAN_ENABLE)) { window.close(); return; @@ -79,6 +82,16 @@ function initialize() { document.getElementById("location").hidden = true; } +#ifdef MOZ_WEBEXTENSIONS + // Only mark the add-on as seen if the page actually gets focus + if (document.hasFocus()) { + aAddon.markAsSeen(); + } + else { + document.addEventListener("focus", () => aAddon.markAsSeen(), false); + } +#endif + var event = document.createEvent("Events"); event.initEvent("AddonDisplayed", true, true); document.dispatchEvent(event); diff --git a/toolkit/mozapps/extensions/jar.mn b/toolkit/mozapps/extensions/jar.mn index e95d93ca0..c4d8874c9 100644 --- a/toolkit/mozapps/extensions/jar.mn +++ b/toolkit/mozapps/extensions/jar.mn @@ -26,7 +26,7 @@ toolkit.jar: content/mozapps/extensions/eula.xul (content/eula.xul) content/mozapps/extensions/eula.js (content/eula.js) content/mozapps/extensions/newaddon.xul (content/newaddon.xul) - content/mozapps/extensions/newaddon.js (content/newaddon.js) +* content/mozapps/extensions/newaddon.js (content/newaddon.js) content/mozapps/extensions/setting.xml (content/setting.xml) content/mozapps/extensions/pluginPrefs.xul (content/pluginPrefs.xul) content/mozapps/extensions/gmpPrefs.xul (content/gmpPrefs.xul) diff --git a/toolkit/mozapps/webextensions/AddonContentPolicy.cpp b/toolkit/mozapps/webextensions/AddonContentPolicy.cpp new file mode 100644 index 000000000..90e53b2ea --- /dev/null +++ b/toolkit/mozapps/webextensions/AddonContentPolicy.cpp @@ -0,0 +1,478 @@ +/* -*- 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/nsCSPUtils.h" +#include "nsCOMPtr.h" +#include "nsContentPolicyUtils.h" +#include "nsContentTypeParser.h" +#include "nsContentUtils.h" +#include "nsIConsoleService.h" +#include "nsIContentSecurityPolicy.h" +#include "nsIContent.h" +#include "nsIDocument.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() +{ +} + +AddonContentPolicy::~AddonContentPolicy() +{ +} + +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 document = content->OwnerDoc(); + NS_ENSURE_TRUE(document, NS_ERROR_FAILURE); + + nsCOMPtr window = document->GetInnerWindow(); + NS_ENSURE_TRUE(window, NS_ERROR_FAILURE); + + *aResult = window->WindowID(); + return NS_OK; +} + +static nsresult +LogMessage(const nsAString &aMessage, nsIURI* aSourceURI, const nsAString &aSourceSample, + nsISupports* aContext) +{ + nsCOMPtr error = do_CreateInstance(NS_SCRIPTERROR_CONTRACTID); + NS_ENSURE_TRUE(error, NS_ERROR_OUT_OF_MEMORY); + + nsCString sourceName = aSourceURI->GetSpecOrDefault(); + + uint64_t windowID = 0; + GetWindowIDFromContext(aContext, &windowID); + + nsresult rv = + error->InitWithWindowID(aMessage, NS_ConvertUTF8toUTF16(sourceName), + 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(uint32_t aContentType, + nsIURI* aContentLocation, + nsIURI* aRequestOrigin, + nsISupports* aContext, + const nsACString& aMimeTypeGuess, + nsISupports* aExtra, + nsIPrincipal* aRequestPrincipal, + int16_t* aShouldLoad) +{ + MOZ_ASSERT(aContentType == nsContentUtils::InternalContentPolicyTypeToExternal(aContentType), + "We should only see external content policy types here."); + + *aShouldLoad = nsIContentPolicy::ACCEPT; + + if (!aRequestOrigin) { + 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. + bool equals; + if (!((NS_SUCCEEDED(aContentLocation->SchemeIs("moz-extension", &equals)) && equals) || + (NS_SUCCEEDED(aRequestOrigin->SchemeIs("moz-extension", &equals)) && equals))) { + return NS_OK; + } + + if (aContentType == nsIContentPolicy::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))) { + *aShouldLoad = nsIContentPolicy::REJECT_REQUEST; + + LogMessage(NS_MULTILINE_LITERAL_STRING(VERSIONED_JS_BLOCKED_MESSAGE), + aRequestOrigin, typeString, aContext); + return NS_OK; + } + } + + return NS_OK; +} + +NS_IMETHODIMP +AddonContentPolicy::ShouldProcess(uint32_t aContentType, + nsIURI* aContentLocation, + nsIURI* aRequestOrigin, + nsISupports* aRequestingContext, + const nsACString& aMimeTypeGuess, + nsISupports* aExtra, + nsIPrincipal* aRequestPrincipal, + int16_t* aShouldProcess) +{ + MOZ_ASSERT(aContentType == nsContentUtils::InternalContentPolicyTypeToExternal(aContentType), + "We should only see external content policy types here."); + + *aShouldProcess = nsIContentPolicy::ACCEPT; + return NS_OK; +} + + +// CSP Validation: + +static const char* allowedSchemes[] = { + "blob", + "filesystem", + nullptr +}; + +static const char* allowedHostSchemes[] = { + "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. + */ +class CSPValidator final : public nsCSPSrcVisitor { + public: + CSPValidator(nsAString& aURL, CSPDirective aDirective, bool aDirectiveRequired = true) : + mURL(aURL), + mDirective(CSP_CSPDirectiveToString(aDirective)), + mFoundSelf(false) + { + // Start with the default error message for a missing directive, since no + // visitors will be called if the directive isn't present. + 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("https")) { + 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: + case CSP_UNSAFE_EVAL: + return true; + + default: + NS_ConvertASCIItoUTF16 keyword(CSP_EnumToKeyword(src.getKeyword())); + + FormatError("csp.error.illegal-keyword", keyword); + return false; + } + }; + + bool visitNonceSrc(const nsCSPNonceSrc& src) override + { + FormatError("csp.error.illegal-keyword", NS_LITERAL_STRING("'nonce-*'")); + 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) + { + const char16_t* params[] = { mDirective.get(), aParams.get()... }; + FormatErrorParams(aName, params, MOZ_ARRAY_LENGTH(params)); + }; + + private: + // Validators + + 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 char16_t** aParams, int32_t aLength) + { + nsresult rv = NS_ERROR_FAILURE; + + nsCOMPtr stringBundle = GetStringBundle(); + + if (stringBundle) { + NS_ConvertASCIItoUTF16 name(aName); + + rv = stringBundle->FormatStringFromName(name.get(), aParams, aLength, + getter_Copies(mError)); + } + + if (NS_WARN_IF(NS_FAILED(rv))) { + mError.AssignLiteral("An unexpected error occurred"); + } + }; + + + // Data members + + nsAutoString mURL; + NS_ConvertASCIItoUTF16 mDirective; + nsXPIDLString mError; + + 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, + 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::CreateCodebasePrincipal(NS_ConvertUTF16toUTF8(url)); + + nsCOMPtr csp; + rv = principal->EnsureCSP(nullptr, getter_AddRefs(csp)); + 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); + aResult.Assign(validator.GetError()); + return NS_OK; + } + + bool haveValidDefaultSrc = 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); + + if (!policy->visitDirectiveSrcs(directive, &validator)) { + aResult.Assign(validator.GetError()); + } else if (!validator.FoundSelf()) { + validator.FormatError("csp.error.missing-source", NS_LITERAL_STRING("'self'")); + aResult.Assign(validator.GetError()); + } + } + + if (aResult.IsVoid()) { + CSPDirective directive = nsIContentSecurityPolicy::OBJECT_SRC_DIRECTIVE; + CSPValidator validator(url, directive, !haveValidDefaultSrc); + + if (!policy->visitDirectiveSrcs(directive, &validator)) { + aResult.Assign(validator.GetError()); + } + } + + return NS_OK; +} diff --git a/toolkit/mozapps/webextensions/AddonContentPolicy.h b/toolkit/mozapps/webextensions/AddonContentPolicy.h new file mode 100644 index 000000000..4c8af4828 --- /dev/null +++ b/toolkit/mozapps/webextensions/AddonContentPolicy.h @@ -0,0 +1,22 @@ +/* -*- 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/webextensions/AddonManager.jsm b/toolkit/mozapps/webextensions/AddonManager.jsm new file mode 100644 index 000000000..a3bcbb504 --- /dev/null +++ b/toolkit/mozapps/webextensions/AddonManager.jsm @@ -0,0 +1,3666 @@ +/* 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 Cc = Components.classes; +const Ci = Components.interfaces; +const Cr = Components.results; +const Cu = Components.utils; + +// 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) { + 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!"); + } +} + +Cu.import("resource://gre/modules/AppConstants.jsm"); + +const MOZ_COMPATIBILITY_NIGHTLY = !['aurora', 'beta', 'release', 'esr'].includes(AppConstants.MOZ_UPDATE_CHANNEL); + +const PREF_BLOCKLIST_PINGCOUNTVERSION = "extensions.blocklist.pingCountVersion"; +const PREF_DEFAULT_PROVIDERS_ENABLED = "extensions.defaultProviders.enabled"; +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_EM_UPDATE_BACKGROUND_URL = "extensions.update.background.url"; +const PREF_APP_UPDATE_ENABLED = "app.update.enabled"; +const PREF_APP_UPDATE_AUTO = "app.update.auto"; +const PREF_EM_HOTFIX_ID = "extensions.hotfix.id"; +const PREF_EM_HOTFIX_LASTVERSION = "extensions.hotfix.lastVersion"; +const PREF_EM_HOTFIX_URL = "extensions.hotfix.url"; +const PREF_EM_CERT_CHECKATTRIBUTES = "extensions.hotfix.cert.checkAttributes"; +const PREF_EM_HOTFIX_CERTS = "extensions.hotfix.certs."; +const PREF_MATCH_OS_LOCALE = "intl.locale.matchOS"; +const PREF_SELECTED_LOCALE = "general.useragent.locale"; +const UNKNOWN_XPCOM_ABI = "unknownABI"; + +const PREF_MIN_WEBEXT_PLATFORM_VERSION = "extensions.webExtensionsMinPlatformVersion"; +const PREF_WEBAPI_TESTING = "extensions.webapi.testing"; + +const UPDATE_REQUEST_VERSION = 2; +const CATEGORY_UPDATE_PARAMS = "extension-update-params"; + +const XMLURI_BLOCKLIST = "http://www.mozilla.org/2006/addons-blocklist"; + +const KEY_PROFILEDIR = "ProfD"; +const KEY_APPDIR = "XCurProcD"; +const FILE_BLOCKLIST = "blocklist.xml"; + +const BRANCH_REGEXP = /^([^\.]+\.[0-9]+[a-z]*).*/gi; +const PREF_EM_CHECK_COMPATIBILITY = "extensions.enableCompatibilityChecking"; + +const TOOLKIT_ID = "toolkit@mozilla.org"; + +const VALID_TYPES_REGEXP = /^[\w\-]+$/; + +const WEBAPI_INSTALL_HOSTS = ["addons.mozilla.org", "testpilot.firefox.com"]; +const WEBAPI_TEST_INSTALL_HOSTS = [ + "addons.allizom.org", "addons-dev.allizom.org", + "testpilot.stage.mozaws.net", "testpilot.dev.mozaws.net", + "example.com", +]; + +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/AsyncShutdown.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "Task", + "resource://gre/modules/Task.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Promise", + "resource://gre/modules/Promise.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "AddonRepository", + "resource://gre/modules/addons/AddonRepository.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Extension", + "resource://gre/modules/Extension.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "FileUtils", + "resource://gre/modules/FileUtils.jsm"); + +XPCOMUtils.defineLazyGetter(this, "CertUtils", function() { + let certUtils = {}; + Components.utils.import("resource://gre/modules/CertUtils.jsm", certUtils); + return certUtils; +}); + +const INTEGER = /^[1-9]\d*$/; + +this.EXPORTED_SYMBOLS = [ "AddonManager", "AddonManagerPrivate" ]; + +const CATEGORY_PROVIDER_MODULE = "addon-provider-module"; + +// A list of providers to load by default +const DEFAULT_PROVIDERS = [ + "resource://gre/modules/addons/XPIProvider.jsm", + "resource://gre/modules/LightweightThemeManager.jsm" +]; + +Cu.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)); +// Set parent logger (and its children) to +// also append to standard out +parentLogger.addAppender(new Log.DumpAppender(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: function() { + Services.prefs.addObserver(PREF_LOGGING_ENABLED, this, false); + Services.obs.addObserver(this, "xpcom-shutdown", false); + this.observe(null, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID, PREF_LOGGING_ENABLED); + }, + + observe: function(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 = false; + try { + debugLogEnabled = Services.prefs.getBoolPref(PREF_LOGGING_ENABLED); + } + catch (e) { + } + 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); + } +} + +/** + * Creates a function that will call the passed callback catching and logging + * any exceptions. + * + * @param aCallback + * The callback method to call + */ +function makeSafe(aCallback) { + return function(...aArgs) { + safeCall(aCallback, ...aArgs); + } +} + +/** + * 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(). + * The last parameter must be a callback function. + * 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 + */ +function callProviderAsync(aProvider, aMethod, ...aArgs) { + let callback = aArgs[aArgs.length - 1]; + if (!(aMethod in aProvider)) { + callback(undefined); + return undefined; + } + try { + return aProvider[aMethod].apply(aProvider, aArgs); + } + catch (e) { + reportProviderError(aProvider, aMethod, e); + callback(undefined); + return undefined; + } +} + +/** + * Calls a method on a provider if it exists and consumes any thrown exception. + * Parameters after aMethod are passed to aProvider.aMethod() and an additional + * callback is added for the provider to return a result to. + * + * @param aProvider + * The provider to call + * @param aMethod + * The method name to call + * @return {Promise} + * @resolves The result the provider returns, or |undefined| if the provider + * does not implement the method or the method throws. + * @rejects Never + */ +function promiseCallProvider(aProvider, aMethod, ...aArgs) { + return new Promise(resolve => { + callProviderAsync(aProvider, aMethod, ...aArgs, resolve); + }); +} + +/** + * Gets the currently selected locale for display. + * @return the selected locale or "en-US" if none is selected + */ +function getLocale() { + try { + if (Services.prefs.getBoolPref(PREF_MATCH_OS_LOCALE)) + return Services.locale.getLocaleComponentForUserAgent(); + } + catch (e) { } + + try { + let locale = Services.prefs.getComplexValue(PREF_SELECTED_LOCALE, + Ci.nsIPrefLocalizedString); + if (locale) + return locale; + } + catch (e) { } + + try { + return Services.prefs.getCharPref(PREF_SELECTED_LOCALE); + } + catch (e) { } + + return "en-US"; +} + +function webAPIForAddon(addon) { + if (!addon) { + return null; + } + + let result = {}; + + // By default just pass through any plain property, the webidl will + // control access. Also filter out private properties, regular Addon + // objects are okay but MockAddon used in tests has non-serializable + // private properties. + for (let prop in addon) { + if (prop[0] != "_" && typeof(addon[prop]) != "function") { + result[prop] = addon[prop]; + } + } + + // A few properties are computed for a nicer API + result.isEnabled = !addon.userDisabled; + result.canUninstall = Boolean(addon.permissions & AddonManager.PERM_CAN_UNINSTALL); + + return result; +} + +/** + * A helper class to repeatedly call a listener with each object in an array + * optionally checking whether the object has a method in it. + * + * @param aObjects + * The array of objects to iterate through + * @param aMethod + * An optional method name, if not null any objects without this method + * will not be passed to the listener + * @param aListener + * A listener implementing nextObject and noMoreObjects methods. The + * former will be called with the AsyncObjectCaller as the first + * parameter and the object as the second. noMoreObjects will be passed + * just the AsyncObjectCaller + */ +function AsyncObjectCaller(aObjects, aMethod, aListener) { + this.objects = [...aObjects]; + this.method = aMethod; + this.listener = aListener; + + this.callNext(); +} + +AsyncObjectCaller.prototype = { + objects: null, + method: null, + listener: null, + + /** + * Passes the next object to the listener or calls noMoreObjects if there + * are none left. + */ + callNext: function() { + if (this.objects.length == 0) { + this.listener.noMoreObjects(this); + return; + } + + let object = this.objects.shift(); + if (!this.method || this.method in object) + this.listener.nextObject(this, object); + else + this.callNext(); + } +}; + +/** + * Listens for a browser changing origin and cancels the installs that were + * started by it. + */ +function BrowserListener(aBrowser, aInstallingPrincipal, aInstalls) { + this.browser = aBrowser; + this.principal = aInstallingPrincipal; + this.installs = aInstalls; + this.installCount = aInstalls.length; + + aBrowser.addProgressListener(this, Ci.nsIWebProgress.NOTIFY_LOCATION); + Services.obs.addObserver(this, "message-manager-close", true); + + for (let install of this.installs) + install.addListener(this); + + this.registered = true; +} + +BrowserListener.prototype = { + browser: null, + installs: null, + installCount: null, + registered: false, + + unregister: function() { + 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); + + for (let install of this.installs) + install.removeListener(this); + this.installs = null; + }, + + cancelInstalls: function() { + for (let install of this.installs) { + try { + install.cancel(); + } + catch (e) { + // Some installs may have already failed or been cancelled, ignore these + } + } + }, + + observe: function(subject, topic, data) { + if (subject != this.browser.messageManager) + return; + + // The browser's message manager has closed and so the browser is + // going away, cancel all installs + this.cancelInstalls(); + }, + + onLocationChange: function(webProgress, request, location) { + if (this.browser.contentPrincipal && this.principal.subsumes(this.browser.contentPrincipal)) + return; + + // The browser has navigated to a new origin so cancel all installs + this.cancelInstalls(); + }, + + onDownloadCancelled: function(install) { + // Don't need to hear more events from this install + install.removeListener(this); + + // Once all installs have ended unregister everything + if (--this.installCount == 0) + this.unregister(); + }, + + onDownloadFailed: function(install) { + this.onDownloadCancelled(install); + }, + + onInstallFailed: function(install) { + this.onDownloadCancelled(install); + }, + + onInstallEnded: function(install) { + this.onDownloadCancelled(install); + }, + + QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference, + Ci.nsIWebProgressListener, + Ci.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: function() { + 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: function() { + return this.url || ""; + } +} + + +/** + * This represents a compatibility override for an addon. + * + * @param aType + * Overrride type - "compatible" or "incompatible" + * @param aMinVersion + * Minimum version of the addon to match + * @param aMaxVersion + * Maximum version of the addon to match + * @param aAppID + * Application ID used to match appMinVersion and appMaxVersion + * @param aAppMinVersion + * Minimum version of the application to match + * @param aAppMaxVersion + * Maximum version of the application to match + */ +function AddonCompatibilityOverride(aType, aMinVersion, aMaxVersion, aAppID, + aAppMinVersion, aAppMaxVersion) { + this.type = aType; + this.minVersion = aMinVersion; + this.maxVersion = aMaxVersion; + this.appID = aAppID; + this.appMinVersion = aAppMinVersion; + this.appMaxVersion = aAppMaxVersion; +} + +AddonCompatibilityOverride.prototype = { + /** + * Type of override - "incompatible" or "compatible". + * Only "incompatible" is supported for now. + */ + type: null, + + /** + * Min version of the addon to match. + */ + minVersion: null, + + /** + * Max version of the addon to match. + */ + maxVersion: null, + + /** + * Application ID to match. + */ + appID: null, + + /** + * Min version of the application to match. + */ + appMinVersion: null, + + /** + * Max version of the application to match. + */ + appMaxVersion: null +}; + + +/** + * 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 or the actual display + * name if aLocaleURI is null. Include %ID% to include the type ID in + * the key + * @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.replace("%ID%", aID)); + }); + } + 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 gHotfixID = null; +var gWebExtensionsMinPlatformVersion = null; +var gShutdownBarrier = null; +var gRepoShutdownState = ""; +var gShutdownInProgress = false; +var gPluginPageListener = null; + +/** + * This is the real manager, kept here rather than in AddonManager to keep its + * contents hidden from API users. + */ +var AddonManagerInternal = { + managerListeners: [], + installListeners: [], + addonListeners: [], + typeListeners: [], + pendingProviders: new Set(), + providers: new Set(), + providerShutdowns: new Map(), + types: {}, + startupChanges: {}, + // Store telemetry details per addon provider + telemetryDetails: {}, + upgradeListeners: new Map(), + + recordTimestamp: function(name, value) { + this.TelemetryTimestamps.add(name, value); + }, + + validateBlocklist: function() { + let appBlocklist = FileUtils.getFile(KEY_APPDIR, [FILE_BLOCKLIST]); + + // If there is no application shipped blocklist then there is nothing to do + if (!appBlocklist.exists()) + return; + + let profileBlocklist = FileUtils.getFile(KEY_PROFILEDIR, [FILE_BLOCKLIST]); + + // If there is no blocklist in the profile then copy the application shipped + // one there + if (!profileBlocklist.exists()) { + try { + appBlocklist.copyTo(profileBlocklist.parent, FILE_BLOCKLIST); + } + catch (e) { + logger.warn("Failed to copy the application shipped blocklist to the profile", e); + } + return; + } + + let fileStream = Cc["@mozilla.org/network/file-input-stream;1"]. + createInstance(Ci.nsIFileInputStream); + try { + let cstream = Cc["@mozilla.org/intl/converter-input-stream;1"]. + createInstance(Ci.nsIConverterInputStream); + fileStream.init(appBlocklist, FileUtils.MODE_RDONLY, FileUtils.PERMS_FILE, 0); + cstream.init(fileStream, "UTF-8", 0, 0); + + let data = ""; + let str = {}; + let read = 0; + do { + read = cstream.readString(0xffffffff, str); + data += str.value; + } while (read != 0); + + let parser = Cc["@mozilla.org/xmlextras/domparser;1"]. + createInstance(Ci.nsIDOMParser); + var doc = parser.parseFromString(data, "text/xml"); + } + catch (e) { + logger.warn("Application shipped blocklist could not be loaded", e); + return; + } + finally { + try { + fileStream.close(); + } + catch (e) { + logger.warn("Unable to close blocklist file stream", e); + } + } + + // If the namespace is incorrect then ignore the application shipped + // blocklist + if (doc.documentElement.namespaceURI != XMLURI_BLOCKLIST) { + logger.warn("Application shipped blocklist has an unexpected namespace (" + + doc.documentElement.namespaceURI + ")"); + return; + } + + // If there is no lastupdate information then ignore the application shipped + // blocklist + if (!doc.documentElement.hasAttribute("lastupdate")) + return; + + // If the application shipped blocklist is older than the profile blocklist + // then do nothing + if (doc.documentElement.getAttribute("lastupdate") <= + profileBlocklist.lastModifiedTime) + return; + + // Otherwise copy the application shipped blocklist to the profile + try { + appBlocklist.copyTo(profileBlocklist.parent, FILE_BLOCKLIST); + } + catch (e) { + logger.warn("Failed to copy the application shipped blocklist to the profile", e); + } + }, + + /** + * Start up a provider, and register its shutdown hook if it has one + */ + _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 incase 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); + AddonManager.shutdown.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: function() { + try { + if (gStarted) + return; + + this.recordTimestamp("AMI_startup_begin"); + + // 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) { } + + Extension.browserUpdated = appChanged; + + let oldPlatformVersion = null; + try { + oldPlatformVersion = Services.prefs.getCharPref(PREF_EM_LAST_PLATFORM_VERSION); + } + catch (e) { } + + 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)); + this.validateBlocklist(); + } + + try { + gCheckCompatibility = Services.prefs.getBoolPref(PREF_EM_CHECK_COMPATIBILITY); + } catch (e) {} + Services.prefs.addObserver(PREF_EM_CHECK_COMPATIBILITY, this, false); + + try { + gStrictCompatibility = Services.prefs.getBoolPref(PREF_EM_STRICT_COMPATIBILITY); + } catch (e) {} + Services.prefs.addObserver(PREF_EM_STRICT_COMPATIBILITY, this, false); + + try { + let defaultBranch = Services.prefs.getDefaultBranch(""); + gCheckUpdateSecurityDefault = defaultBranch.getBoolPref(PREF_EM_CHECK_UPDATE_SECURITY); + } catch (e) {} + + try { + gCheckUpdateSecurity = Services.prefs.getBoolPref(PREF_EM_CHECK_UPDATE_SECURITY); + } catch (e) {} + Services.prefs.addObserver(PREF_EM_CHECK_UPDATE_SECURITY, this, false); + + try { + gUpdateEnabled = Services.prefs.getBoolPref(PREF_EM_UPDATE_ENABLED); + } catch (e) {} + Services.prefs.addObserver(PREF_EM_UPDATE_ENABLED, this, false); + + try { + gAutoUpdateDefault = Services.prefs.getBoolPref(PREF_EM_AUTOUPDATE_DEFAULT); + } catch (e) {} + Services.prefs.addObserver(PREF_EM_AUTOUPDATE_DEFAULT, this, false); + + try { + gHotfixID = Services.prefs.getCharPref(PREF_EM_HOTFIX_ID); + } catch (e) {} + Services.prefs.addObserver(PREF_EM_HOTFIX_ID, this, false); + + try { + gWebExtensionsMinPlatformVersion = Services.prefs.getCharPref(PREF_MIN_WEBEXT_PLATFORM_VERSION); + } catch (e) {} + Services.prefs.addObserver(PREF_MIN_WEBEXT_PLATFORM_VERSION, this, false); + + let defaultProvidersEnabled = true; + try { + defaultProvidersEnabled = Services.prefs.getBoolPref(PREF_DEFAULT_PROVIDERS_ENABLED); + } catch (e) {} + AddonManagerPrivate.recordSimpleMeasure("default_providers", defaultProvidersEnabled); + + // Ensure all default providers have had a chance to register themselves + if (defaultProvidersEnabled) { + for (let url of DEFAULT_PROVIDERS) { + try { + let scope = {}; + Components.utils.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 + let catman = Cc["@mozilla.org/categorymanager;1"]. + getService(Ci.nsICategoryManager); + let entries = catman.enumerateCategory(CATEGORY_PROVIDER_MODULE); + while (entries.hasMoreElements()) { + let entry = entries.getNext().QueryInterface(Ci.nsISupportsCString).data; + let url = catman.getCategoryEntry(CATEGORY_PROVIDER_MODULE, entry); + + try { + Components.utils.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 + gShutdownBarrier = 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]; + } + + // Support for remote about:plugins. Note that this module isn't loaded + // at the top because Services.appinfo is defined late in tests. + let { RemotePages } = Cu.import("resource://gre/modules/RemotePageManager.jsm", {}); + + gPluginPageListener = new RemotePages("about:plugins"); + gPluginPageListener.addMessageListener("RequestPlugins", this.requestPlugins); + + 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 aProvider + * The provider to register + * @param aTypes + * An optional array of add-on types + */ + registerProvider: function(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: type, + providers: [aProvider] + }; + + let typeListeners = this.typeListeners.slice(0); + 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: function(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 == 0) { + let oldType = this.types[type].type; + delete this.types[type]; + + let typeListeners = this.typeListeners.slice(0); + 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 gShutdownBarrier 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); + gShutdownBarrier.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: function(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: function(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 = []; + if (gShutdownBarrier) { + state.push({ + name: gShutdownBarrier.client.name, + state: gShutdownBarrier.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 + */ + shutdownManager: Task.async(function*() { + 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); + Services.prefs.removeObserver(PREF_EM_HOTFIX_ID, this); + gPluginPageListener.destroy(); + gPluginPageListener = null; + + let savedError = null; + // Only shut down providers if they've been started. + if (gStarted) { + try { + yield gShutdownBarrier.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"; + yield 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.splice(0, this.managerListeners.length); + this.installListeners.splice(0, this.installListeners.length); + this.addonListeners.splice(0, this.addonListeners.length); + this.typeListeners.splice(0, this.typeListeners.length); + this.providerShutdowns.clear(); + for (let type in this.startupChanges) + delete this.startupChanges[type]; + gStarted = false; + gStartupComplete = false; + gShutdownBarrier = null; + gShutdownInProgress = false; + if (savedError) { + throw savedError; + } + }), + + requestPlugins: function({ target: port }) { + // Lists all the properties that plugins.html needs + const NEEDED_PROPS = ["name", "pluginLibraries", "pluginFullpath", "version", + "isActive", "blocklistState", "description", + "pluginMimeTypes"]; + function filterProperties(plugin) { + let filtered = {}; + for (let prop of NEEDED_PROPS) { + filtered[prop] = plugin[prop]; + } + return filtered; + } + + AddonManager.getAddonsByTypes(["plugin"], function(aPlugins) { + port.sendAsyncMessage("PluginList", aPlugins.map(filterProperties)); + }); + }, + + /** + * Notified when a preference we're interested in has changed. + * + * @see nsIObserver + */ + observe: function(aSubject, aTopic, aData) { + switch (aData) { + case PREF_EM_CHECK_COMPATIBILITY: { + let oldValue = gCheckCompatibility; + try { + gCheckCompatibility = Services.prefs.getBoolPref(PREF_EM_CHECK_COMPATIBILITY); + } catch (e) { + gCheckCompatibility = true; + } + + this.callManagerListeners("onCompatibilityModeChanged"); + + if (gCheckCompatibility != oldValue) + this.updateAddonAppDisabledStates(); + + break; + } + case PREF_EM_STRICT_COMPATIBILITY: { + let oldValue = gStrictCompatibility; + try { + gStrictCompatibility = Services.prefs.getBoolPref(PREF_EM_STRICT_COMPATIBILITY); + } catch (e) { + gStrictCompatibility = true; + } + + this.callManagerListeners("onCompatibilityModeChanged"); + + if (gStrictCompatibility != oldValue) + this.updateAddonAppDisabledStates(); + + break; + } + case PREF_EM_CHECK_UPDATE_SECURITY: { + let oldValue = gCheckUpdateSecurity; + try { + gCheckUpdateSecurity = Services.prefs.getBoolPref(PREF_EM_CHECK_UPDATE_SECURITY); + } catch (e) { + gCheckUpdateSecurity = true; + } + + this.callManagerListeners("onCheckUpdateSecurityChanged"); + + if (gCheckUpdateSecurity != oldValue) + this.updateAddonAppDisabledStates(); + + break; + } + case PREF_EM_UPDATE_ENABLED: { + let oldValue = gUpdateEnabled; + try { + gUpdateEnabled = Services.prefs.getBoolPref(PREF_EM_UPDATE_ENABLED); + } catch (e) { + gUpdateEnabled = true; + } + + this.callManagerListeners("onUpdateModeChanged"); + break; + } + case PREF_EM_AUTOUPDATE_DEFAULT: { + let oldValue = gAutoUpdateDefault; + try { + gAutoUpdateDefault = Services.prefs.getBoolPref(PREF_EM_AUTOUPDATE_DEFAULT); + } catch (e) { + gAutoUpdateDefault = true; + } + + this.callManagerListeners("onUpdateModeChanged"); + break; + } + case PREF_EM_HOTFIX_ID: { + try { + gHotfixID = Services.prefs.getCharPref(PREF_EM_HOTFIX_ID); + } catch (e) { + gHotfixID = null; + } + 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: function(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"; + if (aAddon.blocklistState == Ci.nsIBlocklistService.STATE_BLOCKED) + addonStatus += ",blocklisted"; + if (aAddon.blocklistState == Ci.nsIBlocklistService.STATE_SOFTBLOCKED) + addonStatus += ",softblocked"; + + try { + var xpcomABI = Services.appinfo.XPCOMABI; + } catch (ex) { + xpcomABI = UNKNOWN_XPCOM_ABI; + } + + let uri = aUri.replace(/%ITEM_ID%/g, aAddon.id); + uri = uri.replace(/%ITEM_VERSION%/g, aAddon.version); + uri = uri.replace(/%ITEM_STATUS%/g, addonStatus); + uri = uri.replace(/%APP_ID%/g, Services.appinfo.ID); + uri = uri.replace(/%APP_VERSION%/g, aAppVersion ? aAppVersion : + Services.appinfo.version); + uri = uri.replace(/%REQ_VERSION%/g, UPDATE_REQUEST_VERSION); + uri = uri.replace(/%APP_OS%/g, Services.appinfo.OS); + uri = uri.replace(/%APP_ABI%/g, xpcomABI); + uri = uri.replace(/%APP_LOCALE%/g, getLocale()); + uri = uri.replace(/%CURRENT_APP_VERSION%/g, Services.appinfo.version); + + // Replace custom parameters (names of custom parameters must have at + // least 3 characters to prevent lookups for something like %D0%C8) + var catMan = null; + uri = uri.replace(/%(\w{3,})%/g, function(aMatch, aParam) { + if (!catMan) { + catMan = Cc["@mozilla.org/categorymanager;1"]. + getService(Ci.nsICategoryManager); + } + + try { + var contractID = catMan.getCategoryEntry(CATEGORY_UPDATE_PARAMS, aParam); + var paramHandler = Cc[contractID].getService(Ci.nsIPropertyBag2); + return paramHandler.getPropertyAsAString(aParam); + } + catch (e) { + return aMatch; + } + }); + + // escape() does not properly encode + symbols in any embedded FVF strings. + return uri.replace(/\+/g, "%2B"); + }, + + /** + * 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: function() { + if (!gStarted) + throw Components.Exception("AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED); + + let buPromise = Task.spawn(function*() { + let hotfixID = this.hotfixID; + + let appUpdateEnabled = Services.prefs.getBoolPref(PREF_APP_UPDATE_ENABLED) && + Services.prefs.getBoolPref(PREF_APP_UPDATE_AUTO); + let checkHotfix = hotfixID && appUpdateEnabled; + + logger.debug("Background update check beginning"); + + Services.obs.notifyObservers(null, "addons-background-update-start", null); + + if (this.updateEnabled) { + let scope = {}; + Components.utils.import("resource://gre/modules/LightweightThemeManager.jsm", scope); + scope.LightweightThemeManager.updateCurrentTheme(); + + let allAddons = yield new Promise((resolve, reject) => this.getAllAddons(resolve)); + + // Repopulate repository cache first, to ensure compatibility overrides + // are up to date before checking for addon updates. + yield AddonRepository.backgroundUpdateCheck(); + + // Keep track of all the async add-on updates happening in parallel + let updates = []; + + for (let addon of allAddons) { + if (addon.id == hotfixID) { + continue; + } + + // Check all add-ons for updates so that any compatibility updates will + // be applied + updates.push(new Promise((resolve, reject) => { + addon.findUpdates({ + onUpdateAvailable: function(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}`); + aInstall.install(); + } + }, + + onUpdateFinished: aAddon => { logger.debug("onUpdateFinished for ${id}", aAddon); resolve(); } + }, AddonManager.UPDATE_WHEN_PERIODIC_UPDATE); + })); + } + yield Promise.all(updates); + } + + if (checkHotfix) { + var hotfixVersion = ""; + try { + hotfixVersion = Services.prefs.getCharPref(PREF_EM_HOTFIX_LASTVERSION); + } + catch (e) { } + + let url = null; + if (Services.prefs.getPrefType(PREF_EM_HOTFIX_URL) == Ci.nsIPrefBranch.PREF_STRING) + url = Services.prefs.getCharPref(PREF_EM_HOTFIX_URL); + else + url = Services.prefs.getCharPref(PREF_EM_UPDATE_BACKGROUND_URL); + + // Build the URI from a fake add-on data. + url = AddonManager.escapeAddonURI({ + id: hotfixID, + version: hotfixVersion, + userDisabled: false, + appDisabled: false + }, url); + + Components.utils.import("resource://gre/modules/addons/AddonUpdateChecker.jsm"); + let update = null; + try { + let foundUpdates = yield new Promise((resolve, reject) => { + AddonUpdateChecker.checkForUpdates(hotfixID, null, url, { + onUpdateCheckComplete: resolve, + onUpdateCheckError: reject + }); + }); + update = AddonUpdateChecker.getNewestCompatibleUpdate(foundUpdates); + } catch (e) { + // AUC.checkForUpdates already logged the error + } + + // Check that we have a hotfix update, and it's newer than the one we already + // have installed (if any) + if (update) { + if (Services.vc.compare(hotfixVersion, update.version) < 0) { + logger.debug("Downloading hotfix version " + update.version); + let aInstall = yield new Promise((resolve, reject) => + AddonManager.getInstallForURL(update.updateURL, resolve, + "application/x-xpinstall", update.updateHash, null, + null, update.version)); + + aInstall.addListener({ + onDownloadEnded: function(aInstall) { + if (aInstall.addon.id != hotfixID) { + logger.warn("The downloaded hotfix add-on did not have the " + + "expected ID and so will not be installed."); + aInstall.cancel(); + return; + } + + // If XPIProvider has reported the hotfix as properly signed then + // there is nothing more to do here + if (aInstall.addon.signedState == AddonManager.SIGNEDSTATE_SIGNED) + return; + + try { + if (!Services.prefs.getBoolPref(PREF_EM_CERT_CHECKATTRIBUTES)) + return; + } + catch (e) { + // By default don't do certificate checks. + return; + } + + try { + CertUtils.validateCert(aInstall.certificate, + CertUtils.readCertPrefs(PREF_EM_HOTFIX_CERTS)); + } + catch (e) { + logger.warn("The hotfix add-on was not signed by the expected " + + "certificate and so will not be installed.", e); + aInstall.cancel(); + } + }, + + onInstallEnded: function(aInstall) { + // Remember the last successfully installed version. + Services.prefs.setCharPref(PREF_EM_HOTFIX_LASTVERSION, + aInstall.version); + }, + + onInstallCancelled: function(aInstall) { + // Revert to the previous version if the installation was + // cancelled. + Services.prefs.setCharPref(PREF_EM_HOTFIX_LASTVERSION, + hotfixVersion); + } + }); + + aInstall.install(); + } + } + } + + if (appUpdateEnabled) { + try { + yield 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", + null); + }.bind(this)); + // Fork the promise chain so we can log the error and let our caller see it too. + buPromise.then(null, 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: function(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: function(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: function(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 = this.managerListeners.slice(0); + 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: function(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 = aExtraListeners.concat(this.installListeners); + else + listeners = this.installListeners.slice(0); + + 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: function(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 = this.addonListeners.slice(0); + 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 + */ + notifyAddonChanged: function(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. Furthermore, LightweightThemeManager may + // not be initialized until after XPIProvider is, and therefore would also + // be unaccessible during XPIProvider startup. Thankfully, these are the + // only two uses 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) { + callProvider(provider, "addonChanged", null, aID, aType, aPendingRestart); + } + }, + + /** + * 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: function() { + 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. + * + * @param aCallback + * Function to call when operation is complete. + */ + updateAddonRepositoryData: function(aCallback) { + if (!gStarted) + throw Components.Exception("AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED); + + if (typeof aCallback != "function") + throw Components.Exception("aCallback must be a function", + Cr.NS_ERROR_INVALID_ARG); + + new AsyncObjectCaller(this.providers, "updateAddonRepositoryData", { + nextObject: function(aCaller, aProvider) { + callProviderAsync(aProvider, "updateAddonRepositoryData", + aCaller.callNext.bind(aCaller)); + }, + noMoreObjects: function(aCaller) { + safeCall(aCallback); + // only tests should care about this + Services.obs.notifyObservers(null, "TEST:addon-repository-data-updated", null); + } + }); + }, + + /** + * Asynchronously gets an AddonInstall for a URL. + * + * @param aUrl + * The string represenation of the URL the add-on is located at + * @param aCallback + * A callback to pass the AddonInstall to + * @param aMimetype + * The mimetype of the add-on + * @param aHash + * An optional hash of the add-on + * @param aName + * An optional placeholder name while the add-on is being downloaded + * @param aIcons + * Optional placeholder icons while the add-on is being downloaded + * @param aVersion + * An optional placeholder version while the add-on is being downloaded + * @param aLoadGroup + * An optional nsILoadGroup to associate any network requests with + * @throws if the aUrl, aCallback or aMimetype arguments are not specified + */ + getInstallForURL: function(aUrl, aCallback, aMimetype, + aHash, aName, aIcons, + aVersion, aBrowser) { + 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 (typeof aCallback != "function") + throw Components.Exception("aCallback must be a function", + Cr.NS_ERROR_INVALID_ARG); + + if (!aMimetype || typeof aMimetype != "string") + throw Components.Exception("aMimetype must be a non-empty string", + Cr.NS_ERROR_INVALID_ARG); + + if (aHash && typeof aHash != "string") + throw Components.Exception("aHash must be a string or null", + Cr.NS_ERROR_INVALID_ARG); + + if (aName && typeof aName != "string") + throw Components.Exception("aName must be a string or null", + Cr.NS_ERROR_INVALID_ARG); + + if (aIcons) { + if (typeof aIcons == "string") + aIcons = { "32": aIcons }; + else if (typeof aIcons != "object") + throw Components.Exception("aIcons must be a string, an object or null", + Cr.NS_ERROR_INVALID_ARG); + } else { + aIcons = {}; + } + + if (aVersion && typeof aVersion != "string") + throw Components.Exception("aVersion must be a string or null", + Cr.NS_ERROR_INVALID_ARG); + + if (aBrowser && (!(aBrowser instanceof Ci.nsIDOMElement))) + throw Components.Exception("aBrowser must be a nsIDOMElement or null", + Cr.NS_ERROR_INVALID_ARG); + + let providers = [...this.providers]; + for (let provider of providers) { + if (callProvider(provider, "supportsMimetype", false, aMimetype)) { + callProviderAsync(provider, "getInstallForURL", + aUrl, aHash, aName, aIcons, aVersion, aBrowser, + function getInstallForURL_safeCall(aInstall) { + safeCall(aCallback, aInstall); + }); + return; + } + } + safeCall(aCallback, null); + }, + + /** + * Asynchronously gets an AddonInstall for an nsIFile. + * + * @param aFile + * The nsIFile where the add-on is located + * @param aCallback + * A callback to pass the AddonInstall to + * @param aMimetype + * An optional mimetype hint for the add-on + * @throws if the aFile or aCallback arguments are not specified + */ + getInstallForFile: function(aFile, aCallback, aMimetype) { + 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 (typeof aCallback != "function") + throw Components.Exception("aCallback must be a function", + 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); + + new AsyncObjectCaller(this.providers, "getInstallForFile", { + nextObject: function(aCaller, aProvider) { + callProviderAsync(aProvider, "getInstallForFile", aFile, + function(aInstall) { + if (aInstall) + safeCall(aCallback, aInstall); + else + aCaller.callNext(); + }); + }, + + noMoreObjects: function(aCaller) { + safeCall(aCallback, null); + } + }); + }, + + /** + * 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 + * @param aCallback + * A callback which will be passed an array of AddonInstalls + * @throws If the aCallback argument is not specified + */ + getInstallsByTypes: function(aTypes, aCallback) { + 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); + + if (typeof aCallback != "function") + throw Components.Exception("aCallback must be a function", + Cr.NS_ERROR_INVALID_ARG); + + let installs = []; + + new AsyncObjectCaller(this.providers, "getInstallsByTypes", { + nextObject: function(aCaller, aProvider) { + callProviderAsync(aProvider, "getInstallsByTypes", aTypes, + function(aProviderInstalls) { + if (aProviderInstalls) { + installs = installs.concat(aProviderInstalls); + } + aCaller.callNext(); + }); + }, + + noMoreObjects: function(aCaller) { + safeCall(aCallback, installs); + } + }); + }, + + /** + * Asynchronously gets all current AddonInstalls. + * + * @param aCallback + * A callback which will be passed an array of AddonInstalls + */ + getAllInstalls: function(aCallback) { + if (!gStarted) + throw Components.Exception("AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED); + + this.getInstallsByTypes(null, aCallback); + }, + + /** + * Synchronously map a URI to the corresponding Addon ID. + * + * Mappable URIs are limited to in-application resources belonging to the + * add-on, such as Javascript compartments, XUL windows, XBL bindings, etc. + * but do not include URIs from meta data, such as the add-on homepage. + * + * @param aURI + * nsIURI to map to an addon id + * @return string containing the Addon ID or null + * @see amIAddonManager.mapURIToAddonID + */ + mapURIToAddonID: function(aURI) { + if (!(aURI instanceof Ci.nsIURI)) { + throw Components.Exception("aURI is not a nsIURI", + Cr.NS_ERROR_INVALID_ARG); + } + + // Try all providers + let providers = [...this.providers]; + for (let provider of providers) { + var id = callProvider(provider, "mapURIToAddonID", null, aURI); + if (id !== null) { + return id; + } + } + + return 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: function(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: function(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); + + let providers = [...this.providers]; + for (let provider of providers) { + if (callProvider(provider, "supportsMimetype", false, aMimetype) && + callProvider(provider, "isInstallAllowed", null, aInstallingPrincipal)) + return true; + } + return false; + }, + + /** + * Starts installation of an array of AddonInstalls notifying the registered + * web install listener of blocked or started installs. + * + * @param aMimetype + * The mimetype of add-ons being installed + * @param aBrowser + * The optional browser element that started the installs + * @param aInstallingPrincipal + * The nsIPrincipal that initiated the install + * @param aInstalls + * The array of AddonInstalls to be installed + */ + installAddonsFromWebpage: function(aMimetype, aBrowser, + aInstallingPrincipal, aInstalls) { + 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 && !(aBrowser instanceof Ci.nsIDOMElement)) + throw Components.Exception("aSource must be a nsIDOMElement, 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); + + if (!Array.isArray(aInstalls)) + throw Components.Exception("aInstalls must be an array", + Cr.NS_ERROR_INVALID_ARG); + + if (!("@mozilla.org/addons/web-install-listener;1" in Cc)) { + logger.warn("No web installer available, cancelling all installs"); + for (let install of aInstalls) + install.cancel(); + return; + } + + // 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; + let docShell = aBrowser.ownerDocument.defaultView + .QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell) + .QueryInterface(Ci.nsIDocShellTreeItem); + if (docShell.itemType == Ci.nsIDocShellTreeItem.typeContent) + topBrowser = docShell.chromeEventHandler; + + try { + let weblistener = Cc["@mozilla.org/addons/web-install-listener;1"]. + getService(Ci.amIWebInstallListener); + + if (!this.isInstallEnabled(aMimetype)) { + for (let install of aInstalls) + install.cancel(); + + weblistener.onWebInstallDisabled(topBrowser, aInstallingPrincipal.URI, + aInstalls, aInstalls.length); + return; + } + else if (!aBrowser.contentPrincipal || !aInstallingPrincipal.subsumes(aBrowser.contentPrincipal)) { + for (let install of aInstalls) + install.cancel(); + + if (weblistener instanceof Ci.amIWebInstallListener2) { + weblistener.onWebInstallOriginBlocked(topBrowser, aInstallingPrincipal.URI, + aInstalls, aInstalls.length); + } + return; + } + + // The installs may start now depending on the web install listener, + // listen for the browser navigating to a new origin and cancel the + // installs in that case. + new BrowserListener(aBrowser, aInstallingPrincipal, aInstalls); + + if (!this.isInstallAllowed(aMimetype, aInstallingPrincipal)) { + if (weblistener.onWebInstallBlocked(topBrowser, aInstallingPrincipal.URI, + aInstalls, aInstalls.length)) { + for (let install of aInstalls) + install.install(); + } + } + else if (weblistener.onWebInstallRequested(topBrowser, aInstallingPrincipal.URI, + aInstalls, aInstalls.length)) { + for (let install of aInstalls) + install.install(); + } + } + catch (e) { + // In the event that the weblistener throws during instantiation or when + // calling onWebInstallBlocked or onWebInstallRequested all of the + // installs should get cancelled. + logger.warn("Failure calling web installer", e); + for (let install of aInstalls) + install.cancel(); + } + }, + + /** + * Adds a new InstallListener if the listener is not already registered. + * + * @param aListener + * The InstallListener to add + */ + addInstallListener: function(aListener) { + if (!aListener || typeof aListener != "object") + throw Components.Exception("aListener must be a InstallListener object", + Cr.NS_ERROR_INVALID_ARG); + + if (!this.installListeners.some(function(i) { + return i == aListener; })) + this.installListeners.push(aListener); + }, + + /** + * Removes an InstallListener if the listener is registered. + * + * @param aListener + * The InstallListener to remove + */ + removeInstallListener: function(aListener) { + if (!aListener || typeof aListener != "object") + throw Components.Exception("aListener must be a InstallListener object", + Cr.NS_ERROR_INVALID_ARG); + + let pos = 0; + while (pos < this.installListeners.length) { + if (this.installListeners[pos] == aListener) + this.installListeners.splice(pos, 1); + else + pos++; + } + }, + /* + * 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: function(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); + + this.getAddonByInstanceID(aInstanceID).then(wrapper => { + if (!wrapper) { + throw Error("No addon matching instanceID:", aInstanceID.toString()); + } + let addonId = wrapper.addonId(); + 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: function(aInstanceID) { + if (!aInstanceID || typeof aInstanceID != "symbol") + throw Components.Exception("aInstanceID must be a symbol", + Cr.NS_ERROR_INVALID_ARG); + + this.getAddonByInstanceID(aInstanceID).then(addon => { + if (!addon) { + throw Error("No addon for instanceID:", aInstanceID.toString()); + } + if (this.upgradeListeners.has(addon.id)) { + this.upgradeListeners.delete(addon.id); + } else { + throw Error("No upgrade listener registered for addon ID:", addon.id); + } + }); + }, + + /** + * 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. + * @return 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: function(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); + }, + + installAddonFromSources: function(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") + .installAddonFromSources(aFile); + }, + + /** + * Returns an Addon corresponding to an instance ID. + * @param aInstanceID + * An Addon Instance ID symbol + * @return {Promise} + * @resolves The found Addon or null if no such add-on exists. + * @rejects Never + * @throws if the aInstanceID argument is not specified + * or the AddonManager is not initialized + */ + getAddonByInstanceID: function(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") + .getAddonByInstanceID(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 + * and icon64URL 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: function(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; + } + if (aAddon.icon64URL) { + icons[64] = aAddon.icon64URL; + } + } + + // 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. + * + * @param aID + * The ID of the add-on to retrieve + * @return {Promise} + * @resolves The found Addon or null if no such add-on exists. + * @rejects Never + * @throws if the aID argument is not specified + */ + getAddonByID: function(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 + * @param aCallback + * The callback to pass the retrieved add-on to. + * @throws if the aGUID or aCallback arguments are not specified + */ + getAddonBySyncGUID: function(aGUID, aCallback) { + 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); + + if (typeof aCallback != "function") + throw Components.Exception("aCallback must be a function", + Cr.NS_ERROR_INVALID_ARG); + + new AsyncObjectCaller(this.providers, "getAddonBySyncGUID", { + nextObject: function(aCaller, aProvider) { + callProviderAsync(aProvider, "getAddonBySyncGUID", aGUID, + function(aAddon) { + if (aAddon) { + safeCall(aCallback, aAddon); + } else { + aCaller.callNext(); + } + }); + }, + + noMoreObjects: function(aCaller) { + safeCall(aCallback, 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: function(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 + * @param aCallback + * The callback to pass an array of Addons to. + * @throws if the aCallback argument is not specified + */ + getAddonsByTypes: function(aTypes, aCallback) { + 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); + + if (typeof aCallback != "function") + throw Components.Exception("aCallback must be a function", + Cr.NS_ERROR_INVALID_ARG); + + let addons = []; + + new AsyncObjectCaller(this.providers, "getAddonsByTypes", { + nextObject: function(aCaller, aProvider) { + callProviderAsync(aProvider, "getAddonsByTypes", aTypes, + function(aProviderAddons) { + if (aProviderAddons) { + addons = addons.concat(aProviderAddons); + } + aCaller.callNext(); + }); + }, + + noMoreObjects: function(aCaller) { + safeCall(aCallback, addons); + } + }); + }, + + /** + * Asynchronously gets all installed add-ons. + * + * @param aCallback + * A callback which will be passed an array of Addons + */ + getAllAddons: function(aCallback) { + if (!gStarted) + throw Components.Exception("AddonManager is not initialized", + Cr.NS_ERROR_NOT_INITIALIZED); + + if (typeof aCallback != "function") + throw Components.Exception("aCallback must be a function", + Cr.NS_ERROR_INVALID_ARG); + + this.getAddonsByTypes(null, aCallback); + }, + + /** + * Asynchronously gets add-ons that have operations waiting for an application + * restart to complete. + * + * @param aTypes + * An optional array of types to retrieve. Each type is a string name + * @param aCallback + * The callback to pass the array of Addons to + * @throws if the aCallback argument is not specified + */ + getAddonsWithOperationsByTypes: function(aTypes, aCallback) { + 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); + + if (typeof aCallback != "function") + throw Components.Exception("aCallback must be a function", + Cr.NS_ERROR_INVALID_ARG); + + let addons = []; + + new AsyncObjectCaller(this.providers, "getAddonsWithOperationsByTypes", { + nextObject: function getAddonsWithOperationsByTypes_nextObject + (aCaller, aProvider) { + callProviderAsync(aProvider, "getAddonsWithOperationsByTypes", aTypes, + function getAddonsWithOperationsByTypes_concatAddons + (aProviderAddons) { + if (aProviderAddons) { + addons = addons.concat(aProviderAddons); + } + aCaller.callNext(); + }); + }, + + noMoreObjects: function(caller) { + safeCall(aCallback, addons); + } + }); + }, + + /** + * Adds a new AddonManagerListener if the listener is not already registered. + * + * @param aListener + * The listener to add + */ + addManagerListener: function(aListener) { + if (!aListener || typeof aListener != "object") + throw Components.Exception("aListener must be an AddonManagerListener object", + Cr.NS_ERROR_INVALID_ARG); + + if (!this.managerListeners.some(i => i == aListener)) + this.managerListeners.push(aListener); + }, + + /** + * Removes an AddonManagerListener if the listener is registered. + * + * @param aListener + * The listener to remove + */ + removeManagerListener: function(aListener) { + if (!aListener || typeof aListener != "object") + throw Components.Exception("aListener must be an AddonManagerListener object", + Cr.NS_ERROR_INVALID_ARG); + + let pos = 0; + while (pos < this.managerListeners.length) { + if (this.managerListeners[pos] == aListener) + this.managerListeners.splice(pos, 1); + else + pos++; + } + }, + + /** + * Adds a new AddonListener if the listener is not already registered. + * + * @param aListener + * The AddonListener to add + */ + addAddonListener: function(aListener) { + if (!aListener || typeof aListener != "object") + throw Components.Exception("aListener must be an AddonListener object", + Cr.NS_ERROR_INVALID_ARG); + + if (!this.addonListeners.some(i => i == aListener)) + this.addonListeners.push(aListener); + }, + + /** + * Removes an AddonListener if the listener is registered. + * + * @param aListener + * The AddonListener to remove + */ + removeAddonListener: function(aListener) { + if (!aListener || typeof aListener != "object") + throw Components.Exception("aListener must be an AddonListener object", + Cr.NS_ERROR_INVALID_ARG); + + let pos = 0; + while (pos < this.addonListeners.length) { + if (this.addonListeners[pos] == aListener) + this.addonListeners.splice(pos, 1); + else + pos++; + } + }, + + /** + * Adds a new TypeListener if the listener is not already registered. + * + * @param aListener + * The TypeListener to add + */ + addTypeListener: function(aListener) { + if (!aListener || typeof aListener != "object") + throw Components.Exception("aListener must be a TypeListener object", + Cr.NS_ERROR_INVALID_ARG); + + if (!this.typeListeners.some(i => i == aListener)) + this.typeListeners.push(aListener); + }, + + /** + * Removes an TypeListener if the listener is registered. + * + * @param aListener + * The TypeListener to remove + */ + removeTypeListener: function(aListener) { + if (!aListener || typeof aListener != "object") + throw Components.Exception("aListener must be a TypeListener object", + Cr.NS_ERROR_INVALID_ARG); + + let pos = 0; + while (pos < this.typeListeners.length) { + if (this.typeListeners[pos] == aListener) + this.typeListeners.splice(pos, 1); + else + pos++; + } + }, + + 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; + }, + + get hotfixID() { + return gHotfixID; + }, + + webAPI: { + // installs maps integer ids to AddonInstall instances. + installs: new Map(), + nextInstall: 0, + + sendEvent: null, + setEventHandler(fn) { + this.sendEvent = fn; + }, + + getAddonByID(target, id) { + return new Promise(resolve => { + AddonManager.getAddonByID(id, (addon) => { + resolve(webAPIForAddon(addon)); + }); + }); + }, + + // 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; + }, + + makeListener(id, mm) { + const events = [ + "onDownloadStarted", + "onDownloadProgress", + "onDownloadEnded", + "onDownloadCancelled", + "onDownloadFailed", + "onInstallStarted", + "onInstallEnded", + "onInstallCancelled", + "onInstallFailed", + ]; + + let listener = {}; + events.forEach(event => { + listener[event] = (install) => { + let data = {event, id}; + AddonManager.webAPI.copyProps(install, data); + this.sendEvent(mm, data); + } + }); + return listener; + }, + + 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, null, null).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`); + } + + return new Promise((resolve, reject) => { + try { + checkInstallUrl(options.url); + } catch (err) { + reject({message: err.message}); + return; + } + + let newInstall = install => { + let id = this.nextInstall++; + let listener = this.makeListener(id, target.messageManager); + install.addListener(listener); + + this.installs.set(id, {install, target, listener}); + + let result = {id}; + this.copyProps(install, result); + resolve(result); + }; + AddonManager.getInstallForURL(options.url, newInstall, "application/x-xpinstall", options.hash); + }); + }, + + addonUninstall(target, id) { + return new Promise(resolve => { + AddonManager.getAddonByID(id, addon => { + if (!addon) { + resolve(false); + } + + try { + addon.uninstall(); + resolve(true); + } catch (err) { + Cu.reportError(err); + resolve(false); + } + }); + }); + }, + + addonSetEnabled(target, id, value) { + return new Promise((resolve, reject) => { + AddonManager.getAddonByID(id, addon => { + if (!addon) { + reject({message: `No such addon ${id}`}); + } + addon.userDisabled = !value; + resolve(); + }); + }); + }, + + addonInstallDoInstall(target, id) { + let state = this.installs.get(id); + if (!state) { + return Promise.reject(`invalid id ${id}`); + } + return Promise.resolve(state.install.install()); + }, + + 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.target.messageManager == mm) { + this.forgetInstall(id); + } + } + }, + }, +}; + +/** + * 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. + */ +this.AddonManagerPrivate = { + startup: function() { + AddonManagerInternal.startup(); + }, + + registerProvider: function(aProvider, aTypes) { + AddonManagerInternal.registerProvider(aProvider, aTypes); + }, + + unregisterProvider: function(aProvider) { + AddonManagerInternal.unregisterProvider(aProvider); + }, + + markProviderSafe: function(aProvider) { + AddonManagerInternal.markProviderSafe(aProvider); + }, + + backgroundUpdateCheck: function() { + return AddonManagerInternal.backgroundUpdateCheck(); + }, + + backgroundUpdateTimerHandler() { + // Don't call through to the real update check if no checks are enabled. + let checkHotfix = AddonManagerInternal.hotfixID && + Services.prefs.getBoolPref(PREF_APP_UPDATE_ENABLED) && + Services.prefs.getBoolPref(PREF_APP_UPDATE_AUTO); + + if (!AddonManagerInternal.updateEnabled && !checkHotfix) { + logger.info("Skipping background update check"); + return; + } + // Don't return the promise here, since the caller doesn't care. + AddonManagerInternal.backgroundUpdateCheck(); + }, + + addStartupChange: function(aType, aID) { + AddonManagerInternal.addStartupChange(aType, aID); + }, + + removeStartupChange: function(aType, aID) { + AddonManagerInternal.removeStartupChange(aType, aID); + }, + + notifyAddonChanged: function(aID, aType, aPendingRestart) { + AddonManagerInternal.notifyAddonChanged(aID, aType, aPendingRestart); + }, + + updateAddonAppDisabledStates: function() { + AddonManagerInternal.updateAddonAppDisabledStates(); + }, + + updateAddonRepositoryData: function(aCallback) { + AddonManagerInternal.updateAddonRepositoryData(aCallback); + }, + + callInstallListeners: function(...aArgs) { + return AddonManagerInternal.callInstallListeners.apply(AddonManagerInternal, + aArgs); + }, + + callAddonListeners: function(...aArgs) { + AddonManagerInternal.callAddonListeners.apply(AddonManagerInternal, aArgs); + }, + + AddonAuthor: AddonAuthor, + + AddonScreenshot: AddonScreenshot, + + AddonCompatibilityOverride: AddonCompatibilityOverride, + + AddonType: AddonType, + + recordTimestamp: function(name, value) { + AddonManagerInternal.recordTimestamp(name, value); + }, + + _simpleMeasures: {}, + recordSimpleMeasure: function(name, value) { + this._simpleMeasures[name] = value; + }, + + recordException: function(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: function() { + return this._simpleMeasures; + }, + + getTelemetryDetails: function() { + return AddonManagerInternal.telemetryDetails; + }, + + setTelemetryDetails: function(aProvider, aDetails) { + AddonManagerInternal.telemetryDetails[aProvider] = aDetails; + }, + + // Start a timer, record a simple measure of the time interval when + // timer.done() is called + simpleTimer: function(aName) { + let startTime = Cu.now(); + return { + done: () => this.recordSimpleMeasure(aName, Math.round(Cu.now() - startTime)) + }; + }, + + /** + * 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: function(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: function(aId) { + return AddonManagerInternal.upgradeListeners.has(aId); + }, + + getUpgradeListener: function(aId) { + return AddonManagerInternal.upgradeListeners.get(aId); + }, +}; + +/** + * This is the public API that UI and developers should be calling. All methods + * just forward to AddonManagerInternal. + */ +this.AddonManager = { + // 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 for compatibility information. + ["STATE_CHECKING", 2], + // The install is downloaded and ready to install. + ["STATE_DOWNLOADED", 3], + // The download failed. + ["STATE_DOWNLOAD_FAILED", 4], + // The install has been postponed. + ["STATE_POSTPONED", 5], + // The add-on is being installed. + ["STATE_INSTALLING", 6], + // The add-on has been installed. + ["STATE_INSTALLED", 7], + // The install failed. + ["STATE_INSTALL_FAILED", 8], + // The install has been cancelled. + ["STATE_CANCELLED", 9], + ]), + + // 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 occured 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], + ]), + + // 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, + + // 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 opened in a new window + OPTIONS_TYPE_DIALOG: 1, + // Options will be displayed within the AM detail view + OPTIONS_TYPE_INLINE: 2, + // Options will be displayed in a new tab, if possible + OPTIONS_TYPE_TAB: 3, + // Same as OPTIONS_TYPE_INLINE, but no Preferences button will be shown. + // Used to indicate that only non-interactive information will be shown. + OPTIONS_TYPE_INLINE_INFO: 4, + // 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, + + // 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; + }, + + get isReady() { + return gStartupComplete && !gShutdownInProgress; + }, + + 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; + }, + + getInstallForURL: function(aUrl, aCallback, aMimetype, + aHash, aName, aIcons, + aVersion, aBrowser) { + AddonManagerInternal.getInstallForURL(aUrl, aCallback, aMimetype, aHash, + aName, aIcons, aVersion, aBrowser); + }, + + getInstallForFile: function(aFile, aCallback, aMimetype) { + AddonManagerInternal.getInstallForFile(aFile, aCallback, aMimetype); + }, + + /** + * 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: function(aType) { + if (!(aType in AddonManagerInternal.startupChanges)) + return []; + return AddonManagerInternal.startupChanges[aType].slice(0); + }, + + getAddonByID: function(aID, aCallback) { + if (typeof aCallback != "function") + throw Components.Exception("aCallback must be a function", + Cr.NS_ERROR_INVALID_ARG); + + AddonManagerInternal.getAddonByID(aID) + .then(makeSafe(aCallback)) + .catch(logger.error); + }, + + getAddonBySyncGUID: function(aGUID, aCallback) { + AddonManagerInternal.getAddonBySyncGUID(aGUID, aCallback); + }, + + getAddonsByIDs: function(aIDs, aCallback) { + if (typeof aCallback != "function") + throw Components.Exception("aCallback must be a function", + Cr.NS_ERROR_INVALID_ARG); + + AddonManagerInternal.getAddonsByIDs(aIDs) + .then(makeSafe(aCallback)) + .catch(logger.error); + }, + + getAddonsWithOperationsByTypes: function(aTypes, aCallback) { + AddonManagerInternal.getAddonsWithOperationsByTypes(aTypes, aCallback); + }, + + getAddonsByTypes: function(aTypes, aCallback) { + AddonManagerInternal.getAddonsByTypes(aTypes, aCallback); + }, + + getAllAddons: function(aCallback) { + AddonManagerInternal.getAllAddons(aCallback); + }, + + getInstallsByTypes: function(aTypes, aCallback) { + AddonManagerInternal.getInstallsByTypes(aTypes, aCallback); + }, + + getAllInstalls: function(aCallback) { + AddonManagerInternal.getAllInstalls(aCallback); + }, + + mapURIToAddonID: function(aURI) { + return AddonManagerInternal.mapURIToAddonID(aURI); + }, + + isInstallEnabled: function(aType) { + return AddonManagerInternal.isInstallEnabled(aType); + }, + + isInstallAllowed: function(aType, aInstallingPrincipal) { + return AddonManagerInternal.isInstallAllowed(aType, aInstallingPrincipal); + }, + + installAddonsFromWebpage: function(aType, aBrowser, aInstallingPrincipal, + aInstalls) { + AddonManagerInternal.installAddonsFromWebpage(aType, aBrowser, + aInstallingPrincipal, + aInstalls); + }, + + installTemporaryAddon: function(aDirectory) { + return AddonManagerInternal.installTemporaryAddon(aDirectory); + }, + + installAddonFromSources: function(aDirectory) { + return AddonManagerInternal.installAddonFromSources(aDirectory); + }, + + getAddonByInstanceID: function(aInstanceID) { + return AddonManagerInternal.getAddonByInstanceID(aInstanceID); + }, + + addManagerListener: function(aListener) { + AddonManagerInternal.addManagerListener(aListener); + }, + + removeManagerListener: function(aListener) { + AddonManagerInternal.removeManagerListener(aListener); + }, + + addInstallListener: function(aListener) { + AddonManagerInternal.addInstallListener(aListener); + }, + + removeInstallListener: function(aListener) { + AddonManagerInternal.removeInstallListener(aListener); + }, + + getUpgradeListener: function(aId) { + return AddonManagerInternal.upgradeListeners.get(aId); + }, + + addUpgradeListener: function(aInstanceID, aCallback) { + AddonManagerInternal.addUpgradeListener(aInstanceID, aCallback); + }, + + removeUpgradeListener: function(aInstanceID) { + AddonManagerInternal.removeUpgradeListener(aInstanceID); + }, + + addAddonListener: function(aListener) { + AddonManagerInternal.addAddonListener(aListener); + }, + + removeAddonListener: function(aListener) { + AddonManagerInternal.removeAddonListener(aListener); + }, + + addTypeListener: function(aListener) { + AddonManagerInternal.addTypeListener(aListener); + }, + + removeTypeListener: function(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: function(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; + }, + + get hotfixID() { + return AddonManagerInternal.hotfixID; + }, + + escapeAddonURI: function(aAddon, aUri, aAppVersion) { + return AddonManagerInternal.escapeAddonURI(aAddon, aUri, aAppVersion); + }, + + getPreferredIconURL: function(aAddon, aSize, aWindow = undefined) { + return AddonManagerInternal.getPreferredIconURL(aAddon, aSize, aWindow); + }, + + get webAPI() { + return AddonManagerInternal.webAPI; + }, + + get shutdown() { + return gShutdownBarrier.client; + }, +}; + +this.AddonManager.init(); + +// load the timestamps module into AddonManagerInternal +Cu.import("resource://gre/modules/TelemetryTimestamps.jsm", AddonManagerInternal); +Object.freeze(AddonManagerInternal); +Object.freeze(AddonManagerPrivate); +Object.freeze(AddonManager); diff --git a/toolkit/mozapps/webextensions/AddonManagerWebAPI.cpp b/toolkit/mozapps/webextensions/AddonManagerWebAPI.cpp new file mode 100644 index 000000000..3f2a7a529 --- /dev/null +++ b/toolkit/mozapps/webextensions/AddonManagerWebAPI.cpp @@ -0,0 +1,171 @@ +/* -*- 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/dom/Navigator.h" +#include "mozilla/dom/NavigatorBinding.h" + +#include "mozilla/Preferences.h" +#include "nsGlobalWindow.h" + +#include "nsIDocShell.h" +#include "nsIScriptObjectPrincipal.h" + +namespace mozilla { +using namespace mozilla::dom; + +static bool +IsValidHost(const nsACString& host) { + // This is ugly, but Preferences.h doesn't have support + // for default prefs or locked prefs + nsCOMPtr prefService (do_GetService(NS_PREFSERVICE_CONTRACTID)); + nsCOMPtr prefs; + if (prefService) { + prefService->GetDefaultBranch(nullptr, getter_AddRefs(prefs)); + bool isEnabled; + if (NS_SUCCEEDED(prefs->GetBoolPref("xpinstall.enabled", &isEnabled)) && !isEnabled) { + bool isLocked; + prefs->PrefIsLocked("xpinstall.enabled", &isLocked); + if (isLocked) { + return false; + } + } + } + + if (host.Equals("addons.mozilla.org") || + host.Equals("discovery.addons.mozilla.org") || + host.Equals("testpilot.firefox.com")) { + 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("discovery.addons.allizom.org") || + host.LowerCaseEqualsLiteral("addons-dev.allizom.org") || + host.LowerCaseEqualsLiteral("discovery.addons-dev.allizom.org") || + host.LowerCaseEqualsLiteral("testpilot.stage.mozaws.net") || + host.LowerCaseEqualsLiteral("testpilot.dev.mozaws.net") || + 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; + } + + bool isSecure; + nsresult rv = uri->SchemeIs("https", &isSecure); + if (NS_FAILED(rv) || !isSecure) { + return false; + } + + nsAutoCString host; + rv = uri->GetHost(host); + if (NS_FAILED(rv)) { + return false; + } + + return IsValidHost(host); +} + +bool +AddonManagerWebAPI::IsAPIEnabled(JSContext* cx, JSObject* obj) +{ + nsGlobalWindow* global = xpc::WindowGlobalOrNull(obj); + if (!global) { + return false; + } + + nsCOMPtr win = global->AsInner(); + 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->GetIsSystemPrincipal()) { + 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 boundaries. + nsCOMPtr parent; + nsresult rv = docShell->GetSameTypeParent(getter_AddRefs(parent)); + if (NS_FAILED(rv)) { + return false; + } + + if (!parent) { + // No parent means we've hit a mozbrowser or chrome boundary so allow + // access to the API. + return true; + } + + nsIDocument* doc = win->GetDoc(); + if (!doc) { + return false; + } + + doc = doc->GetParentDocument(); + 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; +} + +namespace dom { + +bool +AddonManagerPermissions::IsHostPermitted(const GlobalObject& /*unused*/, const nsAString& host) +{ + return IsValidHost(NS_ConvertUTF16toUTF8(host)); +} + +} // namespace mozilla::dom + + +} // namespace mozilla diff --git a/toolkit/mozapps/webextensions/AddonManagerWebAPI.h b/toolkit/mozapps/webextensions/AddonManagerWebAPI.h new file mode 100644 index 000000000..6830bc91f --- /dev/null +++ b/toolkit/mozapps/webextensions/AddonManagerWebAPI.h @@ -0,0 +1,33 @@ +/* -*- 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* cx, JSObject* obj); + +private: + static bool IsValidSite(nsIURI* uri); +}; + +namespace dom { + +class AddonManagerPermissions { +public: + static bool IsHostPermitted(const GlobalObject&, const nsAString& host); +}; + +} // namespace mozilla::dom + +} // namespace mozilla + +#endif // addonmanagerwebapi_h_ diff --git a/toolkit/mozapps/webextensions/AddonPathService.cpp b/toolkit/mozapps/webextensions/AddonPathService.cpp new file mode 100644 index 000000000..8a405c0ea --- /dev/null +++ b/toolkit/mozapps/webextensions/AddonPathService.cpp @@ -0,0 +1,258 @@ +/* -*- Mode: C++; tab-width: 8; 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 "AddonPathService.h" + +#include "amIAddonManager.h" +#include "nsIURI.h" +#include "nsXULAppAPI.h" +#include "jsapi.h" +#include "nsServiceManagerUtils.h" +#include "nsLiteralString.h" +#include "nsThreadUtils.h" +#include "nsIIOService.h" +#include "nsNetUtil.h" +#include "nsIAddonPolicyService.h" +#include "nsIFileURL.h" +#include "nsIResProtocolHandler.h" +#include "nsIChromeRegistry.h" +#include "nsIJARURI.h" +#include "nsJSUtils.h" +#include "mozilla/dom/ScriptSettings.h" +#include "mozilla/dom/ToJSValue.h" +#include "mozilla/AddonPathService.h" +#include "mozilla/Omnijar.h" + +#include + +namespace mozilla { + +struct PathEntryComparator +{ + typedef AddonPathService::PathEntry PathEntry; + + bool Equals(const PathEntry& entry1, const PathEntry& entry2) const + { + return entry1.mPath == entry2.mPath; + } + + bool LessThan(const PathEntry& entry1, const PathEntry& entry2) const + { + return entry1.mPath < entry2.mPath; + } +}; + +AddonPathService::AddonPathService() +{ +} + +AddonPathService::~AddonPathService() +{ + sInstance = nullptr; +} + +NS_IMPL_ISUPPORTS(AddonPathService, amIAddonPathService) + +AddonPathService *AddonPathService::sInstance; + +/* static */ AddonPathService* +AddonPathService::GetInstance() +{ + if (!sInstance) { + sInstance = new AddonPathService(); + } + NS_ADDREF(sInstance); + return sInstance; +} + +static JSAddonId* +ConvertAddonId(const nsAString& addonIdString) +{ + AutoSafeJSContext cx; + JS::RootedValue strv(cx); + if (!mozilla::dom::ToJSValue(cx, addonIdString, &strv)) { + return nullptr; + } + JS::RootedString str(cx, strv.toString()); + return JS::NewAddonId(cx, str); +} + +JSAddonId* +AddonPathService::Find(const nsAString& path) +{ + // Use binary search to find the nearest entry that is <= |path|. + PathEntryComparator comparator; + unsigned index = mPaths.IndexOfFirstElementGt(PathEntry(path, nullptr), comparator); + if (index == 0) { + return nullptr; + } + const PathEntry& entry = mPaths[index - 1]; + + // Return the entry's addon if its path is a prefix of |path|. + if (StringBeginsWith(path, entry.mPath)) { + return entry.mAddonId; + } + return nullptr; +} + +NS_IMETHODIMP +AddonPathService::FindAddonId(const nsAString& path, nsAString& addonIdString) +{ + if (JSAddonId* id = Find(path)) { + JSFlatString* flat = JS_ASSERT_STRING_IS_FLAT(JS::StringOfAddonId(id)); + AssignJSFlatString(addonIdString, flat); + } + return NS_OK; +} + +/* static */ JSAddonId* +AddonPathService::FindAddonId(const nsAString& path) +{ + // If no service has been created, then we're not going to find anything. + if (!sInstance) { + return nullptr; + } + + return sInstance->Find(path); +} + +NS_IMETHODIMP +AddonPathService::InsertPath(const nsAString& path, const nsAString& addonIdString) +{ + JSAddonId* addonId = ConvertAddonId(addonIdString); + + // Add the new path in sorted order. + PathEntryComparator comparator; + mPaths.InsertElementSorted(PathEntry(path, addonId), comparator); + return NS_OK; +} + +NS_IMETHODIMP +AddonPathService::MapURIToAddonId(nsIURI* aURI, nsAString& addonIdString) +{ + if (JSAddonId* id = MapURIToAddonID(aURI)) { + JSFlatString* flat = JS_ASSERT_STRING_IS_FLAT(JS::StringOfAddonId(id)); + AssignJSFlatString(addonIdString, flat); + } + return NS_OK; +} + +static nsresult +ResolveURI(nsIURI* aURI, nsAString& out) +{ + bool equals; + nsresult rv; + nsCOMPtr uri; + nsAutoCString spec; + + // Resolve resource:// URIs. At the end of this if/else block, we + // have both spec and uri variables identifying the same URI. + if (NS_SUCCEEDED(aURI->SchemeIs("resource", &equals)) && equals) { + nsCOMPtr ioService = do_GetIOService(&rv); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + + nsCOMPtr ph; + rv = ioService->GetProtocolHandler("resource", getter_AddRefs(ph)); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + + nsCOMPtr irph(do_QueryInterface(ph, &rv)); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + + rv = irph->ResolveURI(aURI, spec); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + + rv = ioService->NewURI(spec, nullptr, nullptr, getter_AddRefs(uri)); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + } else if (NS_SUCCEEDED(aURI->SchemeIs("chrome", &equals)) && equals) { + nsCOMPtr chromeReg = + mozilla::services::GetChromeRegistryService(); + if (NS_WARN_IF(!chromeReg)) + return NS_ERROR_UNEXPECTED; + + rv = chromeReg->ConvertChromeURL(aURI, getter_AddRefs(uri)); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + } else { + uri = aURI; + } + + if (NS_SUCCEEDED(uri->SchemeIs("jar", &equals)) && equals) { + nsCOMPtr jarURI = do_QueryInterface(uri, &rv); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + + nsCOMPtr jarFileURI; + rv = jarURI->GetJARFile(getter_AddRefs(jarFileURI)); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + + return ResolveURI(jarFileURI, out); + } + + if (NS_SUCCEEDED(uri->SchemeIs("file", &equals)) && equals) { + nsCOMPtr baseFileURL = do_QueryInterface(uri, &rv); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + + nsCOMPtr file; + rv = baseFileURL->GetFile(getter_AddRefs(file)); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + + return file->GetPath(out); + } + return NS_ERROR_FAILURE; +} + +JSAddonId* +MapURIToAddonID(nsIURI* aURI) +{ + if (!NS_IsMainThread() || !XRE_IsParentProcess()) { + return nullptr; + } + + bool equals; + nsresult rv; + if (NS_SUCCEEDED(aURI->SchemeIs("moz-extension", &equals)) && equals) { + nsCOMPtr service = do_GetService("@mozilla.org/addons/policy-service;1"); + if (service) { + nsString addonId; + rv = service->ExtensionURIToAddonId(aURI, addonId); + if (NS_FAILED(rv)) + return nullptr; + + return ConvertAddonId(addonId); + } + } + + nsAutoString filePath; + rv = ResolveURI(aURI, filePath); + if (NS_FAILED(rv)) + return nullptr; + + nsCOMPtr greJar = Omnijar::GetPath(Omnijar::GRE); + nsCOMPtr appJar = Omnijar::GetPath(Omnijar::APP); + if (greJar && appJar) { + nsAutoString greJarString, appJarString; + if (NS_FAILED(greJar->GetPath(greJarString)) || NS_FAILED(appJar->GetPath(appJarString))) + return nullptr; + + // If |aURI| is part of either Omnijar, then it can't be part of an + // add-on. This catches pretty much all URLs for Firefox content. + if (filePath.Equals(greJarString) || filePath.Equals(appJarString)) + return nullptr; + } + + // If it's not part of Firefox, we resort to binary searching through the + // add-on paths. + return AddonPathService::FindAddonId(filePath); +} + +} // namespace mozilla diff --git a/toolkit/mozapps/webextensions/AddonPathService.h b/toolkit/mozapps/webextensions/AddonPathService.h new file mode 100644 index 000000000..f739b018f --- /dev/null +++ b/toolkit/mozapps/webextensions/AddonPathService.h @@ -0,0 +1,55 @@ +//* -*- Mode: C++; tab-width: 8; 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 AddonPathService_h +#define AddonPathService_h + +#include "amIAddonPathService.h" +#include "nsString.h" +#include "nsTArray.h" + +class nsIURI; +class JSAddonId; + +namespace mozilla { + +JSAddonId* +MapURIToAddonID(nsIURI* aURI); + +class AddonPathService final : public amIAddonPathService +{ +public: + AddonPathService(); + + static AddonPathService* GetInstance(); + + JSAddonId* Find(const nsAString& path); + static JSAddonId* FindAddonId(const nsAString& path); + + NS_DECL_ISUPPORTS + NS_DECL_AMIADDONPATHSERVICE + + struct PathEntry + { + nsString mPath; + JSAddonId* mAddonId; + + PathEntry(const nsAString& aPath, JSAddonId* aAddonId) + : mPath(aPath), mAddonId(aAddonId) + {} + }; + +private: + virtual ~AddonPathService(); + + // Paths are stored sorted in order of their mPath. + nsTArray mPaths; + + static AddonPathService* sInstance; +}; + +} // namespace mozilla + +#endif diff --git a/toolkit/mozapps/webextensions/GMPInstallManager.jsm b/toolkit/mozapps/webextensions/GMPInstallManager.jsm new file mode 100644 index 000000000..b5987ca55 --- /dev/null +++ b/toolkit/mozapps/webextensions/GMPInstallManager.jsm @@ -0,0 +1,523 @@ +/* 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"; + +this.EXPORTED_SYMBOLS = []; + +const {classes: Cc, interfaces: Ci, results: Cr, utils: Cu, manager: Cm} = + Components; +// 1 day default +const DEFAULT_SECONDS_BETWEEN_CHECKS = 60 * 60 * 24; + +var GMPInstallFailureReason = { + GMP_INVALID: 1, + GMP_HIDDEN: 2, + GMP_DISABLED: 3, + GMP_UPDATE_DISABLED: 4, +}; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/FileUtils.jsm"); +Cu.import("resource://gre/modules/Promise.jsm"); +Cu.import("resource://gre/modules/Preferences.jsm"); +Cu.import("resource://gre/modules/Log.jsm"); +Cu.import("resource://gre/modules/osfile.jsm"); +Cu.import("resource://gre/modules/Task.jsm"); +Cu.import("resource://gre/modules/GMPUtils.jsm"); +Cu.import("resource://gre/modules/addons/ProductAddonChecker.jsm"); + +this.EXPORTED_SYMBOLS = ["GMPInstallManager", "GMPExtractor", "GMPDownloader", + "GMPAddon"]; + +// Shared code for suppressing bad cert dialogs +XPCOMUtils.defineLazyGetter(this, "gCertUtils", function() { + let temp = { }; + Cu.import("resource://gre/modules/CertUtils.jsm", temp); + return temp; +}); + +XPCOMUtils.defineLazyModuleGetter(this, "UpdateUtils", + "resource://gre/modules/UpdateUtils.jsm"); + +function getScopedLogger(prefix) { + // `PARENT_LOGGER_ID.` being passed here effectively links this logger + // to the parentLogger. + return Log.repository.getLoggerWithMessagePrefix("Toolkit.GMP", prefix + " "); +} + +/** + * Provides an easy API for downloading and installing GMP Addons + */ +function GMPInstallManager() { +} +/** + * Temp file name used for downloading + */ +GMPInstallManager.prototype = { + /** + * Obtains a URL with replacement of vars + */ + _getURL: function() { + let log = getScopedLogger("GMPInstallManager._getURL"); + // Use the override URL if it is specified. The override URL is just like + // the normal URL but it does not check the cert. + let url = GMPPrefs.get(GMPPrefs.KEY_URL_OVERRIDE); + if (url) { + log.info("Using override url: " + url); + } else { + url = GMPPrefs.get(GMPPrefs.KEY_URL); + log.info("Using url: " + url); + } + + url = UpdateUtils.formatUpdateURL(url); + + log.info("Using url (with replacement): " + url); + return url; + }, + /** + * Performs an addon check. + * @return a promise which will be resolved or rejected. + * The promise is resolved with an object with properties: + * gmpAddons: array of GMPAddons + * usedFallback: whether the data was collected from online or + * from fallback data within the build + * The promise is rejected with an object with properties: + * target: The XHR request object + * status: The HTTP status code + * type: Sometimes specifies type of rejection + */ + checkForAddons: function() { + let log = getScopedLogger("GMPInstallManager.checkForAddons"); + if (this._deferred) { + log.error("checkForAddons already called"); + return Promise.reject({type: "alreadycalled"}); + } + this._deferred = Promise.defer(); + let url = this._getURL(); + + let allowNonBuiltIn = true; + let certs = null; + if (!Services.prefs.prefHasUserValue(GMPPrefs.KEY_URL_OVERRIDE)) { + allowNonBuiltIn = !GMPPrefs.get(GMPPrefs.KEY_CERT_REQUIREBUILTIN, true); + if (GMPPrefs.get(GMPPrefs.KEY_CERT_CHECKATTRS, true)) { + certs = gCertUtils.readCertPrefs(GMPPrefs.KEY_CERTS_BRANCH); + } + } + + let addonPromise = ProductAddonChecker + .getProductAddonList(url, allowNonBuiltIn, certs); + + addonPromise.then(res => { + if (!res || !res.gmpAddons) { + this._deferred.resolve({gmpAddons: []}); + } + else { + res.gmpAddons = res.gmpAddons.map(a => new GMPAddon(a)); + this._deferred.resolve(res); + } + delete this._deferred; + }, (ex) => { + this._deferred.reject(ex); + delete this._deferred; + }); + + return this._deferred.promise; + }, + /** + * Installs the specified addon and calls a callback when done. + * @param gmpAddon The GMPAddon object to install + * @return a promise which will be resolved or rejected + * The promise will resolve with an array of paths that were extracted + * The promise will reject with an error object: + * target: The XHR request object + * status: The HTTP status code + * type: A string to represent the type of error + * downloaderr, verifyerr or previouserrorencountered + */ + installAddon: function(gmpAddon) { + if (this._deferred) { + log.error("previous error encountered"); + return Promise.reject({type: "previouserrorencountered"}); + } + this.gmpDownloader = new GMPDownloader(gmpAddon); + return this.gmpDownloader.start(); + }, + _getTimeSinceLastCheck: function() { + let now = Math.round(Date.now() / 1000); + // Default to 0 here because `now - 0` will be returned later if that case + // is hit. We want a large value so a check will occur. + let lastCheck = GMPPrefs.get(GMPPrefs.KEY_UPDATE_LAST_CHECK, 0); + // Handle clock jumps, return now since we want it to represent + // a lot of time has passed since the last check. + if (now < lastCheck) { + return now; + } + return now - lastCheck; + }, + get _isEMEEnabled() { + return GMPPrefs.get(GMPPrefs.KEY_EME_ENABLED, true); + }, + _isAddonEnabled: function(aAddon) { + return GMPPrefs.get(GMPPrefs.KEY_PLUGIN_ENABLED, true, aAddon); + }, + _isAddonUpdateEnabled: function(aAddon) { + return this._isAddonEnabled(aAddon) && + GMPPrefs.get(GMPPrefs.KEY_PLUGIN_AUTOUPDATE, true, aAddon); + }, + _updateLastCheck: function() { + let now = Math.round(Date.now() / 1000); + GMPPrefs.set(GMPPrefs.KEY_UPDATE_LAST_CHECK, now); + }, + _versionchangeOccurred: function() { + let savedBuildID = GMPPrefs.get(GMPPrefs.KEY_BUILDID, null); + let buildID = Services.appinfo.platformBuildID; + if (savedBuildID == buildID) { + return false; + } + GMPPrefs.set(GMPPrefs.KEY_BUILDID, buildID); + return true; + }, + /** + * Wrapper for checkForAddons and installAddon. + * Will only install if not already installed and will log the results. + * This will only install/update the OpenH264 and EME plugins + * @return a promise which will be resolved if all addons could be installed + * successfully, rejected otherwise. + */ + simpleCheckAndInstall: Task.async(function*() { + let log = getScopedLogger("GMPInstallManager.simpleCheckAndInstall"); + + if (this._versionchangeOccurred()) { + log.info("A version change occurred. Ignoring " + + "media.gmp-manager.lastCheck to check immediately for " + + "new or updated GMPs."); + } else { + let secondsBetweenChecks = + GMPPrefs.get(GMPPrefs.KEY_SECONDS_BETWEEN_CHECKS, + DEFAULT_SECONDS_BETWEEN_CHECKS) + let secondsSinceLast = this._getTimeSinceLastCheck(); + log.info("Last check was: " + secondsSinceLast + + " seconds ago, minimum seconds: " + secondsBetweenChecks); + if (secondsBetweenChecks > secondsSinceLast) { + log.info("Will not check for updates."); + return {status: "too-frequent-no-check"}; + } + } + + try { + let {usedFallback, gmpAddons} = yield this.checkForAddons(); + this._updateLastCheck(); + log.info("Found " + gmpAddons.length + " addons advertised."); + let addonsToInstall = gmpAddons.filter(function(gmpAddon) { + log.info("Found addon: " + gmpAddon.toString()); + + if (!gmpAddon.isValid) { + log.info("Addon |" + gmpAddon.id + "| is invalid."); + return false; + } + + if (GMPUtils.isPluginHidden(gmpAddon)) { + log.info("Addon |" + gmpAddon.id + "| has been hidden."); + return false; + } + + if (gmpAddon.isInstalled) { + log.info("Addon |" + gmpAddon.id + "| already installed."); + return false; + } + + // Do not install from fallback if already installed as it + // may be a downgrade + if (usedFallback && gmpAddon.isUpdate) { + log.info("Addon |" + gmpAddon.id + "| not installing updates based " + + "on fallback."); + return false; + } + + let addonUpdateEnabled = false; + if (GMP_PLUGIN_IDS.indexOf(gmpAddon.id) >= 0) { + if (!this._isAddonEnabled(gmpAddon.id)) { + log.info("GMP |" + gmpAddon.id + "| has been disabled; skipping check."); + } else if (!this._isAddonUpdateEnabled(gmpAddon.id)) { + log.info("Auto-update is off for " + gmpAddon.id + + ", skipping check."); + } else { + addonUpdateEnabled = true; + } + } else { + // Currently, we only support installs of OpenH264 and EME plugins. + log.info("Auto-update is off for unknown plugin '" + gmpAddon.id + + "', skipping check."); + } + + return addonUpdateEnabled; + }, this); + + if (!addonsToInstall.length) { + log.info("No new addons to install, returning"); + return {status: "nothing-new-to-install"}; + } + + let installResults = []; + let failureEncountered = false; + for (let addon of addonsToInstall) { + try { + yield this.installAddon(addon); + installResults.push({ + id: addon.id, + result: "succeeded", + }); + } catch (e) { + failureEncountered = true; + installResults.push({ + id: addon.id, + result: "failed", + }); + } + } + if (failureEncountered) { + throw {status: "failed", + results: installResults}; + } + return {status: "succeeded", + results: installResults}; + } catch (e) { + log.error("Could not check for addons", e); + throw e; + } + }), + + /** + * Makes sure everything is cleaned up + */ + uninit: function() { + let log = getScopedLogger("GMPInstallManager.uninit"); + if (this._request) { + log.info("Aborting request"); + this._request.abort(); + } + if (this._deferred) { + log.info("Rejecting deferred"); + this._deferred.reject({type: "uninitialized"}); + } + log.info("Done cleanup"); + }, + + /** + * If set to true, specifies to leave the temporary downloaded zip file. + * This is useful for tests. + */ + overrideLeaveDownloadedZip: false, +}; + +/** + * Used to construct a single GMP addon + * GMPAddon objects are returns from GMPInstallManager.checkForAddons + * GMPAddon objects can also be used in calls to GMPInstallManager.installAddon + * + * @param addon The ProductAddonChecker `addon` object + */ +function GMPAddon(addon) { + let log = getScopedLogger("GMPAddon.constructor"); + for (let name of Object.keys(addon)) { + this[name] = addon[name]; + } + log.info ("Created new addon: " + this.toString()); +} + +GMPAddon.prototype = { + /** + * Returns a string representation of the addon + */ + toString: function() { + return this.id + " (" + + "isValid: " + this.isValid + + ", isInstalled: " + this.isInstalled + + ", hashFunction: " + this.hashFunction+ + ", hashValue: " + this.hashValue + + (this.size !== undefined ? ", size: " + this.size : "" ) + + ")"; + }, + /** + * If all the fields aren't specified don't consider this addon valid + * @return true if the addon is parsed and valid + */ + get isValid() { + return this.id && this.URL && this.version && + this.hashFunction && !!this.hashValue; + }, + get isInstalled() { + return this.version && + GMPPrefs.get(GMPPrefs.KEY_PLUGIN_VERSION, "", this.id) === this.version; + }, + get isEME() { + return this.id == "gmp-widevinecdm" || this.id.indexOf("gmp-eme-") == 0; + }, + /** + * @return true if the addon has been previously installed and this is + * a new version, if this is a fresh install return false + */ + get isUpdate() { + return this.version && + GMPPrefs.get(GMPPrefs.KEY_PLUGIN_VERSION, false, this.id); + }, +}; +/** + * Constructs a GMPExtractor object which is used to extract a GMP zip + * into the specified location. (Which typically leties per platform) + * @param zipPath The path on disk of the zip file to extract + */ +function GMPExtractor(zipPath, installToDirPath) { + this.zipPath = zipPath; + this.installToDirPath = installToDirPath; +} +GMPExtractor.prototype = { + /** + * Obtains a list of all the entries in a zipfile in the format of *.*. + * This also includes files inside directories. + * + * @param zipReader the nsIZipReader to check + * @return An array of string name entries which can be used + * in nsIZipReader.extract + */ + _getZipEntries: function(zipReader) { + let entries = []; + let enumerator = zipReader.findEntries("*.*"); + while (enumerator.hasMore()) { + entries.push(enumerator.getNext()); + } + return entries; + }, + /** + * Installs the this.zipPath contents into the directory used to store GMP + * addons for the current platform. + * + * @return a promise which will be resolved or rejected + * See GMPInstallManager.installAddon for resolve/rejected info + */ + install: function() { + try { + let log = getScopedLogger("GMPExtractor.install"); + this._deferred = Promise.defer(); + log.info("Installing " + this.zipPath + "..."); + // Get the input zip file + let zipFile = Cc["@mozilla.org/file/local;1"]. + createInstance(Ci.nsIFile); + zipFile.initWithPath(this.zipPath); + + // Initialize a zipReader and obtain the entries + var zipReader = Cc["@mozilla.org/libjar/zip-reader;1"]. + createInstance(Ci.nsIZipReader); + zipReader.open(zipFile) + let entries = this._getZipEntries(zipReader); + let extractedPaths = []; + + let destDir = Cc["@mozilla.org/file/local;1"]. + createInstance(Ci.nsILocalFile); + destDir.initWithPath(this.installToDirPath); + // Make sure the destination exists + if (!destDir.exists()) { + destDir.create(Ci.nsIFile.DIRECTORY_TYPE, parseInt("0755", 8)); + } + + // Extract each of the entries + entries.forEach(entry => { + // We don't need these types of files + if (entry.includes("__MACOSX") || + entry == "_metadata/verified_contents.json" || + entry == "imgs/icon-128x128.png") { + return; + } + let outFile = destDir.clone(); + // Do not extract into directories. Extract all files to the same + // directory. DO NOT use |OS.Path.basename()| here, as in Windows it + // does not work properly with forward slashes (which we must use here). + let outBaseName = entry.slice(entry.lastIndexOf("/") + 1); + outFile.appendRelativePath(outBaseName); + + zipReader.extract(entry, outFile); + extractedPaths.push(outFile.path); + // Ensure files are writable and executable. Otherwise we may be unable to + // execute or uninstall them. + outFile.permissions |= parseInt("0700", 8); + log.info(entry + " was successfully extracted to: " + + outFile.path); + }); + zipReader.close(); + if (!GMPInstallManager.overrideLeaveDownloadedZip) { + zipFile.remove(false); + } + + log.info(this.zipPath + " was installed successfully"); + this._deferred.resolve(extractedPaths); + } catch (e) { + if (zipReader) { + zipReader.close(); + } + this._deferred.reject({ + target: this, + status: e, + type: "exception" + }); + } + return this._deferred.promise; + } +}; + + +/** + * Constructs an object which downloads and initiates an install of + * the specified GMPAddon object. + * @param gmpAddon The addon to install. + */ +function GMPDownloader(gmpAddon) +{ + this._gmpAddon = gmpAddon; +} + +GMPDownloader.prototype = { + /** + * Starts the download process for an addon. + * @return a promise which will be resolved or rejected + * See GMPInstallManager.installAddon for resolve/rejected info + */ + start: function() { + let log = getScopedLogger("GMPDownloader"); + let gmpAddon = this._gmpAddon; + + if (!gmpAddon.isValid) { + log.info("gmpAddon is not valid, will not continue"); + return Promise.reject({ + target: this, + status: status, + type: "downloaderr" + }); + } + + return ProductAddonChecker.downloadAddon(gmpAddon).then((zipPath) => { + let path = OS.Path.join(OS.Constants.Path.profileDir, + gmpAddon.id, + gmpAddon.version); + log.info("install to directory path: " + path); + let gmpInstaller = new GMPExtractor(zipPath, path); + let installPromise = gmpInstaller.install(); + return installPromise.then(extractedPaths => { + // Success, set the prefs + let now = Math.round(Date.now() / 1000); + GMPPrefs.set(GMPPrefs.KEY_PLUGIN_LAST_UPDATE, now, gmpAddon.id); + // Remember our ABI, so that if the profile is migrated to another + // platform or from 32 -> 64 bit, we notice and don't try to load the + // unexecutable plugin library. + GMPPrefs.set(GMPPrefs.KEY_PLUGIN_ABI, UpdateUtils.ABI, gmpAddon.id); + // Setting the version pref signals installation completion to consumers, + // if you need to set other prefs etc. do it before this. + GMPPrefs.set(GMPPrefs.KEY_PLUGIN_VERSION, gmpAddon.version, + gmpAddon.id); + return extractedPaths; + }); + }); + }, +}; diff --git a/toolkit/mozapps/webextensions/LightweightThemeManager.jsm b/toolkit/mozapps/webextensions/LightweightThemeManager.jsm new file mode 100644 index 000000000..5dd41831d --- /dev/null +++ b/toolkit/mozapps/webextensions/LightweightThemeManager.jsm @@ -0,0 +1,909 @@ +/* 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"; + +this.EXPORTED_SYMBOLS = ["LightweightThemeManager"]; + +const Cc = Components.classes; +const Ci = Components.interfaces; + +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm"); +Components.utils.import("resource://gre/modules/AddonManager.jsm"); +/* globals AddonManagerPrivate*/ +Components.utils.import("resource://gre/modules/Services.jsm"); + +const ID_SUFFIX = "@personas.mozilla.org"; +const PREF_LWTHEME_TO_SELECT = "extensions.lwThemeToSelect"; +const PREF_GENERAL_SKINS_SELECTEDSKIN = "general.skins.selectedSkin"; +const PREF_EM_DSS_ENABLED = "extensions.dss.enabled"; +const ADDON_TYPE = "theme"; + +const URI_EXTENSION_STRINGS = "chrome://mozapps/locale/extensions/extensions.properties"; + +const STRING_TYPE_NAME = "type.%ID%.name"; + +const DEFAULT_MAX_USED_THEMES_COUNT = 30; + +const MAX_PREVIEW_SECONDS = 30; + +const MANDATORY = ["id", "name", "headerURL"]; +const OPTIONAL = ["footerURL", "textcolor", "accentcolor", "iconURL", + "previewURL", "author", "description", "homepageURL", + "updateURL", "version"]; + +const PERSIST_ENABLED = true; +const PERSIST_BYPASS_CACHE = false; +const PERSIST_FILES = { + headerURL: "lightweighttheme-header", + footerURL: "lightweighttheme-footer" +}; + +XPCOMUtils.defineLazyModuleGetter(this, "LightweightThemeImageOptimizer", + "resource://gre/modules/addons/LightweightThemeImageOptimizer.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "ServiceRequest", + "resource://gre/modules/ServiceRequest.jsm"); + + +XPCOMUtils.defineLazyGetter(this, "_prefs", () => { + return Services.prefs.getBranch("lightweightThemes."); +}); + +Object.defineProperty(this, "_maxUsedThemes", { + get: function() { + delete this._maxUsedThemes; + try { + this._maxUsedThemes = _prefs.getIntPref("maxUsedThemes"); + } + catch (e) { + this._maxUsedThemes = DEFAULT_MAX_USED_THEMES_COUNT; + } + return this._maxUsedThemes; + }, + + set: function(val) { + delete this._maxUsedThemes; + return this._maxUsedThemes = val; + }, + configurable: true, +}); + +// Holds the ID of the theme being enabled or disabled while sending out the +// events so cached AddonWrapper instances can return correct values for +// permissions and pendingOperations +var _themeIDBeingEnabled = null; +var _themeIDBeingDisabled = null; + +// Convert from the old storage format (in which the order of usedThemes +// was combined with isThemeSelected to determine which theme was selected) +// to the new one (where a selectedThemeID determines which theme is selected). +(function() { + let wasThemeSelected = false; + try { + wasThemeSelected = _prefs.getBoolPref("isThemeSelected"); + } catch (e) { } + + if (wasThemeSelected) { + _prefs.clearUserPref("isThemeSelected"); + let themes = []; + try { + themes = JSON.parse(_prefs.getComplexValue("usedThemes", + Ci.nsISupportsString).data); + } catch (e) { } + + if (Array.isArray(themes) && themes[0]) { + _prefs.setCharPref("selectedThemeID", themes[0].id); + } + } +})(); + +this.LightweightThemeManager = { + get name() { + return "LightweightThemeManager"; + }, + + // Themes that can be added for an application. They can't be removed, and + // will always show up at the top of the list. + _builtInThemes: new Map(), + + get usedThemes () { + let themes = []; + try { + themes = JSON.parse(_prefs.getComplexValue("usedThemes", + Ci.nsISupportsString).data); + } catch (e) { } + + themes.push(...this._builtInThemes.values()); + return themes; + }, + + get currentTheme () { + let selectedThemeID = null; + try { + selectedThemeID = _prefs.getCharPref("selectedThemeID"); + } catch (e) {} + + let data = null; + if (selectedThemeID) { + data = this.getUsedTheme(selectedThemeID); + } + return data; + }, + + get currentThemeForDisplay () { + var data = this.currentTheme; + + if (data && PERSIST_ENABLED) { + for (let key in PERSIST_FILES) { + try { + if (data[key] && _prefs.getBoolPref("persisted." + key)) + data[key] = _getLocalImageURI(PERSIST_FILES[key]).spec + + "?" + data.id + ";" + _version(data); + } catch (e) {} + } + } + + return data; + }, + + set currentTheme (aData) { + return _setCurrentTheme(aData, false); + }, + + setLocalTheme: function(aData) { + _setCurrentTheme(aData, true); + }, + + getUsedTheme: function(aId) { + var usedThemes = this.usedThemes; + for (let usedTheme of usedThemes) { + if (usedTheme.id == aId) + return usedTheme; + } + return null; + }, + + forgetUsedTheme: function(aId) { + let theme = this.getUsedTheme(aId); + if (!theme || LightweightThemeManager._builtInThemes.has(theme.id)) + return; + + let wrapper = new AddonWrapper(theme); + AddonManagerPrivate.callAddonListeners("onUninstalling", wrapper, false); + + var currentTheme = this.currentTheme; + if (currentTheme && currentTheme.id == aId) { + this.themeChanged(null); + AddonManagerPrivate.notifyAddonChanged(null, ADDON_TYPE, false); + } + + _updateUsedThemes(_usedThemesExceptId(aId)); + AddonManagerPrivate.callAddonListeners("onUninstalled", wrapper); + }, + + addBuiltInTheme: function(theme) { + if (!theme || !theme.id || this.usedThemes.some(t => t.id == theme.id)) { + throw new Error("Trying to add invalid builtIn theme"); + } + + this._builtInThemes.set(theme.id, theme); + + if (_prefs.getCharPref("selectedThemeID") == theme.id) { + this.currentTheme = theme; + } + }, + + forgetBuiltInTheme: function(id) { + if (!this._builtInThemes.has(id)) { + let currentTheme = this.currentTheme; + if (currentTheme && currentTheme.id == id) { + this.currentTheme = null; + } + } + return this._builtInThemes.delete(id); + }, + + clearBuiltInThemes: function() { + for (let id of this._builtInThemes.keys()) { + this.forgetBuiltInTheme(id); + } + }, + + previewTheme: function(aData) { + let cancel = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool); + cancel.data = false; + Services.obs.notifyObservers(cancel, "lightweight-theme-preview-requested", + JSON.stringify(aData)); + if (cancel.data) + return; + + if (_previewTimer) + _previewTimer.cancel(); + else + _previewTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer); + _previewTimer.initWithCallback(_previewTimerCallback, + MAX_PREVIEW_SECONDS * 1000, + _previewTimer.TYPE_ONE_SHOT); + + _notifyWindows(aData); + }, + + resetPreview: function() { + if (_previewTimer) { + _previewTimer.cancel(); + _previewTimer = null; + _notifyWindows(this.currentThemeForDisplay); + } + }, + + parseTheme: function(aString, aBaseURI) { + try { + return _sanitizeTheme(JSON.parse(aString), aBaseURI, false); + } catch (e) { + return null; + } + }, + + updateCurrentTheme: function() { + try { + if (!_prefs.getBoolPref("update.enabled")) + return; + } catch (e) { + return; + } + + var theme = this.currentTheme; + if (!theme || !theme.updateURL) + return; + + var req = new ServiceRequest(); + + req.mozBackgroundRequest = true; + req.overrideMimeType("text/plain"); + req.open("GET", theme.updateURL, true); + // Prevent the request from reading from the cache. + req.channel.loadFlags |= Ci.nsIRequest.LOAD_BYPASS_CACHE; + // Prevent the request from writing to the cache. + req.channel.loadFlags |= Ci.nsIRequest.INHIBIT_CACHING; + + req.addEventListener("load", () => { + if (req.status != 200) + return; + + let newData = this.parseTheme(req.responseText, theme.updateURL); + if (!newData || + newData.id != theme.id || + _version(newData) == _version(theme)) + return; + + var currentTheme = this.currentTheme; + if (currentTheme && currentTheme.id == theme.id) + this.currentTheme = newData; + }, false); + + req.send(null); + }, + + /** + * Switches to a new lightweight theme. + * + * @param aData + * The lightweight theme to switch to + */ + themeChanged: function(aData) { + if (_previewTimer) { + _previewTimer.cancel(); + _previewTimer = null; + } + + if (aData) { + let usedThemes = _usedThemesExceptId(aData.id); + usedThemes.unshift(aData); + _updateUsedThemes(usedThemes); + if (PERSIST_ENABLED) { + LightweightThemeImageOptimizer.purge(); + _persistImages(aData, function() { + _notifyWindows(this.currentThemeForDisplay); + }.bind(this)); + } + } + + if (aData) + _prefs.setCharPref("selectedThemeID", aData.id); + else + _prefs.setCharPref("selectedThemeID", ""); + + _notifyWindows(aData); + Services.obs.notifyObservers(null, "lightweight-theme-changed", null); + }, + + /** + * Starts the Addons provider and enables the new lightweight theme if + * necessary. + */ + startup: function() { + if (Services.prefs.prefHasUserValue(PREF_LWTHEME_TO_SELECT)) { + let id = Services.prefs.getCharPref(PREF_LWTHEME_TO_SELECT); + if (id) + this.themeChanged(this.getUsedTheme(id)); + else + this.themeChanged(null); + Services.prefs.clearUserPref(PREF_LWTHEME_TO_SELECT); + } + + _prefs.addObserver("", _prefObserver, false); + }, + + /** + * Shuts down the provider. + */ + shutdown: function() { + _prefs.removeObserver("", _prefObserver); + }, + + /** + * Called when a new add-on has been enabled when only one add-on of that type + * can be enabled. + * + * @param aId + * The ID of the newly enabled add-on + * @param aType + * The type of the newly enabled add-on + * @param aPendingRestart + * true if the newly enabled add-on will only become enabled after a + * restart + */ + addonChanged: function(aId, aType, aPendingRestart) { + if (aType != ADDON_TYPE) + return; + + let id = _getInternalID(aId); + let current = this.currentTheme; + + try { + let next = Services.prefs.getCharPref(PREF_LWTHEME_TO_SELECT); + if (id == next && aPendingRestart) + return; + + Services.prefs.clearUserPref(PREF_LWTHEME_TO_SELECT); + if (next) { + AddonManagerPrivate.callAddonListeners("onOperationCancelled", + new AddonWrapper(this.getUsedTheme(next))); + } + else if (id == current.id) { + AddonManagerPrivate.callAddonListeners("onOperationCancelled", + new AddonWrapper(current)); + return; + } + } + catch (e) { + } + + if (current) { + if (current.id == id) + return; + _themeIDBeingDisabled = current.id; + let wrapper = new AddonWrapper(current); + if (aPendingRestart) { + Services.prefs.setCharPref(PREF_LWTHEME_TO_SELECT, ""); + AddonManagerPrivate.callAddonListeners("onDisabling", wrapper, true); + } + else { + AddonManagerPrivate.callAddonListeners("onDisabling", wrapper, false); + this.themeChanged(null); + AddonManagerPrivate.callAddonListeners("onDisabled", wrapper); + } + _themeIDBeingDisabled = null; + } + + if (id) { + let theme = this.getUsedTheme(id); + _themeIDBeingEnabled = id; + let wrapper = new AddonWrapper(theme); + if (aPendingRestart) { + AddonManagerPrivate.callAddonListeners("onEnabling", wrapper, true); + Services.prefs.setCharPref(PREF_LWTHEME_TO_SELECT, id); + + // Flush the preferences to disk so they survive any crash + Services.prefs.savePrefFile(null); + } + else { + AddonManagerPrivate.callAddonListeners("onEnabling", wrapper, false); + this.themeChanged(theme); + AddonManagerPrivate.callAddonListeners("onEnabled", wrapper); + } + _themeIDBeingEnabled = null; + } + }, + + /** + * Called to get an Addon with a particular ID. + * + * @param aId + * The ID of the add-on to retrieve + * @param aCallback + * A callback to pass the Addon to + */ + getAddonByID: function(aId, aCallback) { + let id = _getInternalID(aId); + if (!id) { + aCallback(null); + return; + } + + let theme = this.getUsedTheme(id); + if (!theme) { + aCallback(null); + return; + } + + aCallback(new AddonWrapper(theme)); + }, + + /** + * Called to get Addons of a particular type. + * + * @param aTypes + * An array of types to fetch. Can be null to get all types. + * @param aCallback + * A callback to pass an array of Addons to + */ + getAddonsByTypes: function(aTypes, aCallback) { + if (aTypes && aTypes.indexOf(ADDON_TYPE) == -1) { + aCallback([]); + return; + } + + aCallback(this.usedThemes.map(a => new AddonWrapper(a))); + }, +}; + +const wrapperMap = new WeakMap(); +let themeFor = wrapper => wrapperMap.get(wrapper); + +/** + * The AddonWrapper wraps lightweight theme to provide the data visible to + * consumers of the AddonManager API. + */ +function AddonWrapper(aTheme) { + wrapperMap.set(this, aTheme); +} + +AddonWrapper.prototype = { + get id() { + return themeFor(this).id + ID_SUFFIX; + }, + + get type() { + return ADDON_TYPE; + }, + + get isActive() { + let current = LightweightThemeManager.currentTheme; + if (current) + return themeFor(this).id == current.id; + return false; + }, + + get name() { + return themeFor(this).name; + }, + + get version() { + let theme = themeFor(this); + return "version" in theme ? theme.version : ""; + }, + + get creator() { + let theme = themeFor(this); + return "author" in theme ? new AddonManagerPrivate.AddonAuthor(theme.author) : null; + }, + + get screenshots() { + let url = themeFor(this).previewURL; + return [new AddonManagerPrivate.AddonScreenshot(url)]; + }, + + get pendingOperations() { + let pending = AddonManager.PENDING_NONE; + if (this.isActive == this.userDisabled) + pending |= this.isActive ? AddonManager.PENDING_DISABLE : AddonManager.PENDING_ENABLE; + return pending; + }, + + get operationsRequiringRestart() { + // If a non-default theme is in use then a restart will be required to + // enable lightweight themes unless dynamic theme switching is enabled + if (Services.prefs.prefHasUserValue(PREF_GENERAL_SKINS_SELECTEDSKIN)) { + try { + if (Services.prefs.getBoolPref(PREF_EM_DSS_ENABLED)) + return AddonManager.OP_NEEDS_RESTART_NONE; + } + catch (e) { + } + return AddonManager.OP_NEEDS_RESTART_ENABLE; + } + + return AddonManager.OP_NEEDS_RESTART_NONE; + }, + + get size() { + // The size changes depending on whether the theme is in use or not, this is + // probably not worth exposing. + return null; + }, + + get permissions() { + let permissions = 0; + + // Do not allow uninstall of builtIn themes. + if (!LightweightThemeManager._builtInThemes.has(themeFor(this).id)) + permissions = AddonManager.PERM_CAN_UNINSTALL; + if (this.userDisabled) + permissions |= AddonManager.PERM_CAN_ENABLE; + else + permissions |= AddonManager.PERM_CAN_DISABLE; + return permissions; + }, + + get userDisabled() { + let id = themeFor(this).id; + if (_themeIDBeingEnabled == id) + return false; + if (_themeIDBeingDisabled == id) + return true; + + try { + let toSelect = Services.prefs.getCharPref(PREF_LWTHEME_TO_SELECT); + return id != toSelect; + } + catch (e) { + let current = LightweightThemeManager.currentTheme; + return !current || current.id != id; + } + }, + + set userDisabled(val) { + if (val == this.userDisabled) + return val; + + if (val) + LightweightThemeManager.currentTheme = null; + else + LightweightThemeManager.currentTheme = themeFor(this); + + return val; + }, + + // Lightweight themes are never disabled by the application + get appDisabled() { + return false; + }, + + // Lightweight themes are always compatible + get isCompatible() { + return true; + }, + + get isPlatformCompatible() { + return true; + }, + + get scope() { + return AddonManager.SCOPE_PROFILE; + }, + + get foreignInstall() { + return false; + }, + + uninstall: function() { + LightweightThemeManager.forgetUsedTheme(themeFor(this).id); + }, + + cancelUninstall: function() { + throw new Error("Theme is not marked to be uninstalled"); + }, + + findUpdates: function(listener, reason, appVersion, platformVersion) { + AddonManagerPrivate.callNoUpdateListeners(this, listener, reason, appVersion, platformVersion); + }, + + // Lightweight themes are always compatible + isCompatibleWith: function(appVersion, platformVersion) { + return true; + }, + + // Lightweight themes are always securely updated + get providesUpdatesSecurely() { + return true; + }, + + // Lightweight themes are never blocklisted + get blocklistState() { + return Ci.nsIBlocklistService.STATE_NOT_BLOCKED; + } +}; + +["description", "homepageURL", "iconURL"].forEach(function(prop) { + Object.defineProperty(AddonWrapper.prototype, prop, { + get: function() { + let theme = themeFor(this); + return prop in theme ? theme[prop] : null; + }, + enumarable: true, + }); +}); + +["installDate", "updateDate"].forEach(function(prop) { + Object.defineProperty(AddonWrapper.prototype, prop, { + get: function() { + let theme = themeFor(this); + return prop in theme ? new Date(theme[prop]) : null; + }, + enumarable: true, + }); +}); + +/** + * Converts the ID used by the public AddonManager API to an lightweight theme + * ID. + * + * @param id + * The ID to be converted + * + * @return the lightweight theme ID or null if the ID was not for a lightweight + * theme. + */ +function _getInternalID(id) { + if (!id) + return null; + let len = id.length - ID_SUFFIX.length; + if (len > 0 && id.substring(len) == ID_SUFFIX) + return id.substring(0, len); + return null; +} + +function _setCurrentTheme(aData, aLocal) { + aData = _sanitizeTheme(aData, null, aLocal); + + let needsRestart = (ADDON_TYPE == "theme") && + Services.prefs.prefHasUserValue(PREF_GENERAL_SKINS_SELECTEDSKIN); + + let cancel = Cc["@mozilla.org/supports-PRBool;1"].createInstance(Ci.nsISupportsPRBool); + cancel.data = false; + Services.obs.notifyObservers(cancel, "lightweight-theme-change-requested", + JSON.stringify(aData)); + + if (aData) { + let theme = LightweightThemeManager.getUsedTheme(aData.id); + let isInstall = !theme || theme.version != aData.version; + if (isInstall) { + aData.updateDate = Date.now(); + if (theme && "installDate" in theme) + aData.installDate = theme.installDate; + else + aData.installDate = aData.updateDate; + + var oldWrapper = theme ? new AddonWrapper(theme) : null; + var wrapper = new AddonWrapper(aData); + AddonManagerPrivate.callInstallListeners("onExternalInstall", null, + wrapper, oldWrapper, false); + AddonManagerPrivate.callAddonListeners("onInstalling", wrapper, false); + } + + let current = LightweightThemeManager.currentTheme; + let usedThemes = _usedThemesExceptId(aData.id); + if (current && current.id != aData.id) + usedThemes.splice(1, 0, aData); + else + usedThemes.unshift(aData); + _updateUsedThemes(usedThemes); + + if (isInstall) + AddonManagerPrivate.callAddonListeners("onInstalled", wrapper); + } + + if (cancel.data) + return null; + + AddonManagerPrivate.notifyAddonChanged(aData ? aData.id + ID_SUFFIX : null, + ADDON_TYPE, needsRestart); + + return LightweightThemeManager.currentTheme; +} + +function _sanitizeTheme(aData, aBaseURI, aLocal) { + if (!aData || typeof aData != "object") + return null; + + var resourceProtocols = ["http", "https", "resource"]; + if (aLocal) + resourceProtocols.push("file"); + var resourceProtocolExp = new RegExp("^(" + resourceProtocols.join("|") + "):"); + + function sanitizeProperty(prop) { + if (!(prop in aData)) + return null; + if (typeof aData[prop] != "string") + return null; + let val = aData[prop].trim(); + if (!val) + return null; + + if (!/URL$/.test(prop)) + return val; + + try { + val = _makeURI(val, aBaseURI ? _makeURI(aBaseURI) : null).spec; + if ((prop == "updateURL" ? /^https:/ : resourceProtocolExp).test(val)) + return val; + return null; + } + catch (e) { + return null; + } + } + + let result = {}; + for (let mandatoryProperty of MANDATORY) { + let val = sanitizeProperty(mandatoryProperty); + if (!val) + throw Components.results.NS_ERROR_INVALID_ARG; + result[mandatoryProperty] = val; + } + + for (let optionalProperty of OPTIONAL) { + let val = sanitizeProperty(optionalProperty); + if (!val) + continue; + result[optionalProperty] = val; + } + + return result; +} + +function _usedThemesExceptId(aId) { + return LightweightThemeManager.usedThemes.filter(function(t) { + return "id" in t && t.id != aId; + }); +} + +function _version(aThemeData) { + return aThemeData.version || ""; +} + +function _makeURI(aURL, aBaseURI) { + return Services.io.newURI(aURL, null, aBaseURI); +} + +function _updateUsedThemes(aList) { + // Remove app-specific themes before saving them to the usedThemes pref. + aList = aList.filter(theme => !LightweightThemeManager._builtInThemes.has(theme.id)); + + // Send uninstall events for all themes that need to be removed. + while (aList.length > _maxUsedThemes) { + let wrapper = new AddonWrapper(aList[aList.length - 1]); + AddonManagerPrivate.callAddonListeners("onUninstalling", wrapper, false); + aList.pop(); + AddonManagerPrivate.callAddonListeners("onUninstalled", wrapper); + } + + var str = Cc["@mozilla.org/supports-string;1"] + .createInstance(Ci.nsISupportsString); + str.data = JSON.stringify(aList); + _prefs.setComplexValue("usedThemes", Ci.nsISupportsString, str); + + Services.obs.notifyObservers(null, "lightweight-theme-list-changed", null); +} + +function _notifyWindows(aThemeData) { + Services.obs.notifyObservers(null, "lightweight-theme-styling-update", + JSON.stringify(aThemeData)); +} + +var _previewTimer; +var _previewTimerCallback = { + notify: function() { + LightweightThemeManager.resetPreview(); + } +}; + +/** + * Called when any of the lightweightThemes preferences are changed. + */ +function _prefObserver(aSubject, aTopic, aData) { + switch (aData) { + case "maxUsedThemes": + try { + _maxUsedThemes = _prefs.getIntPref(aData); + } + catch (e) { + _maxUsedThemes = DEFAULT_MAX_USED_THEMES_COUNT; + } + // Update the theme list to remove any themes over the number we keep + _updateUsedThemes(LightweightThemeManager.usedThemes); + break; + } +} + +function _persistImages(aData, aCallback) { + function onSuccess(key) { + return function () { + let current = LightweightThemeManager.currentTheme; + if (current && current.id == aData.id) { + _prefs.setBoolPref("persisted." + key, true); + } + if (--numFilesToPersist == 0 && aCallback) { + aCallback(); + } + }; + } + + let numFilesToPersist = 0; + for (let key in PERSIST_FILES) { + _prefs.setBoolPref("persisted." + key, false); + if (aData[key]) { + numFilesToPersist++; + _persistImage(aData[key], PERSIST_FILES[key], onSuccess(key)); + } + } +} + +function _getLocalImageURI(localFileName) { + var localFile = Services.dirsvc.get("ProfD", Ci.nsIFile); + localFile.append(localFileName); + return Services.io.newFileURI(localFile); +} + +function _persistImage(sourceURL, localFileName, successCallback) { + if (/^(file|resource):/.test(sourceURL)) + return; + + var targetURI = _getLocalImageURI(localFileName); + var sourceURI = _makeURI(sourceURL); + + var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"] + .createInstance(Ci.nsIWebBrowserPersist); + + persist.persistFlags = + Ci.nsIWebBrowserPersist.PERSIST_FLAGS_REPLACE_EXISTING_FILES | + Ci.nsIWebBrowserPersist.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION | + (PERSIST_BYPASS_CACHE ? + Ci.nsIWebBrowserPersist.PERSIST_FLAGS_BYPASS_CACHE : + Ci.nsIWebBrowserPersist.PERSIST_FLAGS_FROM_CACHE); + + persist.progressListener = new _persistProgressListener(successCallback); + + persist.saveURI(sourceURI, null, + null, Ci.nsIHttpChannel.REFERRER_POLICY_NO_REFERRER_WHEN_DOWNGRADE, + null, null, targetURI, null); +} + +function _persistProgressListener(successCallback) { + this.onLocationChange = function() {}; + this.onProgressChange = function() {}; + this.onStatusChange = function() {}; + this.onSecurityChange = function() {}; + this.onStateChange = function(aWebProgress, aRequest, aStateFlags, aStatus) { + if (aRequest && + aStateFlags & Ci.nsIWebProgressListener.STATE_IS_NETWORK && + aStateFlags & Ci.nsIWebProgressListener.STATE_STOP) { + try { + if (aRequest.QueryInterface(Ci.nsIHttpChannel).requestSucceeded) { + // success + successCallback(); + return; + } + } catch (e) { } + // failure + } + }; +} + +AddonManagerPrivate.registerProvider(LightweightThemeManager, [ + new AddonManagerPrivate.AddonType("theme", URI_EXTENSION_STRINGS, + STRING_TYPE_NAME, + AddonManager.VIEW_TYPE_LIST, 5000) +]); diff --git a/toolkit/mozapps/webextensions/addonManager.js b/toolkit/mozapps/webextensions/addonManager.js new file mode 100644 index 000000000..d34cbaf62 --- /dev/null +++ b/toolkit/mozapps/webextensions/addonManager.js @@ -0,0 +1,296 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/** + * This component serves as integration between the platform and AddonManager. + * It is responsible for initializing and shutting down the AddonManager as well + * as passing new installs from webpages to the AddonManager. + */ + +"use strict"; + +const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components; + +// 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_ADDONS = "WebInstallerInstallAddonsFromWebpage"; +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"; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); + +var gSingleton = null; + +function amManager() { + Cu.import("resource://gre/modules/AddonManager.jsm"); + /* globals AddonManagerPrivate*/ + + Services.mm.loadFrameScript(CHILD_SCRIPT, true); + Services.mm.addMessageListener(MSG_INSTALL_ENABLED, this); + Services.mm.addMessageListener(MSG_INSTALL_ADDONS, this); + Services.mm.addMessageListener(MSG_PROMISE_REQUEST, this); + Services.mm.addMessageListener(MSG_INSTALL_CLEANUP, this); + Services.mm.addMessageListener(MSG_ADDON_EVENT_REQ, this); + + Services.obs.addObserver(this, "message-manager-close", false); + Services.obs.addObserver(this, "message-manager-disconnect", false); + + AddonManager.webAPI.setEventHandler(this.sendEvent); + + // Needed so receiveMessage can be called directly by JS callers + this.wrappedJSObject = this; +} + +amManager.prototype = { + observe: function(aSubject, aTopic, aData) { + switch (aTopic) { + case "addons-startup": + AddonManagerPrivate.startup(); + break; + + case "message-manager-close": + case "message-manager-disconnect": + this.childClosed(aSubject); + break; + } + }, + + /** + * @see amIAddonManager.idl + */ + mapURIToAddonID: function(uri, id) { + id.value = AddonManager.mapURIToAddonID(uri); + return !!id.value; + }, + + /** + * @see amIWebInstaller.idl + */ + isInstallEnabled: function(aMimetype, aReferer) { + return AddonManager.isInstallEnabled(aMimetype); + }, + + /** + * @see amIWebInstaller.idl + */ + installAddonsFromWebpage: function(aMimetype, aBrowser, aInstallingPrincipal, + aUris, aHashes, aNames, aIcons, aCallback) { + if (aUris.length == 0) + return false; + + let retval = true; + if (!AddonManager.isInstallAllowed(aMimetype, aInstallingPrincipal)) { + aCallback = null; + retval = false; + } + + let installs = []; + function buildNextInstall() { + if (aUris.length == 0) { + AddonManager.installAddonsFromWebpage(aMimetype, aBrowser, aInstallingPrincipal, installs); + return; + } + let uri = aUris.shift(); + AddonManager.getInstallForURL(uri, function(aInstall) { + function callCallback(aUri, aStatus) { + try { + aCallback.onInstallEnded(aUri, aStatus); + } + catch (e) { + Components.utils.reportError(e); + } + } + + if (aInstall) { + installs.push(aInstall); + if (aCallback) { + aInstall.addListener({ + onDownloadCancelled: function(aInstall) { + callCallback(uri, USER_CANCELLED); + }, + + onDownloadFailed: function(aInstall) { + if (aInstall.error == AddonManager.ERROR_CORRUPT_FILE) + callCallback(uri, CANT_READ_ARCHIVE); + else + callCallback(uri, DOWNLOAD_ERROR); + }, + + onInstallFailed: function(aInstall) { + callCallback(uri, EXECUTION_ERROR); + }, + + onInstallEnded: function(aInstall, aStatus) { + callCallback(uri, SUCCESS); + } + }); + } + } + else if (aCallback) { + aCallback.onInstallEnded(uri, UNSUPPORTED_TYPE); + } + buildNextInstall(); + }, aMimetype, aHashes.shift(), aNames.shift(), aIcons.shift(), null, aBrowser); + } + buildNextInstall(); + + return retval; + }, + + notify: function(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, needsRestart) => { + target.sendAsyncMessage(MSG_ADDON_EVENT, {event, id, needsRestart}); + }; + let listener = { + onEnabling: (addon, needsRestart) => handler("onEnabling", addon.id, needsRestart), + onEnabled: (addon) => handler("onEnabled", addon.id, false), + onDisabling: (addon, needsRestart) => handler("onDisabling", addon.id, needsRestart), + onDisabled: (addon) => handler("onDisabled", addon.id, false), + onInstalling: (addon, needsRestart) => handler("onInstalling", addon.id, needsRestart), + onInstalled: (addon) => handler("onInstalled", addon.id, false), + onUninstalling: (addon, needsRestart) => handler("onUninstalling", addon.id, needsRestart), + onUninstalled: (addon) => handler("onUninstalled", addon.id, false), + onOperationCancelled: (addon) => handler("onOperationCancelled", addon.id, false), + }; + 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: function(aMessage) { + let payload = aMessage.data; + + switch (aMessage.name) { + case MSG_INSTALL_ENABLED: + return AddonManager.isInstallEnabled(payload.mimetype); + + case MSG_INSTALL_ADDONS: { + let callback = null; + if (payload.callbackID != -1) { + let mm = aMessage.target.messageManager; + callback = { + onInstallEnded: function(url, status) { + mm.sendAsyncMessage(MSG_INSTALL_CALLBACK, { + callbackID: payload.callbackID, + url: url, + status: status + }); + }, + }; + } + + return this.installAddonsFromWebpage(payload.mimetype, + aMessage.target, payload.triggeringPrincipal, payload.uris, + payload.hashes, payload.names, payload.icons, callback); + } + + case MSG_PROMISE_REQUEST: { + 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: { + AddonManager.webAPI.clearInstalls(payload.ids); + break; + } + + case MSG_ADDON_EVENT_REQ: { + 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: function(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: XPCOMUtils.generateQI([Ci.amIAddonManager, + Ci.amIWebInstaller, + Ci.nsITimerCallback, + Ci.nsIObserver, + Ci.nsIMessageListener]) +}; + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([amManager]); diff --git a/toolkit/mozapps/webextensions/amInstallTrigger.js b/toolkit/mozapps/webextensions/amInstallTrigger.js new file mode 100644 index 000000000..382791d32 --- /dev/null +++ b/toolkit/mozapps/webextensions/amInstallTrigger.js @@ -0,0 +1,240 @@ +/* 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 {classes: Cc, interfaces: Ci, utils: Cu} = Components; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/Preferences.jsm"); +Cu.import("resource://gre/modules/Log.jsm"); + +const XPINSTALL_MIMETYPE = "application/x-xpinstall"; + +const MSG_INSTALL_ENABLED = "WebInstallerIsInstallEnabled"; +const MSG_INSTALL_ADDONS = "WebInstallerInstallAddonsFromWebpage"; +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, urls, mediator) { + this.id = id; + this.callback = callback; + this.urls = new Set(urls); + this.callCallback = function(url, status) { + try { + this.callback(url, status); + } + catch (e) { + log.warn("InstallTrigger callback threw an exception: " + e); + } + + this.urls.delete(url); + if (this.urls.size == 0) + mediator._callbacks.delete(id); + }; +} + +function RemoteMediator(window) { + window.QueryInterface(Ci.nsIInterfaceRequestor); + let utils = window.getInterface(Ci.nsIDOMWindowUtils); + this._windowID = utils.currentInnerWindowID; + + this.mm = window + .getInterface(Ci.nsIDocShell) + .QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIContentFrameMessageManager); + this.mm.addWeakMessageListener(MSG_INSTALL_CALLBACK, this); + + this._lastCallbackID = 0; + this._callbacks = new Map(); +} + +RemoteMediator.prototype = { + receiveMessage: function(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: function(url) { + let params = { + mimetype: XPINSTALL_MIMETYPE + }; + return this.mm.sendSyncMessage(MSG_INSTALL_ENABLED, params)[0]; + }, + + install: function(installs, principal, callback, window) { + let callbackID = this._addCallback(callback, installs.uris); + + installs.mimetype = XPINSTALL_MIMETYPE; + installs.triggeringPrincipal = principal; + installs.callbackID = callbackID; + + if (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT) { + // When running in the main process this might be a frame inside an + // in-content UI page, walk up to find the first frame element in a chrome + // privileged document + let element = window.frameElement; + let ssm = Services.scriptSecurityManager; + while (element && !ssm.isSystemPrincipal(element.ownerDocument.nodePrincipal)) + element = element.ownerDocument.defaultView.frameElement; + + if (element) { + let listener = Cc["@mozilla.org/addons/integration;1"]. + getService(Ci.nsIMessageListener); + return listener.wrappedJSObject.receiveMessage({ + name: MSG_INSTALL_ADDONS, + target: element, + data: installs, + }); + } + } + + // Fall back to sending through the message manager + let messageManager = window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIWebNavigation) + .QueryInterface(Ci.nsIDocShell) + .QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIContentFrameMessageManager); + + return messageManager.sendSyncMessage(MSG_INSTALL_ADDONS, installs)[0]; + }, + + _addCallback: function(callback, urls) { + if (!callback || typeof callback != "function") + return -1; + + let callbackID = this._windowID + "-" + ++this._lastCallbackID; + let callbackObject = new CallbackObject(callbackID, callback, urls, this); + this._callbacks.set(callbackID, callbackObject); + return callbackID; + }, + + QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference]) +}; + + +function InstallTrigger() { +} + +InstallTrigger.prototype = { + // Here be magic. We've declared ourselves as providing the + // nsIDOMGlobalPropertyInitializer interface, and are registered in the + // "JavaScript-global-property" category in the XPCOM category manager. This + // means that for newly created windows, XPCOM will createinstance this + // object, and then call init, passing in the window for which we need to + // provide an instance. We then initialize ourselves and return the webidl + // version of this object using the webidl-provided _create method, which + // XPCOM will then duly expose as a property value on the window. All this + // indirection is necessary because webidl does not (yet) support statics + // (bug 863952). See bug 926712 for more details about this implementation. + init: function(window) { + this._window = window; + this._principal = window.document.nodePrincipal; + this._url = window.document.documentURIObject; + + try { + this._mediator = new RemoteMediator(window); + } catch (ex) { + // If we can't set up IPC (e.g., because this is a top-level window + // or something), then don't expose InstallTrigger. + return null; + } + + return window.InstallTriggerImpl._create(window, this); + }, + + enabled: function() { + return this._mediator.enabled(this._url.spec); + }, + + updateEnabled: function() { + return this.enabled(); + }, + + install: function(installs, callback) { + let installData = { + uris: [], + hashes: [], + names: [], + icons: [], + }; + + for (let name of Object.keys(installs)) { + let item = installs[name]; + if (typeof item === "string") { + item = { URL: item }; + } + if (!item.URL) { + throw new this._window.Error("Missing URL property for '" + name + "'"); + } + + 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 + } + } + + installData.uris.push(url.spec); + installData.hashes.push(item.Hash || null); + installData.names.push(name); + installData.icons.push(iconUrl ? iconUrl.spec : null); + } + + return this._mediator.install(installData, this._principal, callback, this._window); + }, + + startSoftwareUpdate: function(url, flags) { + let filename = Services.io.newURI(url, null, null) + .QueryInterface(Ci.nsIURL) + .filename; + let args = {}; + args[filename] = { "URL": url }; + return this.install(args); + }, + + installChrome: function(type, url, skin) { + return this.startSoftwareUpdate(url); + }, + + _resolveURL: function(url) { + return Services.io.newURI(url, null, this._url); + }, + + _checkLoadURIFromScript: function(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: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsIDOMGlobalPropertyInitializer]) +}; + + + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([InstallTrigger]); diff --git a/toolkit/mozapps/webextensions/amWebAPI.js b/toolkit/mozapps/webextensions/amWebAPI.js new file mode 100644 index 000000000..5ad0d23f1 --- /dev/null +++ b/toolkit/mozapps/webextensions/amWebAPI.js @@ -0,0 +1,269 @@ +/* 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 {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/Task.jsm"); + +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) => { + Task.spawn(function*() { + let result = yield 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 + .QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell) + .QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIContentFrameMessageManager); + 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) { + return this._apiTask("createInstall", [options], 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); + }); + } + + eventListenerWasAdded(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++; + } + + eventListenerWasRemoved(type) { + this.listenerCount--; + if (this.listenerCount == 0) { + this.broker.setAddonListener(null); + } + } + + QueryInterface(iid) { + if (iid.equals(WebAPI.classID) || iid.equals(Ci.nsISupports) + || iid.equals(Ci.nsIDOMGlobalPropertyInitializer)) { + return this; + } + return Cr.NS_ERROR_NO_INTERFACE; + } +} + +WebAPI.prototype.classID = Components.ID("{8866d8e3-4ea5-48b7-a891-13ba0ac15235}"); +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([WebAPI]); diff --git a/toolkit/mozapps/webextensions/amWebInstallListener.js b/toolkit/mozapps/webextensions/amWebInstallListener.js new file mode 100644 index 000000000..0bcc345e8 --- /dev/null +++ b/toolkit/mozapps/webextensions/amWebInstallListener.js @@ -0,0 +1,348 @@ +/* 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 is a default implementation of amIWebInstallListener that should work + * for most applications but can be overriden. It notifies the observer service + * about blocked installs. For normal installs it pops up an install + * confirmation when all the add-ons have been downloaded. + */ + +"use strict"; + +const Cc = Components.classes; +const Ci = Components.interfaces; +const Cr = Components.results; +const Cu = Components.utils; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/AddonManager.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/Preferences.jsm"); + +XPCOMUtils.defineLazyModuleGetter(this, "PromptUtils", "resource://gre/modules/SharedPromptUtils.jsm"); + +const URI_XPINSTALL_DIALOG = "chrome://mozapps/content/xpinstall/xpinstallConfirm.xul"; + +// Installation can begin from any of these states +const READY_STATES = [ + AddonManager.STATE_AVAILABLE, + AddonManager.STATE_DOWNLOAD_FAILED, + AddonManager.STATE_INSTALL_FAILED, + AddonManager.STATE_CANCELLED +]; + +Cu.import("resource://gre/modules/Log.jsm"); +const LOGGER_ID = "addons.weblistener"; + +// Create a new logger for use by the Addons Web Listener +// (Requires AddonManager.jsm) +var logger = Log.repository.getLogger(LOGGER_ID); + +function notifyObservers(aTopic, aBrowser, aUri, aInstalls) { + let info = { + browser: aBrowser, + originatingURI: aUri, + installs: aInstalls, + + QueryInterface: XPCOMUtils.generateQI([Ci.amIWebInstallInfo]) + }; + Services.obs.notifyObservers(info, aTopic, null); +} + +/** + * Creates a new installer to monitor downloads and prompt to install when + * ready + * + * @param aBrowser + * The browser that started the installations + * @param aUrl + * The URL that started the installations + * @param aInstalls + * An array of AddonInstalls + */ +function Installer(aBrowser, aUrl, aInstalls) { + this.browser = aBrowser; + this.url = aUrl; + this.downloads = aInstalls; + this.installed = []; + + notifyObservers("addon-install-started", aBrowser, aUrl, aInstalls); + + for (let install of aInstalls) { + install.addListener(this); + + // Start downloading if it hasn't already begun + if (READY_STATES.indexOf(install.state) != -1) + install.install(); + } + + this.checkAllDownloaded(); +} + +Installer.prototype = { + browser: null, + downloads: null, + installed: null, + isDownloading: true, + + /** + * Checks if all downloads are now complete and if so prompts to install. + */ + checkAllDownloaded: function() { + // Prevent re-entrancy caused by the confirmation dialog cancelling unwanted + // installs. + if (!this.isDownloading) + return; + + var failed = []; + var installs = []; + + for (let install of this.downloads) { + switch (install.state) { + case AddonManager.STATE_AVAILABLE: + case AddonManager.STATE_DOWNLOADING: + // Exit early if any add-ons haven't started downloading yet or are + // still downloading + return; + case AddonManager.STATE_DOWNLOAD_FAILED: + failed.push(install); + break; + case AddonManager.STATE_DOWNLOADED: + // App disabled items are not compatible and so fail to install + if (install.addon.appDisabled) + failed.push(install); + else + installs.push(install); + + if (install.linkedInstalls) { + for (let linkedInstall of install.linkedInstalls) { + linkedInstall.addListener(this); + // Corrupt or incompatible items fail to install + if (linkedInstall.state == AddonManager.STATE_DOWNLOAD_FAILED || linkedInstall.addon.appDisabled) + failed.push(linkedInstall); + else + installs.push(linkedInstall); + } + } + break; + case AddonManager.STATE_CANCELLED: + // Just ignore cancelled downloads + break; + default: + logger.warn("Download of " + install.sourceURI.spec + " in unexpected state " + + install.state); + } + } + + this.isDownloading = false; + this.downloads = installs; + + if (failed.length > 0) { + // Stop listening and cancel any installs that are failed because of + // compatibility reasons. + for (let install of failed) { + if (install.state == AddonManager.STATE_DOWNLOADED) { + install.removeListener(this); + install.cancel(); + } + } + notifyObservers("addon-install-failed", this.browser, this.url, failed); + } + + // If none of the downloads were successful then exit early + if (this.downloads.length == 0) + return; + + // 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(this.browser, this.url, this.downloads, this.downloads.length); + return; + } + catch (e) {} + } + + if (Preferences.get("xpinstall.customConfirmationUI", false)) { + notifyObservers("addon-install-confirmation", this.browser, this.url, this.downloads); + return; + } + + let args = {}; + args.url = this.url; + args.installs = this.downloads; + args.wrappedJSObject = args; + + try { + Cc["@mozilla.org/base/telemetry;1"]. + getService(Ci.nsITelemetry). + getHistogramById("SECURITY_UI"). + add(Ci.nsISecurityUITelemetry.WARNING_CONFIRM_ADDON_INSTALL); + let parentWindow = null; + if (this.browser) { + parentWindow = this.browser.ownerDocument.defaultView; + PromptUtils.fireDialogEvent(parentWindow, "DOMWillOpenModalDialog", this.browser); + } + Services.ww.openWindow(parentWindow, URI_XPINSTALL_DIALOG, + null, "chrome,modal,centerscreen", args); + } catch (e) { + logger.warn("Exception showing install confirmation dialog", e); + for (let install of this.downloads) { + install.removeListener(this); + // Cancel the installs, as currently there is no way to make them fail + // from here. + install.cancel(); + } + notifyObservers("addon-install-cancelled", this.browser, this.url, + this.downloads); + } + }, + + /** + * Checks if all installs are now complete and if so notifies observers. + */ + checkAllInstalled: function() { + var failed = []; + + for (let install of this.downloads) { + switch (install.state) { + case AddonManager.STATE_DOWNLOADED: + case AddonManager.STATE_INSTALLING: + // Exit early if any add-ons haven't started installing yet or are + // still installing + return; + case AddonManager.STATE_INSTALL_FAILED: + failed.push(install); + break; + } + } + + this.downloads = null; + + if (failed.length > 0) + notifyObservers("addon-install-failed", this.browser, this.url, failed); + + if (this.installed.length > 0) + notifyObservers("addon-install-complete", this.browser, this.url, this.installed); + this.installed = null; + }, + + onDownloadCancelled: function(aInstall) { + aInstall.removeListener(this); + this.checkAllDownloaded(); + }, + + onDownloadFailed: function(aInstall) { + aInstall.removeListener(this); + this.checkAllDownloaded(); + }, + + onDownloadEnded: function(aInstall) { + this.checkAllDownloaded(); + return false; + }, + + onInstallCancelled: function(aInstall) { + aInstall.removeListener(this); + this.checkAllInstalled(); + }, + + onInstallFailed: function(aInstall) { + aInstall.removeListener(this); + this.checkAllInstalled(); + }, + + onInstallEnded: function(aInstall) { + aInstall.removeListener(this); + this.installed.push(aInstall); + + // If installing a theme that is disabled and can be enabled then enable it + if (aInstall.addon.type == "theme" && + aInstall.addon.userDisabled == true && + aInstall.addon.appDisabled == false) { + aInstall.addon.userDisabled = false; + } + + this.checkAllInstalled(); + } +}; + +function extWebInstallListener() { +} + +extWebInstallListener.prototype = { + /** + * @see amIWebInstallListener.idl + */ + onWebInstallDisabled: function(aBrowser, aUri, aInstalls) { + let info = { + browser: aBrowser, + originatingURI: aUri, + installs: aInstalls, + + QueryInterface: XPCOMUtils.generateQI([Ci.amIWebInstallInfo]) + }; + Services.obs.notifyObservers(info, "addon-install-disabled", null); + }, + + /** + * @see amIWebInstallListener.idl + */ + onWebInstallOriginBlocked: function(aBrowser, aUri, aInstalls) { + let info = { + browser: aBrowser, + originatingURI: aUri, + installs: aInstalls, + + install: function() { + }, + + QueryInterface: XPCOMUtils.generateQI([Ci.amIWebInstallInfo]) + }; + Services.obs.notifyObservers(info, "addon-install-origin-blocked", null); + + return false; + }, + + /** + * @see amIWebInstallListener.idl + */ + onWebInstallBlocked: function(aBrowser, aUri, aInstalls) { + let info = { + browser: aBrowser, + originatingURI: aUri, + installs: aInstalls, + + install: function() { + new Installer(this.browser, this.originatingURI, this.installs); + }, + + QueryInterface: XPCOMUtils.generateQI([Ci.amIWebInstallInfo]) + }; + Services.obs.notifyObservers(info, "addon-install-blocked", null); + + return false; + }, + + /** + * @see amIWebInstallListener.idl + */ + onWebInstallRequested: function(aBrowser, aUri, aInstalls) { + new Installer(aBrowser, aUri, aInstalls); + + // We start the installs ourself + return false; + }, + + classDescription: "XPI Install Handler", + contractID: "@mozilla.org/addons/web-install-listener;1", + classID: Components.ID("{0f38e086-89a3-40a5-8ffc-9b694de1d04a}"), + QueryInterface: XPCOMUtils.generateQI([Ci.amIWebInstallListener, + Ci.amIWebInstallListener2]) +}; + +this.NSGetFactory = XPCOMUtils.generateNSGetFactory([extWebInstallListener]); diff --git a/toolkit/mozapps/webextensions/content/about.js b/toolkit/mozapps/webextensions/content/about.js new file mode 100644 index 000000000..4f8fb353e --- /dev/null +++ b/toolkit/mozapps/webextensions/content/about.js @@ -0,0 +1,103 @@ +// -*- 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"; + +/* import-globals-from ../../../content/contentAreaUtils.js */ + +var Cu = Components.utils; +Cu.import("resource://gre/modules/AddonManager.jsm"); + +function init() { + var addon = window.arguments[0]; + var extensionsStrings = document.getElementById("extensionsStrings"); + + document.documentElement.setAttribute("addontype", addon.type); + + var iconURL = AddonManager.getPreferredIconURL(addon, 48, window); + if (iconURL) { + var extensionIcon = document.getElementById("extensionIcon"); + extensionIcon.src = iconURL; + } + + document.title = extensionsStrings.getFormattedString("aboutWindowTitle", [addon.name]); + var extensionName = document.getElementById("extensionName"); + extensionName.textContent = addon.name; + + var extensionVersion = document.getElementById("extensionVersion"); + if (addon.version) + extensionVersion.setAttribute("value", extensionsStrings.getFormattedString("aboutWindowVersionString", [addon.version])); + else + extensionVersion.hidden = true; + + var extensionDescription = document.getElementById("extensionDescription"); + if (addon.description) + extensionDescription.textContent = addon.description; + else + extensionDescription.hidden = true; + + var numDetails = 0; + + var extensionCreator = document.getElementById("extensionCreator"); + if (addon.creator) { + extensionCreator.setAttribute("value", addon.creator); + numDetails++; + } else { + extensionCreator.hidden = true; + var extensionCreatorLabel = document.getElementById("extensionCreatorLabel"); + extensionCreatorLabel.hidden = true; + } + + var extensionHomepage = document.getElementById("extensionHomepage"); + var homepageURL = addon.homepageURL; + if (homepageURL) { + extensionHomepage.setAttribute("homepageURL", homepageURL); + extensionHomepage.setAttribute("tooltiptext", homepageURL); + numDetails++; + } else { + extensionHomepage.hidden = true; + } + + numDetails += appendToList("extensionDevelopers", "developersBox", addon.developers); + numDetails += appendToList("extensionTranslators", "translatorsBox", addon.translators); + numDetails += appendToList("extensionContributors", "contributorsBox", addon.contributors); + + if (numDetails == 0) { + var groove = document.getElementById("groove"); + groove.hidden = true; + var extensionDetailsBox = document.getElementById("extensionDetailsBox"); + extensionDetailsBox.hidden = true; + } + + var acceptButton = document.documentElement.getButton("accept"); + acceptButton.label = extensionsStrings.getString("aboutWindowCloseButton"); + + setTimeout(sizeToContent, 0); +} + +function appendToList(aHeaderId, aNodeId, aItems) { + var header = document.getElementById(aHeaderId); + var node = document.getElementById(aNodeId); + + if (!aItems || aItems.length == 0) { + header.hidden = true; + return 0; + } + + for (let currentItem of aItems) { + var label = document.createElement("label"); + label.textContent = currentItem; + label.setAttribute("class", "contributor"); + node.appendChild(label); + } + + return aItems.length; +} + +function loadHomepage(aEvent) { + window.close(); + openURL(aEvent.target.getAttribute("homepageURL")); +} diff --git a/toolkit/mozapps/webextensions/content/eula.js b/toolkit/mozapps/webextensions/content/eula.js new file mode 100644 index 000000000..537ee7284 --- /dev/null +++ b/toolkit/mozapps/webextensions/content/eula.js @@ -0,0 +1,25 @@ +// -*- 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"; + +var Cu = Components.utils; +Cu.import("resource://gre/modules/AddonManager.jsm"); + +function Startup() { + var bundle = document.getElementById("extensionsStrings"); + var addon = window.arguments[0].addon; + + document.documentElement.setAttribute("addontype", addon.type); + + var iconURL = AddonManager.getPreferredIconURL(addon, 48, window); + if (iconURL) + document.getElementById("icon").src = iconURL; + + var label = document.createTextNode(bundle.getFormattedString("eulaHeader", [addon.name])); + document.getElementById("heading").appendChild(label); + document.getElementById("eula").value = addon.eula; +} diff --git a/toolkit/mozapps/webextensions/content/extensions.css b/toolkit/mozapps/webextensions/content/extensions.css new file mode 100644 index 000000000..cb5313365 --- /dev/null +++ b/toolkit/mozapps/webextensions/content/extensions.css @@ -0,0 +1,270 @@ +/* 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/. */ + +@namespace xhtml "http://www.w3.org/1999/xhtml"; + +/* HTML link elements do weird things to the layout if they are not hidden */ +xhtml|link { + display: none; +} + +#categories { + -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#categories-list"); +} + +.category { + -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#category"); +} + +.sort-controls { + -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#sorters"); +} + +.addon[status="installed"] { + -moz-box-orient: vertical; + -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#addon-generic"); +} + +.addon[status="installing"] { + -moz-box-orient: vertical; + -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#addon-installing"); +} + +.addon[pending="uninstall"] { + -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#addon-uninstalled"); +} + +.creator { + -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#creator-link"); +} + +.meta-rating { + -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#rating"); +} + +.download-progress, .download-progress[mode="undetermined"] { + -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#download-progress"); +} + +.install-status { + -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#install-status"); +} + +.detail-row { + -moz-binding: url("chrome://mozapps/content/extensions/extensions.xml#detail-row"); +} + +.text-list { + white-space: pre-line; + -moz-user-select: element; +} + +setting, row[unsupported="true"] { + display: none; +} + +setting[type="bool"] { + display: -moz-grid-line; + -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-bool"); +} + +setting[type="bool"][localized="true"] { + display: -moz-grid-line; + -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-localized-bool"); +} + +setting[type="bool"]:not([learnmore]) .preferences-learnmore, +setting[type="boolint"]:not([learnmore]) .preferences-learnmore { + visibility: collapse; +} + +setting[type="boolint"] { + display: -moz-grid-line; + -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-boolint"); +} + +setting[type="integer"] { + display: -moz-grid-line; + -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-integer"); +} + +setting[type="integer"]:not([size]) textbox { + -moz-box-flex: 1; +} + +setting[type="control"] { + display: -moz-grid-line; + -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-control"); +} + +setting[type="string"] { + display: -moz-grid-line; + -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-string"); +} + +setting[type="color"] { + display: -moz-grid-line; + -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-color"); +} + +setting[type="file"], +setting[type="directory"] { + display: -moz-grid-line; + -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-path"); +} + +setting[type="radio"], +setting[type="menulist"] { + display: -moz-grid-line; + -moz-binding: url("chrome://mozapps/content/extensions/setting.xml#setting-multi"); +} + +#addonitem-popup > menuitem[disabled="true"] { + display: none; +} + +#addonitem-popup[addontype="theme"] > #menuitem_enableItem, +#addonitem-popup[addontype="theme"] > #menuitem_disableItem, +#addonitem-popup:not([addontype="theme"]) > #menuitem_enableTheme, +#addonitem-popup:not([addontype="theme"]) > #menuitem_disableTheme { + display: none; +} + +#show-disabled-unsigned-extensions .button-text { + margin-inline-start: 3px !important; + margin-inline-end: 2px !important; +} + +#header-searching:not([active]) { + visibility: hidden; +} + +#search-list[local="false"] > .addon[remote="false"], +#search-list[remote="false"] > .addon[remote="true"] { + visibility: collapse; +} + +#detail-view { + overflow: auto; +} + +.addon:not([notification="warning"]) .warning, +.addon:not([notification="error"]) .error, +.addon:not([notification="info"]) .info, +.addon:not([pending]) .pending, +.addon:not([upgrade="true"]) .update-postfix, +.addon[active="true"] .disabled-postfix, +.addon[pending="install"] .update-postfix, +.addon[pending="install"] .disabled-postfix, +#detail-view:not([notification="warning"]) .warning, +#detail-view:not([notification="error"]) .error, +#detail-view:not([notification="info"]) .info, +#detail-view:not([pending]) .pending, +#detail-view:not([upgrade="true"]) .update-postfix, +#detail-view[active="true"] .disabled-postfix, +#detail-view[loading] .detail-view-container, +#detail-view:not([loading]) .alert-container, +.detail-row:not([value]), +#search-list[remote="false"] #search-allresults-link { + display: none; +} + +#addons-page:not([warning]) #list-view > .global-warning-container { + display: none; +} +#addon-list .date-updated { + display: none; +} + +.view-pane:not(#updates-view) .addon .relnotes-toggle, +.view-pane:not(#updates-view) .addon .include-update, +#updates-view:not([updatetype="available"]) .addon .include-update, +#updates-view[updatetype="available"] .addon .update-available-notice { + display: none; +} + +#addons-page:not([warning]) .global-warning, +#addons-page:not([warning="safemode"]) .global-warning-safemode, +#addons-page:not([warning="checkcompatibility"]) .global-warning-checkcompatibility, +#addons-page:not([warning="updatesecurity"]) .global-warning-updatesecurity { + display: none; +} + +/* Plugins aren't yet disabled by safemode (bug 342333), + so don't show that warning when viewing plugins. */ +#addons-page[warning="safemode"] .view-pane[type="plugin"] .global-warning-container, +#addons-page[warning="safemode"] #detail-view[loading="true"] .global-warning { + display: none; +} + +#addons-page .view-pane:not([type="plugin"]) #plugindeprecation-notice { + display: none; +} + +#addons-page .view-pane:not([type="experiment"]) .experiment-info-container { + display: none; +} + +.addon .relnotes { + -moz-user-select: text; +} +#detail-name, #detail-desc, #detail-fulldesc { + -moz-user-select: text; +} + +/* Make sure we're not animating hidden images. See bug 623739. */ +#view-port:not([selectedIndex="0"]) #discover-view .loading, +#discover-view:not([selectedIndex="0"]) .loading { + display: none; +} + +/* Elements in unselected richlistitems cannot be focused */ +richlistitem:not([selected]) * { + -moz-user-focus: ignore; +} + +#header-search { + width: 22em; +} + +#header-utils-btn { + -moz-user-focus: normal; +} + +.discover-button[disabled="true"] { + display: none; +} + +#experiments-learn-more[disabled="true"] { + display: none; +} + +#experiments-change-telemetry[disabled="true"] { + display: none; +} + +.view-pane[type="experiment"] .error, +.view-pane[type="experiment"] .warning, +.view-pane[type="experiment"] .addon:not([pending="uninstall"]) .pending, +.view-pane[type="experiment"] .disabled-postfix, +.view-pane[type="experiment"] .update-postfix, +.view-pane[type="experiment"] .addon-control.enable, +.view-pane[type="experiment"] .addon-control.disable, +#detail-view[type="experiment"] .alert-container, +#detail-view[type="experiment"] #detail-version, +#detail-view[type="experiment"] #detail-creator, +#detail-view[type="experiment"] #detail-enable-btn, +#detail-view[type="experiment"] #detail-disable-btn { + display: none; +} + +.view-pane:not([type="experiment"]) .experiment-container, +.view-pane:not([type="experiment"]) #detail-experiment-container { + display: none; +} + +.addon[type="experiment"][status="installing"] .experiment-time, +.addon[type="experiment"][status="installing"] .experiment-state { + display: none; +} diff --git a/toolkit/mozapps/webextensions/content/extensions.js b/toolkit/mozapps/webextensions/content/extensions.js new file mode 100644 index 000000000..3159eb1e1 --- /dev/null +++ b/toolkit/mozapps/webextensions/content/extensions.js @@ -0,0 +1,3827 @@ +/* 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"; + +/* import-globals-from ../../../content/contentAreaUtils.js */ +/* globals XMLStylesheetProcessingInstruction*/ + +var Cc = Components.classes; +var Ci = Components.interfaces; +var Cu = Components.utils; +var Cr = Components.results; + +Cu.import("resource://gre/modules/XPCOMUtils.jsm"); +Cu.import("resource://gre/modules/Services.jsm"); +Cu.import("resource://gre/modules/DownloadUtils.jsm"); +Cu.import("resource://gre/modules/AddonManager.jsm"); +Cu.import("resource://gre/modules/addons/AddonRepository.jsm"); + +const CONSTANTS = {}; +Cu.import("resource://gre/modules/addons/AddonConstants.jsm", CONSTANTS); +const SIGNING_REQUIRED = CONSTANTS.REQUIRE_SIGNING ? + true : + Services.prefs.getBoolPref("xpinstall.signatures.required"); + +XPCOMUtils.defineLazyModuleGetter(this, "PluralForm", + "resource://gre/modules/PluralForm.jsm"); +XPCOMUtils.defineLazyModuleGetter(this, "Preferences", + "resource://gre/modules/Preferences.jsm"); + +const PREF_DISCOVERURL = "extensions.webservice.discoverURL"; +const PREF_DISCOVER_ENABLED = "extensions.getAddons.showPane"; +const PREF_XPI_ENABLED = "xpinstall.enabled"; +const PREF_MAXRESULTS = "extensions.getAddons.maxResults"; +const PREF_GETADDONS_CACHE_ENABLED = "extensions.getAddons.cache.enabled"; +const PREF_GETADDONS_CACHE_ID_ENABLED = "extensions.%ID%.getAddons.cache.enabled"; +const PREF_UI_TYPE_HIDDEN = "extensions.ui.%TYPE%.hidden"; +const PREF_UI_LASTCATEGORY = "extensions.ui.lastCategory"; + +const LOADING_MSG_DELAY = 100; + +const SEARCH_SCORE_MULTIPLIER_NAME = 2; +const SEARCH_SCORE_MULTIPLIER_DESCRIPTION = 2; + +// Use integers so search scores are sortable by nsIXULSortService +const SEARCH_SCORE_MATCH_WHOLEWORD = 10; +const SEARCH_SCORE_MATCH_WORDBOUNDRY = 6; +const SEARCH_SCORE_MATCH_SUBSTRING = 3; + +const UPDATES_RECENT_TIMESPAN = 2 * 24 * 3600000; // 2 days (in milliseconds) +const UPDATES_RELEASENOTES_TRANSFORMFILE = "chrome://mozapps/content/extensions/updateinfo.xsl"; + +const XMLURI_PARSE_ERROR = "http://www.mozilla.org/newlayout/xml/parsererror.xml" + +var gViewDefault = "addons://discover/"; + +var gStrings = {}; +XPCOMUtils.defineLazyServiceGetter(gStrings, "bundleSvc", + "@mozilla.org/intl/stringbundle;1", + "nsIStringBundleService"); + +XPCOMUtils.defineLazyGetter(gStrings, "brand", function() { + return this.bundleSvc.createBundle("chrome://branding/locale/brand.properties"); +}); +XPCOMUtils.defineLazyGetter(gStrings, "ext", function() { + return this.bundleSvc.createBundle("chrome://mozapps/locale/extensions/extensions.properties"); +}); +XPCOMUtils.defineLazyGetter(gStrings, "dl", function() { + return this.bundleSvc.createBundle("chrome://mozapps/locale/downloads/downloads.properties"); +}); + +XPCOMUtils.defineLazyGetter(gStrings, "brandShortName", function() { + return this.brand.GetStringFromName("brandShortName"); +}); +XPCOMUtils.defineLazyGetter(gStrings, "appVersion", function() { + return Services.appinfo.version; +}); + +document.addEventListener("load", initialize, true); +window.addEventListener("unload", shutdown, false); + +class MessageDispatcher { + constructor(target) { + this.listeners = new Map(); + this.target = target; + } + + addMessageListener(name, handler) { + if (!this.listeners.has(name)) { + this.listeners.set(name, new Set()); + } + + this.listeners.get(name).add(handler); + } + + removeMessageListener(name, handler) { + if (this.listeners.has(name)) { + this.listeners.get(name).delete(handler); + } + } + + sendAsyncMessage(name, data) { + for (let handler of this.listeners.get(name) || new Set()) { + Promise.resolve().then(() => { + handler.receiveMessage({ + name, + data, + target: this.target, + }); + }); + } + } +} + +/** + * A mock FrameMessageManager global to allow frame scripts to run in + * non-top-level, non-remote s as if they were top-level or + * remote. + * + * @param {Element} browser + * A XUL element. + */ +class FakeFrameMessageManager { + constructor(browser) { + let dispatcher = new MessageDispatcher(browser); + let frameDispatcher = new MessageDispatcher(null); + + this.sendAsyncMessage = frameDispatcher.sendAsyncMessage.bind(frameDispatcher); + this.addMessageListener = dispatcher.addMessageListener.bind(dispatcher); + this.removeMessageListener = dispatcher.removeMessageListener.bind(dispatcher); + + this.frame = { + get content() { + return browser.contentWindow; + }, + + get docShell() { + return browser.docShell; + }, + + addEventListener: browser.addEventListener.bind(browser), + removeEventListener: browser.removeEventListener.bind(browser), + + sendAsyncMessage: dispatcher.sendAsyncMessage.bind(dispatcher), + addMessageListener: frameDispatcher.addMessageListener.bind(frameDispatcher), + removeMessageListener: frameDispatcher.removeMessageListener.bind(frameDispatcher), + } + } + + loadFrameScript(url) { + Services.scriptloader.loadSubScript(url, Object.create(this.frame)); + } +} + +var gPendingInitializations = 1; +Object.defineProperty(this, "gIsInitializing", { + get: () => gPendingInitializations > 0 +}); + +function initialize(event) { + // XXXbz this listener gets _all_ load events for all nodes in the + // document... but relies on not being called "too early". + if (event.target instanceof XMLStylesheetProcessingInstruction) { + return; + } + document.removeEventListener("load", initialize, true); + + let globalCommandSet = document.getElementById("globalCommandSet"); + globalCommandSet.addEventListener("command", function(event) { + gViewController.doCommand(event.target.id); + }); + + let viewCommandSet = document.getElementById("viewCommandSet"); + viewCommandSet.addEventListener("commandupdate", function(event) { + gViewController.updateCommands(); + }); + viewCommandSet.addEventListener("command", function(event) { + gViewController.doCommand(event.target.id); + }); + + let detailScreenshot = document.getElementById("detail-screenshot"); + detailScreenshot.addEventListener("load", function(event) { + this.removeAttribute("loading"); + }); + detailScreenshot.addEventListener("error", function(event) { + this.setAttribute("loading", "error"); + }); + + let addonPage = document.getElementById("addons-page"); + addonPage.addEventListener("dragenter", function(event) { + gDragDrop.onDragOver(event); + }); + addonPage.addEventListener("dragover", function(event) { + gDragDrop.onDragOver(event); + }); + addonPage.addEventListener("drop", function(event) { + gDragDrop.onDrop(event); + }); + addonPage.addEventListener("keypress", function(event) { + gHeader.onKeyPress(event); + }); + + if (!isDiscoverEnabled()) { + gViewDefault = "addons://list/extension"; + } + + gViewController.initialize(); + gCategories.initialize(); + gHeader.initialize(); + gEventManager.initialize(); + Services.obs.addObserver(sendEMPong, "EM-ping", false); + Services.obs.notifyObservers(window, "EM-loaded", ""); + + // If the initial view has already been selected (by a call to loadView from + // the above notifications) then bail out now + if (gViewController.initialViewSelected) + return; + + // If there is a history state to restore then use that + if (window.history.state) { + gViewController.updateState(window.history.state); + return; + } + + // Default to the last selected category + var view = gCategories.node.value; + + // Allow passing in a view through the window arguments + if ("arguments" in window && window.arguments.length > 0 && + window.arguments[0] !== null && "view" in window.arguments[0]) { + view = window.arguments[0].view; + } + + gViewController.loadInitialView(view); +} + +function notifyInitialized() { + if (!gIsInitializing) + return; + + gPendingInitializations--; + if (!gIsInitializing) { + var event = document.createEvent("Events"); + event.initEvent("Initialized", true, true); + document.dispatchEvent(event); + } +} + +function shutdown() { + gCategories.shutdown(); + gSearchView.shutdown(); + gEventManager.shutdown(); + gViewController.shutdown(); + Services.obs.removeObserver(sendEMPong, "EM-ping"); +} + +function sendEMPong(aSubject, aTopic, aData) { + Services.obs.notifyObservers(window, "EM-pong", ""); +} + +// Used by external callers to load a specific view into the manager +function loadView(aViewId) { + if (!gViewController.initialViewSelected) { + // The caller opened the window and immediately loaded the view so it + // should be the initial history entry + + gViewController.loadInitialView(aViewId); + } else { + gViewController.loadView(aViewId); + } +} + +function isCorrectlySigned(aAddon) { + // Add-ons without an "isCorrectlySigned" property are correctly signed as + // they aren't the correct type for signing. + return aAddon.isCorrectlySigned !== false; +} + +function isDiscoverEnabled() { + if (Services.prefs.getPrefType(PREF_DISCOVERURL) == Services.prefs.PREF_INVALID) + return false; + + try { + if (!Services.prefs.getBoolPref(PREF_DISCOVER_ENABLED)) + return false; + } catch (e) {} + + try { + if (!Services.prefs.getBoolPref(PREF_XPI_ENABLED)) + return false; + } catch (e) {} + + return true; +} + +/** + * Obtain the main DOMWindow for the current context. + */ +function getMainWindow() { + return window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIWebNavigation) + .QueryInterface(Ci.nsIDocShellTreeItem) + .rootTreeItem + .QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindow); +} + +function getBrowserElement() { + return window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDocShell) + .chromeEventHandler; +} + +/** + * Obtain the DOMWindow that can open a preferences pane. + * + * This is essentially "get the browser chrome window" with the added check + * that the supposed browser chrome window is capable of opening a preferences + * pane. + * + * This may return null if we can't find the browser chrome window. + */ +function getMainWindowWithPreferencesPane() { + let mainWindow = getMainWindow(); + if (mainWindow && "openAdvancedPreferences" in mainWindow) { + return mainWindow; + } + return null; +} + +/** + * A wrapper around the HTML5 session history service that allows the browser + * back/forward controls to work within the manager + */ +var HTML5History = { + get index() { + return window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIWebNavigation) + .sessionHistory.index; + }, + + get canGoBack() { + return window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIWebNavigation) + .canGoBack; + }, + + get canGoForward() { + return window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIWebNavigation) + .canGoForward; + }, + + back: function() { + window.history.back(); + gViewController.updateCommand("cmd_back"); + gViewController.updateCommand("cmd_forward"); + }, + + forward: function() { + window.history.forward(); + gViewController.updateCommand("cmd_back"); + gViewController.updateCommand("cmd_forward"); + }, + + pushState: function(aState) { + window.history.pushState(aState, document.title); + }, + + replaceState: function(aState) { + window.history.replaceState(aState, document.title); + }, + + popState: function() { + function onStatePopped(aEvent) { + window.removeEventListener("popstate", onStatePopped, true); + // TODO To ensure we can't go forward again we put an additional entry + // for the current state into the history. Ideally we would just strip + // the history but there doesn't seem to be a way to do that. Bug 590661 + window.history.pushState(aEvent.state, document.title); + } + window.addEventListener("popstate", onStatePopped, true); + window.history.back(); + gViewController.updateCommand("cmd_back"); + gViewController.updateCommand("cmd_forward"); + } +}; + +/** + * A wrapper around a fake history service + */ +var FakeHistory = { + pos: 0, + states: [null], + + get index() { + return this.pos; + }, + + get canGoBack() { + return this.pos > 0; + }, + + get canGoForward() { + return (this.pos + 1) < this.states.length; + }, + + back: function() { + if (this.pos == 0) + throw Components.Exception("Cannot go back from this point"); + + this.pos--; + gViewController.updateState(this.states[this.pos]); + gViewController.updateCommand("cmd_back"); + gViewController.updateCommand("cmd_forward"); + }, + + forward: function() { + if ((this.pos + 1) >= this.states.length) + throw Components.Exception("Cannot go forward from this point"); + + this.pos++; + gViewController.updateState(this.states[this.pos]); + gViewController.updateCommand("cmd_back"); + gViewController.updateCommand("cmd_forward"); + }, + + pushState: function(aState) { + this.pos++; + this.states.splice(this.pos, this.states.length); + this.states.push(aState); + }, + + replaceState: function(aState) { + this.states[this.pos] = aState; + }, + + popState: function() { + if (this.pos == 0) + throw Components.Exception("Cannot popState from this view"); + + this.states.splice(this.pos, this.states.length); + this.pos--; + + gViewController.updateState(this.states[this.pos]); + gViewController.updateCommand("cmd_back"); + gViewController.updateCommand("cmd_forward"); + } +}; + +// If the window has a session history then use the HTML5 History wrapper +// otherwise use our fake history implementation +if (window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIWebNavigation) + .sessionHistory) { + var gHistory = HTML5History; +} +else { + gHistory = FakeHistory; +} + +var gEventManager = { + _listeners: {}, + _installListeners: [], + + initialize: function() { + const ADDON_EVENTS = ["onEnabling", "onEnabled", "onDisabling", + "onDisabled", "onUninstalling", "onUninstalled", + "onInstalled", "onOperationCancelled", + "onUpdateAvailable", "onUpdateFinished", + "onCompatibilityUpdateAvailable", + "onPropertyChanged"]; + for (let evt of ADDON_EVENTS) { + let event = evt; + this[event] = (...aArgs) => this.delegateAddonEvent(event, aArgs); + } + + const INSTALL_EVENTS = ["onNewInstall", "onDownloadStarted", + "onDownloadEnded", "onDownloadFailed", + "onDownloadProgress", "onDownloadCancelled", + "onInstallStarted", "onInstallEnded", + "onInstallFailed", "onInstallCancelled", + "onExternalInstall"]; + for (let evt of INSTALL_EVENTS) { + let event = evt; + this[event] = (...aArgs) => this.delegateInstallEvent(event, aArgs); + } + + AddonManager.addManagerListener(this); + AddonManager.addInstallListener(this); + AddonManager.addAddonListener(this); + + this.refreshGlobalWarning(); + this.refreshAutoUpdateDefault(); + + var contextMenu = document.getElementById("addonitem-popup"); + contextMenu.addEventListener("popupshowing", function() { + var addon = gViewController.currentViewObj.getSelectedAddon(); + contextMenu.setAttribute("addontype", addon.type); + + var menuSep = document.getElementById("addonitem-menuseparator"); + var countMenuItemsBeforeSep = 0; + for (let child of contextMenu.children) { + if (child == menuSep) { + break; + } + if (child.nodeName == "menuitem" && + gViewController.isCommandEnabled(child.command)) { + countMenuItemsBeforeSep++; + } + } + + // Hide the separator if there are no visible menu items before it + menuSep.hidden = (countMenuItemsBeforeSep == 0); + + }, false); + + let addonTooltip = document.getElementById("addonitem-tooltip"); + addonTooltip.addEventListener("popupshowing", function() { + let addonItem = addonTooltip.triggerNode; + // The way the test triggers the tooltip the richlistitem is the + // tooltipNode but in normal use it is the anonymous node. This allows + // any case + if (addonItem.localName != "richlistitem") + addonItem = document.getBindingParent(addonItem); + + let tiptext = addonItem.getAttribute("name"); + + if (addonItem.mAddon) { + if (shouldShowVersionNumber(addonItem.mAddon)) { + tiptext += " " + (addonItem.hasAttribute("upgrade") ? addonItem.mManualUpdate.version + : addonItem.mAddon.version); + } + } + else if (shouldShowVersionNumber(addonItem.mInstall)) { + tiptext += " " + addonItem.mInstall.version; + } + + addonTooltip.label = tiptext; + }, false); + }, + + shutdown: function() { + AddonManager.removeManagerListener(this); + AddonManager.removeInstallListener(this); + AddonManager.removeAddonListener(this); + }, + + registerAddonListener: function(aListener, aAddonId) { + if (!(aAddonId in this._listeners)) + this._listeners[aAddonId] = []; + else if (this._listeners[aAddonId].indexOf(aListener) != -1) + return; + this._listeners[aAddonId].push(aListener); + }, + + unregisterAddonListener: function(aListener, aAddonId) { + if (!(aAddonId in this._listeners)) + return; + var index = this._listeners[aAddonId].indexOf(aListener); + if (index == -1) + return; + this._listeners[aAddonId].splice(index, 1); + }, + + registerInstallListener: function(aListener) { + if (this._installListeners.indexOf(aListener) != -1) + return; + this._installListeners.push(aListener); + }, + + unregisterInstallListener: function(aListener) { + var i = this._installListeners.indexOf(aListener); + if (i == -1) + return; + this._installListeners.splice(i, 1); + }, + + delegateAddonEvent: function(aEvent, aParams) { + var addon = aParams.shift(); + if (!(addon.id in this._listeners)) + return; + + var listeners = this._listeners[addon.id]; + for (let listener of listeners) { + if (!(aEvent in listener)) + continue; + try { + listener[aEvent].apply(listener, aParams); + } catch (e) { + // this shouldn't be fatal + Cu.reportError(e); + } + } + }, + + delegateInstallEvent: function(aEvent, aParams) { + var existingAddon = aEvent == "onExternalInstall" ? aParams[1] : aParams[0].existingAddon; + // If the install is an update then send the event to all listeners + // registered for the existing add-on + if (existingAddon) + this.delegateAddonEvent(aEvent, [existingAddon].concat(aParams)); + + for (let listener of this._installListeners) { + if (!(aEvent in listener)) + continue; + try { + listener[aEvent].apply(listener, aParams); + } catch (e) { + // this shouldn't be fatal + Cu.reportError(e); + } + } + }, + + refreshGlobalWarning: function() { + var page = document.getElementById("addons-page"); + + if (Services.appinfo.inSafeMode) { + page.setAttribute("warning", "safemode"); + return; + } + + if (AddonManager.checkUpdateSecurityDefault && + !AddonManager.checkUpdateSecurity) { + page.setAttribute("warning", "updatesecurity"); + return; + } + + if (!AddonManager.checkCompatibility) { + page.setAttribute("warning", "checkcompatibility"); + return; + } + + page.removeAttribute("warning"); + }, + + refreshAutoUpdateDefault: function() { + var updateEnabled = AddonManager.updateEnabled; + var autoUpdateDefault = AddonManager.autoUpdateDefault; + + // The checkbox needs to reflect that both prefs need to be true + // for updates to be checked for and applied automatically + document.getElementById("utils-autoUpdateDefault") + .setAttribute("checked", updateEnabled && autoUpdateDefault); + + document.getElementById("utils-resetAddonUpdatesToAutomatic").hidden = !autoUpdateDefault; + document.getElementById("utils-resetAddonUpdatesToManual").hidden = autoUpdateDefault; + }, + + onCompatibilityModeChanged: function() { + this.refreshGlobalWarning(); + }, + + onCheckUpdateSecurityChanged: function() { + this.refreshGlobalWarning(); + }, + + onUpdateModeChanged: function() { + this.refreshAutoUpdateDefault(); + } +}; + + +var gViewController = { + viewPort: null, + currentViewId: "", + currentViewObj: null, + currentViewRequest: 0, + viewObjects: {}, + viewChangeCallback: null, + initialViewSelected: false, + lastHistoryIndex: -1, + + initialize: function() { + this.viewPort = document.getElementById("view-port"); + this.headeredViews = document.getElementById("headered-views"); + this.headeredViewsDeck = document.getElementById("headered-views-content"); + + this.viewObjects["search"] = gSearchView; + this.viewObjects["discover"] = gDiscoverView; + this.viewObjects["list"] = gListView; + this.viewObjects["detail"] = gDetailView; + this.viewObjects["updates"] = gUpdatesView; + + for (let type in this.viewObjects) { + let view = this.viewObjects[type]; + view.initialize(); + } + + window.controllers.appendController(this); + + window.addEventListener("popstate", function(e) { + gViewController.updateState(e.state); + }, + false); + }, + + shutdown: function() { + if (this.currentViewObj) + this.currentViewObj.hide(); + this.currentViewRequest = 0; + + for (let type in this.viewObjects) { + let view = this.viewObjects[type]; + if ("shutdown" in view) { + try { + view.shutdown(); + } catch (e) { + // this shouldn't be fatal + Cu.reportError(e); + } + } + } + + window.controllers.removeController(this); + }, + + updateState: function(state) { + try { + this.loadViewInternal(state.view, state.previousView, state); + this.lastHistoryIndex = gHistory.index; + } + catch (e) { + // The attempt to load the view failed, try moving further along history + if (this.lastHistoryIndex > gHistory.index) { + if (gHistory.canGoBack) + gHistory.back(); + else + gViewController.replaceView(gViewDefault); + } else if (gHistory.canGoForward) { + gHistory.forward(); + } else { + gViewController.replaceView(gViewDefault); + } + } + }, + + parseViewId: function(aViewId) { + var matchRegex = /^addons:\/\/([^\/]+)\/(.*)$/; + var [, viewType, viewParam] = aViewId.match(matchRegex) || []; + return {type: viewType, param: decodeURIComponent(viewParam)}; + }, + + get isLoading() { + return !this.currentViewObj || this.currentViewObj.node.hasAttribute("loading"); + }, + + loadView: function(aViewId) { + var isRefresh = false; + if (aViewId == this.currentViewId) { + if (this.isLoading) + return; + if (!("refresh" in this.currentViewObj)) + return; + if (!this.currentViewObj.canRefresh()) + return; + isRefresh = true; + } + + var state = { + view: aViewId, + previousView: this.currentViewId + }; + if (!isRefresh) { + gHistory.pushState(state); + this.lastHistoryIndex = gHistory.index; + } + this.loadViewInternal(aViewId, this.currentViewId, state); + }, + + // Replaces the existing view with a new one, rewriting the current history + // entry to match. + replaceView: function(aViewId) { + if (aViewId == this.currentViewId) + return; + + var state = { + view: aViewId, + previousView: null + }; + gHistory.replaceState(state); + this.loadViewInternal(aViewId, null, state); + }, + + loadInitialView: function(aViewId) { + var state = { + view: aViewId, + previousView: null + }; + gHistory.replaceState(state); + + this.loadViewInternal(aViewId, null, state); + this.initialViewSelected = true; + notifyInitialized(); + }, + + get displayedView() { + if (this.viewPort.selectedPanel == this.headeredViews) { + return this.headeredViewsDeck.selectedPanel; + } + return this.viewPort.selectedPanel; + }, + + set displayedView(view) { + let node = view.node; + if (node.parentNode == this.headeredViewsDeck) { + this.headeredViewsDeck.selectedPanel = node; + this.viewPort.selectedPanel = this.headeredViews; + } else { + this.viewPort.selectedPanel = node; + } + }, + + loadViewInternal: function(aViewId, aPreviousView, aState) { + var view = this.parseViewId(aViewId); + + if (!view.type || !(view.type in this.viewObjects)) + throw Components.Exception("Invalid view: " + view.type); + + var viewObj = this.viewObjects[view.type]; + if (!viewObj.node) + throw Components.Exception("Root node doesn't exist for '" + view.type + "' view"); + + if (this.currentViewObj && aViewId != aPreviousView) { + try { + let canHide = this.currentViewObj.hide(); + if (canHide === false) + return; + this.displayedView.removeAttribute("loading"); + } catch (e) { + // this shouldn't be fatal + Cu.reportError(e); + } + } + + gCategories.select(aViewId, aPreviousView); + + this.currentViewId = aViewId; + this.currentViewObj = viewObj; + + this.displayedView = this.currentViewObj; + this.currentViewObj.node.setAttribute("loading", "true"); + this.currentViewObj.node.focus(); + + if (aViewId == aPreviousView) + this.currentViewObj.refresh(view.param, ++this.currentViewRequest, aState); + else + this.currentViewObj.show(view.param, ++this.currentViewRequest, aState); + }, + + // Moves back in the document history and removes the current history entry + popState: function(aCallback) { + this.viewChangeCallback = aCallback; + gHistory.popState(); + }, + + notifyViewChanged: function() { + this.displayedView.removeAttribute("loading"); + + if (this.viewChangeCallback) { + this.viewChangeCallback(); + this.viewChangeCallback = null; + } + + var event = document.createEvent("Events"); + event.initEvent("ViewChanged", true, true); + this.currentViewObj.node.dispatchEvent(event); + }, + + commands: { + cmd_back: { + isEnabled: function() { + return gHistory.canGoBack; + }, + doCommand: function() { + gHistory.back(); + } + }, + + cmd_forward: { + isEnabled: function() { + return gHistory.canGoForward; + }, + doCommand: function() { + gHistory.forward(); + } + }, + + cmd_focusSearch: { + isEnabled: () => true, + doCommand: function() { + gHeader.focusSearchBox(); + } + }, + + cmd_restartApp: { + isEnabled: function() { + return true; + }, + doCommand: function() { + let cancelQuit = Cc["@mozilla.org/supports-PRBool;1"]. + createInstance(Ci.nsISupportsPRBool); + Services.obs.notifyObservers(cancelQuit, "quit-application-requested", + "restart"); + if (cancelQuit.data) + return; // somebody canceled our quit request + + let appStartup = Cc["@mozilla.org/toolkit/app-startup;1"]. + getService(Ci.nsIAppStartup); + appStartup.quit(Ci.nsIAppStartup.eAttemptQuit | Ci.nsIAppStartup.eRestart); + } + }, + + cmd_enableCheckCompatibility: { + isEnabled: function() { + return true; + }, + doCommand: function() { + AddonManager.checkCompatibility = true; + } + }, + + cmd_enableUpdateSecurity: { + isEnabled: function() { + return true; + }, + doCommand: function() { + AddonManager.checkUpdateSecurity = true; + } + }, + + cmd_toggleAutoUpdateDefault: { + isEnabled: function() { + return true; + }, + doCommand: function() { + if (!AddonManager.updateEnabled || !AddonManager.autoUpdateDefault) { + // 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; + } + } + }, + + cmd_resetAddonAutoUpdate: { + isEnabled: function() { + return true; + }, + doCommand: function() { + AddonManager.getAllAddons(function(aAddonList) { + for (let addon of aAddonList) { + if ("applyBackgroundUpdates" in addon) + addon.applyBackgroundUpdates = AddonManager.AUTOUPDATE_DEFAULT; + } + }); + } + }, + + cmd_goToDiscoverPane: { + isEnabled: function() { + return gDiscoverView.enabled; + }, + doCommand: function() { + gViewController.loadView("addons://discover/"); + } + }, + + cmd_goToRecentUpdates: { + isEnabled: function() { + return true; + }, + doCommand: function() { + gViewController.loadView("addons://updates/recent"); + } + }, + + cmd_goToAvailableUpdates: { + isEnabled: function() { + return true; + }, + doCommand: function() { + gViewController.loadView("addons://updates/available"); + } + }, + + cmd_showItemDetails: { + isEnabled: function(aAddon) { + return !!aAddon && (gViewController.currentViewObj != gDetailView); + }, + doCommand: function(aAddon, aScrollToPreferences) { + gViewController.loadView("addons://detail/" + + encodeURIComponent(aAddon.id) + + (aScrollToPreferences ? "/preferences" : "")); + } + }, + + cmd_findAllUpdates: { + inProgress: false, + isEnabled: function() { + return !this.inProgress; + }, + doCommand: function() { + this.inProgress = true; + gViewController.updateCommand("cmd_findAllUpdates"); + document.getElementById("updates-noneFound").hidden = true; + document.getElementById("updates-progress").hidden = false; + document.getElementById("updates-manualUpdatesFound-btn").hidden = true; + + var pendingChecks = 0; + var numUpdated = 0; + var numManualUpdates = 0; + var restartNeeded = false; + + let updateStatus = () => { + if (pendingChecks > 0) + return; + + this.inProgress = false; + gViewController.updateCommand("cmd_findAllUpdates"); + document.getElementById("updates-progress").hidden = true; + gUpdatesView.maybeRefresh(); + + if (numManualUpdates > 0 && numUpdated == 0) { + document.getElementById("updates-manualUpdatesFound-btn").hidden = false; + return; + } + + if (numUpdated == 0) { + document.getElementById("updates-noneFound").hidden = false; + return; + } + + if (restartNeeded) { + document.getElementById("updates-downloaded").hidden = false; + document.getElementById("updates-restart-btn").hidden = false; + } else { + document.getElementById("updates-installed").hidden = false; + } + } + + var updateInstallListener = { + onDownloadFailed: function() { + pendingChecks--; + updateStatus(); + }, + onInstallFailed: function() { + pendingChecks--; + updateStatus(); + }, + onInstallEnded: function(aInstall, aAddon) { + pendingChecks--; + numUpdated++; + if (isPending(aInstall.existingAddon, "upgrade")) + restartNeeded = true; + updateStatus(); + } + }; + + var updateCheckListener = { + onUpdateAvailable: function(aAddon, aInstall) { + gEventManager.delegateAddonEvent("onUpdateAvailable", + [aAddon, aInstall]); + if (AddonManager.shouldAutoUpdate(aAddon)) { + aInstall.addListener(updateInstallListener); + aInstall.install(); + } else { + pendingChecks--; + numManualUpdates++; + updateStatus(); + } + }, + onNoUpdateAvailable: function(aAddon) { + pendingChecks--; + updateStatus(); + }, + onUpdateFinished: function(aAddon, aError) { + gEventManager.delegateAddonEvent("onUpdateFinished", + [aAddon, aError]); + } + }; + + AddonManager.getAddonsByTypes(null, function(aAddonList) { + for (let addon of aAddonList) { + if (addon.permissions & AddonManager.PERM_CAN_UPGRADE) { + pendingChecks++; + addon.findUpdates(updateCheckListener, + AddonManager.UPDATE_WHEN_USER_REQUESTED); + } + } + + if (pendingChecks == 0) + updateStatus(); + }); + } + }, + + cmd_findItemUpdates: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + return hasPermission(aAddon, "upgrade"); + }, + doCommand: function(aAddon) { + var listener = { + onUpdateAvailable: function(aAddon, aInstall) { + gEventManager.delegateAddonEvent("onUpdateAvailable", + [aAddon, aInstall]); + if (AddonManager.shouldAutoUpdate(aAddon)) + aInstall.install(); + }, + onNoUpdateAvailable: function(aAddon) { + gEventManager.delegateAddonEvent("onNoUpdateAvailable", + [aAddon]); + } + }; + gEventManager.delegateAddonEvent("onCheckingUpdate", [aAddon]); + aAddon.findUpdates(listener, AddonManager.UPDATE_WHEN_USER_REQUESTED); + } + }, + + cmd_showItemPreferences: { + isEnabled: function(aAddon) { + if (!aAddon || + (!aAddon.isActive && !aAddon.isGMPlugin) || + !aAddon.optionsURL) { + return false; + } + if (gViewController.currentViewObj == gDetailView && + (aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE || + aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE_BROWSER)) { + return false; + } + if (aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE_INFO) + return false; + return true; + }, + doCommand: function(aAddon) { + if (hasInlineOptions(aAddon)) { + gViewController.commands.cmd_showItemDetails.doCommand(aAddon, true); + return; + } + var optionsURL = aAddon.optionsURL; + if (aAddon.optionsType == AddonManager.OPTIONS_TYPE_TAB && + openOptionsInTab(optionsURL)) { + return; + } + var windows = Services.wm.getEnumerator(null); + while (windows.hasMoreElements()) { + var win = windows.getNext(); + if (win.closed) { + continue; + } + if (win.document.documentURI == optionsURL) { + win.focus(); + return; + } + } + var features = "chrome,titlebar,toolbar,centerscreen"; + try { + var instantApply = Services.prefs.getBoolPref("browser.preferences.instantApply"); + features += instantApply ? ",dialog=no" : ",modal"; + } catch (e) { + features += ",modal"; + } + openDialog(optionsURL, "", features); + } + }, + + cmd_showItemAbout: { + isEnabled: function(aAddon) { + // XXXunf This may be applicable to install items too. See bug 561260 + return !!aAddon; + }, + doCommand: function(aAddon) { + var aboutURL = aAddon.aboutURL; + if (aboutURL) + openDialog(aboutURL, "", "chrome,centerscreen,modal", aAddon); + else + openDialog("chrome://mozapps/content/extensions/about.xul", + "", "chrome,centerscreen,modal", aAddon); + } + }, + + cmd_enableItem: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + let addonType = AddonManager.addonTypes[aAddon.type]; + return (!(addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) && + hasPermission(aAddon, "enable")); + }, + doCommand: function(aAddon) { + aAddon.userDisabled = false; + }, + getTooltip: function(aAddon) { + if (!aAddon) + return ""; + if (aAddon.operationsRequiringRestart & AddonManager.OP_NEEDS_RESTART_ENABLE) + return gStrings.ext.GetStringFromName("enableAddonRestartRequiredTooltip"); + return gStrings.ext.GetStringFromName("enableAddonTooltip"); + } + }, + + cmd_disableItem: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + let addonType = AddonManager.addonTypes[aAddon.type]; + return (!(addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) && + hasPermission(aAddon, "disable")); + }, + doCommand: function(aAddon) { + aAddon.userDisabled = true; + }, + getTooltip: function(aAddon) { + if (!aAddon) + return ""; + if (aAddon.operationsRequiringRestart & AddonManager.OP_NEEDS_RESTART_DISABLE) + return gStrings.ext.GetStringFromName("disableAddonRestartRequiredTooltip"); + return gStrings.ext.GetStringFromName("disableAddonTooltip"); + } + }, + + cmd_installItem: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + return aAddon.install && aAddon.install.state == AddonManager.STATE_AVAILABLE; + }, + doCommand: function(aAddon) { + function doInstall() { + gViewController.currentViewObj.getListItemForID(aAddon.id)._installStatus.installRemote(); + } + + if (gViewController.currentViewObj == gDetailView) + gViewController.popState(doInstall); + else + doInstall(); + } + }, + + cmd_purchaseItem: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + return !!aAddon.purchaseURL; + }, + doCommand: function(aAddon) { + openURL(aAddon.purchaseURL); + } + }, + + cmd_uninstallItem: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + return hasPermission(aAddon, "uninstall"); + }, + doCommand: function(aAddon) { + if (gViewController.currentViewObj != gDetailView) { + aAddon.uninstall(); + return; + } + + gViewController.popState(function() { + gViewController.currentViewObj.getListItemForID(aAddon.id).uninstall(); + }); + }, + getTooltip: function(aAddon) { + if (!aAddon) + return ""; + if (aAddon.operationsRequiringRestart & AddonManager.OP_NEEDS_RESTART_UNINSTALL) + return gStrings.ext.GetStringFromName("uninstallAddonRestartRequiredTooltip"); + return gStrings.ext.GetStringFromName("uninstallAddonTooltip"); + } + }, + + cmd_cancelUninstallItem: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + return isPending(aAddon, "uninstall"); + }, + doCommand: function(aAddon) { + aAddon.cancelUninstall(); + } + }, + + cmd_installFromFile: { + isEnabled: function() { + return true; + }, + doCommand: function() { + const nsIFilePicker = Ci.nsIFilePicker; + var fp = Cc["@mozilla.org/filepicker;1"] + .createInstance(nsIFilePicker); + fp.init(window, + gStrings.ext.GetStringFromName("installFromFile.dialogTitle"), + nsIFilePicker.modeOpenMultiple); + try { + fp.appendFilter(gStrings.ext.GetStringFromName("installFromFile.filterName"), + "*.xpi;*.jar"); + fp.appendFilters(nsIFilePicker.filterAll); + } catch (e) { } + + if (fp.show() != nsIFilePicker.returnOK) + return; + + var files = fp.files; + var installs = []; + + function buildNextInstall() { + if (!files.hasMoreElements()) { + if (installs.length > 0) { + // Display the normal install confirmation for the installs + let webInstaller = Cc["@mozilla.org/addons/web-install-listener;1"]. + getService(Ci.amIWebInstallListener); + webInstaller.onWebInstallRequested(getBrowserElement(), + document.documentURIObject, + installs); + } + return; + } + + var file = files.getNext(); + AddonManager.getInstallForFile(file, function(aInstall) { + installs.push(aInstall); + buildNextInstall(); + }); + } + + buildNextInstall(); + } + }, + + cmd_debugAddons: { + isEnabled: function() { + return true; + }, + doCommand: function() { + let mainWindow = getMainWindow(); + if ("switchToTabHavingURI" in mainWindow) { + mainWindow.switchToTabHavingURI("about:debugging#addons", true); + } + }, + }, + + cmd_cancelOperation: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + return aAddon.pendingOperations != AddonManager.PENDING_NONE; + }, + doCommand: function(aAddon) { + if (isPending(aAddon, "install")) { + aAddon.install.cancel(); + } else if (isPending(aAddon, "upgrade")) { + aAddon.pendingUpgrade.install.cancel(); + } else if (isPending(aAddon, "uninstall")) { + aAddon.cancelUninstall(); + } else if (isPending(aAddon, "enable")) { + aAddon.userDisabled = true; + } else if (isPending(aAddon, "disable")) { + aAddon.userDisabled = false; + } + } + }, + + cmd_contribute: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + return ("contributionURL" in aAddon && aAddon.contributionURL); + }, + doCommand: function(aAddon) { + openURL(aAddon.contributionURL); + } + }, + + cmd_askToActivateItem: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + let addonType = AddonManager.addonTypes[aAddon.type]; + return ((addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) && + hasPermission(aAddon, "ask_to_activate")); + }, + doCommand: function(aAddon) { + aAddon.userDisabled = AddonManager.STATE_ASK_TO_ACTIVATE; + } + }, + + cmd_alwaysActivateItem: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + let addonType = AddonManager.addonTypes[aAddon.type]; + return ((addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) && + hasPermission(aAddon, "enable")); + }, + doCommand: function(aAddon) { + aAddon.userDisabled = false; + } + }, + + cmd_neverActivateItem: { + isEnabled: function(aAddon) { + if (!aAddon) + return false; + let addonType = AddonManager.addonTypes[aAddon.type]; + return ((addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) && + hasPermission(aAddon, "disable")); + }, + doCommand: function(aAddon) { + aAddon.userDisabled = true; + } + }, + + cmd_showUnsignedExtensions: { + isEnabled: function() { + return true; + }, + doCommand: function() { + gViewController.loadView("addons://list/extension?unsigned=true"); + }, + }, + + cmd_showAllExtensions: { + isEnabled: function() { + return true; + }, + doCommand: function() { + gViewController.loadView("addons://list/extension"); + }, + }, + }, + + supportsCommand: function(aCommand) { + return (aCommand in this.commands); + }, + + isCommandEnabled: function(aCommand) { + if (!this.supportsCommand(aCommand)) + return false; + var addon = this.currentViewObj.getSelectedAddon(); + return this.commands[aCommand].isEnabled(addon); + }, + + updateCommands: function() { + // wait until the view is initialized + if (!this.currentViewObj) + return; + var addon = this.currentViewObj.getSelectedAddon(); + for (let commandId in this.commands) + this.updateCommand(commandId, addon); + }, + + updateCommand: function(aCommandId, aAddon) { + if (typeof aAddon == "undefined") + aAddon = this.currentViewObj.getSelectedAddon(); + var cmd = this.commands[aCommandId]; + var cmdElt = document.getElementById(aCommandId); + cmdElt.setAttribute("disabled", !cmd.isEnabled(aAddon)); + if ("getTooltip" in cmd) { + let tooltip = cmd.getTooltip(aAddon); + if (tooltip) + cmdElt.setAttribute("tooltiptext", tooltip); + else + cmdElt.removeAttribute("tooltiptext"); + } + }, + + doCommand: function(aCommand, aAddon) { + if (!this.supportsCommand(aCommand)) + return; + var cmd = this.commands[aCommand]; + if (!aAddon) + aAddon = this.currentViewObj.getSelectedAddon(); + if (!cmd.isEnabled(aAddon)) + return; + cmd.doCommand(aAddon); + }, + + onEvent: function() {} +}; + +function hasInlineOptions(aAddon) { + return (aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE || + aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE_BROWSER || + aAddon.optionsType == AddonManager.OPTIONS_TYPE_INLINE_INFO); +} + +function openOptionsInTab(optionsURL) { + let mainWindow = getMainWindow(); + if ("switchToTabHavingURI" in mainWindow) { + mainWindow.switchToTabHavingURI(optionsURL, true); + return true; + } + return false; +} + +function formatDate(aDate) { + const locale = Cc["@mozilla.org/chrome/chrome-registry;1"] + .getService(Ci.nsIXULChromeRegistry) + .getSelectedLocale("global", true); + const dtOptions = { year: 'numeric', month: 'long', day: 'numeric' }; + return aDate.toLocaleDateString(locale, dtOptions); +} + + +function hasPermission(aAddon, aPerm) { + var perm = AddonManager["PERM_CAN_" + aPerm.toUpperCase()]; + return !!(aAddon.permissions & perm); +} + + +function isPending(aAddon, aAction) { + var action = AddonManager["PENDING_" + aAction.toUpperCase()]; + return !!(aAddon.pendingOperations & action); +} + +function isInState(aInstall, aState) { + var state = AddonManager["STATE_" + aState.toUpperCase()]; + return aInstall.state == state; +} + +function shouldShowVersionNumber(aAddon) { + if (!aAddon.version) + return false; + + // The version number is hidden for lightweight themes. + if (aAddon.type == "theme") + return !/@personas\.mozilla\.org$/.test(aAddon.id); + + return true; +} + +function createItem(aObj, aIsInstall, aIsRemote) { + let item = document.createElement("richlistitem"); + + item.setAttribute("class", "addon addon-view"); + item.setAttribute("name", aObj.name); + item.setAttribute("type", aObj.type); + item.setAttribute("remote", !!aIsRemote); + + if (aIsInstall) { + item.mInstall = aObj; + + if (aObj.state != AddonManager.STATE_INSTALLED) { + item.setAttribute("status", "installing"); + return item; + } + aObj = aObj.addon; + } + + item.mAddon = aObj; + + item.setAttribute("status", "installed"); + + // set only attributes needed for sorting and XBL binding, + // the binding handles the rest + item.setAttribute("value", aObj.id); + + return item; +} + +function sortElements(aElements, aSortBy, aAscending) { + // aSortBy is an Array of attributes to sort by, in decending + // order of priority. + + const DATE_FIELDS = ["updateDate"]; + const NUMERIC_FIELDS = ["size", "relevancescore", "purchaseAmount"]; + + // We're going to group add-ons into the following buckets: + // + // enabledInstalled + // * Enabled + // * Incompatible but enabled because compatibility checking is off + // * Waiting to be installed + // * Waiting to be enabled + // + // pendingDisable + // * Waiting to be disabled + // + // pendingUninstall + // * Waiting to be removed + // + // disabledIncompatibleBlocked + // * Disabled + // * Incompatible + // * Blocklisted + + const UISTATE_ORDER = ["enabled", "askToActivate", "pendingDisable", + "pendingUninstall", "disabled"]; + + function dateCompare(a, b) { + var aTime = a.getTime(); + var bTime = b.getTime(); + if (aTime < bTime) + return -1; + if (aTime > bTime) + return 1; + return 0; + } + + function numberCompare(a, b) { + return a - b; + } + + function stringCompare(a, b) { + return a.localeCompare(b); + } + + function uiStateCompare(a, b) { + // If we're in descending order, swap a and b, because + // we don't ever want to have descending uiStates + if (!aAscending) + [a, b] = [b, a]; + + return (UISTATE_ORDER.indexOf(a) - UISTATE_ORDER.indexOf(b)); + } + + function getValue(aObj, aKey) { + if (!aObj) + return null; + + if (aObj.hasAttribute(aKey)) + return aObj.getAttribute(aKey); + + var addon = aObj.mAddon || aObj.mInstall; + var addonType = aObj.mAddon && AddonManager.addonTypes[aObj.mAddon.type]; + + if (!addon) + return null; + + if (aKey == "uiState") { + if (addon.pendingOperations == AddonManager.PENDING_DISABLE) + return "pendingDisable"; + if (addon.pendingOperations == AddonManager.PENDING_UNINSTALL) + return "pendingUninstall"; + if (!addon.isActive && + (addon.pendingOperations != AddonManager.PENDING_ENABLE && + addon.pendingOperations != AddonManager.PENDING_INSTALL)) + return "disabled"; + if (addonType && (addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) && + addon.userDisabled == AddonManager.STATE_ASK_TO_ACTIVATE) + return "askToActivate"; + return "enabled"; + } + + return addon[aKey]; + } + + // aSortFuncs will hold the sorting functions that we'll + // use per element, in the correct order. + var aSortFuncs = []; + + for (let i = 0; i < aSortBy.length; i++) { + var sortBy = aSortBy[i]; + + aSortFuncs[i] = stringCompare; + + if (sortBy == "uiState") + aSortFuncs[i] = uiStateCompare; + else if (DATE_FIELDS.indexOf(sortBy) != -1) + aSortFuncs[i] = dateCompare; + else if (NUMERIC_FIELDS.indexOf(sortBy) != -1) + aSortFuncs[i] = numberCompare; + } + + + aElements.sort(function(a, b) { + if (!aAscending) + [a, b] = [b, a]; + + for (let i = 0; i < aSortFuncs.length; i++) { + var sortBy = aSortBy[i]; + var aValue = getValue(a, sortBy); + var bValue = getValue(b, sortBy); + + if (!aValue && !bValue) + return 0; + if (!aValue) + return -1; + if (!bValue) + return 1; + if (aValue != bValue) { + var result = aSortFuncs[i](aValue, bValue); + + if (result != 0) + return result; + } + } + + // If we got here, then all values of a and b + // must have been equal. + return 0; + + }); +} + +function sortList(aList, aSortBy, aAscending) { + var elements = Array.slice(aList.childNodes, 0); + sortElements(elements, [aSortBy], aAscending); + + while (aList.listChild) + aList.removeChild(aList.lastChild); + + for (let element of elements) + aList.appendChild(element); +} + +function getAddonsAndInstalls(aType, aCallback) { + let addons = null, installs = null; + let types = (aType != null) ? [aType] : null; + + AddonManager.getAddonsByTypes(types, function(aAddonsList) { + addons = aAddonsList.filter(a => !a.hidden); + if (installs != null) + aCallback(addons, installs); + }); + + AddonManager.getInstallsByTypes(types, function(aInstallsList) { + // skip over upgrade installs and non-active installs + installs = aInstallsList.filter(function(aInstall) { + return !(aInstall.existingAddon || + aInstall.state == AddonManager.STATE_AVAILABLE); + }); + + if (addons != null) + aCallback(addons, installs) + }); +} + +function doPendingUninstalls(aListBox) { + // Uninstalling add-ons can mutate the list so find the add-ons first then + // uninstall them + var items = []; + var listitem = aListBox.firstChild; + while (listitem) { + if (listitem.getAttribute("pending") == "uninstall" && + !(listitem.opRequiresRestart("UNINSTALL"))) + items.push(listitem.mAddon); + listitem = listitem.nextSibling; + } + + for (let addon of items) + addon.uninstall(); +} + +var gCategories = { + node: null, + _search: null, + + initialize: function() { + this.node = document.getElementById("categories"); + this._search = this.get("addons://search/"); + + var types = AddonManager.addonTypes; + for (var type in types) + this.onTypeAdded(types[type]); + + AddonManager.addTypeListener(this); + + try { + this.node.value = Services.prefs.getCharPref(PREF_UI_LASTCATEGORY); + } catch (e) { } + + // If there was no last view or no existing category matched the last view + // then the list will default to selecting the search category and we never + // want to show that as the first view so switch to the default category + if (!this.node.selectedItem || this.node.selectedItem == this._search) + this.node.value = gViewDefault; + + this.node.addEventListener("select", () => { + this.maybeHideSearch(); + gViewController.loadView(this.node.selectedItem.value); + }, false); + + this.node.addEventListener("click", (aEvent) => { + var selectedItem = this.node.selectedItem; + if (aEvent.target.localName == "richlistitem" && + aEvent.target == selectedItem) { + var viewId = selectedItem.value; + + if (gViewController.parseViewId(viewId).type == "search") { + viewId += encodeURIComponent(gHeader.searchQuery); + } + + gViewController.loadView(viewId); + } + }, false); + }, + + shutdown: function() { + AddonManager.removeTypeListener(this); + }, + + _insertCategory: function(aId, aName, aView, aPriority, aStartHidden) { + // If this category already exists then don't re-add it + if (document.getElementById("category-" + aId)) + return; + + var category = document.createElement("richlistitem"); + category.setAttribute("id", "category-" + aId); + category.setAttribute("value", aView); + category.setAttribute("class", "category"); + category.setAttribute("name", aName); + category.setAttribute("tooltiptext", aName); + category.setAttribute("priority", aPriority); + category.setAttribute("hidden", aStartHidden); + + var node; + for (node of this.node.children) { + var nodePriority = parseInt(node.getAttribute("priority")); + // If the new type's priority is higher than this one then this is the + // insertion point + if (aPriority < nodePriority) + break; + // If the new type's priority is lower than this one then this is isn't + // the insertion point + if (aPriority > nodePriority) + continue; + // If the priorities are equal and the new type's name is earlier + // alphabetically then this is the insertion point + if (String.localeCompare(aName, node.getAttribute("name")) < 0) + break; + } + + this.node.insertBefore(category, node); + }, + + _removeCategory: function(aId) { + var category = document.getElementById("category-" + aId); + if (!category) + return; + + // If this category is currently selected then switch to the default view + if (this.node.selectedItem == category) + gViewController.replaceView(gViewDefault); + + this.node.removeChild(category); + }, + + onTypeAdded: function(aType) { + // Ignore types that we don't have a view object for + if (!(aType.viewType in gViewController.viewObjects)) + return; + + var aViewId = "addons://" + aType.viewType + "/" + aType.id; + + var startHidden = false; + if (aType.flags & AddonManager.TYPE_UI_HIDE_EMPTY) { + var prefName = PREF_UI_TYPE_HIDDEN.replace("%TYPE%", aType.id); + try { + startHidden = Services.prefs.getBoolPref(prefName); + } + catch (e) { + // Default to hidden + startHidden = true; + } + + gPendingInitializations++; + getAddonsAndInstalls(aType.id, (aAddonsList, aInstallsList) => { + var hidden = (aAddonsList.length == 0 && aInstallsList.length == 0); + var item = this.get(aViewId); + + // Don't load view that is becoming hidden + if (hidden && aViewId == gViewController.currentViewId) + gViewController.loadView(gViewDefault); + + item.hidden = hidden; + Services.prefs.setBoolPref(prefName, hidden); + + if (aAddonsList.length > 0 || aInstallsList.length > 0) { + notifyInitialized(); + return; + } + + gEventManager.registerInstallListener({ + onDownloadStarted: function(aInstall) { + this._maybeShowCategory(aInstall); + }, + + onInstallStarted: function(aInstall) { + this._maybeShowCategory(aInstall); + }, + + onInstallEnded: function(aInstall, aAddon) { + this._maybeShowCategory(aAddon); + }, + + onExternalInstall: function(aAddon, aExistingAddon, aRequiresRestart) { + this._maybeShowCategory(aAddon); + }, + + _maybeShowCategory: aAddon => { + if (aType.id == aAddon.type) { + this.get(aViewId).hidden = false; + Services.prefs.setBoolPref(prefName, false); + gEventManager.unregisterInstallListener(this); + } + } + }); + + notifyInitialized(); + }); + } + + this._insertCategory(aType.id, aType.name, aViewId, aType.uiPriority, + startHidden); + }, + + onTypeRemoved: function(aType) { + this._removeCategory(aType.id); + }, + + get selected() { + return this.node.selectedItem ? this.node.selectedItem.value : null; + }, + + select: function(aId, aPreviousView) { + var view = gViewController.parseViewId(aId); + if (view.type == "detail" && aPreviousView) { + aId = aPreviousView; + view = gViewController.parseViewId(aPreviousView); + } + aId = aId.replace(/\?.*/, ""); + + Services.prefs.setCharPref(PREF_UI_LASTCATEGORY, aId); + + if (this.node.selectedItem && + this.node.selectedItem.value == aId) { + this.node.selectedItem.hidden = false; + this.node.selectedItem.disabled = false; + return; + } + + var item; + if (view.type == "search") + item = this._search; + else + item = this.get(aId); + + if (item) { + item.hidden = false; + item.disabled = false; + this.node.suppressOnSelect = true; + this.node.selectedItem = item; + this.node.suppressOnSelect = false; + this.node.ensureElementIsVisible(item); + + this.maybeHideSearch(); + } + }, + + get: function(aId) { + var items = document.getElementsByAttribute("value", aId); + if (items.length) + return items[0]; + return null; + }, + + setBadge: function(aId, aCount) { + let item = this.get(aId); + if (item) + item.badgeCount = aCount; + }, + + maybeHideSearch: function() { + var view = gViewController.parseViewId(this.node.selectedItem.value); + this._search.disabled = view.type != "search"; + } +}; + + +var gHeader = { + _search: null, + _dest: "", + + initialize: function() { + this._search = document.getElementById("header-search"); + + this._search.addEventListener("command", function(aEvent) { + var query = aEvent.target.value; + if (query.length == 0) + return; + + gViewController.loadView("addons://search/" + encodeURIComponent(query)); + }, false); + + function updateNavButtonVisibility() { + var shouldShow = gHeader.shouldShowNavButtons; + document.getElementById("back-btn").hidden = !shouldShow; + document.getElementById("forward-btn").hidden = !shouldShow; + } + + window.addEventListener("focus", function(aEvent) { + if (aEvent.target == window) + updateNavButtonVisibility(); + }, false); + + updateNavButtonVisibility(); + }, + + focusSearchBox: function() { + this._search.focus(); + }, + + onKeyPress: function(aEvent) { + if (String.fromCharCode(aEvent.charCode) == "/") { + this.focusSearchBox(); + return; + } + }, + + get shouldShowNavButtons() { + var docshellItem = window.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIWebNavigation) + .QueryInterface(Ci.nsIDocShellTreeItem); + + // If there is no outer frame then make the buttons visible + if (docshellItem.rootTreeItem == docshellItem) + return true; + + var outerWin = docshellItem.rootTreeItem.QueryInterface(Ci.nsIInterfaceRequestor) + .getInterface(Ci.nsIDOMWindow); + var outerDoc = outerWin.document; + var node = outerDoc.getElementById("back-button"); + // If the outer frame has no back-button then make the buttons visible + if (!node) + return true; + + // If the back-button or any of its parents are hidden then make the buttons + // visible + while (node != outerDoc) { + var style = outerWin.getComputedStyle(node, ""); + if (style.display == "none") + return true; + if (style.visibility != "visible") + return true; + node = node.parentNode; + } + + return false; + }, + + get searchQuery() { + return this._search.value; + }, + + set searchQuery(aQuery) { + this._search.value = aQuery; + }, +}; + + +var gDiscoverView = { + node: null, + enabled: true, + // Set to true after the view is first shown. If initialization completes + // after this then it must also load the discover homepage + loaded: false, + _browser: null, + _loading: null, + _error: null, + homepageURL: null, + _loadListeners: [], + hideHeader: true, + + initialize: function() { + this.enabled = isDiscoverEnabled(); + if (!this.enabled) { + gCategories.get("addons://discover/").hidden = true; + return; + } + + this.node = document.getElementById("discover-view"); + this._loading = document.getElementById("discover-loading"); + this._error = document.getElementById("discover-error"); + this._browser = document.getElementById("discover-browser"); + + let compatMode = "normal"; + if (!AddonManager.checkCompatibility) + compatMode = "ignore"; + else if (AddonManager.strictCompatibility) + compatMode = "strict"; + + var url = Services.prefs.getCharPref(PREF_DISCOVERURL); + url = url.replace("%COMPATIBILITY_MODE%", compatMode); + url = Services.urlFormatter.formatURL(url); + + let setURL = (aURL) => { + try { + this.homepageURL = Services.io.newURI(aURL, null, null); + } catch (e) { + this.showError(); + notifyInitialized(); + return; + } + + this._browser.homePage = this.homepageURL.spec; + this._browser.addProgressListener(this); + + if (this.loaded) + this._loadURL(this.homepageURL.spec, false, notifyInitialized); + else + notifyInitialized(); + } + + if (Services.prefs.getBoolPref(PREF_GETADDONS_CACHE_ENABLED) == false) { + setURL(url); + return; + } + + gPendingInitializations++; + AddonManager.getAllAddons(function(aAddons) { + var list = {}; + for (let addon of aAddons) { + var prefName = PREF_GETADDONS_CACHE_ID_ENABLED.replace("%ID%", + addon.id); + try { + if (!Services.prefs.getBoolPref(prefName)) + continue; + } catch (e) { } + list[addon.id] = { + name: addon.name, + version: addon.version, + type: addon.type, + userDisabled: addon.userDisabled, + isCompatible: addon.isCompatible, + isBlocklisted: addon.blocklistState == Ci.nsIBlocklistService.STATE_BLOCKED + } + } + + setURL(url + "#" + JSON.stringify(list)); + }); + }, + + destroy: function() { + try { + this._browser.removeProgressListener(this); + } + catch (e) { + // Ignore the case when the listener wasn't already registered + } + }, + + show: function(aParam, aRequest, aState, aIsRefresh) { + gViewController.updateCommands(); + + // If we're being told to load a specific URL then just do that + if (aState && "url" in aState) { + this.loaded = true; + this._loadURL(aState.url); + } + + // If the view has loaded before and still at the homepage (if refreshing), + // and the error page is not visible then there is nothing else to do + if (this.loaded && this.node.selectedPanel != this._error && + (!aIsRefresh || (this._browser.currentURI && + this._browser.currentURI.spec == this._browser.homePage))) { + gViewController.notifyViewChanged(); + return; + } + + this.loaded = true; + + // No homepage means initialization isn't complete, the browser will get + // loaded once initialization is complete + if (!this.homepageURL) { + this._loadListeners.push(gViewController.notifyViewChanged.bind(gViewController)); + return; + } + + this._loadURL(this.homepageURL.spec, aIsRefresh, + gViewController.notifyViewChanged.bind(gViewController)); + }, + + canRefresh: function() { + if (this._browser.currentURI && + this._browser.currentURI.spec == this._browser.homePage) + return false; + return true; + }, + + refresh: function(aParam, aRequest, aState) { + this.show(aParam, aRequest, aState, true); + }, + + hide: function() { }, + + showError: function() { + this.node.selectedPanel = this._error; + }, + + _loadURL: function(aURL, aKeepHistory, aCallback) { + if (this._browser.currentURI.spec == aURL) { + if (aCallback) + aCallback(); + return; + } + + if (aCallback) + this._loadListeners.push(aCallback); + + var flags = 0; + if (!aKeepHistory) + flags |= Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY; + + this._browser.loadURIWithFlags(aURL, flags); + }, + + onLocationChange: function(aWebProgress, aRequest, aLocation, aFlags) { + // Ignore the about:blank load + if (aLocation.spec == "about:blank") + return; + + // When using the real session history the inner-frame will update the + // session history automatically, if using the fake history though it must + // be manually updated + if (gHistory == FakeHistory) { + var docshell = aWebProgress.QueryInterface(Ci.nsIDocShell); + + var state = { + view: "addons://discover/", + url: aLocation.spec + }; + + var replaceHistory = Ci.nsIWebNavigation.LOAD_FLAGS_REPLACE_HISTORY << 16; + if (docshell.loadType & replaceHistory) + gHistory.replaceState(state); + else + gHistory.pushState(state); + gViewController.lastHistoryIndex = gHistory.index; + } + + gViewController.updateCommands(); + + // If the hostname is the same as the new location's host and either the + // default scheme is insecure or the new location is secure then continue + // with the load + if (aLocation.host == this.homepageURL.host && + (!this.homepageURL.schemeIs("https") || aLocation.schemeIs("https"))) + return; + + // Canceling the request will send an error to onStateChange which will show + // the error page + aRequest.cancel(Components.results.NS_BINDING_ABORTED); + }, + + onSecurityChange: function(aWebProgress, aRequest, aState) { + // Don't care about security if the page is not https + if (!this.homepageURL.schemeIs("https")) + return; + + // If the request was secure then it is ok + if (aState & Ci.nsIWebProgressListener.STATE_IS_SECURE) + return; + + // Canceling the request will send an error to onStateChange which will show + // the error page + aRequest.cancel(Components.results.NS_BINDING_ABORTED); + }, + + onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) { + let transferStart = Ci.nsIWebProgressListener.STATE_IS_DOCUMENT | + Ci.nsIWebProgressListener.STATE_IS_REQUEST | + Ci.nsIWebProgressListener.STATE_TRANSFERRING; + // Once transferring begins show the content + if ((aStateFlags & transferStart) === transferStart) + this.node.selectedPanel = this._browser; + + // Only care about the network events + if (!(aStateFlags & (Ci.nsIWebProgressListener.STATE_IS_NETWORK))) + return; + + // If this is the start of network activity then show the loading page + if (aStateFlags & (Ci.nsIWebProgressListener.STATE_START)) + this.node.selectedPanel = this._loading; + + // Ignore anything except stop events + if (!(aStateFlags & (Ci.nsIWebProgressListener.STATE_STOP))) + return; + + // Consider the successful load of about:blank as still loading + if (aRequest instanceof Ci.nsIChannel && aRequest.URI.spec == "about:blank") + return; + + // If there was an error loading the page or the new hostname is not the + // same as the default hostname or the default scheme is secure and the new + // scheme is insecure then show the error page + const NS_ERROR_PARSED_DATA_CACHED = 0x805D0021; + if (!(Components.isSuccessCode(aStatus) || aStatus == NS_ERROR_PARSED_DATA_CACHED) || + (aRequest && aRequest instanceof Ci.nsIHttpChannel && !aRequest.requestSucceeded)) { + this.showError(); + } else { + // Got a successful load, make sure the browser is visible + this.node.selectedPanel = this._browser; + gViewController.updateCommands(); + } + + var listeners = this._loadListeners; + this._loadListeners = []; + + for (let listener of listeners) + listener(); + }, + + onProgressChange: function() { }, + onStatusChange: function() { }, + + QueryInterface: XPCOMUtils.generateQI([Ci.nsIWebProgressListener, + Ci.nsISupportsWeakReference]), + + getSelectedAddon: function() { + return null; + } +}; + + +var gCachedAddons = {}; + +var gSearchView = { + node: null, + _filter: null, + _sorters: null, + _loading: null, + _listBox: null, + _emptyNotice: null, + _allResultsLink: null, + _lastQuery: null, + _lastRemoteTotal: 0, + _pendingSearches: 0, + + initialize: function() { + this.node = document.getElementById("search-view"); + this._filter = document.getElementById("search-filter-radiogroup"); + this._sorters = document.getElementById("search-sorters"); + this._sorters.handler = this; + this._loading = document.getElementById("search-loading"); + this._listBox = document.getElementById("search-list"); + this._emptyNotice = document.getElementById("search-list-empty"); + this._allResultsLink = document.getElementById("search-allresults-link"); + + if (!AddonManager.isInstallEnabled("application/x-xpinstall")) + this._filter.hidden = true; + + this._listBox.addEventListener("keydown", aEvent => { + if (aEvent.keyCode == aEvent.DOM_VK_RETURN) { + var item = this._listBox.selectedItem; + if (item) + item.showInDetailView(); + } + }, false); + + this._filter.addEventListener("command", () => this.updateView(), false); + }, + + shutdown: function() { + if (AddonRepository.isSearching) + AddonRepository.cancelSearch(); + }, + + get isSearching() { + return this._pendingSearches > 0; + }, + + show: function(aQuery, aRequest) { + gEventManager.registerInstallListener(this); + + this.showEmptyNotice(false); + this.showAllResultsLink(0); + this.showLoading(true); + this._sorters.showprice = false; + + gHeader.searchQuery = aQuery; + aQuery = aQuery.trim().toLocaleLowerCase(); + if (this._lastQuery == aQuery) { + this.updateView(); + gViewController.notifyViewChanged(); + return; + } + this._lastQuery = aQuery; + + if (AddonRepository.isSearching) + AddonRepository.cancelSearch(); + + while (this._listBox.firstChild.localName == "richlistitem") + this._listBox.removeChild(this._listBox.firstChild); + + gCachedAddons = {}; + this._pendingSearches = 2; + this._sorters.setSort("relevancescore", false); + + var elements = []; + + let createSearchResults = (aObjsList, aIsInstall, aIsRemote) => { + for (let index in aObjsList) { + let obj = aObjsList[index]; + let score = aObjsList.length - index; + if (!aIsRemote && aQuery.length > 0) { + score = this.getMatchScore(obj, aQuery); + if (score == 0) + continue; + } + + let item = createItem(obj, aIsInstall, aIsRemote); + item.setAttribute("relevancescore", score); + if (aIsRemote) { + gCachedAddons[obj.id] = obj; + if (obj.purchaseURL) + this._sorters.showprice = true; + } + + elements.push(item); + } + } + + let finishSearch = (createdCount) => { + if (elements.length > 0) { + sortElements(elements, [this._sorters.sortBy], this._sorters.ascending); + for (let element of elements) + this._listBox.insertBefore(element, this._listBox.lastChild); + this.updateListAttributes(); + } + + this._pendingSearches--; + this.updateView(); + + if (!this.isSearching) + gViewController.notifyViewChanged(); + } + + getAddonsAndInstalls(null, function(aAddons, aInstalls) { + if (gViewController && aRequest != gViewController.currentViewRequest) + return; + + createSearchResults(aAddons, false, false); + createSearchResults(aInstalls, true, false); + finishSearch(); + }); + + var maxRemoteResults = 0; + try { + maxRemoteResults = Services.prefs.getIntPref(PREF_MAXRESULTS); + } catch (e) {} + + if (maxRemoteResults <= 0) { + finishSearch(0); + return; + } + + AddonRepository.searchAddons(aQuery, maxRemoteResults, { + searchFailed: () => { + if (gViewController && aRequest != gViewController.currentViewRequest) + return; + + this._lastRemoteTotal = 0; + + // XXXunf Better handling of AMO search failure. See bug 579502 + finishSearch(0); // Silently fail + }, + + searchSucceeded: (aAddonsList, aAddonCount, aTotalResults) => { + if (gViewController && aRequest != gViewController.currentViewRequest) + return; + + if (aTotalResults > maxRemoteResults) + this._lastRemoteTotal = aTotalResults; + else + this._lastRemoteTotal = 0; + + var createdCount = createSearchResults(aAddonsList, false, true); + finishSearch(createdCount); + } + }); + }, + + showLoading: function(aLoading) { + this._loading.hidden = !aLoading; + this._listBox.hidden = aLoading; + }, + + updateView: function() { + var showLocal = this._filter.value == "local"; + + if (!showLocal && !AddonManager.isInstallEnabled("application/x-xpinstall")) + showLocal = true; + + this._listBox.setAttribute("local", showLocal); + this._listBox.setAttribute("remote", !showLocal); + + this.showLoading(this.isSearching && !showLocal); + if (!this.isSearching) { + var isEmpty = true; + var results = this._listBox.getElementsByTagName("richlistitem"); + for (let result of results) { + var isRemote = (result.getAttribute("remote") == "true"); + if ((isRemote && !showLocal) || (!isRemote && showLocal)) { + isEmpty = false; + break; + } + } + + this.showEmptyNotice(isEmpty); + this.showAllResultsLink(this._lastRemoteTotal); + } + + gViewController.updateCommands(); + }, + + hide: function() { + gEventManager.unregisterInstallListener(this); + doPendingUninstalls(this._listBox); + }, + + getMatchScore: function(aObj, aQuery) { + var score = 0; + score += this.calculateMatchScore(aObj.name, aQuery, + SEARCH_SCORE_MULTIPLIER_NAME); + score += this.calculateMatchScore(aObj.description, aQuery, + SEARCH_SCORE_MULTIPLIER_DESCRIPTION); + return score; + }, + + calculateMatchScore: function(aStr, aQuery, aMultiplier) { + var score = 0; + if (!aStr || aQuery.length == 0) + return score; + + aStr = aStr.trim().toLocaleLowerCase(); + var haystack = aStr.split(/\s+/); + var needles = aQuery.split(/\s+/); + + for (let needle of needles) { + for (let hay of haystack) { + if (hay == needle) { + // matching whole words is best + score += SEARCH_SCORE_MATCH_WHOLEWORD; + } else { + let i = hay.indexOf(needle); + if (i == 0) // matching on word boundries is also good + score += SEARCH_SCORE_MATCH_WORDBOUNDRY; + else if (i > 0) // substring matches not so good + score += SEARCH_SCORE_MATCH_SUBSTRING; + } + } + } + + // give progressively higher score for longer queries, since longer queries + // are more likely to be unique and therefore more relevant. + if (needles.length > 1 && aStr.indexOf(aQuery) != -1) + score += needles.length; + + return score * aMultiplier; + }, + + showEmptyNotice: function(aShow) { + this._emptyNotice.hidden = !aShow; + this._listBox.hidden = aShow; + }, + + showAllResultsLink: function(aTotalResults) { + if (aTotalResults == 0) { + this._allResultsLink.hidden = true; + return; + } + + var linkStr = gStrings.ext.GetStringFromName("showAllSearchResults"); + linkStr = PluralForm.get(aTotalResults, linkStr); + linkStr = linkStr.replace("#1", aTotalResults); + this._allResultsLink.setAttribute("value", linkStr); + + this._allResultsLink.setAttribute("href", + AddonRepository.getSearchURL(this._lastQuery)); + this._allResultsLink.hidden = false; + }, + + updateListAttributes: function() { + var item = this._listBox.querySelector("richlistitem[remote='true'][first]"); + if (item) + item.removeAttribute("first"); + item = this._listBox.querySelector("richlistitem[remote='true'][last]"); + if (item) + item.removeAttribute("last"); + var items = this._listBox.querySelectorAll("richlistitem[remote='true']"); + if (items.length > 0) { + items[0].setAttribute("first", true); + items[items.length - 1].setAttribute("last", true); + } + + item = this._listBox.querySelector("richlistitem:not([remote='true'])[first]"); + if (item) + item.removeAttribute("first"); + item = this._listBox.querySelector("richlistitem:not([remote='true'])[last]"); + if (item) + item.removeAttribute("last"); + items = this._listBox.querySelectorAll("richlistitem:not([remote='true'])"); + if (items.length > 0) { + items[0].setAttribute("first", true); + items[items.length - 1].setAttribute("last", true); + } + + }, + + onSortChanged: function(aSortBy, aAscending) { + var footer = this._listBox.lastChild; + this._listBox.removeChild(footer); + + sortList(this._listBox, aSortBy, aAscending); + this.updateListAttributes(); + + this._listBox.appendChild(footer); + }, + + onDownloadCancelled: function(aInstall) { + this.removeInstall(aInstall); + }, + + onInstallCancelled: function(aInstall) { + this.removeInstall(aInstall); + }, + + removeInstall: function(aInstall) { + for (let item of this._listBox.childNodes) { + if (item.mInstall == aInstall) { + this._listBox.removeChild(item); + return; + } + } + }, + + getSelectedAddon: function() { + var item = this._listBox.selectedItem; + if (item) + return item.mAddon; + return null; + }, + + getListItemForID: function(aId) { + var listitem = this._listBox.firstChild; + while (listitem) { + if (listitem.getAttribute("status") == "installed" && listitem.mAddon.id == aId) + return listitem; + listitem = listitem.nextSibling; + } + return null; + } +}; + + +var gListView = { + node: null, + _listBox: null, + _emptyNotice: null, + _type: null, + + initialize: function() { + this.node = document.getElementById("list-view"); + this._listBox = document.getElementById("addon-list"); + this._emptyNotice = document.getElementById("addon-list-empty"); + + this._listBox.addEventListener("keydown", (aEvent) => { + if (aEvent.keyCode == aEvent.DOM_VK_RETURN) { + var item = this._listBox.selectedItem; + if (item) + item.showInDetailView(); + } + }, false); + + document.getElementById("signing-learn-more").setAttribute("href", + Services.urlFormatter.formatURLPref("app.support.baseURL") + "unsigned-addons"); + + let findSignedAddonsLink = document.getElementById("find-alternative-addons"); + try { + findSignedAddonsLink.setAttribute("href", + Services.urlFormatter.formatURLPref("extensions.getAddons.link.url")); + } catch (e) { + findSignedAddonsLink.classList.remove("text-link"); + } + + try { + document.getElementById("signing-dev-manual-link").setAttribute("href", + Services.prefs.getCharPref("xpinstall.signatures.devInfoURL")); + } catch (e) { + document.getElementById("signing-dev-info").hidden = true; + } + + // To-Do: remove deprecation notice content. + document.getElementById("plugindeprecation-notice").hidden = true; + }, + + show: function(aType, aRequest) { + let showOnlyDisabledUnsigned = false; + if (aType.endsWith("?unsigned=true")) { + aType = aType.replace(/\?.*/, ""); + showOnlyDisabledUnsigned = true; + } + + if (!(aType in AddonManager.addonTypes)) + throw Components.Exception("Attempting to show unknown type " + aType, Cr.NS_ERROR_INVALID_ARG); + + this._type = aType; + this.node.setAttribute("type", aType); + this.showEmptyNotice(false); + + while (this._listBox.itemCount > 0) + this._listBox.removeItemAt(0); + + if (aType == "plugin") { + navigator.plugins.refresh(false); + } + + getAddonsAndInstalls(aType, (aAddonsList, aInstallsList) => { + if (gViewController && aRequest != gViewController.currentViewRequest) + return; + + var elements = []; + + for (let addonItem of aAddonsList) + elements.push(createItem(addonItem)); + + for (let installItem of aInstallsList) + elements.push(createItem(installItem, true)); + + this.showEmptyNotice(elements.length == 0); + if (elements.length > 0) { + sortElements(elements, ["uiState", "name"], true); + for (let element of elements) + this._listBox.appendChild(element); + } + + this.filterDisabledUnsigned(showOnlyDisabledUnsigned); + + gEventManager.registerInstallListener(this); + gViewController.updateCommands(); + gViewController.notifyViewChanged(); + }); + }, + + hide: function() { + gEventManager.unregisterInstallListener(this); + doPendingUninstalls(this._listBox); + }, + + filterDisabledUnsigned: function(aFilter = true) { + let foundDisabledUnsigned = false; + + if (SIGNING_REQUIRED) { + for (let item of this._listBox.childNodes) { + if (!isCorrectlySigned(item.mAddon)) + foundDisabledUnsigned = true; + else + item.hidden = aFilter; + } + } + + document.getElementById("show-disabled-unsigned-extensions").hidden = + aFilter || !foundDisabledUnsigned; + + document.getElementById("show-all-extensions").hidden = !aFilter; + document.getElementById("disabled-unsigned-addons-info").hidden = !aFilter; + }, + + showEmptyNotice: function(aShow) { + this._emptyNotice.hidden = !aShow; + this._listBox.hidden = aShow; + }, + + onSortChanged: function(aSortBy, aAscending) { + sortList(this._listBox, aSortBy, aAscending); + }, + + onExternalInstall: function(aAddon, aExistingAddon, aRequiresRestart) { + // The existing list item will take care of upgrade installs + if (aExistingAddon) + return; + + if (aAddon.hidden) + return; + + this.addItem(aAddon); + }, + + onDownloadStarted: function(aInstall) { + this.addItem(aInstall, true); + }, + + onInstallStarted: function(aInstall) { + this.addItem(aInstall, true); + }, + + onDownloadCancelled: function(aInstall) { + this.removeItem(aInstall, true); + }, + + onInstallCancelled: function(aInstall) { + this.removeItem(aInstall, true); + }, + + onInstallEnded: function(aInstall) { + // Remove any install entries for upgrades, their status will appear against + // the existing item + if (aInstall.existingAddon) + this.removeItem(aInstall, true); + }, + + addItem: function(aObj, aIsInstall) { + if (aObj.type != this._type) + return; + + if (aIsInstall && aObj.existingAddon) + return; + + let prop = aIsInstall ? "mInstall" : "mAddon"; + for (let item of this._listBox.childNodes) { + if (item[prop] == aObj) + return; + } + + let item = createItem(aObj, aIsInstall); + this._listBox.insertBefore(item, this._listBox.firstChild); + this.showEmptyNotice(false); + }, + + removeItem: function(aObj, aIsInstall) { + let prop = aIsInstall ? "mInstall" : "mAddon"; + + for (let item of this._listBox.childNodes) { + if (item[prop] == aObj) { + this._listBox.removeChild(item); + this.showEmptyNotice(this._listBox.itemCount == 0); + return; + } + } + }, + + getSelectedAddon: function() { + var item = this._listBox.selectedItem; + if (item) + return item.mAddon; + return null; + }, + + getListItemForID: function(aId) { + var listitem = this._listBox.firstChild; + while (listitem) { + if (listitem.getAttribute("status") == "installed" && listitem.mAddon.id == aId) + return listitem; + listitem = listitem.nextSibling; + } + return null; + } +}; + + +var gDetailView = { + node: null, + _addon: null, + _loadingTimer: null, + _autoUpdate: null, + + initialize: function() { + this.node = document.getElementById("detail-view"); + + this._autoUpdate = document.getElementById("detail-autoUpdate"); + + this._autoUpdate.addEventListener("command", () => { + this._addon.applyBackgroundUpdates = this._autoUpdate.value; + }, true); + }, + + shutdown: function() { + AddonManager.removeManagerListener(this); + }, + + onUpdateModeChanged: function() { + this.onPropertyChanged(["applyBackgroundUpdates"]); + }, + + _updateView: function(aAddon, aIsRemote, aScrollToPreferences) { + AddonManager.addManagerListener(this); + this.clearLoading(); + + this._addon = aAddon; + gEventManager.registerAddonListener(this, aAddon.id); + gEventManager.registerInstallListener(this); + + this.node.setAttribute("type", aAddon.type); + + // If the search category isn't selected then make sure to select the + // correct category + if (gCategories.selected != "addons://search/") + gCategories.select("addons://list/" + aAddon.type); + + document.getElementById("detail-name").textContent = aAddon.name; + var icon = AddonManager.getPreferredIconURL(aAddon, 64, window); + document.getElementById("detail-icon").src = icon ? icon : ""; + document.getElementById("detail-creator").setCreator(aAddon.creator, aAddon.homepageURL); + + var version = document.getElementById("detail-version"); + if (shouldShowVersionNumber(aAddon)) { + version.hidden = false; + version.value = aAddon.version; + } else { + version.hidden = true; + } + + var screenshotbox = document.getElementById("detail-screenshot-box"); + var screenshot = document.getElementById("detail-screenshot"); + if (aAddon.screenshots && aAddon.screenshots.length > 0) { + if (aAddon.screenshots[0].thumbnailURL) { + screenshot.src = aAddon.screenshots[0].thumbnailURL; + screenshot.width = aAddon.screenshots[0].thumbnailWidth; + screenshot.height = aAddon.screenshots[0].thumbnailHeight; + } else { + screenshot.src = aAddon.screenshots[0].url; + screenshot.width = aAddon.screenshots[0].width; + screenshot.height = aAddon.screenshots[0].height; + } + screenshot.setAttribute("loading", "true"); + screenshotbox.hidden = false; + } else { + screenshotbox.hidden = true; + } + + var desc = document.getElementById("detail-desc"); + desc.textContent = aAddon.description; + + var fullDesc = document.getElementById("detail-fulldesc"); + if (aAddon.fullDescription) { + // The following is part of an awful hack to include the licenses for GMP + // plugins without having bug 624602 fixed yet, and intentionally ignores + // localisation. + if (aAddon.isGMPlugin) { + fullDesc.innerHTML = aAddon.fullDescription; + } else { + fullDesc.textContent = aAddon.fullDescription; + } + + fullDesc.hidden = false; + } else { + fullDesc.hidden = true; + } + + var contributions = document.getElementById("detail-contributions"); + if ("contributionURL" in aAddon && aAddon.contributionURL) { + contributions.hidden = false; + var amount = document.getElementById("detail-contrib-suggested"); + if (aAddon.contributionAmount) { + amount.value = gStrings.ext.formatStringFromName("contributionAmount2", + [aAddon.contributionAmount], + 1); + amount.hidden = false; + } else { + amount.hidden = true; + } + } else { + contributions.hidden = true; + } + + if ("purchaseURL" in aAddon && aAddon.purchaseURL) { + var purchase = document.getElementById("detail-purchase-btn"); + purchase.label = gStrings.ext.formatStringFromName("cmd.purchaseAddon.label", + [aAddon.purchaseDisplayAmount], + 1); + purchase.accesskey = gStrings.ext.GetStringFromName("cmd.purchaseAddon.accesskey"); + } + + var updateDateRow = document.getElementById("detail-dateUpdated"); + if (aAddon.updateDate) { + var date = formatDate(aAddon.updateDate); + updateDateRow.value = date; + } else { + updateDateRow.value = null; + } + + // TODO if the add-on was downloaded from releases.mozilla.org link to the + // AMO profile (bug 590344) + if (false) { + document.getElementById("detail-repository-row").hidden = false; + document.getElementById("detail-homepage-row").hidden = true; + var repository = document.getElementById("detail-repository"); + repository.value = aAddon.homepageURL; + repository.href = aAddon.homepageURL; + } else if (aAddon.homepageURL) { + document.getElementById("detail-repository-row").hidden = true; + document.getElementById("detail-homepage-row").hidden = false; + var homepage = document.getElementById("detail-homepage"); + homepage.value = aAddon.homepageURL; + homepage.href = aAddon.homepageURL; + } else { + document.getElementById("detail-repository-row").hidden = true; + document.getElementById("detail-homepage-row").hidden = true; + } + + var rating = document.getElementById("detail-rating"); + if (aAddon.averageRating) { + rating.averageRating = aAddon.averageRating; + rating.hidden = false; + } else { + rating.hidden = true; + } + + var reviews = document.getElementById("detail-reviews"); + if (aAddon.reviewURL) { + var text = gStrings.ext.GetStringFromName("numReviews"); + text = PluralForm.get(aAddon.reviewCount, text) + text = text.replace("#1", aAddon.reviewCount); + reviews.value = text; + reviews.hidden = false; + reviews.href = aAddon.reviewURL; + } else { + reviews.hidden = true; + } + + document.getElementById("detail-rating-row").hidden = !aAddon.averageRating && !aAddon.reviewURL; + + var sizeRow = document.getElementById("detail-size"); + if (aAddon.size && aIsRemote) { + let [size, unit] = DownloadUtils.convertByteUnits(parseInt(aAddon.size)); + let formatted = gStrings.dl.GetStringFromName("doneSize"); + formatted = formatted.replace("#1", size).replace("#2", unit); + sizeRow.value = formatted; + } else { + sizeRow.value = null; + } + + var downloadsRow = document.getElementById("detail-downloads"); + if (aAddon.totalDownloads && aIsRemote) { + var downloads = aAddon.totalDownloads; + downloadsRow.value = downloads; + } else { + downloadsRow.value = null; + } + + var canUpdate = !aIsRemote && hasPermission(aAddon, "upgrade") && aAddon.id != AddonManager.hotfixID; + document.getElementById("detail-updates-row").hidden = !canUpdate; + + if ("applyBackgroundUpdates" in aAddon) { + this._autoUpdate.hidden = false; + this._autoUpdate.value = aAddon.applyBackgroundUpdates; + let hideFindUpdates = AddonManager.shouldAutoUpdate(this._addon); + document.getElementById("detail-findUpdates-btn").hidden = hideFindUpdates; + } else { + this._autoUpdate.hidden = true; + document.getElementById("detail-findUpdates-btn").hidden = false; + } + + document.getElementById("detail-prefs-btn").hidden = !aIsRemote && + !gViewController.commands.cmd_showItemPreferences.isEnabled(aAddon); + + var gridRows = document.querySelectorAll("#detail-grid rows row"); + let first = true; + for (let gridRow of gridRows) { + if (first && window.getComputedStyle(gridRow, null).getPropertyValue("display") != "none") { + gridRow.setAttribute("first-row", true); + first = false; + } else { + gridRow.removeAttribute("first-row"); + } + } + + this.fillSettingsRows(aScrollToPreferences, (function() { + this.updateState(); + gViewController.notifyViewChanged(); + }).bind(this)); + }, + + show: function(aAddonId, aRequest) { + let index = aAddonId.indexOf("/preferences"); + let scrollToPreferences = false; + if (index >= 0) { + aAddonId = aAddonId.substring(0, index); + scrollToPreferences = true; + } + + this._loadingTimer = setTimeout(() => { + this.node.setAttribute("loading-extended", true); + }, LOADING_MSG_DELAY); + + var view = gViewController.currentViewId; + + AddonManager.getAddonByID(aAddonId, (aAddon) => { + if (gViewController && aRequest != gViewController.currentViewRequest) + return; + + if (aAddon) { + this._updateView(aAddon, false, scrollToPreferences); + return; + } + + // Look for an add-on pending install + AddonManager.getAllInstalls(aInstalls => { + for (let install of aInstalls) { + if (install.state == AddonManager.STATE_INSTALLED && + install.addon.id == aAddonId) { + this._updateView(install.addon, false); + return; + } + } + + if (aAddonId in gCachedAddons) { + this._updateView(gCachedAddons[aAddonId], true); + return; + } + + // This might happen due to session restore restoring us back to an + // add-on that doesn't exist but otherwise shouldn't normally happen. + // Either way just revert to the default view. + gViewController.replaceView(gViewDefault); + }); + }); + }, + + hide: function() { + AddonManager.removeManagerListener(this); + this.clearLoading(); + if (this._addon) { + if (hasInlineOptions(this._addon)) { + Services.obs.notifyObservers(document, + AddonManager.OPTIONS_NOTIFICATION_HIDDEN, + this._addon.id); + } + + gEventManager.unregisterAddonListener(this, this._addon.id); + gEventManager.unregisterInstallListener(this); + this._addon = null; + + // Flush the preferences to disk so they survive any crash + if (this.node.getElementsByTagName("setting").length) + Services.prefs.savePrefFile(null); + } + }, + + updateState: function() { + gViewController.updateCommands(); + + var pending = this._addon.pendingOperations; + if (pending != AddonManager.PENDING_NONE) { + this.node.removeAttribute("notification"); + + pending = null; + const PENDING_OPERATIONS = ["enable", "disable", "install", "uninstall", + "upgrade"]; + for (let op of PENDING_OPERATIONS) { + if (isPending(this._addon, op)) + pending = op; + } + + this.node.setAttribute("pending", pending); + document.getElementById("detail-pending").textContent = gStrings.ext.formatStringFromName( + "details.notification." + pending, + [this._addon.name, gStrings.brandShortName], 2 + ); + } else { + this.node.removeAttribute("pending"); + + if (this._addon.blocklistState == Ci.nsIBlocklistService.STATE_BLOCKED) { + this.node.setAttribute("notification", "error"); + document.getElementById("detail-error").textContent = gStrings.ext.formatStringFromName( + "details.notification.blocked", + [this._addon.name], 1 + ); + var errorLink = document.getElementById("detail-error-link"); + errorLink.value = gStrings.ext.GetStringFromName("details.notification.blocked.link"); + errorLink.href = this._addon.blocklistURL; + errorLink.hidden = false; + } else if (!isCorrectlySigned(this._addon) && SIGNING_REQUIRED) { + this.node.setAttribute("notification", "error"); + document.getElementById("detail-error").textContent = gStrings.ext.formatStringFromName( + "details.notification.unsignedAndDisabled", [this._addon.name, gStrings.brandShortName], 2 + ); + let errorLink = document.getElementById("detail-error-link"); + errorLink.value = gStrings.ext.GetStringFromName("details.notification.unsigned.link"); + errorLink.href = Services.urlFormatter.formatURLPref("app.support.baseURL") + "unsigned-addons"; + errorLink.hidden = false; + } else if (!this._addon.isCompatible && (AddonManager.checkCompatibility || + (this._addon.blocklistState != Ci.nsIBlocklistService.STATE_SOFTBLOCKED))) { + this.node.setAttribute("notification", "warning"); + document.getElementById("detail-warning").textContent = gStrings.ext.formatStringFromName( + "details.notification.incompatible", + [this._addon.name, gStrings.brandShortName, gStrings.appVersion], 3 + ); + document.getElementById("detail-warning-link").hidden = true; + } else if (!isCorrectlySigned(this._addon)) { + this.node.setAttribute("notification", "warning"); + document.getElementById("detail-warning").textContent = gStrings.ext.formatStringFromName( + "details.notification.unsigned", [this._addon.name, gStrings.brandShortName], 2 + ); + var warningLink = document.getElementById("detail-warning-link"); + warningLink.value = gStrings.ext.GetStringFromName("details.notification.unsigned.link"); + warningLink.href = Services.urlFormatter.formatURLPref("app.support.baseURL") + "unsigned-addons"; + warningLink.hidden = false; + } else if (this._addon.blocklistState == Ci.nsIBlocklistService.STATE_SOFTBLOCKED) { + this.node.setAttribute("notification", "warning"); + document.getElementById("detail-warning").textContent = gStrings.ext.formatStringFromName( + "details.notification.softblocked", + [this._addon.name], 1 + ); + let warningLink = document.getElementById("detail-warning-link"); + warningLink.value = gStrings.ext.GetStringFromName("details.notification.softblocked.link"); + warningLink.href = this._addon.blocklistURL; + warningLink.hidden = false; + } else if (this._addon.blocklistState == Ci.nsIBlocklistService.STATE_OUTDATED) { + this.node.setAttribute("notification", "warning"); + document.getElementById("detail-warning").textContent = gStrings.ext.formatStringFromName( + "details.notification.outdated", + [this._addon.name], 1 + ); + let warningLink = document.getElementById("detail-warning-link"); + warningLink.value = gStrings.ext.GetStringFromName("details.notification.outdated.link"); + warningLink.href = this._addon.blocklistURL; + warningLink.hidden = false; + } else if (this._addon.blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_UPDATE_AVAILABLE) { + this.node.setAttribute("notification", "error"); + document.getElementById("detail-error").textContent = gStrings.ext.formatStringFromName( + "details.notification.vulnerableUpdatable", + [this._addon.name], 1 + ); + let errorLink = document.getElementById("detail-error-link"); + errorLink.value = gStrings.ext.GetStringFromName("details.notification.vulnerableUpdatable.link"); + errorLink.href = this._addon.blocklistURL; + errorLink.hidden = false; + } else if (this._addon.blocklistState == Ci.nsIBlocklistService.STATE_VULNERABLE_NO_UPDATE) { + this.node.setAttribute("notification", "error"); + document.getElementById("detail-error").textContent = gStrings.ext.formatStringFromName( + "details.notification.vulnerableNoUpdate", + [this._addon.name], 1 + ); + let errorLink = document.getElementById("detail-error-link"); + errorLink.value = gStrings.ext.GetStringFromName("details.notification.vulnerableNoUpdate.link"); + errorLink.href = this._addon.blocklistURL; + errorLink.hidden = false; + } else if (this._addon.isGMPlugin && !this._addon.isInstalled && + this._addon.isActive) { + this.node.setAttribute("notification", "warning"); + let warning = document.getElementById("detail-warning"); + warning.textContent = + gStrings.ext.formatStringFromName("details.notification.gmpPending", + [this._addon.name], 1); + } else { + this.node.removeAttribute("notification"); + } + } + + let menulist = document.getElementById("detail-state-menulist"); + let addonType = AddonManager.addonTypes[this._addon.type]; + if (addonType.flags & AddonManager.TYPE_SUPPORTS_ASK_TO_ACTIVATE) { + let askItem = document.getElementById("detail-ask-to-activate-menuitem"); + let alwaysItem = document.getElementById("detail-always-activate-menuitem"); + let neverItem = document.getElementById("detail-never-activate-menuitem"); + let hasActivatePermission = + ["ask_to_activate", "enable", "disable"].some(perm => hasPermission(this._addon, perm)); + + if (!this._addon.isActive) { + menulist.selectedItem = neverItem; + } else if (this._addon.userDisabled == AddonManager.STATE_ASK_TO_ACTIVATE) { + menulist.selectedItem = askItem; + } else { + menulist.selectedItem = alwaysItem; + } + + menulist.disabled = !hasActivatePermission; + menulist.hidden = false; + menulist.classList.add('no-auto-hide'); + } else { + menulist.hidden = true; + } + + this.node.setAttribute("active", this._addon.isActive); + }, + + clearLoading: function() { + if (this._loadingTimer) { + clearTimeout(this._loadingTimer); + this._loadingTimer = null; + } + + this.node.removeAttribute("loading-extended"); + }, + + emptySettingsRows: function() { + var lastRow = document.getElementById("detail-downloads"); + var rows = lastRow.parentNode; + while (lastRow.nextSibling) + rows.removeChild(rows.lastChild); + }, + + fillSettingsRows: function(aScrollToPreferences, aCallback) { + this.emptySettingsRows(); + if (!hasInlineOptions(this._addon)) { + if (aCallback) + aCallback(); + return; + } + + // We can't use a promise for this, since some code (especially in tests) + // relies on us finishing before the ViewChanged event bubbles up to its + // listeners, and promises resolve asynchronously. + let whenViewLoaded = callback => { + if (gViewController.displayedView.hasAttribute("loading")) { + gDetailView.node.addEventListener("ViewChanged", function viewChangedEventListener() { + gDetailView.node.removeEventListener("ViewChanged", viewChangedEventListener); + callback(); + }); + } else { + callback(); + } + }; + + let finish = (firstSetting) => { + // Ensure the page has loaded and force the XBL bindings to be synchronously applied, + // then notify observers. + whenViewLoaded(() => { + if (firstSetting) + firstSetting.clientTop; + Services.obs.notifyObservers(document, + AddonManager.OPTIONS_NOTIFICATION_DISPLAYED, + this._addon.id); + if (aScrollToPreferences) + gDetailView.scrollToPreferencesRows(); + }); + } + + // This function removes and returns the text content of aNode without + // removing any child elements. Removing the text nodes ensures any XBL + // bindings apply properly. + function stripTextNodes(aNode) { + var text = ''; + for (var i = 0; i < aNode.childNodes.length; i++) { + if (aNode.childNodes[i].nodeType != document.ELEMENT_NODE) { + text += aNode.childNodes[i].textContent; + aNode.removeChild(aNode.childNodes[i--]); + } else { + text += stripTextNodes(aNode.childNodes[i]); + } + } + return text; + } + + var rows = document.getElementById("detail-downloads").parentNode; + + try { + if (this._addon.optionsType == AddonManager.OPTIONS_TYPE_INLINE_BROWSER) { + whenViewLoaded(() => { + this.createOptionsBrowser(rows).then(browser => { + // Make sure the browser is unloaded as soon as we change views, + // rather than waiting for the next detail view to load. + document.addEventListener("ViewChanged", function viewChangedEventListener() { + document.removeEventListener("ViewChanged", viewChangedEventListener); + browser.remove(); + }); + + finish(browser); + }); + }); + + if (aCallback) + aCallback(); + } else { + var xhr = new XMLHttpRequest(); + xhr.open("GET", this._addon.optionsURL, true); + xhr.responseType = "xml"; + xhr.onload = (function() { + var xml = xhr.responseXML; + var settings = xml.querySelectorAll(":root > setting"); + + var firstSetting = null; + for (var setting of settings) { + + var desc = stripTextNodes(setting).trim(); + if (!setting.hasAttribute("desc")) + setting.setAttribute("desc", desc); + + var type = setting.getAttribute("type"); + if (type == "file" || type == "directory") + setting.setAttribute("fullpath", "true"); + + setting = document.importNode(setting, true); + var style = setting.getAttribute("style"); + if (style) { + setting.removeAttribute("style"); + setting.setAttribute("style", style); + } + + rows.appendChild(setting); + var visible = window.getComputedStyle(setting, null).getPropertyValue("display") != "none"; + if (!firstSetting && visible) { + setting.setAttribute("first-row", true); + firstSetting = setting; + } + } + + finish(firstSetting); + + if (aCallback) + aCallback(); + }).bind(this); + xhr.onerror = function(aEvent) { + Cu.reportError("Error " + aEvent.target.status + + " occurred while receiving " + this._addon.optionsURL); + if (aCallback) + aCallback(); + }; + xhr.send(); + } + } catch (e) { + Cu.reportError(e); + if (aCallback) + aCallback(); + } + }, + + scrollToPreferencesRows: function() { + // We find this row, rather than remembering it from above, + // in case it has been changed by the observers. + let firstRow = gDetailView.node.querySelector('setting[first-row="true"]'); + if (firstRow) { + let top = firstRow.boxObject.y; + top -= parseInt(window.getComputedStyle(firstRow, null).getPropertyValue("margin-top")); + + let detailViewBoxObject = gDetailView.node.boxObject; + top -= detailViewBoxObject.y; + + detailViewBoxObject.scrollTo(0, top); + } + }, + + createOptionsBrowser: function(parentNode) { + let browser = document.createElement("browser"); + browser.setAttribute("type", "content"); + browser.setAttribute("disableglobalhistory", "true"); + browser.setAttribute("class", "inline-options-browser"); + + return new Promise((resolve, reject) => { + let messageListener = { + receiveMessage({name, data}) { + if (name === "Extension:BrowserResized") + browser.style.height = `${data.height}px`; + else if (name === "Extension:BrowserContentLoaded") + resolve(browser); + }, + }; + + let onload = () => { + browser.removeEventListener("load", onload, true); + + let mm = new FakeFrameMessageManager(browser); + mm.loadFrameScript("chrome://extensions/content/ext-browser-content.js", + false); + mm.addMessageListener("Extension:BrowserContentLoaded", messageListener); + mm.addMessageListener("Extension:BrowserResized", messageListener); + mm.sendAsyncMessage("Extension:InitBrowser", {fixedWidth: true}); + + browser.setAttribute("src", this._addon.optionsURL); + }; + browser.addEventListener("load", onload, true); + browser.addEventListener("error", reject); + + parentNode.appendChild(browser); + }); + }, + + getSelectedAddon: function() { + return this._addon; + }, + + onEnabling: function() { + this.updateState(); + }, + + onEnabled: function() { + this.updateState(); + this.fillSettingsRows(); + }, + + onDisabling: function(aNeedsRestart) { + this.updateState(); + if (!aNeedsRestart && hasInlineOptions(this._addon)) { + Services.obs.notifyObservers(document, + AddonManager.OPTIONS_NOTIFICATION_HIDDEN, + this._addon.id); + } + }, + + onDisabled: function() { + this.updateState(); + this.emptySettingsRows(); + }, + + onUninstalling: function() { + this.updateState(); + }, + + onUninstalled: function() { + gViewController.popState(); + }, + + onOperationCancelled: function() { + this.updateState(); + }, + + onPropertyChanged: function(aProperties) { + if (aProperties.indexOf("applyBackgroundUpdates") != -1) { + this._autoUpdate.value = this._addon.applyBackgroundUpdates; + let hideFindUpdates = AddonManager.shouldAutoUpdate(this._addon); + document.getElementById("detail-findUpdates-btn").hidden = hideFindUpdates; + } + + if (aProperties.indexOf("appDisabled") != -1 || + aProperties.indexOf("signedState") != -1 || + aProperties.indexOf("userDisabled") != -1) + this.updateState(); + }, + + onExternalInstall: function(aAddon, aExistingAddon, aNeedsRestart) { + // Only care about upgrades for the currently displayed add-on + if (!aExistingAddon || aExistingAddon.id != this._addon.id) + return; + + if (!aNeedsRestart) + this._updateView(aAddon, false); + else + this.updateState(); + }, + + onInstallCancelled: function(aInstall) { + if (aInstall.addon.id == this._addon.id) + gViewController.popState(); + } +}; + + +var gUpdatesView = { + node: null, + _listBox: null, + _emptyNotice: null, + _sorters: null, + _updateSelected: null, + _categoryItem: null, + + initialize: function() { + this.node = document.getElementById("updates-view"); + this._listBox = document.getElementById("updates-list"); + this._emptyNotice = document.getElementById("updates-list-empty"); + this._sorters = document.getElementById("updates-sorters"); + this._sorters.handler = this; + + this._categoryItem = gCategories.get("addons://updates/available"); + + this._updateSelected = document.getElementById("update-selected-btn"); + this._updateSelected.addEventListener("command", function() { + gUpdatesView.installSelected(); + }, false); + + this.updateAvailableCount(true); + + AddonManager.addAddonListener(this); + AddonManager.addInstallListener(this); + }, + + shutdown: function() { + AddonManager.removeAddonListener(this); + AddonManager.removeInstallListener(this); + }, + + show: function(aType, aRequest) { + document.getElementById("empty-availableUpdates-msg").hidden = aType != "available"; + document.getElementById("empty-recentUpdates-msg").hidden = aType != "recent"; + this.showEmptyNotice(false); + + while (this._listBox.itemCount > 0) + this._listBox.removeItemAt(0); + + this.node.setAttribute("updatetype", aType); + if (aType == "recent") + this._showRecentUpdates(aRequest); + else + this._showAvailableUpdates(false, aRequest); + }, + + hide: function() { + this._updateSelected.hidden = true; + this._categoryItem.disabled = this._categoryItem.badgeCount == 0; + doPendingUninstalls(this._listBox); + }, + + _showRecentUpdates: function(aRequest) { + AddonManager.getAllAddons((aAddonsList) => { + if (gViewController && aRequest != gViewController.currentViewRequest) + return; + + var elements = []; + let threshold = Date.now() - UPDATES_RECENT_TIMESPAN; + for (let addon of aAddonsList) { + if (addon.hidden || !addon.updateDate || addon.updateDate.getTime() < threshold) + continue; + + elements.push(createItem(addon)); + } + + this.showEmptyNotice(elements.length == 0); + if (elements.length > 0) { + sortElements(elements, [this._sorters.sortBy], this._sorters.ascending); + for (let element of elements) + this._listBox.appendChild(element); + } + + gViewController.notifyViewChanged(); + }); + }, + + _showAvailableUpdates: function(aIsRefresh, aRequest) { + /* Disable the Update Selected button so it can't get clicked + before everything is initialized asynchronously. + It will get re-enabled by maybeDisableUpdateSelected(). */ + this._updateSelected.disabled = true; + + AddonManager.getAllInstalls((aInstallsList) => { + if (!aIsRefresh && gViewController && aRequest && + aRequest != gViewController.currentViewRequest) + return; + + if (aIsRefresh) { + this.showEmptyNotice(false); + this._updateSelected.hidden = true; + + while (this._listBox.childNodes.length > 0) + this._listBox.removeChild(this._listBox.firstChild); + } + + var elements = []; + + for (let install of aInstallsList) { + if (!this.isManualUpdate(install)) + continue; + + let item = createItem(install.existingAddon); + item.setAttribute("upgrade", true); + item.addEventListener("IncludeUpdateChanged", () => { + this.maybeDisableUpdateSelected(); + }, false); + elements.push(item); + } + + this.showEmptyNotice(elements.length == 0); + if (elements.length > 0) { + this._updateSelected.hidden = false; + sortElements(elements, [this._sorters.sortBy], this._sorters.ascending); + for (let element of elements) + this._listBox.appendChild(element); + } + + // ensure badge count is in sync + this._categoryItem.badgeCount = this._listBox.itemCount; + + gViewController.notifyViewChanged(); + }); + }, + + showEmptyNotice: function(aShow) { + this._emptyNotice.hidden = !aShow; + this._listBox.hidden = aShow; + }, + + isManualUpdate: function(aInstall, aOnlyAvailable) { + var isManual = aInstall.existingAddon && + !AddonManager.shouldAutoUpdate(aInstall.existingAddon); + if (isManual && aOnlyAvailable) + return isInState(aInstall, "available"); + return isManual; + }, + + maybeRefresh: function() { + if (gViewController.currentViewId == "addons://updates/available") + this._showAvailableUpdates(true); + this.updateAvailableCount(); + }, + + updateAvailableCount: function(aInitializing) { + if (aInitializing) + gPendingInitializations++; + AddonManager.getAllInstalls((aInstallsList) => { + var count = aInstallsList.filter(aInstall => { + return this.isManualUpdate(aInstall, true); + }).length; + this._categoryItem.disabled = gViewController.currentViewId != "addons://updates/available" && + count == 0; + this._categoryItem.badgeCount = count; + if (aInitializing) + notifyInitialized(); + }); + }, + + maybeDisableUpdateSelected: function() { + for (let item of this._listBox.childNodes) { + if (item.includeUpdate) { + this._updateSelected.disabled = false; + return; + } + } + this._updateSelected.disabled = true; + }, + + installSelected: function() { + for (let item of this._listBox.childNodes) { + if (item.includeUpdate) + item.upgrade(); + } + + this._updateSelected.disabled = true; + }, + + getSelectedAddon: function() { + var item = this._listBox.selectedItem; + if (item) + return item.mAddon; + return null; + }, + + getListItemForID: function(aId) { + var listitem = this._listBox.firstChild; + while (listitem) { + if (listitem.mAddon.id == aId) + return listitem; + listitem = listitem.nextSibling; + } + return null; + }, + + onSortChanged: function(aSortBy, aAscending) { + sortList(this._listBox, aSortBy, aAscending); + }, + + onNewInstall: function(aInstall) { + if (!this.isManualUpdate(aInstall)) + return; + this.maybeRefresh(); + }, + + onInstallStarted: function(aInstall) { + this.updateAvailableCount(); + }, + + onInstallCancelled: function(aInstall) { + if (!this.isManualUpdate(aInstall)) + return; + this.maybeRefresh(); + }, + + onPropertyChanged: function(aAddon, aProperties) { + if (aProperties.indexOf("applyBackgroundUpdates") != -1) + this.updateAvailableCount(); + } +}; + +var gDragDrop = { + onDragOver: function(aEvent) { + var types = aEvent.dataTransfer.types; + if (types.includes("text/uri-list") || + types.includes("text/x-moz-url") || + types.includes("application/x-moz-file")) + aEvent.preventDefault(); + }, + + onDrop: function(aEvent) { + var dataTransfer = aEvent.dataTransfer; + var urls = []; + + // Convert every dropped item into a url + for (var i = 0; i < dataTransfer.mozItemCount; i++) { + var url = dataTransfer.mozGetDataAt("text/uri-list", i); + if (url) { + urls.push(url); + continue; + } + + url = dataTransfer.mozGetDataAt("text/x-moz-url", i); + if (url) { + urls.push(url.split("\n")[0]); + continue; + } + + var file = dataTransfer.mozGetDataAt("application/x-moz-file", i); + if (file) { + urls.push(Services.io.newFileURI(file).spec); + continue; + } + } + + var pos = 0; + var installs = []; + + function buildNextInstall() { + if (pos == urls.length) { + if (installs.length > 0) { + // Display the normal install confirmation for the installs + let webInstaller = Cc["@mozilla.org/addons/web-install-listener;1"]. + getService(Ci.amIWebInstallListener); + webInstaller.onWebInstallRequested(getBrowserElement(), + document.documentURIObject, + installs); + } + return; + } + + AddonManager.getInstallForURL(urls[pos++], function(aInstall) { + installs.push(aInstall); + buildNextInstall(); + }, "application/x-xpinstall"); + } + + buildNextInstall(); + + aEvent.preventDefault(); + } +}; diff --git a/toolkit/mozapps/webextensions/content/extensions.xml b/toolkit/mozapps/webextensions/content/extensions.xml new file mode 100644 index 000000000..b49645cf0 --- /dev/null +++ b/toolkit/mozapps/webextensions/content/extensions.xml @@ -0,0 +1,2008 @@ + + + + + +%extensionsDTD; +]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + i); + ]]> + + + + + + + + + + + + this._updateStars(); + + + + + + + + + + + + + + + + + + + + + + + + + + + document.getAnonymousElementByAttribute(this, "anonid", "progress"); + + + document.getAnonymousElementByAttribute(this, "anonid", "cancel-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", "status"); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + null + + document.getAnonymousElementByAttribute(this, "anonid", "name-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", "date-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", "price-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", "relevance-btn"); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + = 0); + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + document.getAnonymousElementByAttribute(this, "anonid", "label"); + + + document.getAnonymousElementByAttribute(this, "anonid", "creator-link"); + + + document.getAnonymousElementByAttribute(this, "anonid", "creator-name"); + + + + + + + + + + + + + + + + + + + + + + + + + document.getAnonymousElementByAttribute(this, "anonid", "message"); + + + document.getAnonymousElementByAttribute(this, "anonid", "progress"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "purchase-remote-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "install-remote-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "restart-needed"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "undo-btn"); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + document.getAnonymousElementByAttribute(this, "anonid", + "warning-container"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "warning"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "warning-link"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "warning-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "error-container"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "error"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "error-link"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "pending-container"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "pending"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "info-container"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "info"); + + + document.getAnonymousElementByAttribute(this, "anonid", "experiment-state"); + + + document.getAnonymousElementByAttribute(this, "anonid", "experiment-time"); + + + document.getAnonymousElementByAttribute(this, "anonid", "icon"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "date-updated"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "description"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "state-menulist"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "ask-to-activate-menuitem"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "always-activate-menuitem"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "never-activate-menuitem"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "preferences-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "enable-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "disable-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "remove-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "update-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "control-container"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "install-status"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "checking-update"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "update-available"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "include-update"); + + false + + document.getAnonymousElementByAttribute(this, "anonid", + "relnotes-toggle-btn"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "relnotes-loading"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "relnotes-error"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "relnotes-container"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "relnotes"); + + + + + + + + + + + + + + + { + // This can return after the binding has been destroyed, + // so try to detect that and return early + if (!("onNewInstall" in this)) + return; + for (let install of aInstallsList) { + if (install.existingAddon && + install.existingAddon.id == this.mAddon.id && + install.state == AddonManager.STATE_AVAILABLE) { + this.onNewInstall(install); + this.onIncludeUpdateChanged(); + } + } + }); + } + ]]> + + + + + + + + + + + + + this.hasPermission(perm)); + this._stateMenulist.disabled = !hasActivatePermission; + this._stateMenulist.hidden = false; + this._stateMenulist.classList.add('no-auto-hide'); + } else { + this._stateMenulist.hidden = true; + + let enableTooltip = gViewController.commands["cmd_enableItem"] + .getTooltip(this.mAddon); + this._enableBtn.setAttribute("tooltiptext", enableTooltip); + if (this.hasPermission("enable")) { + this._enableBtn.hidden = false; + } else { + this._enableBtn.hidden = true; + } + + let disableTooltip = gViewController.commands["cmd_disableItem"] + .getTooltip(this.mAddon); + this._disableBtn.setAttribute("tooltiptext", disableTooltip); + if (this.hasPermission("disable")) { + this._disableBtn.hidden = false; + } else { + this._disableBtn.hidden = true; + } + } + + let uninstallTooltip = gViewController.commands["cmd_uninstallItem"] + .getTooltip(this.mAddon); + this._removeBtn.setAttribute("tooltiptext", uninstallTooltip); + if (this.hasPermission("uninstall")) { + this._removeBtn.hidden = false; + } else { + this._removeBtn.hidden = true; + } + + this.setAttribute("active", this.mAddon.isActive); + + var showProgress = this.mAddon.purchaseURL || (this.mAddon.install && + this.mAddon.install.state != AddonManager.STATE_INSTALLED); + this._showStatus(showProgress ? "progress" : "none"); + + if (this.mAddon.type == "experiment") { + this.removeAttribute("notification"); + let prefix = "experiment."; + let active = this.mAddon.isActive; + + if (!showProgress) { + let stateKey = prefix + "state." + (active ? "active" : "complete"); + this._experimentState.value = gStrings.ext.GetStringFromName(stateKey); + + let now = Date.now(); + let end = this.endDate; + let days = Math.abs(end - now) / (24 * 60 * 60 * 1000); + + let timeKey = prefix + "time."; + let timeMessage; + + if (days < 1) { + timeKey += (active ? "endsToday" : "endedToday"); + timeMessage = gStrings.ext.GetStringFromName(timeKey); + } else { + timeKey += (active ? "daysRemaining" : "daysPassed"); + days = Math.round(days); + let timeString = gStrings.ext.GetStringFromName(timeKey); + timeMessage = PluralForm.get(days, timeString) + .replace("#1", days); + } + + this._experimentTime.value = timeMessage; + } + } + ]]> + + + + + { + var event = document.createEvent("Events"); + event.initEvent("RelNotesToggle", true, true); + this.dispatchEvent(event); + } + + let showRelNotes = () => { + if (!relNotesData || !transformData) + return; + + this._relNotesLoading.hidden = true; + + var processor = Components.classes["@mozilla.org/document-transformer;1?type=xslt"] + .createInstance(Components.interfaces.nsIXSLTProcessor); + processor.flags |= Components.interfaces.nsIXSLTProcessorPrivate.DISABLE_ALL_LOADS; + + processor.importStylesheet(transformData); + var fragment = processor.transformToFragment(relNotesData, document); + this._relNotes.appendChild(fragment); + if (this.hasAttribute("show-relnotes")) { + var container = this._relNotesContainer; + container.style.height = container.scrollHeight + "px"; + } + sendToggleEvent(); + } + + let handleError = () => { + dataReq.abort(); + styleReq.abort(); + this._relNotesLoading.hidden = true; + this._relNotesError.hidden = false; + this._relNotesLoaded = false; // allow loading to be re-tried + sendToggleEvent(); + } + + function handleResponse(aEvent) { + var req = aEvent.target; + var ct = req.getResponseHeader("content-type"); + if ((!ct || ct.indexOf("text/html") < 0) && + req.responseXML && + req.responseXML.documentElement.namespaceURI != XMLURI_PARSE_ERROR) { + if (req == dataReq) + relNotesData = req.responseXML; + else + transformData = req.responseXML; + showRelNotes(); + } else { + handleError(); + } + } + + var dataReq = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] + .createInstance(Components.interfaces.nsIXMLHttpRequest); + dataReq.open("GET", aURI.spec, true); + dataReq.responseType = "document"; + dataReq.addEventListener("load", handleResponse, false); + dataReq.addEventListener("error", handleError, false); + dataReq.send(null); + + var styleReq = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"] + .createInstance(Components.interfaces.nsIXMLHttpRequest); + styleReq.open("GET", UPDATES_RELEASENOTES_TRANSFORMFILE, true); + styleReq.responseType = "document"; + styleReq.addEventListener("load", handleResponse, false); + styleReq.addEventListener("error", handleError, false); + styleReq.send(null); + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + document.getAnonymousElementByAttribute(this, "anonid", "notice"); + + + document.getAnonymousElementByAttribute(this, "anonid", "restart-btn"); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + document.getAnonymousElementByAttribute(this, "anonid", "icon"); + + + document.getAnonymousElementByAttribute(this, "anonid", "name"); + + + document.getAnonymousElementByAttribute(this, "anonid", "warning"); + + + document.getAnonymousElementByAttribute(this, "anonid", "warning-link"); + + + document.getAnonymousElementByAttribute(this, "anonid", + "install-status"); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/toolkit/mozapps/webextensions/content/extensions.xul b/toolkit/mozapps/webextensions/content/extensions.xul new file mode 100644 index 000000000..70939d024 --- /dev/null +++ b/toolkit/mozapps/webextensions/content/extensions.xul @@ -0,0 +1,715 @@ + + + + + + + + +%brandDTD; + +%extensionsDTD; +]> + + + + + +