Skip to content

armgit / ente

Public Imported from GitHub
0

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

Use consumer-oriented errors across bindings

Manav Rathid37de424e640
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.kt
index 4ca359c9ba..92e3a78d38 100644
--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.kt
+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/knowledge/KnowledgeStore.kt
@@ -236,9 +236,7 @@ class KnowledgeStore(
is AssetDownloadException.Http ->
"The knowledge pack is currently unavailable. Please try again later."
is AssetDownloadException.Validation,
- is AssetDownloadException.SizeMismatch,
- is AssetDownloadException.Protocol,
- is AssetDownloadException.InvalidTarget ->
+ is AssetDownloadException.InvalidDownload ->
"The knowledge pack couldn't be verified. Please try again."
is AssetDownloadException.Io ->
"Couldn't save the knowledge pack. Please try again."
diff --git a/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift b/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift
index 39c8fe997f..6e9170d1d5 100644
--- a/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift
+++ b/apple/apps/ensu/Ensu/Services/KnowledgeStore.swift
@@ -213,9 +213,7 @@ final class KnowledgeStore: ObservableObject {
case AssetDownloadError.Http:
return "The knowledge pack is currently unavailable. Please try again later."
case AssetDownloadError.Validation,
- AssetDownloadError.SizeMismatch,
- AssetDownloadError.Protocol,
- AssetDownloadError.InvalidTarget:
+ AssetDownloadError.InvalidDownload:
return "The knowledge pack couldn't be verified. Please try again."
case AssetDownloadError.Io:
return "Couldn't save the knowledge pack. Please try again."
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index 4e7fd51440..0900106012 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -91,7 +91,7 @@ Future<dynamic> isolateFunction(
try {
result = await analyzeImageRust(args);
} on rust_ml.RustMlError_CorruptModel catch (e) {
- return RustCorruptModelException(e.field0);
+ return RustCorruptModelException(e.message);
}
return result.toJsonString();
@@ -162,7 +162,7 @@ Future<dynamic> isolateFunction(
),
);
} on rust_ml.RustMlError_CorruptModel catch (e) {
- return RustCorruptModelException(e.field0);
+ return RustCorruptModelException(e.message);
}
return List<double>.from(result.embedding, growable: false);
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 2ce7b6e7a5..b462505380 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -1049,8 +1049,7 @@ String formatExpectedMlSkipReasonForLogs(Object error) {
}
bool _isRustImageIssue(Object error) {
- return error is rust_ml.RustMlError_Decode ||
- error is rust_ml.RustMlError_Image;
+ return error is rust_ml.RustMlError_InvalidImage;
}
bool _isRustCorruptModelIssue(Object error) {
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 862a0dc682..23d0ed8dce 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2433,7 +2433,10 @@ name = "ente-cast-wasm"
version = "0.0.0"
dependencies = [
"ente-cast",
+ "ente-core",
"ente-wasm-log",
+ "js-sys",
+ "thiserror 2.0.18",
"wasm-bindgen",
]
diff --git a/rust/bindings/frb/locker/src/api/document_scanner_api.rs b/rust/bindings/frb/locker/src/api/document_scanner_api.rs
index 9bdae52253..64b0bb18b4 100644
--- a/rust/bindings/frb/locker/src/api/document_scanner_api.rs
+++ b/rust/bindings/frb/locker/src/api/document_scanner_api.rs
@@ -59,19 +59,9 @@ pub struct RustScanResult {
pub processed_image: Vec<u8>,
}
-#[derive(Clone, Copy, Debug)]
-pub enum RustScanErrorKind {
- InvalidInput,
- ModelLoad,
- Codec,
- Pipeline,
- Internal,
-}
-
#[derive(Clone, Debug)]
-pub struct RustScanError {
- pub kind: RustScanErrorKind,
- pub message: String,
+pub enum RustScanError {
+ Other { message: String },
}
#[frb(opaque)]
@@ -100,8 +90,7 @@ impl ScannerSession {
rotation_degrees: i32,
) -> Result<Option<RustQuad>, RustScanError> {
catch_panic(|| {
- let row_stride = u32::try_from(row_stride).map_err(|_| RustScanError {
- kind: RustScanErrorKind::InvalidInput,
+ let row_stride = u32::try_from(row_stride).map_err(|_| RustScanError::Other {
message: format!("negative row stride {row_stride}"),
})?;
let quad =
@@ -159,8 +148,7 @@ impl ScannerSession {
fn catch_panic<T>(body: impl FnOnce() -> Result<T, RustScanError>) -> Result<T, RustScanError> {
catch_unwind(AssertUnwindSafe(body)).unwrap_or_else(|panic| {
- Err(RustScanError {
- kind: RustScanErrorKind::Internal,
+ Err(RustScanError::Other {
message: panic_message(&panic),
})
})
@@ -178,13 +166,9 @@ fn panic_message(panic: &Box<dyn Any + Send>) -> String {
impl From<scan::ScanError> for RustScanError {
fn from(value: scan::ScanError) -> Self {
- let (kind, message) = match value {
- scan::ScanError::InvalidInput(message) => (RustScanErrorKind::InvalidInput, message),
- scan::ScanError::ModelLoad(message) => (RustScanErrorKind::ModelLoad, message),
- scan::ScanError::Codec(message) => (RustScanErrorKind::Codec, message),
- scan::ScanError::Pipeline(message) => (RustScanErrorKind::Pipeline, message),
- };
- RustScanError { kind, message }
+ Self::Other {
+ message: value.to_string(),
+ }
}
}
diff --git a/rust/bindings/frb/photos/src/api/ml_indexing_api.rs b/rust/bindings/frb/photos/src/api/ml_indexing_api.rs
index 28eaf14388..b75d3024a9 100644
--- a/rust/bindings/frb/photos/src/api/ml_indexing_api.rs
+++ b/rust/bindings/frb/photos/src/api/ml_indexing_api.rs
@@ -26,14 +26,9 @@ pub struct AnalyzeImageRequest {
#[derive(Clone, Debug)]
pub enum RustMlError {
- InvalidRequest(String),
- Decode(String),
- Image(String),
- Preprocess(String),
- Ort(String),
- CorruptModel(String),
- Postprocess(String),
- Runtime(String),
+ InvalidImage { message: String },
+ CorruptModel { message: String },
+ Other { message: String },
}
#[derive(Clone, Debug)]
@@ -200,14 +195,13 @@ fn to_model_paths(paths: &RustModelPaths) -> ModelPaths {
impl From<MlError> for RustMlError {
fn from(value: MlError) -> Self {
match value {
- MlError::InvalidRequest(message) => RustMlError::InvalidRequest(message),
- MlError::Decode(message) => RustMlError::Decode(message),
- MlError::Image(message) => RustMlError::Image(message),
- MlError::Preprocess(message) => RustMlError::Preprocess(message),
- MlError::Ort(message) => RustMlError::Ort(message),
- MlError::CorruptModel(message) => RustMlError::CorruptModel(message),
- MlError::Postprocess(message) => RustMlError::Postprocess(message),
- MlError::Runtime(message) => RustMlError::Runtime(message),
+ MlError::Decode(message) | MlError::Image(message) => Self::InvalidImage { message },
+ MlError::CorruptModel(message) => Self::CorruptModel { message },
+ MlError::InvalidRequest(message)
+ | MlError::Preprocess(message)
+ | MlError::Ort(message)
+ | MlError::Postprocess(message)
+ | MlError::Runtime(message) => Self::Other { message },
}
}
}
diff --git a/rust/bindings/uniffi/cast/src/lib.rs b/rust/bindings/uniffi/cast/src/lib.rs
index 163cd62373..e3dbaa8cea 100644
--- a/rust/bindings/uniffi/cast/src/lib.rs
+++ b/rust/bindings/uniffi/cast/src/lib.rs
@@ -9,19 +9,23 @@ use thiserror::Error;
#[derive(Debug, Error, uniffi::Error)]
pub enum CastCryptoError {
- #[error("{0}")]
- Message(String),
+ #[error("{detail}")]
+ Other { detail: String },
}
impl From<crypto::Error> for CastCryptoError {
fn from(err: crypto::Error) -> Self {
- CastCryptoError::Message(ente_core::error::chain(&err))
+ CastCryptoError::Other {
+ detail: ente_core::error::chain(&err),
+ }
}
}
impl From<ente_cast::Error> for CastCryptoError {
fn from(err: ente_cast::Error) -> Self {
- CastCryptoError::Message(ente_core::error::chain(&err))
+ CastCryptoError::Other {
+ detail: ente_core::error::chain(&err),
+ }
}
}
diff --git a/rust/bindings/uniffi/ensu/src/assets.rs b/rust/bindings/uniffi/ensu/src/assets.rs
index fe9f6c4510..a0998de1f3 100644
--- a/rust/bindings/uniffi/ensu/src/assets.rs
+++ b/rust/bindings/uniffi/ensu/src/assets.rs
@@ -25,12 +25,8 @@ pub enum AssetDownloadError {
Http { status: u16 },
#[error("network: {detail}")]
Network { detail: String },
- #[error("size mismatch: expected {expected} bytes, got {actual}")]
- SizeMismatch { expected: u64, actual: u64 },
- #[error("range protocol violation: {detail}")]
- Protocol { detail: String },
- #[error("invalid download target: {detail}")]
- InvalidTarget { detail: String },
+ #[error("{detail}")]
+ InvalidDownload { detail: String },
#[error("not enough storage space")]
StorageFull,
#[error("{detail}")]
@@ -46,11 +42,15 @@ impl From<download::Error> for AssetDownloadError {
download::Error::Validation(detail) => Self::Validation { detail },
download::Error::Http(status) => Self::Http { status },
download::Error::Network(detail) => Self::Network { detail },
- download::Error::SizeMismatch { expected, actual } => {
- Self::SizeMismatch { expected, actual }
- }
- download::Error::Protocol(detail) => Self::Protocol { detail },
- download::Error::InvalidTarget(detail) => Self::InvalidTarget { detail },
+ download::Error::SizeMismatch { expected, actual } => Self::InvalidDownload {
+ detail: format!("size mismatch: expected {expected} bytes, got {actual}"),
+ },
+ download::Error::Protocol(detail) => Self::InvalidDownload {
+ detail: format!("range protocol violation: {detail}"),
+ },
+ download::Error::InvalidTarget(detail) => Self::InvalidDownload {
+ detail: format!("invalid download target: {detail}"),
+ },
download::Error::StorageFull => Self::StorageFull,
download::Error::Io(error) => Self::Io {
detail: error.to_string(),
diff --git a/rust/bindings/uniffi/ensu/src/image.rs b/rust/bindings/uniffi/ensu/src/image.rs
index 8f635010ad..da52ed94c3 100644
--- a/rust/bindings/uniffi/ensu/src/image.rs
+++ b/rust/bindings/uniffi/ensu/src/image.rs
@@ -3,11 +3,13 @@ use thiserror::Error;
#[derive(Debug, Error, uniffi::Error)]
pub enum ImageError {
- #[error("{0}")]
- Message(String),
+ #[error("{detail}")]
+ Other { detail: String },
}
#[uniffi::export]
pub fn compress_attachment_image(data: Vec<u8>) -> Result<Vec<u8>, ImageError> {
- image::compress_attachment_image(&data).map_err(|e| ImageError::Message(e.to_string()))
+ image::compress_attachment_image(&data).map_err(|error| ImageError::Other {
+ detail: ente_core::error::chain(&error),
+ })
}
diff --git a/rust/bindings/uniffi/ensu/src/llm.rs b/rust/bindings/uniffi/ensu/src/llm.rs
index ebe8d9cf2e..cb10e30742 100644
--- a/rust/bindings/uniffi/ensu/src/llm.rs
+++ b/rust/bindings/uniffi/ensu/src/llm.rs
@@ -7,33 +7,16 @@ use thiserror::Error;
pub enum LlmError {
#[error("Generation cancelled")]
Cancelled,
- #[error("Generation panicked")]
- Panicked,
- #[error("{detail}")]
- InvalidInput { detail: String },
- #[error("{what} not found at {path}")]
- NotFound { what: String, path: String },
- #[error("{detail}")]
- Unsupported { detail: String },
#[error("Prompt length {tokens} exceeds context size {context_size}")]
PromptTooLong { tokens: u64, context_size: u32 },
- #[error("{op}: {detail}")]
- Llama { op: String, detail: String },
+ #[error("{detail}")]
+ Other { detail: String },
}
impl From<llm::Error> for LlmError {
fn from(value: llm::Error) -> Self {
match value {
llm::Error::Cancelled => Self::Cancelled,
- llm::Error::Panicked => Self::Panicked,
- llm::Error::InvalidInput(message) => Self::InvalidInput { detail: message },
- llm::Error::NotFound { what, path } => Self::NotFound {
- what: what.to_string(),
- path,
- },
- llm::Error::Unsupported(message) => Self::Unsupported {
- detail: message.to_string(),
- },
llm::Error::PromptTooLong {
tokens,
context_size,
@@ -41,9 +24,8 @@ impl From<llm::Error> for LlmError {
tokens: tokens as u64,
context_size,
},
- llm::Error::Llama { op, message } => Self::Llama {
- op: op.to_string(),
- detail: message,
+ error => Self::Other {
+ detail: ente_core::error::chain(&error),
},
}
}
diff --git a/rust/bindings/uniffi/ensu/src/retrieval.rs b/rust/bindings/uniffi/ensu/src/retrieval.rs
index 8d2145d0ba..06a9a4242a 100644
--- a/rust/bindings/uniffi/ensu/src/retrieval.rs
+++ b/rust/bindings/uniffi/ensu/src/retrieval.rs
@@ -7,30 +7,14 @@ use crate::assets::{Asset, AssetStoreCore};
#[derive(Debug, Error, uniffi::Error)]
pub enum KnowledgeRetrievalError {
- #[error("invalid retrieval input: {detail}")]
- InvalidInput { detail: String },
- #[error("invalid knowledge pack: {detail}")]
- InvalidPack { detail: String },
- #[error("knowledge pack I/O failed: {detail}")]
- Io { detail: String },
- #[error("knowledge pack JSON failed: {detail}")]
- Json { detail: String },
- #[error("knowledge pack metadata decompression failed: {detail}")]
- Zstd { detail: String },
+ #[error("{detail}")]
+ Other { detail: String },
}
impl From<core::RetrievalError> for KnowledgeRetrievalError {
fn from(value: core::RetrievalError) -> Self {
- match value {
- core::RetrievalError::InvalidInput(detail) => Self::InvalidInput { detail },
- core::RetrievalError::InvalidPack(detail) => Self::InvalidPack { detail },
- core::RetrievalError::Io(error) => Self::Io {
- detail: error.to_string(),
- },
- core::RetrievalError::Json(error) => Self::Json {
- detail: error.to_string(),
- },
- core::RetrievalError::Zstd(detail) => Self::Zstd { detail },
+ Self::Other {
+ detail: ente_core::error::chain(&value),
}
}
}
@@ -38,10 +22,8 @@ impl From<core::RetrievalError> for KnowledgeRetrievalError {
fn knowledge_dataset(
stable_id: &str,
) -> Result<ente_ensu::config::KnowledgeDatasetConfig, KnowledgeRetrievalError> {
- ente_ensu::config::knowledge_dataset(stable_id).ok_or_else(|| {
- KnowledgeRetrievalError::InvalidInput {
- detail: format!("unknown knowledge dataset ID: {stable_id}"),
- }
+ ente_ensu::config::knowledge_dataset(stable_id).ok_or_else(|| KnowledgeRetrievalError::Other {
+ detail: format!("invalid retrieval input: unknown knowledge dataset ID: {stable_id}"),
})
}
@@ -163,8 +145,8 @@ pub fn reconcile_knowledge_pack(
) -> Result<KnowledgeReconciliation, KnowledgeRetrievalError> {
let dataset = knowledge_dataset(&stable_id)?;
let pack_root = core::knowledge_pack_root(store.store(), &dataset).map_err(|error| {
- KnowledgeRetrievalError::InvalidInput {
- detail: error.to_string(),
+ KnowledgeRetrievalError::Other {
+ detail: format!("invalid retrieval input: {error}"),
}
})?;
core::reconcile_knowledge_pack(pack_root, &dataset)
@@ -180,8 +162,8 @@ pub fn cleanup_obsolete_knowledge_pack_revisions(
) -> Result<(), KnowledgeRetrievalError> {
let dataset = knowledge_dataset(&stable_id)?;
let pack_root = core::knowledge_pack_root(store.store(), &dataset).map_err(|error| {
- KnowledgeRetrievalError::InvalidInput {
- detail: error.to_string(),
+ KnowledgeRetrievalError::Other {
+ detail: format!("invalid retrieval input: {error}"),
}
})?;
core::cleanup_obsolete_knowledge_pack_revisions(pack_root, &dataset, &active_identity)
@@ -295,7 +277,7 @@ pub fn knowledge_pack_asset(stable_id: String) -> Result<Arc<Asset>, KnowledgeRe
let dataset = knowledge_dataset(&stable_id)?;
core::knowledge_asset(&dataset)
.map(Asset::new)
- .map_err(|error| KnowledgeRetrievalError::InvalidInput {
- detail: error.to_string(),
+ .map_err(|error| KnowledgeRetrievalError::Other {
+ detail: format!("invalid retrieval input: {error}"),
})
}
diff --git a/rust/bindings/wasm/cast/Cargo.toml b/rust/bindings/wasm/cast/Cargo.toml
index 5ea2c9ba61..28fffb4e33 100644
--- a/rust/bindings/wasm/cast/Cargo.toml
+++ b/rust/bindings/wasm/cast/Cargo.toml
@@ -7,5 +7,8 @@ crate-type = ["cdylib"]
[dependencies]
ente-cast.workspace = true
+ente-core.workspace = true
ente-wasm-log.workspace = true
+js-sys.workspace = true
+thiserror.workspace = true
wasm-bindgen.workspace = true
diff --git a/rust/bindings/wasm/cast/src/lib.rs b/rust/bindings/wasm/cast/src/lib.rs
index f2f631e41e..ba05541c6d 100644
--- a/rust/bindings/wasm/cast/src/lib.rs
+++ b/rust/bindings/wasm/cast/src/lib.rs
@@ -3,6 +3,32 @@ use wasm_bindgen::prelude::*;
use ente_wasm_log as _;
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error(transparent)]
+ Cast(#[from] ente_cast::Error),
+}
+
+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()
+ }
+}
+
#[wasm_bindgen]
pub struct CastReceiver {
inner: ReceiverCredentials,
@@ -34,7 +60,7 @@ impl CastReceiver {
}
#[wasm_bindgen(js_name = openPayload)]
- pub fn open_payload(&self, encrypted_payload: &str) -> Result<CastPayload, JsError> {
+ pub fn open_payload(&self, encrypted_payload: &str) -> Result<CastPayload, Error> {
Ok(self.inner.open_payload(encrypted_payload)?.into())
}
}
@@ -98,7 +124,7 @@ pub fn prepare_payload(
pq_public_key: Option<String>,
collection_id: i64,
collection_key: &str,
-) -> Result<PreparedCastPayload, JsError> {
+) -> Result<PreparedCastPayload, Error> {
Ok(ente_cast::prepare_payload(
public_key,
pq_public_key.as_deref(),
diff --git a/rust/bindings/wasm/core/src/auth.rs b/rust/bindings/wasm/core/src/auth.rs
index 82677be90a..816aa102bf 100644
--- a/rust/bindings/wasm/core/src/auth.rs
+++ b/rust/bindings/wasm/core/src/auth.rs
@@ -2,60 +2,32 @@ use ente_accounts::auth;
use ente_core::b64;
use wasm_bindgen::prelude::*;
-#[wasm_bindgen]
-pub struct AccountsError {
- code: String,
- message: String,
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error(transparent)]
+ Accounts(#[from] ente_accounts::Error),
}
-#[wasm_bindgen]
-impl AccountsError {
- #[wasm_bindgen(getter)]
- pub fn code(&self) -> String {
- self.code.clone()
+impl Error {
+ fn name(&self) -> Option<&'static str> {
+ match self {
+ Self::Accounts(ente_accounts::Error::InsufficientMemory) => Some("insufficient_memory"),
+ _ => None,
+ }
}
- #[wasm_bindgen(getter)]
- pub fn message(&self) -> String {
- self.message.clone()
+ fn message(&self) -> String {
+ ente_core::error::chain(self)
}
}
-impl From<ente_accounts::Error> for AccountsError {
- fn from(e: ente_accounts::Error) -> Self {
- use ente_accounts::Error as E;
-
- let code = match &e {
- E::Http(_) => "http",
- E::Serialization(_) => "serialization",
- E::Crypto(_) => "crypto",
- E::Decode(_) => "decode",
- E::IncorrectPassword => "incorrect_password",
- E::IncorrectRecoveryKey => "incorrect_recovery_key",
- E::InvalidKeyAttributes => "invalid_key_attributes",
- E::InsufficientMemory => "insufficient_memory",
- E::MissingField(_) => "missing_field",
- E::InvalidKey(_) => "invalid_key",
- E::Srp(_) => "srp",
- E::InvalidInput(_) => "invalid_input",
- E::IncorrectEmailVerificationCode => "incorrect_email_verification_code",
- E::EmailVerificationCodeExpired => "email_verification_code_expired",
- E::EmailVerificationRateLimited => "email_verification_rate_limited",
- E::IncorrectTotp => "incorrect_totp",
- E::TotpRateLimited => "totp_rate_limited",
- E::SecondFactorSessionExpired => "second_factor_session_expired",
- E::SessionInvalid => "session_invalid",
- E::MissingKeyAttributes => "missing_key_attributes",
- E::AccountAlreadyExists => "account_already_exists",
- E::Protocol(_) => "protocol",
- E::Ui(_) => "ui",
- }
- .to_string();
-
- Self {
- code,
- message: ente_core::error::chain(&e),
+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()
}
}
@@ -121,13 +93,13 @@ pub fn auth_derive_kek(
kek_salt_b64: &str,
mem_limit: u32,
ops_limit: u32,
-) -> Result<String, AccountsError> {
+) -> Result<String, Error> {
let kek = auth::derive_kek(password, kek_salt_b64, mem_limit, ops_limit)?;
Ok(b64::encode(&kek))
}
#[wasm_bindgen]
-pub fn auth_generate_sensitive_kek(password: &str) -> Result<GeneratedKek, AccountsError> {
+pub fn auth_generate_sensitive_kek(password: &str) -> Result<GeneratedKek, Error> {
let generated = auth::generate_sensitive_kek(password)?;
Ok(GeneratedKek {
key: b64::encode(&generated.key),
@@ -138,7 +110,7 @@ pub fn auth_generate_sensitive_kek(password: &str) -> Result<GeneratedKek, Accou
}
#[wasm_bindgen]
-pub fn auth_generate_interactive_kek(password: &str) -> Result<GeneratedKek, AccountsError> {
+pub fn auth_generate_interactive_kek(password: &str) -> Result<GeneratedKek, Error> {
let generated = auth::generate_interactive_kek(password)?;
Ok(GeneratedKek {
key: b64::encode(&generated.key),
@@ -152,11 +124,9 @@ pub fn auth_generate_interactive_kek(password: &str) -> Result<GeneratedKek, Acc
pub fn auth_generate_srp_setup(
kek_b64: &str,
srp_user_id: &str,
-) -> Result<GeneratedSrpSetup, AccountsError> {
- let kek = b64::decode(kek_b64).map_err(|e| AccountsError {
- code: "decode".to_string(),
- message: format!("kek: {}", e),
- })?;
+) -> Result<GeneratedSrpSetup, Error> {
+ let kek =
+ b64::decode(kek_b64).map_err(|e| ente_accounts::Error::Decode(format!("kek: {e}")))?;
let generated = auth::generate_srp_setup(&kek, srp_user_id)?;
Ok(GeneratedSrpSetup {
@@ -167,13 +137,13 @@ pub fn auth_generate_srp_setup(
}
#[wasm_bindgen]
-pub fn auth_recovery_key_from_mnemonic_or_hex(input: &str) -> Result<String, AccountsError> {
+pub fn auth_recovery_key_from_mnemonic_or_hex(input: &str) -> Result<String, Error> {
let recovery_key = auth::recovery_key_from_mnemonic_or_hex(input)?;
Ok(b64::encode(&recovery_key))
}
#[wasm_bindgen]
-pub fn auth_recovery_key_to_mnemonic(recovery_key_b64: &str) -> Result<String, AccountsError> {
+pub fn auth_recovery_key_to_mnemonic(recovery_key_b64: &str) -> Result<String, Error> {
auth::recovery_key_to_mnemonic(recovery_key_b64).map_err(Into::into)
}
@@ -189,7 +159,7 @@ impl SrpSession {
srp_user_id: &str,
srp_salt_b64: &str,
login_key_b64: &str,
- ) -> Result<SrpSession, AccountsError> {
+ ) -> Result<SrpSession, Error> {
let srp_salt = b64::decode(srp_salt_b64)
.map_err(|e| ente_accounts::Error::Decode(format!("srp_salt: {}", e)))?;
let login_key = b64::decode(login_key_b64)
@@ -203,14 +173,14 @@ impl SrpSession {
b64::encode(&self.inner.public_a())
}
- pub fn compute_m1(&mut self, srp_b_b64: &str) -> Result<String, AccountsError> {
+ pub fn compute_m1(&mut self, srp_b_b64: &str) -> Result<String, Error> {
let srp_b = b64::decode(srp_b_b64)
.map_err(|e| ente_accounts::Error::Decode(format!("srpB: {}", e)))?;
let m1 = self.inner.compute_m1(&srp_b)?;
Ok(b64::encode(&m1))
}
- pub fn verify_m2(&self, srp_m2_b64: &str) -> Result<(), AccountsError> {
+ pub fn verify_m2(&self, srp_m2_b64: &str) -> Result<(), Error> {
let srp_m2 = b64::decode(srp_m2_b64)
.map_err(|e| ente_accounts::Error::Decode(format!("srpM2: {}", e)))?;
self.inner.verify_m2(&srp_m2)?;
diff --git a/web/packages/accounts/services/crypto/kdf.ts b/web/packages/accounts/services/crypto/kdf.ts
index 84b942ea56..7529bab10f 100644
--- a/web/packages/accounts/services/crypto/kdf.ts
+++ b/web/packages/accounts/services/crypto/kdf.ts
@@ -16,32 +16,13 @@ interface WasmDerivedKey {
}
const normalizeDerivedKeyError = (error: unknown): Error => {
- const code =
- typeof error === "object" && error && "code" in error
- ? String(error.code)
- : undefined;
if (error instanceof Error) {
- if (
- code === "insufficient_memory" ||
- error.message.includes("insufficient memory") ||
- error.message.includes("KeyDerivationFailed") ||
- error.message.includes("key_derivation_failed")
- ) {
+ if (error.name === "insufficient_memory") {
return new Error(deriveKeyInsufficientMemoryErrorMessage);
}
return error;
}
- return new Error(deriveKeyInsufficientMemoryErrorMessage);
-};
-
-// wasm-bindgen errors are not Errors and cannot cross Comlink's structured clone.
-const toPlainError = (error: unknown): Error => {
- if (error instanceof Error) return error;
- const message =
- typeof error === "object" && error && "message" in error
- ? error.message
- : error;
- return new Error(String(message));
+ return new Error(String(error));
};
export const deriveKey = async (
@@ -50,12 +31,8 @@ export const deriveKey = async (
opsLimit: number,
memLimit: number,
) => {
- try {
- const wasm = await import("ente-core-wasm");
- return wasm.auth_derive_kek(password, saltB64, memLimit, opsLimit);
- } catch (error) {
- throw toPlainError(error);
- }
+ const wasm = await import("ente-core-wasm");
+ return wasm.auth_derive_kek(password, saltB64, memLimit, opsLimit);
};
const normalizeDerivedKey = (result: WasmDerivedKey): DerivedKey => ({