Skip to content

Truly independent web browser

20.0 KB
Raw Blame
/*
 * Copyright (c) 2024, Tim Ledbetter <[email protected]>
 * Copyright (c) 2024, Jamie Mansfield <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/NeverDestroyed.h>
#include <LibGC/Heap.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/Realm.h>
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/DOMURL/DOMURL.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/ServiceWorker/Job.h>
#include <LibWeb/ServiceWorker/Registration.h>
#include <LibWeb/ServiceWorker/ServiceWorker.h>
#include <LibWeb/ServiceWorker/ServiceWorkerContainer.h>
#include <LibWeb/ServiceWorker/ServiceWorkerRegistration.h>
#include <LibWeb/StorageAPI/StorageKey.h>
#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
#include <LibWeb/TrustedTypes/TrustedScriptURL.h>
#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>

namespace Web::ServiceWorker {

GC_DEFINE_ALLOCATOR(ServiceWorkerContainer);

struct ServiceWorkerContainerReadyPromiseCacheEntry {
    GC::Weak<ServiceWorkerContainer> container;
    Bindings::WrapperWorldWeakValueCache<WebIDL::Promise> ready_promises;
};

static Vector<ServiceWorkerContainerReadyPromiseCacheEntry>& service_worker_container_ready_promise_caches()
{
    static thread_local NeverDestroyed<Vector<ServiceWorkerContainerReadyPromiseCacheEntry>> caches;
    return *caches;
}

void clear_service_worker_container_ready_promise_caches()
{
    service_worker_container_ready_promise_caches().clear();
}

static void prune_service_worker_container_ready_promise_caches()
{
    service_worker_container_ready_promise_caches().remove_all_matching([](auto const& entry) {
        return !entry.container;
    });
}

static Bindings::WrapperWorldWeakValueCache<WebIDL::Promise>& ready_promise_cache_for(ServiceWorkerContainer& container)
{
    auto& caches = service_worker_container_ready_promise_caches();
    prune_service_worker_container_ready_promise_caches();

    for (auto& entry : caches) {
        if (entry.container.ptr() == GC::Ref { container })
            return entry.ready_promises;
    }

    caches.append(ServiceWorkerContainerReadyPromiseCacheEntry { container, {} });
    return caches.last().ready_promises;
}

static void resolve_service_worker_registration_promise(JS::Realm& realm, WebIDL::Promise& promise, GC::Ref<ServiceWorkerRegistration> registration)
{
    WebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, registration));
}

static void resolve_service_worker_registration_list_promise(JS::Realm& realm, WebIDL::Promise& promise, ReadonlySpan<GC::Ref<ServiceWorkerRegistration>> registrations)
{
    GC::RootVector<JS::Value> registration_values;
    for (auto registration : registrations)
        registration_values.append(Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, registration));

    auto array = JS::Array::create_from(realm, registration_values);
    MUST(array->set_integrity_level(JS::Object::IntegrityLevel::Frozen));
    WebIDL::resolve_promise(promise, array);
}

ServiceWorkerContainer::ServiceWorkerContainer(HTML::EnvironmentSettingsObject& service_worker_client)
    : DOM::EventTarget()
    , m_service_worker_client(service_worker_client)
{
}

ServiceWorkerContainer::~ServiceWorkerContainer() = default;

void ServiceWorkerContainer::visit_edges(Cell::Visitor& visitor)
{
    Base::visit_edges(visitor);
    visitor.visit(m_service_worker_client);
}

GC::Ref<ServiceWorkerContainer> ServiceWorkerContainer::create(HTML::EnvironmentSettingsObject& service_worker_client)
{
    return GC::Heap::the().allocate<ServiceWorkerContainer>(service_worker_client);
}

// https://w3c.github.io/ServiceWorker/#navigator-service-worker-controller
GC::Ptr<ServiceWorker> ServiceWorkerContainer::controller() const
{
    // 1. Let client be this's service worker client.
    // 2. If client's active service worker is null, then return null.
    // FIXME: Track the active service worker of a service worker client, and do the rest of these steps. Until then, no
    //        client has one.
    return nullptr;

    // 3. Return the result of getting the service worker object that represents client's active service worker in
    //    this's relevant settings object.
}

// https://w3c.github.io/ServiceWorker/#navigator-service-worker-ready
GC::Ref<WebIDL::Promise> ServiceWorkerContainer::ready()
{
    auto& realm = m_service_worker_client->realm();
    auto& wrapper_world = Bindings::host_defined_wrapper_world(realm);
    auto& cache = ready_promise_cache_for(*this);

    // 1. If this’s ready promise is null, then set this’s ready promise to a new promise.
    if (auto ready_promise = cache.get(wrapper_world))
        return *ready_promise;

    auto ready_promise = WebIDL::create_promise_for(m_service_worker_client);
    cache.set(wrapper_world, ready_promise);

    // 2. Let readyPromise be this’s ready promise.
    start_ready_promise_steps(ready_promise);

    // 4. Return readyPromise.
    return ready_promise;
}

// https://w3c.github.io/ServiceWorker/#navigator-service-worker-register
void ServiceWorkerContainer::register_(JS::Realm& realm, TrustedTypes::TrustedScriptURLOrString script_url, RegistrationOptions const& options, GC::Ref<WebIDL::Promise> promise)
{
    // Note: The register(scriptURL, options) method creates or updates a service worker registration for the given scope url.
    // If successful, a service worker registration ties the provided scriptURL to a scope url,
    // which is subsequently used for navigation matching.

    // 2. Set scriptURL to the result of invoking Get Trusted Type compliant string with TrustedScriptURL,
    //    this's relevant global object, scriptURL, "ServiceWorkerContainer register", and "script".
    auto const compliant_script_url = MUST(TrustedTypes::get_trusted_type_compliant_string(
        TrustedTypes::TrustedTypeName::TrustedScriptURL,
        m_service_worker_client->global_object(),
        script_url,
        TrustedTypes::InjectionSink::ServiceWorkerContainer_register,
        TrustedTypes::Script.view()));

    // 3 Let client be this's service worker client.
    auto client = m_service_worker_client;

    // 4. Let scriptURL be the result of parsing scriptURL with this's relevant settings object’s API base URL.
    auto base_url = m_service_worker_client->api_base_url();
    auto parsed_script_url = DOMURL::parse(compliant_script_url.utf16_view(), base_url);

    // 5. Let scopeURL be null.
    Optional<URL::URL> scope_url;

    // 6. If options["scope"] exists, set scopeURL to the result of parsing options["scope"] with this's relevant settings object’s API base URL.
    if (options.scope.has_value()) {
        scope_url = DOMURL::parse(options.scope->utf16_view(), base_url);
    }

    // 7. Invoke Start Register with scopeURL, scriptURL, p, client, client’s creation URL, options["type"], and options["updateViaCache"].
    start_register(realm, scope_url, parsed_script_url, promise, client, client->creation_url, options.type, options.update_via_cache);
}

// https://w3c.github.io/ServiceWorker/#navigator-service-worker-getRegistration
void ServiceWorkerContainer::get_registration(JS::Realm& realm, Utf16String const& client_url, GC::Ref<WebIDL::Promise> promise)
{
    // 1. Let client be this's service worker client.
    auto& client = service_worker_client();

    // 2. Let storage key be the result of running obtain a storage key given client.
    auto storage_key = StorageAPI::obtain_a_storage_key(client);

    // FIXME: Ad-Hoc. Spec should handle this failure.
    if (!storage_key.has_value()) {
        WebIDL::reject_promise(promise, JS::TypeError::create(realm, "Failed to obtain a storage key"sv));
        return;
    }

    // 3. Let clientURL be the result of parsing clientURL with this's relevant settings object’s API base URL.
    auto base_url = client.api_base_url();
    auto parsed_client_url = DOMURL::parse(client_url, base_url);

    // 4. If clientURL is failure, return a promise rejected with a TypeError.
    if (!parsed_client_url.has_value()) {
        WebIDL::reject_promise(promise, JS::TypeError::create(realm, "clientURL is not a valid URL"sv));
        return;
    }

    // 5. Set clientURL’s fragment to null.
    parsed_client_url->set_fragment({});

    // 6. If the origin of clientURL is not client’s origin, return a promise rejected with a "SecurityError" DOMException.
    if (!parsed_client_url->origin().is_same_origin(client.origin())) {
        WebIDL::reject_promise(promise, WebIDL::SecurityError::create(realm, "clientURL is not the same origin as the client's origin"_utf16));
        return;
    }

    // 8. Run the following substeps in parallel:
    Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(promise, storage_key, *parsed_client_url), [](auto& promise, auto& storage_key, auto& parsed_client_url) {
        auto& realm = HTML::relevant_realm(promise->promise());
        HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };

        // 1. Let registration be the result of running Match Service Worker Registration given storage key and clientURL.
        auto maybe_registration = Registration::match(storage_key.value(), parsed_client_url);

        // 2. If registration is null, resolve promise with undefined and abort these steps.
        if (!maybe_registration.has_value()) {
            WebIDL::resolve_promise(promise);
            return;
        }

        // 3. Resolve promise with the result of getting the service worker registration object that represents registration in promise’s relevant settings object.
        auto registration_object = HTML::relevant_settings_object(promise->promise()).get_service_worker_registration_object(maybe_registration.value());
        resolve_service_worker_registration_promise(realm, promise, registration_object);
    }));
}

// https://w3c.github.io/ServiceWorker/#navigator-service-worker-getRegistrations
void ServiceWorkerContainer::get_registrations(JS::Realm& realm, GC::Ref<WebIDL::Promise> promise)
{
    // 1. Let client be this's service worker client.
    auto& client = service_worker_client();

    // 2. Let client storage key be the result of running obtain a storage key given client.
    auto client_storage_key = StorageAPI::obtain_a_storage_key(client);

    if (!client_storage_key.has_value()) {
        WebIDL::reject_promise(promise, JS::TypeError::create(realm, "Failed to obtain a storage key"sv));
        return;
    }

    // 4. Run the following steps in parallel:
    Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(promise, client_storage_key.release_value()), [](auto& promise, auto& client_storage_key) {
        // 1. Let registrations be a new list.
        // 2. For each (storage key, scope) -> registration of registration map:
        //     1. If storage key equals client storage key, then append registration to registrations.
        auto registrations = Registration::for_storage_key(client_storage_key);

        GC::RootVector<GC::Ref<ServiceWorkerRegistration>> registration_objects;
        for (auto const* registration : registrations)
            registration_objects.append(HTML::relevant_settings_object(promise->promise()).get_service_worker_registration_object(*registration));

        // 3. Queue a task on promise's relevant settings object's responsible event loop, using the DOM manipulation task source, to run the following steps:
        HTML::queue_a_task(HTML::Task::Source::DOMManipulation, HTML::relevant_settings_object(promise->promise()).responsible_event_loop(), {}, GC::create_function(GC::Heap::the(), GC::captures(promise, move(registration_objects)), [](auto& promise, auto& registration_objects) {
            auto& realm = HTML::relevant_realm(promise->promise());
            HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };

            // 3. Resolve promise with a new frozen array of registrationObjects in promise's relevant Realm.
            resolve_service_worker_registration_list_promise(realm, promise, registration_objects);
        }));
    }));
}

// https://w3c.github.io/ServiceWorker/#start-register-algorithm
void ServiceWorkerContainer::start_register(JS::Realm& realm, Optional<URL::URL> scope_url,
    Optional<URL::URL> script_url, GC::Ref<WebIDL::Promise> promise,
    HTML::EnvironmentSettingsObject& client, URL::URL referrer, WorkerType worker_type,
    ServiceWorkerUpdateViaCache update_via_cache)
{
    auto& vm = realm.vm();

    // 1. If scriptURL is failure, reject promise with a TypeError and abort these steps.
    if (!script_url.has_value()) {
        WebIDL::reject_promise(promise, JS::TypeError::create(realm, "scriptURL is not a valid URL"_utf16));
        return;
    }

    // 2. Set scriptURL’s fragment to null.
    // Note:  The user agent does not store the fragment of the script’s url.
    //        This means that the fragment does not have an effect on identifying service workers.
    script_url->set_fragment({});

    // 3. If scriptURL’s scheme is not one of "http" and "https", reject promise with a TypeError and abort these steps.
    if (!script_url->scheme().is_one_of("http"sv, "https"sv)) {
        WebIDL::reject_promise(promise, JS::TypeError::create(realm, "scriptURL must have a scheme of 'http' or 'https'"_utf16));
        return;
    }

    // 4. If any of the strings in scriptURL’s path contains either ASCII case-insensitive "%2f" or ASCII case-insensitive "%5c",
    //    reject promise with a TypeError and abort these steps.
    auto is_invalid_path_segment = [](StringView path) {
        return path.contains("%2f"sv, CaseSensitivity::CaseInsensitive) || path.contains("%5c"sv, CaseSensitivity::CaseInsensitive);
    };
    if (any_of(script_url->path_segments(), is_invalid_path_segment)) {
        WebIDL::reject_promise(promise, JS::TypeError::create(realm, "scriptURL path must not contain '%2f' or '%5c'"_utf16));
        return;
    }

    // 5. If scopeURL is null, set scopeURL to the result of parsing the string "./" with scriptURL.
    // Note: The scope url for the registration is set to the location of the service worker script by default.
    if (!scope_url.has_value()) {
        scope_url = DOMURL::parse({ u"./", 2 }, script_url);
    }

    // 6. If scopeURL is failure, reject promise with a TypeError and abort these steps.
    if (!scope_url.has_value()) {
        WebIDL::reject_promise(promise, JS::TypeError::create(realm, "scopeURL is not a valid URL"_utf16));
        return;
    }

    // 7. Set scopeURL’s fragment to null.
    // Note: The user agent does not store the fragment of the scope url.
    //       This means that the fragment does not have an effect on identifying service worker registrations.
    scope_url->set_fragment({});

    // 8. If scopeURL’s scheme is not one of "http" and "https", reject promise with a TypeError and abort these steps.
    if (!scope_url->scheme().is_one_of("http"sv, "https"sv)) {
        WebIDL::reject_promise(promise, JS::TypeError::create(realm, "scopeURL must have a scheme of 'http' or 'https'"_utf16));
        return;
    }

    // 9. If any of the strings in scopeURL’s path contains either ASCII case-insensitive "%2f" or ASCII case-insensitive "%5c",
    //    reject promise with a TypeError and abort these steps.
    if (any_of(scope_url->path_segments(), is_invalid_path_segment)) {
        WebIDL::reject_promise(promise, JS::TypeError::create(realm, "scopeURL path must not contain '%2f' or '%5c'"_utf16));
        return;
    }

    // 10. Let storage key be the result of running obtain a storage key given client.
    auto storage_key = StorageAPI::obtain_a_storage_key(client);

    // FIXME: Ad-Hoc. Spec should handle this failure here, or earlier.
    if (!storage_key.has_value()) {
        WebIDL::reject_promise(promise, JS::TypeError::create(realm, "Failed to obtain a storage key"_utf16));
        return;
    }

    // 11. Let job be the result of running Create Job with register, storage key, scopeURL, scriptURL, promise, and client.
    auto job = Job::create(Job::Type::Register, storage_key.value(), scope_url.value(), script_url.release_value(), promise, client);

    // 12. Set job’s worker type to workerType.
    job->worker_type = worker_type;

    // 13. Set job’s update via cache to updateViaCache.
    job->update_via_cache = update_via_cache;

    // 14. Set job’s referrer to referrer.
    job->referrer = move(referrer);

    // 15. Invoke Schedule Job with job.
    schedule_job(vm, job);
}

// https://w3c.github.io/ServiceWorker/#navigator-service-worker-ready
void ServiceWorkerContainer::start_ready_promise_steps(GC::Ref<WebIDL::Promise> ready_promise)
{
    // 3. If readyPromise is pending, run the following substeps in parallel:
    Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, ready_promise), [](auto& self, auto& ready_promise) {
        // 1. Let client be this’s service worker client.
        auto client = self.m_service_worker_client;

        // 2. Let storage key be the result of running obtain a storage key given client.
        auto storage_key = StorageAPI::obtain_a_storage_key(client);
        if (!storage_key.has_value()) {
            // AD-HOC: Spec doesn't say what to do here, but we can't continue without a storage key.
            return;
        }

        // 3. Let registration be the result of running Match Service Worker Registration given storage key and client’s creation URL.
        auto maybe_registration = Registration::match(storage_key.value(), client->creation_url);

        // 4. If registration is not null, and registration’s active worker is not null, queue a task on
        //    readyPromise’s relevant settings object’s responsible event loop, using the DOM manipulation task source,
        //    to resolve readyPromise with the result of getting the service worker registration object that represents
        //    registration in readyPromise’s relevant settings object.
        if (maybe_registration.has_value() && maybe_registration->active_worker() != nullptr) {
            auto registration_object = HTML::relevant_settings_object(ready_promise->promise()).get_service_worker_registration_object(maybe_registration.value());
            queue_a_task(HTML::Task::Source::DOMManipulation, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(ready_promise, registration_object), [](auto& ready_promise, auto& registration_object) {
                auto& realm = HTML::relevant_realm(ready_promise->promise());
                HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
                resolve_service_worker_registration_promise(realm, ready_promise, registration_object);
            }));
        }
        // NOTE: The returned ready promise will never reject.
        //       If it does not resolve in this algorithm, it will eventually resolve when a matching service worker
        //       registration is registered and its active worker is set. (See the relevant Activate algorithm step.)
    }));
}

#undef __ENUMERATE
#define __ENUMERATE(attribute_name, event_name)                                    \
    void ServiceWorkerContainer::set_##attribute_name(WebIDL::CallbackType* value) \
    {                                                                              \
        set_event_handler_attribute(event_name, move(value));                      \
    }                                                                              \
    WebIDL::CallbackType* ServiceWorkerContainer::attribute_name()                 \
    {                                                                              \
        return event_handler_attribute(event_name);                                \
    }
ENUMERATE_SERVICE_WORKER_CONTAINER_EVENT_HANDLERS(__ENUMERATE)
#undef __ENUMERATE

}