use std::{error, fmt};
use derec_proto::{ContactMessage, TransportProtocol};
use js_sys::{Array, Function, Object, Promise, Reflect, Uint8Array};
use prost::Message as _;
use serde::de::DeserializeOwned;
use wasm_bindgen::JsValue;
use wasm_bindgen_futures::JsFuture;
use crate::{
Error,
interop::secret_batch,
protocol::{
error::{ChannelStoreError, Refusal, SecretStoreError, ShareStoreError, StateStoreError},
traits::{
ChannelStoreFuture, DeRecChannelStore, DeRecSecretStore, DeRecShareStore,
DeRecStateStore, DeRecTransport, DeRecUserSecretStore, SecretStoreFuture,
ShareStoreFuture, StateStoreFuture, TransportFuture,
},
types::{
ChannelQuery, ChannelRecord, ChannelStatus, HelperChannel, HelperFilter, MissingPolicy,
PairingKeyMaterial, ReplicaFilter, ReplicaMember, SecretKind, SecretValue, Share,
StateItem, StateKey, StateKind, UserSecret, UserSecrets,
},
},
types::ChannelId,
};
#[derive(Debug)]
struct JsCallError(String);
impl fmt::Display for JsCallError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl error::Error for JsCallError {}
fn box_err(msg: String) -> Box<dyn error::Error + Send + Sync + 'static> {
Box::new(JsCallError(msg))
}
fn call_method(obj: &JsValue, method: &str, args: &Array) -> Result<JsValue, String> {
let func_val = Reflect::get(obj, &JsValue::from_str(method))
.map_err(|e| format!("failed to get method '{method}': {e:?}"))?;
let func = Function::from(func_val);
func.apply(obj, args)
.map_err(|e| format!("failed to call method '{method}': {e:?}"))
}
async fn resolve_promise(val: JsValue) -> Result<JsValue, String> {
JsFuture::from(Promise::from(val))
.await
.map_err(|e| format!("promise rejected: {e:?}"))
}
fn call_method_value(obj: &JsValue, method: &str, args: &Array) -> Result<JsValue, JsValue> {
let func_val = Reflect::get(obj, &JsValue::from_str(method))?;
Function::from(func_val).apply(obj, args)
}
async fn resolve_promise_value(val: JsValue) -> Result<JsValue, JsValue> {
JsFuture::from(Promise::from(val)).await
}
fn refusal_from_js(value: &JsValue) -> Option<Refusal> {
Reflect::get(value, &JsValue::from_str("refusal"))
.ok()
.and_then(|v| v.as_string())
.and_then(|reason| refusal_from_reason(&reason))
}
fn refusal_from_reason(reason: &str) -> Option<Refusal> {
match reason {
"too_frequent" => Some(Refusal::TooFrequent),
"size_limit_exceeded" => Some(Refusal::SizeLimitExceeded),
"rejected" => Some(Refusal::Rejected),
_ => None,
}
}
fn share_store_call_error(method: &str, value: &JsValue) -> ShareStoreError {
match refusal_from_js(value) {
Some(refusal) => ShareStoreError::Refused(refusal),
None => {
ShareStoreError::Backend(box_err(format!("share store {method} failed: {value:?}")))
}
}
}
fn decode_secret_value(kind: SecretKind, bytes: &[u8]) -> Result<SecretValue, SecretStoreError> {
match kind {
SecretKind::SharedKey => {
if bytes.len() != 32 {
return Err(SecretStoreError::Backend(box_err(format!(
"shared key must be 32 bytes, got {}",
bytes.len()
))));
}
let mut key = [0u8; 32];
key.copy_from_slice(bytes);
Ok(SecretValue::SharedKey(key))
}
SecretKind::PairingSecret => Ok(SecretValue::PairingSecret(
PairingKeyMaterial::from_bytes(bytes.to_vec()),
)),
SecretKind::PairingContact => {
let contact = ContactMessage::decode(bytes)
.map_err(|e| SecretStoreError::Backend(box_err(e.to_string())))?;
Ok(SecretValue::PairingContact(contact))
}
}
}
pub struct JsSecretStore(pub JsValue);
impl DeRecSecretStore for JsSecretStore {
fn load(
&self,
secret_id: u64,
channel_id: ChannelId,
kind: SecretKind,
) -> SecretStoreFuture<'_, Option<SecretValue>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let channel_str = channel_id.0.to_string();
let kind_num = kind as u32;
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
args.push(&JsValue::from_f64(kind_num as f64));
let promise_val = call_method(&obj, "load", &args)
.map_err(|e| SecretStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| SecretStoreError::Backend(box_err(e)))?;
if value.is_null() || value.is_undefined() {
return Ok(None);
}
let bytes = Uint8Array::new(&value).to_vec();
Ok(Some(decode_secret_value(kind, &bytes)?))
})
}
fn load_many(
&self,
secret_id: u64,
channel_ids: &[ChannelId],
kind: SecretKind,
missing_policy: MissingPolicy,
) -> SecretStoreFuture<'_, Vec<(ChannelId, SecretValue)>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let ids_vec: Vec<String> = channel_ids.iter().map(|c| c.0.to_string()).collect();
let requested = channel_ids.to_vec();
let kind_num = kind as u32;
Box::pin(async move {
let js_ids = Array::new();
for id in &ids_vec {
js_ids.push(&JsValue::from_str(id));
}
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&js_ids);
args.push(&JsValue::from_f64(kind_num as f64));
let promise_val = call_method(&obj, "loadMany", &args)
.map_err(|e| SecretStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| SecretStoreError::Backend(box_err(e)))?;
let entries: Vec<Option<Vec<u8>>> = Array::from(&value)
.iter()
.map(|raw| {
(!raw.is_null() && !raw.is_undefined()).then(|| Uint8Array::new(&raw).to_vec())
})
.collect();
secret_batch::collect(&requested, entries, kind, missing_policy, |bytes| {
decode_secret_value(kind, &bytes)
})
})
}
fn save(
&mut self,
secret_id: u64,
channel_id: ChannelId,
value: SecretValue,
) -> SecretStoreFuture<'_, ()> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let channel_str = channel_id.0.to_string();
Box::pin(async move {
let (kind_num, bytes) = match &value {
SecretValue::SharedKey(key) => (0u32, key.to_vec()),
SecretValue::PairingSecret(material) => (1u32, material.as_bytes().to_vec()),
SecretValue::PairingContact(contact) => (2u32, contact.encode_to_vec()),
};
let js_bytes = Uint8Array::from(bytes.as_slice());
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
args.push(&JsValue::from_f64(kind_num as f64));
args.push(&js_bytes);
let promise_val = call_method(&obj, "save", &args)
.map_err(|e| SecretStoreError::Backend(box_err(e)))?;
resolve_promise(promise_val)
.await
.map_err(|e| SecretStoreError::Backend(box_err(e)))?;
Ok(())
})
}
fn remove(
&mut self,
secret_id: u64,
channel_id: ChannelId,
kind: SecretKind,
) -> SecretStoreFuture<'_, ()> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let channel_str = channel_id.0.to_string();
let kind_num = kind as u32;
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
args.push(&JsValue::from_f64(kind_num as f64));
let promise_val = call_method(&obj, "remove", &args)
.map_err(|e| SecretStoreError::Backend(box_err(e)))?;
resolve_promise(promise_val)
.await
.map_err(|e| SecretStoreError::Backend(box_err(e)))?;
Ok(())
})
}
}
pub struct JsChannelStore(pub JsValue);
fn query_key(query: ChannelQuery) -> (String, String) {
match query {
ChannelQuery::Helper { channel_id } => (channel_id.0.to_string(), "0".to_owned()),
ChannelQuery::Replica {
channel_id,
replica_id,
} => (channel_id.0.to_string(), replica_id.0.to_string()),
}
}
fn record_key(record: &ChannelRecord) -> (String, String) {
match record {
ChannelRecord::Helper(h) => (h.channel_id.0.to_string(), "0".to_owned()),
ChannelRecord::Replica(r) => (r.channel_id.0.to_string(), r.replica_id.0.to_string()),
}
}
fn encode_filter<Role: serde::Serialize>(
ids: &[u64],
status: &[ChannelStatus],
role: Option<&Role>,
exclude: &[u64],
) -> Result<JsValue, ChannelStoreError> {
let obj = Object::new();
let set = |key: &str, value: &JsValue| -> Result<(), ChannelStoreError> {
Reflect::set(&obj, &JsValue::from_str(key), value)
.map(|_| ())
.map_err(|e| ChannelStoreError::Backend(box_err(format!("{e:?}"))))
};
let id_array = |values: &[u64]| {
let arr = Array::new();
for v in values {
arr.push(&JsValue::from_str(&v.to_string()));
}
arr
};
set("ids", &id_array(ids))?;
set("exclude", &id_array(exclude))?;
let status_array = Array::new();
for s in status {
let encoded = serde_wasm_bindgen::to_value(s)
.map_err(|e| ChannelStoreError::Backend(box_err(e.to_string())))?;
status_array.push(&encoded);
}
set("status", &status_array)?;
let role = match role {
Some(r) => serde_wasm_bindgen::to_value(r)
.map_err(|e| ChannelStoreError::Backend(box_err(e.to_string())))?,
None => JsValue::NULL,
};
set("role", &role)?;
Ok(obj.into())
}
async fn list_records<T: DeserializeOwned>(
obj: &JsValue,
method: &str,
secret_str: &str,
filter: JsValue,
) -> Result<Vec<T>, ChannelStoreError> {
let args = Array::new();
args.push(&JsValue::from_str(secret_str));
args.push(&filter);
let promise_val =
call_method(obj, method, &args).map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
if value.is_null() || value.is_undefined() {
return Ok(Vec::new());
}
let bytes = Uint8Array::new(&value).to_vec();
if bytes.is_empty() {
return Ok(Vec::new());
}
serde_json::from_slice(&bytes).map_err(|e| ChannelStoreError::Backend(box_err(e.to_string())))
}
impl DeRecChannelStore for JsChannelStore {
fn load(
&self,
secret_id: u64,
query: ChannelQuery,
) -> ChannelStoreFuture<'_, Option<ChannelRecord>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let (channel_str, replica_str) = query_key(query);
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
args.push(&JsValue::from_str(&replica_str));
let promise_val = call_method(&obj, "load", &args)
.map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
if value.is_null() || value.is_undefined() {
return Ok(None);
}
let bytes = Uint8Array::new(&value).to_vec();
if bytes.is_empty() {
return Ok(None);
}
let record: ChannelRecord = serde_json::from_slice(&bytes)
.map_err(|e| ChannelStoreError::Backend(box_err(e.to_string())))?;
Ok(Some(record))
})
}
fn save(&mut self, secret_id: u64, record: ChannelRecord) -> ChannelStoreFuture<'_, ()> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let (channel_str, replica_str) = record_key(&record);
Box::pin(async move {
let bytes = serde_json::to_vec(&record)
.map_err(|e| ChannelStoreError::Backend(box_err(e.to_string())))?;
let js_bytes = Uint8Array::from(bytes.as_slice());
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
args.push(&JsValue::from_str(&replica_str));
args.push(&js_bytes);
let promise_val = call_method(&obj, "save", &args)
.map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
resolve_promise(promise_val)
.await
.map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
Ok(())
})
}
fn remove(&mut self, secret_id: u64, query: ChannelQuery) -> ChannelStoreFuture<'_, bool> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let (channel_str, replica_str) = query_key(query);
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
args.push(&JsValue::from_str(&replica_str));
let promise_val = call_method(&obj, "remove", &args)
.map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
value.as_bool().ok_or_else(|| {
ChannelStoreError::Backend(box_err("remove must return a boolean".to_string()))
})
})
}
fn helpers(
&self,
secret_id: u64,
filter: HelperFilter,
) -> ChannelStoreFuture<'_, Vec<HelperChannel>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
Box::pin(async move {
let ids: Vec<u64> = filter.ids.iter().map(|c| c.0).collect();
let exclude: Vec<u64> = filter.exclude.iter().map(|c| c.0).collect();
let filter = encode_filter(&ids, &filter.status, filter.role.as_ref(), &exclude)?;
list_records(&obj, "listHelpers", &secret_str, filter).await
})
}
fn replicas(
&self,
secret_id: u64,
filter: ReplicaFilter,
) -> ChannelStoreFuture<'_, Vec<ReplicaMember>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
Box::pin(async move {
let ids: Vec<u64> = filter.ids.iter().map(|r| r.0).collect();
let exclude: Vec<u64> = filter.exclude.iter().map(|r| r.0).collect();
let filter = encode_filter(&ids, &filter.status, filter.role.as_ref(), &exclude)?;
list_records(&obj, "listReplicas", &secret_str, filter).await
})
}
fn link_channel(
&mut self,
secret_id: u64,
a: ChannelId,
b: ChannelId,
) -> ChannelStoreFuture<'_, ()> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let a_str = a.0.to_string();
let b_str = b.0.to_string();
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&a_str));
args.push(&JsValue::from_str(&b_str));
let promise_val = call_method(&obj, "linkChannel", &args)
.map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
resolve_promise(promise_val)
.await
.map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
Ok(())
})
}
fn linked_channels(
&self,
secret_id: u64,
channel_id: ChannelId,
) -> ChannelStoreFuture<'_, Vec<ChannelId>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let channel_str = channel_id.0.to_string();
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
let promise_val = call_method(&obj, "linkedChannels", &args)
.map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| ChannelStoreError::Backend(box_err(e)))?;
let arr = Array::from(&value);
let mut result = Vec::with_capacity(arr.length() as usize);
for i in 0..arr.length() {
let s = arr.get(i).as_string().ok_or_else(|| {
ChannelStoreError::Backend(box_err(
"linkedChannels must return an array of channel-id strings".to_string(),
))
})?;
let id = s
.parse::<u64>()
.map_err(|e| ChannelStoreError::Backend(box_err(e.to_string())))?;
result.push(ChannelId(id));
}
Ok(result)
})
}
}
pub struct JsShareStore(pub JsValue);
fn share_to_js(share: &Share) -> JsValue {
let obj = Object::new();
Reflect::set(
&obj,
&"secretId".into(),
&JsValue::from_str(&share.secret_id.to_string()),
)
.unwrap_or_default();
Reflect::set(
&obj,
&"version".into(),
&JsValue::from_f64(share.version as f64),
)
.unwrap_or_default();
let js_bytes = Uint8Array::from(share.bytes.as_slice());
Reflect::set(&obj, &"bytes".into(), &js_bytes).unwrap_or_default();
for (key, value) in [
("subshares", share.subshares),
("threshold", share.threshold),
] {
if let Some(value) = value {
Reflect::set(&obj, &key.into(), &JsValue::from_f64(f64::from(value)))
.unwrap_or_default();
}
}
obj.into()
}
fn u32_from_js(value: &JsValue) -> Option<u32> {
value
.as_f64()
.filter(|n| n.fract() == 0.0 && *n >= 0.0 && *n <= f64::from(u32::MAX))
.map(|n| n as u32)
}
fn optional_string_from_js(
item: &JsValue,
what: &str,
key: &str,
) -> Result<Option<String>, ShareStoreError> {
let value = Reflect::get(item, &key.into()).unwrap_or(JsValue::UNDEFINED);
if value.is_undefined() || value.is_null() {
return Ok(None);
}
value.as_string().map(Some).ok_or_else(|| {
ShareStoreError::Backend(box_err(format!(
"{what}.{key} must be a string, null or undefined"
)))
})
}
fn optional_u32_from_js(
item: &JsValue,
what: &str,
key: &str,
) -> Result<Option<u32>, ShareStoreError> {
let value = Reflect::get(item, &key.into()).unwrap_or(JsValue::UNDEFINED);
if value.is_undefined() || value.is_null() {
return Ok(None);
}
u32_from_js(&value).map(Some).ok_or_else(|| {
ShareStoreError::Backend(box_err(format!(
"{what}.{key} must be a u32, null or undefined"
)))
})
}
fn share_from_js(item: &JsValue) -> Result<Share, ShareStoreError> {
let secret_id_str = Reflect::get(item, &"secretId".into())
.ok()
.and_then(|v| v.as_string())
.unwrap_or_default();
let secret_id = secret_id_str.parse::<u64>().map_err(|e| {
ShareStoreError::Backend(box_err(format!(
"share.secretId must be a numeric string: {e}"
)))
})?;
let version = Reflect::get(item, &"version".into())
.ok()
.and_then(|v| u32_from_js(&v))
.ok_or_else(|| {
ShareStoreError::Backend(box_err("share.version must be a u32".to_string()))
})?;
let bytes_val = Reflect::get(item, &"bytes".into()).unwrap_or(JsValue::null());
let bytes = Uint8Array::new(&bytes_val).to_vec();
Ok(Share {
secret_id,
version,
bytes,
subshares: optional_u32_from_js(item, "share", "subshares")?,
threshold: optional_u32_from_js(item, "share", "threshold")?,
})
}
impl DeRecShareStore for JsShareStore {
fn load(
&self,
secret_id: u64,
channel_id: ChannelId,
versions: &[u32],
) -> ShareStoreFuture<'_, Vec<Share>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let channel_str = channel_id.0.to_string();
let versions_vec: Vec<u32> = versions.to_vec();
Box::pin(async move {
let js_versions = Array::new();
for v in &versions_vec {
js_versions.push(&JsValue::from_f64(*v as f64));
}
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
args.push(&js_versions);
let promise_val = call_method(&obj, "load", &args)
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
let arr = Array::from(&value);
let mut result = Vec::with_capacity(arr.length() as usize);
for i in 0..arr.length() {
result.push(share_from_js(&arr.get(i))?);
}
Ok(result)
})
}
fn latest_version(&self, secret_id: u64) -> ShareStoreFuture<'_, Option<u32>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
let promise_val = call_method(&obj, "latestVersion", &args)
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
if value.is_null() || value.is_undefined() {
Ok(None)
} else {
let v = u32_from_js(&value).ok_or_else(|| {
ShareStoreError::Backend(box_err(
"latestVersion must return a u32 or null".to_string(),
))
})?;
Ok(Some(v))
}
})
}
fn save(
&mut self,
secret_id: u64,
channel_id: ChannelId,
share: Share,
) -> ShareStoreFuture<'_, ()> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let channel_str = channel_id.0.to_string();
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
args.push(&share_to_js(&share));
let promise_val = call_method_value(&obj, "save", &args)
.map_err(|e| share_store_call_error("save", &e))?;
resolve_promise_value(promise_val)
.await
.map_err(|e| share_store_call_error("save", &e))?;
Ok(())
})
}
fn load_many(
&self,
secret_id: u64,
channel_ids: &[ChannelId],
versions: &[u32],
) -> ShareStoreFuture<'_, Vec<Share>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let ids_vec: Vec<String> = channel_ids.iter().map(|c| c.0.to_string()).collect();
let versions_vec: Vec<u32> = versions.to_vec();
Box::pin(async move {
let js_ids = Array::new();
for id in &ids_vec {
js_ids.push(&JsValue::from_str(id));
}
let js_versions = Array::new();
for v in &versions_vec {
js_versions.push(&JsValue::from_f64(*v as f64));
}
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&js_ids);
args.push(&js_versions);
let promise_val = call_method(&obj, "loadMany", &args)
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
let arr = Array::from(&value);
let mut result = Vec::with_capacity(arr.length() as usize);
for i in 0..arr.length() {
result.push(share_from_js(&arr.get(i))?);
}
Ok(result)
})
}
fn load_all(
&self,
secret_id: u64,
channel_ids: &[ChannelId],
) -> ShareStoreFuture<'_, Vec<Share>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let ids_vec: Vec<String> = channel_ids.iter().map(|c| c.0.to_string()).collect();
Box::pin(async move {
let js_ids = Array::new();
for id in &ids_vec {
js_ids.push(&JsValue::from_str(id));
}
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&js_ids);
let promise_val = call_method(&obj, "loadAll", &args)
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
let arr = Array::from(&value);
let mut result = Vec::with_capacity(arr.length() as usize);
for i in 0..arr.length() {
result.push(share_from_js(&arr.get(i))?);
}
Ok(result)
})
}
fn remove_channel(
&mut self,
secret_id: u64,
channel_id: ChannelId,
) -> ShareStoreFuture<'_, ()> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let channel_str = channel_id.0.to_string();
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
let promise_val = call_method(&obj, "removeChannel", &args)
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
resolve_promise(promise_val)
.await
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
Ok(())
})
}
fn remove_versions(
&mut self,
secret_id: u64,
channel_id: ChannelId,
versions: &[u32],
) -> ShareStoreFuture<'_, ()> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let channel_str = channel_id.0.to_string();
let versions_vec: Vec<u32> = versions.to_vec();
Box::pin(async move {
let js_versions = Array::new();
for v in &versions_vec {
js_versions.push(&JsValue::from_f64(*v as f64));
}
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
args.push(&js_versions);
let promise_val = call_method(&obj, "removeVersions", &args)
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
resolve_promise(promise_val)
.await
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
Ok(())
})
}
fn keep_version(&self, secret_id: u64, version: u32) -> ShareStoreFuture<'_, u32> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_f64(f64::from(version)));
let promise_val = call_method(&obj, "keepVersion", &args)
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
value
.as_f64()
.filter(|f| f.fract() == 0.0 && (0.0..=f64::from(u32::MAX)).contains(f))
.map(|f| f as u32)
.ok_or_else(|| {
ShareStoreError::Backend(box_err(
"keepVersion must return an integer in 0..=4294967295".to_string(),
))
})
})
}
fn record_verification(
&mut self,
secret_id: u64,
channel_id: ChannelId,
version: u32,
) -> ShareStoreFuture<'_, ()> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let channel_str = channel_id.0.to_string();
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_str(&channel_str));
args.push(&JsValue::from_f64(f64::from(version)));
let promise_val = call_method_value(&obj, "recordVerification", &args)
.map_err(|e| share_store_call_error("recordVerification", &e))?;
resolve_promise_value(promise_val)
.await
.map_err(|e| share_store_call_error("recordVerification", &e))?;
Ok(())
})
}
}
pub struct JsUserSecretStore(pub JsValue);
fn user_secrets_to_js(value: &UserSecrets) -> JsValue {
let obj = Object::new();
Reflect::set(
&obj,
&"version".into(),
&JsValue::from_f64(f64::from(value.version)),
)
.unwrap_or_default();
let entries = Array::new();
for s in &value.secrets {
let entry = Object::new();
let id = Uint8Array::from(s.id.as_slice());
let data = Uint8Array::from(s.data.as_slice());
Reflect::set(&entry, &"id".into(), &id).unwrap_or_default();
Reflect::set(&entry, &"name".into(), &JsValue::from_str(&s.name)).unwrap_or_default();
Reflect::set(&entry, &"data".into(), &data).unwrap_or_default();
entries.push(&entry);
}
Reflect::set(&obj, &"secrets".into(), &entries).unwrap_or_default();
if let Some(d) = value.description.as_deref() {
Reflect::set(&obj, &"description".into(), &JsValue::from_str(d)).unwrap_or_default();
}
if let Some(author) = value.author_replica_id {
Reflect::set(
&obj,
&"author_replica_id".into(),
&JsValue::from_str(&author.to_string()),
)
.unwrap_or_default();
}
if let Some(threshold) = value.threshold {
Reflect::set(
&obj,
&"threshold".into(),
&JsValue::from_f64(f64::from(threshold)),
)
.unwrap_or_default();
}
obj.into()
}
fn user_secrets_from_js(value: &JsValue) -> Result<UserSecrets, ShareStoreError> {
let version = Reflect::get(value, &"version".into())
.ok()
.and_then(|v| u32_from_js(&v))
.ok_or_else(|| {
ShareStoreError::Backend(box_err("userSecrets.version must be a u32".to_string()))
})?;
#[derive(serde::Deserialize)]
struct UserSecretShape {
#[serde(with = "serde_bytes")]
id: Vec<u8>,
name: String,
#[serde(with = "serde_bytes")]
data: Vec<u8>,
}
let entries_val = Reflect::get(value, &"secrets".into()).unwrap_or(JsValue::UNDEFINED);
if !Array::is_array(&entries_val) {
return Err(ShareStoreError::Backend(box_err(
"userSecrets.secrets must be an array".to_string(),
)));
}
let secrets = serde_wasm_bindgen::from_value::<Vec<UserSecretShape>>(entries_val)
.map_err(|e| {
ShareStoreError::Backend(box_err(format!("invalid userSecrets.secrets: {e}")))
})?
.into_iter()
.map(|s| UserSecret {
id: s.id,
name: s.name,
data: s.data,
})
.collect();
let description = optional_string_from_js(value, "userSecrets", "description")?;
let author_replica_id = optional_string_from_js(value, "userSecrets", "author_replica_id")?
.map(|id| {
id.parse::<u64>().map_err(|_| {
ShareStoreError::Backend(box_err(format!(
"userSecrets.author_replica_id is not a decimal u64: {id}"
)))
})
})
.transpose()?;
Ok(UserSecrets {
version,
secrets,
description,
author_replica_id,
threshold: optional_u32_from_js(value, "userSecrets", "threshold")?,
})
}
impl DeRecUserSecretStore for JsUserSecretStore {
fn load_latest(&self, secret_id: u64) -> ShareStoreFuture<'_, Option<UserSecrets>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
let promise_val = call_method(&obj, "loadLatest", &args)
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
if value.is_null() || value.is_undefined() {
Ok(None)
} else {
Ok(Some(user_secrets_from_js(&value)?))
}
})
}
fn save_latest(&mut self, secret_id: u64, value: UserSecrets) -> ShareStoreFuture<'_, ()> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let js_value = user_secrets_to_js(&value);
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&js_value);
let promise_val = call_method(&obj, "saveLatest", &args)
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
resolve_promise(promise_val)
.await
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
Ok(())
})
}
fn remove(&mut self, secret_id: u64) -> ShareStoreFuture<'_, ()> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
let promise_val = call_method(&obj, "remove", &args)
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
resolve_promise(promise_val)
.await
.map_err(|e| ShareStoreError::Backend(box_err(e)))?;
Ok(())
})
}
}
pub struct JsTransport(pub JsValue);
#[derive(serde::Serialize)]
struct EndpointJs {
protocol: String,
uri: String,
}
impl DeRecTransport for JsTransport {
fn send(&self, endpoints: &[TransportProtocol], message: Vec<u8>) -> TransportFuture<'_> {
let mut js_endpoints = Vec::with_capacity(endpoints.len());
for endpoint in endpoints {
let Some(protocol) = super::protocol_discriminant_to_name(endpoint.protocol) else {
return Box::pin(async move {
Err(Error::InvalidInput(
"unknown transport protocol discriminant",
))
});
};
js_endpoints.push(EndpointJs {
protocol: protocol.to_owned(),
uri: endpoint.uri.to_owned(),
});
}
let obj = self.0.clone();
Box::pin(async move {
let endpoints_js = serde_wasm_bindgen::to_value(&js_endpoints)
.map_err(|_| Error::InvalidInput("failed to serialize endpoints"))?;
let js_message = Uint8Array::from(message.as_slice());
let args = Array::new();
args.push(&endpoints_js);
args.push(&js_message);
let promise_val = call_method(&obj, "send", &args)
.map_err(|_| Error::InvalidInput("transport.send call failed"))?;
resolve_promise(promise_val)
.await
.map_err(|_| Error::TransportSendFailed)?;
Ok(())
})
}
}
use crate::protocol::types::state_record::{StateItemRecord, StateKeyRecord};
fn state_kind_to_u32(kind: StateKind) -> u32 {
match kind {
StateKind::PendingVerification => 0,
StateKind::PendingRecovery => 1,
StateKind::PendingUnpair => 2,
StateKind::SharingRound => 3,
StateKind::PendingReplicaDiscovery => 4,
}
}
pub struct JsStateStore(pub JsValue);
impl DeRecStateStore for JsStateStore {
fn save(&mut self, secret_id: u64, item: StateItem) -> StateStoreFuture<'_, ()> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
Box::pin(async move {
let record = StateItemRecord::from(&item);
let bytes = serde_json::to_vec(&record)
.map_err(|e| StateStoreError::Backend(box_err(e.to_string())))?;
let js_bytes = Uint8Array::from(bytes.as_slice());
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&js_bytes);
let promise_val = call_method(&obj, "save", &args)
.map_err(|e| StateStoreError::Backend(box_err(e)))?;
resolve_promise(promise_val)
.await
.map_err(|e| StateStoreError::Backend(box_err(e)))?;
Ok(())
})
}
fn load(&self, secret_id: u64, key: StateKey) -> StateStoreFuture<'_, Option<StateItem>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
Box::pin(async move {
let key_record = StateKeyRecord::from(&key);
let key_bytes = serde_json::to_vec(&key_record)
.map_err(|e| StateStoreError::Backend(box_err(e.to_string())))?;
let js_key = Uint8Array::from(key_bytes.as_slice());
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&js_key);
let promise_val = call_method(&obj, "load", &args)
.map_err(|e| StateStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| StateStoreError::Backend(box_err(e)))?;
if value.is_null() || value.is_undefined() {
return Ok(None);
}
let bytes = Uint8Array::new(&value).to_vec();
let record: StateItemRecord = serde_json::from_slice(&bytes)
.map_err(|e| StateStoreError::Backend(box_err(e.to_string())))?;
let item = record
.into_item()
.map_err(|e| StateStoreError::Backend(box_err(e)))?;
Ok(Some(item))
})
}
fn remove(&mut self, secret_id: u64, key: StateKey) -> StateStoreFuture<'_, bool> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
Box::pin(async move {
let key_record = StateKeyRecord::from(&key);
let key_bytes = serde_json::to_vec(&key_record)
.map_err(|e| StateStoreError::Backend(box_err(e.to_string())))?;
let js_key = Uint8Array::from(key_bytes.as_slice());
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&js_key);
let promise_val = call_method(&obj, "remove", &args)
.map_err(|e| StateStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| StateStoreError::Backend(box_err(e)))?;
value.as_bool().ok_or_else(|| {
StateStoreError::Backend(box_err("remove must return a boolean".to_string()))
})
})
}
fn load_all(&self, secret_id: u64, kind: StateKind) -> StateStoreFuture<'_, Vec<StateItem>> {
let obj = self.0.clone();
let secret_str = secret_id.to_string();
let kind_num = state_kind_to_u32(kind);
Box::pin(async move {
let args = Array::new();
args.push(&JsValue::from_str(&secret_str));
args.push(&JsValue::from_f64(kind_num as f64));
let promise_val = call_method(&obj, "loadAll", &args)
.map_err(|e| StateStoreError::Backend(box_err(e)))?;
let value = resolve_promise(promise_val)
.await
.map_err(|e| StateStoreError::Backend(box_err(e)))?;
let arr = Array::from(&value);
let mut out = Vec::with_capacity(arr.length() as usize);
for i in 0..arr.length() {
let entry = arr.get(i);
let bytes = Uint8Array::new(&entry).to_vec();
let record: StateItemRecord = serde_json::from_slice(&bytes)
.map_err(|e| StateStoreError::Backend(box_err(e.to_string())))?;
out.push(
record
.into_item()
.map_err(|e| StateStoreError::Backend(box_err(e)))?,
);
}
Ok(out)
})
}
}