Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Move contacts out of core WASM

Manav Rathia0938c29f6cc
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 23d0ed8dce..4d8effbb44 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2496,17 +2496,12 @@ name = "ente-core-wasm"
version = "0.0.0"
dependencies = [
"ente-accounts",
- "ente-contacts",
"ente-core",
- "ente-legacy",
"ente-wasm-log",
"js-sys",
"md-5 0.11.0",
- "serde",
- "serde-wasm-bindgen",
"thiserror 2.0.18",
"wasm-bindgen",
- "wasm-bindgen-futures",
]
[[package]]
@@ -2611,6 +2606,7 @@ dependencies = [
name = "ente-legacy-wasm"
version = "0.0.0"
dependencies = [
+ "ente-accounts",
"ente-core",
"ente-legacy",
"ente-wasm-log",
@@ -2636,6 +2632,21 @@ dependencies = [
"flutter_rust_bridge",
]
+[[package]]
+name = "ente-locker-wasm"
+version = "0.0.0"
+dependencies = [
+ "ente-contacts",
+ "ente-core",
+ "ente-wasm-log",
+ "js-sys",
+ "serde",
+ "serde-wasm-bindgen",
+ "thiserror 2.0.18",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+]
+
[[package]]
name = "ente-ml"
version = "0.0.0"
@@ -2728,6 +2739,21 @@ dependencies = [
"ort",
]
+[[package]]
+name = "ente-photos-wasm"
+version = "0.0.0"
+dependencies = [
+ "ente-contacts",
+ "ente-core",
+ "ente-wasm-log",
+ "js-sys",
+ "serde",
+ "serde-wasm-bindgen",
+ "thiserror 2.0.18",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+]
+
[[package]]
name = "ente-rs"
version = "0.0.1"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index ef399090ec..ccdf8b886f 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -16,7 +16,9 @@ members = [
"bindings/wasm/ensu",
"bindings/wasm/legacy",
"bindings/wasm/log",
+ "bindings/wasm/locker",
"bindings/wasm/paste",
+ "bindings/wasm/photos",
"bindings/wasm/space",
"crates/accounts",
"crates/assets",
diff --git a/rust/bindings/wasm/core/Cargo.toml b/rust/bindings/wasm/core/Cargo.toml
index 5914076292..52937ebe97 100644
--- a/rust/bindings/wasm/core/Cargo.toml
+++ b/rust/bindings/wasm/core/Cargo.toml
@@ -7,14 +7,9 @@ crate-type = ["cdylib"]
[dependencies]
ente-accounts.workspace = true
-ente-contacts.workspace = true
ente-core.workspace = true
-ente-legacy.workspace = true
ente-wasm-log.workspace = true
js-sys.workspace = true
md-5.workspace = true
-serde.workspace = true
-serde-wasm-bindgen.workspace = true
thiserror.workspace = true
wasm-bindgen.workspace = true
-wasm-bindgen-futures.workspace = true
diff --git a/rust/bindings/wasm/core/src/contacts.rs b/rust/bindings/wasm/core/src/contacts.rs
deleted file mode 100644
index 03eeadbaf9..0000000000
--- a/rust/bindings/wasm/core/src/contacts.rs
+++ /dev/null
@@ -1,322 +0,0 @@
-use std::sync::Arc;
-
-use ente_accounts::auth::KeyAttributes;
-use ente_contacts::{ContactsClient, OpenContactsInput, RootKeySource, WrappedRootContactKey};
-use ente_core::{
- b64,
- crypto::SecretVec,
- http::{Api, ApiConfig, Auth, Http},
-};
-use ente_legacy::{LegacyClient, LegacyContactState};
-use js_sys::{Object, Reflect};
-use serde::{Deserialize, Serialize};
-use serde_wasm_bindgen as swb;
-use wasm_bindgen::prelude::*;
-
-#[derive(Debug, thiserror::Error)]
-pub enum Error {
- #[error(transparent)]
- Contacts(#[from] ente_contacts::Error),
- #[error(transparent)]
- Legacy(#[from] ente_legacy::Error),
- #[error(transparent)]
- Serde(#[from] swb::Error),
- #[error(transparent)]
- Decode(#[from] b64::DecodeError),
-}
-
-impl Error {
- fn name(&self) -> Option<&'static str> {
- match self {
- Self::Legacy(ente_legacy::Error::ContactNotOnEnte) => Some("contact_not_on_ente"),
- Self::Legacy(ente_legacy::Error::ActiveRecoverySession) => {
- Some("active_recovery_session")
- }
- _ => None,
- }
- }
-
- fn message(&self) -> String {
- ente_core::error::chain(self)
- }
-}
-
-impl From<Error> for JsValue {
- fn from(error: Error) -> Self {
- let js_error = js_sys::Error::new(&error.message());
- if let Some(name) = error.name() {
- js_error.set_name(name);
- }
- js_error.into()
- }
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct OpenContactsCtxJsInput {
- base_url: String,
- auth_token: String,
- user_id: i64,
- master_key_b64: String,
- cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,
- user_agent: Option<String>,
- client_package: Option<String>,
- client_version: Option<String>,
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct ContactRecordJs {
- id: String,
- contact_user_id: i64,
- email: Option<String>,
- name: Option<String>,
- #[serde(rename = "profilePictureAttachmentID")]
- profile_picture_attachment_id: Option<String>,
- is_deleted: bool,
- created_at: i64,
- updated_at: i64,
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct LegacyRecoveryBundleJs {
- recovery_key: String,
- user_key_attributes: KeyAttributes,
-}
-
-impl From<ente_contacts::ContactRecord> for ContactRecordJs {
- fn from(value: ente_contacts::ContactRecord) -> Self {
- Self {
- id: value.id,
- contact_user_id: value.contact_user_id,
- email: value.email,
- name: value.name,
- profile_picture_attachment_id: value.profile_picture_attachment_id,
- is_deleted: value.is_deleted,
- created_at: value.created_at,
- updated_at: value.updated_at,
- }
- }
-}
-
-#[wasm_bindgen]
-pub async fn contacts_open_ctx(input: JsValue) -> Result<JsValue, Error> {
- let input: OpenContactsCtxJsInput = swb::from_value(input)?;
- let master_key = b64::decode(&input.master_key_b64)?;
- let api = Arc::new(Api::new(
- Http::new().map_err(ente_contacts::Error::from)?,
- ApiConfig {
- origin: input.base_url,
- client_package: input.client_package,
- client_version: input.client_version,
- user_agent: input.user_agent,
- auth: Some(Auth::User(input.auth_token)),
- },
- ));
- let master_key = Arc::new(SecretVec::new(master_key));
- let result = ContactsClient::open(
- Arc::clone(&api),
- Arc::clone(&master_key),
- OpenContactsInput {
- user_id: input.user_id,
- cached_wrapped_root_contact_key: input.cached_wrapped_root_contact_key,
- },
- )?;
- let legacy = LegacyClient::new(Arc::clone(&api), master_key);
-
- let output = Object::new();
- Reflect::set(
- &output,
- &JsValue::from_str("ctx"),
- &JsValue::from(ContactsCtxHandle {
- api,
- contacts: result.client,
- legacy,
- }),
- )
- .expect("setting ctx should not fail");
- Reflect::set(
- &output,
- &JsValue::from_str("wrappedRootContactKey"),
- &swb::to_value(&result.wrapped_root_contact_key)?,
- )
- .expect("setting wrappedRootContactKey should not fail");
- Reflect::set(
- &output,
- &JsValue::from_str("rootKeySource"),
- &JsValue::from_str(match result.root_key_source {
- RootKeySource::Cache => "cache",
- RootKeySource::Unresolved => "unresolved",
- }),
- )
- .expect("setting rootKeySource should not fail");
-
- Ok(output.into())
-}
-
-#[wasm_bindgen]
-pub struct ContactsCtxHandle {
- api: Arc<Api>,
- contacts: ContactsClient,
- legacy: LegacyClient,
-}
-
-#[wasm_bindgen]
-impl ContactsCtxHandle {
- pub fn update_auth_token(&self, auth_token: String) {
- self.api.set_auth(Some(Auth::User(auth_token)));
- }
-
- pub fn current_wrapped_root_contact_key(&self) -> Result<JsValue, Error> {
- swb::to_value(&self.contacts.current_wrapped_root_contact_key()).map_err(Into::into)
- }
-
- pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<JsValue, Error> {
- let diff: Vec<ContactRecordJs> = self
- .contacts
- .get_diff(since_time, limit)
- .await?
- .into_iter()
- .map(Into::into)
- .collect();
- swb::to_value(&diff).map_err(Into::into)
- }
-
- pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>, Error> {
- self.contacts
- .get_profile_picture(contact_id)
- .await
- .map_err(Into::into)
- }
-
- pub async fn legacy_get_info(&self) -> Result<JsValue, Error> {
- let info = self.legacy.info().await?;
- swb::to_value(&info).map_err(Into::into)
- }
-
- pub async fn legacy_public_key(&self, email: String) -> Result<JsValue, Error> {
- let public_key = self.legacy.public_key(&email).await?;
- swb::to_value(&public_key).map_err(Into::into)
- }
-
- pub fn legacy_verification_id(&self, public_key_b64: String) -> Result<String, Error> {
- self.legacy
- .verification_id(&public_key_b64)
- .map_err(Into::into)
- }
-
- pub async fn legacy_add_contact(
- &self,
- email: String,
- current_user_key_attrs: JsValue,
- recovery_notice_in_days: Option<i32>,
- ) -> Result<(), Error> {
- let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
- self.legacy
- .add_contact(&email, &current_user_key_attrs, recovery_notice_in_days)
- .await
- .map_err(Into::into)
- }
-
- pub async fn legacy_update_contact(
- &self,
- user_id: i64,
- emergency_contact_id: i64,
- state: JsValue,
- ) -> Result<(), Error> {
- let state: LegacyContactState = swb::from_value(state)?;
- self.legacy
- .update_contact(user_id, emergency_contact_id, state)
- .await
- .map_err(Into::into)
- }
-
- pub async fn legacy_update_recovery_notice(
- &self,
- emergency_contact_id: i64,
- recovery_notice_in_days: i32,
- ) -> Result<(), Error> {
- self.legacy
- .update_recovery_notice(emergency_contact_id, recovery_notice_in_days)
- .await
- .map_err(Into::into)
- }
-
- pub async fn legacy_start_recovery(
- &self,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<(), Error> {
- self.legacy
- .start_recovery(user_id, emergency_contact_id)
- .await
- .map_err(Into::into)
- }
-
- pub async fn legacy_stop_recovery(
- &self,
- recovery_id: String,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<(), Error> {
- self.legacy
- .stop_recovery(&recovery_id, user_id, emergency_contact_id)
- .await
- .map_err(Into::into)
- }
-
- pub async fn legacy_reject_recovery(
- &self,
- recovery_id: String,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<(), Error> {
- self.legacy
- .reject_recovery(&recovery_id, user_id, emergency_contact_id)
- .await
- .map_err(Into::into)
- }
-
- pub async fn legacy_approve_recovery(
- &self,
- recovery_id: String,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<(), Error> {
- self.legacy
- .approve_recovery(&recovery_id, user_id, emergency_contact_id)
- .await
- .map_err(Into::into)
- }
-
- pub async fn legacy_recovery_bundle(
- &self,
- recovery_id: String,
- current_user_key_attrs: JsValue,
- ) -> Result<JsValue, Error> {
- let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
- let bundle = self
- .legacy
- .recovery_bundle(&recovery_id, &current_user_key_attrs)
- .await?;
- swb::to_value(&LegacyRecoveryBundleJs {
- recovery_key: b64::encode(bundle.recovery_key.as_ref()),
- user_key_attributes: bundle.user_key_attributes,
- })
- .map_err(Into::into)
- }
-
- pub async fn legacy_change_password(
- &self,
- recovery_id: String,
- current_user_key_attrs: JsValue,
- new_password: String,
- ) -> Result<(), Error> {
- let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
- self.legacy
- .change_password(&recovery_id, &current_user_key_attrs, &new_password)
- .await
- .map_err(Into::into)
- }
-}
diff --git a/rust/bindings/wasm/core/src/lib.rs b/rust/bindings/wasm/core/src/lib.rs
index a8a0d8c99a..ceb5a7ab4b 100644
--- a/rust/bindings/wasm/core/src/lib.rs
+++ b/rust/bindings/wasm/core/src/lib.rs
@@ -1,5 +1,4 @@
use ente_wasm_log as _;
mod auth;
-mod contacts;
mod crypto;
diff --git a/rust/bindings/wasm/legacy/Cargo.toml b/rust/bindings/wasm/legacy/Cargo.toml
index 18d98b8c7a..3005732638 100644
--- a/rust/bindings/wasm/legacy/Cargo.toml
+++ b/rust/bindings/wasm/legacy/Cargo.toml
@@ -6,6 +6,7 @@ edition = "2024"
crate-type = ["cdylib"]
[dependencies]
+ente-accounts.workspace = true
ente-core.workspace = true
ente-legacy.workspace = true
ente-wasm-log.workspace = true
diff --git a/rust/bindings/wasm/legacy/src/lib.rs b/rust/bindings/wasm/legacy/src/lib.rs
index 4a29bd9ed6..e6d65834f3 100644
--- a/rust/bindings/wasm/legacy/src/lib.rs
+++ b/rust/bindings/wasm/legacy/src/lib.rs
@@ -1,4 +1,14 @@
-use ente_legacy::{LegacyKitRecoveryClient, LegacyKitShare};
+use std::sync::Arc;
+
+use ente_accounts::auth::KeyAttributes;
+use ente_core::{
+ b64,
+ crypto::SecretVec,
+ http::{Api, ApiConfig, Auth, Http},
+};
+use ente_legacy::{
+ LegacyClient as InnerLegacyClient, LegacyContactState, LegacyKitRecoveryClient, LegacyKitShare,
+};
use serde::Deserialize;
use serde_wasm_bindgen as swb;
use wasm_bindgen::prelude::*;
@@ -11,12 +21,18 @@ pub enum Error {
Legacy(#[from] ente_legacy::Error),
#[error(transparent)]
Serde(#[from] swb::Error),
+ #[error(transparent)]
+ Decode(#[from] b64::DecodeError),
}
impl Error {
fn name(&self) -> Option<&'static str> {
match self {
Self::Legacy(ente_legacy::Error::LegacyKitInactive) => Some("legacy_kit_inactive"),
+ Self::Legacy(ente_legacy::Error::ContactNotOnEnte) => Some("contact_not_on_ente"),
+ Self::Legacy(ente_legacy::Error::ActiveRecoverySession) => {
+ Some("active_recovery_session")
+ }
_ => None,
}
}
@@ -36,6 +52,147 @@ impl From<Error> for JsValue {
}
}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct OpenLegacyInput {
+ base_url: String,
+ auth_token: String,
+ master_key_b64: String,
+ client_package: Option<String>,
+ client_version: Option<String>,
+}
+
+#[wasm_bindgen(js_name = openLegacy)]
+pub fn open_legacy(input: JsValue) -> Result<LegacyClient, Error> {
+ let input: OpenLegacyInput = swb::from_value(input)?;
+ let api = Arc::new(Api::new(
+ Http::new().map_err(ente_legacy::Error::from)?,
+ ApiConfig {
+ origin: input.base_url,
+ client_package: input.client_package,
+ client_version: input.client_version,
+ user_agent: None,
+ auth: Some(Auth::User(input.auth_token)),
+ },
+ ));
+ let master_key = Arc::new(SecretVec::new(b64::decode(&input.master_key_b64)?));
+
+ Ok(LegacyClient(InnerLegacyClient::new(api, master_key)))
+}
+
+#[wasm_bindgen]
+pub struct LegacyClient(InnerLegacyClient);
+
+#[wasm_bindgen]
+impl LegacyClient {
+ #[wasm_bindgen(js_name = getInfo)]
+ pub async fn get_info(&self) -> Result<JsValue, Error> {
+ swb::to_value(&self.0.info().await?).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = publicKey)]
+ pub async fn public_key(&self, email: String) -> Result<Option<String>, Error> {
+ self.0.public_key(&email).await.map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = verificationID)]
+ pub fn verification_id(&self, public_key_b64: String) -> Result<String, Error> {
+ self.0.verification_id(&public_key_b64).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = addContact)]
+ pub async fn add_contact(
+ &self,
+ email: String,
+ current_user_key_attrs: JsValue,
+ recovery_notice_in_days: Option<i32>,
+ ) -> Result<(), Error> {
+ let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
+ self.0
+ .add_contact(&email, &current_user_key_attrs, recovery_notice_in_days)
+ .await
+ .map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = updateContact)]
+ pub async fn update_contact(
+ &self,
+ user_id: i64,
+ emergency_contact_id: i64,
+ state: JsValue,
+ ) -> Result<(), Error> {
+ let state: LegacyContactState = swb::from_value(state)?;
+ self.0
+ .update_contact(user_id, emergency_contact_id, state)
+ .await
+ .map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = updateRecoveryNotice)]
+ pub async fn update_recovery_notice(
+ &self,
+ emergency_contact_id: i64,
+ recovery_notice_in_days: i32,
+ ) -> Result<(), Error> {
+ self.0
+ .update_recovery_notice(emergency_contact_id, recovery_notice_in_days)
+ .await
+ .map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = startRecovery)]
+ pub async fn start_recovery(
+ &self,
+ user_id: i64,
+ emergency_contact_id: i64,
+ ) -> Result<(), Error> {
+ self.0
+ .start_recovery(user_id, emergency_contact_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = stopRecovery)]
+ pub async fn stop_recovery(
+ &self,
+ recovery_id: String,
+ user_id: i64,
+ emergency_contact_id: i64,
+ ) -> Result<(), Error> {
+ self.0
+ .stop_recovery(&recovery_id, user_id, emergency_contact_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = rejectRecovery)]
+ pub async fn reject_recovery(
+ &self,
+ recovery_id: String,
+ user_id: i64,
+ emergency_contact_id: i64,
+ ) -> Result<(), Error> {
+ self.0
+ .reject_recovery(&recovery_id, user_id, emergency_contact_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = changePassword)]
+ pub async fn change_password(
+ &self,
+ recovery_id: String,
+ current_user_key_attrs: JsValue,
+ new_password: String,
+ ) -> Result<(), Error> {
+ let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
+ self.0
+ .change_password(&recovery_id, &current_user_key_attrs, &new_password)
+ .await
+ .map_err(Into::into)
+ }
+}
+
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct OpenLegacyKitRecoveryInput {
diff --git a/rust/bindings/wasm/locker/Cargo.toml b/rust/bindings/wasm/locker/Cargo.toml
new file mode 100644
index 0000000000..0c8aaefab6
--- /dev/null
+++ b/rust/bindings/wasm/locker/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "ente-locker-wasm"
+edition = "2024"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+ente-contacts.workspace = true
+ente-core.workspace = true
+ente-wasm-log.workspace = true
+js-sys.workspace = true
+serde.workspace = true
+serde-wasm-bindgen.workspace = true
+thiserror.workspace = true
+wasm-bindgen.workspace = true
+wasm-bindgen-futures.workspace = true
diff --git a/rust/bindings/wasm/locker/src/lib.rs b/rust/bindings/wasm/locker/src/lib.rs
new file mode 100644
index 0000000000..adee8abf41
--- /dev/null
+++ b/rust/bindings/wasm/locker/src/lib.rs
@@ -0,0 +1,149 @@
+use std::sync::Arc;
+
+use ente_contacts::{OpenContactsInput, WrappedRootContactKey};
+use ente_core::{
+ b64,
+ crypto::SecretVec,
+ http::{Api, ApiConfig, Auth, Http},
+};
+use serde::{Deserialize, Serialize};
+use serde_wasm_bindgen as swb;
+use wasm_bindgen::prelude::*;
+
+use ente_wasm_log as _;
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error(transparent)]
+ Contacts(#[from] ente_contacts::Error),
+ #[error(transparent)]
+ Serde(#[from] swb::Error),
+ #[error(transparent)]
+ Decode(#[from] b64::DecodeError),
+}
+
+impl Error {
+ fn name(&self) -> Option<&'static str> {
+ None
+ }
+
+ fn message(&self) -> String {
+ ente_core::error::chain(self)
+ }
+}
+
+impl From<Error> for JsValue {
+ fn from(error: Error) -> Self {
+ let js_error = js_sys::Error::new(&error.message());
+ if let Some(name) = error.name() {
+ js_error.set_name(name);
+ }
+ js_error.into()
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct OpenContactsJsInput {
+ base_url: String,
+ auth_token: String,
+ user_id: i64,
+ master_key_b64: String,
+ cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,
+ client_package: Option<String>,
+ client_version: Option<String>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ContactRecordJs {
+ id: String,
+ contact_user_id: i64,
+ email: Option<String>,
+ name: Option<String>,
+ #[serde(rename = "profilePictureAttachmentID")]
+ profile_picture_attachment_id: Option<String>,
+ is_deleted: bool,
+ updated_at: i64,
+}
+
+impl From<ente_contacts::ContactRecord> for ContactRecordJs {
+ fn from(value: ente_contacts::ContactRecord) -> Self {
+ Self {
+ id: value.id,
+ contact_user_id: value.contact_user_id,
+ email: value.email,
+ name: value.name,
+ profile_picture_attachment_id: value.profile_picture_attachment_id,
+ is_deleted: value.is_deleted,
+ updated_at: value.updated_at,
+ }
+ }
+}
+
+#[wasm_bindgen(js_name = openContacts)]
+pub fn open_contacts(input: JsValue) -> Result<ContactsClient, Error> {
+ let input: OpenContactsJsInput = swb::from_value(input)?;
+ let api = Arc::new(Api::new(
+ Http::new().map_err(ente_contacts::Error::from)?,
+ ApiConfig {
+ origin: input.base_url,
+ client_package: input.client_package,
+ client_version: input.client_version,
+ user_agent: None,
+ auth: Some(Auth::User(input.auth_token)),
+ },
+ ));
+ let opened = ente_contacts::ContactsClient::open(
+ Arc::clone(&api),
+ Arc::new(SecretVec::new(b64::decode(&input.master_key_b64)?)),
+ OpenContactsInput {
+ user_id: input.user_id,
+ cached_wrapped_root_contact_key: input.cached_wrapped_root_contact_key,
+ },
+ )?;
+
+ Ok(ContactsClient {
+ api,
+ inner: opened.client,
+ })
+}
+
+#[wasm_bindgen]
+pub struct ContactsClient {
+ api: Arc<Api>,
+ inner: ente_contacts::ContactsClient,
+}
+
+#[wasm_bindgen]
+impl ContactsClient {
+ #[wasm_bindgen(js_name = updateAuthToken)]
+ pub fn update_auth_token(&self, auth_token: String) {
+ self.api.set_auth(Some(Auth::User(auth_token)));
+ }
+
+ #[wasm_bindgen(js_name = currentWrappedRootContactKey)]
+ pub fn current_wrapped_root_contact_key(&self) -> Result<JsValue, Error> {
+ swb::to_value(&self.inner.current_wrapped_root_contact_key()).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = getDiff)]
+ pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<JsValue, Error> {
+ let diff: Vec<ContactRecordJs> = self
+ .inner
+ .get_diff(since_time, limit)
+ .await?
+ .into_iter()
+ .map(Into::into)
+ .collect();
+ swb::to_value(&diff).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = getProfilePicture)]
+ pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>, Error> {
+ self.inner
+ .get_profile_picture(contact_id)
+ .await
+ .map_err(Into::into)
+ }
+}
diff --git a/rust/bindings/wasm/photos/Cargo.toml b/rust/bindings/wasm/photos/Cargo.toml
new file mode 100644
index 0000000000..a214c429f8
--- /dev/null
+++ b/rust/bindings/wasm/photos/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "ente-photos-wasm"
+edition = "2024"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+ente-contacts.workspace = true
+ente-core.workspace = true
+ente-wasm-log.workspace = true
+js-sys.workspace = true
+serde.workspace = true
+serde-wasm-bindgen.workspace = true
+thiserror.workspace = true
+wasm-bindgen.workspace = true
+wasm-bindgen-futures.workspace = true
diff --git a/rust/bindings/wasm/photos/src/lib.rs b/rust/bindings/wasm/photos/src/lib.rs
new file mode 100644
index 0000000000..adee8abf41
--- /dev/null
+++ b/rust/bindings/wasm/photos/src/lib.rs
@@ -0,0 +1,149 @@
+use std::sync::Arc;
+
+use ente_contacts::{OpenContactsInput, WrappedRootContactKey};
+use ente_core::{
+ b64,
+ crypto::SecretVec,
+ http::{Api, ApiConfig, Auth, Http},
+};
+use serde::{Deserialize, Serialize};
+use serde_wasm_bindgen as swb;
+use wasm_bindgen::prelude::*;
+
+use ente_wasm_log as _;
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error(transparent)]
+ Contacts(#[from] ente_contacts::Error),
+ #[error(transparent)]
+ Serde(#[from] swb::Error),
+ #[error(transparent)]
+ Decode(#[from] b64::DecodeError),
+}
+
+impl Error {
+ fn name(&self) -> Option<&'static str> {
+ None
+ }
+
+ fn message(&self) -> String {
+ ente_core::error::chain(self)
+ }
+}
+
+impl From<Error> for JsValue {
+ fn from(error: Error) -> Self {
+ let js_error = js_sys::Error::new(&error.message());
+ if let Some(name) = error.name() {
+ js_error.set_name(name);
+ }
+ js_error.into()
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct OpenContactsJsInput {
+ base_url: String,
+ auth_token: String,
+ user_id: i64,
+ master_key_b64: String,
+ cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,
+ client_package: Option<String>,
+ client_version: Option<String>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct ContactRecordJs {
+ id: String,
+ contact_user_id: i64,
+ email: Option<String>,
+ name: Option<String>,
+ #[serde(rename = "profilePictureAttachmentID")]
+ profile_picture_attachment_id: Option<String>,
+ is_deleted: bool,
+ updated_at: i64,
+}
+
+impl From<ente_contacts::ContactRecord> for ContactRecordJs {
+ fn from(value: ente_contacts::ContactRecord) -> Self {
+ Self {
+ id: value.id,
+ contact_user_id: value.contact_user_id,
+ email: value.email,
+ name: value.name,
+ profile_picture_attachment_id: value.profile_picture_attachment_id,
+ is_deleted: value.is_deleted,
+ updated_at: value.updated_at,
+ }
+ }
+}
+
+#[wasm_bindgen(js_name = openContacts)]
+pub fn open_contacts(input: JsValue) -> Result<ContactsClient, Error> {
+ let input: OpenContactsJsInput = swb::from_value(input)?;
+ let api = Arc::new(Api::new(
+ Http::new().map_err(ente_contacts::Error::from)?,
+ ApiConfig {
+ origin: input.base_url,
+ client_package: input.client_package,
+ client_version: input.client_version,
+ user_agent: None,
+ auth: Some(Auth::User(input.auth_token)),
+ },
+ ));
+ let opened = ente_contacts::ContactsClient::open(
+ Arc::clone(&api),
+ Arc::new(SecretVec::new(b64::decode(&input.master_key_b64)?)),
+ OpenContactsInput {
+ user_id: input.user_id,
+ cached_wrapped_root_contact_key: input.cached_wrapped_root_contact_key,
+ },
+ )?;
+
+ Ok(ContactsClient {
+ api,
+ inner: opened.client,
+ })
+}
+
+#[wasm_bindgen]
+pub struct ContactsClient {
+ api: Arc<Api>,
+ inner: ente_contacts::ContactsClient,
+}
+
+#[wasm_bindgen]
+impl ContactsClient {
+ #[wasm_bindgen(js_name = updateAuthToken)]
+ pub fn update_auth_token(&self, auth_token: String) {
+ self.api.set_auth(Some(Auth::User(auth_token)));
+ }
+
+ #[wasm_bindgen(js_name = currentWrappedRootContactKey)]
+ pub fn current_wrapped_root_contact_key(&self) -> Result<JsValue, Error> {
+ swb::to_value(&self.inner.current_wrapped_root_contact_key()).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = getDiff)]
+ pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<JsValue, Error> {
+ let diff: Vec<ContactRecordJs> = self
+ .inner
+ .get_diff(since_time, limit)
+ .await?
+ .into_iter()
+ .map(Into::into)
+ .collect();
+ swb::to_value(&diff).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = getProfilePicture)]
+ pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>, Error> {
+ self.inner
+ .get_profile_picture(contact_id)
+ .await
+ .map_err(Into::into)
+ }
+}
diff --git a/web/apps/locker/package.json b/web/apps/locker/package.json
index 45202c24d1..4d24cab209 100644
--- a/web/apps/locker/package.json
+++ b/web/apps/locker/package.json
@@ -8,8 +8,9 @@
"@hugeicons/react": "1.1.6",
"ente-accounts": "*",
"ente-base": "*",
- "ente-contacts-web": "*",
- "ente-core-wasm": "*"
+ "ente-contacts": "*",
+ "ente-core-wasm": "*",
+ "ente-locker-wasm": "*"
},
"devDependencies": {
"ente-build-config": "*"
diff --git a/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx b/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
index 3b187b765f..c385e639c7 100644
--- a/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
+++ b/web/apps/locker/src/components/LockerCollectionShareDrawer.tsx
@@ -34,7 +34,8 @@ import {
ensureContactsReady,
useResolvedContactAvatar,
useResolvedContactDisplay,
-} from "ente-contacts-web";
+} from "ente-contacts";
+import { openContacts } from "ente-locker-wasm";
import { t } from "i18next";
import React, { useCallback, useEffect, useMemo, useState } from "react";
@@ -144,10 +145,10 @@ export const LockerCollectionShareDrawer: React.FC<
if (!masterKeyB64) {
return;
}
- await ensureContactsReady({
- userID: currentUser.id,
- masterKeyB64,
- });
+ await ensureContactsReady(
+ { userID: currentUser.id, masterKeyB64 },
+ openContacts,
+ );
} catch (error) {
log.warn(
"[LockerCollectionShareDrawer] Failed to warm contacts display cache",
diff --git a/web/apps/locker/src/components/LockerLegacyDrawer.tsx b/web/apps/locker/src/components/LockerLegacyDrawer.tsx
index 992b3ef846..745b4744e6 100644
--- a/web/apps/locker/src/components/LockerLegacyDrawer.tsx
+++ b/web/apps/locker/src/components/LockerLegacyDrawer.tsx
@@ -1,7 +1,7 @@
import {
LegacyDrawerContent,
type LegacySuggestedUser,
-} from "ente-contacts-web/legacy";
+} from "ente-contacts/legacy";
import React from "react";
import {
LockerTitledNestedSidebarDrawer,
diff --git a/web/apps/locker/src/components/LockerSidebar.tsx b/web/apps/locker/src/components/LockerSidebar.tsx
index 52be7baad3..0db9029468 100644
--- a/web/apps/locker/src/components/LockerSidebar.tsx
+++ b/web/apps/locker/src/components/LockerSidebar.tsx
@@ -18,7 +18,7 @@ import { useBaseContext } from "ente-base/context";
import {
mergeLegacySuggestedUsers,
type LegacySuggestedUser,
-} from "ente-contacts-web/legacy";
+} from "ente-contacts/legacy";
import { t } from "i18next";
import dynamic from "next/dynamic";
import React, { useEffect, useMemo, useState } from "react";
diff --git a/web/apps/locker/src/components/lockerPage/useLockerData.ts b/web/apps/locker/src/components/lockerPage/useLockerData.ts
index d70d26d127..c82c7b171f 100644
--- a/web/apps/locker/src/components/lockerPage/useLockerData.ts
+++ b/web/apps/locker/src/components/lockerPage/useLockerData.ts
@@ -23,7 +23,8 @@ import {
import log from "ente-base/log";
import { apiURL } from "ente-base/origins";
import { savedAuthToken } from "ente-base/token";
-import { ensureContactsReady } from "ente-contacts-web";
+import { ensureContactsReady } from "ente-contacts";
+import { openContacts } from "ente-locker-wasm";
import { t } from "i18next";
import type { NextRouter } from "next/router";
import { useCallback, useEffect, useRef, useState } from "react";
@@ -314,10 +315,10 @@ export const useLockerData = ({
}
setMasterKey(mk);
- void ensureContactsReady({
- userID: ensureLocalUser().id,
- masterKeyB64: mk,
- }).catch((error: unknown) => {
+ void ensureContactsReady(
+ { userID: ensureLocalUser().id, masterKeyB64: mk },
+ openContacts,
+ ).catch((error: unknown) => {
log.warn(
"[locker] Failed to warm contacts display cache",
error,
diff --git a/web/apps/photos/package.json b/web/apps/photos/package.json
index 3dae2e1530..b7338ed0c8 100644
--- a/web/apps/photos/package.json
+++ b/web/apps/photos/package.json
@@ -16,11 +16,11 @@
"ente-accounts": "*",
"ente-base": "*",
"ente-cast-wasm": "*",
- "ente-contacts-web": "*",
- "ente-core-wasm": "*",
+ "ente-contacts": "*",
"ente-gallery": "*",
"ente-media": "*",
"ente-new": "*",
+ "ente-photos-wasm": "*",
"i18next": "26.3.1",
"memoize-one": "6.0.0",
"ml-matrix": "6.12.2",
diff --git a/web/apps/photos/src/components/Avatar.tsx b/web/apps/photos/src/components/Avatar.tsx
index d77dbfd105..5ddb7f7f3a 100644
--- a/web/apps/photos/src/components/Avatar.tsx
+++ b/web/apps/photos/src/components/Avatar.tsx
@@ -6,7 +6,7 @@ import {
} from "@/services/avatar";
import { styled } from "@mui/material";
import type { LocalUser } from "ente-accounts/services/user";
-import { useResolvedContactAvatar } from "ente-contacts-web";
+import { useResolvedContactAvatar } from "ente-contacts";
import type { EnteFile } from "ente-media/file";
import React, { useMemo } from "react";
diff --git a/web/apps/photos/src/components/Collections/CollectionShare.tsx b/web/apps/photos/src/components/Collections/CollectionShare.tsx
index fe9e60f65e..0eaba9de30 100644
--- a/web/apps/photos/src/components/Collections/CollectionShare.tsx
+++ b/web/apps/photos/src/components/Collections/CollectionShare.tsx
@@ -53,7 +53,7 @@ import { deriveInteractiveKey } from "ente-base/crypto";
import { isHTTPErrorWithStatus, isMuseumHTTPError } from "ente-base/http";
import { formattedDateTime } from "ente-base/i18n-date";
import log from "ente-base/log";
-import { useResolvedContactDisplay } from "ente-contacts-web";
+import { useResolvedContactDisplay } from "ente-contacts";
import { appendCollectionKeyToShareURL } from "ente-gallery/services/share";
import type {
Collection,
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 38fdf8142e..8ea3467a77 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -89,7 +89,7 @@ import {
} from "ente-base/session";
import { savedAuthToken } from "ente-base/token";
import type { Location } from "ente-base/types";
-import { ensureContactsReady } from "ente-contacts-web";
+import { ensureContactsReady } from "ente-contacts";
import { DownloadStatusNotifications } from "ente-gallery/components/DownloadStatusNotifications";
import { FullScreenDropZone } from "ente-gallery/components/FullScreenDropZone";
import type { UploadTypeSelectorIntent } from "ente-gallery/components/Upload";
@@ -131,6 +131,7 @@ import {
addManualFileAssignmentsToPerson,
isMLEnabled,
} from "ente-new/photos/services/ml";
+import { openContacts } from "ente-photos-wasm";
import { postPullFiles, prePullFiles, pullFiles } from "@/services/pull";
import { uploadManager } from "@/services/upload-manager";
@@ -509,10 +510,10 @@ const Page: React.FC = () => {
const user = ensureLocalUser();
const masterKey = await masterKeyFromSession();
if (masterKey) {
- void ensureContactsReady({
- userID: user.id,
- masterKeyB64: masterKey,
- }).catch((error: unknown) => {
+ void ensureContactsReady(
+ { userID: user.id, masterKeyB64: masterKey },
+ openContacts,
+ ).catch((error: unknown) => {
log.warn(
"[gallery] Failed to warm contacts display cache",
error,
diff --git a/web/package-lock.json b/web/package-lock.json
index 87178978b2..ef53c80b32 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -232,8 +232,9 @@
"@hugeicons/react": "1.1.6",
"ente-accounts": "*",
"ente-base": "*",
- "ente-contacts-web": "*",
- "ente-core-wasm": "*"
+ "ente-contacts": "*",
+ "ente-core-wasm": "*",
+ "ente-locker-wasm": "*"
},
"devDependencies": {
"ente-build-config": "*"
@@ -296,11 +297,11 @@
"ente-accounts": "*",
"ente-base": "*",
"ente-cast-wasm": "*",
- "ente-contacts-web": "*",
- "ente-core-wasm": "*",
+ "ente-contacts": "*",
"ente-gallery": "*",
"ente-media": "*",
"ente-new": "*",
+ "ente-photos-wasm": "*",
"i18next": "26.3.1",
"memoize-one": "6.0.0",
"ml-matrix": "6.12.2",
@@ -4737,7 +4738,7 @@
"resolved": "packages/wasm/cast",
"link": true
},
- "node_modules/ente-contacts-web": {
+ "node_modules/ente-contacts": {
"resolved": "packages/contacts",
"link": true
},
@@ -4757,6 +4758,10 @@
"resolved": "packages/wasm/legacy",
"link": true
},
+ "node_modules/ente-locker-wasm": {
+ "resolved": "packages/wasm/locker",
+ "link": true
+ },
"node_modules/ente-media": {
"resolved": "packages/media",
"link": true
@@ -4769,6 +4774,10 @@
"resolved": "packages/wasm/paste",
"link": true
},
+ "node_modules/ente-photos-wasm": {
+ "resolved": "packages/wasm/photos",
+ "link": true
+ },
"node_modules/ente-space-wasm": {
"resolved": "packages/wasm/space",
"link": true
@@ -11239,14 +11248,14 @@
}
},
"packages/contacts": {
- "name": "ente-contacts-web",
+ "name": "ente-contacts",
"version": "0.0.0",
"dependencies": {
"@mui/icons-material": "9.3.1",
"@mui/material": "9.3.1",
"ente-accounts": "*",
"ente-base": "*",
- "ente-core-wasm": "*",
+ "ente-legacy-wasm": "*",
"react": "19.2.7",
"zod": "4.4.3"
},
@@ -11266,7 +11275,7 @@
"bs58": "6.0.0",
"ente-accounts": "*",
"ente-base": "*",
- "ente-contacts-web": "*",
+ "ente-contacts": "*",
"ente-utils": "*",
"exifreader": "4.40.3",
"hls-video-element": "1.5.11",
@@ -11364,6 +11373,14 @@
"wasm-pack": "0.15.0"
}
},
+ "packages/wasm/locker": {
+ "name": "ente-locker-wasm",
+ "version": "0.0.0",
+ "devDependencies": {
+ "ente-build-config": "*",
+ "wasm-pack": "0.15.0"
+ }
+ },
"packages/wasm/paste": {
"name": "ente-paste-wasm",
"version": "0.0.0",
@@ -11377,6 +11394,14 @@
"wasm-pack": "0.15.0"
}
},
+ "packages/wasm/photos": {
+ "name": "ente-photos-wasm",
+ "version": "0.0.0",
+ "devDependencies": {
+ "ente-build-config": "*",
+ "wasm-pack": "0.15.0"
+ }
+ },
"packages/wasm/space": {
"name": "ente-space-wasm",
"version": "0.0.0",
diff --git a/web/package.json b/web/package.json
index 89e7d5cf5e..1efab99a31 100644
--- a/web/package.json
+++ b/web/package.json
@@ -20,17 +20,19 @@
"build:ensu-wasm": "npm run build --workspace ente-ensu-wasm",
"build:legacy": "npm run build:legacy-wasm && npm exec --workspace legacy -- next build --webpack",
"build:legacy-wasm": "npm run build --workspace ente-legacy-wasm",
- "build:locker": "npm run build:core-wasm && npm exec --workspace locker -- next build --webpack",
+ "build:locker": "npm run build:core-wasm && npm run build:legacy-wasm && npm run build:locker-wasm && npm exec --workspace locker -- next build --webpack",
+ "build:locker-wasm": "npm run build --workspace ente-locker-wasm",
"build:memories": "npm run build:core-wasm && npm exec --workspace memories -- next build --webpack && npm run build:post --workspace memories",
"build:paste": "npm run build:paste-wasm && npm exec --workspace paste -- next build --webpack && npm run build:post --workspace paste",
"build:paste-wasm": "npm run build --workspace ente-paste-wasm",
"build:payments": "npm run build --workspace payments",
- "build:photos": "npm run build:core-wasm && npm run build:cast-wasm && npm exec --workspace photos -- next build --webpack",
+ "build:photos": "npm run build:core-wasm && npm run build:cast-wasm && npm run build:photos-wasm && npm exec --workspace photos -- next build --webpack",
+ "build:photos-wasm": "npm run build --workspace ente-photos-wasm",
"build:share": "npm run build:core-wasm && npm exec --workspace share -- next build --webpack && npm run build:post --workspace share",
"build:space": "npm run build:core-wasm && npm run build:space-wasm && npm exec --workspace space -- next build --webpack && npm run build:post --workspace space",
"build:space-wasm": "npm run build --workspace ente-space-wasm",
"build:twoof3": "npm exec --workspace twoof3 -- next build --webpack",
- "build:wasm": "npm run build:core-wasm && npm run build:cast-wasm && npm run build:ensu-wasm && npm run build:legacy-wasm && npm run build:paste-wasm && npm run build:space-wasm",
+ "build:wasm": "npm run build:core-wasm && npm run build:cast-wasm && npm run build:ensu-wasm && npm run build:legacy-wasm && npm run build:locker-wasm && npm run build:paste-wasm && npm run build:photos-wasm && npm run build:space-wasm",
"dev": "npm run dev:photos",
"dev:accounts": "npm run build:core-wasm && npm exec --workspace accounts -- next dev --webpack -p 3001",
"dev:albums": "npm run build:core-wasm && npm exec --workspace albums -- next dev --webpack -p 3002",
@@ -39,17 +41,17 @@
"dev:embed": "npm run build:core-wasm && npm exec --workspace embed -- next dev --webpack -p 3006",
"dev:ensu": "npm run build:ensu-wasm && npm exec --workspace ensu -- next dev --webpack -p 3007",
"dev:legacy": "npm run build:legacy-wasm && npm exec --workspace legacy -- next dev --webpack -p 3011",
- "dev:locker": "npm run build:core-wasm && npm exec --workspace locker -- next dev --webpack -p 3009",
+ "dev:locker": "npm run build:core-wasm && npm run build:legacy-wasm && npm run build:locker-wasm && npm exec --workspace locker -- next dev --webpack -p 3009",
"dev:memories": "npm run build:core-wasm && npm exec --workspace memories -- next dev --webpack -p 3010",
"dev:paste": "npm run build:paste-wasm && npm exec --workspace paste -- next dev --webpack -p 3008",
"dev:payments": "npm run dev --workspace payments",
- "dev:photos": "npm run build:core-wasm && npm run build:cast-wasm && npm exec --workspace photos -- next dev --webpack -p 3000",
+ "dev:photos": "npm run build:core-wasm && npm run build:cast-wasm && npm run build:photos-wasm && npm exec --workspace photos -- next dev --webpack -p 3000",
"dev:share": "npm run build:core-wasm && npm exec --workspace share -- next dev --webpack -p 3005",
"dev:space": "npm run build:core-wasm && npm run build:space-wasm && npm exec --workspace space -- next dev --webpack -p 3013",
"dev:twoof3": "npm exec --workspace twoof3 -- next dev --webpack -p 3012",
"lint": "concurrently --names 'prettier,eslint,tsc' \"prettier --check --log-level warn .\" \"npm exec --workspaces -- eslint --max-warnings 0\" \"npm exec --workspaces -- tsc\"",
"lint:fix": "concurrently --names 'prettier,eslint,tsc' \"prettier --write --log-level warn .\" \"npm exec --workspaces -- eslint --fix --max-warnings 0\" \"npm exec --workspaces -- tsc\"",
- "test": "npm run test --workspace ente-core-wasm && npm run test --workspace ente-paste-wasm && npm run test --workspace ente-contacts-web && npm run test --workspace photos"
+ "test": "npm run test --workspace ente-core-wasm && npm run test --workspace ente-paste-wasm && npm run test --workspace ente-contacts && npm run test --workspace photos"
},
"overrides": {
"@types/react": "19.2.17",
diff --git a/web/packages/contacts/index.test.ts b/web/packages/contacts/index.test.ts
index 7e30964be6..0336877b74 100644
--- a/web/packages/contacts/index.test.ts
+++ b/web/packages/contacts/index.test.ts
@@ -9,7 +9,6 @@ beforeEach(() => {
interface SetupOptions {
diff?: object[];
- legacyInfo?: object;
getProfilePictureError?: Error;
getProfilePictureBytes?: Uint8Array;
rootKeySource?: "cache" | "unresolved";
@@ -33,17 +32,16 @@ const setupContactsModule = async (options: SetupOptions = {}) => {
const info = vi.fn();
const warn = vi.fn();
const error = vi.fn();
- const update_auth_token = vi.fn();
- const current_wrapped_root_contact_key = vi.fn(
- () =>
- options.currentWrappedRootContactKey ??
- options.wrappedRootContactKey ??
- (options.rootKeySource === "unresolved"
- ? { encryptedKey: "wrapped-root-key", header: "wrapped-header" }
- : {
- encryptedKey: "wrapped-root-key",
- header: "wrapped-header",
- }),
+ const updateAuthToken = vi.fn();
+ let isRootKeyResolved = options.rootKeySource !== "unresolved";
+ const currentWrappedRootContactKey = vi.fn(() =>
+ isRootKeyResolved
+ ? (options.currentWrappedRootContactKey ??
+ options.wrappedRootContactKey ?? {
+ encryptedKey: "wrapped-root-key",
+ header: "wrapped-header",
+ })
+ : undefined,
);
const diff = options.diff ?? [
{
@@ -57,11 +55,14 @@ const setupContactsModule = async (options: SetupOptions = {}) => {
},
];
- const get_diff = vi
+ const getDiff = vi
.fn()
- .mockResolvedValueOnce(diff)
+ .mockImplementationOnce(() => {
+ if (diff.length > 0) isRootKeyResolved = true;
+ return Promise.resolve(diff);
+ })
.mockResolvedValueOnce([]);
- const get_profile_picture = vi.fn(() => {
+ const getProfilePicture = vi.fn(() => {
if (options.getProfilePictureBytes) {
return Promise.resolve(options.getProfilePictureBytes);
}
@@ -69,17 +70,6 @@ const setupContactsModule = async (options: SetupOptions = {}) => {
options.getProfilePictureError ?? new Error("boom"),
);
});
- const legacy_get_info = vi.fn(() =>
- Promise.resolve(
- options.legacyInfo ?? {
- contacts: [],
- recoverSessions: [],
- othersEmergencyContact: [],
- othersRecoverySession: [],
- },
- ),
- );
-
vi.doMock("ente-base/kv", () => ({ getKV, getKVN, setKV }));
vi.doMock("ente-base/token", () => ({ savedAuthToken }));
vi.doMock("ente-base/origins", () => ({ apiOrigin }));
@@ -99,49 +89,35 @@ const setupContactsModule = async (options: SetupOptions = {}) => {
desktopAppVersion: undefined,
isDesktop: false,
}));
- vi.doMock("ente-core-wasm", () => ({
- contacts_open_ctx: vi.fn(() => ({
- ctx: {
- update_auth_token,
- current_wrapped_root_contact_key,
- get_diff,
- get_profile_picture,
- legacy_get_info,
- },
- wrappedRootContactKey:
- options.wrappedRootContactKey ??
- (options.rootKeySource === "unresolved"
- ? undefined
- : {
- encryptedKey: "wrapped-root-key",
- header: "wrapped-header",
- }),
- rootKeySource: options.rootKeySource ?? "cache",
- })),
- }));
-
const contacts = await import("./index");
+ const openContacts = () =>
+ Promise.resolve({
+ updateAuthToken,
+ currentWrappedRootContactKey,
+ getDiff,
+ getProfilePicture,
+ });
return {
contacts,
+ openContacts,
setKV,
savedAuthToken,
- update_auth_token,
- get_diff,
- get_profile_picture,
- legacy_get_info,
+ updateAuthToken,
+ getDiff,
+ getProfilePicture,
info,
};
};
describe("ensureContactsReady", () => {
test("does not persist auth token or master key in contacts kv", async () => {
- const { contacts, setKV } = await setupContactsModule();
+ const { contacts, openContacts, setKV } = await setupContactsModule();
- await contacts.ensureContactsReady({
- userID: 101,
- masterKeyB64: "MASTER_KEY_SHOULD_NOT_PERSIST",
- });
+ await contacts.ensureContactsReady(
+ { userID: 101, masterKeyB64: "MASTER_KEY_SHOULD_NOT_PERSIST" },
+ openContacts,
+ );
const persisted = setKV.mock.calls
.map(([key, value]) => `${key}:${JSON.stringify(value)}`)
@@ -158,15 +134,15 @@ describe("ensureContactsReady", () => {
});
test("does not persist an unresolved wrapped root contact key", async () => {
- const { contacts, setKV } = await setupContactsModule({
+ const { contacts, openContacts, setKV } = await setupContactsModule({
rootKeySource: "unresolved",
diff: [],
});
- await contacts.ensureContactsReady({
- userID: 101,
- masterKeyB64: "MASTER_KEY_SHOULD_NOT_PERSIST",
- });
+ await contacts.ensureContactsReady(
+ { userID: 101, masterKeyB64: "MASTER_KEY_SHOULD_NOT_PERSIST" },
+ openContacts,
+ );
const persisted = setKV.mock.calls
.map(([key, value]) => `${key}:${JSON.stringify(value)}`)
@@ -176,14 +152,14 @@ describe("ensureContactsReady", () => {
});
test("persists a resolved wrapped root contact key after non-empty diff", async () => {
- const { contacts, setKV } = await setupContactsModule({
+ const { contacts, openContacts, setKV } = await setupContactsModule({
rootKeySource: "unresolved",
});
- await contacts.ensureContactsReady({
- userID: 101,
- masterKeyB64: "MASTER_KEY_SHOULD_NOT_PERSIST",
- });
+ await contacts.ensureContactsReady(
+ { userID: 101, masterKeyB64: "MASTER_KEY_SHOULD_NOT_PERSIST" },
+ openContacts,
+ );
const persisted = setKV.mock.calls
.map(([key, value]) => `${key}:${JSON.stringify(value)}`)
@@ -195,15 +171,15 @@ describe("ensureContactsReady", () => {
describe("profile picture loading", () => {
test("negative-caches failed profile picture fetches and logs at info", async () => {
- const { contacts, get_profile_picture, info } =
+ const { contacts, getProfilePicture, info, openContacts } =
await setupContactsModule({
getProfilePictureError: new Error("network failure"),
});
- await contacts.ensureContactsReady({
- userID: 101,
- masterKeyB64: "ignored",
- });
+ await contacts.ensureContactsReady(
+ { userID: 101, masterKeyB64: "ignored" },
+ openContacts,
+ );
await contacts.__testing.preloadResolvedContactAvatar({
userID: 101,
@@ -214,7 +190,7 @@ describe("profile picture loading", () => {
});
- expect(get_profile_picture).toHaveBeenCalledTimes(1);
+ expect(getProfilePicture).toHaveBeenCalledTimes(1);
expect(info).toHaveBeenCalledTimes(1);
expect(info.mock.calls[0]?.[0]).toContain(
"Failed to load contact profile picture for ct_1",
@@ -229,14 +205,14 @@ describe("profile picture loading", () => {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00,
0x0d,
]);
- const { contacts } = await setupContactsModule({
+ const { contacts, openContacts } = await setupContactsModule({
getProfilePictureBytes: pngBytes,
});
- await contacts.ensureContactsReady({
- userID: 101,
- masterKeyB64: "ignored",
- });
+ await contacts.ensureContactsReady(
+ { userID: 101, masterKeyB64: "ignored" },
+ openContacts,
+ );
await contacts.__testing.preloadResolvedContactAvatar({ userID: 101 });
const blobArg = createObjectURL.mock.calls[0]?.[0] as Blob | undefined;
@@ -247,9 +223,9 @@ describe("profile picture loading", () => {
describe("retry after warm-up failure", () => {
test("recovers from a transient failure with bounded background retry", async () => {
vi.useFakeTimers();
- const { contacts, get_diff } = await setupContactsModule();
- get_diff.mockReset();
- get_diff
+ const { contacts, getDiff, openContacts } = await setupContactsModule();
+ getDiff.mockReset();
+ getDiff
.mockRejectedValueOnce(new Error("transient"))
.mockResolvedValueOnce([
{
@@ -264,27 +240,27 @@ describe("retry after warm-up failure", () => {
])
.mockResolvedValueOnce([]);
- const ready = contacts.ensureContactsReady({
- userID: 101,
- masterKeyB64: "ignored",
- });
+ const ready = contacts.ensureContactsReady(
+ { userID: 101, masterKeyB64: "ignored" },
+ openContacts,
+ );
await vi.advanceTimersByTimeAsync(10_001);
await expect(ready).resolves.toBeUndefined();
- expect(get_diff).toHaveBeenCalledTimes(3);
+ expect(getDiff).toHaveBeenCalledTimes(3);
});
test("stops after bounded background retries keep failing", async () => {
vi.useFakeTimers();
- const { contacts, get_diff } = await setupContactsModule();
- get_diff.mockReset();
- get_diff.mockRejectedValue(new Error("down"));
+ const { contacts, getDiff, openContacts } = await setupContactsModule();
+ getDiff.mockReset();
+ getDiff.mockRejectedValue(new Error("down"));
const ready = expect(
- contacts.ensureContactsReady({
- userID: 101,
- masterKeyB64: "ignored",
- }),
+ contacts.ensureContactsReady(
+ { userID: 101, masterKeyB64: "ignored" },
+ openContacts,
+ ),
).rejects.toThrow("down");
await vi.advanceTimersByTimeAsync(10_001);
@@ -292,95 +268,52 @@ describe("retry after warm-up failure", () => {
await vi.advanceTimersByTimeAsync(120_001);
await ready;
- expect(get_diff).toHaveBeenCalledTimes(4);
+ expect(getDiff).toHaveBeenCalledTimes(4);
await vi.advanceTimersByTimeAsync(300_000);
- expect(get_diff).toHaveBeenCalledTimes(4);
+ expect(getDiff).toHaveBeenCalledTimes(4);
});
test("stale retry does not update a newer generation context token", async () => {
vi.useFakeTimers();
- const { contacts, savedAuthToken, update_auth_token, get_diff } =
- await setupContactsModule();
+ const {
+ contacts,
+ savedAuthToken,
+ updateAuthToken,
+ getDiff,
+ openContacts,
+ } = await setupContactsModule();
savedAuthToken
.mockReturnValueOnce("old-token")
.mockReturnValueOnce(undefined)
.mockReturnValue("new-token");
- get_diff.mockReset();
- get_diff
+ getDiff.mockReset();
+ getDiff
.mockRejectedValueOnce(new Error("transient"))
.mockResolvedValueOnce([])
.mockResolvedValueOnce([]);
- const staleReady = contacts.ensureContactsReady({
- userID: 101,
- masterKeyB64: "old-master-key",
- });
+ const staleReady = contacts.ensureContactsReady(
+ { userID: 101, masterKeyB64: "old-master-key" },
+ openContacts,
+ );
await vi.advanceTimersByTimeAsync(0);
- expect(get_diff).toHaveBeenCalledTimes(1);
+ expect(getDiff).toHaveBeenCalledTimes(1);
- await contacts.ensureContactsReady({
- userID: 101,
- masterKeyB64: "clearing-master-key",
- });
- expect(get_diff).toHaveBeenCalledTimes(1);
+ await contacts.ensureContactsReady(
+ { userID: 101, masterKeyB64: "clearing-master-key" },
+ openContacts,
+ );
+ expect(getDiff).toHaveBeenCalledTimes(1);
- await contacts.ensureContactsReady({
- userID: 101,
- masterKeyB64: "new-master-key",
- });
- expect(get_diff).toHaveBeenCalledTimes(2);
+ await contacts.ensureContactsReady(
+ { userID: 101, masterKeyB64: "new-master-key" },
+ openContacts,
+ );
+ expect(getDiff).toHaveBeenCalledTimes(2);
await vi.advanceTimersByTimeAsync(10_001);
await expect(staleReady).resolves.toBeUndefined();
- expect(update_auth_token).not.toHaveBeenCalled();
- expect(get_diff).toHaveBeenCalledTimes(2);
- });
-});
-
-describe("legacyGetInfo", () => {
- test("normalizes bigint legacy numeric fields at the API boundary", async () => {
- const { contacts } = await setupContactsModule({
- legacyInfo: {
- contacts: [
- {
- user: { id: 101n, email: "[email protected]" },
- emergencyContact: {
- id: 202n,
- email: "[email protected]",
- },
- state: "ACCEPTED",
- recoveryNoticeInDays: 14n,
- },
- ],
- recoverSessions: [
- {
- id: "session_1",
- user: { id: 101n, email: "[email protected]" },
- emergencyContact: {
- id: 202n,
- email: "[email protected]",
- },
- status: "WAITING",
- waitTill: 3_600_000_000n,
- createdAt: 1_700_000_000_000_000n,
- },
- ],
- othersEmergencyContact: [],
- othersRecoverySession: [],
- },
- });
-
- const info = await contacts.legacyGetInfo();
-
- expect(info.contacts[0]?.user.id).toBe(101);
- expect(info.contacts[0]?.emergencyContact.id).toBe(202);
- expect(info.contacts[0]?.recoveryNoticeInDays).toBe(14);
- expect(typeof info.contacts[0]?.user.id).toBe("number");
- expect(typeof info.contacts[0]?.emergencyContact.id).toBe("number");
- expect(typeof info.contacts[0]?.recoveryNoticeInDays).toBe("number");
- expect(info.recoverSessions[0]?.waitTill).toBe(3_600_000_000);
- expect(info.recoverSessions[0]?.createdAt).toBe(1_700_000_000_000_000);
- expect(typeof info.recoverSessions[0]?.waitTill).toBe("number");
- expect(typeof info.recoverSessions[0]?.createdAt).toBe("number");
+ expect(updateAuthToken).not.toHaveBeenCalled();
+ expect(getDiff).toHaveBeenCalledTimes(2);
});
});
diff --git a/web/packages/contacts/index.ts b/web/packages/contacts/index.ts
index 4f2badf033..9309f290fe 100644
--- a/web/packages/contacts/index.ts
+++ b/web/packages/contacts/index.ts
@@ -1,14 +1,9 @@
-import { savedKeyAttributes } from "ente-accounts/services/accounts-db";
-import { getUserRecoveryKey } from "ente-accounts/services/recovery-key";
-import { masterKeyFromSession } from "ente-accounts/services/session-storage";
-import { ensureLocalUser } from "ente-accounts/services/user";
import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
import { ensureArrayBufferBacked } from "ente-base/bytes";
import { retryAsyncOperation } from "ente-base/http";
import log from "ente-base/log";
import { apiOrigin } from "ente-base/origins";
import { savedAuthToken } from "ente-base/token";
-import type { ContactsCtxHandle } from "ente-core-wasm";
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
import {
saveContactDisplayRecords,
@@ -27,10 +22,6 @@ import type {
ContactDisplayRecord,
ContactLookup,
ContactsDisplaySnapshot,
- LegacyContactState,
- LegacyInfo,
- LegacyRecoveryBundle,
- LegacyRecoveryStatus,
ResolvedContactAvatar,
ResolvedContactDisplay,
WrappedRootContactKey,
@@ -42,7 +33,6 @@ export type {
LegacyContactRecord,
LegacyContactState,
LegacyInfo,
- LegacyRecoveryBundle,
LegacyRecoverySession,
LegacyRecoveryStatus,
LegacyUser,
@@ -55,7 +45,7 @@ const CONTACT_DIFF_LIMIT = 500;
const AVATAR_FAILURE_TTL_MS = 60_000;
const CONTACTS_CACHE_SCHEMA_VERSION = 2;
-interface RemoteContactRecord {
+export interface RemoteContactRecord {
id: string;
contactUserId: number | bigint;
email?: string | null;
@@ -66,35 +56,7 @@ interface RemoteContactRecord {
updatedAt: number | bigint;
}
-interface RemoteLegacyUser {
- id: number | bigint;
- email: string;
-}
-
-interface RemoteLegacyContactRecord {
- user: RemoteLegacyUser;
- emergencyContact: RemoteLegacyUser;
- state: LegacyContactState;
- recoveryNoticeInDays: number | bigint;
-}
-
-interface RemoteLegacyRecoverySession {
- id: string;
- user: RemoteLegacyUser;
- emergencyContact: RemoteLegacyUser;
- status: LegacyRecoveryStatus;
- waitTill: number | bigint;
- createdAt: number | bigint;
-}
-
-interface RemoteLegacyInfo {
- contacts: RemoteLegacyContactRecord[];
- recoverSessions: RemoteLegacyRecoverySession[];
- othersEmergencyContact: RemoteLegacyContactRecord[];
- othersRecoverySession: RemoteLegacyRecoverySession[];
-}
-
-interface ContactsReadyInput {
+export interface ContactsReadyInput {
userID: number;
masterKeyB64: string;
}
@@ -104,23 +66,40 @@ type ContactsSessionInput = ContactsReadyInput & {
baseURL: string;
authToken: string;
generation: number;
+ openContacts: OpenContacts;
};
-type RootKeySource = "cache" | "unresolved";
+export interface ContactsClient {
+ updateAuthToken: (authToken: string) => void;
+ currentWrappedRootContactKey: () => WrappedRootContactKey | undefined;
+ getDiff: (
+ sinceTime: bigint,
+ limit: number,
+ ) => Promise<RemoteContactRecord[]>;
+ getProfilePicture: (contactID: string) => Promise<Uint8Array>;
+}
-interface OpenedContactsCtx {
- ctx: ContactsCtxHandle;
- wrappedRootContactKey?: WrappedRootContactKey;
- rootKeySource: RootKeySource;
+export interface OpenContactsInput {
+ baseUrl: string;
+ authToken: string;
+ userId: number;
+ masterKeyB64: string;
+ cachedWrappedRootContactKey?: WrappedRootContactKey;
+ clientPackage?: string;
+ clientVersion?: string;
}
+export type OpenContacts = (
+ input: OpenContactsInput,
+) => Promise<ContactsClient>;
+
interface ContactsState {
snapshot: ContactsDisplaySnapshot;
listeners: Set<() => void>;
currentSessionKey: string | undefined;
sessionGeneration: number;
currentAuthToken: string | undefined;
- ctx: ContactsCtxHandle | undefined;
+ client: ContactsClient | undefined;
readyPromise: Promise<void> | undefined;
contactsByID: Map<string, ContactDisplayRecord>;
contactIDByUserID: Map<number, string>;
@@ -144,7 +123,7 @@ const state: ContactsState = {
currentSessionKey: undefined,
sessionGeneration: 0,
currentAuthToken: undefined,
- ctx: undefined,
+ client: undefined,
readyPromise: undefined,
contactsByID: new Map(),
contactIDByUserID: new Map(),
@@ -189,7 +168,7 @@ const clearInMemoryState = () => {
for (const avatarURL of state.avatarURLByContactID.values()) {
URL.revokeObjectURL(avatarURL);
}
- state.ctx = undefined;
+ state.client = undefined;
state.currentAuthToken = undefined;
state.readyPromise = undefined;
state.contactsByID = new Map();
@@ -352,28 +331,28 @@ const ensureSessionLoaded = async (sessionKey: string) =>
? state.sessionGeneration
: loadLocalSessionState(sessionKey);
-const ensureContactsCtxOpen = async ({
+const ensureContactsClientOpen = async ({
sessionKey,
baseURL,
authToken,
userID,
masterKeyB64,
generation,
+ openContacts,
}: ContactsSessionInput) => {
if (!isCurrentSession(sessionKey, generation)) {
return;
}
- let ctx = state.ctx;
+ let client = state.client;
- if (!ctx) {
+ if (!client) {
const cachedWrappedRootContactKey =
await savedWrappedRootContactKey(sessionKey);
if (!isCurrentSession(sessionKey, generation)) {
return;
}
- const { contacts_open_ctx } = await import("ente-core-wasm");
- const openedCtx = (await contacts_open_ctx({
+ const openedClient = await openContacts({
baseUrl: baseURL,
authToken,
userId: userID,
@@ -381,23 +360,21 @@ const ensureContactsCtxOpen = async ({
cachedWrappedRootContactKey,
clientPackage: clientPackageName,
clientVersion: isDesktop ? desktopAppVersion : undefined,
- })) as OpenedContactsCtx;
+ });
if (!isCurrentSession(sessionKey, generation)) {
return;
}
- state.ctx = openedCtx.ctx;
- ctx = openedCtx.ctx;
- if (openedCtx.wrappedRootContactKey) {
- await saveWrappedRootContactKey(
- sessionKey,
- openedCtx.wrappedRootContactKey,
- );
+ state.client = openedClient;
+ client = openedClient;
+ const wrappedRootContactKey = client.currentWrappedRootContactKey();
+ if (wrappedRootContactKey) {
+ await saveWrappedRootContactKey(sessionKey, wrappedRootContactKey);
if (!isCurrentSession(sessionKey, generation)) {
return;
}
}
} else if (state.currentAuthToken !== authToken) {
- ctx.update_auth_token(authToken);
+ client.updateAuthToken(authToken);
}
if (!isCurrentSession(sessionKey, generation)) {
@@ -405,7 +382,7 @@ const ensureContactsCtxOpen = async ({
}
state.currentAuthToken = authToken;
- return ctx;
+ return client;
};
const syncContacts = async ({
@@ -415,16 +392,18 @@ const syncContacts = async ({
userID,
masterKeyB64,
generation,
+ openContacts,
}: ContactsSessionInput) => {
- const ctx = await ensureContactsCtxOpen({
+ const client = await ensureContactsClientOpen({
sessionKey,
baseURL,
authToken,
userID,
masterKeyB64,
generation,
+ openContacts,
});
- if (!ctx) {
+ if (!client) {
return;
}
@@ -432,10 +411,10 @@ const syncContacts = async ({
let didChange = false;
while (true) {
- const diff = (await ctx.get_diff(
+ const diff = await client.getDiff(
BigInt(sinceTime),
CONTACT_DIFF_LIMIT,
- )) as RemoteContactRecord[];
+ );
if (!isCurrentSession(sessionKey, generation)) {
return;
}
@@ -458,10 +437,7 @@ const syncContacts = async ({
if (!isCurrentSession(sessionKey, generation)) {
return;
}
- const wrappedRootContactKey =
- (await ctx.current_wrapped_root_contact_key()) as
- | WrappedRootContactKey
- | undefined;
+ const wrappedRootContactKey = client.currentWrappedRootContactKey();
if (wrappedRootContactKey) {
await saveWrappedRootContactKey(sessionKey, wrappedRootContactKey);
if (!isCurrentSession(sessionKey, generation)) {
@@ -476,10 +452,10 @@ const syncContacts = async ({
}
};
-export const ensureContactsReady = async ({
- userID,
- masterKeyB64,
-}: ContactsReadyInput) => {
+export const ensureContactsReady = async (
+ { userID, masterKeyB64 }: ContactsReadyInput,
+ openContacts: OpenContacts,
+) => {
const authToken = await savedAuthToken();
if (!authToken) {
state.sessionGeneration += 1;
@@ -510,6 +486,7 @@ export const ensureContactsReady = async ({
userID,
masterKeyB64,
generation,
+ openContacts,
}),
{ retryProfile: "background" },
).finally(() => {
@@ -523,212 +500,6 @@ export const ensureContactsReady = async ({
return readyPromise;
};
-const ensureCurrentLegacyCtx = async () => {
- const masterKeyB64 = await masterKeyFromSession();
- if (!masterKeyB64) {
- throw new Error("Missing current master key");
- }
- const authToken = await savedAuthToken();
- if (!authToken) {
- throw new Error("Missing auth token");
- }
- const user = ensureLocalUser();
- const baseURL = await apiOrigin();
- const sessionKey = buildSessionKey(baseURL, user.id);
- const generation = await ensureSessionLoaded(sessionKey);
- if (generation === undefined) {
- throw new Error("Contacts context not available");
- }
- const ctx = await ensureContactsCtxOpen({
- sessionKey,
- baseURL,
- authToken,
- userID: user.id,
- masterKeyB64,
- generation,
- });
- if (!ctx) {
- throw new Error("Contacts context not available");
- }
- return ctx;
-};
-
-const ensureCurrentLegacyKeyAttributes = () => {
- const keyAttributes = savedKeyAttributes();
- if (!keyAttributes) {
- throw new Error("Missing current key attributes");
- }
- return keyAttributes as unknown as Record<string, unknown>;
-};
-
-const normalizeLegacyUser = (user: RemoteLegacyUser) => ({
- id: Number(user.id),
- email: user.email,
-});
-
-const normalizeLegacyContactRecord = (record: RemoteLegacyContactRecord) => ({
- user: normalizeLegacyUser(record.user),
- emergencyContact: normalizeLegacyUser(record.emergencyContact),
- state: record.state,
- recoveryNoticeInDays: Number(record.recoveryNoticeInDays),
-});
-
-const normalizeLegacyRecoverySession = (
- session: RemoteLegacyRecoverySession,
-) => ({
- id: session.id,
- user: normalizeLegacyUser(session.user),
- emergencyContact: normalizeLegacyUser(session.emergencyContact),
- status: session.status,
- waitTill: Number(session.waitTill),
- createdAt: Number(session.createdAt),
-});
-
-const normalizeLegacyInfo = (info: RemoteLegacyInfo): LegacyInfo => ({
- contacts: info.contacts.map(normalizeLegacyContactRecord),
- recoverSessions: info.recoverSessions.map(normalizeLegacyRecoverySession),
- othersEmergencyContact: info.othersEmergencyContact.map(
- normalizeLegacyContactRecord,
- ),
- othersRecoverySession: info.othersRecoverySession.map(
- normalizeLegacyRecoverySession,
- ),
-});
-
-export const legacyGetInfo = async (): Promise<LegacyInfo> => {
- const ctx = await ensureCurrentLegacyCtx();
- return normalizeLegacyInfo(
- (await ctx.legacy_get_info()) as RemoteLegacyInfo,
- );
-};
-
-export const legacyPublicKey = async (email: string) => {
- const ctx = await ensureCurrentLegacyCtx();
- const publicKey = (await ctx.legacy_public_key(email)) as
- | string
- | null
- | undefined;
- return publicKey ?? undefined;
-};
-
-export const legacyVerificationID = async (email: string) => {
- const ctx = await ensureCurrentLegacyCtx();
- const publicKey = (await ctx.legacy_public_key(email)) as
- | string
- | null
- | undefined;
- return publicKey ? ctx.legacy_verification_id(publicKey) : undefined;
-};
-
-export const legacyAddContact = async (
- email: string,
- recoveryNoticeInDays?: number,
-) => {
- await getUserRecoveryKey();
- const ctx = await ensureCurrentLegacyCtx();
- return ctx.legacy_add_contact(
- email,
- ensureCurrentLegacyKeyAttributes(),
- recoveryNoticeInDays,
- );
-};
-
-export const legacyUpdateContact = async (
- userID: number,
- emergencyContactID: number,
- state: LegacyContactState,
-) => {
- const ctx = await ensureCurrentLegacyCtx();
- return ctx.legacy_update_contact(
- BigInt(userID),
- BigInt(emergencyContactID),
- state,
- );
-};
-
-export const legacyUpdateRecoveryNotice = async (
- emergencyContactID: number,
- recoveryNoticeInDays: number,
-) => {
- const ctx = await ensureCurrentLegacyCtx();
- return ctx.legacy_update_recovery_notice(
- BigInt(emergencyContactID),
- recoveryNoticeInDays,
- );
-};
-
-export const legacyStartRecovery = async (
- userID: number,
- emergencyContactID: number,
-) => {
- const ctx = await ensureCurrentLegacyCtx();
- return ctx.legacy_start_recovery(
- BigInt(userID),
- BigInt(emergencyContactID),
- );
-};
-
-export const legacyStopRecovery = async (
- recoveryID: string,
- userID: number,
- emergencyContactID: number,
-) => {
- const ctx = await ensureCurrentLegacyCtx();
- return ctx.legacy_stop_recovery(
- recoveryID,
- BigInt(userID),
- BigInt(emergencyContactID),
- );
-};
-
-export const legacyRejectRecovery = async (
- recoveryID: string,
- userID: number,
- emergencyContactID: number,
-) => {
- const ctx = await ensureCurrentLegacyCtx();
- return ctx.legacy_reject_recovery(
- recoveryID,
- BigInt(userID),
- BigInt(emergencyContactID),
- );
-};
-
-export const legacyApproveRecovery = async (
- recoveryID: string,
- userID: number,
- emergencyContactID: number,
-) => {
- const ctx = await ensureCurrentLegacyCtx();
- return ctx.legacy_approve_recovery(
- recoveryID,
- BigInt(userID),
- BigInt(emergencyContactID),
- );
-};
-
-export const legacyRecoveryBundle = async (
- recoveryID: string,
-): Promise<LegacyRecoveryBundle> => {
- const ctx = await ensureCurrentLegacyCtx();
- return (await ctx.legacy_recovery_bundle(
- recoveryID,
- ensureCurrentLegacyKeyAttributes(),
- )) as LegacyRecoveryBundle;
-};
-
-export const legacyChangePassword = async (
- recoveryID: string,
- newPassword: string,
-) => {
- const ctx = await ensureCurrentLegacyCtx();
- return ctx.legacy_change_password(
- recoveryID,
- ensureCurrentLegacyKeyAttributes(),
- newPassword,
- );
-};
-
const inferImageMimeType = (bytes: Uint8Array) => {
if (
bytes.length >= 12 &&
@@ -778,10 +549,10 @@ const inferImageMimeType = (bytes: Uint8Array) => {
const ensureProfilePictureLoaded = async (contactID: string) => {
const contact = state.contactsByID.get(contactID);
- const ctx = state.ctx;
+ const client = state.client;
const sessionKey = state.currentSessionKey;
const generation = state.sessionGeneration;
- if (!contact?.profilePictureAttachmentID || !ctx || !sessionKey) {
+ if (!contact?.profilePictureAttachmentID || !client || !sessionKey) {
return;
}
@@ -800,12 +571,12 @@ const ensureProfilePictureLoaded = async (contactID: string) => {
return;
}
- const load = ctx
- .get_profile_picture(contactID)
+ const load = client
+ .getProfilePicture(contactID)
.then((bytes: Uint8Array) => {
if (
!isCurrentSession(sessionKey, generation) ||
- state.ctx !== ctx
+ state.client !== client
) {
return;
}
@@ -821,7 +592,7 @@ const ensureProfilePictureLoaded = async (contactID: string) => {
.catch((error: unknown) => {
if (
!isCurrentSession(sessionKey, generation) ||
- state.ctx !== ctx
+ state.client !== client
) {
return;
}
diff --git a/web/packages/contacts/legacy/index.ts b/web/packages/contacts/legacy/index.ts
index 6bcbf59d20..d1574e5e45 100644
--- a/web/packages/contacts/legacy/index.ts
+++ b/web/packages/contacts/legacy/index.ts
@@ -1,24 +1,21 @@
+export { LegacyDrawerContent } from "./components/LegacyDrawerContent";
export {
legacyAddContact,
- legacyApproveRecovery,
legacyChangePassword,
legacyGetInfo,
legacyPublicKey,
- legacyRecoveryBundle,
legacyRejectRecovery,
legacyStartRecovery,
legacyStopRecovery,
legacyUpdateContact,
legacyUpdateRecoveryNotice,
legacyVerificationID,
-} from "../index";
-export { LegacyDrawerContent } from "./components/LegacyDrawerContent";
+} from "./service";
export { mergeLegacySuggestedUsers } from "./suggestions";
export type {
LegacyContactRecord,
LegacyContactState,
LegacyInfo,
- LegacyRecoveryBundle,
LegacyRecoverySession,
LegacyRecoveryStatus,
LegacySuggestedUser,
diff --git a/web/packages/contacts/legacy/service.test.ts b/web/packages/contacts/legacy/service.test.ts
new file mode 100644
index 0000000000..d096131637
--- /dev/null
+++ b/web/packages/contacts/legacy/service.test.ts
@@ -0,0 +1,64 @@
+import { expect, test, vi } from "vitest";
+
+const { free, getInfo } = vi.hoisted(() => ({
+ free: vi.fn(),
+ getInfo: vi.fn(() =>
+ Promise.resolve({
+ contacts: [
+ {
+ user: { id: 101n, email: "[email protected]" },
+ emergencyContact: { id: 202n, email: "[email protected]" },
+ state: "ACCEPTED",
+ recoveryNoticeInDays: 14n,
+ },
+ ],
+ recoverSessions: [
+ {
+ id: "session_1",
+ user: { id: 101n, email: "[email protected]" },
+ emergencyContact: { id: 202n, email: "[email protected]" },
+ status: "WAITING",
+ waitTill: 3_600_000_000n,
+ createdAt: 1_700_000_000_000_000n,
+ },
+ ],
+ othersEmergencyContact: [],
+ othersRecoverySession: [],
+ }),
+ ),
+}));
+
+vi.mock("ente-accounts/services/accounts-db", () => ({
+ savedKeyAttributes: vi.fn(),
+}));
+vi.mock("ente-accounts/services/recovery-key", () => ({
+ getUserRecoveryKey: vi.fn(),
+}));
+vi.mock("ente-accounts/services/session-storage", () => ({
+ masterKeyFromSession: () => "master-key",
+}));
+vi.mock("ente-base/app", () => ({
+ clientPackageName: "io.ente.test",
+ desktopAppVersion: undefined,
+ isDesktop: false,
+}));
+vi.mock("ente-base/origins", () => ({
+ apiOrigin: () => "https://api.example",
+}));
+vi.mock("ente-base/token", () => ({ savedAuthToken: () => "auth-token" }));
+vi.mock("ente-legacy-wasm/authenticated", () => ({
+ openLegacy: () => Promise.resolve({ free, getInfo }),
+}));
+
+test("normalizes legacy numeric fields at the wasm boundary", async () => {
+ const { legacyGetInfo } = await import("./service");
+
+ const info = await legacyGetInfo();
+
+ expect(info.contacts[0]?.user.id).toBe(101);
+ expect(info.contacts[0]?.emergencyContact.id).toBe(202);
+ expect(info.contacts[0]?.recoveryNoticeInDays).toBe(14);
+ expect(info.recoverSessions[0]?.waitTill).toBe(3_600_000_000);
+ expect(info.recoverSessions[0]?.createdAt).toBe(1_700_000_000_000_000);
+ expect(free).toHaveBeenCalledOnce();
+});
diff --git a/web/packages/contacts/legacy/service.ts b/web/packages/contacts/legacy/service.ts
new file mode 100644
index 0000000000..ed9e838923
--- /dev/null
+++ b/web/packages/contacts/legacy/service.ts
@@ -0,0 +1,232 @@
+import { savedKeyAttributes } from "ente-accounts/services/accounts-db";
+import { getUserRecoveryKey } from "ente-accounts/services/recovery-key";
+import { masterKeyFromSession } from "ente-accounts/services/session-storage";
+import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
+import { apiOrigin } from "ente-base/origins";
+import { savedAuthToken } from "ente-base/token";
+import { openLegacy } from "ente-legacy-wasm/authenticated";
+import type {
+ LegacyContactState,
+ LegacyInfo,
+ LegacyRecoveryStatus,
+} from "./types";
+
+type KeyAttributes = NonNullable<ReturnType<typeof savedKeyAttributes>>;
+
+interface RemoteLegacyUser {
+ id: number | bigint;
+ email: string;
+}
+
+interface RemoteLegacyContactRecord {
+ user: RemoteLegacyUser;
+ emergencyContact: RemoteLegacyUser;
+ state: LegacyContactState;
+ recoveryNoticeInDays: number | bigint;
+}
+
+interface RemoteLegacyRecoverySession {
+ id: string;
+ user: RemoteLegacyUser;
+ emergencyContact: RemoteLegacyUser;
+ status: LegacyRecoveryStatus;
+ waitTill: number | bigint;
+ createdAt: number | bigint;
+}
+
+interface RemoteLegacyInfo {
+ contacts: RemoteLegacyContactRecord[];
+ recoverSessions: RemoteLegacyRecoverySession[];
+ othersEmergencyContact: RemoteLegacyContactRecord[];
+ othersRecoverySession: RemoteLegacyRecoverySession[];
+}
+
+interface LegacyClient {
+ free: () => void;
+ getInfo: () => Promise<RemoteLegacyInfo>;
+ publicKey: (email: string) => Promise<string | undefined>;
+ verificationID: (publicKeyB64: string) => string;
+ addContact: (
+ email: string,
+ currentUserKeyAttributes: KeyAttributes,
+ recoveryNoticeInDays?: number,
+ ) => Promise<void>;
+ updateContact: (
+ userID: bigint,
+ emergencyContactID: bigint,
+ state: LegacyContactState,
+ ) => Promise<void>;
+ updateRecoveryNotice: (
+ emergencyContactID: bigint,
+ recoveryNoticeInDays: number,
+ ) => Promise<void>;
+ startRecovery: (
+ userID: bigint,
+ emergencyContactID: bigint,
+ ) => Promise<void>;
+ stopRecovery: (
+ recoveryID: string,
+ userID: bigint,
+ emergencyContactID: bigint,
+ ) => Promise<void>;
+ rejectRecovery: (
+ recoveryID: string,
+ userID: bigint,
+ emergencyContactID: bigint,
+ ) => Promise<void>;
+ changePassword: (
+ recoveryID: string,
+ currentUserKeyAttributes: KeyAttributes,
+ newPassword: string,
+ ) => Promise<void>;
+}
+
+const withLegacyClient = async <T>(
+ operation: (client: LegacyClient) => T | Promise<T>,
+) => {
+ const masterKeyB64 = await masterKeyFromSession();
+ if (!masterKeyB64) {
+ throw new Error("Missing current master key");
+ }
+ const authToken = await savedAuthToken();
+ if (!authToken) {
+ throw new Error("Missing auth token");
+ }
+ const client: LegacyClient = await openLegacy({
+ baseUrl: await apiOrigin(),
+ authToken,
+ masterKeyB64,
+ clientPackage: clientPackageName,
+ clientVersion: isDesktop ? desktopAppVersion : undefined,
+ });
+ try {
+ return await operation(client);
+ } finally {
+ client.free();
+ }
+};
+
+const currentKeyAttributes = () => {
+ const keyAttributes = savedKeyAttributes();
+ if (!keyAttributes) {
+ throw new Error("Missing current key attributes");
+ }
+ return keyAttributes;
+};
+
+const normalizeLegacyUser = (user: RemoteLegacyUser) => ({
+ id: Number(user.id),
+ email: user.email,
+});
+
+const normalizeLegacyContactRecord = (record: RemoteLegacyContactRecord) => ({
+ user: normalizeLegacyUser(record.user),
+ emergencyContact: normalizeLegacyUser(record.emergencyContact),
+ state: record.state,
+ recoveryNoticeInDays: Number(record.recoveryNoticeInDays),
+});
+
+const normalizeLegacyRecoverySession = (
+ session: RemoteLegacyRecoverySession,
+) => ({
+ id: session.id,
+ user: normalizeLegacyUser(session.user),
+ emergencyContact: normalizeLegacyUser(session.emergencyContact),
+ status: session.status,
+ waitTill: Number(session.waitTill),
+ createdAt: Number(session.createdAt),
+});
+
+const normalizeLegacyInfo = (info: RemoteLegacyInfo): LegacyInfo => ({
+ contacts: info.contacts.map(normalizeLegacyContactRecord),
+ recoverSessions: info.recoverSessions.map(normalizeLegacyRecoverySession),
+ othersEmergencyContact: info.othersEmergencyContact.map(
+ normalizeLegacyContactRecord,
+ ),
+ othersRecoverySession: info.othersRecoverySession.map(
+ normalizeLegacyRecoverySession,
+ ),
+});
+
+export const legacyGetInfo = () =>
+ withLegacyClient(async (client) =>
+ normalizeLegacyInfo(await client.getInfo()),
+ );
+
+export const legacyPublicKey = (email: string) =>
+ withLegacyClient((client) => client.publicKey(email));
+
+export const legacyVerificationID = (email: string) =>
+ withLegacyClient(async (client) => {
+ const publicKey = await client.publicKey(email);
+ return publicKey ? client.verificationID(publicKey) : undefined;
+ });
+
+export const legacyAddContact = async (
+ email: string,
+ recoveryNoticeInDays?: number,
+) => {
+ await getUserRecoveryKey();
+ return withLegacyClient((client) =>
+ client.addContact(email, currentKeyAttributes(), recoveryNoticeInDays),
+ );
+};
+
+export const legacyUpdateContact = (
+ userID: number,
+ emergencyContactID: number,
+ state: LegacyContactState,
+) =>
+ withLegacyClient((client) =>
+ client.updateContact(BigInt(userID), BigInt(emergencyContactID), state),
+ );
+
+export const legacyUpdateRecoveryNotice = (
+ emergencyContactID: number,
+ recoveryNoticeInDays: number,
+) =>
+ withLegacyClient((client) =>
+ client.updateRecoveryNotice(
+ BigInt(emergencyContactID),
+ recoveryNoticeInDays,
+ ),
+ );
+
+export const legacyStartRecovery = (
+ userID: number,
+ emergencyContactID: number,
+) =>
+ withLegacyClient((client) =>
+ client.startRecovery(BigInt(userID), BigInt(emergencyContactID)),
+ );
+
+export const legacyStopRecovery = (
+ recoveryID: string,
+ userID: number,
+ emergencyContactID: number,
+) =>
+ withLegacyClient((client) =>
+ client.stopRecovery(
+ recoveryID,
+ BigInt(userID),
+ BigInt(emergencyContactID),
+ ),
+ );
+
+export const legacyRejectRecovery = (
+ recoveryID: string,
+ userID: number,
+ emergencyContactID: number,
+) =>
+ withLegacyClient((client) =>
+ client.rejectRecovery(
+ recoveryID,
+ BigInt(userID),
+ BigInt(emergencyContactID),
+ ),
+ );
+
+export const legacyChangePassword = (recoveryID: string, newPassword: string) =>
+ withLegacyClient((client) =>
+ client.changePassword(recoveryID, currentKeyAttributes(), newPassword),
+ );
diff --git a/web/packages/contacts/legacy/types.ts b/web/packages/contacts/legacy/types.ts
index 6643c4578c..2bee42ffab 100644
--- a/web/packages/contacts/legacy/types.ts
+++ b/web/packages/contacts/legacy/types.ts
@@ -2,7 +2,6 @@ export type {
LegacyContactRecord,
LegacyContactState,
LegacyInfo,
- LegacyRecoveryBundle,
LegacyRecoverySession,
LegacyRecoveryStatus,
LegacyUser,
diff --git a/web/packages/contacts/package.json b/web/packages/contacts/package.json
index 10ad3bec80..54b5870104 100644
--- a/web/packages/contacts/package.json
+++ b/web/packages/contacts/package.json
@@ -1,5 +1,5 @@
{
- "name": "ente-contacts-web",
+ "name": "ente-contacts",
"version": "0.0.0",
"private": true,
"main": "./index.ts",
@@ -12,7 +12,7 @@
"@mui/material": "9.3.1",
"ente-accounts": "*",
"ente-base": "*",
- "ente-core-wasm": "*",
+ "ente-legacy-wasm": "*",
"react": "19.2.7",
"zod": "4.4.3"
},
diff --git a/web/packages/contacts/types.ts b/web/packages/contacts/types.ts
index 8e791d7c1a..ef59ca4e00 100644
--- a/web/packages/contacts/types.ts
+++ b/web/packages/contacts/types.ts
@@ -79,8 +79,3 @@ export interface LegacyInfo {
othersEmergencyContact: LegacyContactRecord[];
othersRecoverySession: LegacyRecoverySession[];
}
-
-export interface LegacyRecoveryBundle {
- recoveryKey: string;
- userKeyAttributes: Record<string, unknown>;
-}
diff --git a/web/packages/gallery/components/viewer/CommentsSidebar.tsx b/web/packages/gallery/components/viewer/CommentsSidebar.tsx
index 176622bca8..f0a0e69282 100644
--- a/web/packages/gallery/components/viewer/CommentsSidebar.tsx
+++ b/web/packages/gallery/components/viewer/CommentsSidebar.tsx
@@ -17,7 +17,7 @@ import log from "ente-base/log";
import {
useResolvedContactAvatar,
useResolvedContactDisplay,
-} from "ente-contacts-web";
+} from "ente-contacts";
import { downloadManager } from "ente-gallery/services/download";
import { getAvatarColor } from "ente-gallery/utils/avatar-colors";
import type { EnteFile } from "ente-media/file";
diff --git a/web/packages/gallery/components/viewer/LikesSidebar.tsx b/web/packages/gallery/components/viewer/LikesSidebar.tsx
index 5ebbe0f4de..7f056e3624 100644
--- a/web/packages/gallery/components/viewer/LikesSidebar.tsx
+++ b/web/packages/gallery/components/viewer/LikesSidebar.tsx
@@ -11,7 +11,7 @@ import {
} from "@mui/material";
import type { ModalVisibilityProps } from "ente-base/components/utils/modal";
import log from "ente-base/log";
-import { useResolvedContactAvatar } from "ente-contacts-web";
+import { useResolvedContactAvatar } from "ente-contacts";
import { downloadManager } from "ente-gallery/services/download";
import { getAvatarColor } from "ente-gallery/utils/avatar-colors";
import type { EnteFile } from "ente-media/file";
diff --git a/web/packages/gallery/package.json b/web/packages/gallery/package.json
index 99c3ab3c34..66fa17b128 100644
--- a/web/packages/gallery/package.json
+++ b/web/packages/gallery/package.json
@@ -9,7 +9,7 @@
"bs58": "6.0.0",
"ente-accounts": "*",
"ente-base": "*",
- "ente-contacts-web": "*",
+ "ente-contacts": "*",
"ente-utils": "*",
"exifreader": "4.40.3",
"hls-video-element": "1.5.11",
diff --git a/web/packages/wasm/legacy/authenticated.ts b/web/packages/wasm/legacy/authenticated.ts
new file mode 100644
index 0000000000..93996e9033
--- /dev/null
+++ b/web/packages/wasm/legacy/authenticated.ts
@@ -0,0 +1,2 @@
+export const openLegacy = async (input: unknown) =>
+ (await import("./pkg/ente_legacy_wasm")).openLegacy(input);
diff --git a/web/packages/wasm/legacy/package.json b/web/packages/wasm/legacy/package.json
index 14e9dac984..cc496cacf4 100644
--- a/web/packages/wasm/legacy/package.json
+++ b/web/packages/wasm/legacy/package.json
@@ -6,6 +6,10 @@
".": {
"types": "./index.ts",
"import": "./index.ts"
+ },
+ "./authenticated": {
+ "types": "./authenticated.ts",
+ "import": "./authenticated.ts"
}
},
"module": "./index.ts",
diff --git a/web/packages/wasm/locker/eslint.config.mjs b/web/packages/wasm/locker/eslint.config.mjs
new file mode 100644
index 0000000000..e6c7d4d3b0
--- /dev/null
+++ b/web/packages/wasm/locker/eslint.config.mjs
@@ -0,0 +1,3 @@
+import config from "ente-build-config/eslintrc-base.mjs";
+
+export default [...config, { ignores: ["pkg/"] }];
diff --git a/web/packages/wasm/locker/index.ts b/web/packages/wasm/locker/index.ts
new file mode 100644
index 0000000000..901bc78a02
--- /dev/null
+++ b/web/packages/wasm/locker/index.ts
@@ -0,0 +1,2 @@
+export const openContacts = async (input: unknown) =>
+ (await import("./pkg/ente_locker_wasm")).openContacts(input);
diff --git a/web/packages/wasm/locker/package.json b/web/packages/wasm/locker/package.json
new file mode 100644
index 0000000000..d9f72e95bb
--- /dev/null
+++ b/web/packages/wasm/locker/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "ente-locker-wasm",
+ "version": "0.0.0",
+ "private": true,
+ "exports": {
+ ".": {
+ "types": "./index.ts",
+ "import": "./index.ts"
+ }
+ },
+ "module": "./index.ts",
+ "types": "./index.ts",
+ "scripts": {
+ "build": "wasm-pack build ../../../../rust/bindings/wasm/locker --target bundler --out-dir ../../../../web/packages/wasm/locker/pkg --no-pack"
+ },
+ "devDependencies": {
+ "ente-build-config": "*",
+ "wasm-pack": "0.15.0"
+ }
+}
diff --git a/web/packages/wasm/locker/tsconfig.json b/web/packages/wasm/locker/tsconfig.json
new file mode 100644
index 0000000000..3f3b6cd165
--- /dev/null
+++ b/web/packages/wasm/locker/tsconfig.json
@@ -0,0 +1 @@
+{ "extends": "ente-build-config/tsconfig-typecheck.json", "include": ["."] }
diff --git a/web/packages/wasm/photos/eslint.config.mjs b/web/packages/wasm/photos/eslint.config.mjs
new file mode 100644
index 0000000000..e6c7d4d3b0
--- /dev/null
+++ b/web/packages/wasm/photos/eslint.config.mjs
@@ -0,0 +1,3 @@
+import config from "ente-build-config/eslintrc-base.mjs";
+
+export default [...config, { ignores: ["pkg/"] }];
diff --git a/web/packages/wasm/photos/index.ts b/web/packages/wasm/photos/index.ts
new file mode 100644
index 0000000000..2183624bc4
--- /dev/null
+++ b/web/packages/wasm/photos/index.ts
@@ -0,0 +1,2 @@
+export const openContacts = async (input: unknown) =>
+ (await import("./pkg/ente_photos_wasm")).openContacts(input);
diff --git a/web/packages/wasm/photos/package.json b/web/packages/wasm/photos/package.json
new file mode 100644
index 0000000000..6c2ea3401f
--- /dev/null
+++ b/web/packages/wasm/photos/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "ente-photos-wasm",
+ "version": "0.0.0",
+ "private": true,
+ "exports": {
+ ".": {
+ "types": "./index.ts",
+ "import": "./index.ts"
+ }
+ },
+ "module": "./index.ts",
+ "types": "./index.ts",
+ "scripts": {
+ "build": "wasm-pack build ../../../../rust/bindings/wasm/photos --target bundler --out-dir ../../../../web/packages/wasm/photos/pkg --no-pack"
+ },
+ "devDependencies": {
+ "ente-build-config": "*",
+ "wasm-pack": "0.15.0"
+ }
+}
diff --git a/web/packages/wasm/photos/tsconfig.json b/web/packages/wasm/photos/tsconfig.json
new file mode 100644
index 0000000000..3f3b6cd165
--- /dev/null
+++ b/web/packages/wasm/photos/tsconfig.json
@@ -0,0 +1 @@
+{ "extends": "ente-build-config/tsconfig-typecheck.json", "include": ["."] }