WindowOrWorkerGlobalScope.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. /*
  2. * Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
  3. * Copyright (c) 2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Base64.h>
  9. #include <AK/QuickSort.h>
  10. #include <AK/String.h>
  11. #include <AK/Utf8View.h>
  12. #include <AK/Vector.h>
  13. #include <LibTextCodec/Decoder.h>
  14. #include <LibWeb/Bindings/MainThreadVM.h>
  15. #include <LibWeb/Fetch/FetchMethod.h>
  16. #include <LibWeb/Forward.h>
  17. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  18. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  19. #include <LibWeb/HTML/Scripting/Environments.h>
  20. #include <LibWeb/HTML/Scripting/ExceptionReporter.h>
  21. #include <LibWeb/HTML/StructuredSerialize.h>
  22. #include <LibWeb/HTML/Timer.h>
  23. #include <LibWeb/HTML/Window.h>
  24. #include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
  25. #include <LibWeb/Infra/Base64.h>
  26. #include <LibWeb/WebIDL/AbstractOperations.h>
  27. #include <LibWeb/WebIDL/DOMException.h>
  28. #include <LibWeb/WebIDL/ExceptionOr.h>
  29. namespace Web::HTML {
  30. WindowOrWorkerGlobalScopeMixin::~WindowOrWorkerGlobalScopeMixin() = default;
  31. void WindowOrWorkerGlobalScopeMixin::visit_edges(JS::Cell::Visitor& visitor)
  32. {
  33. for (auto& it : m_timers)
  34. visitor.visit(it.value);
  35. }
  36. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-origin
  37. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::origin() const
  38. {
  39. auto& vm = this_impl().vm();
  40. // The origin getter steps are to return this's relevant settings object's origin, serialized.
  41. return TRY_OR_THROW_OOM(vm, String::from_deprecated_string(relevant_settings_object(this_impl()).origin().serialize()));
  42. }
  43. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-issecurecontext
  44. bool WindowOrWorkerGlobalScopeMixin::is_secure_context() const
  45. {
  46. // The isSecureContext getter steps are to return true if this's relevant settings object is a secure context, or false otherwise.
  47. return HTML::is_secure_context(relevant_settings_object(this_impl()));
  48. }
  49. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-crossoriginisolated
  50. bool WindowOrWorkerGlobalScopeMixin::cross_origin_isolated() const
  51. {
  52. // The crossOriginIsolated getter steps are to return this's relevant settings object's cross-origin isolated capability.
  53. return relevant_settings_object(this_impl()).cross_origin_isolated_capability() == CanUseCrossOriginIsolatedAPIs::Yes;
  54. }
  55. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
  56. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::btoa(String const& data) const
  57. {
  58. auto& vm = this_impl().vm();
  59. auto& realm = *vm.current_realm();
  60. // The btoa(data) method must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF.
  61. Vector<u8> byte_string;
  62. byte_string.ensure_capacity(data.bytes().size());
  63. for (u32 code_point : Utf8View(data)) {
  64. if (code_point > 0xff)
  65. return WebIDL::InvalidCharacterError::create(realm, "Data contains characters outside the range U+0000 and U+00FF");
  66. byte_string.append(code_point);
  67. }
  68. // 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,
  69. // and then must apply forgiving-base64 encode to that byte sequence and return the result.
  70. return TRY_OR_THROW_OOM(vm, encode_base64(byte_string.span()));
  71. }
  72. // https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
  73. WebIDL::ExceptionOr<String> WindowOrWorkerGlobalScopeMixin::atob(String const& data) const
  74. {
  75. auto& vm = this_impl().vm();
  76. auto& realm = *vm.current_realm();
  77. // 1. Let decodedData be the result of running forgiving-base64 decode on data.
  78. auto decoded_data = Infra::decode_forgiving_base64(data.bytes_as_string_view());
  79. // 2. If decodedData is failure, then throw an "InvalidCharacterError" DOMException.
  80. if (decoded_data.is_error())
  81. return WebIDL::InvalidCharacterError::create(realm, "Input string is not valid base64 data");
  82. // 3. Return decodedData.
  83. // decode_base64() returns a byte string. LibJS uses UTF-8 for strings. Use Latin1Decoder to convert bytes 128-255 to UTF-8.
  84. auto decoder = TextCodec::decoder_for("windows-1252"sv);
  85. VERIFY(decoder.has_value());
  86. return TRY_OR_THROW_OOM(vm, decoder->to_utf8(decoded_data.value()));
  87. }
  88. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-queuemicrotask
  89. void WindowOrWorkerGlobalScopeMixin::queue_microtask(WebIDL::CallbackType& callback)
  90. {
  91. auto& vm = this_impl().vm();
  92. auto& realm = *vm.current_realm();
  93. JS::GCPtr<DOM::Document> document;
  94. if (is<Window>(this_impl()))
  95. document = &static_cast<Window&>(this_impl()).associated_document();
  96. // The queueMicrotask(callback) method must queue a microtask to invoke callback, and if callback throws an exception, report the exception.
  97. HTML::queue_a_microtask(document, [&callback, &realm] {
  98. auto result = WebIDL::invoke_callback(callback, {});
  99. if (result.is_error())
  100. HTML::report_exception(result, realm);
  101. });
  102. }
  103. // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
  104. WebIDL::ExceptionOr<JS::Value> WindowOrWorkerGlobalScopeMixin::structured_clone(JS::Value value, StructuredSerializeOptions const& options) const
  105. {
  106. auto& vm = this_impl().vm();
  107. (void)options;
  108. // 1. Let serialized be ? StructuredSerializeWithTransfer(value, options["transfer"]).
  109. // FIXME: Use WithTransfer variant of the AO
  110. auto serialized = TRY(structured_serialize(vm, value));
  111. // 2. Let deserializeRecord be ? StructuredDeserializeWithTransfer(serialized, this's relevant realm).
  112. // FIXME: Use WithTransfer variant of the AO
  113. auto deserialized = TRY(structured_deserialize(vm, serialized, relevant_realm(this_impl()), {}));
  114. // 3. Return deserializeRecord.[[Deserialized]].
  115. return deserialized;
  116. }
  117. JS::NonnullGCPtr<JS::Promise> WindowOrWorkerGlobalScopeMixin::fetch(Fetch::RequestInfo const& input, Fetch::RequestInit const& init) const
  118. {
  119. auto& vm = this_impl().vm();
  120. return Fetch::fetch(vm, input, init);
  121. }
  122. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-settimeout
  123. i32 WindowOrWorkerGlobalScopeMixin::set_timeout(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  124. {
  125. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::No);
  126. }
  127. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-setinterval
  128. i32 WindowOrWorkerGlobalScopeMixin::set_interval(TimerHandler handler, i32 timeout, JS::MarkedVector<JS::Value> arguments)
  129. {
  130. return run_timer_initialization_steps(move(handler), timeout, move(arguments), Repeat::Yes);
  131. }
  132. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeout
  133. void WindowOrWorkerGlobalScopeMixin::clear_timeout(i32 id)
  134. {
  135. m_timers.remove(id);
  136. }
  137. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearinterval
  138. void WindowOrWorkerGlobalScopeMixin::clear_interval(i32 id)
  139. {
  140. m_timers.remove(id);
  141. }
  142. // https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps
  143. 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)
  144. {
  145. // 1. Let thisArg be global if that is a WorkerGlobalScope object; otherwise let thisArg be the WindowProxy that corresponds to global.
  146. // 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.
  147. auto id = previous_id.has_value() ? previous_id.value() : m_timer_id_allocator.allocate();
  148. // 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.
  149. // 4. If timeout is less than 0, then set timeout to 0.
  150. if (timeout < 0)
  151. timeout = 0;
  152. // FIXME: 5. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.
  153. // 6. Let callerRealm be the current Realm Record, and calleeRealm be global's relevant Realm.
  154. // FIXME: Implement this when step 9.3.2 is implemented.
  155. // FIXME: The active script becomes null on repeated setInterval callbacks. In JS::VM::get_active_script_or_module,
  156. // the execution context stack is empty on the repeated invocations, thus it returns null. We will need
  157. // to figure out why it becomes empty. But all we need from the active script is the base URL, so we
  158. // grab it on the first invocation an reuse it on repeated invocations.
  159. if (!base_url.has_value()) {
  160. // 7. Let initiating script be the active script.
  161. auto const* initiating_script = Web::Bindings::active_script();
  162. // 8. Assert: initiating script is not null, since this algorithm is always called from some script.
  163. VERIFY(initiating_script);
  164. base_url = initiating_script->base_url();
  165. }
  166. // 9. Let task be a task that runs the following substeps:
  167. JS::SafeFunction<void()> task = [this, handler = move(handler), timeout, arguments = move(arguments), repeat, id, base_url = move(base_url)]() mutable {
  168. // 1. If id does not exist in global's map of active timers, then abort these steps.
  169. if (!m_timers.contains(id))
  170. return;
  171. handler.visit(
  172. // 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.
  173. [&](JS::Handle<WebIDL::CallbackType> const& callback) {
  174. if (auto result = WebIDL::invoke_callback(*callback, &this_impl(), arguments); result.is_error())
  175. report_exception(result, this_impl().realm());
  176. },
  177. // 3. Otherwise:
  178. [&](String const& source) {
  179. // 1. Assert: handler is a string.
  180. // FIXME: 2. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, catch it, report the exception, and abort these steps.
  181. // 3. Let settings object be global's relevant settings object.
  182. auto& settings_object = relevant_settings_object(this_impl());
  183. // 4. Let base URL be initiating script's base URL.
  184. // 5. Assert: base URL is not null, as initiating script is a classic script or a JavaScript module script.
  185. VERIFY(base_url.has_value());
  186. // 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.
  187. // 7. Let script be the result of creating a classic script given handler, settings object, base URL, and fetch options.
  188. auto script = ClassicScript::create(base_url->basename(), source, settings_object, *base_url);
  189. // 8. Run the classic script script.
  190. (void)script->run();
  191. });
  192. // 4. If id does not exist in global's map of active timers, then abort these steps.
  193. if (!m_timers.contains(id))
  194. return;
  195. switch (repeat) {
  196. // 5. If repeat is true, then perform the timer initialization steps again, given global, handler, timeout, arguments, true, and id.
  197. case Repeat::Yes:
  198. run_timer_initialization_steps(handler, timeout, move(arguments), repeat, id, move(base_url));
  199. break;
  200. // 6. Otherwise, remove global's map of active timers[id].
  201. case Repeat::No:
  202. m_timers.remove(id);
  203. break;
  204. }
  205. };
  206. // FIXME: 10. Increment nesting level by one.
  207. // FIXME: 11. Set task's timer nesting level to nesting level.
  208. // 12. Let completionStep be an algorithm step which queues a global task on the timer task source given global to run task.
  209. JS::SafeFunction<void()> completion_step = [this, task = move(task)]() mutable {
  210. queue_global_task(Task::Source::TimerTask, this_impl(), move(task));
  211. };
  212. // 13. Run steps after a timeout given global, "setTimeout/setInterval", timeout, completionStep, and id.
  213. auto timer = Timer::create(this_impl(), timeout, move(completion_step), id);
  214. m_timers.set(id, timer);
  215. timer->start();
  216. // 14. Return id.
  217. return id;
  218. }
  219. // https://www.w3.org/TR/performance-timeline/#dfn-filter-buffer-by-name-and-type
  220. static ErrorOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> filter_buffer_by_name_and_type(Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>> const& buffer, Optional<String> name, Optional<String> type)
  221. {
  222. // 1. Let result be an initially empty list.
  223. Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>> result;
  224. // 2. For each PerformanceEntry entry in buffer, run the following steps:
  225. for (auto const& entry : buffer) {
  226. // 1. If type is not null and if type is not identical to entry's entryType attribute, continue to next entry.
  227. if (type.has_value() && type.value() != entry->entry_type())
  228. continue;
  229. // 2. If name is not null and if name is not identical to entry's name attribute, continue to next entry.
  230. if (name.has_value() && name.value() != entry->name())
  231. continue;
  232. // 3. append entry to result.
  233. TRY(result.try_append(entry));
  234. }
  235. // 3. Sort results's entries in chronological order with respect to startTime
  236. quick_sort(result, [](auto const& left_entry, auto const& right_entry) {
  237. return left_entry->start_time() < right_entry->start_time();
  238. });
  239. // 4. Return result.
  240. return result;
  241. }
  242. // https://www.w3.org/TR/performance-timeline/#dfn-filter-buffer-map-by-name-and-type
  243. ErrorOr<Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>>> WindowOrWorkerGlobalScopeMixin::filter_buffer_map_by_name_and_type(Optional<String> name, Optional<String> type) const
  244. {
  245. // 1. Let result be an initially empty list.
  246. Vector<JS::Handle<PerformanceTimeline::PerformanceEntry>> result;
  247. // 2. Let map be the performance entry buffer map associated with the relevant global object of this.
  248. auto const& map = m_performance_entry_buffer_map;
  249. // 3. Let tuple list be an empty list.
  250. Vector<PerformanceTimeline::PerformanceEntryTuple const&> tuple_list;
  251. // 4. If type is not null, append the result of getting the value of entry on map given type as key to tuple list.
  252. // Otherwise, assign the result of get the values on map to tuple list.
  253. if (type.has_value()) {
  254. auto maybe_tuple = map.get(type.value());
  255. if (maybe_tuple.has_value())
  256. TRY(tuple_list.try_append(maybe_tuple.release_value()));
  257. } else {
  258. for (auto const& it : map)
  259. TRY(tuple_list.try_append(it.value));
  260. }
  261. // 5. For each tuple in tuple list, run the following steps:
  262. for (auto const& tuple : tuple_list) {
  263. // 1. Let buffer be tuple's performance entry buffer.
  264. auto const& buffer = tuple.performance_entry_buffer;
  265. // 2. If tuple's availableFromTimeline is false, continue to the next tuple.
  266. if (tuple.available_from_timeline == PerformanceTimeline::AvailableFromTimeline::No)
  267. continue;
  268. // 3. Let entries be the result of running filter buffer by name and type with buffer, name and type as inputs.
  269. auto entries = TRY(filter_buffer_by_name_and_type(buffer, name, type));
  270. // 4. For each entry in entries, append entry to result.
  271. TRY(result.try_extend(entries));
  272. }
  273. // 6. Sort results's entries in chronological order with respect to startTime
  274. quick_sort(result, [](auto const& left_entry, auto const& right_entry) {
  275. return left_entry->start_time() < right_entry->start_time();
  276. });
  277. // 7. Return result.
  278. return result;
  279. }
  280. }