Truly independent web browser
LibWeb: Convert unwrapped JWKs through the WebIDL dictionary conversion
Tim Ledbetter9b30c81fecc7
diff --git a/Libraries/LibWeb/Bindings/NewGlobalObject.cpp b/Libraries/LibWeb/Bindings/NewGlobalObject.cppnew file mode 100644index 00000000000..4116e5a589c--- /dev/null+++ b/Libraries/LibWeb/Bindings/NewGlobalObject.cpp@@ -0,0 +1,20 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibWeb/Bindings/NewGlobalObject.h>+#include <LibWeb/HTML/StructuredSerialize.h>+#include <LibWeb/WebIDL/ExceptionOrUtils.h>++namespace Web::Bindings {++JS::Completion throw_copy_of_error_in_current_realm(JS::VM& vm, JS::Value error)+{+ auto& realm = *vm.current_realm();+ auto serialized_error = TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] { return HTML::structured_serialize(vm, error); }));+ return JS::throw_completion(TRY(WebIDL::throw_dom_exception_if_needed(vm, realm, [&] { return HTML::structured_deserialize(vm, serialized_error, realm); })));+}++}diff --git a/Libraries/LibWeb/Bindings/NewGlobalObject.h b/Libraries/LibWeb/Bindings/NewGlobalObject.hnew file mode 100644index 00000000000..e6eb760add7--- /dev/null+++ b/Libraries/LibWeb/Bindings/NewGlobalObject.h@@ -0,0 +1,34 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Function.h>+#include <LibJS/Forward.h>+#include <LibJS/Runtime/Completion.h>+#include <LibJS/Runtime/Realm.h>+#include <LibJS/Runtime/VM.h>++namespace Web::Bindings {++JS::Completion throw_copy_of_error_in_current_realm(JS::VM&, JS::Value error);++template<typename T>+JS::ThrowCompletionOr<T> run_in_a_new_global_object(JS::VM& vm, Function<JS::ThrowCompletionOr<T>(JS::Realm&)> const& steps)+{+ auto execution_context = MUST(JS::Realm::initialize_host_defined_realm(vm, nullptr, nullptr));+ auto result = steps(*execution_context->realm);+ auto* popped_execution_context = vm.pop_execution_context();+ VERIFY(popped_execution_context == execution_context.ptr());++ // An error that the steps throw belongs to the new global object. Recreate it in the current realm, so that no+ // object of the new global object reaches script.+ if (result.is_error())+ return throw_copy_of_error_in_current_realm(vm, result.error_value());+ return result;+}++}diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 2b0aceb5054..f8c69ead5bf 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -25,6 +25,7 @@ set(SOURCESBindings/InterfaceObject.cppBindings/Intrinsics.cppBindings/MainThreadVM.cpp+ Bindings/NewGlobalObject.cppBindings/OptionConstructor.cppBindings/PlatformObject.cppBindings/RustBindingsServices.cppdiff --git a/Libraries/LibWeb/Crypto/CryptoBindings.cpp b/Libraries/LibWeb/Crypto/CryptoBindings.cppindex f83cc1af606..29ee9921248 100644--- a/Libraries/LibWeb/Crypto/CryptoBindings.cpp+++ b/Libraries/LibWeb/Crypto/CryptoBindings.cpp@@ -5,8 +5,6 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/JsonObject.h>-#include <AK/JsonValue.h>#include <LibJS/Runtime/Array.h>#include <LibJS/Runtime/ArrayBuffer.h>#include <LibJS/Runtime/Object.h>@@ -21,76 +19,28 @@namespace Web::Crypto {-#define JWK_PARSE_STRING_PROPERTY(name) \- if (auto value = json_object.get_string(#name##sv); value.has_value()) { \- key.name = Utf16String::from_utf8(value.release_value()); \- }--JS::ThrowCompletionOr<JsonWebKey> parse_json_web_key(JS::Realm& realm, ReadonlyBytes data)+// https://w3c.github.io/webcrypto/#concept-parse-a-jwk+WebIDL::ExceptionOr<JsonWebKey> parse_json_web_key(JS::Realm& realm, ReadonlyBytes data){// 1. Let data be the sequence of bytes to be parsed.// 2. Let json be the Unicode string that results from interpreting data according to UTF-8.// 3. Convert json to UTF-16.- auto json = MUST(String::from_utf8(data));+ auto json = Utf16String::from_utf8_with_replacement_character(StringView { data }, Utf16String::WithBOMHandling::Yes);// 4. Let result be the object literal that results from executing the JSON.parse internal function// in the context of a new global object, with text argument set to a JavaScript String containing json.- auto maybe_json_value = JsonValue::from_string(json);- if (maybe_json_value.is_error())- return throw_completion(realm, WebIDL::SyntaxError::create(Utf16String::from_utf16(JS::ErrorType::JsonMalformed.message())));-- auto json_value = maybe_json_value.release_value();- if (!json_value.is_object()) {- return throw_completion(realm, WebIDL::SyntaxError::create("JSON value is not an object"_utf16));- }-- auto const& json_object = json_value.as_object();-// 5. Let key be the result of converting result to the IDL dictionary type of JsonWebKey.- JsonWebKey key {};- JWK_PARSE_STRING_PROPERTY(kty);- JWK_PARSE_STRING_PROPERTY(use);- JWK_PARSE_STRING_PROPERTY(alg);- JWK_PARSE_STRING_PROPERTY(crv);- JWK_PARSE_STRING_PROPERTY(x);- JWK_PARSE_STRING_PROPERTY(y);- JWK_PARSE_STRING_PROPERTY(d);- JWK_PARSE_STRING_PROPERTY(n);- JWK_PARSE_STRING_PROPERTY(e);- JWK_PARSE_STRING_PROPERTY(p);- JWK_PARSE_STRING_PROPERTY(q);- JWK_PARSE_STRING_PROPERTY(dp);- JWK_PARSE_STRING_PROPERTY(dq);- JWK_PARSE_STRING_PROPERTY(qi);- JWK_PARSE_STRING_PROPERTY(k);- JWK_PARSE_STRING_PROPERTY(pub);- JWK_PARSE_STRING_PROPERTY(priv);-- key.ext = json_object.get_bool("ext"sv);-- if (auto key_ops = json_object.get_array("key_ops"sv); key_ops.has_value()) {- key.key_ops = Vector<Utf16String> {};- key.key_ops->ensure_capacity(key_ops->size());-- key_ops->for_each([&](auto const& value) {- key.key_ops->append(Utf16String::from_utf8(value.as_string()));- });- }-- if (json_object.has("oth"sv))- TODO();+ auto key = TRY(Bindings::convert_json_to_idl_value_for_json_web_key(realm.vm(), json));// 6. If the kty field of key is not defined, then throw a DataError.if (!key.kty.has_value())- return throw_completion(realm, WebIDL::DataError::create("kty field is not defined"_utf16));+ return WebIDL::DataError::create("kty field is not defined"_utf16);// 7. Return key.return key;}-#undef JWK_PARSE_STRING_PROPERTY-void resolve_crypto_key_promise(JS::Realm& realm, WebIDL::Promise& promise, GC::Ref<CryptoKey> key){WebIDL::resolve_promise(promise, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, key));diff --git a/Libraries/LibWeb/Crypto/CryptoBindings.h b/Libraries/LibWeb/Crypto/CryptoBindings.hindex 0fb20c7fe44..e0ab4ea1436 100644--- a/Libraries/LibWeb/Crypto/CryptoBindings.h+++ b/Libraries/LibWeb/Crypto/CryptoBindings.h@@ -12,6 +12,7 @@#include <AK/Utf16String.h>#include <AK/Vector.h>#include <LibWeb/Bindings/SubtleCrypto.h>+#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::Crypto {@@ -23,7 +24,7 @@ using KeyFormat = Bindings::KeyFormat;using RsaOtherPrimesInfo = Bindings::RsaOtherPrimesInfo;using JsonWebKey = Bindings::JsonWebKey;-JS::ThrowCompletionOr<JsonWebKey> parse_json_web_key(JS::Realm& realm, ReadonlyBytes data);+WebIDL::ExceptionOr<JsonWebKey> parse_json_web_key(JS::Realm&, ReadonlyBytes data);void resolve_crypto_key_promise(JS::Realm&, WebIDL::Promise&, GC::Ref<CryptoKey>);JS::ThrowCompletionOr<GC::Ref<JS::Object>> encapsulated_bits(JS::Realm&, EncapsulatedBits const&);JS::ThrowCompletionOr<GC::Ref<JS::Object>> encapsulated_key(JS::Realm&, EncapsulatedKey const&);diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Libraries/LibWeb/Crypto/SubtleCrypto.cppindex 49e7eeba99c..a980c60d898 100644--- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp@@ -1079,7 +1079,7 @@ GC::Ref<WebIDL::Promise> SubtleCrypto::unwrap_key(JS::Realm& realm, KeyFormat fo// Let key be the result of executing the parse a JWK algorithm, with bytes as the data to be parsed.auto maybe_parsed = parse_json_web_key(realm, bytes.bytes());if (maybe_parsed.is_error()) {- WebIDL::reject_promise(promise, maybe_parsed.release_error().release_value());+ WebIDL::reject_promise_with_exception(promise, maybe_parsed.release_error());return;}diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.idl b/Libraries/LibWeb/Crypto/SubtleCrypto.idlindex 8364f19d1bb..c533715939a 100644--- a/Libraries/LibWeb/Crypto/SubtleCrypto.idl+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.idl@@ -15,7 +15,7 @@ dictionary RsaOtherPrimesInfo {};// https://wicg.github.io/webcrypto-modern-algos/#partial-JsonWebKey-dictionary-[GenerateToValue]+[GenerateToValue, GenerateFromJSON]dictionary JsonWebKey {// The following fields are defined in Section 3.1 of JSON Web KeyDOMString kty;diff --git a/Meta/CMake/libweb_generators.cmake b/Meta/CMake/libweb_generators.cmakeindex 414a4812620..60c50ccb4ba 100644--- a/Meta/CMake/libweb_generators.cmake+++ b/Meta/CMake/libweb_generators.cmake@@ -317,6 +317,7 @@ function (generate_js_bindings target)"${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/interfaces.py""${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/intrinsics.py""${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/iterables.py"+ "${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/json_conversions.py""${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/named_and_indexed_properties.py""${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/namespaces.py""${LADYBIRD_SOURCE_DIR}/Meta/Generators/libweb_bindings/operations.py"diff --git a/Meta/Generators/generate_libweb_bindings.py b/Meta/Generators/generate_libweb_bindings.pyindex dcdea39e2e4..7b0cf47718d 100644--- a/Meta/Generators/generate_libweb_bindings.py+++ b/Meta/Generators/generate_libweb_bindings.py@@ -27,6 +27,8 @@ from Generators.libweb_bindings.intrinsics import write_exposed_interface_implemfrom Generators.libweb_bindings.intrinsics import write_intrinsic_definitions_headerfrom Generators.libweb_bindings.intrinsics import write_intrinsic_definitions_implementationfrom Generators.libweb_bindings.intrinsics import write_wrapper_factory_implementation+from Generators.libweb_bindings.json_conversions import write_dictionary_json_conversions+from Generators.libweb_bindings.json_conversions import write_dictionary_json_declarationsfrom Generators.libweb_bindings.rust_usage import DefinitionUsagefrom Generators.libweb_bindings.structured_serialize import write_structured_serialize_bindings_implementationfrom Generators.libweb_bindings.to_idl_value import dictionaries_in_dependency_order@@ -123,6 +125,7 @@ def write_idl_header(out: TextIO, module: Module, context: GenerationContext, usfor dictionary in dictionaries_in_dependency_order(usage.cpp_dictionaries(module), context):write_dictionary_declaration(body, dictionary, includes, context)write_dictionary_to_javascript_value_declaration(body, dictionary)+ write_dictionary_json_declarations(body, dictionary, includes)out.write("#pragma once\n\n")includes.write(out)@@ -148,6 +151,7 @@ def write_idl_implementation(out: TextIO, module: Module, context: GenerationConfor dictionary in usage.cpp_dictionaries(module):write_dictionary_conversion(body, dictionary, includes, context)write_dictionary_to_javascript_value_conversion(body, dictionary, includes, context)+ write_dictionary_json_conversions(body, dictionary, includes)includes.write(out)out.write("namespace Web::Bindings {\n\n")diff --git a/Meta/Generators/libweb_bindings/json_conversions.py b/Meta/Generators/libweb_bindings/json_conversions.pynew file mode 100644index 00000000000..3ccc737dc70--- /dev/null+++ b/Meta/Generators/libweb_bindings/json_conversions.py@@ -0,0 +1,39 @@+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++from typing import TextIO++from Generators.libweb_bindings.cpp_types import converter_function_name+from Generators.libweb_bindings.includes import GeneratedIncludes+from Utils.utils import make_name_acceptable_cpp+from Utils.utils import title_case_to_snake_case+from Utils.webidl_parser import Dictionary+++def from_json_function_name(dictionary: Dictionary) -> str:+ return f"convert_json_to_idl_value_for_{make_name_acceptable_cpp(title_case_to_snake_case(dictionary.name))}"+++def write_dictionary_json_declarations(out: TextIO, dictionary: Dictionary, includes: GeneratedIncludes) -> None:+ if "GenerateFromJSON" in dictionary.extended_attributes:+ includes.add("AK/Utf16View.h")+ out.write(+ f"JS::ThrowCompletionOr<{dictionary.name}> {from_json_function_name(dictionary)}(JS::VM&, Utf16View);\n\n"+ )+++def write_dictionary_json_conversions(out: TextIO, dictionary: Dictionary, includes: GeneratedIncludes) -> None:+ if "GenerateFromJSON" in dictionary.extended_attributes:+ includes.add("LibJS/Runtime/JSONObject.h")+ includes.add("LibWeb/Bindings/NewGlobalObject.h")+ out.write(+ f"""JS::ThrowCompletionOr<{dictionary.name}> {from_json_function_name(dictionary)}(JS::VM& vm, Utf16View json)+{{+ return run_in_a_new_global_object<{dictionary.name}>(vm, [&](JS::Realm&) -> JS::ThrowCompletionOr<{dictionary.name}> {{+ return {converter_function_name(dictionary)}(vm, TRY(JS::JSONObject::parse_json(vm, json)));+ }});+}}++"""+ )diff --git a/Meta/Utils/webidl_parser.py b/Meta/Utils/webidl_parser.pyindex c436e343728..2f30981438f 100644--- a/Meta/Utils/webidl_parser.py+++ b/Meta/Utils/webidl_parser.py@@ -35,6 +35,7 @@ ALLOWED_EXTENDED_ATTRIBUTES = frozenset("FIXME","DirectGetter","FlyString",+ "GenerateFromJSON","GenerateToValue","Global","HTMLConstructor",diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-unwrapKey-jwk-dictionary-conversion.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-unwrapKey-jwk-dictionary-conversion.txtnew file mode 100644index 00000000000..2e1820e2ac8--- /dev/null+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-unwrapKey-jwk-dictionary-conversion.txt@@ -0,0 +1,20 @@+{"kty":"oct","k":"AA"} as non-extractable verify: unwrapKey secret extractable=false usages=verify, importKey secret extractable=false usages=verify+{"kty":"oct","k":"AA","kid":"x","x5c":[1,{}],"nested":{"a":[null]}} as non-extractable verify: unwrapKey secret extractable=false usages=verify, importKey secret extractable=false usages=verify+{"kty":"oct","k":"AA","kid":"é中"} as non-extractable verify: unwrapKey secret extractable=false usages=verify, importKey secret extractable=false usages=verify+{"kty":"oct","k":"AA","oth":[]} as non-extractable verify: unwrapKey secret extractable=false usages=verify, importKey secret extractable=false usages=verify+{"kty":"oct","k":"AA","oth":[{"r":"AA","d":"AA","t":"AA"}]} as non-extractable verify: unwrapKey secret extractable=false usages=verify, importKey secret extractable=false usages=verify+{"kty":"oct","k":"AA","key_ops":["verify"]} as non-extractable verify: unwrapKey secret extractable=false usages=verify, importKey secret extractable=false usages=verify+{"kty":"oct","k":"AA","key_ops":["verify"]} as non-extractable sign: unwrapKey DataError, importKey DataError+{"kty":"oct","k":"AA","key_ops":[0]} as non-extractable verify: unwrapKey DataError, importKey DataError+{"kty":"oct","k":"AA","key_ops":{}} as non-extractable sign: unwrapKey TypeError, importKey TypeError+{"kty":"oct","k":"AA","ext":false} as extractable verify: unwrapKey DataError, importKey DataError+{"kty":"oct","k":"AA","ext":0} as extractable verify: unwrapKey DataError, importKey DataError+{"kty":"oct","k":"AA","alg":"HS512"} as non-extractable sign: unwrapKey DataError, importKey DataError+{"kty":"oct","k":"AA","alg":0} as non-extractable sign: unwrapKey DataError, importKey DataError+{"kty":"oct","k":"AA","use":"enc"} as non-extractable sign: unwrapKey DataError, importKey DataError+{"k":"AA"} as non-extractable verify: unwrapKey DataError, importKey DataError+{} as non-extractable verify: unwrapKey DataError, importKey DataError+[] as non-extractable verify: unwrapKey DataError, importKey DataError+null as non-extractable verify: unwrapKey DataError, importKey DataError+{: unwrapKey SyntaxError+0xff: unwrapKey SyntaxErrordiff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-unwrapKey-jwk-new-global-object.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-unwrapKey-jwk-new-global-object.txtnew file mode 100644index 00000000000..9010fcdc764--- /dev/null+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-unwrapKey-jwk-new-global-object.txt@@ -0,0 +1,9 @@+Object.prototype.ext is false: secret extractable=true usages=verify+Object.prototype.alg is HS512: secret extractable=false usages=sign+Object.prototype.key_ops is ["verify"]: secret extractable=false usages=sign+Object.prototype.use is a throwing getter: secret extractable=false usages=verify+Array iterator yields "sign" for key_ops ["verify"]: DataError+Malformed JSON: rejected with an Error of this realm: true+Deeply nested JSON: rejected with an Error of this realm: true+String member holding an array of an object without toString: rejected with an Error of this realm: true+key_ops element holding an array of an object without toString: rejected with an Error of this realm: truediff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-unwrapKey-jwk-dictionary-conversion.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-unwrapKey-jwk-dictionary-conversion.htmlnew file mode 100644index 00000000000..3fdfa0d7798--- /dev/null+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-unwrapKey-jwk-dictionary-conversion.html@@ -0,0 +1,57 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const subtle = crypto.subtle;+ const hmac = { name: "HMAC", hash: "SHA-256" };+ const wrapAlgorithm = { name: "AES-GCM", iv: new Uint8Array(12) };+ const wrappingKey = await subtle.importKey("raw", new Uint8Array(16), "AES-GCM", false, ["encrypt", "unwrapKey"]);++ const describe = key => `${key.type} extractable=${key.extractable} usages=${key.usages}`;++ async function unwrap(bytes, extractable, usages) {+ const wrapped = await subtle.encrypt(wrapAlgorithm, wrappingKey, bytes);+ try {+ return describe(await subtle.unwrapKey("jwk", wrapped, wrappingKey, wrapAlgorithm, hmac, extractable, usages));+ } catch (error) {+ return error.name;+ }+ }++ async function import_(jwk, extractable, usages) {+ try {+ return describe(await subtle.importKey("jwk", jwk, hmac, extractable, usages));+ } catch (error) {+ return error.name;+ }+ }++ for (const [json, extractable, usages] of [+ ['{"kty":"oct","k":"AA"}', false, ["verify"]],+ ['{"kty":"oct","k":"AA","kid":"x","x5c":[1,{}],"nested":{"a":[null]}}', false, ["verify"]],+ ['{"kty":"oct","k":"AA","kid":"é中"}', false, ["verify"]],+ ['{"kty":"oct","k":"AA","oth":[]}', false, ["verify"]],+ ['{"kty":"oct","k":"AA","oth":[{"r":"AA","d":"AA","t":"AA"}]}', false, ["verify"]],+ ['{"kty":"oct","k":"AA","key_ops":["verify"]}', false, ["verify"]],+ ['{"kty":"oct","k":"AA","key_ops":["verify"]}', false, ["sign"]],+ ['{"kty":"oct","k":"AA","key_ops":[0]}', false, ["verify"]],+ ['{"kty":"oct","k":"AA","key_ops":{}}', false, ["sign"]],+ ['{"kty":"oct","k":"AA","ext":false}', true, ["verify"]],+ ['{"kty":"oct","k":"AA","ext":0}', true, ["verify"]],+ ['{"kty":"oct","k":"AA","alg":"HS512"}', false, ["sign"]],+ ['{"kty":"oct","k":"AA","alg":0}', false, ["sign"]],+ ['{"kty":"oct","k":"AA","use":"enc"}', false, ["sign"]],+ ['{"k":"AA"}', false, ["verify"]],+ ['{}', false, ["verify"]],+ ['[]', false, ["verify"]],+ ['null', false, ["verify"]],+ ]) {+ const unwrapped = await unwrap(new TextEncoder().encode(json), extractable, usages);+ const imported = await import_(JSON.parse(json), extractable, usages);+ println(`${json} as ${extractable ? "extractable" : "non-extractable"} ${usages}: unwrapKey ${unwrapped}, importKey ${imported}`);+ }++ println(`{: unwrapKey ${await unwrap(new TextEncoder().encode("{"), false, ["verify"])}`);+ println(`0xff: unwrapKey ${await unwrap(new Uint8Array([0xff]), false, ["verify"])}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-unwrapKey-jwk-new-global-object.html b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-unwrapKey-jwk-new-global-object.htmlnew file mode 100644index 00000000000..f320aadcd3d--- /dev/null+++ b/Tests/LibWeb/Text/input/Crypto/SubtleCrypto-unwrapKey-jwk-new-global-object.html@@ -0,0 +1,76 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const subtle = crypto.subtle;+ const hmac = { name: "HMAC", hash: "SHA-256" };+ const wrapAlgorithm = { name: "AES-GCM", iv: new Uint8Array(12) };+ const wrappingKey = await subtle.importKey("raw", new Uint8Array(16), "AES-GCM", false, ["encrypt", "unwrapKey"]);+ const arrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());++ async function unwrapWhile(description, setUp, json, extractable, usages) {+ const wrapped = await subtle.encrypt(wrapAlgorithm, wrappingKey, new TextEncoder().encode(json));+ const tearDown = setUp();+ let result;+ try {+ const key = await subtle.unwrapKey("jwk", wrapped, wrappingKey, wrapAlgorithm, hmac, extractable, usages);+ result = `${key.type} extractable=${key.extractable} usages=${key.usages}`;+ } catch (error) {+ result = error.name;+ } finally {+ tearDown();+ }+ println(`${description}: ${result}`);+ }++ await unwrapWhile("Object.prototype.ext is false", () => {+ Object.prototype.ext = false;+ return () => delete Object.prototype.ext;+ }, '{"kty":"oct","k":"AA"}', true, ["verify"]);++ await unwrapWhile("Object.prototype.alg is HS512", () => {+ Object.prototype.alg = "HS512";+ return () => delete Object.prototype.alg;+ }, '{"kty":"oct","k":"AA"}', false, ["sign"]);++ await unwrapWhile("Object.prototype.key_ops is [\"verify\"]", () => {+ Object.prototype.key_ops = ["verify"];+ return () => delete Object.prototype.key_ops;+ }, '{"kty":"oct","k":"AA"}', false, ["sign"]);++ await unwrapWhile("Object.prototype.use is a throwing getter", () => {+ Object.defineProperty(Object.prototype, "use", {+ get() {+ throw new Error("The page's getter ran");+ },+ configurable: true,+ });+ return () => delete Object.prototype.use;+ }, '{"kty":"oct","k":"AA"}', false, ["verify"]);++ await unwrapWhile("Array iterator yields \"sign\" for key_ops [\"verify\"]", () => {+ const next = arrayIteratorPrototype.next;+ arrayIteratorPrototype.next = function () {+ const step = next.call(this);+ return step.done ? step : { value: "sign", done: false };+ };+ return () => (arrayIteratorPrototype.next = next);+ }, '{"kty":"oct","k":"AA","key_ops":["verify"]}', false, ["sign"]);++ for (const [description, json] of [+ ["Malformed JSON", "{"],+ ["Deeply nested JSON", "[".repeat(200000) + "]".repeat(200000)],+ ["String member holding an array of an object without toString", '{"kty":"oct","k":"AA","alg":[{"toString":null}]}'],+ ["key_ops element holding an array of an object without toString", '{"kty":"oct","k":"AA","key_ops":[[{"toString":null}]]}'],+ ]) {+ const wrapped = await subtle.encrypt(wrapAlgorithm, wrappingKey, new TextEncoder().encode(json));+ try {+ await subtle.unwrapKey("jwk", wrapped, wrappingKey, wrapAlgorithm, hmac, false, ["verify"]);+ println(`${description}: resolved`);+ } catch (error) {+ const ofThisRealm = error instanceof Error && error.constructor.constructor("return globalThis")() === globalThis;+ println(`${description}: rejected with an Error of this realm: ${ofThisRealm}`);+ }+ }+ });+</script>