Skip to content

armgit / ente

Public Imported from GitHub
0

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

Introduce shared authenticated sessions

Manav Rathi4de32c355a11
diff --git a/mobile/apps/locker/lib/services/frb_legacy_kit_rust_api.dart b/mobile/apps/locker/lib/services/frb_legacy_kit_rust_api.dart
index 40871a376c..1ff3e4b62e 100644
--- a/mobile/apps/locker/lib/services/frb_legacy_kit_rust_api.dart
+++ b/mobile/apps/locker/lib/services/frb_legacy_kit_rust_api.dart
@@ -4,7 +4,8 @@ import "package:ente_base/models/key_attributes.dart";
import "package:ente_contacts/contacts.dart" as contacts;
import "package:ente_legacy/models/legacy_kit_models.dart";
import "package:ente_legacy/services/legacy_kit_rust_api.dart";
-import "package:locker/src/rust/api/contacts.dart" as rust;
+import "package:locker/src/rust/api/legacy.dart" as rust;
+import "package:locker/src/rust/api/session.dart" as rust_session;
class FrbLegacyKitRustApi implements LegacyKitRustApi {
const FrbLegacyKitRustApi();
@@ -14,34 +15,31 @@ class FrbLegacyKitRustApi implements LegacyKitRustApi {
contacts.ContactsSession session,
Uint8List accountKey,
) async {
- final opened = await rust.openContactsCtx(
- input: rust.OpenContactsCtxInput(
- baseUrl: session.baseUrl,
- authToken: session.authToken,
- userId: session.userId,
- masterKey: accountKey,
- userAgent: session.userAgent,
- clientPackage: session.clientPackage,
- clientVersion: session.clientVersion,
- ),
+ final opened = rust_session.openSession(
+ baseUrl: session.baseUrl,
+ authToken: session.authToken,
+ masterKey: accountKey,
+ userAgent: session.userAgent,
+ clientPackage: session.clientPackage,
+ clientVersion: session.clientVersion,
);
- return _FrbLegacyKitRustContext(opened.ctx);
+ return _FrbLegacyKitRustContext(opened);
}
}
class _FrbLegacyKitRustContext implements LegacyKitRustContext {
- final rust.ContactsCtx _inner;
+ final rust_session.Session _session;
- const _FrbLegacyKitRustContext(this._inner);
+ const _FrbLegacyKitRustContext(this._session);
@override
Future<void> updateAuthToken(String authToken) {
- return _run(() => _inner.updateAuthToken(authToken: authToken));
+ return _session.updateAuthToken(authToken: authToken);
}
@override
Future<List<LegacyKit>> legacyKits() async {
- final kits = await _run(_inner.legacyKits);
+ final kits = await _run(() => rust.kits(session: _session));
return kits.map(_fromRustKit).toList(growable: false);
}
@@ -52,7 +50,8 @@ class _FrbLegacyKitRustContext implements LegacyKitRustContext {
required int noticePeriodInHours,
}) async {
final result = await _run(
- () => _inner.legacyKitCreate(
+ () => rust.createKit(
+ session: _session,
currentUserKeyAttrs: _toRustKeyAttributes(currentUserKeyAttrs),
partNames: partNames,
noticePeriodInHours: noticePeriodInHours,
@@ -67,7 +66,7 @@ class _FrbLegacyKitRustContext implements LegacyKitRustContext {
@override
Future<List<LegacyKitShare>> legacyKitDownloadShares(String kitId) async {
final shares = await _run(
- () => _inner.legacyKitDownloadShares(kitId: kitId),
+ () => rust.downloadKitShares(session: _session, kitId: kitId),
);
return shares.map(_fromRustShare).toList(growable: false);
}
@@ -77,7 +76,7 @@ class _FrbLegacyKitRustContext implements LegacyKitRustContext {
String kitId,
) async {
final details = await _run(
- () => _inner.legacyKitRecoverySession(kitId: kitId),
+ () => rust.kitRecoverySession(session: _session, kitId: kitId),
);
return LegacyKitOwnerRecoverySessionDetails(
session: details.session == null
@@ -101,7 +100,8 @@ class _FrbLegacyKitRustContext implements LegacyKitRustContext {
required int noticePeriodInHours,
}) {
return _run(
- () => _inner.legacyKitUpdateRecoveryNotice(
+ () => rust.updateKitRecoveryNotice(
+ session: _session,
kitId: kitId,
noticePeriodInHours: noticePeriodInHours,
),
@@ -110,19 +110,19 @@ class _FrbLegacyKitRustContext implements LegacyKitRustContext {
@override
Future<void> legacyKitBlockRecovery(String kitId) {
- return _run(() => _inner.legacyKitBlockRecovery(kitId: kitId));
+ return _run(() => rust.blockKitRecovery(session: _session, kitId: kitId));
}
@override
Future<void> legacyKitDelete(String kitId) {
- return _run(() => _inner.legacyKitDelete(kitId: kitId));
+ return _run(() => rust.deleteKit(session: _session, kitId: kitId));
}
}
Future<T> _run<T>(Future<T> Function() action) async {
try {
return await action();
- } on rust.ContactsError_ActiveRecoverySession {
+ } on rust.LegacyError_ActiveRecoverySession {
throw LegacyKitActiveRecoverySessionException();
}
}
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 1a626a7808..1f9ef338ec 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2609,6 +2609,7 @@ dependencies = [
"ente-accounts",
"ente-core",
"ente-legacy",
+ "ente-wasm-core",
"ente-wasm-log",
"js-sys",
"serde",
@@ -2645,6 +2646,7 @@ version = "0.0.0"
dependencies = [
"ente-contacts",
"ente-core",
+ "ente-wasm-core",
"ente-wasm-log",
"js-sys",
"serde",
@@ -2753,6 +2755,7 @@ version = "0.0.0"
dependencies = [
"ente-contacts",
"ente-core",
+ "ente-wasm-core",
"ente-wasm-log",
"js-sys",
"serde",
@@ -2849,6 +2852,16 @@ dependencies = [
"log",
]
+[[package]]
+name = "ente-wasm-core"
+version = "0.0.0"
+dependencies = [
+ "ente-core",
+ "js-sys",
+ "thiserror 2.0.18",
+ "wasm-bindgen",
+]
+
[[package]]
name = "ente-wasm-log"
version = "0.0.0"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 93c4953006..ceaa6648c5 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -13,6 +13,7 @@ members = [
"bindings/uniffi/log",
"bindings/wasm/cast",
"bindings/wasm/core",
+ "bindings/wasm/core-wasm",
"bindings/wasm/ensu",
"bindings/wasm/legacy",
"bindings/wasm/log",
@@ -55,6 +56,7 @@ ente-photos = { path = "crates/photos" }
ente-space = { path = "crates/space" }
ente-test-support = { path = "crates/test-support" }
ente-uniffi-log = { path = "bindings/uniffi/log" }
+ente-wasm-core = { path = "bindings/wasm/core" }
ente-wasm-log = { path = "bindings/wasm/log" }
flutter_rust_bridge = "=2.12.0"
flutter_rust_bridge_codegen = "=2.12.0"
diff --git a/rust/bindings/frb/locker/src/api/contacts.rs b/rust/bindings/frb/locker/src/api/contacts.rs
index 5da4e5c90f..19acf869fd 100644
--- a/rust/bindings/frb/locker/src/api/contacts.rs
+++ b/rust/bindings/frb/locker/src/api/contacts.rs
@@ -1,15 +1,14 @@
use std::sync::Arc;
use ente_core::{
+ Session,
crypto::SecretVec,
- http::{Api, ApiConfig, Auth, Http},
+ http::{ApiConfig, Auth},
};
-use ente_legacy::{LegacyClient, LegacyKitOwnerRecoverySession, LegacyKitRecoveryInitiator};
use flutter_rust_bridge::frb;
#[frb]
pub enum ContactsError {
- ActiveRecoverySession { message: String },
Other { message: String },
}
@@ -21,18 +20,6 @@ impl From<ente_contacts::Error> for ContactsError {
}
}
-impl From<ente_legacy::Error> for ContactsError {
- fn from(e: ente_legacy::Error) -> Self {
- use ente_legacy::Error as E;
-
- let message = ente_core::error::chain(&e);
- match e {
- E::ActiveRecoverySession => Self::ActiveRecoverySession { message },
- _ => Self::Other { message },
- }
- }
-}
-
#[frb]
#[derive(Clone)]
pub struct WrappedRootContactKey {
@@ -58,43 +45,6 @@ impl From<WrappedRootContactKey> for ente_contacts::WrappedRootContactKey {
}
}
-#[frb]
-#[derive(Clone)]
-pub struct AccountKeyAttributes {
- pub kek_salt: String,
- pub encrypted_key: String,
- pub key_decryption_nonce: String,
- pub public_key: String,
- pub encrypted_secret_key: String,
- pub secret_key_decryption_nonce: String,
- pub mem_limit: u32,
- pub ops_limit: u32,
- pub master_key_encrypted_with_recovery_key: Option<String>,
- pub master_key_decryption_nonce: Option<String>,
- pub recovery_key_encrypted_with_master_key: Option<String>,
- pub recovery_key_decryption_nonce: Option<String>,
-}
-
-impl From<AccountKeyAttributes> for ente_accounts::auth::KeyAttributes {
- fn from(value: AccountKeyAttributes) -> Self {
- Self {
- kek_salt: value.kek_salt,
- kek_hash: None,
- encrypted_key: value.encrypted_key,
- key_decryption_nonce: value.key_decryption_nonce,
- public_key: value.public_key,
- encrypted_secret_key: value.encrypted_secret_key,
- secret_key_decryption_nonce: value.secret_key_decryption_nonce,
- mem_limit: value.mem_limit,
- ops_limit: value.ops_limit,
- master_key_encrypted_with_recovery_key: value.master_key_encrypted_with_recovery_key,
- master_key_decryption_nonce: value.master_key_decryption_nonce,
- recovery_key_encrypted_with_master_key: value.recovery_key_encrypted_with_master_key,
- recovery_key_decryption_nonce: value.recovery_key_decryption_nonce,
- }
- }
-}
-
#[frb]
#[derive(Clone)]
pub struct ContactData {
@@ -139,198 +89,6 @@ impl From<ente_contacts::ContactRecord> for ContactRecord {
}
}
-#[frb]
-#[derive(Clone, Copy)]
-pub enum LegacyKitVariant {
- TwoOfThree,
-}
-
-impl From<ente_legacy::LegacyKitVariant> for LegacyKitVariant {
- fn from(value: ente_legacy::LegacyKitVariant) -> Self {
- match value {
- ente_legacy::LegacyKitVariant::TwoOfThree => Self::TwoOfThree,
- }
- }
-}
-
-#[frb]
-#[derive(Clone, Copy)]
-pub enum LegacyKitRecoveryStatus {
- Waiting,
- Ready,
- Blocked,
- Cancelled,
- Recovered,
-}
-
-impl From<ente_legacy::LegacyKitRecoveryStatus> for LegacyKitRecoveryStatus {
- fn from(value: ente_legacy::LegacyKitRecoveryStatus) -> Self {
- match value {
- ente_legacy::LegacyKitRecoveryStatus::Waiting => Self::Waiting,
- ente_legacy::LegacyKitRecoveryStatus::Ready => Self::Ready,
- ente_legacy::LegacyKitRecoveryStatus::Blocked => Self::Blocked,
- ente_legacy::LegacyKitRecoveryStatus::Cancelled => Self::Cancelled,
- ente_legacy::LegacyKitRecoveryStatus::Recovered => Self::Recovered,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct LegacyKitRecoverySession {
- pub id: String,
- pub kit_id: String,
- pub status: LegacyKitRecoveryStatus,
- pub wait_till: i64,
- pub created_at: i64,
-}
-
-impl From<ente_legacy::LegacyKitRecoverySession> for LegacyKitRecoverySession {
- fn from(value: ente_legacy::LegacyKitRecoverySession) -> Self {
- Self {
- id: value.id,
- kit_id: value.kit_id,
- status: value.status.into(),
- wait_till: value.wait_till,
- created_at: value.created_at,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct LegacyKitRecoveryInitiatorHint {
- pub used_part_indexes: Vec<u8>,
- pub ip: String,
- pub user_agent: String,
-}
-
-impl From<LegacyKitRecoveryInitiator> for LegacyKitRecoveryInitiatorHint {
- fn from(value: LegacyKitRecoveryInitiator) -> Self {
- Self {
- used_part_indexes: value.used_part_indexes,
- ip: value.ip,
- user_agent: value.user_agent,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct LegacyKitOwnerRecoverySessionDetails {
- pub session: Option<LegacyKitRecoverySession>,
- pub initiators: Vec<LegacyKitRecoveryInitiatorHint>,
-}
-
-impl From<LegacyKitOwnerRecoverySession> for LegacyKitOwnerRecoverySessionDetails {
- fn from(value: LegacyKitOwnerRecoverySession) -> Self {
- Self {
- session: value.session.map(Into::into),
- initiators: value.initiators.into_iter().map(Into::into).collect(),
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct LegacyKitPart {
- pub index: u8,
- pub name: String,
-}
-
-impl From<ente_legacy::LegacyKitPart> for LegacyKitPart {
- fn from(value: ente_legacy::LegacyKitPart) -> Self {
- Self {
- index: value.index,
- name: value.name,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct LegacyKitMetadata {
- pub parts: Vec<LegacyKitPart>,
-}
-
-impl From<ente_legacy::LegacyKitMetadata> for LegacyKitMetadata {
- fn from(value: ente_legacy::LegacyKitMetadata) -> Self {
- Self {
- parts: value.parts.into_iter().map(Into::into).collect(),
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct LegacyKit {
- pub id: String,
- pub variant: LegacyKitVariant,
- pub notice_period_in_hours: i32,
- pub legacy_url: String,
- pub metadata: LegacyKitMetadata,
- pub created_at: i64,
- pub updated_at: i64,
- pub active_recovery_session: Option<LegacyKitRecoverySession>,
-}
-
-impl From<ente_legacy::LegacyKit> for LegacyKit {
- fn from(value: ente_legacy::LegacyKit) -> Self {
- Self {
- id: value.id,
- variant: value.variant.into(),
- notice_period_in_hours: value.notice_period_in_hours,
- legacy_url: value.legacy_url,
- metadata: value.metadata.into(),
- created_at: value.created_at,
- updated_at: value.updated_at,
- active_recovery_session: value.active_recovery_session.map(Into::into),
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct LegacyKitShare {
- pub payload_version: u8,
- pub variant: LegacyKitVariant,
- pub kit_id: String,
- pub share_index: u8,
- pub share: String,
- pub checksum: String,
- pub part_name: String,
-}
-
-impl From<ente_legacy::LegacyKitShare> for LegacyKitShare {
- fn from(value: ente_legacy::LegacyKitShare) -> Self {
- Self {
- payload_version: value.payload_version,
- variant: value.variant.into(),
- kit_id: value.kit_id,
- share_index: value.share_index,
- share: value.share,
- checksum: value.checksum,
- part_name: value.part_name,
- }
- }
-}
-
-#[frb]
-#[derive(Clone)]
-pub struct LegacyKitCreateResult {
- pub kit: LegacyKit,
- pub shares: Vec<LegacyKitShare>,
-}
-
-impl From<ente_legacy::LegacyKitCreateResult> for LegacyKitCreateResult {
- fn from(value: ente_legacy::LegacyKitCreateResult) -> Self {
- Self {
- kit: value.kit.into(),
- shares: value.shares.into_iter().map(Into::into).collect(),
- }
- }
-}
-
#[frb]
#[derive(Clone)]
pub enum RootKeySource {
@@ -383,41 +141,38 @@ pub struct OpenContactsCtxResult {
#[frb(opaque)]
#[derive(Clone)]
pub struct ContactsCtx {
- api: Arc<Api>,
+ session: Arc<Session>,
contacts: Arc<ente_contacts::ContactsClient>,
- legacy: Arc<LegacyClient>,
}
#[frb]
pub async fn open_contacts_ctx(
input: OpenContactsCtxInput,
) -> Result<OpenContactsCtxResult, ContactsError> {
- let api = Arc::new(Api::new(
- Http::new().map_err(ente_contacts::Error::from)?,
- ApiConfig {
- origin: input.base_url,
- client_package: input.client_package,
- client_version: input.client_version,
- user_agent: input.user_agent,
- auth: Some(Auth::User(input.auth_token)),
- },
- ));
- let master_key = Arc::new(SecretVec::new(input.master_key));
+ let session = Arc::new(
+ Session::new(
+ ApiConfig {
+ origin: input.base_url,
+ client_package: input.client_package,
+ client_version: input.client_version,
+ user_agent: input.user_agent,
+ auth: Some(Auth::User(input.auth_token)),
+ },
+ SecretVec::new(input.master_key),
+ )
+ .map_err(ente_contacts::Error::from)?,
+ );
let opened = ente_contacts::ContactsClient::open(
- Arc::clone(&api),
- Arc::clone(&master_key),
+ Arc::clone(&session),
ente_contacts::OpenContactsInput {
user_id: input.user_id,
cached_wrapped_root_contact_key: input.cached_wrapped_root_contact_key.map(Into::into),
},
)?;
- let legacy = LegacyClient::new(Arc::clone(&api), master_key);
-
Ok(OpenContactsCtxResult {
ctx: ContactsCtx {
- api,
+ session,
contacts: Arc::new(opened.client),
- legacy: Arc::new(legacy),
},
wrapped_root_contact_key: opened.wrapped_root_contact_key.map(Into::into),
root_key_source: opened.root_key_source.into(),
@@ -431,7 +186,7 @@ impl ContactsCtx {
}
pub fn update_auth_token(&self, auth_token: String) {
- self.api.set_auth(Some(Auth::User(auth_token)));
+ self.session.api.set_auth(Some(Auth::User(auth_token)));
}
#[frb(sync)]
@@ -519,76 +274,4 @@ impl ContactsCtx {
.await
.map_err(Into::into)
}
-
- pub async fn legacy_kits(&self) -> Result<Vec<LegacyKit>, ContactsError> {
- self.legacy
- .kits()
- .await
- .map(|kits| kits.into_iter().map(Into::into).collect())
- .map_err(Into::into)
- }
-
- pub async fn legacy_kit_create(
- &self,
- current_user_key_attrs: AccountKeyAttributes,
- part_names: Vec<String>,
- notice_period_in_hours: i32,
- ) -> Result<LegacyKitCreateResult, ContactsError> {
- let part_names: [String; 3] = part_names.try_into().map_err(|_| ContactsError::Other {
- message: "legacy kit requires exactly three part names".into(),
- })?;
- self.legacy
- .create_kit(
- &current_user_key_attrs.into(),
- part_names,
- notice_period_in_hours,
- )
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn legacy_kit_download_shares(
- &self,
- kit_id: String,
- ) -> Result<Vec<LegacyKitShare>, ContactsError> {
- self.legacy
- .download_kit_shares(&kit_id)
- .await
- .map(|shares| shares.into_iter().map(Into::into).collect())
- .map_err(Into::into)
- }
-
- pub async fn legacy_kit_recovery_session(
- &self,
- kit_id: String,
- ) -> Result<LegacyKitOwnerRecoverySessionDetails, ContactsError> {
- self.legacy
- .kit_recovery_session(&kit_id)
- .await
- .map(Into::into)
- .map_err(Into::into)
- }
-
- pub async fn legacy_kit_update_recovery_notice(
- &self,
- kit_id: String,
- notice_period_in_hours: i32,
- ) -> Result<(), ContactsError> {
- self.legacy
- .update_kit_recovery_notice(&kit_id, notice_period_in_hours)
- .await
- .map_err(Into::into)
- }
-
- pub async fn legacy_kit_block_recovery(&self, kit_id: String) -> Result<(), ContactsError> {
- self.legacy
- .block_kit_recovery(&kit_id)
- .await
- .map_err(Into::into)
- }
-
- pub async fn legacy_kit_delete(&self, kit_id: String) -> Result<(), ContactsError> {
- self.legacy.delete_kit(&kit_id).await.map_err(Into::into)
- }
}
diff --git a/rust/bindings/frb/locker/src/api/legacy.rs b/rust/bindings/frb/locker/src/api/legacy.rs
new file mode 100644
index 0000000000..5b8c96ab8b
--- /dev/null
+++ b/rust/bindings/frb/locker/src/api/legacy.rs
@@ -0,0 +1,318 @@
+use ente_legacy::{LegacyKitOwnerRecoverySession, LegacyKitRecoveryInitiator};
+use flutter_rust_bridge::frb;
+
+use super::session::Session;
+
+#[frb]
+pub enum LegacyError {
+ ActiveRecoverySession { message: String },
+ Other { message: String },
+}
+
+impl From<ente_legacy::Error> for LegacyError {
+ fn from(error: ente_legacy::Error) -> Self {
+ let message = ente_core::error::chain(&error);
+ match error {
+ ente_legacy::Error::ActiveRecoverySession => Self::ActiveRecoverySession { message },
+ _ => Self::Other { message },
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct AccountKeyAttributes {
+ pub kek_salt: String,
+ pub encrypted_key: String,
+ pub key_decryption_nonce: String,
+ pub public_key: String,
+ pub encrypted_secret_key: String,
+ pub secret_key_decryption_nonce: String,
+ pub mem_limit: u32,
+ pub ops_limit: u32,
+ pub master_key_encrypted_with_recovery_key: Option<String>,
+ pub master_key_decryption_nonce: Option<String>,
+ pub recovery_key_encrypted_with_master_key: Option<String>,
+ pub recovery_key_decryption_nonce: Option<String>,
+}
+
+impl From<AccountKeyAttributes> for ente_accounts::auth::KeyAttributes {
+ fn from(value: AccountKeyAttributes) -> Self {
+ Self {
+ kek_salt: value.kek_salt,
+ kek_hash: None,
+ encrypted_key: value.encrypted_key,
+ key_decryption_nonce: value.key_decryption_nonce,
+ public_key: value.public_key,
+ encrypted_secret_key: value.encrypted_secret_key,
+ secret_key_decryption_nonce: value.secret_key_decryption_nonce,
+ mem_limit: value.mem_limit,
+ ops_limit: value.ops_limit,
+ master_key_encrypted_with_recovery_key: value.master_key_encrypted_with_recovery_key,
+ master_key_decryption_nonce: value.master_key_decryption_nonce,
+ recovery_key_encrypted_with_master_key: value.recovery_key_encrypted_with_master_key,
+ recovery_key_decryption_nonce: value.recovery_key_decryption_nonce,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone, Copy)]
+pub enum LegacyKitVariant {
+ TwoOfThree,
+}
+
+impl From<ente_legacy::LegacyKitVariant> for LegacyKitVariant {
+ fn from(value: ente_legacy::LegacyKitVariant) -> Self {
+ match value {
+ ente_legacy::LegacyKitVariant::TwoOfThree => Self::TwoOfThree,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone, Copy)]
+pub enum LegacyKitRecoveryStatus {
+ Waiting,
+ Ready,
+ Blocked,
+ Cancelled,
+ Recovered,
+}
+
+impl From<ente_legacy::LegacyKitRecoveryStatus> for LegacyKitRecoveryStatus {
+ fn from(value: ente_legacy::LegacyKitRecoveryStatus) -> Self {
+ match value {
+ ente_legacy::LegacyKitRecoveryStatus::Waiting => Self::Waiting,
+ ente_legacy::LegacyKitRecoveryStatus::Ready => Self::Ready,
+ ente_legacy::LegacyKitRecoveryStatus::Blocked => Self::Blocked,
+ ente_legacy::LegacyKitRecoveryStatus::Cancelled => Self::Cancelled,
+ ente_legacy::LegacyKitRecoveryStatus::Recovered => Self::Recovered,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitRecoverySession {
+ pub id: String,
+ pub kit_id: String,
+ pub status: LegacyKitRecoveryStatus,
+ pub wait_till: i64,
+ pub created_at: i64,
+}
+
+impl From<ente_legacy::LegacyKitRecoverySession> for LegacyKitRecoverySession {
+ fn from(value: ente_legacy::LegacyKitRecoverySession) -> Self {
+ Self {
+ id: value.id,
+ kit_id: value.kit_id,
+ status: value.status.into(),
+ wait_till: value.wait_till,
+ created_at: value.created_at,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitRecoveryInitiatorHint {
+ pub used_part_indexes: Vec<u8>,
+ pub ip: String,
+ pub user_agent: String,
+}
+
+impl From<LegacyKitRecoveryInitiator> for LegacyKitRecoveryInitiatorHint {
+ fn from(value: LegacyKitRecoveryInitiator) -> Self {
+ Self {
+ used_part_indexes: value.used_part_indexes,
+ ip: value.ip,
+ user_agent: value.user_agent,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitOwnerRecoverySessionDetails {
+ pub session: Option<LegacyKitRecoverySession>,
+ pub initiators: Vec<LegacyKitRecoveryInitiatorHint>,
+}
+
+impl From<LegacyKitOwnerRecoverySession> for LegacyKitOwnerRecoverySessionDetails {
+ fn from(value: LegacyKitOwnerRecoverySession) -> Self {
+ Self {
+ session: value.session.map(Into::into),
+ initiators: value.initiators.into_iter().map(Into::into).collect(),
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitPart {
+ pub index: u8,
+ pub name: String,
+}
+
+impl From<ente_legacy::LegacyKitPart> for LegacyKitPart {
+ fn from(value: ente_legacy::LegacyKitPart) -> Self {
+ Self {
+ index: value.index,
+ name: value.name,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitMetadata {
+ pub parts: Vec<LegacyKitPart>,
+}
+
+impl From<ente_legacy::LegacyKitMetadata> for LegacyKitMetadata {
+ fn from(value: ente_legacy::LegacyKitMetadata) -> Self {
+ Self {
+ parts: value.parts.into_iter().map(Into::into).collect(),
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKit {
+ pub id: String,
+ pub variant: LegacyKitVariant,
+ pub notice_period_in_hours: i32,
+ pub legacy_url: String,
+ pub metadata: LegacyKitMetadata,
+ pub created_at: i64,
+ pub updated_at: i64,
+ pub active_recovery_session: Option<LegacyKitRecoverySession>,
+}
+
+impl From<ente_legacy::LegacyKit> for LegacyKit {
+ fn from(value: ente_legacy::LegacyKit) -> Self {
+ Self {
+ id: value.id,
+ variant: value.variant.into(),
+ notice_period_in_hours: value.notice_period_in_hours,
+ legacy_url: value.legacy_url,
+ metadata: value.metadata.into(),
+ created_at: value.created_at,
+ updated_at: value.updated_at,
+ active_recovery_session: value.active_recovery_session.map(Into::into),
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitShare {
+ pub payload_version: u8,
+ pub variant: LegacyKitVariant,
+ pub kit_id: String,
+ pub share_index: u8,
+ pub share: String,
+ pub checksum: String,
+ pub part_name: String,
+}
+
+impl From<ente_legacy::LegacyKitShare> for LegacyKitShare {
+ fn from(value: ente_legacy::LegacyKitShare) -> Self {
+ Self {
+ payload_version: value.payload_version,
+ variant: value.variant.into(),
+ kit_id: value.kit_id,
+ share_index: value.share_index,
+ share: value.share,
+ checksum: value.checksum,
+ part_name: value.part_name,
+ }
+ }
+}
+
+#[frb]
+#[derive(Clone)]
+pub struct LegacyKitCreateResult {
+ pub kit: LegacyKit,
+ pub shares: Vec<LegacyKitShare>,
+}
+
+impl From<ente_legacy::LegacyKitCreateResult> for LegacyKitCreateResult {
+ fn from(value: ente_legacy::LegacyKitCreateResult) -> Self {
+ Self {
+ kit: value.kit.into(),
+ shares: value.shares.into_iter().map(Into::into).collect(),
+ }
+ }
+}
+
+pub async fn kits(session: &Session) -> Result<Vec<LegacyKit>, LegacyError> {
+ ente_legacy::kits(session.inner())
+ .await
+ .map(|kits| kits.into_iter().map(Into::into).collect())
+ .map_err(Into::into)
+}
+
+pub async fn create_kit(
+ session: &Session,
+ current_user_key_attrs: AccountKeyAttributes,
+ part_names: Vec<String>,
+ notice_period_in_hours: i32,
+) -> Result<LegacyKitCreateResult, LegacyError> {
+ let part_names: [String; 3] = part_names.try_into().map_err(|_| LegacyError::Other {
+ message: "legacy kit requires exactly three part names".into(),
+ })?;
+ ente_legacy::create_kit(
+ session.inner(),
+ &current_user_key_attrs.into(),
+ part_names,
+ notice_period_in_hours,
+ )
+ .await
+ .map(Into::into)
+ .map_err(Into::into)
+}
+
+pub async fn download_kit_shares(
+ session: &Session,
+ kit_id: String,
+) -> Result<Vec<LegacyKitShare>, LegacyError> {
+ ente_legacy::download_kit_shares(session.inner(), &kit_id)
+ .await
+ .map(|shares| shares.into_iter().map(Into::into).collect())
+ .map_err(Into::into)
+}
+
+pub async fn kit_recovery_session(
+ session: &Session,
+ kit_id: String,
+) -> Result<LegacyKitOwnerRecoverySessionDetails, LegacyError> {
+ ente_legacy::kit_recovery_session(session.inner(), &kit_id)
+ .await
+ .map(Into::into)
+ .map_err(Into::into)
+}
+
+pub async fn update_kit_recovery_notice(
+ session: &Session,
+ kit_id: String,
+ notice_period_in_hours: i32,
+) -> Result<(), LegacyError> {
+ ente_legacy::update_kit_recovery_notice(session.inner(), &kit_id, notice_period_in_hours)
+ .await
+ .map_err(Into::into)
+}
+
+pub async fn block_kit_recovery(session: &Session, kit_id: String) -> Result<(), LegacyError> {
+ ente_legacy::block_kit_recovery(session.inner(), &kit_id)
+ .await
+ .map_err(Into::into)
+}
+
+pub async fn delete_kit(session: &Session, kit_id: String) -> Result<(), LegacyError> {
+ ente_legacy::delete_kit(session.inner(), &kit_id)
+ .await
+ .map_err(Into::into)
+}
diff --git a/rust/bindings/frb/locker/src/api/mod.rs b/rust/bindings/frb/locker/src/api/mod.rs
index e8b00b234c..2489114aca 100644
--- a/rust/bindings/frb/locker/src/api/mod.rs
+++ b/rust/bindings/frb/locker/src/api/mod.rs
@@ -1,5 +1,7 @@
pub mod contacts;
pub mod document_scanner_api;
pub mod init;
+pub mod legacy;
#[cfg(any(feature = "flutter", frb_expand))]
pub mod log;
+pub mod session;
diff --git a/rust/bindings/frb/locker/src/api/session.rs b/rust/bindings/frb/locker/src/api/session.rs
new file mode 100644
index 0000000000..b811d5d53a
--- /dev/null
+++ b/rust/bindings/frb/locker/src/api/session.rs
@@ -0,0 +1,56 @@
+use std::sync::Arc;
+
+use ente_core::{
+ Session as InnerSession,
+ crypto::SecretVec,
+ http::{ApiConfig, Auth},
+};
+use flutter_rust_bridge::frb;
+
+#[frb]
+pub enum SessionError {
+ Other { message: String },
+}
+
+impl From<ente_core::http::Error> for SessionError {
+ fn from(error: ente_core::http::Error) -> Self {
+ Self::Other {
+ message: ente_core::error::chain(&error),
+ }
+ }
+}
+
+#[frb(opaque)]
+#[derive(Clone)]
+pub struct Session(Arc<InnerSession>);
+
+#[frb(sync)]
+pub fn open_session(
+ base_url: String,
+ auth_token: String,
+ master_key: Vec<u8>,
+ user_agent: Option<String>,
+ client_package: Option<String>,
+ client_version: Option<String>,
+) -> Result<Session, SessionError> {
+ Ok(Session(Arc::new(InnerSession::new(
+ ApiConfig {
+ origin: base_url,
+ client_package,
+ client_version,
+ user_agent,
+ auth: Some(Auth::User(auth_token)),
+ },
+ SecretVec::new(master_key),
+ )?)))
+}
+
+impl Session {
+ pub(crate) fn inner(&self) -> &InnerSession {
+ &self.0
+ }
+
+ pub fn update_auth_token(&self, auth_token: String) {
+ self.0.api.set_auth(Some(Auth::User(auth_token)));
+ }
+}
diff --git a/rust/bindings/frb/photos/src/api/contacts.rs b/rust/bindings/frb/photos/src/api/contacts.rs
index 933ee4f05e..af15c54158 100644
--- a/rust/bindings/frb/photos/src/api/contacts.rs
+++ b/rust/bindings/frb/photos/src/api/contacts.rs
@@ -1,8 +1,9 @@
use std::sync::Arc;
use ente_core::{
+ Session,
crypto::SecretVec,
- http::{Api, ApiConfig, Auth, Http},
+ http::{ApiConfig, Auth},
};
use flutter_rust_bridge::frb;
@@ -140,7 +141,7 @@ pub struct OpenContactsCtxResult {
#[frb(opaque)]
#[derive(Clone)]
pub struct ContactsCtx {
- api: Arc<Api>,
+ session: Arc<Session>,
contacts: Arc<ente_contacts::ContactsClient>,
}
@@ -148,19 +149,21 @@ pub struct ContactsCtx {
pub async fn open_contacts_ctx(
input: OpenContactsCtxInput,
) -> Result<OpenContactsCtxResult, ContactsError> {
- let api = Arc::new(Api::new(
- Http::new().map_err(ente_contacts::Error::from)?,
- ApiConfig {
- origin: input.base_url,
- client_package: input.client_package,
- client_version: input.client_version,
- user_agent: input.user_agent,
- auth: Some(Auth::User(input.auth_token)),
- },
- ));
+ let session = Arc::new(
+ Session::new(
+ ApiConfig {
+ origin: input.base_url,
+ client_package: input.client_package,
+ client_version: input.client_version,
+ user_agent: input.user_agent,
+ auth: Some(Auth::User(input.auth_token)),
+ },
+ SecretVec::new(input.master_key),
+ )
+ .map_err(ente_contacts::Error::from)?,
+ );
let opened = ente_contacts::ContactsClient::open(
- Arc::clone(&api),
- Arc::new(SecretVec::new(input.master_key)),
+ Arc::clone(&session),
ente_contacts::OpenContactsInput {
user_id: input.user_id,
cached_wrapped_root_contact_key: input.cached_wrapped_root_contact_key.map(Into::into),
@@ -169,7 +172,7 @@ pub async fn open_contacts_ctx(
Ok(OpenContactsCtxResult {
ctx: ContactsCtx {
- api,
+ session,
contacts: Arc::new(opened.client),
},
wrapped_root_contact_key: opened.wrapped_root_contact_key.map(Into::into),
@@ -184,7 +187,7 @@ impl ContactsCtx {
}
pub fn update_auth_token(&self, auth_token: String) {
- self.api.set_auth(Some(Auth::User(auth_token)));
+ self.session.api.set_auth(Some(Auth::User(auth_token)));
}
#[frb(sync)]
diff --git a/rust/bindings/wasm/core-wasm/Cargo.toml b/rust/bindings/wasm/core-wasm/Cargo.toml
new file mode 100644
index 0000000000..52937ebe97
--- /dev/null
+++ b/rust/bindings/wasm/core-wasm/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "ente-core-wasm"
+edition = "2024"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+ente-accounts.workspace = true
+ente-core.workspace = true
+ente-wasm-log.workspace = true
+js-sys.workspace = true
+md-5.workspace = true
+thiserror.workspace = true
+wasm-bindgen.workspace = true
diff --git a/rust/bindings/wasm/core/src/auth.rs b/rust/bindings/wasm/core-wasm/src/auth.rs
similarity index 100%
rename from rust/bindings/wasm/core/src/auth.rs
rename to rust/bindings/wasm/core-wasm/src/auth.rs
diff --git a/rust/bindings/wasm/core/src/crypto.rs b/rust/bindings/wasm/core-wasm/src/crypto.rs
similarity index 100%
rename from rust/bindings/wasm/core/src/crypto.rs
rename to rust/bindings/wasm/core-wasm/src/crypto.rs
diff --git a/rust/bindings/wasm/core-wasm/src/lib.rs b/rust/bindings/wasm/core-wasm/src/lib.rs
new file mode 100644
index 0000000000..ceb5a7ab4b
--- /dev/null
+++ b/rust/bindings/wasm/core-wasm/src/lib.rs
@@ -0,0 +1,4 @@
+use ente_wasm_log as _;
+
+mod auth;
+mod crypto;
diff --git a/rust/bindings/wasm/core/Cargo.toml b/rust/bindings/wasm/core/Cargo.toml
index 52937ebe97..bf4cda4a0e 100644
--- a/rust/bindings/wasm/core/Cargo.toml
+++ b/rust/bindings/wasm/core/Cargo.toml
@@ -1,15 +1,9 @@
[package]
-name = "ente-core-wasm"
+name = "ente-wasm-core"
edition = "2024"
-[lib]
-crate-type = ["cdylib"]
-
[dependencies]
-ente-accounts.workspace = true
ente-core.workspace = true
-ente-wasm-log.workspace = true
js-sys.workspace = true
-md-5.workspace = true
thiserror.workspace = true
wasm-bindgen.workspace = true
diff --git a/rust/bindings/wasm/core/src/lib.rs b/rust/bindings/wasm/core/src/lib.rs
index ceb5a7ab4b..97f450b133 100644
--- a/rust/bindings/wasm/core/src/lib.rs
+++ b/rust/bindings/wasm/core/src/lib.rs
@@ -1,4 +1,77 @@
-use ente_wasm_log as _;
+use std::sync::Arc;
-mod auth;
-mod crypto;
+use ente_core::{
+ Session as InnerSession, b64,
+ crypto::SecretVec,
+ http::{ApiConfig, Auth},
+};
+use wasm_bindgen::prelude::*;
+
+#[wasm_bindgen(js_name = openSession)]
+pub fn open_session(
+ base_url: String,
+ auth_token: String,
+ master_key_b64: String,
+ client_package: Option<String>,
+ client_version: Option<String>,
+) -> Result<Session, Error> {
+ Ok(Session(Arc::new(InnerSession::new(
+ ApiConfig {
+ origin: base_url,
+ client_package,
+ client_version,
+ user_agent: None,
+ auth: Some(Auth::User(auth_token)),
+ },
+ SecretVec::new(b64::decode(&master_key_b64)?),
+ )?)))
+}
+
+#[wasm_bindgen]
+pub struct Session(Arc<InnerSession>);
+
+impl Session {
+ pub fn inner(&self) -> &InnerSession {
+ &self.0
+ }
+
+ pub fn clone_inner(&self) -> Arc<InnerSession> {
+ Arc::clone(&self.0)
+ }
+}
+
+#[wasm_bindgen]
+impl Session {
+ #[wasm_bindgen(js_name = updateAuthToken)]
+ pub fn update_auth_token(&self, auth_token: String) {
+ self.0.api.set_auth(Some(Auth::User(auth_token)));
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error(transparent)]
+ Http(#[from] ente_core::http::Error),
+ #[error(transparent)]
+ Decode(#[from] b64::DecodeError),
+}
+
+impl Error {
+ fn name(&self) -> Option<&'static str> {
+ None
+ }
+
+ fn message(&self) -> String {
+ ente_core::error::chain(self)
+ }
+}
+
+impl From<Error> for JsValue {
+ fn from(error: Error) -> Self {
+ let js_error = js_sys::Error::new(&error.message());
+ if let Some(name) = error.name() {
+ js_error.set_name(name);
+ }
+ js_error.into()
+ }
+}
diff --git a/rust/bindings/wasm/legacy/Cargo.toml b/rust/bindings/wasm/legacy/Cargo.toml
index 3005732638..950f17de72 100644
--- a/rust/bindings/wasm/legacy/Cargo.toml
+++ b/rust/bindings/wasm/legacy/Cargo.toml
@@ -9,6 +9,7 @@ crate-type = ["cdylib"]
ente-accounts.workspace = true
ente-core.workspace = true
ente-legacy.workspace = true
+ente-wasm-core.workspace = true
ente-wasm-log.workspace = true
js-sys.workspace = true
serde.workspace = true
diff --git a/rust/bindings/wasm/legacy/src/lib.rs b/rust/bindings/wasm/legacy/src/lib.rs
index 1616af53d6..1bd4b18703 100644
--- a/rust/bindings/wasm/legacy/src/lib.rs
+++ b/rust/bindings/wasm/legacy/src/lib.rs
@@ -1,14 +1,7 @@
-use std::sync::Arc;
-
use ente_accounts::auth::KeyAttributes;
-use ente_core::{
- b64,
- crypto::SecretVec,
- http::{Api, ApiConfig, Auth, Http},
-};
-use ente_legacy::{
- LegacyClient as InnerLegacyClient, LegacyContactState, LegacyKitRecoveryClient, LegacyKitShare,
-};
+use ente_core::b64;
+use ente_legacy::{LegacyContactState, LegacyKitRecoveryClient, LegacyKitShare};
+use ente_wasm_core::Session;
use serde::Deserialize;
use serde_wasm_bindgen as swb;
use wasm_bindgen::prelude::*;
@@ -52,140 +45,120 @@ impl From<Error> for JsValue {
}
}
-#[wasm_bindgen(js_name = openLegacy)]
-pub fn open_legacy(
- base_url: String,
- auth_token: String,
- master_key_b64: String,
- client_package: Option<String>,
- client_version: Option<String>,
-) -> Result<LegacyClient, Error> {
- let api = Arc::new(Api::new(
- Http::new().map_err(ente_legacy::Error::from)?,
- ApiConfig {
- origin: base_url,
- client_package,
- client_version,
- user_agent: None,
- auth: Some(Auth::User(auth_token)),
- },
- ));
- let master_key = Arc::new(SecretVec::new(b64::decode(&master_key_b64)?));
-
- Ok(LegacyClient(InnerLegacyClient::new(api, master_key)))
+#[wasm_bindgen(js_name = legacyGetInfo)]
+pub async fn legacy_get_info(session: &Session) -> Result<JsValue, Error> {
+ swb::to_value(&ente_legacy::info(session.inner()).await?).map_err(Into::into)
}
-#[wasm_bindgen]
-pub struct LegacyClient(InnerLegacyClient);
-
-#[wasm_bindgen]
-impl LegacyClient {
- #[wasm_bindgen(js_name = getInfo)]
- pub async fn get_info(&self) -> Result<JsValue, Error> {
- swb::to_value(&self.0.info().await?).map_err(Into::into)
- }
-
- #[wasm_bindgen(js_name = publicKey)]
- pub async fn public_key(&self, email: String) -> Result<Option<String>, Error> {
- self.0.public_key(&email).await.map_err(Into::into)
- }
+#[wasm_bindgen(js_name = legacyPublicKey)]
+pub async fn legacy_public_key(session: &Session, email: String) -> Result<Option<String>, Error> {
+ ente_legacy::public_key(session.inner(), &email)
+ .await
+ .map_err(Into::into)
+}
- #[wasm_bindgen(js_name = verificationID)]
- pub fn verification_id(&self, public_key_b64: String) -> Result<String, Error> {
- self.0.verification_id(&public_key_b64).map_err(Into::into)
- }
+#[wasm_bindgen(js_name = legacyVerificationID)]
+pub fn legacy_verification_id(public_key_b64: String) -> Result<String, Error> {
+ ente_legacy::verification_id(&public_key_b64).map_err(Into::into)
+}
- #[wasm_bindgen(js_name = addContact)]
- pub async fn add_contact(
- &self,
- email: String,
- current_user_key_attrs: JsValue,
- recovery_notice_in_days: Option<i32>,
- ) -> Result<(), Error> {
- let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
- self.0
- .add_contact(&email, &current_user_key_attrs, recovery_notice_in_days)
- .await
- .map_err(Into::into)
- }
+#[wasm_bindgen(js_name = legacyAddContact)]
+pub async fn legacy_add_contact(
+ session: &Session,
+ email: String,
+ current_user_key_attrs: JsValue,
+ recovery_notice_in_days: Option<i32>,
+) -> Result<(), Error> {
+ let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
+ ente_legacy::add_contact(
+ session.inner(),
+ &email,
+ &current_user_key_attrs,
+ recovery_notice_in_days,
+ )
+ .await
+ .map_err(Into::into)
+}
- #[wasm_bindgen(js_name = updateContact)]
- pub async fn update_contact(
- &self,
- user_id: i64,
- emergency_contact_id: i64,
- state: JsValue,
- ) -> Result<(), Error> {
- let state: LegacyContactState = swb::from_value(state)?;
- self.0
- .update_contact(user_id, emergency_contact_id, state)
- .await
- .map_err(Into::into)
- }
+#[wasm_bindgen(js_name = legacyUpdateContact)]
+pub async fn legacy_update_contact(
+ session: &Session,
+ user_id: i64,
+ emergency_contact_id: i64,
+ state: JsValue,
+) -> Result<(), Error> {
+ let state: LegacyContactState = swb::from_value(state)?;
+ ente_legacy::update_contact(session.inner(), user_id, emergency_contact_id, state)
+ .await
+ .map_err(Into::into)
+}
- #[wasm_bindgen(js_name = updateRecoveryNotice)]
- pub async fn update_recovery_notice(
- &self,
- emergency_contact_id: i64,
- recovery_notice_in_days: i32,
- ) -> Result<(), Error> {
- self.0
- .update_recovery_notice(emergency_contact_id, recovery_notice_in_days)
- .await
- .map_err(Into::into)
- }
+#[wasm_bindgen(js_name = legacyUpdateRecoveryNotice)]
+pub async fn legacy_update_recovery_notice(
+ session: &Session,
+ emergency_contact_id: i64,
+ recovery_notice_in_days: i32,
+) -> Result<(), Error> {
+ ente_legacy::update_recovery_notice(
+ session.inner(),
+ emergency_contact_id,
+ recovery_notice_in_days,
+ )
+ .await
+ .map_err(Into::into)
+}
- #[wasm_bindgen(js_name = startRecovery)]
- pub async fn start_recovery(
- &self,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<(), Error> {
- self.0
- .start_recovery(user_id, emergency_contact_id)
- .await
- .map_err(Into::into)
- }
+#[wasm_bindgen(js_name = legacyStartRecovery)]
+pub async fn legacy_start_recovery(
+ session: &Session,
+ user_id: i64,
+ emergency_contact_id: i64,
+) -> Result<(), Error> {
+ ente_legacy::start_recovery(session.inner(), user_id, emergency_contact_id)
+ .await
+ .map_err(Into::into)
+}
- #[wasm_bindgen(js_name = stopRecovery)]
- pub async fn stop_recovery(
- &self,
- recovery_id: String,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<(), Error> {
- self.0
- .stop_recovery(&recovery_id, user_id, emergency_contact_id)
- .await
- .map_err(Into::into)
- }
+#[wasm_bindgen(js_name = legacyStopRecovery)]
+pub async fn legacy_stop_recovery(
+ session: &Session,
+ recovery_id: String,
+ user_id: i64,
+ emergency_contact_id: i64,
+) -> Result<(), Error> {
+ ente_legacy::stop_recovery(session.inner(), &recovery_id, user_id, emergency_contact_id)
+ .await
+ .map_err(Into::into)
+}
- #[wasm_bindgen(js_name = rejectRecovery)]
- pub async fn reject_recovery(
- &self,
- recovery_id: String,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<(), Error> {
- self.0
- .reject_recovery(&recovery_id, user_id, emergency_contact_id)
- .await
- .map_err(Into::into)
- }
+#[wasm_bindgen(js_name = legacyRejectRecovery)]
+pub async fn legacy_reject_recovery(
+ session: &Session,
+ recovery_id: String,
+ user_id: i64,
+ emergency_contact_id: i64,
+) -> Result<(), Error> {
+ ente_legacy::reject_recovery(session.inner(), &recovery_id, user_id, emergency_contact_id)
+ .await
+ .map_err(Into::into)
+}
- #[wasm_bindgen(js_name = changePassword)]
- pub async fn change_password(
- &self,
- recovery_id: String,
- current_user_key_attrs: JsValue,
- new_password: String,
- ) -> Result<(), Error> {
- let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
- self.0
- .change_password(&recovery_id, &current_user_key_attrs, &new_password)
- .await
- .map_err(Into::into)
- }
+#[wasm_bindgen(js_name = legacyChangePassword)]
+pub async fn legacy_change_password(
+ session: &Session,
+ recovery_id: String,
+ current_user_key_attrs: JsValue,
+ new_password: String,
+) -> Result<(), Error> {
+ let current_user_key_attrs: KeyAttributes = swb::from_value(current_user_key_attrs)?;
+ ente_legacy::change_password(
+ session.inner(),
+ &recovery_id,
+ &current_user_key_attrs,
+ &new_password,
+ )
+ .await
+ .map_err(Into::into)
}
#[derive(Deserialize)]
diff --git a/rust/bindings/wasm/locker/Cargo.toml b/rust/bindings/wasm/locker/Cargo.toml
index 0c8aaefab6..2d0c29d4a7 100644
--- a/rust/bindings/wasm/locker/Cargo.toml
+++ b/rust/bindings/wasm/locker/Cargo.toml
@@ -8,6 +8,7 @@ crate-type = ["cdylib"]
[dependencies]
ente-contacts.workspace = true
ente-core.workspace = true
+ente-wasm-core.workspace = true
ente-wasm-log.workspace = true
js-sys.workspace = true
serde.workspace = true
diff --git a/rust/bindings/wasm/locker/src/lib.rs b/rust/bindings/wasm/locker/src/lib.rs
index 3bd11ceba8..b9f44dbc3d 100644
--- a/rust/bindings/wasm/locker/src/lib.rs
+++ b/rust/bindings/wasm/locker/src/lib.rs
@@ -1,11 +1,5 @@
-use std::sync::Arc;
-
use ente_contacts::{OpenContactsInput, WrappedRootContactKey};
-use ente_core::{
- b64,
- crypto::SecretVec,
- http::{Api, ApiConfig, Auth, Http},
-};
+use ente_wasm_core::Session;
use serde::Serialize;
use serde_wasm_bindgen as swb;
use wasm_bindgen::prelude::*;
@@ -18,8 +12,6 @@ pub enum Error {
Contacts(#[from] ente_contacts::Error),
#[error(transparent)]
Serde(#[from] swb::Error),
- #[error(transparent)]
- Decode(#[from] b64::DecodeError),
}
impl Error {
@@ -71,28 +63,13 @@ impl From<ente_contacts::ContactRecord> for ContactRecordJs {
#[wasm_bindgen(js_name = openContacts)]
pub fn open_contacts(
- base_url: String,
- auth_token: String,
+ session: &Session,
user_id: i64,
- master_key_b64: String,
cached_encrypted_key: Option<String>,
cached_header: Option<String>,
- client_package: Option<String>,
- client_version: Option<String>,
) -> Result<ContactsClient, Error> {
- let api = Arc::new(Api::new(
- Http::new().map_err(ente_contacts::Error::from)?,
- ApiConfig {
- origin: base_url,
- client_package,
- client_version,
- user_agent: None,
- auth: Some(Auth::User(auth_token)),
- },
- ));
let opened = ente_contacts::ContactsClient::open(
- Arc::clone(&api),
- Arc::new(SecretVec::new(b64::decode(&master_key_b64)?)),
+ session.clone_inner(),
OpenContactsInput {
user_id,
cached_wrapped_root_contact_key: cached_encrypted_key.zip(cached_header).map(
@@ -104,34 +81,23 @@ pub fn open_contacts(
},
)?;
- Ok(ContactsClient {
- api,
- inner: opened.client,
- })
+ Ok(ContactsClient(opened.client))
}
#[wasm_bindgen]
-pub struct ContactsClient {
- api: Arc<Api>,
- inner: ente_contacts::ContactsClient,
-}
+pub struct ContactsClient(ente_contacts::ContactsClient);
#[wasm_bindgen]
impl ContactsClient {
- #[wasm_bindgen(js_name = updateAuthToken)]
- pub fn update_auth_token(&self, auth_token: String) {
- self.api.set_auth(Some(Auth::User(auth_token)));
- }
-
#[wasm_bindgen(js_name = currentWrappedRootContactKey)]
pub fn current_wrapped_root_contact_key(&self) -> Result<JsValue, Error> {
- swb::to_value(&self.inner.current_wrapped_root_contact_key()).map_err(Into::into)
+ swb::to_value(&self.0.current_wrapped_root_contact_key()).map_err(Into::into)
}
#[wasm_bindgen(js_name = getDiff)]
pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<JsValue, Error> {
let diff: Vec<ContactRecordJs> = self
- .inner
+ .0
.get_diff(since_time, limit)
.await?
.into_iter()
@@ -142,7 +108,7 @@ impl ContactsClient {
#[wasm_bindgen(js_name = getProfilePicture)]
pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>, Error> {
- self.inner
+ self.0
.get_profile_picture(contact_id)
.await
.map_err(Into::into)
diff --git a/rust/bindings/wasm/photos/Cargo.toml b/rust/bindings/wasm/photos/Cargo.toml
index a214c429f8..2a6cef7cbf 100644
--- a/rust/bindings/wasm/photos/Cargo.toml
+++ b/rust/bindings/wasm/photos/Cargo.toml
@@ -8,6 +8,7 @@ crate-type = ["cdylib"]
[dependencies]
ente-contacts.workspace = true
ente-core.workspace = true
+ente-wasm-core.workspace = true
ente-wasm-log.workspace = true
js-sys.workspace = true
serde.workspace = true
diff --git a/rust/bindings/wasm/photos/src/lib.rs b/rust/bindings/wasm/photos/src/lib.rs
index 3bd11ceba8..b9f44dbc3d 100644
--- a/rust/bindings/wasm/photos/src/lib.rs
+++ b/rust/bindings/wasm/photos/src/lib.rs
@@ -1,11 +1,5 @@
-use std::sync::Arc;
-
use ente_contacts::{OpenContactsInput, WrappedRootContactKey};
-use ente_core::{
- b64,
- crypto::SecretVec,
- http::{Api, ApiConfig, Auth, Http},
-};
+use ente_wasm_core::Session;
use serde::Serialize;
use serde_wasm_bindgen as swb;
use wasm_bindgen::prelude::*;
@@ -18,8 +12,6 @@ pub enum Error {
Contacts(#[from] ente_contacts::Error),
#[error(transparent)]
Serde(#[from] swb::Error),
- #[error(transparent)]
- Decode(#[from] b64::DecodeError),
}
impl Error {
@@ -71,28 +63,13 @@ impl From<ente_contacts::ContactRecord> for ContactRecordJs {
#[wasm_bindgen(js_name = openContacts)]
pub fn open_contacts(
- base_url: String,
- auth_token: String,
+ session: &Session,
user_id: i64,
- master_key_b64: String,
cached_encrypted_key: Option<String>,
cached_header: Option<String>,
- client_package: Option<String>,
- client_version: Option<String>,
) -> Result<ContactsClient, Error> {
- let api = Arc::new(Api::new(
- Http::new().map_err(ente_contacts::Error::from)?,
- ApiConfig {
- origin: base_url,
- client_package,
- client_version,
- user_agent: None,
- auth: Some(Auth::User(auth_token)),
- },
- ));
let opened = ente_contacts::ContactsClient::open(
- Arc::clone(&api),
- Arc::new(SecretVec::new(b64::decode(&master_key_b64)?)),
+ session.clone_inner(),
OpenContactsInput {
user_id,
cached_wrapped_root_contact_key: cached_encrypted_key.zip(cached_header).map(
@@ -104,34 +81,23 @@ pub fn open_contacts(
},
)?;
- Ok(ContactsClient {
- api,
- inner: opened.client,
- })
+ Ok(ContactsClient(opened.client))
}
#[wasm_bindgen]
-pub struct ContactsClient {
- api: Arc<Api>,
- inner: ente_contacts::ContactsClient,
-}
+pub struct ContactsClient(ente_contacts::ContactsClient);
#[wasm_bindgen]
impl ContactsClient {
- #[wasm_bindgen(js_name = updateAuthToken)]
- pub fn update_auth_token(&self, auth_token: String) {
- self.api.set_auth(Some(Auth::User(auth_token)));
- }
-
#[wasm_bindgen(js_name = currentWrappedRootContactKey)]
pub fn current_wrapped_root_contact_key(&self) -> Result<JsValue, Error> {
- swb::to_value(&self.inner.current_wrapped_root_contact_key()).map_err(Into::into)
+ swb::to_value(&self.0.current_wrapped_root_contact_key()).map_err(Into::into)
}
#[wasm_bindgen(js_name = getDiff)]
pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<JsValue, Error> {
let diff: Vec<ContactRecordJs> = self
- .inner
+ .0
.get_diff(since_time, limit)
.await?
.into_iter()
@@ -142,7 +108,7 @@ impl ContactsClient {
#[wasm_bindgen(js_name = getProfilePicture)]
pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>, Error> {
- self.inner
+ self.0
.get_profile_picture(contact_id)
.await
.map_err(Into::into)
diff --git a/rust/crates/contacts/src/client/attachment.rs b/rust/crates/contacts/src/client/attachment.rs
index ea28ca568a..df55974d9a 100644
--- a/rust/crates/contacts/src/client/attachment.rs
+++ b/rust/crates/contacts/src/client/attachment.rs
@@ -34,7 +34,7 @@ impl ContactsClient {
pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>> {
let current = self
- .api
+ .api()
.get(&format!("/contacts/{contact_id}"))
.send()
.await?
@@ -75,7 +75,7 @@ impl ContactsClient {
self.ensure_confirmed_root_contact_key().await?;
let current = self
- .api
+ .api()
.get(&format!("/contacts/{contact_id}"))
.send()
.await?
@@ -92,7 +92,7 @@ impl ContactsClient {
let size = encrypted_attachment.len() as i64;
let upload = self
- .api
+ .api()
.post(&format!(
"/attachments/{}/upload-url",
attachment_type.as_str()
@@ -107,7 +107,7 @@ impl ContactsClient {
.json::<AttachmentUploadUrlResponse>()
.await?;
- self.api
+ self.api()
.http()
.put(&upload.url)
.header("Content-MD5", &content_md5)
@@ -117,7 +117,7 @@ impl ContactsClient {
.error_for_status()?;
let response = self
- .api
+ .api()
.put(&format!(
"/contacts/{contact_id}/attachments/{}",
attachment_type.as_str()
@@ -141,7 +141,7 @@ impl ContactsClient {
attachment_id: &str,
) -> Result<Vec<u8>> {
let download = self
- .api
+ .api()
.get(&format!(
"/attachments/{}/{attachment_id}",
attachment_type.as_str()
@@ -152,7 +152,7 @@ impl ContactsClient {
.json::<SignedUrlResponse>()
.await?;
Ok(self
- .api
+ .api()
.http()
.get(&download.url)
.send()
@@ -169,7 +169,7 @@ impl ContactsClient {
) -> Result<ContactRecord> {
self.ensure_confirmed_root_contact_key().await?;
let response = self
- .api
+ .api()
.delete(&format!(
"/contacts/{contact_id}/attachments/{}",
attachment_type.as_str()
diff --git a/rust/crates/contacts/src/client/contact.rs b/rust/crates/contacts/src/client/contact.rs
index 9ed7194ac7..7d7ebad1ba 100644
--- a/rust/crates/contacts/src/client/contact.rs
+++ b/rust/crates/contacts/src/client/contact.rs
@@ -33,7 +33,7 @@ impl ContactsClient {
let wrapped_contact_key = self.encrypt_contact_key(&contact_key)?;
let encrypted_data = encrypt_contact_data(data, &contact_key)?;
let response = self
- .api
+ .api()
.post("/contacts")
.json(&CreateContactRequest {
contact_user_id: data.contact_user_id,
@@ -51,7 +51,7 @@ impl ContactsClient {
pub async fn get_contact(&self, contact_id: &str) -> Result<ContactRecord> {
let response = self
- .api
+ .api()
.get(&format!("/contacts/{contact_id}"))
.send()
.await?
@@ -73,7 +73,7 @@ impl ContactsClient {
self.ensure_confirmed_root_contact_key().await?;
let current = self
- .api
+ .api()
.get(&format!("/contacts/{contact_id}"))
.send()
.await?
@@ -88,7 +88,7 @@ impl ContactsClient {
let encrypted_data = encrypt_contact_data(data, &contact_key)?;
let response = self
- .api
+ .api()
.put(&format!("/contacts/{contact_id}"))
.json(&UpdateContactRequest {
contact_user_id: data.contact_user_id,
@@ -104,7 +104,7 @@ impl ContactsClient {
}
pub async fn delete_contact(&self, contact_id: &str) -> Result<()> {
- self.api
+ self.api()
.delete(&format!("/contacts/{contact_id}"))
.send()
.await?
@@ -114,7 +114,7 @@ impl ContactsClient {
pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<Vec<ContactRecord>> {
let response = self
- .api
+ .api()
.get("/contacts/diff")
.query(&[
("sinceTime", since_time.to_string()),
diff --git a/rust/crates/contacts/src/client/mod.rs b/rust/crates/contacts/src/client/mod.rs
index 0dbaf77e74..0bed0f2c1e 100644
--- a/rust/crates/contacts/src/client/mod.rs
+++ b/rust/crates/contacts/src/client/mod.rs
@@ -6,6 +6,7 @@ pub use contact::{ContactData, ContactRecord};
use std::sync::{Arc, RwLock};
+use ente_core::Session;
use ente_core::b64;
use ente_core::crypto::{self, SecretVec, secretbox};
use ente_core::http::Api;
@@ -41,23 +42,18 @@ pub struct OpenContactsResult {
pub struct ContactsClient {
user_id: i64,
- api: Arc<Api>,
- master_key: Arc<SecretVec>,
+ session: Arc<Session>,
root_contact_key: Arc<RwLock<Option<SecretVec>>>,
wrapped_root_contact_key: Arc<RwLock<Option<WrappedRootContactKey>>>,
}
impl ContactsClient {
- pub fn open(
- api: Arc<Api>,
- master_key: Arc<SecretVec>,
- input: OpenContactsInput,
- ) -> Result<OpenContactsResult> {
+ pub fn open(session: Arc<Session>, input: OpenContactsInput) -> Result<OpenContactsResult> {
let (root_contact_key, wrapped_root_contact_key, root_key_source) =
if let Some(cached_wrapped_root_contact_key) = input.cached_wrapped_root_contact_key {
let root_contact_key = decrypt_root_contact_key(
&cached_wrapped_root_contact_key,
- master_key.as_ref(),
+ &session.master_key,
)?;
(
Some(root_contact_key),
@@ -69,8 +65,7 @@ impl ContactsClient {
};
let client = Self {
user_id: input.user_id,
- api,
- master_key,
+ session,
root_contact_key: Arc::new(RwLock::new(root_contact_key)),
wrapped_root_contact_key: Arc::new(RwLock::new(wrapped_root_contact_key.clone())),
};
@@ -93,6 +88,10 @@ impl ContactsClient {
.clone()
}
+ fn api(&self) -> &Api {
+ &self.session.api
+ }
+
fn encrypt_contact_key(&self, contact_key: &[u8]) -> Result<String> {
let root_contact_key = self
.root_contact_key
@@ -134,14 +133,14 @@ impl ContactsClient {
return Ok(());
}
- if let Some(remote_root_key) = fetch_root_key(&self.api).await? {
+ if let Some(remote_root_key) = fetch_root_key(self.api()).await? {
self.apply_wrapped_root_contact_key(remote_root_key.into())?;
} else {
let generated_root_contact_key = SecretVec::new(crypto::random_bytes(32));
let generated_wrapped_root_contact_key =
- encrypt_root_contact_key(&generated_root_contact_key, self.master_key.as_ref())?;
+ encrypt_root_contact_key(&generated_root_contact_key, &self.session.master_key)?;
if let Some(remote_root_key) =
- create_root_key(&self.api, &generated_wrapped_root_contact_key).await?
+ create_root_key(self.api(), &generated_wrapped_root_contact_key).await?
{
self.apply_wrapped_root_contact_key(remote_root_key.into())?;
} else {
@@ -157,7 +156,7 @@ impl ContactsClient {
wrapped_root_contact_key: WrappedRootContactKey,
) -> Result<()> {
let decrypted_root_key =
- decrypt_root_contact_key(&wrapped_root_contact_key, self.master_key.as_ref())?;
+ decrypt_root_contact_key(&wrapped_root_contact_key, &self.session.master_key)?;
*self
.root_contact_key
.write()
diff --git a/rust/crates/contacts/tests/contacts.rs b/rust/crates/contacts/tests/contacts.rs
index 08198f8a65..bffe55f93d 100644
--- a/rust/crates/contacts/tests/contacts.rs
+++ b/rust/crates/contacts/tests/contacts.rs
@@ -131,31 +131,36 @@ async fn run_contacts_stage(endpoint: &str, pair: &legacy::LegacyPair) {
}
async fn run_legacy_reject_stage(pair: &legacy::LegacyPair) {
- pair.trusted_ctx
- .start_recovery(pair.owner.user_id, pair.trusted.user_id)
- .await
- .unwrap();
+ ente_legacy::start_recovery(
+ &pair.trusted_session,
+ pair.owner.user_id,
+ pair.trusted.user_id,
+ )
+ .await
+ .unwrap();
assert!(matches!(
- pair.owner_ctx
- .update_recovery_notice(pair.trusted.user_id, 1)
- .await,
+ ente_legacy::update_recovery_notice(&pair.owner_session, pair.trusted.user_id, 1).await,
Err(ente_legacy::Error::ActiveRecoverySession)
));
- let owner_info = pair.owner_ctx.info().await.unwrap();
+ let owner_info = ente_legacy::info(&pair.owner_session).await.unwrap();
let recovery =
legacy::owner_recovery_session(&owner_info, pair.owner.user_id, pair.trusted.user_id)
.expect("owner recovery session missing");
assert_eq!(recovery.status, LegacyRecoveryStatus::Waiting);
- pair.owner_ctx
- .reject_recovery(&recovery.id, pair.owner.user_id, pair.trusted.user_id)
- .await
- .unwrap();
-
- let owner_info = pair.owner_ctx.info().await.unwrap();
- let trusted_info = pair.trusted_ctx.info().await.unwrap();
+ ente_legacy::reject_recovery(
+ &pair.owner_session,
+ &recovery.id,
+ pair.owner.user_id,
+ pair.trusted.user_id,
+ )
+ .await
+ .unwrap();
+
+ let owner_info = ente_legacy::info(&pair.owner_session).await.unwrap();
+ let trusted_info = ente_legacy::info(&pair.trusted_session).await.unwrap();
assert!(
legacy::owner_recovery_session(&owner_info, pair.owner.user_id, pair.trusted.user_id)
.is_none()
@@ -172,24 +177,31 @@ async fn run_legacy_reject_stage(pair: &legacy::LegacyPair) {
}
async fn run_legacy_stop_stage(pair: &legacy::LegacyPair) {
- pair.trusted_ctx
- .start_recovery(pair.owner.user_id, pair.trusted.user_id)
- .await
- .unwrap();
-
- let trusted_info = pair.trusted_ctx.info().await.unwrap();
+ ente_legacy::start_recovery(
+ &pair.trusted_session,
+ pair.owner.user_id,
+ pair.trusted.user_id,
+ )
+ .await
+ .unwrap();
+
+ let trusted_info = ente_legacy::info(&pair.trusted_session).await.unwrap();
let recovery =
legacy::trusted_recovery_session(&trusted_info, pair.owner.user_id, pair.trusted.user_id)
.expect("trusted recovery session missing");
assert_eq!(recovery.status, LegacyRecoveryStatus::Waiting);
- pair.trusted_ctx
- .stop_recovery(&recovery.id, pair.owner.user_id, pair.trusted.user_id)
- .await
- .unwrap();
-
- let owner_info = pair.owner_ctx.info().await.unwrap();
- let trusted_info = pair.trusted_ctx.info().await.unwrap();
+ ente_legacy::stop_recovery(
+ &pair.trusted_session,
+ &recovery.id,
+ pair.owner.user_id,
+ pair.trusted.user_id,
+ )
+ .await
+ .unwrap();
+
+ let owner_info = ente_legacy::info(&pair.owner_session).await.unwrap();
+ let trusted_info = ente_legacy::info(&pair.trusted_session).await.unwrap();
assert!(
legacy::owner_recovery_session(&owner_info, pair.owner.user_id, pair.trusted.user_id)
.is_none()
@@ -201,37 +213,41 @@ async fn run_legacy_stop_stage(pair: &legacy::LegacyPair) {
}
async fn run_legacy_reinvite_stage(pair: &legacy::LegacyPair) {
- pair.owner_ctx
- .update_contact(
- pair.owner.user_id,
- pair.trusted.user_id,
- LegacyContactState::Revoked,
- )
- .await
- .unwrap();
-
- let owner_info = pair.owner_ctx.info().await.unwrap();
- let trusted_info = pair.trusted_ctx.info().await.unwrap();
+ ente_legacy::update_contact(
+ &pair.owner_session,
+ pair.owner.user_id,
+ pair.trusted.user_id,
+ LegacyContactState::Revoked,
+ )
+ .await
+ .unwrap();
+
+ let owner_info = ente_legacy::info(&pair.owner_session).await.unwrap();
+ let trusted_info = ente_legacy::info(&pair.trusted_session).await.unwrap();
assert!(legacy::owner_contact(&owner_info, pair.owner.user_id, pair.trusted.user_id).is_none());
assert!(
legacy::trusted_contact(&trusted_info, pair.owner.user_id, pair.trusted.user_id).is_none()
);
- pair.owner_ctx
- .add_contact(&pair.trusted.email, &pair.owner.key_attributes, Some(14))
- .await
- .unwrap();
- pair.trusted_ctx
- .update_contact(
- pair.owner.user_id,
- pair.trusted.user_id,
- LegacyContactState::Accepted,
- )
- .await
- .unwrap();
-
- let owner_info = pair.owner_ctx.info().await.unwrap();
- let trusted_info = pair.trusted_ctx.info().await.unwrap();
+ ente_legacy::add_contact(
+ &pair.owner_session,
+ &pair.trusted.email,
+ &pair.owner.key_attributes,
+ Some(14),
+ )
+ .await
+ .unwrap();
+ ente_legacy::update_contact(
+ &pair.trusted_session,
+ pair.owner.user_id,
+ pair.trusted.user_id,
+ LegacyContactState::Accepted,
+ )
+ .await
+ .unwrap();
+
+ let owner_info = ente_legacy::info(&pair.owner_session).await.unwrap();
+ let trusted_info = ente_legacy::info(&pair.trusted_session).await.unwrap();
let owner_contact =
legacy::owner_contact(&owner_info, pair.owner.user_id, pair.trusted.user_id)
.expect("reinvited contact missing from owner view");
@@ -249,23 +265,30 @@ async fn run_legacy_reset_stage(endpoint: &str, pair: &mut legacy::LegacyPair) {
.expect("two-factor status before recovery fetch failed")
);
- pair.trusted_ctx
- .start_recovery(pair.owner.user_id, pair.trusted.user_id)
- .await
- .unwrap();
+ ente_legacy::start_recovery(
+ &pair.trusted_session,
+ pair.owner.user_id,
+ pair.trusted.user_id,
+ )
+ .await
+ .unwrap();
- let owner_info = pair.owner_ctx.info().await.unwrap();
+ let owner_info = ente_legacy::info(&pair.owner_session).await.unwrap();
let recovery =
legacy::owner_recovery_session(&owner_info, pair.owner.user_id, pair.trusted.user_id)
.expect("owner recovery session missing");
assert_eq!(recovery.status, LegacyRecoveryStatus::Waiting);
- pair.owner_ctx
- .approve_recovery(&recovery.id, pair.owner.user_id, pair.trusted.user_id)
- .await
- .unwrap();
+ ente_legacy::approve_recovery(
+ &pair.owner_session,
+ &recovery.id,
+ pair.owner.user_id,
+ pair.trusted.user_id,
+ )
+ .await
+ .unwrap();
- let owner_info = pair.owner_ctx.info().await.unwrap();
+ let owner_info = ente_legacy::info(&pair.owner_session).await.unwrap();
let recovery =
legacy::owner_recovery_session(&owner_info, pair.owner.user_id, pair.trusted.user_id)
.expect("approved recovery session missing");
@@ -273,10 +296,14 @@ async fn run_legacy_reset_stage(endpoint: &str, pair: &mut legacy::LegacyPair) {
let previous_password = pair.owner.password.clone();
let new_password = support::unique_password("LegacyRecovered");
- pair.trusted_ctx
- .change_password(&recovery.id, &pair.trusted.key_attributes, &new_password)
- .await
- .unwrap();
+ ente_legacy::change_password(
+ &pair.trusted_session,
+ &recovery.id,
+ &pair.trusted.key_attributes,
+ &new_password,
+ )
+ .await
+ .unwrap();
match auth::login_without_totp(endpoint, &pair.owner.email, &previous_password).await {
Err(ente_accounts::Error::IncorrectPassword) => {}
@@ -300,9 +327,9 @@ async fn run_legacy_reset_stage(endpoint: &str, pair: &mut legacy::LegacyPair) {
.expect("two-factor status after recovery fetch failed")
);
- let recovered_owner_ctx = legacy::open_client(endpoint, &recovered_owner);
- let owner_info = recovered_owner_ctx.info().await.unwrap();
- let trusted_info = pair.trusted_ctx.info().await.unwrap();
+ let recovered_owner_session = legacy::open_session(endpoint, &recovered_owner);
+ let owner_info = ente_legacy::info(&recovered_owner_session).await.unwrap();
+ let trusted_info = ente_legacy::info(&pair.trusted_session).await.unwrap();
assert!(
legacy::owner_recovery_session(&owner_info, pair.owner.user_id, pair.trusted.user_id)
.is_none()
@@ -318,7 +345,7 @@ async fn run_legacy_reset_stage(endpoint: &str, pair: &mut legacy::LegacyPair) {
assert_eq!(owner_contact.state, LegacyContactState::Accepted);
pair.owner = recovered_owner;
- pair.owner_ctx = recovered_owner_ctx;
+ pair.owner_session = recovered_owner_session;
}
async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitOwner) {
@@ -360,22 +387,19 @@ async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitO
.expect("legacy kit invalid create request failed");
assert_eq!(invalid_create.status(), reqwest::StatusCode::BAD_REQUEST);
- let waiting_kit = owner
- .owner_ctx
- .create_kit(
- &owner.owner.key_attributes,
- ["North".into(), "East".into(), "West".into()],
- 24,
- )
- .await
- .expect("waiting legacy kit create failed");
+ let waiting_kit = ente_legacy::create_kit(
+ &owner.owner_session,
+ &owner.owner.key_attributes,
+ ["North".into(), "East".into(), "West".into()],
+ 24,
+ )
+ .await
+ .expect("waiting legacy kit create failed");
assert_eq!(waiting_kit.kit.notice_period_in_hours, 24);
assert_eq!(waiting_kit.kit.metadata.parts.len(), 3);
assert_eq!(waiting_kit.shares.len(), 3);
- let listed = owner
- .owner_ctx
- .kits()
+ let listed = ente_legacy::kits(&owner.owner_session)
.await
.expect("legacy kit list failed");
let listed_waiting_kit = listed
@@ -385,11 +409,10 @@ async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitO
assert_eq!(listed_waiting_kit.metadata.parts.len(), 3);
assert_eq!(listed_waiting_kit.metadata.parts[0].name, "North");
- let downloaded_shares = owner
- .owner_ctx
- .download_kit_shares(&waiting_kit.kit.id)
- .await
- .expect("legacy kit share download failed");
+ let downloaded_shares =
+ ente_legacy::download_kit_shares(&owner.owner_session, &waiting_kit.kit.id)
+ .await
+ .expect("legacy kit share download failed");
assert_eq!(downloaded_shares.len(), 3);
assert_eq!(downloaded_shares[0].kit_id, waiting_kit.kit.id);
assert_eq!(
@@ -427,9 +450,7 @@ async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitO
.expect("legacy kit invalid recovery open request failed");
assert_eq!(invalid_open.status(), reqwest::StatusCode::BAD_REQUEST);
- let listed_after_invalid_open = owner
- .owner_ctx
- .kits()
+ let listed_after_invalid_open = ente_legacy::kits(&owner.owner_session)
.await
.expect("legacy kit list after invalid challenge failed");
let listed_waiting_after_invalid_open = listed_after_invalid_open
@@ -529,11 +550,10 @@ async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitO
.await
.expect("resumed legacy kit session fetch failed");
assert_eq!(resumed_session.status, LegacyKitRecoveryStatus::Waiting);
- let owner_recovery_session = owner
- .owner_ctx
- .kit_recovery_session(&waiting_kit.kit.id)
- .await
- .expect("owner legacy kit recovery session fetch failed");
+ let owner_recovery_session =
+ ente_legacy::kit_recovery_session(&owner.owner_session, &waiting_kit.kit.id)
+ .await
+ .expect("owner legacy kit recovery session fetch failed");
let owner_active_session = owner_recovery_session
.session
.as_ref()
@@ -561,9 +581,7 @@ async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitO
.all(|initiator| !initiator.user_agent.is_empty())
);
- owner
- .owner_ctx
- .block_kit_recovery(&waiting_kit.kit.id)
+ ente_legacy::block_kit_recovery(&owner.owner_session, &waiting_kit.kit.id)
.await
.expect("legacy kit block failed");
let blocked_session = resumed_waiting_handle
@@ -579,22 +597,17 @@ async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitO
blocked_original_session.status,
LegacyKitRecoveryStatus::Blocked
);
- let blocked_owner_recovery_session = owner
- .owner_ctx
- .kit_recovery_session(&waiting_kit.kit.id)
- .await
- .expect("owner legacy kit recovery session fetch after block failed");
+ let blocked_owner_recovery_session =
+ ente_legacy::kit_recovery_session(&owner.owner_session, &waiting_kit.kit.id)
+ .await
+ .expect("owner legacy kit recovery session fetch after block failed");
assert!(blocked_owner_recovery_session.session.is_none());
assert!(blocked_owner_recovery_session.initiators.is_empty());
- owner
- .owner_ctx
- .delete_kit(&waiting_kit.kit.id)
+ ente_legacy::delete_kit(&owner.owner_session, &waiting_kit.kit.id)
.await
.expect("legacy kit delete failed");
- let listed_after_delete = owner
- .owner_ctx
- .kits()
+ let listed_after_delete = ente_legacy::kits(&owner.owner_session)
.await
.expect("legacy kit list after delete failed");
assert!(
@@ -614,15 +627,14 @@ async fn run_legacy_kit_stage(endpoint: &str, owner: &mut legacy_kit::LegacyKitO
ente_legacy::Error::LegacyKitInactive
));
- let immediate_kit = owner
- .owner_ctx
- .create_kit(
- &owner.owner.key_attributes,
- ["Alpha".into(), "Bravo".into(), "Charlie".into()],
- 0,
- )
- .await
- .expect("immediate legacy kit create failed");
+ let immediate_kit = ente_legacy::create_kit(
+ &owner.owner_session,
+ &owner.owner.key_attributes,
+ ["Alpha".into(), "Bravo".into(), "Charlie".into()],
+ 0,
+ )
+ .await
+ .expect("immediate legacy kit create failed");
let ready_handle = recovery_client
.open_from_shares(&immediate_kit.shares[0..2], Some("[email protected]"))
.await
diff --git a/rust/crates/contacts/tests/contacts_mock.rs b/rust/crates/contacts/tests/contacts_mock.rs
index f77c3323a9..b3f7c9a8fb 100644
--- a/rust/crates/contacts/tests/contacts_mock.rs
+++ b/rust/crates/contacts/tests/contacts_mock.rs
@@ -5,7 +5,7 @@ use ente_contacts::{
RootKeySource, WrappedRootContactKey,
};
use ente_core::{
- b64,
+ Session, b64,
crypto::{Key, SecretVec, blob, secretbox},
http::{Api, ApiConfig, Auth, Http},
};
@@ -34,8 +34,10 @@ fn open(
},
);
ContactsClient::open(
- Arc::new(api),
- Arc::new(SecretVec::new(master_key)),
+ Arc::new(Session {
+ api,
+ master_key: SecretVec::new(master_key),
+ }),
OpenContactsInput {
user_id: 7,
cached_wrapped_root_contact_key,
diff --git a/rust/crates/contacts/tests/support/contacts.rs b/rust/crates/contacts/tests/support/contacts.rs
index 8d9f7f5901..f30cb70cc4 100644
--- a/rust/crates/contacts/tests/support/contacts.rs
+++ b/rust/crates/contacts/tests/support/contacts.rs
@@ -2,6 +2,7 @@ use std::sync::Arc;
use ente_contacts::{ContactsClient, OpenContactsInput};
use ente_core::{
+ Session,
crypto::SecretVec,
http::{Api, ApiConfig, Auth, Http},
};
@@ -21,8 +22,10 @@ pub fn open_client(endpoint: &str, account: &TestAccount) -> ContactsClient {
},
);
ContactsClient::open(
- Arc::new(api),
- Arc::new(SecretVec::new(account.master_key.clone())),
+ Arc::new(Session {
+ api,
+ master_key: SecretVec::new(account.master_key.clone()),
+ }),
OpenContactsInput {
user_id: account.user_id,
cached_wrapped_root_contact_key: None,
diff --git a/rust/crates/contacts/tests/support/legacy.rs b/rust/crates/contacts/tests/support/legacy.rs
index d51b545b45..60a386e9d5 100644
--- a/rust/crates/contacts/tests/support/legacy.rs
+++ b/rust/crates/contacts/tests/support/legacy.rs
@@ -1,12 +1,9 @@
-use std::sync::Arc;
-
use ente_core::{
+ Session,
crypto::SecretVec,
- http::{Api, ApiConfig, Auth, Http},
-};
-use ente_legacy::{
- LegacyClient, LegacyContactRecord, LegacyContactState, LegacyInfo, LegacyRecoverySession,
+ http::{ApiConfig, Auth},
};
+use ente_legacy::{LegacyContactRecord, LegacyContactState, LegacyInfo, LegacyRecoverySession};
use crate::CLIENT_PACKAGE;
use crate::support::auth::{self, TestAccount};
@@ -19,13 +16,12 @@ pub struct LegacyPairState {
pub struct LegacyPair {
pub owner: TestAccount,
pub trusted: TestAccount,
- pub owner_ctx: LegacyClient,
- pub trusted_ctx: LegacyClient,
+ pub owner_session: Session,
+ pub trusted_session: Session,
}
-pub fn open_client(endpoint: &str, account: &TestAccount) -> LegacyClient {
- let api = Api::new(
- Http::new().unwrap(),
+pub fn open_session(endpoint: &str, account: &TestAccount) -> Session {
+ Session::new(
ApiConfig {
origin: endpoint.to_string(),
client_package: Some(CLIENT_PACKAGE.to_string()),
@@ -33,11 +29,9 @@ pub fn open_client(endpoint: &str, account: &TestAccount) -> LegacyClient {
user_agent: Some("ente-legacy-e2e".to_string()),
auth: Some(Auth::User(account.auth_token.clone())),
},
- );
- LegacyClient::new(
- Arc::new(api),
- Arc::new(SecretVec::new(account.master_key.clone())),
+ SecretVec::new(account.master_key.clone()),
)
+ .unwrap()
}
pub async fn create_accepted_pair_state(
@@ -47,21 +41,25 @@ pub async fn create_accepted_pair_state(
let owner = auth::create_account_strict(endpoint, "legacy-owner", "LegacyOwner").await;
let trusted = auth::create_fixture_account(endpoint, "legacy-trusted").await;
- let owner_ctx = open_client(endpoint, &owner);
- let trusted_ctx = open_client(endpoint, &trusted);
+ let owner_session = open_session(endpoint, &owner);
+ let trusted_session = open_session(endpoint, &trusted);
- owner_ctx
- .add_contact(
- &trusted.email,
- &owner.key_attributes,
- Some(recovery_notice_in_days),
- )
- .await
- .unwrap();
- trusted_ctx
- .update_contact(owner.user_id, trusted.user_id, LegacyContactState::Accepted)
- .await
- .unwrap();
+ ente_legacy::add_contact(
+ &owner_session,
+ &trusted.email,
+ &owner.key_attributes,
+ Some(recovery_notice_in_days),
+ )
+ .await
+ .unwrap();
+ ente_legacy::update_contact(
+ &trusted_session,
+ owner.user_id,
+ trusted.user_id,
+ LegacyContactState::Accepted,
+ )
+ .await
+ .unwrap();
LegacyPairState { owner, trusted }
}
@@ -69,14 +67,14 @@ pub async fn create_accepted_pair_state(
pub fn open_pair(endpoint: &str, state: &LegacyPairState) -> LegacyPair {
let owner = state.owner.clone();
let trusted = state.trusted.clone();
- let owner_ctx = open_client(endpoint, &owner);
- let trusted_ctx = open_client(endpoint, &trusted);
+ let owner_session = open_session(endpoint, &owner);
+ let trusted_session = open_session(endpoint, &trusted);
LegacyPair {
owner,
trusted,
- owner_ctx,
- trusted_ctx,
+ owner_session,
+ trusted_session,
}
}
diff --git a/rust/crates/contacts/tests/support/legacy_kit.rs b/rust/crates/contacts/tests/support/legacy_kit.rs
index 002730558e..3bd6b9404f 100644
--- a/rust/crates/contacts/tests/support/legacy_kit.rs
+++ b/rust/crates/contacts/tests/support/legacy_kit.rs
@@ -1,4 +1,4 @@
-use ente_legacy::LegacyClient;
+use ente_core::Session;
use crate::support::{
auth::{self, TestAccount},
@@ -7,11 +7,14 @@ use crate::support::{
pub struct LegacyKitOwner {
pub owner: TestAccount,
- pub owner_ctx: LegacyClient,
+ pub owner_session: Session,
}
pub async fn create_owner(endpoint: &str) -> LegacyKitOwner {
let owner = auth::create_fixture_account(endpoint, "legacy-kit-owner").await;
- let owner_ctx = legacy::open_client(endpoint, &owner);
- LegacyKitOwner { owner, owner_ctx }
+ let owner_session = legacy::open_session(endpoint, &owner);
+ LegacyKitOwner {
+ owner,
+ owner_session,
+ }
}
diff --git a/rust/crates/core/src/lib.rs b/rust/crates/core/src/lib.rs
index d47232895e..4d4862e8a1 100644
--- a/rust/crates/core/src/lib.rs
+++ b/rust/crates/core/src/lib.rs
@@ -4,4 +4,7 @@ pub mod error;
pub mod http;
pub mod id;
pub mod io;
+mod session;
pub mod urls;
+
+pub use session::Session;
diff --git a/rust/crates/core/src/session.rs b/rust/crates/core/src/session.rs
new file mode 100644
index 0000000000..45503a9be7
--- /dev/null
+++ b/rust/crates/core/src/session.rs
@@ -0,0 +1,18 @@
+use crate::{
+ crypto::SecretVec,
+ http::{Api, ApiConfig, Error, Http},
+};
+
+pub struct Session {
+ pub api: Api,
+ pub master_key: SecretVec,
+}
+
+impl Session {
+ pub fn new(config: ApiConfig, master_key: SecretVec) -> Result<Self, Error> {
+ Ok(Self {
+ api: Api::new(Http::new()?, config),
+ master_key,
+ })
+ }
+}
diff --git a/rust/crates/legacy/src/client/contact.rs b/rust/crates/legacy/src/client/contact.rs
index 488787cee9..5b093d5a57 100644
--- a/rust/crates/legacy/src/client/contact.rs
+++ b/rust/crates/legacy/src/client/contact.rs
@@ -1,11 +1,11 @@
use ente_accounts::auth::KeyAttributes;
-use ente_core::b64;
use ente_core::crypto::{self, sealed};
use ente_core::http;
+use ente_core::{Session, b64};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
-use super::LegacyClient;
+use super::current_recovery_key;
use crate::{Error, Result};
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
@@ -67,120 +67,119 @@ pub struct LegacyInfo {
pub others_recovery_session: Vec<LegacyRecoverySession>,
}
-impl LegacyClient {
- pub async fn info(&self) -> Result<LegacyInfo> {
- Ok(self
- .api
- .get("/emergency-contacts/info")
- .send()
- .await?
- .error_for_status()?
- .json::<LegacyInfo>()
- .await?)
- }
+pub async fn info(session: &Session) -> Result<LegacyInfo> {
+ Ok(session
+ .api
+ .get("/emergency-contacts/info")
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<LegacyInfo>()
+ .await?)
+}
- pub async fn public_key(&self, email: &str) -> Result<Option<String>> {
- let response = self
- .api
- .get("/users/public-key")
- .query(&[("email", email.trim())])
- .send()
- .await?;
- if response.status() == 404 {
- return Ok(None);
- }
- let response = response
- .error_for_status()?
- .json::<LegacyPublicKeyResponse>()
- .await?;
- Ok(Some(response.public_key))
+pub async fn public_key(session: &Session, email: &str) -> Result<Option<String>> {
+ let response = session
+ .api
+ .get("/users/public-key")
+ .query(&[("email", email.trim())])
+ .send()
+ .await?;
+ if response.status() == 404 {
+ return Ok(None);
}
+ let response = response
+ .error_for_status()?
+ .json::<LegacyPublicKeyResponse>()
+ .await?;
+ Ok(Some(response.public_key))
+}
- pub fn verification_id(&self, public_key_b64: &str) -> Result<String> {
- let public_key = b64::decode(public_key_b64)?;
- let digest = Sha256::digest(&public_key);
- ente_accounts::auth::recovery_key_to_mnemonic(&b64::encode(digest.as_slice()))
- .map_err(Into::into)
- }
+pub fn verification_id(public_key_b64: &str) -> Result<String> {
+ let public_key = b64::decode(public_key_b64)?;
+ let digest = Sha256::digest(&public_key);
+ ente_accounts::auth::recovery_key_to_mnemonic(&b64::encode(digest.as_slice()))
+ .map_err(Into::into)
+}
- pub async fn add_contact(
- &self,
- email: &str,
- current_user_key_attrs: &KeyAttributes,
- recovery_notice_in_days: Option<i32>,
- ) -> Result<()> {
- let public_key = self
- .public_key(email)
- .await?
- .ok_or(Error::ContactNotOnEnte)?;
- let recovery_key = self.current_recovery_key(current_user_key_attrs)?;
- let recipient_public_key = b64::decode(&public_key)?;
- let encrypted_key = sealed::seal(
- &recovery_key,
- &crypto::PublicKey::try_from_slice(&recipient_public_key)?,
- )?;
-
- self.api
- .post("/emergency-contacts/add")
- .json(&LegacyAddContactRequest {
- email: email.trim().to_string(),
- encrypted_key: b64::encode(&encrypted_key),
- recovery_notice_in_days,
- })
- .send()
- .await?
- .error_for_status()?;
- Ok(())
- }
+pub async fn add_contact(
+ session: &Session,
+ email: &str,
+ current_user_key_attrs: &KeyAttributes,
+ recovery_notice_in_days: Option<i32>,
+) -> Result<()> {
+ let public_key = public_key(session, email)
+ .await?
+ .ok_or(Error::ContactNotOnEnte)?;
+ let recovery_key = current_recovery_key(session, current_user_key_attrs)?;
+ let recipient_public_key = b64::decode(&public_key)?;
+ let encrypted_key = sealed::seal(
+ &recovery_key,
+ &crypto::PublicKey::try_from_slice(&recipient_public_key)?,
+ )?;
+
+ session
+ .api
+ .post("/emergency-contacts/add")
+ .json(&LegacyAddContactRequest {
+ email: email.trim().to_string(),
+ encrypted_key: b64::encode(&encrypted_key),
+ recovery_notice_in_days,
+ })
+ .send()
+ .await?
+ .error_for_status()?;
+ Ok(())
+}
- pub async fn update_contact(
- &self,
- user_id: i64,
- emergency_contact_id: i64,
- state: LegacyContactState,
- ) -> Result<()> {
- self.api
- .post("/emergency-contacts/update")
- .json(&LegacyUpdateContactRequest {
- user_id,
- emergency_contact_id,
- state,
- })
- .send()
- .await?
- .error_for_status()?;
- Ok(())
- }
+pub async fn update_contact(
+ session: &Session,
+ user_id: i64,
+ emergency_contact_id: i64,
+ state: LegacyContactState,
+) -> Result<()> {
+ session
+ .api
+ .post("/emergency-contacts/update")
+ .json(&LegacyUpdateContactRequest {
+ user_id,
+ emergency_contact_id,
+ state,
+ })
+ .send()
+ .await?
+ .error_for_status()?;
+ Ok(())
+}
- pub async fn update_recovery_notice(
- &self,
- emergency_contact_id: i64,
- recovery_notice_in_days: i32,
- ) -> Result<()> {
- let path = "/emergency-contacts/update-recovery-notice";
- let response = self
- .api
- .post(path)
- .json(&LegacyUpdateRecoveryNoticeRequest {
- emergency_contact_id,
- recovery_notice_in_days,
- })
- .send()
- .await?;
- if response.status() == 400 {
- return if response.text().await?.contains("active recovery session") {
- Err(Error::ActiveRecoverySession)
- } else {
- Err(http::Error::Http {
- status: 400,
- path: path.into(),
- }
- .into())
- };
- }
- response.error_for_status()?;
- Ok(())
+pub async fn update_recovery_notice(
+ session: &Session,
+ emergency_contact_id: i64,
+ recovery_notice_in_days: i32,
+) -> Result<()> {
+ let path = "/emergency-contacts/update-recovery-notice";
+ let response = session
+ .api
+ .post(path)
+ .json(&LegacyUpdateRecoveryNoticeRequest {
+ emergency_contact_id,
+ recovery_notice_in_days,
+ })
+ .send()
+ .await?;
+ if response.status() == 400 {
+ return if response.text().await?.contains("active recovery session") {
+ Err(Error::ActiveRecoverySession)
+ } else {
+ Err(http::Error::Http {
+ status: 400,
+ path: path.into(),
+ }
+ .into())
+ };
}
+ response.error_for_status()?;
+ Ok(())
}
#[derive(Deserialize)]
diff --git a/rust/crates/legacy/src/client/kit/mod.rs b/rust/crates/legacy/src/client/kit/mod.rs
index 87cd5e9ccf..df4725c572 100644
--- a/rust/crates/legacy/src/client/kit/mod.rs
+++ b/rust/crates/legacy/src/client/kit/mod.rs
@@ -1,13 +1,13 @@
mod owner_blob;
use ente_accounts::auth::KeyAttributes;
-use ente_core::b64;
use ente_core::crypto::{self, SecretVec, secretbox};
use ente_core::http;
+use ente_core::{Session, b64};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
-use super::LegacyClient;
+use super::current_recovery_key;
use crate::kit::{
LEGACY_KIT_PAYLOAD_VERSION, LegacyKit, LegacyKitCreateResult, LegacyKitOwnerRecoverySession,
LegacyKitRecoveryInitiator, LegacyKitRecoverySession, LegacyKitShare, LegacyKitVariant,
@@ -20,130 +20,130 @@ use owner_blob::{
const NOTICE_PERIOD_OPTIONS: [i32; 5] = [0, 24, 168, 360, 720];
-impl LegacyClient {
- pub async fn kits(&self) -> Result<Vec<LegacyKit>> {
- let response = self
- .api
- .get("/legacy-kits")
- .send()
- .await?
- .error_for_status()?
- .json::<ListLegacyKitsResponse>()
- .await?;
- response
- .kits
- .into_iter()
- .map(|kit| decode_kit_record(kit, self.master_key.as_ref()))
- .collect()
- }
+pub async fn kits(session: &Session) -> Result<Vec<LegacyKit>> {
+ let response = session
+ .api
+ .get("/legacy-kits")
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ListLegacyKitsResponse>()
+ .await?;
+ response
+ .kits
+ .into_iter()
+ .map(|kit| decode_kit_record(kit, &session.master_key))
+ .collect()
+}
- pub async fn create_kit(
- &self,
- key_attributes: &KeyAttributes,
- part_names: [String; 3],
- notice_period_in_hours: i32,
- ) -> Result<LegacyKitCreateResult> {
- let (request, shares) = {
- let recovery_key = self.current_recovery_key(key_attributes)?;
- create_kit_request(
- &recovery_key,
- self.master_key.as_ref(),
- part_names,
- notice_period_in_hours,
- )?
- };
+pub async fn create_kit(
+ session: &Session,
+ key_attributes: &KeyAttributes,
+ part_names: [String; 3],
+ notice_period_in_hours: i32,
+) -> Result<LegacyKitCreateResult> {
+ let (request, shares) = {
+ let recovery_key = current_recovery_key(session, key_attributes)?;
+ create_kit_request(
+ &recovery_key,
+ &session.master_key,
+ part_names,
+ notice_period_in_hours,
+ )?
+ };
- let response = self
- .api
- .post("/legacy-kits")
- .json(&request)
- .send()
- .await?
- .error_for_status()?
- .json::<LegacyKitRecordResponse>()
- .await?;
- let kit = decode_kit_record(response, self.master_key.as_ref())?;
- Ok(LegacyKitCreateResult { kit, shares })
- }
+ let response = session
+ .api
+ .post("/legacy-kits")
+ .json(&request)
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<LegacyKitRecordResponse>()
+ .await?;
+ let kit = decode_kit_record(response, &session.master_key)?;
+ Ok(LegacyKitCreateResult { kit, shares })
+}
- pub async fn download_kit_shares(&self, kit_id: &str) -> Result<Vec<LegacyKitShare>> {
- let response = self
- .api
- .get(&format!("/legacy-kits/{kit_id}/download-content"))
- .send()
- .await?
- .error_for_status()?
- .json::<LegacyKitDownloadContentResponse>()
- .await?;
- decode_download_content(response, self.master_key.as_ref())
- }
+pub async fn download_kit_shares(session: &Session, kit_id: &str) -> Result<Vec<LegacyKitShare>> {
+ let response = session
+ .api
+ .get(&format!("/legacy-kits/{kit_id}/download-content"))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<LegacyKitDownloadContentResponse>()
+ .await?;
+ decode_download_content(response, &session.master_key)
+}
- pub async fn kit_recovery_session(
- &self,
- kit_id: &str,
- ) -> Result<LegacyKitOwnerRecoverySession> {
- let response = self
- .api
- .get(&format!("/legacy-kits/{kit_id}/recovery-session"))
- .send()
- .await?
- .error_for_status()?
- .json::<LegacyKitOwnerRecoverySessionResponse>()
- .await?;
- Ok(response.into())
- }
+pub async fn kit_recovery_session(
+ session: &Session,
+ kit_id: &str,
+) -> Result<LegacyKitOwnerRecoverySession> {
+ let response = session
+ .api
+ .get(&format!("/legacy-kits/{kit_id}/recovery-session"))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<LegacyKitOwnerRecoverySessionResponse>()
+ .await?;
+ Ok(response.into())
+}
- pub async fn update_kit_recovery_notice(
- &self,
- kit_id: &str,
- notice_period_in_hours: i32,
- ) -> Result<()> {
- validate_notice_period(notice_period_in_hours)?;
- let path = "/legacy-kits/update-recovery-notice";
- let response = self
- .api
- .post(path)
- .json(&LegacyKitUpdateRecoveryNoticeRequest {
- kit_id: kit_id.to_string(),
- notice_period_in_hours,
- })
- .send()
- .await?;
- if response.status() == 400 {
- return if response.text().await?.contains("active recovery session") {
- Err(Error::ActiveRecoverySession)
- } else {
- Err(http::Error::Http {
- status: 400,
- path: path.into(),
- }
- .into())
- };
- }
- response.error_for_status()?;
- Ok(())
+pub async fn update_kit_recovery_notice(
+ session: &Session,
+ kit_id: &str,
+ notice_period_in_hours: i32,
+) -> Result<()> {
+ validate_notice_period(notice_period_in_hours)?;
+ let path = "/legacy-kits/update-recovery-notice";
+ let response = session
+ .api
+ .post(path)
+ .json(&LegacyKitUpdateRecoveryNoticeRequest {
+ kit_id: kit_id.to_string(),
+ notice_period_in_hours,
+ })
+ .send()
+ .await?;
+ if response.status() == 400 {
+ return if response.text().await?.contains("active recovery session") {
+ Err(Error::ActiveRecoverySession)
+ } else {
+ Err(http::Error::Http {
+ status: 400,
+ path: path.into(),
+ }
+ .into())
+ };
}
+ response.error_for_status()?;
+ Ok(())
+}
- pub async fn block_kit_recovery(&self, kit_id: &str) -> Result<()> {
- self.api
- .post("/legacy-kits/block-recovery")
- .json(&LegacyKitOwnerActionRequest {
- kit_id: kit_id.to_string(),
- })
- .send()
- .await?
- .error_for_status()?;
- Ok(())
- }
+pub async fn block_kit_recovery(session: &Session, kit_id: &str) -> Result<()> {
+ session
+ .api
+ .post("/legacy-kits/block-recovery")
+ .json(&LegacyKitOwnerActionRequest {
+ kit_id: kit_id.to_string(),
+ })
+ .send()
+ .await?
+ .error_for_status()?;
+ Ok(())
+}
- pub async fn delete_kit(&self, kit_id: &str) -> Result<()> {
- self.api
- .delete(&format!("/legacy-kits/{kit_id}"))
- .send()
- .await?
- .error_for_status()?;
- Ok(())
- }
+pub async fn delete_kit(session: &Session, kit_id: &str) -> Result<()> {
+ session
+ .api
+ .delete(&format!("/legacy-kits/{kit_id}"))
+ .send()
+ .await?
+ .error_for_status()?;
+ Ok(())
}
fn create_kit_request(
diff --git a/rust/crates/legacy/src/client/mod.rs b/rust/crates/legacy/src/client/mod.rs
index b2ccec727f..db884eb66d 100644
--- a/rust/crates/legacy/src/client/mod.rs
+++ b/rust/crates/legacy/src/client/mod.rs
@@ -4,30 +4,24 @@ mod recovery;
pub use contact::{
LegacyContactRecord, LegacyContactState, LegacyInfo, LegacyRecoverySession,
- LegacyRecoveryStatus, LegacyUser,
+ LegacyRecoveryStatus, LegacyUser, add_contact, info, public_key, update_contact,
+ update_recovery_notice, verification_id,
+};
+pub use kit::{
+ block_kit_recovery, create_kit, delete_kit, download_kit_shares, kit_recovery_session, kits,
+ update_kit_recovery_notice,
+};
+pub use recovery::{
+ LegacyRecoveryBundle, approve_recovery, change_password, recovery_bundle, reject_recovery,
+ start_recovery, stop_recovery,
};
-pub use recovery::LegacyRecoveryBundle;
-
-use std::sync::Arc;
use ente_accounts::auth::{self, KeyAttributes};
-use ente_core::crypto::SecretVec;
-use ente_core::http::Api;
+use ente_core::{Session, crypto::SecretVec};
use crate::Result;
-pub struct LegacyClient {
- api: Arc<Api>,
- master_key: Arc<SecretVec>,
-}
-
-impl LegacyClient {
- pub fn new(api: Arc<Api>, master_key: Arc<SecretVec>) -> Self {
- Self { api, master_key }
- }
-
- fn current_recovery_key(&self, key_attributes: &KeyAttributes) -> Result<SecretVec> {
- let recovery_key = auth::get_recovery_key(self.master_key.as_ref(), key_attributes)?;
- Ok(auth::recovery_key_from_mnemonic_or_hex(&recovery_key)?)
- }
+fn current_recovery_key(session: &Session, key_attributes: &KeyAttributes) -> Result<SecretVec> {
+ let recovery_key = auth::get_recovery_key(&session.master_key, key_attributes)?;
+ Ok(auth::recovery_key_from_mnemonic_or_hex(&recovery_key)?)
}
diff --git a/rust/crates/legacy/src/client/recovery.rs b/rust/crates/legacy/src/client/recovery.rs
index 720a56ad0b..488cba94f4 100644
--- a/rust/crates/legacy/src/client/recovery.rs
+++ b/rust/crates/legacy/src/client/recovery.rs
@@ -1,10 +1,9 @@
use ente_accounts::auth::{self, KeyAttributes, SrpSession};
-use ente_core::b64;
use ente_core::crypto::{self, SecretVec, sealed, secretbox};
+use ente_core::{Session, b64};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
-use super::LegacyClient;
use crate::{Error, Result};
#[derive(Debug)]
@@ -13,215 +12,221 @@ pub struct LegacyRecoveryBundle {
pub user_key_attributes: KeyAttributes,
}
-impl LegacyClient {
- pub async fn start_recovery(&self, user_id: i64, emergency_contact_id: i64) -> Result<()> {
- self.contact_action(
- "/emergency-contacts/start-recovery",
- user_id,
- emergency_contact_id,
- )
- .await
- }
+pub async fn start_recovery(
+ session: &Session,
+ user_id: i64,
+ emergency_contact_id: i64,
+) -> Result<()> {
+ contact_action(
+ session,
+ "/emergency-contacts/start-recovery",
+ user_id,
+ emergency_contact_id,
+ )
+ .await
+}
- pub async fn stop_recovery(
- &self,
- recovery_id: &str,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<()> {
- self.recovery_action(
- "/emergency-contacts/stop-recovery",
- recovery_id,
- user_id,
- emergency_contact_id,
- )
- .await
- }
+pub async fn stop_recovery(
+ session: &Session,
+ recovery_id: &str,
+ user_id: i64,
+ emergency_contact_id: i64,
+) -> Result<()> {
+ recovery_action(
+ session,
+ "/emergency-contacts/stop-recovery",
+ recovery_id,
+ user_id,
+ emergency_contact_id,
+ )
+ .await
+}
- pub async fn reject_recovery(
- &self,
- recovery_id: &str,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<()> {
- self.recovery_action(
- "/emergency-contacts/reject-recovery",
- recovery_id,
- user_id,
- emergency_contact_id,
- )
- .await
- }
+pub async fn reject_recovery(
+ session: &Session,
+ recovery_id: &str,
+ user_id: i64,
+ emergency_contact_id: i64,
+) -> Result<()> {
+ recovery_action(
+ session,
+ "/emergency-contacts/reject-recovery",
+ recovery_id,
+ user_id,
+ emergency_contact_id,
+ )
+ .await
+}
- pub async fn approve_recovery(
- &self,
- recovery_id: &str,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<()> {
- self.recovery_action(
- "/emergency-contacts/approve-recovery",
- recovery_id,
- user_id,
- emergency_contact_id,
- )
- .await
- }
+pub async fn approve_recovery(
+ session: &Session,
+ recovery_id: &str,
+ user_id: i64,
+ emergency_contact_id: i64,
+) -> Result<()> {
+ recovery_action(
+ session,
+ "/emergency-contacts/approve-recovery",
+ recovery_id,
+ user_id,
+ emergency_contact_id,
+ )
+ .await
+}
- pub async fn recovery_bundle(
- &self,
- recovery_id: &str,
- current_user_key_attrs: &KeyAttributes,
- ) -> Result<LegacyRecoveryBundle> {
- let response = self.recovery_info(recovery_id).await?;
- let recovery_key =
- self.decrypt_recovery_key(&response.encrypted_key, current_user_key_attrs)?;
+pub async fn recovery_bundle(
+ session: &Session,
+ recovery_id: &str,
+ current_user_key_attrs: &KeyAttributes,
+) -> Result<LegacyRecoveryBundle> {
+ let response = recovery_info(session, recovery_id).await?;
+ let recovery_key =
+ decrypt_recovery_key(session, &response.encrypted_key, current_user_key_attrs)?;
- Ok(LegacyRecoveryBundle {
- recovery_key,
- user_key_attributes: response.user_key_attr,
- })
- }
+ Ok(LegacyRecoveryBundle {
+ recovery_key,
+ user_key_attributes: response.user_key_attr,
+ })
+}
- pub async fn change_password(
- &self,
- recovery_id: &str,
- current_user_key_attrs: &KeyAttributes,
- new_password: &str,
- ) -> Result<()> {
- let bundle = self
- .recovery_bundle(recovery_id, current_user_key_attrs)
- .await?;
- let target_master_key = decrypt_master_key_with_recovery_key(
- &bundle.user_key_attributes,
- &bundle.recovery_key,
- )?;
- let (updated_key_attrs, login_key) = 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, &login_key)?;
- let init_response = self
- .api
- .post("/emergency-contacts/init-change-password")
- .json(&LegacyInitChangePasswordRequest {
- recovery_id: recovery_id.to_string(),
- setup_srp_request: setup_request,
- })
- .send()
- .await?
- .error_for_status()?
- .json::<LegacySetupSrpResponse>()
- .await?;
- 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,
- ops_limit: updated_key_attrs.ops_limit,
- };
+pub async fn change_password(
+ session: &Session,
+ recovery_id: &str,
+ current_user_key_attrs: &KeyAttributes,
+ new_password: &str,
+) -> Result<()> {
+ let bundle = recovery_bundle(session, recovery_id, current_user_key_attrs).await?;
+ let target_master_key =
+ decrypt_master_key_with_recovery_key(&bundle.user_key_attributes, &bundle.recovery_key)?;
+ let (updated_key_attrs, login_key) = 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, &login_key)?;
+ let init_response = session
+ .api
+ .post("/emergency-contacts/init-change-password")
+ .json(&LegacyInitChangePasswordRequest {
+ recovery_id: recovery_id.to_string(),
+ setup_srp_request: setup_request,
+ })
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<LegacySetupSrpResponse>()
+ .await?;
+ 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,
+ ops_limit: updated_key_attrs.ops_limit,
+ };
- let change_response = self
- .api
- .post("/emergency-contacts/change-password")
- .json(&LegacyChangePasswordRequest {
- recovery_id: recovery_id.to_string(),
- update_srp_and_keys_request: LegacyUpdateSrpAndKeysRequest {
- setup_id: init_response.setup_id,
- srp_m1,
- updated_key_attr,
- },
- })
- .send()
- .await?
- .error_for_status()?
- .json::<LegacyChangePasswordResponse>()
- .await?;
+ let change_response = session
+ .api
+ .post("/emergency-contacts/change-password")
+ .json(&LegacyChangePasswordRequest {
+ recovery_id: recovery_id.to_string(),
+ update_srp_and_keys_request: LegacyUpdateSrpAndKeysRequest {
+ setup_id: init_response.setup_id,
+ srp_m1,
+ updated_key_attr,
+ },
+ })
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<LegacyChangePasswordResponse>()
+ .await?;
- let server_m2 = b64::decode(&change_response.srp_m2)?;
- srp_session.verify_m2(&server_m2)?;
- Ok(())
- }
+ let server_m2 = b64::decode(&change_response.srp_m2)?;
+ srp_session.verify_m2(&server_m2)?;
+ Ok(())
+}
- async fn contact_action(
- &self,
- path: &str,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<()> {
- self.api
- .post(path)
- .json(&LegacyContactIdentifier {
- user_id,
- emergency_contact_id,
- })
- .send()
- .await?
- .error_for_status()?;
- Ok(())
- }
+async fn contact_action(
+ session: &Session,
+ path: &str,
+ user_id: i64,
+ emergency_contact_id: i64,
+) -> Result<()> {
+ session
+ .api
+ .post(path)
+ .json(&LegacyContactIdentifier {
+ user_id,
+ emergency_contact_id,
+ })
+ .send()
+ .await?
+ .error_for_status()?;
+ Ok(())
+}
- async fn recovery_action(
- &self,
- path: &str,
- recovery_id: &str,
- user_id: i64,
- emergency_contact_id: i64,
- ) -> Result<()> {
- self.api
- .post(path)
- .json(&LegacyRecoveryIdentifier {
- id: recovery_id.to_string(),
- user_id,
- emergency_contact_id,
- })
- .send()
- .await?
- .error_for_status()?;
- Ok(())
- }
+async fn recovery_action(
+ session: &Session,
+ path: &str,
+ recovery_id: &str,
+ user_id: i64,
+ emergency_contact_id: i64,
+) -> Result<()> {
+ session
+ .api
+ .post(path)
+ .json(&LegacyRecoveryIdentifier {
+ id: recovery_id.to_string(),
+ user_id,
+ emergency_contact_id,
+ })
+ .send()
+ .await?
+ .error_for_status()?;
+ Ok(())
+}
- async fn recovery_info(&self, recovery_id: &str) -> Result<LegacyRecoveryInfoResponse> {
- Ok(self
- .api
- .get(&format!("/emergency-contacts/recovery-info/{recovery_id}"))
- .send()
- .await?
- .error_for_status()?
- .json::<LegacyRecoveryInfoResponse>()
- .await?)
- }
+async fn recovery_info(session: &Session, recovery_id: &str) -> Result<LegacyRecoveryInfoResponse> {
+ Ok(session
+ .api
+ .get(&format!("/emergency-contacts/recovery-info/{recovery_id}"))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<LegacyRecoveryInfoResponse>()
+ .await?)
+}
- fn decrypt_recovery_key(
- &self,
- encrypted_key_b64: &str,
- current_user_key_attrs: &KeyAttributes,
- ) -> Result<SecretVec> {
- let public_key = b64::decode(&current_user_key_attrs.public_key)?;
- let encrypted_key = b64::decode(encrypted_key_b64)?;
- let secret_key = self.current_secret_key(current_user_key_attrs)?;
- let decrypted = sealed::open(
- &encrypted_key,
- &crypto::PublicKey::try_from_slice(&public_key)?,
- &crypto::SecretKey::try_from_slice(&secret_key)?,
- )?;
- Ok(SecretVec::new(decrypted))
- }
+fn decrypt_recovery_key(
+ session: &Session,
+ encrypted_key_b64: &str,
+ current_user_key_attrs: &KeyAttributes,
+) -> Result<SecretVec> {
+ let public_key = b64::decode(&current_user_key_attrs.public_key)?;
+ let encrypted_key = b64::decode(encrypted_key_b64)?;
+ let secret_key = current_secret_key(session, current_user_key_attrs)?;
+ let decrypted = sealed::open(
+ &encrypted_key,
+ &crypto::PublicKey::try_from_slice(&public_key)?,
+ &crypto::SecretKey::try_from_slice(&secret_key)?,
+ )?;
+ Ok(SecretVec::new(decrypted))
+}
- fn current_secret_key(&self, current_user_key_attrs: &KeyAttributes) -> Result<SecretVec> {
- let encrypted_secret_key = b64::decode(&current_user_key_attrs.encrypted_secret_key)?;
- let secret_key_nonce = b64::decode(&current_user_key_attrs.secret_key_decryption_nonce)?;
- let secret_key = secretbox::decrypt(
- &encrypted_secret_key,
- &crypto::Nonce::try_from_slice(&secret_key_nonce)?,
- &crypto::Key::try_from_slice(self.master_key.as_ref())?,
- )?;
- Ok(SecretVec::new(secret_key))
- }
+fn current_secret_key(
+ session: &Session,
+ current_user_key_attrs: &KeyAttributes,
+) -> Result<SecretVec> {
+ let encrypted_secret_key = b64::decode(&current_user_key_attrs.encrypted_secret_key)?;
+ let secret_key_nonce = b64::decode(&current_user_key_attrs.secret_key_decryption_nonce)?;
+ let secret_key = secretbox::decrypt(
+ &encrypted_secret_key,
+ &crypto::Nonce::try_from_slice(&secret_key_nonce)?,
+ &crypto::Key::try_from_slice(&session.master_key)?,
+ )?;
+ Ok(SecretVec::new(secret_key))
}
fn decrypt_master_key_with_recovery_key(
diff --git a/rust/crates/legacy/src/lib.rs b/rust/crates/legacy/src/lib.rs
index f0e0bac854..ed37af1b76 100644
--- a/rust/crates/legacy/src/lib.rs
+++ b/rust/crates/legacy/src/lib.rs
@@ -3,8 +3,12 @@ mod error;
mod kit;
pub use client::{
- LegacyClient, LegacyContactRecord, LegacyContactState, LegacyInfo, LegacyRecoveryBundle,
- LegacyRecoverySession, LegacyRecoveryStatus, LegacyUser,
+ LegacyContactRecord, LegacyContactState, LegacyInfo, LegacyRecoveryBundle,
+ LegacyRecoverySession, LegacyRecoveryStatus, LegacyUser, add_contact, approve_recovery,
+ block_kit_recovery, change_password, create_kit, delete_kit, download_kit_shares, info,
+ kit_recovery_session, kits, public_key, recovery_bundle, reject_recovery, start_recovery,
+ stop_recovery, update_contact, update_kit_recovery_notice, update_recovery_notice,
+ verification_id,
};
pub use error::{Error, Result};
pub use kit::{
diff --git a/web/packages/contacts/legacy/service.ts b/web/packages/contacts/legacy/service.ts
index 59437f1ee7..7543489309 100644
--- a/web/packages/contacts/legacy/service.ts
+++ b/web/packages/contacts/legacy/service.ts
@@ -4,14 +4,22 @@ import { masterKeyFromSession } from "ente-accounts/services/session-storage";
import { clientPackageName, desktopAppVersion, isDesktop } from "ente-base/app";
import { apiOrigin } from "ente-base/origins";
import { savedAuthToken } from "ente-base/token";
-import { openLegacy } from "ente-legacy-wasm/authenticated";
+import {
+ addContact,
+ changePassword,
+ getInfo,
+ publicKey,
+ rejectRecovery,
+ startRecovery,
+ stopRecovery,
+ updateContact,
+ updateRecoveryNotice,
+ verificationID,
+ type SessionInput,
+} from "ente-legacy-wasm/authenticated";
import type { LegacyContactState, LegacyInfo } from "./types";
-type LegacyClient = Awaited<ReturnType<typeof openLegacy>>;
-
-const withLegacyClient = async <T>(
- operation: (client: LegacyClient) => T | Promise<T>,
-) => {
+const sessionInput = async (): Promise<SessionInput> => {
const masterKeyB64 = await masterKeyFromSession();
if (!masterKeyB64) {
throw new Error("Missing current master key");
@@ -20,18 +28,13 @@ const withLegacyClient = async <T>(
if (!authToken) {
throw new Error("Missing auth token");
}
- const client = await openLegacy({
+ return {
baseUrl: await apiOrigin(),
authToken,
masterKeyB64,
clientPackage: clientPackageName,
clientVersion: isDesktop ? desktopAppVersion : undefined,
- });
- try {
- return await operation(client);
- } finally {
- client.close();
- }
+ };
};
const currentKeyAttributes = () => {
@@ -42,72 +45,76 @@ const currentKeyAttributes = () => {
return keyAttributes;
};
-export const legacyGetInfo = (): Promise<LegacyInfo> =>
- withLegacyClient((client) => client.getInfo());
+export const legacyGetInfo = async (): Promise<LegacyInfo> =>
+ getInfo(await sessionInput());
-export const legacyPublicKey = (email: string) =>
- withLegacyClient((client) => client.publicKey(email));
+export const legacyPublicKey = async (email: string) =>
+ publicKey(await sessionInput(), email);
-export const legacyVerificationID = (email: string) =>
- withLegacyClient(async (client) => {
- const publicKey = await client.publicKey(email);
- return publicKey ? client.verificationID(publicKey) : undefined;
- });
+export const legacyVerificationID = async (email: string) => {
+ const key = await publicKey(await sessionInput(), email);
+ return key ? verificationID(key) : undefined;
+};
export const legacyAddContact = async (
email: string,
recoveryNoticeInDays?: number,
) => {
await getUserRecoveryKey();
- return withLegacyClient((client) =>
- client.addContact(email, currentKeyAttributes(), recoveryNoticeInDays),
+ return addContact(
+ await sessionInput(),
+ email,
+ currentKeyAttributes(),
+ recoveryNoticeInDays,
);
};
-export const legacyUpdateContact = (
+export const legacyUpdateContact = async (
userID: number,
emergencyContactID: number,
state: LegacyContactState,
-) =>
- withLegacyClient((client) =>
- client.updateContact(userID, emergencyContactID, state),
- );
+) => updateContact(await sessionInput(), userID, emergencyContactID, state);
-export const legacyUpdateRecoveryNotice = (
+export const legacyUpdateRecoveryNotice = async (
emergencyContactID: number,
recoveryNoticeInDays: number,
) =>
- withLegacyClient((client) =>
- client.updateRecoveryNotice(emergencyContactID, recoveryNoticeInDays),
+ updateRecoveryNotice(
+ await sessionInput(),
+ emergencyContactID,
+ recoveryNoticeInDays,
);
-export const legacyStartRecovery = (
+export const legacyStartRecovery = async (
userID: number,
emergencyContactID: number,
-) =>
- withLegacyClient((client) =>
- client.startRecovery(userID, emergencyContactID),
- );
+) => startRecovery(await sessionInput(), userID, emergencyContactID);
-export const legacyStopRecovery = (
+export const legacyStopRecovery = async (
recoveryID: string,
userID: number,
emergencyContactID: number,
-) =>
- withLegacyClient((client) =>
- client.stopRecovery(recoveryID, userID, emergencyContactID),
- );
+) => stopRecovery(await sessionInput(), recoveryID, userID, emergencyContactID);
-export const legacyRejectRecovery = (
+export const legacyRejectRecovery = async (
recoveryID: string,
userID: number,
emergencyContactID: number,
) =>
- withLegacyClient((client) =>
- client.rejectRecovery(recoveryID, userID, emergencyContactID),
+ rejectRecovery(
+ await sessionInput(),
+ recoveryID,
+ userID,
+ emergencyContactID,
);
-export const legacyChangePassword = (recoveryID: string, newPassword: string) =>
- withLegacyClient((client) =>
- client.changePassword(recoveryID, currentKeyAttributes(), newPassword),
+export const legacyChangePassword = async (
+ recoveryID: string,
+ newPassword: string,
+) =>
+ changePassword(
+ await sessionInput(),
+ recoveryID,
+ currentKeyAttributes(),
+ newPassword,
);
diff --git a/web/packages/wasm/core/package.json b/web/packages/wasm/core/package.json
index 59c8eebb62..1974ae1388 100644
--- a/web/packages/wasm/core/package.json
+++ b/web/packages/wasm/core/package.json
@@ -11,7 +11,7 @@
"module": "./pkg/ente_core_wasm.js",
"types": "./pkg/ente_core_wasm.d.ts",
"scripts": {
- "build": "wasm-pack build ../../../../rust/bindings/wasm/core --target bundler --out-dir ../../../../web/packages/wasm/core/pkg --no-pack",
+ "build": "wasm-pack build ../../../../rust/bindings/wasm/core-wasm --target bundler --out-dir ../../../../web/packages/wasm/core/pkg --no-pack",
"test": "vitest --run"
},
"devDependencies": {
diff --git a/web/packages/wasm/legacy/authenticated.ts b/web/packages/wasm/legacy/authenticated.ts
index 17e6773dee..d728b6b252 100644
--- a/web/packages/wasm/legacy/authenticated.ts
+++ b/web/packages/wasm/legacy/authenticated.ts
@@ -1,4 +1,4 @@
-export interface OpenLegacyInput {
+export interface SessionInput {
baseUrl: string;
authToken: string;
masterKeyB64: string;
@@ -65,86 +65,145 @@ interface LegacyInfo {
othersRecoverySession: LegacyRecoverySession[];
}
-export const openLegacy = async ({
- baseUrl,
- authToken,
- masterKeyB64,
- clientPackage,
- clientVersion,
-}: OpenLegacyInput) => {
- const client = (await import("./pkg/ente_legacy_wasm")).openLegacy(
+type Wasm = typeof import("./pkg/ente_legacy_wasm");
+type Session = ReturnType<Wasm["openSession"]>;
+
+const withSession = async <T>(
+ {
+ baseUrl,
+ authToken,
+ masterKeyB64,
+ clientPackage,
+ clientVersion,
+ }: SessionInput,
+ operation: (wasm: Wasm, session: Session) => Promise<T>,
+) => {
+ const wasm = await import("./pkg/ente_legacy_wasm");
+ const session = wasm.openSession(
baseUrl,
authToken,
masterKeyB64,
clientPackage,
clientVersion,
);
+ try {
+ return await operation(wasm, session);
+ } finally {
+ session.free();
+ }
+};
+
+export const getInfo = (input: SessionInput) =>
+ withSession(
+ input,
+ (wasm, session) => wasm.legacyGetInfo(session) as Promise<LegacyInfo>,
+ );
- return {
- close: () => client.free(),
- getInfo: () => client.getInfo() as Promise<LegacyInfo>,
- publicKey: (email: string) => client.publicKey(email),
- verificationID: (publicKeyB64: string) =>
- client.verificationID(publicKeyB64),
- addContact: (
- email: string,
- currentUserKeyAttributes: KeyAttributes,
- recoveryNoticeInDays?: number,
- ) =>
- client.addContact(
- email,
- currentUserKeyAttributes,
- recoveryNoticeInDays,
- ),
- updateContact: (
- userID: number,
- emergencyContactID: number,
- state: LegacyContactState,
- ) =>
- client.updateContact(
- BigInt(userID),
- BigInt(emergencyContactID),
- state,
- ),
- updateRecoveryNotice: (
- emergencyContactID: number,
- recoveryNoticeInDays: number,
- ) =>
- client.updateRecoveryNotice(
- BigInt(emergencyContactID),
- recoveryNoticeInDays,
- ),
- startRecovery: (userID: number, emergencyContactID: number) =>
- client.startRecovery(BigInt(userID), BigInt(emergencyContactID)),
- stopRecovery: (
- recoveryID: string,
- userID: number,
- emergencyContactID: number,
- ) =>
- client.stopRecovery(
- recoveryID,
- BigInt(userID),
- BigInt(emergencyContactID),
- ),
- rejectRecovery: (
- recoveryID: string,
- userID: number,
- emergencyContactID: number,
- ) =>
- client.rejectRecovery(
- recoveryID,
- BigInt(userID),
- BigInt(emergencyContactID),
- ),
- changePassword: (
- recoveryID: string,
- currentUserKeyAttributes: KeyAttributes,
- newPassword: string,
- ) =>
- client.changePassword(
- recoveryID,
- currentUserKeyAttributes,
- newPassword,
- ),
- };
+export const publicKey = (input: SessionInput, email: string) =>
+ withSession(input, (wasm, session) => wasm.legacyPublicKey(session, email));
+
+export const verificationID = async (publicKeyB64: string) => {
+ const wasm = await import("./pkg/ente_legacy_wasm");
+ return wasm.legacyVerificationID(publicKeyB64);
};
+
+export const addContact = (
+ input: SessionInput,
+ email: string,
+ currentUserKeyAttributes: KeyAttributes,
+ recoveryNoticeInDays?: number,
+) =>
+ withSession(input, (wasm, session) =>
+ wasm.legacyAddContact(
+ session,
+ email,
+ currentUserKeyAttributes,
+ recoveryNoticeInDays,
+ ),
+ );
+
+export const updateContact = (
+ input: SessionInput,
+ userID: number,
+ emergencyContactID: number,
+ state: LegacyContactState,
+) =>
+ withSession(input, (wasm, session) =>
+ wasm.legacyUpdateContact(
+ session,
+ BigInt(userID),
+ BigInt(emergencyContactID),
+ state,
+ ),
+ );
+
+export const updateRecoveryNotice = (
+ input: SessionInput,
+ emergencyContactID: number,
+ recoveryNoticeInDays: number,
+) =>
+ withSession(input, (wasm, session) =>
+ wasm.legacyUpdateRecoveryNotice(
+ session,
+ BigInt(emergencyContactID),
+ recoveryNoticeInDays,
+ ),
+ );
+
+export const startRecovery = (
+ input: SessionInput,
+ userID: number,
+ emergencyContactID: number,
+) =>
+ withSession(input, (wasm, session) =>
+ wasm.legacyStartRecovery(
+ session,
+ BigInt(userID),
+ BigInt(emergencyContactID),
+ ),
+ );
+
+export const stopRecovery = (
+ input: SessionInput,
+ recoveryID: string,
+ userID: number,
+ emergencyContactID: number,
+) =>
+ withSession(input, (wasm, session) =>
+ wasm.legacyStopRecovery(
+ session,
+ recoveryID,
+ BigInt(userID),
+ BigInt(emergencyContactID),
+ ),
+ );
+
+export const rejectRecovery = (
+ input: SessionInput,
+ recoveryID: string,
+ userID: number,
+ emergencyContactID: number,
+) =>
+ withSession(input, (wasm, session) =>
+ wasm.legacyRejectRecovery(
+ session,
+ recoveryID,
+ BigInt(userID),
+ BigInt(emergencyContactID),
+ ),
+ );
+
+export const changePassword = (
+ input: SessionInput,
+ recoveryID: string,
+ currentUserKeyAttributes: KeyAttributes,
+ newPassword: string,
+) =>
+ withSession(input, (wasm, session) =>
+ wasm.legacyChangePassword(
+ session,
+ recoveryID,
+ currentUserKeyAttributes,
+ newPassword,
+ ),
+ );
diff --git a/web/packages/wasm/locker/index.ts b/web/packages/wasm/locker/index.ts
index d2c9a227cd..db24c45cfd 100644
--- a/web/packages/wasm/locker/index.ts
+++ b/web/packages/wasm/locker/index.ts
@@ -32,20 +32,24 @@ export const openContacts = async ({
clientPackage,
clientVersion,
}: OpenContactsInput) => {
- const client = (await import("./pkg/ente_locker_wasm")).openContacts(
+ const wasm = await import("./pkg/ente_locker_wasm");
+ const session = wasm.openSession(
baseUrl,
authToken,
- BigInt(userId),
masterKeyB64,
- cachedWrappedRootContactKey?.encryptedKey,
- cachedWrappedRootContactKey?.header,
clientPackage,
clientVersion,
);
+ const client = wasm.openContacts(
+ session,
+ BigInt(userId),
+ cachedWrappedRootContactKey?.encryptedKey,
+ cachedWrappedRootContactKey?.header,
+ );
return {
updateAuthToken: (authToken: string) =>
- client.updateAuthToken(authToken),
+ session.updateAuthToken(authToken),
currentWrappedRootContactKey: () =>
client.currentWrappedRootContactKey() as
| WrappedRootContactKey
diff --git a/web/packages/wasm/photos/index.ts b/web/packages/wasm/photos/index.ts
index a1b12ae325..552e15f3e1 100644
--- a/web/packages/wasm/photos/index.ts
+++ b/web/packages/wasm/photos/index.ts
@@ -32,20 +32,24 @@ export const openContacts = async ({
clientPackage,
clientVersion,
}: OpenContactsInput) => {
- const client = (await import("./pkg/ente_photos_wasm")).openContacts(
+ const wasm = await import("./pkg/ente_photos_wasm");
+ const session = wasm.openSession(
baseUrl,
authToken,
- BigInt(userId),
masterKeyB64,
- cachedWrappedRootContactKey?.encryptedKey,
- cachedWrappedRootContactKey?.header,
clientPackage,
clientVersion,
);
+ const client = wasm.openContacts(
+ session,
+ BigInt(userId),
+ cachedWrappedRootContactKey?.encryptedKey,
+ cachedWrappedRootContactKey?.header,
+ );
return {
updateAuthToken: (authToken: string) =>
- client.updateAuthToken(authToken),
+ session.updateAuthToken(authToken),
currentWrappedRootContactKey: () =>
client.currentWrappedRootContactKey() as
| WrappedRootContactKey