Truly independent web browser
Tests/LibWeb: Cover storage mirrors across processes and browser clears
sideshowbarker6117b0339bdd
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex c05f97925f5..bd05e40c8dc 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -113,6 +113,7 @@#include <LibWebCommon/Clipboard/SystemClipboard.h>#include <LibWebCommon/Page/DragEvent.h>#include <LibWebCommon/Page/InputEvent.h>+#include <LibWebCommon/StorageAPI/StorageEndpoint.h>namespace Web::Internals {@@ -1149,6 +1150,12 @@ void Internals::simulate_drop(double x, double y)page.handle_drag_and_drop_event(DragEvent::Type::Drop, position, position, UIEvents::MouseButton::Primary, 0, 0, {});}+void Internals::clear_storage_for_testing(Utf16String const& type)+{+ auto storage_endpoint = type == "session"_utf16 ? StorageAPI::StorageEndpointType::SessionStorage : StorageAPI::StorageEndpointType::LocalStorage;+ page().client().page_did_request_clear_storage_for_testing(storage_endpoint, window().associated_document().relevant_settings_object());+}+void Internals::expire_cookies_with_time_offset(WebIDL::LongLong seconds){page().client().page_did_expire_cookies_with_time_offset(AK::Duration::from_seconds(seconds));diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex feea0f5abac..2cd34685ffc 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -149,6 +149,7 @@ public:void simulate_drop(double x, double y);void expire_cookies_with_time_offset(WebIDL::LongLong seconds);+ void clear_storage_for_testing(Utf16String const& type);GC::Ref<WebIDL::Promise> delete_all_cookies();WebIDL::ExceptionOr<bool> has_cookie_for_url(Utf16String const& url, String const& name, String const& value);diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex 1c741c6b8bb..d5fc0ad41ce 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -143,6 +143,8 @@ interface Internals {undefined simulateDrop(double x, double y);undefined expireCookiesWithTimeOffset(long long seconds);+ // Clears this document's local ("local") or session ("session") storage the way the browser does, through its jar.+ undefined clearStorageForTesting(DOMString type);Promise<undefined> deleteAllCookies();boolean hasCookieForURL(DOMString url, ByteString name, ByteString value);diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.hindex bd0e4d397c4..95e069c6dba 100644--- a/Libraries/LibWeb/Page/Page.h+++ b/Libraries/LibWeb/Page/Page.h@@ -795,6 +795,7 @@ public:virtual void page_did_lose_request_server_connection() { }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 void page_did_request_clear_storage_for_testing(StorageAPI::StorageEndpointType, HTML::EnvironmentSettingsObject const&) { }virtual bool page_did_is_known_hsts_host(String const&) { return false; }virtual u64 page_did_request_storage_usage([[maybe_unused]] Web::HTML::EnvironmentId const& environment_id) { return {}; }diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cppindex b8f05e684c9..7f5260f6b4d 100644--- a/Libraries/LibWebView/WebContentPage.cpp+++ b/Libraries/LibWebView/WebContentPage.cpp@@ -1241,6 +1241,14 @@ void WebContentPage::did_request_document_cookie_version_index(Web::HTML::Enviro}}+void WebContentPage::clear_storage_for_testing(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId const& 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 e1626361579..889a86b4a88 100644--- a/Libraries/LibWebView/WebContentPage.h+++ b/Libraries/LibWebView/WebContentPage.h@@ -94,6 +94,8 @@ public:Optional<bool> hosted_environment_has_cross_site_ancestor(Web::HTML::EnvironmentId const& environment_id) const;bool hosts_an_environment_with_storage_key(Web::StorageAPI::StorageKey const&) const;void spoof_document_origin_for_testing(Web::HTML::EnvironmentId const& environment_id, URL::Origin);+ // Clears the bottle an environment of this page names, the way the browser's own clearing does: through the jar.+ void clear_storage_for_testing(Web::StorageAPI::StorageEndpointType, Web::HTML::EnvironmentId const&);// The process and page hosting the document of a navigable that a page represents. A page represents every// navigable of its tab whose document it does not host, so those are the ones it can ask to navigate or post to.RefPtr<WebContentPage> endpoint_hosting_navigable_represented_by(Web::HTML::CrossProcessId navigable_id) const;diff --git a/Libraries/LibWebView/WebContentTestClient.cpp b/Libraries/LibWebView/WebContentTestClient.cppindex e4abf3a64c3..5f9034e9d3e 100644--- a/Libraries/LibWebView/WebContentTestClient.cpp+++ b/Libraries/LibWebView/WebContentTestClient.cpp@@ -49,6 +49,12 @@ void WebContentTestClient::did_spoof_document_origin_for_testing(Web::PageId pagpage->spoof_document_origin_for_testing(environment_id, move(origin));}+void WebContentTestClient::did_request_clear_storage_for_testing(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id)+{+ if (auto* page = m_client.page(page_id))+ page->clear_storage_for_testing(storage_endpoint, environment_id);+}+void WebContentTestClient::did_store_hsts_policy_for_testing(String domain, HTTP::HSTS::ParsedHSTSPolicy policy){m_client.session().hsts_store->store_policy(domain, policy);diff --git a/Libraries/LibWebView/WebContentTestClient.h b/Libraries/LibWebView/WebContentTestClient.hindex 2c3eed90719..7026f180b93 100644--- a/Libraries/LibWebView/WebContentTestClient.h+++ b/Libraries/LibWebView/WebContentTestClient.h@@ -34,6 +34,7 @@ private:virtual void did_expire_cookies_with_time_offset(AK::Duration) override;virtual void did_spoof_document_origin_for_testing(Web::PageId, Web::HTML::EnvironmentId environment_id, URL::Origin) override;virtual void did_store_hsts_policy_for_testing(String domain, HTTP::HSTS::ParsedHSTSPolicy) override;+ virtual void did_request_clear_storage_for_testing(Web::PageId, Web::StorageAPI::StorageEndpointType, Web::HTML::EnvironmentId environment_id) override;virtual Messages::WebContentTestClient::DidRequestUiProcessSessionHistoryForTestingResponse did_request_ui_process_session_history_for_testing(Web::PageId page_id) override;virtual Messages::WebContentTestClient::DidRequestSiteIsolationProcessTreeForTestingResponse did_request_site_isolation_process_tree_for_testing(Web::PageId page_id) override;virtual Messages::WebContentTestClient::DidRequestHasPopulatedDocumentForTestingResponse did_request_has_populated_document_for_testing(Web::PageId page_id, Web::HTML::CrossProcessId navigable_id) override;diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cppindex 01b95bfc759..f3be63bdd0b 100644--- a/Services/WebContent/PageClient.cpp+++ b/Services/WebContent/PageClient.cpp@@ -1533,6 +1533,14 @@ void PageClient::page_did_store_hsts_policy_for_testing(String const& domain, HTtest_connection->did_store_hsts_policy_for_testing(domain, policy);}+void PageClient::page_did_request_clear_storage_for_testing(Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentSettingsObject const& environment)+{+ // Synchronous, so the browser has relayed the change before the page reads again; the mirror applies it once this+ // task yields, like any other change made elsewhere.+ if (auto* test_connection = client().test_connection())+ test_connection->did_request_clear_storage_for_testing(m_id, storage_endpoint, environment.id);+}+bool PageClient::page_did_is_known_hsts_host(String const& domain){auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::DidIsKnownHstsHost>(domain);diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.hindex 4056475e4eb..286b10bec53 100644--- a/Services/WebContent/PageClient.h+++ b/Services/WebContent/PageClient.h@@ -298,6 +298,7 @@ private:virtual void page_did_lose_request_server_connection() override;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 void page_did_request_clear_storage_for_testing(Web::StorageAPI::StorageEndpointType, Web::HTML::EnvironmentSettingsObject const&) override;virtual bool page_did_is_known_hsts_host(String const&) override;virtual u64 page_did_request_storage_usage(Web::HTML::EnvironmentId const& environment_id) override;virtual void page_did_update_indexed_database(String const& url, Web::IndexedDB::TransactionChanges const&) override;diff --git a/Services/WebContent/WebContentTestClient.ipc b/Services/WebContent/WebContentTestClient.ipcindex fb80f516702..db3e671e23c 100644--- a/Services/WebContent/WebContentTestClient.ipc+++ b/Services/WebContent/WebContentTestClient.ipc@@ -5,6 +5,7 @@#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>#include <LibWebCommon/HTML/SessionHistoryEntryDescriptor.h>#include <LibWebCommon/Page/PageId.h>+#include <LibWebCommon/StorageAPI/StorageEndpoint.h>endpoint WebContentTestClient routed by Web::PageId page_id{@@ -14,6 +15,7 @@ endpoint WebContentTestClient routed by Web::PageId page_iddid_expire_cookies_with_time_offset(AK::Duration offset) => ()did_store_hsts_policy_for_testing(String domain, HTTP::HSTS::ParsedHSTSPolicy policy) => ()+ [NotRouted] did_request_clear_storage_for_testing(Web::PageId page_id, Web::StorageAPI::StorageEndpointType storage_endpoint, Web::HTML::EnvironmentId environment_id) => ()did_simulate_worker_request_server_connection_loss(Web::PageId page_id) => ()[NotRouted] did_spoof_document_origin_for_testing(Web::PageId page_id, Web::HTML::EnvironmentId environment_id, URL::Origin origin) => ()diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.iniindex 5694e2373e8..6abc9a18868 100644--- a/Tests/LibWeb/TestConfig.ini+++ b/Tests/LibWeb/TestConfig.ini@@ -192,6 +192,7 @@ Text/input/localStorage.htmlText/input/HTML/local-storage-usage-after-nav.htmlText/input/HTML/storage-in-documents-created-without-a-fetch.htmlText/input/HTML/storage-shared-across-same-origin-frames.html+Text/input/HTML/storage-cleared-by-the-browser-reaches-the-open-page.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/Text/expected/HTML/storage-cleared-by-the-browser-reaches-the-open-page.txt b/Tests/LibWeb/Text/expected/HTML/storage-cleared-by-the-browser-reaches-the-open-page.txtnew file mode 100644index 00000000000..fe1cee8bf7b--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/storage-cleared-by-the-browser-reaches-the-open-page.txt@@ -0,0 +1,6 @@+before: local length 2, session length 1+after the browser clears local storage: length 0, a=null, session length 1+storage event: key=null oldValue=null newValue=null storageArea-is-localStorage=true+after the browser clears session storage: length 0, s=null+storage event: key=null storageArea-is-sessionStorage=true+clearing empty storage fires nothing: truediff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/storage-events-cross-processes.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/storage-events-cross-processes.txtindex 8ec99affacc..d02f453a208 100644--- a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/storage-events-cross-processes.txt+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/storage-events-cross-processes.txt@@ -4,9 +4,8 @@ peer saw key="a" oldValue="2" newValue=null url-is-actor=true storageArea-is-locpeer saw key="b" oldValue=null newValue="1" url-is-actor=true storageArea-is-localStorage=truepeer saw key=null oldValue=null newValue=null url-is-actor=true storageArea-is-localStorage=truepeer saw 5 events for 6 operations (one changed nothing)-racing writes: neither threw: true-racing writes: events in total: 2; on one side only: true-racing writes: accepted write seen once: true; its value: <3145728 chars>-racing writes: refused write reverted once: true; its old value: <3145728 chars>; storageArea is localStorage: true-racing writes: the loser's own window saw the revert: true-racing writes: one key kept: 1+racing writes: at most one write was refused outright: true+racing writes: exactly one 3 MiB key kept, and both sides agree on which: true+racing writes: the kept write reached the other side as one storage event: true+racing writes: a write the browser refused after its window accepted it was reverted there with a storage event, and nothing else was: true+racing writes: no other events: truediff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/storage-mirrors-stay-consistent-across-processes.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/storage-mirrors-stay-consistent-across-processes.txtnew file mode 100644index 00000000000..f0573ab0803--- /dev/null+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/storage-mirrors-stay-consistent-across-processes.txt@@ -0,0 +1,14 @@+peer initial: length 0+after actor sets a=1, peer sees length 1: a=1+after peer sets b=2, actor sees length 2: a=1,b=2+after actor overwrites a=3, peer sees length 2: a=3,b=2+after peer overwrites b=4, actor sees length 2: a=3,b=4+after actor removes a, peer sees length 1: b=4+after peer removes b, actor sees length 0+after actor sets c=5 and peer sets d=6, actor sees length 2: c=5,d=6+after actor sets c=5 and peer sets d=6, peer sees length 2: c=5,d=6+after peer clears, actor sees length 0+after actor sets e=7 then clears, peer sees length 0+after both write 3 MiB at once from stale mirrors, at most one write was refused outright: true+after both write 3 MiB at once from stale mirrors, actor keeps 1 key: a 3 MiB write+after both write 3 MiB at once from stale mirrors, peer agrees: truediff --git a/Tests/LibWeb/Text/input/HTML/storage-cleared-by-the-browser-reaches-the-open-page.html b/Tests/LibWeb/Text/input/HTML/storage-cleared-by-the-browser-reaches-the-open-page.htmlnew file mode 100644index 00000000000..d043e178f8f--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/storage-cleared-by-the-browser-reaches-the-open-page.html@@ -0,0 +1,38 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // A change the browser makes to web storage — clearing site data, a DevTools edit — has to reach a page that+ // already holds that storage, with no reload in between, and fire the storage event the change calls for: the+ // browser relays every change to every process mirroring the storage, whoever made it. The test hook clears this+ // page's bottle the way the browser's own clearing does, through the jar.+ asyncTest(async (done) => {+ localStorage.clear();+ sessionStorage.clear();+ localStorage.setItem("a", "1");+ localStorage.setItem("b", "2");+ sessionStorage.setItem("s", "3");+ println("before: local length " + localStorage.length + ", session length " + sessionStorage.length);++ const nextStorageEvent = () => new Promise((resolve) => addEventListener("storage", resolve, { once: true }));++ let event = nextStorageEvent();+ internals.clearStorageForTesting("local");+ let e = await event;+ println("after the browser clears local storage: length " + localStorage.length + ", a=" + localStorage.getItem("a") + ", session length " + sessionStorage.length);+ println("storage event: key=" + e.key + " oldValue=" + e.oldValue + " newValue=" + e.newValue + " storageArea-is-localStorage=" + (e.storageArea === localStorage));++ event = nextStorageEvent();+ internals.clearStorageForTesting("session");+ e = await event;+ println("after the browser clears session storage: length " + sessionStorage.length + ", s=" + sessionStorage.getItem("s"));+ println("storage event: key=" + e.key + " storageArea-is-sessionStorage=" + (e.storageArea === sessionStorage));++ // Clearing what is already empty changes nothing, so nothing is relayed and nothing fires.+ let fired = false;+ addEventListener("storage", () => { fired = true; }, { once: true });+ internals.clearStorageForTesting("local");+ await new Promise((resolve) => setTimeout(resolve, 0));+ println("clearing empty storage fires nothing: " + !fired);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/storage-events-cross-processes.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/storage-events-cross-processes.htmlindex 578ab4e421b..69d4cd564e5 100644--- a/Tests/LibWeb/Text/input/SiteIsolation/iframe/storage-events-cross-processes.html+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/storage-events-cross-processes.html@@ -37,7 +37,9 @@addEventListener("storage", (e) => channel.postMessage(describe(e)));channel.onmessage = (e) => {const command = e.data;- if (command.op === "setBig") {+ if (command.op === "keys") {+ channel.postMessage({ type: "keys", keys: Object.keys(localStorage).sort() });+ } else if (command.op === "setBig") {let threw = false;try {localStorage.setItem(command.key, "p".repeat(command.size));@@ -125,11 +127,14 @@peerEvents.length = 0;// Two writes that fit alone but not together, each made from a mirror that can't know about the- // other: the actor writes in the task that posts the peer's command, and that command reaches- // the peer ahead of the actor's change. So both are accepted locally, and the owner refuses- // whichever reaches it second. The loser's process then hears the refusal, falls back in line- // with the owner, and fires a storage event for the value that vanished — on the window that- // wrote it, which is the one that most needs to know.+ // other. The actor posts the peer's command and writes in the same task, so the command reaches+ // the peer ahead of the actor's change — but the peer handles the command in a queued task,+ // while a change is applied the moment it arrives, so the peer may or may not already see the+ // actor's write by then. Three outcomes are possible, and every line below holds in each: the+ // browser keeps exactly one of the two writes, both sides agree on which, and a write the+ // browser refused after its own window accepted it is reverted there with a storage event — on+ // the window that wrote it, which is the one that most needs to know. A "keys" round trip+ // settles both sides: it's handled after every change either side had in flight.const size = 3 * 1024 * 1024;const peerWritten = nextReply();channel.postMessage({ op: "setBig", key: "peerBig", size });@@ -140,17 +145,28 @@actorThrew = true;}const peerThrew = (await peerWritten).threw;- report("racing writes: neither threw: " + !(actorThrew || peerThrew));- await waitFor(() => peerEvents.length + ownEvents.length >= 2);- const events = [...peerEvents, ...ownEvents];+ channel.postMessage({ op: "keys" });+ const peerKeys = (await nextReply()).keys;+ const actorKeys = Object.keys(localStorage).sort();const bigKey = (key) => key === "actorBig" || key === "peerBig";- const accepted = events.filter((event) => bigKey(event.key) && event.newValue !== null);- const reverted = events.filter((event) => bigKey(event.key) && event.newValue === null);- report("racing writes: events in total: " + events.length + "; on one side only: " + (peerEvents.length === 0 || ownEvents.length === 0));- report("racing writes: accepted write seen once: " + (accepted.length === 1) + "; its value: " + accepted[0]?.newValue);- report("racing writes: refused write reverted once: " + (reverted.length === 1) + "; its old value: " + reverted[0]?.oldValue + "; storageArea is localStorage: " + reverted[0]?.isLocalStorage);- report("racing writes: the loser's own window saw the revert: " + (reverted.length === 1 && (reverted[0].key === "actorBig") === (ownEvents.includes(reverted[0]))));- report("racing writes: one key kept: " + localStorage.length);+ const actorBigKeys = actorKeys.filter(bigKey);+ const peerBigKeys = peerKeys.filter(bigKey);+ report("racing writes: at most one write was refused outright: " + !(actorThrew && peerThrew));+ report("racing writes: exactly one 3 MiB key kept, and both sides agree on which: " + (actorBigKeys.length === 1 && peerBigKeys.length === 1 && actorBigKeys[0] === peerBigKeys[0]));+ const kept = actorBigKeys[0];+ const accepted = [...peerEvents, ...ownEvents].filter((event) => bigKey(event.key) && event.newValue !== null);+ const reverted = [...peerEvents, ...ownEvents].filter((event) => bigKey(event.key) && event.newValue === null);+ const keptOnActor = kept === "actorBig";+ report("racing writes: the kept write reached the other side as one storage event: " + (accepted.length === 1 && accepted[0].key === kept && accepted[0].newValue === "<" + size + " chars>" && (keptOnActor ? peerEvents : ownEvents).includes(accepted[0])));+ // The other write was either refused outright by its own mirror (then nothing was ever applied,+ // and nothing reverts) or accepted there and refused by the browser (then its window reverts).+ const refusedOutright = actorThrew || peerThrew;+ const loserEvents = keptOnActor ? peerEvents : ownEvents;+ const revertedRight = refusedOutright+ ? reverted.length === 0+ : reverted.length === 1 && reverted[0].key !== kept && reverted[0].oldValue === "<" + size + " chars>" && reverted[0].isLocalStorage && loserEvents.includes(reverted[0]);+ report("racing writes: a write the browser refused after its window accepted it was reverted there with a storage event, and nothing else was: " + revertedRight);+ report("racing writes: no other events: " + (peerEvents.length + ownEvents.length === accepted.length + reverted.length));localStorage.clear();channel.postMessage({ op: "close" });diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/storage-mirrors-stay-consistent-across-processes.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/storage-mirrors-stay-consistent-across-processes.htmlnew file mode 100644index 00000000000..dd972103bc6--- /dev/null+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/storage-mirrors-stay-consistent-across-processes.html@@ -0,0 +1,186 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script>+ // Each process answers web storage from a mirror of it, and the browser relays every change to every other process+ // mirroring it. So two same-origin documents in two processes have to see each other's writes, overwrites,+ // removals, and clears on their next read, keys and length included. And a write a process accepts from a stale+ // mirror, but the browser then refuses, has to vanish from that process on its next read. The actor popup reports+ // each observation to this page, and drives the peer over a BroadcastChannel.+ //+ // The peer runs in a second process because it's opened with noopener on a cross-site trampoline host, and the+ // trampoline's navigation to the same-origin peer page is a cross-site top-level navigation in a browsing context+ // group of one — which site isolation hands to a new WebContent process. A popup's first navigation away from+ // about:blank stays in its opener's process, so opening the peer page directly would leave both in one process.+ asyncTest(async (done) => {+ const httpServer = httpTestServer();+ const host = uniqueLocalhostHostname("storage-cache");+ const runId = crypto.randomUUID();+ const channelName = `storage-cache-${runId}`;+ const htmlHeaders = { "Content-Type": "text/html" };++ const snapshotSource = `+ const snapshot = () => {+ const entries = [];+ for (let i = 0; i < localStorage.length; ++i) {+ const key = localStorage.key(i);+ entries.push(key + "=" + localStorage.getItem(key));+ }+ return "length " + localStorage.length + (entries.length ? ": " + entries.sort().join(",") : "");+ };+ const keys = () => {+ const names = [];+ for (let i = 0; i < localStorage.length; ++i)+ names.push(localStorage.key(i));+ return names.sort();+ };+ const trySet = (key, value) => {+ try {+ localStorage.setItem(key, value);+ return false;+ } catch {+ return true;+ }+ };`;++ const peerUrl = new URL(+ await httpServer.createEcho("GET", `/storage-cache-peer-${runId}`, {+ status: 200,+ headers: htmlHeaders,+ body: `<!DOCTYPE html><script>+ ${snapshotSource}+ const channel = new BroadcastChannel(${JSON.stringify(channelName)});+ channel.onmessage = (e) => {+ const command = e.data;+ if (command.op === "set")+ localStorage.setItem(command.key, command.value);+ else if (command.op === "remove")+ localStorage.removeItem(command.key);+ else if (command.op === "clear")+ localStorage.clear();+ else if (command.op === "setBig") {+ const threw = trySet(command.key, "p".repeat(command.size));+ return channel.postMessage({ type: "written", threw });+ }+ else if (command.op === "keys")+ return channel.postMessage({ type: "keys", keys: keys() });+ else if (command.op === "close")+ return window.close();+ channel.postMessage({ type: "snapshot", snapshot: snapshot() });+ };+ // Load this process's mirror before the actor writes anything: that copy is what has to be kept current.+ snapshot();+ channel.postMessage({ type: "ready" });+ <\/script>`,+ })+ );+ peerUrl.hostname = host;++ const trampolineUrl = new URL(+ await httpServer.createEcho("GET", `/storage-cache-trampoline-${runId}`, {+ status: 200,+ headers: htmlHeaders,+ body: `<!DOCTYPE html><script>location.replace(${JSON.stringify(peerUrl.href)});<\/script>`,+ })+ );+ trampolineUrl.hostname = uniqueLocalhostHostname("storage-cache-trampoline");++ const actorUrl = new URL(+ await httpServer.createEcho("GET", `/storage-cache-actor-${runId}`, {+ status: 200,+ headers: htmlHeaders,+ body: `<!DOCTYPE html><script>+ ${snapshotSource}+ const report = (line) => opener.postMessage(line, "*");+ const channel = new BroadcastChannel(${JSON.stringify(channelName)});+ const replies = [];+ let waiter = null;+ const wake = () => {+ if (waiter && waiter.ready()) {+ const resolve = waiter.resolve;+ waiter = null;+ resolve();+ }+ };+ const waitFor = (ready) => new Promise((resolve) => {+ waiter = { ready, resolve };+ wake();+ });+ channel.onmessage = (e) => {+ replies.push(e.data);+ wake();+ };+ const nextReply = async () => {+ await waitFor(() => replies.length > 0);+ return replies.shift();+ };+ const ask = async (command) => {+ channel.postMessage(command);+ return nextReply();+ };+ const peerSnapshot = async () => (await ask({ op: "snapshot" })).snapshot;+ (async () => {+ localStorage.clear();+ snapshot();+ window.open(${JSON.stringify(trampolineUrl.href)}, "_blank", "noopener");+ await nextReply();+ report("peer initial: " + await peerSnapshot());+ localStorage.setItem("a", "1");+ report("after actor sets a=1, peer sees " + await peerSnapshot());+ await ask({ op: "set", key: "b", value: "2" });+ report("after peer sets b=2, actor sees " + snapshot());+ localStorage.setItem("a", "3");+ report("after actor overwrites a=3, peer sees " + await peerSnapshot());+ await ask({ op: "set", key: "b", value: "4" });+ report("after peer overwrites b=4, actor sees " + snapshot());+ localStorage.removeItem("a");+ report("after actor removes a, peer sees " + await peerSnapshot());+ await ask({ op: "remove", key: "b" });+ report("after peer removes b, actor sees " + snapshot());+ localStorage.setItem("c", "5");+ await ask({ op: "set", key: "d", value: "6" });+ report("after actor sets c=5 and peer sets d=6, actor sees " + snapshot());+ report("after actor sets c=5 and peer sets d=6, peer sees " + await peerSnapshot());+ await ask({ op: "clear" });+ report("after peer clears, actor sees " + snapshot());+ localStorage.setItem("e", "7");+ localStorage.clear();+ report("after actor sets e=7 then clears, peer sees " + await peerSnapshot());+ // Two writes that fit alone but not together, each made from a mirror that can't know about the+ // other. The actor posts the peer's command and writes in the same task, so the command reaches+ // the peer ahead of the actor's change — but the peer handles the command in a queued task,+ // while a change is applied the moment it arrives, so the peer may or may not already see the+ // actor's write by then. Whichever way it goes, the browser keeps exactly one of the two writes+ // and both sides agree on which; the "keys" round trip settles both sides first, since it's+ // handled after every change either side had in flight.+ const size = 3 * 1024 * 1024;+ const peerWritten = ask({ op: "setBig", key: "peerBig", size });+ const actorThrew = trySet("actorBig", "a".repeat(size));+ const peerThrew = (await peerWritten).threw;+ const bothWrote = "after both write 3 MiB at once from stale mirrors, ";+ report(bothWrote + "at most one write was refused outright: " + !(actorThrew && peerThrew));+ const peerKeys = (await ask({ op: "keys" })).keys;+ const actorKeys = keys();+ const bigKeys = ["actorBig", "peerBig"];+ const kept = actorKeys.map((key) => (bigKeys.includes(key) ? "a 3 MiB write" : key));+ report(bothWrote + "actor keeps " + kept.length + " key: " + kept.join(","));+ report(bothWrote + "peer agrees: " + (peerKeys.join(",") === actorKeys.join(",")));+ channel.postMessage({ op: "close" });+ report("done");+ })();+ <\/script>`,+ })+ );+ actorUrl.hostname = host;++ let actor = null;+ addEventListener("message", (event) => {+ if (event.data === "done") {+ actor.close();+ done();+ return;+ }+ println(event.data);+ });+ actor = window.open(actorUrl);+ });+</script>