WindowOrWorkerGlobalScope.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /*
  2. * Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
  3. * Copyright (c) 2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Base64.h>
  8. #include <AK/String.h>
  9. #include <AK/Utf8View.h>
  10. #include <AK/Vector.h>
  11. #include <LibTextCodec/Decoder.h>
  12. #include <LibWeb/Bindings/MainThreadVM.h>
  13. #include <LibWeb/Fetch/FetchMethod.h>
  14. #include <LibWeb/Forward.h>
  15. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  16. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  17. #include <LibWeb/HTML/Scripting/Environments.h>
  18. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  19. #include <LibWeb/HTML/StructuredSerialize.h>
  20. #include <LibWeb/HTML/Timer.h>
  21. #include <LibWeb/HTML/Window.h>
  22. #include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
  23. #include <LibWeb/Infra/Base64.h>
  24. #include <LibWeb/WebIDL/AbstractOperations.h>
  25. #include <LibWeb/WebIDL/DOMException.h>
  26. #include <LibWeb/WebIDL/ExceptionOr.h>
  27. namespace Web::HTML {
  28. WindowOrWorkerGlobalScopeMixin::~WindowOrWorkerGlobalScopeMixin() = default;
  29. void WindowOrWorkerGlobalScopeMixin::visit_edges(JS::Cell::Visitor& visitor)
  30. {
  31. for (auto& it : m_timers)
  32. visitor.visit(it.value);
  33. }
  34. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-origin
  35. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::origin() const
  36. {
  37. auto& vm = this_impl().vm();
  38. // The origin getter steps are to return this's relevant settings object's origin, serialized.
  39. return TRY_OR_THROW_OOM(vm, String::from_deprecated_string(relevant_settings_object(this_impl()).origin().serialize()));
  40. }
  41. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-issecurecontext
  42. bool WindowOrWorkerGlobalScopeMixin::is_secure_context() const
  43. {
  44. // The isSecureContext getter steps are to return true if this's relevant settings object is a secure context, or false otherwise.
  45. return HTML::is_secure_context(relevant_settings_object(this_impl()));
  46. }
  47. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-crossoriginisolated
  48. bool WindowOrWorkerGlobalScopeMixin::cross_origin_isolated() const
  49. {
  50. // The crossOriginIsolated getter steps are to return this's relevant settings object's cross-origin isolated capability.
  51. return relevant_settings_object(this_impl()).cross_origin_isolated_capability() == CanUseCrossOriginIsolatedAPIs::Yes;
  52. }
  53. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
  54. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::btoa(String const& data) const
  55. {
  56. auto& vm = this_impl().vm();
  57. auto& realm = *vm.current_realm();
  58. // The btoa(data) method must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF.
  59. Vector<u8> byte_string;
  60. byte_string.ensure_capacity(data.bytes().size());
  61. for (u32 code_point : Utf8View(data)) {
  62. if (code_point > 0xff)
  63. return WebIDL::InvalidCharacterError::create(realm, "Data contains characters outside the range U+0000 and U+00FF");
  64. byte_string.append(code_point);
  65. }
  66. // Otherwise, the user agent must convert data to a byte sequence whose nth byte is the eight-bit representation of the nth code point of data,
  67. // and then must apply forgiving-base64 encode to that byte sequence and return the result.
  68. return TRY_OR_THROW_OOM(vm, encode_base64(byte_string.span()));
  69. }
  70. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
  71. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::atob(String const& data) const
  72. {
  73. auto& vm = this_impl().vm();
  74. auto& realm = *vm.current_realm();
  75. // 1. Let decodedData be the result of running forgiving-base64 decode on data.
  76. auto decoded_data = Infra::decode_forgiving_base64(data.bytes_as_string_view());
  77. // 2. If decodedData is failure, then throw an "InvalidCharacterError" DOMException.
  78. if (decoded_data.is_error())
  79. return WebIDL::InvalidCharacterError::create(realm, "Input string is not valid base64 data");
  80. // 3. Return decodedData.
  81. // decode_base64() returns a byte string. LibJS uses UTF-8 for strings. Use Latin1Decoder to convert bytes 128-255 to UTF-8.
  82. auto decoder = TextCodec::decoder_for("windows-1252"sv);
  83. VERIFY(decoder.has_value());
  84. return TRY_OR_THROW_OOM(vm, decoder->to_utf8(decoded_data.value()));
  85. }
  86. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-queuemicrotask
  87. void WindowOrWorkerGlobalScopeMixin::queue_microtask(WebIDL::CallbackType& callback)
  88. {
  89. auto& vm = this_impl().vm();
  90. auto& realm = *vm.current_realm();
  91. JS::GCPtr<DOM::Document> document;
  92. if (is<Window>(this_impl()))
  93. document = &static_cast<Window&>(this_impl()).associated_document();
  94. // The queueMicrotask(callback) method must queue a microtask to invoke callback, and if callback throws an exception, report the exception.
  95. HTML::queue_a_microtask(document, [&callback, &realm] {
  96. auto result = WebIDL::invoke_callback(callback, {});
  97. if (result.is_error())
  98. HTML::report_exception(result, realm);
  99. });
  100. }
  101. // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
  102. WebIDL::ExceptionOr<JS::Value> WindowOrWorkerGlobalScopeMixin::structured_clone(JS::Value value, StructuredSerializeOptions const& options) const
  103. {
  104. auto& vm = this_impl().vm();
  105. (void)options;
  106. // 1. Let serialized be ? StructuredSerializeWithTransfer(value, options["transfer"]).
  107. // FIXME: Use WithTransfer variant of the AO
  108. auto serialized = TRY(structured_serialize(vm, value));
  109. // 2. Let deserializeRecord be ? StructuredDeserializeWithTransfer(serialized, this's relevant realm).
  110. // FIXME: Use WithTransfer variant of the AO
  111. auto deserialized = TRY(structured_deserialize(vm, serialized, relevant_realm(this_impl()), {}));
  112. // 3. Return deserializeRecord.[[Deserialized]].
  113. return deserialized;
  114. }
  115. JS::NonnullGCPtr<JS::Promise> WindowOrWorkerGlobalScopeMixin::fetch(Fetch::RequestInfo const& input, Fetch::RequestInit const& init) const
  116. {
  117. auto& vm = this_impl().vm();
  118. return Fetch::fetch(vm, input, init);
  119. }
  120. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  121. i32 WindowOrWorkerGlobalScopeMixin::set_timeout(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  122. {
  123. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::No);
  124. }
  125. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  126. i32 WindowOrWorkerGlobalScopeMixin::set_interval(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  127. {
  128. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::Yes);
  129. }
  130. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  131. void WindowOrWorkerGlobalScopeMixin::clear_timeout(i32 id)
  132. {
  133. m_timers.remove(id);
  134. }
  135. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  136. void WindowOrWorkerGlobalScopeMixin::clear_interval(i32 id)
  137. {
  138. m_timers.remove(id);
  139. }
  140. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
  141. i32 WindowOrWorkerGlobalScopeMixin::run_timer_initialization_steps(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments, Repeat repeat, Optional<i32> previous_id, Optional<AK::URL> base_url)
  142. {
  143. // 1. Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.
  144. // 2. If previousId was given, let id be previousId; otherwise, let id be an implementation-defined integer that is greater than zero and does not already exist in global's map of active timers.
  145. auto id = previous_id.has_value() ? previous_id.value() : m_timer_id_allocator.allocate();
  146. // FIXME: 3. If the surrounding agent's event loop's currently running task is a task that was created by this algorithm, then let nesting level be the task's timer nesting level. Otherwise, let nesting level be zero.
  147. // 4. If timeout is less than 0, then set timeout to 0.
  148. if (timeout < 0)
  149. timeout = 0;
  150. // FIXME: 5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
  151. // 6. Let callerRealm be the current Realm Record, and calleeRealm be global's relevant Realm.
  152. // FIXME: Implement this when step 9.3.2 is implemented.
  153. // FIXME: The active script becomes null on repeated setInterval callbacks. In JS::VM::get_active_script_or_module,
  154. // the execution context stack is empty on the repeated invocations, thus it returns null. We will need
  155. // to figure out why it becomes empty. But all we need from the active script is the base URL, so we
  156. // grab it on the first invocation an reuse it on repeated invocations.
  157. if (!base_url.has_value()) {
  158. // 7. Let initiating script be the active script.
  159. auto const* initiating_script = Web::Bindings::active_script();
  160. // 8. Assert: initiating script is not null, since this algorithm is always called from some script.
  161. VERIFY(initiating_script);
  162. base_url = initiating_script->base_url();
  163. }
  164. // 9. Let task be a task that runs the following substeps:
  165. JS::SafeFunction<void()> task = [this, handler = move(handler), timeout, arguments = move(arguments), repeat, id, base_url = move(base_url)]() mutable {
  166. // 1. If id does not exist in global's map of active timers, then abort these steps.
  167. if (!m_timers.contains(id))
  168. return;
  169. handler.visit(
  170. // 2. If handler is a Function, then invoke handler given arguments with the callback this value set to thisArg. If this throws an exception, catch it, and report the exception.
  171. [&](JS::Handle<WebIDL::CallbackType> const& callback) {
  172. if (auto result = WebIDL::invoke_callback(*callback, &this_impl(), arguments); result.is_error())
  173. report_exception(result, this_impl().realm());
  174. },
  175. // 3. Otherwise:
  176. [&](String const& source) {
  177. // 1. Assert: handler is a string.
  178. // FIXME: 2. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, catch it, report the exception, and abort these steps.
  179. // 3. Let settings object be global's relevant settings object.
  180. auto& settings_object = relevant_settings_object(this_impl());
  181. // 4. Let base URL be initiating script's base URL.
  182. // 5. Assert: base URL is not null, as initiating script is a classic script or a JavaScript module script.
  183. VERIFY(base_url.has_value());
  184. // 6. Let fetch options be a script fetch options whose cryptographic nonce is initiating script's fetch options's cryptographic nonce, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is initiating script's fetch options's credentials mode, and referrer policy is initiating script's fetch options's referrer policy.
  185. // 7. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.
  186. auto script = ClassicScript::create(base_url->basename(), source, settings_object, *base_url);
  187. // 8. Run the classic script script.
  188. (void)script->run();
  189. });
  190. // 4. If id does not exist in global's map of active timers, then abort these steps.
  191. if (!m_timers.contains(id))
  192. return;
  193. switch (repeat) {
  194. // 5. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.
  195. case Repeat::Yes:
  196. run_timer_initialization_steps(handler, timeout, move(arguments), repeat, id, move(base_url));
  197. break;
  198. // 6. Otherwise, remove global's map of active timers[id].
  199. case Repeat::No:
  200. m_timers.remove(id);
  201. break;
  202. }
  203. };
  204. // FIXME: 10. Increment nesting level by one.
  205. // FIXME: 11. Set task's timer nesting level to nesting level.
  206. // 12. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.
  207. JS::SafeFunction<void()> completion_step = [this, task = move(task)]() mutable {
  208. queue_global_task(Task::Source::TimerTask, this_impl(), move(task));
  209. };
  210. // 13. Run steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep, and id.
  211. auto timer = Timer::create(this_impl(), timeout, move(completion_step), id);
  212. m_timers.set(id, timer);
  213. timer->start();
  214. // 14. Return id.
  215. return id;
  216. }
  217. }