Truly independent web browser
LibWeb: Answer web storage from a mirror the browser keeps current
sideshowbarker5df393386b7f
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 8982e75de30..f41f0c2ee3d 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -840,6 +840,7 @@ set(SOURCESSpeech/SpeechSynthesisVoice.cppSRI/SRI.cppStorageAPI/NavigatorStorage.cpp+ StorageAPI/StorageAreaMirror.cppStorageAPI/StorageBottle.cppStorageAPI/StorageKey.cppStorageAPI/StorageManager.cppdiff --git a/Libraries/LibWeb/HTML/Storage.cpp b/Libraries/LibWeb/HTML/Storage.cppindex 7d6ea53204a..0f6c044b4bd 100644--- a/Libraries/LibWeb/HTML/Storage.cpp+++ b/Libraries/LibWeb/HTML/Storage.cpp@@ -95,7 +95,7 @@ WebIDL::ExceptionOr<void> Storage::set_item(Utf16View key, Utf16View value)// 4. If value cannot be stored, then throw a "QuotaExceededError" DOMException.// 5. Set this's map[key] to value.- auto result = m_storage_bottle->set(key, value);+ auto result = m_storage_bottle->set(key, value, m_window->associated_document().url().serialize());if (result.has<WebView::StorageOperationError>())return WebIDL::QuotaExceededError::create(Utf16String::formatted("Unable to store more than {} bytes in storage", *m_storage_bottle->quota()));@@ -132,7 +132,7 @@ void Storage::remove_item(Utf16View key)return;// 3. Remove this's map[key].- m_storage_bottle->remove(key);+ m_storage_bottle->remove(key, m_window->associated_document().url().serialize());// 4. Reorder this.reorder();@@ -149,7 +149,7 @@ void Storage::clear()return;// 2. Clear this's map.- m_storage_bottle->clear();+ m_storage_bottle->clear(m_window->associated_document().url().serialize());// 3. Broadcast this with null, null, and null.broadcast({}, {}, {});diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex dd076a8d99d..bd0e4d397c4 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -796,12 +796,7 @@ public:virtual void page_did_simulate_worker_request_server_connection_loss() { }virtual void page_did_store_hsts_policy_for_testing(String const&, HTTP::HSTS::ParsedHSTSPolicy const&) { }virtual bool page_did_is_known_hsts_host(String const&) { return false; }- virtual Optional<Utf16String> page_did_request_storage_item([[maybe_unused]] Web::StorageAPI::StorageEndpointType storage_endpoint, [[maybe_unused]] Web::HTML::EnvironmentId const& environment_id, [[maybe_unused]] Utf16String const& bottle_key) { return {}; }- virtual WebView::StorageSetResult page_did_set_storage_item([[maybe_unused]] Web::StorageAPI::StorageEndpointType storage_endpoint, [[maybe_unused]] Web::HTML::EnvironmentId const& environment_id, [[maybe_unused]] Utf16String const& bottle_key, [[maybe_unused]] Utf16String const& value) { return WebView::StorageOperationError::QuotaExceededError; }- virtual void page_did_remove_storage_item([[maybe_unused]] Web::StorageAPI::StorageEndpointType storage_endpoint, [[maybe_unused]] Web::HTML::EnvironmentId const& environment_id, [[maybe_unused]] Utf16String const& bottle_key) { }- virtual Vector<Utf16String> page_did_request_storage_keys([[maybe_unused]] Web::StorageAPI::StorageEndpointType storage_endpoint, [[maybe_unused]] Web::HTML::EnvironmentId const& environment_id) { return {}; }virtual u64 page_did_request_storage_usage([[maybe_unused]] Web::HTML::EnvironmentId const& environment_id) { return {}; }- virtual void page_did_clear_storage([[maybe_unused]] Web::StorageAPI::StorageEndpointType storage_endpoint, [[maybe_unused]] Web::HTML::EnvironmentId const& environment_id) { }virtual URL::BlobURLEntry::Token page_did_add_blob_url_entry(HTML::EnvironmentSettingsObject const&, [[maybe_unused]] Utf16String const& url, [[maybe_unused]] FileAPI::SerializedBlobURLEntry const& entry) { return 0; }virtual void page_did_remove_blob_url_entries(HTML::EnvironmentSettingsObject const&, [[maybe_unused]] Vector<Utf16String> const& urls) { }diff --git a/Libraries/LibWeb/StorageAPI/StorageAreaMirror.cpp b/Libraries/LibWeb/StorageAPI/StorageAreaMirror.cppnew file mode 100644index 00000000000..b384e402b3d--- /dev/null+++ b/Libraries/LibWeb/StorageAPI/StorageAreaMirror.cpp@@ -0,0 +1,372 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibWeb/StorageAPI/StorageAreaMirror.h>++namespace Web::StorageAPI {++static StorageAreaMirrorClient* s_client = nullptr;++void set_storage_area_mirror_client(StorageAreaMirrorClient* client)+{+ s_client = client;+}++// The mirrors this process holds, by the key a bottle finds them with and by the area id the owner's messages name.+// Weak, so a mirror lives exactly as long as some bottle addresses it; each mirror removes itself when it dies.+struct MirrorRegistry {+ AK_ALLOC_WITH_KMALLOC;++ HashMap<String, WeakPtr<StorageAreaMirror>> by_key;+ HashMap<StorageAreaId, WeakPtr<StorageAreaMirror>> by_id;+};++static MirrorRegistry& registry()+{+ // Outlives the process, rather than running a destructor at exit.+ static auto* registry = new MirrorRegistry;+ return *registry;+}++static String registry_key_for(StorageEndpointType endpoint_type, Optional<PageId> session_page, StorageKey const& storage_key)+{+ if (session_page.has_value())+ return MUST(String::formatted("{}/{}/{}", to_underlying(endpoint_type), *session_page, storage_key.to_string()));+ return MUST(String::formatted("{}//{}", to_underlying(endpoint_type), storage_key.to_string()));+}++NonnullRefPtr<StorageAreaMirror> StorageAreaMirror::obtain(StorageEndpointType endpoint_type, Optional<PageId> session_page, StorageKey const& storage_key, Optional<u64> quota)+{+ auto key = registry_key_for(endpoint_type, session_page, storage_key);+ if (auto existing = registry().by_key.find(key); existing != registry().by_key.end()) {+ if (auto live = existing->value.strong_ref())+ return live.release_nonnull();+ }++ auto mirror = adopt_ref(*new StorageAreaMirror(endpoint_type, session_page, storage_key, quota, key));+ registry().by_key.set(key, mirror->make_weak_ptr());+ return mirror;+}++StorageAreaMirror::StorageAreaMirror(StorageEndpointType endpoint_type, Optional<PageId> session_page, StorageKey storage_key, Optional<u64> quota, String registry_key)+ : m_endpoint_type(endpoint_type)+ , m_session_page(session_page)+ , m_storage_key(move(storage_key))+ , m_quota(quota)+ , m_registry_key(move(registry_key))+{+}++StorageAreaMirror::~StorageAreaMirror()+{+ registry().by_key.remove(m_registry_key);+ if (m_id.has_value()) {+ registry().by_id.remove(*m_id);+ if (s_client)+ s_client->disconnect_from_storage_area(*m_id);+ }+}++static String requester_key(StorageAreaMirror::Requester const& requester)+{+ return MUST(String::formatted("{}/{}", requester.page_id, requester.environment_id));+}++bool StorageAreaMirror::ensure_primed(Requester const& requester)+{+ if (m_primed)+ return true;+ if (!s_client)+ return false;++ auto key = requester_key(requester);+ if (m_failed_requesters.contains(key))+ return false;++ // One round trip loads the map and registers this process for every change after it, so nothing is missed or+ // seen twice.+ auto connection = s_client->connect_to_storage_area(requester.page_id, m_endpoint_type, requester.environment_id);+ if (!connection.id.has_value()) {+ m_failed_requesters.set(move(key));+ return false;+ }++ // The owner sends one value per key. Taking the shorter of the two would prime a map that's quietly missing+ // entries, and nothing downstream could tell that from an empty bottle.+ VERIFY(connection.keys.size() == connection.values.size());++ m_id = connection.id;+ registry().by_id.set(*m_id, make_weak_ptr());+ for (size_t i = 0; i < connection.keys.size(); ++i) {+ auto quota_size = storage_quota_size(connection.keys[i]) + storage_quota_size(connection.values[i]);+ m_entries.set(move(connection.keys[i]), Entry { move(connection.values[i]), quota_size });+ }+ m_quota_used = connection.usage;+ m_primed = true;+ m_failed_requesters.clear();+ return true;+}++size_t StorageAreaMirror::size(Requester const& requester)+{+ if (!ensure_primed(requester))+ return 0;+ return m_entries.size();+}++Vector<Utf16String> StorageAreaMirror::keys(Requester const& requester)+{+ if (!ensure_primed(requester))+ return {};+ Vector<Utf16String> keys;+ keys.ensure_capacity(m_entries.size());+ for (auto const& entry : m_entries)+ keys.unchecked_append(entry.key);+ return keys;+}++Optional<Utf16String> StorageAreaMirror::get(Requester const& requester, Utf16View key)+{+ if (!ensure_primed(requester))+ return {};+ auto entry = m_entries.find(Utf16String::from_utf16(key));+ if (entry == m_entries.end())+ return {};+ return entry->value.value;+}++WebView::StorageSetResult StorageAreaMirror::set(Requester const& requester, Utf16View key, Utf16View value, String const& document_url)+{+ // OPTIMIZATION: An item too large to ever fit is refused before loading the map, so storing one enormous string+ // into a bottle this process hasn't read yet costs no round trip. Quota is measured in UTF-8 bytes, and a UTF-16+ // code unit never encodes to fewer than one of those, so the code unit count is a lower bound.+ if (m_quota.has_value() && key.length_in_code_units() + value.length_in_code_units() > *m_quota)+ return WebView::StorageOperationError::QuotaExceededError;++ if (!ensure_primed(requester))+ return WebView::StorageOperationError::QuotaExceededError;++ auto owned_key = Utf16String::from_utf16(key);+ auto owned_value = Utf16String::from_utf16(value);++ Optional<Utf16String> old_value;+ u64 replaced_size = 0;+ if (auto existing = m_entries.find(owned_key); existing != m_entries.end()) {+ old_value = existing->value.value;+ replaced_size = existing->value.quota_size;+ }++ // The same rule the owner applies, so a write accepted here is one the owner accepts too — unless another+ // process filled the bottle in between, which the owner then refuses and this mirror hears of.+ auto new_size = storage_quota_size(key) + storage_quota_size(value);+ if (m_quota.has_value() && m_quota_used - replaced_size + new_size > *m_quota)+ return WebView::StorageOperationError::QuotaExceededError;++ apply_set(owned_key, owned_value, new_size);+ push_pending_write(owned_key, owned_value);+ s_client->set_storage_item(*m_id, owned_key, owned_value, document_url);+ return old_value;+}++Optional<Utf16String> StorageAreaMirror::remove(Requester const& requester, Utf16View key, String const& document_url)+{+ if (!ensure_primed(requester))+ return {};++ auto owned_key = Utf16String::from_utf16(key);+ auto existing = m_entries.find(owned_key);+ if (existing == m_entries.end())+ return {};++ auto old_value = existing->value.value;+ apply_remove(owned_key);+ push_pending_write(owned_key, {});+ s_client->remove_storage_item(*m_id, owned_key, document_url);+ return old_value;+}++bool StorageAreaMirror::clear(Requester const& requester, String const& document_url)+{+ if (!ensure_primed(requester) || m_entries.is_empty())+ return false;++ apply_clear();+ push_pending_write({}, {});+ s_client->clear_storage_area(*m_id, document_url);+ return true;+}++void StorageAreaMirror::apply_set(Utf16String const& key, Utf16String const& value, u64 quota_size)+{+ if (auto existing = m_entries.find(key); existing != m_entries.end())+ m_quota_used -= existing->value.quota_size;+ m_quota_used += quota_size;+ m_entries.set(key, Entry { value, quota_size });+}++void StorageAreaMirror::apply_remove(Utf16String const& key)+{+ if (auto existing = m_entries.find(key); existing != m_entries.end()) {+ m_quota_used -= existing->value.quota_size;+ m_entries.remove(existing);+ }+}++void StorageAreaMirror::apply_clear()+{+ m_entries.clear();+ m_quota_used = 0;+}++void StorageAreaMirror::push_pending_write(Optional<Utf16String> key, Optional<Utf16String> new_value)+{+ if (key.has_value())+ ++m_pending_count_by_key.ensure(*key);+ else+ ++m_pending_clear_count;+ m_pending_writes.append({ move(key), move(new_value) });+}++StorageAreaMirror::PendingWrite StorageAreaMirror::pop_pending_write()+{+ // The owner answers every write, in the order they were sent.+ VERIFY(m_first_pending_write < m_pending_writes.size());+ auto write = move(m_pending_writes[m_first_pending_write++]);+ if (m_first_pending_write == m_pending_writes.size()) {+ m_pending_writes.clear();+ m_first_pending_write = 0;+ }+ if (write.key.has_value()) {+ auto count = m_pending_count_by_key.get(*write.key);+ VERIFY(count.has_value() && *count > 0);+ if (*count == 1)+ m_pending_count_by_key.remove(*write.key);+ else+ m_pending_count_by_key.set(*write.key, *count - 1);+ } else {+ VERIFY(m_pending_clear_count > 0);+ --m_pending_clear_count;+ }+ return write;+}++// The owner hasn't applied these yet, so whatever state it just described predates them.+void StorageAreaMirror::reapply_pending_writes()+{+ for (auto const& write : m_pending_writes.span().slice(m_first_pending_write)) {+ if (!write.key.has_value())+ apply_clear();+ else if (write.new_value.has_value())+ apply_set(*write.key, *write.new_value, storage_quota_size(*write.key) + storage_quota_size(*write.new_value));+ else+ apply_remove(*write.key);+ }+}++void StorageAreaMirror::reset_to(Vector<Utf16String> keys, Vector<Utf16String> values)+{+ VERIFY(keys.size() == values.size());++ auto old_entries = move(m_entries);+ m_entries.clear();+ m_quota_used = 0;+ for (size_t i = 0; i < keys.size(); ++i)+ apply_set(keys[i], values[i], storage_quota_size(keys[i]) + storage_quota_size(values[i]));+ reapply_pending_writes();++ if (!on_remote_change)+ return;++ // AD-HOC: The spec's broadcast fires an event for each change a script makes, and never for a write refused after+ // the fact; it has no such thing. Whatever differs from before is a change this process's windows didn't+ // see being made, so each gets an event for it — the window whose write was refused included.+ auto url = m_storage_key.to_string();+ for (auto const& entry : old_entries) {+ Optional<Utf16String> now;+ if (auto it = m_entries.find(entry.key); it != m_entries.end())+ now = it->value.value;+ if (now != entry.value.value)+ on_remote_change(entry.key, entry.value.value, now, url);+ }+ for (auto const& entry : m_entries) {+ if (!old_entries.contains(entry.key))+ on_remote_change(entry.key, {}, entry.value.value, url);+ }+}++// A change another process made, as the owner serialized it. One that reached the owner before a write this process+// still has pending predates that write, so the mirror already shows the later state and leaves it be. While a clear+// is pending, that goes for every change.+void StorageAreaMirror::apply_remote_change(Optional<Utf16String> const& key, Optional<Utf16String> const& new_value)+{+ if (m_pending_clear_count > 0)+ return;++ if (!key.has_value()) {+ // The owner emptied the bottle before applying this process's pending writes, so those come back on top.+ apply_clear();+ reapply_pending_writes();+ return;+ }++ if (m_pending_count_by_key.contains(*key))+ return;++ if (new_value.has_value())+ apply_set(*key, *new_value, storage_quota_size(*key) + storage_quota_size(*new_value));+ else+ apply_remove(*key);+}++static RefPtr<StorageAreaMirror> mirror_for(StorageAreaId id)+{+ auto entry = registry().by_id.find(id);+ if (entry == registry().by_id.end())+ return {};+ return entry->value.strong_ref();+}++void StorageAreaMirror::did_change(StorageAreaId id, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url)+{+ auto mirror = mirror_for(id);+ if (!mirror)+ return;++ mirror->apply_remote_change(key, new_value);+ if (mirror->on_remote_change)+ mirror->on_remote_change(key, old_value, new_value, url);+}++void StorageAreaMirror::did_acknowledge_write(StorageAreaId id)+{+ auto mirror = mirror_for(id);+ if (!mirror)+ return;+ mirror->pop_pending_write();+}++void StorageAreaMirror::did_refuse_write(StorageAreaId id, Vector<Utf16String> keys, Vector<Utf16String> values)+{+ auto mirror = mirror_for(id);+ if (!mirror)+ return;++ // Only a set can be refused: it was applied here on the strength of a quota check another process's write+ // overtook. The owner's map puts this one back in agreement.+ auto refused = mirror->pop_pending_write();+ VERIFY(refused.key.has_value() && refused.new_value.has_value());+ mirror->reset_to(move(keys), move(values));+}++void StorageAreaMirror::did_reset(StorageAreaId id, Vector<Utf16String> keys, Vector<Utf16String> values)+{+ auto mirror = mirror_for(id);+ if (!mirror)+ return;+ mirror->reset_to(move(keys), move(values));+}++}diff --git a/Libraries/LibWeb/StorageAPI/StorageAreaMirror.h b/Libraries/LibWeb/StorageAPI/StorageAreaMirror.hnew file mode 100644index 00000000000..8dbcf39ba1d--- /dev/null+++ b/Libraries/LibWeb/StorageAPI/StorageAreaMirror.h@@ -0,0 +1,151 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Function.h>+#include <AK/HashMap.h>+#include <AK/HashTable.h>+#include <AK/NonnullRefPtr.h>+#include <AK/Optional.h>+#include <AK/RefCounted.h>+#include <AK/String.h>+#include <AK/Utf16String.h>+#include <AK/Vector.h>+#include <AK/WeakPtr.h>+#include <AK/Weakable.h>+#include <LibWeb/Export.h>+#include <LibWeb/StorageAPI/StorageKey.h>+#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>+#include <LibWebCommon/Page/PageId.h>+#include <LibWebCommon/StorageAPI/StorageAreaId.h>+#include <LibWebCommon/StorageAPI/StorageEndpoint.h>+#include <LibWebCommon/WebView/StorageSetResult.h>++namespace Web::StorageAPI {++// What the process that owns the storage areas answers when this process connects to one: the area's id and+// everything the bottle holds. No id means the area couldn't be resolved, and the mirror stays detached.+struct StorageAreaConnection {+ Optional<StorageAreaId> id;+ Vector<Utf16String> keys;+ Vector<Utf16String> values;+ u64 usage { 0 };+};++// The process's one link to the storage areas' owner. WebContent connects it to the browser process; a process without+// one (a unit test) leaves every mirror detached.+class WEB_API StorageAreaMirrorClient {+public:+ virtual ~StorageAreaMirrorClient() = default;++ virtual StorageAreaConnection connect_to_storage_area(PageId, StorageEndpointType, HTML::EnvironmentId const&) = 0;+ virtual void disconnect_from_storage_area(StorageAreaId) = 0;+ virtual void set_storage_item(StorageAreaId, Utf16String const& key, Utf16String const& value, String const& document_url) = 0;+ virtual void remove_storage_item(StorageAreaId, Utf16String const& key, String const& document_url) = 0;+ virtual void clear_storage_area(StorageAreaId, String const& document_url) = 0;+};++WEB_API void set_storage_area_mirror_client(StorageAreaMirrorClient*);++// https://storage.spec.whatwg.org/#storage-bottle+// This process's copy of one storage bottle's map. The map itself is kept by the browser process, which makes it+// available across agent cluster boundaries this way: a process loads the map once, with one synchronous round trip+// that also registers it for every later change, and from then on answers reads from the copy, applies writes to the+// copy before sending them, and applies the changes other processes make as the owner relays them. Every storage+// bottle in this process for the same area shares one mirror, so two windows of one origin can't see different maps.+class WEB_API StorageAreaMirror final+ : public RefCounted<StorageAreaMirror>+ , public Weakable<StorageAreaMirror> {+public:+ // The page and environment a bottle asks on behalf of, which the owner resolves to the area. A mirror outlives+ // the document that first asked for it, so every call names its own requester.+ struct Requester {+ PageId page_id;+ HTML::EnvironmentId environment_id;+ };++ // One mirror per storage key for local storage, and per page and storage key for session storage: a page's+ // documents all belong to one traversable, and the traversable is what partitions session storage.+ static NonnullRefPtr<StorageAreaMirror> obtain(StorageEndpointType, Optional<PageId> session_page, StorageKey const&, Optional<u64> quota);+ ~StorageAreaMirror();++ size_t size(Requester const&);+ Vector<Utf16String> keys(Requester const&);+ Optional<Utf16String> get(Requester const&, Utf16View key);+ // The value the key had, or the quota's refusal. The write is applied here and sent on without waiting.+ WebView::StorageSetResult set(Requester const&, Utf16View key, Utf16View value, String const& document_url);+ // The value removed, if the key existed.+ Optional<Utf16String> remove(Requester const&, Utf16View key, String const& document_url);+ // False when there was nothing to clear.+ bool clear(Requester const&, String const& document_url);++ // What the owner relays, found by area id. A change for an area this process no longer mirrors is dropped.+ static void did_change(StorageAreaId, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url);+ static void did_acknowledge_write(StorageAreaId);+ static void did_refuse_write(StorageAreaId, Vector<Utf16String> keys, Vector<Utf16String> values);+ static void did_reset(StorageAreaId, Vector<Utf16String> keys, Vector<Utf16String> values);++ // Every change another party made to the map, as the owner relayed it (or, after a reset, as the diff shows it),+ // for the storage events it calls for. A null key is a clear.+ Function<void(Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url)> on_remote_change;++ StorageEndpointType endpoint_type() const { return m_endpoint_type; }+ StorageKey const& storage_key() const { return m_storage_key; }+ Optional<PageId> session_page() const { return m_session_page; }++ u64 quota_used() const { return m_quota_used; }+ size_t pending_write_count() const { return m_pending_writes.size() - m_first_pending_write; }++private:+ StorageAreaMirror(StorageEndpointType, Optional<PageId> session_page, StorageKey, Optional<u64> quota, String registry_key);++ // A write this process applied and sent, until the owner acknowledges or refuses it. A null key is a clear; a+ // null value is a removal.+ struct PendingWrite {+ Optional<Utf16String> key;+ Optional<Utf16String> new_value;+ };++ // An entry's quota size is kept beside its value, so overwriting or removing it never measures the old value again.+ struct Entry {+ Utf16String value;+ u64 quota_size { 0 };+ };++ // False when the owner couldn't resolve the requester's area; that requester is then not asked about again, but+ // another requester of the same mirror still can be (the first may have been a page on its way out).+ bool ensure_primed(Requester const&);+ void apply_set(Utf16String const& key, Utf16String const& value, u64 quota_size);+ void apply_remove(Utf16String const& key);+ void apply_clear();+ void push_pending_write(Optional<Utf16String> key, Optional<Utf16String> new_value);+ PendingWrite pop_pending_write();+ void reapply_pending_writes();+ void reset_to(Vector<Utf16String> keys, Vector<Utf16String> values);+ void apply_remote_change(Optional<Utf16String> const& key, Optional<Utf16String> const& new_value);++ StorageEndpointType m_endpoint_type;+ Optional<PageId> m_session_page;+ StorageKey m_storage_key;+ Optional<u64> m_quota;+ String m_registry_key;++ OrderedHashMap<Utf16String, Entry> m_entries;+ u64 m_quota_used { 0 };+ Optional<StorageAreaId> m_id;+ bool m_primed { false };+ HashTable<String> m_failed_requesters;++ // The writes the owner hasn't answered yet are the ones from m_first_pending_write on. Answered ones stay in place+ // until the queue drains, so a script that queues thousands of writes in one task costs nothing more per answer.+ Vector<PendingWrite> m_pending_writes;+ size_t m_first_pending_write { 0 };+ HashMap<Utf16String, u32> m_pending_count_by_key;+ u32 m_pending_clear_count { 0 };+};++}diff --git a/Libraries/LibWeb/StorageAPI/StorageBottle.cpp b/Libraries/LibWeb/StorageAPI/StorageBottle.cppindex 51744022e0e..342f092a3b7 100644--- a/Libraries/LibWeb/StorageAPI/StorageBottle.cpp+++ b/Libraries/LibWeb/StorageAPI/StorageBottle.cpp@@ -14,8 +14,7 @@namespace Web::StorageAPI {-GC_DEFINE_ALLOCATOR(LocalStorageBottle);-GC_DEFINE_ALLOCATOR(SessionStorageBottle);+GC_DEFINE_ALLOCATOR(StorageBottle);GC_DEFINE_ALLOCATOR(StorageBucket);void StorageBucket::visit_edges(GC::Cell::Visitor& visitor)@@ -25,7 +24,7 @@ void StorageBucket::visit_edges(GC::Cell::Visitor& visitor)visitor.visit(entry);}-StorageBucket::StorageBucket(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageType type)+StorageBucket::StorageBucket(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageKey const& key, StorageType type){// 1. Let bucket be null.// 2. If type is "local", then set bucket to a new local storage bucket.@@ -36,7 +35,7 @@ StorageBucket::StorageBucket(GC::Ref<Page> page, HTML::EnvironmentId environment// 4. For each endpoint of registered storage endpoints whose types contain type, set bucket’s bottle map[endpoint’s identifier] to a new storage bottle whose quota is endpoint’s quota.for (auto const& endpoint : StorageEndpoint::registered_endpoints()) {if (endpoint.type == type)- m_bottle_map[to_underlying(endpoint.identifier)] = StorageBottle::create(page, endpoint, environment_id);+ m_bottle_map[to_underlying(endpoint.identifier)] = StorageBottle::create(page, endpoint, environment_id, key);}// 5. Return bucket.@@ -50,7 +49,7 @@ GC::Ptr<StorageBottle> obtain_a_storage_bottle_map(StorageType type, HTML::Envir// 3. Otherwise:// 1. Assert: type is "session".// 2. Set shed to environment’s global object’s associated Document’s node navigable’s traversable navigable’s storage shed.- // NB: Both sheds are kept by the browser process, in a StorageJar, which the bottle returned here proxies. The+ // NB: Both sheds are kept by the browser process, in a StorageJar, which the bottle returned here mirrors. The// bottle names environment, from which the browser process obtains the storage key itself.// 4. Let shelf be the result of running obtain a storage shelf, with shed, environment, and type.@@ -70,7 +69,7 @@ GC::Ptr<StorageBottle> obtain_a_storage_bottle_map(StorageType type, HTML::Envir// 9. Append proxyMap to bottle’s proxy map reference set.// 10. Return proxyMap.auto& page = HTML::relevant_window(environment.global_object()).page();- return StorageBottle::create(page, *endpoint, environment.id);+ return StorageBottle::create(page, *endpoint, environment.id, *key);}// https://storage.spec.whatwg.org/#obtain-a-local-storage-bottle-map@@ -89,83 +88,60 @@ GC::Ptr<StorageBottle> obtain_a_session_storage_bottle_map(HTML::EnvironmentSettreturn obtain_a_storage_bottle_map(StorageType::Session, environment, identifier);}-GC::Ref<StorageBottle> StorageBottle::create(GC::Ref<Page> page, StorageEndpoint const& endpoint, HTML::EnvironmentId environment_id)+GC::Ref<StorageBottle> StorageBottle::create(GC::Ref<Page> page, StorageEndpoint const& endpoint, HTML::EnvironmentId environment_id, StorageKey const& key){- if (endpoint.type == StorageType::Local)- return LocalStorageBottle::create(page, endpoint.identifier, move(environment_id), endpoint.quota);- return SessionStorageBottle::create(page, endpoint.identifier, move(environment_id), endpoint.quota);+ return GC::Heap::the().allocate<StorageBottle>(page, endpoint.identifier, move(environment_id), key, endpoint.quota);}-void LocalStorageBottle::visit_edges(GC::Cell::Visitor& visitor)+StorageBottle::StorageBottle(GC::Ref<Page> page, StorageEndpointType endpoint_type, HTML::EnvironmentId environment_id, StorageKey const& key, Optional<u64> quota)+ : m_page(page)+ , m_environment_id(move(environment_id))+ , m_quota(quota)+ // Session storage is partitioned by the traversable, and a page's documents all belong to one traversable, so+ // a session bottle's mirror is found by its page as well as its storage key.+ , m_mirror(StorageAreaMirror::obtain(endpoint_type, endpoint_type == StorageEndpointType::SessionStorage ? Optional<PageId> { page->client().id() } : Optional<PageId> {}, key, quota)){- Base::visit_edges(visitor);- visitor.visit(m_page);-}--size_t LocalStorageBottle::size() const-{- return m_page->client().page_did_request_storage_keys(m_endpoint_type, m_environment_id).size();-}--Vector<Utf16String> LocalStorageBottle::keys() const-{- return m_page->client().page_did_request_storage_keys(m_endpoint_type, m_environment_id);-}--Optional<Utf16String> LocalStorageBottle::get(Utf16View key) const-{- return m_page->client().page_did_request_storage_item(m_endpoint_type, m_environment_id, Utf16String::from_utf16(key));}-StorageSetResult LocalStorageBottle::set(Utf16View key, Utf16View value)+void StorageBottle::visit_edges(GC::Cell::Visitor& visitor){- return m_page->client().page_did_set_storage_item(m_endpoint_type, m_environment_id, Utf16String::from_utf16(key), Utf16String::from_utf16(value));-}--void LocalStorageBottle::clear()-{- m_page->client().page_did_clear_storage(m_endpoint_type, m_environment_id);-}--void LocalStorageBottle::remove(Utf16View key)-{- m_page->client().page_did_remove_storage_item(m_endpoint_type, m_environment_id, Utf16String::from_utf16(key));+ Base::visit_edges(visitor);+ visitor.visit(m_page);}-void SessionStorageBottle::visit_edges(GC::Cell::Visitor& visitor)+StorageAreaMirror::Requester StorageBottle::requester() const{- Base::visit_edges(visitor);- visitor.visit(m_page);+ return { m_page->client().id(), m_environment_id };}-size_t SessionStorageBottle::size() const+size_t StorageBottle::size() const{- return m_page->client().page_did_request_storage_keys(m_endpoint_type, m_environment_id).size();+ return m_mirror->size(requester());}-Vector<Utf16String> SessionStorageBottle::keys() const+Vector<Utf16String> StorageBottle::keys() const{- return m_page->client().page_did_request_storage_keys(m_endpoint_type, m_environment_id);+ return m_mirror->keys(requester());}-Optional<Utf16String> SessionStorageBottle::get(Utf16View key) const+Optional<Utf16String> StorageBottle::get(Utf16View key) const{- return m_page->client().page_did_request_storage_item(m_endpoint_type, m_environment_id, Utf16String::from_utf16(key));+ return m_mirror->get(requester(), key);}-StorageSetResult SessionStorageBottle::set(Utf16View key, Utf16View value)+StorageSetResult StorageBottle::set(Utf16View key, Utf16View value, String const& document_url){- return m_page->client().page_did_set_storage_item(m_endpoint_type, m_environment_id, Utf16String::from_utf16(key), Utf16String::from_utf16(value));+ return m_mirror->set(requester(), key, value, document_url);}-void SessionStorageBottle::clear()+void StorageBottle::clear(String const& document_url){- m_page->client().page_did_clear_storage(m_endpoint_type, m_environment_id);+ m_mirror->clear(requester(), document_url);}-void SessionStorageBottle::remove(Utf16View key)+void StorageBottle::remove(Utf16View key, String const& document_url){- m_page->client().page_did_remove_storage_item(m_endpoint_type, m_environment_id, Utf16String::from_utf16(key));+ (void)m_mirror->remove(requester(), key, document_url);}}diff --git a/Libraries/LibWeb/StorageAPI/StorageBottle.h b/Libraries/LibWeb/StorageAPI/StorageBottle.hindex e182621cf86..6d9966a96fc 100644--- a/Libraries/LibWeb/StorageAPI/StorageBottle.h+++ b/Libraries/LibWeb/StorageAPI/StorageBottle.h@@ -8,11 +8,14 @@#pragma once#include <AK/HashMap.h>+#include <AK/NonnullRefPtr.h>#include <AK/String.h>#include <LibGC/Heap.h>#include <LibGC/Ptr.h>#include <LibWeb/Forward.h>#include <LibWeb/Page/Page.h>+#include <LibWeb/StorageAPI/StorageAreaMirror.h>+#include <LibWeb/StorageAPI/StorageKey.h>#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>#include <LibWebCommon/StorageAPI/StorageEndpoint.h>#include <LibWebCommon/StorageAPI/StorageType.h>@@ -23,99 +26,41 @@ namespace Web::StorageAPI {using StorageSetResult = Variant<WebView::StorageOperationError, Optional<Utf16String>>;// https://storage.spec.whatwg.org/#storage-bottle+// NB: The bottle's map lives in the browser process; what a bottle here holds is this process's mirror of it, shared+// with every other bottle in the process for the same area. Each bottle object is one storage proxy map over it.class StorageBottle : public GC::Cell {GC_CELL(StorageBottle, GC::Cell);+ GC_DECLARE_ALLOCATOR(StorageBottle);public:- static GC::Ref<StorageBottle> create(GC::Ref<Page> page, StorageEndpoint const& endpoint, HTML::EnvironmentId environment_id);+ static GC::Ref<StorageBottle> create(GC::Ref<Page>, StorageEndpoint const&, HTML::EnvironmentId, StorageKey const&);virtual ~StorageBottle() = default;// A storage bottle also has a proxy map reference set, which is initially an empty setGC::Ref<StorageBottle> proxy() { return *this; }- virtual size_t size() const = 0;- virtual Vector<Utf16String> keys() const = 0;- virtual Optional<Utf16String> get(Utf16View) const = 0;- virtual StorageSetResult set(Utf16View key, Utf16View value) = 0;- virtual void clear() = 0;- virtual void remove(Utf16View) = 0;+ size_t size() const;+ Vector<Utf16String> keys() const;+ Optional<Utf16String> get(Utf16View) const;+ // The URL is the document's, carried to the storage events other processes fire for the change.+ StorageSetResult set(Utf16View key, Utf16View value, String const& document_url);+ void clear(String const& document_url);+ void remove(Utf16View, String const& document_url);Optional<u64> quota() const { return m_quota; }-protected:- explicit StorageBottle(Optional<u64> quota)- : m_quota(quota)- {- }-- Optional<u64> m_quota;-};--class LocalStorageBottle final : public StorageBottle {- GC_CELL(LocalStorageBottle, StorageBottle);- GC_DECLARE_ALLOCATOR(LocalStorageBottle);--public:- static GC::Ref<LocalStorageBottle> create(GC::Ref<Page> page, StorageEndpointType endpoint_type, HTML::EnvironmentId environment_id, Optional<u64> quota)- {- return GC::Heap::the().allocate<LocalStorageBottle>(page, endpoint_type, move(environment_id), quota);- }-- virtual size_t size() const override;- virtual Vector<Utf16String> keys() const override;- virtual Optional<Utf16String> get(Utf16View) const override;- virtual StorageSetResult set(Utf16View key, Utf16View value) override;- virtual void clear() override;- virtual void remove(Utf16View) override;-virtual void visit_edges(GC::Cell::Visitor& visitor) override;private:- explicit LocalStorageBottle(GC::Ref<Page> page, StorageEndpointType endpoint_type, HTML::EnvironmentId environment_id, Optional<u64> quota)- : StorageBottle(quota)- , m_page(move(page))- , m_endpoint_type(endpoint_type)- , m_environment_id(move(environment_id))- {- }-- GC::Ref<Page> m_page;- StorageEndpointType m_endpoint_type;- HTML::EnvironmentId m_environment_id;-};+ StorageBottle(GC::Ref<Page>, StorageEndpointType, HTML::EnvironmentId, StorageKey const&, Optional<u64> quota);-class SessionStorageBottle final : public StorageBottle {- GC_CELL(SessionStorageBottle, StorageBottle);- GC_DECLARE_ALLOCATOR(SessionStorageBottle);--public:- static GC::Ref<SessionStorageBottle> create(GC::Ref<Page> page, StorageEndpointType endpoint_type, HTML::EnvironmentId environment_id, Optional<u64> quota)- {- return GC::Heap::the().allocate<SessionStorageBottle>(page, endpoint_type, move(environment_id), quota);- }-- virtual size_t size() const override;- virtual Vector<Utf16String> keys() const override;- virtual Optional<Utf16String> get(Utf16View) const override;- virtual StorageSetResult set(Utf16View key, Utf16View value) override;- virtual void clear() override;- virtual void remove(Utf16View) override;-- virtual void visit_edges(GC::Cell::Visitor& visitor) override;--private:- explicit SessionStorageBottle(GC::Ref<Page> page, StorageEndpointType endpoint_type, HTML::EnvironmentId environment_id, Optional<u64> quota)- : StorageBottle(quota)- , m_page(move(page))- , m_endpoint_type(endpoint_type)- , m_environment_id(move(environment_id))- {- }+ StorageAreaMirror::Requester requester() const;GC::Ref<Page> m_page;- StorageEndpointType m_endpoint_type;HTML::EnvironmentId m_environment_id;+ Optional<u64> m_quota;+ NonnullRefPtr<StorageAreaMirror> m_mirror;};using BottleMap = Array<GC::Ptr<StorageBottle>, to_underlying(StorageEndpointType::Count)>;@@ -127,7 +72,7 @@ class StorageBucket : public GC::Cell {GC_DECLARE_ALLOCATOR(StorageBucket);public:- static GC::Ref<StorageBucket> create(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageType type) { return GC::Heap::the().allocate<StorageBucket>(page, move(environment_id), type); }+ static GC::Ref<StorageBucket> create(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageKey const& key, StorageType type) { return GC::Heap::the().allocate<StorageBucket>(page, move(environment_id), key, type); }BottleMap& bottle_map() { return m_bottle_map; }BottleMap const& bottle_map() const { return m_bottle_map; }@@ -135,7 +80,7 @@ public:virtual void visit_edges(GC::Cell::Visitor& visitor) override;private:- explicit StorageBucket(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageType type);+ explicit StorageBucket(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageKey const& key, StorageType type);// A storage bucket has a bottle map of storage identifiers to storage bottles.BottleMap m_bottle_map;diff --git a/Libraries/LibWeb/StorageAPI/StorageShelf.cpp b/Libraries/LibWeb/StorageAPI/StorageShelf.cppindex d86bac142d3..7efa46f27fd 100644--- a/Libraries/LibWeb/StorageAPI/StorageShelf.cpp+++ b/Libraries/LibWeb/StorageAPI/StorageShelf.cpp@@ -23,13 +23,13 @@ void StorageShelf::visit_edges(GC::Cell::Visitor& visitor)}// https://storage.spec.whatwg.org/#create-a-storage-shelf-StorageShelf::StorageShelf(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageType type)+StorageShelf::StorageShelf(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageKey const& key, StorageType type): m_page(page), m_environment_id(move(environment_id)){// 1. Let shelf be a new storage shelf.// 2. Set shelf’s bucket map["default"] to the result of running create a storage bucket with type.- m_bucket_map.set("default"_string, StorageBucket::create(page, m_environment_id, type));+ m_bucket_map.set("default"_string, StorageBucket::create(page, m_environment_id, key, type));// 3. Return shelf.}@@ -66,7 +66,7 @@ GC::Ptr<StorageShelf> obtain_a_local_storage_shelf(HTML::EnvironmentSettingsObje// AD-HOC: The user agent's storage shed is kept by the browser process, in a StorageJar. This shelf is a transient// helper for computing estimate()'s usage and quota — so a standalone shelf is functionally equivalent to// the spec's requirement to obtain one from a shed.- return StorageShelf::create(window.page(), settings.id, StorageType::Local);+ return StorageShelf::create(window.page(), settings.id, *key, StorageType::Local);}}diff --git a/Libraries/LibWeb/StorageAPI/StorageShelf.h b/Libraries/LibWeb/StorageAPI/StorageShelf.hindex 8d9a0ec0e37..f13333f5823 100644--- a/Libraries/LibWeb/StorageAPI/StorageShelf.h+++ b/Libraries/LibWeb/StorageAPI/StorageShelf.h@@ -25,7 +25,7 @@ class StorageShelf : public GC::Cell {GC_DECLARE_ALLOCATOR(StorageShelf);public:- static GC::Ref<StorageShelf> create(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageType type) { return GC::Heap::the().allocate<StorageShelf>(page, move(environment_id), type); }+ static GC::Ref<StorageShelf> create(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageKey const& key, StorageType type) { return GC::Heap::the().allocate<StorageShelf>(page, move(environment_id), key, type); }BucketMap& bucket_map() { return m_bucket_map; }BucketMap const& bucket_map() const { return m_bucket_map; }@@ -36,7 +36,7 @@ public:virtual void visit_edges(GC::Cell::Visitor& visitor) override;private:- explicit StorageShelf(GC::Ref<Page>, HTML::EnvironmentId, StorageType);+ explicit StorageShelf(GC::Ref<Page>, HTML::EnvironmentId, StorageKey const&, StorageType);GC::Ref<Page> m_page;HTML::EnvironmentId m_environment_id;diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cppindex 79ff84ca9e4..ceb1b8454bb 100644--- a/Libraries/LibWebView/WebContentClient.cpp+++ b/Libraries/LibWebView/WebContentClient.cpp@@ -670,31 +670,6 @@ Messages::WebContentClient::DidRequestCookieResponse WebContentClient::did_requereturn cookie;}-Messages::WebContentClient::DidSetStorageItemResponse WebContentClient::did_set_storage_item(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key, Utf16String value)-{- if (auto* page = this->page(page_id))- return page->did_set_storage_item(storage_endpoint, move(environment_id), move(bottle_key), move(value));-- // A closed page has no storage left to set. Its reply cannot be empty, so it hears the refusal a full jar gives.- return WebView::StorageOperationError::QuotaExceededError;-}--Messages::WebContentClient::DidRequestStorageItemResponse WebContentClient::did_request_storage_item(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key)-{- if (auto* page = this->page(page_id))- return page->did_request_storage_item(storage_endpoint, move(environment_id), move(bottle_key));-- return Optional<Utf16String> {};-}--Messages::WebContentClient::DidRequestStorageKeysResponse WebContentClient::did_request_storage_keys(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id)-{- if (auto* page = this->page(page_id))- return page->did_request_storage_keys(storage_endpoint, move(environment_id));-- return Vector<Utf16String> {};-}-Messages::WebContentClient::DidRequestStorageUsageResponse WebContentClient::did_request_storage_usage(Web::PageId page_id, Web::HTML::EnvironmentId environment_id){if (auto* page = this->page(page_id))diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.hindex 9ee824b372d..5c4883365c2 100644--- a/Libraries/LibWebView/WebContentClient.h+++ b/Libraries/LibWebView/WebContentClient.h@@ -189,9 +189,6 @@ private:virtual Messages::WebContentClient::DidRequestNamedCookieResponse did_request_named_cookie(URL::URL, String) override;virtual Messages::WebContentClient::DidRequestCookieResponse did_request_cookie(Web::PageId page_id, Optional<Web::HTML::EnvironmentId>, URL::URL, HTTP::Cookie::Source) override;virtual void did_close_browsing_context(Web::PageId page_id) override;- virtual Messages::WebContentClient::DidSetStorageItemResponse did_set_storage_item(Web::PageId page_id, Web::StorageAPI::StorageEndpointType, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key, Utf16String value) override;- virtual Messages::WebContentClient::DidRequestStorageItemResponse did_request_storage_item(Web::PageId page_id, Web::StorageAPI::StorageEndpointType, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key) override;- virtual Messages::WebContentClient::DidRequestStorageKeysResponse did_request_storage_keys(Web::PageId page_id, Web::StorageAPI::StorageEndpointType, Web::HTML::EnvironmentId environment_id) override;virtual Messages::WebContentClient::DidRequestStorageUsageResponse did_request_storage_usage(Web::PageId page_id, Web::HTML::EnvironmentId environment_id) override;virtual Messages::WebContentClient::ConnectToStorageAreaResponse connect_to_storage_area(Web::PageId page_id, Web::StorageAPI::StorageEndpointType, Web::HTML::EnvironmentId environment_id) override;virtual void disconnect_from_storage_area(Web::StorageAPI::StorageAreaId) override;diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex 5f612c2e266..b8f05e684c9 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -1241,49 +1241,6 @@ void WebContentPage::did_request_document_cookie_version_index(Web::HTML::Enviro}}-Messages::WebContentClient::DidRequestStorageItemResponse WebContentPage::did_request_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key)-{- auto canonical_key = canonical_storage_key(environment_id);- auto* storage_jar = this->storage_jar(storage_endpoint);- if (!canonical_key.has_value() || !storage_jar)- return Optional<Utf16String> {};- return storage_jar->get_item(storage_endpoint, *canonical_key, bottle_key);-}--Messages::WebContentClient::DidSetStorageItemResponse WebContentPage::did_set_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key, Utf16String value)-{- auto canonical_key = canonical_storage_key(environment_id);- auto* storage_jar = this->storage_jar(storage_endpoint);- if (!canonical_key.has_value() || !storage_jar)- return WebView::StorageOperationError::QuotaExceededError;- return storage_jar->set_item(storage_endpoint, *canonical_key, bottle_key, value);-}--void WebContentPage::did_remove_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key)-{- auto canonical_key = canonical_storage_key(environment_id);- auto* storage_jar = this->storage_jar(storage_endpoint);- if (canonical_key.has_value() && storage_jar)- storage_jar->remove_item(storage_endpoint, *canonical_key, bottle_key);-}--Messages::WebContentClient::DidRequestStorageKeysResponse WebContentPage::did_request_storage_keys(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id)-{- auto canonical_key = canonical_storage_key(environment_id);- auto* storage_jar = this->storage_jar(storage_endpoint);- if (!canonical_key.has_value() || !storage_jar)- return Vector<Utf16String> {};- return storage_jar->get_all_keys(storage_endpoint, *canonical_key);-}--void WebContentPage::did_clear_storage(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id)-{- auto canonical_key = canonical_storage_key(environment_id);- auto* storage_jar = this->storage_jar(storage_endpoint);- if (canonical_key.has_value() && storage_jar)- storage_jar->clear_storage_key(storage_endpoint, *canonical_key);-}-Messages::WebContentClient::ConnectToStorageAreaResponse WebContentPage::connect_to_storage_area(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id){auto canonical_key = canonical_storage_key(environment_id);diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.hindex afe7818da58..e1626361579 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -231,11 +231,6 @@ private:virtual void did_request_document_cookie_version_index(Web::HTML::EnvironmentId environment_id, i64 document_id, String domain) override;virtual void did_set_cookie(Optional<Web::HTML::EnvironmentId>, URL::URL, HTTP::Cookie::ParsedCookie, HTTP::Cookie::Source) override;virtual void did_remove_blob_url_entries(Web::HTML::EnvironmentId environment_id, Vector<Utf16String> urls) override;- Messages::WebContentClient::DidRequestStorageItemResponse did_request_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key);- Messages::WebContentClient::DidSetStorageItemResponse did_set_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key, Utf16String value);- virtual void did_remove_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key) override;- Messages::WebContentClient::DidRequestStorageKeysResponse did_request_storage_keys(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id);- virtual void did_clear_storage(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id) override;Messages::WebContentClient::ConnectToStorageAreaResponse connect_to_storage_area(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id);virtual void did_change_needs_beforeunload_check(bool needs_beforeunload_check) override;virtual void did_consume_user_activation(Web::HTML::UserActivationConsumption consumption) override;diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex 1d29b8f158a..bb27c4d63b7 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -116,9 +116,13 @@ ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transpo, m_page_host(PageHost::create(*this)), m_enable_test_mode(enable_test_mode){+ Web::StorageAPI::set_storage_area_mirror_client(this);}-ConnectionFromClient::~ConnectionFromClient() = default;+ConnectionFromClient::~ConnectionFromClient()+{+ Web::StorageAPI::set_storage_area_mirror_client(nullptr);+}Web::Compositor::CompositorConnection* ConnectionFromClient::compositor_process_connection() const{@@ -1246,20 +1250,54 @@ void ConnectionFromClient::inspect_storage(Web::PageId page_id, Web::StorageAPI:async_did_inspect_storage(page_id, request_id, storage_items.serialized());}-void ConnectionFromClient::storage_area_changed(Web::StorageAPI::StorageAreaId, Optional<Utf16String>, Optional<Utf16String>, Optional<Utf16String>, String)+Web::StorageAPI::StorageAreaConnection ConnectionFromClient::connect_to_storage_area(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& environment_id)+{+ auto response = send_sync_but_allow_failure<Messages::WebContentClient::ConnectToStorageArea>(page_id, storage_endpoint, environment_id);+ if (!response) {+ dbgln("WebContent client disconnected during ConnectToStorageArea. Exiting peacefully.");+ Core::Process::terminate_immediately(0);+ }+ return { response->area_id(), response->take_keys(), response->take_values(), response->usage() };+}++void ConnectionFromClient::disconnect_from_storage_area(Web::StorageAPI::StorageAreaId area_id)+{+ async_disconnect_from_storage_area(area_id);+}++void ConnectionFromClient::set_storage_item(Web::StorageAPI::StorageAreaId area_id, Utf16String const& key, Utf16String const& value, String const& document_url)+{+ async_set_storage_item(area_id, key, value, document_url);+}++void ConnectionFromClient::remove_storage_item(Web::StorageAPI::StorageAreaId area_id, Utf16String const& key, String const& document_url)+{+ async_remove_storage_item(area_id, key, document_url);+}++void ConnectionFromClient::clear_storage_area(Web::StorageAPI::StorageAreaId area_id, String const& document_url)+{+ async_clear_storage_area(area_id, document_url);+}++void ConnectionFromClient::storage_area_changed(Web::StorageAPI::StorageAreaId area_id, Optional<Utf16String> key, Optional<Utf16String> old_value, Optional<Utf16String> new_value, String url){+ Web::StorageAPI::StorageAreaMirror::did_change(area_id, key, old_value, new_value, url);}-void ConnectionFromClient::storage_area_write_acknowledged(Web::StorageAPI::StorageAreaId)+void ConnectionFromClient::storage_area_write_acknowledged(Web::StorageAPI::StorageAreaId area_id){+ Web::StorageAPI::StorageAreaMirror::did_acknowledge_write(area_id);}-void ConnectionFromClient::storage_area_write_refused(Web::StorageAPI::StorageAreaId, Vector<Utf16String>, Vector<Utf16String>)+void ConnectionFromClient::storage_area_write_refused(Web::StorageAPI::StorageAreaId area_id, Vector<Utf16String> keys, Vector<Utf16String> values){+ Web::StorageAPI::StorageAreaMirror::did_refuse_write(area_id, move(keys), move(values));}-void ConnectionFromClient::storage_area_reset(Web::StorageAPI::StorageAreaId, Vector<Utf16String>, Vector<Utf16String>)+void ConnectionFromClient::storage_area_reset(Web::StorageAPI::StorageAreaId area_id, Vector<Utf16String> keys, Vector<Utf16String> values){+ Web::StorageAPI::StorageAreaMirror::did_reset(area_id, move(keys), move(values));}void ConnectionFromClient::inspect_dom_node(Web::PageId page_id, WebView::DOMNodeProperties::Type property_type, Web::UniqueNodeID node_id, Optional<Web::CSS::PseudoElement> pseudo_element, JsonValue options_value)diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.hindex 22886c1f3af..be206dab41a 100644--- a/Services/WebContent/ConnectionFromClient.h+++ b/Services/WebContent/ConnectionFromClient.h@@ -27,6 +27,7 @@#include <LibWeb/Loader/FileRequest.h>#include <LibWeb/Page/Page.h>#include <LibWeb/Platform/Timer.h>+#include <LibWeb/StorageAPI/StorageAreaMirror.h>#include <LibWebCommon/CSS/PreferredColorScheme.h>#include <LibWebCommon/CSS/PreferredContrast.h>#include <LibWebCommon/CSS/PreferredMotion.h>@@ -52,7 +53,8 @@namespace WebContent {class ConnectionFromClient final- : public IPC::ConnectionFromClient<WebContentClientEndpoint, WebContentServerEndpoint> {+ : public IPC::ConnectionFromClient<WebContentClientEndpoint, WebContentServerEndpoint>+ , public Web::StorageAPI::StorageAreaMirrorClient {C_OBJECT(ConnectionFromClient);friend class TestConnection;@@ -169,6 +171,13 @@ private:virtual void get_source(Web::PageId page_id) override;virtual void inspect_dom_tree(Web::PageId page_id) override;virtual void inspect_storage(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, u64 request_id) override;+ // Web::StorageAPI::StorageAreaMirrorClient: the mirrors' link to the browser process, which owns the storage.+ virtual Web::StorageAPI::StorageAreaConnection connect_to_storage_area(Web::PageId, Web::StorageAPI::StorageEndpointType, Web::HTML::EnvironmentId const&) override;+ virtual void disconnect_from_storage_area(Web::StorageAPI::StorageAreaId) override;+ virtual void set_storage_item(Web::StorageAPI::StorageAreaId, Utf16String const& key, Utf16String const& value, String const& document_url) override;+ virtual void remove_storage_item(Web::StorageAPI::StorageAreaId, Utf16String const& key, String const& document_url) override;+ virtual void clear_storage_area(Web::StorageAPI::StorageAreaId, String const& document_url) override;+virtual void storage_area_changed(Web::StorageAPI::StorageAreaId area_id, Optional<Utf16String> key, Optional<Utf16String> old_value, Optional<Utf16String> new_value, String url) override;virtual void storage_area_write_acknowledged(Web::StorageAPI::StorageAreaId area_id) override;virtual void storage_area_write_refused(Web::StorageAPI::StorageAreaId area_id, Vector<Utf16String> keys, Vector<Utf16String> values) override;diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex f8d14ab4387..01b95bfc759 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -1543,45 +1543,6 @@ bool PageClient::page_did_is_known_hsts_host(String const& domain)return response->result();}-Optional<Utf16String> PageClient::page_did_request_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& environment_id, Utf16String const& bottle_key)-{- auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::DidRequestStorageItem>(m_id, storage_endpoint, environment_id, bottle_key);- if (!response) {- dbgln("WebContent client disconnected during DidRequestStorageItem. Exiting peacefully.");- Core::Process::terminate_immediately(0);- }- return response->take_value();-}--WebView::StorageSetResult PageClient::page_did_set_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& environment_id, Utf16String const& bottle_key, Utf16String const& value)-{- auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::DidSetStorageItem>(m_id, storage_endpoint, environment_id, bottle_key, value);- if (!response) {- dbgln("WebContent client disconnected during DidSetStorageItem. Exiting peacefully.");- Core::Process::terminate_immediately(0);- }- return response->result();-}--void PageClient::page_did_remove_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& environment_id, Utf16String const& bottle_key)-{- auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::DidRemoveStorageItem>(m_id, storage_endpoint, environment_id, bottle_key);- if (!response) {- dbgln("WebContent client disconnected during DidRemoveStorageItem. Exiting peacefully.");- Core::Process::terminate_immediately(0);- }-}--Vector<Utf16String> PageClient::page_did_request_storage_keys(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& environment_id)-{- auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::DidRequestStorageKeys>(m_id, storage_endpoint, environment_id);- if (!response) {- dbgln("WebContent client disconnected during DidRequestStorageKeys. Exiting peacefully.");- Core::Process::terminate_immediately(0);- }- return response->take_keys();-}-u64 PageClient::page_did_request_storage_usage(Web::HTML::EnvironmentId const& environment_id){auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::DidRequestStorageUsage>(m_id, environment_id);@@ -1592,15 +1553,6 @@ u64 PageClient::page_did_request_storage_usage(Web::HTML::EnvironmentId const& ereturn response->usage();}-void PageClient::page_did_clear_storage(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& environment_id)-{- auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::DidClearStorage>(m_id, storage_endpoint, environment_id);- if (!response) {- dbgln("WebContent client disconnected during DidClearStorage. Exiting peacefully.");- Core::Process::terminate_immediately(0);- }-}-void PageClient::page_did_update_indexed_database(String const& url, Web::IndexedDB::TransactionChanges const& changes){if (!has_devtools_client())diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex 743a44ff476..4056475e4eb 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -299,12 +299,7 @@ private:virtual void page_did_simulate_worker_request_server_connection_loss() override;virtual void page_did_store_hsts_policy_for_testing(String const&, HTTP::HSTS::ParsedHSTSPolicy const&) override;virtual bool page_did_is_known_hsts_host(String const&) override;- virtual Optional<Utf16String> page_did_request_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& environment_id, Utf16String const& bottle_key) override;- virtual WebView::StorageSetResult page_did_set_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& environment_id, Utf16String const& bottle_key, Utf16String const& value) override;- virtual void page_did_remove_storage_item(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& environment_id, Utf16String const& bottle_key) override;- virtual Vector<Utf16String> page_did_request_storage_keys(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& environment_id) override;virtual u64 page_did_request_storage_usage(Web::HTML::EnvironmentId const& environment_id) override;- virtual void page_did_clear_storage(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& environment_id) override;virtual void page_did_update_indexed_database(String const& url, Web::IndexedDB::TransactionChanges const&) override;virtual void page_did_update_resource_count(i32) override;virtual NewWebViewResult page_did_request_new_web_view(Web::HTML::ActivateTab, Web::HTML::WebViewHints, Optional<Web::HTML::CrossProcessId> opener_navigable_id, Optional<URL::URL> opener_base_url, Utf16String const& target_name, Web::HTML::SandboxingFlagSet popup_sandboxing_flag_set) override;diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipcindex 0ba2c828e06..cbcdb423fc5 100644--- a/Services/WebContent/WebContentClient.ipc+++ b/Services/WebContent/WebContentClient.ipc@@ -197,11 +197,6 @@ endpoint WebContentClient routed by Web::PageId page_idrequest_audio_server_connection() => (Optional<IPC::TransportHandle> handle)request_video_presentation_channel() =|- [NotRouted] did_request_storage_item(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key) => (Optional<Utf16String> value)- [NotRouted] did_set_storage_item(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key, Utf16String value) => (WebView::StorageSetResult result)- did_remove_storage_item(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id, Utf16String bottle_key) => ()- [NotRouted] did_request_storage_keys(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id) => (Vector<Utf16String> keys)- did_clear_storage(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id) => ()[NotRouted] did_request_storage_usage(Web::PageId page_id, Web::HTML::EnvironmentId environment_id) => (u64 usage)[NotRouted] connect_to_storage_area(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id) => (Optional<Web::StorageAPI::StorageAreaId> area_id, Vector<Utf16String> keys, Vector<Utf16String> values, u64 usage)disconnect_from_storage_area(Web::StorageAPI::StorageAreaId area_id) =|diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txtindex 343ac476b8c..7e87ad400dd 100644--- a/Tests/LibWeb/CMakeLists.txt+++ b/Tests/LibWeb/CMakeLists.txt@@ -28,6 +28,7 @@ set(TEST_SOURCESTestSharedCompiledStyleSheet.cppTestSimpleRealm.cppTestSourceHighlighter.cpp+ TestStorageAreaMirror.cppTestStructuredSerializeCorpus.cppTestStructuredSerializeDurability.cppTestStructuredSerializeFormat.cpp@@ -63,6 +64,7 @@ endforeach()target_link_libraries(BenchmarkDisplayListRecording PRIVATE LibGC LibGfx LibIPC LibJS LibURL LibWebView)target_link_libraries(TestAudioWorkletPipe PRIVATE LibCore LibThreading)target_link_libraries(TestContentBlocker PRIVATE LibURL)+target_link_libraries(TestStorageAreaMirror PRIVATE LibURL LibWebCommon)target_link_libraries(TestFetchEngineMessages PRIVATE LibCore LibIPC LibRequests)target_link_libraries(TestFetchExecutor PRIVATE LibCore LibIPC LibThreading)if (NOT WIN32)diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex 2efb919d3aa..5694e2373e8 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -191,6 +191,7 @@ Text/input/wpt-import/html/webappapis/dynamic-markup-insertion/opening-the-inputText/input/localStorage.htmlText/input/HTML/local-storage-usage-after-nav.htmlText/input/HTML/storage-in-documents-created-without-a-fetch.html+Text/input/HTML/storage-shared-across-same-origin-frames.htmlText/input/wpt-import/webstorage/defineProperty.window.htmlText/input/wpt-import/webstorage/storage_enumerate.window.htmlText/input/wpt-import/webstorage/storage_local_setitem_quotaexceedederr.window.htmldiff --git a/Tests/LibWeb/TestStorageAreaMirror.cpp b/Tests/LibWeb/TestStorageAreaMirror.cppnew file mode 100644index 00000000000..93642ac031b--- /dev/null+++ b/Tests/LibWeb/TestStorageAreaMirror.cpp@@ -0,0 +1,383 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Vector.h>+#include <LibTest/TestCase.h>+#include <LibURL/Parser.h>+#include <LibWeb/StorageAPI/StorageAreaMirror.h>+#include <LibWebCommon/StorageAPI/StorageEndpoint.h>++using Web::StorageAPI::StorageAreaId;+using Web::StorageAPI::StorageAreaMirror;+using Web::StorageAPI::StorageEndpointType;++namespace {++struct Sent {+ enum class Kind : u8 {+ Connect,+ Disconnect,+ Set,+ Remove,+ Clear,+ };++ Kind kind;+ Optional<StorageAreaId> area_id;+ Utf16String key;+ Utf16String value;+ String url;+};++class FakeClient final : public Web::StorageAPI::StorageAreaMirrorClient {+public:+ Vector<Sent> sent;+ // What the next connect answers with.+ Vector<Utf16String> keys;+ Vector<Utf16String> values;+ u64 usage { 0 };+ bool detached { false };+ u64 next_id { 1 };++ virtual Web::StorageAPI::StorageAreaConnection connect_to_storage_area(Web::PageId, StorageEndpointType, Web::HTML::EnvironmentId const&) override+ {+ sent.append({ Sent::Kind::Connect, {}, {}, {}, {} });+ if (detached)+ return {};+ return { StorageAreaId { next_id++ }, keys, values, usage };+ }+ virtual void disconnect_from_storage_area(StorageAreaId area_id) override+ {+ sent.append({ Sent::Kind::Disconnect, area_id, {}, {}, {} });+ }+ virtual void set_storage_item(StorageAreaId area_id, Utf16String const& key, Utf16String const& value, String const& url) override+ {+ sent.append({ Sent::Kind::Set, area_id, key, value, url });+ }+ virtual void remove_storage_item(StorageAreaId area_id, Utf16String const& key, String const& url) override+ {+ sent.append({ Sent::Kind::Remove, area_id, key, {}, url });+ }+ virtual void clear_storage_area(StorageAreaId area_id, String const& url) override+ {+ sent.append({ Sent::Kind::Clear, area_id, {}, {}, url });+ }+};++struct Reported {+ Optional<Utf16String> key;+ Optional<Utf16String> old_value;+ Optional<Utf16String> new_value;+ String url;+};++struct Fixture {+ FakeClient client;+ StorageAreaMirror::Requester requester { Web::PageId { 1 }, Web::HTML::EnvironmentId::generate() };+ String const url = "https://a.example/page.html"_string;++ Fixture() { Web::StorageAPI::set_storage_area_mirror_client(&client); }+ ~Fixture() { Web::StorageAPI::set_storage_area_mirror_client(nullptr); }++ static Web::StorageAPI::StorageKey key_for(StringView origin)+ {+ return { URL::Parser::basic_parse(origin)->origin() };+ }++ NonnullRefPtr<StorageAreaMirror> mirror(StringView origin = "https://a.example"sv)+ {+ return StorageAreaMirror::obtain(StorageEndpointType::LocalStorage, {}, key_for(origin), Web::StorageAPI::StorageEndpoint::LOCAL_STORAGE_QUOTA);+ }++ static Vector<Reported>& record(StorageAreaMirror& mirror, Vector<Reported>& reports)+ {+ mirror.on_remote_change = [&reports](auto const& key, auto const& old_value, auto const& new_value, auto const& url) {+ reports.append({ key, old_value, new_value, url });+ };+ return reports;+ }+};++size_t count(Vector<Sent> const& sent, Sent::Kind kind)+{+ size_t n = 0;+ for (auto const& entry : sent)+ n += entry.kind == kind;+ return n;+}++}++TEST_CASE(prime_once_per_area_and_share_between_bottles)+{+ Fixture f;+ f.client.keys = { "a"_utf16 };+ f.client.values = { "1"_utf16 };+ f.client.usage = 2;++ auto first = f.mirror("https://shared.example"sv);+ auto second = f.mirror("https://shared.example"sv);+ EXPECT_EQ(first.ptr(), second.ptr());++ auto other_page = StorageAreaMirror::obtain(StorageEndpointType::SessionStorage, Web::PageId { 7 }, Fixture::key_for("https://shared.example"sv), {});+ EXPECT(other_page.ptr() != first.ptr());++ EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 0u);+ EXPECT_EQ(first->get(f.requester, "a"_utf16), Optional<Utf16String> { "1"_utf16 });+ EXPECT_EQ(second->size(f.requester), 1u);+ EXPECT_EQ(second->keys(f.requester), Vector { "a"_utf16 });+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 1u);+ EXPECT_EQ(first->quota_used(), 2u);+}++TEST_CASE(local_write_applies_sends_and_tracks_pending_until_acked)+{+ Fixture f;+ auto mirror = f.mirror("https://write.example"sv);++ auto result = mirror->set(f.requester, "k"_utf16, "v"_utf16, f.url);+ EXPECT(result.has<Optional<Utf16String>>());+ EXPECT_EQ(result.get<Optional<Utf16String>>(), Optional<Utf16String> {});+ EXPECT_EQ(mirror->get(f.requester, "k"_utf16), Optional<Utf16String> { "v"_utf16 });+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Set), 1u);+ EXPECT_EQ(f.client.sent.last().key, "k"_utf16);+ EXPECT_EQ(f.client.sent.last().value, "v"_utf16);+ EXPECT_EQ(f.client.sent.last().url, f.url);+ EXPECT_EQ(mirror->pending_write_count(), 1u);++ auto id = *f.client.sent.last().area_id;+ StorageAreaMirror::did_acknowledge_write(id);+ EXPECT_EQ(mirror->pending_write_count(), 0u);++ // Overwrite returns the old value; removal returns the removed value; clear reports whether there was anything.+ EXPECT_EQ(mirror->set(f.requester, "k"_utf16, "w"_utf16, f.url).get<Optional<Utf16String>>(), Optional<Utf16String> { "v"_utf16 });+ EXPECT_EQ(mirror->remove(f.requester, "k"_utf16, f.url), Optional<Utf16String> { "w"_utf16 });+ EXPECT_EQ(mirror->remove(f.requester, "k"_utf16, f.url), Optional<Utf16String> {});+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Remove), 1u);+ EXPECT(!mirror->clear(f.requester, f.url));+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Clear), 0u);+ mirror->set(f.requester, "k"_utf16, "v"_utf16, f.url);+ EXPECT(mirror->clear(f.requester, f.url));+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Clear), 1u);+ EXPECT_EQ(mirror->size(f.requester), 0u);+}++TEST_CASE(remote_changes_apply_except_over_pending_local_writes)+{+ Fixture f;+ f.client.keys = { "a"_utf16, "b"_utf16 };+ f.client.values = { "1"_utf16, "2"_utf16 };+ f.client.usage = 4;+ auto mirror = f.mirror("https://remote.example"sv);+ Vector<Reported> reports;+ Fixture::record(*mirror, reports);++ mirror->set(f.requester, "a"_utf16, "mine"_utf16, f.url);+ auto id = *f.client.sent.last().area_id;++ // The owner serialized this change before our pending write, so our mirror already reflects the later state.+ StorageAreaMirror::did_change(id, "a"_utf16, "1"_utf16, "theirs"_utf16, "https://remote.example/other.html"_string);+ EXPECT_EQ(mirror->get(f.requester, "a"_utf16), Optional<Utf16String> { "mine"_utf16 });+ EXPECT_EQ(reports.size(), 1u);+ EXPECT_EQ(reports[0].key, Optional<Utf16String> { "a"_utf16 });+ EXPECT_EQ(reports[0].new_value, Optional<Utf16String> { "theirs"_utf16 });+ EXPECT_EQ(reports[0].url, "https://remote.example/other.html"_string);++ // A change to another key applies.+ StorageAreaMirror::did_change(id, "b"_utf16, "2"_utf16, "3"_utf16, f.url);+ EXPECT_EQ(mirror->get(f.requester, "b"_utf16), Optional<Utf16String> { "3"_utf16 });+ StorageAreaMirror::did_change(id, "b"_utf16, "3"_utf16, {}, f.url);+ EXPECT_EQ(mirror->get(f.requester, "b"_utf16), Optional<Utf16String> {});+ EXPECT_EQ(reports.size(), 3u);++ StorageAreaMirror::did_acknowledge_write(id);+ StorageAreaMirror::did_change(id, "a"_utf16, "mine"_utf16, "later"_utf16, f.url);+ EXPECT_EQ(mirror->get(f.requester, "a"_utf16), Optional<Utf16String> { "later"_utf16 });++ // While a local clear is unacknowledged, every incoming change predates it.+ mirror->clear(f.requester, f.url);+ StorageAreaMirror::did_change(id, "c"_utf16, {}, "4"_utf16, f.url);+ StorageAreaMirror::did_change(id, {}, {}, {}, f.url);+ EXPECT_EQ(mirror->size(f.requester), 0u);+ EXPECT_EQ(reports.size(), 6u);+ StorageAreaMirror::did_acknowledge_write(id);+ StorageAreaMirror::did_change(id, "c"_utf16, {}, "4"_utf16, f.url);+ EXPECT_EQ(mirror->get(f.requester, "c"_utf16), Optional<Utf16String> { "4"_utf16 });+ EXPECT_EQ(mirror->quota_used(), 2u);+}++TEST_CASE(refusal_resets_to_the_snapshot_reapplies_pending_writes_and_reports_the_diff)+{+ Fixture f;+ auto mirror = f.mirror("https://refused.example"sv);+ Vector<Reported> reports;+ Fixture::record(*mirror, reports);++ mirror->set(f.requester, "big"_utf16, "xxxx"_utf16, f.url);+ auto id = *f.client.sent.last().area_id;+ mirror->set(f.requester, "b"_utf16, "2"_utf16, f.url);+ EXPECT_EQ(mirror->pending_write_count(), 2u);++ // The owner refused the first write; the snapshot shows what another process stored in the meantime.+ StorageAreaMirror::did_refuse_write(id, { "a"_utf16 }, { "1"_utf16 });++ EXPECT_EQ(mirror->get(f.requester, "big"_utf16), Optional<Utf16String> {});+ EXPECT_EQ(mirror->get(f.requester, "a"_utf16), Optional<Utf16String> { "1"_utf16 });+ EXPECT_EQ(mirror->get(f.requester, "b"_utf16), Optional<Utf16String> { "2"_utf16 });+ EXPECT_EQ(mirror->pending_write_count(), 1u);+ EXPECT_EQ(mirror->quota_used(), 4u);++ // Two keys changed from the mirror's point of view: the refused one vanished, and "a" appeared.+ EXPECT_EQ(reports.size(), 2u);+ bool saw_big = false;+ bool saw_a = false;+ for (auto const& report : reports) {+ if (report.key == Optional<Utf16String> { "big"_utf16 }) {+ saw_big = true;+ EXPECT_EQ(report.old_value, Optional<Utf16String> { "xxxx"_utf16 });+ EXPECT_EQ(report.new_value, Optional<Utf16String> {});+ }+ if (report.key == Optional<Utf16String> { "a"_utf16 }) {+ saw_a = true;+ EXPECT_EQ(report.old_value, Optional<Utf16String> {});+ EXPECT_EQ(report.new_value, Optional<Utf16String> { "1"_utf16 });+ }+ }+ EXPECT(saw_big);+ EXPECT(saw_a);++ // A reset from the browser takes the same path, with nothing pending to re-apply afterwards.+ StorageAreaMirror::did_acknowledge_write(id);+ StorageAreaMirror::did_reset(id, {}, {});+ EXPECT_EQ(mirror->size(f.requester), 0u);+ EXPECT_EQ(mirror->quota_used(), 0u);+}++// A script can queue thousands of writes in one task; their acknowledgments arrive after it yields. Each one has to be+// cheap, and a refusal in the middle of the stream replays only the writes the owner hasn't answered yet.+TEST_CASE(a_long_queue_of_pending_writes_drains_in_order_and_a_refusal_replays_only_the_outstanding_ones)+{+ Fixture f;+ auto mirror = f.mirror("https://queue.example"sv);+ Vector<Reported> reports;+ Fixture::record(*mirror, reports);++ constexpr size_t write_count = 5000;+ for (size_t i = 0; i < write_count; ++i)+ mirror->set(f.requester, Utf16String::number(i), "v"_utf16, f.url);+ EXPECT_EQ(mirror->pending_write_count(), write_count);+ auto id = *f.client.sent.last().area_id;++ for (size_t i = 0; i < write_count - 2; ++i)+ StorageAreaMirror::did_acknowledge_write(id);+ EXPECT_EQ(mirror->pending_write_count(), 2u);++ // The owner refused the second-to-last write and describes an empty bottle: everything acknowledged is gone from+ // it, and only the last write is still in flight on top.+ StorageAreaMirror::did_refuse_write(id, {}, {});+ EXPECT_EQ(mirror->pending_write_count(), 1u);+ EXPECT_EQ(mirror->size(f.requester), 1u);+ EXPECT_EQ(mirror->get(f.requester, Utf16String::number(write_count - 1)), Optional<Utf16String> { "v"_utf16 });+ EXPECT_EQ(mirror->get(f.requester, Utf16String::number(write_count - 2)), Optional<Utf16String> {});+ EXPECT_EQ(mirror->quota_used(), Web::StorageAPI::storage_quota_size(Utf16String::number(write_count - 1)) + Web::StorageAPI::storage_quota_size("v"_utf16));++ // The diff reports every acknowledged write as gone, and nothing for the one still pending.+ EXPECT_EQ(reports.size(), write_count - 1);++ StorageAreaMirror::did_acknowledge_write(id);+ EXPECT_EQ(mirror->pending_write_count(), 0u);+}++TEST_CASE(quota_used_matches_the_jar_rule_after_mixed_writes)+{+ Fixture f;+ auto mirror = f.mirror("https://quota.example"sv);+ auto size = [](Utf16String const& key, Utf16String const& value) {+ return Web::StorageAPI::storage_quota_size(key) + Web::StorageAPI::storage_quota_size(value);+ };++ mirror->set(f.requester, "k1"_utf16, "éé"_utf16, f.url);+ mirror->set(f.requester, "k2"_utf16, "value"_utf16, f.url);+ mirror->set(f.requester, "k1"_utf16, "x"_utf16, f.url);+ (void)mirror->remove(f.requester, "k2"_utf16, f.url);+ EXPECT_EQ(mirror->quota_used(), size("k1"_utf16, "x"_utf16));++ // A write that would exceed the quota is refused locally and leaves the mirror untouched.+ auto too_large = Utf16String::repeated('y', Web::StorageAPI::StorageEndpoint::LOCAL_STORAGE_QUOTA - 2);+ auto result = mirror->set(f.requester, "k3"_utf16, too_large, f.url);+ EXPECT(result.has<WebView::StorageOperationError>());+ EXPECT_EQ(mirror->get(f.requester, "k3"_utf16), Optional<Utf16String> {});+ EXPECT_EQ(mirror->quota_used(), size("k1"_utf16, "x"_utf16));+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Set), 3u);++ // One too large to ever fit is refused before the mirror is even primed.+ FakeClient fresh;+ Web::StorageAPI::set_storage_area_mirror_client(&fresh);+ auto unprimed = f.mirror("https://unprimed.example"sv);+ auto enormous = Utf16String::repeated('z', Web::StorageAPI::StorageEndpoint::LOCAL_STORAGE_QUOTA + 1);+ EXPECT(unprimed->set(f.requester, "k"_utf16, enormous, f.url).has<WebView::StorageOperationError>());+ EXPECT(fresh.sent.is_empty());+ Web::StorageAPI::set_storage_area_mirror_client(&f.client);+}++TEST_CASE(detached_mirror_reads_empty_and_refuses_writes)+{+ Fixture f;+ f.client.detached = true;+ auto mirror = f.mirror("https://detached.example"sv);++ EXPECT_EQ(mirror->size(f.requester), 0u);+ EXPECT_EQ(mirror->get(f.requester, "k"_utf16), Optional<Utf16String> {});+ EXPECT(mirror->set(f.requester, "k"_utf16, "v"_utf16, f.url).has<WebView::StorageOperationError>());+ EXPECT_EQ(mirror->remove(f.requester, "k"_utf16, f.url), Optional<Utf16String> {});+ EXPECT(!mirror->clear(f.requester, f.url));+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 1u);+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Set), 0u);+}++TEST_CASE(a_failed_connect_detaches_only_the_requester_it_failed_for)+{+ Fixture f;+ f.client.detached = true;+ auto mirror = f.mirror("https://partly.example"sv);+ StorageAreaMirror::Requester closing_page { Web::PageId { 9 }, Web::HTML::EnvironmentId::generate() };++ // A page the browser can't resolve (it's closing) reads empty and can't write; it isn't asked about again.+ EXPECT_EQ(mirror->size(closing_page), 0u);+ EXPECT(mirror->set(closing_page, "k"_utf16, "v"_utf16, f.url).has<WebView::StorageOperationError>());+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 1u);+ EXPECT_EQ(mirror->size(closing_page), 0u);+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 1u);++ // Another document of the origin in this process, which the browser does resolve, still gets its storage.+ f.client.detached = false;+ f.client.keys = { "a"_utf16 };+ f.client.values = { "1"_utf16 };+ f.client.usage = 2;+ EXPECT_EQ(mirror->get(f.requester, "a"_utf16), Optional<Utf16String> { "1"_utf16 });+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 2u);+ EXPECT(mirror->set(f.requester, "k"_utf16, "v"_utf16, f.url).has<Optional<Utf16String>>());+ // And once the mirror is connected, every requester reads it.+ EXPECT_EQ(mirror->size(closing_page), 2u);+}++TEST_CASE(the_last_bottle_disconnects_the_mirror)+{+ Fixture f;+ {+ auto mirror = f.mirror("https://lastbottle.example"sv);+ auto another = f.mirror("https://lastbottle.example"sv);+ mirror->size(f.requester);+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Disconnect), 0u);+ }+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Disconnect), 1u);++ // A mirror that was never primed has nothing to disconnect from.+ {+ auto never = f.mirror("https://never.example"sv);+ }+ EXPECT_EQ(count(f.client.sent, Sent::Kind::Disconnect), 1u);+}diff --git a/Tests/LibWeb/Text/expected/HTML/storage-shared-across-same-origin-frames.txt b/Tests/LibWeb/Text/expected/HTML/storage-shared-across-same-origin-frames.txtnew file mode 100644index 00000000000..a3b6099148b--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/storage-shared-across-same-origin-frames.txt@@ -0,0 +1,10 @@+child read session from-parent: s1+child read local from-parent: l1+parent read session from-child: s2+parent read local from-child: l2+parent session keys: from-child,from-parent+parent local keys: from-child,from-parent+child session keys: from-child,from-parent+child local keys: from-child,from-parent+child sees removal: null null+child session length after removal: 1diff --git a/Tests/LibWeb/Text/input/HTML/storage-shared-across-same-origin-frames.html b/Tests/LibWeb/Text/input/HTML/storage-shared-across-same-origin-frames.htmlnew file mode 100644index 00000000000..8e3deae75a1--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/storage-shared-across-same-origin-frames.html@@ -0,0 +1,48 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // Every bottle one page makes for a storage key has to answer from the same process-local cache — session storage+ // included, which is partitioned per page. So a same-origin iframe and its parent must see one session map and one+ // local map, in both directions and with no reload in between: a write in either frame is visible to a read in the+ // other, and so is a removal.+ asyncTest(done => {+ sessionStorage.clear();+ localStorage.clear();+ sessionStorage.setItem("from-parent", "s1");+ localStorage.setItem("from-parent", "l1");++ window.addEventListener("message", event => {+ const report = event.data;+ println("child read session from-parent: " + report.session);+ println("child read local from-parent: " + report.local);+ println("parent read session from-child: " + sessionStorage.getItem("from-child"));+ println("parent read local from-child: " + localStorage.getItem("from-child"));+ println("parent session keys: " + Object.keys(sessionStorage).sort().join(","));+ println("parent local keys: " + Object.keys(localStorage).sort().join(","));+ println("child session keys: " + report.sessionKeys);+ println("child local keys: " + report.localKeys);+ sessionStorage.removeItem("from-parent");+ localStorage.removeItem("from-parent");+ println("child sees removal: " + event.source.sessionStorage.getItem("from-parent") + " " + event.source.localStorage.getItem("from-parent"));+ println("child session length after removal: " + event.source.sessionStorage.length);+ sessionStorage.clear();+ localStorage.clear();+ done();+ });++ const iframe = document.createElement("iframe");+ iframe.srcdoc = `<script>+ const session = sessionStorage.getItem("from-parent");+ const local = localStorage.getItem("from-parent");+ sessionStorage.setItem("from-child", "s2");+ localStorage.setItem("from-child", "l2");+ parent.postMessage({+ session,+ local,+ sessionKeys: Object.keys(sessionStorage).sort().join(","),+ localKeys: Object.keys(localStorage).sort().join(","),+ }, "*");+ <\/script>`;+ document.body.appendChild(iframe);+ });+</script>