Skip to content

Truly independent web browser

LibWeb+LibWebView: Limit session history entries and their states

Shannon Booth08390f1cccdf
diff --git a/Libraries/LibWeb/HTML/History.cpp b/Libraries/LibWeb/HTML/History.cpp
index 3a31952428a..655fbf0d7bb 100644
--- a/Libraries/LibWeb/HTML/History.cpp
+++ b/Libraries/LibWeb/HTML/History.cpp
@@ -178,7 +178,7 @@ WebIDL::ExceptionOr<void> History::shared_history_push_replace_state(JS::Realm&
return WebIDL::SecurityError::create("Cannot perform pushState or replaceState on a document that isn't fully active."_utf16);
// 3. Let serializedData be StructuredSerializeForStorage(data). Rethrow any exceptions.
- auto serialized_data = TRY(structured_serialize_for_storage(realm.vm(), data));
+ auto serialized_data = TRY(structured_serialize_session_history_state(realm.vm(), data));
// 4. Let newURL be document's URL.
auto new_url = document.url();
diff --git a/Libraries/LibWeb/HTML/Navigation.cpp b/Libraries/LibWeb/HTML/Navigation.cpp
index ff00436c5da..44257d08282 100644
--- a/Libraries/LibWeb/HTML/Navigation.cpp
+++ b/Libraries/LibWeb/HTML/Navigation.cpp
@@ -170,7 +170,7 @@ WebIDL::ExceptionOr<void> Navigation::update_current_entry(NavigationUpdateCurre
return WebIDL::InvalidStateError::create("Cannot update current NavigationHistoryEntry when there is no current entry"_utf16);
// 3. Let serializedState be StructuredSerializeForStorage(options["state"]), rethrowing any exceptions.
- auto serialized_state = TRY(structured_serialize_for_storage(window().principal_realm().vm(), options.state));
+ auto serialized_state = TRY(structured_serialize_session_history_state(window().principal_realm().vm(), options.state));
// 4. Set current's session history entry's navigation API state to serializedState.
current->session_history_entry().set_navigation_api_state(serialized_state);
@@ -272,7 +272,7 @@ WebIDL::ExceptionOr<NavigationResult> Navigation::navigate(Utf16String url, Bind
// error result for that exception.
// NOTE: It is important to perform this step early, since serialization can invoke web developer code, which in
// turn might change various things we check in later steps.
- auto serialized_state_or_error = structured_serialize_for_storage(realm.vm(), state);
+ auto serialized_state_or_error = structured_serialize_session_history_state(realm.vm(), state);
if (serialized_state_or_error.is_error()) {
return early_error_result(serialized_state_or_error.release_error());
}
@@ -334,7 +334,7 @@ WebIDL::ExceptionOr<NavigationResult> Navigation::reload_internal(NavigationRelo
// NOTE: It is important to perform this step early, since serialization can invoke web developer code, which in
// turn might change various things we check in later steps.
if (options.state.has_value()) {
- auto serialized_state_or_error = structured_serialize_for_storage(realm.vm(), *options.state);
+ auto serialized_state_or_error = structured_serialize_session_history_state(realm.vm(), *options.state);
if (serialized_state_or_error.is_error())
return early_error_result(serialized_state_or_error.release_error());
serialized_state = serialized_state_or_error.release_value();
diff --git a/Libraries/LibWeb/HTML/NavigationPrecommitController.cpp b/Libraries/LibWeb/HTML/NavigationPrecommitController.cpp
index 26f329f8c67..b630bece17d 100644
--- a/Libraries/LibWeb/HTML/NavigationPrecommitController.cpp
+++ b/Libraries/LibWeb/HTML/NavigationPrecommitController.cpp
@@ -80,7 +80,7 @@ WebIDL::ExceptionOr<void> NavigationPrecommitController::redirect(Utf16String co
if (options.state.has_value()) {
// 1. Let serializedState be the result of calling StructuredSerializeForStorage(options["state"]). This may
// throw an exception.
- auto serialized_state = TRY(structured_serialize_for_storage(window.principal_realm().vm(), *options.state));
+ auto serialized_state = TRY(structured_serialize_session_history_state(window.principal_realm().vm(), *options.state));
// 2. Set this's event's destination's state to serializedState.
m_event->destination()->set_state(serialized_state);
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.cpp b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
index eb234d0ad45..43e9d7065e0 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.cpp
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.cpp
@@ -14,6 +14,7 @@
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/WebIDL/DOMException.h>
+#include <LibWeb/WebIDL/QuotaExceededError.h>
namespace Web::HTML {
@@ -112,6 +113,18 @@ WebIDL::ExceptionOr<StorageSerializationRecord> structured_serialize_for_storage
return serialized;
}
+WebIDL::ExceptionOr<StorageSerializationRecord> structured_serialize_session_history_state(JS::VM& vm, JS::Value value)
+{
+ // AD-HOC: The spec puts no limit on the state a session history entry holds. But a navigable's same-origin entries
+ // go to its process in one message, states included, which must stay within what IPC can carry.
+ static constexpr size_t maximum_size = 16 * MiB;
+
+ auto serialized = TRY(structured_serialize_for_storage(vm, value));
+ if (serialized.data.size() > maximum_size)
+ return WebIDL::QuotaExceededError::create(Utf16String::formatted("Serialized state is {} bytes, more than the {} bytes a session history entry can hold", serialized.data.size(), maximum_size));
+ return serialized;
+}
+
// https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeforstorage
// NB: StructuredSerializeInternal returns undefined and null as primitives at step 4, which needs no VM.
StorageSerializationRecord structured_serialize_undefined_or_null_for_storage(JS::Value value)
diff --git a/Libraries/LibWeb/HTML/StructuredSerialize.h b/Libraries/LibWeb/HTML/StructuredSerialize.h
index 870ad419351..e0d3bae3a66 100644
--- a/Libraries/LibWeb/HTML/StructuredSerialize.h
+++ b/Libraries/LibWeb/HTML/StructuredSerialize.h
@@ -66,6 +66,8 @@ WEB_API WebIDL::ExceptionOr<IPCSerializationRecord> structured_serialize(JS::VM&
WEB_API WebIDL::ExceptionOr<StorageSerializationRecord> structured_serialize_for_storage(JS::VM&, JS::Value);
WEB_API StorageSerializationRecord structured_serialize_undefined_or_null_for_storage(JS::Value);
+WEB_API WebIDL::ExceptionOr<StorageSerializationRecord> structured_serialize_session_history_state(JS::VM&, JS::Value);
+
WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM&, IPCSerializationRecord const&, JS::Realm&);
WEB_API WebIDL::ExceptionOr<JS::Value> structured_deserialize(JS::VM&, StorageSerializationRecord const&, JS::Realm&);
diff --git a/Libraries/LibWebView/ApplyHistoryStep.cpp b/Libraries/LibWebView/ApplyHistoryStep.cpp
index 0dad65b3a6b..66f88f675fc 100644
--- a/Libraries/LibWebView/ApplyHistoryStep.cpp
+++ b/Libraries/LibWebView/ApplyHistoryStep.cpp
@@ -51,7 +51,7 @@ void ApplyHistoryStep::apply_the_history_step()
// FIXME: 1. Assert: This is running within traversable's session history traversal queue.
// 2. Let targetStep be the result of getting the used step given traversable and step.
- m_target_step = m_session_history.get_the_used_step(m_step).value();
+ m_target_step = m_session_history.get_the_used_step(m_step);
// 3. If initiatorToCheck is not null, then:
if (m_initiator_to_check.has_value()) {
@@ -301,7 +301,7 @@ void ApplyHistoryStep::process_changing_navigable_continuations()
// NB: targetStep was computed before the asynchronous parts of this algorithm. Re-normalize it in case a
// child navigable's removal made it unused meanwhile.
- m_target_step = m_session_history.get_the_used_step(m_step).value();
+ m_target_step = m_session_history.get_the_used_step(m_step);
auto& navigable = changing_navigable_continuation.navigable();
@@ -310,11 +310,13 @@ void ApplyHistoryStep::process_changing_navigable_continuations()
// job was paused, and can have taken that entry out of the session history: A replace (replaceState
// during a reload, e.g.) puts a new entry in its slot, and a push clears it away with the rest of the
// forward history (pushState during a forward traversal, or while a navigation's own new entry is still
- // ahead of the current step, e.g.). Activating such an entry gives its doc a navigation API entry list
+ // ahead of the current step, e.g.), or with the oldest steps when it caps the session history
+ // (pushState during a reload, e.g.). Activating such an entry gives its doc a navigation API entry list
// without the document's own entry in it, and leaves the navigable on an entry that the session history
// doesn't have. So this looks the target entry up again. A replacement in the claimed slot is the entry
- // to activate now. A traversal whose slot is gone is stale — the push that cleared the slot owns the
- // visible outcome. And a navigation whose new entry is gone appends it again, after the pushed entry.
+ // to activate now. A traversal or reload whose slot is gone is stale — the push that cleared the slot
+ // owns the visible outcome. And a navigation whose new entry is gone appends it again, after the pushed
+ // entry.
// See https://github.com/whatwg/html/issues/12961.
//
// Gecko/WebKit/Blink don't look a traversal's target up til the traversal runs, which is after any such
@@ -332,7 +334,7 @@ void ApplyHistoryStep::process_changing_navigable_continuations()
// NB: The job follows a replacement, so that the entry recorded as the navigable's active one is the
// entry as the session history has it.
changing_navigable_continuation.target_entry = *target_entry;
- } else if (m_navigation_type == Web::Bindings::NavigationType::Traverse) {
+ } else if (m_navigation_type == Web::Bindings::NavigationType::Traverse || m_navigation_type == Web::Bindings::NavigationType::Reload) {
return_result(Web::HTML::HistoryStepResult::Applied);
return;
} else if (m_navigation_type == Web::Bindings::NavigationType::Push) {
@@ -391,7 +393,7 @@ void ApplyHistoryStep::append_the_claimed_target_entry_again(CanonicalNavigable&
void ApplyHistoryStep::update_nonchanging_navigables()
{
// NB: targetStep is re-normalized once more; the continuation loop can have removed child navigables.
- m_target_step = m_session_history.get_the_used_step(m_step).value();
+ m_target_step = m_session_history.get_the_used_step(m_step);
// 17. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index
// given traversable and targetStep.
@@ -420,7 +422,7 @@ void ApplyHistoryStep::set_current_session_history_step()
// See https://github.com/whatwg/html/issues/12576.
if (m_generation > m_traversable_state.committed_generation) {
// 20. Set traversable's current session history step to targetStep.
- auto used_target_step = m_session_history.get_the_used_step(m_target_step).value();
+ auto used_target_step = m_session_history.get_the_used_step(m_target_step);
if (m_session_history.current_step() != used_target_step)
m_traversable_state.committed_generation = m_generation;
m_session_history.set_current_session_history_step(used_target_step);
diff --git a/Libraries/LibWebView/CanonicalTraversable.cpp b/Libraries/LibWebView/CanonicalTraversable.cpp
index 6a63a9842da..e4a347c6009 100644
--- a/Libraries/LibWebView/CanonicalTraversable.cpp
+++ b/Libraries/LibWebView/CanonicalTraversable.cpp
@@ -1058,8 +1058,8 @@ struct HistoryOperation {
Vector<NonnullRefPtr<WebContentPage>> completion_endpoints;
u64 sequence_number;
Optional<Web::HTML::CrossProcessId> beforeunload_check_id;
- // The view is showing a load for the top-level document this traversal has yet to activate.
- bool has_unactivated_traversal_load { false };
+ // The view is showing a load for the top-level document this operation has yet to activate.
+ bool has_unactivated_load { false };
ChangingNavigable* pending_changing_job(Web::HTML::CrossProcessId navigable_id) const
{
@@ -1266,7 +1266,7 @@ void CanonicalTraversable::recover_from_web_content_process_crash()
// The step a traversal the crash interrupted was applying is applied again, otherwise the current step is.
auto target_step = m_session_history.current_step();
if (auto* traversal = ongoing_browser_history_traversal())
- target_step = traversal->browser_traversal().target_step;
+ target_step = m_session_history.get_the_used_step(traversal->browser_traversal().target_step);
abandon_history_operations();
// The tab's document is reloaded, the crashed process having destroyed the one its entry holds. That reload never
@@ -1568,10 +1568,9 @@ bool CanonicalTraversable::run_changing_navigable_history_step_job(ApplyHistoryS
auto is_traversal_load = !is_reload && populates_target_entry_document && !operation.parameters.has<Web::FinalizeCrossDocumentNavigationHistoryOperationParameters>();
if (auto view = this->view(); view.has_value() && navigable.is_top_level_traversable() && (is_reload || is_traversal_load)) {
// NB: A traversal's load returns to a page already visited. A reload's visit transition is the reload's own.
- if (is_traversal_load) {
+ if (is_traversal_load)
view->set_next_history_visit_transition(HistoryVisitTransition::Restore);
- operation.has_unactivated_traversal_load = true;
- }
+ operation.has_unactivated_load = true;
// NB: A load a history operation starts, rather than a navigation, is tracked as the active document's.
clear_active_document_load();
@@ -1734,7 +1733,7 @@ void CanonicalTraversable::did_activate_history_entry(HistoryOperation& operatio
reload->value.activated = true;
}
if (navigable.is_top_level_traversable())
- operation.has_unactivated_traversal_load = false;
+ operation.has_unactivated_load = false;
auto const* replaced_document = &navigable.active_document();
// NB: The page that activated the document hosts it: the job's, which hosts the document the job populated, or else
// the navigable's.
@@ -2747,23 +2746,22 @@ void CanonicalTraversable::finish_history_operation(Web::HTML::CrossProcessId op
}
// The requesting page learns the result before the operation completes.
- if (result.has_value()) {
- if (operation->requesting_page)
- operation->requesting_page->async_history_step_applied(operation_id, *result);
- if (auto const* reload = operation->parameters.get_pointer<Web::ReloadHistoryOperationParameters>(); reload && result != Web::HTML::HistoryStepResult::Applied)
- did_not_apply_reload(reload->navigable_id, reload_navigation_id(operation_id));
+ if (result.has_value() && operation->requesting_page)
+ operation->requesting_page->async_history_step_applied(operation_id, *result);
+
+ // A load the operation began ends with it if the document it was for was never activated.
+ auto const* reload = operation->parameters.get_pointer<Web::ReloadHistoryOperationParameters>();
+ if (reload && ((result.has_value() && *result != Web::HTML::HistoryStepResult::Applied) || operation->has_unactivated_load)) {
+ did_not_apply_reload(reload->navigable_id, reload_navigation_id(operation_id));
+ } else if (operation->has_unactivated_load) {
+ if (auto view = this->view(); view.has_value())
+ view->did_not_activate_history_traversal_load();
}
// NB: A skipped or stale reload job can finish with "applied" without activating a document.
- if (auto reload = m_reload_navigation_ids.take(operation_id); reload.has_value() && !reload->activated) {
+ if (auto reload_navigation = m_reload_navigation_ids.take(operation_id); reload_navigation.has_value() && !reload_navigation->activated) {
if (auto* bidi = WebDriverBiDi::the())
- bidi->reload_did_not_apply(*this, reload->id);
- }
-
- // A load the traversal began ends with it if the document it was for was never activated.
- if (operation->has_unactivated_traversal_load) {
- if (auto view = this->view(); view.has_value())
- view->did_not_activate_history_traversal_load();
+ bidi->reload_did_not_apply(*this, reload_navigation->id);
}
auto committed_step = operation->algorithm ? operation->algorithm->committed_step() : Optional<i32> {};
@@ -2809,7 +2807,7 @@ void CanonicalTraversable::finish_history_operation(Web::HTML::CrossProcessId op
void CanonicalTraversable::abandon_browser_traversal_load()
{
auto* traversal = ongoing_browser_history_traversal();
- if (!traversal || !traversal->has_unactivated_traversal_load)
+ if (!traversal || !traversal->has_unactivated_load)
return;
// NB: Once the job has stopped populating, the displayed document may already be unloading.
@@ -2822,9 +2820,9 @@ void CanonicalTraversable::abandon_browser_traversal_load()
finish_history_operation(traversal->operation_id);
}
-bool CanonicalTraversable::has_unactivated_traversal_load() const
+bool CanonicalTraversable::has_unactivated_load() const
{
- return any_of(m_history_operations, [](auto const& entry) { return entry.value->has_unactivated_traversal_load; });
+ return any_of(m_history_operations, [](auto const& entry) { return entry.value->has_unactivated_load; });
}
void CanonicalTraversable::abandon_history_operations()
diff --git a/Libraries/LibWebView/CanonicalTraversable.h b/Libraries/LibWebView/CanonicalTraversable.h
index b3710f43498..bf984907f18 100644
--- a/Libraries/LibWebView/CanonicalTraversable.h
+++ b/Libraries/LibWebView/CanonicalTraversable.h
@@ -78,7 +78,7 @@ public:
void run_history_operation_at_queue_position(Web::HTML::CrossProcessId operation_id, Web::HistoryOperationParameters, RefPtr<WebContentPage> requesting_page, u64 sequence_number, RefPtr<CanonicalSessionHistoryEntry> target_entry, NonnullRefPtr<Core::Promise<Empty>>);
u64 next_sequence_number() { return m_next_sequence_number++; }
void abandon_history_operations();
- bool has_unactivated_traversal_load() const;
+ bool has_unactivated_load() const;
RefPtr<WebContentPage> page_hosting(CanonicalNavigable const&) const;
diff --git a/Libraries/LibWebView/SessionHistory.cpp b/Libraries/LibWebView/SessionHistory.cpp
index e4812907ad1..66a2bbf30f5 100644
--- a/Libraries/LibWebView/SessionHistory.cpp
+++ b/Libraries/LibWebView/SessionHistory.cpp
@@ -220,6 +220,46 @@ static void clear_forward_session_history_entries(Vector<NonnullRefPtr<Canonical
}
}
+// AD-HOC: The back counterpart of clearing the forward session history, which removes every step before step.
+// See: https://github.com/whatwg/html/issues/8620#issuecomment-1352745250
+static void clear_back_session_history_entries(Vector<NonnullRefPtr<CanonicalSessionHistoryEntry>>& entries, i32 step)
+{
+ // 1. Let entryLists be the ordered set « traversable's session history entries ».
+ Vector<Vector<NonnullRefPtr<CanonicalSessionHistoryEntry>>*> entry_lists { &entries };
+
+ // 2. For each entryList of entryLists:
+ while (!entry_lists.is_empty()) {
+ auto* entry_list = entry_lists.take_first();
+
+ // 1. Let shownEntry be the last session history entry of entryList that has a step less than or equal to
+ // step, if any.
+ RefPtr<CanonicalSessionHistoryEntry> shown_entry;
+ for (auto& entry : *entry_list) {
+ if (entry->step <= step)
+ shown_entry = entry;
+ }
+
+ // 2. Remove every session history entry other than shownEntry from entryList that has a step less than step.
+ entry_list->remove_all_matching([&](auto const& entry) {
+ return entry != shown_entry && entry->step < step;
+ });
+
+ // 3. If shownEntry is non-null, then set shownEntry's step to step.
+ if (shown_entry)
+ shown_entry->step = step;
+
+ // 4. For each entry of entryList:
+ for (auto& entry : *entry_list) {
+ // 1. For each nestedHistory of entry's document state's nested histories, append
+ // nestedHistory's entries list to entryLists.
+ for (auto& nested_history : entry->document_state->nested_histories) {
+ if (!entry_lists.contains_slow(&nested_history.entries))
+ entry_lists.append(&nested_history.entries);
+ }
+ }
+ }
+}
+
bool TraversableSessionHistory::initialize_for_testing(Vector<Web::HTML::SessionHistoryEntryDescriptor> entries, Vector<i32> used_steps, size_t current_used_step_index)
{
if (entries.is_empty() || current_used_step_index >= used_steps.size())
@@ -360,6 +400,11 @@ i32 TraversableSessionHistory::push_session_history_entry(CanonicalNavigable con
// NB: targetEntries is a list of this session history.
const_cast<Vector<NonnullRefPtr<CanonicalSessionHistoryEntry>>&>(*target_entries).append(move(entry));
+ // https://html.spec.whatwg.org/multipage/nav-history-apis.html#the-history-interface:implementation-defined
+ // Cap the session history to 50 steps. See: https://github.com/whatwg/html/issues/8620
+ if (auto steps = used_steps(); steps.size() > 50)
+ clear_back_session_history_entries(m_entries, steps[steps.size() - 50]);
+
return target_step;
}
@@ -412,7 +457,7 @@ size_t TraversableSessionHistory::current_top_level_entry_index() const
size_t TraversableSessionHistory::current_used_step_index() const
{
- return used_steps().find_first_index(get_the_used_step(m_current_session_history_step).value()).value();
+ return used_steps().find_first_index(get_the_used_step(m_current_session_history_step)).value();
}
Vector<DocumentStateLocalFileRoot> TraversableSessionHistory::local_file_roots_of_document_states() const
@@ -543,13 +588,17 @@ CanonicalSessionHistoryEntry* TraversableSessionHistory::top_level_entry_for_ste
}
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-used-step
-Optional<i32> TraversableSessionHistory::get_the_used_step(i32 step) const
+i32 TraversableSessionHistory::get_the_used_step(i32 step) const
{
// 1. Let steps be the result of getting all used history steps within traversable.
+ auto steps = used_steps();
+
// 2. Return the greatest item in steps that is less than or equal to step.
- Optional<i32> used_step;
- for (auto candidate : used_steps()) {
- if (candidate <= step && (!used_step.has_value() || candidate > *used_step))
+ // AD-HOC: Or the least item in steps, as clearing the back session history can remove every step up to step.
+ // See: https://github.com/whatwg/html/issues/8620
+ auto used_step = steps.first();
+ for (auto candidate : steps) {
+ if (candidate <= step)
used_step = candidate;
}
return used_step;
diff --git a/Libraries/LibWebView/SessionHistory.h b/Libraries/LibWebView/SessionHistory.h
index ff05b8d2789..96316008b51 100644
--- a/Libraries/LibWebView/SessionHistory.h
+++ b/Libraries/LibWebView/SessionHistory.h
@@ -72,7 +72,7 @@ public:
[[nodiscard]] bool has_only_top_level_used_steps() const;
[[nodiscard]] Optional<TraversalTarget> traversal_target_for_step(i32 step) const;
[[nodiscard]] Optional<Vector<NonnullRefPtr<CanonicalSessionHistoryEntry>> const&> get_session_history_entries(CanonicalNavigable const&) const;
- [[nodiscard]] Optional<i32> get_the_used_step(i32 step) const;
+ [[nodiscard]] i32 get_the_used_step(i32 step) const;
[[nodiscard]] CanonicalSessionHistoryEntry* get_the_target_history_entry(CanonicalNavigable const&, i32 step) const;
[[nodiscard]] Web::HTML::HistoryObjectLengthAndIndex get_the_history_object_length_and_index(i32 step) const;
[[nodiscard]] Optional<Vector<Web::HTML::SessionHistoryEntryDescriptor>> get_session_history_entries_for_the_navigation_api(CanonicalNavigable const&, i32 target_step) const;
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 90367317599..688a9287b4a 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -2343,10 +2343,6 @@ void WebContentPage::request_history_operation(Web::HTML::CrossProcessId operati
async_complete_history_operation(operation_id, {}, traversable().session_history().size());
return;
}
- if (auto const* resume = parameters.get_pointer<Web::ResumeTraverseHistoryOperationParameters>(); resume && !traversable().session_history().get_the_used_step(resume->target_step).has_value()) {
- client().did_misbehave("request_history_operation"sv, "resumed traversal to a step before every used step"sv);
- return;
- }
traversable().enqueue_history_operation(operation_id, move(parameters), *this);
}
@@ -3105,8 +3101,8 @@ void WebContentPage::did_finish_loading(Web::HTML::CrossProcessId navigable_id,
if (navigable->tracked_load_navigation_id() != navigable->active_document_load().navigation_id)
return;
- // NB: The document a traversal is fetching a replacement for does not finish the traversal's load.
- if (navigable->is_top_level_traversable() && traversable().has_unactivated_traversal_load())
+ // NB: The document a history operation is fetching a replacement for does not finish the operation's load.
+ if (navigable->is_top_level_traversable() && traversable().has_unactivated_load())
return;
navigable->clear_active_document_load();
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index ef6c5031b1f..04990dd313d 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -19,6 +19,8 @@ Text/input/HTML/HTMLObjectElement-window-stop-during-body.html
Text/input/wpt-import/html/semantics/embedded-content/the-embed-element/embed-ignored-in-media-element.html
Text/input/wpt-import/html/semantics/embedded-content/the-embed-element/embed-document.html
Text/input/wpt-import/html/semantics/embedded-content/the-embed-element/embed-in-object-fallback.html
+; A file: page has an opaque origin, so the navigation API gives it no entries to hold state.
+Text/input/HTML/session-history-state-size-limit.html
Text/input/MediaSession/active-session-duration.html
; Site-compatibility rules match the site of the page, and a file: page has none.
Text/input/Fetch/site-compatibility-user-agent-change-during-fetch.html
diff --git a/Tests/LibWeb/Text/expected/HTML/session-history-entry-limit.txt b/Tests/LibWeb/Text/expected/HTML/session-history-entry-limit.txt
new file mode 100644
index 00000000000..ae6a032c2e2
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/session-history-entry-limit.txt
@@ -0,0 +1,4 @@
+entries before this document's: 1
+history.length: 50
+history.state after going back: 59
+oldest entry: #11, history.state 11
diff --git a/Tests/LibWeb/Text/expected/HTML/session-history-state-size-limit.txt b/Tests/LibWeb/Text/expected/HTML/session-history-state-size-limit.txt
new file mode 100644
index 00000000000..fe47e581248
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/session-history-state-size-limit.txt
@@ -0,0 +1,8 @@
+pushState() with 1 MiB: stored
+pushState() with more than 16 MiB: QuotaExceededError
+replaceState() with more than 16 MiB: QuotaExceededError
+updateCurrentEntry() with 1 MiB: stored
+updateCurrentEntry() with more than 16 MiB: QuotaExceededError
+navigate() with more than 16 MiB: committed QuotaExceededError, finished QuotaExceededError
+history.state is the 1 MiB state: true
+location.hash: #small
diff --git a/Tests/LibWeb/Text/input/HTML/session-history-entry-limit.html b/Tests/LibWeb/Text/input/HTML/session-history-entry-limit.html
new file mode 100644
index 00000000000..3470fe0ebab
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/session-history-entry-limit.html
@@ -0,0 +1,25 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ function go(delta) {
+ const popstate = new Promise(resolve => addEventListener("popstate", resolve, { once: true }));
+ history.go(delta);
+ return popstate;
+ }
+
+ const startLength = history.length;
+ println(`entries before this document's: ${startLength - 1}`);
+ for (let i = 1; i <= 60; ++i)
+ history.pushState(i, "", `#${i}`);
+
+ // NB: Going back applies the history steps of every push before it.
+ await go(-1);
+ println(`history.length: ${history.length}`);
+ println(`history.state after going back: ${history.state}`);
+
+ await go(-(history.length - 2));
+ println(`oldest entry: ${location.hash}, history.state ${history.state}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/HTML/session-history-state-size-limit.html b/Tests/LibWeb/Text/input/HTML/session-history-state-size-limit.html
new file mode 100644
index 00000000000..62c6c3c5332
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/session-history-state-size-limit.html
@@ -0,0 +1,39 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ asyncTest(async done => {
+ const small = new ArrayBuffer(1024 * 1024);
+ const large = new ArrayBuffer(16 * 1024 * 1024 + 1);
+
+ function check(name, callback) {
+ try {
+ callback();
+ println(`${name}: stored`);
+ } catch (e) {
+ println(`${name}: ${e.name}`);
+ }
+ }
+
+ check("pushState() with 1 MiB", () => history.pushState(small, "", "#small"));
+ check("pushState() with more than 16 MiB", () => history.pushState(large, "", "#large"));
+ check("replaceState() with more than 16 MiB", () => history.replaceState(large, ""));
+ check("updateCurrentEntry() with 1 MiB", () => navigation.updateCurrentEntry({ state: small }));
+ check("updateCurrentEntry() with more than 16 MiB", () => navigation.updateCurrentEntry({ state: large }));
+
+ let result;
+ try {
+ result = navigation.navigate("#navigated", { state: large });
+ } catch (e) {
+ println(`FAIL: navigate() threw ${e.name} instead of rejecting its promises`);
+ }
+ if (result) {
+ const outcomes = await Promise.allSettled([result.committed, result.finished]);
+ const describe = outcome => outcome.status === "rejected" ? outcome.reason.name : "fulfilled";
+ println(`navigate() with more than 16 MiB: committed ${describe(outcomes[0])}, finished ${describe(outcomes[1])}`);
+ }
+
+ println(`history.state is the 1 MiB state: ${history.state instanceof ArrayBuffer && history.state.byteLength === small.byteLength}`);
+ println(`location.hash: ${location.hash}`);
+ done();
+ });
+</script>