mod events;
pub(super) use crate::interop::protocol_names::{
protocol_discriminant_to_name, protocol_name_to_discriminant,
};
pub(crate) use crate::protocol::utils::pending_action_wire;
mod stores;
use std::collections::HashMap;
use crate::interop::protocol_names::unpair_ack_from_name;
use crate::interop::wasm::primitives::pairing::ContactMessage as PairingContactMessage;
use crate::{
interop::wasm::ts_bindings_utils::{js_error, js_error_from_lib},
protocol::{
DeRecFlow, DeRecProtocol, DeRecProtocolBuilder, DeRecProtocolConfig, TimeoutsConfig,
types::{Target, UserSecret},
},
types::{ChannelId, WeightedChannel},
};
use derec_proto::{SenderKind, TransportProtocol};
use js_sys::Array;
use stores::{
JsChannelStore, JsSecretStore, JsShareStore, JsStateStore, JsTransport, JsUserSecretStore,
};
use wasm_bindgen::prelude::*;
type WasmProtocol = DeRecProtocol<
JsChannelStore,
JsShareStore,
JsSecretStore,
JsUserSecretStore,
JsStateStore,
JsTransport,
>;
#[wasm_bindgen]
pub struct DeRecProtocolWasm {
inner: tokio::sync::Mutex<WasmProtocol>,
secret_id: u64,
}
fn js_object_into<T: serde::de::DeserializeOwned>(value: JsValue) -> Result<T, String> {
let json: serde_json::Value =
serde_wasm_bindgen::from_value(value).map_err(|e| e.to_string())?;
crate::interop::strict_json::object_into(json)
}
#[wasm_bindgen(js_name = DeRecProtocolBuilder)]
pub struct DeRecProtocolBuilderWasm {
secret_id: u64,
channel_store: Option<JsValue>,
share_store: Option<JsValue>,
secret_store: Option<JsValue>,
user_secret_store: Option<JsValue>,
state_store: Option<JsValue>,
transport: Option<JsValue>,
config: DeRecProtocolConfig,
}
#[wasm_bindgen(js_class = DeRecProtocolBuilder)]
impl DeRecProtocolBuilderWasm {
#[wasm_bindgen(constructor)]
pub fn new(secret_id: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
let secret_id = js_value_to_u64(secret_id)
.map_err(|e| js_error("invalid_secret_id", format!("{e:?}")))?;
Ok(DeRecProtocolBuilderWasm {
secret_id,
channel_store: None,
share_store: None,
secret_store: None,
user_secret_store: None,
state_store: None,
transport: None,
config: DeRecProtocolConfig::default(),
})
}
#[wasm_bindgen(js_name = withChannelStore)]
pub fn with_channel_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
self.channel_store = Some(store);
self
}
#[wasm_bindgen(js_name = withShareStore)]
pub fn with_share_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
self.share_store = Some(store);
self
}
#[wasm_bindgen(js_name = withSecretStore)]
pub fn with_secret_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
self.secret_store = Some(store);
self
}
#[wasm_bindgen(js_name = withUserSecretStore)]
pub fn with_user_secret_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
self.user_secret_store = Some(store);
self
}
#[wasm_bindgen(js_name = withStateStore)]
pub fn with_state_store(mut self, store: JsValue) -> DeRecProtocolBuilderWasm {
self.state_store = Some(store);
self
}
#[wasm_bindgen(js_name = withStores)]
pub fn with_stores(mut self, stores: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
let get = |key: &str, setter_name: &str| -> Result<JsValue, JsValue> {
let value = js_sys::Reflect::get(&stores, &JsValue::from_str(key))
.map_err(|e| js_error("decode_error", format!("missing {key}: {e:?}")))?;
if value.is_undefined() || value.is_null() {
return Err(js_error(
"builder_missing",
format!("{setter_name} is required"),
));
}
Ok(value)
};
self.channel_store = Some(get("channelStore", "withChannelStore")?);
self.share_store = Some(get("shareStore", "withShareStore")?);
self.secret_store = Some(get("secretStore", "withSecretStore")?);
self.user_secret_store = Some(get("userSecretStore", "withUserSecretStore")?);
self.state_store = Some(get("stateStore", "withStateStore")?);
Ok(self)
}
#[wasm_bindgen(js_name = withTransport)]
pub fn with_transport(mut self, transport: JsValue) -> DeRecProtocolBuilderWasm {
self.transport = Some(transport);
self
}
#[wasm_bindgen(js_name = withOwnTransports)]
pub fn with_own_transports(
mut self,
transports: Vec<JsValue>,
) -> Result<DeRecProtocolBuilderWasm, JsValue> {
#[derive(serde::Deserialize)]
struct EndpointShape {
uri: String,
protocol: String,
}
let mut parsed_transports = Vec::with_capacity(transports.len());
for endpoint in transports {
let parsed: EndpointShape = serde_wasm_bindgen::from_value(endpoint)
.map_err(|e| js_error("invalid_own_transport", e.to_string()))?;
let protocol_num =
protocol_name_to_discriminant(&parsed.protocol).ok_or_else(|| {
js_error(
"invalid_protocol",
format!("unknown protocol: {}", parsed.protocol.to_lowercase()),
)
})?;
let proto_tp = TransportProtocol {
uri: parsed.uri,
protocol: protocol_num,
};
let tp = crate::transport::TransportProtocol::try_from(&proto_tp)
.map_err(|e| js_error("invalid_own_transport", e.to_string()))?;
parsed_transports.push(tp);
}
self.config.own_transports = Some(parsed_transports);
Ok(self)
}
#[wasm_bindgen(js_name = withThreshold)]
pub fn with_threshold(
mut self,
threshold: JsValue,
) -> Result<DeRecProtocolBuilderWasm, JsValue> {
self.config.threshold = Some(js_number_to_u32(&threshold, "threshold")? as usize);
Ok(self)
}
#[wasm_bindgen(js_name = withUnsafeConnection)]
pub fn with_unsafe_connection(mut self, allow: bool) -> DeRecProtocolBuilderWasm {
self.config.unsafe_connection = Some(allow);
self
}
#[wasm_bindgen(js_name = withTimeouts)]
pub fn with_timeouts(mut self, timeouts: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
let parsed: TimeoutsConfig =
js_object_into(timeouts).map_err(|e| js_error("invalid_timeouts", e))?;
self.config.timeouts = Some(parsed);
Ok(self)
}
#[wasm_bindgen(js_name = withCommunicationInfo)]
pub fn with_communication_info(
mut self,
info: JsValue,
) -> Result<DeRecProtocolBuilderWasm, JsValue> {
let parsed: HashMap<String, String> = serde_wasm_bindgen::from_value(info)
.map_err(|e| js_error("invalid_communication_info", e.to_string()))?;
self.config.communication_info = Some(parsed);
Ok(self)
}
#[wasm_bindgen(js_name = withAutoRespondOnFailure)]
pub fn with_auto_respond_on_failure(mut self, enabled: bool) -> DeRecProtocolBuilderWasm {
self.config.auto_respond_on_failure = Some(enabled);
self
}
#[wasm_bindgen(js_name = withUnpairAck)]
pub fn with_unpair_ack(mut self, ack: String) -> Result<DeRecProtocolBuilderWasm, JsValue> {
self.config.unpair_ack = Some(unpair_ack_from_name(&ack).ok_or_else(|| {
js_error(
"invalid_unpair_ack",
format!(
"unknown unpair_ack value: {ack:?}; expected \"required\" or \"not_required\""
),
)
})?);
Ok(self)
}
#[wasm_bindgen(js_name = withAutoReplyTo)]
pub fn with_auto_reply_to(mut self, enabled: bool) -> DeRecProtocolBuilderWasm {
self.config.auto_reply_to = Some(enabled);
self
}
#[wasm_bindgen(js_name = withAutoAccept)]
pub fn with_auto_accept(
mut self,
policy: JsValue,
) -> Result<DeRecProtocolBuilderWasm, JsValue> {
#[derive(serde::Deserialize, Default)]
#[serde(rename_all = "camelCase", default)]
struct AutoAcceptPolicyShape {
pairing: bool,
pre_pair: bool,
store_share: bool,
verify_share: bool,
discovery: bool,
get_share: bool,
unpair: bool,
update_channel_info: bool,
}
let parsed: AutoAcceptPolicyShape = serde_wasm_bindgen::from_value(policy)
.map_err(|e| js_error("invalid_auto_accept_policy", e.to_string()))?;
self.config.auto_accept = Some(crate::protocol::AutoAcceptPolicy {
pairing: parsed.pairing,
pre_pair: parsed.pre_pair,
store_share: parsed.store_share,
verify_share: parsed.verify_share,
discovery: parsed.discovery,
get_share: parsed.get_share,
unpair: parsed.unpair,
update_channel_info: parsed.update_channel_info,
});
Ok(self)
}
#[wasm_bindgen(js_name = withReplicaId)]
pub fn with_replica_id(mut self, id: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
let v =
js_value_to_u64(id).map_err(|e| js_error("invalid_replica_id", format!("{e:?}")))?;
self.config.replica_id = Some(v);
Ok(self)
}
#[wasm_bindgen(js_name = withParameterRange)]
pub fn with_parameter_range(
mut self,
range: JsValue,
) -> Result<DeRecProtocolBuilderWasm, JsValue> {
#[derive(serde::Deserialize)]
struct In {
#[serde(default)]
min_share_size: i64,
#[serde(default)]
max_share_size: i64,
#[serde(default)]
min_time_between_verifications: i64,
#[serde(default)]
max_time_between_verifications: i64,
#[serde(default)]
min_time_between_share_updates: i64,
#[serde(default)]
max_time_between_share_updates: i64,
#[serde(default)]
min_unresponsive_deletion_timeout: i64,
#[serde(default)]
max_unresponsive_deletion_timeout: i64,
#[serde(default)]
min_unresponsive_deactivation_timeout: i64,
#[serde(default)]
max_unresponsive_deactivation_timeout: i64,
}
let parsed: In = serde_wasm_bindgen::from_value(range)
.map_err(|e| js_error("invalid_parameter_range", e.to_string()))?;
self.config.parameter_range = Some(derec_proto::ParameterRange {
min_share_size: parsed.min_share_size,
max_share_size: parsed.max_share_size,
min_time_between_verifications: parsed.min_time_between_verifications,
max_time_between_verifications: parsed.max_time_between_verifications,
min_time_between_share_updates: parsed.min_time_between_share_updates,
max_time_between_share_updates: parsed.max_time_between_share_updates,
min_unresponsive_deletion_timeout: parsed.min_unresponsive_deletion_timeout,
max_unresponsive_deletion_timeout: parsed.max_unresponsive_deletion_timeout,
min_unresponsive_deactivation_timeout: parsed.min_unresponsive_deactivation_timeout,
max_unresponsive_deactivation_timeout: parsed.max_unresponsive_deactivation_timeout,
});
Ok(self)
}
#[wasm_bindgen(js_name = withMaxSubshares)]
pub fn with_max_subshares(mut self, max: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
let v = js_value_to_u64(max)
.map_err(|e| js_error("invalid_max_subshares", format!("{e:?}")))?;
self.config.max_subshares = Some(v);
Ok(self)
}
#[wasm_bindgen(js_name = withConfig)]
pub fn with_config(mut self, config: JsValue) -> Result<DeRecProtocolBuilderWasm, JsValue> {
let parsed: DeRecProtocolConfig = js_object_into(config)
.map_err(|e| js_error("decode_error", format!("invalid config: {e}")))?;
self.config.layer(parsed);
Ok(self)
}
pub fn build(self) -> Result<DeRecProtocolWasm, JsValue> {
let channel_store = self
.channel_store
.ok_or_else(|| js_error("builder_missing", "withChannelStore is required"))?;
let share_store = self
.share_store
.ok_or_else(|| js_error("builder_missing", "withShareStore is required"))?;
let secret_store = self
.secret_store
.ok_or_else(|| js_error("builder_missing", "withSecretStore is required"))?;
let user_secret_store = self
.user_secret_store
.ok_or_else(|| js_error("builder_missing", "withUserSecretStore is required"))?;
let state_store = self
.state_store
.ok_or_else(|| js_error("builder_missing", "withStateStore is required"))?;
let transport = self
.transport
.ok_or_else(|| js_error("builder_missing", "withTransport is required"))?;
let builder = DeRecProtocolBuilder::new(self.secret_id)
.with_channel_store(JsChannelStore(channel_store))
.with_share_store(JsShareStore(share_store))
.with_secret_store(JsSecretStore(secret_store))
.with_user_secret_store(JsUserSecretStore(user_secret_store))
.with_state_store(JsStateStore(state_store))
.with_transport(JsTransport(transport))
.with_config(self.config);
let inner = builder.build().map_err(js_error_from_lib)?;
Ok(DeRecProtocolWasm {
secret_id: inner.secret_id(),
inner: tokio::sync::Mutex::new(inner),
})
}
}
#[wasm_bindgen]
impl DeRecProtocolWasm {
#[wasm_bindgen(js_name = "secretId")]
pub fn secret_id(&self) -> u64 {
self.secret_id
}
#[wasm_bindgen(js_name = "createContact")]
pub async fn create_contact(
&self,
channel_id: JsValue,
contact_mode: JsValue,
nonce: JsValue,
) -> Result<JsValue, JsValue> {
let id = parse_optional_channel_id(channel_id)?;
let mode = match js_number_to_u32(&contact_mode, "contact_mode")? {
0 => derec_proto::ContactMode::InlineKeys,
1 => derec_proto::ContactMode::HashedKeys,
2 => derec_proto::ContactMode::NoKeys,
other => {
return Err(js_error(
"invalid_contact_mode",
format!(
"unknown contact_mode: {other}; expected 0 (InlineKeys), 1 (HashedKeys), or 2 (NoKeys)"
),
));
}
};
let nonce = if nonce.is_null() || nonce.is_undefined() {
None
} else {
Some(js_value_to_u64(nonce)?)
};
let contact = self
.inner
.lock()
.await
.create_contact(id, mode, nonce)
.await
.map_err(js_error_from_lib)?;
let contact: PairingContactMessage = contact.into();
let serializer =
serde_wasm_bindgen::Serializer::new().serialize_large_number_types_as_bigints(true);
use serde::Serialize as _;
contact
.serialize(&serializer)
.map_err(|e| js_error("wasm_serialize_error", e.to_string()))
}
#[wasm_bindgen(js_name = "setCommunicationInfo")]
pub async fn set_communication_info(&self, info: JsValue) -> Result<(), JsValue> {
let map: HashMap<String, String> = if info.is_null() || info.is_undefined() {
HashMap::new()
} else {
serde_wasm_bindgen::from_value(info)
.map_err(|e| js_error("invalid_communication_info", e.to_string()))?
};
self.inner.lock().await.set_communication_info(map);
Ok(())
}
#[wasm_bindgen(js_name = "setOwnTransports")]
pub async fn set_own_transports(&self, transports: Vec<JsValue>) -> Result<(), JsValue> {
#[derive(serde::Deserialize)]
struct EndpointShape {
uri: String,
protocol: String,
}
let mut validated = Vec::with_capacity(transports.len());
for endpoint in transports {
let parsed: EndpointShape = serde_wasm_bindgen::from_value(endpoint)
.map_err(|e| js_error("invalid_own_transport", e.to_string()))?;
let protocol_num =
protocol_name_to_discriminant(&parsed.protocol).ok_or_else(|| {
js_error(
"invalid_protocol",
format!("unknown protocol: {}", parsed.protocol.to_lowercase()),
)
})?;
let proto_tp = TransportProtocol {
uri: parsed.uri,
protocol: protocol_num,
};
validated.push(
crate::transport::TransportProtocol::try_from(&proto_tp)
.map_err(|e| js_error("invalid_own_transport", e.to_string()))?,
);
}
self.inner
.lock()
.await
.set_own_transports(validated)
.map_err(|e| js_error("invalid_own_transport", e.to_string()))?;
Ok(())
}
#[wasm_bindgen(js_name = "start")]
pub async fn start(&self, flow_kind: JsValue, params: JsValue) -> Result<JsValue, JsValue> {
let flow = parse_flow(js_number_to_u32(&flow_kind, "flow_kind")?, params)?;
let rust_events = self
.inner
.lock()
.await
.start(flow)
.await
.map_err(js_error_from_lib)?;
let js_events = Array::new();
for event in rust_events {
js_events.push(&events::event_to_js(event)?);
}
Ok(js_events.into())
}
#[wasm_bindgen(js_name = "getFingerprint")]
pub async fn get_fingerprint(&self, channel_id: JsValue) -> Result<String, JsValue> {
let id = js_value_to_u64(channel_id)?;
self.inner
.lock()
.await
.get_fingerprint(ChannelId(id))
.await
.map_err(js_error_from_lib)
}
#[wasm_bindgen(js_name = "verifyFingerprint")]
pub async fn verify_fingerprint(
&self,
channel_id: JsValue,
fingerprint: String,
) -> Result<bool, JsValue> {
let id = js_value_to_u64(channel_id)?;
self.inner
.lock()
.await
.verify_fingerprint(ChannelId(id), &fingerprint)
.await
.map_err(js_error_from_lib)
}
#[wasm_bindgen(js_name = removeExpiredChannels)]
pub async fn remove_expired_channels(
&self,
older_than_secs: JsValue,
) -> Result<JsValue, JsValue> {
let older_than_secs = js_value_to_u64(older_than_secs)?;
let ids = self
.inner
.lock()
.await
.remove_expired_channels(older_than_secs)
.await
.map_err(js_error_from_lib)?;
let decimal: Vec<String> = ids.iter().map(|c| c.0.to_string()).collect();
serde_wasm_bindgen::to_value(&decimal)
.map_err(|e| js_error("wasm_serialize_error", e.to_string()))
}
pub async fn accept(&self, action_bytes: &[u8]) -> Result<JsValue, JsValue> {
let action = pending_action_wire::deserialize(action_bytes)
.map_err(|e| js_error("decode_error", e))?;
let rust_events = self
.inner
.lock()
.await
.accept(action)
.await
.map_err(js_error_from_lib)?;
let js_events = Array::new();
for event in rust_events {
js_events.push(&events::event_to_js(event)?);
}
Ok(js_events.into())
}
pub async fn reject(
&self,
action_bytes: &[u8],
status: JsValue,
memo: &str,
) -> Result<(), JsValue> {
let action = pending_action_wire::deserialize(action_bytes)
.map_err(|e| js_error("decode_error", e))?;
let status_enum = status
.as_f64()
.filter(|f| f.fract() == 0.0 && (f64::from(i32::MIN)..=f64::from(i32::MAX)).contains(f))
.and_then(|f| derec_proto::StatusEnum::try_from(f as i32).ok())
.ok_or_else(|| {
js_error(
"invalid_status",
format!("invalid StatusEnum value: {status:?}"),
)
})?;
self.inner
.lock()
.await
.reject(action, status_enum, memo)
.await
.map_err(js_error_from_lib)
}
pub async fn tick(&self) -> Result<JsValue, JsValue> {
let rust_events = self.inner.lock().await.tick().await;
let js_events = Array::new();
for event in rust_events {
js_events.push(&events::event_to_js(event)?);
}
Ok(js_events.into())
}
pub async fn process(&self, message: &[u8]) -> Result<JsValue, JsValue> {
let rust_events = self
.inner
.lock()
.await
.process(message)
.await
.map_err(|e| {
let error = js_error_from_lib(e.source);
if let Some(channel_id) = e.channel_id {
let _ = js_sys::Reflect::set(
&error,
&JsValue::from_str("channel_id"),
&JsValue::from_str(&channel_id.0.to_string()),
);
}
let settled = Array::new();
for event in e.events {
match events::event_to_js(event) {
Ok(js_event) => {
settled.push(&js_event);
}
Err(encode_error) => return encode_error,
}
}
let _ = js_sys::Reflect::set(&error, &JsValue::from_str("events"), &settled);
error
})?;
let js_events = Array::new();
for event in rust_events {
js_events.push(&events::event_to_js(event)?);
}
Ok(js_events.into())
}
#[wasm_bindgen(js_name = "restore")]
pub async fn restore(
&self,
recovered_secret: JsValue,
version: JsValue,
) -> Result<JsValue, JsValue> {
let version = js_number_to_u32(&version, "version")?;
let secret = parse_recovered_secret(recovered_secret)?;
let rust_events = self
.inner
.lock()
.await
.restore(&secret, version)
.await
.map_err(js_error_from_lib)?;
let js_events = Array::new();
for event in rust_events {
js_events.push(&events::event_to_js(event)?);
}
Ok(js_events.into())
}
}
fn parse_recovered_secret(value: JsValue) -> Result<crate::protocol::types::Secret, JsValue> {
serde_wasm_bindgen::from_value::<crate::interop::recovered_secret::RecoveredSecretIn>(value)
.map_err(|e| js_error("invalid_recovered_secret", e.to_string()))?
.into_secret()
.map_err(|e| js_error("invalid_recovered_secret", e))
}
fn parse_optional_channel_id(val: JsValue) -> Result<Option<ChannelId>, JsValue> {
if val.is_null() || val.is_undefined() {
return Ok(None);
}
Ok(Some(ChannelId(js_value_to_u64(val)?)))
}
fn js_value_to_u64(val: JsValue) -> Result<u64, JsValue> {
if val.is_bigint() {
let s = js_sys::BigInt::from(val)
.to_string(10)
.map_err(|e| js_error("decode_error", format!("{e:?}")))?
.as_string()
.ok_or_else(|| js_error("decode_error", "BigInt.toString returned non-string"))?;
crate::interop::recovered_secret::parse_decimal_u64(&s, "bigint")
.map_err(|e| js_error("decode_error", e))
} else if let Some(s) = val.as_string() {
crate::interop::recovered_secret::parse_decimal_u64(&s, "string")
.map_err(|e| js_error("decode_error", e))
} else if let Some(f) = val.as_f64() {
exact_u64_from_f64(f).ok_or_else(|| {
js_error(
"decode_error",
format!(
"number {f} is not a non-negative safe integer; pass a bigint or decimal string"
),
)
})
} else {
Err(js_error(
"decode_error",
"value must be BigInt, number, or decimal string",
))
}
}
const MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
fn exact_u64_from_f64(f: f64) -> Option<u64> {
(f.is_finite() && f.fract() == 0.0 && (0.0..=MAX_SAFE_INTEGER).contains(&f)).then_some(f as u64)
}
fn js_number_to_u32(val: &JsValue, field: &str) -> Result<u32, JsValue> {
val.as_f64()
.filter(|f| f.fract() == 0.0 && (0.0..=f64::from(u32::MAX)).contains(f))
.map(|f| f as u32)
.ok_or_else(|| {
js_error(
"decode_error",
format!("{field} must be an integer in 0..=4294967295"),
)
})
}
fn parse_sender_kind(kind: u32) -> Result<SenderKind, JsValue> {
match kind {
0 => Ok(SenderKind::Owner),
1 => Ok(SenderKind::Helper),
3 => Ok(SenderKind::ReplicaSource),
4 => Ok(SenderKind::ReplicaDestination),
_ => Err(js_error(
"invalid_sender_kind",
format!(
"invalid sender kind: {kind}, valid values are 0 (Owner), 1 (Helper), 3 (ReplicaSource), 4 (ReplicaDestination)"
),
)),
}
}
fn parse_target(val: JsValue) -> Result<Target, JsValue> {
if val.is_null() || val.is_undefined() {
return Ok(Target::All);
}
if val.is_bigint() || val.as_f64().is_some() {
let id = js_value_to_u64(val)?;
return Ok(Target::Single(ChannelId(id)));
}
if Array::is_array(&val) {
let arr = Array::from(&val);
let mut ids = Vec::with_capacity(arr.length() as usize);
for i in 0..arr.length() {
ids.push(ChannelId(js_value_to_u64(arr.get(i))?));
}
return Ok(Target::Many(ids));
}
Err(js_error(
"invalid_discovery_target",
"target must be null (all), a BigInt (single), or an array of BigInts (many)",
))
}
fn parse_weights(val: JsValue) -> Result<HashMap<ChannelId, u32>, JsValue> {
if val.is_null() || val.is_undefined() {
return Ok(HashMap::new());
}
if !val.is_instance_of::<js_sys::Map>() {
return Err(js_error(
"decode_error",
"weights must be a Map of channel ID to weight",
));
}
let map = js_sys::Map::from(val);
let mut weights = HashMap::with_capacity(map.size() as usize);
for entry in map.entries() {
let entry = Array::from(&entry.map_err(|e| js_error("decode_error", format!("{e:?}")))?);
let channel_id = ChannelId(js_value_to_u64(entry.get(0))?);
let weight = js_number_to_u32(&entry.get(1), "weight")?;
weights.insert(channel_id, weight);
}
Ok(weights)
}
pub(crate) fn parse_weighted_channels(val: JsValue) -> Result<Vec<WeightedChannel>, JsValue> {
if !Array::is_array(&val) {
return Err(js_error(
"decode_error",
"channels must be an array of [channelId, weight] tuples",
));
}
let arr = Array::from(&val);
let mut channels = Vec::with_capacity(arr.length() as usize);
for i in 0..arr.length() {
let entry = arr.get(i);
if !Array::is_array(&entry) || Array::from(&entry).length() != 2 {
return Err(js_error(
"decode_error",
format!("channels[{i}] must be a [channelId, weight] tuple"),
));
}
let entry = Array::from(&entry);
let channel_id = ChannelId(js_value_to_u64(entry.get(0))?);
let weight = js_number_to_u32(&entry.get(1), "weight")?;
channels.push((channel_id, weight));
}
Ok(channels)
}
fn parse_user_secrets(val: JsValue) -> Result<Vec<UserSecret>, JsValue> {
#[derive(serde::Deserialize)]
struct UserSecretShape {
#[serde(with = "serde_bytes")]
id: Vec<u8>,
name: String,
#[serde(with = "serde_bytes")]
data: Vec<u8>,
}
if !Array::is_array(&val) {
return Err(js_error("decode_error", "secrets must be an array"));
}
let parsed: Vec<UserSecretShape> = serde_wasm_bindgen::from_value(val)
.map_err(|e| js_error("decode_error", format!("invalid secrets: {e}")))?;
Ok(parsed
.into_iter()
.map(|s| UserSecret {
id: s.id,
name: s.name,
data: s.data,
})
.collect())
}
fn optional_string(params: &JsValue, key: &str) -> Result<Option<String>, JsValue> {
let value = js_sys::Reflect::get(params, &JsValue::from_str(key)).unwrap_or(JsValue::UNDEFINED);
if value.is_undefined() || value.is_null() {
return Ok(None);
}
value
.as_string()
.map(Some)
.ok_or_else(|| js_error("decode_error", format!("{key} must be a string")))
}
fn parse_flow(flow_kind: u32, params: JsValue) -> Result<DeRecFlow, JsValue> {
match flow_kind {
0 => {
let kind_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("kind"))
.map_err(|e| js_error("decode_error", format!("missing kind: {e:?}")))?;
let kind = js_number_to_u32(&kind_val, "kind")?;
let sender_kind = parse_sender_kind(kind)?;
let contact_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("contact"))
.map_err(|e| js_error("decode_error", format!("missing contact: {e:?}")))?;
let contact: PairingContactMessage = serde_wasm_bindgen::from_value(contact_val)
.map_err(|e| js_error("decode_error", e.to_string()))?;
let contact: derec_proto::ContactMessage = contact.into();
let raw = js_sys::Reflect::get(¶ms, &JsValue::from_str("peerCommunicationInfo"))
.unwrap_or(JsValue::UNDEFINED);
let peer_communication_info: HashMap<String, String> =
if raw.is_null() || raw.is_undefined() {
HashMap::new()
} else {
serde_wasm_bindgen::from_value(raw)
.map_err(|e| js_error("invalid_peer_communication_info", e.to_string()))?
};
Ok(DeRecFlow::Pairing {
kind: sender_kind,
contact,
peer_communication_info,
})
}
1 => {
let target_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("target"))
.unwrap_or(JsValue::UNDEFINED);
let target = parse_target(target_val)?;
Ok(DeRecFlow::Discovery { target })
}
2 => {
let secrets_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("secrets"))
.map_err(|e| js_error("decode_error", format!("missing secrets: {e:?}")))?;
let secrets = parse_user_secrets(secrets_val)?;
let description = optional_string(¶ms, "description")?;
let weights_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("weights"))
.unwrap_or(JsValue::UNDEFINED);
let weights = parse_weights(weights_val)?;
let threshold_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("threshold"))
.unwrap_or(JsValue::UNDEFINED);
let threshold = if threshold_val.is_undefined() || threshold_val.is_null() {
None
} else {
Some(js_number_to_u32(&threshold_val, "threshold")?)
};
Ok(DeRecFlow::ProtectSecret {
secrets,
description,
weights,
threshold,
})
}
3 => {
let secret_id_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("secretId"))
.map_err(|e| js_error("decode_error", format!("missing secretId: {e:?}")))?;
let secret_id = js_value_to_u64(secret_id_val)?;
let version_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("version"))
.map_err(|e| js_error("decode_error", format!("missing version: {e:?}")))?;
let version = js_number_to_u32(&version_val, "version")?;
let target_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("target"))
.unwrap_or(JsValue::UNDEFINED);
let target = parse_target(target_val)?;
Ok(DeRecFlow::VerifyShares {
secret_id,
version,
target,
})
}
4 => {
let secret_id_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("secretId"))
.map_err(|e| js_error("decode_error", format!("missing secretId: {e:?}")))?;
let secret_id = js_value_to_u64(secret_id_val)?;
let version_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("version"))
.map_err(|e| js_error("decode_error", format!("missing version: {e:?}")))?;
let version = js_number_to_u32(&version_val, "version")?;
Ok(DeRecFlow::RecoverSecret { secret_id, version })
}
5 => {
let channel_id_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("channel_id"))
.map_err(|e| js_error("decode_error", format!("missing channel_id: {e:?}")))?;
let channel_id = ChannelId(js_value_to_u64(channel_id_val)?);
let memo = optional_string(¶ms, "memo")?;
Ok(DeRecFlow::Unpair { channel_id, memo })
}
6 => {
let target_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("target"))
.unwrap_or(JsValue::UNDEFINED);
let target = parse_target(target_val)?;
let communication_info_val =
js_sys::Reflect::get(¶ms, &JsValue::from_str("communication_info"))
.unwrap_or(JsValue::UNDEFINED);
let communication_info: Option<HashMap<String, String>> =
if communication_info_val.is_null() || communication_info_val.is_undefined() {
None
} else {
Some(
serde_wasm_bindgen::from_value(communication_info_val)
.map_err(|e| js_error("invalid_communication_info", e.to_string()))?,
)
};
#[derive(serde::Deserialize)]
struct TransportShape {
uri: String,
#[serde(deserialize_with = "crate::interop::protocol_names::protocol_from_name")]
protocol: i32,
}
let read_one = |v: JsValue| -> Result<TransportProtocol, JsValue> {
let parsed: TransportShape = serde_wasm_bindgen::from_value(v)
.map_err(|e| js_error("invalid_transport_protocol", e.to_string()))?;
Ok(TransportProtocol {
uri: parsed.uri,
protocol: parsed.protocol,
})
};
let own_transports_val =
js_sys::Reflect::get(¶ms, &JsValue::from_str("own_transports"))
.unwrap_or(JsValue::UNDEFINED);
let own_transports =
if own_transports_val.is_null() || own_transports_val.is_undefined() {
Vec::new()
} else {
let array = js_sys::Array::from(&own_transports_val);
let mut out = Vec::with_capacity(array.length() as usize);
for entry in array.iter() {
out.push(read_one(entry)?);
}
out
};
Ok(DeRecFlow::UpdateChannelInfo {
target,
communication_info,
own_transports,
})
}
8 => {
let replica_id_val = js_sys::Reflect::get(¶ms, &JsValue::from_str("replica_id"))
.unwrap_or(JsValue::UNDEFINED);
let replica_id: u64 = replica_id_val
.as_string()
.ok_or_else(|| {
js_error(
"invalid_flow_params",
"replica_id must be a decimal string".to_owned(),
)
})?
.parse::<u64>()
.map_err(|e| {
js_error(
"invalid_flow_params",
format!("replica_id must be a decimal u64: {e}"),
)
})?;
let memo = optional_string(¶ms, "memo")?;
Ok(DeRecFlow::UnpairReplica { replica_id, memo })
}
7 => {
Ok(DeRecFlow::ReplicaDiscovery)
}
_ => Err(js_error(
"invalid_flow_kind",
format!("invalid flow kind: {flow_kind}, must be 0..8"),
)),
}
}