Truly independent web browser
LibWeb: Port SubtleCrypto and Crypto to Rust
Shannon Bootha6463084ada8
diff --git a/Libraries/LibJS/Rust/src/api.rs b/Libraries/LibJS/Rust/src/api.rsindex bb21f27d2db..d324f79d377 100644--- a/Libraries/LibJS/Rust/src/api.rs+++ b/Libraries/LibJS/Rust/src/api.rs@@ -97,6 +97,6 @@ pub use crate::runtime::typed_array::{typed_array_byte_length, typed_array_length,};pub use crate::runtime::value::{number_to_string, same_value};-pub use crate::utf16::{Utf16Display, Utf16View, to_well_formed};+pub use crate::utf16::{Utf16Display, Utf16View, to_well_formed, utf16_formatted};/// Derives Trace for a type of the embedder, which marks the type `#[gc(crate = libjs_rust)]`.pub use libjs_runtime_macros::Trace;diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rsindex e28808fdb94..e8e0a599a1a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/conversions.rs@@ -1157,6 +1157,15 @@ impl ToJs for Gc<TypedArrayBase> {}}+impl ToJs for ArrayBufferView {+ fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {+ Ok(match self {+ Self::DataView(view) => Value::from_object(view),+ Self::TypedArray(array) => Value::from_object(array),+ })+ }+}+impl ToJs for Gc<ArrayBuffer> {fn to_js(self, _: &CallContext) -> ThrowCompletionOr<Value> {Ok(Value::from_object(self))diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto.rsnew file mode 100644index 00000000000..05484515d0e--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto.rs@@ -0,0 +1,143 @@+/*+ * Copyright (c) 2021, Idan Horowitz <[email protected]>+ * Copyright (c) 2022, stelar7 <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;++use ak::{Span, SpanMut, Utf16String};+use libjs_rust::api::{+ ArrayBufferOrder, ErrorType, Throw, Trace, TypedArrayKind, Value, Vm, is_typed_array_out_of_bounds,+ make_typed_array_with_buffer_witness_record, typed_array_byte_length,+};++use crate::bindings::conversions::{ArrayBufferView, BufferSource};+use crate::bindings::interface::{Ref, Wrappable, allocate, cell_into_abi};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::crypto::subtle_crypto::SubtleCrypto;+use crate::webidl::dom_exception::DOMExceptionFields;+use crate::webidl::quota_exceeded_error::{self, QuotaExceededErrorFields};++unsafe extern "C" {+ fn web_crypto_fill_with_random(bytes: SpanMut<'_, u8>);+ fn web_crypto_generate_random_uuid(state: *mut c_void, receive: unsafe extern "C" fn(*mut c_void, Span<'_, u8>));+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Crypto {+ subtle: Ref<SubtleCrypto>,+}++impl Wrappable for Crypto {}++#[allow(+ clippy::unnecessary_wraps,+ reason = "the generated bindings can propagate exceptions from every getter"+)]+impl Crypto {+ pub(crate) fn subtle(&self, _: &mut CallContext) -> WebIdlResult<Ref<SubtleCrypto>> {+ Ok(self.subtle)+ }++ // https://w3c.github.io/webcrypto/#dfn-Crypto-method-getRandomValues+ pub(crate) fn get_random_values(+ &self,+ cx: &mut CallContext,+ array: ArrayBufferView,+ ) -> WebIdlResult<ArrayBufferView> {+ let array_view = BufferSource::from(array);++ // 1. If array is not an Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array, then throw a TypeMismatchError and terminate the algorithm.+ let type_mismatch_error = || {+ Exception::Dom("TypeMismatchError", Utf16String::from_ascii(b"array must be one of Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array"))+ };+ let ArrayBufferView::TypedArray(typed_array) = array else {+ return Err(type_mismatch_error());+ };++ use TypedArrayKind::{+ BigInt64Array, BigUint64Array, Int8Array, Int16Array, Int32Array, Uint8Array, Uint8ClampedArray,+ Uint16Array, Uint32Array,+ };+ if !matches!(+ typed_array.kind(),+ Int8Array+ | Uint8Array+ | Uint8ClampedArray+ | Int16Array+ | Uint16Array+ | Int32Array+ | Uint32Array+ | BigInt64Array+ | BigUint64Array+ ) {+ return Err(type_mismatch_error());+ }++ let typed_array_record = make_typed_array_with_buffer_witness_record(&typed_array, ArrayBufferOrder::SeqCst);++ // IMPLEMENTATION DEFINED: If the viewed array buffer is out-of-bounds, throw a InvalidStateError and terminate the algorithm.+ if is_typed_array_out_of_bounds(&typed_array_record) {+ return Err(Exception::Dom(+ "InvalidStateError",+ ErrorType::BufferOutOfBounds.message(&[&"TypedArray"]),+ ));+ }++ // 2. If the byteLength of array is greater than 65536, throw a QuotaExceededError and terminate the algorithm.+ if typed_array_byte_length(&typed_array_record) > 65536 {+ let fields = QuotaExceededErrorFields {+ dom_exception: DOMExceptionFields {+ name: Utf16String::from_ascii(b"QuotaExceededError"),+ message: Utf16String::from_ascii(b"array's byteLength may not be greater than 65536"),+ },+ quota: None,+ requested: None,+ };+ return Err(Throw::new(Value::from_object(quota_exceeded_error::create(cx.realm(), &fields))).into());+ }++ // 3. Overwrite all elements of array with cryptographically strong random values of the appropriate type.+ let extent = array_view.extent();+ let mut random_bytes = vec![0; extent.byte_length];+ // SAFETY: The span is writable for the call.+ unsafe { web_crypto_fill_with_random(SpanMut::new(&mut random_bytes)) };+ extent.buffer.overwrite(extent.byte_offset, &random_bytes);++ // 4. Return array.+ Ok(array)+ }++ // https://w3c.github.io/webcrypto/#dfn-Crypto-method-randomUUID+ pub(crate) fn random_uuid(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(generate_random_uuid())+ }+}++// https://w3c.github.io/webcrypto/#dfn-generate-a-random-uuid+fn generate_random_uuid() -> Utf16String {+ unsafe extern "C" fn receive(state: *mut c_void, bytes: Span<'_, u8>) {+ // SAFETY: The caller lends the string and the service lends the UUID bytes.+ unsafe { *state.cast::<Utf16String>() = Utf16String::from_ascii(bytes.as_slice()) };+ }+ let mut uuid = Utf16String::default();+ // SAFETY: The state is writable for the call.+ unsafe { web_crypto_generate_random_uuid((&raw mut uuid).cast(), receive) };+ uuid+}++/// # Safety+///+/// The VM must be live.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_crypto_create(vm: *const c_void) -> *mut c_void {+ // SAFETY: The caller passes a live VM.+ let vm = unsafe { &*vm.cast::<Vm>() };+ cell_into_abi(allocate(vm, |_| Crypto {+ subtle: allocate(vm, |_| SubtleCrypto),+ }))+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rsnew file mode 100644index 00000000000..867a60a7e11--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs@@ -0,0 +1,752 @@+/*+ * Copyright (c) 2024, Andrew Kaster <[email protected]>+ * Copyright (c) 2024, stelar7 <[email protected]>+ * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2024, Andreas Kling <[email protected]>+ * Copyright (c) 2024-2025, Altomani Gianluca <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;+use core::ptr::{NonNull, null, null_mut};+use std::rc::Rc;++use ak::{Span, Utf16String};+use libjs_rust::api::{Gc, RawNativeFunctionResult, Realm, Trace, Value};++use crate::bindings::WebIdlResult;+use crate::bindings::interface::{Ref, cell_from_abi, cell_into_abi};+use crate::crypto::crypto_bindings::{CryptoKeyPair, JsonWebKey, RawJsonWebKey};+use crate::crypto::crypto_key::{CryptoKey, KeyUsage};+use crate::crypto::subtle_crypto::{CryptoKeyOrCryptoKeyPair, KeyFormat};++#[derive(Clone, Copy)]+#[repr(u8)]+pub(crate) enum AlgorithmId {+ RsassaPkcs1,+ RsaPss,+ RsaOaep,+ Ecdsa,+ Ecdh,+ AesCtr,+ AesCbc,+ AesGcm,+ AesKw,+ Hmac,+ Sha,+ CShake,+ Hkdf,+ Pbkdf2,+ X25519,+ X448,+ ED25519,+ ED448,+ MlDsa,+ MlKem,+ Argon2,+ ChaCha20Poly1305,+ AesOcb,+ Kmac,+}++#[derive(Clone, Copy)]+#[repr(u8)]+#[allow(+ clippy::enum_variant_names,+ reason = "each variant names an algorithm parameter dictionary"+)]+pub(crate) enum ParameterId {+ AlgorithmParams,+ RsaHashedKeyGenParams,+ RsaHashedImportParams,+ RsaPssParams,+ RsaOaepParams,+ EcdsaParams,+ EcKeyGenParams,+ EcKeyImportParams,+ EcdhKeyDeriveParams,+ AesCtrParams,+ AesKeyGenParams,+ AesDerivedKeyParams,+ AesCbcParams,+ AesGcmParams,+ HmacKeyGenParams,+ HmacImportParams,+ CShakeParams,+ HkdfParams,+ Pbkdf2Params,+ Ed448Params,+ ContextParams,+ Argon2Params,+ AeadParams,+ KmacParams,+ KmacKeyGenParams,+ KmacImportParams,+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Bytes(#[gc(untraced)] Rc<Vec<u8>>);++impl Bytes {+ pub(crate) fn new(bytes: Vec<u8>) -> Self {+ Self(Rc::new(bytes))+ }++ pub(crate) fn as_slice(&self) -> &[u8] {+ self.0.as_slice()+ }+}++pub(crate) enum ExportKeyResult {+ Bytes(Bytes),+ JsonWebKey(JsonWebKey),+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum ImportKeyData {+ Bytes(Bytes),+ JsonWebKey(JsonWebKey),+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct EncapsulatedBitsData {+ pub(crate) shared_key: Option<Bytes>,+ pub(crate) ciphertext: Option<Bytes>,+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct EncapsulatedKeyData {+ pub(crate) shared_key: Ref<CryptoKey>,+ pub(crate) ciphertext: Option<Bytes>,+}++#[repr(C)]+#[derive(Default)]+struct OptionalLength {+ has_value: bool,+ value: u32,+}++impl From<Option<u32>> for OptionalLength {+ fn from(value: Option<u32>) -> Self {+ Self {+ has_value: value.is_some(),+ value: value.unwrap_or_default(),+ }+ }+}++type ReceiveBytes = unsafe extern "C" fn(*mut c_void, Span<'_, u8>);+type ReceiveUsages = unsafe extern "C" fn(*mut c_void, Span<'_, KeyUsage>);+type ReceiveJsonWebKey = unsafe extern "C" fn(*mut c_void, &RawJsonWebKey<'_>);++unsafe extern "C" {+ fn web_crypto_algorithm_from_value(+ realm: *mut c_void,+ method_id: AlgorithmId,+ parameter_id: ParameterId,+ value: u64,+ name: usize,+ out: &mut *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_destroy(algorithm: *mut c_void);+ fn web_crypto_algorithm_public_key_usages(algorithm: *mut c_void, state: *mut c_void, receive: ReceiveUsages);+ fn web_crypto_normalized_key_usages(usages: Span<'_, KeyUsage>, state: *mut c_void, receive: ReceiveUsages);+ fn web_crypto_public_key_for_private_key(key: *mut c_void) -> *mut c_void;+ fn web_crypto_algorithm_encrypt(+ realm: *mut c_void,+ algorithm: *mut c_void,+ key: *mut c_void,+ data: Span<'_, u8>,+ state: *mut c_void,+ receive: ReceiveBytes,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_decrypt(+ realm: *mut c_void,+ algorithm: *mut c_void,+ key: *mut c_void,+ data: Span<'_, u8>,+ state: *mut c_void,+ receive: ReceiveBytes,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_sign(+ realm: *mut c_void,+ algorithm: *mut c_void,+ key: *mut c_void,+ data: Span<'_, u8>,+ state: *mut c_void,+ receive: ReceiveBytes,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_verify(+ realm: *mut c_void,+ algorithm: *mut c_void,+ key: *mut c_void,+ signature: Span<'_, u8>,+ data: Span<'_, u8>,+ out: &mut bool,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_digest(+ realm: *mut c_void,+ algorithm: *mut c_void,+ data: Span<'_, u8>,+ state: *mut c_void,+ receive: ReceiveBytes,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_derive_bits(+ realm: *mut c_void,+ algorithm: *mut c_void,+ key: *mut c_void,+ length: OptionalLength,+ state: *mut c_void,+ receive: ReceiveBytes,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_import_key(+ realm: *mut c_void,+ algorithm: *mut c_void,+ format: KeyFormat,+ key_data: Span<'_, u8>,+ jwk: *const c_void,+ extractable: bool,+ usages: Span<'_, KeyUsage>,+ out: &mut *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_generate_key(+ realm: *mut c_void,+ algorithm: *mut c_void,+ extractable: bool,+ usages: Span<'_, KeyUsage>,+ out_key: &mut *mut c_void,+ out_public_key: &mut *mut c_void,+ out_private_key: &mut *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_export_key(+ realm: *mut c_void,+ algorithm: *mut c_void,+ format: KeyFormat,+ key: *mut c_void,+ state: *mut c_void,+ receive_bytes: ReceiveBytes,+ receive_jwk: ReceiveJsonWebKey,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_get_key_length(+ realm: *mut c_void,+ algorithm: *mut c_void,+ out: &mut OptionalLength,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_get_shared_key_length(+ realm: *mut c_void,+ algorithm: *mut c_void,+ out: &mut u32,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_wrap_key(+ realm: *mut c_void,+ algorithm: *mut c_void,+ key: *mut c_void,+ data: Span<'_, u8>,+ state: *mut c_void,+ receive: ReceiveBytes,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_unwrap_key(+ realm: *mut c_void,+ algorithm: *mut c_void,+ key: *mut c_void,+ data: Span<'_, u8>,+ state: *mut c_void,+ receive: ReceiveBytes,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_encapsulate(+ realm: *mut c_void,+ algorithm: *mut c_void,+ key: *mut c_void,+ shared_key: *mut c_void,+ ciphertext: *mut c_void,+ receive: ReceiveBytes,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_decapsulate(+ realm: *mut c_void,+ algorithm: *mut c_void,+ key: *mut c_void,+ data: Span<'_, u8>,+ state: *mut c_void,+ receive: ReceiveBytes,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_validate_encrypt_parameters(+ realm: *mut c_void,+ algorithm: *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_validate_decrypt_parameters(+ realm: *mut c_void,+ algorithm: *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_validate_sign_parameters(+ realm: *mut c_void,+ algorithm: *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_validate_verify_parameters(+ realm: *mut c_void,+ algorithm: *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_validate_digest_parameters(+ realm: *mut c_void,+ algorithm: *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_validate_generate_key_parameters(+ realm: *mut c_void,+ algorithm: *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_validate_import_key_parameters(+ realm: *mut c_void,+ algorithm: *mut c_void,+ ) -> RawNativeFunctionResult;+ fn web_crypto_algorithm_validate_derive_bits_parameters(+ realm: *mut c_void,+ algorithm: *mut c_void,+ length: OptionalLength,+ ) -> RawNativeFunctionResult;+}++pub(crate) struct CppAlgorithm(NonNull<c_void>);++impl Drop for CppAlgorithm {+ fn drop(&mut self) {+ // SAFETY: This object owns the C++ algorithm.+ unsafe { web_crypto_algorithm_destroy(self.0.as_ptr()) };+ }+}++impl CppAlgorithm {+ pub(crate) fn from_value(+ realm: Gc<Realm>,+ method_id: AlgorithmId,+ parameter_id: ParameterId,+ value: Value,+ name: &Utf16String,+ ) -> WebIdlResult<Self> {+ let mut out = null_mut();+ // SAFETY: The realm and value are live, and the call borrows the name.+ unsafe {+ web_crypto_algorithm_from_value(+ realm.as_ptr().cast(),+ method_id,+ parameter_id,+ value.to_raw(),+ name.raw_identity(),+ &mut out,+ )+ }+ .into_completion()?;+ Ok(Self(NonNull::new(out).expect("LibWeb returns an algorithm")))+ }++ pub(crate) fn into_raw(self) -> *mut c_void {+ core::mem::ManuallyDrop::new(self).0.as_ptr()+ }++ pub(crate) fn public_key_usages(&self) -> Option<Vec<KeyUsage>> {+ let mut usages = None;+ // SAFETY: This object owns the algorithm and the state is writable for the call.+ unsafe {+ web_crypto_algorithm_public_key_usages(+ self.0.as_ptr(),+ core::ptr::from_mut(&mut usages).cast(),+ receive_usages,+ );+ };+ usages+ }++ pub(crate) fn encrypt(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {+ let mut out: Option<Bytes> = None;+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_encrypt(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ cell_into_abi(key),+ Span::new(data.as_slice()),+ core::ptr::from_mut(&mut out).cast(),+ receive_bytes,+ )+ }+ .into_completion()?;+ Ok(out.expect("LibWeb returns bytes"))+ }++ pub(crate) fn decrypt(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {+ let mut out: Option<Bytes> = None;+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_decrypt(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ cell_into_abi(key),+ Span::new(data.as_slice()),+ core::ptr::from_mut(&mut out).cast(),+ receive_bytes,+ )+ }+ .into_completion()?;+ Ok(out.expect("LibWeb returns bytes"))+ }++ pub(crate) fn sign(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {+ let mut out: Option<Bytes> = None;+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_sign(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ cell_into_abi(key),+ Span::new(data.as_slice()),+ core::ptr::from_mut(&mut out).cast(),+ receive_bytes,+ )+ }+ .into_completion()?;+ Ok(out.expect("LibWeb returns bytes"))+ }++ pub(crate) fn verify(+ &self,+ realm: Gc<Realm>,+ key: Ref<CryptoKey>,+ signature: &Bytes,+ data: &Bytes,+ ) -> WebIdlResult<bool> {+ let mut out = false;+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_verify(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ cell_into_abi(key),+ Span::new(signature.as_slice()),+ Span::new(data.as_slice()),+ &mut out,+ )+ }+ .into_completion()?;+ Ok(out)+ }++ pub(crate) fn digest(&self, realm: Gc<Realm>, data: &Bytes) -> WebIdlResult<Bytes> {+ let mut out: Option<Bytes> = None;+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_digest(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ Span::new(data.as_slice()),+ core::ptr::from_mut(&mut out).cast(),+ receive_bytes,+ )+ }+ .into_completion()?;+ Ok(out.expect("LibWeb returns bytes"))+ }++ pub(crate) fn derive_bits(+ &self,+ realm: Gc<Realm>,+ key: Ref<CryptoKey>,+ length: Option<u32>,+ ) -> WebIdlResult<Bytes> {+ let mut out: Option<Bytes> = None;+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_derive_bits(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ cell_into_abi(key),+ length.into(),+ core::ptr::from_mut(&mut out).cast(),+ receive_bytes,+ )+ }+ .into_completion()?;+ Ok(out.expect("LibWeb returns bytes"))+ }++ pub(crate) fn import_key(+ &self,+ realm: Gc<Realm>,+ format: KeyFormat,+ key_data: ImportKeyData,+ extractable: bool,+ usages: &[KeyUsage],+ ) -> WebIdlResult<Ref<CryptoKey>> {+ let mut out = null_mut();+ let mut import = |data, jwk| {+ // SAFETY: The realm and algorithm are live, and the input and output are lent for the call.+ unsafe {+ web_crypto_algorithm_import_key(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ format,+ data,+ jwk,+ extractable,+ Span::new(usages),+ &mut out,+ )+ }+ .into_completion()+ };+ match key_data {+ ImportKeyData::Bytes(bytes) => import(Span::new(bytes.as_slice()), null())?,+ ImportKeyData::JsonWebKey(key) => {+ key.with_raw_fields(|fields| import(Span::default(), core::ptr::from_ref(fields).cast()))?+ }+ };+ // SAFETY: LibWeb returns a live CryptoKey cell.+ Ok(unsafe { cell_from_abi(out) })+ }++ pub(crate) fn generate_key(+ &self,+ realm: Gc<Realm>,+ extractable: bool,+ usages: &[KeyUsage],+ ) -> WebIdlResult<CryptoKeyOrCryptoKeyPair> {+ let (mut key, mut public_key, mut private_key) = (null_mut(), null_mut(), null_mut());+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_generate_key(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ extractable,+ Span::new(usages),+ &mut key,+ &mut public_key,+ &mut private_key,+ )+ }+ .into_completion()?;+ // SAFETY: LibWeb returns a live CryptoKey or two live CryptoKeys.+ unsafe {+ if !key.is_null() {+ Ok(CryptoKeyOrCryptoKeyPair::CryptoKey(cell_from_abi(key)))+ } else {+ Ok(CryptoKeyOrCryptoKeyPair::CryptoKeyPair(CryptoKeyPair {+ public_key: Some(cell_from_abi(public_key)),+ private_key: Some(cell_from_abi(private_key)),+ }))+ }+ }+ }++ pub(crate) fn export_key(+ &self,+ realm: Gc<Realm>,+ format: KeyFormat,+ key: Ref<CryptoKey>,+ ) -> WebIdlResult<ExportKeyResult> {+ let mut out: Option<ExportKeyResult> = None;+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_export_key(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ format,+ cell_into_abi(key),+ core::ptr::from_mut(&mut out).cast(),+ receive_export_bytes,+ receive_export_jwk,+ )+ }+ .into_completion()?;+ Ok(out.expect("LibWeb returns an export result"))+ }++ pub(crate) fn get_key_length(&self, realm: Gc<Realm>) -> WebIdlResult<Option<u32>> {+ let mut out = OptionalLength::default();+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe { web_crypto_algorithm_get_key_length(realm.as_ptr().cast(), self.0.as_ptr(), &mut out) }+ .into_completion()?;+ Ok(out.has_value.then_some(out.value))+ }++ pub(crate) fn get_shared_key_length(&self, realm: Gc<Realm>) -> WebIdlResult<u32> {+ let mut out = 0;+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe { web_crypto_algorithm_get_shared_key_length(realm.as_ptr().cast(), self.0.as_ptr(), &mut out) }+ .into_completion()?;+ Ok(out)+ }++ pub(crate) fn wrap_key(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {+ let mut out: Option<Bytes> = None;+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_wrap_key(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ cell_into_abi(key),+ Span::new(data.as_slice()),+ core::ptr::from_mut(&mut out).cast(),+ receive_bytes,+ )+ }+ .into_completion()?;+ Ok(out.expect("LibWeb returns bytes"))+ }++ pub(crate) fn unwrap_key(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {+ let mut out: Option<Bytes> = None;+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_unwrap_key(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ cell_into_abi(key),+ Span::new(data.as_slice()),+ core::ptr::from_mut(&mut out).cast(),+ receive_bytes,+ )+ }+ .into_completion()?;+ Ok(out.expect("LibWeb returns bytes"))+ }++ pub(crate) fn encapsulate(&self, realm: Gc<Realm>, key: Ref<CryptoKey>) -> WebIdlResult<EncapsulatedBitsData> {+ let (mut shared_key, mut ciphertext): (Option<Bytes>, Option<Bytes>) = (None, None);+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_encapsulate(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ cell_into_abi(key),+ core::ptr::from_mut(&mut shared_key).cast(),+ core::ptr::from_mut(&mut ciphertext).cast(),+ receive_bytes,+ )+ }+ .into_completion()?;+ Ok(EncapsulatedBitsData { shared_key, ciphertext })+ }++ pub(crate) fn decapsulate(&self, realm: Gc<Realm>, key: Ref<CryptoKey>, data: &Bytes) -> WebIdlResult<Bytes> {+ let mut out: Option<Bytes> = None;+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_decapsulate(+ realm.as_ptr().cast(),+ self.0.as_ptr(),+ cell_into_abi(key),+ Span::new(data.as_slice()),+ core::ptr::from_mut(&mut out).cast(),+ receive_bytes,+ )+ }+ .into_completion()?;+ Ok(out.expect("LibWeb returns bytes"))+ }++ pub(crate) fn validate_encrypt_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe { web_crypto_algorithm_validate_encrypt_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }+ .into_completion()?;+ Ok(())+ }++ pub(crate) fn validate_decrypt_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe { web_crypto_algorithm_validate_decrypt_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }+ .into_completion()?;+ Ok(())+ }++ pub(crate) fn validate_sign_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe { web_crypto_algorithm_validate_sign_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }+ .into_completion()?;+ Ok(())+ }++ pub(crate) fn validate_verify_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe { web_crypto_algorithm_validate_verify_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }+ .into_completion()?;+ Ok(())+ }++ pub(crate) fn validate_digest_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe { web_crypto_algorithm_validate_digest_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }+ .into_completion()?;+ Ok(())+ }++ pub(crate) fn validate_generate_key_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe { web_crypto_algorithm_validate_generate_key_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }+ .into_completion()?;+ Ok(())+ }++ pub(crate) fn validate_import_key_parameters(&self, realm: Gc<Realm>) -> WebIdlResult<()> {+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe { web_crypto_algorithm_validate_import_key_parameters(realm.as_ptr().cast(), self.0.as_ptr()) }+ .into_completion()?;+ Ok(())+ }++ pub(crate) fn validate_derive_bits_parameters(&self, realm: Gc<Realm>, length: Option<u32>) -> WebIdlResult<()> {+ // SAFETY: The realm, algorithm and cells are live, and the other arguments are lent for the call.+ unsafe {+ web_crypto_algorithm_validate_derive_bits_parameters(realm.as_ptr().cast(), self.0.as_ptr(), length.into())+ }+ .into_completion()?;+ Ok(())+ }+}++unsafe extern "C" fn receive_bytes(state: *mut c_void, bytes: Span<'_, u8>) {+ // SAFETY: The state is the caller's slot, and the service lends the bytes.+ unsafe { *state.cast::<Option<Bytes>>() = Some(Bytes::new(bytes.as_slice().to_vec())) };+}++unsafe extern "C" fn receive_usages(state: *mut c_void, usages: Span<'_, KeyUsage>) {+ // SAFETY: The state is the caller's slot, and the service lends the usages.+ unsafe { *state.cast::<Option<Vec<KeyUsage>>>() = Some(usages.as_slice().to_vec()) };+}++unsafe extern "C" fn receive_export_bytes(state: *mut c_void, bytes: Span<'_, u8>) {+ // SAFETY: The state is the caller's slot, and the service lends the bytes.+ unsafe {+ *state.cast::<Option<ExportKeyResult>>() = Some(ExportKeyResult::Bytes(Bytes::new(bytes.as_slice().to_vec())));+ };+}++unsafe extern "C" fn receive_export_jwk(state: *mut c_void, key: &RawJsonWebKey<'_>) {+ // SAFETY: The state is the caller's slot, and the service lends the fields.+ unsafe {+ *state.cast::<Option<ExportKeyResult>>() = Some(ExportKeyResult::JsonWebKey(JsonWebKey::from_raw_fields(key)));+ };+}++pub(crate) fn normalized_key_usages(usages: &[KeyUsage]) -> Vec<KeyUsage> {+ let mut normalized: Option<Vec<KeyUsage>> = None;+ // SAFETY: The usages and the output slot are lent for the call.+ unsafe {+ web_crypto_normalized_key_usages(+ Span::new(usages),+ core::ptr::from_mut(&mut normalized).cast(),+ receive_usages,+ );+ };+ normalized.expect("LibWeb returns the normalized usages")+}++pub(crate) fn public_key_for_private_key(key: Ref<CryptoKey>) -> Option<Ref<CryptoKey>> {+ // SAFETY: The key is live.+ let public_key = unsafe { web_crypto_public_key_for_private_key(cell_into_abi(key)) };+ // SAFETY: A non-null pointer returned by LibWeb is a live CryptoKey cell.+ NonNull::new(public_key).map(|key| unsafe { cell_from_abi(key.as_ptr()) })+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_bindings.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_bindings.rsnew file mode 100644index 00000000000..d4b2234ec78--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_bindings.rs@@ -0,0 +1,352 @@+/*+ * Copyright (c) 2024, Andrew Kaster <[email protected]>+ * Copyright (c) 2024, Altomani Gianluca <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;++use ak::{Span, Utf16String};+use libjs_rust::api::{+ ArrayBuffer, ArrayBufferShared, ErrorKind, ErrorType, Gc, PropertyKey, RawNativeFunctionResult, Realm,+ ThrowCompletionOr, Trace, Utf16View, Value, Vm,+};++use crate::bindings::interface::{Ref, cell_into_abi, create_dictionary_object, implementation_if_wrapper, wrap};+use crate::bindings::promise::{WebIdlPromise, resolve_promise};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::crypto::crypto_algorithms::{Bytes, EncapsulatedBitsData, EncapsulatedKeyData};+use crate::crypto::crypto_key::CryptoKey;++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct RsaOtherPrimesInfo {+ pub(crate) d: Option<Utf16String>,+ pub(crate) r: Option<Utf16String>,+ pub(crate) t: Option<Utf16String>,+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct JsonWebKey {+ pub(crate) alg: Option<Utf16String>,+ pub(crate) crv: Option<Utf16String>,+ pub(crate) d: Option<Utf16String>,+ pub(crate) dp: Option<Utf16String>,+ pub(crate) dq: Option<Utf16String>,+ pub(crate) e: Option<Utf16String>,+ pub(crate) k: Option<Utf16String>,+ pub(crate) kty: Option<Utf16String>,+ pub(crate) n: Option<Utf16String>,+ pub(crate) p: Option<Utf16String>,+ pub(crate) r#priv: Option<Utf16String>,+ pub(crate) r#pub: Option<Utf16String>,+ pub(crate) q: Option<Utf16String>,+ pub(crate) qi: Option<Utf16String>,+ pub(crate) r#use: Option<Utf16String>,+ pub(crate) x: Option<Utf16String>,+ pub(crate) y: Option<Utf16String>,+ pub(crate) ext: Option<bool>,+ pub(crate) key_ops: Option<Vec<Utf16String>>,+ pub(crate) oth: Option<Vec<RsaOtherPrimesInfo>>,+}++pub(crate) struct CryptoKeyPair {+ pub(crate) public_key: Option<Ref<CryptoKey>>,+ pub(crate) private_key: Option<Ref<CryptoKey>>,+}++pub(crate) struct EncapsulatedKey {+ pub(crate) shared_key: Option<Ref<CryptoKey>>,+ pub(crate) ciphertext: Option<Gc<ArrayBuffer>>,+}++pub(crate) struct EncapsulatedBits {+ pub(crate) shared_key: Option<Gc<ArrayBuffer>>,+ pub(crate) ciphertext: Option<Gc<ArrayBuffer>>,+}++#[repr(C)]+struct RawRsaOtherPrimesInfo {+ d: usize,+ r: usize,+ t: usize,+}++#[repr(C)]+pub(crate) struct RawJsonWebKey<'a> {+ alg: usize,+ crv: usize,+ d: usize,+ dp: usize,+ dq: usize,+ e: usize,+ k: usize,+ kty: usize,+ n: usize,+ p: usize,+ r#priv: usize,+ r#pub: usize,+ q: usize,+ qi: usize,+ r#use: usize,+ x: usize,+ y: usize,+ ext: u8,+ has_key_ops: bool,+ key_ops: Span<'a, usize>,+ has_oth: bool,+ oth: Span<'a, RawRsaOtherPrimesInfo>,+}++fn raw_string(string: Option<&Utf16String>) -> usize {+ string.map_or(0, Utf16String::raw_identity)+}++unsafe fn string_from_raw(raw: usize) -> Option<Utf16String> {+ if raw == 0 {+ return None;+ }+ // SAFETY: The caller lends a valid string reference.+ unsafe { ak::reference_utf16_string(raw) };+ // SAFETY: The reference taken above belongs to the new owner.+ Some(unsafe { Utf16String::from_raw_owned(raw) })+}++impl JsonWebKey {+ pub(crate) fn with_raw_fields<T>(&self, steps: impl FnOnce(&RawJsonWebKey<'_>) -> T) -> T {+ let key_ops: Vec<_> = self.key_ops.iter().flatten().map(Utf16String::raw_identity).collect();+ let oth: Vec<_> = self+ .oth+ .iter()+ .flatten()+ .map(|prime| RawRsaOtherPrimesInfo {+ d: raw_string(prime.d.as_ref()),+ r: raw_string(prime.r.as_ref()),+ t: raw_string(prime.t.as_ref()),+ })+ .collect();+ steps(&RawJsonWebKey {+ alg: raw_string(self.alg.as_ref()),+ crv: raw_string(self.crv.as_ref()),+ d: raw_string(self.d.as_ref()),+ dp: raw_string(self.dp.as_ref()),+ dq: raw_string(self.dq.as_ref()),+ e: raw_string(self.e.as_ref()),+ k: raw_string(self.k.as_ref()),+ kty: raw_string(self.kty.as_ref()),+ n: raw_string(self.n.as_ref()),+ p: raw_string(self.p.as_ref()),+ r#priv: raw_string(self.r#priv.as_ref()),+ r#pub: raw_string(self.r#pub.as_ref()),+ q: raw_string(self.q.as_ref()),+ qi: raw_string(self.qi.as_ref()),+ r#use: raw_string(self.r#use.as_ref()),+ x: raw_string(self.x.as_ref()),+ y: raw_string(self.y.as_ref()),+ ext: self.ext.map_or(0, |ext| if ext { 2 } else { 1 }),+ has_key_ops: self.key_ops.is_some(),+ key_ops: Span::new(&key_ops),+ has_oth: self.oth.is_some(),+ oth: Span::new(&oth),+ })+ }++ /// # Safety+ ///+ /// Every nonzero string word must be a live AK::Utf16String.+ pub(crate) unsafe fn from_raw_fields(raw: &RawJsonWebKey<'_>) -> Self {+ // SAFETY: The caller lends the strings and spans for the call.+ unsafe {+ Self {+ alg: string_from_raw(raw.alg),+ crv: string_from_raw(raw.crv),+ d: string_from_raw(raw.d),+ dp: string_from_raw(raw.dp),+ dq: string_from_raw(raw.dq),+ e: string_from_raw(raw.e),+ k: string_from_raw(raw.k),+ kty: string_from_raw(raw.kty),+ n: string_from_raw(raw.n),+ p: string_from_raw(raw.p),+ r#priv: string_from_raw(raw.r#priv),+ r#pub: string_from_raw(raw.r#pub),+ q: string_from_raw(raw.q),+ qi: string_from_raw(raw.qi),+ r#use: string_from_raw(raw.r#use),+ x: string_from_raw(raw.x),+ y: string_from_raw(raw.y),+ ext: (raw.ext != 0).then_some(raw.ext == 2),+ key_ops: raw.has_key_ops.then(|| {+ raw.key_ops+ .as_slice()+ .iter()+ .map(|&word| string_from_raw(word).expect("a key usage is a string"))+ .collect()+ }),+ oth: raw.has_oth.then(|| {+ raw.oth+ .as_slice()+ .iter()+ .map(|prime| RsaOtherPrimesInfo {+ d: string_from_raw(prime.d),+ r: string_from_raw(prime.r),+ t: string_from_raw(prime.t),+ })+ .collect()+ }),+ }+ }+ }+}++// https://w3c.github.io/webcrypto/#concept-parse-a-jwk+pub(crate) fn parse_json_web_key(vm: &Vm, data: &[u8]) -> WebIdlResult<JsonWebKey> {+ // 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.+ let data = data.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(data);+ let json = Utf16String::from_utf8(&String::from_utf8_lossy(data));++ // 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.+ // 5. Let key be the result of converting result to the IDL dictionary type of JsonWebKey.+ #[cfg(web_idl_bindings)]+ let key = JsonWebKey::from_json(vm, Utf16View::of_string(&json))?;+ #[cfg(not(web_idl_bindings))]+ let key: JsonWebKey = bindings_unavailable((vm, Utf16View::of_string(&json)));++ // 6. If the kty field of key is not defined, then throw a DataError.+ if key.kty.is_none() {+ return Err(Exception::Dom(+ "DataError",+ Utf16String::from_ascii(b"kty field is not defined"),+ ));+ }++ // 7. Return key.+ Ok(key)+}++#[cfg(not(web_idl_bindings))]+pub(crate) fn bindings_unavailable<T>(_: impl Sized) -> T {+ unreachable!("Crypto dictionary conversions require the generated bindings")+}++pub(crate) fn resolve_crypto_key_promise(vm: &Vm, realm: Gc<Realm>, promise: WebIdlPromise, key: Ref<CryptoKey>) {+ resolve_promise(vm, promise, Value::from_object(wrap(&CallContext::new(vm, realm), key)));+}++pub(crate) fn encapsulated_bits(+ vm: &Vm,+ realm: Gc<Realm>,+ encapsulated_bits: &EncapsulatedBitsData,+) -> ThrowCompletionOr<Value> {+ let object = create_dictionary_object(&CallContext::new(vm, realm));++ if let Some(shared_key) = &encapsulated_bits.shared_key {+ object.create_data_property(+ vm,+ &PropertyKey::from_utf8("sharedKey"),+ array_buffer(vm, realm, shared_key),+ None,+ None,+ )?;+ }++ if let Some(ciphertext) = &encapsulated_bits.ciphertext {+ object.create_data_property(+ vm,+ &PropertyKey::from_utf8("ciphertext"),+ array_buffer(vm, realm, ciphertext),+ None,+ None,+ )?;+ }++ Ok(Value::from_object(object))+}++pub(crate) fn encapsulated_key(+ vm: &Vm,+ realm: Gc<Realm>,+ encapsulated_key: &EncapsulatedKeyData,+) -> ThrowCompletionOr<Value> {+ let cx = CallContext::new(vm, realm);+ let object = create_dictionary_object(&cx);++ object.create_data_property(+ vm,+ &PropertyKey::from_utf8("sharedKey"),+ Value::from_object(wrap(&cx, encapsulated_key.shared_key)),+ None,+ None,+ )?;++ if let Some(ciphertext) = &encapsulated_key.ciphertext {+ object.create_data_property(+ vm,+ &PropertyKey::from_utf8("ciphertext"),+ array_buffer(vm, realm, ciphertext),+ None,+ None,+ )?;+ }++ Ok(Value::from_object(object))+}++pub(crate) fn crypto_key_pair(vm: &Vm, realm: Gc<Realm>, key_pair: &CryptoKeyPair) -> ThrowCompletionOr<Value> {+ let cx = CallContext::new(vm, realm);+ let object = create_dictionary_object(&cx);+ let public_key = key_pair.public_key.expect("a generated pair has a public key");+ let private_key = key_pair.private_key.expect("a generated pair has a private key");+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("publicKey"),+ Value::from_object(wrap(&cx, public_key)),+ )?;+ object.create_data_property_or_throw(+ vm,+ &PropertyKey::from_utf8("privateKey"),+ Value::from_object(wrap(&cx, private_key)),+ )?;+ Ok(Value::from_object(object))+}++pub(crate) fn array_buffer(vm: &Vm, realm: Gc<Realm>, bytes: &Bytes) -> Value {+ Value::from_object(ArrayBuffer::create_from_bytes(+ vm,+ realm,+ bytes.as_slice(),+ ArrayBufferShared::No,+ ))+}++fn crypto_key_from_value(vm: &Vm, value: Value) -> ThrowCompletionOr<Ref<CryptoKey>> {+ let key_object = value.to_object(vm)?;+ let Some(key) = implementation_if_wrapper::<CryptoKey>(key_object) else {+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&"CryptoKey"]);+ };+ Ok(key)+}++/// # Safety+///+/// The VM and value must be live and the output pointer must be writable.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_crypto_key_from_value(+ vm: *const c_void,+ value: u64,+ out: &mut *mut c_void,+) -> RawNativeFunctionResult {+ // SAFETY: The caller supplies the live VM and value.+ let (vm, value) = unsafe { (&*vm.cast::<Vm>(), Value::from_raw(value)) };+ RawNativeFunctionResult::from_completion(crypto_key_from_value(vm, value).map(|key| {+ *out = cell_into_abi(key);+ Value::UNDEFINED+ }))+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rsindex 314b45fb565..b9e272aa8be 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_key.rs@@ -17,12 +17,14 @@ use libjs_rust::api::{};use crate::bindings::conversions::create_uint8_array;-use crate::bindings::interface::{Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, create_dictionary_object};+use crate::bindings::interface::{+ Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, create_dictionary_object, realm_arguments, wrap,+};use crate::bindings::setlike::WorldEntries;use crate::bindings::structured_data::{Serializable, SerializationReader, SerializationWriter};use crate::bindings::{CallContext, Exception, WebIdlResult};-#[derive(Clone, Copy)]+#[derive(Clone, Copy, PartialEq, Eq)]#[repr(u8)]pub(crate) enum KeyType {Public,@@ -32,7 +34,8 @@ pub(crate) enum KeyType {const KEY_TYPE_VALUES: [KeyType; 3] = [KeyType::Public, KeyType::Private, KeyType::Secret];-#[derive(Clone, Copy)]+#[derive(Clone, Copy, PartialEq, Eq, Trace)]+#[gc(crate = libjs_rust)]#[repr(u8)]pub(crate) enum KeyUsage {Encrypt,@@ -64,7 +67,8 @@ const KEY_USAGE_VALUES: [KeyUsage; 12] = [KeyUsage::DecapsulateBits,];-enum InternalAlgorithmData {+#[derive(Clone)]+pub(crate) enum InternalAlgorithmData {Key {name: Utf16String,},@@ -279,17 +283,37 @@ impl CryptoKey {self.handle.borrow().as_ref().expect("a live key has its handle").0}- fn set_algorithm(&self, algorithm: InternalAlgorithmData) {+ pub(crate) fn internal_algorithm(&self) -> core::cell::Ref<'_, InternalAlgorithmData> {+ self.algorithm.borrow()+ }++ pub(crate) fn internal_usages(&self) -> core::cell::Ref<'_, [KeyUsage]> {+ core::cell::Ref::map(self.key_usages.borrow(), Vec::as_slice)+ }++ pub(crate) fn is_extractable(&self) -> bool {+ self.extractable.get()+ }++ pub(crate) fn set_extractable(&self, extractable: bool) {+ self.extractable.set(extractable);+ }++ pub(crate) fn set_type(&self, key_type: KeyType) {+ self.r#type.set(Some(key_type));+ }++ pub(crate) fn set_algorithm(&self, algorithm: InternalAlgorithmData) {self.algorithm.replace(algorithm);self.algorithm_name.replace(Utf16String::default());self.cached_algorithm_objects.replace(Vec::new());}- fn set_usages(&self, usages: Vec<KeyUsage>) {+ pub(crate) fn set_usages(&self, usages: Vec<KeyUsage>) {self.key_usages.replace(usages);}- fn key_type(&self) -> KeyType {+ pub(crate) fn key_type(&self) -> KeyType {self.r#type.get().expect("the key type is initialized before it is read")@@ -345,7 +369,7 @@ impl CryptoKey {Ok(Value::from_object(usages))}- fn algorithm_name(&self) -> Utf16String {+ pub(crate) fn algorithm_name(&self) -> Utf16String {let mut algorithm_name = self.algorithm_name.borrow_mut();if algorithm_name.is_empty() {*algorithm_name = self.algorithm.borrow().name().clone();@@ -776,6 +800,20 @@ pub unsafe extern "C" fn web_rust_crypto_key_create(vm: *const c_void, handle: *cell_into_abi(CryptoKey::create(vm, handle))}+/// # Safety+///+/// The VM, realm, and CryptoKey cell must be live.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_crypto_key_wrap(+ vm: *mut c_void,+ realm: *mut c_void,+ key: *mut c_void,+) -> *mut c_void {+ // SAFETY: The caller supplies the live VM, realm, and CryptoKey cell.+ let ((vm, realm), key) = unsafe { (realm_arguments(vm, realm), cell_from_abi::<CryptoKey>(key)) };+ wrap(&CallContext::new(vm, realm), key).as_ptr().cast()+}+/// # Safety////// The key must be a live CryptoKey cell.diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/mod.rsindex 3237617c898..38084ff0ee7 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/mod.rs@@ -6,5 +6,16 @@//! The Web Cryptography API.+#[cfg_attr(not(web_idl_bindings), allow(dead_code))]+#[allow(clippy::module_inception, reason = "the module mirrors the Crypto interface file")]+pub(crate) mod crypto;+#[cfg_attr(not(web_idl_bindings), allow(dead_code))]+pub(crate) mod crypto_algorithms;+#[cfg_attr(not(web_idl_bindings), allow(dead_code))]+pub(crate) mod crypto_bindings;+#[cfg_attr(not(web_idl_bindings), allow(dead_code))]pub(crate) mod crypto_key;++#[cfg_attr(not(web_idl_bindings), allow(dead_code))]+pub(crate) mod subtle_crypto;diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rsnew file mode 100644index 00000000000..763c86db7c7--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/subtle_crypto.rs@@ -0,0 +1,3643 @@+/*+ * Copyright (c) 2021-2022, Linus Groh <[email protected]>+ * Copyright (c) 2023-2024, stelar7 <[email protected]>+ * Copyright (c) 2024, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;+use core::ptr::NonNull;+use std::collections::HashMap;+use std::rc::Rc;+use std::sync::LazyLock;++use ak::{Span, Utf16String};+use libjs_rust::api::{+ ArrayBuffer, ArrayBufferShared, ErrorKind, ErrorType, Gc, Must, Object, PrimitiveString, PropertyKey,+ RawNativeFunctionResult, Realm, Trace, Value, Vm,+};++use crate::bindings::conversions::BufferSource;+#[cfg(web_idl_bindings)]+use crate::bindings::conversions::ToJs;+use crate::bindings::interface::{+ Ref, Wrappable, create_dictionary_object, with_temporary_execution_context,+ with_temporary_execution_context_and_callbacks,+};+use crate::bindings::promise::{+ TaskSource, WebIdlPromise, create_promise, create_rejected_promise, deferred_invoke, promise_realm,+ queue_a_global_task, reject_promise, resolve_promise,+};+use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};+use crate::crypto::crypto_algorithms::{+ AlgorithmId, Bytes, CppAlgorithm, EncapsulatedKeyData, ExportKeyResult, ImportKeyData, ParameterId,+ normalized_key_usages, public_key_for_private_key,+};+#[allow(+ unused_imports,+ reason = "the generated bindings name definitions through their IDL file"+)]+pub(crate) use crate::crypto::crypto_bindings::{+ CryptoKeyPair, EncapsulatedBits, EncapsulatedKey, JsonWebKey, RsaOtherPrimesInfo,+};+use crate::crypto::crypto_bindings::{+ array_buffer, crypto_key_pair, encapsulated_bits as encapsulated_bits_value,+ encapsulated_key as encapsulated_key_value, parse_json_web_key, resolve_crypto_key_promise,+};+use crate::crypto::crypto_key::{CryptoKey, KeyType, KeyUsage};++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum AlgorithmIdentifier {+ Object(Gc<Object>),+ DOMString(Utf16String),+}++pub(crate) enum KeyDataType {+ BufferSource(BufferSource),+ JsonWebKey(JsonWebKey),+}++pub(crate) enum CryptoKeyOrCryptoKeyPair {+ CryptoKey(Ref<CryptoKey>),+ CryptoKeyPair(CryptoKeyPair),+}++pub(crate) enum ArrayBufferOrJsonWebKey {+ ArrayBuffer(Gc<libjs_rust::api::ArrayBuffer>),+ JsonWebKey(JsonWebKey),+}++#[derive(Clone, Copy, PartialEq, Eq, Trace)]+#[gc(crate = libjs_rust)]+#[repr(u8)]+pub(crate) enum KeyFormat {+ RawPublic,+ RawPrivate,+ RawSeed,+ RawSecret,+ Raw,+ Spki,+ Pkcs8,+ Jwk,+}++#[derive(Clone, Copy)]+struct RegisteredAlgorithm {+ method_id: AlgorithmId,+ parameter_id: ParameterId,+}++type RegisteredAlgorithms = HashMap<&'static str, RegisteredAlgorithm>;+type SupportedAlgorithmsMap = HashMap<&'static str, RegisteredAlgorithms>;++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct NormalizedAlgorithmAndParameter {+ pub(crate) name: Utf16String,+ #[gc(untraced)]+ pub(crate) methods: Rc<CppAlgorithm>,+}++// NB: Getting a copy of the bytes held by a buffer source can only fail when allocating the copy fails.+fn get_a_copy_of_the_bytes(vm: &Vm, buffer_source: BufferSource) -> WebIdlResult<Bytes> {+ // SAFETY: Copying the bytes neither runs script nor allocates a cell.+ let data = unsafe {+ buffer_source.with_bytes(|bytes| {+ let mut data = Vec::new();+ data.try_reserve_exact(bytes.len())?;+ data.extend_from_slice(bytes);+ Ok::<_, std::collections::TryReserveError>(data)+ })+ };+ match data {+ Ok(bytes) => Ok(Bytes::new(bytes)),+ Err(_) => vm+ .throw_completion(ErrorKind::InternalError, ErrorType::OutOfMemory, &[])+ .map_err(Into::into),+ }+}++#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct SubtleCrypto;++impl Wrappable for SubtleCrypto {}++fn export_key_result_to_js_value(vm: &Vm, realm: Gc<Realm>, result: ExportKeyResult) -> WebIdlResult<Value> {+ let result = match result {+ ExportKeyResult::Bytes(bytes) => ArrayBufferOrJsonWebKey::ArrayBuffer(ArrayBuffer::create_from_bytes(+ vm,+ realm,+ bytes.as_slice(),+ ArrayBufferShared::No,+ )),+ ExportKeyResult::JsonWebKey(key) => ArrayBufferOrJsonWebKey::JsonWebKey(key),+ };+ #[cfg(web_idl_bindings)]+ return result.to_js(&CallContext::new(vm, realm)).map_err(Into::into);+ #[cfg(not(web_idl_bindings))]+ crate::crypto::crypto_bindings::bindings_unavailable(result)+}++#[cfg_attr(not(web_idl_bindings), allow(clippy::unnecessary_wraps))]+fn export_key_result_to_bytes(vm: &Vm, result: ExportKeyResult) -> WebIdlResult<Bytes> {+ if let ExportKeyResult::Bytes(bytes) = result {+ return Ok(bytes);+ }+ let ExportKeyResult::JsonWebKey(key) = result else {+ unreachable!()+ };+ #[cfg(web_idl_bindings)]+ let json = key.to_json(vm)?;+ #[cfg(not(web_idl_bindings))]+ let json: Utf16String = crate::crypto::crypto_bindings::bindings_unavailable((vm, key));+ Ok(Bytes::new(String::from_utf16_lossy(&json.to_utf16()).into_bytes()))+}++fn dom_error(name: &'static str, message: &[u8]) -> Exception {+ Exception::Dom(name, Utf16String::from_ascii(message))+}++fn create_rejected_promise_from_exception(vm: &Vm, realm: Gc<Realm>, exception: Exception) -> WebIdlPromise {+ with_temporary_execution_context(realm, || {+ let reason = exception.throw(&CallContext::new(vm, realm)).value();+ create_rejected_promise(vm, realm, reason)+ })+}++fn reject_promise_with_exception(vm: &Vm, promise: WebIdlPromise, exception: Exception) {+ let realm = promise_realm(promise);+ with_temporary_execution_context(realm, || {+ let reason = exception.throw(&CallContext::new(vm, realm)).value();+ reject_promise(vm, promise, reason);+ });+}++// https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm+pub(crate) fn normalize_an_algorithm(+ vm: &Vm,+ realm: Gc<Realm>,+ algorithm: &AlgorithmIdentifier,+ operation: &str,+) -> WebIdlResult<NormalizedAlgorithmAndParameter> {+ // If alg is an instance of a DOMString:+ if let AlgorithmIdentifier::DOMString(algorithm) = algorithm {+ // Return the result of running the normalize an algorithm algorithm,+ // with the alg set to a new Algorithm dictionary whose name attribute is alg, and with the op set to op.+ let dictionary = create_algorithm_dictionary(vm, realm, algorithm)?;+ return normalize_an_algorithm(vm, realm, &AlgorithmIdentifier::Object(dictionary), operation);+ }+ let AlgorithmIdentifier::Object(algorithm) = algorithm else {+ unreachable!()+ };++ // If alg is an object:+ // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.+ let internal_object = supported_algorithms();+ let maybe_registered_algorithms = internal_object.get(operation);++ // NB: supports() can normalize with op set to "deriveKey", for which there is no container and thus no registered+ // algorithm.+ let Some(registered_algorithms) = maybe_registered_algorithms else {+ return Err(Exception::Dom(+ "NotSupportedError",+ Utf16String::from_utf8(&format!("Operation '{operation}' is not supported")),+ ));+ };++ // 2. Let initialAlg be the result of converting the ECMAScript object represented by alg to+ // the IDL dictionary type Algorithm, as defined by [WebIDL].+ // 3. If an error occurred, return the error and terminate this algorithm.+ // Note: We're not going to bother creating an Algorithm object, all we want is the name attribute so that we can+ // fetch the actual algorithm factory from the registeredAlgorithms map.+ let initial_algorithm = algorithm.get(vm, &PropertyKey::from_utf8("name"))?;++ if initial_algorithm.is_undefined() {+ return vm+ .throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&"Algorithm"])+ .map_err(Into::into);+ }++ // 4. Let algName be the value of the name attribute of initialAlg.+ let mut algorithm_name = initial_algorithm.to_utf16_string(vm)?;++ let mut desired_type = None;++ // 5. If registeredAlgorithms contains a key that is a case-insensitive string match for algName:+ let algorithm_name_utf8 = String::from_utf16_lossy(&algorithm_name.to_utf16());+ for (&key, ®istered_algorithm) in registered_algorithms {+ if !key.eq_ignore_ascii_case(&algorithm_name_utf8) {+ continue;+ }++ // 1. Set algName to the value of the matching key.+ algorithm_name = Utf16String::from_ascii(key.as_bytes());++ // 2. Let desiredType be the IDL dictionary type stored at algName in registeredAlgorithms.+ desired_type = Some(registered_algorithm);+ break;+ }++ let Some(desired_type) = desired_type else {+ // Otherwise:+ // Return a new NotSupportedError and terminate this algorithm.+ return Err(Exception::Dom(+ "NotSupportedError",+ libjs_rust::api::utf16_formatted(+ "Algorithm '{}' is not supported for operation '{}'",+ &[&algorithm_name, &operation],+ ),+ ));+ };++ // 8. Let normalizedAlgorithm be the result of converting the ECMAScript object represented by alg+ // to the IDL dictionary type desiredType, as defined by [WebIDL].+ // 10. If an error occurred, return the error and terminate this algorithm.+ // 11. Let dictionaries be a list consisting of the IDL dictionary type desiredType+ // and all of desiredType's inherited dictionaries, in order from least to most derived.+ // 12. For each dictionary dictionary in dictionaries:+ // Note: All of these steps are handled by the create_methods and parameter_from_value methods.+ let methods = Rc::new(CppAlgorithm::from_value(+ realm,+ desired_type.method_id,+ desired_type.parameter_id,+ Value::from_object(*algorithm),+ &algorithm_name,+ )?);++ // 9. Set the name attribute of normalizedAlgorithm to algName.+ let normalized_algorithm = NormalizedAlgorithmAndParameter {+ methods,+ name: algorithm_name,+ };++ // 13. Return normalizedAlgorithm.+ Ok(normalized_algorithm)+}++#[allow(+ clippy::too_many_arguments,+ clippy::unnecessary_wraps,+ reason = "the generated bindings pass the IDL arguments and can propagate an exception"+)]+impl SubtleCrypto {+ // https://w3c.github.io/webcrypto/#SubtleCrypto-method-encrypt+ pub(crate) fn encrypt(+ &self,+ cx: &mut CallContext,+ algorithm: AlgorithmIdentifier,+ key: Ref<CryptoKey>,+ data_parameter: BufferSource,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());++ // 1. Let algorithm and key be the algorithm and key parameters passed to the encrypt() method, respectively.++ // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "encrypt".+ let normalized_algorithm = normalize_an_algorithm(vm, realm, &algorithm, "encrypt");++ // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.+ if let Err(error) = normalized_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. Let data be the result of getting a copy of the bytes held by the data parameter passed to the encrypt() method.+ let data_or_error = get_a_copy_of_the_bytes(vm, data_parameter);+ if let Err(error) = data_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let data = data_or_error.must();++ // 5. Let realm be the relevant realm of this.++ // 6. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 7. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (realm, normalized_algorithm.must(), promise, key, data),+ |vm, (realm, normalized_algorithm, promise, key, data)| {+ with_temporary_execution_context(realm, || {+ // 8. If the following steps or referenced procedures say to throw an error, queue a global task on the+ // crypto task source, given realm's global object, to reject promise with the returned error and then terminate the algorithm.+ let throw_in_this_context = |exception: Exception| {+ let value = exception.throw(&CallContext::new(vm, realm)).value();+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, value),+ |vm, (realm, promise, value)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise(vm, promise, value);+ });+ },+ );+ };++ // 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.+ if normalized_algorithm.name != key.algorithm_name() {+ throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));+ return;+ }++ // 10. If the [[usages]] internal slot of key does not contain an entry that is "encrypt", then throw an InvalidAccessError.+ if !key.internal_usages().contains(&KeyUsage::Encrypt) {+ throw_in_this_context(dom_error("InvalidAccessError", b"Key does not support encryption"));+ return;+ }++ // 11. Let ciphertext be the result of performing the encrypt operation specified by normalizedAlgorithm using algorithm and key and with data as plaintext.+ let cipher_text = normalized_algorithm.methods.encrypt(realm, key, &data);+ if let Err(error) = cipher_text {+ throw_in_this_context(error);+ return;+ }++ // 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, cipher_text.must()),+ |vm, (realm, promise, cipher_text_bytes)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 13. Let result be the result of creating an ArrayBuffer in realm, containing ciphertext.+ // 14. Resolve promise with result.+ resolve_promise(vm, promise, array_buffer(vm, realm, &cipher_text_bytes));+ });+ },+ );+ });+ },+ );++ Ok(promise)+ }++ // https://w3c.github.io/webcrypto/#SubtleCrypto-method-decrypt+ pub(crate) fn decrypt(+ &self,+ cx: &mut CallContext,+ algorithm: AlgorithmIdentifier,+ key: Ref<CryptoKey>,+ data_parameter: BufferSource,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());++ // 1. Let algorithm and key be the algorithm and key parameters passed to the decrypt() method, respectively.++ // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "decrypt".+ let normalized_algorithm = normalize_an_algorithm(vm, realm, &algorithm, "decrypt");++ // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.+ if let Err(error) = normalized_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. Let data be the result of getting a copy of the bytes held by the data parameter passed to the decrypt() method.+ let data_or_error = get_a_copy_of_the_bytes(vm, data_parameter);+ if let Err(error) = data_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let data = data_or_error.must();++ // 5. Let realm be the relevant realm of this.++ // 6. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 7. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (realm, normalized_algorithm.must(), promise, key, data),+ |vm, (realm, normalized_algorithm, promise, key, data)| {+ with_temporary_execution_context(realm, || {+ // 8. If the following steps or referenced procedures say to throw an error, queue a global task on the+ // crypto task source, given realm's global object, to reject promise with the returned error and then terminate the algorithm.+ let throw_in_this_context = |exception: Exception| {+ let value = exception.throw(&CallContext::new(vm, realm)).value();+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, value),+ |vm, (realm, promise, value)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise(vm, promise, value);+ });+ },+ );+ };++ // 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.+ if normalized_algorithm.name != key.algorithm_name() {+ throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));+ return;+ }++ // 10. If the [[usages]] internal slot of key does not contain an entry that is "decrypt", then throw an InvalidAccessError.+ if !key.internal_usages().contains(&KeyUsage::Decrypt) {+ throw_in_this_context(dom_error("InvalidAccessError", b"Key does not support decryption"));+ return;+ }++ // 11. Let plaintext be the result of performing the decrypt operation specified by normalizedAlgorithm using key and algorithm and with data as ciphertext.+ let plain_text = normalized_algorithm.methods.decrypt(realm, key, &data);+ if let Err(error) = plain_text {+ throw_in_this_context(error);+ return;+ }++ // 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, plain_text.must()),+ |vm, (realm, promise, plain_text_bytes)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 13. Let result be the result of creating an ArrayBuffer in realm, containing plaintext.+ // 14. Resolve promise with result.+ resolve_promise(vm, promise, array_buffer(vm, realm, &plain_text_bytes));+ });+ },+ );+ });+ },+ );++ Ok(promise)+ }++ // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-digest+ pub(crate) fn digest(+ &self,+ cx: &mut CallContext,+ algorithm: AlgorithmIdentifier,+ data: BufferSource,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());++ // 1. Let algorithm be the algorithm parameter passed to the digest() method.++ // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "digest".+ let normalized_algorithm = normalize_an_algorithm(vm, realm, &algorithm, "digest");++ // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.+ // FIXME: Spec bug: link to https://webidl.spec.whatwg.org/#a-promise-rejected-with+ if let Err(error) = normalized_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. Let data be the result of getting a copy of the bytes held by the data parameter passed to the digest() method.+ let data_buffer_or_error = get_a_copy_of_the_bytes(vm, data);+ if let Err(error) = data_buffer_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let data_buffer = data_buffer_or_error.must();++ // 5. Let realm be the relevant realm of this.++ // 6. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 7. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (realm, normalized_algorithm.must(), promise, data_buffer),+ |vm, (realm, algorithm_object, promise, data_buffer)| {+ with_temporary_execution_context(realm, || {+ // 8. If the following steps or referenced procedures say to throw an error, queue a global task on the+ // crypto task source, given realm's global object, to reject promise with the returned error and then terminate the algorithm.+ let throw_in_this_context = |exception: Exception| {+ let value = exception.throw(&CallContext::new(vm, realm)).value();+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, value),+ |vm, (realm, promise, value)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise(vm, promise, value);+ });+ },+ );+ };++ // 9. Let digest be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message.+ let digest = algorithm_object.methods.digest(realm, &data_buffer);++ if let Err(error) = digest {+ throw_in_this_context(error);+ return;+ }++ // 10. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, digest.must()),+ |vm, (realm, promise, digest_bytes)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 11. Let result be the result of creating an ArrayBuffer in realm, containing digest.+ // 12. Resolve promise with result.+ resolve_promise(vm, promise, array_buffer(vm, realm, &digest_bytes));+ });+ },+ );+ });+ },+ );++ Ok(promise)+ }++ // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-generateKey+ pub(crate) fn generate_key(+ &self,+ cx: &mut CallContext,+ algorithm: AlgorithmIdentifier,+ extractable: bool,+ key_usages: Vec<KeyUsage>,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());+ // 1. Let algorithm, extractable and usages be the algorithm, extractable and keyUsages+ // parameters passed to the generateKey() method, respectively.++ // 2. Let normalizedAlgorithm be the result of normalizing an algorithm,+ // with alg set to algorithm and op set to "generateKey".+ let normalized_algorithm = normalize_an_algorithm(vm, realm, &algorithm, "generateKey");++ // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.+ if let Err(error) = normalized_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 5. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (realm, normalized_algorithm.must(), promise, extractable, key_usages),+ |vm, (realm, normalized_algorithm, promise, extractable, key_usages)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 6. If the following steps or referenced procedures say to throw an error, reject promise with+ // the returned error and then terminate the algorithm.++ // 7. Let result be the result of performing the generate key operation specified by normalizedAlgorithm+ // using algorithm, extractable and usages.+ let result_or_error = normalized_algorithm+ .methods+ .generate_key(realm, extractable, &key_usages);++ if let Err(error) = result_or_error {+ reject_promise_with_exception(vm, promise, error);+ return;+ }+ let result = result_or_error.must();++ // 8. If result is a CryptoKey object:+ // If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.+ // If result is a CryptoKeyPair object:+ // If the [[usages]] internal slot of the privateKey attribute of result is the empty sequence, then throw a SyntaxError.+ // 9. Resolve promise with result.+ match result {+ CryptoKeyOrCryptoKeyPair::CryptoKey(key) => {+ if (key.key_type() == KeyType::Secret || key.key_type() == KeyType::Private)+ && key_usages.is_empty()+ {+ reject_promise(+ vm,+ promise,+ dom_error("SyntaxError", b"usages must not be empty")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }+ resolve_crypto_key_promise(vm, realm, promise, key);+ }+ CryptoKeyOrCryptoKeyPair::CryptoKeyPair(key_pair) => {+ if key_pair+ .private_key+ .expect("a generated pair has a private key")+ .internal_usages()+ .is_empty()+ {+ reject_promise(+ vm,+ promise,+ dom_error("SyntaxError", b"usages must not be empty")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }+ let object = crypto_key_pair(vm, realm, &key_pair);+ if let Err(error) = object {+ reject_promise_with_exception(vm, promise, error.into());+ return;+ }+ resolve_promise(vm, promise, object.must());+ }+ }+ });+ },+ );++ Ok(promise)+ }++ // https://w3c.github.io/webcrypto/#SubtleCrypto-method-importKey+ pub(crate) fn import_key(+ &self,+ cx: &mut CallContext,+ format: KeyFormat,+ key_data: KeyDataType,+ algorithm: AlgorithmIdentifier,+ extractable: bool,+ key_usages: Vec<KeyUsage>,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());+ // 1. Let format, algorithm, extractable and usages, be the format, algorithm, extractable and keyUsages+ // parameters passed to the importKey() method, respectively.++ // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "importKey".+ let normalized_algorithm = normalize_an_algorithm(vm, realm, &algorithm, "importKey");++ // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.+ if let Err(error) = normalized_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. If format is equal to the string "jwk":+ let real_key_data = if format == KeyFormat::Jwk {+ // 1. If the keyData parameter passed to the importKey() method is not a JsonWebKey dictionary, throw a TypeError.+ if !matches!(&key_data, KeyDataType::JsonWebKey(_)) {+ return Ok(create_rejected_promise_from_exception(+ vm,+ realm,+ Exception::from(+ vm.throw_completion::<()>(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&"JsonWebKey"])+ .expect_err("a throw completion is an error"),+ ),+ ));+ }++ // 2. Let keyData be the keyData parameter passed to the importKey() method.+ let KeyDataType::JsonWebKey(key) = key_data else {+ unreachable!()+ };+ ImportKeyData::JsonWebKey(key)+ }+ // Otherwise:+ else {+ // 1. If the keyData parameter passed to the importKey() method is a JsonWebKey dictionary, throw a TypeError.+ if matches!(&key_data, KeyDataType::JsonWebKey(_)) {+ return Ok(create_rejected_promise_from_exception(+ vm,+ realm,+ Exception::from(+ vm.throw_completion::<()>(+ ErrorKind::TypeError,+ ErrorType::NotAnObjectOfType,+ &[&"BufferSource"],+ )+ .expect_err("a throw completion is an error"),+ ),+ ));+ }++ // 2. Let keyData be the result of getting a copy of the bytes held by the keyData parameter passed to the+ // importKey() method.+ let KeyDataType::BufferSource(buffer_source) = key_data else {+ unreachable!()+ };+ let key_data_or_error = get_a_copy_of_the_bytes(vm, buffer_source);+ if let Err(error) = key_data_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ ImportKeyData::Bytes(key_data_or_error.must())+ };++ // 5. Let realm be the relevant realm of this.++ // 6. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 7. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (+ realm,+ real_key_data,+ normalized_algorithm.must(),+ promise,+ format,+ extractable,+ key_usages,+ algorithm,+ ),+ |vm, (realm, real_key_data, normalized_algorithm, promise, format, extractable, key_usages, _algorithm)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // FIXME: 8. If the following steps or referenced procedures say to throw an error, queue a global task on the+ // crypto task source, given realm's global object, to reject promise with the returned error; and then+ // terminate the algorithm.++ // 9. Let result be the CryptoKey object that results from performing the import key operation+ // specified by normalizedAlgorithm using keyData, algorithm, format, extractable and usages.+ let maybe_result =+ normalized_algorithm+ .methods+ .import_key(realm, format, real_key_data, extractable, &key_usages);+ if let Err(error) = maybe_result {+ reject_promise_with_exception(vm, promise, error);+ return;+ }+ let result = maybe_result.must();++ // 10. If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.+ if (result.key_type() == KeyType::Secret || result.key_type() == KeyType::Private)+ && key_usages.is_empty()+ {+ reject_promise(+ vm,+ promise,+ dom_error("SyntaxError", b"usages must not be empty")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 11. Set the [[extractable]] internal slot of result to extractable.+ result.set_extractable(extractable);++ // 12. Set the [[usages]] internal slot of result to the normalized value of usages.+ result.set_usages(normalized_key_usages(&key_usages));++ // FIXME: 13. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ // FIXME: 14. Let result be the result of converting result to an ECMAScript Object in realm, as defined by [WebIDL].++ // 15. Resolve promise with result.+ resolve_crypto_key_promise(vm, realm, promise, result);+ });+ },+ );++ Ok(promise)+ }++ // https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-exportKey+ pub(crate) fn export_key(+ &self,+ cx: &mut CallContext,+ format: KeyFormat,+ key: Ref<CryptoKey>,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());+ // 1. Let format and key be the format and key parameters passed to the exportKey() method, respectively.++ // 2. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 3. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (realm, key, promise, format),+ |vm, (realm, key, promise, format)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 4. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.++ // 5. If the name member of the [[algorithm]] internal slot of key does not identify a registered algorithm that supports the export key operation,+ // then throw a NotSupportedError.+ // Note: Handled by the base AlgorithmMethods implementation+ // FIXME: Stash the AlgorithmMethods on the KeyAlgorithm+ let normalized_algorithm_or_error = normalize_an_algorithm(+ vm,+ realm,+ &AlgorithmIdentifier::DOMString(key.algorithm_name()),+ "exportKey",+ );+ if let Err(error) = normalized_algorithm_or_error {+ reject_promise_with_exception(vm, promise, error);+ return;+ }+ let normalized_algorithm = normalized_algorithm_or_error.must();++ // 6. If the [[extractable]] internal slot of key is false, then throw an InvalidAccessError.+ if !key.is_extractable() {+ reject_promise(+ vm,+ promise,+ dom_error("InvalidAccessError", b"Key is not extractable")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 7. Let result be the result of performing the export key operation specified by the [[algorithm]] internal slot of key using key and format.+ let result_or_error = normalized_algorithm.methods.export_key(realm, format, key);+ if let Err(error) = result_or_error {+ reject_promise_with_exception(vm, promise, error);+ return;+ }++ // 8. Resolve promise with result.+ let result = export_key_result_to_js_value(vm, realm, result_or_error.must());+ if let Err(error) = result {+ reject_promise_with_exception(vm, promise, error);+ return;+ }+ resolve_promise(vm, promise, result.must());+ });+ },+ );++ Ok(promise)+ }++ // https://w3c.github.io/webcrypto/#SubtleCrypto-method-sign+ pub(crate) fn sign(+ &self,+ cx: &mut CallContext,+ algorithm: AlgorithmIdentifier,+ key: Ref<CryptoKey>,+ data_parameter: BufferSource,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());++ // 1. Let algorithm and key be the algorithm and key parameters passed to the sign() method, respectively.++ // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "sign".+ let normalized_algorithm = normalize_an_algorithm(vm, realm, &algorithm, "sign");++ // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.+ if let Err(error) = normalized_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. Let data be the result of getting a copy of the bytes held by the data parameter passed to the sign() method.+ let data_or_error = get_a_copy_of_the_bytes(vm, data_parameter);+ if let Err(error) = data_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let data = data_or_error.must();++ // 5. Let realm be the relevant realm of this.++ // 6. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 7. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (realm, normalized_algorithm.must(), promise, key, data),+ |vm, (realm, normalized_algorithm, promise, key, data)| {+ with_temporary_execution_context(realm, || {+ // 8. If the following steps or referenced procedures say to throw an error, queue a global task on the+ // crypto task source, given realm's global object, to reject promise with the returned error; and then+ // terminate the algorithm.+ let throw_in_this_context = |exception: Exception| {+ let value = exception.throw(&CallContext::new(vm, realm)).value();+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, value),+ |vm, (realm, promise, value)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise(vm, promise, value);+ });+ },+ );+ };++ // 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]]+ // internal slot of key then throw an InvalidAccessError.+ if normalized_algorithm.name != key.algorithm_name() {+ throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));+ return;+ }++ // 10. If the [[usages]] internal slot of key does not contain an entry that is "sign", then throw an InvalidAccessError.+ if !key.internal_usages().contains(&KeyUsage::Sign) {+ throw_in_this_context(dom_error("InvalidAccessError", b"Key does not support signing"));+ return;+ }++ // 11. Let signature be the result of performing the sign operation specified by normalizedAlgorithm using key+ // and algorithm and with data as message.+ let signature = normalized_algorithm.methods.sign(realm, key, &data);+ if let Err(error) = signature {+ throw_in_this_context(error);+ return;+ }++ // 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, signature.must()),+ |vm, (realm, promise, signature_bytes)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 13. Let result be the result of creating an ArrayBuffer in realm, containing signature.+ // 14. Resolve promise with result.+ resolve_promise(vm, promise, array_buffer(vm, realm, &signature_bytes));+ });+ },+ );+ });+ },+ );++ Ok(promise)+ }++ // https://w3c.github.io/webcrypto/#SubtleCrypto-method-verify+ pub(crate) fn verify(+ &self,+ cx: &mut CallContext,+ algorithm: AlgorithmIdentifier,+ key: Ref<CryptoKey>,+ signature_data: BufferSource,+ data_parameter: BufferSource,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());++ // 1. Let algorithm and key be the algorithm and key parameters passed to the verify() method, respectively.++ // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "verify".+ let normalized_algorithm = normalize_an_algorithm(vm, realm, &algorithm, "verify");++ // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.+ if let Err(error) = normalized_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. Let signature be the result of getting a copy of the bytes held by the signature parameter passed to the verify() method.+ let signature_or_error = get_a_copy_of_the_bytes(vm, signature_data);+ if let Err(error) = signature_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let signature = signature_or_error.must();++ // 5. Let data be the result of getting a copy of the bytes held by the data parameter passed to the verify() method.+ let data_or_error = get_a_copy_of_the_bytes(vm, data_parameter);+ if let Err(error) = data_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let data = data_or_error.must();++ // 6. Let realm be the relevant realm of this.++ // 7. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 8. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (realm, normalized_algorithm.must(), promise, key, signature, data),+ |vm, (realm, normalized_algorithm, promise, key, signature, data)| {+ with_temporary_execution_context(realm, || {+ // 9. If the following steps or referenced procedures say to throw an error, queue a global task on the+ // crypto task source, given realm's global object, to reject promise with the returned error; and then+ // terminate the algorithm.+ let throw_in_this_context = |exception: Exception| {+ let value = exception.throw(&CallContext::new(vm, realm)).value();+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, value),+ |vm, (realm, promise, value)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise(vm, promise, value);+ });+ },+ );+ };++ // 10. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]]+ // internal slot of key then throw an InvalidAccessError.+ if normalized_algorithm.name != key.algorithm_name() {+ throw_in_this_context(dom_error("InvalidAccessError", b"Algorithm mismatch"));+ return;+ }++ // 11. If the [[usages]] internal slot of key does not contain an entry that is "verify", then throw an InvalidAccessError.+ if !key.internal_usages().contains(&KeyUsage::Verify) {+ throw_in_this_context(dom_error("InvalidAccessError", b"Key does not support verification"));+ return;+ }++ // 12. Let result be the result of performing the verify operation specified by normalizedAlgorithm using key,+ // algorithm and signature and with data as message.+ let result = normalized_algorithm.methods.verify(realm, key, &signature, &data);+ if let Err(error) = result {+ throw_in_this_context(error);+ return;+ }++ // 13. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, result.must()),+ |vm, (realm, promise, verification_result)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 14. Resolve promise with result.+ resolve_promise(vm, promise, Value::from_bool(verification_result));+ });+ },+ );+ });+ },+ );++ Ok(promise)+ }++ // https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveBits+ pub(crate) fn derive_bits(+ &self,+ cx: &mut CallContext,+ algorithm: AlgorithmIdentifier,+ base_key: Ref<CryptoKey>,+ length_optional: Option<u32>,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());+ // 1. Let algorithm, baseKey and length, be the algorithm, baseKey and length parameters passed to the deriveBits() method, respectively.++ // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "deriveBits".+ let normalized_algorithm = normalize_an_algorithm(vm, realm, &algorithm, "deriveBits");++ // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.+ if let Err(error) = normalized_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. Let promise be a new Promise object.+ let promise = create_promise(vm, realm);++ // 5. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (realm, normalized_algorithm.must(), promise, base_key, length_optional),+ |vm, (realm, normalized_algorithm, promise, base_key, length_optional)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 6. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.++ // 7. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of baseKey then throw an InvalidAccessError.+ if normalized_algorithm.name != base_key.algorithm_name() {+ reject_promise(+ vm,+ promise,+ dom_error("InvalidAccessError", b"Algorithm mismatch")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 8. If the [[usages]] internal slot of baseKey does not contain an entry that is "deriveBits", then throw an InvalidAccessError.+ if !base_key.internal_usages().contains(&KeyUsage::DeriveBits) {+ reject_promise(+ vm,+ promise,+ dom_error("InvalidAccessError", b"Key does not support deriving bits")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 9. Let result be the result of creating an ArrayBuffer containing the result of performing the derive bits operation specified by normalizedAlgorithm using baseKey, algorithm and length.+ let result = normalized_algorithm+ .methods+ .derive_bits(realm, base_key, length_optional);+ if let Err(error) = result {+ reject_promise_with_exception(vm, promise, error);+ return;+ }++ // 10. Resolve promise with result.+ resolve_promise(vm, promise, array_buffer(vm, realm, &result.must()));+ });+ },+ );++ Ok(promise)+ }++ // https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveKey+ pub(crate) fn derive_key(+ &self,+ cx: &mut CallContext,+ algorithm: AlgorithmIdentifier,+ base_key: Ref<CryptoKey>,+ derived_key_type: AlgorithmIdentifier,+ extractable: bool,+ key_usages: Vec<KeyUsage>,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());+ // 1. Let algorithm, baseKey, derivedKeyType, extractable and usages be the algorithm, baseKey, derivedKeyType, extractable and keyUsages parameters passed to the deriveKey() method, respectively.++ // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "deriveBits".+ let normalized_algorithm = normalize_an_algorithm(vm, realm, &algorithm, "deriveBits");++ // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.+ if let Err(error) = normalized_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. Let normalizedDerivedKeyAlgorithmImport be the result of normalizing an algorithm, with alg set to derivedKeyType and op set to "importKey".+ let normalized_derived_key_algorithm_import = normalize_an_algorithm(vm, realm, &derived_key_type, "importKey");++ // 5. If an error occurred, return a Promise rejected with normalizedDerivedKeyAlgorithmImport.+ if let Err(error) = normalized_derived_key_algorithm_import {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 6. Let normalizedDerivedKeyAlgorithmLength be the result of normalizing an algorithm, with alg set to derivedKeyType and op set to "get key length".+ let normalized_derived_key_algorithm_length =+ normalize_an_algorithm(vm, realm, &derived_key_type, "get key length");++ // 7. If an error occurred, return a Promise rejected with normalizedDerivedKeyAlgorithmLength.+ if let Err(error) = normalized_derived_key_algorithm_length {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 8. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 9. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (+ realm,+ normalized_algorithm.must(),+ promise,+ normalized_derived_key_algorithm_import.must(),+ normalized_derived_key_algorithm_length.must(),+ base_key,+ extractable,+ key_usages,+ ),+ |vm,+ (+ realm,+ normalized_algorithm,+ promise,+ normalized_derived_key_algorithm_import,+ normalized_derived_key_algorithm_length,+ base_key,+ extractable,+ key_usages,+ )| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 10. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.++ // 11. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of baseKey then throw an InvalidAccessError.+ if normalized_algorithm.name != base_key.algorithm_name() {+ reject_promise(+ vm,+ promise,+ dom_error("InvalidAccessError", b"Algorithm mismatch")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 12. If the [[usages]] internal slot of baseKey does not contain an entry that is "deriveKey", then throw an InvalidAccessError.+ if !base_key.internal_usages().contains(&KeyUsage::DeriveKey) {+ reject_promise(+ vm,+ promise,+ dom_error("InvalidAccessError", b"Key does not support deriving keys")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 13. Let length be the result of performing the get key length algorithm specified by normalizedDerivedKeyAlgorithmLength using derivedKeyType.+ let length_result = normalized_derived_key_algorithm_length.methods.get_key_length(realm);+ if let Err(error) = length_result {+ reject_promise_with_exception(vm, promise, error);+ return;+ }++ let length = length_result.must();++ // 14. Let secret be the result of performing the derive bits operation specified by normalizedAlgorithm using key, algorithm and length.+ let secret = normalized_algorithm.methods.derive_bits(realm, base_key, length);+ if let Err(error) = secret {+ reject_promise_with_exception(vm, promise, error);+ return;+ }++ // 15. Let result be the result of performing the import key operation specified by normalizedDerivedKeyAlgorithmImport using "raw" as format, secret as keyData, derivedKeyType as algorithm and using extractable and usages.+ let secret_bytes = secret.must();+ let result_or_error = normalized_derived_key_algorithm_import.methods.import_key(+ realm,+ KeyFormat::Raw,+ ImportKeyData::Bytes(secret_bytes),+ extractable,+ &key_usages,+ );+ if let Err(error) = result_or_error {+ reject_promise_with_exception(vm, promise, error);+ return;+ }+ let result = result_or_error.must();++ // 16. If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.+ if (result.key_type() == KeyType::Secret || result.key_type() == KeyType::Private)+ && key_usages.is_empty()+ {+ reject_promise(+ vm,+ promise,+ dom_error("SyntaxError", b"usages must not be empty")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 17. Set the [[extractable]] internal slot of result to extractable.+ result.set_extractable(extractable);++ // 18. Set the [[usages]] internal slot of result to the normalized value of usages.+ result.set_usages(normalized_key_usages(&key_usages));++ // 19. Resolve promise with result.+ resolve_crypto_key_promise(vm, realm, promise, result);+ });+ },+ );++ Ok(promise)+ }++ // https://w3c.github.io/webcrypto/#SubtleCrypto-method-wrapKey+ pub(crate) fn wrap_key(+ &self,+ cx: &mut CallContext,+ format: KeyFormat,+ key: Ref<CryptoKey>,+ wrapping_key: Ref<CryptoKey>,+ algorithm: AlgorithmIdentifier,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());+ // 5. Let realm be the relevant realm of this.+ // 1. Let format, key, wrappingKey and algorithm be the format, key, wrappingKey and wrapAlgorithm parameters passed to the wrapKey() method, respectively.++ let mut operation = "";+ let normalized_algorithm_or_error = (|| -> WebIdlResult<NormalizedAlgorithmAndParameter> {+ // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "wrapKey".+ let normalized_algorithm_wrap_key_or_error = normalize_an_algorithm(vm, realm, &algorithm, "wrapKey");++ // 3. If an error occurred, let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "encrypt".+ // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.+ if normalized_algorithm_wrap_key_or_error.is_err() {+ let normalized_algorithm_encrypt_or_error = normalize_an_algorithm(vm, realm, &algorithm, "encrypt");+ if let Err(error) = normalized_algorithm_encrypt_or_error {+ return Err(error);+ }++ operation = "encrypt";+ normalized_algorithm_encrypt_or_error+ } else {+ operation = "wrapKey";+ normalized_algorithm_wrap_key_or_error+ }+ })();+ if let Err(error) = normalized_algorithm_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ let normalized_algorithm = normalized_algorithm_or_error.must();++ // 6. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 7. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (+ realm,+ normalized_algorithm,+ promise,+ wrapping_key,+ key,+ format,+ operation,+ ),+ |vm, (realm, normalized_algorithm, promise, wrapping_key, key, format, operation)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // FIXME: 8. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.++ // 9. If the name member of normalizedAlgorithm is not equal to the name attribute+ // of the [[algorithm]] internal slot of wrappingKey then throw an InvalidAccessError.+ if normalized_algorithm.name != wrapping_key.algorithm_name() {+ reject_promise(+ vm,+ promise,+ dom_error("InvalidAccessError", b"Algorithm mismatch")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 10. If the [[usages]] internal slot of wrappingKey does not contain an entry that is "wrapKey", then throw an InvalidAccessError.+ if !wrapping_key.internal_usages().contains(&KeyUsage::WrapKey) {+ reject_promise(+ vm,+ promise,+ dom_error("InvalidAccessError", b"Key does not support wrapping keys")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 11. If the algorithm identified by the [[algorithm]] internal slot of key does not support the export key operation, then throw a NotSupportedError.+ // Note: Handled by the base AlgorithmMethods implementation++ // 12. If the [[extractable]] internal slot of key is false, then throw an InvalidAccessError.+ if !key.is_extractable() {+ reject_promise(+ vm,+ promise,+ dom_error("InvalidAccessError", b"Key is not extractable")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 13. Let exportedKey be the result of performing the export key operation specified by the [[algorithm]] internal slot of key using key and format.+ // NOTE: The spec does not mention we need to normalize this, but it's the only way we have to get to export_key.+ let normalized_key_algorithm = normalize_an_algorithm(+ vm,+ realm,+ &AlgorithmIdentifier::DOMString(key.algorithm_name()),+ "exportKey",+ );+ if let Err(error) = normalized_key_algorithm {+ reject_promise_with_exception(vm, promise, error);+ return;+ }++ let exported_key_or_error = normalized_key_algorithm.must().methods.export_key(realm, format, key);+ if let Err(error) = exported_key_or_error {+ reject_promise_with_exception(vm, promise, error);+ return;+ }++ // 14. If format is equal to the string "jwk":+ // 1. Let json be the result of representing exportedKey as a UTF-16 string conforming to the JSON grammar;+ // for example, by executing the JSON.stringify algorithm specified in [ECMA-262] in the context of a new+ // global object.+ // 2. Let bytes be the result of UTF-8 encoding json.+ // Otherwise:+ // Let bytes be exportedKey.+ let bytes_or_error = export_key_result_to_bytes(vm, exported_key_or_error.must());+ if let Err(error) = bytes_or_error {+ reject_promise_with_exception(vm, promise, error);+ return;+ }+ let bytes = bytes_or_error.must();++ // 15. If normalizedAlgorithm supports the wrap key operation:+ let result = if operation == "wrapKey" {+ // Let result be the result of performing the wrap key operation specified by normalizedAlgorithm+ // using algorithm, wrappingKey as key and bytes as plaintext.+ let result_or_error = normalized_algorithm.methods.wrap_key(realm, wrapping_key, &bytes);+ if let Err(error) = result_or_error {+ reject_promise_with_exception(vm, promise, error);+ return;+ }++ result_or_error.must()+ }+ // Otherwise, if normalizedAlgorithm supports the encrypt operation:+ else if operation == "encrypt" {+ // Let result be the result of performing the encrypt operation specified by normalizedAlgorithm+ // using algorithm, wrappingKey as key and bytes as plaintext.+ let result_or_error = normalized_algorithm.methods.encrypt(realm, wrapping_key, &bytes);+ if let Err(error) = result_or_error {+ reject_promise_with_exception(vm, promise, error);+ return;+ }++ result_or_error.must()+ }+ // Otherwise:+ else {+ // throw a NotSupportedError.+ reject_promise(+ vm,+ promise,+ dom_error("NotSupportedError", b"Algorithm does not support wrapping")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ };++ // FIXME: 16. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ // FIXME: 17. Let result be the result of creating an ArrayBuffer in realm, containing result.+ // 18. Resolve promise with result.+ resolve_promise(vm, promise, array_buffer(vm, realm, &result));+ });+ },+ );++ Ok(promise)+ }++ // https://w3c.github.io/webcrypto/#SubtleCrypto-method-unwrapKey+ pub(crate) fn unwrap_key(+ &self,+ cx: &mut CallContext,+ format: KeyFormat,+ wrapped_key: BufferSource,+ unwrapping_key: Ref<CryptoKey>,+ algorithm: AlgorithmIdentifier,+ unwrapped_key_algorithm: AlgorithmIdentifier,+ extractable: bool,+ key_usages: Vec<KeyUsage>,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());+ // 8. Let realm be the relevant realm of this.+ // 1. Let format, unwrappingKey, algorithm, unwrappedKeyAlgorithm, extractable and usages, be the format, unwrappingKey, unwrapAlgorithm,+ // unwrappedKeyAlgorithm, extractable and keyUsages parameters passed to the unwrapKey() method, respectively.++ let mut operation = "";+ let normalized_algorithm_or_error = (|| -> WebIdlResult<NormalizedAlgorithmAndParameter> {+ // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "unwrapKey".+ let normalized_algorithm_unwrap_key_or_error = normalize_an_algorithm(vm, realm, &algorithm, "unwrapKey");++ // 3. If an error occurred, let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "decrypt".+ // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.+ if normalized_algorithm_unwrap_key_or_error.is_err() {+ let normalized_algorithm_decrypt_or_error = normalize_an_algorithm(vm, realm, &algorithm, "decrypt");+ if let Err(error) = normalized_algorithm_decrypt_or_error {+ return Err(error);+ }++ operation = "decrypt";+ normalized_algorithm_decrypt_or_error+ } else {+ operation = "unwrapKey";+ normalized_algorithm_unwrap_key_or_error+ }+ })();+ if let Err(error) = normalized_algorithm_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ let normalized_algorithm = normalized_algorithm_or_error.must();++ // 5. Let normalizedKeyAlgorithm be the result of normalizing an algorithm, with alg set to unwrappedKeyAlgorithm and op set to "importKey".+ let normalized_key_algorithm_or_error =+ normalize_an_algorithm(vm, realm, &unwrapped_key_algorithm, "importKey");+ if let Err(error) = normalized_key_algorithm_or_error {+ // 6. If an error occurred, return a Promise rejected with normalizedKeyAlgorithm.+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ let normalized_key_algorithm = normalized_key_algorithm_or_error.must();++ // 7. Let wrappedKey be the result of getting a copy of the bytes held by the wrappedKey parameter passed to the unwrapKey() method.+ let real_wrapped_key_or_error = get_a_copy_of_the_bytes(vm, wrapped_key);+ if let Err(error) = real_wrapped_key_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let real_wrapped_key = real_wrapped_key_or_error.must();++ // 9. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 10. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (+ realm,+ normalized_algorithm,+ promise,+ unwrapping_key,+ real_wrapped_key,+ operation,+ format,+ (extractable, key_usages, normalized_key_algorithm),+ ),+ |vm,+ (+ realm,+ normalized_algorithm,+ promise,+ unwrapping_key,+ real_wrapped_key,+ operation,+ format,+ (extractable, key_usages, normalized_key_algorithm),+ )| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // FIXME: 11. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.++ // 12. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot+ // of unwrappingKey then throw an InvalidAccessError.+ if normalized_algorithm.name != unwrapping_key.algorithm_name() {+ reject_promise(+ vm,+ promise,+ dom_error("InvalidAccessError", b"Algorithm mismatch")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 13. If the [[usages]] internal slot of unwrappingKey does not contain an entry that is "unwrapKey", then throw an InvalidAccessError.+ if !unwrapping_key.internal_usages().contains(&KeyUsage::UnwrapKey) {+ reject_promise(+ vm,+ promise,+ dom_error("InvalidAccessError", b"Key does not support unwrapping keys")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 14. If normalizedAlgorithm supports an unwrap key operation:+ let bytes_or_error = if operation == "unwrapKey" {+ // Let bytes be the result of performing the unwrap key operation specified by normalizedAlgorithm+ // using algorithm, unwrappingKey as key and wrappedKey as ciphertext.+ normalized_algorithm+ .methods+ .unwrap_key(realm, unwrapping_key, &real_wrapped_key)+ }+ // Otherwise, if normalizedAlgorithm supports a decrypt operation:+ else if operation == "decrypt" {+ // Let bytes be the result of performing the decrypt operation specified by normalizedAlgorithm+ // using algorithm, unwrappingKey as key and wrappedKey as ciphertext.+ normalized_algorithm+ .methods+ .decrypt(realm, unwrapping_key, &real_wrapped_key)+ }+ // Otherwise:+ else {+ // throw a NotSupportedError.+ Err(dom_error("NotSupportedError", b"Algorithm does not support wrapping"))+ };+ if let Err(error) = bytes_or_error {+ reject_promise_with_exception(vm, promise, error);+ return;+ }++ let bytes = bytes_or_error.must();++ // 15. If format is equal to the string "jwk":+ let key = if format == KeyFormat::Jwk {+ // Let key be the result of executing the parse a JWK algorithm, with bytes as the data to be parsed.+ let maybe_parsed = parse_json_web_key(vm, bytes.as_slice());+ if let Err(error) = maybe_parsed {+ reject_promise_with_exception(vm, promise, error);+ return;+ }++ ImportKeyData::JsonWebKey(maybe_parsed.must())+ }+ // Otherwise:+ else {+ // Let key be bytes.+ ImportKeyData::Bytes(bytes)+ };++ // 16. Let result be the result of performing the import key operation specified by normalizedKeyAlgorithm+ // using unwrappedKeyAlgorithm as algorithm, format, usages and extractable and with key as keyData.+ let result_or_error =+ normalized_key_algorithm+ .methods+ .import_key(realm, format, key, extractable, &key_usages);+ if let Err(error) = result_or_error {+ reject_promise_with_exception(vm, promise, error);+ return;+ }++ let result = result_or_error.must();++ // 17. If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.+ if (result.key_type() == KeyType::Secret || result.key_type() == KeyType::Private)+ && key_usages.is_empty()+ {+ reject_promise(+ vm,+ promise,+ dom_error("SyntaxError", b"Usages must not be empty")+ .throw(&CallContext::new(vm, realm))+ .value(),+ );+ return;+ }++ // 18. Set the [[extractable]] internal slot of result to extractable.+ result.set_extractable(extractable);++ // 19. Set the [[usages]] internal slot of result to the normalized value of usages.+ result.set_usages(normalized_key_usages(&key_usages));++ // FIXME: 20. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ // FIXME: 21. Let result be the result of converting result to an ECMAScript Object in realm, as defined by [WebIDL].+ // 22. Resolve promise with result.+ resolve_crypto_key_promise(vm, realm, promise, result);+ });+ },+ );++ Ok(promise)+ }++ // https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-encapsulateKey+ pub(crate) fn encapsulate_key(+ &self,+ cx: &mut CallContext,+ encapsulation_algorithm: AlgorithmIdentifier,+ encapsulation_key: Ref<CryptoKey>,+ shared_key_algorithm: AlgorithmIdentifier,+ extractable: bool,+ key_usages: Vec<KeyUsage>,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());++ // 1. Let encapsulationAlgorithm, encapsulationKey, sharedKeyAlgorithm, extractable and usages be the+ // encapsulationAlgorithm, encapsulationKey, sharedKeyAlgorithm, extractable and keyUsages parameters passed to+ // the encapsulateKey() method, respectively.++ // 2. Let normalizedEncapsulationAlgorithm be the result of normalizing an algorithm, with alg set to+ // encapsulationAlgorithm and op set to "encapsulate".+ let maybe_normalized_encapsulation_algorithm =+ normalize_an_algorithm(vm, realm, &encapsulation_algorithm, "encapsulate");++ // 3. If an error occurred, return a Promise rejected with normalizedEncapsulationAlgorithm.+ if let Err(error) = maybe_normalized_encapsulation_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let normalized_encapsulation_algorithm = maybe_normalized_encapsulation_algorithm.must();++ // 4. Let normalizedSharedKeyAlgorithm be the result of normalizing an algorithm, with alg+ // set to sharedKeyAlgorithm and op set to "importKey".+ let maybe_normalized_shared_key_algorithm =+ normalize_an_algorithm(vm, realm, &shared_key_algorithm, "importKey");++ // 5. If an error occurred, return a Promise rejected with normalizedSharedKeyAlgorithm.+ if let Err(error) = maybe_normalized_shared_key_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let normalized_shared_key_algorithm = maybe_normalized_shared_key_algorithm.must();++ // 6. Let realm be the relevant realm of this.++ // 7. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 8. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (+ realm,+ normalized_encapsulation_algorithm,+ encapsulation_key,+ promise,+ normalized_shared_key_algorithm,+ extractable,+ key_usages,+ ),+ |vm,+ (+ realm,+ normalized_encapsulation_algorithm,+ encapsulation_key,+ promise,+ normalized_shared_key_algorithm,+ extractable,+ usages,+ )| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 9. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task+ // source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.+ let throw_in_this_context = |exception: Exception| {+ let value = exception.throw(&CallContext::new(vm, realm)).value();+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, value),+ |vm, (realm, promise, value)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise(vm, promise, value);+ });+ },+ );+ };++ // 10. If the name member of normalizedEncapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]+ // internal slot of encapsulationKey then throw an InvalidAccessError.+ if normalized_encapsulation_algorithm.name != encapsulation_key.algorithm_name() {+ throw_in_this_context(dom_error("InvalidAccessError", b"Invalid encapsulation key algorithm"));+ return;+ }++ // 11. If the [[usages]] internal slot of encapsulationKey does not contain an entry that is "encapsulateKey", then+ // throw an InvalidAccessError.+ if !encapsulation_key.internal_usages().contains(&KeyUsage::EncapsulateKey) {+ throw_in_this_context(dom_error("InvalidAccessError", b"Invalid encapsulation key usage"));+ return;+ }++ // 12. Let encapsulatedBits be the result of performing the encapsulate operation specified by the [[algorithm]]+ // internal slot of encapsulationKey using encapsulationKey.+ let maybe_encapsulated_bits = normalized_encapsulation_algorithm+ .methods+ .encapsulate(realm, encapsulation_key);+ if let Err(error) = maybe_encapsulated_bits {+ throw_in_this_context(error);+ return;+ }+ let encapsulated_bits = maybe_encapsulated_bits.must();++ // 13. Let sharedKey be the result of performing the import key operation specified by+ // normalizedSharedKeyAlgorithm using "raw-secret" as format, the sharedKey field of encapsulatedBits as+ // keyData, sharedKeyAlgorithm as algorithm and using extractable and usages.+ let maybe_shared_key = normalized_shared_key_algorithm.methods.import_key(+ realm,+ KeyFormat::RawSecret,+ ImportKeyData::Bytes(+ encapsulated_bits+ .shared_key+ .expect("encapsulation returns a shared key"),+ ),+ extractable,+ &usages,+ );+ if let Err(error) = maybe_shared_key {+ throw_in_this_context(error);+ return;+ }+ let shared_key = maybe_shared_key.must();++ // 14. Set the [[extractable]] internal slot of sharedKey to extractable.+ shared_key.set_extractable(extractable);++ // 15. Set the [[usages]] internal slot of sharedKey to the normalized value of usages.+ shared_key.set_usages(normalized_key_usages(&usages));++ // 16. Let encapsulatedKey be a new EncapsulatedKey dictionary with sharedKey set to sharedKey and ciphertext set+ // to the ciphertext field of encapsulatedBits.+ let encapsulated_key = EncapsulatedKeyData {+ shared_key,+ ciphertext: encapsulated_bits.ciphertext,+ };++ // 17. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, encapsulated_key),+ |vm, (realm, promise, encapsulated_key)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 18. Let result be the result of converting encapsulatedKey to an ECMAScript Object in realm, as defined by [WebIDL].+ let maybe_result = encapsulated_key_value(vm, realm, &encapsulated_key);+ if let Err(error) = maybe_result {+ reject_promise(vm, promise, error.value());+ return;+ }+ let result = maybe_result.must();++ // 19. Resolve promise with result.+ resolve_promise(vm, promise, result);+ });+ },+ );+ });+ },+ );++ Ok(promise)+ }++ // https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-encapsulateBits+ pub(crate) fn encapsulate_bits(+ &self,+ cx: &mut CallContext,+ encapsulation_algorithm: AlgorithmIdentifier,+ encapsulation_key: Ref<CryptoKey>,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());++ // 1. Let encapsulationAlgorithm and encapsulationKey be the encapsulationAlgorithm and encapsulationKey+ // parameters passed to the encapsulateBits() method, respectively.++ // 2. Let normalizedEncapsulationAlgorithm be the result of normalizing an algorithm, with alg set to+ // encapsulationAlgorithm and op set to "encapsulate".+ let maybe_normalized_encapsulation_algorithm =+ normalize_an_algorithm(vm, realm, &encapsulation_algorithm, "encapsulate");++ // 3. If an error occurred, return a Promise rejected with normalizedEncapsulationAlgorithm.+ if let Err(error) = maybe_normalized_encapsulation_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let normalized_encapsulation_algorithm = maybe_normalized_encapsulation_algorithm.must();++ // 4. Let realm be the relevant realm of this.++ // 5. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 6. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (realm, normalized_encapsulation_algorithm, promise, encapsulation_key),+ |vm, (realm, normalized_encapsulation_algorithm, promise, encapsulation_key)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 7. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task+ // source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.+ let throw_in_this_context = |exception: Exception| {+ let value = exception.throw(&CallContext::new(vm, realm)).value();+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, value),+ |vm, (realm, promise, value)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise(vm, promise, value);+ });+ },+ );+ };++ // 8. If the name member of normalizedEncapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]+ // internal slot of encapsulationKey then throw an InvalidAccessError.+ if normalized_encapsulation_algorithm.name != encapsulation_key.algorithm_name() {+ throw_in_this_context(dom_error("InvalidAccessError", b"Invalid encapsulation key algorithm"));+ return;+ }++ // 9. If the [[usages]] internal slot of encapsulationKey does not contain an entry that is "encapsulateBits", then+ // throw an InvalidAccessError.+ if !encapsulation_key.internal_usages().contains(&KeyUsage::EncapsulateBits) {+ throw_in_this_context(dom_error("InvalidAccessError", b"Invalid encapsulation key usages"));+ return;+ }++ // 10. Let encapsulatedBits be the result of performing the encapsulate operation specified by the [[algorithm]]+ // internal slot of encapsulationKey using encapsulationKey.+ let maybe_encapsulated_bits = normalized_encapsulation_algorithm+ .methods+ .encapsulate(realm, encapsulation_key);+ if let Err(error) = maybe_encapsulated_bits {+ throw_in_this_context(error);+ return;+ }+ let encapsulated_bits = maybe_encapsulated_bits.must();++ // 11. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, encapsulated_bits),+ |vm, (realm, promise, encapsulated_bits)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 12. Let result be the result of converting encapsulatedBits to an ECMAScript Object in realm, as defined by [WebIDL].+ let maybe_result = encapsulated_bits_value(vm, realm, &encapsulated_bits);+ if let Err(error) = maybe_result {+ reject_promise(vm, promise, error.value());+ return;+ }+ let result = maybe_result.must();++ // 13. Resolve promise with result.+ resolve_promise(vm, promise, result);+ });+ },+ );+ });+ },+ );++ Ok(promise)+ }++ // https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-decapsulateKey+ pub(crate) fn decapsulate_key(+ &self,+ cx: &mut CallContext,+ decapsulation_algorithm: AlgorithmIdentifier,+ decapsulation_key: Ref<CryptoKey>,+ ciphertext: BufferSource,+ shared_key_algorithm: AlgorithmIdentifier,+ extractable: bool,+ usages: Vec<KeyUsage>,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());++ // 1. Let decapsulationAlgorithm, decapsulationKey, sharedKeyAlgorithm, extractable and usages be the+ // decapsulationAlgorithm, decapsulationKey, sharedKeyAlgorithm, extractable and keyUsages parameters passed to+ // the decapsulateKey() method, respectively.++ // 2. Let normalizedDecapsulationAlgorithm be the result of normalizing an algorithm, with alg set to+ // decapsulationAlgorithm and op set to "decapsulate".+ let normalized_decapsulation_algorithm =+ normalize_an_algorithm(vm, realm, &decapsulation_algorithm, "decapsulate");++ // 3. If an error occurred, return a Promise rejected with normalizedDecapsulationAlgorithm.+ if let Err(error) = normalized_decapsulation_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. Let normalizedSharedKeyAlgorithm be the result of normalizing an algorithm, with alg+ // set to sharedKeyAlgorithm and op set to "importKey".+ let normalized_shared_key_algorithm = normalize_an_algorithm(vm, realm, &shared_key_algorithm, "importKey");++ // 5. If an error occurred, return a Promise rejected with normalizedSharedKeyAlgorithm.+ if let Err(error) = normalized_shared_key_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 6. Let ciphertext be the result of getting a copy of the bytes held by the ciphertext parameter passed to the+ // decapsulateKey() method.+ let cipher_text_or_error = get_a_copy_of_the_bytes(vm, ciphertext);+ if let Err(error) = cipher_text_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let cipher_text = cipher_text_or_error.must();++ // 7. Let realm be the relevant realm of this.++ // 8. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 9. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (+ realm,+ normalized_decapsulation_algorithm.must(),+ promise,+ decapsulation_key,+ cipher_text,+ normalized_shared_key_algorithm.must(),+ extractable,+ usages,+ ),+ |vm,+ (+ realm,+ normalized_decapsulation_algorithm,+ promise,+ decapsulation_key,+ cipher_text,+ normalized_shared_key_algorithm,+ extractable,+ usages,+ )| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 10. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task+ // source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.+ let throw_in_this_context = |exception: Exception| {+ let value = exception.throw(&CallContext::new(vm, realm)).value();+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, value),+ |vm, (realm, promise, value)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise(vm, promise, value);+ });+ },+ );+ };++ // 11. If the name member of normalizedDecapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]+ // internal slot of decapsulationKey then throw an InvalidAccessError.+ if normalized_decapsulation_algorithm.name != decapsulation_key.algorithm_name() {+ throw_in_this_context(dom_error("InvalidAccessError", b"Invalid algorithm name"));+ return;+ }++ // 12. If the [[usages]] internal slot of decapsulationKey does not contain an entry that is "decapsulateKey", then+ // throw an InvalidAccessError.+ if !decapsulation_key.internal_usages().contains(&KeyUsage::DecapsulateKey) {+ throw_in_this_context(dom_error("InvalidAccessError", b"Invalid key usages"));+ return;+ }+ // 13. Let decapsulatedBits be the result of performing the decapsulate operation specified by the [[algorithm]]+ // internal slot of decapsulationKey using decapsulationKey and ciphertext.+ let maybe_decapsulated_bits =+ normalized_decapsulation_algorithm+ .methods+ .decapsulate(realm, decapsulation_key, &cipher_text);+ if let Err(error) = maybe_decapsulated_bits {+ throw_in_this_context(error);+ return;+ }+ let decapsulated_bits = maybe_decapsulated_bits.must();++ // 14. Let sharedKey be the result of performing the import key operation specified by+ // normalizedSharedKeyAlgorithm using "raw-secret" as format, the decapsulatedBits as keyData,+ // sharedKeyAlgorithm as algorithm and using extractable and usages.+ let maybe_shared_key = normalized_shared_key_algorithm.methods.import_key(+ realm,+ KeyFormat::RawSecret,+ ImportKeyData::Bytes(decapsulated_bits),+ extractable,+ &usages,+ );+ if let Err(error) = maybe_shared_key {+ throw_in_this_context(error);+ return;+ }+ let shared_key = maybe_shared_key.must();++ // 15. Set the [[extractable]] internal slot of sharedKey to extractable.+ shared_key.set_extractable(extractable);++ // 16. Set the [[usages]] internal slot of sharedKey to the normalized value of usages.+ shared_key.set_usages(normalized_key_usages(&usages));++ // 17. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, shared_key),+ |vm, (realm, promise, shared_key)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 18. Let result be the result of converting sharedKey to an ECMAScript Object in realm, as defined by [WebIDL].+ // 19. Resolve promise with result.+ resolve_crypto_key_promise(vm, realm, promise, shared_key);+ });+ },+ );+ });+ },+ );++ Ok(promise)+ }++ // https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-decapsulateBits+ pub(crate) fn decapsulate_bits(+ &self,+ cx: &mut CallContext,+ decapsulation_algorithm: AlgorithmIdentifier,+ decapsulation_key: Ref<CryptoKey>,+ ciphertext: BufferSource,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());++ // 1. Let decapsulationAlgorithm and decapsulationKey be the decapsulationAlgorithm and decapsulationKey+ // parameters passed to the decapsulateBits() method, respectively.++ // 2. Let normalizedDecapsulationAlgorithm be the result of normalizing an algorithm, with alg set to+ // decapsulationAlgorithm and op set to "decapsulate".+ let normalized_decapsulation_algorithm =+ normalize_an_algorithm(vm, realm, &decapsulation_algorithm, "decapsulate");++ // 3. If an error occurred, return a Promise rejected with normalizedDecapsulationAlgorithm.+ if let Err(error) = normalized_decapsulation_algorithm {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. Let ciphertext be the result of getting a copy of the bytes held by the ciphertext parameter passed to the+ // decapsulateBits() method.+ let cipher_text_or_error = get_a_copy_of_the_bytes(vm, ciphertext);+ if let Err(error) = cipher_text_or_error {+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }+ let cipher_text = cipher_text_or_error.must();++ // 5. Let realm be the relevant realm of this.++ // 6. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 7. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (+ realm,+ normalized_decapsulation_algorithm.must(),+ promise,+ decapsulation_key,+ cipher_text,+ ),+ |vm, (realm, normalized_decapsulation_algorithm, promise, decapsulation_key, cipher_text)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 8. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task+ // source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.+ let throw_in_this_context = |exception: Exception| {+ let value = exception.throw(&CallContext::new(vm, realm)).value();+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, value),+ |vm, (realm, promise, value)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise(vm, promise, value);+ });+ },+ );+ };++ // 9. If the name member of normalizedDecapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]+ // internal slot of decapsulationKey then throw an InvalidAccessError.+ if normalized_decapsulation_algorithm.name != decapsulation_key.algorithm_name() {+ throw_in_this_context(dom_error("InvalidAccessError", b"Invalid algorithm name"));+ return;+ }++ // 10. If the [[usages]] internal slot of decapsulationKey does not contain an entry that is "decapsulateBits", then+ // throw an InvalidAccessError.+ if !decapsulation_key.internal_usages().contains(&KeyUsage::DecapsulateBits) {+ throw_in_this_context(dom_error("InvalidAccessError", b"Invalid key usages"));+ return;+ }++ // 11. Let decapsulatedBits be the result of performing the decapsulate operation specified by the [[algorithm]]+ // internal slot of decapsulationKey using decapsulationKey and ciphertext.+ let maybe_decapsulated_bits =+ normalized_decapsulation_algorithm+ .methods+ .decapsulate(realm, decapsulation_key, &cipher_text);+ if let Err(error) = maybe_decapsulated_bits {+ throw_in_this_context(error);+ return;+ }+ let decapsulated_bits = maybe_decapsulated_bits.must();++ // 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, decapsulated_bits),+ |vm, (realm, promise, decapsulated_bits)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 13. Let result be the result of creating an ArrayBuffer in realm, containing decapsulatedBits.+ // 14. Resolve promise with result.+ resolve_promise(vm, promise, array_buffer(vm, realm, &decapsulated_bits));+ });+ },+ );+ });+ },+ );++ Ok(promise)+ }++ // https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-getPublicKey+ pub(crate) fn get_public_key(+ &self,+ cx: &mut CallContext,+ key: Ref<CryptoKey>,+ key_usages: Vec<KeyUsage>,+ ) -> WebIdlResult<WebIdlPromise> {+ let (vm, realm) = (cx.vm(), cx.realm());++ // 1. Let key and usages be the key and keyUsages parameters passed to the getPublicKey() method, respectively.++ // 2. Let algorithm be the [[algorithm]] internal slot of key.+ // NB: Every algorithm that supports deriving a public key registers an export key operation, which lets us find+ // the algorithm's methods.+ let normalized_algorithm = normalize_an_algorithm(+ vm,+ realm,+ &AlgorithmIdentifier::DOMString(key.algorithm_name()),+ "exportKey",+ );++ // 3. If the cryptographic algorithm identified by algorithm does not support deriving a public key from a private+ // key, then return a Promise rejected with a NotSupportedError.+ let mut public_key_usages = None;+ if let Ok(normalized_algorithm) = normalized_algorithm {+ public_key_usages = normalized_algorithm.methods.public_key_usages();+ }+ if !public_key_usages.is_some() {+ let error = Exception::Dom(+ "NotSupportedError",+ libjs_rust::api::utf16_formatted(+ "Algorithm '{}' does not support deriving a public key",+ &[&key.algorithm_name()],+ ),+ );+ return Ok(create_rejected_promise_from_exception(vm, realm, error));+ }++ // 4. Let realm be the relevant realm of this.++ // 5. Let promise be a new Promise.+ let promise = create_promise(vm, realm);++ // 6. Return promise and perform the remaining steps in parallel.+ deferred_invoke(+ vm,+ (+ realm,+ promise,+ key,+ key_usages,+ public_key_usages.expect("the algorithm supports public keys"),+ ),+ |vm, (realm, promise, key, key_usages, public_key_usages)| {+ with_temporary_execution_context(realm, || {+ // 7. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto+ // task source, given realm's global object, to reject promise with the returned error; and then terminate+ // the algorithm.+ let throw_in_this_context = |exception: Exception| {+ let value = exception.throw(&CallContext::new(vm, realm)).value();+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, value),+ |vm, (realm, promise, value)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ reject_promise(vm, promise, value);+ });+ },+ );+ };++ // 8. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.+ if key.key_type() != KeyType::Private {+ throw_in_this_context(dom_error("InvalidAccessError", b"Key is not a private key"));+ return;+ }++ // 9. If usages contains an entry which is not supported for a public key by the algorithm identified by+ // algorithm, then throw a SyntaxError.+ for usage in &key_usages {+ if !public_key_usages.contains(usage) {+ throw_in_this_context(dom_error("SyntaxError", b"Invalid key usage for a public key"));+ return;+ }+ }++ // 10. Let publicKey be a new CryptoKey representing the public key corresponding to the private key represented+ // by the [[handle]] internal slot of key.+ let public_key_data = public_key_for_private_key(key);++ // 11. If an error occurred, then throw a OperationError.+ if public_key_data.is_none() {+ throw_in_this_context(dom_error("OperationError", b"Failed to derive the public key"));+ return;+ }+ let public_key = public_key_data.expect("the public key was derived");++ // 12. Set the [[type]] internal slot of publicKey to "public".+ public_key.set_type(KeyType::Public);++ // 13. Set the [[algorithm]] internal slot of publicKey to algorithm.+ public_key.set_algorithm(key.internal_algorithm().clone());++ // 14. Set the [[extractable]] internal slot of publicKey to true.+ public_key.set_extractable(true);++ // 15. Set the [[usages]] internal slot of publicKey to the normalized value of usages.+ public_key.set_usages(normalized_key_usages(&key_usages));++ // 16. Queue a global task on the crypto task source, given realm's global object, to perform the remaining+ // steps.+ queue_a_global_task(+ vm,+ realm.global_object(),+ TaskSource::Crypto,+ (realm, promise, public_key),+ |vm, (realm, promise, public_key)| {+ with_temporary_execution_context_and_callbacks(realm, || {+ // 17. Let result be the result of converting publicKey to an ECMAScript Object in realm, as defined by+ // [WebIDL].+ // 18. Resolve promise with result.+ resolve_crypto_key_promise(vm, realm, promise, public_key);+ });+ },+ );+ });+ },+ );++ Ok(promise)+ }++ // https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-supports+ pub(crate) fn supports_length(+ cx: &mut CallContext,+ operation: Utf16String,+ algorithm: AlgorithmIdentifier,+ length: Option<u32>,+ ) -> WebIdlResult<bool> {+ let (vm, realm) = (cx.vm(), cx.realm());+ let operation = String::from_utf16_lossy(&operation.to_utf16());+ // 1. If operation is not one of "encrypt", "decrypt", "sign", "verify", "digest", "generateKey", "deriveKey",+ // "deriveBits", "importKey", "exportKey", "wrapKey", "unwrapKey", "encapsulateKey", "encapsulateBits",+ // "decapsulateKey", "decapsulateBits" or "getPublicKey", return false.+ if !is_a_supported_operation(&operation) {+ return Ok(false);+ }++ // 2. Return the result of checking support for an algorithm, with op set to operation, alg set to algorithm, and+ // length set to length.+ Ok(check_support_for_an_algorithm(+ vm, realm, &operation, &algorithm, length,+ ))+ }++ // https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-supports-additionalAlgorithm+ pub(crate) fn supports_additional_algorithm(+ cx: &mut CallContext,+ operation: Utf16String,+ algorithm: AlgorithmIdentifier,+ additional_algorithm: AlgorithmIdentifier,+ ) -> WebIdlResult<bool> {+ let (vm, realm) = (cx.vm(), cx.realm());+ let operation = String::from_utf16_lossy(&operation.to_utf16());+ // 1. If operation is not one of "encrypt", "decrypt", "sign", "verify", "digest", "generateKey", "deriveKey",+ // "deriveBits", "importKey", "exportKey", "wrapKey", "unwrapKey", "encapsulateKey", "encapsulateBits",+ // "decapsulateKey", "decapsulateBits" or "getPublicKey", return false.+ if !is_a_supported_operation(&operation) {+ return Ok(false);+ }++ let mut op = operation.as_str();++ // 2. If operation is "deriveKey" or "unwrapKey":+ if matches!(op, "deriveKey" | "unwrapKey") {+ // 1. If the result of checking support for an algorithm with op set to "importKey" and alg set to+ // additionalAlgorithm is false, return false.+ if !check_support_for_an_algorithm(vm, realm, "importKey", &additional_algorithm, None) {+ return Ok(false);+ }+ }++ // 3. If operation is "wrapKey":+ if op == "wrapKey" {+ // 1. If the result of checking support for an algorithm with op set to "exportKey" and alg set to+ // additionalAlgorithm is false, return false.+ if !check_support_for_an_algorithm(vm, realm, "exportKey", &additional_algorithm, None) {+ return Ok(false);+ }+ }++ // 4. If operation is "encapsulateKey" or "decapsulateKey":+ if matches!(op, "encapsulateKey" | "decapsulateKey") {+ // 1. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set+ // to "get shared key length".+ let normalized_algorithm = normalize_an_algorithm(vm, realm, &algorithm, "get shared key length");++ // 2. If an error occurred, return false.+ if normalized_algorithm.is_err() {+ return Ok(false);+ }++ // 3. Let sharedKeyLength be the result of performing the get shared key length algorithm specified by+ // normalizedAlgorithm using algorithm.+ let shared_key_length = normalized_algorithm.must().methods.get_shared_key_length(realm);+ if shared_key_length.is_err() {+ return Ok(false);+ }++ // 4. Let normalizedAdditionalAlgorithm be the result of normalizing an algorithm, with alg set to+ // additionalAlgorithm and op set to "importKey".+ let normalized_additional_algorithm = normalize_an_algorithm(vm, realm, &additional_algorithm, "importKey");++ // 5. If an error occurred, return false.+ if normalized_additional_algorithm.is_err() {+ return Ok(false);+ }++ // 6. If the result of determining support from operation steps with op set to "importKey" and+ // normalizedAlgorithm set to normalizedAdditionalAlgorithm, and length set to null is false, return false.+ let normalized_additional_algorithm = normalized_additional_algorithm.must();+ if !determine_support_from_operation_steps(realm, "importKey", &normalized_additional_algorithm, None) {+ return Ok(false);+ }++ // 7. If the import key operation specified by normalizedAdditionalAlgorithm would throw an error for every value+ // of keyData that is a byte sequence whose length in bits is sharedKeyLength when format is "raw-secret",+ // return false.+ // NB: Whether importing secret key data fails depends on its length only, so importing zeroes of that length+ // tells whether every such keyData fails.+ let key_data = ImportKeyData::Bytes(Bytes::new(vec![0; shared_key_length.must().div_ceil(8) as usize]));+ let import_algorithm = normalized_additional_algorithm;+ if import_algorithm+ .methods+ .import_key(realm, KeyFormat::RawSecret, key_data, false, &[])+ .is_err()+ {+ return Ok(false);+ }+ }++ // 5. Let length be null.+ let mut length = None;++ // 6. If operation is "deriveKey":+ if op == "deriveKey" {+ // 1. If the result of checking support for an algorithm with op set to "get key length" and alg set to+ // additionalAlgorithm is false, return false.+ if !check_support_for_an_algorithm(vm, realm, "get key length", &additional_algorithm, None) {+ return Ok(false);+ }++ // 2. Let normalizedAdditionalAlgorithm be the result of normalizing an algorithm, with alg set to+ // additionalAlgorithm and op set to "get key length".+ // NB: Normalizing can run author code, so this second normalization can fail even though the first succeeded.+ let normalized_additional_algorithm =+ normalize_an_algorithm(vm, realm, &additional_algorithm, "get key length");+ if normalized_additional_algorithm.is_err() {+ return Ok(false);+ }++ // 3. Let length be the result of performing the get key length algorithm specified by additionalAlgorithm+ // using normalizedAdditionalAlgorithm.+ let normalized_length_algorithm = normalized_additional_algorithm.must();+ let key_length = normalized_length_algorithm.methods.get_key_length(realm);+ if key_length.is_err() {+ return Ok(false);+ }+ length = key_length.must();++ // 4. Set operation to "deriveBits".+ op = "deriveBits";+ }++ // 7. Return the result of checking support for an algorithm, with op set to operation, alg set to algorithm, and+ // length set to length.+ Ok(check_support_for_an_algorithm(vm, realm, op, &algorithm, length))+ }+}++// https://wicg.github.io/webcrypto-modern-algos/#dfn-determine-support-from-operation-steps+fn determine_support_from_operation_steps(+ realm: Gc<Realm>,+ op: &str,+ normalized_algorithm: &NormalizedAlgorithmAndParameter,+ length: Option<u32>,+) -> bool {+ let methods = &normalized_algorithm.methods;++ // 1. If the specified operation or normalized algorithm (or one of its parameter values) is expected to fail (for+ // any key and/or data) for an implementation-specific reason (e.g. known nonconformance to the specification),+ // return false.+ // NB: The validate_*_parameters() methods of the algorithms also reject parameters that we do not support.++ // 2. If op is "generateKey" or "importKey", let usages be the empty list.+ // NB: An empty list of usages never makes a step of these operations throw.++ // 3. For each of the steps of the operation specified by op of the algorithm specified by normalizedAlgorithm:+ // -> If the step says to throw an error: Return false.+ // -> If the step says to generate a key: Return true.+ // -> If the step relies on an unavailable parameter, such as key, plaintext or ciphertext: Return true.+ // -> If the step says to return a value: Return true.+ // -> Otherwise: Execute the step.+ // NB: The validate_*_parameters() methods of an algorithm perform the steps of its operations that come before the+ // first step that relies on an unavailable parameter, generates a key or returns a value. The operations that+ // have no such method rely on an unavailable parameter in their first steps. The get key length operation+ // relies on its parameters only, so we perform it in full.+ let result = (|| -> WebIdlResult<()> {+ if op == "encrypt" {+ return methods.validate_encrypt_parameters(realm);+ }+ if op == "decrypt" {+ return methods.validate_decrypt_parameters(realm);+ }+ if op == "sign" {+ return methods.validate_sign_parameters(realm);+ }+ if op == "verify" {+ return methods.validate_verify_parameters(realm);+ }+ if op == "digest" {+ return methods.validate_digest_parameters(realm);+ }+ if op == "generateKey" {+ return methods.validate_generate_key_parameters(realm);+ }+ if op == "importKey" {+ return methods.validate_import_key_parameters(realm);+ }+ if op == "deriveBits" {+ return methods.validate_derive_bits_parameters(realm, length);+ }+ if op == "get key length" {+ methods.get_key_length(realm)?;+ }+ Ok(())+ })();+ result.is_ok()+}++// https://wicg.github.io/webcrypto-modern-algos/#dfn-check-support-for-algorithm+fn check_support_for_an_algorithm(+ vm: &Vm,+ realm: Gc<Realm>,+ mut op: &str,+ alg: &AlgorithmIdentifier,+ length: Option<u32>,+) -> bool {+ // 1. If op is "encapsulateKey" or "encapsulateBits", set op to "encapsulate".+ if matches!(op, "encapsulateKey" | "encapsulateBits") {+ op = "encapsulate";+ }++ // 2. If op is "decapsulateKey" or "decapsulateBits", set op to "decapsulate".+ if matches!(op, "decapsulateKey" | "decapsulateBits") {+ op = "decapsulate";+ }++ // 3. If op is "getPublicKey":+ if op == "getPublicKey" {+ // 1. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to alg and op set to+ // "exportKey".+ let normalized_algorithm = normalize_an_algorithm(vm, realm, alg, "exportKey");++ // 2. If an error occurred, return false.+ if normalized_algorithm.is_err() {+ return false;+ }++ // 3. If the cryptographic algorithm identified by normalizedAlgorithm does not support deriving a public key+ // from a private key, then return false.+ // 4. Otherwise, return true.+ return normalized_algorithm.must().methods.public_key_usages().is_some();+ }++ // 4. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to alg and op set to op.+ let normalized_algorithm = normalize_an_algorithm(vm, realm, alg, op);++ // 5. If an error occurred:+ if normalized_algorithm.is_err() {+ // 1. If op is "wrapKey", return the result of checking support for an algorithm with op set to "encrypt" and+ // alg set to alg.+ if op == "wrapKey" {+ return check_support_for_an_algorithm(vm, realm, "encrypt", alg, None);+ }++ // 2. If op is "unwrapKey", return the result of checking support for an algorithm with op set to "decrypt" and+ // alg set to alg.+ if op == "unwrapKey" {+ return check_support_for_an_algorithm(vm, realm, "decrypt", alg, None);+ }++ // 3. Otherwise, return false.+ return false;+ }++ // 6. Return the result of determining support from operation steps, with op set to op, normalizedAlgorithm set to+ // normalizedAlgorithm, and length set to length.+ determine_support_from_operation_steps(realm, op, &normalized_algorithm.must(), length)+}++fn is_a_supported_operation(operation: &str) -> bool {+ matches!(+ operation,+ "encrypt"+ | "decrypt"+ | "sign"+ | "verify"+ | "digest"+ | "generateKey"+ | "deriveKey"+ | "deriveBits"+ | "importKey"+ | "exportKey"+ | "wrapKey"+ | "unwrapKey"+ | "encapsulateKey"+ | "encapsulateBits"+ | "decapsulateKey"+ | "decapsulateBits"+ | "getPublicKey"+ )+}++// https://w3c.github.io/webcrypto/#algorithm-normalization-internal+fn supported_algorithms() -> &'static SupportedAlgorithmsMap {+ static SUPPORTED_ALGORITHMS: LazyLock<SupportedAlgorithmsMap> = LazyLock::new(|| {+ let mut internal_object = HashMap::new();++ // 1. For each value, v in the List of supported operations,+ // set the v key of the internal object supportedAlgorithms to a new associative container.+ let supported_operations = [+ "encrypt",+ "decrypt",+ "sign",+ "verify",+ "digest",+ "deriveBits",+ "wrapKey",+ "unwrapKey",+ "generateKey",+ "importKey",+ "exportKey",+ "get key length",+ "encapsulate",+ "decapsulate",+ "get shared key length",+ ];++ for operation in supported_operations {+ internal_object.insert(operation, HashMap::new());+ }++ // https://w3c.github.io/webcrypto/#algorithm-conventions++ // https://w3c.github.io/webcrypto/#rsassa-pkcs1-registration+ define_an_algorithm(+ &mut internal_object,+ "sign",+ "RSASSA-PKCS1-v1_5",+ AlgorithmId::RsassaPkcs1,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "verify",+ "RSASSA-PKCS1-v1_5",+ AlgorithmId::RsassaPkcs1,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "RSASSA-PKCS1-v1_5",+ AlgorithmId::RsassaPkcs1,+ ParameterId::RsaHashedKeyGenParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "RSASSA-PKCS1-v1_5",+ AlgorithmId::RsassaPkcs1,+ ParameterId::RsaHashedImportParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "RSASSA-PKCS1-v1_5",+ AlgorithmId::RsassaPkcs1,+ ParameterId::AlgorithmParams,+ );++ // https://w3c.github.io/webcrypto/#rsa-pss-registration+ define_an_algorithm(+ &mut internal_object,+ "sign",+ "RSA-PSS",+ AlgorithmId::RsaPss,+ ParameterId::RsaPssParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "verify",+ "RSA-PSS",+ AlgorithmId::RsaPss,+ ParameterId::RsaPssParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "RSA-PSS",+ AlgorithmId::RsaPss,+ ParameterId::RsaHashedKeyGenParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "RSA-PSS",+ AlgorithmId::RsaPss,+ ParameterId::RsaHashedImportParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "RSA-PSS",+ AlgorithmId::RsaPss,+ ParameterId::AlgorithmParams,+ );++ // https://w3c.github.io/webcrypto/#rsa-oaep-registration+ define_an_algorithm(+ &mut internal_object,+ "encrypt",+ "RSA-OAEP",+ AlgorithmId::RsaOaep,+ ParameterId::RsaOaepParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "decrypt",+ "RSA-OAEP",+ AlgorithmId::RsaOaep,+ ParameterId::RsaOaepParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "RSA-OAEP",+ AlgorithmId::RsaOaep,+ ParameterId::RsaHashedKeyGenParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "RSA-OAEP",+ AlgorithmId::RsaOaep,+ ParameterId::RsaHashedImportParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "RSA-OAEP",+ AlgorithmId::RsaOaep,+ ParameterId::AlgorithmParams,+ );++ // https://w3c.github.io/webcrypto/#ecdsa-registration+ define_an_algorithm(+ &mut internal_object,+ "sign",+ "ECDSA",+ AlgorithmId::Ecdsa,+ ParameterId::EcdsaParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "verify",+ "ECDSA",+ AlgorithmId::Ecdsa,+ ParameterId::EcdsaParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "ECDSA",+ AlgorithmId::Ecdsa,+ ParameterId::EcKeyGenParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "ECDSA",+ AlgorithmId::Ecdsa,+ ParameterId::EcKeyImportParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "ECDSA",+ AlgorithmId::Ecdsa,+ ParameterId::AlgorithmParams,+ );++ // https://w3c.github.io/webcrypto/#ecdh-registration+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "ECDH",+ AlgorithmId::Ecdh,+ ParameterId::EcKeyImportParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "ECDH",+ AlgorithmId::Ecdh,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "deriveBits",+ "ECDH",+ AlgorithmId::Ecdh,+ ParameterId::EcdhKeyDeriveParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "ECDH",+ AlgorithmId::Ecdh,+ ParameterId::EcKeyGenParams,+ );++ // https://w3c.github.io/webcrypto/#aes-ctr-registration+ define_an_algorithm(+ &mut internal_object,+ "encrypt",+ "AES-CTR",+ AlgorithmId::AesCtr,+ ParameterId::AesCtrParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "decrypt",+ "AES-CTR",+ AlgorithmId::AesCtr,+ ParameterId::AesCtrParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "AES-CTR",+ AlgorithmId::AesCtr,+ ParameterId::AesKeyGenParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "AES-CTR",+ AlgorithmId::AesCtr,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "AES-CTR",+ AlgorithmId::AesCtr,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "get key length",+ "AES-CTR",+ AlgorithmId::AesCtr,+ ParameterId::AesDerivedKeyParams,+ );++ // https://w3c.github.io/webcrypto/#aes-cbc-registration+ define_an_algorithm(+ &mut internal_object,+ "encrypt",+ "AES-CBC",+ AlgorithmId::AesCbc,+ ParameterId::AesCbcParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "decrypt",+ "AES-CBC",+ AlgorithmId::AesCbc,+ ParameterId::AesCbcParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "AES-CBC",+ AlgorithmId::AesCbc,+ ParameterId::AesKeyGenParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "AES-CBC",+ AlgorithmId::AesCbc,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "AES-CBC",+ AlgorithmId::AesCbc,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "get key length",+ "AES-CBC",+ AlgorithmId::AesCbc,+ ParameterId::AesDerivedKeyParams,+ );++ // https://w3c.github.io/webcrypto/#aes-gcm-registration+ define_an_algorithm(+ &mut internal_object,+ "encrypt",+ "AES-GCM",+ AlgorithmId::AesGcm,+ ParameterId::AesGcmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "decrypt",+ "AES-GCM",+ AlgorithmId::AesGcm,+ ParameterId::AesGcmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "AES-GCM",+ AlgorithmId::AesGcm,+ ParameterId::AesKeyGenParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "AES-GCM",+ AlgorithmId::AesGcm,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "AES-GCM",+ AlgorithmId::AesGcm,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "get key length",+ "AES-GCM",+ AlgorithmId::AesGcm,+ ParameterId::AesDerivedKeyParams,+ );++ // https://w3c.github.io/webcrypto/#aes-kw-registration+ define_an_algorithm(+ &mut internal_object,+ "wrapKey",+ "AES-KW",+ AlgorithmId::AesKw,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "unwrapKey",+ "AES-KW",+ AlgorithmId::AesKw,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "AES-KW",+ AlgorithmId::AesKw,+ ParameterId::AesKeyGenParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "AES-KW",+ AlgorithmId::AesKw,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "AES-KW",+ AlgorithmId::AesKw,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "get key length",+ "AES-KW",+ AlgorithmId::AesKw,+ ParameterId::AesDerivedKeyParams,+ );++ // https://w3c.github.io/webcrypto/#hmac-registration+ define_an_algorithm(+ &mut internal_object,+ "sign",+ "HMAC",+ AlgorithmId::Hmac,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "verify",+ "HMAC",+ AlgorithmId::Hmac,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "HMAC",+ AlgorithmId::Hmac,+ ParameterId::HmacKeyGenParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "HMAC",+ AlgorithmId::Hmac,+ ParameterId::HmacImportParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "HMAC",+ AlgorithmId::Hmac,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "get key length",+ "HMAC",+ AlgorithmId::Hmac,+ ParameterId::HmacImportParams,+ );++ // https://w3c.github.io/webcrypto/#sha-registration+ define_an_algorithm(+ &mut internal_object,+ "digest",+ "SHA-1",+ AlgorithmId::Sha,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "digest",+ "SHA-256",+ AlgorithmId::Sha,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "digest",+ "SHA-384",+ AlgorithmId::Sha,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "digest",+ "SHA-512",+ AlgorithmId::Sha,+ ParameterId::AlgorithmParams,+ );++ // https://wicg.github.io/webcrypto-modern-algos/#sha3-registration+ define_an_algorithm(+ &mut internal_object,+ "digest",+ "SHA3-256",+ AlgorithmId::Sha,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "digest",+ "SHA3-384",+ AlgorithmId::Sha,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "digest",+ "SHA3-512",+ AlgorithmId::Sha,+ ParameterId::AlgorithmParams,+ );++ // https://wicg.github.io/webcrypto-modern-algos/#cshake-registration+ define_an_algorithm(+ &mut internal_object,+ "digest",+ "cSHAKE128",+ AlgorithmId::CShake,+ ParameterId::CShakeParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "digest",+ "cSHAKE256",+ AlgorithmId::CShake,+ ParameterId::CShakeParams,+ );++ // https://w3c.github.io/webcrypto/#hkdf-registration+ define_an_algorithm(+ &mut internal_object,+ "deriveBits",+ "HKDF",+ AlgorithmId::Hkdf,+ ParameterId::HkdfParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "HKDF",+ AlgorithmId::Hkdf,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "get key length",+ "HKDF",+ AlgorithmId::Hkdf,+ ParameterId::AlgorithmParams,+ );++ // https://w3c.github.io/webcrypto/#pbkdf2-registration+ define_an_algorithm(+ &mut internal_object,+ "deriveBits",+ "PBKDF2",+ AlgorithmId::Pbkdf2,+ ParameterId::Pbkdf2Params,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "PBKDF2",+ AlgorithmId::Pbkdf2,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "get key length",+ "PBKDF2",+ AlgorithmId::Pbkdf2,+ ParameterId::AlgorithmParams,+ );++ // https://wicg.github.io/webcrypto-secure-curves/#x25519-registration+ define_an_algorithm(+ &mut internal_object,+ "deriveBits",+ "X25519",+ AlgorithmId::X25519,+ ParameterId::EcdhKeyDeriveParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "X25519",+ AlgorithmId::X25519,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "X25519",+ AlgorithmId::X25519,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "X25519",+ AlgorithmId::X25519,+ ParameterId::AlgorithmParams,+ );++ // https://wicg.github.io/webcrypto-secure-curves/#x448-registration+ define_an_algorithm(+ &mut internal_object,+ "deriveBits",+ "X448",+ AlgorithmId::X448,+ ParameterId::EcdhKeyDeriveParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "X448",+ AlgorithmId::X448,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "X448",+ AlgorithmId::X448,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "X448",+ AlgorithmId::X448,+ ParameterId::AlgorithmParams,+ );++ // https://wicg.github.io/webcrypto-secure-curves/#ed25519-registration+ define_an_algorithm(+ &mut internal_object,+ "sign",+ "Ed25519",+ AlgorithmId::ED25519,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "verify",+ "Ed25519",+ AlgorithmId::ED25519,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "Ed25519",+ AlgorithmId::ED25519,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "Ed25519",+ AlgorithmId::ED25519,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "Ed25519",+ AlgorithmId::ED25519,+ ParameterId::AlgorithmParams,+ );++ // https://wicg.github.io/webcrypto-secure-curves/#ed448-registration+ define_an_algorithm(+ &mut internal_object,+ "sign",+ "Ed448",+ AlgorithmId::ED448,+ ParameterId::Ed448Params,+ );+ define_an_algorithm(+ &mut internal_object,+ "verify",+ "Ed448",+ AlgorithmId::ED448,+ ParameterId::Ed448Params,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "Ed448",+ AlgorithmId::ED448,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "Ed448",+ AlgorithmId::ED448,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "Ed448",+ AlgorithmId::ED448,+ ParameterId::AlgorithmParams,+ );++ // https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-registration+ for name in ["ML-DSA-44", "ML-DSA-65", "ML-DSA-87"] {+ define_an_algorithm(+ &mut internal_object,+ "sign",+ name,+ AlgorithmId::MlDsa,+ ParameterId::ContextParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "verify",+ name,+ AlgorithmId::MlDsa,+ ParameterId::ContextParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ name,+ AlgorithmId::MlDsa,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ name,+ AlgorithmId::MlDsa,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ name,+ AlgorithmId::MlDsa,+ ParameterId::AlgorithmParams,+ );+ }++ // https://wicg.github.io/webcrypto-modern-algos/#ml-kem-registration+ for name in ["ML-KEM-512", "ML-KEM-768", "ML-KEM-1024"] {+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ name,+ AlgorithmId::MlKem,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ name,+ AlgorithmId::MlKem,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ name,+ AlgorithmId::MlKem,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "encapsulate",+ name,+ AlgorithmId::MlKem,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "decapsulate",+ name,+ AlgorithmId::MlKem,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "get shared key length",+ name,+ AlgorithmId::MlKem,+ ParameterId::AlgorithmParams,+ );+ }++ // https://wicg.github.io/webcrypto-modern-algos/#argon2-registration+ for algorithm in ["Argon2d", "Argon2i", "Argon2id"] {+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ algorithm,+ AlgorithmId::Argon2,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "deriveBits",+ algorithm,+ AlgorithmId::Argon2,+ ParameterId::Argon2Params,+ );+ define_an_algorithm(+ &mut internal_object,+ "get key length",+ algorithm,+ AlgorithmId::Argon2,+ ParameterId::AlgorithmParams,+ );+ }++ // https://wicg.github.io/webcrypto-modern-algos/#chacha20-poly1305-registration+ define_an_algorithm(+ &mut internal_object,+ "encrypt",+ "ChaCha20-Poly1305",+ AlgorithmId::ChaCha20Poly1305,+ ParameterId::AeadParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "decrypt",+ "ChaCha20-Poly1305",+ AlgorithmId::ChaCha20Poly1305,+ ParameterId::AeadParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "ChaCha20-Poly1305",+ AlgorithmId::ChaCha20Poly1305,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "ChaCha20-Poly1305",+ AlgorithmId::ChaCha20Poly1305,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "ChaCha20-Poly1305",+ AlgorithmId::ChaCha20Poly1305,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "get key length",+ "ChaCha20-Poly1305",+ AlgorithmId::ChaCha20Poly1305,+ ParameterId::AlgorithmParams,+ );++ // https://wicg.github.io/webcrypto-modern-algos/#aes-ocb-registration+ define_an_algorithm(+ &mut internal_object,+ "encrypt",+ "AES-OCB",+ AlgorithmId::AesOcb,+ ParameterId::AeadParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "decrypt",+ "AES-OCB",+ AlgorithmId::AesOcb,+ ParameterId::AeadParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ "AES-OCB",+ AlgorithmId::AesOcb,+ ParameterId::AesKeyGenParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ "AES-OCB",+ AlgorithmId::AesOcb,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ "AES-OCB",+ AlgorithmId::AesOcb,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "get key length",+ "AES-OCB",+ AlgorithmId::AesOcb,+ ParameterId::AesDerivedKeyParams,+ );++ // https://wicg.github.io/webcrypto-modern-algos/#kmac-registration+ for algorithm in ["KMAC128", "KMAC256"] {+ define_an_algorithm(+ &mut internal_object,+ "sign",+ algorithm,+ AlgorithmId::Kmac,+ ParameterId::KmacParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "verify",+ algorithm,+ AlgorithmId::Kmac,+ ParameterId::KmacParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "generateKey",+ algorithm,+ AlgorithmId::Kmac,+ ParameterId::KmacKeyGenParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "importKey",+ algorithm,+ AlgorithmId::Kmac,+ ParameterId::KmacImportParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "exportKey",+ algorithm,+ AlgorithmId::Kmac,+ ParameterId::AlgorithmParams,+ );+ define_an_algorithm(+ &mut internal_object,+ "get key length",+ algorithm,+ AlgorithmId::Kmac,+ ParameterId::KmacImportParams,+ );+ }++ internal_object+ });+ &SUPPORTED_ALGORITHMS+}++// https://w3c.github.io/webcrypto/#concept-define-an-algorithm+fn define_an_algorithm(+ internal_object: &mut SupportedAlgorithmsMap,+ op: &'static str,+ algorithm: &'static str,+ method_id: AlgorithmId,+ parameter_id: ParameterId,+) {+ // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.+ // NOTE: There should always be a container at the op key.+ let registered_algorithms = internal_object.get_mut(op).expect("the operation has a container");++ // 2. Set the alg key of registeredAlgorithms to the IDL dictionary type type.+ registered_algorithms.insert(+ algorithm,+ RegisteredAlgorithm {+ method_id,+ parameter_id,+ },+ );+}++fn create_algorithm_dictionary(vm: &Vm, realm: Gc<Realm>, name: &Utf16String) -> WebIdlResult<Gc<Object>> {+ let dictionary = create_dictionary_object(&CallContext::new(vm, realm));+ dictionary.create_data_property(+ vm,+ &PropertyKey::from_utf8("name"),+ Value::from_string(PrimitiveString::create(vm, name.clone())),+ None,+ None,+ )?;+ Ok(dictionary)+}++/// # Safety+///+/// The caller supplies a live VM and realm, a live object or string, and writable output storage.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_crypto_normalize_an_algorithm(+ vm: *const c_void,+ realm: *mut c_void,+ object: *mut c_void,+ name: usize,+ operation: Span<'_, u8>,+ out: &mut *mut c_void,+) -> RawNativeFunctionResult {+ // SAFETY: The VM, realm, and algorithm value are live.+ let (vm, realm, algorithm) = unsafe {+ let vm = &*vm.cast::<Vm>();+ let realm = Gc::from_non_null(NonNull::new(realm.cast()).expect("the caller passes the realm"));+ let algorithm = if let Some(object) = NonNull::new(object.cast::<Object>()) {+ AlgorithmIdentifier::Object(Gc::from_non_null(object))+ } else {+ ak::reference_utf16_string(name);+ AlgorithmIdentifier::DOMString(Utf16String::from_raw_owned(name))+ };+ (vm, realm, algorithm)+ };+ let operation = std::str::from_utf8(operation.as_slice()).expect("an operation name is UTF-8");+ let result = normalize_an_algorithm(vm, realm, &algorithm, operation)+ .map(|normalized_algorithm| {+ *out = Rc::into_inner(normalized_algorithm.methods)+ .expect("a new algorithm has one owner")+ .into_raw();+ Value::UNDEFINED+ })+ .map_err(|exception| exception.throw(&CallContext::new(vm, realm)));+ RawNativeFunctionResult::from_completion(result)+}diff --git a/Libraries/LibWeb/Crypto/Crypto.cpp b/Libraries/LibWeb/Crypto/Crypto.cppindex 12448e0ba03..f2d01a1c1a2 100644--- a/Libraries/LibWeb/Crypto/Crypto.cpp+++ b/Libraries/LibWeb/Crypto/Crypto.cpp@@ -5,82 +5,35 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/ByteBuffer.h>#include <AK/Random.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/TypedArray.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Crypto/Crypto.h>-#include <LibWeb/Crypto/SubtleCrypto.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/QuotaExceededError.h>namespace Web::Crypto {-GC_DEFINE_ALLOCATOR(Crypto);--GC::Ref<Crypto> Crypto::create()-{- return GC::Heap::the().allocate<Crypto>();-}--Crypto::Crypto()- : m_subtle(SubtleCrypto::create())-{-}--Crypto::~Crypto() = default;--void Crypto::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_subtle);+extern "C" {+Crypto* web_rust_crypto_create(JSVM*);+void web_crypto_fill_with_random(Bytes);+void web_crypto_generate_random_uuid(void*, void (*)(void*, ReadonlyBytes));}-GC::Ref<SubtleCrypto> Crypto::subtle() const+GC::Ref<Crypto> Crypto::create(){- return *m_subtle;+ return *web_rust_crypto_create(JS::HostABI::vm_to_abi(JS::VM::the()));}-// https://w3c.github.io/webcrypto/#dfn-Crypto-method-getRandomValues-WebIDL::ExceptionOr<WebIDL::ArrayBufferViewVariant> Crypto::get_random_values(WebIDL::ArrayBufferViewVariant array) const+void web_crypto_fill_with_random(Bytes bytes){- WebIDL::ArrayBufferView array_view { array };-- // 1. If array is not an Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array, then throw a TypeMismatchError and terminate the algorithm.- auto typed_array = array_view.typed_array_base();- if (!typed_array)- return WebIDL::TypeMismatchError::create("array must be one of Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array"_utf16);-- if (!JS::typed_array_element_name(typed_array->kind()).is_one_of("Int8Array"sv, "Uint8Array"sv, "Uint8ClampedArray"sv, "Int16Array"sv, "Uint16Array"sv, "Int32Array"sv, "Uint32Array"sv, "BigInt64Array"sv, "BigUint64Array"sv))- return WebIDL::TypeMismatchError::create("array must be one of Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, or BigUint64Array"_utf16);-- auto typed_array_record = JS::make_typed_array_with_buffer_witness_record(*typed_array, JS::ArrayBuffer::Order::SeqCst);-- // IMPLEMENTATION DEFINED: If the viewed array buffer is out-of-bounds, throw a InvalidStateError and terminate the algorithm.- if (JS::is_typed_array_out_of_bounds(typed_array_record))- return WebIDL::InvalidStateError::create(Utf16String::formatted(JS::ErrorType::BufferOutOfBounds.format(), "TypedArray"sv));-- // 2. If the byteLength of array is greater than 65536, throw a QuotaExceededError and terminate the algorithm.- if (JS::typed_array_byte_length(typed_array_record) > 65536)- return WebIDL::QuotaExceededError::create("array's byteLength may not be greater than 65536"_utf16);-- // 3. Overwrite all elements of array with cryptographically strong random values of the appropriate type.- auto random_bytes = MUST(ByteBuffer::create_uninitialized(array_view.byte_length()));- fill_with_random(random_bytes);- array_view.viewed_array_buffer()->overwrite(array_view.byte_offset(), random_bytes.data(), random_bytes.size());-- // 4. Return array.- return array;+ fill_with_random(bytes);}-// https://w3c.github.io/webcrypto/#dfn-Crypto-method-randomUUID-Utf16String Crypto::random_uuid() const+void web_crypto_generate_random_uuid(void* state, void (*receive)(void*, ReadonlyBytes)){auto uuid = generate_random_uuid();- return Utf16String::from_ascii_without_validation(uuid.bytes_as_string_view().bytes());+ receive(state, uuid.bytes());}-// https://w3c.github.io/webcrypto/#dfn-generate-a-random-uuidString generate_random_uuid(){return AK::generate_random_uuid();diff --git a/Libraries/LibWeb/Crypto/Crypto.h b/Libraries/LibWeb/Crypto/Crypto.hindex 53e64aa1777..29770297f2a 100644--- a/Libraries/LibWeb/Crypto/Crypto.h+++ b/Libraries/LibWeb/Crypto/Crypto.h@@ -6,34 +6,17 @@#pragma once-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Crypto/SubtleCrypto.h>+#include <LibWeb/Bindings/Crypto.h>+#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Export.h>-#include <LibWeb/WebIDL/ExceptionOr.h>namespace Web::Crypto {-class Crypto : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(Crypto, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(Crypto);+class Crypto : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(Crypto, crypto)public:[[nodiscard]] static GC::Ref<Crypto> create();-- virtual ~Crypto() override;-- GC::Ref<SubtleCrypto> subtle() const;-- WebIDL::ExceptionOr<WebIDL::ArrayBufferViewVariant> get_random_values(WebIDL::ArrayBufferViewVariant) const;- Utf16String random_uuid() const;--protected:- virtual void visit_edges(GC::Cell::Visitor&) override;--private:- Crypto();-- GC::Ptr<SubtleCrypto> m_subtle;};WEB_API String generate_random_uuid();diff --git a/Libraries/LibWeb/Crypto/Crypto.idl b/Libraries/LibWeb/Crypto/Crypto.idlindex baa1f265e01..b35976bcc57 100644--- a/Libraries/LibWeb/Crypto/Crypto.idl+++ b/Libraries/LibWeb/Crypto/Crypto.idl@@ -3,7 +3,7 @@ partial interface mixin WindowOrWorkerGlobalScope {[SameObject] readonly attribute Crypto crypto;};-[Exposed=(Window,Worker)]+[Exposed=(Window,Worker),ImplementedIn=Rust]interface Crypto {[SecureContext] readonly attribute SubtleCrypto subtle;ArrayBufferView getRandomValues(ArrayBufferView array);diff --git a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h b/Libraries/LibWeb/Crypto/CryptoAlgorithms.hindex ba036758a8d..9cd9e37a354 100644--- a/Libraries/LibWeb/Crypto/CryptoAlgorithms.h+++ b/Libraries/LibWeb/Crypto/CryptoAlgorithms.h@@ -25,15 +25,8 @@ namespace Web::Crypto {using AlgorithmIdentifier = Variant<GC::Ref<JS::Object>, Utf16String>;using NamedCurve = Utf16String;-using KeyDataType = FlattenVariant<WebIDL::BufferSourceVariant, Variant<JsonWebKey>>;using ExportKeyResult = Variant<ByteBuffer, JsonWebKey>;-// https://wicg.github.io/webcrypto-modern-algos/#encapsulation-struct EncapsulatedKey {- Optional<GC::Root<CryptoKey>> shared_key;- Optional<ByteBuffer> ciphertext;-};-// https://wicg.github.io/webcrypto-modern-algos/#encapsulationstruct EncapsulatedBits {Optional<ByteBuffer> shared_key;diff --git a/Libraries/LibWeb/Crypto/CryptoBindings.cpp b/Libraries/LibWeb/Crypto/CryptoBindings.cppindex 29ee9921248..1c95e4ae913 100644--- a/Libraries/LibWeb/Crypto/CryptoBindings.cpp+++ b/Libraries/LibWeb/Crypto/CryptoBindings.cpp@@ -5,94 +5,18 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibJS/Runtime/Array.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/Object.h>-#include <LibJS/Runtime/Realm.h>-#include <LibJS/Runtime/ValueInlines.h>-#include <LibWeb/Bindings/CryptoKey.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/Crypto/CryptoAlgorithms.h>-#include <LibWeb/Crypto/CryptoBindings.h>-#include <LibWeb/WebIDL/DOMException.h>-#include <LibWeb/WebIDL/Promise.h>+#include <LibJS/HostClassBuilder.h>+#include <LibWeb/Crypto/CryptoKey.h>namespace Web::Crypto {-// 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 = 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.- // 5. Let key be the result of converting result to the IDL dictionary type of JsonWebKey.- 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 WebIDL::DataError::create("kty field is not defined"_utf16);-- // 7. Return key.- return key;-}--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));-}--JS::ThrowCompletionOr<GC::Ref<JS::Object>> encapsulated_bits(JS::Realm& realm, EncapsulatedBits const& encapsulated_bits)-{- auto object = JS::Object::create(realm, realm.intrinsics().object_prototype());-- if (encapsulated_bits.shared_key.has_value())- TRY(object->create_data_property("sharedKey"_utf16_fly_string, JS::ArrayBuffer::create(realm, encapsulated_bits.shared_key.value())));-- if (encapsulated_bits.ciphertext.has_value())- TRY(object->create_data_property("ciphertext"_utf16_fly_string, JS::ArrayBuffer::create(realm, encapsulated_bits.ciphertext.value())));-- return object;-}--JS::ThrowCompletionOr<GC::Ref<JS::Object>> encapsulated_key(JS::Realm& realm, EncapsulatedKey const& encapsulated_key)-{- auto object = JS::Object::create(realm, realm.intrinsics().object_prototype());-- if (encapsulated_key.shared_key.has_value())- TRY(object->create_data_property("sharedKey"_utf16_fly_string, Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref { *encapsulated_key.shared_key.value() })));-- if (encapsulated_key.ciphertext.has_value())- TRY(object->create_data_property("ciphertext"_utf16_fly_string, JS::ArrayBuffer::create(realm, encapsulated_key.ciphertext.value())));-- return object;-}--JS::Value crypto_key(JS::Realm& realm, GC::Ref<CryptoKey> key)-{- return Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, key);-}--JS::ThrowCompletionOr<GC::Ref<JS::Object>> crypto_key_pair(JS::Realm& realm, CryptoKeyPair const& key_pair)-{- auto object = JS::Object::create(realm, realm.intrinsics().object_prototype());- TRY(object->create_data_property_or_throw("publicKey"_utf16_fly_string, crypto_key(realm, key_pair.public_key)));- TRY(object->create_data_property_or_throw("privateKey"_utf16_fly_string, crypto_key(realm, key_pair.private_key)));- return object;-}+extern "C" JSCompletion web_rust_crypto_key_from_value(JSVM*, JSValue, CryptoKey**);JS::ThrowCompletionOr<GC::Ref<CryptoKey>> crypto_key_from_value(JS::VM& vm, JS::Value value){- auto key_object = TRY(value.to_object(vm));-- auto* key = Bindings::impl_from<CryptoKey>(&*key_object);- if (!key)- return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "CryptoKey");-+ CryptoKey* key = nullptr;+ TRY(JS::HostABI::completion_from_abi<void>(web_rust_crypto_key_from_value(+ JS::HostABI::vm_to_abi(vm), JS::HostABI::value_to_abi(value), &key)));return GC::Ref { *key };}diff --git a/Libraries/LibWeb/Crypto/CryptoBindings.h b/Libraries/LibWeb/Crypto/CryptoBindings.hindex e0ab4ea1436..661f32ee213 100644--- a/Libraries/LibWeb/Crypto/CryptoBindings.h+++ b/Libraries/LibWeb/Crypto/CryptoBindings.h@@ -16,20 +16,37 @@namespace Web::Crypto {-struct CryptoKeyPair;-struct EncapsulatedBits;-struct EncapsulatedKey;-using KeyFormat = Bindings::KeyFormat;-using RsaOtherPrimesInfo = Bindings::RsaOtherPrimesInfo;-using JsonWebKey = Bindings::JsonWebKey;--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&);-JS::Value crypto_key(JS::Realm&, GC::Ref<CryptoKey>);-JS::ThrowCompletionOr<GC::Ref<JS::Object>> crypto_key_pair(JS::Realm&, CryptoKeyPair const&);++struct RsaOtherPrimesInfo {+ Optional<Utf16String> d {};+ Optional<Utf16String> r {};+ Optional<Utf16String> t {};+};++struct JsonWebKey {+ Optional<Utf16String> alg {};+ Optional<Utf16String> crv {};+ Optional<Utf16String> d {};+ Optional<Utf16String> dp {};+ Optional<Utf16String> dq {};+ Optional<Utf16String> e {};+ Optional<bool> ext {};+ Optional<Utf16String> k {};+ Optional<Vector<Utf16String>> key_ops {};+ Optional<Utf16String> kty {};+ Optional<Utf16String> n {};+ Optional<Vector<RsaOtherPrimesInfo>> oth {};+ Optional<Utf16String> p {};+ Optional<Utf16String> priv {};+ Optional<Utf16String> pub {};+ Optional<Utf16String> q {};+ Optional<Utf16String> qi {};+ Optional<Utf16String> use {};+ Optional<Utf16String> x {};+ Optional<Utf16String> y {};+};+JS::ThrowCompletionOr<GC::Ref<CryptoKey>> crypto_key_from_value(JS::VM&, JS::Value);}diff --git a/Libraries/LibWeb/Crypto/CryptoKey.cpp b/Libraries/LibWeb/Crypto/CryptoKey.cppindex dbcf2abc750..7ac85cfca97 100644--- a/Libraries/LibWeb/Crypto/CryptoKey.cpp+++ b/Libraries/LibWeb/Crypto/CryptoKey.cpp@@ -7,9 +7,11 @@#include <AK/Memory.h>#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/HostObject.h>#include <LibJS/Runtime/Realm.h>#include <LibJS/Runtime/VM.h>#include <LibWeb/Bindings/RustSerialization.h>+#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/Crypto/CryptoKey.h>#include <LibWeb/Crypto/CryptoKeySerializationTags.h>#include <LibWeb/WebIDL/AbstractOperations.h>@@ -362,3 +364,16 @@ JSCompletion web_crypto_key_decode_handle(void* realm, CryptoKeyHandleFields con}}++namespace Web::Bindings {++extern "C" JSObject* web_rust_crypto_key_wrap(JSVM*, void*, Crypto::CryptoKey*);++GC::Ref<JS::HostObject> wrap(WrapperWorld& wrapper_world, JS::Realm& preferred_realm, GC::Ref<Crypto::CryptoKey> key)+{+ VERIFY(&wrapper_world == &host_defined_wrapper_world(preferred_realm));+ auto* wrapper = web_rust_crypto_key_wrap(JS::HostABI::vm_to_abi(preferred_realm.vm()), &preferred_realm, key.ptr());+ return as<JS::HostObject>(*JS::HostABI::object_from_abi(wrapper));+}++}diff --git a/Libraries/LibWeb/Crypto/CryptoKey.h b/Libraries/LibWeb/Crypto/CryptoKey.hindex b29edc22fe0..246bee6def3 100644--- a/Libraries/LibWeb/Crypto/CryptoKey.h+++ b/Libraries/LibWeb/Crypto/CryptoKey.h@@ -139,3 +139,9 @@ struct CryptoKeyPair {};}++namespace Web::Bindings {++WEB_API GC::Ref<JS::HostObject> wrap(WrapperWorld&, JS::Realm&, GC::Ref<Crypto::CryptoKey>);++}diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp b/Libraries/LibWeb/Crypto/SubtleCrypto.cppindex def4033d70f..92b07b5e598 100644--- a/Libraries/LibWeb/Crypto/SubtleCrypto.cpp+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.cpp@@ -6,1510 +6,389 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/ByteBuffer.h>-#include <AK/NeverDestroyed.h>#include <LibCrypto/Curves/EdwardsCurve.h>#include <LibCrypto/Curves/SECPxxxr1.h>-#include <LibCrypto/Hash/HashManager.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/ArrayBuffer.h>-#include <LibJS/Runtime/Object.h>-#include <LibJS/Runtime/PrimitiveString.h>-#include <LibJS/Runtime/ValueInlines.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/Realm.h>+#include <LibWeb/Bindings/RustSerialization.h>#include <LibWeb/Crypto/SubtleCrypto.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/Platform/EventLoopPlugin.h>-#include <LibWeb/WebIDL/AbstractOperations.h>-#include <LibWeb/WebIDL/Buffers.h>-#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWeb/WebIDL/ExceptionOrUtils.h>-#include <LibWeb/WebIDL/Promise.h>namespace Web::Crypto {-struct RegisteredAlgorithm {- NonnullOwnPtr<AlgorithmMethods> (*create_methods)() = nullptr;- JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> (*parameter_from_value)(JS::Realm&, JS::Value) = nullptr;+enum class AlgorithmId : u8 {+ RSASSAPKCS1,+ RSAPSS,+ RSAOAEP,+ ECDSA,+ ECDH,+ AesCtr,+ AesCbc,+ AesGcm,+ AesKw,+ HMAC,+ SHA,+ CShake,+ HKDF,+ PBKDF2,+ X25519,+ X448,+ ED25519,+ ED448,+ MLDSA,+ MLKEM,+ Argon2,+ ChaCha20Poly1305,+ AesOcb,+ KMAC,};-using RegisteredAlgorithms = HashMap<Utf16String, RegisteredAlgorithm>;-using SupportedAlgorithmsMap = HashMap<String, RegisteredAlgorithms>;-static SupportedAlgorithmsMap& supported_algorithms_internal();-static SupportedAlgorithmsMap const& supported_algorithms();-static void define_supported_algorithms();--template<typename Methods, typename Param = AlgorithmParams>-static void define_an_algorithm(String op, StringView algorithm);--GC_DEFINE_ALLOCATOR(SubtleCrypto);--// NB: Getting a copy of the bytes held by a buffer source can only fail when allocating the copy fails.-static WebIDL::ExceptionOr<ByteBuffer> get_a_copy_of_the_bytes(JS::VM& vm, WebIDL::BufferSource const& buffer_source)-{- return TRY_OR_THROW_OOM(vm, WebIDL::get_buffer_source_copy(buffer_source));-}--GC::Ref<SubtleCrypto> SubtleCrypto::create()-{- return GC::Heap::the().allocate<SubtleCrypto>();-}--SubtleCrypto::SubtleCrypto()-{-}--SubtleCrypto::~SubtleCrypto() = default;--static JS::ThrowCompletionOr<JS::Value> export_key_result_to_js_value(JS::Realm& realm, ExportKeyResult result)-{- if (result.has<ByteBuffer>())- return JS::Value(JS::ArrayBuffer::create(realm, move(result.get<ByteBuffer>())));-- return Bindings::json_web_key_to_value(realm, result.get<JsonWebKey>());-}--static JS::ThrowCompletionOr<ByteBuffer> export_key_result_to_bytes(JS::Realm& realm, ExportKeyResult result)-{- if (result.has<ByteBuffer>())- return move(result.get<ByteBuffer>());-- auto json = TRY(Bindings::json_web_key_to_json(realm.vm(), result.get<JsonWebKey>())).to_well_formed_utf8();- return MUST(ByteBuffer::copy(json.bytes()));-}--// https://w3c.github.io/webcrypto/#dfn-normalize-an-algorithm-WebIDL::ExceptionOr<NormalizedAlgorithmAndParameter> normalize_an_algorithm(JS::Realm& realm, AlgorithmIdentifier const& algorithm, String operation)-{- auto& vm = realm.vm();-- // If alg is an instance of a DOMString:- if (algorithm.has<Utf16String>()) {- // Return the result of running the normalize an algorithm algorithm,- // with the alg set to a new Algorithm dictionary whose name attribute is alg, and with the op set to op.- auto dictionary = TRY(Bindings::create_algorithm_dictionary(realm, algorithm.get<Utf16String>()));- return normalize_an_algorithm(realm, dictionary, operation);- }+enum class ParameterId : u8 {+ AlgorithmParams,+ RsaHashedKeyGenParams,+ RsaHashedImportParams,+ RsaPssParams,+ RsaOaepParams,+ EcdsaParams,+ EcKeyGenParams,+ EcKeyImportParams,+ EcdhKeyDeriveParams,+ AesCtrParams,+ AesKeyGenParams,+ AesDerivedKeyParams,+ AesCbcParams,+ AesGcmParams,+ HmacKeyGenParams,+ HmacImportParams,+ CShakeParams,+ HKDFParams,+ PBKDF2Params,+ Ed448Params,+ ContextParams,+ Argon2Params,+ AeadParams,+ KmacParams,+ KmacKeyGenParams,+ KmacImportParams,+};- // If alg is an object:- // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.- auto const& internal_object = supported_algorithms();- auto maybe_registered_algorithms = internal_object.get(operation);+struct RawRsaOtherPrimesInfo {+ FlatPtr d;+ FlatPtr r;+ FlatPtr t;+};- // NB: supports() can normalize with op set to "deriveKey", for which there is no container and thus no registered- // algorithm.- if (!maybe_registered_algorithms.has_value())- return WebIDL::NotSupportedError::create(Utf16String::formatted("Operation '{}' is not supported", operation));- auto registered_algorithms = maybe_registered_algorithms.value();+struct RawJsonWebKey {+ FlatPtr alg;+ FlatPtr crv;+ FlatPtr d;+ FlatPtr dp;+ FlatPtr dq;+ FlatPtr e;+ FlatPtr k;+ FlatPtr kty;+ FlatPtr n;+ FlatPtr p;+ FlatPtr priv;+ FlatPtr pub;+ FlatPtr q;+ FlatPtr qi;+ FlatPtr use;+ FlatPtr x;+ FlatPtr y;+ u8 ext;+ bool has_key_ops;+ ReadonlySpan<FlatPtr> key_ops;+ bool has_oth;+ ReadonlySpan<RawRsaOtherPrimesInfo> oth;+};- // 2. Let initialAlg be the result of converting the ECMAScript object represented by alg to- // the IDL dictionary type Algorithm, as defined by [WebIDL].- // 3. If an error occurred, return the error and terminate this algorithm.- // Note: We're not going to bother creating an Algorithm object, all we want is the name attribute so that we can- // fetch the actual algorithm factory from the registeredAlgorithms map.- auto initial_algorithm = TRY(algorithm.get<GC::Ref<JS::Object>>()->get("name"_utf16_fly_string));+struct OptionalLength {+ bool has_value;+ u32 value;- if (initial_algorithm.is_undefined()) {- return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Algorithm");+ Optional<u32> to_optional() const+ {+ if (has_value)+ return value;+ return {};}+};- // 4. Let algName be the value of the name attribute of initialAlg.- auto algorithm_name = TRY(initial_algorithm.to_utf16_string(vm));-- RegisteredAlgorithm desired_type;-- // 5. If registeredAlgorithms contains a key that is a case-insensitive string match for algName:- for (auto const& entry : registered_algorithms) {- if (!entry.key.equals_ignoring_ascii_case(algorithm_name))- continue;-- // 1. Set algName to the value of the matching key.- algorithm_name = entry.key;-- // 2. Let desiredType be the IDL dictionary type stored at algName in registeredAlgorithms.- desired_type = entry.value;- break;+using ReceiveBytes = void (*)(void*, ReadonlyBytes);+using ReceiveJsonWebKey = void (*)(void*, RawJsonWebKey const&);+using ReceiveUsages = void (*)(void*, ReadonlySpan<KeyUsage>);++extern "C" {+JSCompletion web_rust_crypto_normalize_an_algorithm(JSVM*, JS::Realm*, JSObject*, FlatPtr, ReadonlyBytes, NormalizedAlgorithmAndParameter**);+JSCompletion web_crypto_algorithm_from_value(JS::Realm*, AlgorithmId, ParameterId, JSValue, FlatPtr, NormalizedAlgorithmAndParameter**);+void web_crypto_algorithm_destroy(NormalizedAlgorithmAndParameter*);+void web_crypto_algorithm_public_key_usages(NormalizedAlgorithmAndParameter const*, void*, ReceiveUsages);+void web_crypto_normalized_key_usages(ReadonlySpan<KeyUsage>, void*, ReceiveUsages);+CryptoKey* web_crypto_public_key_for_private_key(CryptoKey const*);+JSCompletion web_crypto_algorithm_encrypt(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);+JSCompletion web_crypto_algorithm_decrypt(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);+JSCompletion web_crypto_algorithm_sign(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);+JSCompletion web_crypto_algorithm_verify(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes signature, ReadonlyBytes data, bool* out);+JSCompletion web_crypto_algorithm_digest(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, ReadonlyBytes data, void* state, ReceiveBytes receive);+JSCompletion web_crypto_algorithm_derive_bits(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, OptionalLength length, void* state, ReceiveBytes receive);+JSCompletion web_crypto_algorithm_import_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, KeyFormat format, ReadonlyBytes key_data, RawJsonWebKey const* jwk, bool extractable, ReadonlySpan<KeyUsage> usages, CryptoKey** out);+JSCompletion web_crypto_algorithm_generate_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, bool extractable, ReadonlySpan<KeyUsage> usages, CryptoKey** out_key, CryptoKey** out_public_key, CryptoKey** out_private_key);+JSCompletion web_crypto_algorithm_export_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, KeyFormat format, CryptoKey* key, void* state, ReceiveBytes receive_bytes, ReceiveJsonWebKey receive_jwk);+JSCompletion web_crypto_algorithm_get_key_length(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, OptionalLength* out);+JSCompletion web_crypto_algorithm_get_shared_key_length(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, u32* out);+JSCompletion web_crypto_algorithm_wrap_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);+JSCompletion web_crypto_algorithm_unwrap_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);+JSCompletion web_crypto_algorithm_encapsulate(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, void* shared_key, void* ciphertext, ReceiveBytes receive);+JSCompletion web_crypto_algorithm_decapsulate(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive);+JSCompletion web_crypto_algorithm_validate_encrypt_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);+JSCompletion web_crypto_algorithm_validate_decrypt_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);+JSCompletion web_crypto_algorithm_validate_sign_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);+JSCompletion web_crypto_algorithm_validate_verify_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);+JSCompletion web_crypto_algorithm_validate_digest_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);+JSCompletion web_crypto_algorithm_validate_generate_key_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);+JSCompletion web_crypto_algorithm_validate_import_key_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm);+JSCompletion web_crypto_algorithm_validate_derive_bits_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, OptionalLength length);+}++static Optional<Utf16String> string_from_raw(FlatPtr raw)+{+ if (raw)+ return Utf16String::from_raw(raw);+ return {};+}++static JsonWebKey json_web_key_from_raw(RawJsonWebKey const& raw)+{+ JsonWebKey key;+ key.alg = string_from_raw(raw.alg);+ key.crv = string_from_raw(raw.crv);+ key.d = string_from_raw(raw.d);+ key.dp = string_from_raw(raw.dp);+ key.dq = string_from_raw(raw.dq);+ key.e = string_from_raw(raw.e);+ key.k = string_from_raw(raw.k);+ key.kty = string_from_raw(raw.kty);+ key.n = string_from_raw(raw.n);+ key.p = string_from_raw(raw.p);+ key.priv = string_from_raw(raw.priv);+ key.pub = string_from_raw(raw.pub);+ key.q = string_from_raw(raw.q);+ key.qi = string_from_raw(raw.qi);+ key.use = string_from_raw(raw.use);+ key.x = string_from_raw(raw.x);+ key.y = string_from_raw(raw.y);+ if (raw.ext)+ key.ext = raw.ext == 2;+ if (raw.has_key_ops) {+ key.key_ops = Vector<Utf16String> {};+ for (auto value : raw.key_ops)+ key.key_ops->append(Utf16String::from_raw(value));}-- if (!desired_type.create_methods) {- // Otherwise:- // Return a new NotSupportedError and terminate this algorithm.- return WebIDL::NotSupportedError::create(Utf16String::formatted("Algorithm '{}' is not supported for operation '{}'", algorithm_name, operation));+ if (raw.has_oth) {+ key.oth = Vector<RsaOtherPrimesInfo> {};+ for (auto const& prime : raw.oth)+ key.oth->append(RsaOtherPrimesInfo { string_from_raw(prime.d), string_from_raw(prime.r), string_from_raw(prime.t) });}-- // 8. Let normalizedAlgorithm be the result of converting the ECMAScript object represented by alg- // to the IDL dictionary type desiredType, as defined by [WebIDL].- // 10. If an error occurred, return the error and terminate this algorithm.- // 11. Let dictionaries be a list consisting of the IDL dictionary type desiredType- // and all of desiredType's inherited dictionaries, in order from least to most derived.- // 12. For each dictionary dictionary in dictionaries:- // Note: All of these steps are handled by the create_methods and parameter_from_value methods.- auto methods = desired_type.create_methods();- auto parameter = TRY(desired_type.parameter_from_value(realm, algorithm.get<GC::Ref<JS::Object>>()));-- // 9. Set the name attribute of normalizedAlgorithm to algName.- VERIFY(parameter->name.is_empty());- parameter->name = algorithm_name;-- auto normalized_algorithm = NormalizedAlgorithmAndParameter { move(methods), move(parameter) };-- // 13. Return normalizedAlgorithm.- return normalized_algorithm;-}--// https://w3c.github.io/webcrypto/#SubtleCrypto-method-encrypt-GC::Ref<WebIDL::Promise> SubtleCrypto::encrypt(JS::Realm& realm, AlgorithmIdentifier const& algorithm, GC::Ref<CryptoKey> key, WebIDL::BufferSourceVariant const& data_parameter)-{- auto& vm = realm.vm();- auto& global = realm.global_object();-- // 1. Let algorithm and key be the algorithm and key parameters passed to the encrypt() method, respectively.-- // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "encrypt".- auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "encrypt"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.- if (normalized_algorithm.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());-- // 4. Let data be the result of getting a copy of the bytes held by the data parameter passed to the encrypt() method.- auto data_or_error = get_a_copy_of_the_bytes(vm, WebIDL::BufferSource { data_parameter });- if (data_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, data_or_error.release_error());- auto data = data_or_error.release_value();-- // 5. Let realm be the relevant realm of this.-- // 6. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, global, normalized_algorithm.release_value(), promise, key, move(data)), [](auto& realm, auto& global, auto& normalized_algorithm, auto& promise, auto& key, auto& data) -> void {- auto& heap = GC::Heap::the();- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);-- // 8. If the following steps or referenced procedures say to throw an error, queue a global task on the- // crypto task source, given realm's global object, to reject promise with the returned error and then terminate the algorithm.- auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- WebIDL::reject_promise(promise, value);- }));- };-- // 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.- if (normalized_algorithm.parameter->name != key->algorithm_name()) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Algorithm mismatch"_utf16)));- return;- }-- // 10. If the [[usages]] internal slot of key does not contain an entry that is "encrypt", then throw an InvalidAccessError.- if (!key->internal_usages().contains_slow(KeyUsage::Encrypt)) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Key does not support encryption"_utf16)));- return;- }-- // 11. Let ciphertext be the result of performing the encrypt operation specified by normalizedAlgorithm using algorithm and key and with data as plaintext.- auto cipher_text = normalized_algorithm.methods->encrypt(realm, *normalized_algorithm.parameter, key, data);- if (cipher_text.is_error()) {- throw_in_this_context(WebIDL::exception_to_throw_completion(realm.vm(), realm, cipher_text.release_error()));- return;- }-- // 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, cipher_text.release_value()), [](auto& realm, auto& promise, auto& cipher_text_bytes) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);-- // 13. Let result be the result of creating an ArrayBuffer in realm, containing ciphertext.- // 14. Resolve promise with result.- WebIDL::resolve_promise(promise, JS::ArrayBuffer::create(realm, move(cipher_text_bytes)));- }));- }));-- return promise;-}--// https://w3c.github.io/webcrypto/#SubtleCrypto-method-decrypt-GC::Ref<WebIDL::Promise> SubtleCrypto::decrypt(JS::Realm& realm, AlgorithmIdentifier const& algorithm, GC::Ref<CryptoKey> key, WebIDL::BufferSourceVariant const& data_parameter)-{- auto& vm = realm.vm();- auto& global = realm.global_object();-- // 1. Let algorithm and key be the algorithm and key parameters passed to the decrypt() method, respectively.-- // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "decrypt".- auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "decrypt"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.- if (normalized_algorithm.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());-- // 4. Let data be the result of getting a copy of the bytes held by the data parameter passed to the decrypt() method.- auto data_or_error = get_a_copy_of_the_bytes(vm, WebIDL::BufferSource { data_parameter });- if (data_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, data_or_error.release_error());- auto data = data_or_error.release_value();-- // 5. Let realm be the relevant realm of this.-- // 6. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, global, normalized_algorithm.release_value(), promise, key, move(data)), [](auto& realm, auto& global, auto& normalized_algorithm, auto& promise, auto& key, auto& data) -> void {- auto& heap = GC::Heap::the();- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);-- // 8. If the following steps or referenced procedures say to throw an error, queue a global task on the- // crypto task source, given realm's global object, to reject promise with the returned error and then terminate the algorithm.- auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- WebIDL::reject_promise(promise, value);- }));- };-- // 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of key then throw an InvalidAccessError.- if (normalized_algorithm.parameter->name != key->algorithm_name()) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Algorithm mismatch"_utf16)));- return;- }-- // 10. If the [[usages]] internal slot of key does not contain an entry that is "decrypt", then throw an InvalidAccessError.- if (!key->internal_usages().contains_slow(KeyUsage::Decrypt)) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Key does not support decryption"_utf16)));- return;- }-- // 11. Let plaintext be the result of performing the decrypt operation specified by normalizedAlgorithm using key and algorithm and with data as ciphertext.- auto plain_text = normalized_algorithm.methods->decrypt(realm, *normalized_algorithm.parameter, key, data);- if (plain_text.is_error()) {- throw_in_this_context(WebIDL::exception_to_throw_completion(realm.vm(), realm, plain_text.release_error()));- return;- }-- // 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, plain_text.release_value()), [](auto& realm, auto& promise, auto& plain_text_bytes) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);-- // 13. Let result be the result of creating an ArrayBuffer in realm, containing plaintext.- // 14. Resolve promise with result.- WebIDL::resolve_promise(promise, JS::ArrayBuffer::create(realm, move(plain_text_bytes)));- }));- }));-- return promise;+ return key;}-// https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-digest-GC::Ref<WebIDL::Promise> SubtleCrypto::digest(JS::Realm& realm, AlgorithmIdentifier const& algorithm, WebIDL::BufferSourceVariant const& data)+static FlatPtr raw_string(Optional<Utf16String> const& string){- auto& vm = realm.vm();- auto& global = realm.global_object();-- // 1. Let algorithm be the algorithm parameter passed to the digest() method.-- // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "digest".- auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "digest"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.- // FIXME: Spec bug: link to https://webidl.spec.whatwg.org/#a-promise-rejected-with- if (normalized_algorithm.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());-- // 4. Let data be the result of getting a copy of the bytes held by the data parameter passed to the digest() method.- auto data_buffer_or_error = get_a_copy_of_the_bytes(vm, WebIDL::BufferSource { data });- if (data_buffer_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, data_buffer_or_error.release_error());- auto data_buffer = data_buffer_or_error.release_value();-- // 5. Let realm be the relevant realm of this.-- // 6. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, global, normalized_algorithm.release_value(), promise, move(data_buffer)), [](auto& realm, auto& global, auto& algorithm_object, auto& promise, auto& data_buffer) -> void {- auto& heap = GC::Heap::the();- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);-- // 8. If the following steps or referenced procedures say to throw an error, queue a global task on the- // crypto task source, given realm's global object, to reject promise with the returned error and then terminate the algorithm.- auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- WebIDL::reject_promise(promise, value);- }));- };-- // 9. Let digest be the result of performing the digest operation specified by normalizedAlgorithm using algorithm, with data as message.- auto digest = algorithm_object.methods->digest(realm, *algorithm_object.parameter, data_buffer);-- if (digest.is_exception()) {- throw_in_this_context(WebIDL::exception_to_throw_completion(realm.vm(), realm, digest.release_error()));- return;- }-- // 10. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, digest.release_value()), [](auto& realm, auto& promise, auto& digest_bytes) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);-- // 11. Let result be the result of creating an ArrayBuffer in realm, containing digest.- // 12. Resolve promise with result.- WebIDL::resolve_promise(promise, JS::ArrayBuffer::create(realm, move(digest_bytes)));- }));- }));-- return promise;+ return string.has_value() ? string->raw_identity() : 0;}-// https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-generateKey-GC::Ref<WebIDL::Promise> SubtleCrypto::generate_key(JS::Realm& realm, AlgorithmIdentifier algorithm, bool extractable, Vector<KeyUsage> key_usages)+static void with_raw_json_web_key(JsonWebKey const& key, void* state, ReceiveJsonWebKey receive){- // 1. Let algorithm, extractable and usages be the algorithm, extractable and keyUsages- // parameters passed to the generateKey() method, respectively.-- // 2. Let normalizedAlgorithm be the result of normalizing an algorithm,- // with alg set to algorithm and op set to "generateKey".- auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "generateKey"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.- if (normalized_algorithm.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());-- // 4. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 5. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, normalized_algorithm.release_value(), promise, extractable, move(key_usages)), [](auto& realm, auto& normalized_algorithm, auto& promise, auto& extractable, auto& key_usages) -> void {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // 6. If the following steps or referenced procedures say to throw an error, reject promise with- // the returned error and then terminate the algorithm.-- // 7. Let result be the result of performing the generate key operation specified by normalizedAlgorithm- // using algorithm, extractable and usages.- auto result_or_error = normalized_algorithm.methods->generate_key(realm, *normalized_algorithm.parameter, extractable, key_usages);-- if (result_or_error.is_error()) {- WebIDL::reject_promise_with_exception(promise, result_or_error.release_error());- return;- }- auto result = result_or_error.release_value();-- // 8. If result is a CryptoKey object:- // If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.- // If result is a CryptoKeyPair object:- // If the [[usages]] internal slot of the privateKey attribute of result is the empty sequence, then throw a SyntaxError.- // 9. Resolve promise with result.- result.visit(- [&](GC::Ref<CryptoKey>& key) {- if ((key->type() == KeyType::Secret || key->type() == KeyType::Private) && key_usages.is_empty()) {- WebIDL::reject_promise(promise, WebIDL::SyntaxError::create("usages must not be empty"_utf16));- return;- }- resolve_crypto_key_promise(realm, promise, key);- },- [&](CryptoKeyPair& key_pair) {- if (key_pair.private_key->internal_usages().is_empty()) {- WebIDL::reject_promise(promise, WebIDL::SyntaxError::create("usages must not be empty"_utf16));- return;- }- auto object = crypto_key_pair(realm, key_pair);- if (object.is_error()) {- WebIDL::reject_promise_with_exception(promise, object.release_error());- return;- }- WebIDL::resolve_promise(promise, object.release_value());- });- }));-- return promise;-}--// https://w3c.github.io/webcrypto/#SubtleCrypto-method-importKey-GC::Ref<WebIDL::Promise> SubtleCrypto::import_key(JS::Realm& realm, KeyFormat format, KeyDataType key_data, AlgorithmIdentifier algorithm, bool extractable, Vector<KeyUsage> key_usages)-{- // 1. Let format, algorithm, extractable and usages, be the format, algorithm, extractable and keyUsages- // parameters passed to the importKey() method, respectively.-- // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "importKey".- auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "importKey"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.- if (normalized_algorithm.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());-- Variant<ByteBuffer, JsonWebKey, Empty> real_key_data;-- // 4. If format is equal to the string "jwk":- if (format == KeyFormat::Jwk) {- // 1. If the keyData parameter passed to the importKey() method is not a JsonWebKey dictionary, throw a TypeError.- if (!key_data.has<JsonWebKey>())- return WebIDL::create_rejected_promise_from_exception(realm, realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "JsonWebKey"));-- // 2. Let keyData be the keyData parameter passed to the importKey() method.- real_key_data = move(key_data.get<JsonWebKey>());+ Vector<FlatPtr> key_ops;+ if (key.key_ops.has_value()) {+ for (auto const& value : *key.key_ops)+ key_ops.append(value.raw_identity());}- // Otherwise:- else {- // 1. If the keyData parameter passed to the importKey() method is a JsonWebKey dictionary, throw a TypeError.- if (key_data.has<JsonWebKey>())- return WebIDL::create_rejected_promise_from_exception(realm, realm.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "BufferSource"));-- // 2. Let keyData be the result of getting a copy of the bytes held by the keyData parameter passed to the- // importKey() method.- auto key_data_or_error = get_a_copy_of_the_bytes(realm.vm(), WebIDL::BufferSource { key_data.downcast<WebIDL::BufferSourceVariant>() });- if (key_data_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, key_data_or_error.release_error());- real_key_data = key_data_or_error.release_value();+ Vector<RawRsaOtherPrimesInfo> oth;+ if (key.oth.has_value()) {+ for (auto const& prime : *key.oth)+ oth.append(RawRsaOtherPrimesInfo { raw_string(prime.d), raw_string(prime.r), raw_string(prime.t) });}-- // 5. Let realm be the relevant realm of this.-- // 6. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, move(real_key_data), normalized_algorithm.release_value(), promise, format, extractable, move(key_usages)), [](auto& realm, auto& real_key_data, auto& normalized_algorithm, auto& promise, auto& format, auto& extractable, auto& key_usages) -> void {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);-- // FIXME: 8. If the following steps or referenced procedures say to throw an error, queue a global task on the- // crypto task source, given realm's global object, to reject promise with the returned error; and then- // terminate the algorithm.-- // 9. Let result be the CryptoKey object that results from performing the import key operation- // specified by normalizedAlgorithm using keyData, algorithm, format, extractable and usages.- auto maybe_result = normalized_algorithm.methods->import_key(realm, *normalized_algorithm.parameter, format, real_key_data.template downcast<CryptoKey::ImportKeyData>(), extractable, key_usages);- if (maybe_result.is_error()) {- WebIDL::reject_promise_with_exception(promise, maybe_result.release_error());- return;- }- auto result = maybe_result.release_value();-- // 10. If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.- if ((result->type() == KeyType::Secret || result->type() == KeyType::Private) && key_usages.is_empty()) {- WebIDL::reject_promise(promise, WebIDL::SyntaxError::create("usages must not be empty"_utf16));- return;- }-- // 11. Set the [[extractable]] internal slot of result to extractable.- result->set_extractable(extractable);-- // 12. Set the [[usages]] internal slot of result to the normalized value of usages.- result->set_usages(normalized_key_usages(key_usages));-- // FIXME: 13. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- // FIXME: 14. Let result be the result of converting result to an ECMAScript Object in realm, as defined by [WebIDL].-- // 15. Resolve promise with result.- resolve_crypto_key_promise(realm, promise, result);- }));-- return promise;-}--// https://w3c.github.io/webcrypto/#dfn-SubtleCrypto-method-exportKey-GC::Ref<WebIDL::Promise> SubtleCrypto::export_key(JS::Realm& realm, KeyFormat format, GC::Ref<CryptoKey> key)-{- // 1. Let format and key be the format and key parameters passed to the exportKey() method, respectively.-- // 2. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 3. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, key, promise, format), [](auto& realm, auto& key, auto& promise, auto& format) -> void {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // 4. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.-- // 5. If the name member of the [[algorithm]] internal slot of key does not identify a registered algorithm that supports the export key operation,- // then throw a NotSupportedError.- // Note: Handled by the base AlgorithmMethods implementation- // FIXME: Stash the AlgorithmMethods on the KeyAlgorithm- auto normalized_algorithm_or_error = normalize_an_algorithm(realm, key->algorithm_name(), "exportKey"_string);- if (normalized_algorithm_or_error.is_error()) {- WebIDL::reject_promise_with_exception(promise, normalized_algorithm_or_error.release_error());- return;- }- auto normalized_algorithm = normalized_algorithm_or_error.release_value();-- // 6. If the [[extractable]] internal slot of key is false, then throw an InvalidAccessError.- if (!key->extractable()) {- WebIDL::reject_promise(promise, WebIDL::InvalidAccessError::create("Key is not extractable"_utf16));- return;- }-- // 7. Let result be the result of performing the export key operation specified by the [[algorithm]] internal slot of key using key and format.- auto result_or_error = normalized_algorithm.methods->export_key(realm, format, key);- if (result_or_error.is_error()) {- WebIDL::reject_promise_with_exception(promise, result_or_error.release_error());- return;- }-- // 8. Resolve promise with result.- auto result = export_key_result_to_js_value(realm, result_or_error.release_value());- if (result.is_error()) {- WebIDL::reject_promise(promise, result.release_error().release_value());- return;- }- WebIDL::resolve_promise(promise, result.release_value());- }));-- return promise;-}--// https://w3c.github.io/webcrypto/#SubtleCrypto-method-sign-GC::Ref<WebIDL::Promise> SubtleCrypto::sign(JS::Realm& realm, AlgorithmIdentifier const& algorithm, GC::Ref<CryptoKey> key, WebIDL::BufferSourceVariant const& data_parameter)-{- auto& vm = realm.vm();- auto& global = realm.global_object();-- // 1. Let algorithm and key be the algorithm and key parameters passed to the sign() method, respectively.-- // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "sign".- auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "sign"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.- if (normalized_algorithm.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());-- // 4. Let data be the result of getting a copy of the bytes held by the data parameter passed to the sign() method.- auto data_or_error = get_a_copy_of_the_bytes(vm, WebIDL::BufferSource { data_parameter });- if (data_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, data_or_error.release_error());- auto data = data_or_error.release_value();-- // 5. Let realm be the relevant realm of this.-- // 6. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, global, normalized_algorithm.release_value(), promise, key, move(data)), [](auto& realm, auto& global, auto& normalized_algorithm, auto& promise, auto& key, auto& data) {- auto& heap = GC::Heap::the();- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);-- // 8. If the following steps or referenced procedures say to throw an error, queue a global task on the- // crypto task source, given realm's global object, to reject promise with the returned error; and then- // terminate the algorithm.- auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- WebIDL::reject_promise(promise, value);- }));- };-- // 9. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]]- // internal slot of key then throw an InvalidAccessError.- if (normalized_algorithm.parameter->name != key->algorithm_name()) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Algorithm mismatch"_utf16)));- return;- }-- // 10. If the [[usages]] internal slot of key does not contain an entry that is "sign", then throw an InvalidAccessError.- if (!key->internal_usages().contains_slow(KeyUsage::Sign)) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Key does not support signing"_utf16)));- return;- }-- // 11. Let signature be the result of performing the sign operation specified by normalizedAlgorithm using key- // and algorithm and with data as message.- auto signature = normalized_algorithm.methods->sign(realm, *normalized_algorithm.parameter, key, data);- if (signature.is_error()) {- throw_in_this_context(WebIDL::exception_to_throw_completion(realm.vm(), realm, signature.release_error()));- return;- }-- // 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, signature.release_value()), [](auto& realm, auto& promise, auto& signature_bytes) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);-- // 13. Let result be the result of creating an ArrayBuffer in realm, containing signature.- // 14. Resolve promise with result.- WebIDL::resolve_promise(promise, JS::ArrayBuffer::create(realm, move(signature_bytes)));- }));- }));-- return promise;-}--// https://w3c.github.io/webcrypto/#SubtleCrypto-method-verify-GC::Ref<WebIDL::Promise> SubtleCrypto::verify(JS::Realm& realm, AlgorithmIdentifier const& algorithm, GC::Ref<CryptoKey> key, WebIDL::BufferSourceVariant const& signature_data, WebIDL::BufferSourceVariant const& data_parameter)-{- auto& vm = realm.vm();- auto& global = realm.global_object();-- // 1. Let algorithm and key be the algorithm and key parameters passed to the verify() method, respectively.-- // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "verify".- auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "verify"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.- if (normalized_algorithm.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());-- // 4. Let signature be the result of getting a copy of the bytes held by the signature parameter passed to the verify() method.- auto signature_or_error = get_a_copy_of_the_bytes(vm, WebIDL::BufferSource { signature_data });- if (signature_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, signature_or_error.release_error());- auto signature = signature_or_error.release_value();-- // 5. Let data be the result of getting a copy of the bytes held by the data parameter passed to the verify() method.- auto data_or_error = get_a_copy_of_the_bytes(vm, WebIDL::BufferSource { data_parameter });- if (data_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, data_or_error.release_error());- auto data = data_or_error.release_value();-- // 6. Let realm be the relevant realm of this.-- // 7. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 8. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, global, normalized_algorithm.release_value(), promise, key, move(signature), move(data)), [](auto& realm, auto& global, auto& normalized_algorithm, auto& promise, auto& key, auto& signature, auto& data) {- auto& heap = GC::Heap::the();- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);-- // 9. If the following steps or referenced procedures say to throw an error, queue a global task on the- // crypto task source, given realm's global object, to reject promise with the returned error; and then- // terminate the algorithm.- auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- WebIDL::reject_promise(promise, value);- }));- };-- // 10. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]]- // internal slot of key then throw an InvalidAccessError.- if (normalized_algorithm.parameter->name != key->algorithm_name()) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Algorithm mismatch"_utf16)));- return;- }-- // 11. If the [[usages]] internal slot of key does not contain an entry that is "verify", then throw an InvalidAccessError.- if (!key->internal_usages().contains_slow(KeyUsage::Verify)) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Key does not support verification"_utf16)));- return;- }-- // 12. Let result be the result of performing the verify operation specified by normalizedAlgorithm using key,- // algorithm and signature and with data as message.- auto result = normalized_algorithm.methods->verify(realm, *normalized_algorithm.parameter, key, signature, data);- if (result.is_error()) {- throw_in_this_context(WebIDL::exception_to_throw_completion(realm.vm(), realm, result.release_error()));- return;- }-- // 13. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, result.release_value()), [](auto& realm, auto& promise, auto& verification_result) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);-- // 14. Resolve promise with result.- WebIDL::resolve_promise(promise, JS::Value(verification_result));- }));- }));-- return promise;-}--// https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveBits-GC::Ref<WebIDL::Promise> SubtleCrypto::derive_bits(JS::Realm& realm, AlgorithmIdentifier algorithm, GC::Ref<CryptoKey> base_key, Optional<u32> length_optional)-{- // 1. Let algorithm, baseKey and length, be the algorithm, baseKey and length parameters passed to the deriveBits() method, respectively.-- // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "deriveBits".- auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "deriveBits"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.- if (normalized_algorithm.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());-- // 4. Let promise be a new Promise object.- auto promise = WebIDL::create_promise(realm);-- // 5. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, normalized_algorithm.release_value(), promise, base_key, length_optional), [](auto& realm, auto& normalized_algorithm, auto& promise, auto& base_key, auto& length_optional) -> void {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // 6. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.-- // 7. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of baseKey then throw an InvalidAccessError.- if (normalized_algorithm.parameter->name != base_key->algorithm_name()) {- WebIDL::reject_promise(promise, WebIDL::InvalidAccessError::create("Algorithm mismatch"_utf16));- return;- }-- // 8. If the [[usages]] internal slot of baseKey does not contain an entry that is "deriveBits", then throw an InvalidAccessError.- if (!base_key->internal_usages().contains_slow(KeyUsage::DeriveBits)) {- WebIDL::reject_promise(promise, WebIDL::InvalidAccessError::create("Key does not support deriving bits"_utf16));- return;- }-- // 9. Let result be the result of creating an ArrayBuffer containing the result of performing the derive bits operation specified by normalizedAlgorithm using baseKey, algorithm and length.- auto result = normalized_algorithm.methods->derive_bits(realm, *normalized_algorithm.parameter, base_key, length_optional);- if (result.is_error()) {- WebIDL::reject_promise_with_exception(promise, result.release_error());- return;- }-- // 10. Resolve promise with result.- WebIDL::resolve_promise(promise, JS::ArrayBuffer::create(realm, result.release_value()));- }));-- return promise;-}--// https://w3c.github.io/webcrypto/#SubtleCrypto-method-deriveKey-GC::Ref<WebIDL::Promise> SubtleCrypto::derive_key(JS::Realm& realm, AlgorithmIdentifier algorithm, GC::Ref<CryptoKey> base_key, AlgorithmIdentifier derived_key_type, bool extractable, Vector<KeyUsage> key_usages)-{- // 1. Let algorithm, baseKey, derivedKeyType, extractable and usages be the algorithm, baseKey, derivedKeyType, extractable and keyUsages parameters passed to the deriveKey() method, respectively.-- // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "deriveBits".- auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "deriveBits"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedAlgorithm.- if (normalized_algorithm.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm.release_error());-- // 4. Let normalizedDerivedKeyAlgorithmImport be the result of normalizing an algorithm, with alg set to derivedKeyType and op set to "importKey".- auto normalized_derived_key_algorithm_import = normalize_an_algorithm(realm, derived_key_type, "importKey"_string);-- // 5. If an error occurred, return a Promise rejected with normalizedDerivedKeyAlgorithmImport.- if (normalized_derived_key_algorithm_import.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_derived_key_algorithm_import.release_error());-- // 6. Let normalizedDerivedKeyAlgorithmLength be the result of normalizing an algorithm, with alg set to derivedKeyType and op set to "get key length".- auto normalized_derived_key_algorithm_length = normalize_an_algorithm(realm, derived_key_type, "get key length"_string);-- // 7. If an error occurred, return a Promise rejected with normalizedDerivedKeyAlgorithmLength.- if (normalized_derived_key_algorithm_length.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_derived_key_algorithm_length.release_error());-- // 8. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 9. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, normalized_algorithm.release_value(), promise, normalized_derived_key_algorithm_import.release_value(), normalized_derived_key_algorithm_length.release_value(), move(base_key), extractable, move(key_usages)), [](auto& realm, auto& normalized_algorithm, auto& promise, auto& normalized_derived_key_algorithm_import, auto& normalized_derived_key_algorithm_length, auto& base_key, auto& extractable, auto& key_usages) -> void {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // 10. If the following steps or referenced procedures say to throw an error, reject promise with the returned error and then terminate the algorithm.-- // 11. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot of baseKey then throw an InvalidAccessError.- if (normalized_algorithm.parameter->name != base_key->algorithm_name()) {- WebIDL::reject_promise(promise, WebIDL::InvalidAccessError::create("Algorithm mismatch"_utf16));- return;- }-- // 12. If the [[usages]] internal slot of baseKey does not contain an entry that is "deriveKey", then throw an InvalidAccessError.- if (!base_key->internal_usages().contains_slow(KeyUsage::DeriveKey)) {- WebIDL::reject_promise(promise, WebIDL::InvalidAccessError::create("Key does not support deriving keys"_utf16));- return;- }-- // 13. Let length be the result of performing the get key length algorithm specified by normalizedDerivedKeyAlgorithmLength using derivedKeyType.- auto length_result = normalized_derived_key_algorithm_length.methods->get_key_length(realm, *normalized_derived_key_algorithm_length.parameter);- if (length_result.is_error()) {- WebIDL::reject_promise_with_exception(promise, length_result.release_error());- return;- }-- auto length = length_result.release_value();-- // 14. Let secret be the result of performing the derive bits operation specified by normalizedAlgorithm using key, algorithm and length.- auto secret = normalized_algorithm.methods->derive_bits(realm, *normalized_algorithm.parameter, base_key, length);- if (secret.is_error()) {- WebIDL::reject_promise_with_exception(promise, secret.release_error());- return;- }-- // 15. Let result be the result of performing the import key operation specified by normalizedDerivedKeyAlgorithmImport using "raw" as format, secret as keyData, derivedKeyType as algorithm and using extractable and usages.- auto secret_bytes = secret.release_value();- auto result_or_error = normalized_derived_key_algorithm_import.methods->import_key(realm, *normalized_derived_key_algorithm_import.parameter, KeyFormat::Raw, move(secret_bytes), extractable, key_usages);- if (result_or_error.is_error()) {- WebIDL::reject_promise_with_exception(promise, result_or_error.release_error());- return;- }- auto result = result_or_error.release_value();-- // 16. If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.- if ((result->type() == KeyType::Secret || result->type() == KeyType::Private) && key_usages.is_empty()) {- WebIDL::reject_promise(promise, WebIDL::SyntaxError::create("usages must not be empty"_utf16));- return;- }-- // 17. Set the [[extractable]] internal slot of result to extractable.- result->set_extractable(extractable);-- // 18. Set the [[usages]] internal slot of result to the normalized value of usages.- result->set_usages(normalized_key_usages(key_usages));-- // 19. Resolve promise with result.- resolve_crypto_key_promise(realm, promise, result);- }));-- return promise;+ RawJsonWebKey raw {+ raw_string(key.alg),+ raw_string(key.crv),+ raw_string(key.d),+ raw_string(key.dp),+ raw_string(key.dq),+ raw_string(key.e),+ raw_string(key.k),+ raw_string(key.kty),+ raw_string(key.n),+ raw_string(key.p),+ raw_string(key.priv),+ raw_string(key.pub),+ raw_string(key.q),+ raw_string(key.qi),+ raw_string(key.use),+ raw_string(key.x),+ raw_string(key.y),+ static_cast<u8>(key.ext.has_value() ? (*key.ext ? 2 : 1) : 0),+ key.key_ops.has_value(),+ key_ops.span(),+ key.oth.has_value(),+ oth.span(),+ };+ receive(state, raw);}-// https://w3c.github.io/webcrypto/#SubtleCrypto-method-wrapKey-GC::Ref<WebIDL::Promise> SubtleCrypto::wrap_key(JS::Realm& realm, KeyFormat format, GC::Ref<CryptoKey> key, GC::Ref<CryptoKey> wrapping_key, AlgorithmIdentifier algorithm)+WebIDL::ExceptionOr<NormalizedAlgorithmAndParameter> normalize_an_algorithm(JS::Realm& realm, AlgorithmIdentifier const& algorithm, String operation){- // 5. Let realm be the relevant realm of this.- // 1. Let format, key, wrappingKey and algorithm be the format, key, wrappingKey and wrapAlgorithm parameters passed to the wrapKey() method, respectively.-- String operation;- auto normalized_algorithm_or_error = [&]() -> WebIDL::ExceptionOr<NormalizedAlgorithmAndParameter> {- // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "wrapKey".- auto normalized_algorithm_wrap_key_or_error = normalize_an_algorithm(realm, algorithm, "wrapKey"_string);-- // 3. If an error occurred, let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "encrypt".- // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.- if (normalized_algorithm_wrap_key_or_error.is_error()) {- auto normalized_algorithm_encrypt_or_error = normalize_an_algorithm(realm, algorithm, "encrypt"_string);- if (normalized_algorithm_encrypt_or_error.is_error())- return normalized_algorithm_encrypt_or_error.release_error();-- operation = "encrypt"_string;- return normalized_algorithm_encrypt_or_error.release_value();- } else {- operation = "wrapKey"_string;- return normalized_algorithm_wrap_key_or_error.release_value();- }+ JSObject* object = nullptr;+ FlatPtr name = 0;+ if (algorithm.has<Utf16String>())+ name = algorithm.get<Utf16String>().raw_identity();+ else+ object = JS::HostABI::object_to_abi(algorithm.get<GC::Ref<JS::Object>>().ptr());++ NormalizedAlgorithmAndParameter* normalized_algorithm = nullptr;+ TRY(JS::HostABI::completion_from_abi<void>(web_rust_crypto_normalize_an_algorithm(+ JS::HostABI::vm_to_abi(realm.vm()), &realm, object, name, operation.bytes(), &normalized_algorithm)));+ return move(*adopt_own(*normalized_algorithm));+}++JSCompletion web_crypto_algorithm_from_value(JS::Realm* realm_pointer, AlgorithmId method_id, ParameterId parameter_id, JSValue value, FlatPtr name, NormalizedAlgorithmAndParameter** out)+{+ auto& realm = *realm_pointer;+ auto methods = [&]() -> NonnullOwnPtr<AlgorithmMethods> {+ switch (method_id) {+ case AlgorithmId::RSASSAPKCS1:+ return RSASSAPKCS1::create();+ case AlgorithmId::RSAPSS:+ return RSAPSS::create();+ case AlgorithmId::RSAOAEP:+ return RSAOAEP::create();+ case AlgorithmId::ECDSA:+ return ECDSA::create();+ case AlgorithmId::ECDH:+ return ECDH::create();+ case AlgorithmId::AesCtr:+ return AesCtr::create();+ case AlgorithmId::AesCbc:+ return AesCbc::create();+ case AlgorithmId::AesGcm:+ return AesGcm::create();+ case AlgorithmId::AesKw:+ return AesKw::create();+ case AlgorithmId::HMAC:+ return HMAC::create();+ case AlgorithmId::SHA:+ return SHA::create();+ case AlgorithmId::CShake:+ return CShake::create();+ case AlgorithmId::HKDF:+ return HKDF::create();+ case AlgorithmId::PBKDF2:+ return PBKDF2::create();+ case AlgorithmId::X25519:+ return X25519::create();+ case AlgorithmId::X448:+ return X448::create();+ case AlgorithmId::ED25519:+ return ED25519::create();+ case AlgorithmId::ED448:+ return ED448::create();+ case AlgorithmId::MLDSA:+ return MLDSA::create();+ case AlgorithmId::MLKEM:+ return MLKEM::create();+ case AlgorithmId::Argon2:+ return Argon2::create();+ case AlgorithmId::ChaCha20Poly1305:+ return ChaCha20Poly1305::create();+ case AlgorithmId::AesOcb:+ return AesOcb::create();+ case AlgorithmId::KMAC:+ return KMAC::create();+ }+ VERIFY_NOT_REACHED();}();- if (normalized_algorithm_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm_or_error.release_error());-- auto normalized_algorithm = normalized_algorithm_or_error.release_value();-- // 6. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, move(normalized_algorithm), promise, move(wrapping_key), move(key), format, operation), [](auto& realm, auto& normalized_algorithm, auto& promise, auto& wrapping_key, auto& key, auto& format, auto& operation) -> void {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // FIXME: 8. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.-- // 9. If the name member of normalizedAlgorithm is not equal to the name attribute- // of the [[algorithm]] internal slot of wrappingKey then throw an InvalidAccessError.- if (normalized_algorithm.parameter->name != wrapping_key->algorithm_name()) {- WebIDL::reject_promise(promise, WebIDL::InvalidAccessError::create("Algorithm mismatch"_utf16));- return;- }-- // 10. If the [[usages]] internal slot of wrappingKey does not contain an entry that is "wrapKey", then throw an InvalidAccessError.- if (!wrapping_key->internal_usages().contains_slow(KeyUsage::WrapKey)) {- WebIDL::reject_promise(promise, WebIDL::InvalidAccessError::create("Key does not support wrapping keys"_utf16));- return;- }-- // 11. If the algorithm identified by the [[algorithm]] internal slot of key does not support the export key operation, then throw a NotSupportedError.- // Note: Handled by the base AlgorithmMethods implementation-- // 12. If the [[extractable]] internal slot of key is false, then throw an InvalidAccessError.- if (!key->extractable()) {- WebIDL::reject_promise(promise, WebIDL::InvalidAccessError::create("Key is not extractable"_utf16));- return;- }-- // 13. Let exportedKey be the result of performing the export key operation specified by the [[algorithm]] internal slot of key using key and format.- // NOTE: The spec does not mention we need to normalize this, but it's the only way we have to get to export_key.- auto normalized_key_algorithm = normalize_an_algorithm(realm, key->algorithm_name(), "exportKey"_string);- if (normalized_key_algorithm.is_error()) {- WebIDL::reject_promise_with_exception(promise, normalized_key_algorithm.release_error());- return;- }-- auto exported_key_or_error = normalized_key_algorithm.release_value().methods->export_key(realm, format, key);- if (exported_key_or_error.is_error()) {- WebIDL::reject_promise_with_exception(promise, exported_key_or_error.release_error());- return;- }-- // 14. If format is equal to the string "jwk":- // 1. Let json be the result of representing exportedKey as a UTF-16 string conforming to the JSON grammar;- // for example, by executing the JSON.stringify algorithm specified in [ECMA-262] in the context of a new- // global object.- // 2. Let bytes be the result of UTF-8 encoding json.- // Otherwise:- // Let bytes be exportedKey.- auto bytes_or_error = export_key_result_to_bytes(realm, exported_key_or_error.release_value());- if (bytes_or_error.is_error()) {- WebIDL::reject_promise(promise, bytes_or_error.release_error().release_value());- return;- }- auto bytes = bytes_or_error.release_value();-- ByteBuffer result;- // 15. If normalizedAlgorithm supports the wrap key operation:- if (operation == "wrapKey") {- // Let result be the result of performing the wrap key operation specified by normalizedAlgorithm- // using algorithm, wrappingKey as key and bytes as plaintext.- auto result_or_error = normalized_algorithm.methods->wrap_key(realm, *normalized_algorithm.parameter, wrapping_key, bytes);- if (result_or_error.is_error()) {- WebIDL::reject_promise_with_exception(promise, result_or_error.release_error());- return;- }-- result = result_or_error.release_value();- }-- // Otherwise, if normalizedAlgorithm supports the encrypt operation:- else if (operation == "encrypt") {- // Let result be the result of performing the encrypt operation specified by normalizedAlgorithm- // using algorithm, wrappingKey as key and bytes as plaintext.- auto result_or_error = normalized_algorithm.methods->encrypt(realm, *normalized_algorithm.parameter, wrapping_key, bytes);- if (result_or_error.is_error()) {- WebIDL::reject_promise_with_exception(promise, result_or_error.release_error());- return;- }-- result = result_or_error.release_value();- }-- // Otherwise:- else {- // throw a NotSupportedError.- WebIDL::reject_promise(promise, WebIDL::NotSupportedError::create("Algorithm does not support wrapping"_utf16));- return;- }-- // FIXME: 16. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- // FIXME: 17. Let result be the result of creating an ArrayBuffer in realm, containing result.- // 18. Resolve promise with result.- WebIDL::resolve_promise(promise, JS::ArrayBuffer::create(realm, move(result)));- }));-- return promise;-}--// https://w3c.github.io/webcrypto/#SubtleCrypto-method-unwrapKey-GC::Ref<WebIDL::Promise> SubtleCrypto::unwrap_key(JS::Realm& realm, KeyFormat format, WebIDL::BufferSourceVariant wrapped_key, GC::Ref<CryptoKey> unwrapping_key, AlgorithmIdentifier algorithm, AlgorithmIdentifier unwrapped_key_algorithm, bool extractable, Vector<KeyUsage> key_usages)-{- // 8. Let realm be the relevant realm of this.- // 1. Let format, unwrappingKey, algorithm, unwrappedKeyAlgorithm, extractable and usages, be the format, unwrappingKey, unwrapAlgorithm,- // unwrappedKeyAlgorithm, extractable and keyUsages parameters passed to the unwrapKey() method, respectively.-- String operation;- auto normalized_algorithm_or_error = [&]() -> WebIDL::ExceptionOr<NormalizedAlgorithmAndParameter> {- // 2. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "unwrapKey".- auto normalized_algorithm_unwrap_key_or_error = normalize_an_algorithm(realm, algorithm, "unwrapKey"_string);-- // 3. If an error occurred, let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set to "decrypt".- // 4. If an error occurred, return a Promise rejected with normalizedAlgorithm.- if (normalized_algorithm_unwrap_key_or_error.is_error()) {- auto normalized_algorithm_decrypt_or_error = normalize_an_algorithm(realm, algorithm, "decrypt"_string);- if (normalized_algorithm_decrypt_or_error.is_error())- return normalized_algorithm_decrypt_or_error.release_error();-- operation = "decrypt"_string;- return normalized_algorithm_decrypt_or_error.release_value();- } else {- operation = "unwrapKey"_string;- return normalized_algorithm_unwrap_key_or_error.release_value();- }+ auto parameter_or_error = [&]() -> JS::ThrowCompletionOr<NonnullOwnPtr<AlgorithmParams>> {+ auto object = JS::HostABI::value_from_abi(value);+ switch (parameter_id) {+ case ParameterId::AlgorithmParams:+ return AlgorithmParams::from_value(realm, object);+ case ParameterId::RsaHashedKeyGenParams:+ return RsaHashedKeyGenParams::from_value(realm, object);+ case ParameterId::RsaHashedImportParams:+ return RsaHashedImportParams::from_value(realm, object);+ case ParameterId::RsaPssParams:+ return RsaPssParams::from_value(realm, object);+ case ParameterId::RsaOaepParams:+ return RsaOaepParams::from_value(realm, object);+ case ParameterId::EcdsaParams:+ return EcdsaParams::from_value(realm, object);+ case ParameterId::EcKeyGenParams:+ return EcKeyGenParams::from_value(realm, object);+ case ParameterId::EcKeyImportParams:+ return EcKeyImportParams::from_value(realm, object);+ case ParameterId::EcdhKeyDeriveParams:+ return EcdhKeyDeriveParams::from_value(realm, object);+ case ParameterId::AesCtrParams:+ return AesCtrParams::from_value(realm, object);+ case ParameterId::AesKeyGenParams:+ return AesKeyGenParams::from_value(realm, object);+ case ParameterId::AesDerivedKeyParams:+ return AesDerivedKeyParams::from_value(realm, object);+ case ParameterId::AesCbcParams:+ return AesCbcParams::from_value(realm, object);+ case ParameterId::AesGcmParams:+ return AesGcmParams::from_value(realm, object);+ case ParameterId::HmacKeyGenParams:+ return HmacKeyGenParams::from_value(realm, object);+ case ParameterId::HmacImportParams:+ return HmacImportParams::from_value(realm, object);+ case ParameterId::CShakeParams:+ return CShakeParams::from_value(realm, object);+ case ParameterId::HKDFParams:+ return HKDFParams::from_value(realm, object);+ case ParameterId::PBKDF2Params:+ return PBKDF2Params::from_value(realm, object);+ case ParameterId::Ed448Params:+ return Ed448Params::from_value(realm, object);+ case ParameterId::ContextParams:+ return ContextParams::from_value(realm, object);+ case ParameterId::Argon2Params:+ return Argon2Params::from_value(realm, object);+ case ParameterId::AeadParams:+ return AeadParams::from_value(realm, object);+ case ParameterId::KmacParams:+ return KmacParams::from_value(realm, object);+ case ParameterId::KmacKeyGenParams:+ return KmacKeyGenParams::from_value(realm, object);+ case ParameterId::KmacImportParams:+ return KmacImportParams::from_value(realm, object);+ }+ VERIFY_NOT_REACHED();}();- if (normalized_algorithm_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, normalized_algorithm_or_error.release_error());-- auto normalized_algorithm = normalized_algorithm_or_error.release_value();-- // 5. Let normalizedKeyAlgorithm be the result of normalizing an algorithm, with alg set to unwrappedKeyAlgorithm and op set to "importKey".- auto normalized_key_algorithm_or_error = normalize_an_algorithm(realm, unwrapped_key_algorithm, "importKey"_string);- if (normalized_key_algorithm_or_error.is_error()) {- // 6. If an error occurred, return a Promise rejected with normalizedKeyAlgorithm.- return WebIDL::create_rejected_promise_from_exception(realm, normalized_key_algorithm_or_error.release_error());- }-- auto normalized_key_algorithm = normalized_key_algorithm_or_error.release_value();-- // 7. Let wrappedKey be the result of getting a copy of the bytes held by the wrappedKey parameter passed to the unwrapKey() method.- auto real_wrapped_key_or_error = get_a_copy_of_the_bytes(realm.vm(), WebIDL::BufferSource { wrapped_key });- if (real_wrapped_key_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, real_wrapped_key_or_error.release_error());- auto real_wrapped_key = real_wrapped_key_or_error.release_value();-- // 9. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 10. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(realm, move(normalized_algorithm), promise, unwrapping_key, move(real_wrapped_key), operation, format, extractable, move(key_usages), move(normalized_key_algorithm)), [](auto& realm, auto& normalized_algorithm, auto& promise, auto& unwrapping_key, auto& real_wrapped_key, auto& operation, auto& format, auto& extractable, auto& key_usages, auto& normalized_key_algorithm) -> void {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // FIXME: 11. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.-- // 12. If the name member of normalizedAlgorithm is not equal to the name attribute of the [[algorithm]] internal slot- // of unwrappingKey then throw an InvalidAccessError.- if (normalized_algorithm.parameter->name != unwrapping_key->algorithm_name()) {- WebIDL::reject_promise(promise, WebIDL::InvalidAccessError::create("Algorithm mismatch"_utf16));- return;- }-- // 13. If the [[usages]] internal slot of unwrappingKey does not contain an entry that is "unwrapKey", then throw an InvalidAccessError.- if (!unwrapping_key->internal_usages().contains_slow(KeyUsage::UnwrapKey)) {- WebIDL::reject_promise(promise, WebIDL::InvalidAccessError::create("Key does not support unwrapping keys"_utf16));- return;- }-- auto bytes_or_error = [&]() -> WebIDL::ExceptionOr<ByteBuffer> {- // 14. If normalizedAlgorithm supports an unwrap key operation:- if (operation == "unwrapKey") {- // Let bytes be the result of performing the unwrap key operation specified by normalizedAlgorithm- // using algorithm, unwrappingKey as key and wrappedKey as ciphertext.- return normalized_algorithm.methods->unwrap_key(realm, *normalized_algorithm.parameter, unwrapping_key, real_wrapped_key);- }-- // Otherwise, if normalizedAlgorithm supports a decrypt operation:- else if (operation == "decrypt") {- // Let bytes be the result of performing the decrypt operation specified by normalizedAlgorithm- // using algorithm, unwrappingKey as key and wrappedKey as ciphertext.- return normalized_algorithm.methods->decrypt(realm, *normalized_algorithm.parameter, unwrapping_key, real_wrapped_key);- }-- // Otherwise:- else {- // throw a NotSupportedError.- return WebIDL::NotSupportedError::create("Algorithm does not support wrapping"_utf16);- }- }();- if (bytes_or_error.is_error()) {- WebIDL::reject_promise_with_exception(promise, bytes_or_error.release_error());- return;- }-- auto bytes = bytes_or_error.release_value();-- Variant<ByteBuffer, JsonWebKey, Empty> key;-- // 15. If format is equal to the string "jwk":- if (format == KeyFormat::Jwk) {- // 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_with_exception(promise, maybe_parsed.release_error());- return;- }-- key = maybe_parsed.release_value();- }-- // Otherwise:- else {- // Let key be bytes.- key = move(bytes);- }-- // 16. Let result be the result of performing the import key operation specified by normalizedKeyAlgorithm- // using unwrappedKeyAlgorithm as algorithm, format, usages and extractable and with key as keyData.- auto result_or_error = normalized_key_algorithm.methods->import_key(realm, *normalized_key_algorithm.parameter, format, key.downcast<CryptoKey::ImportKeyData>(), extractable, key_usages);- if (result_or_error.is_error()) {- WebIDL::reject_promise_with_exception(promise, result_or_error.release_error());- return;- }-- auto result = result_or_error.release_value();-- // 17. If the [[type]] internal slot of result is "secret" or "private" and usages is empty, then throw a SyntaxError.- if ((result->type() == KeyType::Secret || result->type() == KeyType::Private) && key_usages.is_empty()) {- WebIDL::reject_promise(promise, WebIDL::SyntaxError::create("Usages must not be empty"_utf16));- return;- }-- // 18. Set the [[extractable]] internal slot of result to extractable.- result->set_extractable(extractable);-- // 19. Set the [[usages]] internal slot of result to the normalized value of usages.- result->set_usages(normalized_key_usages(key_usages));-- // FIXME: 20. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- // FIXME: 21. Let result be the result of converting result to an ECMAScript Object in realm, as defined by [WebIDL].- // 22. Resolve promise with result.- resolve_crypto_key_promise(realm, promise, result);- }));-- return promise;+ if (parameter_or_error.is_error())+ return JS::HostABI::throw_completion_to_abi(parameter_or_error.release_error().value());+ auto parameter = parameter_or_error.release_value();+ VERIFY(parameter->name.is_empty());+ parameter->name = Utf16String::from_raw(name);+ *out = new NormalizedAlgorithmAndParameter { move(methods), move(parameter) };+ return JS::HostABI::normal_completion_to_abi(0);}-// https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-encapsulateKey-GC::Ref<WebIDL::Promise> SubtleCrypto::encapsulate_key(JS::Realm& realm, AlgorithmIdentifier encapsulation_algorithm, GC::Ref<CryptoKey> encapsulation_key, AlgorithmIdentifier shared_key_algorithm, bool extractable, Vector<KeyUsage> key_usages)+void web_crypto_algorithm_destroy(NormalizedAlgorithmAndParameter* algorithm){- auto& global = realm.global_object();- auto& heap = GC::Heap::the();-- // 1. Let encapsulationAlgorithm, encapsulationKey, sharedKeyAlgorithm, extractable and usages be the- // encapsulationAlgorithm, encapsulationKey, sharedKeyAlgorithm, extractable and keyUsages parameters passed to- // the encapsulateKey() method, respectively.-- // 2. Let normalizedEncapsulationAlgorithm be the result of normalizing an algorithm, with alg set to- // encapsulationAlgorithm and op set to "encapsulate".- auto maybe_normalized_encapsulation_algorithm = normalize_an_algorithm(realm, encapsulation_algorithm, "encapsulate"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedEncapsulationAlgorithm.- if (maybe_normalized_encapsulation_algorithm.is_error()) {- return WebIDL::create_rejected_promise_from_exception(realm, maybe_normalized_encapsulation_algorithm.exception());- }- auto normalized_encapsulation_algorithm = maybe_normalized_encapsulation_algorithm.release_value();-- // 4. Let normalizedSharedKeyAlgorithm be the result of normalizing an algorithm, with alg- // set to sharedKeyAlgorithm and op set to "importKey".- auto maybe_normalized_shared_key_algorithm = normalize_an_algorithm(realm, shared_key_algorithm, "importKey"_string);-- // 5. If an error occurred, return a Promise rejected with normalizedSharedKeyAlgorithm.- if (maybe_normalized_shared_key_algorithm.is_error()) {- return WebIDL::create_rejected_promise_from_exception(realm, maybe_normalized_shared_key_algorithm.exception());- }- auto normalized_shared_key_algorithm = maybe_normalized_shared_key_algorithm.release_value();-- // 6. Let realm be the relevant realm of this.-- // 7. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 8. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, GC::captures(realm, global, move(normalized_encapsulation_algorithm), encapsulation_key, promise, move(normalized_shared_key_algorithm), extractable, move(key_usages)), [](auto& realm, auto& global, auto& normalized_encapsulation_algorithm, auto& encapsulation_key, auto& promise, auto& normalized_shared_key_algorithm, auto& extractable, auto& usages) -> void {- auto& heap = GC::Heap::the();- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // 9. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task- // source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.- auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- WebIDL::reject_promise(promise, value);- }));- };-- // 10. If the name member of normalizedEncapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]- // internal slot of encapsulationKey then throw an InvalidAccessError.- if (normalized_encapsulation_algorithm.parameter->name != encapsulation_key->algorithm_name()) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Invalid encapsulation key algorithm"_utf16)));- return;- }-- // 11. If the [[usages]] internal slot of encapsulationKey does not contain an entry that is "encapsulateKey", then- // throw an InvalidAccessError.- if (!encapsulation_key->internal_usages().contains_slow(KeyUsage::EncapsulateKey)) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Invalid encapsulation key usage"_utf16)));- return;- }-- // 12. Let encapsulatedBits be the result of performing the encapsulate operation specified by the [[algorithm]]- // internal slot of encapsulationKey using encapsulationKey.- auto maybe_encapsulated_bits = normalized_encapsulation_algorithm.methods->encapsulate(realm, *normalized_encapsulation_algorithm.parameter, encapsulation_key);- if (maybe_encapsulated_bits.is_error()) {- throw_in_this_context(WebIDL::exception_to_throw_completion(realm.vm(), realm, maybe_encapsulated_bits.release_error()));- return;- }- auto encapsulated_bits = maybe_encapsulated_bits.release_value();-- // 13. Let sharedKey be the result of performing the import key operation specified by- // normalizedSharedKeyAlgorithm using "raw-secret" as format, the sharedKey field of encapsulatedBits as- // keyData, sharedKeyAlgorithm as algorithm and using extractable and usages.- auto maybe_shared_key = normalized_shared_key_algorithm.methods->import_key(realm,- *normalized_shared_key_algorithm.parameter,- KeyFormat::RawSecret,- encapsulated_bits.shared_key.value(),- extractable,- usages);- if (maybe_shared_key.is_error()) {- throw_in_this_context(WebIDL::exception_to_throw_completion(realm.vm(), realm, maybe_shared_key.release_error()));- return;- }- auto shared_key = maybe_shared_key.release_value();-- // 14. Set the [[extractable]] internal slot of sharedKey to extractable.- shared_key->set_extractable(extractable);-- // 15. Set the [[usages]] internal slot of sharedKey to the normalized value of usages.- shared_key->set_usages(normalized_key_usages(usages));-- // 16. Let encapsulatedKey be a new EncapsulatedKey dictionary with sharedKey set to sharedKey and ciphertext set- // to the ciphertext field of encapsulatedBits.- // NB: The task makes encapsulatedKey of the captured sharedKey and ciphertext, as the dictionary roots its key.-- // 17. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, shared_key, encapsulated_bits.ciphertext), [](auto& realm, auto& promise, auto& shared_key, auto& ciphertext) {- auto encapsulated_key = EncapsulatedKey { shared_key, ciphertext };- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // 18. Let result be the result of converting encapsulatedKey to an ECMAScript Object in realm, as defined by [WebIDL].- auto maybe_result = ::Web::Crypto::encapsulated_key(realm, encapsulated_key);- if (maybe_result.is_error()) {- WebIDL::reject_promise(promise, maybe_result.release_error().value());- return;- }- auto const result = maybe_result.release_value();-- // 19. Resolve promise with result.- WebIDL::resolve_promise(promise, result);- }));- }));-- return promise;+ delete algorithm;}-// https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-encapsulateBits-GC::Ref<WebIDL::Promise> SubtleCrypto::encapsulate_bits(JS::Realm& realm, AlgorithmIdentifier encapsulation_algorithm, GC::Ref<CryptoKey> encapsulation_key)+void web_crypto_algorithm_public_key_usages(NormalizedAlgorithmAndParameter const* algorithm, void* state, ReceiveUsages receive){- auto& global = realm.global_object();- auto& heap = GC::Heap::the();-- // 1. Let encapsulationAlgorithm and encapsulationKey be the encapsulationAlgorithm and encapsulationKey- // parameters passed to the encapsulateBits() method, respectively.-- // 2. Let normalizedEncapsulationAlgorithm be the result of normalizing an algorithm, with alg set to- // encapsulationAlgorithm and op set to "encapsulate".- auto maybe_normalized_encapsulation_algorithm = normalize_an_algorithm(realm, encapsulation_algorithm, "encapsulate"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedEncapsulationAlgorithm.- if (maybe_normalized_encapsulation_algorithm.is_error()) {- return WebIDL::create_rejected_promise_from_exception(realm, maybe_normalized_encapsulation_algorithm.release_error());- }- auto normalized_encapsulation_algorithm = maybe_normalized_encapsulation_algorithm.release_value();-- // 4. Let realm be the relevant realm of this.-- // 5. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 6. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, GC::captures(realm, global, move(normalized_encapsulation_algorithm), promise, encapsulation_key), [](auto& realm, auto& global, auto& normalized_encapsulation_algorithm, auto& promise, auto& encapsulation_key) -> void {- auto& heap = GC::Heap::the();- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // 7. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task- // source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.- auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- WebIDL::reject_promise(promise, value);- }));- };-- // 8. If the name member of normalizedEncapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]- // internal slot of encapsulationKey then throw an InvalidAccessError.- if (normalized_encapsulation_algorithm.parameter->name != encapsulation_key->algorithm_name()) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Invalid encapsulation key algorithm"_utf16)));- return;- }-- // 9. If the [[usages]] internal slot of encapsulationKey does not contain an entry that is "encapsulateBits", then- // throw an InvalidAccessError.- if (!encapsulation_key->internal_usages().contains_slow(KeyUsage::EncapsulateBits)) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Invalid encapsulation key usages"_utf16)));- return;- }-- // 10. Let encapsulatedBits be the result of performing the encapsulate operation specified by the [[algorithm]]- // internal slot of encapsulationKey using encapsulationKey.- auto maybe_encapsulated_bits = normalized_encapsulation_algorithm.methods->encapsulate(realm, *normalized_encapsulation_algorithm.parameter, encapsulation_key);- if (maybe_encapsulated_bits.is_error()) {- throw_in_this_context(WebIDL::exception_to_throw_completion(realm.vm(), realm, maybe_encapsulated_bits.release_error()));- return;- }- auto encapsulated_bits = maybe_encapsulated_bits.release_value();-- // 11. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, encapsulated_bits), [](auto& realm, auto& promise, auto& encapsulated_bits) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);-- // 12. Let result be the result of converting encapsulatedBits to an ECMAScript Object in realm, as defined by [WebIDL].- auto maybe_result = ::Web::Crypto::encapsulated_bits(realm, encapsulated_bits);- if (maybe_result.is_error()) {- WebIDL::reject_promise(promise, maybe_result.release_error().value());- return;- }- auto const result = maybe_result.release_value();-- // 13. Resolve promise with result.- WebIDL::resolve_promise(promise, result);- }));- }));-- return promise;+ if (auto usages = algorithm->methods->public_key_usages(); usages.has_value())+ receive(state, *usages);}-// https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-decapsulateKey-GC::Ref<WebIDL::Promise> SubtleCrypto::decapsulate_key(JS::Realm& realm, AlgorithmIdentifier decapsulation_algorithm, GC::Ref<CryptoKey> decapsulation_key, WebIDL::BufferSourceVariant const& ciphertext, AlgorithmIdentifier shared_key_algorithm, bool extractable, Vector<KeyUsage> const& usages)+void web_crypto_normalized_key_usages(ReadonlySpan<KeyUsage> usages, void* state, ReceiveUsages receive){- auto& global = realm.global_object();- auto& heap = GC::Heap::the();-- // 1. Let decapsulationAlgorithm, decapsulationKey, sharedKeyAlgorithm, extractable and usages be the- // decapsulationAlgorithm, decapsulationKey, sharedKeyAlgorithm, extractable and keyUsages parameters passed to- // the decapsulateKey() method, respectively.-- // 2. Let normalizedDecapsulationAlgorithm be the result of normalizing an algorithm, with alg set to- // decapsulationAlgorithm and op set to "decapsulate".- auto normalized_decapsulation_algorithm = normalize_an_algorithm(realm, decapsulation_algorithm, "decapsulate"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedDecapsulationAlgorithm.- if (normalized_decapsulation_algorithm.is_error()) {- return WebIDL::create_rejected_promise_from_exception(realm, normalized_decapsulation_algorithm.release_error());- }-- // 4. Let normalizedSharedKeyAlgorithm be the result of normalizing an algorithm, with alg- // set to sharedKeyAlgorithm and op set to "importKey".- auto normalized_shared_key_algorithm = normalize_an_algorithm(realm, shared_key_algorithm, "importKey"_string);-- // 5. If an error occurred, return a Promise rejected with normalizedSharedKeyAlgorithm.- if (normalized_shared_key_algorithm.is_error()) {- return WebIDL::create_rejected_promise_from_exception(realm, normalized_shared_key_algorithm.release_error());- }-- // 6. Let ciphertext be the result of getting a copy of the bytes held by the ciphertext parameter passed to the- // decapsulateKey() method.- auto cipher_text_or_error = get_a_copy_of_the_bytes(realm.vm(), WebIDL::BufferSource { ciphertext });- if (cipher_text_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, cipher_text_or_error.release_error());- auto cipher_text = cipher_text_or_error.release_value();-- // 7. Let realm be the relevant realm of this.-- // 8. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 9. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, GC::captures(realm, global, normalized_decapsulation_algorithm.release_value(), promise, decapsulation_key, move(cipher_text), normalized_shared_key_algorithm.release_value(), extractable, usages), [](auto& realm, auto& global, auto& normalized_decapsulation_algorithm, auto& promise, auto& decapsulation_key, auto& cipher_text, auto& normalized_shared_key_algorithm, auto& extractable, auto& usages) -> void {- auto& heap = GC::Heap::the();- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // 10. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task- // source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.- auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- WebIDL::reject_promise(promise, value);- }));- };-- // 11. If the name member of normalizedDecapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]- // internal slot of decapsulationKey then throw an InvalidAccessError.- if (normalized_decapsulation_algorithm.parameter->name != decapsulation_key->algorithm_name()) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Invalid algorithm name"_utf16)));- return;- }-- // 12. If the [[usages]] internal slot of decapsulationKey does not contain an entry that is "decapsulateKey", then- // throw an InvalidAccessError.- if (!decapsulation_key->internal_usages().contains_slow(KeyUsage::DecapsulateKey)) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Invalid key usages"_utf16)));- return;- }- // 13. Let decapsulatedBits be the result of performing the decapsulate operation specified by the [[algorithm]]- // internal slot of decapsulationKey using decapsulationKey and ciphertext.- auto maybe_decapsulated_bits = normalized_decapsulation_algorithm.methods->decapsulate(realm,- *normalized_decapsulation_algorithm.parameter,- decapsulation_key,- cipher_text);- if (maybe_decapsulated_bits.is_error()) {- throw_in_this_context(WebIDL::exception_to_throw_completion(realm.vm(), realm, maybe_decapsulated_bits.release_error()));- return;- }- auto const decapsulated_bits = maybe_decapsulated_bits.release_value();-- // 14. Let sharedKey be the result of performing the import key operation specified by- // normalizedSharedKeyAlgorithm using "raw-secret" as format, the decapsulatedBits as keyData,- // sharedKeyAlgorithm as algorithm and using extractable and usages.- auto maybe_shared_key = normalized_shared_key_algorithm.methods->import_key(realm,- *normalized_shared_key_algorithm.parameter,- KeyFormat::RawSecret,- MUST(ByteBuffer::copy(decapsulated_bits.bytes())),- extractable,- usages);- if (maybe_shared_key.is_error()) {- throw_in_this_context(WebIDL::exception_to_throw_completion(realm.vm(), realm, maybe_shared_key.release_error()));- return;- }- auto const shared_key = maybe_shared_key.release_value();-- // 15. Set the [[extractable]] internal slot of sharedKey to extractable.- shared_key->set_extractable(extractable);-- // 16. Set the [[usages]] internal slot of sharedKey to the normalized value of usages.- shared_key->set_usages(normalized_key_usages(usages));-- // 17. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, shared_key), [](auto& realm, auto& promise, auto& shared_key) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // 18. Let result be the result of converting sharedKey to an ECMAScript Object in realm, as defined by [WebIDL].- // 19. Resolve promise with result.- resolve_crypto_key_promise(realm, promise, shared_key);- }));- }));-- return promise;-}--// https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-decapsulateBits-GC::Ref<WebIDL::Promise> SubtleCrypto::decapsulate_bits(JS::Realm& realm, AlgorithmIdentifier decapsulation_algorithm, GC::Ref<CryptoKey> decapsulation_key, WebIDL::BufferSourceVariant const& ciphertext)-{- auto& global = realm.global_object();- auto& heap = GC::Heap::the();-- // 1. Let decapsulationAlgorithm and decapsulationKey be the decapsulationAlgorithm and decapsulationKey- // parameters passed to the decapsulateBits() method, respectively.-- // 2. Let normalizedDecapsulationAlgorithm be the result of normalizing an algorithm, with alg set to- // decapsulationAlgorithm and op set to "decapsulate".- auto normalized_decapsulation_algorithm = normalize_an_algorithm(realm, decapsulation_algorithm, "decapsulate"_string);-- // 3. If an error occurred, return a Promise rejected with normalizedDecapsulationAlgorithm.- if (normalized_decapsulation_algorithm.is_error()) {- return WebIDL::create_rejected_promise_from_exception(realm, normalized_decapsulation_algorithm.release_error());- }-- // 4. Let ciphertext be the result of getting a copy of the bytes held by the ciphertext parameter passed to the- // decapsulateBits() method.- auto cipher_text_or_error = get_a_copy_of_the_bytes(realm.vm(), WebIDL::BufferSource { ciphertext });- if (cipher_text_or_error.is_error())- return WebIDL::create_rejected_promise_from_exception(realm, cipher_text_or_error.release_error());- auto cipher_text = cipher_text_or_error.release_value();-- // 5. Let realm be the relevant realm of this.-- // 6. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 7. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, GC::captures(realm, global, normalized_decapsulation_algorithm.release_value(), promise, decapsulation_key, move(cipher_text)), [](auto& realm, auto& global, auto& normalized_decapsulation_algorithm, auto& promise, auto& decapsulation_key, auto& cipher_text) -> void {- auto& heap = GC::Heap::the();- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // 8. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto task- // source, given realm's global object, to reject promise with the returned error; and then terminate the algorithm.- auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- WebIDL::reject_promise(promise, value);- }));- };-- // 9. If the name member of normalizedDecapsulationAlgorithm is not equal to the name attribute of the [[algorithm]]- // internal slot of decapsulationKey then throw an InvalidAccessError.- if (normalized_decapsulation_algorithm.parameter->name != decapsulation_key->algorithm_name()) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Invalid algorithm name"_utf16)));- return;- }-- // 10. If the [[usages]] internal slot of decapsulationKey does not contain an entry that is "decapsulateBits", then- // throw an InvalidAccessError.- if (!decapsulation_key->internal_usages().contains_slow(KeyUsage::DecapsulateBits)) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Invalid key usages"_utf16)));- return;- }-- // 11. Let decapsulatedBits be the result of performing the decapsulate operation specified by the [[algorithm]]- // internal slot of decapsulationKey using decapsulationKey and ciphertext.- auto maybe_decapsulated_bits = normalized_decapsulation_algorithm.methods->decapsulate(realm,- *normalized_decapsulation_algorithm.parameter,- decapsulation_key,- cipher_text);- if (maybe_decapsulated_bits.is_error()) {- throw_in_this_context(WebIDL::exception_to_throw_completion(realm.vm(), realm, maybe_decapsulated_bits.release_error()));- return;- }- auto const decapsulated_bits = maybe_decapsulated_bits.release_value();-- // 12. Queue a global task on the crypto task source, given realm's global object, to perform the remaining steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, decapsulated_bits), [](auto& realm, auto& promise, auto& decapsulated_bits) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- // 13. Let result be the result of creating an ArrayBuffer in realm, containing decapsulatedBits.- // 14. Resolve promise with result.- WebIDL::resolve_promise(promise, JS::ArrayBuffer::create(realm, decapsulated_bits));- }));- }));-- return promise;+ auto normalized = normalized_key_usages(usages);+ receive(state, normalized.span());}static ErrorOr<CryptoKey::InternalKeyData> public_key_for_private_key(CryptoKey const& key)@@ -1561,573 +440,249 @@ static ErrorOr<CryptoKey::InternalKeyData> public_key_for_private_key(CryptoKey});}-// https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-getPublicKey-GC::Ref<WebIDL::Promise> SubtleCrypto::get_public_key(JS::Realm& realm, GC::Ref<CryptoKey> key, Vector<KeyUsage> key_usages)+CryptoKey* web_crypto_public_key_for_private_key(CryptoKey const* key){- auto& global = realm.global_object();- auto& heap = GC::Heap::the();-- // 1. Let key and usages be the key and keyUsages parameters passed to the getPublicKey() method, respectively.-- // 2. Let algorithm be the [[algorithm]] internal slot of key.- // NB: Every algorithm that supports deriving a public key registers an export key operation, which lets us find- // the algorithm's methods.- auto normalized_algorithm = normalize_an_algorithm(realm, key->algorithm_name(), "exportKey"_string);-- // 3. If the cryptographic algorithm identified by algorithm does not support deriving a public key from a private- // key, then return a Promise rejected with a NotSupportedError.- Optional<ReadonlySpan<KeyUsage>> public_key_usages;- if (!normalized_algorithm.is_error())- public_key_usages = normalized_algorithm.value().methods->public_key_usages();- if (!public_key_usages.has_value()) {- auto error = WebIDL::NotSupportedError::create(Utf16String::formatted("Algorithm '{}' does not support deriving a public key", key->algorithm_name()));- return WebIDL::create_rejected_promise_from_exception(realm, error);- }-- // 4. Let realm be the relevant realm of this.-- // 5. Let promise be a new Promise.- auto promise = WebIDL::create_promise(realm);-- // 6. Return promise and perform the remaining steps in parallel.- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(heap, GC::captures(realm, global, promise, key, move(key_usages), Vector<KeyUsage>(*public_key_usages)), [](auto& realm, auto& global, auto& promise, auto& key, auto& key_usages, auto& public_key_usages) -> void {- auto& heap = GC::Heap::the();- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::No);-- // 7. If the following steps or referenced procedures say to throw an error, queue a global task on the crypto- // task source, given realm's global object, to reject promise with the returned error; and then terminate- // the algorithm.- auto const throw_in_this_context = [&realm, &global, &heap, &promise](JS::Completion completion) {- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, completion.value()), [](auto& realm, auto& promise, auto& value) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);- WebIDL::reject_promise(promise, value);- }));- };-- // 8. If the [[type]] internal slot of key is not "private", then throw an InvalidAccessError.- if (key->type() != KeyType::Private) {- throw_in_this_context(throw_completion(realm, WebIDL::InvalidAccessError::create("Key is not a private key"_utf16)));- return;- }-- // 9. If usages contains an entry which is not supported for a public key by the algorithm identified by- // algorithm, then throw a SyntaxError.- for (auto usage : key_usages) {- if (!public_key_usages.contains_slow(usage)) {- throw_in_this_context(throw_completion(realm, WebIDL::SyntaxError::create("Invalid key usage for a public key"_utf16)));- return;- }- }-- // 10. Let publicKey be a new CryptoKey representing the public key corresponding to the private key represented- // by the [[handle]] internal slot of key.- auto public_key_data = public_key_for_private_key(key);-- // 11. If an error occurred, then throw a OperationError.- if (public_key_data.is_error()) {- throw_in_this_context(throw_completion(realm, WebIDL::OperationError::create("Failed to derive the public key"_utf16)));- return;- }- auto public_key = CryptoKey::create(public_key_data.release_value());-- // 12. Set the [[type]] internal slot of publicKey to "public".- public_key->set_type(KeyType::Public);-- // 13. Set the [[algorithm]] internal slot of publicKey to algorithm.- public_key->set_algorithm(key->internal_algorithm());-- // 14. Set the [[extractable]] internal slot of publicKey to true.- public_key->set_extractable(true);-- // 15. Set the [[usages]] internal slot of publicKey to the normalized value of usages.- public_key->set_usages(normalized_key_usages(key_usages));-- // 16. Queue a global task on the crypto task source, given realm's global object, to perform the remaining- // steps.- HTML::queue_global_task(HTML::Task::Source::Crypto, global, GC::create_function(heap, GC::captures(realm, promise, public_key), [](auto& realm, auto& promise, auto& public_key) {- HTML::TemporaryExecutionContext context(realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes);-- // 17. Let result be the result of converting publicKey to an ECMAScript Object in realm, as defined by- // [WebIDL].- // 18. Resolve promise with result.- resolve_crypto_key_promise(realm, promise, public_key);- }));- }));-- return promise;+ auto data = public_key_for_private_key(*key);+ if (data.is_error())+ return nullptr;+ return CryptoKey::create(data.release_value()).ptr();}-// https://wicg.github.io/webcrypto-modern-algos/#dfn-determine-support-from-operation-steps-static bool determine_support_from_operation_steps(JS::Realm& realm, StringView op, NormalizedAlgorithmAndParameter& normalized_algorithm, Optional<u32> length)+JSCompletion web_crypto_algorithm_encrypt(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive){- auto& methods = *normalized_algorithm.methods;- auto const& parameter = *normalized_algorithm.parameter;-- // 1. If the specified operation or normalized algorithm (or one of its parameter values) is expected to fail (for- // any key and/or data) for an implementation-specific reason (e.g. known nonconformance to the specification),- // return false.- // NB: The validate_*_parameters() methods of the algorithms also reject parameters that we do not support.-- // 2. If op is "generateKey" or "importKey", let usages be the empty list.- // NB: An empty list of usages never makes a step of these operations throw.-- // 3. For each of the steps of the operation specified by op of the algorithm specified by normalizedAlgorithm:- // -> If the step says to throw an error: Return false.- // -> If the step says to generate a key: Return true.- // -> If the step relies on an unavailable parameter, such as key, plaintext or ciphertext: Return true.- // -> If the step says to return a value: Return true.- // -> Otherwise: Execute the step.- // NB: The validate_*_parameters() methods of an algorithm perform the steps of its operations that come before the- // first step that relies on an unavailable parameter, generates a key or returns a value. The operations that- // have no such method rely on an unavailable parameter in their first steps. The get key length operation- // relies on its parameters only, so we perform it in full.- auto result = [&] -> WebIDL::ExceptionOr<void> {- if (op == "encrypt"sv)- return methods.validate_encrypt_parameters(parameter);- if (op == "decrypt"sv)- return methods.validate_decrypt_parameters(parameter);- if (op == "sign"sv)- return methods.validate_sign_parameters(parameter);- if (op == "verify"sv)- return methods.validate_verify_parameters(parameter);- if (op == "digest"sv)- return methods.validate_digest_parameters(parameter);- if (op == "generateKey"sv)- return methods.validate_generate_key_parameters(parameter);- if (op == "importKey"sv)- return methods.validate_import_key_parameters(parameter);- if (op == "deriveBits"sv)- return methods.validate_derive_bits_parameters(parameter, length);- if (op == "get key length"sv)- TRY(methods.get_key_length(realm, parameter));- return {};- }();- return !result.is_error();+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->encrypt(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ receive(state, result.value().span());+ return JS::HostABI::normal_completion_to_abi(0);}-// https://wicg.github.io/webcrypto-modern-algos/#dfn-check-support-for-algorithm-static bool check_support_for_an_algorithm(JS::Realm& realm, String op, AlgorithmIdentifier const& alg, Optional<u32> length)+JSCompletion web_crypto_algorithm_decrypt(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive){- // 1. If op is "encapsulateKey" or "encapsulateBits", set op to "encapsulate".- if (op.is_one_of("encapsulateKey"sv, "encapsulateBits"sv))- op = "encapsulate"_string;-- // 2. If op is "decapsulateKey" or "decapsulateBits", set op to "decapsulate".- if (op.is_one_of("decapsulateKey"sv, "decapsulateBits"sv))- op = "decapsulate"_string;-- // 3. If op is "getPublicKey":- if (op == "getPublicKey"sv) {- // 1. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to alg and op set to- // "exportKey".- auto normalized_algorithm = normalize_an_algorithm(realm, alg, "exportKey"_string);-- // 2. If an error occurred, return false.- if (normalized_algorithm.is_error())- return false;-- // 3. If the cryptographic algorithm identified by normalizedAlgorithm does not support deriving a public key- // from a private key, then return false.- // 4. Otherwise, return true.- return normalized_algorithm.value().methods->public_key_usages().has_value();- }-- // 4. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to alg and op set to op.- auto normalized_algorithm = normalize_an_algorithm(realm, alg, op);-- // 5. If an error occurred:- if (normalized_algorithm.is_error()) {- // 1. If op is "wrapKey", return the result of checking support for an algorithm with op set to "encrypt" and- // alg set to alg.- if (op == "wrapKey"sv)- return check_support_for_an_algorithm(realm, "encrypt"_string, alg, {});-- // 2. If op is "unwrapKey", return the result of checking support for an algorithm with op set to "decrypt" and- // alg set to alg.- if (op == "unwrapKey"sv)- return check_support_for_an_algorithm(realm, "decrypt"_string, alg, {});-- // 3. Otherwise, return false.- return false;- }-- // 6. Return the result of determining support from operation steps, with op set to op, normalizedAlgorithm set to- // normalizedAlgorithm, and length set to length.- return determine_support_from_operation_steps(realm, op, normalized_algorithm.value(), length);+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->decrypt(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ receive(state, result.value().span());+ return JS::HostABI::normal_completion_to_abi(0);}-static bool is_a_supported_operation(Utf16String const& operation)+JSCompletion web_crypto_algorithm_sign(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive){- return operation.is_one_of("encrypt"sv, "decrypt"sv, "sign"sv, "verify"sv, "digest"sv, "generateKey"sv,- "deriveKey"sv, "deriveBits"sv, "importKey"sv, "exportKey"sv, "wrapKey"sv, "unwrapKey"sv, "encapsulateKey"sv,- "encapsulateBits"sv, "decapsulateKey"sv, "decapsulateBits"sv, "getPublicKey"sv);+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->sign(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ receive(state, result.value().span());+ return JS::HostABI::normal_completion_to_abi(0);}-// https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-supports-bool SubtleCrypto::supports(JS::Realm& realm, Utf16String const& operation, AlgorithmIdentifier const& algorithm, Optional<u32> length)+JSCompletion web_crypto_algorithm_verify(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes signature, ReadonlyBytes data, bool* out){- // 1. If operation is not one of "encrypt", "decrypt", "sign", "verify", "digest", "generateKey", "deriveKey",- // "deriveBits", "importKey", "exportKey", "wrapKey", "unwrapKey", "encapsulateKey", "encapsulateBits",- // "decapsulateKey", "decapsulateBits" or "getPublicKey", return false.- if (!is_a_supported_operation(operation))- return false;-- // 2. Return the result of checking support for an algorithm, with op set to operation, alg set to algorithm, and- // length set to length.- return check_support_for_an_algorithm(realm, operation.to_utf8(), algorithm, length);+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->verify(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(signature)), MUST(ByteBuffer::copy(data)));+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ *out = result.value();+ return JS::HostABI::normal_completion_to_abi(0);}-// https://wicg.github.io/webcrypto-modern-algos/#dfn-SubtleCrypto-method-supports-additionalAlgorithm-bool SubtleCrypto::supports(JS::Realm& realm, Utf16String const& operation, AlgorithmIdentifier const& algorithm, AlgorithmIdentifier const& additional_algorithm)+JSCompletion web_crypto_algorithm_digest(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, ReadonlyBytes data, void* state, ReceiveBytes receive){- // 1. If operation is not one of "encrypt", "decrypt", "sign", "verify", "digest", "generateKey", "deriveKey",- // "deriveBits", "importKey", "exportKey", "wrapKey", "unwrapKey", "encapsulateKey", "encapsulateBits",- // "decapsulateKey", "decapsulateBits" or "getPublicKey", return false.- if (!is_a_supported_operation(operation))- return false;-- auto op = operation.to_utf8();-- // 2. If operation is "deriveKey" or "unwrapKey":- if (op.is_one_of("deriveKey"sv, "unwrapKey"sv)) {- // 1. If the result of checking support for an algorithm with op set to "importKey" and alg set to- // additionalAlgorithm is false, return false.- if (!check_support_for_an_algorithm(realm, "importKey"_string, additional_algorithm, {}))- return false;- }-- // 3. If operation is "wrapKey":- if (op == "wrapKey"sv) {- // 1. If the result of checking support for an algorithm with op set to "exportKey" and alg set to- // additionalAlgorithm is false, return false.- if (!check_support_for_an_algorithm(realm, "exportKey"_string, additional_algorithm, {}))- return false;- }-- // 4. If operation is "encapsulateKey" or "decapsulateKey":- if (op.is_one_of("encapsulateKey"sv, "decapsulateKey"sv)) {- // 1. Let normalizedAlgorithm be the result of normalizing an algorithm, with alg set to algorithm and op set- // to "get shared key length".- auto normalized_algorithm = normalize_an_algorithm(realm, algorithm, "get shared key length"_string);-- // 2. If an error occurred, return false.- if (normalized_algorithm.is_error())- return false;-- // 3. Let sharedKeyLength be the result of performing the get shared key length algorithm specified by- // normalizedAlgorithm using algorithm.- auto shared_key_length = normalized_algorithm.value().methods->get_shared_key_length(*normalized_algorithm.value().parameter);- if (shared_key_length.is_error())- return false;-- // 4. Let normalizedAdditionalAlgorithm be the result of normalizing an algorithm, with alg set to- // additionalAlgorithm and op set to "importKey".- auto normalized_additional_algorithm = normalize_an_algorithm(realm, additional_algorithm, "importKey"_string);-- // 5. If an error occurred, return false.- if (normalized_additional_algorithm.is_error())- return false;-- // 6. If the result of determining support from operation steps with op set to "importKey" and- // normalizedAlgorithm set to normalizedAdditionalAlgorithm, and length set to null is false, return false.- if (!determine_support_from_operation_steps(realm, "importKey"sv, normalized_additional_algorithm.value(), {}))- return false;-- // 7. If the import key operation specified by normalizedAdditionalAlgorithm would throw an error for every value- // of keyData that is a byte sequence whose length in bits is sharedKeyLength when format is "raw-secret",- // return false.- // NB: Whether importing secret key data fails depends on its length only, so importing zeroes of that length- // tells whether every such keyData fails.- auto key_data = MUST(ByteBuffer::create_zeroed(ceil_div(shared_key_length.value(), 8u)));- auto const& import_algorithm = normalized_additional_algorithm.value();- if (import_algorithm.methods->import_key(realm, *import_algorithm.parameter, KeyFormat::RawSecret, move(key_data), false, {}).is_error())- return false;- }-- // 5. Let length be null.- Optional<u32> length;-- // 6. If operation is "deriveKey":- if (op == "deriveKey"sv) {- // 1. If the result of checking support for an algorithm with op set to "get key length" and alg set to- // additionalAlgorithm is false, return false.- if (!check_support_for_an_algorithm(realm, "get key length"_string, additional_algorithm, {}))- return false;-- // 2. Let normalizedAdditionalAlgorithm be the result of normalizing an algorithm, with alg set to- // additionalAlgorithm and op set to "get key length".- // NB: Normalizing can run author code, so this second normalization can fail even though the first succeeded.- auto normalized_additional_algorithm = normalize_an_algorithm(realm, additional_algorithm, "get key length"_string);- if (normalized_additional_algorithm.is_error())- return false;-- // 3. Let length be the result of performing the get key length algorithm specified by additionalAlgorithm- // using normalizedAdditionalAlgorithm.- auto& normalized_length_algorithm = normalized_additional_algorithm.value();- auto key_length = normalized_length_algorithm.methods->get_key_length(realm, *normalized_length_algorithm.parameter);- if (key_length.is_error())- return false;- length = key_length.release_value();-- // 4. Set operation to "deriveBits".- op = "deriveBits"_string;- }-- // 7. Return the result of checking support for an algorithm, with op set to operation, alg set to algorithm, and- // length set to length.- return check_support_for_an_algorithm(realm, move(op), algorithm, length);+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->digest(realm, *algorithm->parameter, MUST(ByteBuffer::copy(data)));+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ receive(state, result.value().span());+ return JS::HostABI::normal_completion_to_abi(0);}-SupportedAlgorithmsMap& supported_algorithms_internal()+JSCompletion web_crypto_algorithm_derive_bits(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, OptionalLength length, void* state, ReceiveBytes receive){- static NeverDestroyed<SupportedAlgorithmsMap> supported_algorithms;- return *supported_algorithms;+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->derive_bits(realm, *algorithm->parameter, *key, length.to_optional());+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ receive(state, result.value().span());+ return JS::HostABI::normal_completion_to_abi(0);}-SupportedAlgorithmsMap const& supported_algorithms()+JSCompletion web_crypto_algorithm_import_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, KeyFormat format, ReadonlyBytes key_data, RawJsonWebKey const* jwk, bool extractable, ReadonlySpan<KeyUsage> usages, CryptoKey** out){- // NB: Every agent of the process reads this map, so it is defined once and never changes after that.- [[maybe_unused]] static bool const is_defined = [] {- define_supported_algorithms();- return true;- }();- return supported_algorithms_internal();+ auto& realm = *realm_pointer;+ Vector<KeyUsage> usage_vector;+ usage_vector.append(usages.data(), usages.size());+ CryptoKey::ImportKeyData data = jwk ? CryptoKey::ImportKeyData { json_web_key_from_raw(*jwk) } : CryptoKey::ImportKeyData { MUST(ByteBuffer::copy(key_data)) };+ auto result = algorithm->methods->import_key(realm, *algorithm->parameter, format, move(data), extractable, usage_vector);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ *out = result.value().ptr();+ return JS::HostABI::normal_completion_to_abi(0);}-// https://w3c.github.io/webcrypto/#algorithm-normalization-internal-void define_supported_algorithms()+JSCompletion web_crypto_algorithm_generate_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, bool extractable, ReadonlySpan<KeyUsage> usages, CryptoKey** out_key, CryptoKey** out_public_key, CryptoKey** out_private_key){- auto& internal_object = supported_algorithms_internal();-- // 1. For each value, v in the List of supported operations,- // set the v key of the internal object supportedAlgorithms to a new associative container.- auto supported_operations = Vector {- "encrypt"_string,- "decrypt"_string,- "sign"_string,- "verify"_string,- "digest"_string,- "deriveBits"_string,- "wrapKey"_string,- "unwrapKey"_string,- "generateKey"_string,- "importKey"_string,- "exportKey"_string,- "get key length"_string,- "encapsulate"_string,- "decapsulate"_string,- "get shared key length"_string- };-- for (auto& operation : supported_operations) {- internal_object.set(operation, {});- }-- // https://w3c.github.io/webcrypto/#algorithm-conventions-- // https://w3c.github.io/webcrypto/#rsassa-pkcs1-registration- define_an_algorithm<RSASSAPKCS1>("sign"_string, "RSASSA-PKCS1-v1_5"_string);- define_an_algorithm<RSASSAPKCS1>("verify"_string, "RSASSA-PKCS1-v1_5"_string);- define_an_algorithm<RSASSAPKCS1, RsaHashedKeyGenParams>("generateKey"_string, "RSASSA-PKCS1-v1_5"_string);- define_an_algorithm<RSASSAPKCS1, RsaHashedImportParams>("importKey"_string, "RSASSA-PKCS1-v1_5"_string);- define_an_algorithm<RSASSAPKCS1>("exportKey"_string, "RSASSA-PKCS1-v1_5"_string);-- // https://w3c.github.io/webcrypto/#rsa-pss-registration- define_an_algorithm<RSAPSS, RsaPssParams>("sign"_string, "RSA-PSS"_string);- define_an_algorithm<RSAPSS, RsaPssParams>("verify"_string, "RSA-PSS"_string);- define_an_algorithm<RSAPSS, RsaHashedKeyGenParams>("generateKey"_string, "RSA-PSS"_string);- define_an_algorithm<RSAPSS, RsaHashedImportParams>("importKey"_string, "RSA-PSS"_string);- define_an_algorithm<RSAPSS>("exportKey"_string, "RSA-PSS"_string);-- // https://w3c.github.io/webcrypto/#rsa-oaep-registration- define_an_algorithm<RSAOAEP, RsaOaepParams>("encrypt"_string, "RSA-OAEP"_string);- define_an_algorithm<RSAOAEP, RsaOaepParams>("decrypt"_string, "RSA-OAEP"_string);- define_an_algorithm<RSAOAEP, RsaHashedKeyGenParams>("generateKey"_string, "RSA-OAEP"_string);- define_an_algorithm<RSAOAEP, RsaHashedImportParams>("importKey"_string, "RSA-OAEP"_string);- define_an_algorithm<RSAOAEP>("exportKey"_string, "RSA-OAEP"_string);-- // https://w3c.github.io/webcrypto/#ecdsa-registration- define_an_algorithm<ECDSA, EcdsaParams>("sign"_string, "ECDSA"_string);- define_an_algorithm<ECDSA, EcdsaParams>("verify"_string, "ECDSA"_string);- define_an_algorithm<ECDSA, EcKeyGenParams>("generateKey"_string, "ECDSA"_string);- define_an_algorithm<ECDSA, EcKeyImportParams>("importKey"_string, "ECDSA"_string);- define_an_algorithm<ECDSA>("exportKey"_string, "ECDSA"_string);-- // https://w3c.github.io/webcrypto/#ecdh-registration- define_an_algorithm<ECDH, EcKeyImportParams>("importKey"_string, "ECDH"_string);- define_an_algorithm<ECDH>("exportKey"_string, "ECDH"_string);- define_an_algorithm<ECDH, EcdhKeyDeriveParams>("deriveBits"_string, "ECDH"_string);- define_an_algorithm<ECDH, EcKeyGenParams>("generateKey"_string, "ECDH"_string);-- // https://w3c.github.io/webcrypto/#aes-ctr-registration- define_an_algorithm<AesCtr, AesCtrParams>("encrypt"_string, "AES-CTR"_string);- define_an_algorithm<AesCtr, AesCtrParams>("decrypt"_string, "AES-CTR"_string);- define_an_algorithm<AesCtr, AesKeyGenParams>("generateKey"_string, "AES-CTR"_string);- define_an_algorithm<AesCtr>("importKey"_string, "AES-CTR"_string);- define_an_algorithm<AesCtr>("exportKey"_string, "AES-CTR"_string);- define_an_algorithm<AesCtr, AesDerivedKeyParams>("get key length"_string, "AES-CTR"_string);-- // https://w3c.github.io/webcrypto/#aes-cbc-registration- define_an_algorithm<AesCbc, AesCbcParams>("encrypt"_string, "AES-CBC"_string);- define_an_algorithm<AesCbc, AesCbcParams>("decrypt"_string, "AES-CBC"_string);- define_an_algorithm<AesCbc, AesKeyGenParams>("generateKey"_string, "AES-CBC"_string);- define_an_algorithm<AesCbc>("importKey"_string, "AES-CBC"_string);- define_an_algorithm<AesCbc>("exportKey"_string, "AES-CBC"_string);- define_an_algorithm<AesCbc, AesDerivedKeyParams>("get key length"_string, "AES-CBC"_string);-- // https://w3c.github.io/webcrypto/#aes-gcm-registration- define_an_algorithm<AesGcm, AesGcmParams>("encrypt"_string, "AES-GCM"_string);- define_an_algorithm<AesGcm, AesGcmParams>("decrypt"_string, "AES-GCM"_string);- define_an_algorithm<AesGcm, AesKeyGenParams>("generateKey"_string, "AES-GCM"_string);- define_an_algorithm<AesGcm>("importKey"_string, "AES-GCM"_string);- define_an_algorithm<AesGcm>("exportKey"_string, "AES-GCM"_string);- define_an_algorithm<AesGcm, AesDerivedKeyParams>("get key length"_string, "AES-GCM"_string);-- // https://w3c.github.io/webcrypto/#aes-kw-registration- define_an_algorithm<AesKw>("wrapKey"_string, "AES-KW"_string);- define_an_algorithm<AesKw>("unwrapKey"_string, "AES-KW"_string);- define_an_algorithm<AesKw, AesKeyGenParams>("generateKey"_string, "AES-KW"_string);- define_an_algorithm<AesKw>("importKey"_string, "AES-KW"_string);- define_an_algorithm<AesKw>("exportKey"_string, "AES-KW"_string);- define_an_algorithm<AesKw, AesDerivedKeyParams>("get key length"_string, "AES-KW"_string);-- // https://w3c.github.io/webcrypto/#hmac-registration- define_an_algorithm<HMAC>("sign"_string, "HMAC"_string);- define_an_algorithm<HMAC>("verify"_string, "HMAC"_string);- define_an_algorithm<HMAC, HmacKeyGenParams>("generateKey"_string, "HMAC"_string);- define_an_algorithm<HMAC, HmacImportParams>("importKey"_string, "HMAC"_string);- define_an_algorithm<HMAC>("exportKey"_string, "HMAC"_string);- define_an_algorithm<HMAC, HmacImportParams>("get key length"_string, "HMAC"_string);-- // https://w3c.github.io/webcrypto/#sha-registration- define_an_algorithm<SHA>("digest"_string, "SHA-1"_string);- define_an_algorithm<SHA>("digest"_string, "SHA-256"_string);- define_an_algorithm<SHA>("digest"_string, "SHA-384"_string);- define_an_algorithm<SHA>("digest"_string, "SHA-512"_string);-- // https://wicg.github.io/webcrypto-modern-algos/#sha3-registration- define_an_algorithm<SHA>("digest"_string, "SHA3-256"_string);- define_an_algorithm<SHA>("digest"_string, "SHA3-384"_string);- define_an_algorithm<SHA>("digest"_string, "SHA3-512"_string);-- // https://wicg.github.io/webcrypto-modern-algos/#cshake-registration- define_an_algorithm<CShake, CShakeParams>("digest"_string, "cSHAKE128"_string);- define_an_algorithm<CShake, CShakeParams>("digest"_string, "cSHAKE256"_string);-- // https://w3c.github.io/webcrypto/#hkdf-registration- define_an_algorithm<HKDF, HKDFParams>("deriveBits"_string, "HKDF"_string);- define_an_algorithm<HKDF>("importKey"_string, "HKDF"_string);- define_an_algorithm<HKDF>("get key length"_string, "HKDF"_string);-- // https://w3c.github.io/webcrypto/#pbkdf2-registration- define_an_algorithm<PBKDF2, PBKDF2Params>("deriveBits"_string, "PBKDF2"_string);- define_an_algorithm<PBKDF2>("importKey"_string, "PBKDF2"_string);- define_an_algorithm<PBKDF2>("get key length"_string, "PBKDF2"_string);-- // https://wicg.github.io/webcrypto-secure-curves/#x25519-registration- define_an_algorithm<X25519, EcdhKeyDeriveParams>("deriveBits"_string, "X25519"_string);- define_an_algorithm<X25519>("generateKey"_string, "X25519"_string);- define_an_algorithm<X25519>("importKey"_string, "X25519"_string);- define_an_algorithm<X25519>("exportKey"_string, "X25519"_string);+ auto& realm = *realm_pointer;+ Vector<KeyUsage> usage_vector;+ usage_vector.append(usages.data(), usages.size());+ auto result = algorithm->methods->generate_key(realm, *algorithm->parameter, extractable, usage_vector);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ result.value().visit(+ [&](GC::Ref<CryptoKey> const& key) { *out_key = key.ptr(); },+ [&](CryptoKeyPair const& pair) {+ *out_public_key = pair.public_key.ptr();+ *out_private_key = pair.private_key.ptr();+ });+ return JS::HostABI::normal_completion_to_abi(0);+}- // https://wicg.github.io/webcrypto-secure-curves/#x448-registration- define_an_algorithm<X448, EcdhKeyDeriveParams>("deriveBits"_string, "X448"_string);- define_an_algorithm<X448>("generateKey"_string, "X448"_string);- define_an_algorithm<X448>("importKey"_string, "X448"_string);- define_an_algorithm<X448>("exportKey"_string, "X448"_string);+JSCompletion web_crypto_algorithm_export_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, KeyFormat format, CryptoKey* key, void* state, ReceiveBytes receive_bytes, ReceiveJsonWebKey receive_jwk)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->export_key(realm, format, *key);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ result.value().visit(+ [&](ByteBuffer const& bytes) { receive_bytes(state, bytes.span()); },+ [&](JsonWebKey const& key) { with_raw_json_web_key(key, state, receive_jwk); });+ return JS::HostABI::normal_completion_to_abi(0);+}- // https://wicg.github.io/webcrypto-secure-curves/#ed25519-registration- define_an_algorithm<ED25519>("sign"_string, "Ed25519"_string);- define_an_algorithm<ED25519>("verify"_string, "Ed25519"_string);- define_an_algorithm<ED25519>("generateKey"_string, "Ed25519"_string);- define_an_algorithm<ED25519>("importKey"_string, "Ed25519"_string);- define_an_algorithm<ED25519>("exportKey"_string, "Ed25519"_string);+JSCompletion web_crypto_algorithm_get_key_length(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, OptionalLength* out)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->get_key_length(realm, *algorithm->parameter);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ *out = { result.value().has_value(), result.value().value_or(0) };+ return JS::HostABI::normal_completion_to_abi(0);+}- // https://wicg.github.io/webcrypto-secure-curves/#ed448-registration- define_an_algorithm<ED448, Ed448Params>("sign"_string, "Ed448"_string);- define_an_algorithm<ED448, Ed448Params>("verify"_string, "Ed448"_string);- define_an_algorithm<ED448>("generateKey"_string, "Ed448"_string);- define_an_algorithm<ED448>("importKey"_string, "Ed448"_string);- define_an_algorithm<ED448>("exportKey"_string, "Ed448"_string);+JSCompletion web_crypto_algorithm_get_shared_key_length(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, u32* out)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->get_shared_key_length(*algorithm->parameter);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ *out = result.value();+ return JS::HostABI::normal_completion_to_abi(0);+}- // https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-registration- for (auto const& name : { "ML-DSA-44"_string, "ML-DSA-65"_string, "ML-DSA-87"_string }) {- define_an_algorithm<MLDSA, ContextParams>("sign"_string, name);- define_an_algorithm<MLDSA, ContextParams>("verify"_string, name);- define_an_algorithm<MLDSA>("generateKey"_string, name);- define_an_algorithm<MLDSA>("importKey"_string, name);- define_an_algorithm<MLDSA>("exportKey"_string, name);- }+JSCompletion web_crypto_algorithm_wrap_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->wrap_key(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ receive(state, result.value().span());+ return JS::HostABI::normal_completion_to_abi(0);+}- // https://wicg.github.io/webcrypto-modern-algos/#ml-kem-registration- for (auto const& name : { "ML-KEM-512"_string, "ML-KEM-768"_string, "ML-KEM-1024"_string }) {- define_an_algorithm<MLKEM>("generateKey"_string, name);- define_an_algorithm<MLKEM>("importKey"_string, name);- define_an_algorithm<MLKEM>("exportKey"_string, name);- define_an_algorithm<MLKEM>("encapsulate"_string, name);- define_an_algorithm<MLKEM>("decapsulate"_string, name);- define_an_algorithm<MLKEM>("get shared key length"_string, name);- }+JSCompletion web_crypto_algorithm_unwrap_key(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->unwrap_key(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ receive(state, result.value().span());+ return JS::HostABI::normal_completion_to_abi(0);+}- // https://wicg.github.io/webcrypto-modern-algos/#argon2-registration- for (auto const& algorithm : { "Argon2d"_string, "Argon2i"_string, "Argon2id"_string }) {- define_an_algorithm<Argon2>("importKey"_string, algorithm);- define_an_algorithm<Argon2, Argon2Params>("deriveBits"_string, algorithm);- define_an_algorithm<Argon2>("get key length"_string, algorithm);- }+JSCompletion web_crypto_algorithm_encapsulate(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, void* shared_key, void* ciphertext, ReceiveBytes receive)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->encapsulate(realm, *algorithm->parameter, *key);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ if (result.value().shared_key.has_value())+ receive(shared_key, result.value().shared_key->span());+ if (result.value().ciphertext.has_value())+ receive(ciphertext, result.value().ciphertext->span());+ return JS::HostABI::normal_completion_to_abi(0);+}- // https://wicg.github.io/webcrypto-modern-algos/#chacha20-poly1305-registration- define_an_algorithm<ChaCha20Poly1305, AeadParams>("encrypt"_string, "ChaCha20-Poly1305"_string);- define_an_algorithm<ChaCha20Poly1305, AeadParams>("decrypt"_string, "ChaCha20-Poly1305"_string);- define_an_algorithm<ChaCha20Poly1305>("generateKey"_string, "ChaCha20-Poly1305"_string);- define_an_algorithm<ChaCha20Poly1305>("importKey"_string, "ChaCha20-Poly1305"_string);- define_an_algorithm<ChaCha20Poly1305>("exportKey"_string, "ChaCha20-Poly1305"_string);- define_an_algorithm<ChaCha20Poly1305>("get key length"_string, "ChaCha20-Poly1305"_string);+JSCompletion web_crypto_algorithm_decapsulate(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, CryptoKey* key, ReadonlyBytes data, void* state, ReceiveBytes receive)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->decapsulate(realm, *algorithm->parameter, *key, MUST(ByteBuffer::copy(data)));+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ receive(state, result.value().span());+ return JS::HostABI::normal_completion_to_abi(0);+}- // https://wicg.github.io/webcrypto-modern-algos/#aes-ocb-registration- define_an_algorithm<AesOcb, AeadParams>("encrypt"_string, "AES-OCB"_string);- define_an_algorithm<AesOcb, AeadParams>("decrypt"_string, "AES-OCB"_string);- define_an_algorithm<AesOcb, AesKeyGenParams>("generateKey"_string, "AES-OCB"_string);- define_an_algorithm<AesOcb>("importKey"_string, "AES-OCB"_string);- define_an_algorithm<AesOcb>("exportKey"_string, "AES-OCB"_string);- define_an_algorithm<AesOcb, AesDerivedKeyParams>("get key length"_string, "AES-OCB"_string);+JSCompletion web_crypto_algorithm_validate_encrypt_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->validate_encrypt_parameters(*algorithm->parameter);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ return JS::HostABI::normal_completion_to_abi(0);+}- // https://wicg.github.io/webcrypto-modern-algos/#kmac-registration- for (auto const& algorithm : { "KMAC128"_string, "KMAC256"_string }) {- define_an_algorithm<KMAC, KmacParams>("sign"_string, algorithm);- define_an_algorithm<KMAC, KmacParams>("verify"_string, algorithm);- define_an_algorithm<KMAC, KmacKeyGenParams>("generateKey"_string, algorithm);- define_an_algorithm<KMAC, KmacImportParams>("importKey"_string, algorithm);- define_an_algorithm<KMAC>("exportKey"_string, algorithm);- define_an_algorithm<KMAC, KmacImportParams>("get key length"_string, algorithm);- }+JSCompletion web_crypto_algorithm_validate_decrypt_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->validate_decrypt_parameters(*algorithm->parameter);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ return JS::HostABI::normal_completion_to_abi(0);}-// https://w3c.github.io/webcrypto/#concept-define-an-algorithm-template<typename Methods, typename Param>-void define_an_algorithm(AK::String op, StringView algorithm)+JSCompletion web_crypto_algorithm_validate_sign_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm){- auto& internal_object = supported_algorithms_internal();+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->validate_sign_parameters(*algorithm->parameter);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ return JS::HostABI::normal_completion_to_abi(0);+}- // 1. Let registeredAlgorithms be the associative container stored at the op key of supportedAlgorithms.- // NOTE: There should always be a container at the op key.- auto maybe_registered_algorithms = internal_object.get(op);- auto registered_algorithms = maybe_registered_algorithms.value();+JSCompletion web_crypto_algorithm_validate_verify_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->validate_verify_parameters(*algorithm->parameter);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ return JS::HostABI::normal_completion_to_abi(0);+}- // 2. Set the alg key of registeredAlgorithms to the IDL dictionary type type.- registered_algorithms.set(Utf16String::from_ascii_without_validation(algorithm.bytes()), RegisteredAlgorithm { &Methods::create, &Param::from_value });- internal_object.set(op, registered_algorithms);+JSCompletion web_crypto_algorithm_validate_digest_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->validate_digest_parameters(*algorithm->parameter);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ return JS::HostABI::normal_completion_to_abi(0);}+JSCompletion web_crypto_algorithm_validate_generate_key_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->validate_generate_key_parameters(*algorithm->parameter);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ return JS::HostABI::normal_completion_to_abi(0);}-namespace Web::Bindings {+JSCompletion web_crypto_algorithm_validate_import_key_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm)+{+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->validate_import_key_parameters(*algorithm->parameter);+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ return JS::HostABI::normal_completion_to_abi(0);+}-JS::ThrowCompletionOr<GC::Ref<JS::Object>> create_algorithm_dictionary(JS::Realm& realm, Utf16String const& name)+JSCompletion web_crypto_algorithm_validate_derive_bits_parameters(JS::Realm* realm_pointer, NormalizedAlgorithmAndParameter const* algorithm, OptionalLength length){- auto dictionary = JS::Object::create(realm, realm.intrinsics().object_prototype());- TRY(dictionary->create_data_property("name"_utf16_fly_string, JS::PrimitiveString::create(realm.vm(), name)));- return dictionary;+ auto& realm = *realm_pointer;+ auto result = algorithm->methods->validate_derive_bits_parameters(*algorithm->parameter, length.to_optional());+ if (result.is_exception())+ return Bindings::completion_to_abi(realm, result.release_error());+ return JS::HostABI::normal_completion_to_abi(0);}}diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.h b/Libraries/LibWeb/Crypto/SubtleCrypto.hindex 3386e1cf72f..bc226b77be4 100644--- a/Libraries/LibWeb/Crypto/SubtleCrypto.h+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.h@@ -7,80 +7,16 @@#pragma once-#include <AK/String.h>-#include <AK/Vector.h>-#include <LibGC/Forward.h>-#include <LibJS/Forward.h>-#include <LibJS/Runtime/Completion.h>-#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Crypto/CryptoAlgorithms.h>-#include <LibWeb/Crypto/CryptoKey.h>-#include <LibWeb/Export.h>namespace Web::Crypto {-class SubtleCrypto final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(SubtleCrypto, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(SubtleCrypto);--public:- [[nodiscard]] static GC::Ref<SubtleCrypto> create();-- virtual ~SubtleCrypto() override;-- GC::Ref<WebIDL::Promise> encrypt(JS::Realm&, AlgorithmIdentifier const& algorithm, GC::Ref<CryptoKey> key, WebIDL::BufferSourceVariant const& data_parameter);- GC::Ref<WebIDL::Promise> decrypt(JS::Realm&, AlgorithmIdentifier const& algorithm, GC::Ref<CryptoKey> key, WebIDL::BufferSourceVariant const& data_parameter);- GC::Ref<WebIDL::Promise> sign(JS::Realm&, AlgorithmIdentifier const& algorithm, GC::Ref<CryptoKey> key, WebIDL::BufferSourceVariant const& data_parameter);- GC::Ref<WebIDL::Promise> verify(JS::Realm&, AlgorithmIdentifier const& algorithm, GC::Ref<CryptoKey> key, WebIDL::BufferSourceVariant const& signature, WebIDL::BufferSourceVariant const& data_parameter);-- GC::Ref<WebIDL::Promise> digest(JS::Realm&, AlgorithmIdentifier const& algorithm, WebIDL::BufferSourceVariant const& data);-- GC::Ref<WebIDL::Promise> generate_key(JS::Realm&, AlgorithmIdentifier algorithm, bool extractable, Vector<KeyUsage> key_usages);- GC::Ref<WebIDL::Promise> derive_bits(JS::Realm&, AlgorithmIdentifier algorithm, GC::Ref<CryptoKey> base_key, Optional<u32> length_optional);- GC::Ref<WebIDL::Promise> derive_key(JS::Realm&, AlgorithmIdentifier algorithm, GC::Ref<CryptoKey> base_key, AlgorithmIdentifier derived_key_type, bool extractable, Vector<KeyUsage> key_usages);-- GC::Ref<WebIDL::Promise> import_key(JS::Realm&, KeyFormat format, KeyDataType key_data, AlgorithmIdentifier algorithm, bool extractable, Vector<KeyUsage> key_usages);- GC::Ref<WebIDL::Promise> export_key(JS::Realm&, KeyFormat format, GC::Ref<CryptoKey> key);-- GC::Ref<WebIDL::Promise> wrap_key(JS::Realm&, KeyFormat format, GC::Ref<CryptoKey> key, GC::Ref<CryptoKey> wrapping_key, AlgorithmIdentifier wrap_algorithm);- GC::Ref<WebIDL::Promise> unwrap_key(JS::Realm&, KeyFormat format, WebIDL::BufferSourceVariant wrapped_key, GC::Ref<CryptoKey> unwrapping_key, AlgorithmIdentifier unwrap_algorithm, AlgorithmIdentifier unwrapped_key_algorithm, bool extractable, Vector<KeyUsage> key_usages);-- GC::Ref<WebIDL::Promise> encapsulate_key(JS::Realm&, AlgorithmIdentifier encapsulation_algorithm, GC::Ref<CryptoKey> encapsulation_key, AlgorithmIdentifier shared_key_algorithm, bool extractable, Vector<KeyUsage> key_usages);- GC::Ref<WebIDL::Promise> encapsulate_bits(JS::Realm&, AlgorithmIdentifier encapsulation_algorithm, GC::Ref<CryptoKey> encapsulation_key);-- GC::Ref<WebIDL::Promise> decapsulate_key(JS::Realm&, AlgorithmIdentifier decapsulation_algorithm, GC::Ref<CryptoKey> decapsulation_key, WebIDL::BufferSourceVariant const& ciphertext, AlgorithmIdentifier shared_key_algorithm, bool extractable, Vector<KeyUsage> const& usages);- GC::Ref<WebIDL::Promise> decapsulate_bits(JS::Realm&, AlgorithmIdentifier decapsulation_algorithm, GC::Ref<CryptoKey> decapsulation_key, WebIDL::BufferSourceVariant const& ciphertext);-- GC::Ref<WebIDL::Promise> get_public_key(JS::Realm&, GC::Ref<CryptoKey> key, Vector<KeyUsage> key_usages);-- static bool supports(JS::Realm&, Utf16String const& operation, AlgorithmIdentifier const& algorithm, Optional<u32> length);- static bool supports(JS::Realm&, Utf16String const& operation, AlgorithmIdentifier const& algorithm, AlgorithmIdentifier const& additional_algorithm);--private:- SubtleCrypto();-};-struct NormalizedAlgorithmAndParameter {+ AK_ALLOC_WITH_KMALLOC;+NonnullOwnPtr<AlgorithmMethods> methods;NonnullOwnPtr<AlgorithmParams> parameter;};WebIDL::ExceptionOr<NormalizedAlgorithmAndParameter> normalize_an_algorithm(JS::Realm&, AlgorithmIdentifier const& algorithm, String operation);}--namespace Web::Bindings {--WEB_API JS::ThrowCompletionOr<GC::Ref<JS::Object>> create_algorithm_dictionary(JS::Realm&, Utf16String const& name);--WEB_API GC::Ref<WebIDL::Promise> generate_key(JS::Realm&, Crypto::SubtleCrypto&, Crypto::AlgorithmIdentifier, bool extractable, Vector<KeyUsage>);-WEB_API GC::Ref<WebIDL::Promise> derive_key(JS::Realm&, Crypto::SubtleCrypto&, Crypto::AlgorithmIdentifier, GC::Ref<Crypto::CryptoKey>, Crypto::AlgorithmIdentifier, bool extractable, Vector<KeyUsage>);-WEB_API GC::Ref<WebIDL::Promise> export_key(JS::Realm&, Crypto::SubtleCrypto&, KeyFormat, GC::Ref<Crypto::CryptoKey>);-WEB_API GC::Ref<WebIDL::Promise> wrap_key(JS::Realm&, Crypto::SubtleCrypto&, KeyFormat, GC::Ref<Crypto::CryptoKey>, GC::Ref<Crypto::CryptoKey>, Crypto::AlgorithmIdentifier);-WEB_API GC::Ref<WebIDL::Promise> unwrap_key(JS::Realm&, Crypto::SubtleCrypto&, KeyFormat, WebIDL::BufferSourceVariant, GC::Ref<Crypto::CryptoKey>, Crypto::AlgorithmIdentifier, Crypto::AlgorithmIdentifier, bool extractable, Vector<KeyUsage>);-WEB_API GC::Ref<WebIDL::Promise> encapsulate_key(JS::Realm&, Crypto::SubtleCrypto&, Crypto::AlgorithmIdentifier, GC::Ref<Crypto::CryptoKey>, Crypto::AlgorithmIdentifier, bool extractable, Vector<KeyUsage>);-WEB_API GC::Ref<WebIDL::Promise> decapsulate_key(JS::Realm&, Crypto::SubtleCrypto&, Crypto::AlgorithmIdentifier, GC::Ref<Crypto::CryptoKey>, WebIDL::BufferSourceVariant const&, Crypto::AlgorithmIdentifier, bool extractable, Vector<KeyUsage>);--}--// NB: The methods and parameters of an algorithm are not cells, and keep any cell they use in a GC::Root.-GC_UNTRACED_CAPTURE(Web::Crypto::NormalizedAlgorithmAndParameter);diff --git a/Libraries/LibWeb/Crypto/SubtleCrypto.idl b/Libraries/LibWeb/Crypto/SubtleCrypto.idlindex cdc6ea4e427..36c2f452238 100644--- a/Libraries/LibWeb/Crypto/SubtleCrypto.idl+++ b/Libraries/LibWeb/Crypto/SubtleCrypto.idl@@ -7,6 +7,8 @@ dictionary Algorithm {// https://wicg.github.io/webcrypto-modern-algos/#subtlecrypto-interface-keyformatenum KeyFormat { "raw-public", "raw-private", "raw-seed", "raw-secret", "raw", "spki", "pkcs8", "jwk" };+typedef (BufferSource or JsonWebKey) KeyDataType;+dictionary RsaOtherPrimesInfo {// The following fields are defined in Section 6.3.2.7 of JSON Web AlgorithmsDOMString r;@@ -46,6 +48,12 @@ dictionary JsonWebKey {DOMString priv;};+// https://w3c.github.io/webcrypto/#dfn-CryptoKeyPair+dictionary CryptoKeyPair {+ CryptoKey publicKey;+ CryptoKey privateKey;+};+// https://wicg.github.io/webcrypto-modern-algos/#encapsulationdictionary EncapsulatedKey {CryptoKey sharedKey;@@ -59,7 +67,7 @@ dictionary EncapsulatedBits {};// https://w3c.github.io/webcrypto/#subtlecrypto-interface-[SecureContext,Exposed=(Window,Worker)]+[SecureContext,Exposed=(Window,Worker),ImplementedIn=Rust]interface SubtleCrypto {[NeedsCallerRealm] Promise<ArrayBuffer> encrypt(AlgorithmIdentifier algorithm, CryptoKey key, BufferSource data);[NeedsCallerRealm] Promise<ArrayBuffer> decrypt(AlgorithmIdentifier algorithm, CryptoKey key, BufferSource data);@@ -72,7 +80,7 @@ interface SubtleCrypto {[NeedsCallerRealm] Promise<CryptoKey> deriveKey(AlgorithmIdentifier algorithm, CryptoKey baseKey, AlgorithmIdentifier derivedKeyType, boolean extractable, sequence<KeyUsage> keyUsages);[NeedsCallerRealm] Promise<ArrayBuffer> deriveBits(AlgorithmIdentifier algorithm, CryptoKey baseKey, optional [EnforceRange] unsigned long? length = null);- [NeedsCallerRealm] Promise<CryptoKey> importKey(KeyFormat format, (BufferSource or JsonWebKey) keyData, AlgorithmIdentifier algorithm, boolean extractable, sequence<KeyUsage> keyUsages);+ [NeedsCallerRealm] Promise<CryptoKey> importKey(KeyFormat format, KeyDataType keyData, AlgorithmIdentifier algorithm, boolean extractable, sequence<KeyUsage> keyUsages);[NeedsCallerRealm] Promise<(ArrayBuffer or JsonWebKey)> exportKey(KeyFormat format, CryptoKey key);[NeedsCallerRealm] Promise<ArrayBuffer> wrapKey(KeyFormat format, CryptoKey key, CryptoKey wrappingKey, AlgorithmIdentifier wrapAlgorithm);@@ -84,6 +92,6 @@ interface SubtleCrypto {[NeedsCallerRealm] Promise<CryptoKey> decapsulateKey(AlgorithmIdentifier decapsulationAlgorithm, CryptoKey decapsulationKey, BufferSource ciphertext, AlgorithmIdentifier sharedKeyAlgorithm, boolean extractable, sequence<KeyUsage> keyUsages);[NeedsCallerRealm] Promise<ArrayBuffer> decapsulateBits(AlgorithmIdentifier decapsulationAlgorithm, CryptoKey decapsulationKey, BufferSource ciphertext);[NeedsCallerRealm] Promise<CryptoKey> getPublicKey(CryptoKey key, sequence<KeyUsage> keyUsages);- [NeedsCallerRealm] static boolean supports(DOMString operation, AlgorithmIdentifier algorithm, optional [EnforceRange] unsigned long? length = null);- [NeedsCallerRealm] static boolean supports(DOMString operation, AlgorithmIdentifier algorithm, AlgorithmIdentifier additionalAlgorithm);+ [NeedsCallerRealm, ImplementedAs=supports_length] static boolean supports(DOMString operation, AlgorithmIdentifier algorithm, optional [EnforceRange] unsigned long? length = null);+ [NeedsCallerRealm, ImplementedAs=supports_additional_algorithm] static boolean supports(DOMString operation, AlgorithmIdentifier algorithm, AlgorithmIdentifier additionalAlgorithm);};diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 1b6c45619a9..882182313e2 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -45,10 +45,11 @@ ALLOWED_REALM_MENTIONS = {"ContentSecurityPolicy": (4, 10, "CSP violation/report objects and callbacks still materialize JS-facing values"),"CookieStore": (2, 19, "cookie-store async callbacks and promise/value materialization still thread realms"),"Crypto": (- 7,- 371,+ 6,+ 358,"WebCrypto algorithms still use realms for buffer/key/promise materialization and for normalizing algorithm "- "dictionaries, which SubtleCrypto.supports() does in the caller realm",+ "dictionaries, which SubtleCrypto.supports() does in the caller realm. The native CryptoKey wrapper "+ "uses the caller's realm and wrapper world",),"DOM": (10,