Coverage Report

Created: 2026-02-14 08:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/serenity/Userland/Libraries/LibWeb/HTML/Scripting/Environments.cpp
Line
Count
Source
1
/*
2
 * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
3
 * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
4
 * Copyright (c) 2022, networkException <networkexception@serenityos.org>
5
 *
6
 * SPDX-License-Identifier: BSD-2-Clause
7
 */
8
9
#include <LibWeb/Bindings/MainThreadVM.h>
10
#include <LibWeb/DOM/Document.h>
11
#include <LibWeb/Fetch/Infrastructure/FetchRecord.h>
12
#include <LibWeb/HTML/PromiseRejectionEvent.h>
13
#include <LibWeb/HTML/Scripting/Environments.h>
14
#include <LibWeb/HTML/Scripting/ExceptionReporter.h>
15
#include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
16
#include <LibWeb/HTML/Window.h>
17
#include <LibWeb/HTML/WorkerGlobalScope.h>
18
#include <LibWeb/Page/Page.h>
19
#include <LibWeb/SecureContexts/AbstractOperations.h>
20
#include <LibWeb/StorageAPI/StorageManager.h>
21
22
namespace Web::HTML {
23
24
0
Environment::~Environment() = default;
25
26
void Environment::visit_edges(Cell::Visitor& visitor)
27
0
{
28
0
    Base::visit_edges(visitor);
29
0
    visitor.visit(target_browsing_context);
30
0
}
31
32
EnvironmentSettingsObject::EnvironmentSettingsObject(NonnullOwnPtr<JS::ExecutionContext> realm_execution_context)
33
0
    : m_realm_execution_context(move(realm_execution_context))
34
0
{
35
0
    m_realm_execution_context->context_owner = this;
36
37
    // Register with the responsible event loop so we can perform step 4 of "perform a microtask checkpoint".
38
0
    responsible_event_loop().register_environment_settings_object({}, *this);
39
0
}
40
41
EnvironmentSettingsObject::~EnvironmentSettingsObject()
42
0
{
43
0
    responsible_event_loop().unregister_environment_settings_object({}, *this);
44
0
}
45
46
void EnvironmentSettingsObject::initialize(JS::Realm& realm)
47
0
{
48
0
    Base::initialize(realm);
49
0
    m_module_map = realm.heap().allocate_without_realm<ModuleMap>();
50
0
}
51
52
void EnvironmentSettingsObject::visit_edges(Cell::Visitor& visitor)
53
0
{
54
0
    Base::visit_edges(visitor);
55
0
    visitor.visit(m_responsible_event_loop);
56
0
    visitor.visit(m_module_map);
57
0
    m_realm_execution_context->visit_edges(visitor);
58
0
    visitor.visit(m_fetch_group);
59
0
    visitor.visit(m_storage_manager);
60
0
}
61
62
JS::ExecutionContext& EnvironmentSettingsObject::realm_execution_context()
63
0
{
64
    // NOTE: All environment settings objects are created with a realm execution context, so it's stored and returned here in the base class.
65
0
    return *m_realm_execution_context;
66
0
}
67
68
ModuleMap& EnvironmentSettingsObject::module_map()
69
0
{
70
0
    return *m_module_map;
71
0
}
72
73
// https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object%27s-realm
74
JS::Realm& EnvironmentSettingsObject::realm()
75
0
{
76
    // An environment settings object's realm execution context's Realm component is the environment settings object's Realm.
77
0
    return *realm_execution_context().realm;
78
0
}
79
80
// https://html.spec.whatwg.org/multipage/webappapis.html#concept-settings-object-global
81
JS::Object& EnvironmentSettingsObject::global_object()
82
0
{
83
    // An environment settings object's Realm then has a [[GlobalObject]] field, which contains the environment settings object's global object.
84
0
    return realm().global_object();
85
0
}
86
87
// https://html.spec.whatwg.org/multipage/webappapis.html#responsible-event-loop
88
EventLoop& EnvironmentSettingsObject::responsible_event_loop()
89
0
{
90
    // An environment settings object's responsible event loop is its global object's relevant agent's event loop.
91
    // This is here in case the realm that is holding onto this ESO is destroyed before the ESO is. The responsible event loop pointer is needed in the ESO destructor to deregister from the event loop.
92
    // FIXME: Figure out why the realm can be destroyed before the ESO, as the realm is holding onto this with an OwnPtr, but the heap block deallocator calls the ESO destructor directly instead of through the realm destructor.
93
0
    if (m_responsible_event_loop)
94
0
        return *m_responsible_event_loop;
95
96
0
    auto& vm = global_object().vm();
97
0
    auto& event_loop = verify_cast<Bindings::WebEngineCustomData>(vm.custom_data())->event_loop;
98
0
    m_responsible_event_loop = event_loop;
99
0
    return *event_loop;
100
0
}
101
102
// https://html.spec.whatwg.org/multipage/webappapis.html#check-if-we-can-run-script
103
RunScriptDecision EnvironmentSettingsObject::can_run_script()
104
0
{
105
    // 1. If the global object specified by settings is a Window object whose Document object is not fully active, then return "do not run".
106
0
    if (is<HTML::Window>(global_object()) && !verify_cast<HTML::Window>(global_object()).associated_document().is_fully_active())
107
0
        return RunScriptDecision::DoNotRun;
108
109
    // 2. If scripting is disabled for settings, then return "do not run".
110
0
    if (is_scripting_disabled())
111
0
        return RunScriptDecision::DoNotRun;
112
113
    // 3. Return "run".
114
0
    return RunScriptDecision::Run;
115
0
}
116
117
// https://html.spec.whatwg.org/multipage/webappapis.html#prepare-to-run-script
118
void EnvironmentSettingsObject::prepare_to_run_script()
119
0
{
120
    // 1. Push settings's realm execution context onto the JavaScript execution context stack; it is now the running JavaScript execution context.
121
0
    global_object().vm().push_execution_context(realm_execution_context());
122
123
    // FIXME: 2. Add settings to the currently running task's script evaluation environment settings object set.
124
0
}
125
126
// https://html.spec.whatwg.org/multipage/webappapis.html#clean-up-after-running-script
127
void EnvironmentSettingsObject::clean_up_after_running_script()
128
0
{
129
0
    auto& vm = global_object().vm();
130
131
    // 1. Assert: settings's realm execution context is the running JavaScript execution context.
132
0
    VERIFY(&realm_execution_context() == &vm.running_execution_context());
133
134
    // 2. Remove settings's realm execution context from the JavaScript execution context stack.
135
0
    vm.pop_execution_context();
136
137
    // 3. If the JavaScript execution context stack is now empty, perform a microtask checkpoint. (If this runs scripts, these algorithms will be invoked reentrantly.)
138
0
    if (vm.execution_context_stack().is_empty())
139
0
        responsible_event_loop().perform_a_microtask_checkpoint();
140
0
}
141
142
static JS::ExecutionContext* top_most_script_having_execution_context(JS::VM& vm)
143
0
{
144
    // Here, the topmost script-having execution context is the topmost entry of the JavaScript execution context stack that has a non-null ScriptOrModule component,
145
    // or null if there is no such entry in the JavaScript execution context stack.
146
0
    auto execution_context = vm.execution_context_stack().last_matching([&](JS::ExecutionContext* context) {
147
0
        return !context->script_or_module.has<Empty>();
148
0
    });
149
150
0
    if (!execution_context.has_value())
151
0
        return nullptr;
152
153
0
    return execution_context.value();
154
0
}
155
156
// https://html.spec.whatwg.org/multipage/webappapis.html#prepare-to-run-a-callback
157
void EnvironmentSettingsObject::prepare_to_run_callback()
158
0
{
159
0
    auto& vm = global_object().vm();
160
161
    // 1. Push settings onto the backup incumbent settings object stack.
162
    // NOTE: The spec doesn't say which event loop's stack to put this on. However, all the examples of the incumbent settings object use iframes and cross browsing context communication to demonstrate the concept.
163
    //       This means that it must rely on some global state that can be accessed by all browsing contexts, which is the main thread event loop.
164
0
    HTML::main_thread_event_loop().push_onto_backup_incumbent_settings_object_stack({}, *this);
165
166
    // 2. Let context be the topmost script-having execution context.
167
0
    auto* context = top_most_script_having_execution_context(vm);
168
169
    // 3. If context is not null, increment context's skip-when-determining-incumbent counter.
170
0
    if (context)
171
0
        context->skip_when_determining_incumbent_counter++;
172
0
}
173
174
// https://html.spec.whatwg.org/multipage/urls-and-fetching.html#parse-a-url
175
URL::URL EnvironmentSettingsObject::parse_url(StringView url)
176
0
{
177
    // 1. Let encoding be document's character encoding, if document was given, and environment settings object's API URL character encoding otherwise.
178
    // FIXME: Pass in environment settings object's API URL character encoding.
179
180
    // 2. Let baseURL be document's base URL, if document was given, and environment settings object's API base URL otherwise.
181
0
    auto base_url = api_base_url();
182
183
    // 3. Let urlRecord be the result of applying the URL parser to url, with baseURL and encoding.
184
    // 4. If urlRecord is failure, then return failure.
185
    // 5. Let urlString be the result of applying the URL serializer to urlRecord.
186
    // 6. Return urlString as the resulting URL string and urlRecord as the resulting URL record.
187
0
    return base_url.complete_url(url);
188
0
}
189
190
// https://html.spec.whatwg.org/multipage/webappapis.html#clean-up-after-running-a-callback
191
void EnvironmentSettingsObject::clean_up_after_running_callback()
192
0
{
193
0
    auto& vm = global_object().vm();
194
195
    // 1. Let context be the topmost script-having execution context.
196
0
    auto* context = top_most_script_having_execution_context(vm);
197
198
    // 2. If context is not null, decrement context's skip-when-determining-incumbent counter.
199
0
    if (context)
200
0
        context->skip_when_determining_incumbent_counter--;
201
202
    // 3. Assert: the topmost entry of the backup incumbent settings object stack is settings.
203
0
    auto& event_loop = HTML::main_thread_event_loop();
204
0
    VERIFY(&event_loop.top_of_backup_incumbent_settings_object_stack() == this);
205
206
    // 4. Remove settings from the backup incumbent settings object stack.
207
0
    event_loop.pop_backup_incumbent_settings_object_stack({});
208
0
}
209
210
// https://html.spec.whatwg.org/multipage/webappapis.html#concept-environment-script
211
bool EnvironmentSettingsObject::is_scripting_enabled() const
212
0
{
213
    // Scripting is enabled for an environment settings object settings when all of the following conditions are true:
214
    // The user agent supports scripting.
215
    // NOTE: This is always true in LibWeb :^)
216
217
    // FIXME: Do the right thing for workers.
218
0
    if (!is<HTML::Window>(m_realm_execution_context->realm->global_object()))
219
0
        return true;
220
221
    // The user has not disabled scripting for settings at this time. (User agents may provide users with the option to disable scripting globally, or in a finer-grained manner, e.g., on a per-origin basis, down to the level of individual environment settings objects.)
222
0
    auto document = const_cast<EnvironmentSettingsObject&>(*this).responsible_document();
223
0
    VERIFY(document);
224
0
    if (!document->page().is_scripting_enabled())
225
0
        return false;
226
227
    // FIXME: Either settings's global object is not a Window object, or settings's global object's associated Document's active sandboxing flag set does not have its sandboxed scripts browsing context flag set.
228
229
0
    return true;
230
0
}
231
232
// https://html.spec.whatwg.org/multipage/webappapis.html#concept-environment-noscript
233
bool EnvironmentSettingsObject::is_scripting_disabled() const
234
0
{
235
    // Scripting is disabled for an environment settings object when scripting is not enabled for it, i.e., when any of the above conditions are false.
236
0
    return !is_scripting_enabled();
237
0
}
238
239
// https://html.spec.whatwg.org/multipage/webappapis.html#module-type-allowed
240
bool EnvironmentSettingsObject::module_type_allowed(StringView module_type) const
241
0
{
242
    // 1. If moduleType is not "javascript", "css", or "json", then return false.
243
0
    if (module_type != "javascript"sv && module_type != "css"sv && module_type != "json"sv)
244
0
        return false;
245
246
    // FIXME: 2. If moduleType is "css" and the CSSStyleSheet interface is not exposed in settings's Realm, then return false.
247
248
    // 3. Return true.
249
0
    return true;
250
0
}
251
252
// https://html.spec.whatwg.org/multipage/webappapis.html#disallow-further-import-maps
253
void EnvironmentSettingsObject::disallow_further_import_maps()
254
0
{
255
    // 1. Let global be settingsObject's global object.
256
0
    auto& global = global_object();
257
258
    // 2. If global does not implement Window, then return.
259
0
    if (!is<Window>(global))
260
0
        return;
261
262
    // 3. Set global's import maps allowed to false.
263
0
    verify_cast<Window>(global).set_import_maps_allowed(false);
264
0
}
265
266
// https://html.spec.whatwg.org/multipage/webappapis.html#incumbent-settings-object
267
EnvironmentSettingsObject& incumbent_settings_object()
268
0
{
269
0
    auto& event_loop = HTML::main_thread_event_loop();
270
0
    auto& vm = event_loop.vm();
271
272
    // 1. Let context be the topmost script-having execution context.
273
0
    auto* context = top_most_script_having_execution_context(vm);
274
275
    // 2. If context is null, or if context's skip-when-determining-incumbent counter is greater than zero, then:
276
0
    if (!context || context->skip_when_determining_incumbent_counter > 0) {
277
        // 1. Assert: the backup incumbent settings object stack is not empty.
278
        // NOTE: If this assertion fails, it's because the incumbent settings object was used with no involvement of JavaScript.
279
0
        VERIFY(!event_loop.is_backup_incumbent_settings_object_stack_empty());
280
281
        // 2. Return the topmost entry of the backup incumbent settings object stack.
282
0
        return event_loop.top_of_backup_incumbent_settings_object_stack();
283
0
    }
284
285
    // 3. Return context's Realm component's settings object.
286
0
    return Bindings::host_defined_environment_settings_object(*context->realm);
287
0
}
288
289
// https://html.spec.whatwg.org/multipage/webappapis.html#concept-incumbent-realm
290
JS::Realm& incumbent_realm()
291
0
{
292
    // Then, the incumbent Realm is the Realm of the incumbent settings object.
293
0
    return incumbent_settings_object().realm();
294
0
}
295
296
// https://html.spec.whatwg.org/multipage/webappapis.html#concept-incumbent-global
297
JS::Object& incumbent_global_object()
298
0
{
299
    // Similarly, the incumbent global object is the global object of the incumbent settings object.
300
0
    return incumbent_settings_object().global_object();
301
0
}
302
303
// https://html.spec.whatwg.org/multipage/webappapis.html#current-settings-object
304
EnvironmentSettingsObject& current_settings_object()
305
0
{
306
0
    auto& event_loop = HTML::main_thread_event_loop();
307
0
    auto& vm = event_loop.vm();
308
309
    // Then, the current settings object is the environment settings object of the current Realm Record.
310
0
    return Bindings::host_defined_environment_settings_object(*vm.current_realm());
311
0
}
312
313
// https://html.spec.whatwg.org/multipage/webappapis.html#current-global-object
314
JS::Object& current_global_object()
315
0
{
316
0
    auto& event_loop = HTML::main_thread_event_loop();
317
0
    auto& vm = event_loop.vm();
318
319
    // Similarly, the current global object is the global object of the current Realm Record.
320
0
    return vm.current_realm()->global_object();
321
0
}
322
323
// https://html.spec.whatwg.org/multipage/webappapis.html#concept-relevant-realm
324
JS::Realm& relevant_realm(JS::Object const& object)
325
0
{
326
    // The relevant Realm for a platform object is the value of its [[Realm]] field.
327
0
    return object.shape().realm();
328
0
}
329
330
// https://html.spec.whatwg.org/multipage/webappapis.html#relevant-settings-object
331
EnvironmentSettingsObject& relevant_settings_object(JS::Object const& object)
332
0
{
333
    // Then, the relevant settings object for a platform object o is the environment settings object of the relevant Realm for o.
334
0
    return Bindings::host_defined_environment_settings_object(relevant_realm(object));
335
0
}
336
337
EnvironmentSettingsObject& relevant_settings_object(DOM::Node const& node)
338
0
{
339
    // Then, the relevant settings object for a platform object o is the environment settings object of the relevant Realm for o.
340
0
    return const_cast<DOM::Document&>(node.document()).relevant_settings_object();
341
0
}
342
343
// https://html.spec.whatwg.org/multipage/webappapis.html#concept-relevant-global
344
JS::Object& relevant_global_object(JS::Object const& object)
345
0
{
346
    // Similarly, the relevant global object for a platform object o is the global object of the relevant Realm for o.
347
0
    return relevant_realm(object).global_object();
348
0
}
349
350
// https://html.spec.whatwg.org/multipage/webappapis.html#concept-entry-realm
351
JS::Realm& entry_realm()
352
0
{
353
0
    auto& event_loop = HTML::main_thread_event_loop();
354
0
    auto& vm = event_loop.vm();
355
356
    // With this in hand, we define the entry execution context to be the most recently pushed item in the JavaScript execution context stack that is a realm execution context.
357
    // The entry realm is the entry execution context's Realm component.
358
    // NOTE: Currently all execution contexts in LibJS are realm execution contexts
359
0
    return *vm.running_execution_context().realm;
360
0
}
361
362
// https://html.spec.whatwg.org/multipage/webappapis.html#entry-settings-object
363
EnvironmentSettingsObject& entry_settings_object()
364
0
{
365
    // Then, the entry settings object is the environment settings object of the entry realm.
366
0
    return Bindings::host_defined_environment_settings_object(entry_realm());
367
0
}
368
369
// https://html.spec.whatwg.org/multipage/webappapis.html#entry-global-object
370
JS::Object& entry_global_object()
371
0
{
372
    // Similarly, the entry global object is the global object of the entry realm.
373
0
    return entry_realm().global_object();
374
0
}
375
376
JS::VM& relevant_agent(JS::Object const& object)
377
0
{
378
    // The relevant agent for a platform object platformObject is platformObject's relevant Realm's agent.
379
    // Spec Note: This pointer is not yet defined in the JavaScript specification; see tc39/ecma262#1357.
380
0
    return relevant_realm(object).vm();
381
0
}
382
383
// https://html.spec.whatwg.org/multipage/webappapis.html#secure-context
384
bool is_secure_context(Environment const& environment)
385
0
{
386
    // 1. If environment is an environment settings object, then:
387
0
    if (is<EnvironmentSettingsObject>(environment)) {
388
        // 1. Let global be environment's global object.
389
        // FIXME: Add a const global_object() getter to ESO
390
0
        auto& global = static_cast<EnvironmentSettingsObject&>(const_cast<Environment&>(environment)).global_object();
391
392
        // 2. If global is a WorkerGlobalScope, then:
393
0
        if (is<WorkerGlobalScope>(global)) {
394
            // FIXME: 1. If global's owner set[0]'s relevant settings object is a secure context, then return true.
395
            // NOTE: We only need to check the 0th item since they will necessarily all be consistent.
396
397
            // 2. Return false.
398
0
            return false;
399
0
        }
400
401
        // FIXME: 3. If global is a WorkletGlobalScope, then return true.
402
        // NOTE: Worklets can only be created in secure contexts.
403
0
    }
404
405
    // 2. If the result of Is url potentially trustworthy? given environment's top-level creation URL is "Potentially Trustworthy", then return true.
406
0
    if (SecureContexts::is_url_potentially_trustworthy(environment.top_level_creation_url) == SecureContexts::Trustworthiness::PotentiallyTrustworthy)
407
0
        return true;
408
409
    // 3. Return false.
410
0
    return false;
411
0
}
412
413
// https://html.spec.whatwg.org/multipage/webappapis.html#non-secure-context
414
bool is_non_secure_context(Environment const& environment)
415
0
{
416
    // An environment is a non-secure context if it is not a secure context.
417
0
    return !is_secure_context(environment);
418
0
}
419
420
SerializedEnvironmentSettingsObject EnvironmentSettingsObject::serialize()
421
0
{
422
0
    SerializedEnvironmentSettingsObject object;
423
424
0
    object.id = this->id;
425
0
    object.creation_url = this->creation_url;
426
0
    object.top_level_creation_url = this->top_level_creation_url;
427
0
    object.top_level_origin = this->top_level_origin;
428
429
0
    object.api_url_character_encoding = api_url_character_encoding();
430
0
    object.api_base_url = api_base_url();
431
0
    object.origin = origin();
432
0
    object.policy_container = policy_container();
433
0
    object.cross_origin_isolated_capability = cross_origin_isolated_capability();
434
435
0
    return object;
436
0
}
437
438
JS::NonnullGCPtr<StorageAPI::StorageManager> EnvironmentSettingsObject::storage_manager()
439
0
{
440
0
    if (!m_storage_manager)
441
0
        m_storage_manager = realm().heap().allocate<StorageAPI::StorageManager>(realm(), realm());
442
0
    return *m_storage_manager;
443
0
}
444
445
}