Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add Rust-backed legacy recovery to Locker web

Neeraj Gupta9c4ec3bbfa04
diff --git a/mobile/packages/rust/rust/Cargo.lock b/mobile/packages/rust/rust/Cargo.lock
index d526f3c545..07b3bffd1b 100644
--- a/mobile/packages/rust/rust/Cargo.lock
+++ b/mobile/packages/rust/rust/Cargo.lock
@@ -106,6 +106,12 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+[[package]]
+name = "autocfg"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
+
[[package]]
name = "backtrace"
version = "0.3.76"
@@ -445,7 +451,9 @@ dependencies = [
"md-5",
"serde",
"serde_json",
+ "sha2",
"thiserror",
+ "uuid",
]
[[package]]
@@ -465,6 +473,8 @@ dependencies = [
"salsa20",
"serde",
"serde_json",
+ "sha2",
+ "srp",
"subtle",
"thiserror",
"x25519-dalek",
@@ -557,6 +567,12 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
[[package]]
name = "form_urlencoded"
version = "1.2.2"
@@ -687,11 +703,24 @@ dependencies = [
"cfg-if",
"js-sys",
"libc",
- "r-efi",
+ "r-efi 5.3.0",
"wasip2",
"wasm-bindgen",
]
+[[package]]
+name = "getrandom"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 6.0.0",
+ "wasip2",
+ "wasip3",
+]
+
[[package]]
name = "gimli"
version = "0.32.3"
@@ -723,12 +752,27 @@ version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash",
+]
+
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
[[package]]
name = "hermit-abi"
version = "0.5.2"
@@ -936,6 +980,12 @@ dependencies = [
"zerovec",
]
+[[package]]
+name = "id-arena"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
+
[[package]]
name = "idna"
version = "1.1.0"
@@ -965,6 +1015,8 @@ checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2"
dependencies = [
"equivalent",
"hashbrown 0.16.1",
+ "serde",
+ "serde_core",
]
[[package]]
@@ -1015,6 +1067,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+[[package]]
+name = "leb128fmt"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+
[[package]]
name = "libc"
version = "0.2.178"
@@ -1090,6 +1148,34 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "num-bigint"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-integer"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
[[package]]
name = "num_cpus"
version = "1.17.0"
@@ -1215,6 +1301,16 @@ dependencies = [
"zerocopy",
]
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.103"
@@ -1294,6 +1390,12 @@ version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
[[package]]
name = "rand"
version = "0.9.2"
@@ -1614,6 +1716,17 @@ dependencies = [
"serde",
]
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
[[package]]
name = "shlex"
version = "1.3.0"
@@ -1642,6 +1755,19 @@ dependencies = [
"windows-sys 0.60.2",
]
+[[package]]
+name = "srp"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cdd40049b29ab1315ccba7ffcf1eece8162982eab14edfac3cf2c2ffab18193"
+dependencies = [
+ "digest",
+ "generic-array",
+ "lazy_static",
+ "num-bigint",
+ "subtle",
+]
+
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@@ -1888,6 +2014,12 @@ dependencies = [
"tinyvec",
]
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
[[package]]
name = "universal-hash"
version = "0.5.1"
@@ -1922,6 +2054,17 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+[[package]]
+name = "uuid"
+version = "1.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9"
+dependencies = [
+ "getrandom 0.4.2",
+ "js-sys",
+ "wasm-bindgen",
+]
+
[[package]]
name = "version_check"
version = "0.9.5"
@@ -1949,7 +2092,16 @@ version = "1.0.1+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
dependencies = [
- "wit-bindgen",
+ "wit-bindgen 0.46.0",
+]
+
+[[package]]
+name = "wasip3"
+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
+dependencies = [
+ "wit-bindgen 0.51.0",
]
[[package]]
@@ -2010,6 +2162,40 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "wasm-encoder"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
+dependencies = [
+ "leb128fmt",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.15.5",
+ "indexmap",
+ "semver",
+]
+
[[package]]
name = "web-sys"
version = "0.3.83"
@@ -2236,6 +2422,94 @@ version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+dependencies = [
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "prettyplease",
+ "syn",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
+dependencies = [
+ "anyhow",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+ "wasmparser",
+]
+
[[package]]
name = "writeable"
version = "0.6.2"
diff --git a/mobile/packages/rust/rust/src/api/contacts.rs b/mobile/packages/rust/rust/src/api/contacts.rs
index 095722e5c1..58b04144fc 100644
--- a/mobile/packages/rust/rust/src/api/contacts.rs
+++ b/mobile/packages/rust/rust/src/api/contacts.rs
@@ -40,6 +40,11 @@ pub enum ContactsError {
/// Cryptographic error description.
message: String,
},
+ /// Authentication or recovery crypto operation failed.
+ Auth {
+ /// Authentication error description.
+ message: String,
+ },
/// Input validation failed.
InvalidInput {
/// Validation failure description.
@@ -71,6 +76,9 @@ impl From<CoreContactsError> for ContactsError {
CoreContactsError::Crypto(message) => ContactsError::Crypto {
message: message.to_string(),
},
+ CoreContactsError::Auth(message) => ContactsError::Auth {
+ message: message.to_string(),
+ },
CoreContactsError::InvalidInput(message) => ContactsError::InvalidInput { message },
CoreContactsError::MissingEncryptedData => ContactsError::MissingEncryptedData,
CoreContactsError::MissingEncryptedKey => ContactsError::MissingEncryptedKey,
@@ -177,7 +185,7 @@ pub enum RootKeySource {
Cache,
/// Fetched the wrapped root key from the server.
Server,
- /// Created a new wrapped root key on the server.
+ /// Created a new wrapped root key locally; it is confirmed on first write.
Created,
}
diff --git a/rust/contacts/Cargo.lock b/rust/contacts/Cargo.lock
index e932814a4b..356e6f044d 100644
--- a/rust/contacts/Cargo.lock
+++ b/rust/contacts/Cargo.lock
@@ -647,8 +647,10 @@ dependencies = [
"reqwest",
"serde",
"serde_json",
+ "sha2",
"thiserror 2.0.18",
"tokio",
+ "uuid",
"zeroize",
]
diff --git a/rust/contacts/Cargo.toml b/rust/contacts/Cargo.toml
index 091bd63b53..52d9db4451 100644
--- a/rust/contacts/Cargo.toml
+++ b/rust/contacts/Cargo.toml
@@ -4,11 +4,13 @@ version = "0.0.1"
edition = "2024"
[dependencies]
-ente-core = { path = "../core" }
+ente-core = { path = "../core", features = ["srp"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
md-5 = "0.10"
+sha2 = "0.10"
+uuid = { version = "1", features = ["v4", "js"] }
[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
diff --git a/rust/contacts/src/client.rs b/rust/contacts/src/client.rs
index 089a199e24..bcd2e4dca0 100644
--- a/rust/contacts/src/client.rs
+++ b/rust/contacts/src/client.rs
@@ -1,11 +1,22 @@
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};
-use ente_core::crypto::{SecretVec, keys};
+use ente_core::auth::{self, KeyAttributes, SrpSession};
+use ente_core::crypto::{self, SecretVec, keys, sealed, secretbox};
use ente_core::http::{Error as HttpError, HttpClient, HttpConfig};
+use sha2::{Digest, Sha256};
+use uuid::Uuid;
use crate::crypto as contacts_crypto;
use crate::error::{ContactsError, Result};
+use crate::legacy_models::{LegacyContactState, LegacyInfo, LegacyRecoveryBundle};
+use crate::legacy_transport::{
+ LegacyAddContactRequest, LegacyChangePasswordRequest, LegacyChangePasswordResponse,
+ LegacyContactIdentifier, LegacyInfoResponse, LegacyInitChangePasswordRequest,
+ LegacyPublicKeyResponse, LegacyRecoveryIdentifier, LegacyRecoveryInfoResponse,
+ LegacySetupSrpRequest, LegacySetupSrpResponse, LegacyUpdateContactRequest,
+ LegacyUpdateRecoveryNoticeRequest, LegacyUpdateSrpAndKeysRequest, LegacyUpdatedKeyAttr,
+};
use crate::models::{AttachmentType, ContactData, ContactRecord, WrappedRootContactKey};
use crate::transport::{
AttachmentUploadUrlRequest, AttachmentUploadUrlResponse, CommitAttachmentRequest,
@@ -95,28 +106,12 @@ impl ContactsCtx {
&generated_root_contact_key,
&input.master_key,
)?;
- if let Some(remote_root_key) =
- create_root_key(&http, &generated_wrapped_root_key).await?
- {
- let wrapped_root_key = wrapped_root_key_from_response(remote_root_key);
- let root_contact_key = contacts_crypto::decrypt_root_contact_key(
- &wrapped_root_key,
- &input.master_key,
- )?;
- (
- root_contact_key,
- wrapped_root_key,
- RootKeySource::Server,
- true,
- )
- } else {
- (
- generated_root_contact_key,
- generated_wrapped_root_key,
- RootKeySource::Created,
- true,
- )
- }
+ (
+ generated_root_contact_key,
+ generated_wrapped_root_key,
+ RootKeySource::Created,
+ false,
+ )
};
let ctx = Self {
@@ -411,6 +406,245 @@ impl ContactsCtx {
.await
}
+ pub async fn legacy_info(&self) -> Result<LegacyInfo> {
+ self.http
+ .get_json::<LegacyInfoResponse>("/emergency-contacts/info", &[])
+ .await
+ .map_err(Into::into)
+ .map_err(|error| with_http_context("legacy info fetch failed", error))
+ }
+
+ pub async fn legacy_public_key(&self, email: &str) -> Result<Option<String>> {
+ self.http
+ .get_json_optional::<LegacyPublicKeyResponse>(
+ "/users/public-key",
+ &[("email", email.trim().to_string())],
+ )
+ .await
+ .map(|response| response.map(|result| result.public_key))
+ .map_err(Into::into)
+ .map_err(|error| with_http_context("legacy public key fetch failed", error))
+ }
+
+ pub fn legacy_verification_id(&self, public_key_b64: &str) -> Result<String> {
+ let public_key = crypto::decode_b64(public_key_b64)?;
+ let digest = Sha256::digest(&public_key);
+ auth::recovery_key_to_mnemonic(&crypto::encode_b64(digest.as_slice())).map_err(Into::into)
+ }
+
+ pub async fn legacy_add_contact(
+ &self,
+ email: &str,
+ current_user_key_attrs: &KeyAttributes,
+ recovery_notice_in_days: Option<i32>,
+ ) -> Result<()> {
+ let public_key = self
+ .legacy_public_key(email)
+ .await?
+ .ok_or_else(|| ContactsError::InvalidInput("legacy contact is not on Ente".into()))?;
+ let recovery_key = self.current_recovery_key(current_user_key_attrs)?;
+ let recipient_public_key = crypto::decode_b64(&public_key)?;
+ let encrypted_key = sealed::seal(&recovery_key, &recipient_public_key)?;
+
+ self.http
+ .post_empty(
+ "/emergency-contacts/add",
+ &LegacyAddContactRequest {
+ email: email.trim().to_string(),
+ encrypted_key: crypto::encode_b64(&encrypted_key),
+ recovery_notice_in_days,
+ },
+ )
+ .await
+ .map_err(Into::into)
+ .map_err(|error| with_http_context("legacy contact add failed", error))
+ }
+
+ pub async fn legacy_update_contact(
+ &self,
+ user_id: i64,
+ emergency_contact_id: i64,
+ state: LegacyContactState,
+ ) -> Result<()> {
+ self.http
+ .post_empty(
+ "/emergency-contacts/update",
+ &LegacyUpdateContactRequest {
+ user_id,
+ emergency_contact_id,
+ state,
+ },
+ )
+ .await
+ .map_err(Into::into)
+ .map_err(|error| with_http_context("legacy contact update failed", error))
+ }
+
+ pub async fn legacy_update_recovery_notice(
+ &self,
+ emergency_contact_id: i64,
+ recovery_notice_in_days: i32,
+ ) -> Result<()> {
+ self.http
+ .post_empty(
+ "/emergency-contacts/update-recovery-notice",
+ &LegacyUpdateRecoveryNoticeRequest {
+ emergency_contact_id,
+ recovery_notice_in_days,
+ },
+ )
+ .await
+ .map_err(Into::into)
+ .map_err(|error| with_http_context("legacy recovery notice update failed", error))
+ }
+
+ pub async fn legacy_start_recovery(
+ &self,
+ user_id: i64,
+ emergency_contact_id: i64,
+ ) -> Result<()> {
+ self.legacy_contact_action(
+ "/emergency-contacts/start-recovery",
+ user_id,
+ emergency_contact_id,
+ "legacy recovery start failed",
+ )
+ .await
+ }
+
+ pub async fn legacy_stop_recovery(
+ &self,
+ recovery_id: &str,
+ user_id: i64,
+ emergency_contact_id: i64,
+ ) -> Result<()> {
+ self.legacy_recovery_action(
+ "/emergency-contacts/stop-recovery",
+ recovery_id,
+ user_id,
+ emergency_contact_id,
+ "legacy recovery stop failed",
+ )
+ .await
+ }
+
+ pub async fn legacy_reject_recovery(
+ &self,
+ recovery_id: &str,
+ user_id: i64,
+ emergency_contact_id: i64,
+ ) -> Result<()> {
+ self.legacy_recovery_action(
+ "/emergency-contacts/reject-recovery",
+ recovery_id,
+ user_id,
+ emergency_contact_id,
+ "legacy recovery reject failed",
+ )
+ .await
+ }
+
+ pub async fn legacy_approve_recovery(
+ &self,
+ recovery_id: &str,
+ user_id: i64,
+ emergency_contact_id: i64,
+ ) -> Result<()> {
+ self.legacy_recovery_action(
+ "/emergency-contacts/approve-recovery",
+ recovery_id,
+ user_id,
+ emergency_contact_id,
+ "legacy recovery approve failed",
+ )
+ .await
+ }
+
+ pub async fn legacy_recovery_bundle(
+ &self,
+ recovery_id: &str,
+ current_user_key_attrs: &KeyAttributes,
+ ) -> Result<LegacyRecoveryBundle> {
+ let response = self
+ .legacy_recovery_info(recovery_id)
+ .await
+ .map_err(|error| with_http_context("legacy recovery info fetch failed", error))?;
+ let recovery_key =
+ self.decrypt_legacy_recovery_key(&response.encrypted_key, current_user_key_attrs)?;
+
+ Ok(LegacyRecoveryBundle {
+ recovery_key: crypto::encode_hex(&recovery_key),
+ user_key_attributes: response.user_key_attr,
+ })
+ }
+
+ pub async fn legacy_change_password(
+ &self,
+ recovery_id: &str,
+ current_user_key_attrs: &KeyAttributes,
+ new_password: &str,
+ ) -> Result<()> {
+ let bundle = self
+ .legacy_recovery_bundle(recovery_id, current_user_key_attrs)
+ .await?;
+ let recovery_key = auth::recovery_key_from_mnemonic_or_hex(&bundle.recovery_key)?;
+ let target_master_key =
+ decrypt_master_key_with_recovery_key(&bundle.user_key_attributes, &recovery_key)?;
+ let (updated_key_attrs, _) = auth::generate_key_attributes_for_new_password(
+ &target_master_key,
+ &bundle.user_key_attributes,
+ new_password,
+ )?;
+ let srp_user_id = Uuid::new_v4().to_string();
+ let (mut srp_session, setup_request) =
+ password_reset_setup_request(&srp_user_id, new_password, &updated_key_attrs)?;
+ let init_response = self
+ .http
+ .post_json::<LegacySetupSrpResponse, _>(
+ "/emergency-contacts/init-change-password",
+ &LegacyInitChangePasswordRequest {
+ recovery_id: recovery_id.to_string(),
+ setup_srp_request: setup_request,
+ },
+ )
+ .await
+ .map_err(Into::into)
+ .map_err(|error| with_http_context("legacy password reset init failed", error))?;
+ let srp_m1 = srp_session_m1(&mut srp_session, &init_response)?;
+ let updated_key_attr = LegacyUpdatedKeyAttr {
+ kek_salt: updated_key_attrs.kek_salt.clone(),
+ encrypted_key: updated_key_attrs.encrypted_key.clone(),
+ key_decryption_nonce: updated_key_attrs.key_decryption_nonce.clone(),
+ mem_limit: updated_key_attrs.mem_limit.ok_or_else(|| {
+ ContactsError::InvalidInput("updated key attributes missing memLimit".into())
+ })?,
+ ops_limit: updated_key_attrs.ops_limit.ok_or_else(|| {
+ ContactsError::InvalidInput("updated key attributes missing opsLimit".into())
+ })?,
+ };
+
+ let change_response = self
+ .http
+ .post_json::<LegacyChangePasswordResponse, _>(
+ "/emergency-contacts/change-password",
+ &LegacyChangePasswordRequest {
+ recovery_id: recovery_id.to_string(),
+ update_srp_and_keys_request: LegacyUpdateSrpAndKeysRequest {
+ setup_id: init_response.setup_id,
+ srp_m1,
+ updated_key_attr,
+ },
+ },
+ )
+ .await
+ .map_err(Into::into)
+ .map_err(|error| with_http_context("legacy password reset failed", error))?;
+
+ let server_m2 = crypto::decode_b64(&change_response.srp_m2)?;
+ srp_session.verify_m2(&server_m2)?;
+ Ok(())
+ }
+
fn decode_contact(&self, entity: ContactEntityResponse) -> Result<ContactRecord> {
if entity.is_deleted {
return Ok(ContactRecord {
@@ -471,6 +705,86 @@ impl ContactsCtx {
self.root_key_confirmed.store(true, Ordering::Release);
Ok(())
}
+
+ async fn legacy_contact_action(
+ &self,
+ path: &str,
+ user_id: i64,
+ emergency_contact_id: i64,
+ error_context: &'static str,
+ ) -> Result<()> {
+ self.http
+ .post_empty(
+ path,
+ &LegacyContactIdentifier {
+ user_id,
+ emergency_contact_id,
+ },
+ )
+ .await
+ .map_err(Into::into)
+ .map_err(|error| with_http_context(error_context, error))
+ }
+
+ async fn legacy_recovery_action(
+ &self,
+ path: &str,
+ recovery_id: &str,
+ user_id: i64,
+ emergency_contact_id: i64,
+ error_context: &'static str,
+ ) -> Result<()> {
+ self.http
+ .post_empty(
+ path,
+ &LegacyRecoveryIdentifier {
+ id: recovery_id.to_string(),
+ user_id,
+ emergency_contact_id,
+ },
+ )
+ .await
+ .map_err(Into::into)
+ .map_err(|error| with_http_context(error_context, error))
+ }
+
+ async fn legacy_recovery_info(&self, recovery_id: &str) -> Result<LegacyRecoveryInfoResponse> {
+ self.http
+ .get_json::<LegacyRecoveryInfoResponse>(
+ &format!("/emergency-contacts/recovery-info/{recovery_id}"),
+ &[],
+ )
+ .await
+ .map_err(Into::into)
+ }
+
+ fn current_recovery_key(&self, current_user_key_attrs: &KeyAttributes) -> Result<SecretVec> {
+ let master_key = self.master_key.read().expect("master key lock poisoned");
+ let recovery_key_hex = auth::get_recovery_key(&master_key, current_user_key_attrs)?;
+ Ok(SecretVec::new(crypto::decode_hex(&recovery_key_hex)?))
+ }
+
+ fn decrypt_legacy_recovery_key(
+ &self,
+ encrypted_key_b64: &str,
+ current_user_key_attrs: &KeyAttributes,
+ ) -> Result<SecretVec> {
+ let public_key = crypto::decode_b64(&current_user_key_attrs.public_key)?;
+ let encrypted_key = crypto::decode_b64(encrypted_key_b64)?;
+ let secret_key = self.current_secret_key(current_user_key_attrs)?;
+ let decrypted = sealed::open(&encrypted_key, &public_key, &secret_key)?;
+ Ok(SecretVec::new(decrypted))
+ }
+
+ fn current_secret_key(&self, current_user_key_attrs: &KeyAttributes) -> Result<SecretVec> {
+ let encrypted_secret_key = crypto::decode_b64(&current_user_key_attrs.encrypted_secret_key)?;
+ let secret_key_nonce =
+ crypto::decode_b64(&current_user_key_attrs.secret_key_decryption_nonce)?;
+ let master_key = self.master_key.read().expect("master key lock poisoned");
+ let secret_key =
+ secretbox::decrypt(&encrypted_secret_key, &secret_key_nonce, &master_key)?;
+ Ok(SecretVec::new(secret_key))
+ }
}
async fn fetch_root_key(http: &HttpClient) -> Result<Option<RootKeyResponse>> {
@@ -533,3 +847,70 @@ fn with_http_context(context: &'static str, error: ContactsError) -> ContactsErr
other => other,
}
}
+
+fn decrypt_master_key_with_recovery_key(
+ key_attributes: &KeyAttributes,
+ recovery_key: &[u8],
+) -> Result<SecretVec> {
+ let encrypted_master_key = key_attributes
+ .master_key_encrypted_with_recovery_key
+ .as_ref()
+ .ok_or_else(|| {
+ ContactsError::InvalidInput(
+ "target key attributes missing masterKeyEncryptedWithRecoveryKey".into(),
+ )
+ })?;
+ let master_key_nonce = key_attributes
+ .master_key_decryption_nonce
+ .as_ref()
+ .ok_or_else(|| {
+ ContactsError::InvalidInput(
+ "target key attributes missing masterKeyDecryptionNonce".into(),
+ )
+ })?;
+ let encrypted_master_key = crypto::decode_b64(encrypted_master_key)?;
+ let master_key_nonce = crypto::decode_b64(master_key_nonce)?;
+ secretbox::decrypt(&encrypted_master_key, &master_key_nonce, recovery_key)
+ .map(SecretVec::new)
+ .map_err(Into::into)
+}
+
+fn password_reset_setup_request(
+ srp_user_id: &str,
+ new_password: &str,
+ updated_key_attrs: &KeyAttributes,
+) -> Result<(SrpSession, LegacySetupSrpRequest)> {
+ let mem_limit = updated_key_attrs
+ .mem_limit
+ .ok_or_else(|| ContactsError::InvalidInput("updated key attributes missing memLimit".into()))?;
+ let ops_limit = updated_key_attrs
+ .ops_limit
+ .ok_or_else(|| ContactsError::InvalidInput("updated key attributes missing opsLimit".into()))?;
+ let kek = auth::derive_kek(new_password, &updated_key_attrs.kek_salt, mem_limit, ops_limit)?;
+ let generated_srp = auth::generate_srp_setup(&kek, srp_user_id)?;
+ let srp_session = SrpSession::new(
+ srp_user_id,
+ &generated_srp.srp_salt,
+ &generated_srp.login_sub_key,
+ )?;
+ let srp_a = crypto::encode_b64(&srp_session.public_a());
+
+ Ok((
+ srp_session,
+ LegacySetupSrpRequest {
+ srp_user_id: srp_user_id.to_string(),
+ srp_salt: crypto::encode_b64(&generated_srp.srp_salt),
+ srp_verifier: crypto::encode_b64(&generated_srp.srp_verifier),
+ srp_a,
+ },
+ ))
+}
+
+fn srp_session_m1(
+ srp_session: &mut SrpSession,
+ init_response: &LegacySetupSrpResponse,
+) -> Result<String> {
+ let server_b = crypto::decode_b64(&init_response.srp_b)?;
+ let client_m1 = srp_session.compute_m1(&server_b)?;
+ Ok(crypto::encode_b64(&client_m1))
+}
diff --git a/rust/contacts/src/error.rs b/rust/contacts/src/error.rs
index 059ce1b4e4..89c38b6d60 100644
--- a/rust/contacts/src/error.rs
+++ b/rust/contacts/src/error.rs
@@ -1,4 +1,4 @@
-use ente_core::{crypto::CryptoError, http::Error as HttpError};
+use ente_core::{auth::AuthError, crypto::CryptoError, http::Error as HttpError};
use thiserror::Error;
#[derive(Debug, Error)]
@@ -9,6 +9,9 @@ pub enum ContactsError {
#[error(transparent)]
Crypto(#[from] CryptoError),
+ #[error(transparent)]
+ Auth(#[from] AuthError),
+
#[error("invalid input: {0}")]
InvalidInput(String),
diff --git a/rust/contacts/src/legacy_models.rs b/rust/contacts/src/legacy_models.rs
new file mode 100644
index 0000000000..a006c437c6
--- /dev/null
+++ b/rust/contacts/src/legacy_models.rs
@@ -0,0 +1,68 @@
+use ente_core::auth::KeyAttributes;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum LegacyContactState {
+ Invited,
+ Revoked,
+ Accepted,
+ ContactLeft,
+ ContactDenied,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum LegacyRecoveryStatus {
+ Initiated,
+ Waiting,
+ Rejected,
+ Recovered,
+ Stopped,
+ Ready,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyUser {
+ pub id: i64,
+ pub email: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyContactRecord {
+ pub user: LegacyUser,
+ pub emergency_contact: LegacyUser,
+ pub state: LegacyContactState,
+ pub recovery_notice_in_days: i32,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyRecoverySession {
+ pub id: String,
+ pub user: LegacyUser,
+ pub emergency_contact: LegacyUser,
+ pub status: LegacyRecoveryStatus,
+ pub wait_till: i64,
+ pub created_at: i64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyInfo {
+ pub contacts: Vec<LegacyContactRecord>,
+ #[serde(rename = "recoverSessions")]
+ pub recover_sessions: Vec<LegacyRecoverySession>,
+ pub others_emergency_contact: Vec<LegacyContactRecord>,
+ #[serde(rename = "othersRecoverySession")]
+ pub others_recovery_session: Vec<LegacyRecoverySession>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyRecoveryBundle {
+ pub recovery_key: String,
+ pub user_key_attributes: KeyAttributes,
+}
diff --git a/rust/contacts/src/legacy_transport.rs b/rust/contacts/src/legacy_transport.rs
new file mode 100644
index 0000000000..90c9e238fa
--- /dev/null
+++ b/rust/contacts/src/legacy_transport.rs
@@ -0,0 +1,124 @@
+use ente_core::auth::KeyAttributes;
+use serde::{Deserialize, Serialize};
+
+use crate::legacy_models::{LegacyContactState, LegacyInfo};
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyPublicKeyResponse {
+ pub public_key: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyAddContactRequest {
+ pub email: String,
+ pub encrypted_key: String,
+ pub recovery_notice_in_days: Option<i32>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyUpdateContactRequest {
+ pub user_id: i64,
+ pub emergency_contact_id: i64,
+ pub state: LegacyContactState,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyUpdateRecoveryNoticeRequest {
+ pub emergency_contact_id: i64,
+ pub recovery_notice_in_days: i32,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyContactIdentifier {
+ pub user_id: i64,
+ pub emergency_contact_id: i64,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyRecoveryIdentifier {
+ pub id: String,
+ pub user_id: i64,
+ pub emergency_contact_id: i64,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyRecoveryInfoResponse {
+ pub encrypted_key: String,
+ #[serde(rename = "userKeyAttr")]
+ pub user_key_attr: KeyAttributes,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacySetupSrpRequest {
+ #[serde(rename = "srpUserID")]
+ pub srp_user_id: String,
+ pub srp_salt: String,
+ pub srp_verifier: String,
+ #[serde(rename = "srpA")]
+ pub srp_a: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyInitChangePasswordRequest {
+ pub recovery_id: String,
+ #[serde(rename = "setupSRPRequest")]
+ pub setup_srp_request: LegacySetupSrpRequest,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacySetupSrpResponse {
+ #[serde(rename = "setupID")]
+ pub setup_id: String,
+ #[serde(rename = "srpB")]
+ pub srp_b: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyUpdatedKeyAttr {
+ pub kek_salt: String,
+ pub encrypted_key: String,
+ pub key_decryption_nonce: String,
+ pub mem_limit: u32,
+ pub ops_limit: u32,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyUpdateSrpAndKeysRequest {
+ #[serde(rename = "setupID")]
+ pub setup_id: String,
+ #[serde(rename = "srpM1")]
+ pub srp_m1: String,
+ #[serde(rename = "updatedKeyAttr")]
+ pub updated_key_attr: LegacyUpdatedKeyAttr,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyChangePasswordRequest {
+ pub recovery_id: String,
+ #[serde(rename = "updateSrpAndKeysRequest")]
+ pub update_srp_and_keys_request: LegacyUpdateSrpAndKeysRequest,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LegacyChangePasswordResponse {
+ #[serde(rename = "setupID")]
+ pub setup_id: String,
+ #[serde(rename = "srpM2")]
+ pub srp_m2: String,
+}
+
+pub type LegacyInfoResponse = LegacyInfo;
diff --git a/rust/contacts/src/lib.rs b/rust/contacts/src/lib.rs
index 1c6bb4fdf8..7d36d0071f 100644
--- a/rust/contacts/src/lib.rs
+++ b/rust/contacts/src/lib.rs
@@ -1,9 +1,15 @@
pub mod client;
pub mod crypto;
pub mod error;
+pub mod legacy_models;
+pub mod legacy_transport;
pub mod models;
pub mod transport;
pub use client::{ContactsCtx, OpenContactsCtxInput, OpenContactsCtxResult, RootKeySource};
pub use error::{ContactsError, Result};
+pub use legacy_models::{
+ LegacyContactRecord, LegacyContactState, LegacyInfo, LegacyRecoveryBundle,
+ LegacyRecoverySession, LegacyRecoveryStatus, LegacyUser,
+};
pub use models::{AttachmentType, ContactData, ContactRecord, WrappedRootContactKey};
diff --git a/rust/core/src/http.rs b/rust/core/src/http.rs
index 42efd8ce38..164f1b01b9 100644
--- a/rust/core/src/http.rs
+++ b/rust/core/src/http.rs
@@ -631,6 +631,7 @@ impl HttpClient {
fn build_public_headers(&self) -> Result<HeaderMap, Error> {
let mut headers = HeaderMap::new();
+ #[cfg(not(target_arch = "wasm32"))]
if let Some(user_agent) = &self.user_agent {
let value =
HeaderValue::from_str(user_agent).map_err(|e| Error::Parse(e.to_string()))?;
diff --git a/web/apps/locker/src/components/LockerLegacyDrawer.tsx b/web/apps/locker/src/components/LockerLegacyDrawer.tsx
new file mode 100644
index 0000000000..992b3ef846
--- /dev/null
+++ b/web/apps/locker/src/components/LockerLegacyDrawer.tsx
@@ -0,0 +1,23 @@
+import {
+ LegacyDrawerContent,
+ type LegacySuggestedUser,
+} from "ente-contacts-web/legacy";
+import React from "react";
+import {
+ LockerTitledNestedSidebarDrawer,
+ type LockerNestedSidebarDrawerVisibilityProps,
+} from "./LockerSidebarShell";
+
+export const LockerLegacyDrawer: React.FC<
+ LockerNestedSidebarDrawerVisibilityProps & {
+ suggestedUsers: LegacySuggestedUser[];
+ }
+> = ({ open, onClose, onRootClose, suggestedUsers }) => (
+ <LockerTitledNestedSidebarDrawer
+ {...{ open, onClose, onRootClose }}
+ title="Legacy"
+ caption="Legacy allows trusted contacts to access your account in your absence."
+ >
+ <LegacyDrawerContent open={open} suggestedUsers={suggestedUsers} />
+ </LockerTitledNestedSidebarDrawer>
+);
diff --git a/web/apps/locker/src/components/LockerSidebar.tsx b/web/apps/locker/src/components/LockerSidebar.tsx
index 43df48aaa5..be0193621a 100644
--- a/web/apps/locker/src/components/LockerSidebar.tsx
+++ b/web/apps/locker/src/components/LockerSidebar.tsx
@@ -1,5 +1,6 @@
import {
Delete02Icon,
+ FavouriteIcon,
HelpCircleIcon,
Home01Icon,
InformationCircleIcon,
@@ -12,8 +13,13 @@ import CloseIcon from "@mui/icons-material/Close";
import { Box, IconButton, Stack, Typography, useTheme } from "@mui/material";
import { EnteLogo } from "ente-base/components/EnteLogo";
import { useBaseContext } from "ente-base/context";
+import {
+ mergeLegacySuggestedUsers,
+ type LegacySuggestedUser,
+} from "ente-contacts-web/legacy";
import { t } from "i18next";
-import React, { useEffect, useState } from "react";
+import dynamic from "next/dynamic";
+import React, { useEffect, useMemo, useState } from "react";
import type { LockerCollection } from "types";
import { visibleLockerCollections } from "types";
import { LockerAboutDrawer } from "./LockerAboutDrawer";
@@ -23,6 +29,14 @@ import { LockerSidebarDrawer } from "./LockerSidebarShell";
import { LockerSocialFooter } from "./LockerSocialFooter";
import { LockerSupportDrawer } from "./LockerSupportDrawer";
+const LockerLegacyDrawer = dynamic(
+ () =>
+ import("./LockerLegacyDrawer").then(
+ ({ LockerLegacyDrawer }) => LockerLegacyDrawer,
+ ),
+ { ssr: false },
+);
+
interface LockerSidebarProps {
open: boolean;
onClose: () => void;
@@ -72,8 +86,26 @@ export const LockerSidebar: React.FC<LockerSidebarProps> = ({
0,
);
const [isAccountOpen, setIsAccountOpen] = useState(false);
+ const [isLegacyOpen, setIsLegacyOpen] = useState(false);
const [isSupportOpen, setIsSupportOpen] = useState(false);
const [isAboutOpen, setIsAboutOpen] = useState(false);
+ const legacySuggestedUsers = useMemo(() => {
+ const participants: LegacySuggestedUser[] = collections.flatMap(
+ (collection) =>
+ [collection.owner, ...collection.sharees]
+ .filter(
+ (
+ participant,
+ ): participant is { id: number; email: string } =>
+ !!participant.email?.trim(),
+ )
+ .map((participant) => ({
+ id: participant.id,
+ email: participant.email,
+ })),
+ );
+ return mergeLegacySuggestedUsers(participants);
+ }, [collections]);
const maxFileCount = userDetails
? Math.max(userDetails.lockerFileLimit, 1)
@@ -96,6 +128,7 @@ export const LockerSidebar: React.FC<LockerSidebarProps> = ({
useEffect(() => {
if (!open) {
setIsAccountOpen(false);
+ setIsLegacyOpen(false);
setIsSupportOpen(false);
setIsAboutOpen(false);
}
@@ -351,6 +384,12 @@ export const LockerSidebar: React.FC<LockerSidebarProps> = ({
endIcon={<ChevronRightIcon />}
onClick={() => setIsAccountOpen(true)}
/>
+ <LockerSidebarCardButton
+ icon={FavouriteIcon}
+ label="Legacy"
+ endIcon={<ChevronRightIcon />}
+ onClick={() => setIsLegacyOpen(true)}
+ />
<LockerSidebarCardButton
icon={HelpCircleIcon}
label={t("help_and_support")}
@@ -401,6 +440,12 @@ export const LockerSidebar: React.FC<LockerSidebarProps> = ({
onClose={() => setIsAccountOpen(false)}
onRootClose={onClose}
/>
+ <LockerLegacyDrawer
+ open={isLegacyOpen}
+ onClose={() => setIsLegacyOpen(false)}
+ onRootClose={onClose}
+ suggestedUsers={legacySuggestedUsers}
+ />
<LockerSupportDrawer
open={isSupportOpen}
onClose={() => setIsSupportOpen(false)}
diff --git a/web/apps/locker/src/components/LockerSidebarShell.tsx b/web/apps/locker/src/components/LockerSidebarShell.tsx
index 1294d5d454..73f45076e0 100644
--- a/web/apps/locker/src/components/LockerSidebarShell.tsx
+++ b/web/apps/locker/src/components/LockerSidebarShell.tsx
@@ -1,4 +1,4 @@
-import ArrowBackIcon from "@mui/icons-material/ArrowBack";
+import ArrowBackOutlinedIcon from "@mui/icons-material/ArrowBackOutlined";
import CloseIcon from "@mui/icons-material/Close";
import {
Box,
@@ -112,7 +112,7 @@ const LockerSidebarTitlebar: React.FC<LockerSidebarTitlebarProps> = ({
<Stack sx={{ gap: "4px" }}>
<Stack direction="row" sx={{ justifyContent: "space-between" }}>
<IconButton onClick={onClose} color="primary">
- <ArrowBackIcon />
+ <ArrowBackOutlinedIcon />
</IconButton>
<Stack direction="row" sx={{ gap: "4px" }}>
{actionButton && actionButton}
diff --git a/web/packages/contacts/index.ts b/web/packages/contacts/index.ts
index 5dc2a54ae7..bc59d90189 100644
--- a/web/packages/contacts/index.ts
+++ b/web/packages/contacts/index.ts
@@ -1,8 +1,12 @@
+import { savedKeyAttributes } from "ente-accounts-rs/services/accounts-db";
+import { getUserRecoveryKey } from "ente-accounts-rs/services/recovery-key";
+import { masterKeyFromSession } from "ente-accounts-rs/services/session-storage";
+import { ensureLocalUser } from "ente-accounts-rs/services/user";
import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
import log from "ente-base/log";
import { apiOrigin } from "ente-base/origins";
import { savedAuthToken } from "ente-base/token";
-import { contacts_open_ctx, type ContactsCtxHandle } from "ente-wasm";
+import type { ContactsCtxHandle } from "ente-wasm";
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
import {
saveContactDisplayRecords,
@@ -21,6 +25,24 @@ import type {
ContactDisplayRecord,
ContactLookup,
ContactsDisplaySnapshot,
+ LegacyContactState,
+ LegacyInfo,
+ LegacyRecoveryBundle,
+ ResolvedContactAvatar,
+ ResolvedContactDisplay,
+ WrappedRootContactKey,
+} from "./types";
+export type {
+ ContactDisplayRecord,
+ ContactLookup,
+ ContactsDisplaySnapshot,
+ LegacyContactRecord,
+ LegacyContactState,
+ LegacyInfo,
+ LegacyRecoveryBundle,
+ LegacyRecoverySession,
+ LegacyRecoveryStatus,
+ LegacyUser,
ResolvedContactAvatar,
ResolvedContactDisplay,
WrappedRootContactKey,
@@ -31,6 +53,15 @@ const AVATAR_FAILURE_TTL_MS = 60_000;
const READY_RETRY_COOLDOWN_MS = 5_000;
const CONTACTS_CACHE_SCHEMA_VERSION = 2;
+type EnteWasmModule = typeof import("ente-wasm");
+
+let _wasmPromise: Promise<EnteWasmModule> | undefined;
+
+const enteWasm = async () => {
+ _wasmPromise ??= import("ente-wasm");
+ return _wasmPromise;
+};
+
interface RemoteContactRecord {
id: string;
contactUserId: number | bigint;
@@ -287,7 +318,7 @@ const loadLocalSessionState = async (sessionKey: string) => {
emitSnapshot(true);
};
-const syncContacts = async ({
+const ensureContactsCtxOpen = async ({
sessionKey,
baseURL,
authToken,
@@ -300,21 +331,19 @@ const syncContacts = async ({
}) => {
let ctx = state.ctx;
const generation = state.sessionGeneration;
+
if (!ctx) {
const cachedRootKey = await savedWrappedRootContactKey(sessionKey);
if (!isCurrentSession(sessionKey, generation)) {
return;
}
+ const { contacts_open_ctx } = await enteWasm();
const openedCtx = await contacts_open_ctx({
baseUrl: baseURL,
authToken,
userId: userID,
masterKeyB64,
cachedRootKey,
- userAgent:
- typeof navigator === "undefined"
- ? undefined
- : navigator.userAgent,
clientPackage: clientPackageName,
clientVersion: isDesktop ? desktopAppVersion : undefined,
});
@@ -338,6 +367,31 @@ const syncContacts = async ({
}
state.currentAuthToken = authToken;
+ return ctx;
+};
+
+const syncContacts = async ({
+ sessionKey,
+ baseURL,
+ authToken,
+ userID,
+ masterKeyB64,
+}: ContactsReadyInput & {
+ sessionKey: string;
+ baseURL: string;
+ authToken: string;
+}) => {
+ const ctx = await ensureContactsCtxOpen({
+ sessionKey,
+ baseURL,
+ authToken,
+ userID,
+ masterKeyB64,
+ });
+ if (!ctx) {
+ return;
+ }
+ const generation = state.sessionGeneration;
let sinceTime = (await savedContactsSinceTime(sessionKey)) ?? 0;
let didChange = false;
@@ -439,6 +493,174 @@ 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);
+ if (state.currentSessionKey !== sessionKey) {
+ await loadLocalSessionState(sessionKey);
+ }
+ const ctx = await ensureContactsCtxOpen({
+ sessionKey,
+ baseURL,
+ authToken,
+ userID: user.id,
+ masterKeyB64,
+ });
+ 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>;
+};
+
+export const legacyGetInfo = async (): Promise<LegacyInfo> => {
+ const ctx = await ensureCurrentLegacyCtx();
+ return (await ctx.legacy_get_info()) as LegacyInfo;
+};
+
+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 &&
diff --git a/web/packages/contacts/legacy/components/ActionButton.tsx b/web/packages/contacts/legacy/components/ActionButton.tsx
new file mode 100644
index 0000000000..d2305b6e1c
--- /dev/null
+++ b/web/packages/contacts/legacy/components/ActionButton.tsx
@@ -0,0 +1,119 @@
+import { type ButtonProps } from "@mui/material";
+import { LoadingButton } from "ente-base/components/mui/LoadingButton";
+import { isSxArray } from "ente-base/components/utils/sx";
+import React from "react";
+
+export type ActionButtonType =
+ | "primary"
+ | "secondary"
+ | "critical"
+ | "tertiaryCritical"
+ | "link";
+
+interface ActionButtonProps extends Omit<ButtonProps, "color" | "variant"> {
+ buttonType: ActionButtonType;
+ loading?: boolean;
+}
+
+const pillSx = {
+ minHeight: 52,
+ borderRadius: "999px",
+ px: 3,
+ py: 1.5,
+ fontWeight: 600,
+ textTransform: "none",
+ boxShadow: "none",
+};
+
+const typeSx = {
+ primary: {
+ ...pillSx,
+ backgroundColor: "accent.main",
+ color: "accent.contrastText",
+ "&:hover": {
+ backgroundColor: "accent.main",
+ opacity: 0.92,
+ boxShadow: "none",
+ },
+ "&.Mui-disabled": {
+ backgroundColor: "fill.faint",
+ color: "text.muted",
+ },
+ },
+ secondary: {
+ ...pillSx,
+ backgroundColor: "fill.faint",
+ color: "text.base",
+ "&:hover": { backgroundColor: "fill.faintHover", boxShadow: "none" },
+ "&.Mui-disabled": {
+ backgroundColor: "fill.faint",
+ color: "text.muted",
+ },
+ },
+ critical: {
+ ...pillSx,
+ backgroundColor: "critical.main",
+ color: "critical.contrastText",
+ "&:hover": {
+ backgroundColor: "critical.main",
+ opacity: 0.92,
+ boxShadow: "none",
+ },
+ "&.Mui-disabled": {
+ backgroundColor: "fill.faint",
+ color: "text.muted",
+ },
+ },
+ tertiaryCritical: {
+ minHeight: 0,
+ px: 0,
+ py: 0,
+ borderRadius: 0,
+ fontWeight: 600,
+ textTransform: "none",
+ color: "critical.main",
+ "&:hover": { backgroundColor: "transparent", color: "critical.main" },
+ "&.Mui-disabled": { color: "text.muted" },
+ },
+ link: {
+ minHeight: 0,
+ px: 0,
+ py: 0,
+ borderRadius: 0,
+ fontWeight: 600,
+ textTransform: "none",
+ color: "accent.main",
+ textDecoration: "underline",
+ textDecorationColor: "accent.main",
+ "&:hover": {
+ backgroundColor: "transparent",
+ color: "accent.main",
+ textDecorationColor: "accent.main",
+ },
+ "&.Mui-disabled": {
+ color: "text.muted",
+ textDecorationColor: "text.muted",
+ },
+ },
+} satisfies Record<ActionButtonType, ButtonProps["sx"]>;
+
+const muiVariant = (buttonType: ActionButtonType): ButtonProps["variant"] =>
+ buttonType === "link" || buttonType === "tertiaryCritical"
+ ? "text"
+ : "contained";
+
+export const ActionButton: React.FC<ActionButtonProps> = ({
+ buttonType,
+ loading,
+ sx,
+ disableElevation = true,
+ ...props
+}) => (
+ <LoadingButton
+ {...props}
+ loading={loading}
+ disableElevation={disableElevation}
+ variant={muiVariant(buttonType)}
+ sx={[typeSx[buttonType], ...(sx ? (isSxArray(sx) ? sx : [sx]) : [])]}
+ />
+);
diff --git a/web/packages/contacts/legacy/components/LegacyActionSheet.tsx b/web/packages/contacts/legacy/components/LegacyActionSheet.tsx
new file mode 100644
index 0000000000..97e2cd607b
--- /dev/null
+++ b/web/packages/contacts/legacy/components/LegacyActionSheet.tsx
@@ -0,0 +1,83 @@
+import CloseIcon from "@mui/icons-material/Close";
+import {
+ Dialog,
+ IconButton,
+ Stack,
+ Typography,
+ type DialogProps,
+} from "@mui/material";
+import React from "react";
+
+interface LegacyActionSheetProps {
+ open: boolean;
+ title: string;
+ subtitle?: React.ReactNode;
+ onClose: () => void;
+ children: React.ReactNode;
+}
+
+export const LegacyActionSheet: React.FC<LegacyActionSheetProps> = ({
+ open,
+ title,
+ subtitle,
+ onClose,
+ children,
+}) => {
+ const handleClose: DialogProps["onClose"] = () => {
+ onClose();
+ };
+
+ return (
+ <Dialog
+ open={open}
+ onClose={handleClose}
+ fullWidth
+ maxWidth={false}
+ slotProps={{
+ backdrop: { sx: { backgroundColor: "rgba(0, 0, 0, 0.48)" } },
+ paper: {
+ sx: {
+ m: 0,
+ position: "fixed",
+ left: "50%",
+ top: "50%",
+ transform: "translate(-50%, -50%)",
+ width: "min(100%, 375px)",
+ maxHeight: "calc(100vh - 48px)",
+ borderRadius: "24px",
+ backgroundColor: "background.paper",
+ px: 2,
+ pt: 2,
+ pb: 2,
+ overflowY: "auto",
+ },
+ },
+ }}
+ >
+ <Stack sx={{ gap: 2.5 }}>
+ <Stack direction="row" sx={{ justifyContent: "flex-end" }}>
+ <IconButton onClick={onClose} color="secondary">
+ <CloseIcon />
+ </IconButton>
+ </Stack>
+ <Stack sx={{ gap: 2 }}>
+ <Typography variant="h4" sx={{ wordBreak: "break-word" }}>
+ {title}
+ </Typography>
+ {subtitle && (
+ <Typography
+ variant="body"
+ sx={{
+ color: "text.muted",
+ wordBreak: "break-word",
+ }}
+ >
+ {subtitle}
+ </Typography>
+ )}
+ </Stack>
+ {children}
+ </Stack>
+ </Dialog>
+ );
+};
diff --git a/web/packages/contacts/legacy/components/LegacyAddContactContent.tsx b/web/packages/contacts/legacy/components/LegacyAddContactContent.tsx
new file mode 100644
index 0000000000..82b2c007b9
--- /dev/null
+++ b/web/packages/contacts/legacy/components/LegacyAddContactContent.tsx
@@ -0,0 +1,324 @@
+import SearchIcon from "@mui/icons-material/Search";
+import {
+ Box,
+ InputAdornment,
+ Stack,
+ TextField,
+ Typography,
+} from "@mui/material";
+import { ensureLocalUser } from "ente-accounts-rs/services/user";
+import { useBaseContext } from "ente-base/context";
+import React, { useMemo, useState } from "react";
+import {
+ legacyAddContact,
+ legacyPublicKey,
+ legacyVerificationID,
+ type LegacySuggestedUser,
+} from "..";
+import { contactsDisplaySnapshot } from "../..";
+import { resolveContactDisplayFromSnapshot } from "../../resolver";
+import { ActionButton } from "./ActionButton";
+import { LegacyIdentityRow } from "./LegacyIdentityRow";
+import { LegacyRecoveryDayPicker } from "./LegacyRecoveryDayPicker";
+
+const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+
+interface LegacyAddContactContentProps {
+ existingEmails: string[];
+ onAdded: () => Promise<void>;
+ suggestedUsers: LegacySuggestedUser[];
+ variant?: "page" | "sheet";
+}
+
+const getErrorMessage = (error: unknown) =>
+ error instanceof Error ? error.message : "Something went wrong";
+
+const nonEnteDialogAttributes = (email: string) => ({
+ title: "Cannot add trusted contact",
+ message: `${email} is not linked to an Ente account yet, so it cannot be used as a trusted contact.`,
+});
+
+export const LegacyAddContactContent: React.FC<
+ LegacyAddContactContentProps
+> = ({ existingEmails, onAdded, suggestedUsers, variant = "page" }) => {
+ const { showMiniDialog, onGenericError } = useBaseContext();
+ const currentUser = ensureLocalUser();
+ const [email, setEmail] = useState("");
+ const [selectedRecoveryDays, setSelectedRecoveryDays] = useState(14);
+ const snapshot = contactsDisplaySnapshot();
+
+ const normalizedExistingEmails = useMemo(
+ () =>
+ new Set(existingEmails.map((value) => value.trim().toLowerCase())),
+ [existingEmails],
+ );
+
+ const filteredSuggestions = useMemo(() => {
+ const normalizedQuery = email.trim().toLowerCase();
+ const byEmail = new Map<string, LegacySuggestedUser>();
+ for (const user of suggestedUsers) {
+ const normalizedEmail = user.email.trim().toLowerCase();
+ const resolvedDisplay = resolveContactDisplayFromSnapshot(
+ snapshot,
+ { email: user.email, userID: user.id },
+ );
+ const normalizedName = resolvedDisplay.primaryLabel
+ .trim()
+ .toLowerCase();
+ if (
+ !normalizedEmail ||
+ normalizedEmail === currentUser.email.toLowerCase() ||
+ normalizedExistingEmails.has(normalizedEmail)
+ ) {
+ continue;
+ }
+ if (
+ normalizedQuery &&
+ !normalizedEmail.includes(normalizedQuery) &&
+ !normalizedName.includes(normalizedQuery)
+ ) {
+ continue;
+ }
+ byEmail.set(normalizedEmail, user);
+ }
+ return [...byEmail.values()].sort((a, b) =>
+ a.email.localeCompare(b.email, undefined, { sensitivity: "base" }),
+ );
+ }, [
+ currentUser.email,
+ email,
+ normalizedExistingEmails,
+ snapshot,
+ suggestedUsers,
+ ]);
+
+ const normalizedEmail = email.trim().toLowerCase();
+
+ const handleVerify = async () => {
+ if (!normalizedEmail || !EMAIL_PATTERN.test(normalizedEmail)) {
+ showMiniDialog({
+ title: "Invalid email",
+ message: "Enter a valid email address before verifying its ID.",
+ });
+ return;
+ }
+ try {
+ const verificationID = await legacyVerificationID(normalizedEmail);
+ if (!verificationID) {
+ showMiniDialog({
+ title: "Verification ID unavailable",
+ message:
+ "That email is not linked to an Ente account yet, so there is no public key to verify.",
+ });
+ return;
+ }
+ showMiniDialog({
+ title: "Verification ID",
+ message: (
+ <Box
+ sx={{ whiteSpace: "pre-wrap", wordBreak: "break-word" }}
+ >
+ {verificationID}
+ </Box>
+ ),
+ });
+ } catch (error) {
+ onGenericError(error);
+ }
+ };
+
+ const handleAdd = () => {
+ if (!normalizedEmail) {
+ return;
+ }
+ if (!EMAIL_PATTERN.test(normalizedEmail)) {
+ showMiniDialog({
+ title: "Invalid email",
+ message:
+ "Enter a valid email address for your trusted contact.",
+ });
+ return;
+ }
+ if (normalizedEmail === currentUser.email.toLowerCase()) {
+ showMiniDialog({
+ title: "Invalid trusted contact",
+ message:
+ "You cannot add your own account as a trusted contact.",
+ });
+ return;
+ }
+ if (normalizedExistingEmails.has(normalizedEmail)) {
+ showMiniDialog({
+ title: "Already added",
+ message: "That email is already present in your Legacy setup.",
+ });
+ return;
+ }
+
+ void (async () => {
+ try {
+ const publicKey = await legacyPublicKey(normalizedEmail);
+ if (!publicKey) {
+ showMiniDialog(nonEnteDialogAttributes(normalizedEmail));
+ return;
+ }
+
+ showMiniDialog({
+ title: "Add trusted contact?",
+ message: `Ente will wait ${selectedRecoveryDays} days before ${normalizedEmail} can recover your account.`,
+ continue: {
+ text: "Add trusted contact",
+ color: "primary",
+ action: async () => {
+ try {
+ await legacyAddContact(
+ normalizedEmail,
+ selectedRecoveryDays,
+ );
+ } catch (error) {
+ const message = getErrorMessage(error);
+ if (message.includes("not on Ente")) {
+ setTimeout(() => {
+ showMiniDialog(
+ nonEnteDialogAttributes(
+ normalizedEmail,
+ ),
+ );
+ }, 0);
+ return;
+ }
+ throw error instanceof Error
+ ? error
+ : new Error(message);
+ }
+ await onAdded();
+ },
+ },
+ });
+ } catch (error) {
+ onGenericError(error);
+ }
+ })();
+ };
+
+ const isSheet = variant === "sheet";
+
+ return (
+ <Stack sx={{ gap: 2, ...(isSheet ? {} : { px: 2, pb: 2 }) }}>
+ {!isSheet && (
+ <Stack sx={{ gap: 1 }}>
+ <Typography variant="h4">Add trusted contact</Typography>
+ <Typography variant="small" sx={{ color: "text.muted" }}>
+ Search an email, verify the identity if needed, and
+ choose how long recovery should wait.
+ </Typography>
+ </Stack>
+ )}
+
+ <Stack
+ sx={{
+ gap: 2,
+ ...(isSheet
+ ? {}
+ : {
+ p: 2,
+ borderRadius: "20px",
+ backgroundColor: "backdrop.base",
+ }),
+ }}
+ >
+ <TextField
+ autoFocus
+ size="small"
+ type="email"
+ value={email}
+ onChange={(event) => setEmail(event.target.value)}
+ placeholder="Enter email"
+ slotProps={{
+ input: {
+ startAdornment: (
+ <InputAdornment position="start">
+ <SearchIcon fontSize="small" />
+ </InputAdornment>
+ ),
+ },
+ }}
+ />
+
+ {!!filteredSuggestions.length && (
+ <Stack sx={{ gap: 1 }}>
+ <Typography
+ variant="small"
+ sx={{ color: "text.muted" }}
+ >
+ Choose from an existing contact
+ </Typography>
+ <Stack
+ sx={{
+ gap: 0.5,
+ p: 0.75,
+ borderRadius: "18px",
+ backgroundColor: "fill.faint",
+ maxHeight: 260,
+ overflowY: "auto",
+ }}
+ >
+ {filteredSuggestions.map((user) => (
+ <LegacyIdentityRow
+ key={`${user.id ?? "email"}:${user.email}`}
+ email={user.email}
+ userID={user.id}
+ selected={
+ normalizedEmail ===
+ user.email.trim().toLowerCase()
+ }
+ onClick={() => setEmail(user.email)}
+ />
+ ))}
+ </Stack>
+ </Stack>
+ )}
+
+ {!!email.trim() &&
+ !filteredSuggestions.length &&
+ EMAIL_PATTERN.test(normalizedEmail) && (
+ <Typography
+ variant="small"
+ sx={{ color: "text.muted" }}
+ >
+ No existing contact matched. You can still add this
+ email directly.
+ </Typography>
+ )}
+
+ <Stack sx={{ gap: 1 }}>
+ <Typography variant="small" sx={{ color: "text.muted" }}>
+ Choose a recovery time
+ </Typography>
+ <LegacyRecoveryDayPicker
+ selectedDays={selectedRecoveryDays}
+ onChange={setSelectedRecoveryDays}
+ />
+ </Stack>
+
+ <ActionButton
+ fullWidth
+ buttonType="primary"
+ onClick={handleAdd}
+ disabled={!email.trim()}
+ >
+ Add trusted contact
+ </ActionButton>
+
+ <ActionButton
+ buttonType="link"
+ onClick={() => void handleVerify()}
+ disabled={!email.trim()}
+ sx={{ alignSelf: "center" }}
+ >
+ Verify
+ </ActionButton>
+ </Stack>
+ </Stack>
+ );
+};
diff --git a/web/packages/contacts/legacy/components/LegacyDrawerContent.tsx b/web/packages/contacts/legacy/components/LegacyDrawerContent.tsx
new file mode 100644
index 0000000000..e72190e936
--- /dev/null
+++ b/web/packages/contacts/legacy/components/LegacyDrawerContent.tsx
@@ -0,0 +1,908 @@
+import ChevronRightIcon from "@mui/icons-material/ChevronRight";
+import WarningAmberRoundedIcon from "@mui/icons-material/WarningAmberRounded";
+import { Box, CircularProgress, Stack, Typography } from "@mui/material";
+import { useBaseContext } from "ente-base/context";
+import log from "ente-base/log";
+import React, { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ legacyChangePassword,
+ legacyGetInfo,
+ legacyRejectRecovery,
+ legacyStartRecovery,
+ legacyStopRecovery,
+ legacyUpdateContact,
+ legacyUpdateRecoveryNotice,
+ type LegacyContactRecord,
+ type LegacyInfo,
+ type LegacyRecoverySession,
+ type LegacySuggestedUser,
+} from "..";
+import { mergeLegacySuggestedUsers } from "../suggestions";
+import { ActionButton } from "./ActionButton";
+import { LegacyActionSheet } from "./LegacyActionSheet";
+import { LegacyAddContactContent } from "./LegacyAddContactContent";
+import { LegacyIdentityRow } from "./LegacyIdentityRow";
+import { LegacyRecoveryDayPicker } from "./LegacyRecoveryDayPicker";
+import { LegacyResetPasswordPage } from "./LegacyResetPasswordPage";
+import { LegacyTrustedAccountPage } from "./LegacyTrustedAccountPage";
+type ActiveSheet =
+ | { kind: "add" }
+ | { kind: "owner"; contact: LegacyContactRecord }
+ | { kind: "trustedInvite"; contact: LegacyContactRecord }
+ | { kind: "recovery"; session: LegacyRecoverySession }
+ | undefined;
+
+type ActivePage =
+ | { kind: "trusted"; contact: LegacyContactRecord }
+ | {
+ kind: "resetPassword";
+ contact: LegacyContactRecord;
+ session: LegacyRecoverySession;
+ }
+ | undefined;
+
+const pairKey = (userID: number, emergencyContactID: number) =>
+ `${userID}:${emergencyContactID}`;
+
+const isActiveRecoveryStatus = (status: LegacyRecoverySession["status"]) =>
+ status === "WAITING" || status === "READY";
+
+const preferredRecoverySession = (
+ current: LegacyRecoverySession | undefined,
+ candidate: LegacyRecoverySession,
+) => {
+ if (!current) {
+ return candidate;
+ }
+ if (candidate.status === "READY" && current.status !== "READY") {
+ return candidate;
+ }
+ if (candidate.status !== "READY" && current.status === "READY") {
+ return current;
+ }
+ return candidate.createdAt >= current.createdAt ? candidate : current;
+};
+
+const formatWait = (session: LegacyRecoverySession) => {
+ if (session.status === "READY" || session.waitTill <= 0) {
+ return "Ready now";
+ }
+ const totalHours = Math.ceil(session.waitTill / (1000 * 1000 * 60 * 60));
+ if (totalHours >= 24) {
+ const days = Math.ceil(totalHours / 24);
+ return `${days} day${days === 1 ? "" : "s"} remaining`;
+ }
+ return `${totalHours} hour${totalHours === 1 ? "" : "s"} remaining`;
+};
+
+const formatWaitDuration = (session: LegacyRecoverySession) => {
+ if (session.status === "READY" || session.waitTill <= 0) {
+ return "now";
+ }
+ const totalHours = Math.ceil(session.waitTill / (1000 * 1000 * 60 * 60));
+ if (totalHours >= 24) {
+ const days = Math.ceil(totalHours / 24);
+ return `${days} day${days === 1 ? "" : "s"}`;
+ }
+ return `${totalHours} hour${totalHours === 1 ? "" : "s"}`;
+};
+
+const ownerMessage = (contact: LegacyContactRecord) => {
+ const email = contact.emergencyContact.email;
+ switch (contact.state) {
+ case "ACCEPTED":
+ return `You have added ${email} as a trusted contact. They have accepted your invite.`;
+ case "INVITED":
+ return `You have invited ${email} to be a trusted contact. They are yet to accept your invite.`;
+ case "CONTACT_DENIED":
+ return `${email} declined your trusted-contact invite.`;
+ case "CONTACT_LEFT":
+ return `${email} removed themselves as your trusted contact.`;
+ case "REVOKED":
+ return `You removed ${email} from your trusted contacts.`;
+ }
+};
+
+const recoveryAttemptMessage = (session: LegacyRecoverySession) => {
+ const email = session.emergencyContact.email;
+ if (session.status === "READY") {
+ return `${email} is ready to recover your account.`;
+ }
+ return `${email} is trying to recover your account. ${formatWait(session)}.`;
+};
+
+const attentionIndicator = (
+ <WarningAmberRoundedIcon
+ sx={{ fontSize: 18, color: "warning.main", flexShrink: 0 }}
+ />
+);
+
+const sectionTitleSx = {
+ color: "text.muted",
+ fontSize: 18,
+ lineHeight: "24px",
+ fontWeight: 500,
+};
+
+const groupedCardSx = {
+ p: 0.5,
+ borderRadius: "20px",
+ backgroundColor: "fill.faint",
+};
+
+const warningBannerSx = {
+ p: 2,
+ gap: 1.5,
+ borderRadius: "18px",
+ backgroundColor: "rgba(255, 82, 82, 0.14)",
+};
+
+const getErrorMessage = (error: unknown) =>
+ error instanceof Error ? error.message : "Something went wrong";
+
+interface LegacyDrawerContentProps {
+ open: boolean;
+ suggestedUsers?: LegacySuggestedUser[];
+}
+
+interface ConfirmActionDialogInput {
+ title: string;
+ message: React.ReactNode;
+ continueText: string;
+ continueColor?: "accent" | "critical" | "primary" | "secondary";
+ action: () => Promise<void>;
+}
+
+export const LegacyDrawerContent: React.FC<LegacyDrawerContentProps> = ({
+ open,
+ suggestedUsers = [],
+}) => {
+ const { showMiniDialog, onGenericError } = useBaseContext();
+ const [info, setInfo] = useState<LegacyInfo | undefined>();
+ const [isLoading, setIsLoading] = useState(false);
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [activeSheet, setActiveSheet] = useState<ActiveSheet>();
+ const [activePage, setActivePage] = useState<ActivePage>();
+ const [selectedOwnerDays, setSelectedOwnerDays] = useState(14);
+
+ const loadInfo = useCallback(
+ async (reportErrors: boolean) => {
+ setIsLoading(true);
+ try {
+ setInfo(await legacyGetInfo());
+ return true;
+ } catch (error) {
+ if (reportErrors) {
+ onGenericError(error);
+ } else {
+ log.error(
+ "Legacy refresh failed after successful mutation",
+ error,
+ );
+ }
+ return false;
+ } finally {
+ setIsLoading(false);
+ }
+ },
+ [onGenericError],
+ );
+
+ const refresh = useCallback(async () => {
+ await loadInfo(true);
+ }, [loadInfo]);
+
+ useEffect(() => {
+ if (open) {
+ void refresh();
+ } else {
+ setInfo(undefined);
+ setIsLoading(false);
+ setIsSubmitting(false);
+ setActiveSheet(undefined);
+ setActivePage(undefined);
+ }
+ }, [open, refresh]);
+
+ useEffect(() => {
+ const selectedOwnerContact =
+ activeSheet?.kind === "owner" ? activeSheet.contact : undefined;
+ setSelectedOwnerDays(selectedOwnerContact?.recoveryNoticeInDays ?? 14);
+ }, [activeSheet]);
+
+ const activeRecoveriesByPair = useMemo(() => {
+ const map = new Map<string, LegacyRecoverySession>();
+ for (const session of info?.othersRecoverySession ?? []) {
+ if (!isActiveRecoveryStatus(session.status)) {
+ continue;
+ }
+ const key = pairKey(session.user.id, session.emergencyContact.id);
+ map.set(key, preferredRecoverySession(map.get(key), session));
+ }
+ return map;
+ }, [info?.othersRecoverySession]);
+
+ const existingEmails = useMemo(
+ () =>
+ info?.contacts.map((contact) => contact.emergencyContact.email) ??
+ [],
+ [info?.contacts],
+ );
+
+ const addScreenSuggestedUsers = useMemo(() => {
+ return mergeLegacySuggestedUsers(
+ suggestedUsers,
+ info?.othersEmergencyContact.map((contact) => ({
+ id: contact.user.id,
+ email: contact.user.email,
+ })),
+ );
+ }, [info?.othersEmergencyContact, suggestedUsers]);
+
+ const selectedOwnerContact =
+ activeSheet?.kind === "owner" ? activeSheet.contact : undefined;
+ const selectedTrustedInvite =
+ activeSheet?.kind === "trustedInvite" ? activeSheet.contact : undefined;
+ const selectedTrustedContact =
+ activePage?.kind === "trusted" || activePage?.kind === "resetPassword"
+ ? activePage.contact
+ : undefined;
+ const selectedRecoveryAttempt =
+ activeSheet?.kind === "recovery" ? activeSheet.session : undefined;
+ const isAddSheetOpen = activeSheet?.kind === "add";
+
+ const selectedTrustedRecovery = useMemo(() => {
+ if (!selectedTrustedContact) {
+ return undefined;
+ }
+ return activeRecoveriesByPair.get(
+ pairKey(
+ selectedTrustedContact.user.id,
+ selectedTrustedContact.emergencyContact.id,
+ ),
+ );
+ }, [activeRecoveriesByPair, selectedTrustedContact]);
+
+ const hasOverviewEntries = Boolean(
+ info?.recoverSessions.length ||
+ info?.contacts.length ||
+ info?.othersEmergencyContact.length,
+ );
+
+ const refreshAfterMutation = useCallback(async () => {
+ await loadInfo(false);
+ }, [loadInfo]);
+
+ const runAction = useCallback(
+ async (
+ action: () => Promise<unknown>,
+ onSuccess?: () => void | Promise<void>,
+ ) => {
+ let didSucceed = false;
+ try {
+ setIsSubmitting(true);
+ await action();
+ didSucceed = true;
+ await onSuccess?.();
+ } catch (error) {
+ onGenericError(error);
+ } finally {
+ setIsSubmitting(false);
+ }
+ if (didSucceed) {
+ await refreshAfterMutation();
+ }
+ },
+ [onGenericError, refreshAfterMutation],
+ );
+
+ const confirmAction = useCallback(
+ ({
+ title,
+ message,
+ continueText,
+ continueColor = "critical",
+ action,
+ }: ConfirmActionDialogInput) => {
+ showMiniDialog({
+ title,
+ message,
+ continue: {
+ text: continueText,
+ color: continueColor,
+ action: async () => {
+ await action();
+ await refreshAfterMutation();
+ },
+ },
+ });
+ },
+ [refreshAfterMutation, showMiniDialog],
+ );
+
+ const handleSaveRecoveryNotice = useCallback(async () => {
+ if (!selectedOwnerContact) {
+ return;
+ }
+ setIsSubmitting(true);
+ try {
+ await legacyUpdateRecoveryNotice(
+ selectedOwnerContact.emergencyContact.id,
+ selectedOwnerDays,
+ );
+ setActiveSheet(undefined);
+ await refreshAfterMutation();
+ } catch (error) {
+ const message = getErrorMessage(error);
+ if (message.includes("active recovery session")) {
+ showMiniDialog({
+ title: "Recovery in progress",
+ message:
+ "You cannot change the recovery notice while an active recovery attempt exists for this contact.",
+ });
+ } else {
+ onGenericError(error);
+ }
+ } finally {
+ setIsSubmitting(false);
+ }
+ }, [
+ onGenericError,
+ refreshAfterMutation,
+ selectedOwnerContact,
+ selectedOwnerDays,
+ showMiniDialog,
+ ]);
+
+ const resetPasswordPage =
+ activePage?.kind === "resetPassword" ? activePage : undefined;
+ const trustedWaitLabel = selectedTrustedRecovery
+ ? formatWaitDuration(selectedTrustedRecovery)
+ : undefined;
+
+ return (
+ <>
+ {activePage?.kind === "trusted" && selectedTrustedContact ? (
+ <LegacyTrustedAccountPage
+ contact={selectedTrustedContact}
+ activeRecovery={selectedTrustedRecovery}
+ isSubmitting={isSubmitting}
+ waitLabel={trustedWaitLabel}
+ onBack={() => setActivePage(undefined)}
+ onStartRecovery={() =>
+ confirmAction({
+ title: "Start recovery",
+ message: `Are you sure you want to initiate recovery for ${selectedTrustedContact.user.email}'s account?`,
+ continueText: "Start recovery",
+ continueColor: "accent",
+ action: async () => {
+ await legacyStartRecovery(
+ selectedTrustedContact.user.id,
+ selectedTrustedContact.emergencyContact.id,
+ );
+ },
+ })
+ }
+ onRecoverAccount={() => {
+ if (!selectedTrustedRecovery) {
+ return;
+ }
+ setActivePage({
+ kind: "resetPassword",
+ contact: selectedTrustedContact,
+ session: selectedTrustedRecovery,
+ });
+ }}
+ onCancelRecovery={() => {
+ if (!selectedTrustedRecovery) {
+ return;
+ }
+ confirmAction({
+ title: "Cancel recovery",
+ message: `Are you sure you want to cancel recovery of ${selectedTrustedContact.user.email}'s account?`,
+ continueText: "Cancel recovery",
+ action: async () => {
+ await legacyStopRecovery(
+ selectedTrustedRecovery.id,
+ selectedTrustedRecovery.user.id,
+ selectedTrustedRecovery.emergencyContact.id,
+ );
+ },
+ });
+ }}
+ onRemoveContact={() =>
+ confirmAction({
+ title: "Remove contact",
+ message: `If you remove yourself as a trusted contact, you'll lose access to ${selectedTrustedContact.user.email}'s account after their inactivity period.`,
+ continueText: "Remove contact",
+ action: async () => {
+ await legacyUpdateContact(
+ selectedTrustedContact.user.id,
+ selectedTrustedContact.emergencyContact.id,
+ "CONTACT_LEFT",
+ );
+ setActivePage(undefined);
+ },
+ })
+ }
+ />
+ ) : resetPasswordPage ? (
+ <LegacyResetPasswordPage
+ session={resetPasswordPage.session}
+ isSubmitting={isSubmitting}
+ onBack={() =>
+ setActivePage({
+ kind: "trusted",
+ contact: resetPasswordPage.contact,
+ })
+ }
+ onSubmit={async (password) => {
+ setIsSubmitting(true);
+ try {
+ await legacyChangePassword(
+ resetPasswordPage.session.id,
+ password,
+ );
+ setActivePage(undefined);
+ showMiniDialog({
+ title: "Account recovered",
+ message: `You can now sign in to ${resetPasswordPage.session.user.email} with the new password.`,
+ cancel: "Done",
+ });
+ void refreshAfterMutation();
+ } finally {
+ setIsSubmitting(false);
+ }
+ }}
+ />
+ ) : (
+ <Stack sx={{ px: 2, pt: 2, pb: 2, gap: 2.5 }}>
+ {isLoading && !info ? (
+ <Stack
+ sx={{
+ alignItems: "center",
+ justifyContent: "center",
+ py: 6,
+ color: "text.muted",
+ gap: 1.5,
+ }}
+ >
+ <CircularProgress size={24} />
+ <Typography variant="small">
+ Loading Legacy information
+ </Typography>
+ </Stack>
+ ) : (
+ <>
+ {!!info?.recoverSessions.length && (
+ <Stack sx={{ gap: 2 }}>
+ <Stack direction="row" sx={warningBannerSx}>
+ <WarningAmberRoundedIcon
+ sx={{
+ fontSize: 28,
+ color: "warning.main",
+ flexShrink: 0,
+ mt: 0.25,
+ }}
+ />
+ <Typography
+ variant="body"
+ sx={{
+ color: "warning.main",
+ fontWeight: 700,
+ lineHeight: 1.35,
+ }}
+ >
+ A trusted contact is trying to
+ access your account
+ </Typography>
+ </Stack>
+ <Stack sx={groupedCardSx}>
+ {info.recoverSessions.map(
+ (session, index) => (
+ <Box
+ key={session.id}
+ sx={{
+ pt:
+ index === 0
+ ? 0
+ : 0.75,
+ borderTop:
+ index === 0
+ ? undefined
+ : "1px solid",
+ borderColor: "divider",
+ }}
+ >
+ <LegacyIdentityRow
+ email={
+ session
+ .emergencyContact
+ .email
+ }
+ userID={
+ session
+ .emergencyContact
+ .id
+ }
+ primaryColor="warning.main"
+ action={
+ <ChevronRightIcon
+ sx={{
+ color: "text.muted",
+ }}
+ />
+ }
+ onClick={() =>
+ setActiveSheet({
+ kind: "recovery",
+ session,
+ })
+ }
+ />
+ </Box>
+ ),
+ )}
+ </Stack>
+ </Stack>
+ )}
+
+ {!!info?.contacts.length && (
+ <Stack sx={{ gap: 1 }}>
+ <Typography sx={sectionTitleSx}>
+ Trusted contacts
+ </Typography>
+ <Stack sx={groupedCardSx}>
+ {info.contacts.map((contact, index) => (
+ <Box
+ key={pairKey(
+ contact.user.id,
+ contact.emergencyContact.id,
+ )}
+ sx={{
+ pt: index === 0 ? 0 : 0.75,
+ borderTop:
+ index === 0
+ ? undefined
+ : "1px solid",
+ borderColor: "divider",
+ }}
+ >
+ <LegacyIdentityRow
+ email={
+ contact.emergencyContact
+ .email
+ }
+ userID={
+ contact.emergencyContact
+ .id
+ }
+ statusIndicator={
+ contact.state ===
+ "ACCEPTED"
+ ? undefined
+ : attentionIndicator
+ }
+ action={
+ <ChevronRightIcon
+ sx={{
+ color: "text.muted",
+ }}
+ />
+ }
+ onClick={() =>
+ setActiveSheet({
+ kind: "owner",
+ contact,
+ })
+ }
+ />
+ </Box>
+ ))}
+ </Stack>
+ </Stack>
+ )}
+
+ <ActionButton
+ fullWidth
+ buttonType="primary"
+ loading={isLoading}
+ disabled={!info || isSubmitting}
+ onClick={() => setActiveSheet({ kind: "add" })}
+ >
+ Add trusted contact
+ </ActionButton>
+
+ {!!info?.othersEmergencyContact.length && (
+ <>
+ <Box
+ sx={{
+ mt: 0.5,
+ borderTop: "1px solid",
+ borderColor: "divider",
+ }}
+ />
+ <Stack sx={{ gap: 1 }}>
+ <Typography sx={sectionTitleSx}>
+ Legacy accounts
+ </Typography>
+ <Stack sx={groupedCardSx}>
+ {info.othersEmergencyContact.map(
+ (contact, index) => {
+ const activeRecovery =
+ activeRecoveriesByPair.get(
+ pairKey(
+ contact.user.id,
+ contact
+ .emergencyContact
+ .id,
+ ),
+ );
+ return (
+ <Box
+ key={pairKey(
+ contact.user.id,
+ contact
+ .emergencyContact
+ .id,
+ )}
+ sx={{
+ pt:
+ index === 0
+ ? 0
+ : 0.75,
+ borderTop:
+ index === 0
+ ? undefined
+ : "1px solid",
+ borderColor:
+ "divider",
+ }}
+ >
+ <LegacyIdentityRow
+ email={
+ contact.user
+ .email
+ }
+ userID={
+ contact.user
+ .id
+ }
+ statusIndicator={
+ contact.state !==
+ "ACCEPTED" ||
+ !!activeRecovery
+ ? attentionIndicator
+ : undefined
+ }
+ action={
+ <ChevronRightIcon
+ sx={{
+ color: "text.muted",
+ }}
+ />
+ }
+ onClick={() =>
+ contact.state ===
+ "INVITED"
+ ? setActiveSheet(
+ {
+ kind: "trustedInvite",
+ contact,
+ },
+ )
+ : setActivePage(
+ {
+ kind: "trusted",
+ contact,
+ },
+ )
+ }
+ />
+ </Box>
+ );
+ },
+ )}
+ </Stack>
+ </Stack>
+ </>
+ )}
+
+ {!hasOverviewEntries && !!info && (
+ <Typography
+ variant="small"
+ sx={{
+ color: "text.muted",
+ textAlign: "center",
+ py: 1,
+ }}
+ >
+ No Legacy activity yet.
+ </Typography>
+ )}
+ </>
+ )}
+ </Stack>
+ )}
+
+ <LegacyActionSheet
+ open={isAddSheetOpen}
+ title="Add trusted contact"
+ onClose={() => setActiveSheet(undefined)}
+ >
+ <LegacyAddContactContent
+ variant="sheet"
+ suggestedUsers={addScreenSuggestedUsers}
+ existingEmails={existingEmails}
+ onAdded={async () => {
+ setActiveSheet(undefined);
+ await refreshAfterMutation();
+ }}
+ />
+ </LegacyActionSheet>
+
+ <LegacyActionSheet
+ open={!!selectedOwnerContact}
+ title={selectedOwnerContact?.emergencyContact.email ?? ""}
+ subtitle={
+ selectedOwnerContact
+ ? ownerMessage(selectedOwnerContact)
+ : undefined
+ }
+ onClose={() => setActiveSheet(undefined)}
+ >
+ {selectedOwnerContact &&
+ (selectedOwnerContact.state === "INVITED" ||
+ selectedOwnerContact.state === "ACCEPTED") && (
+ <Stack sx={{ gap: 2 }}>
+ <LegacyRecoveryDayPicker
+ selectedDays={selectedOwnerDays}
+ onChange={setSelectedOwnerDays}
+ />
+ <ActionButton
+ fullWidth
+ buttonType="primary"
+ loading={isSubmitting}
+ disabled={
+ isSubmitting ||
+ selectedOwnerDays ===
+ selectedOwnerContact.recoveryNoticeInDays
+ }
+ onClick={() => void handleSaveRecoveryNotice()}
+ >
+ Update time
+ </ActionButton>
+ <ActionButton
+ buttonType="tertiaryCritical"
+ onClick={() =>
+ confirmAction({
+ title:
+ selectedOwnerContact.state ===
+ "INVITED"
+ ? "Cancel invite"
+ : "Remove contact",
+ message:
+ selectedOwnerContact.state ===
+ "INVITED"
+ ? "If you delete this invite, you'll need to send a new one if you change your mind."
+ : "If you delete this contact, you'll need to send a new invitation, and the contact will have to accept it again.",
+ continueText:
+ selectedOwnerContact.state ===
+ "INVITED"
+ ? "Revoke invite"
+ : "Remove contact",
+ action: async () => {
+ await legacyUpdateContact(
+ selectedOwnerContact.user.id,
+ selectedOwnerContact
+ .emergencyContact.id,
+ "REVOKED",
+ );
+ setActiveSheet(undefined);
+ },
+ })
+ }
+ disabled={isSubmitting}
+ >
+ {selectedOwnerContact.state === "INVITED"
+ ? "Revoke invite"
+ : "Remove"}
+ </ActionButton>
+ </Stack>
+ )}
+ </LegacyActionSheet>
+
+ <LegacyActionSheet
+ open={!!selectedTrustedInvite}
+ title={selectedTrustedInvite?.user.email ?? ""}
+ subtitle={
+ selectedTrustedInvite
+ ? `${selectedTrustedInvite.user.email} has invited you to be a trusted contact.`
+ : undefined
+ }
+ onClose={() => setActiveSheet(undefined)}
+ >
+ {selectedTrustedInvite && (
+ <Stack sx={{ gap: 1.5 }}>
+ <ActionButton
+ fullWidth
+ buttonType="primary"
+ loading={isSubmitting}
+ onClick={() =>
+ void runAction(
+ () =>
+ legacyUpdateContact(
+ selectedTrustedInvite.user.id,
+ selectedTrustedInvite
+ .emergencyContact.id,
+ "ACCEPTED",
+ ),
+ () => setActiveSheet(undefined),
+ )
+ }
+ >
+ Accept invite
+ </ActionButton>
+ <ActionButton
+ buttonType="tertiaryCritical"
+ onClick={() =>
+ void runAction(
+ () =>
+ legacyUpdateContact(
+ selectedTrustedInvite.user.id,
+ selectedTrustedInvite
+ .emergencyContact.id,
+ "CONTACT_DENIED",
+ ),
+ () => setActiveSheet(undefined),
+ )
+ }
+ disabled={isSubmitting}
+ >
+ Decline invite
+ </ActionButton>
+ </Stack>
+ )}
+ </LegacyActionSheet>
+
+ <LegacyActionSheet
+ open={!!selectedRecoveryAttempt}
+ title={selectedRecoveryAttempt?.emergencyContact.email ?? ""}
+ subtitle={
+ selectedRecoveryAttempt
+ ? recoveryAttemptMessage(selectedRecoveryAttempt)
+ : undefined
+ }
+ onClose={() => setActiveSheet(undefined)}
+ >
+ {selectedRecoveryAttempt && (
+ <ActionButton
+ fullWidth
+ buttonType="critical"
+ onClick={() =>
+ confirmAction({
+ title: "Reject recovery",
+ message: recoveryAttemptMessage(
+ selectedRecoveryAttempt,
+ ),
+ continueText: "Reject recovery",
+ action: async () => {
+ await legacyRejectRecovery(
+ selectedRecoveryAttempt.id,
+ selectedRecoveryAttempt.user.id,
+ selectedRecoveryAttempt.emergencyContact
+ .id,
+ );
+ setActiveSheet(undefined);
+ },
+ })
+ }
+ disabled={isSubmitting}
+ >
+ Reject recovery
+ </ActionButton>
+ )}
+ </LegacyActionSheet>
+ </>
+ );
+};
diff --git a/web/packages/contacts/legacy/components/LegacyIdentityRow.tsx b/web/packages/contacts/legacy/components/LegacyIdentityRow.tsx
new file mode 100644
index 0000000000..caeab672b8
--- /dev/null
+++ b/web/packages/contacts/legacy/components/LegacyIdentityRow.tsx
@@ -0,0 +1,124 @@
+import CheckIcon from "@mui/icons-material/Check";
+import {
+ Avatar,
+ Box,
+ IconButton,
+ Stack,
+ Typography,
+ type SxProps,
+ type Theme,
+} from "@mui/material";
+import { isSxArray } from "ente-base/components/utils/sx";
+import React from "react";
+import {
+ useResolvedContactAvatar,
+ useResolvedContactDisplay,
+} from "../../index";
+
+interface LegacyIdentityRowProps {
+ email: string;
+ userID?: number;
+ subtitle?: string;
+ statusIndicator?: React.ReactNode;
+ primaryColor?: string;
+ selected?: boolean;
+ onClick?: () => void;
+ action?: React.ReactNode;
+ sx?: SxProps<Theme>;
+}
+
+export const LegacyIdentityRow: React.FC<LegacyIdentityRowProps> = ({
+ email,
+ userID,
+ subtitle,
+ statusIndicator,
+ primaryColor,
+ selected,
+ onClick,
+ action,
+ sx,
+}) => {
+ const lookup = userID === undefined ? { email } : { email, userID };
+ const resolvedDisplay = useResolvedContactDisplay(lookup);
+ const resolvedAvatar = useResolvedContactAvatar(lookup);
+ const label = resolvedDisplay.primaryLabel || email;
+ const secondaryLabel =
+ label.toLowerCase() === email.toLowerCase() ? subtitle : email;
+ const subtext =
+ subtitle && secondaryLabel !== subtitle
+ ? `${secondaryLabel} β€’ ${subtitle}`
+ : secondaryLabel || subtitle;
+
+ return (
+ <Stack
+ direction="row"
+ onClick={onClick}
+ sx={[
+ {
+ alignItems: "center",
+ gap: 1.25,
+ px: 2,
+ py: 1.5,
+ borderRadius: "20px",
+ transition: "background-color 160ms ease",
+ cursor: onClick ? "pointer" : "default",
+ "&:hover": onClick
+ ? { backgroundColor: "fill.faintHover" }
+ : undefined,
+ },
+ ...(sx ? (isSxArray(sx) ? sx : [sx]) : []),
+ ]}
+ >
+ <Avatar
+ src={resolvedAvatar.avatarURL}
+ sx={{
+ width: 28,
+ height: 28,
+ fontSize: 14,
+ bgcolor: "fill.faintHover",
+ color: "text.base",
+ }}
+ >
+ {resolvedAvatar.initial}
+ </Avatar>
+ <Box sx={{ flex: 1, minWidth: 0 }}>
+ <Stack
+ direction="row"
+ sx={{ alignItems: "center", gap: 0.75, minWidth: 0 }}
+ >
+ <Typography
+ variant="body"
+ sx={{ fontWeight: 600, color: primaryColor }}
+ noWrap
+ >
+ {label}
+ </Typography>
+ {statusIndicator}
+ </Stack>
+ {subtext && (
+ <Typography
+ variant="small"
+ sx={{ color: "text.muted", mt: 0.25 }}
+ noWrap
+ >
+ {subtext}
+ </Typography>
+ )}
+ </Box>
+ {selected ? (
+ <IconButton
+ size="small"
+ disableRipple
+ sx={{
+ color: "accent.main",
+ "&:hover": { backgroundColor: "transparent" },
+ }}
+ >
+ <CheckIcon fontSize="small" />
+ </IconButton>
+ ) : (
+ action
+ )}
+ </Stack>
+ );
+};
diff --git a/web/packages/contacts/legacy/components/LegacyPageFrame.tsx b/web/packages/contacts/legacy/components/LegacyPageFrame.tsx
new file mode 100644
index 0000000000..27786d246a
--- /dev/null
+++ b/web/packages/contacts/legacy/components/LegacyPageFrame.tsx
@@ -0,0 +1,47 @@
+import ArrowBackOutlinedIcon from "@mui/icons-material/ArrowBackOutlined";
+import { IconButton, Stack, Typography } from "@mui/material";
+import React from "react";
+
+interface LegacyPageFrameProps {
+ title: string;
+ caption?: React.ReactNode;
+ description?: React.ReactNode;
+ onBack: () => void;
+ children: React.ReactNode;
+}
+
+export const LegacyPageFrame: React.FC<LegacyPageFrameProps> = ({
+ title,
+ caption,
+ description,
+ onBack,
+ children,
+}) => (
+ <Stack sx={{ px: 2, pt: 2, pb: 2, gap: 3 }}>
+ <Stack direction="row" sx={{ alignItems: "center" }}>
+ <IconButton onClick={onBack} color="primary" sx={{ ml: -0.5 }}>
+ <ArrowBackOutlinedIcon />
+ </IconButton>
+ </Stack>
+ <Stack sx={{ gap: 0.5 }}>
+ <Typography variant="h3">{title}</Typography>
+ {caption && (
+ <Typography
+ variant="small"
+ sx={{ color: "text.muted", wordBreak: "break-word" }}
+ >
+ {caption}
+ </Typography>
+ )}
+ </Stack>
+ {description && (
+ <Typography
+ variant="body"
+ sx={{ color: "text.muted", lineHeight: 1.5 }}
+ >
+ {description}
+ </Typography>
+ )}
+ {children}
+ </Stack>
+);
diff --git a/web/packages/contacts/legacy/components/LegacyRecoveryDayPicker.tsx b/web/packages/contacts/legacy/components/LegacyRecoveryDayPicker.tsx
new file mode 100644
index 0000000000..e371e06300
--- /dev/null
+++ b/web/packages/contacts/legacy/components/LegacyRecoveryDayPicker.tsx
@@ -0,0 +1,48 @@
+import { Stack, ToggleButton, ToggleButtonGroup } from "@mui/material";
+import React from "react";
+
+export const legacyRecoveryDayOptions = [7, 14, 30] as const;
+
+interface LegacyRecoveryDayPickerProps {
+ selectedDays: number;
+ onChange: (days: number) => void;
+}
+
+export const LegacyRecoveryDayPicker: React.FC<
+ LegacyRecoveryDayPickerProps
+> = ({ selectedDays, onChange }) => (
+ <ToggleButtonGroup
+ exclusive
+ value={selectedDays}
+ onChange={(_, value: number | null) => value && onChange(value)}
+ fullWidth
+ sx={{
+ gap: 1,
+ "& .MuiToggleButton-root": {
+ flex: 1,
+ px: 1.5,
+ py: 1.25,
+ border: 0,
+ borderRadius: "14px !important",
+ textTransform: "none",
+ fontWeight: 600,
+ color: "text.base",
+ backgroundColor: "fill.faint",
+ },
+ "& .MuiToggleButton-root.Mui-selected": {
+ color: "#FFFFFF",
+ backgroundColor: "accent.main",
+ },
+ "& .MuiToggleButton-root:hover": { backgroundColor: "fill.muted" },
+ "& .MuiToggleButton-root.Mui-selected:hover": {
+ backgroundColor: "accent.main",
+ },
+ }}
+ >
+ {legacyRecoveryDayOptions.map((days) => (
+ <ToggleButton key={days} value={days}>
+ <Stack sx={{ alignItems: "center" }}>{days} days</Stack>
+ </ToggleButton>
+ ))}
+ </ToggleButtonGroup>
+);
diff --git a/web/packages/contacts/legacy/components/LegacyResetPasswordPage.tsx b/web/packages/contacts/legacy/components/LegacyResetPasswordPage.tsx
new file mode 100644
index 0000000000..338d65cbd0
--- /dev/null
+++ b/web/packages/contacts/legacy/components/LegacyResetPasswordPage.tsx
@@ -0,0 +1,135 @@
+import { Input, Stack, TextField } from "@mui/material";
+import { isWeakPassword } from "ente-accounts-rs/utils/password";
+import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";
+import React, { useState } from "react";
+import type { LegacyRecoverySession } from "..";
+import { ActionButton } from "./ActionButton";
+import { LegacyPageFrame } from "./LegacyPageFrame";
+
+interface LegacyResetPasswordPageProps {
+ session: LegacyRecoverySession;
+ isSubmitting: boolean;
+ onBack: () => void;
+ onSubmit: (password: string) => Promise<void>;
+}
+
+export const LegacyResetPasswordPage: React.FC<
+ LegacyResetPasswordPageProps
+> = ({ session, isSubmitting, onBack, onSubmit }) => {
+ const email = session.user.email;
+ const [password, setPassword] = useState("");
+ const [confirmPassword, setConfirmPassword] = useState("");
+ const [showPassword, setShowPassword] = useState(false);
+ const [showConfirmPassword, setShowConfirmPassword] = useState(false);
+ const [errorMessage, setErrorMessage] = useState<string | undefined>();
+
+ const passwordMismatch =
+ !!confirmPassword && password !== confirmPassword
+ ? "Passwords do not match."
+ : undefined;
+ const passwordTooWeak =
+ !!password && isWeakPassword(password)
+ ? "Use a stronger password."
+ : undefined;
+
+ const canSubmit =
+ !!password &&
+ !!confirmPassword &&
+ !isWeakPassword(password) &&
+ password === confirmPassword &&
+ !isSubmitting;
+
+ const handleSubmit = async () => {
+ setErrorMessage(undefined);
+ try {
+ await onSubmit(password);
+ } catch (error) {
+ setErrorMessage(
+ error instanceof Error
+ ? error.message
+ : "Something went wrong while resetting the password.",
+ );
+ }
+ };
+
+ return (
+ <LegacyPageFrame
+ title="Reset password"
+ description={`Enter new password for ${email} account. You will be able to use this password to login into ${email} account.`}
+ onBack={onBack}
+ >
+ <Stack sx={{ gap: 2, px: 0.5 }}>
+ <Input
+ sx={{ display: "none" }}
+ name="email"
+ type="email"
+ autoComplete="username"
+ value={email}
+ />
+ <TextField
+ autoFocus
+ fullWidth
+ type={showPassword ? "text" : "password"}
+ label="Password"
+ autoComplete="new-password"
+ value={password}
+ onChange={(event) => {
+ setPassword(event.target.value);
+ setErrorMessage(undefined);
+ }}
+ error={!!passwordTooWeak}
+ helperText={passwordTooWeak ?? " "}
+ slotProps={{
+ input: {
+ endAdornment: (
+ <ShowHidePasswordInputAdornment
+ showPassword={showPassword}
+ onToggle={() =>
+ setShowPassword((value) => !value)
+ }
+ />
+ ),
+ },
+ }}
+ />
+ <TextField
+ fullWidth
+ type={showConfirmPassword ? "text" : "password"}
+ label="Confirm password"
+ autoComplete="new-password"
+ value={confirmPassword}
+ onChange={(event) => {
+ setConfirmPassword(event.target.value);
+ setErrorMessage(undefined);
+ }}
+ error={!!(passwordMismatch || errorMessage)}
+ helperText={passwordMismatch ?? errorMessage ?? " "}
+ slotProps={{
+ input: {
+ endAdornment: (
+ <ShowHidePasswordInputAdornment
+ showPassword={showConfirmPassword}
+ onToggle={() =>
+ setShowConfirmPassword(
+ (value) => !value,
+ )
+ }
+ />
+ ),
+ },
+ }}
+ />
+ <ActionButton
+ fullWidth
+ buttonType="primary"
+ loading={isSubmitting}
+ disabled={!canSubmit}
+ onClick={() => void handleSubmit()}
+ sx={{ mt: 2 }}
+ >
+ Reset password
+ </ActionButton>
+ </Stack>
+ </LegacyPageFrame>
+ );
+};
diff --git a/web/packages/contacts/legacy/components/LegacyTrustedAccountPage.tsx b/web/packages/contacts/legacy/components/LegacyTrustedAccountPage.tsx
new file mode 100644
index 0000000000..3188b4520c
--- /dev/null
+++ b/web/packages/contacts/legacy/components/LegacyTrustedAccountPage.tsx
@@ -0,0 +1,145 @@
+import { Stack, Typography } from "@mui/material";
+import React from "react";
+import type { LegacyContactRecord, LegacyRecoverySession } from "..";
+import { ActionButton } from "./ActionButton";
+import { LegacyPageFrame } from "./LegacyPageFrame";
+
+interface LegacyTrustedAccountPageProps {
+ contact: LegacyContactRecord;
+ activeRecovery: LegacyRecoverySession | undefined;
+ isSubmitting: boolean;
+ waitLabel: string | undefined;
+ onBack: () => void;
+ onStartRecovery: () => void;
+ onRecoverAccount: () => void;
+ onCancelRecovery: () => void;
+ onRemoveContact: () => void;
+}
+
+const trustedAccountDescription = (
+ email: string,
+ recoveryNoticeInDays: number,
+ activeRecovery: LegacyRecoverySession | undefined,
+ waitLabel: string | undefined,
+) => {
+ if (!activeRecovery) {
+ return `You can recover ${email}'s account in ${recoveryNoticeInDays} days after starting the recovery process.`;
+ }
+ if (activeRecovery.status === "READY") {
+ return `You can now recover ${email}'s account by setting a new password.`;
+ }
+ return `You can recover ${email}'s account after ${waitLabel}.`;
+};
+
+export const LegacyTrustedAccountPage: React.FC<
+ LegacyTrustedAccountPageProps
+> = ({
+ contact,
+ activeRecovery,
+ isSubmitting,
+ waitLabel,
+ onBack,
+ onStartRecovery,
+ onRecoverAccount,
+ onCancelRecovery,
+ onRemoveContact,
+}) => {
+ const email = contact.user.email;
+ const isReady = activeRecovery?.status === "READY";
+
+ return (
+ <LegacyPageFrame
+ title="Recover account"
+ caption={email}
+ description={trustedAccountDescription(
+ email,
+ contact.recoveryNoticeInDays,
+ activeRecovery,
+ waitLabel,
+ )}
+ onBack={onBack}
+ >
+ <Stack sx={{ gap: 1.5, px: 0.5 }}>
+ {!activeRecovery && (
+ <ActionButton
+ fullWidth
+ buttonType="primary"
+ loading={isSubmitting}
+ onClick={onStartRecovery}
+ >
+ Start recovery
+ </ActionButton>
+ )}
+
+ {isReady && (
+ <>
+ <ActionButton
+ fullWidth
+ buttonType="primary"
+ loading={isSubmitting}
+ onClick={onRecoverAccount}
+ >
+ Recover account
+ </ActionButton>
+ <ActionButton
+ buttonType="tertiaryCritical"
+ onClick={onCancelRecovery}
+ disabled={isSubmitting}
+ sx={{ alignSelf: "center" }}
+ >
+ Cancel recovery
+ </ActionButton>
+ <Typography
+ variant="body"
+ sx={{ color: "text.muted", lineHeight: 1.5, mt: 2 }}
+ >
+ Or remove yourself as {email}'s trusted contact
+ </Typography>
+ <ActionButton
+ fullWidth
+ buttonType="critical"
+ loading={isSubmitting}
+ onClick={onRemoveContact}
+ >
+ Remove contact
+ </ActionButton>
+ </>
+ )}
+
+ {activeRecovery && !isReady && (
+ <>
+ <ActionButton
+ fullWidth
+ buttonType="secondary"
+ loading={isSubmitting}
+ onClick={onCancelRecovery}
+ >
+ Cancel recovery
+ </ActionButton>
+ <ActionButton
+ fullWidth
+ buttonType="critical"
+ loading={isSubmitting}
+ onClick={onRemoveContact}
+ sx={{ mt: 1 }}
+ >
+ Remove contact
+ </ActionButton>
+ </>
+ )}
+
+ {!activeRecovery && (
+ <ActionButton
+ fullWidth
+ buttonType="critical"
+ loading={isSubmitting}
+ onClick={onRemoveContact}
+ sx={{ mt: 1 }}
+ >
+ Remove contact
+ </ActionButton>
+ )}
+ </Stack>
+ </LegacyPageFrame>
+ );
+};
diff --git a/web/packages/contacts/legacy/index.ts b/web/packages/contacts/legacy/index.ts
new file mode 100644
index 0000000000..6bcbf59d20
--- /dev/null
+++ b/web/packages/contacts/legacy/index.ts
@@ -0,0 +1,26 @@
+export {
+ legacyAddContact,
+ legacyApproveRecovery,
+ legacyChangePassword,
+ legacyGetInfo,
+ legacyPublicKey,
+ legacyRecoveryBundle,
+ legacyRejectRecovery,
+ legacyStartRecovery,
+ legacyStopRecovery,
+ legacyUpdateContact,
+ legacyUpdateRecoveryNotice,
+ legacyVerificationID,
+} from "../index";
+export { LegacyDrawerContent } from "./components/LegacyDrawerContent";
+export { mergeLegacySuggestedUsers } from "./suggestions";
+export type {
+ LegacyContactRecord,
+ LegacyContactState,
+ LegacyInfo,
+ LegacyRecoveryBundle,
+ LegacyRecoverySession,
+ LegacyRecoveryStatus,
+ LegacySuggestedUser,
+ LegacyUser,
+} from "./types";
diff --git a/web/packages/contacts/legacy/suggestions.ts b/web/packages/contacts/legacy/suggestions.ts
new file mode 100644
index 0000000000..3e798beff6
--- /dev/null
+++ b/web/packages/contacts/legacy/suggestions.ts
@@ -0,0 +1,21 @@
+import type { LegacySuggestedUser } from "./types";
+
+export const mergeLegacySuggestedUsers = (
+ ...groups: (LegacySuggestedUser[] | undefined)[]
+): LegacySuggestedUser[] => {
+ const byEmail = new Map<string, LegacySuggestedUser>();
+
+ for (const group of groups) {
+ for (const user of group ?? []) {
+ const email = user.email.trim();
+ if (!email) {
+ continue;
+ }
+ byEmail.set(email.toLowerCase(), { id: user.id, email });
+ }
+ }
+
+ return [...byEmail.values()].sort((a, b) =>
+ a.email.localeCompare(b.email, undefined, { sensitivity: "base" }),
+ );
+};
diff --git a/web/packages/contacts/legacy/types.ts b/web/packages/contacts/legacy/types.ts
new file mode 100644
index 0000000000..6643c4578c
--- /dev/null
+++ b/web/packages/contacts/legacy/types.ts
@@ -0,0 +1,14 @@
+export type {
+ LegacyContactRecord,
+ LegacyContactState,
+ LegacyInfo,
+ LegacyRecoveryBundle,
+ LegacyRecoverySession,
+ LegacyRecoveryStatus,
+ LegacyUser,
+} from "../types";
+
+export interface LegacySuggestedUser {
+ id?: number;
+ email: string;
+}
diff --git a/web/packages/contacts/package.json b/web/packages/contacts/package.json
index 685c2bcc73..1ab06ef687 100644
--- a/web/packages/contacts/package.json
+++ b/web/packages/contacts/package.json
@@ -8,6 +8,9 @@
"test": "vitest"
},
"dependencies": {
+ "@mui/icons-material": "^7.3.4",
+ "@mui/material": "^7.3.4",
+ "ente-accounts-rs": "*",
"ente-base": "*",
"ente-wasm": "*",
"react": "^19.2.0",
diff --git a/web/packages/contacts/tsconfig.json b/web/packages/contacts/tsconfig.json
index da0ebfdddb..73f42a78cb 100644
--- a/web/packages/contacts/tsconfig.json
+++ b/web/packages/contacts/tsconfig.json
@@ -1,4 +1,12 @@
{
"extends": "ente-build-config/tsconfig-typecheck.json",
- "include": [".", "../base/global-electron.d.ts"]
+ "compilerOptions": {
+ /* MUI doesn't work with exactOptionalPropertyTypes yet. */
+ "exactOptionalPropertyTypes": false
+ },
+ "include": [
+ ".",
+ "../base/global-electron.d.ts",
+ "../base/components/utils/mui-theme.d.ts"
+ ]
}
diff --git a/web/packages/contacts/types.ts b/web/packages/contacts/types.ts
index 489961f215..8e791d7c1a 100644
--- a/web/packages/contacts/types.ts
+++ b/web/packages/contacts/types.ts
@@ -36,3 +36,51 @@ export interface ResolvedContactDisplay {
export interface ResolvedContactAvatar extends ResolvedContactDisplay {
avatarURL: string | undefined;
}
+
+export type LegacyContactState =
+ | "INVITED"
+ | "REVOKED"
+ | "ACCEPTED"
+ | "CONTACT_LEFT"
+ | "CONTACT_DENIED";
+
+export type LegacyRecoveryStatus =
+ | "INITIATED"
+ | "WAITING"
+ | "REJECTED"
+ | "RECOVERED"
+ | "STOPPED"
+ | "READY";
+
+export interface LegacyUser {
+ id: number;
+ email: string;
+}
+
+export interface LegacyContactRecord {
+ user: LegacyUser;
+ emergencyContact: LegacyUser;
+ state: LegacyContactState;
+ recoveryNoticeInDays: number;
+}
+
+export interface LegacyRecoverySession {
+ id: string;
+ user: LegacyUser;
+ emergencyContact: LegacyUser;
+ status: LegacyRecoveryStatus;
+ waitTill: number;
+ createdAt: number;
+}
+
+export interface LegacyInfo {
+ contacts: LegacyContactRecord[];
+ recoverSessions: LegacyRecoverySession[];
+ othersEmergencyContact: LegacyContactRecord[];
+ othersRecoverySession: LegacyRecoverySession[];
+}
+
+export interface LegacyRecoveryBundle {
+ recoveryKey: string;
+ userKeyAttributes: Record<string, unknown>;
+}
diff --git a/web/packages/wasm/Cargo.lock b/web/packages/wasm/Cargo.lock
index 15c1923827..36b5e35a28 100644
--- a/web/packages/wasm/Cargo.lock
+++ b/web/packages/wasm/Cargo.lock
@@ -12,6 +12,12 @@ dependencies = [
"generic-array",
]
+[[package]]
+name = "anyhow"
+version = "1.0.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
+
[[package]]
name = "argon2"
version = "0.5.3"
@@ -311,7 +317,9 @@ dependencies = [
"md-5",
"serde",
"serde_json",
+ "sha2",
"thiserror",
+ "uuid",
]
[[package]]
@@ -377,6 +385,12 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
[[package]]
name = "form_urlencoded"
version = "1.2.2"
@@ -458,11 +472,24 @@ dependencies = [
"cfg-if",
"js-sys",
"libc",
- "r-efi",
+ "r-efi 5.3.0",
"wasip2",
"wasm-bindgen",
]
+[[package]]
+name = "getrandom"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 6.0.0",
+ "wasip2",
+ "wasip3",
+]
+
[[package]]
name = "h2"
version = "0.4.13"
@@ -482,12 +509,27 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash",
+]
+
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
[[package]]
name = "hex"
version = "0.4.3"
@@ -689,6 +731,12 @@ dependencies = [
"zerovec",
]
+[[package]]
+name = "id-arena"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
+
[[package]]
name = "idna"
version = "1.1.0"
@@ -717,7 +765,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
dependencies = [
"equivalent",
- "hashbrown",
+ "hashbrown 0.16.1",
+ "serde",
+ "serde_core",
]
[[package]]
@@ -768,6 +818,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+[[package]]
+name = "leb128fmt"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+
[[package]]
name = "libc"
version = "0.2.180"
@@ -929,6 +985,16 @@ dependencies = [
"zerocopy",
]
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.105"
@@ -1008,6 +1074,12 @@ version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
[[package]]
name = "rand"
version = "0.9.2"
@@ -1578,6 +1650,12 @@ dependencies = [
"tinyvec",
]
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
[[package]]
name = "universal-hash"
version = "0.5.1"
@@ -1612,6 +1690,17 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+[[package]]
+name = "uuid"
+version = "1.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9"
+dependencies = [
+ "getrandom 0.4.2",
+ "js-sys",
+ "wasm-bindgen",
+]
+
[[package]]
name = "version_check"
version = "0.9.5"
@@ -1642,6 +1731,15 @@ dependencies = [
"wit-bindgen",
]
+[[package]]
+name = "wasip3"
+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
+dependencies = [
+ "wit-bindgen",
+]
+
[[package]]
name = "wasm-bindgen"
version = "0.2.108"
@@ -1701,6 +1799,40 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "wasm-encoder"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
+dependencies = [
+ "leb128fmt",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.15.5",
+ "indexmap",
+ "semver",
+]
+
[[package]]
name = "web-sys"
version = "0.3.85"
@@ -1926,6 +2058,88 @@ name = "wit-bindgen"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+dependencies = [
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "prettyplease",
+ "syn",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
+dependencies = [
+ "anyhow",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+ "wasmparser",
+]
[[package]]
name = "writeable"
diff --git a/web/packages/wasm/src/contacts.rs b/web/packages/wasm/src/contacts.rs
index dfad4a456d..4948189078 100644
--- a/web/packages/wasm/src/contacts.rs
+++ b/web/packages/wasm/src/contacts.rs
@@ -1,9 +1,10 @@
//! WASM bindings for contacts sync and attachment reads.
use ente_contacts::{
- ContactsCtx, ContactsError as CoreContactsError, OpenContactsCtxInput, WrappedRootContactKey,
+ ContactsCtx, ContactsError as CoreContactsError, LegacyContactState, OpenContactsCtxInput,
+ WrappedRootContactKey,
};
-use ente_core::crypto;
+use ente_core::{auth::KeyAttributes, crypto};
use serde::{Deserialize, Serialize};
use serde_wasm_bindgen as swb;
use wasm_bindgen::prelude::*;
@@ -35,6 +36,7 @@ impl From<CoreContactsError> for ContactsError {
let code = match &e {
CoreContactsError::Http(_) => "http",
CoreContactsError::Crypto(_) => "crypto",
+ CoreContactsError::Auth(_) => "auth",
CoreContactsError::InvalidInput(_) => "invalid_input",
CoreContactsError::MissingEncryptedData => "missing_encrypted_data",
CoreContactsError::MissingEncryptedKey => "missing_encrypted_key",
@@ -163,4 +165,145 @@ impl ContactsCtxHandle {
.await
.map_err(Into::into)
}
+
+ /// Fetch legacy/emergency contact info for the current user.
+ pub async fn legacy_get_info(&self) -> Result<JsValue, ContactsError> {
+ let info = self.inner.legacy_info().await?;
+ swb::to_value(&info).map_err(Into::into)
+ }
+
+ /// Lookup a user's public key by email for legacy verify/add flows.
+ pub async fn legacy_public_key(&self, email: String) -> Result<JsValue, ContactsError> {
+ let public_key = self.inner.legacy_public_key(&email).await?;
+ swb::to_value(&public_key).map_err(Into::into)
+ }
+
+ /// Generate the mnemonic-style verification ID for a public key.
+ pub fn legacy_verification_id(&self, public_key_b64: String) -> Result<String, ContactsError> {
+ self.inner
+ .legacy_verification_id(&public_key_b64)
+ .map_err(Into::into)
+ }
+
+ /// Add a trusted legacy contact after sealing the current user's recovery key in Rust.
+ pub async fn legacy_add_contact(
+ &self,
+ email: String,
+ current_user_key_attrs: JsValue,
+ recovery_notice_in_days: Option<i32>,
+ ) -> Result<(), ContactsError> {
+ let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
+ self.inner
+ .legacy_add_contact(&email, &current_user_key_attrs, recovery_notice_in_days)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Update a legacy contact relationship state.
+ pub async fn legacy_update_contact(
+ &self,
+ user_id: i64,
+ emergency_contact_id: i64,
+ state: JsValue,
+ ) -> Result<(), ContactsError> {
+ let state: LegacyContactState = swb::from_value(state)?;
+ self.inner
+ .legacy_update_contact(user_id, emergency_contact_id, state)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Update the notice period for an existing trusted contact.
+ pub async fn legacy_update_recovery_notice(
+ &self,
+ emergency_contact_id: i64,
+ recovery_notice_in_days: i32,
+ ) -> Result<(), ContactsError> {
+ self.inner
+ .legacy_update_recovery_notice(
+ emergency_contact_id,
+ recovery_notice_in_days,
+ )
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Start a recovery flow as the trusted contact.
+ pub async fn legacy_start_recovery(
+ &self,
+ user_id: i64,
+ emergency_contact_id: i64,
+ ) -> Result<(), ContactsError> {
+ self.inner
+ .legacy_start_recovery(user_id, emergency_contact_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Stop a recovery flow as the trusted contact.
+ pub async fn legacy_stop_recovery(
+ &self,
+ recovery_id: String,
+ user_id: i64,
+ emergency_contact_id: i64,
+ ) -> Result<(), ContactsError> {
+ self.inner
+ .legacy_stop_recovery(&recovery_id, user_id, emergency_contact_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Reject a recovery flow as the account owner.
+ pub async fn legacy_reject_recovery(
+ &self,
+ recovery_id: String,
+ user_id: i64,
+ emergency_contact_id: i64,
+ ) -> Result<(), ContactsError> {
+ self.inner
+ .legacy_reject_recovery(&recovery_id, user_id, emergency_contact_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Approve a recovery flow as the account owner.
+ pub async fn legacy_approve_recovery(
+ &self,
+ recovery_id: String,
+ user_id: i64,
+ emergency_contact_id: i64,
+ ) -> Result<(), ContactsError> {
+ self.inner
+ .legacy_approve_recovery(&recovery_id, user_id, emergency_contact_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ /// Fetch and decrypt the recovery payload for a ready session.
+ pub async fn legacy_recovery_bundle(
+ &self,
+ recovery_id: String,
+ current_user_key_attrs: JsValue,
+ ) -> Result<JsValue, ContactsError> {
+ let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
+ let bundle = self
+ .inner
+ .legacy_recovery_bundle(&recovery_id, &current_user_key_attrs)
+ .await?;
+ swb::to_value(&bundle).map_err(Into::into)
+ }
+
+ /// Complete the legacy password reset flow fully in Rust.
+ pub async fn legacy_change_password(
+ &self,
+ recovery_id: String,
+ current_user_key_attrs: JsValue,
+ new_password: String,
+ ) -> Result<(), ContactsError> {
+ let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
+ self.inner
+ .legacy_change_password(&recovery_id, &current_user_key_attrs, &new_password)
+ .await
+ .map_err(Into::into)
+ }
}