Truly independent web browser
LibWebView+LibWeb: Persist site exceptions for content blocking
Timothy Flynn9265ea090248
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 12c765584f9..9408213df04 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -972,9 +972,14 @@ void Document::visit_edges(Cell::Visitor& visitor)visitor.visit(m_ancestor_origins_list);}+bool Document::content_blocking_enabled() const+{+ return page().content_blocking_enabled_for_url(relevant_settings_object().top_level_creation_url);+}+Utf16String const& Document::content_blocker_style_sheet(){- if (is_decoded_svg() || !page().content_blocking_enabled()) {+ if (is_decoded_svg() || !content_blocking_enabled()) {if (!m_content_blocker_style_sheet.has_value())m_content_blocker_style_sheet = Utf16String {};return m_content_blocker_style_sheet.value();@@ -1019,7 +1024,7 @@ void Document::invalidate_content_blocker_style_sheet()bool Document::content_blocker_style_sheet_may_need_refresh_for_class_or_id(Utf16FlyString const* id, ReadonlySpan<Utf16FlyString> class_names){- if (is_decoded_svg() || !page().content_blocking_enabled())+ if (is_decoded_svg() || !content_blocking_enabled())return false;if (!m_content_blocker_style_sheet.has_value())diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex de9a483a2bc..b1d20680fdf 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -1591,6 +1591,8 @@ public:CSS::StyleScope const& style_scope() const { return m_style_scope; }CSS::StyleScope& style_scope() { return m_style_scope; }++ bool content_blocking_enabled() const;Utf16String const& content_blocker_style_sheet();void invalidate_content_blocker_style_sheet();bool content_blocker_style_sheet_may_need_refresh_for_class_or_id(Utf16FlyString const* id, ReadonlySpan<Utf16FlyString> class_names);diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex e57c74e41af..2f2c4458ee5 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -283,7 +283,7 @@ static void invalidate_content_blocker_style_if_needed(Element& element){if (!element.is_connected())return;- if (!element.document().page().content_blocking_enabled() || !ContentBlocker::the().has_cosmetic_rules())+ if (!element.document().content_blocking_enabled() || !ContentBlocker::the().has_cosmetic_rules())return;auto const& id = element.id();diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cppindex e25a0fd3e37..da067c430b7 100644--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp@@ -2314,6 +2314,11 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(load_request.set_source_url(content_blocker_source_url_for_request(*request));load_request.set_network_isolation_key(Infrastructure::determine_the_network_partition_key(*request));+ if (auto environment = request->reserved_client())+ load_request.set_top_level_creation_url(environment->top_level_creation_url);+ else if (auto client = request->client())+ load_request.set_top_level_creation_url(client->top_level_creation_url);+if (auto const* body = request->body().get_pointer<GC::Ref<Infrastructure::Body>>()) {(*body)->source().visit([&](ByteBuffer const& byte_buffer) {diff --git a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp b/Libraries/LibWeb/HTML/HTMLLinkElement.cppindex 3a009234374..a6a4228a863 100644--- a/Libraries/LibWeb/HTML/HTMLLinkElement.cpp+++ b/Libraries/LibWeb/HTML/HTMLLinkElement.cpp@@ -565,7 +565,7 @@ void HTMLLinkElement::fetch_and_process_linked_dns_prefetch_resource()// FIXME: This should go through Fetch: https://fetch.spec.whatwg.org/#resolve-an-originif (!ResourceLoader::is_initialized())return;- ResourceLoader::the().prefetch_dns(document().page(), url.value(), document().fallback_base_url());+ ResourceLoader::the().prefetch_dns(document(), url.value(), document().fallback_base_url());}// https://html.spec.whatwg.org/multipage/links.html#link-type-preconnect:fetch-and-process-the-linked-resource-2@@ -822,9 +822,8 @@ void HTMLLinkElement::preconnect(LinkProcessingOptions const& options)if (!ResourceLoader::is_initialized())return;- GC::Ptr<Page> page = options.document ? &options.document->page() : nullptr;auto source_url = options.document ? options.document->fallback_base_url() : options.environment->api_base_url();- ResourceLoader::the().preconnect(page, *url, source_url);+ ResourceLoader::the().preconnect(options.document, *url, source_url);}// https://html.spec.whatwg.org/multipage/links.html#match-preload-typediff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 6a5cc15899f..3268fe8d08b 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -1149,7 +1149,7 @@ WebIDL::ExceptionOr<void> Internals::set_site_compatibility_data(Utf16String convoid Internals::set_content_blocking_enabled(bool enabled){- page().set_content_blocking_enabled(enabled);+ page().set_content_blocking_policy(enabled, {});}WebIDL::UnsignedLongLong Internals::partial_layout_count()diff --git a/Libraries/LibWeb/Loader/LoadRequest.h b/Libraries/LibWeb/Loader/LoadRequest.hindex 1c6c1f0cf58..3043b07cf94 100644--- a/Libraries/LibWeb/Loader/LoadRequest.h+++ b/Libraries/LibWeb/Loader/LoadRequest.h@@ -68,6 +68,9 @@ public:Optional<URL::URL> const& source_url() const { return m_source_url; }void set_source_url(URL::URL source_url) { m_source_url = move(source_url); }+ Optional<URL::URL> const& top_level_creation_url() const { return m_top_level_creation_url; }+ void set_top_level_creation_url(Optional<URL::URL> url) { m_top_level_creation_url = move(url); }+void start_timer() { m_load_timer.start(); }AK::Duration load_time() const { return m_load_timer.elapsed_time(); }@@ -92,6 +95,7 @@ private:bool m_is_navigation_request { false };Fetch::Infrastructure::Request::Priority m_priority { Fetch::Infrastructure::Request::Priority::Auto };Optional<URL::URL> m_source_url;+ Optional<URL::URL> m_top_level_creation_url;Optional<HTTP::NetworkIsolationKey> m_network_isolation_key;};diff --git a/Libraries/LibWeb/Loader/ResourceLoader.cpp b/Libraries/LibWeb/Loader/ResourceLoader.cppindex dfda48a5683..3fd428bc776 100644--- a/Libraries/LibWeb/Loader/ResourceLoader.cpp+++ b/Libraries/LibWeb/Loader/ResourceLoader.cpp@@ -16,6 +16,7 @@#include <LibRequests/Request.h>#include <LibRequests/RequestClient.h>#include <LibURL/Parser.h>+#include <LibWeb/DOM/Document.h>#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>#include <LibWeb/Fetch/Infrastructure/URL.h>#include <LibWeb/Loader/ContentBlocker.h>@@ -73,12 +74,12 @@ void ResourceLoader::set_client(NonnullRefPtr<Requests::RequestClient> request_c};}-void ResourceLoader::prefetch_dns(GC::Ptr<Page> page, URL::URL const& url, URL::URL const& source_url)+void ResourceLoader::prefetch_dns(GC::Ptr<DOM::Document> document, URL::URL const& url, URL::URL const& source_url){if (url.scheme().is_one_of("file"sv, "data"sv))return;- if (!page || page->content_blocking_enabled()) {+ if (!document || document->content_blocking_enabled()) {if (ContentBlocker::the().is_filtered(url, source_url, ContentBlocker::ResourceType::Other)) {dbgln("ResourceLoader: Refusing to prefetch DNS for '{}': \033[31;1mURL was filtered\033[0m", url);return;@@ -90,12 +91,12 @@ void ResourceLoader::prefetch_dns(GC::Ptr<Page> page, URL::URL const& url, URL::m_request_client->ensure_connection(url, RequestServer::CacheLevel::ResolveOnly);}-void ResourceLoader::preconnect(GC::Ptr<Page> page, URL::URL const& url, URL::URL const& source_url)+void ResourceLoader::preconnect(GC::Ptr<DOM::Document> document, URL::URL const& url, URL::URL const& source_url){if (url.scheme().is_one_of("file"sv, "data"sv))return;- if (!page || page->content_blocking_enabled()) {+ if (!document || document->content_blocking_enabled()) {if (ContentBlocker::the().is_filtered(url, source_url, ContentBlocker::ResourceType::Other)) {dbgln("ResourceLoader: Refusing to pre-connect to '{}': \033[31;1mURL was filtered\033[0m", url);return;@@ -190,7 +191,7 @@ static bool should_block_request(LoadRequest const& request)return true;}- if (auto page = request.page(); !page || page->content_blocking_enabled()) {+ if (auto page = request.page(); !page || page->content_blocking_enabled_for_url(request.top_level_creation_url())) {auto source_url = request.source_url().value_or(url);if (ContentBlocker::the().is_filtered(url, source_url, request.destination(), request.initiator_type(), request.request_mode())) {log_filtered_request(request);diff --git a/Libraries/LibWeb/Loader/ResourceLoader.h b/Libraries/LibWeb/Loader/ResourceLoader.hindex 1832df8da64..45204fec13d 100644--- a/Libraries/LibWeb/Loader/ResourceLoader.h+++ b/Libraries/LibWeb/Loader/ResourceLoader.h@@ -44,8 +44,8 @@ public:RefPtr<Requests::RequestClient>& request_client() { return m_request_client; }- void prefetch_dns(GC::Ptr<Page>, URL::URL const&, URL::URL const& source_url);- void preconnect(GC::Ptr<Page>, URL::URL const&, URL::URL const& source_url);+ void prefetch_dns(GC::Ptr<DOM::Document>, URL::URL const&, URL::URL const& source_url);+ void preconnect(GC::Ptr<DOM::Document>, URL::URL const&, URL::URL const& source_url);static bool is_known_hsts_host(Page&, String const& host);diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cppindex cf94eb0baaf..25e4e1175da 100644--- a/Libraries/LibWeb/Page/Page.cpp+++ b/Libraries/LibWeb/Page/Page.cpp@@ -48,6 +48,7 @@#include <LibWebCommon/Clipboard/SystemClipboard.h>#include <LibWebCommon/HTML/NavigationPopulationRequest.h>#include <LibWebCommon/HTML/SelectedFile.h>+#include <LibWebCommon/Loader/ContentBlocking.h>namespace Web {@@ -1750,14 +1751,30 @@ void Page::invalidate_style_for_preference_change()}}-void Page::set_content_blocking_enabled(bool enabled)+bool Page::content_blocking_enabled_for_url(Optional<URL::URL> const& url) const{- if (m_content_blocking_enabled == enabled)- return;- m_content_blocking_enabled = enabled;+ if (!m_content_blocking_enabled)+ return false;+ if (!url.has_value())+ return true;- if (ContentBlocker::the().has_cosmetic_rules())- invalidate_user_style();+ auto host = content_blocking_site(*url);+ return !host.has_value() || !m_content_blocking_disabled_sites.contains(*host);+}++void Page::set_content_blocking_policy(bool enabled, ReadonlySpan<String> disabled_sites)+{+ HashTable<String> sites;+ sites.ensure_capacity(disabled_sites.size());++ for (auto const& site : disabled_sites) {+ if (auto host = canonical_content_blocking_host(site); host.has_value())+ sites.set(host.release_value());+ }++ m_content_blocking_enabled = enabled;+ m_content_blocking_disabled_sites = move(sites);+ invalidate_user_style();}Vector<GC::Root<DOM::Document>> Page::documents_in_active_window() constdiff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex 3201dc248c2..a33bb25daa7 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -396,8 +396,8 @@ public:void invalidate_user_style();void invalidate_style_for_preference_change();- bool content_blocking_enabled() const { return m_content_blocking_enabled; }- void set_content_blocking_enabled(bool);+ bool content_blocking_enabled_for_url(Optional<URL::URL> const&) const;+ void set_content_blocking_policy(bool enabled, ReadonlySpan<String> disabled_sites);bool pdf_viewer_supported() const { return m_pdf_viewer_supported; }@@ -567,6 +567,7 @@ private:Optional<Utf16String> m_user_style_sheet_source;bool m_content_blocking_enabled { true };+ HashTable<String> m_content_blocking_disabled_sites;// https://html.spec.whatwg.org/multipage/system-state.html#pdf-viewer-supported// Each user agent has a PDF viewer supported boolean, whose value is implementation-defined (and might varydiff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txtindex 984e33c882d..878e15d9db9 100644--- a/Libraries/LibWebCommon/CMakeLists.txt+++ b/Libraries/LibWebCommon/CMakeLists.txt@@ -40,6 +40,7 @@ set(SOURCESHTML/WebViewHints.cppHTML/WorkerAgentTypes.cppInfra/Strings.cpp+ Loader/ContentBlocking.cppLoader/DownloadFilename.cppLoader/SiteCompatibility.cppMimeSniff/MimeType.cppdiff --git a/Libraries/LibWebCommon/Loader/ContentBlocking.cpp b/Libraries/LibWebCommon/Loader/ContentBlocking.cppnew file mode 100644index 00000000000..c3aaaebeee7--- /dev/null+++ b/Libraries/LibWebCommon/Loader/ContentBlocking.cpp@@ -0,0 +1,46 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/CharacterTypes.h>+#include <LibURL/Parser.h>+#include <LibWebCommon/Loader/ContentBlocking.h>++namespace Web {++Optional<String> content_blocking_site(URL::URL const& url)+{+ if (!url.scheme().is_one_of("http"sv, "https"sv) || !url.host().has_value())+ return {};++ auto host = url.serialized_host();+ if (host.ends_with('.'))+ host = host.substring_view(0, host.length() - 1);+ if (host.is_empty())+ return {};++ return host.to_ascii_lowercase_string();+}++Optional<String> canonical_content_blocking_host(StringView host)+{+ if (host.is_empty())+ return {};+ if (host.contains(':') && !(host.starts_with('[') && host.ends_with(']')))+ return {};++ for (auto character : host) {+ if (is_ascii_control(character) || " /\\?#@*%"sv.contains(character))+ return {};+ }++ auto url = URL::Parser::basic_parse(MUST(String::formatted("http://{}/", host)));+ if (!url.has_value() || url->port().has_value() || !url->username().is_empty() || !url->password().is_empty())+ return {};++ return content_blocking_site(*url);+}++}diff --git a/Libraries/LibWebCommon/Loader/ContentBlocking.h b/Libraries/LibWebCommon/Loader/ContentBlocking.hnew file mode 100644index 00000000000..7c044a63b54--- /dev/null+++ b/Libraries/LibWebCommon/Loader/ContentBlocking.h@@ -0,0 +1,19 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Optional.h>+#include <AK/String.h>+#include <LibURL/URL.h>+#include <LibWebCommon/Export.h>++namespace Web {++WEBCOMMON_API Optional<String> content_blocking_site(URL::URL const&);+WEBCOMMON_API Optional<String> canonical_content_blocking_host(StringView);++}diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cppindex fbd8f327735..e0a3223a90b 100644--- a/Libraries/LibWebView/Application.cpp+++ b/Libraries/LibWebView/Application.cpp@@ -742,14 +742,16 @@ void Application::rebuild_content_blocker_list_paths()}}-ErrorOr<void> Application::load_content_blocker_lists()+ErrorOr<bool> Application::load_content_blocker_lists(){StringView custom_filters;if (m_web_content_options.is_test_mode == IsTestMode::No)custom_filters = m_settings->custom_content_blocker_filters();if (m_browser_options.content_blocker_list_paths.is_empty() && custom_filters.is_empty()) {+ if (m_content_blocker_list_buffer.has_value() && m_content_blocker_list_buffer->size() == 0)+ return false;m_content_blocker_list_buffer = TRY(Core::AnonymousBuffer::create_with_size(0));- return {};+ return true;}Checked<size_t> total_size = 0;@@ -780,9 +782,11 @@ ErrorOr<void> Application::load_content_blocker_lists()bytes[offset++] = '\n';VERIFY(offset == bytes.size());- m_content_blocker_list_buffer = move(blocker_list_buffer);+ if (m_content_blocker_list_buffer.has_value() && m_content_blocker_list_buffer->bytes() == blocker_list_buffer.bytes())+ return false;- return {};+ m_content_blocker_list_buffer = move(blocker_list_buffer);+ return true;}void Application::start_content_blocker_list_update(ContentBlockerListUpdateTrigger trigger, Optional<StringView> requested_identifier)@@ -1100,6 +1104,9 @@ ErrorOr<NonnullRefPtr<WebContentClient>> Application::create_web_content_client(client->async_connect_to_wasm_compiler(wasm_compiler_handle);#endif+ if (m_content_blocker_list_buffer.has_value())+ client->async_set_content_blockers(*m_content_blocker_list_buffer);+m_web_content_clients.set(client);return client;}@@ -2715,12 +2722,7 @@ void Application::apply_view_options(Badge<ViewImplementation>, ViewImplementatiview.set_preferred_contrast(m_contrast);view.set_preferred_motion(m_motion);- // Test mode supplies its own filter lists independently of profile preferences.- auto content_blocking_enabled = m_browser_options.enable_content_blocker == EnableContentBlocker::Yes- && (m_web_content_options.is_test_mode == IsTestMode::Yes || m_settings->content_blocker_enabled());- page.async_set_content_blocking_enabled(content_blocking_enabled);- if (m_content_blocker_list_buffer.has_value())- page.client().async_set_content_blockers(*m_content_blocker_list_buffer);+ apply_content_blocking_policy(page);page.async_debug_request("set-line-box-borders"sv, m_show_line_box_borders_action->checked() ? "on"sv : "off"sv);page.async_debug_request("set-caret-hit-test-debug-overlay"sv, m_show_caret_hit_test_debug_overlay_action->checked() ? "on"sv : "off"sv);@@ -2762,6 +2764,24 @@ void Application::background_networking_settings_changed(Badge<ApplicationSettinstart_content_blocker_list_update(ContentBlockerListUpdateTrigger::Automatic);}+bool Application::content_blocking_enabled() const+{+ // Test mode supplies its own filter lists independently of profile preferences.+ return m_browser_options.enable_content_blocker == EnableContentBlocker::Yes+ && (m_web_content_options.is_test_mode == IsTestMode::Yes || m_settings->content_blocker_enabled());+}++bool Application::has_content_blocking_rules() const+{+ return m_content_blocker_list_buffer.has_value() && m_content_blocker_list_buffer->size() > 0;+}++void Application::apply_content_blocking_policy(WebContentPage& page)+{+ auto disabled_sites = m_web_content_options.is_test_mode == IsTestMode::Yes ? Vector<String> {} : m_settings->content_blocker_disabled_sites().values();+ page.async_set_content_blocking_policy(content_blocking_enabled(), disabled_sites);+}+void Application::content_blocker_settings_changed(Badge<ApplicationSettingsObserver>){apply_content_blocker_settings();@@ -2769,24 +2789,24 @@ void Application::content_blocker_settings_changed(Badge<ApplicationSettingsObsevoid Application::apply_content_blocker_settings(){- bool lists_loaded = false;+ bool rules_changed = false;if (m_web_content_options.is_test_mode == IsTestMode::No) {rebuild_content_blocker_list_paths();if (auto result = load_content_blocker_lists(); result.is_error())warnln("Unable to apply content blocker settings: {}", result.error());else- lists_loaded = true;+ rules_changed = result.release_value();}- auto enabled = m_browser_options.enable_content_blocker == EnableContentBlocker::Yes- && (m_web_content_options.is_test_mode == IsTestMode::Yes || m_settings->content_blocker_enabled());+ auto enabled = content_blocking_enabled();+ auto disabled_sites = m_web_content_options.is_test_mode == IsTestMode::Yes ? Vector<String> {} : m_settings->content_blocker_disabled_sites().values();WebContentClient::for_each_client([&](WebContentClient& client) {client.for_each_page([&](WebContentPage& page) {- client.async_set_content_blocking_enabled(page.id(), enabled);+ client.async_set_content_blocking_policy(page.id(), enabled, disabled_sites);return IterationDecision::Continue;});- if (lists_loaded)+ if (rules_changed)client.async_set_content_blockers(*m_content_blocker_list_buffer);return IterationDecision::Continue;});diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.hindex 08ff22eaf2d..9d5b040f63e 100644--- a/Libraries/LibWebView/Application.h+++ b/Libraries/LibWebView/Application.h@@ -144,8 +144,14 @@ public:void update_bookmark_action_for_current_web_view();void bookmarks_changed(Badge<ApplicationBookmarkStoreObserver>);void show_bookmarks_bar_changed(Badge<ApplicationSettingsObserver>);+void background_networking_settings_changed(Badge<ApplicationSettingsObserver>);++ bool content_blocking_enabled() const;+ bool has_content_blocking_rules() const;+ void apply_content_blocking_policy(WebContentPage&);void content_blocker_settings_changed(Badge<ApplicationSettingsObserver>);+bool content_blocker_list_update_in_progress() const;void update_content_blocker_lists(Badge<SettingsUI>);void download_content_blocker_list_if_needed(Badge<Application, SettingsUI>, StringView identifier);@@ -428,7 +434,8 @@ private:ErrorOr<void> launch_wasm_compiler_server();#endifErrorOr<void> launch_devtools_server();- ErrorOr<void> load_content_blocker_lists();+ // Returns whether the combined rules changed.+ ErrorOr<bool> load_content_blocker_lists();void apply_content_blocker_settings();void rebuild_content_blocker_list_paths();ByteString content_blocker_list_path(StringView identifier) const;diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cppindex 23a951c388e..cdc25f5909a 100644--- a/Libraries/LibWebView/CanonicalNavigable.cpp+++ b/Libraries/LibWebView/CanonicalNavigable.cpp@@ -769,7 +769,10 @@ ErrorOr<NonnullRefPtr<WebContentPage>> CanonicalNavigable::obtain_page_to_host_itraversable.represent_group_in(*host);}- return *host->page(page_id);+ auto& page = *host->page(page_id);+ if (traversable.view().has_value())+ Application::the().apply_content_blocking_policy(page);+ return page;}ErrorOr<CanonicalNavigable::PageToPopulateDocument> CanonicalNavigable::obtain_page_to_populate_document(CanonicalSessionHistoryEntry& entry, NavigationLoader& loader, WebContentPage& page_that_created_navigation_params)diff --git a/Libraries/LibWebView/Settings.cpp b/Libraries/LibWebView/Settings.cppindex de542505955..976ae42e1d3 100644--- a/Libraries/LibWebView/Settings.cpp+++ b/Libraries/LibWebView/Settings.cpp@@ -16,6 +16,7 @@#include <LibURL/InternalURLs.h>#include <LibURL/Parser.h>#include <LibUnicode/Locale.h>+#include <LibWebCommon/Loader/ContentBlocking.h>#include <LibWebView/Application.h>#include <LibWebView/Settings.h>#include <LibWebView/UserAgent.h>@@ -78,6 +79,7 @@ static constexpr auto BACKGROUND_NETWORKING_ENABLED_KEY = "enabled"sv;static constexpr auto BACKGROUND_NETWORKING_FEATURES_KEY = "features"sv;static constexpr auto CONTENT_BLOCKERS_KEY = "contentBlockers"sv;+static constexpr auto CONTENT_BLOCKER_DISABLED_SITES_KEY = "disabledSites"sv;static constexpr auto CONTENT_BLOCKER_BUILT_IN_LISTS_KEY = "builtInLists"sv;static constexpr auto CONTENT_BLOCKER_CUSTOM_SUBSCRIPTIONS_KEY = "customSubscriptions"sv;static constexpr auto CONTENT_BLOCKER_LOCAL_LISTS_KEY = "localLists"sv;@@ -354,6 +356,16 @@ Settings Settings::create(ByteString settings_path)if (auto content_blockers = settings_json.value().get_object(CONTENT_BLOCKERS_KEY); content_blockers.has_value()) {settings.m_content_blocker_enabled = content_blockers->get_bool(CONTENT_BLOCKER_ENABLED_KEY).value_or(false);++ if (auto sites = content_blockers->get_array(CONTENT_BLOCKER_DISABLED_SITES_KEY); sites.has_value()) {+ sites->for_each([&](JsonValue const& entry) {+ if (!entry.is_string())+ return;+ if (auto host = Web::canonical_content_blocking_host(entry.as_string()); host.has_value())+ settings.m_content_blocker_disabled_sites.set(host.release_value());+ });+ }+if (auto built_in_lists = content_blockers->get_object(CONTENT_BLOCKER_BUILT_IN_LISTS_KEY); built_in_lists.has_value()) {for (auto& list : settings.m_content_blocker_lists)list.enabled = built_in_lists->get_bool(list.identifier).value_or(list.enabled);@@ -547,6 +559,11 @@ JsonValue Settings::serialize_json() constbackground_networking.set(BACKGROUND_NETWORKING_FEATURES_KEY, move(background_network_features));settings.set(BACKGROUND_NETWORKING_KEY, move(background_networking));+ JsonArray disabled_sites;+ disabled_sites.ensure_capacity(m_content_blocker_disabled_sites.size());+ for (auto const& host : m_content_blocker_disabled_sites)+ disabled_sites.must_append(host);+JsonObject built_in_content_blocker_lists;JsonArray custom_content_blocker_subscriptions;JsonArray local_content_blocker_lists;@@ -569,6 +586,7 @@ JsonValue Settings::serialize_json() constJsonObject content_blockers;content_blockers.set(CONTENT_BLOCKER_ENABLED_KEY, m_content_blocker_enabled);+ content_blockers.set(CONTENT_BLOCKER_DISABLED_SITES_KEY, move(disabled_sites));content_blockers.set(CONTENT_BLOCKER_BUILT_IN_LISTS_KEY, move(built_in_content_blocker_lists));content_blockers.set(CONTENT_BLOCKER_CUSTOM_SUBSCRIPTIONS_KEY, move(custom_content_blocker_subscriptions));content_blockers.set(CONTENT_BLOCKER_LOCAL_LISTS_KEY, move(local_content_blocker_lists));@@ -1054,6 +1072,32 @@ Optional<ContentBlockerList const&> Settings::content_blocker_list(StringView idreturn {};}+bool Settings::content_blocker_enabled_for_site(StringView site) const+{+ auto host = Web::canonical_content_blocking_host(site);+ return !host.has_value() || !m_content_blocker_disabled_sites.contains(*host);+}++ErrorOr<void> Settings::set_content_blocker_enabled_for_site(StringView site, bool enabled)+{+ auto host = Web::canonical_content_blocking_host(site);+ if (!host.has_value())+ return Error::from_string_literal("Invalid site hostname");++ auto changed = enabled+ ? m_content_blocker_disabled_sites.remove(*host)+ : m_content_blocker_disabled_sites.set(*host) == HashSetResult::InsertedNewEntry;+ if (!changed)+ return {};++ // FIXME: persist_settings should return an error so we can propagate to the UI.+ persist_settings();++ for (auto& observer : m_observers)+ observer.content_blocker_settings_changed();+ return {};+}+void Settings::set_content_blocker_enabled(bool enabled){if (m_content_blocker_enabled == enabled)diff --git a/Libraries/LibWebView/Settings.h b/Libraries/LibWebView/Settings.hindex e08f4dc649c..3e48664f4c5 100644--- a/Libraries/LibWebView/Settings.h+++ b/Libraries/LibWebView/Settings.h@@ -204,6 +204,10 @@ public:bool content_blocker_enabled() const { return m_content_blocker_enabled; }void set_content_blocker_enabled(bool);+ HashTable<String> const& content_blocker_disabled_sites() const { return m_content_blocker_disabled_sites; }+ bool content_blocker_enabled_for_site(StringView) const;+ ErrorOr<void> set_content_blocker_enabled_for_site(StringView, bool enabled);+Vector<ContentBlockerList> const& content_blocker_lists() const { return m_content_blocker_lists; }Optional<ContentBlockerList const&> content_blocker_list(StringView identifier) const;String add_content_blocker_list(String name, Optional<URL::URL> = {});@@ -256,6 +260,7 @@ private:bool m_background_networking_enabled { true };bool m_filter_list_updates_enabled { false };bool m_content_blocker_enabled { false };+ HashTable<String> m_content_blocker_disabled_sites;Vector<ContentBlockerList> m_content_blocker_lists;String m_custom_content_blocker_filters;diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex 6a79d01835f..620e25f6e89 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -3073,10 +3073,10 @@ void ConnectionFromClient::update_input_method_state(Web::PageId page_id)async_did_update_input_method_state(page_id, caret_rect, is_enabled, cursor_position, anchor_position, move(text_before_cursor), move(text_after_cursor));}-void ConnectionFromClient::set_content_blocking_enabled(Web::PageId page_id, bool enabled)+void ConnectionFromClient::set_content_blocking_policy(Web::PageId page_id, bool enabled, Vector<String> disabled_sites){if (auto page = this->page(page_id); page.has_value())- page->page().set_content_blocking_enabled(enabled);+ page->page().set_content_blocking_policy(enabled, disabled_sites);}void ConnectionFromClient::set_content_blockers(Core::AnonymousBuffer patterns_buffer)diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.hindex 5c6c912ded6..6dd74967548 100644--- a/Services/WebContent/ConnectionFromClient.h+++ b/Services/WebContent/ConnectionFromClient.h@@ -230,7 +230,7 @@ private:virtual void clone_dom_node(Web::PageId page_id, Web::UniqueNodeID node_id) override;virtual void remove_dom_node(Web::PageId page_id, Web::UniqueNodeID node_id) override;- virtual void set_content_blocking_enabled(Web::PageId page_id, bool enabled) override;+ virtual void set_content_blocking_policy(Web::PageId page_id, bool enabled, Vector<String> disabled_sites) override;virtual void set_content_blockers(Core::AnonymousBuffer patterns) override;virtual void set_autoplay_settings(Web::PageId page_id, Web::HTML::AutoplayPolicy policy, Vector<Utf16String> allowlist) override;diff --git a/Services/WebContent/WebContentServer.ipc b/Services/WebContent/WebContentServer.ipcindex b7a8bb75f33..e72dcdd157f 100644--- a/Services/WebContent/WebContentServer.ipc+++ b/Services/WebContent/WebContentServer.ipc@@ -238,7 +238,7 @@ endpoint WebContentServer routed by Web::PageId page_idfind_in_page_previous_match(Web::PageId page_id) =|find_in_page_end(Web::PageId page_id) =|- set_content_blocking_enabled(Web::PageId page_id, bool enabled) =|+ set_content_blocking_policy(Web::PageId page_id, bool enabled, Vector<String> disabled_sites) =|set_content_blockers(Core::AnonymousBuffer patterns) =|set_autoplay_settings(Web::PageId page_id, Web::HTML::AutoplayPolicy policy, Vector<Utf16String> allowlist) =|diff --git a/Tests/LibWeb/TestInlineStyle.cpp b/Tests/LibWeb/TestInlineStyle.cppindex a8f3bca29b1..1db980a7678 100644--- a/Tests/LibWeb/TestInlineStyle.cpp+++ b/Tests/LibWeb/TestInlineStyle.cpp@@ -9,6 +9,7 @@#include <LibJS/Runtime/Realm.h>#include <LibJS/Runtime/VM.h>#include <LibTest/TestCase.h>+#include <LibURL/Parser.h>#include <LibWeb/Bindings/MainThreadVM.h>#include <LibWeb/Bindings/PrincipalHostDefined.h>#include <LibWeb/CSS/CSSStyleProperties.h>@@ -16,6 +17,7 @@#include <LibWeb/HTML/HTMLDocument.h>#include <LibWeb/HTML/HTMLElement.h>#include <LibWeb/HTML/LocalTraversableNavigable.h>+#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/Loader/ContentBlocker.h>#include <LibWeb/Namespace.h>#include <LibWeb/Page/Page.h>@@ -140,14 +142,25 @@ TEST_CASE(content_blocking_policy_isolated_between_pages)auto& second_document = *static_cast<Web::HTML::LocalNavigable&>(*second_page->top_level_traversable()).active_document();EXPECT(!first_document.content_blocker_style_sheet().is_empty());EXPECT(!second_document.content_blocker_style_sheet().is_empty());- first_page->set_content_blocking_enabled(false);- EXPECT(!first_page->content_blocking_enabled());- EXPECT(second_page->content_blocking_enabled());+ first_page->set_content_blocking_policy(false, {});+ EXPECT(!first_document.content_blocking_enabled());+ EXPECT(second_document.content_blocking_enabled());EXPECT(first_document.content_blocker_style_sheet().is_empty());EXPECT(!second_document.content_blocker_style_sheet().is_empty());EXPECT(blocker.has_rules());- first_page->set_content_blocking_enabled(true);+ first_page->set_content_blocking_policy(true, {});EXPECT(!first_document.content_blocker_style_sheet().is_empty());EXPECT(!second_document.content_blocker_style_sheet().is_empty());+ auto site = URL::Parser::basic_parse("https://example.com:8443/"sv).value();+ first_document.relevant_settings_object().top_level_creation_url = site;+ second_document.relevant_settings_object().top_level_creation_url = site;+ first_page->set_content_blocking_policy(true, { { "EXAMPLE.COM."_string } });+ EXPECT(!first_page->content_blocking_enabled_for_url(site));+ EXPECT(second_page->content_blocking_enabled_for_url(site));+ EXPECT(first_document.content_blocker_style_sheet().is_empty());+ EXPECT(!second_document.content_blocker_style_sheet().is_empty());+ EXPECT(first_page->content_blocking_enabled_for_url(URL::Parser::basic_parse("https://shop.example.com/"sv).value()));+ first_page->set_content_blocking_policy(true, {});+ EXPECT(!first_document.content_blocker_style_sheet().is_empty());MUST(blocker.set_patterns({}));}