π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add accounts-rs
Neeraj Gupta6b5599f77038
diff --git a/mobile/packages/rust/rust/Cargo.lock b/mobile/packages/rust/rust/Cargo.lockindex 3ece55720e..34d6addc71 100644--- a/mobile/packages/rust/rust/Cargo.lock+++ b/mobile/packages/rust/rust/Cargo.lock@@ -133,6 +133,26 @@ version = "1.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"+[[package]]+name = "bip39"+version = "2.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"+dependencies = [+ "bitcoin_hashes",+ "serde",+ "unicode-normalization",+]++[[package]]+name = "bitcoin_hashes"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26ec84b80c482df901772e931a9a681e26a1b9ee2302edeff23cb30328745c8b"+dependencies = [+ "hex-conservative",+]+[[package]]name = "bitflags"version = "2.10.0"@@ -423,6 +443,7 @@ version = "0.0.1"dependencies = ["argon2","base64",+ "bip39","blake2b_simd","crypto_secretstream","getrandom 0.2.16",@@ -708,6 +729,15 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "hex-conservative"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f"+dependencies = [+ "arrayvec",+]+[[package]]name = "http"version = "1.4.0"@@ -1835,6 +1865,15 @@ version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"+[[package]]+name = "unicode-normalization"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"+dependencies = [+ "tinyvec",+]+[[package]]name = "universal-hash"version = "0.5.1"diff --git a/rust/apps/ensu/src-tauri/Cargo.lock b/rust/apps/ensu/src-tauri/Cargo.lockindex 87546ea5a1..d8da0afb11 100644--- a/rust/apps/ensu/src-tauri/Cargo.lock+++ b/rust/apps/ensu/src-tauri/Cargo.lock@@ -154,6 +154,26 @@ dependencies = ["syn 2.0.114",]+[[package]]+name = "bip39"+version = "2.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"+dependencies = [+ "bitcoin_hashes",+ "serde",+ "unicode-normalization",+]++[[package]]+name = "bitcoin_hashes"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26ec84b80c482df901772e931a9a681e26a1b9ee2302edeff23cb30328745c8b"+dependencies = [+ "hex-conservative",+]+[[package]]name = "bitflags"version = "1.3.2"@@ -735,7 +755,7 @@ dependencies = ["libc","option-ext","redox_users",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -914,6 +934,7 @@ version = "0.0.1"dependencies = ["argon2","base64 0.22.1",+ "bip39","blake2b_simd","crypto_secretstream","getrandom 0.2.17",@@ -977,7 +998,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -1538,6 +1559,15 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "hex-conservative"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f"+dependencies = [+ "arrayvec",+]+[[package]]name = "hkdf"version = "0.12.4"@@ -2639,7 +2669,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"dependencies = ["libc",- "windows-sys 0.45.0",+ "windows-sys 0.61.2",][[package]]@@ -4855,6 +4885,15 @@ version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "537dd038a89878be9b64dd4bd1b260315c1bb94f4d784956b81e27a088d9a09e"+[[package]]+name = "unicode-normalization"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"+dependencies = [+ "tinyvec",+]+[[package]]name = "unicode-segmentation"version = "1.12.0"@@ -5214,7 +5253,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]diff --git a/rust/apps/ensu/src-tauri/src/commands.rs b/rust/apps/ensu/src-tauri/src/commands.rsindex cc36057e8f..1d7c1060e7 100644--- a/rust/apps/ensu/src-tauri/src/commands.rs+++ b/rust/apps/ensu/src-tauri/src/commands.rs@@ -120,6 +120,7 @@ impl From<core_auth::AuthError> for ApiError {E::IncorrectPassword => "incorrect_password",E::IncorrectRecoveryKey => "incorrect_recovery_key",E::InvalidKeyAttributes => "invalid_key_attributes",+ E::InsufficientMemory => "insufficient_memory",E::MissingField(_) => "missing_field",E::Crypto(_) => "crypto",E::Decode(_) => "decode",diff --git a/rust/cli/Cargo.lock b/rust/cli/Cargo.lockindex 79fbe65f70..884ebd1017 100644--- a/rust/cli/Cargo.lock+++ b/rust/cli/Cargo.lock@@ -221,6 +221,26 @@ version = "1.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba"+[[package]]+name = "bip39"+version = "2.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"+dependencies = [+ "bitcoin_hashes",+ "serde",+ "unicode-normalization",+]++[[package]]+name = "bitcoin_hashes"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26ec84b80c482df901772e931a9a681e26a1b9ee2302edeff23cb30328745c8b"+dependencies = [+ "hex-conservative",+]+[[package]]name = "bitflags"version = "2.9.2"@@ -708,6 +728,7 @@ version = "0.0.1"dependencies = ["argon2","base64",+ "bip39","blake2b_simd","crypto_secretstream","getrandom 0.2.16",@@ -1117,6 +1138,15 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "hex-conservative"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f"+dependencies = [+ "arrayvec",+]+[[package]]name = "hkdf"version = "0.12.4"diff --git a/rust/cli/src/models/error.rs b/rust/cli/src/models/error.rsindex 29de383d3e..cad3a05f8c 100644--- a/rust/cli/src/models/error.rs+++ b/rust/cli/src/models/error.rs@@ -66,6 +66,7 @@ impl From<AuthError> for Error {Error::AuthenticationFailed("Incorrect recovery key".to_string())}AuthError::InvalidKeyAttributes => Error::Crypto(err.to_string()),+ AuthError::InsufficientMemory => Error::Crypto(err.to_string()),AuthError::MissingField(field) => Error::Crypto(format!("Missing field: {field}")),AuthError::Crypto(source) => source.into(),AuthError::Decode(msg) => Error::Crypto(msg),diff --git a/rust/core/Cargo.lock b/rust/core/Cargo.lockindex 38a5c4a4d2..ff942c9e2b 100644--- a/rust/core/Cargo.lock+++ b/rust/core/Cargo.lock@@ -60,6 +60,26 @@ version = "1.8.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0e050f626429857a27ddccb31e0aca21356bfa709c04041aefddac081a8f068a"+[[package]]+name = "bip39"+version = "2.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"+dependencies = [+ "bitcoin_hashes",+ "serde",+ "unicode-normalization",+]++[[package]]+name = "bitcoin_hashes"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26ec84b80c482df901772e931a9a681e26a1b9ee2302edeff23cb30328745c8b"+dependencies = [+ "hex-conservative",+]+[[package]]name = "bitflags"version = "2.10.0"@@ -289,6 +309,7 @@ version = "0.0.1"dependencies = ["argon2","base64",+ "bip39","blake2b_simd","chacha20","crypto_secretstream",@@ -450,6 +471,15 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "hex-conservative"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f"+dependencies = [+ "arrayvec",+]+[[package]]name = "http"version = "1.4.0"@@ -1515,6 +1545,15 @@ version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"+[[package]]+name = "unicode-normalization"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"+dependencies = [+ "tinyvec",+]+[[package]]name = "universal-hash"version = "0.5.1"diff --git a/rust/core/Cargo.toml b/rust/core/Cargo.tomlindex 480a1ea9db..6ba0a1206f 100644--- a/rust/core/Cargo.toml+++ b/rust/core/Cargo.toml@@ -34,6 +34,7 @@ getrandom = { version = "0.2", features = ["js"] }# Common dependenciesbase64 = "0.22"hex = "0.4"+bip39 = { version = "2", default-features = false, features = ["std"] }zeroize = { version = "1.8", features = ["derive"] }[dev-dependencies]diff --git a/rust/core/src/auth/api.rs b/rust/core/src/auth/api.rsindex 090d5556af..e33f96aeb3 100644--- a/rust/core/src/auth/api.rs+++ b/rust/core/src/auth/api.rs@@ -3,12 +3,18 @@//! This module provides the main entry points that CLI/GUI applications should use//! for authentication flows. It wraps the lower-level crypto operations.+#[cfg(feature = "srp")]+use crate::crypto::keys;use crate::crypto::{self, argon, kdf, sealed, secretbox};use super::{AuthError, KeyAttributes, Result, SrpAttributes};#[cfg(feature = "srp")]use super::srp::SrpSession;+#[cfg(feature = "srp")]+use sha2::Sha256;+#[cfg(feature = "srp")]+use srp::{client::SrpClient as SrpClientInner, groups::G_4096};/// Credentials derived from password for SRP authentication.#[derive(Debug)]@@ -30,6 +36,31 @@ pub struct DecryptedSecrets {pub token: Vec<u8>,}+/// A derived key-encryption-key and the parameters used to derive it.+#[derive(Debug)]+pub struct GeneratedKek {+ /// Derived KEK bytes.+ pub key: Vec<u8>,+ /// Salt used for Argon2 derivation.+ pub salt: Vec<u8>,+ /// Argon2 memory limit in bytes.+ pub mem_limit: u32,+ /// Argon2 operations limit.+ pub ops_limit: u32,+}++/// Attributes needed to register or update SRP for a user.+#[cfg(feature = "srp")]+#[derive(Debug)]+pub struct GeneratedSrpSetup {+ /// SRP salt bytes.+ pub srp_salt: Vec<u8>,+ /// SRP verifier bytes.+ pub srp_verifier: Vec<u8>,+ /// Derived 16-byte login sub-key bytes.+ pub login_sub_key: Vec<u8>,+}+/// Derive SRP credentials from password.////// This is the first step in the SRP login flow. Call this after password entry@@ -79,6 +110,47 @@ pub fn derive_kek(argon::derive_key(password, &salt, mem_limit, ops_limit).map_err(AuthError::from)}+/// Generate a KEK using the current sensitive web policy.+pub fn generate_sensitive_kek(password: &str) -> Result<GeneratedKek> {+ let derived = argon::derive_sensitive_key(password).map_err(|e| match e {+ crypto::CryptoError::InvalidKeyDerivationParams(_) => AuthError::Crypto(e),+ _ => AuthError::InsufficientMemory,+ })?;++ Ok(GeneratedKek {+ key: derived.key,+ salt: derived.salt,+ mem_limit: derived.mem_limit,+ ops_limit: derived.ops_limit,+ })+}++/// Generate a KEK using the current interactive web policy.+pub fn generate_interactive_kek(password: &str) -> Result<GeneratedKek> {+ let derived = argon::derive_interactive_key(password)?;+ Ok(GeneratedKek {+ key: derived.key,+ salt: derived.salt,+ mem_limit: derived.mem_limit,+ ops_limit: derived.ops_limit,+ })+}++/// Generate the SRP setup payload for a given KEK and SRP user ID.+#[cfg(feature = "srp")]+pub fn generate_srp_setup(kek: &[u8], srp_user_id: &str) -> Result<GeneratedSrpSetup> {+ let login_sub_key = kdf::derive_login_key(kek)?;+ let srp_salt = keys::generate_salt();+ let client = SrpClientInner::<Sha256>::new(&G_4096);+ let srp_verifier = client.compute_verifier(srp_user_id.as_bytes(), &login_sub_key, &srp_salt);++ Ok(GeneratedSrpSetup {+ srp_salt,+ srp_verifier,+ login_sub_key,+ })+}+/// Decrypt only the master key and secret key.////// Use this when you only need access to the decrypted keys (e.g. when the@@ -261,6 +333,49 @@ mod tests {assert!(matches!(result, Err(AuthError::IncorrectPassword)));}+ #[test]+ fn test_generate_sensitive_kek() {+ crate::crypto::init().unwrap();++ let generated = generate_sensitive_kek("test_password").unwrap();++ assert_eq!(generated.key.len(), 32);+ assert_eq!(generated.salt.len(), 16);+ assert!(generated.mem_limit > 0);+ assert!(generated.ops_limit > 0);+ }++ #[test]+ fn test_generate_interactive_kek() {+ crate::crypto::init().unwrap();++ let generated = generate_interactive_kek("test_password").unwrap();++ assert_eq!(generated.key.len(), 32);+ assert_eq!(generated.salt.len(), 16);+ assert_eq!(+ generated.mem_limit,+ crate::crypto::argon::MEMLIMIT_INTERACTIVE+ );+ assert_eq!(+ generated.ops_limit,+ crate::crypto::argon::OPSLIMIT_INTERACTIVE+ );+ }++ #[cfg(feature = "srp")]+ #[test]+ fn test_generate_srp_setup() {+ crate::crypto::init().unwrap();++ let generated = generate_sensitive_kek("test_password").unwrap();+ let srp_setup = generate_srp_setup(&generated.key, "test-user-id").unwrap();++ assert_eq!(srp_setup.srp_salt.len(), 16);+ assert_eq!(srp_setup.login_sub_key.len(), 16);+ assert!(!srp_setup.srp_verifier.is_empty());+ }+#[cfg(feature = "srp")]#[test]fn test_start_srp_session() {diff --git a/rust/core/src/auth/mod.rs b/rust/core/src/auth/mod.rsindex e69e55ec77..2b8222dbb5 100644--- a/rust/core/src/auth/mod.rs+++ b/rust/core/src/auth/mod.rs@@ -62,8 +62,15 @@ impl SrpSession {}// High-level API (recommended for applications)-pub use api::{DecryptedSecrets, SrpCredentials};-pub use api::{decrypt_keys_only, decrypt_secrets, derive_kek, derive_srp_credentials};+#[cfg(feature = "srp")]+pub use api::GeneratedSrpSetup;+#[cfg(feature = "srp")]+pub use api::generate_srp_setup;+pub use api::{DecryptedSecrets, GeneratedKek, SrpCredentials};+pub use api::{+ decrypt_keys_only, decrypt_secrets, derive_kek, derive_srp_credentials,+ generate_interactive_kek, generate_sensitive_kek,+};// Key generation (for signup)pub use key_gen::{@@ -79,7 +86,9 @@ pub use login::{};// Recovery-pub use recovery::{get_recovery_key, recover_with_key};+pub use recovery::{+ get_recovery_key, recover_with_key, recovery_key_from_mnemonic_or_hex, recovery_key_to_mnemonic,+};// Typespub use types::{diff --git a/rust/core/src/auth/recovery.rs b/rust/core/src/auth/recovery.rsindex f8463bcec9..a2cdb50710 100644--- a/rust/core/src/auth/recovery.rs+++ b/rust/core/src/auth/recovery.rs@@ -1,5 +1,7 @@//! Account recovery using recovery key.+use bip39::{Language, Mnemonic};+use crate::crypto::{self, sealed, secretbox};use super::{AuthError, KeyAttributes, LoginResult, Result};@@ -92,6 +94,51 @@ pub fn get_recovery_key(master_key: &[u8], attributes: &KeyAttributes) -> ResultOk(crypto::encode_hex(&recovery_key))}+/// Convert a user-provided recovery key mnemonic or hex string into raw bytes.+///+/// The mnemonic form must be a 24-word English BIP-39 phrase. The legacy hex+/// form is still accepted for compatibility.+pub fn recovery_key_from_mnemonic_or_hex(recovery_key_mnemonic_or_hex: &str) -> Result<Vec<u8>> {+ let trimmed_input = recovery_key_mnemonic_or_hex+ .split_whitespace()+ .map(str::trim)+ .filter(|part| !part.is_empty())+ .collect::<Vec<_>>()+ .join(" ");++ let recovery_key = if trimmed_input.contains(' ') {+ if trimmed_input.split(' ').count() != 24 {+ return Err(AuthError::IncorrectRecoveryKey);+ }++ let mnemonic = Mnemonic::parse_in_normalized(Language::English, &trimmed_input)+ .map_err(|_| AuthError::IncorrectRecoveryKey)?;+ mnemonic.to_entropy()+ } else {+ crypto::decode_hex(&trimmed_input).map_err(|_| AuthError::IncorrectRecoveryKey)?+ };++ if recovery_key.len() != 32 {+ return Err(AuthError::IncorrectRecoveryKey);+ }++ Ok(recovery_key)+}++/// Convert a base64-encoded recovery key into its 24-word English mnemonic.+pub fn recovery_key_to_mnemonic(recovery_key_b64: &str) -> Result<String> {+ let recovery_key = crypto::decode_b64(recovery_key_b64)+ .map_err(|e| AuthError::Decode(format!("recovery_key: {}", e)))?;++ if recovery_key.len() != 32 {+ return Err(AuthError::IncorrectRecoveryKey);+ }++ Mnemonic::from_entropy_in(Language::English, &recovery_key)+ .map(|mnemonic| mnemonic.to_string())+ .map_err(|e| AuthError::InvalidKey(format!("recovery_key: {}", e)))+}+#[cfg(test)]mod tests {use super::*;@@ -150,4 +197,34 @@ mod tests {let recovered = get_recovery_key(&master_key, &gen_result.key_attributes).unwrap();assert_eq!(recovered, gen_result.private_key_attributes.recovery_key);}++ #[test]+ fn test_recovery_key_mnemonic_roundtrip() {+ crypto::init().unwrap();++ let gen_result = generate_test_keys("password");+ let master_key = crypto::decode_b64(&gen_result.private_key_attributes.key).unwrap();+ let recovery_key_hex = get_recovery_key(&master_key, &gen_result.key_attributes).unwrap();+ let recovery_key_b64 = crypto::encode_b64(&crypto::decode_hex(&recovery_key_hex).unwrap());++ let mnemonic = recovery_key_to_mnemonic(&recovery_key_b64).unwrap();+ let decoded = recovery_key_from_mnemonic_or_hex(&mnemonic).unwrap();++ assert_eq!(decoded, crypto::decode_hex(&recovery_key_hex).unwrap());+ }++ #[test]+ fn test_recovery_key_from_hex_accepts_legacy_format() {+ crypto::init().unwrap();++ let gen_result = generate_test_keys("password");+ let decoded =+ recovery_key_from_mnemonic_or_hex(&gen_result.private_key_attributes.recovery_key)+ .unwrap();++ assert_eq!(+ decoded,+ crypto::decode_hex(&gen_result.private_key_attributes.recovery_key).unwrap()+ );+ }}diff --git a/rust/core/src/auth/types.rs b/rust/core/src/auth/types.rsindex 2d631445be..7fb4d655d1 100644--- a/rust/core/src/auth/types.rs+++ b/rust/core/src/auth/types.rs@@ -112,6 +112,10 @@ pub enum AuthError {#[error("Invalid key attributes")]InvalidKeyAttributes,+ /// The device could not derive a sensitive key with the required policy.+ #[error("Failed to derive key (insufficient memory)")]+ InsufficientMemory,+/// A required field is missing from the key attributes.#[error("Missing required field: {0}")]MissingField(&'static str),diff --git a/rust/uniffi/core/Cargo.lock b/rust/uniffi/core/Cargo.lockindex f6d1af8be7..3577d03e94 100644--- a/rust/uniffi/core/Cargo.lock+++ b/rust/uniffi/core/Cargo.lock@@ -117,6 +117,26 @@ dependencies = ["serde",]+[[package]]+name = "bip39"+version = "2.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"+dependencies = [+ "bitcoin_hashes",+ "serde",+ "unicode-normalization",+]++[[package]]+name = "bitcoin_hashes"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26ec84b80c482df901772e931a9a681e26a1b9ee2302edeff23cb30328745c8b"+dependencies = [+ "hex-conservative",+]+[[package]]name = "bitflags"version = "2.10.0"@@ -389,6 +409,7 @@ version = "0.0.1"dependencies = ["argon2","base64",+ "bip39","blake2b_simd","crypto_secretstream","getrandom 0.2.17",@@ -597,6 +618,15 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "hex-conservative"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f"+dependencies = [+ "arrayvec",+]+[[package]]name = "http"version = "1.4.0"@@ -1825,6 +1855,15 @@ version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"+[[package]]+name = "unicode-normalization"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"+dependencies = [+ "tinyvec",+]+[[package]]name = "uniffi"version = "0.31.0"diff --git a/web/packages/accounts-rs/README.md b/web/packages/accounts-rs/README.mdnew file mode 100644index 0000000000..98dcd4554d--- /dev/null+++ b/web/packages/accounts-rs/README.md@@ -0,0 +1,15 @@+## ente-accounts-rs++A package for sharing the pages involved in the signup/login flow.++Currently this is used by the photos and auth apps.++> [!NOTE]+>+> This is distinct from the accounts _app_, which currently acts as a broker for+> passkeys.++### Packaging++This (internal) package exports a React TypeScript library. We rely on the+importing project to transpile and bundle it.diff --git a/web/packages/accounts-rs/components/CodeBlock.tsx b/web/packages/accounts-rs/components/CodeBlock.tsxnew file mode 100644index 0000000000..63fd696064--- /dev/null+++ b/web/packages/accounts-rs/components/CodeBlock.tsx@@ -0,0 +1,77 @@+import ContentCopyIcon from "@mui/icons-material/ContentCopy";+import DoneIcon from "@mui/icons-material/Done";+import { Box, IconButton, Tooltip, Typography } from "@mui/material";+import { CenteredRow } from "ente-base/components/containers";+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";+import { useClipboardCopy } from "ente-base/components/utils/hooks";+import { t } from "i18next";+import React from "react";++interface CodeBlockProps {+ /**+ * The code (an arbitrary string) to show.+ *+ * If not present, then an activity indicator will be shown.+ */+ code: string | undefined;+}++/**+ * A component that shows a "code" (e.g. the user's recovery key, or a 2FA setup+ * code), alongwith a button to copy it.+ */+export const CodeBlock: React.FC<CodeBlockProps> = ({ code }) => {+ if (!code) {+ return (+ <CenteredRow sx={{ minHeight: "80px" }}>+ <ActivityIndicator />+ </CenteredRow>+ );+ }++ return (+ <Box+ sx={{+ position: "relative",+ bgcolor: "accent.dark",+ borderRadius: 1,+ }}+ >+ <Typography+ sx={{+ padding: "16px 44px 16px 16px",+ wordBreak: "break-word",+ color: "accent.contrastText",+ // Increase the line height from the body default.+ lineHeight: 1.5,+ }}+ >+ {code}+ </Typography>+ <Box sx={{ position: "absolute", top: 0, right: 0, mt: 1 }}>+ <CopyButton code={code} />+ </Box>+ </Box>+ );+};++interface CopyButtonProps {+ /**+ * The code to copy when the button is clicked.+ */+ code: string;+}++export const CopyButton: React.FC<CopyButtonProps> = ({ code }) => {+ const [copied, handleClick] = useClipboardCopy(code);++ const Icon = copied ? DoneIcon : ContentCopyIcon;++ return (+ <Tooltip arrow open={copied} title={t("copied")}>+ <IconButton onClick={handleClick}>+ <Icon sx={{ color: "accent.contrastText" }} fontSize="small" />+ </IconButton>+ </Tooltip>+ );+};diff --git a/web/packages/accounts-rs/components/LoginComponents.tsx b/web/packages/accounts-rs/components/LoginComponents.tsxnew file mode 100644index 0000000000..e56ba359f2--- /dev/null+++ b/web/packages/accounts-rs/components/LoginComponents.tsx@@ -0,0 +1,209 @@+import { CircularProgress, Stack, Typography, styled } from "@mui/material";+import { sessionExpiredDialogAttributes } from "ente-accounts-rs/components/utils/dialog";+import {+ checkPasskeyVerificationStatus,+ passkeySessionExpiredErrorMessage,+ saveCredentialsAndNavigateTo,+} from "ente-accounts-rs/services/passkey";+import { LinkButton } from "ente-base/components/LinkButton";+import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { genericErrorDialogAttributes } from "ente-base/components/utils/dialog";+import log from "ente-base/log";+import { customAPIHost } from "ente-base/origins";+import { t } from "i18next";+import { useRouter } from "next/router";+import React, { useEffect, useState } from "react";+import {+ AccountsPageContents,+ AccountsPageFooter,+} from "./layouts/centered-paper";++interface HeaderCaptionProps {+ /**+ * If specified, then a caption to display below the title (which is+ * expected to be passed as the `children`).+ *+ * The components which use the {@link HeaderCaptionProps} that they'll have+ * the same height irrespective of whether or not the caption is provided.+ * This allows us to use this component to get a similar look across various+ * pages in the login flow (some of which have a caption, some which not).+ */+ caption?: string;+}++export const PasswordHeader: React.FC<HeaderCaptionProps> = (props) => (+ <AccountsPageTitleWithCaption {...props}>+ {t("password")}+ </AccountsPageTitleWithCaption>+);++const PasskeyHeader: React.FC<HeaderCaptionProps> = (props) => (+ <AccountsPageTitleWithCaption {...props}>+ {t("passkey")}+ </AccountsPageTitleWithCaption>+);++export const AccountsPageTitleWithCaption: React.FC<+ React.PropsWithChildren<HeaderCaptionProps>+> = ({ caption, children }) => {+ return (+ <Header_>+ <Typography variant="h3">{children}</Typography>+ <Typography sx={{ color: "text.faint" }}>+ {caption ?? ""}+ </Typography>+ </Header_>+ );+};++const Header_ = styled("div")`+ margin-block-end: 24px;+ display: flex;+ flex-direction: column;+ gap: 8px;+`;++export const AccountsPageFooterWithHost: React.FC<React.PropsWithChildren> = ({+ children,+}) => {+ const [host, setHost] = useState<string | undefined>();++ useEffect(() => void customAPIHost().then(setHost), []);++ return (+ <Stack sx={{ gap: 3 }}>+ <AccountsPageFooter>{children}</AccountsPageFooter>+ {host && (+ <Typography+ variant="small"+ sx={{ mx: "4px", color: "text.faint" }}+ >+ {host}+ </Typography>+ )}+ </Stack>+ );+};++interface VerifyingPasskeyProps {+ /** ID of the current passkey verification session. */+ passkeySessionID: string;+ /** The email of the user whose passkey we're verifying. */+ email: string | undefined;+ /** Called when the user wants to redirect again. */+ onRetry: () => void;+ /** Perform the (possibly app specific) logout sequence. */+ logout: () => void;+ showMiniDialog: (attrs: MiniDialogAttributes) => void;+}++export const VerifyingPasskey: React.FC<VerifyingPasskeyProps> = ({+ passkeySessionID,+ email,+ onRetry,+ logout,+ showMiniDialog,+}) => {+ type VerificationStatus = "waiting" | "checking" | "pending";+ const [verificationStatus, setVerificationStatus] =+ useState<VerificationStatus>("waiting");++ const router = useRouter();++ const handleRetry = () => {+ setVerificationStatus("waiting");+ onRetry();+ };++ const handleCheckStatus = async () => {+ setVerificationStatus("checking");+ try {+ const response =+ await checkPasskeyVerificationStatus(passkeySessionID);+ if (!response) setVerificationStatus("pending");+ else void router.push(await saveCredentialsAndNavigateTo(response));+ } catch (e) {+ log.error("Passkey verification status check failed", e);+ showMiniDialog(+ e instanceof Error &&+ e.message == passkeySessionExpiredErrorMessage+ ? sessionExpiredDialogAttributes(logout)+ : genericErrorDialogAttributes(),+ );+ setVerificationStatus("waiting");+ }+ };++ const handleRecover = () => {+ void router.push("/passkeys/recover");+ };++ return (+ <AccountsPageContents>+ <PasskeyHeader caption={email} />++ <VerifyingPasskeyMiddle>+ <VerifyingPasskeyStatus>+ {verificationStatus == "checking" ? (+ <Typography>+ <CircularProgress color="accent" size="1.5em" />+ </Typography>+ ) : (+ <Typography sx={{ color: "text.muted" }}>+ {verificationStatus == "waiting"+ ? t("waiting_for_verification")+ : t("verification_still_pending")}+ </Typography>+ )}+ </VerifyingPasskeyStatus>++ <ButtonStack>+ <FocusVisibleButton+ onClick={handleRetry}+ fullWidth+ color="secondary"+ >+ {t("try_again")}+ </FocusVisibleButton>++ <FocusVisibleButton+ onClick={handleCheckStatus}+ fullWidth+ color="accent"+ >+ {t("check_status")}+ </FocusVisibleButton>+ </ButtonStack>+ </VerifyingPasskeyMiddle>++ <AccountsPageFooterWithHost>+ <LinkButton onClick={handleRecover}>+ {t("recover_account")}+ </LinkButton>+ <LinkButton onClick={logout}>{t("change_email")}</LinkButton>+ </AccountsPageFooterWithHost>+ </AccountsPageContents>+ );+};++const VerifyingPasskeyMiddle = styled("div")`+ display: flex;+ flex-direction: column;++ padding-block: 1rem;+ gap: 4rem;+`;++const VerifyingPasskeyStatus = styled("div")`+ text-align: center;+ /* Size of the CircularProgress (+ some margin) so that there is no layout+ shift when it is shown */+ min-height: 2em;+`;++const ButtonStack = styled("div")`+ display: flex;+ flex-direction: column;+ gap: 1rem;+`;diff --git a/web/packages/accounts-rs/components/LoginContents.tsx b/web/packages/accounts-rs/components/LoginContents.tsxnew file mode 100644index 0000000000..64f803a8d9--- /dev/null+++ b/web/packages/accounts-rs/components/LoginContents.tsx@@ -0,0 +1,173 @@+import { Input, Stack, TextField, Typography } from "@mui/material";+import { AccountsPageFooter } from "ente-accounts-rs/components/layouts/centered-paper";+import {+ replaceSavedLocalUser,+ saveSRPAttributes,+} from "ente-accounts-rs/services/accounts-db";+import { getSRPAttributes } from "ente-accounts-rs/services/srp";+import { sendOTT } from "ente-accounts-rs/services/user";+import { appName } from "ente-base/app";+import { LinkButton } from "ente-base/components/LinkButton";+import { LoadingButton } from "ente-base/components/mui/LoadingButton";+import { HTTPError } from "ente-base/http";+import log from "ente-base/log";+import { JOIN_ALBUM_CONTEXT_KEY } from "ente-new/albums/services/join-album";+import { useFormik } from "formik";+import { t } from "i18next";+import { useRouter } from "next/router";+import React, { useCallback, useEffect, useState } from "react";+import { z } from "zod";+import { AccountsPageTitleWithCaption } from "./LoginComponents";++interface LoginContentsProps {+ /**+ * Reactive value of {@link customAPIHost}.+ */+ host: string | undefined;+ /**+ * Called when the user clicks the signup option instead.+ */+ onSignUp: () => void;+}++/**+ * A contents of the "login" form.+ *+ * It is used both on the "/login" page, and as the embedded login form on the+ * "/" page where the user can toggle between the signup and login forms inline.+ */+export const LoginContents: React.FC<LoginContentsProps> = ({+ onSignUp,+ host,+}) => {+ const router = useRouter();+ const [isJoinAlbumContext, setIsJoinAlbumContext] = useState(false);+ const isEnsu = appName === "ensu";++ useEffect(() => {+ // Check if we're in a join album context+ const joinAlbumContext = sessionStorage.getItem(JOIN_ALBUM_CONTEXT_KEY);+ setIsJoinAlbumContext(!!joinAlbumContext);+ }, []);++ const loginUser = useCallback(+ async (email: string, setFieldError: (message: string) => void) => {+ const srpAttributes = await getSRPAttributes(email);+ if (!srpAttributes || srpAttributes.isEmailMFAEnabled) {+ try {+ await sendOTT(email, "login");+ } catch (e) {+ if (e instanceof HTTPError && e.res.status === 404) {+ let errorCode: string | undefined;+ try {+ errorCode = z+ .object({ code: z.string() })+ .parse(await e.res.json()).code;+ } catch (parseErr) {+ log.warn(+ "Ignoring error when parsing error payload",+ parseErr,+ );+ }+ if (errorCode === "USER_NOT_REGISTERED") {+ setFieldError(t("email_not_registered"));+ return;+ }+ if (errorCode === "USER_SIGNUP_INCOMPLETE") {+ setFieldError(+ t("account_setup_incomplete_create_account"),+ );+ return;+ }+ }+ throw e;+ }+ replaceSavedLocalUser({ email });+ void router.push("/verify");+ } else {+ replaceSavedLocalUser({ email });+ saveSRPAttributes(srpAttributes);+ void router.push("/credentials");+ }+ },+ [router],+ );++ const formik = useFormik({+ initialValues: { email: "" },+ onSubmit: async ({ email }, { setFieldError }) => {+ const setEmailFieldError = (message: string) =>+ setFieldError("email", message);++ if (!email) {+ setEmailFieldError(t("required"));+ return;+ }++ if (!z.email().safeParse(email).success) {+ setEmailFieldError(t("invalid_email_error"));+ return;+ }++ try {+ await loginUser(email, setEmailFieldError);+ } catch (e) {+ log.error("Failed to login", e);+ setEmailFieldError(t("generic_error"));+ }+ },+ });++ return (+ <>+ <AccountsPageTitleWithCaption>+ {isJoinAlbumContext ? t("login_to_join_album") : t("login")}+ </AccountsPageTitleWithCaption>+ <form onSubmit={formik.handleSubmit}>+ <TextField+ name="email"+ value={formik.values.email}+ onChange={formik.handleChange}+ type="email"+ autoComplete="username"+ label={t("enter_email")}+ fullWidth+ autoFocus+ margin="normal"+ disabled={formik.isSubmitting}+ error={!!formik.errors.email}+ // See: [Note: Use space as default TextField helperText]+ helperText={formik.errors.email ?? " "}+ />+ <Input sx={{ display: "none" }} type="password" value="" />+ <LoadingButton+ fullWidth+ type="submit"+ loading={formik.isSubmitting}+ color="accent"+ >+ {t("login")}+ </LoadingButton>+ </form>+ <AccountsPageFooter>+ <Stack sx={{ gap: 3, textAlign: "center" }}>+ {isEnsu ? (+ <LinkButton onClick={() => void router.push("/chat")}>+ {t("cancel")}+ </LinkButton>+ ) : (+ <LinkButton onClick={onSignUp}>+ {t("no_account")}+ </LinkButton>+ )}+ <Typography+ variant="mini"+ sx={{ color: "text.faint", minHeight: "16px" }}+ >+ {host ?? "" /* prevent layout shift with a minHeight */}+ </Typography>+ </Stack>+ </AccountsPageFooter>+ </>+ );+};diff --git a/web/packages/accounts-rs/components/NewPasswordForm.tsx b/web/packages/accounts-rs/components/NewPasswordForm.tsxnew file mode 100644index 0000000000..2d6b23f86a--- /dev/null+++ b/web/packages/accounts-rs/components/NewPasswordForm.tsx@@ -0,0 +1,163 @@+import { Input, TextField, Typography } from "@mui/material";+import { isWeakPassword } from "ente-accounts-rs/utils/password";+import { LoadingButton } from "ente-base/components/mui/LoadingButton";+import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";+import log from "ente-base/log";+import { useFormik } from "formik";+import { t } from "i18next";+import { useCallback, useState } from "react";+import { Trans } from "react-i18next";+import { PasswordStrengthHint } from "./PasswordStrength";++export interface NewPasswordFormProps {+ /**+ * The email of the user whose password we are setting.+ *+ * This is used to show a hidden input field of type email (and the provided+ * value) to aid password managers to detect and save the new password,+ * associating it with the user's email.+ */+ userEmail: string;+ /**+ * The title of the form's submit button.+ */+ submitButtonTitle: string;+ /**+ * Submission handler. A callback invoked when the submit button is pressed.+ *+ * @param password The new password entered by the user. The form will first+ * check that both of the passwords entered by the user match, and that the+ * password is not too weak.+ *+ * @param setPasswordsFieldError A function that can be called to show an+ * error message below the password fields.+ */+ onSubmit: (+ password: string,+ setPasswordsFieldError: (message: string) => void,+ ) => Promise<void>;+}++/**+ * A form showing two password input fields, a password strength indicator, and+ * a submit button.+ *+ * This form can be used both for the initial setup of the password, and for+ * later changing it.+ */+export const NewPasswordForm: React.FC<NewPasswordFormProps> = ({+ userEmail,+ submitButtonTitle,+ onSubmit,+}) => {+ const [showPassword, setShowPassword] = useState(false);++ const handleToggleShowHidePassword = useCallback(+ () => setShowPassword((show) => !show),+ [],+ );++ const formik = useFormik({+ initialValues: { password: "", confirmPassword: "" },+ onSubmit: async ({ password, confirmPassword }, { setFieldError }) => {+ const setPasswordsFieldError = (message: string) =>+ setFieldError("confirmPassword", message);++ if (!confirmPassword) {+ setPasswordsFieldError(t("required"));+ return;+ }++ if (password != confirmPassword) {+ setPasswordsFieldError(t("password_mismatch_error"));+ return;+ }++ try {+ await onSubmit(password, setPasswordsFieldError);+ } catch (e) {+ log.error("Could not set password", e);+ setPasswordsFieldError(t("generic_error"));+ }+ },+ });++ return (+ <form onSubmit={formik.handleSubmit}>+ <Typography variant="small" sx={{ mb: 2, color: "text.muted" }}>+ {t("pick_password_hint")}+ </Typography>++ <Input+ sx={{ display: "none" }}+ name="email"+ type="email"+ autoComplete="username"+ value={userEmail}+ />+ <TextField+ name="password"+ autoComplete="new-password"+ type={showPassword ? "text" : "password"}+ label={t("password")}+ value={formik.values.password}+ onChange={formik.handleChange}+ disabled={formik.isSubmitting}+ fullWidth+ autoFocus+ slotProps={{+ input: {+ endAdornment: (+ <ShowHidePasswordInputAdornment+ showPassword={showPassword}+ onToggle={handleToggleShowHidePassword}+ />+ ),+ },+ }}+ />+ <TextField+ name="confirmPassword"+ autoComplete="new-password"+ type="password"+ label={t("confirm_password")}+ value={formik.values.confirmPassword}+ onChange={formik.handleChange}+ error={!!formik.errors.confirmPassword}+ // See: [Note: Use space as default TextField helperText]+ helperText={formik.errors.confirmPassword ?? " "}+ disabled={formik.isSubmitting}+ fullWidth+ />+ <PasswordStrengthHint password={formik.values.password} />++ <Typography+ variant="small"+ sx={{ color: "text.muted", my: 2, mb: 4 }}+ >+ <Trans i18nKey={"pick_password_caution"} />+ </Typography>++ <LoadingButton+ color="accent"+ type="submit"+ loading={formik.isSubmitting}+ disabled={isWeakPassword(formik.values.password)}+ fullWidth+ >+ {submitButtonTitle}+ </LoadingButton>+ <Typography+ variant="small"+ sx={(theme) => ({+ textAlign: "center",+ mt: 1,+ color: "text.muted",+ minHeight: theme.typography.small.lineHeight,+ })}+ >+ {formik.isSubmitting ? t("key_generation_in_progress") : ""}+ </Typography>+ </form>+ );+};diff --git a/web/packages/accounts-rs/components/PasswordStrength.tsx b/web/packages/accounts-rs/components/PasswordStrength.tsxnew file mode 100644index 0000000000..5b106a9a05--- /dev/null+++ b/web/packages/accounts-rs/components/PasswordStrength.tsx@@ -0,0 +1,44 @@+import { Typography, useTheme } from "@mui/material";+import { t } from "i18next";+import React, { useMemo } from "react";+import { estimatePasswordStrength } from "../utils/password";++interface PasswordStrengthHintProps {+ password: string;+}++export const PasswordStrengthHint: React.FC<PasswordStrengthHintProps> = ({+ password,+}) => {+ const passwordStrength = useMemo(+ () => estimatePasswordStrength(password),+ [password],+ );++ const theme = useTheme();+ const color =+ passwordStrength == "weak"+ ? theme.vars.palette.critical.main+ : passwordStrength == "moderate"+ ? theme.vars.palette.warning.main+ : theme.vars.palette.accent.main;++ return (+ <Typography+ variant="small"+ sx={{+ mt: "8px",+ mx: "2px",+ alignSelf: "flex-start",+ whiteSpace: "pre",+ color: "var(--et-color)",+ }}+ style={{ "--et-color": color } as React.CSSProperties}+ >+ {password+ ? t("password_strength", { context: passwordStrength })+ : /* empty space + white-space: pre to prevent layout shift. */+ " "}+ </Typography>+ );+};diff --git a/web/packages/accounts-rs/components/RecoveryKey.tsx b/web/packages/accounts-rs/components/RecoveryKey.tsxnew file mode 100644index 0000000000..16c8899736--- /dev/null+++ b/web/packages/accounts-rs/components/RecoveryKey.tsx@@ -0,0 +1,121 @@+import {+ Dialog,+ DialogActions,+ DialogContent,+ DialogTitle,+ Stack,+ Typography,+} from "@mui/material";+import { type MiniDialogAttributes } from "ente-base/components/MiniDialog";+import { SpacedRow } from "ente-base/components/containers";+import { DialogCloseIconButton } from "ente-base/components/mui/DialogCloseIconButton";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { errorDialogAttributes } from "ente-base/components/utils/dialog";+import { useIsSmallWidth } from "ente-base/components/utils/hooks";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import log from "ente-base/log";+import { saveStringAsFile } from "ente-base/utils/web";+import { t } from "i18next";+import { useCallback, useEffect, useState } from "react";+import {+ getUserRecoveryKey,+ recoveryKeyToMnemonic,+} from "../services/recovery-key";+import { CodeBlock } from "./CodeBlock";++type RecoveryKeyProps = ModalVisibilityProps & {+ showMiniDialog: (attributes: MiniDialogAttributes) => void;+};++export const RecoveryKey: React.FC<RecoveryKeyProps> = ({+ open,+ onClose,+ showMiniDialog,+}) => {+ const [recoveryKey, setRecoveryKey] = useState<string | undefined>();+ const fullScreen = useIsSmallWidth();++ const handleLoadError = useCallback(+ (e: unknown) => {+ log.error("Failed to generate recovery key", e);+ showMiniDialog(+ errorDialogAttributes(t("recovery_key_generation_failed")),+ );+ onClose();+ },+ [onClose, showMiniDialog],+ );++ useEffect(() => {+ if (!open) return;++ void getUserRecoveryKeyMnemonic()+ .then((key) => setRecoveryKey(key))+ .catch(handleLoadError);+ }, [open, handleLoadError]);++ const handleSaveClick = () => {+ saveRecoveryKeyMnemonicAsFile(recoveryKey!);+ onClose();+ };++ return (+ <Dialog+ fullScreen={fullScreen}+ open={open}+ onClose={onClose}+ // [Note: maxWidth "xs" on MUI dialogs]+ //+ // While logically the "xs" breakpoint doesn't make sense as a+ // maxWidth value (since as a breakpoint it's value is 0), in+ // practice MUI has hardcoded its value to a reasonable 444px.+ // https://github.com/mui/material-ui/issues/34646.+ maxWidth="xs"+ fullWidth+ >+ <SpacedRow sx={{ p: "8px 4px 8px 0" }}>+ <DialogTitle variant="h3">{t("recovery_key")}</DialogTitle>+ <DialogCloseIconButton {...{ onClose }} />+ </SpacedRow>+ <DialogContent>+ <Typography sx={{ mb: 3 }}>+ {t("recovery_key_description")}+ </Typography>+ <Stack+ sx={{+ border: "1px dashed",+ borderColor: "stroke.muted",+ borderRadius: 1,+ }}+ >+ <CodeBlock code={recoveryKey} />+ <Typography sx={{ m: 2 }}>+ {t("key_not_stored_note")}+ </Typography>+ </Stack>+ </DialogContent>+ <DialogActions>+ <FocusVisibleButton+ color="secondary"+ fullWidth+ onClick={onClose}+ >+ {t("do_this_later")}+ </FocusVisibleButton>+ <FocusVisibleButton+ color="accent"+ fullWidth+ onClick={handleSaveClick}+ >+ {t("save_key")}+ </FocusVisibleButton>+ </DialogActions>+ </Dialog>+ );+};++const getUserRecoveryKeyMnemonic = async () =>+ recoveryKeyToMnemonic(await getUserRecoveryKey());++const saveRecoveryKeyMnemonicAsFile = (key: string) =>+ saveStringAsFile(key, "ente-recovery-key.txt");diff --git a/web/packages/accounts-rs/components/SecondFactorChoice.tsx b/web/packages/accounts-rs/components/SecondFactorChoice.tsxnew file mode 100644index 0000000000..251db57014--- /dev/null+++ b/web/packages/accounts-rs/components/SecondFactorChoice.tsx@@ -0,0 +1,60 @@+import { Dialog, DialogContent, DialogTitle, Stack } from "@mui/material";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import type { ModalVisibilityProps } from "ente-base/components/utils/modal";+import { t } from "i18next";+import React from "react";++export type SecondFactorType = "totp" | "passkey";++type SecondFactorChoiceProps = ModalVisibilityProps & {+ /**+ * Callback invoked with the selected choice.+ *+ * The dialog will automatically be closed before this callback is invoked.+ */+ onSelect: (factor: SecondFactorType) => void;+};++/**+ * A {@link Dialog} that allow the user to choose which second factor they'd+ * like to verify during login.+ */+export const SecondFactorChoice: React.FC<SecondFactorChoiceProps> = ({+ open,+ onClose,+ onSelect,+}) => (+ <Dialog+ open={open}+ onClose={(_, reason) => {+ if (reason != "backdropClick") onClose();+ }}+ fullWidth+ slotProps={{ paper: { sx: { maxWidth: "360px", padding: "12px" } } }}+ >+ <DialogTitle>{t("two_factor")}</DialogTitle>+ <DialogContent>+ <Stack sx={{ gap: "12px" }}>+ <FocusVisibleButton+ color="accent"+ onClick={() => {+ onClose();+ onSelect("totp");+ }}+ >+ {t("totp_login")}+ </FocusVisibleButton>++ <FocusVisibleButton+ color="accent"+ onClick={() => {+ onClose();+ onSelect("passkey");+ }}+ >+ {t("passkey_login")}+ </FocusVisibleButton>+ </Stack>+ </DialogContent>+ </Dialog>+);diff --git a/web/packages/accounts-rs/components/SignUpContents.tsx b/web/packages/accounts-rs/components/SignUpContents.tsxnew file mode 100644index 0000000000..6163655888--- /dev/null+++ b/web/packages/accounts-rs/components/SignUpContents.tsx@@ -0,0 +1,346 @@+import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";+import {+ Checkbox,+ Divider,+ FormControlLabel,+ FormGroup,+ IconButton,+ InputAdornment,+ InputLabel,+ Link,+ Stack,+ TextField,+ Tooltip,+ Typography,+} from "@mui/material";+import {+ replaceSavedLocalUser,+ saveJustSignedUp,+ saveOriginalKeyAttributes,+ stashReferralSource,+ stashSRPSetupAttributes,+} from "ente-accounts-rs/services/accounts-db";+import { generateSRPSetupAttributes } from "ente-accounts-rs/services/srp";+import {+ generateAndSaveInteractiveKeyAttributes,+ generateKeysAndAttributes,+ sendOTT,+ type GenerateKeysAndAttributesResult,+} from "ente-accounts-rs/services/user";+import { isWeakPassword } from "ente-accounts-rs/utils/password";+import { LinkButton } from "ente-base/components/LinkButton";+import { LoadingButton } from "ente-base/components/mui/LoadingButton";+import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";+import { deriveKeyInsufficientMemoryErrorMessage } from "ente-accounts-rs/services/crypto";+import { isMuseumHTTPError } from "ente-base/http";+import log from "ente-base/log";+import { saveMasterKeyInSessionAndSafeStore } from "ente-accounts-rs/services/session-storage";+import { JOIN_ALBUM_CONTEXT_KEY } from "ente-new/albums/services/join-album";+import { useFormik } from "formik";+import { t } from "i18next";+import type { NextRouter } from "next/router";+import React, { useCallback, useEffect, useState } from "react";+import { Trans } from "react-i18next";+import { z } from "zod";+import { PasswordStrengthHint } from "./PasswordStrength";+import {+ AccountsPageFooter,+ AccountsPageTitle,+} from "./layouts/centered-paper";++interface SignUpContentsProps {+ router: NextRouter;+ /** Called when the user clicks the login option instead. */+ onLogin: () => void;+ /** Reactive value of {@link customAPIHost}. */+ host: string | undefined;+}++/**+ * A contents of the "signup" form.+ *+ * It is used both on the "/signup" page itself, and as a subcomponent of the+ * "/" page where the user can toggle between the signup and login forms inline.+ */+export const SignUpContents: React.FC<SignUpContentsProps> = ({+ router,+ onLogin,+ host,+}) => {+ const [showPassword, setShowPassword] = useState(false);+ const [isJoinAlbumContext, setIsJoinAlbumContext] = useState(false);++ useEffect(() => {+ // Check if we're in a join album context+ const joinAlbumContext = sessionStorage.getItem(JOIN_ALBUM_CONTEXT_KEY);+ setIsJoinAlbumContext(!!joinAlbumContext);+ }, []);++ const handleToggleShowHidePassword = useCallback(+ () => setShowPassword((show) => !show),+ [],+ );++ const formik = useFormik({+ initialValues: {+ email: "",+ password: "",+ confirmPassword: "",+ referral: "",+ acceptedTerms: false,+ },+ onSubmit: async (+ { email, password, confirmPassword, referral },+ { setFieldError },+ ) => {+ if (!email) {+ setFieldError("email", t("required"));+ return;+ }++ if (!z.email().safeParse(email).success) {+ setFieldError("email", t("invalid_email_error"));+ return;+ }++ if (!password) {+ setFieldError("password", t("required"));+ return;+ }++ if (!confirmPassword) {+ setFieldError("confirmPassword", t("required"));+ return;+ }++ if (password != confirmPassword) {+ setFieldError("confirmPassword", t("password_mismatch_error"));+ return;+ }++ try {+ const cleanedReferral = referral.trim();+ if (cleanedReferral) stashReferralSource(cleanedReferral);++ try {+ await sendOTT(email, "signup");+ } catch (e) {+ if (+ await isMuseumHTTPError(+ e,+ 409,+ "USER_ALREADY_REGISTERED",+ )+ ) {+ setFieldError("email", t("email_already_registered"));+ return;+ }+ throw e;+ }++ replaceSavedLocalUser({ email });++ let gkResult: GenerateKeysAndAttributesResult;+ try {+ gkResult = await generateKeysAndAttributes(password);+ } catch (e) {+ if (+ e instanceof Error &&+ e.message == deriveKeyInsufficientMemoryErrorMessage+ ) {+ setFieldError(+ "confirmPassword",+ t("password_generation_failed"),+ );+ return;+ }+ throw e;+ }++ const { masterKey, kek, keyAttributes } = gkResult;+ saveOriginalKeyAttributes(keyAttributes);+ stashSRPSetupAttributes(await generateSRPSetupAttributes(kek));+ await generateAndSaveInteractiveKeyAttributes(+ password,+ keyAttributes,+ masterKey,+ );+ await saveMasterKeyInSessionAndSafeStore(masterKey);++ saveJustSignedUp();+ void router.push("/verify");+ } catch (e) {+ log.error("Signup failed", e);+ setFieldError("confirmPassword", t("generic_error"));+ }+ },+ });++ const form = (+ <form onSubmit={formik.handleSubmit}>+ <TextField+ name="email"+ type="email"+ autoComplete="username"+ label={t("enter_email")}+ value={formik.values.email}+ onChange={formik.handleChange}+ error={!!formik.errors.email}+ helperText={formik.errors.email}+ disabled={formik.isSubmitting}+ fullWidth+ autoFocus+ />+ <TextField+ name="password"+ autoComplete="new-password"+ type={showPassword ? "text" : "password"}+ label={t("password")}+ value={formik.values.password}+ onChange={formik.handleChange}+ error={!!formik.errors.password}+ helperText={formik.errors.password}+ disabled={formik.isSubmitting}+ fullWidth+ slotProps={{+ input: {+ endAdornment: (+ <ShowHidePasswordInputAdornment+ showPassword={showPassword}+ onToggle={handleToggleShowHidePassword}+ />+ ),+ },+ }}+ />+ <TextField+ name="confirmPassword"+ autoComplete="new-password"+ type="password"+ label={t("confirm_password")}+ value={formik.values.confirmPassword}+ onChange={formik.handleChange}+ error={!!formik.errors.confirmPassword}+ helperText={formik.errors.confirmPassword}+ disabled={formik.isSubmitting}+ fullWidth+ />+ <PasswordStrengthHint password={formik.values.password} />+ <InputLabel+ htmlFor="referral"+ sx={{ color: "text.muted", mt: "24px", mx: "2px" }}+ >+ {t("referral_source_hint")}+ </InputLabel>+ <TextField+ hiddenLabel+ id="referral"+ type="text"+ value={formik.values.referral}+ onChange={formik.handleChange}+ error={!!formik.errors.referral}+ disabled={formik.isSubmitting}+ fullWidth+ slotProps={{+ input: {+ endAdornment: (+ <InputAdornment position="end">+ <Tooltip title={t("referral_source_info")}>+ <IconButton+ tabIndex={-1}+ color="secondary"+ edge={"end"}+ >+ <InfoOutlinedIcon />+ </IconButton>+ </Tooltip>+ </InputAdornment>+ ),+ },+ }}+ />+ <FormGroup sx={{ color: "text.muted", mt: 2, mb: 2.5, mx: "4px" }}>+ <FormControlLabel+ control={+ <Checkbox+ name="acceptedTerms"+ size="small"+ color="accent"+ checked={formik.values.acceptedTerms}+ onChange={formik.handleChange}+ disabled={formik.isSubmitting}+ />+ }+ label={+ <Typography variant="small">+ <Trans+ i18nKey={"terms_and_conditions"}+ components={{+ a: (+ <Link+ href="https://ente.io/terms"+ target="_blank"+ />+ ),+ b: (+ <Link+ href="https://ente.io/privacy"+ target="_blank"+ />+ ),+ }}+ />+ </Typography>+ }+ />+ </FormGroup>+ <LoadingButton+ fullWidth+ color="accent"+ type="submit"+ loading={formik.isSubmitting}+ disabled={+ !formik.values.acceptedTerms ||+ isWeakPassword(formik.values.password)+ }+ >+ {t("create_account")}+ </LoadingButton>+ <Typography+ variant="small"+ sx={(theme) => ({+ mt: 1,+ textAlign: "center",+ color: "text.muted",+ // Prevent layout shift by using a minHeight equal to the+ // lineHeight of the eventual content that'll be shown.+ minHeight: theme.typography.small.lineHeight,+ })}+ >+ {formik.isSubmitting ? t("key_generation_in_progress") : ""}+ </Typography>+ </form>+ );++ return (+ <>+ <AccountsPageTitle>+ {isJoinAlbumContext ? t("signup_to_join_album") : t("sign_up")}+ </AccountsPageTitle>+ {form}+ <Divider sx={{ mt: 1 }} />+ <AccountsPageFooter>+ <Stack sx={{ gap: 3, textAlign: "center" }}>+ <LinkButton onClick={onLogin}>+ {t("existing_account")}+ </LinkButton>+ {host && (+ <Typography variant="mini" sx={{ color: "text.faint" }}>+ {host}+ </Typography>+ )}+ </Stack>+ </AccountsPageFooter>+ </>+ );+};diff --git a/web/packages/accounts-rs/components/Verify2FACodeForm.tsx b/web/packages/accounts-rs/components/Verify2FACodeForm.tsxnew file mode 100644index 0000000000..2e3cb1c2d8--- /dev/null+++ b/web/packages/accounts-rs/components/Verify2FACodeForm.tsx@@ -0,0 +1,127 @@+import { Stack, styled, Typography } from "@mui/material";+import { LoadingButton } from "ente-base/components/mui/LoadingButton";+import { isHTTP401Error } from "ente-base/http";+import log from "ente-base/log";+import { useFormik } from "formik";+import { t } from "i18next";+import React, { useEffect, useState } from "react";+import OtpInput from "react-otp-input";++interface Verify2FACodeFormProps {+ /**+ * Called when the user submits the OTP.+ *+ * The submission can happen in two ways:+ * 1. The fill-in all the required 6 digits, or+ * 2. They press the "Enable" button.+ *+ * The form will stay in a submitting state until this callback returns.+ *+ * @param otp The OTP that the user entered.+ */+ onSubmit: (otp: string) => Promise<void>;+ /**+ * The label for the submit button.+ */+ submitButtonText: string;+}++/**+ * A form that can be used to ask the user to fill in a 6 digit OTP that their+ * authenticator app is providing them with.+ */+export const Verify2FACodeForm: React.FC<Verify2FACodeFormProps> = ({+ onSubmit,+ submitButtonText,+}) => {+ const [shouldAutoFocus, setShouldAutoFocus] = useState(true);++ const {+ values,+ errors,+ handleChange,+ handleSubmit,+ submitForm,+ isSubmitting,+ } = useFormik<{ otp: string }>({+ initialValues: { otp: "" },+ validateOnBlur: false,+ validateOnChange: false,+ onSubmit: async ({ otp }, { setFieldError, resetForm }) => {+ try {+ await onSubmit(otp);+ resetForm(); // Prevent resubmission via the useEffect.+ } catch (e) {+ log.error("Failed to submit 2FA code", e);+ resetForm();+ setFieldError(+ "otp",+ isHTTP401Error(e)+ ? t("incorrect_code")+ : t("generic_error"),+ );+ // Workaround (toggling shouldAutoFocus) to reset the focus back+ // to the first input field in case of errors.+ // https://github.com/devfolioco/react-otp-input/issues/420+ setShouldAutoFocus(false);+ setTimeout(() => setShouldAutoFocus(true), 100);+ }+ },+ });++ useEffect(() => {+ if (values.otp.length == 6 && !isSubmitting) void submitForm();+ }, [values, isSubmitting, submitForm]);++ return (+ <form onSubmit={handleSubmit}>+ <Stack sx={{ gap: 3, textAlign: "center" }}>+ <Typography variant="small" sx={{ color: "text.muted" }}>+ {t("enter_two_factor_otp")}+ </Typography>+ <OtpInput+ containerStyle={{ justifyContent: "center" }}+ shouldAutoFocus={shouldAutoFocus}+ value={values.otp}+ onChange={handleChange("otp")}+ numInputs={6}+ renderSeparator={<span>-</span>}+ renderInput={(props) => <IndividualInput {...props} />}+ />+ {errors.otp && (+ <Typography variant="mini" sx={{ color: "critical.main" }}>+ {errors.otp}+ </Typography>+ )}+ <LoadingButton+ type="submit"+ color="accent"+ fullWidth+ loading={isSubmitting}+ disabled={values.otp.length < 6}+ >+ {submitButtonText}+ </LoadingButton>+ </Stack>+ </form>+ );+};++const IndividualInput = styled("input")(+ ({ theme }) => `+ font-size: 1.5rem;+ padding: 4px;+ width: 40px !important;+ aspect-ratio: 1;+ margin-inline: 6px;+ border: 1px solid ${theme.vars.palette.accent.main};+ border-radius: 1px;+ outline-color: ${theme.vars.palette.accent.light};+ transition: 0.5s;+ ${theme.breakpoints.down("sm")} {+ font-size: 1rem;+ padding: 4px;+ width: 32px !important;+ }+`,+);diff --git a/web/packages/accounts-rs/components/VerifyMasterPasswordForm.tsx b/web/packages/accounts-rs/components/VerifyMasterPasswordForm.tsxnew file mode 100644index 0000000000..bef4da1a9a--- /dev/null+++ b/web/packages/accounts-rs/components/VerifyMasterPasswordForm.tsx@@ -0,0 +1,257 @@+import { Input, TextField } from "@mui/material";+import {+ srpVerificationUnauthorizedErrorMessage,+ type SRPAttributes,+} from "ente-accounts-rs/services/srp";+import type { KeyAttributes } from "ente-accounts-rs/services/user";+import { LoadingButton } from "ente-base/components/mui/LoadingButton";+import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";+import { decryptBox, deriveKey } from "ente-accounts-rs/services/crypto";+import log from "ente-base/log";+import { useFormik } from "formik";+import { t } from "i18next";+import { useCallback, useState } from "react";++export interface VerifyMasterPasswordFormProps {+ /**+ * The email of the user whose password we're trying to verify.+ */+ userEmail: string;+ /**+ * The user's SRP attributes.+ *+ * The SRP attributes are used to derive the KEK from the user's password.+ * If they are not present, the {@link keyAttributes} will be used instead.+ *+ * At least one of {@link srpAttributes} and {@link keyAttributes} must be+ * present, otherwise the verification will fail.+ */+ srpAttributes?: SRPAttributes;+ /**+ * The user's key attributes.+ *+ * If they are present, they are used to derive the KEK from the user's+ * password when {@link srpAttributes} are not present. This is the case+ * when the user has already logged in (or signed up) on this client before,+ * and is now doing a reauthentication.+ *+ * If they are not present, then {@link getKeyAttributes} must be present+ * and will be used to obtain the user's key attributes. This is the case+ * when the user is logging into a new client.+ */+ keyAttributes: KeyAttributes | undefined;+ /**+ * A callback invoked when the form wants to get {@link KeyAttributes}.+ *+ * It is only provided during the login flow, where we do not have+ * {@link keyAttributes} already available for the user. In case the form is+ * used for reauthenticating the user after they've already logged in, then+ * this function will not be provided.+ *+ * @returns The user's key attributes obtained from remote, or+ * "redirecting-second-factor" if the user has an additional second factor+ * verification required and the app is redirecting there.+ *+ * @throws A Error with message+ * {@link srpVerificationUnauthorizedErrorMessage} to signal that either+ * that the password is incorrect, or no account with the provided email+ * exists.+ */+ getKeyAttributes?: (+ srpAttributes: SRPAttributes,+ kek: string,+ ) => Promise<KeyAttributes | "redirecting-second-factor" | undefined>;+ /**+ * The title of the submit button on the form.+ */+ submitButtonTitle: string;+ /**+ * The callback invoked with the verified password, and all the other+ * auxillary information that was ascertained when verifying it.+ *+ * @param key The user's master key obtained after decrypting it by using+ * the KEK derived from their password.+ *+ * @param kek The key used for encrypting the user's master key.+ *+ * @param keyAttributes The user's key attributes (either those that we+ * started with, or those that we fetched on the way using+ * {@link getKeyAttributes}).+ *+ * @param password The plaintext password. This can be used during login to+ * derive another encrypted key using interactive mem/ops limits for faster+ * reauthentication after the initial login.+ */+ onVerify: (+ key: string,+ kek: string,+ keyAttributes: KeyAttributes,+ password: string,+ ) => void;+}++/**+ * A form with a text field that can be used to ask the user to verify their+ * password.+ *+ * We use it both during the initial authentication (the "/credentials" page,+ * shown when logging in, or reopening the web app in a new tab), and when the+ * user is trying to perform a sensitive action when already logged in and+ * having a session (the {@link AuthenticateUser} component).+ */+export const VerifyMasterPasswordForm: React.FC<+ VerifyMasterPasswordFormProps+> = ({+ userEmail,+ keyAttributes,+ srpAttributes,+ getKeyAttributes,+ onVerify,+ submitButtonTitle,+}) => {+ const [showPassword, setShowPassword] = useState(false);++ const handleToggleShowHidePassword = useCallback(+ () => setShowPassword((show) => !show),+ [],+ );++ const formik = useFormik({+ initialValues: { password: "" },+ onSubmit: async ({ password }, { setFieldError }) => {+ const setPasswordFieldError = (message: string) =>+ setFieldError("password", message);++ if (!password) {+ setPasswordFieldError(t("required"));+ return;+ }++ try {+ await verifyPassword(password, setPasswordFieldError);+ } catch (e) {+ log.error("Failed to to verify password", e);+ setPasswordFieldError(t("generic_error"));+ }+ },+ });++ const verifyPassword = async (+ password: string,+ setFieldError: (message: string) => void,+ ) => {+ let kek: string;+ if (srpAttributes) {+ try {+ kek = await deriveKey(+ password,+ srpAttributes.kekSalt,+ srpAttributes.opsLimit,+ srpAttributes.memLimit,+ );+ } catch (e) {+ log.error("Failed to derive kek", e);+ setFieldError(t("weak_device_hint"));+ return;+ }+ } else if (keyAttributes) {+ try {+ kek = await deriveKey(+ password,+ keyAttributes.kekSalt,+ keyAttributes.opsLimit,+ keyAttributes.memLimit,+ );+ } catch (e) {+ log.error("Failed to derive kek", e);+ setFieldError(t("weak_device_hint"));+ return;+ }+ } else throw new Error("Both SRP and key attributes are missing");++ if (!keyAttributes && getKeyAttributes && srpAttributes) {+ try {+ const result = await getKeyAttributes(srpAttributes, kek);+ if (result == "redirecting-second-factor") {+ // Two factor enabled, user has been redirected to the+ // corresponding second factor verification page.+ return;+ } else {+ keyAttributes = result;+ }+ } catch (e) {+ if (+ e instanceof Error &&+ e.message == srpVerificationUnauthorizedErrorMessage+ ) {+ log.error("Incorrect password or no account", e);+ setFieldError(t("incorrect_password_or_no_account"));+ return;+ }+ throw e;+ }+ }++ if (!keyAttributes) throw Error("Couldn't get key attributes");++ let key: string;+ try {+ key = await decryptBox(+ {+ encryptedData: keyAttributes.encryptedKey,+ nonce: keyAttributes.keyDecryptionNonce,+ },+ kek,+ );+ } catch {+ setFieldError(t("incorrect_password"));+ return;+ }++ onVerify(key, kek, keyAttributes, password);+ };++ return (+ <form onSubmit={formik.handleSubmit}>+ <Input+ sx={{ display: "none" }}+ name="email"+ autoComplete="username"+ type="email"+ value={userEmail}+ />+ <TextField+ name="password"+ value={formik.values.password}+ onChange={formik.handleChange}+ type={showPassword ? "text" : "password"}+ autoComplete="current-password"+ label={t("password")}+ fullWidth+ autoFocus+ margin="normal"+ disabled={formik.isSubmitting}+ error={!!formik.errors.password}+ helperText={formik.errors.password ?? " "}+ slotProps={{+ input: {+ endAdornment: (+ <ShowHidePasswordInputAdornment+ showPassword={showPassword}+ onToggle={handleToggleShowHidePassword}+ />+ ),+ },+ }}+ />+ <LoadingButton+ fullWidth+ type="submit"+ loading={formik.isSubmitting}+ color={"accent"}+ >+ {submitButtonTitle}+ </LoadingButton>+ </form>+ );+};diff --git a/web/packages/accounts-rs/components/layouts/centered-paper.tsx b/web/packages/accounts-rs/components/layouts/centered-paper.tsxnew file mode 100644index 0000000000..521707f864--- /dev/null+++ b/web/packages/accounts-rs/components/layouts/centered-paper.tsx@@ -0,0 +1,88 @@+import { Paper, Stack, styled, Typography } from "@mui/material";+import { CenteredFill } from "ente-base/components/containers";+import { EnteLogo } from "ente-base/components/EnteLogo";+import { NavbarBase } from "ente-base/components/Navbar";++/**+ * An ad-hoc component that abstracts the layout common to many of the pages+ * exported by the the accounts package.+ *+ * The layout is roughly:+ * - Set height to 100vh+ * - An app bar at the top+ * - Center a {@link Paper} in the rest of the space.+ * - The children passed to this component go within this {@link Paper}.+ *+ * {@link AccountsPageTitle} and {@link AccountsPageFooter} are meant to be used+ * in tandem with, as children of, {@link AccountsPageContents}.+ */+export const AccountsPageContents: React.FC<React.PropsWithChildren> = ({+ children,+}) => (+ <Stack+ sx={[+ { minHeight: "100svh", bgcolor: "secondary.main" },+ (theme) =>+ theme.applyStyles("dark", { bgcolor: "background.default" }),+ ]}+ >+ <NavbarBase+ sx={{+ boxShadow: "none",+ borderBottom: "none",+ bgcolor: "transparent",+ }}+ >+ <EnteLogo />+ </NavbarBase>+ <CenteredFill+ sx={[+ { bgcolor: "secondary.main" },+ (theme) =>+ theme.applyStyles("dark", {+ bgcolor: "background.default",+ }),+ ]}+ >+ <AccountsPagePaper>{children}</AccountsPagePaper>+ </CenteredFill>+ </Stack>+);++const AccountsPagePaper = styled(Paper)(({ theme }) => ({+ marginBlock: theme.spacing(2),+ padding: theme.spacing(5, 3),+ [theme.breakpoints.up("sm")]: { padding: theme.spacing(5) },+ width: "min(420px, 85vw)",+ minHeight: "375px",+ display: "flex",+ flexDirection: "column",+ gap: theme.spacing(4),+ boxShadow: "none",+ borderRadius: "20px",+}));++export const AccountsPageTitle: React.FC<React.PropsWithChildren> = ({+ children,+}) => (+ <Typography variant="h3" sx={{ flex: 1 }}>+ {children}+ </Typography>+);++export const AccountsPageFooter: React.FC<React.PropsWithChildren> = ({+ children,+}) => (+ <Stack+ direction="row"+ sx={{+ mx: "4px",+ // Put the items to the side,+ justifyContent: "space-between",+ // Unless there is just one, in which case center it.+ "& :only-child": { marginInline: "auto" },+ }}+ >+ {children}+ </Stack>+);diff --git a/web/packages/accounts-rs/components/utils/dialog.ts b/web/packages/accounts-rs/components/utils/dialog.tsnew file mode 100644index 0000000000..333d06a509--- /dev/null+++ b/web/packages/accounts-rs/components/utils/dialog.ts@@ -0,0 +1,22 @@+import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";+import { t } from "i18next";++/**+ * {@link MiniDialogAttributes} for showing asking the user to login again when+ * their session has expired.+ *+ * There is one button, which allows them to logout.+ *+ * @param onLogin Called when the user presses the "Login" button on the error+ * dialog.+ */+export const sessionExpiredDialogAttributes = (+ onLogin: () => void,+): MiniDialogAttributes => ({+ title: t("session_expired"),+ message: t("session_expired_message"),+ nonClosable: true,+ nonReplaceable: true,+ continue: { text: t("login"), action: onLogin },+ cancel: false,+});diff --git a/web/packages/accounts-rs/components/utils/second-factor-choice.ts b/web/packages/accounts-rs/components/utils/second-factor-choice.tsnew file mode 100644index 0000000000..d908018cc7--- /dev/null+++ b/web/packages/accounts-rs/components/utils/second-factor-choice.ts@@ -0,0 +1,90 @@+/**+ * @file This code is conceputally related to `SecondFactorChoice.tsx`, but+ * needs to be in a separate file to allow fast refresh.+ */++import type { EmailOrSRPVerificationResponse } from "ente-accounts-rs/services/user";+import { useModalVisibility } from "ente-base/components/utils/modal";+import { useCallback, useMemo, useRef } from "react";+import type { SecondFactorType } from "../SecondFactorChoice";++/**+ * A convenience hook for keeping track of the state and logic that is needed+ * after password verification to determine which second factor (if any) we+ * should be asking the user for.+ *+ * This is a rather ad-hoc abstraction meant to be used in a very specific way;+ * the only intent is to reduce code duplication between the two pages that need+ * this choice.+ */+export const useSecondFactorChoiceIfNeeded = () => {+ const resolveSecondFactorChoice = useRef<+ | ((value: SecondFactorType | PromiseLike<SecondFactorType>) => void)+ | undefined+ >(undefined);+ const {+ show: showSecondFactorChoice,+ props: secondFactorChoiceVisibilityProps,+ } = useModalVisibility();++ const onSelect = useCallback((factor: SecondFactorType) => {+ const resolve = resolveSecondFactorChoice.current!;+ resolveSecondFactorChoice.current = undefined;+ resolve(factor);+ }, []);++ const secondFactorChoiceProps = useMemo(+ () => ({ ...secondFactorChoiceVisibilityProps, onSelect }),+ [secondFactorChoiceVisibilityProps, onSelect],+ );++ const userVerificationResultAfterResolvingSecondFactorChoice = useCallback(+ async (response: EmailOrSRPVerificationResponse) => {+ const {+ twoFactorSessionID: _twoFactorSessionIDV1,+ twoFactorSessionIDV2: _twoFactorSessionIDV2,+ passkeySessionID: _passkeySessionID,+ } = response;++ // When the user has both TOTP and pk set as the second factor,+ // we'll get two session IDs. For backward compat, the TOTP session+ // ID will be in a V2 attribute during a transient migration period.+ //+ // Note the use of || instead of ?? since _twoFactorSessionIDV1 will+ // be an empty string, not undefined, if it is unset.+ const _twoFactorSessionID =+ _twoFactorSessionIDV1 || _twoFactorSessionIDV2;++ let passkeySessionID: string | undefined;+ let twoFactorSessionID: string | undefined;+ // If both factors are set, ask the user which one they want to use.+ if (_twoFactorSessionID && _passkeySessionID) {+ const choice = await new Promise<SecondFactorType>(+ (resolve) => {+ resolveSecondFactorChoice.current = resolve;+ showSecondFactorChoice();+ },+ );+ switch (choice) {+ case "passkey":+ passkeySessionID = _passkeySessionID;+ break;+ case "totp":+ twoFactorSessionID = _twoFactorSessionID;+ break;+ }+ } else {+ passkeySessionID = _passkeySessionID;+ twoFactorSessionID = _twoFactorSessionID;+ }++ return { ...response, passkeySessionID, twoFactorSessionID };+ },+ [showSecondFactorChoice],+ );++ return {+ secondFactorChoiceProps,+ userVerificationResultAfterResolvingSecondFactorChoice,+ };+};diff --git a/web/packages/accounts-rs/components/utils/use-redirect.ts b/web/packages/accounts-rs/components/utils/use-redirect.tsnew file mode 100644index 0000000000..03a2a3992b--- /dev/null+++ b/web/packages/accounts-rs/components/utils/use-redirect.ts@@ -0,0 +1,24 @@+import { haveMasterKeyInSession } from "ente-accounts-rs/services/session-storage";+import { useRouter } from "next/router";+import { useEffect } from "react";+import { stashRedirect } from "../../services/redirect";++/**+ * Redirect to the appropriate credential step (password reverify, or a full+ * login) and then back to the current page if the user's master key is not+ * present in the session storage.+ *+ * @param currentPageSlug The slug for the current page where this hook is being+ * used. If a redirect happens, then this slug will be stashed and used to+ * redirect back here after the credentials have been obtained.+ */+export const useRedirectIfNeedsCredentials = (currentPageSlug: string) => {+ const router = useRouter();++ useEffect(() => {+ if (!haveMasterKeyInSession()) {+ stashRedirect(currentPageSlug);+ void router.push("/");+ }+ }, [router]);+};diff --git a/web/packages/accounts-rs/eslint.config.mjs b/web/packages/accounts-rs/eslint.config.mjsnew file mode 100644index 0000000000..f732329223--- /dev/null+++ b/web/packages/accounts-rs/eslint.config.mjs@@ -0,0 +1,42 @@+import baseConfig from "ente-build-config/eslintrc-react.mjs";++export default [+ ...baseConfig,+ {+ files: ["**/*.{ts,tsx}"],+ rules: {+ "no-restricted-imports": [+ "error",+ {+ paths: [+ {+ name: "ente-base/crypto",+ message:+ "Use ente-accounts-rs/services/crypto instead.",+ },+ {+ name: "ente-base/crypto/types",+ message:+ "Use ente-accounts-rs/services/crypto instead.",+ },+ {+ name: "ente-base/session",+ message:+ "Use ente-accounts-rs/services/session-storage instead.",+ },+ {+ name: "fast-srp-hap",+ message:+ "Use Rust/WASM SRP helpers from ente-accounts-rs/services/srp.",+ },+ {+ name: "bip39",+ message:+ "Use Rust/WASM recovery helpers from ente-accounts-rs/services/crypto.",+ },+ ],+ },+ ],+ },+ },+];diff --git a/web/packages/accounts-rs/package.json b/web/packages/accounts-rs/package.jsonnew file mode 100644index 0000000000..bded9942ae--- /dev/null+++ b/web/packages/accounts-rs/package.json@@ -0,0 +1,20 @@+{+ "name": "ente-accounts-rs",+ "version": "0.0.0",+ "private": true,+ "dependencies": {+ "ente-base": "*",+ "ente-wasm": "*",+ "react": "^19.2.0",+ "react-dom": "^19.2.0",+ "react-otp-input": "^3.1.1",+ "uuid": "^13.0.0",+ "zxcvbn": "^4.4.2"+ },+ "devDependencies": {+ "@types/react": "^19.2.2",+ "@types/react-dom": "^19.2.2",+ "@types/zxcvbn": "^4.4.5",+ "ente-build-config": "*"+ }+}diff --git a/web/packages/accounts-rs/pages/change-email.tsx b/web/packages/accounts-rs/pages/change-email.tsxnew file mode 100644index 0000000000..ddefd3c0b1--- /dev/null+++ b/web/packages/accounts-rs/pages/change-email.tsx@@ -0,0 +1,182 @@+import CheckIcon from "@mui/icons-material/Check";+import { Alert, Box, TextField } from "@mui/material";+import {+ AccountsPageContents,+ AccountsPageFooter,+ AccountsPageTitle,+} from "ente-accounts-rs/components/layouts/centered-paper";+import { useRedirectIfNeedsCredentials } from "ente-accounts-rs/components/utils/use-redirect";+import { appHomeRoute } from "ente-accounts-rs/services/redirect";+import { changeEmail, sendOTT } from "ente-accounts-rs/services/user";+import { LinkButton } from "ente-base/components/LinkButton";+import { LoadingButton } from "ente-base/components/mui/LoadingButton";+import { isHTTPErrorWithStatus } from "ente-base/http";+import log from "ente-base/log";+import { useFormik } from "formik";+import { t } from "i18next";+import { useRouter } from "next/router";+import { useCallback, useState } from "react";+import { Trans } from "react-i18next";+import { z } from "zod";++/**+ * A page that allows a user to change the email address associated with their+ * Ente account.+ */+const Page: React.FC = () => {+ useRedirectIfNeedsCredentials("/change-email");++ return (+ <AccountsPageContents>+ <AccountsPageTitle>{t("change_email")}</AccountsPageTitle>+ <ChangeEmailForm />+ </AccountsPageContents>+ );+};++export default Page;++const ChangeEmailForm: React.FC = () => {+ const [requestedEmail, setRequestedEmail] = useState("");+ const [showSentConfirmation, setShowSentConfirmation] = useState(false);++ const router = useRouter();++ const redirectToAppHome = useCallback(() => {+ void router.push(appHomeRoute);+ }, [router]);++ const formik = useFormik({+ initialValues: { email: "", ott: "" },+ onSubmit: async ({ email, ott }, { setFieldError }) => {+ if (!email) {+ setFieldError("email", t("required"));+ return;+ }++ if (!z.email().safeParse(email).success) {+ setFieldError("email", t("invalid_email_error"));+ return;+ }++ if (!requestedEmail) {+ try {+ await sendOTT(email, "change");+ } catch (e) {+ log.error("Could not send OTT for email change", e);+ setFieldError(+ "email",+ isHTTPErrorWithStatus(e, 403)+ ? t("email_already_taken")+ : t("generic_error"),+ );+ return;+ }++ setRequestedEmail(email);+ setShowSentConfirmation(true);+ } else {+ if (!ott) {+ setFieldError("ott", t("required"));+ return;+ }++ try {+ await changeEmail(email, ott);+ } catch (e) {+ log.error("Could not change email", e);+ setFieldError(+ "ott",+ isHTTPErrorWithStatus(e, 401)+ ? t("incorrect_code")+ : isHTTPErrorWithStatus(e, 410)+ ? t("expired_code_error")+ : t("generic_error"),+ );+ return;+ }++ redirectToAppHome();+ }+ },+ });++ return (+ <>+ {requestedEmail && showSentConfirmation && (+ <Alert+ icon={<CheckIcon fontSize="inherit" />}+ severity="success"+ onClose={() => setShowSentConfirmation(false)}+ >+ <Trans+ i18nKey="email_sent"+ components={{+ a: (+ <Box+ component={"span"}+ sx={{ color: "text.muted" }}+ />+ ),+ }}+ values={{ email: requestedEmail }}+ />+ </Alert>+ )}+ <form onSubmit={formik.handleSubmit}>+ <TextField+ name="email"+ type="email"+ label={t("enter_email")}+ value={formik.values.email}+ onChange={formik.handleChange}+ error={!!formik.errors.email}+ // See: [Note: Use space as default TextField helperText]+ //+ // Also, we only need keep the extra space until the email+ // has been entered (since the email field is read only+ // after that).+ helperText={+ formik.errors.email ?? (requestedEmail ? "" : " ")+ }+ disabled={formik.isSubmitting}+ autoFocus+ fullWidth+ slotProps={{ input: { readOnly: !!requestedEmail } }}+ />+ {requestedEmail && (+ <TextField+ name="ott"+ type="text"+ label={t("verification_code")}+ value={formik.values.ott}+ onChange={formik.handleChange}+ error={!!formik.errors.ott}+ helperText={formik.errors.ott ?? " "}+ disabled={formik.isSubmitting}+ fullWidth+ />+ )}+ <LoadingButton+ type="submit"+ color="accent"+ fullWidth+ loading={formik.isSubmitting}+ sx={{ mt: 1, mb: 3 }}+ >+ {!requestedEmail ? t("send_otp") : t("verify")}+ </LoadingButton>+ </form>+ <AccountsPageFooter>+ {requestedEmail && (+ <LinkButton onClick={() => setRequestedEmail("")}>+ {t("change_email")}?+ </LinkButton>+ )}+ <LinkButton onClick={redirectToAppHome}>+ {t("go_back")}+ </LinkButton>+ </AccountsPageFooter>+ </>+ );+};diff --git a/web/packages/accounts-rs/pages/change-password.tsx b/web/packages/accounts-rs/pages/change-password.tsxnew file mode 100644index 0000000000..3861649968--- /dev/null+++ b/web/packages/accounts-rs/pages/change-password.tsx@@ -0,0 +1,101 @@+import { Divider } from "@mui/material";+import {+ AccountsPageContents,+ AccountsPageFooter,+ AccountsPageTitle,+} from "ente-accounts-rs/components/layouts/centered-paper";+import { appHomeRoute, stashRedirect } from "ente-accounts-rs/services/redirect";+import { changePassword, type LocalUser } from "ente-accounts-rs/services/user";+import { LinkButton } from "ente-base/components/LinkButton";+import { LoadingIndicator } from "ente-base/components/loaders";+import { deriveKeyInsufficientMemoryErrorMessage } from "ente-accounts-rs/services/crypto";+import log from "ente-base/log";+import { t } from "i18next";+import { useRouter } from "next/router";+import React, { useCallback, useEffect, useState } from "react";+import {+ NewPasswordForm,+ type NewPasswordFormProps,+} from "../components/NewPasswordForm";+import { savedLocalUser } from "../services/accounts-db";++/**+ * A page that allows a user to reset or change their password.+ *+ * See: [Note: Login pages]+ */+const Page: React.FC = () => {+ const [user, setUser] = useState<LocalUser | undefined>(undefined);++ const router = useRouter();++ // We're invoked with the "?op=reset" query parameter in the recovery flow.+ const isReset = router.query.op == "reset";++ useEffect(() => {+ const user = savedLocalUser();+ if (user) {+ setUser(user);+ } else {+ stashRedirect("/change-password");+ void router.replace("/");+ }+ }, [router]);++ return user ? (+ <PageContents {...{ user, isReset }} />+ ) : (+ <LoadingIndicator />+ );+};++export default Page;++interface PageContentsProps {+ user: LocalUser;+ /**+ * True if the password is being reset during the account recovery flow.+ */+ isReset: boolean;+}++const PageContents: React.FC<PageContentsProps> = ({ user, isReset }) => {+ const router = useRouter();++ const handleSubmit: NewPasswordFormProps["onSubmit"] = useCallback(+ async (password, setPasswordsFieldError) =>+ changePassword(password)+ .then(() => void router.push(appHomeRoute))+ .catch((e: unknown) => {+ log.error("Could not change password", e);+ setPasswordsFieldError(+ e instanceof Error &&+ e.message == deriveKeyInsufficientMemoryErrorMessage+ ? t("password_generation_failed")+ : t("generic_error"),+ );+ }),+ [router],+ );++ return (+ <AccountsPageContents>+ <AccountsPageTitle>{t("change_password")}</AccountsPageTitle>+ <NewPasswordForm+ userEmail={user.email}+ submitButtonTitle={t("change_password")}+ onSubmit={handleSubmit}+ />+ {!isReset && (+ <>+ <Divider sx={{ mt: 1 }} />+ <AccountsPageFooter>+ <LinkButton onClick={router.back}>+ {t("go_back")}+ </LinkButton>+ </AccountsPageFooter>+ </>+ )}+ </AccountsPageContents>+ );+};diff --git a/web/packages/accounts-rs/pages/credentials.tsx b/web/packages/accounts-rs/pages/credentials.tsxnew file mode 100644index 0000000000..0611153585--- /dev/null+++ b/web/packages/accounts-rs/pages/credentials.tsx@@ -0,0 +1,375 @@+import { AccountsPageContents } from "ente-accounts-rs/components/layouts/centered-paper";+import {+ AccountsPageFooterWithHost,+ PasswordHeader,+ VerifyingPasskey,+} from "ente-accounts-rs/components/LoginComponents";+import { SecondFactorChoice } from "ente-accounts-rs/components/SecondFactorChoice";+import { sessionExpiredDialogAttributes } from "ente-accounts-rs/components/utils/dialog";+import { useSecondFactorChoiceIfNeeded } from "ente-accounts-rs/components/utils/second-factor-choice";+import {+ VerifyMasterPasswordForm,+ type VerifyMasterPasswordFormProps,+} from "ente-accounts-rs/components/VerifyMasterPasswordForm";+import {+ savedIsFirstLogin,+ savedKeyAttributes,+ savedPartialLocalUser,+ savedSRPAttributes,+ saveIsFirstLogin,+ saveKeyAttributes,+ saveSRPAttributes,+ updateSavedLocalUser,+} from "ente-accounts-rs/services/accounts-db";+import {+ openPasskeyVerificationURL,+ passkeyVerificationRedirectURL,+} from "ente-accounts-rs/services/passkey";+import {+ appHomeRoute,+ stashRedirect,+ unstashRedirect,+} from "ente-accounts-rs/services/redirect";+import { checkSessionValidity } from "ente-accounts-rs/services/session";+import type { SRPAttributes } from "ente-accounts-rs/services/srp";+import {+ generateSRPSetupAttributes,+ getAndSaveSRPAttributes,+ getSRPAttributes,+ setupSRP,+ verifySRP,+} from "ente-accounts-rs/services/srp";+import {+ decryptAndStoreTokenIfNeeded,+ generateAndSaveInteractiveKeyAttributes,+ type KeyAttributes,+} from "ente-accounts-rs/services/user";+import { LinkButton } from "ente-base/components/LinkButton";+import { LoadingIndicator } from "ente-base/components/loaders";+import { useBaseContext } from "ente-base/context";+import { decryptBox } from "ente-accounts-rs/services/crypto";+import { isDevBuild } from "ente-base/env";+import { clearLocalStorage } from "ente-base/local-storage";+import log from "ente-base/log";+import {+ masterKeyFromSession,+ saveMasterKeyInSessionAndSafeStore,+ stashKeyEncryptionKeyInSessionStore,+ unstashKeyEncryptionKeyFromSession,+ updateSessionFromElectronSafeStorageIfNeeded,+} from "ente-accounts-rs/services/session-storage";+import { saveAuthToken, savedAuthToken } from "ente-base/token";+import { t } from "i18next";+import { useRouter } from "next/router";+import { useCallback, useEffect, useState } from "react";++/**+ * A page that allows the user to authenticate using their password.+ *+ * It is shown in two cases:+ *+ * - Initial authentication, when the user is logging in on to a new client.+ *+ * - Subsequent reauthentication, when the user opens the web app in a new tab.+ * Such a tab won't have the user's master key in session storage, so we ask+ * the user to reauthenticate using their password.+ *+ * See: [Note: Login pages]+ */+const Page: React.FC = () => {+ const { logout, showMiniDialog } = useBaseContext();++ const [userEmail, setUserEmail] = useState<string>("");+ const [keyAttributes, setKeyAttributes] = useState<+ KeyAttributes | undefined+ >(undefined);+ const [srpAttributes, setSRPAttributes] = useState<+ SRPAttributes | undefined+ >(undefined);+ const [passkeyVerificationData, setPasskeyVerificationData] = useState<+ { passkeySessionID: string; url: string } | undefined+ >(undefined);+ const [sessionValidityCheck, setSessionValidityCheck] = useState<+ Promise<void> | undefined+ >(undefined);++ const {+ secondFactorChoiceProps,+ userVerificationResultAfterResolvingSecondFactorChoice,+ } = useSecondFactorChoiceIfNeeded();++ const router = useRouter();++ const validateSession = useCallback(async () => {+ const showSessionExpiredDialog = () =>+ showMiniDialog(sessionExpiredDialogAttributes(logout));++ try {+ const session = await checkSessionValidity();+ switch (session.status) {+ case "invalid":+ showSessionExpiredDialog();+ break;+ case "valid":+ break;+ case "validButPasswordChanged":+ saveKeyAttributes(session.updatedKeyAttributes);+ saveSRPAttributes(session.updatedSRPAttributes);+ // Set a flag that causes new interactive key attributes to+ // be generated.+ saveIsFirstLogin();+ // This should be a rare occurrence, instead of building the+ // scaffolding to update all the in-memory state, just+ // reload everything.+ window.location.reload();+ }+ } catch (e) {+ // Ignore errors since we shouldn't be logging the user out for+ // potentially transient issues.+ log.warn("Ignoring error when determining session validity", e);+ }+ }, [logout, showMiniDialog]);++ const postVerification = useCallback(+ async (+ userEmail: string,+ masterKey: string,+ kek: string,+ keyAttributes: KeyAttributes,+ ) => {+ await saveMasterKeyInSessionAndSafeStore(masterKey);+ await decryptAndStoreTokenIfNeeded(keyAttributes, masterKey);+ try {+ let srpAttributes = savedSRPAttributes();+ if (!srpAttributes) {+ srpAttributes = await getSRPAttributes(userEmail);+ if (srpAttributes) {+ saveSRPAttributes(srpAttributes);+ } else {+ await setupSRP(await generateSRPSetupAttributes(kek));+ await getAndSaveSRPAttributes(userEmail);+ }+ }+ } catch (e) {+ log.error("SRP migration failed", e);+ }+ void router.push(unstashRedirect() ?? appHomeRoute);+ },+ [router],+ );++ useEffect(() => {+ void (async () => {+ const user = savedPartialLocalUser();+ const userEmail = user?.email;+ if (!userEmail) {+ await router.replace("/");+ return;+ }++ await updateSessionFromElectronSafeStorageIfNeeded();+ if ((await masterKeyFromSession()) && (await savedAuthToken())) {+ await router.replace(appHomeRoute);+ return;+ }++ setUserEmail(userEmail);+ if (user.token) setSessionValidityCheck(validateSession());++ const kek = await unstashKeyEncryptionKeyFromSession();+ const keyAttributes = savedKeyAttributes();++ // Refreshing an existing tab, or desktop app, or only the token+ // needs to decrypted and set.+ if (kek && keyAttributes) {+ const masterKey = await decryptBox(+ {+ encryptedData: keyAttributes.encryptedKey,+ nonce: keyAttributes.keyDecryptionNonce,+ },+ kek,+ );+ await postVerification(+ userEmail,+ masterKey,+ kek,+ keyAttributes,+ );+ return;+ }++ // Reauthentication in a new tab on the web app. Use previously+ // generated interactive key attributes to verify password.+ if (keyAttributes) {+ if (!user.token && !user.encryptedToken) {+ // TODO: Why? For now, add a dev mode circuit breaker.+ if (isDevBuild) throw new Error("Unexpected case reached");+ clearLocalStorage();+ void router.replace("/");+ return;+ }+ setKeyAttributes(keyAttributes);+ return;+ }++ // First login on a new client. `getKeyAttributes` from below will+ // be used during password verification to generate interactive key+ // attributes for subsequent reauthentications.+ const srpAttributes = savedSRPAttributes();+ if (srpAttributes) {+ setSRPAttributes(srpAttributes);+ return;+ }++ void router.replace("/");+ })();+ }, [router, validateSession, postVerification]);++ const getKeyAttributes: VerifyMasterPasswordFormProps["getKeyAttributes"] =+ useCallback(+ async (srpAttributes: SRPAttributes, kek: string) => {+ const {+ id,+ keyAttributes,+ token,+ encryptedToken,+ twoFactorSessionID,+ passkeySessionID,+ accountsUrl,+ } =+ await userVerificationResultAfterResolvingSecondFactorChoice(+ await verifySRP(srpAttributes, kek),+ );++ // If we had to ask remote for the key attributes, it is the+ // initial login on this client.+ saveIsFirstLogin();++ if (passkeySessionID) {+ await stashKeyEncryptionKeyInSessionStore(kek);+ updateSavedLocalUser({ passkeySessionID });+ stashRedirect("/");+ const url = passkeyVerificationRedirectURL(+ accountsUrl!,+ passkeySessionID,+ );+ setPasskeyVerificationData({ passkeySessionID, url });+ openPasskeyVerificationURL({ passkeySessionID, url });+ return "redirecting-second-factor";+ } else if (twoFactorSessionID) {+ await stashKeyEncryptionKeyInSessionStore(kek);+ updateSavedLocalUser({+ isTwoFactorEnabled: true,+ twoFactorSessionID,+ });+ void router.push("/two-factor/verify");+ return "redirecting-second-factor";+ } else {+ // In rare cases, if the user hasn't already setup their key+ // attributes, we might get the plaintext token from remote.+ if (token) await saveAuthToken(token);+ updateSavedLocalUser({+ id,+ token,+ encryptedToken,+ isTwoFactorEnabled: undefined,+ twoFactorSessionID: undefined,+ passkeySessionID: undefined,+ });+ if (keyAttributes) saveKeyAttributes(keyAttributes);+ return keyAttributes;+ }+ },+ [userVerificationResultAfterResolvingSecondFactorChoice, router],+ );++ const handleVerifyMasterPassword: VerifyMasterPasswordFormProps["onVerify"] =+ useCallback(+ (key, kek, keyAttributes, password) => {+ void (async () => {+ // Currently the page will get reloaded if any of the+ // attributes have changed, so we don't need to worry about+ // the KEK having been generated using stale credentials.+ //+ // This await on the promise is here to only ensure we're+ // done with the check before we let the user in.+ if (sessionValidityCheck) await sessionValidityCheck;++ const updatedKeyAttributes = savedIsFirstLogin()+ ? await generateAndSaveInteractiveKeyAttributes(+ password,+ keyAttributes,+ key,+ )+ : keyAttributes;++ await postVerification(+ userEmail,+ key,+ kek,+ updatedKeyAttributes,+ );+ })();+ },+ [postVerification, userEmail, sessionValidityCheck],+ );++ if (!userEmail) {+ return <LoadingIndicator />;+ }++ if (!keyAttributes && !srpAttributes) {+ return <LoadingIndicator />;+ }++ if (passkeyVerificationData) {+ // We only need to handle this scenario when running in the desktop app+ // because the web app will navigate to Passkey verification URL.+ // However, still we add an additional `globalThis.electron` check to+ // show a spinner. This prevents the VerifyingPasskey component from+ // being disorientingly shown for a fraction of a second as the redirect+ // happens on the web app.+ //+ // See: [Note: Passkey verification in the desktop app]++ if (!globalThis.electron) {+ return <LoadingIndicator />;+ }++ return (+ <VerifyingPasskey+ email={userEmail}+ passkeySessionID={passkeyVerificationData.passkeySessionID}+ onRetry={() =>+ openPasskeyVerificationURL(passkeyVerificationData)+ }+ {...{ logout, showMiniDialog }}+ />+ );+ }++ return (+ <AccountsPageContents>+ <PasswordHeader caption={userEmail} />+ <VerifyMasterPasswordForm+ {...{+ userEmail,+ keyAttributes,+ getKeyAttributes,+ srpAttributes,+ }}+ submitButtonTitle={t("sign_in")}+ onVerify={handleVerifyMasterPassword}+ />+ <AccountsPageFooterWithHost>+ <LinkButton onClick={() => router.push("/recover")}>+ {t("forgot_password")}+ </LinkButton>+ <LinkButton onClick={logout}>{t("change_email")}</LinkButton>+ </AccountsPageFooterWithHost>+ <SecondFactorChoice {...secondFactorChoiceProps} />+ </AccountsPageContents>+ );+};++export default Page;diff --git a/web/packages/accounts-rs/pages/generate.tsx b/web/packages/accounts-rs/pages/generate.tsxnew file mode 100644index 0000000000..bf01807fe7--- /dev/null+++ b/web/packages/accounts-rs/pages/generate.tsx@@ -0,0 +1,130 @@+import { Divider } from "@mui/material";+import {+ AccountsPageContents,+ AccountsPageFooter,+ AccountsPageTitle,+} from "ente-accounts-rs/components/layouts/centered-paper";+import { RecoveryKey } from "ente-accounts-rs/components/RecoveryKey";+import {+ savedJustSignedUp,+ savedOriginalKeyAttributes,+ savedPartialLocalUser,+ saveJustSignedUp,+} from "ente-accounts-rs/services/accounts-db";+import { appHomeRoute } from "ente-accounts-rs/services/redirect";+import {+ generateSRPSetupAttributes,+ getAndSaveSRPAttributes,+ setupSRP,+} from "ente-accounts-rs/services/srp";+import {+ generateAndSaveInteractiveKeyAttributes,+ generateKeysAndAttributes,+ putUserKeyAttributes,+} from "ente-accounts-rs/services/user";+import { LinkButton } from "ente-base/components/LinkButton";+import { LoadingIndicator } from "ente-base/components/loaders";+import { useBaseContext } from "ente-base/context";+import { deriveKeyInsufficientMemoryErrorMessage } from "ente-accounts-rs/services/crypto";+import log from "ente-base/log";+import {+ haveMasterKeyInSession,+ saveMasterKeyInSessionAndSafeStore,+} from "ente-accounts-rs/services/session-storage";+import { t } from "i18next";+import { useRouter } from "next/router";+import { useCallback, useEffect, useState } from "react";+import {+ NewPasswordForm,+ type NewPasswordFormProps,+} from "../components/NewPasswordForm";++/**+ * A page that allows the user to generate key attributes if needed, and shows+ * them their recovery key if they just signed up.+ *+ * See: [Note: Login pages]+ */+const Page: React.FC = () => {+ const { logout, showMiniDialog } = useBaseContext();++ const [userEmail, setUserEmail] = useState("");+ const [openRecoveryKey, setOpenRecoveryKey] = useState(false);++ const router = useRouter();++ useEffect(() => {+ const user = savedPartialLocalUser();+ if (!user?.email || !user.token) {+ void router.replace("/");+ } else if (haveMasterKeyInSession()) {+ if (savedJustSignedUp()) {+ setOpenRecoveryKey(true);+ } else {+ void router.replace(appHomeRoute);+ }+ } else if (savedOriginalKeyAttributes()) {+ void router.replace("/credentials");+ } else {+ setUserEmail(user.email);+ }+ }, [router]);++ const handleSubmit: NewPasswordFormProps["onSubmit"] = useCallback(+ async (password, setPasswordsFieldError) => {+ try {+ const { masterKey, kek, keyAttributes } =+ await generateKeysAndAttributes(password);+ await putUserKeyAttributes(keyAttributes);+ await setupSRP(await generateSRPSetupAttributes(kek));+ await getAndSaveSRPAttributes(userEmail);+ await generateAndSaveInteractiveKeyAttributes(+ password,+ keyAttributes,+ masterKey,+ );+ await saveMasterKeyInSessionAndSafeStore(masterKey);+ saveJustSignedUp();+ setOpenRecoveryKey(true);+ } catch (e) {+ log.error("Could not generate key attributes from password", e);+ setPasswordsFieldError(+ e instanceof Error &&+ e.message == deriveKeyInsufficientMemoryErrorMessage+ ? t("password_generation_failed")+ : t("generic_error"),+ );+ }+ },+ [userEmail],+ );++ return (+ <>+ {openRecoveryKey ? (+ <RecoveryKey+ open={openRecoveryKey}+ onClose={() => void router.push(appHomeRoute)}+ showMiniDialog={showMiniDialog}+ />+ ) : userEmail ? (+ <AccountsPageContents>+ <AccountsPageTitle>{t("set_password")}</AccountsPageTitle>+ <NewPasswordForm+ userEmail={userEmail}+ submitButtonTitle={t("set_password")}+ onSubmit={handleSubmit}+ />+ <Divider sx={{ mt: 1 }} />+ <AccountsPageFooter>+ <LinkButton onClick={logout}>{t("go_back")}</LinkButton>+ </AccountsPageFooter>+ </AccountsPageContents>+ ) : (+ <LoadingIndicator />+ )}+ </>+ );+};++export default Page;diff --git a/web/packages/accounts-rs/pages/login.tsx b/web/packages/accounts-rs/pages/login.tsxnew file mode 100644index 0000000000..f722876666--- /dev/null+++ b/web/packages/accounts-rs/pages/login.tsx@@ -0,0 +1,161 @@+import { AccountsPageContents } from "ente-accounts-rs/components/layouts/centered-paper";+import { LoginContents } from "ente-accounts-rs/components/LoginContents";+import { savedPartialLocalUser } from "ente-accounts-rs/services/accounts-db";+import { LoadingIndicator } from "ente-base/components/loaders";+import { customAPIHost } from "ente-base/origins";+import { useRouter } from "next/router";+import React, { useCallback, useEffect, useState } from "react";++/**+ * A page that allows the user to login into their existing Ente account.+ *+ * [Note: Login pages]+ *+ * There are multiple pages that comprise the login flow, with redirects amongst+ * themselves depending on various scenarios and partial login states.+ *+ * - "/signup" - A page that allows the user to signup for a new Ente account.+ *+ * - Redirects to "/login" if the user chooses the "already have an account"+ * option.+ *+ * - Redirects to "/verify" if there is already an `email` present in the+ * saved partial local user, or after obtaining the email.+ *+ * - "/login" - A page that allows the user to login into their existing Ente+ * account.+ *+ * - Redirects to "/signup" if the user chooses the "create new account"+ * option.+ *+ * - Redirects to "/verify" if there is already an `email` present in the+ * saved partial local user, or after obtaining the email if the user's has+ * enabled email verification for their account.+ *+ * - Redirects to "/credentials" after obtaining the email if the user has not+ * enabled email verification for their account.+ *+ * - "/verify" - A page that allows the user to verify their email.+ *+ * - Redirects to "/" if there is no `email` present in the saved partial+ * local user.+ *+ * - Redirects to "/credentials" if both saved key attributes and a `token`+ * (or `encryptedToken`) in present in the saved partial local user, or if+ * email verification is not needed, or when email verification completes+ * and remote sent us key attributes (which will happen on login).+ *+ * - Redirects to "/generate" once email verification is complete and the user+ * does not have key attributes (which will happen for new signups).+ *+ * - Redirects to "/two-factor/verify" when email verification completes and+ * the user has setup a TOTP second factor that also needs to be verified.+ *+ * - Redirects to the passkey app when email verification completes and the+ * user has setup a passkey that also needs to be verified. Before+ * redirecting, `inflightPasskeySessionID` in saved in session storage.+ *+ * - "/credentials" - A page that allows the user to enter their password to+ * authenticate (initial login) or reauthenticate (new web app tab)+ *+ * - Redirects to "/" if there is no `email` present in the saved partial+ * local user.+ *+ * - Redirects to "/two-factor/verify" if saved key attributes are not present+ * once password is verified and the user has setup a TOTP second factor+ * that also needs to be verified.+ *+ * - Redirects to the passkey app once password is verified if saved key+ * attributes are not present if the user has setup a passkey that also+ * needs to be verified. Before redirecting, `inflightPasskeySessionID` is+ * saved in session storage.+ *+ * - Redirects to the `appHomeRoute` otherwise (e.g. /gallery). **The flow is+ * complete**.+ *+ * - "/generate" - A page that allows the user to generate key attributes if+ * needed, and shows them their recovery key if they just signed up.+ *+ * - Redirects to "/" if there is no `email` or `token` present in the saved+ * partial user.+ *+ * - Redirects to `appHomeRoute` after viewing the recovery key if they have a+ * master key in session, or after setting the password and then viewing the+ * recovery key (if they did not have a master key in session store).+ *+ * - Redirects to "/credentials" if if they don't have a master key in session+ * store but have saved original key attributes.+ *+ * - "/recover" - A page that allows the user to recover their master key using+ * their recovery key.+ *+ * - Redirects to "/" if there is no `email` present in the saved partial+ * local user.+ *+ * - Redirects to "/verify" if there is no `encryptedToken` (or `token`)+ * present in the saved partial local user.+ *+ * - Redirects to "/generate" if there are no saved key attributes.+ *+ * - Redirects to "/change-password" once the recovery key is verified.+ *+ * - "/change-password" - A page that allows the user to reset their password.+ *+ * - Redirects to "/" if there is no `email` present in the saved partial+ * user, and after successfully changing the password.+ *+ * - "/two-factor/verify" - A page that allows the user to verify their TOTP+ * based second factor.+ *+ * - Redirects to "/" if there is no `email` or `twoFactorSessionID` in the+ * saved partial local user.+ *+ * - Redirects to "/credentials" if `isTwoFactorEnabled` is not `true` and+ * either of `encryptedToken` or `token` is present in the saved partial+ * local user.+ *+ * - "/passkeys/finish" - A page where the accounts app hands off control back+ * to us (the calling app) once the passkey has been verified.+ *+ * - Redirects to "/" if there is no matching `inflightPasskeySessionID` in+ * session storage.+ *+ * - Redirects to "/credentials" otherwise.+ *+ * - "/two-factor/recover" and "/passkeys/recover" - Pages that allow the user+ * to reset or bypass their second factor if they possess their recovery key.+ * Both pages work similarly, except for the second factor they act on.+ *+ * - Redirect to "/" if there is no `email` or `twoFactorSessionID` /+ * `passkeySessionID` in the saved partial local user.+ *+ * - Redirect to "/generate" if there is an `encryptedToken` or `token` in the+ * saved partial local user.+ *+ * - Redirect to "/credentials" after recovery.+ *+ */+const Page: React.FC = () => {+ const [loading, setLoading] = useState(true);+ const [host, setHost] = useState<string | undefined>(undefined);++ const router = useRouter();++ useEffect(() => {+ void customAPIHost().then(setHost);+ if (savedPartialLocalUser()?.email) void router.replace("/verify");+ setLoading(false);+ }, [router]);++ const onSignUp = useCallback(() => void router.push("/signup"), [router]);++ return loading ? (+ <LoadingIndicator />+ ) : (+ <AccountsPageContents>+ <LoginContents {...{ host, onSignUp }} />+ </AccountsPageContents>+ );+};++export default Page;diff --git a/web/packages/accounts-rs/pages/passkeys/finish.tsx b/web/packages/accounts-rs/pages/passkeys/finish.tsxnew file mode 100644index 0000000000..9ed9f456a7--- /dev/null+++ b/web/packages/accounts-rs/pages/passkeys/finish.tsx@@ -0,0 +1,106 @@+import {+ saveKeyAttributes,+ updateSavedLocalUser,+} from "ente-accounts-rs/services/accounts-db";+import { clearInflightPasskeySessionID } from "ente-accounts-rs/services/passkey";+import { unstashRedirect } from "ente-accounts-rs/services/redirect";+import {+ resetSavedLocalUserTokens,+ TwoFactorAuthorizationResponse,+} from "ente-accounts-rs/services/user";+import { LoadingIndicator } from "ente-base/components/loaders";+import { fromB64URLSafeNoPadding } from "ente-accounts-rs/services/crypto";+import log from "ente-base/log";+import { nullToUndefined } from "ente-utils/transform";+import { useRouter } from "next/router";+import React, { useEffect } from "react";++/**+ * The page where the accounts app hands back control to us once the passkey has+ * been verified.+ *+ * See: [Note: Login pages]+ *+ * [Note: Finish passkey flow in the requesting app]+ *+ * The passkey finish step needs to happen in the context of the client which+ * invoked the passkey flow since it needs to save the obtained credentials+ * in local storage (which is tied to the current origin).+ */+const Page: React.FC = () => {+ const router = useRouter();++ useEffect(() => {+ // Extract response from query params.+ const searchParams = new URLSearchParams(window.location.search);+ const passkeySessionID = searchParams.get("passkeySessionID");+ const response = searchParams.get("response");+ if (!passkeySessionID || !response) return;++ void saveQueryCredentialsAndNavigateTo(passkeySessionID, response).then(+ (slug) => router.replace(slug),+ );+ }, [router]);++ return <LoadingIndicator />;+};++export default Page;++/**+ * Extract credentials from a successful passkey flow "response" query parameter+ * and save them to local storage for use by subsequent steps (or normal+ * functioning) of the app.+ *+ * @param passkeySessionID The string that is passed as the "passkeySessionID"+ * query parameter to us.+ *+ * @param response The string that is passed as the "response" query parameter to+ * us (we're the final "finish" page in the passkey flow).+ *+ * @returns the slug that we should navigate to now.+ */+const saveQueryCredentialsAndNavigateTo = async (+ passkeySessionID: string,+ response: string,+) => {+ // This function's implementation is on the same lines as that of the+ // `saveCredentialsAndNavigateTo` function in passkey utilities.+ //+ // See: [Note: Ending the passkey flow]++ const inflightPasskeySessionID = nullToUndefined(+ sessionStorage.getItem("inflightPasskeySessionID"),+ );++ if (+ !inflightPasskeySessionID ||+ passkeySessionID != inflightPasskeySessionID+ ) {+ // This is not the princess we were looking for. However, we have+ // already entered this castle. Redirect back to home without changing+ // any state, hopefully this will get the user back to where they were.+ log.info(+ `Ignoring redirect for unexpected passkeySessionID ${passkeySessionID}`,+ );+ return "/";+ }++ clearInflightPasskeySessionID();++ // Decode response string (inverse of the steps we perform in+ // `passkeyAuthenticationSuccessRedirectURL`).+ const decodedResponse = TwoFactorAuthorizationResponse.parse(+ JSON.parse(+ new TextDecoder().decode(await fromB64URLSafeNoPadding(response)),+ ),+ );++ const { id, keyAttributes, encryptedToken } = decodedResponse;++ await resetSavedLocalUserTokens(id, encryptedToken);+ updateSavedLocalUser({ passkeySessionID: undefined });+ saveKeyAttributes(keyAttributes);++ return unstashRedirect() ?? "/credentials";+};diff --git a/web/packages/accounts-rs/pages/passkeys/recover.tsx b/web/packages/accounts-rs/pages/passkeys/recover.tsxnew file mode 100644index 0000000000..6d29d53c6a--- /dev/null+++ b/web/packages/accounts-rs/pages/passkeys/recover.tsx@@ -0,0 +1,5 @@+import Page_ from "../two-factor/recover";++const Page = () => <Page_ twoFactorType="passkey" />;++export default Page;diff --git a/web/packages/accounts-rs/pages/recover.tsx b/web/packages/accounts-rs/pages/recover.tsxnew file mode 100644index 0000000000..3d526bbcaf--- /dev/null+++ b/web/packages/accounts-rs/pages/recover.tsx@@ -0,0 +1,126 @@+import {+ AccountsPageContents,+ AccountsPageFooter,+ AccountsPageTitle,+} from "ente-accounts-rs/components/layouts/centered-paper";+import {+ savedKeyAttributes,+ savedPartialLocalUser,+} from "ente-accounts-rs/services/accounts-db";+import { recoveryKeyFromMnemonic } from "ente-accounts-rs/services/recovery-key";+import { appHomeRoute, stashRedirect } from "ente-accounts-rs/services/redirect";+import type { KeyAttributes } from "ente-accounts-rs/services/user";+import {+ decryptAndStoreTokenIfNeeded,+ sendOTT,+} from "ente-accounts-rs/services/user";+import { LinkButton } from "ente-base/components/LinkButton";+import {+ SingleInputForm,+ type SingleInputFormProps,+} from "ente-base/components/SingleInputForm";+import { useBaseContext } from "ente-base/context";+import { decryptBox } from "ente-accounts-rs/services/crypto";+import log from "ente-base/log";+import {+ haveMasterKeyInSession,+ saveMasterKeyInSessionAndSafeStore,+} from "ente-accounts-rs/services/session-storage";+import { t } from "i18next";+import { useRouter } from "next/router";+import { useCallback, useEffect, useState } from "react";++/**+ * A page that allows the user to enter their recovery key to recover their+ * master key if they've forgotten their password.+ *+ * See: [Note: Login pages]+ */+const Page: React.FC = () => {+ const { showMiniDialog } = useBaseContext();++ const [keyAttributes, setKeyAttributes] = useState<+ KeyAttributes | undefined+ >(undefined);++ const router = useRouter();++ useEffect(() => {+ void (async () => {+ const user = savedPartialLocalUser();+ if (!user?.email) {+ await router.replace("/");+ return;+ }++ if (!user.encryptedToken && !user.token) {+ await sendOTT(user.email, undefined);+ stashRedirect("/recover");+ await router.replace("/verify");+ return;+ }++ const keyAttributes = savedKeyAttributes();+ if (!keyAttributes) {+ await router.replace("/generate");+ } else if (haveMasterKeyInSession()) {+ await router.replace(appHomeRoute);+ } else {+ setKeyAttributes(keyAttributes);+ }+ })();+ }, [router]);++ const handleSubmit: SingleInputFormProps["onSubmit"] = useCallback(+ async (recoveryKeyMnemonic: string, setFieldError) => {+ try {+ const keyAttr = keyAttributes!;+ const masterKey = await decryptBox(+ {+ encryptedData:+ keyAttr.masterKeyEncryptedWithRecoveryKey!,+ nonce: keyAttr.masterKeyDecryptionNonce!,+ },+ await recoveryKeyFromMnemonic(recoveryKeyMnemonic),+ );+ await saveMasterKeyInSessionAndSafeStore(masterKey);+ await decryptAndStoreTokenIfNeeded(keyAttr, masterKey);++ void router.push("/change-password?op=reset");+ } catch (e) {+ log.error("Master key recovery failed", e);+ setFieldError(t("incorrect_recovery_key"));+ }+ },+ [router, keyAttributes],+ );++ const showNoRecoveryKeyMessage = useCallback(() => {+ showMiniDialog({+ title: t("sorry"),+ message: t("no_recovery_key_message"),+ continue: { color: "secondary" },+ cancel: false,+ });+ }, [showMiniDialog]);++ return (+ <AccountsPageContents>+ <AccountsPageTitle>{t("recover_account")}</AccountsPageTitle>+ <SingleInputForm+ autoComplete="off"+ label={t("recovery_key")}+ submitButtonTitle={t("recover")}+ onSubmit={handleSubmit}+ />+ <AccountsPageFooter>+ <LinkButton onClick={showNoRecoveryKeyMessage}>+ {t("no_recovery_key_title")}+ </LinkButton>+ <LinkButton onClick={router.back}>{t("go_back")}</LinkButton>+ </AccountsPageFooter>+ </AccountsPageContents>+ );+};++export default Page;diff --git a/web/packages/accounts-rs/pages/signup.tsx b/web/packages/accounts-rs/pages/signup.tsxnew file mode 100644index 0000000000..0f6fdd5e97--- /dev/null+++ b/web/packages/accounts-rs/pages/signup.tsx@@ -0,0 +1,37 @@+import { AccountsPageContents } from "ente-accounts-rs/components/layouts/centered-paper";+import { SignUpContents } from "ente-accounts-rs/components/SignUpContents";+import { savedPartialLocalUser } from "ente-accounts-rs/services/accounts-db";+import { LoadingIndicator } from "ente-base/components/loaders";+import { customAPIHost } from "ente-base/origins";+import { useRouter } from "next/router";+import React, { useCallback, useEffect, useState } from "react";++/**+ * A page that allows the user to signup for a new Ente account.+ *+ * See: [Note: Login pages]+ */+const Page: React.FC = () => {+ const [loading, setLoading] = useState(true);+ const [host, setHost] = useState<string | undefined>(undefined);++ const router = useRouter();++ useEffect(() => {+ void customAPIHost().then(setHost);+ if (savedPartialLocalUser()?.email) void router.replace("/verify");+ setLoading(false);+ }, [router]);++ const onLogin = useCallback(() => void router.push("/login"), [router]);++ return loading ? (+ <LoadingIndicator />+ ) : (+ <AccountsPageContents>+ <SignUpContents {...{ router, host, onLogin }} />+ </AccountsPageContents>+ );+};++export default Page;diff --git a/web/packages/accounts-rs/pages/two-factor/recover.tsx b/web/packages/accounts-rs/pages/two-factor/recover.tsxnew file mode 100644index 0000000000..ece6e90fe5--- /dev/null+++ b/web/packages/accounts-rs/pages/two-factor/recover.tsx@@ -0,0 +1,145 @@+import { Link } from "@mui/material";+import {+ AccountsPageContents,+ AccountsPageFooter,+ AccountsPageTitle,+} from "ente-accounts-rs/components/layouts/centered-paper";+import { savedPartialLocalUser } from "ente-accounts-rs/services/accounts-db";+import {+ getRecoverTwoFactor,+ recoverTwoFactorFinish,+ type TwoFactorRecoveryResponse,+ type TwoFactorType,+} from "ente-accounts-rs/services/user";+import { LinkButton } from "ente-base/components/LinkButton";+import { LoadingIndicator } from "ente-base/components/loaders";+import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";+import {+ SingleInputForm,+ type SingleInputFormProps,+} from "ente-base/components/SingleInputForm";+import { useBaseContext } from "ente-base/context";+import { isHTTP4xxError, isHTTPErrorWithStatus } from "ente-base/http";+import log from "ente-base/log";+import { t } from "i18next";+import { useRouter } from "next/router";+import { useCallback, useEffect, useMemo, useState } from "react";+import { Trans } from "react-i18next";++export interface RecoverPageProps {+ twoFactorType: TwoFactorType;+}++/**+ * A page where the user can enter their recovery key to reset or bypass their+ * second factor in case they no longer have access to it.+ */+const Page: React.FC<RecoverPageProps> = ({ twoFactorType }) => {+ const { logout, showMiniDialog, onGenericError } = useBaseContext();++ const [sessionID, setSessionID] = useState<string | undefined>(undefined);+ const [recoveryResponse, setRecoveryResponse] = useState<+ TwoFactorRecoveryResponse | undefined+ >(undefined);++ const router = useRouter();++ const showContactSupportDialog = useCallback(+ (dialogContinue?: MiniDialogAttributes["continue"]) =>+ showMiniDialog({+ title: t("contact_support"),+ message: (+ <Trans+ i18nKey={"no_two_factor_recovery_key_message"}+ components={{+ a: <Link href="mailto:[email protected]" />,+ }}+ values={{ emailID: "[email protected]" }}+ />+ ),+ continue: { color: "secondary", ...(dialogContinue ?? {}) },+ cancel: false,+ }),+ [showMiniDialog],+ );++ useEffect(() => {+ void (async () => {+ const user = savedPartialLocalUser();+ const sessionID =+ twoFactorType == "passkey"+ ? user?.passkeySessionID+ : user?.twoFactorSessionID;+ if (!user?.email || !sessionID) {+ await router.replace("/");+ } else if (user.encryptedToken || user.token) {+ await router.replace("/generate");+ } else {+ setSessionID(sessionID);+ try {+ setRecoveryResponse(+ await getRecoverTwoFactor(twoFactorType, sessionID),+ );+ } catch (e) {+ log.error("Second factor recovery page setup failed", e);+ if (isHTTPErrorWithStatus(e, 404)) {+ logout();+ } else if (isHTTP4xxError(e)) {+ showContactSupportDialog({ action: router.back });+ } else {+ onGenericError(e);+ }+ }+ }+ })();+ }, [+ twoFactorType,+ logout,+ showContactSupportDialog,+ onGenericError,+ router,+ ]);++ const handleSubmit: SingleInputFormProps["onSubmit"] | undefined = useMemo(+ () =>+ sessionID && recoveryResponse+ ? (recoveryKeyMnemonic, setFieldError) =>+ recoverTwoFactorFinish(+ twoFactorType,+ sessionID,+ recoveryResponse,+ recoveryKeyMnemonic,+ )+ .then(() => router.push("/credentials"))+ .catch((e: unknown) => {+ log.error("Second factor recovery failed", e);+ setFieldError(t("incorrect_recovery_key"));+ })+ : undefined,+ [twoFactorType, router, sessionID, recoveryResponse],+ );++ if (!handleSubmit) {+ return <LoadingIndicator />;+ }++ return (+ <AccountsPageContents>+ <AccountsPageTitle>{t("recover_two_factor")}</AccountsPageTitle>+ <SingleInputForm+ autoComplete="off"+ label={t("recovery_key")}+ submitButtonTitle={t("recover")}+ onSubmit={handleSubmit}+ />+ <AccountsPageFooter>+ <LinkButton onClick={() => showContactSupportDialog()}>+ {t("no_recovery_key_title")}+ </LinkButton>+ <LinkButton onClick={router.back}>{t("go_back")}</LinkButton>+ </AccountsPageFooter>+ </AccountsPageContents>+ );+};++export default Page;diff --git a/web/packages/accounts-rs/pages/two-factor/setup.tsx b/web/packages/accounts-rs/pages/two-factor/setup.tsxnew file mode 100644index 0000000000..d75cead67a--- /dev/null+++ b/web/packages/accounts-rs/pages/two-factor/setup.tsx@@ -0,0 +1,176 @@+import { Paper, Stack, styled, Typography } from "@mui/material";+import { CodeBlock } from "ente-accounts-rs/components/CodeBlock";+import { Verify2FACodeForm } from "ente-accounts-rs/components/Verify2FACodeForm";+import { appHomeRoute } from "ente-accounts-rs/services/redirect";+import type { TwoFactorSecret } from "ente-accounts-rs/services/user";+import {+ setupTwoFactor,+ setupTwoFactorFinish,+} from "ente-accounts-rs/services/user";+import { CenteredFill } from "ente-base/components/containers";+import { EnteLogo } from "ente-base/components/EnteLogo";+import { LinkButton } from "ente-base/components/LinkButton";+import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";+import { NavbarBase } from "ente-base/components/Navbar";+import { t } from "i18next";+import { useRouter } from "next/router";+import React, { useEffect, useState } from "react";++const Page: React.FC = () => {+ const [twoFactorSecret, setTwoFactorSecret] = useState<+ TwoFactorSecret | undefined+ >();++ const router = useRouter();++ useEffect(() => {+ void setupTwoFactor().then(setTwoFactorSecret);+ }, []);++ const handleSubmit = async (otp: string) => {+ await setupTwoFactorFinish(twoFactorSecret!.secretCode, otp);+ await router.push(appHomeRoute);+ };++ return (+ <Stack+ sx={[+ { minHeight: "100svh", bgcolor: "secondary.main" },+ (theme) =>+ theme.applyStyles("dark", {+ bgcolor: "background.default",+ }),+ ]}+ >+ <NavbarBase+ sx={{+ boxShadow: "none",+ borderBottom: "none",+ bgcolor: "transparent",+ }}+ >+ <EnteLogo />+ </NavbarBase>+ <CenteredFill>+ <ContentsPaper>+ <Typography variant="h5" sx={{ textAlign: "center" }}>+ {t("two_factor")}+ </Typography>+ <Instructions twoFactorSecret={twoFactorSecret} />+ <Verify2FACodeForm+ onSubmit={handleSubmit}+ submitButtonText={t("enable")}+ />+ <Stack sx={{ alignItems: "center" }}>+ <FocusVisibleButton+ variant="text"+ onClick={router.back}+ >+ {t("go_back")}+ </FocusVisibleButton>+ </Stack>+ </ContentsPaper>+ </CenteredFill>+ </Stack>+ );+};++export default Page;++const ContentsPaper = styled(Paper)(({ theme }) => ({+ marginBlock: theme.spacing(2),+ padding: theme.spacing(5, 3),+ [theme.breakpoints.up("sm")]: { padding: theme.spacing(5) },+ // Wide enough to fit the QR code secret in one line under default settings.+ width: "min(440px, 85vw)",+ minHeight: "375px",+ display: "flex",+ flexDirection: "column",+ gap: theme.spacing(4),+ boxShadow: "none",+ borderRadius: "20px",+}));++interface InstructionsProps {+ twoFactorSecret: TwoFactorSecret | undefined;+}++const Instructions: React.FC<InstructionsProps> = ({ twoFactorSecret }) => {+ const [setupMode, setSetupMode] = useState<"qr" | "manual">("qr");++ return (+ <Stack sx={{ gap: 3, alignItems: "center" }}>+ {setupMode == "qr" ? (+ <SetupQRMode+ twoFactorSecret={twoFactorSecret}+ onChangeMode={() => setSetupMode("manual")}+ />+ ) : (+ <SetupManualMode+ twoFactorSecret={twoFactorSecret}+ onChangeMode={() => setSetupMode("qr")}+ />+ )}+ </Stack>+ );+};++interface SetupManualModeProps {+ twoFactorSecret: TwoFactorSecret | undefined;+ onChangeMode: () => void;+}++const SetupManualMode: React.FC<SetupManualModeProps> = ({+ twoFactorSecret,+ onChangeMode,+}) => (+ <>+ <Typography sx={{ color: "text.muted", textAlign: "center", px: 2 }}>+ {t("two_factor_manual_entry_message")}+ </Typography>+ <CodeBlock code={twoFactorSecret?.secretCode} />+ <LinkButton onClick={onChangeMode}>{t("scan_qr_title")}</LinkButton>+ </>+);++interface SetupQRModeProps {+ twoFactorSecret?: TwoFactorSecret;+ onChangeMode: () => void;+}++const SetupQRMode: React.FC<SetupQRModeProps> = ({+ twoFactorSecret,+ onChangeMode,+}) => (+ <>+ <Typography sx={{ color: "text.muted", textAlign: "center" }}>+ {t("two_factor_qr_help")}+ </Typography>+ {twoFactorSecret ? (+ <QRCode src={`data:image/png;base64,${twoFactorSecret.qrCode}`} />+ ) : (+ <LoadingQRCode>+ <ActivityIndicator />+ </LoadingQRCode>+ )}+ <LinkButton onClick={onChangeMode}>+ {t("two_factor_manual_entry_title")}+ </LinkButton>+ </>+);++const QRCode = styled("img")(`+ width: 200px;+ height: 200px;+`);++const LoadingQRCode = styled(Stack)(+ ({ theme }) => `+ width: 200px;+ height: 200px;+ border: 1px solid ${theme.vars.palette.stroke.muted};+ align-items: center;+ justify-content: center;+ `,+);diff --git a/web/packages/accounts-rs/pages/two-factor/verify.tsx b/web/packages/accounts-rs/pages/two-factor/verify.tsxnew file mode 100644index 0000000000..67c70eba63--- /dev/null+++ b/web/packages/accounts-rs/pages/two-factor/verify.tsx@@ -0,0 +1,87 @@+import { Verify2FACodeForm } from "ente-accounts-rs/components/Verify2FACodeForm";+import {+ savedPartialLocalUser,+ saveKeyAttributes,+ updateSavedLocalUser,+} from "ente-accounts-rs/services/accounts-db";+import {+ resetSavedLocalUserTokens,+ verifyTwoFactor,+} from "ente-accounts-rs/services/user";+import { LinkButton } from "ente-base/components/LinkButton";+import { useBaseContext } from "ente-base/context";+import { isHTTPErrorWithStatus } from "ente-base/http";+import { t } from "i18next";+import { useRouter } from "next/router";+import { useCallback, useEffect, useState } from "react";+import {+ AccountsPageContents,+ AccountsPageFooter,+ AccountsPageTitle,+} from "../../components/layouts/centered-paper";+import { unstashRedirect } from "../../services/redirect";++/**+ * A page that allows the user to verify their TOTP based second factor.+ *+ * See: [Note: Login pages]+ */+const Page: React.FC = () => {+ const { logout } = useBaseContext();++ const [twoFactorSessionID, setTwoFactorSessionID] = useState("");++ const router = useRouter();++ useEffect(() => {+ const user = savedPartialLocalUser();+ if (!user?.email || !user.twoFactorSessionID) {+ void router.replace("/");+ } else if (+ !user.isTwoFactorEnabled &&+ (user.encryptedToken || user.token)+ ) {+ void router.replace("/credentials");+ } else {+ setTwoFactorSessionID(user.twoFactorSessionID);+ }+ }, [router]);++ const handleSubmit = useCallback(+ async (otp: string) => {+ try {+ const { keyAttributes, encryptedToken, id } =+ await verifyTwoFactor(otp, twoFactorSessionID);+ await resetSavedLocalUserTokens(id, encryptedToken);+ updateSavedLocalUser({ twoFactorSessionID: undefined });+ saveKeyAttributes(keyAttributes);+ await router.push(unstashRedirect() ?? "/credentials");+ } catch (e) {+ if (isHTTPErrorWithStatus(e, 404)) {+ logout();+ } else {+ throw e;+ }+ }+ },+ [logout, router, twoFactorSessionID],+ );++ return (+ <AccountsPageContents>+ <AccountsPageTitle>{t("two_factor")}</AccountsPageTitle>+ <Verify2FACodeForm+ onSubmit={handleSubmit}+ submitButtonText={t("verify")}+ />+ <AccountsPageFooter>+ <LinkButton onClick={() => router.push("/two-factor/recover")}>+ {t("lost_2fa_device")}+ </LinkButton>+ <LinkButton onClick={logout}>{t("change_email")}</LinkButton>+ </AccountsPageFooter>+ </AccountsPageContents>+ );+};++export default Page;diff --git a/web/packages/accounts-rs/pages/verify.tsx b/web/packages/accounts-rs/pages/verify.tsxnew file mode 100644index 0000000000..d5440a3c6d--- /dev/null+++ b/web/packages/accounts-rs/pages/verify.tsx@@ -0,0 +1,293 @@+import { Box, Typography } from "@mui/material";+import {+ AccountsPageContents,+ AccountsPageFooter,+ AccountsPageTitle,+} from "ente-accounts-rs/components/layouts/centered-paper";+import { VerifyingPasskey } from "ente-accounts-rs/components/LoginComponents";+import { SecondFactorChoice } from "ente-accounts-rs/components/SecondFactorChoice";+import { useSecondFactorChoiceIfNeeded } from "ente-accounts-rs/components/utils/second-factor-choice";+import {+ replaceSavedLocalUser,+ savedKeyAttributes,+ savedOriginalKeyAttributes,+ savedPartialLocalUser,+ savedSRPAttributes,+ saveIsFirstLogin,+ saveKeyAttributes,+ saveOriginalKeyAttributes,+ unstashAfterUseSRPSetupAttributes,+ unstashReferralSource,+ updateSavedLocalUser,+} from "ente-accounts-rs/services/accounts-db";+import {+ openPasskeyVerificationURL,+ passkeyVerificationRedirectURL,+} from "ente-accounts-rs/services/passkey";+import {+ stashedRedirect,+ unstashRedirect,+} from "ente-accounts-rs/services/redirect";+import {+ getAndSaveSRPAttributes,+ getSRPAttributes,+ setupSRP,+} from "ente-accounts-rs/services/srp";+import {+ putUserKeyAttributes,+ sendOTT,+ verifyEmail,+} from "ente-accounts-rs/services/user";+import { LinkButton } from "ente-base/components/LinkButton";+import { LoadingIndicator } from "ente-base/components/loaders";+import {+ SingleInputForm,+ type SingleInputFormProps,+} from "ente-base/components/SingleInputForm";+import { useBaseContext } from "ente-base/context";+import { isHTTPErrorWithStatus } from "ente-base/http";+import log from "ente-base/log";+import { clearSessionStorage } from "ente-accounts-rs/services/session-storage";+import { saveAuthToken } from "ente-base/token";+import { t } from "i18next";+import { useRouter } from "next/router";+import { useCallback, useEffect, useState } from "react";+import { Trans } from "react-i18next";++/**+ * A page that allows the user to verify their email.+ *+ * See: [Note: Login pages]+ */+const Page: React.FC = () => {+ const { logout, showMiniDialog } = useBaseContext();++ const [email, setEmail] = useState("");+ const [resend, setResend] = useState<"enable" | "sending" | "sent">(+ "enable",+ );+ const [passkeyVerificationData, setPasskeyVerificationData] = useState<+ { passkeySessionID: string; url: string } | undefined+ >();++ const {+ secondFactorChoiceProps,+ userVerificationResultAfterResolvingSecondFactorChoice,+ } = useSecondFactorChoiceIfNeeded();++ const router = useRouter();++ useEffect(() => {+ void redirectionIfNeededOrEmail().then((redirectOrEmail) => {+ if (typeof redirectOrEmail == "string") {+ void router.replace(redirectOrEmail);+ } else {+ setEmail(redirectOrEmail.email);+ }+ });+ }, [router]);++ const onSubmit: SingleInputFormProps["onSubmit"] = async (+ ott,+ setFieldError,+ ) => {+ try {+ const referralSource = unstashReferralSource();+ const cleanedReferral = referralSource+ ? `web:${referralSource}`+ : undefined;+ const {+ keyAttributes,+ encryptedToken,+ token,+ id,+ twoFactorSessionID,+ passkeySessionID,+ accountsUrl,+ } = await userVerificationResultAfterResolvingSecondFactorChoice(+ await verifyEmail(email, ott, cleanedReferral),+ );++ // The following flow is similar to (but not the same) as what+ // happens after `verifySRP` in the `/credentials` page.++ if (passkeySessionID) {+ updateSavedLocalUser({ passkeySessionID });+ saveIsFirstLogin();+ const url = passkeyVerificationRedirectURL(+ accountsUrl!,+ passkeySessionID,+ );+ setPasskeyVerificationData({ passkeySessionID, url });+ openPasskeyVerificationURL({ passkeySessionID, url });+ } else if (twoFactorSessionID) {+ updateSavedLocalUser({+ isTwoFactorEnabled: true,+ twoFactorSessionID,+ });+ saveIsFirstLogin();+ void router.push("/two-factor/verify");+ } else {+ if (token) await saveAuthToken(token);+ replaceSavedLocalUser({ id, email, token, encryptedToken });+ if (keyAttributes) {+ saveKeyAttributes(keyAttributes);+ saveOriginalKeyAttributes(keyAttributes);+ } else {+ const originalKeyAttributes = savedOriginalKeyAttributes();+ if (originalKeyAttributes) {+ await putUserKeyAttributes(originalKeyAttributes);+ }+ await unstashAfterUseSRPSetupAttributes(setupSRP);+ await getAndSaveSRPAttributes(email);+ }+ saveIsFirstLogin();+ if (keyAttributes) {+ clearSessionStorage();+ void router.push(unstashRedirect() ?? "/credentials");+ } else {+ void router.push(unstashRedirect() ?? "/generate");+ }+ }+ } catch (e) {+ if (isHTTPErrorWithStatus(e, 401)) {+ setFieldError(t("invalid_code_error"));+ } else if (isHTTPErrorWithStatus(e, 410)) {+ setFieldError(t("expired_code_error"));+ } else {+ log.error("OTT verification failed", e);+ throw e;+ }+ }+ };++ const resendEmail = useCallback(async () => {+ setResend("sending");+ await sendOTT(email, undefined);+ setResend("sent");+ setTimeout(() => setResend("enable"), 3000);+ }, [email]);++ if (!email) {+ return <LoadingIndicator />;+ }++ if (passkeyVerificationData) {+ // We only need to handle this scenario when running in the desktop app+ // because the web app will navigate to Passkey verification URL.+ // However, still we add an additional `globalThis.electron` check to+ // show a spinner. This prevents the VerifyingPasskey component from+ // being disorientingly shown for a fraction of a second as the redirect+ // happens on the web app.+ //+ // See: [Note: Passkey verification in the desktop app]++ if (!globalThis.electron) {+ return <LoadingIndicator />;+ }++ return (+ <VerifyingPasskey+ email={email}+ passkeySessionID={passkeyVerificationData.passkeySessionID}+ onRetry={() =>+ openPasskeyVerificationURL(passkeyVerificationData)+ }+ {...{ logout, showMiniDialog }}+ />+ );+ }++ return (+ <AccountsPageContents>+ <AccountsPageTitle>+ <Trans+ i18nKey="email_sent"+ components={{+ a: (+ <Box+ component={"span"}+ sx={{+ color: "text.muted",+ wordBreak: "break-word",+ }}+ />+ ),+ }}+ values={{ email }}+ />+ </AccountsPageTitle>++ <Typography variant="small" sx={{ color: "text.muted", mb: 2 }}>+ {t("check_inbox_hint")}+ </Typography>+ <SingleInputForm+ autoComplete="one-time-code"+ label={t("verification_code")}+ submitButtonTitle={t("verify")}+ onSubmit={onSubmit}+ />++ <AccountsPageFooter>+ {resend == "enable" && (+ <LinkButton onClick={resendEmail}>+ {t("resend_code")}+ </LinkButton>+ )}+ {resend == "sending" && <span>{t("status_sending")}</span>}+ {resend == "sent" && <span>{t("status_sent")}</span>}+ <LinkButton onClick={logout}>{t("change_email")}</LinkButton>+ </AccountsPageFooter>++ <SecondFactorChoice {...secondFactorChoiceProps} />+ </AccountsPageContents>+ );+};++export default Page;++/**+ * A function called during page load to see if a redirection is required+ *+ * @returns The slug to redirect to, if needed. Otherwise an object containing+ * the saved partial user's email.+ */+const redirectionIfNeededOrEmail = async () => {+ const user = savedPartialLocalUser();++ const email = user?.email;+ if (!email) {+ return "/";+ }++ if (savedKeyAttributes() && (user.token || user.encryptedToken)) {+ return "/credentials";+ }++ // If we're coming here during the recover flow, do not redirect.+ if (stashedRedirect() == "/recover") return { email };++ // The user might have email verification disabled, but after previously+ // entering their email on the login screen, they might've closed the tab+ // before proceeding (or opened a us in a new tab at this point).+ //+ // In such cases, we'll end up here with an email present.+ //+ // To distinguish this scenario from the normal email verification flow, we+ // can check to see the SRP attributes (the login page would've fetched and+ // saved them). If they are present and indicate that email verification is+ // not required, redirect to the password verification page.++ const srpAttributes = savedSRPAttributes();+ if (srpAttributes && !srpAttributes.isEmailMFAEnabled) {+ // Fetch the latest SRP attributes instead of relying on the potentially+ // stale stored values. This is an infrequent scenario path, so extra+ // API calls are fine.+ const latestSRPAttributes = await getSRPAttributes(email);+ if (latestSRPAttributes && !latestSRPAttributes.isEmailMFAEnabled) {+ return "/credentials";+ }+ }++ return { email };+};diff --git a/web/packages/accounts-rs/services/accounts-db.ts b/web/packages/accounts-rs/services/accounts-db.tsnew file mode 100644index 0000000000..a1b6214674--- /dev/null+++ b/web/packages/accounts-rs/services/accounts-db.ts@@ -0,0 +1,460 @@+/**+ * @file [Note: Accounts DB]+ *+ * The accounts package stores various state both during the login / signup+ * flow, and post login to identify the logged in user.+ *+ * This state is stored in local storage.+ *+ * Most of this state is meant to be transitory - various bits and bobs that we+ * accumulate and want to persist as the user goes through the login or signup+ * flow. One the user is successfully logged in and the first pull has+ * completed, then only a few of these are expected to remain:+ *+ * - "user"+ * - "keyAttributes"+ * - "originalKeyAttributes"+ * - "srpAttributes"+ */++import { savedAuthToken } from "ente-base/token";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";+import {+ RemoteSRPAttributes,+ SRPSetupAttributes,+ type SRPAttributes,+} from "./srp";+import {+ RemoteKeyAttributes,+ type KeyAttributes,+ type LocalUser,+} from "./user";++/**+ * The local storage data about the user before login or signup is complete.+ *+ * [Note: Partial local user]+ *+ * During login or signup, the user object exists in various partial states in+ * local storage.+ *+ * - Initially, there is no user object in local storage.+ *+ * - When the user enters their email, the email property of the stored object+ * is set, but nothing else.+ *+ * - After they verify their password, we have two cases: if second factor+ * verification is not set, and when it is set.+ *+ * - If second factor verification is not set, then after verifying their+ * password their {@link id} and {@link encryptedToken} will get filled in,+ * and {@link isTwoFactorEnabled} will be set to false.+ *+ * - If they have second factor verification set, then after verifying their+ * password {@link isTwoFactorEnabled} and {@link twoFactorSessionID} will+ * also get filled in. Once they verify their TOTP based second factor, their+ * {@link id} and {@link encryptedToken} will also get filled in.+ *+ * - If they have a passkey set as a second factor set, then after verifying+ * their password the {@link passkeySessionID} will be set.+ *+ * - As the login or signup sequence completes, a {@link token} obtained from+ * the {@link encryptedToken} will be written out, and the+ * {@link encryptedToken} cleared since it is not needed anymore.+ *+ * So while the underlying storage is the same, we offer two APIs for code to+ * obtain the user:+ *+ * - Before login is complete, or when it is unknown if login is complete or+ * not, then {@link savedPartialLocalUser} can be used to obtain a+ * {@link PartialLocalUser} with all of its properties set to be optional (and+ * some additional properties not available in the regular user object).+ *+ * - When we know that the login has completed, we can use either+ * {@link savedLocalUser} (which returns `undefined` if our assumption is+ * false) or {@link ensureSavedLocalUser} (which throws if our assumption is+ * false) to obtain an object with all the properties expected to be present+ * for a locally persisted user set to be required.+ */+export interface PartialLocalUser {+ id?: number;+ email?: string;+ token?: string;+ encryptedToken?: string;+ isTwoFactorEnabled?: boolean;+ twoFactorSessionID?: string;+ passkeySessionID?: string;+}++const PartialLocalUser = z.object({+ id: z.number().nullish().transform(nullToUndefined),+ email: z.string().nullish().transform(nullToUndefined),+ token: z.string().nullish().transform(nullToUndefined),+ encryptedToken: z.string().nullish().transform(nullToUndefined),+ isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),+ twoFactorSessionID: z.string().nullish().transform(nullToUndefined),+ passkeySessionID: z.string().nullish().transform(nullToUndefined),+});++/**+ * Zod schema for the {@link LocalUser} TypeScript type.+ *+ * The type itself is in `user.ts`.+ */+const LocalUser = z.object({+ id: z.number(),+ email: z.string(),+ token: z.string(),+ isTwoFactorEnabled: z.boolean().nullish().transform(nullToUndefined),+});++/**+ * Return the local storage value of the user's data.+ *+ * This function is meant to be called during the login or signup sequence.+ * After the user is logged in, use {@link savedLocalUser} or+ * {@link ensureLocalUser} instead.+ *+ * Use {@link replaceSavedLocalUser} to updated the saved value.+ */+export const savedPartialLocalUser = (): PartialLocalUser | undefined => {+ const jsonString = localStorage.getItem("user");+ if (!jsonString) return undefined;+ const result = PartialLocalUser.parse(JSON.parse(jsonString));+ void ensureTokensMatch(result);+ return result;+};++/**+ * Save the users data as we accrue it during the signup or login flow.+ *+ * See: [Note: Partial local user].+ *+ * This method replaces the existing data. Use {@link updateSavedLocalUser} to+ * update selected fields while keeping the other fields as it is.+ */+export const replaceSavedLocalUser = (partialLocalUser: PartialLocalUser) =>+ localStorage.setItem("user", JSON.stringify(partialLocalUser));++/**+ * Partially update the saved user data.+ *+ * This is a delta variant of {@link replaceSavedLocalUser}, which replaces the+ * entire saved object, while this function spreads the provided {@link updates}+ * onto the currently saved value.+ *+ * @param updates A subset of {@link PartialLocalUser} fields that we'd like to+ * update. The other fields, if present in local storage, remain unchanged.+ */+export const updateSavedLocalUser = (updates: Partial<PartialLocalUser>) =>+ replaceSavedLocalUser({ ...savedPartialLocalUser(), ...updates });++/**+ * Return data about the logged-in user, if someone is indeed logged in.+ * Otherwise return `undefined`.+ *+ * The user's data is stored in the browser's localStorage. Thus, this function+ * only works from the main thread, not from web workers since local storage is+ * not accessible to web workers.+ *+ * There is no setter corresponding to this function since this is only a view+ * on data saved using {@link replaceSavedLocalUser} or+ * {@link updateSavedLocalUser}.+ *+ * See: [Note: Partial local user] for more about the whole shebang.+ */+export const savedLocalUser = (): LocalUser | undefined => {+ const jsonString = localStorage.getItem("user");+ if (!jsonString) return undefined;+ // We might have some data, but not all of it. So do a non-throwing parse.+ const { success, data } = LocalUser.safeParse(JSON.parse(jsonString));+ if (success) void ensureTokensMatch(data);+ return success ? data : undefined;+};++/**+ * Sanity check to ensure that KV token and local storage token are the same.+ *+ * TODO: Added July 2025, can just be removed soon, there is already a sanity+ * check `isLocalStorageAndIndexedDBMismatch` on app start (tag: Migration).+ */+export const ensureTokensMatch = async (user: PartialLocalUser | undefined) => {+ if (user?.token !== (await savedAuthToken())) {+ throw new Error("Token mismatch");+ }+};++/**+ * Return true if the user's data is in local storage but not in IndexedDB.+ *+ * This acts a sanity check on IndexedDB by ensuring that if the user has a+ * token in local storage, then it should also be present in IndexedDB.+ */+export const isLocalStorageAndIndexedDBMismatch = async () =>+ savedPartialLocalUser()?.token && !(await savedAuthToken());++/**+ * Return the user's {@link KeyAttributes} if they are present in local storage.+ *+ * The key attributes are stored in the browser's localStorage. Thus, this+ * function only works from the main thread, not from web workers (local storage+ * is not accessible to web workers).+ *+ * See also: [Note: Original vs interactive key attributes]+ */+export const savedKeyAttributes = (): KeyAttributes | undefined => {+ const jsonString = localStorage.getItem("keyAttributes");+ if (!jsonString) return undefined;+ return RemoteKeyAttributes.parse(JSON.parse(jsonString));+};++/**+ * Save the user's {@link KeyAttributes} in local storage.+ *+ * Use {@link savedKeyAttributes} to retrieve them.+ */+export const saveKeyAttributes = (keyAttributes: KeyAttributes) =>+ localStorage.setItem("keyAttributes", JSON.stringify(keyAttributes));++/**+ * Return the user's original {@link KeyAttributes} if they are present in local+ * storage.+ *+ * [Note: Original vs interactive key attributes]+ *+ * This function is similar to {@link savedKeyAttributes} except it returns the+ * user's "original" key attributes. These are the key attributes that were+ * either freshly generated (if the user signed up on this client) or were+ * fetched from remote (otherwise).+ *+ * > NOTE: Currently the code does not guarantee that savedOriginalKeyAttributes+ * > will always be set when savedKeyAttributes is set.+ *+ * In contrast, the regular key attributes get overwritten by the local only+ * interactive key attributes for the user's convenience. See the documentation+ * of {@link generateAndSaveInteractiveKeyAttributes} for more details.+ */+export const savedOriginalKeyAttributes = (): KeyAttributes | undefined => {+ const jsonString = localStorage.getItem("originalKeyAttributes");+ if (!jsonString) return undefined;+ return RemoteKeyAttributes.parse(JSON.parse(jsonString));+};++/**+ * Save the user's {@link KeyAttributes} in local storage.+ *+ * Once saved, these values are not replaced (in contrast with the regular key+ * attributes which can get overwritten with interactive ones).+ *+ * Use {@link savedOriginalKeyAttributes} to retrieve them.+ */+export const saveOriginalKeyAttributes = (keyAttributes: KeyAttributes) =>+ localStorage.setItem(+ "originalKeyAttributes",+ JSON.stringify(keyAttributes),+ );++/**+ * Return the user's {@link SRPAttributes} if they are present in local storage.+ *+ * Like key attributes, SRP attributes are also stored in the browser's local+ * storage so will not be accessible to web workers.+ */+export const savedSRPAttributes = (): SRPAttributes | undefined => {+ const jsonString = localStorage.getItem("srpAttributes");+ if (!jsonString) return undefined;+ return RemoteSRPAttributes.parse(JSON.parse(jsonString));+};++/**+ * Save the user's {@link SRPAttributes} in local storage.+ *+ * Use {@link savedSRPAttributes} to retrieve them.+ */+export const saveSRPAttributes = (srpAttributes: SRPAttributes) =>+ localStorage.setItem("srpAttributes", JSON.stringify(srpAttributes));++/**+ * Save {@link SRPSetupAttributes} in local storage for later use via+ * {@link unstashAfterUseSRPSetupAttributes}.+ *+ * See: [Note: SRP setup attributes]+ */+export const stashSRPSetupAttributes = (+ srpSetupAttributes: SRPSetupAttributes,+) =>+ localStorage.setItem(+ "srpSetupAttributes",+ JSON.stringify(srpSetupAttributes),+ );++/**+ * Retrieve the {@link SRPSetupAttributes}, if any, that were stashed by a+ * previous call to {@link stashSRPSetupAttributes}.+ *+ * - If they are found, then invoke the provided callback ({@link cb}) with the+ * value. If the promise returned by the callback fulfills, then remove the+ * stashed value from local storage.+ *+ * - If they are not found, then the callback is not invoked.+ */+export const unstashAfterUseSRPSetupAttributes = async (+ cb: (srpSetupAttributes: SRPSetupAttributes) => Promise<void>,+) => {+ const jsonString = localStorage.getItem("srpSetupAttributes");+ if (!jsonString) return;+ const srpSetupAttributes = SRPSetupAttributes.parse(JSON.parse(jsonString));+ await cb(srpSetupAttributes);+ localStorage.removeItem("srpSetupAttributes");+};++/**+ * Zod schema for the legacy format in which the {@link savedIsFirstLogin} and+ * {@link savedJustSignedUp} flags were saved in local storage.+ *+ * Starting 1.7.15-beta (July 2025), we started saving the booleans directly,+ * but when reading we fallback to the old format if needed. This fallback can+ * be removed, and soonish, since these are transient flags that are saved+ * during the login / signup sequence and wouldn't be expected to remain in the+ * user's local storage for long anyway. (tag: Migration).+ */+const LocalLegacyBooleanFlag = z.object({+ status: z.boolean().nullish().transform(nullToUndefined),+});++/**+ * Return `true` if it is the user's first login on this client.+ *+ * The {@link savedIsFirstLogin} flag is saved in local storage (using+ * {@link saveIsFirstLogin}) if we determine during the login flow that it a+ * fresh login on this client. If so, we+ *+ * - Generate interactive key attributes for them, and+ *+ * - Display them a special indicator post login to notify them that the first+ * load might take extra time. At this point, we also clear the flag (the read+ * and clear is done by the same {@link getAndClearIsFirstLogin} function).+ */+export const savedIsFirstLogin = () => {+ const jsonString = localStorage.getItem("isFirstLogin");+ if (!jsonString) return false;+ try {+ return z.boolean().parse(JSON.parse(jsonString));+ } catch {+ return (+ LocalLegacyBooleanFlag.parse(JSON.parse(jsonString)).status ?? false+ );+ }+};++/**+ * Save a flag in local storage to indicate that this is the user's first login+ * on this client.+ *+ * This is the setter corresponding to {@link savedIsFirstLogin}.+ */+export const saveIsFirstLogin = () => {+ localStorage.setItem("isFirstLogin", JSON.stringify({ status: true }));+};++/**+ * Get the saved value of the local storage flag that indicates that this is the+ * user' first login on this client. Also remove the flag after reading.+ *+ * The flag can be set by using {@link saveIsFirstLogin}, and can be read+ * without clearing it by using {@link savedIsFirstLogin}.+ */+export const getAndClearIsFirstLogin = () => {+ // Completely unrelated, but since this code runs on each /gallery load, use+ // this as a chance to remove the unused "showBackButton" property saved in+ // local storage. This code was added 1.7.15-beta (July 2025) and can be+ // removed after a while, soonish (tag: Migration).+ localStorage.removeItem("showBackButton");++ const result = savedIsFirstLogin();+ localStorage.removeItem("isFirstLogin");+ return result;+};++/**+ * Return `true` if the user created a new account on this client during the+ * current (in-progress) or just completed login / signup sequence.+ */+export const savedJustSignedUp = () => {+ const jsonString = localStorage.getItem("justSignedUp");+ if (!jsonString) return false;+ try {+ return z.boolean().parse(JSON.parse(jsonString));+ } catch {+ return (+ LocalLegacyBooleanFlag.parse(JSON.parse(jsonString)).status ?? false+ );+ }+};++/**+ * Save a flag in local storage to indicate that the user signed up for a+ * new Ente account during the current login / signup sequence.+ *+ * This is the setter corresponding to {@link savedJustSignedUp}.+ */+export const saveJustSignedUp = () => {+ localStorage.setItem("justSignedUp", JSON.stringify({ status: true }));+};++/**+ * Get the saved value of the local storage flag that indicates that the user just+ * signed up. Also remove the flag from local storage after reading.+ *+ * The flag can be set by using {@link saveJustSignedUp}, and can be read+ * without clearing it by using {@link savedJustSignedUp}.+ */+export const getAndClearJustSignedUp = () => {+ const result = savedJustSignedUp();+ localStorage.removeItem("justSignedUp");+ return result;+};++/**+ * Zod schema for the format in which the {@link stashReferralSource} used to+ * saved the referral source in local storage.+ *+ * Starting 1.7.15-beta (July 2025), we started saving the string directly, but+ * when reading we fallback to the old format if needed. This fallback can be+ * removed, and soonish, since these is a transient value that isn't expected to+ * remain in the user's local storage for long anyway. (tag: Migration).+ */+const LocalLegacyReferralSource = z.object({ source: z.string() });++/**+ * Save the referral source entered by the user on the signup screen in local+ * storage.+ *+ * The saved value can be retrieved post email verification using+ * {@link unstashReferralSource}.+ */+export const stashReferralSource = (referralSource: string) => {+ localStorage.setItem("referralSource", referralSource);+};++/**+ * Retrieve the previously saved referral source (using+ * {@link stashReferralSource}), returning the saved value and also clearing it+ * from local storage.+ */+export const unstashReferralSource = () => {+ const jsonString = localStorage.getItem("referralSource");+ if (!jsonString) return undefined;+ localStorage.removeItem("referralSource");+ try {+ // Try the old format first. The trim is also a legacy expectation and+ // can be removed when we remove this fallfront.+ return LocalLegacyReferralSource.parse(+ JSON.parse(jsonString),+ ).source.trim();+ } catch {+ // Otherwise try the new format.+ return jsonString;+ }+};diff --git a/web/packages/accounts-rs/services/crypto.ts b/web/packages/accounts-rs/services/crypto.tsnew file mode 100644index 0000000000..358e5426fb--- /dev/null+++ b/web/packages/accounts-rs/services/crypto.ts@@ -0,0 +1,220 @@+import { ensureCryptoInit, enteWasm } from "./wasm";++export const deriveKeyInsufficientMemoryErrorMessage =+ "Failed to derive key (insufficient memory)";++export interface EncryptedBox {+ encryptedData: string;+ nonce: string;+}++export interface KeyPair {+ publicKey: string;+ privateKey: string;+}++export interface DerivedKey {+ key: string;+ salt: string;+ opsLimit: number;+ memLimit: number;+}++interface WasmDerivedKey {+ key: string;+ salt: string;+ ops_limit: number;+ mem_limit: number;+}++interface WasmGeneratedSRPSetup {+ srp_salt: string;+ srp_verifier: string;+ login_sub_key: string;+}++const b64ToBinary = (b64: string) => atob(b64);++export const fromB64 = async (b64String: string): Promise<Uint8Array> => {+ const binary = b64ToBinary(b64String);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i++) {+ bytes[i] = binary.charCodeAt(i);+ }+ return bytes;+};++export const toB64 = async (bytes: Uint8Array): Promise<string> => {+ let binary = "";+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return btoa(binary);+};++export const toB64URLSafe = async (bytes: Uint8Array): Promise<string> =>+ (await toB64(bytes)).replace(/\+/g, "-").replace(/\//g, "_");++export const fromB64URLSafeNoPadding = async (b64String: string) => {+ let normalized = b64String.replace(/-/g, "+").replace(/_/g, "/");+ while (normalized.length % 4) normalized += "=";+ return fromB64(normalized);+};++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")+ ) {+ return new Error(deriveKeyInsufficientMemoryErrorMessage);+ }+ return error;+ }+ return new Error(deriveKeyInsufficientMemoryErrorMessage);+};++export const deriveKey = async (+ password: string,+ saltB64: string,+ opsLimit: number,+ memLimit: number,+) => {+ await ensureCryptoInit();+ const wasm = await enteWasm();+ return wasm.auth_derive_kek(password, saltB64, memLimit, opsLimit);+};++const normalizeDerivedKey = (result: WasmDerivedKey): DerivedKey => ({+ key: result.key,+ salt: result.salt,+ opsLimit: result.ops_limit,+ memLimit: result.mem_limit,+});++export const deriveSensitiveKey = async (+ password: string,+): Promise<DerivedKey> => {+ await ensureCryptoInit();+ try {+ const wasm = await enteWasm();+ return normalizeDerivedKey(+ wasm.auth_generate_sensitive_kek(password) as WasmDerivedKey,+ );+ } catch (error) {+ throw normalizeDerivedKeyError(error);+ }+};++export const deriveInteractiveKey = async (+ password: string,+): Promise<DerivedKey> => {+ await ensureCryptoInit();+ try {+ const wasm = await enteWasm();+ return normalizeDerivedKey(+ wasm.auth_generate_interactive_kek(password) as WasmDerivedKey,+ );+ } catch (error) {+ throw normalizeDerivedKeyError(error);+ }+};++export const generateKey = async (): Promise<string> => {+ await ensureCryptoInit();+ const wasm = await enteWasm();+ return wasm.crypto_generate_key();+};++export const generateKeyPair = async (): Promise<KeyPair> => {+ await ensureCryptoInit();+ const wasm = await enteWasm();+ const keyPair = wasm.crypto_generate_keypair();+ return {+ publicKey: keyPair.public_key,+ privateKey: keyPair.secret_key,+ };+};++export const encryptBox = async (+ dataB64: string,+ keyB64: string,+): Promise<EncryptedBox> => {+ await ensureCryptoInit();+ const wasm = await enteWasm();+ const box = wasm.crypto_encrypt_box(dataB64, keyB64);+ return {+ encryptedData: box.encrypted_data,+ nonce: box.nonce,+ };+};++export const decryptBox = async (+ box: EncryptedBox,+ keyB64: string,+): Promise<string> => {+ await ensureCryptoInit();+ const wasm = await enteWasm();+ return wasm.crypto_decrypt_box(box.encryptedData, box.nonce, keyB64);+};++export const boxSealOpenBytes = async (+ encryptedData: string,+ keyPair: KeyPair,+): Promise<Uint8Array> => {+ await ensureCryptoInit();+ const wasm = await enteWasm();+ return fromB64(+ wasm.crypto_box_seal_open(+ encryptedData,+ keyPair.publicKey,+ keyPair.privateKey,+ ),+ );+};++export const deriveSubKeyBytes = async (+ keyB64: string,+ subKeyLength: number,+ subKeyID: number,+ context: string,+) => {+ await ensureCryptoInit();+ const wasm = await enteWasm();+ return fromB64(+ wasm.crypto_derive_subkey(keyB64, subKeyLength, BigInt(subKeyID), context),+ );+};++export const generateSRPSetupAttributesRust = async (+ kekB64: string,+ srpUserID: string,+) => {+ await ensureCryptoInit();+ const wasm = await enteWasm();+ const setup = wasm.auth_generate_srp_setup(+ kekB64,+ srpUserID,+ ) as WasmGeneratedSRPSetup;+ return {+ srpSalt: setup.srp_salt,+ srpVerifier: setup.srp_verifier,+ loginSubKey: setup.login_sub_key,+ };+};++export const recoveryKeyFromMnemonicOrHex = async (value: string) => {+ await ensureCryptoInit();+ const wasm = await enteWasm();+ return wasm.auth_recovery_key_from_mnemonic_or_hex(value);+};++export const recoveryKeyToMnemonicRust = async (recoveryKey: string) => {+ await ensureCryptoInit();+ const wasm = await enteWasm();+ return wasm.auth_recovery_key_to_mnemonic(recoveryKey);+};diff --git a/web/packages/accounts-rs/services/logout.ts b/web/packages/accounts-rs/services/logout.tsnew file mode 100644index 0000000000..b72ec8ab59--- /dev/null+++ b/web/packages/accounts-rs/services/logout.ts@@ -0,0 +1,81 @@+import { clearBlobCaches } from "ente-base/blob-cache";+import { clearKVDB } from "ente-base/kv";+import { clearLocalStorage } from "ente-base/local-storage";+import log from "ente-base/log";+import { clearSessionStorage } from "ente-accounts-rs/services/session-storage";+import { clearStashedRedirect } from "./redirect";+import { remoteLogoutIfNeeded } from "./user";++/**+ * Logout sequence common to all apps that rely on the accounts package.+ *+ * [Note: Do not throw during logout]+ *+ * This function is guaranteed to not thrown any errors, and will try to+ * independently complete all the steps in the sequence that can be completed.+ * This allows the user to logout and start again even if somehow their account+ * gets in an unexpected state.+ */+export const accountLogout = async () => {+ const ignoreError = (label: string, e: unknown) =>+ log.error(`Ignoring error during logout (${label})`, e);++ log.info("logout (account)");++ try {+ await remoteLogoutIfNeeded();+ } catch (e) {+ ignoreError("Remote", e);+ }+ try {+ clearStashedRedirect();+ } catch (e) {+ ignoreError("In-memory store", e);+ }+ try {+ clearSessionStorage();+ } catch (e) {+ ignoreError("Session storage", e);+ }+ try {+ clearLocalStorage();+ } catch (e) {+ ignoreError("Local storage", e);+ }+ try {+ await clearBlobCaches();+ } catch (e) {+ ignoreError("Blob cache", e);+ }+ try {+ await clearKVDB();+ } catch (e) {+ ignoreError("KV DB", e);+ }+};++/**+ * This is a subset of the cleanup of local persistence that has already+ * happened during {@link accountLogout}. However, once the logout sequence is+ * complete, we do these specific steps again to clear any state that might've+ * been persisted meanwhile because of in-flight requests getting completed.+ *+ * Post this, we'll reload the page so that in-flight requests are discarded.+ */+export const logoutClearStateAgain = async () => {+ const ignoreError = (label: string, e: unknown) =>+ log.error(`Ignoring error during logout (${label})`, e);++ log.info("logout (sweep)");++ try {+ clearLocalStorage();+ } catch (e) {+ ignoreError("Local storage", e);+ }+ try {+ await clearKVDB();+ } catch (e) {+ ignoreError("KV DB", e);+ }+};diff --git a/web/packages/accounts-rs/services/passkey.ts b/web/packages/accounts-rs/services/passkey.tsnew file mode 100644index 0000000000..87eb1a746d--- /dev/null+++ b/web/packages/accounts-rs/services/passkey.ts@@ -0,0 +1,280 @@+import {+ saveKeyAttributes,+ updateSavedLocalUser,+} from "ente-accounts-rs/services/accounts-db";+import {+ resetSavedLocalUserTokens,+ TwoFactorAuthorizationResponse,+} from "ente-accounts-rs/services/user";+import { clientPackageName, isDesktop } from "ente-base/app";+import { encryptBox, generateKey } from "ente-accounts-rs/services/crypto";+import {+ authenticatedRequestHeaders,+ ensureOk,+ HTTPError,+ publicRequestHeaders,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";+import { getUserRecoveryKey } from "./recovery-key";+import { unstashRedirect } from "./redirect";++/**+ * Construct a redirect URL to take the user to Ente accounts app to+ * authenticate using their second factor, a passkey they've configured.+ *+ * On successful verification, the accounts app will redirect back to our+ * `/passkeys/finish` page.+ *+ * @param accountsURL The URL for the accounts app (provided to us by remote in+ * the email or SRP verification response).+ *+ * @param passkeySessionID An identifier provided by museum for this passkey+ * verification session.+ */+export const passkeyVerificationRedirectURL = (+ accountsURL: string,+ passkeySessionID: string,+) => {+ const clientPackage = clientPackageName;+ // Using `window.location.origin` will work both when we're running in a web+ // browser, and in our desktop app. See: [Note: Using deeplinks to navigate+ // in desktop app]+ const redirect = `${window.location.origin}/passkeys/finish`;+ // See: [Note: Conditional passkey recover option on accounts]+ const recoverOption: Record<string, string> = isDesktop+ ? {}+ : { recover: `${window.location.origin}/passkeys/recover` };+ const params = new URLSearchParams({+ clientPackage,+ passkeySessionID,+ redirect,+ ...recoverOption,+ });+ return `${accountsURL}/passkeys/verify?${params.toString()}`;+};++interface OpenPasskeyVerificationURLOptions {+ /**+ * The passkeySessionID for which we are redirecting.+ *+ * This is compared to the saved session id in the browser's session storage+ * to allow us to ignore redirects to the passkey flow finish page except+ * the ones for this specific session we're awaiting.+ */+ passkeySessionID: string;+ /** The URL to redirect to or open in the system browser. */+ url: string;+}++/**+ * Open or redirect to a passkey verification URL previously constructed using+ * {@link passkeyVerificationRedirectURL}.+ *+ * [Note: Passkey verification in the desktop app]+ *+ * Our desktop app bundles the web app and serves it over a custom protocol.+ * Passkeys are tied to origins, and will not work with this custom protocol+ * even if we move the passkey creation and authentication inline to within the+ * Photos web app.+ *+ * Thus, passkey creation and authentication in the desktop app works the same+ * way it works in the mobile app - the system browser is invoked to open+ * accounts.ente.io.+ *+ * - For passkey creation, this is a one-way open. Passkeys get created at+ * accounts.ente.io, and that's it.+ *+ * - For passkey verification, the flow is two-way. We register a custom+ * protocol and provide that as a return path redirect. Passkey authentication+ * happens at accounts.ente.io, and on success there is redirected back to the+ * desktop app.+ */+export const openPasskeyVerificationURL = ({+ passkeySessionID,+ url,+}: OpenPasskeyVerificationURLOptions) => {+ sessionStorage.setItem("inflightPasskeySessionID", passkeySessionID);++ if (globalThis.electron) window.open(url);+ else window.location.href = url;+};++/**+ * Open a new window showing a page on the Ente accounts app where the user can+ * see and their manage their passkeys.+ */+export const openAccountsManagePasskeysPage = async () => {+ // Check if the user has passkey recovery enabled.+ const { isPasskeyRecoveryEnabled } = await getTwoFactorRecoveryStatus();+ if (!isPasskeyRecoveryEnabled) {+ // If not, enable it for them by creating the necessary recovery+ // information to prevent them from getting locked out.+ const resetSecret = await generateKey();+ const { encryptedData, nonce } = await encryptBox(+ resetSecret,+ await getUserRecoveryKey(),+ );+ await configurePasskeyRecovery(resetSecret, encryptedData, nonce);+ }++ // Redirect to the Ente Accounts app where they can view and add and manage+ // their passkeys.+ const { accountsToken: token, accountsUrl: accountsURL } =+ await getAccountsTokenAndURL();+ const params = new URLSearchParams({ token });++ window.open(`${accountsURL}/passkeys?${params.toString()}`);+};++const TwoFactorRecoveryStatus = z.object({+ /**+ * `true` if the passkey recovery setup has been completed.+ */+ isPasskeyRecoveryEnabled: z.boolean(),+});++/**+ * Obtain the second factor recovery status from remote.+ */+export const getTwoFactorRecoveryStatus = async () => {+ const res = await fetch(await apiURL("/users/two-factor/recovery-status"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return TwoFactorRecoveryStatus.parse(await res.json());+};++/**+ * Allow the user to bypass their passkeys by saving the provided recovery+ * credentials on remote.+ */+const configurePasskeyRecovery = async (+ secret: string,+ userSecretCipher: string,+ userSecretNonce: string,+) =>+ ensureOk(+ await fetch(+ await apiURL("/users/two-factor/passkeys/configure-recovery"),+ {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({+ secret,+ userSecretCipher,+ userSecretNonce,+ }),+ },+ ),+ );++/**+ * Fetch an Ente Accounts specific JWT token.+ *+ * This token can be used to authenticate with the Ente accounts app running at+ * accountsURL (the result contains both pieces of information).+ */+const getAccountsTokenAndURL = async () => {+ const res = await fetch(await apiURL("/users/accounts-token"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return z+ .object({+ // The origin that serves the accounts app.+ accountsUrl: z.string(),+ // A token that can be used to authenticate with the accounts app.+ accountsToken: z.string(),+ })+ .parse(await res.json());+};++/**+ * The passkey session whose status we are trying to check has already expired.+ * The user should attempt to login again.+ */+export const passkeySessionExpiredErrorMessage = "Passkey session has expired";++/**+ * Check if the user has already authenticated using their passkey for the given+ * session.+ *+ * This is useful in case the automatic redirect back from accounts.ente.io to+ * the desktop app does not work for some reason. In such cases, the user can+ * press the "Check status" button: we'll make an API call to see if the+ * authentication has already completed, and if so, get the same "response"+ * object we'd have gotten as a query parameter in a redirect in+ * {@link saveCredentialsAndNavigateTo} on the "/passkeys/finish" page.+ *+ * @param sessionID The passkey session whose session we wish to check the+ * status of.+ *+ * @returns A {@link TwoFactorAuthorizationResponse} if the passkey+ * authentication has completed, and `undefined` otherwise.+ *+ * @throws In addition to arbitrary errors, it throws errors with the message+ * {@link passkeySessionExpiredErrorMessage}.+ */+export const checkPasskeyVerificationStatus = async (+ sessionID: string,+): Promise<TwoFactorAuthorizationResponse | undefined> => {+ const res = await fetch(+ await apiURL("/users/two-factor/passkeys/get-token", { sessionID }),+ { headers: publicRequestHeaders() },+ );+ if (!res.ok) {+ if (res.status == 404 || res.status == 410)+ throw new Error(passkeySessionExpiredErrorMessage);+ if (res.status == 400) return undefined; /* verification pending */+ throw new HTTPError(res);+ }+ return TwoFactorAuthorizationResponse.parse(await res.json());+};++/**+ * Extract credentials from a successful passkey verification response and save+ * them to local storage for use by subsequent steps (or normal functioning) of+ * the app.+ *+ * @param response The result of a successful+ * {@link checkPasskeyVerificationStatus}.+ *+ * @returns the slug that we should navigate to now.+ */+export const saveCredentialsAndNavigateTo = async (+ response: TwoFactorAuthorizationResponse,+) => {+ // [Note: Ending the passkey flow]+ //+ // The implementation of this function is similar to that of the+ // `saveQueryCredentialsAndNavigateTo` on the "/passkeys/finish" page.+ //+ // This one, `saveCredentialsAndNavigateTo`, is used when the user presses+ // the check verification status button on the page that triggered the+ // passkey flow (when they're using the desktop app).+ //+ // The other one, `saveQueryCredentialsAndNavigateTo`, is used when the user+ // goes through the passkey flow in the browser itself (when they are using+ // the web app).++ clearInflightPasskeySessionID();++ const { id, encryptedToken, keyAttributes } = response;++ await resetSavedLocalUserTokens(id, encryptedToken);+ updateSavedLocalUser({ passkeySessionID: undefined });+ saveKeyAttributes(keyAttributes);++ return unstashRedirect() ?? "/credentials";+};++/**+ * Remove the inflight passkey session ID, if any, present in session storage.+ *+ * This should be called whenever we get back control from the passkey app to+ * clean up after ourselves.+ */+export const clearInflightPasskeySessionID = () => {+ sessionStorage.removeItem("inflightPasskeySessionID");+};diff --git a/web/packages/accounts-rs/services/recovery-key.ts b/web/packages/accounts-rs/services/recovery-key.tsnew file mode 100644index 0000000000..9baea68904--- /dev/null+++ b/web/packages/accounts-rs/services/recovery-key.ts@@ -0,0 +1,94 @@+import { savedKeyAttributes } from "ente-accounts-rs/services/accounts-db";+import {+ decryptBox,+ encryptBox,+ generateKey,+ recoveryKeyFromMnemonicOrHex,+ recoveryKeyToMnemonicRust,+} from "ente-accounts-rs/services/crypto";+import { ensureMasterKeyFromSession } from "ente-accounts-rs/services/session-storage";+import { saveKeyAttributes } from "./accounts-db";+import { putUserRecoveryKeyAttributes, type KeyAttributes } from "./user";++/**+ * Convert the provided BIP-39 mnemonic string into its base64 representation.+ *+ * @param recoveryKeyMnemonicOrHex The BIP-39 mnemonic (24 word) string+ * representing the recovery key. For legacy compatibility, the function also+ * works if provided the hex representation of the recovery key.+ *+ * @returns A base64 string representing the underlying bytes of the recovery key.+ */+export const recoveryKeyFromMnemonic = (+ recoveryKeyMnemonicOrHex: string,+) => recoveryKeyFromMnemonicOrHex(recoveryKeyMnemonicOrHex);++/**+ * Convert the provided base64 encoded recovery key into its BIP-39 mnemonic.+ *+ * @param recoveryKey The base64 encoded recovery key to mnemonize.+ *+ * @returns A 24-word mnemonic that serves as the user visible recovery key.+ */+export const recoveryKeyToMnemonic = async (recoveryKey: string) =>+ recoveryKeyToMnemonicRust(recoveryKey);++/**+ * Return the (decrypted) recovery key of the logged in user, reading it from+ * local storage.+ *+ * As a fallback for old accounts that generated recovery keys on first view,+ * this function will also generate a new recovery key if needed.+ *+ * @returns The user's base64 encoded recovery key.+ */+export const getUserRecoveryKey = async () => {+ const masterKey = await ensureMasterKeyFromSession();++ const keyAttributes = savedKeyAttributes()!;+ const { recoveryKeyEncryptedWithMasterKey, recoveryKeyDecryptionNonce } =+ keyAttributes;++ if (recoveryKeyEncryptedWithMasterKey && recoveryKeyDecryptionNonce) {+ return decryptBox(+ {+ encryptedData: recoveryKeyEncryptedWithMasterKey,+ nonce: recoveryKeyDecryptionNonce,+ },+ masterKey,+ );+ } else {+ return createNewRecoveryKey(masterKey, keyAttributes);+ }+};++/**+ * Generate a new recovery key, tell remote about it, update our local state,+ * and then return it.+ *+ * This function is meant only for (very!) old accounts for whom the app did not+ * generate recovery keys on sign up but instead generated them on first view.+ *+ * @returns a new base64 encoded recovery key.+ */+const createNewRecoveryKey = async (+ masterKey: string,+ existingKeyAttributes: KeyAttributes,+) => {+ const recoveryKey = await generateKey();+ const encryptedMasterKey = await encryptBox(masterKey, recoveryKey);+ const encryptedRecoveryKey = await encryptBox(recoveryKey, masterKey);++ const recoveryKeyAttributes = {+ masterKeyEncryptedWithRecoveryKey: encryptedMasterKey.encryptedData,+ masterKeyDecryptionNonce: encryptedMasterKey.nonce,+ recoveryKeyEncryptedWithMasterKey: encryptedRecoveryKey.encryptedData,+ recoveryKeyDecryptionNonce: encryptedRecoveryKey.nonce,+ };++ await putUserRecoveryKeyAttributes(recoveryKeyAttributes);++ saveKeyAttributes({ ...existingKeyAttributes, ...recoveryKeyAttributes });++ return recoveryKey;+};diff --git a/web/packages/accounts-rs/services/redirect.ts b/web/packages/accounts-rs/services/redirect.tsnew file mode 100644index 0000000000..bfe9ae7031--- /dev/null+++ b/web/packages/accounts-rs/services/redirect.ts@@ -0,0 +1,34 @@+import { appName } from "ente-base/app";++/**+ * The default page ("home route") for each of our apps.+ *+ * This is where we redirect to after successful authentication.+ */+export const appHomeRoute: string = {+ accounts: "/passkeys",+ auth: "/auth",+ cast: "/" /* The cast app doesn't use this, this is an arbitrary value. */,+ embed: "/" /* The embed app doesn't use this either. */,+ share: "/" /* The locker public app also doesn't use this. */,+ photos: "/gallery",+ ensu: "/",+ locker: "/locker",+}[appName];++let _stashedRedirect: string | undefined;++/**+ * An in-memory redirect saved during the login flow (mostly).+ */+export const stashedRedirect = () => _stashedRedirect;++export const stashRedirect = (r: string) => (_stashedRedirect = r);++export const unstashRedirect = () => {+ const r = _stashedRedirect;+ _stashedRedirect = undefined;+ return r;+};++export const clearStashedRedirect = () => (_stashedRedirect = undefined);diff --git a/web/packages/accounts-rs/services/session-storage.ts b/web/packages/accounts-rs/services/session-storage.tsnew file mode 100644index 0000000000..f1459b429f--- /dev/null+++ b/web/packages/accounts-rs/services/session-storage.ts@@ -0,0 +1,85 @@+import { z } from "zod";+import { decryptBox, encryptBox, generateKey } from "./crypto";++/**+ * Remove all data stored in session storage (data tied to the browser tab).+ */+export const clearSessionStorage = () => sessionStorage.clear();++const SessionKeyData = z.object({+ encryptedData: z.string(),+ key: z.string(),+ nonce: z.string(),+});++type SessionKeyData = z.infer<typeof SessionKeyData>;++const sessionKeyData = async (keyData: string): Promise<SessionKeyData> => {+ const key = await generateKey();+ const box = await encryptBox(keyData, key);+ return { key, ...box };+};++export const ensureMasterKeyFromSession = async () => {+ const key = await masterKeyFromSession();+ if (!key) throw new Error("Master key not found in session");+ return key;+};++export const haveMasterKeyInSession = () =>+ !!sessionStorage.getItem("encryptionKey");++export const masterKeyFromSession = async () => {+ const value = sessionStorage.getItem("encryptionKey");+ if (!value) return undefined;++ const { encryptedData, key, nonce } = SessionKeyData.parse(+ JSON.parse(value),+ );+ return decryptBox({ encryptedData, nonce }, key);+};++export const saveMasterKeyInSessionAndSafeStore = async (masterKey: string) => {+ await saveKeyInSessionStore("encryptionKey", masterKey);+ try {+ await globalThis.electron?.saveMasterKeyInSafeStorage(masterKey);+ } catch {+ // Best effort, matching the current accounts package behaviour.+ }+};++const saveKeyInSessionStore = async (keyName: string, keyData: string) => {+ sessionStorage.setItem(+ keyName,+ JSON.stringify(await sessionKeyData(keyData)),+ );+};++export const updateSessionFromElectronSafeStorageIfNeeded = async () => {+ const electron = globalThis.electron;+ if (!electron || haveMasterKeyInSession()) return;++ let masterKey: string | undefined;+ try {+ masterKey = await electron.masterKeyFromSafeStorage();+ } catch {+ masterKey = undefined;+ }++ if (masterKey) await saveKeyInSessionStore("encryptionKey", masterKey);+};++export const stashKeyEncryptionKeyInSessionStore = (kek: string) =>+ saveKeyInSessionStore("keyEncryptionKey", kek);++export const unstashKeyEncryptionKeyFromSession = async () => {+ const value = sessionStorage.getItem("keyEncryptionKey");+ if (!value) return undefined;++ sessionStorage.removeItem("keyEncryptionKey");++ const { encryptedData, key, nonce } = SessionKeyData.parse(+ JSON.parse(value),+ );+ return decryptBox({ encryptedData, nonce }, key);+};diff --git a/web/packages/accounts-rs/services/session.ts b/web/packages/accounts-rs/services/session.tsnew file mode 100644index 0000000000..61cfdf29ef--- /dev/null+++ b/web/packages/accounts-rs/services/session.ts@@ -0,0 +1,177 @@+import {+ savedOriginalKeyAttributes,+ savedSRPAttributes,+} from "ente-accounts-rs/services/accounts-db";+import type { KeyAttributes } from "ente-accounts-rs/services/user";+import { authenticatedRequestHeaders, HTTPError } from "ente-base/http";+import log from "ente-base/log";+import { apiURL } from "ente-base/origins";+import { savedAuthToken } from "ente-base/token";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";+import { getSRPAttributes, type SRPAttributes } from "./srp";+import {+ ensureLocalUser,+ putUserKeyAttributes,+ RemoteKeyAttributes,+} from "./user";++type SessionValidity =+ | { status: "invalid" }+ | { status: "valid" }+ | {+ status: "validButPasswordChanged";+ updatedKeyAttributes: KeyAttributes;+ updatedSRPAttributes: SRPAttributes;+ };++const SessionValidityResponse = z.object({+ hasSetKeys: z.boolean(),+ /**+ * Will not be present if {@link hasSetKeys} is `false`.+ */+ keyAttributes: RemoteKeyAttributes.nullish().transform(nullToUndefined),+});++/**+ * Check if the local token and/or key attributes we have are still valid.+ *+ * This function does not take any parameters because it reads the current state+ * (key attributes) from local storage.+ *+ * @returns+ *+ * - status "invalid" if the current token has been invalidated,+ * - status "valid" normally+ * - status "validButPasswordChanged" we detected that user changed their+ * password on a different device (without choosing the option to log out of+ * all existing sessions).+ *+ * ---+ *+ * [Note: Handling password changes]+ *+ * If the user changes their password on a different device, then we need to+ * update our local state so that we use the latest password for verification.+ *+ * There is a straightforward way of doing this by always making a blocking API+ * call before showing the password unlock page, however that would add latency+ * to the 99% user experience (of normal unlocks) for the 1% case (they've+ * changed their password elsewhere).+ *+ * The approach we instead use is to make an non-blocking `/session-validity`+ * API call when this page is loaded. Usually this'll complete well before the+ * password enters their password and presses "Sign in", but we also+ * transparently await for this API call to finish before initiating the actual+ * verification. Thus there is no extra latency in the happy paths.+ *+ * The `/session-validity` API call tells us:+ *+ * 1. Whether or not the session has been invalidated (by the user choosing to+ * log out from all devices elsewhere).+ *+ * 2. What are their latest key attributes.+ *+ * If the session has been invalidated, we log them out here too.+ *+ * If the key attributes we get are different from the ones we have locally, we+ * regenerate new ones locally, and then use those for verifying the password+ * subsequently.+ */+export const checkSessionValidity = async (): Promise<SessionValidity> => {+ const res = await fetch(await apiURL("/users/session-validity/v2"), {+ headers: await authenticatedRequestHeaders(),+ });+ if (!res.ok) {+ if (res.status == 401)+ return { status: "invalid" }; /* session is no longer valid */+ else throw new HTTPError(res);+ }++ // See if the response contains keyAttributes (it will not if `hasSetKeys`+ // in the response is `false`).+ const { keyAttributes } = SessionValidityResponse.parse(await res.json());+ if (keyAttributes) {+ const remoteKeyAttributes = keyAttributes;++ // We should have these values locally if we reach here.+ const email = ensureLocalUser().email;+ const localSRPAttributes = savedSRPAttributes()!;++ // Fetch the remote SRP attributes.+ //+ // The key attributes we have saved locally are the locally generated+ // ones for interactive usage, and thus they'll always differ from the+ // ones we get from remote. To detect if the user changed their+ // password, we also need to fetch their SRP attributes (which will be+ // identical between remote and us if the password is the same).+ const remoteSRPAttributes = await getSRPAttributes(email);++ // If we get something (and usually we should),+ if (remoteSRPAttributes) {+ // See if it is different from the one we have locally. Use the kekSalt+ // as a proxy for comparing the entire object (The kekSalt will be+ // different if a new password has been generated).+ if (remoteSRPAttributes.kekSalt != localSRPAttributes.kekSalt) {+ // The token is still valid, but the key and SRP attributes have+ // changed.+ return {+ status: "validButPasswordChanged",+ updatedKeyAttributes: remoteKeyAttributes,+ updatedSRPAttributes: remoteSRPAttributes,+ };+ }+ }+ }++ // The token is still valid.+ return { status: "valid" };+};++/**+ * Return `true` if the user does not have a saved auth token, of it is no+ * longer valid. If needed, also update the key attributes at remote.+ *+ * This is a subset of {@link checkSessionValidity} that has been tailored for+ * use during each remote pull, to detect if the user has been logged out+ * elsewhere.+ *+ * @returns `true` if either we don't have an auth token, or if remote tells us+ * that the auth token (and the associated session) has been invalidated. In all+ * other cases, return `false`.+ *+ * In particular, this function doesn't throw and instead returns `false` on+ * errors. This is because returning `true` will trigger a blocking alert that+ * ends in logging the user out, and we don't want to log the user out on on+ * e.g. transient network issues.+ */+export const isSessionInvalid = async (): Promise<boolean> => {+ const token = await savedAuthToken();+ if (!token) {+ return true; /* No saved token, session is invalid */+ }++ try {+ const res = await fetch(await apiURL("/users/session-validity/v2"), {+ headers: await authenticatedRequestHeaders(),+ });+ if (!res.ok) {+ if (res.status == 401) return true; /* session is no longer valid */+ else throw new HTTPError(res);+ }++ const { hasSetKeys } = SessionValidityResponse.parse(await res.json());+ if (!hasSetKeys) {+ const originalKeyAttributes = savedOriginalKeyAttributes();+ if (originalKeyAttributes)+ await putUserKeyAttributes(originalKeyAttributes);+ }+ } catch (e) {+ log.warn("Failed to check session validity", e);+ // Don't logout user on potentially transient errors.+ return false;+ }++ // Everything seems ok.+ return false;+};diff --git a/web/packages/accounts-rs/services/sessions.ts b/web/packages/accounts-rs/services/sessions.tsnew file mode 100644index 0000000000..5b252083f7--- /dev/null+++ b/web/packages/accounts-rs/services/sessions.ts@@ -0,0 +1,73 @@+import { authenticatedRequestHeaders, ensureOk } from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { z } from "zod";++/**+ * Zod schema for an individual session returned by the API.+ */+const Session = z.object({+ /**+ * The session token.+ */+ token: z.string(),+ /**+ * The time (epoch microseconds) when the session was created.+ */+ creationTime: z.number(),+ /**+ * The IP address from which the session was created.+ */+ ip: z.string(),+ /**+ * The raw user agent string.+ */+ ua: z.string(),+ /**+ * A human-readable version of the user agent.+ */+ prettyUA: z.string(),+ /**+ * The time (epoch microseconds) when the session was last used.+ */+ lastUsedTime: z.number(),+});++/**+ * TypeScript type for a session, derived from the Zod schema.+ */+export type Session = z.infer<typeof Session>;++/**+ * Zod schema for the sessions API response.+ */+const SessionsResponse = z.object({ sessions: z.array(Session) });++/**+ * Fetch all active sessions for the current user.+ *+ * @returns A promise that resolves to an array of {@link Session} objects,+ * sorted by last used time (most recent first).+ */+export const getActiveSessions = async (): Promise<Session[]> => {+ const res = await fetch(await apiURL("/users/sessions"), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ const { sessions } = SessionsResponse.parse(await res.json());+ // Sort by last used time, most recent first.+ return sessions.sort((a, b) => b.lastUsedTime - a.lastUsedTime);+};++/**+ * Terminate a specific session.+ *+ * @param token The token of the session to terminate.+ */+export const terminateSession = async (token: string): Promise<void> => {+ const url = await apiURL("/users/session");+ const res = await fetch(`${url}?token=${encodeURIComponent(token)}`, {+ method: "DELETE",+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+};diff --git a/web/packages/accounts-rs/services/srp.ts b/web/packages/accounts-rs/services/srp.tsnew file mode 100644index 0000000000..123804ffd7--- /dev/null+++ b/web/packages/accounts-rs/services/srp.ts@@ -0,0 +1,271 @@+import {+ deriveSubKeyBytes,+ generateSRPSetupAttributesRust,+ toB64,+} from "ente-accounts-rs/services/crypto";+import {+ authenticatedRequestHeaders,+ ensureOk,+ publicRequestHeaders,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { ensure } from "ente-utils/ensure";+import { v4 as uuidv4 } from "uuid";+import { z } from "zod";+import { saveSRPAttributes } from "./accounts-db";+import {+ RemoteSRPVerificationResponse,+ type EmailOrSRPVerificationResponse,+} from "./user";+import { enteWasm } from "./wasm";++export interface SRPAttributes {+ srpUserID: string;+ srpSalt: string;+ memLimit: number;+ opsLimit: number;+ kekSalt: string;+ isEmailMFAEnabled: boolean;+}++export const RemoteSRPAttributes = z.object({+ srpUserID: z.string(),+ srpSalt: z.string(),+ memLimit: z.number(),+ opsLimit: z.number(),+ kekSalt: z.string(),+ isEmailMFAEnabled: z.boolean(),+});++export const getSRPAttributes = async (+ email: string,+): Promise<SRPAttributes | undefined> => {+ const res = await fetch(await apiURL("/users/srp/attributes", { email }), {+ headers: publicRequestHeaders(),+ });+ if (res.status == 404) return undefined;+ ensureOk(res);+ return z.object({ attributes: RemoteSRPAttributes }).parse(await res.json())+ .attributes;+};++export const SRPSetupAttributes = z.object({+ srpUserID: z.string(),+ srpSalt: z.string(),+ srpVerifier: z.string(),+ loginSubKey: z.string(),+});++export type SRPSetupAttributes = z.infer<typeof SRPSetupAttributes>;++export const generateSRPSetupAttributes = async (+ kek: string,+): Promise<SRPSetupAttributes> => {+ const srpUserID = uuidv4();+ return {+ srpUserID,+ ...(await generateSRPSetupAttributesRust(kek, srpUserID)),+ };+};++export const setupSRP = async (srpSetupAttributes: SRPSetupAttributes) =>+ srpSetupOrReconfigure(srpSetupAttributes, completeSRPSetup);++type SRPSetupOrReconfigureExchangeCallback = ({+ setupID,+ srpM1,+}: {+ setupID: string;+ srpM1: string;+}) => Promise<{ srpM2: string }>;++const srpSetupOrReconfigure = async (+ { srpSalt, srpUserID, srpVerifier, loginSubKey }: SRPSetupAttributes,+ exchangeCB: SRPSetupOrReconfigureExchangeCallback,+) => {+ const session = await createSRPSession(srpSalt, srpUserID, loginSubKey);++ const { setupID, srpB } = await startSRPSetup({+ srpUserID,+ srpSalt,+ srpVerifier,+ srpA: session.public_a(),+ });++ const { srpM2 } = await exchangeCB({+ setupID,+ srpM1: session.compute_m1(srpB),+ });++ session.verify_m2(srpM2);+};++const createSRPSession = async (+ srpSalt: string,+ srpUserID: string,+ loginSubKey: string,+) => {+ const wasm = await enteWasm();+ return new wasm.SrpSession(srpUserID, srpSalt, loginSubKey);+};++interface SetupSRPRequest {+ srpUserID: string;+ srpSalt: string;+ srpVerifier: string;+ srpA: string;+}++const SetupSRPResponse = z.object({ setupID: z.string(), srpB: z.string() });++const startSRPSetup = async (+ setupSRPRequest: SetupSRPRequest,+): Promise<z.infer<typeof SetupSRPResponse>> => {+ const res = await fetch(await apiURL("/users/srp/setup"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(setupSRPRequest),+ });+ ensureOk(res);+ return SetupSRPResponse.parse(await res.json());+};++const CompleteSRPSetupResponse = z.object({+ setupID: z.string(),+ srpM2: z.string(),+});++const completeSRPSetup = async ({+ setupID,+ srpM1,+}: {+ setupID: string;+ srpM1: string;+}) => {+ const res = await fetch(await apiURL("/users/srp/complete"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ setupID, srpM1 }),+ });+ ensureOk(res);+ return CompleteSRPSetupResponse.parse(await res.json());+};++export const getAndSaveSRPAttributes = async (userEmail: string) =>+ saveSRPAttributes(ensure(await getSRPAttributes(userEmail)));++export interface UpdatedKeyAttr {+ kekSalt: string;+ encryptedKey: string;+ keyDecryptionNonce: string;+ opsLimit: number;+ memLimit: number;+}++export const updateSRPAndKeyAttributes = (+ srpSetupAttributes: SRPSetupAttributes,+ updatedKeyAttr: UpdatedKeyAttr,+) =>+ srpSetupOrReconfigure(srpSetupAttributes, ({ setupID, srpM1 }) =>+ updateSRPAndKeys({ setupID, srpM1, updatedKeyAttr }),+ );++interface UpdateSRPAndKeysRequest {+ setupID: string;+ srpM1: string;+ updatedKeyAttr: UpdatedKeyAttr;+ logOutOtherDevices?: boolean;+}++const UpdateSRPAndKeysResponse = z.object({+ srpM2: z.string(),+ setupID: z.string(),+});++const updateSRPAndKeys = async (+ updateSRPAndKeysRequest: UpdateSRPAndKeysRequest,+): Promise<z.infer<typeof UpdateSRPAndKeysResponse>> => {+ const res = await fetch(await apiURL("/users/srp/update"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(updateSRPAndKeysRequest),+ });+ ensureOk(res);+ return UpdateSRPAndKeysResponse.parse(await res.json());+};++export const srpVerificationUnauthorizedErrorMessage =+ "SRP verification failed (HTTP 401 Unauthorized)";++const deriveSRPLoginSubKey = async (kek: string) => {+ const kekSubKeyBytes = await deriveSubKeyBytes(kek, 32, 1, "loginctx");+ return toB64(kekSubKeyBytes.slice(0, 16));+};++export const verifySRP = async (+ { srpUserID, srpSalt }: SRPAttributes,+ kek: string,+): Promise<EmailOrSRPVerificationResponse> => {+ const session = await createSRPSession(+ srpSalt,+ srpUserID,+ await deriveSRPLoginSubKey(kek),+ );++ const { srpB, sessionID } = await createSRPSessionOnRemote({+ srpUserID,+ srpA: session.public_a(),+ });++ const { srpM2, ...rest } = await verifySRPSession({+ sessionID,+ srpUserID,+ srpM1: session.compute_m1(srpB),+ });++ session.verify_m2(srpM2);++ return rest;+};++const CreateSRPSessionResponse = z.object({+ sessionID: z.string(),+ srpB: z.string(),+});++const createSRPSessionOnRemote = async ({+ srpUserID,+ srpA,+}: {+ srpUserID: string;+ srpA: string;+}): Promise<z.infer<typeof CreateSRPSessionResponse>> => {+ const res = await fetch(await apiURL("/users/srp/create-session"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify({ srpUserID, srpA }),+ });+ ensureOk(res);+ return CreateSRPSessionResponse.parse(await res.json());+};++const verifySRPSession = async ({+ sessionID,+ srpUserID,+ srpM1,+}: {+ sessionID: string;+ srpUserID: string;+ srpM1: string;+}): Promise<z.infer<typeof RemoteSRPVerificationResponse>> => {+ const res = await fetch(await apiURL("/users/srp/verify-session"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify({ sessionID, srpUserID, srpM1 }),+ });+ if (res.status == 401) {+ throw new Error(srpVerificationUnauthorizedErrorMessage);+ }+ ensureOk(res);+ return RemoteSRPVerificationResponse.parse(await res.json());+};diff --git a/web/packages/accounts-rs/services/user.ts b/web/packages/accounts-rs/services/user.tsnew file mode 100644index 0000000000..667fcc24f3--- /dev/null+++ b/web/packages/accounts-rs/services/user.ts@@ -0,0 +1,1070 @@+import {+ replaceSavedLocalUser,+ savedKeyAttributes,+ savedLocalUser,+ savedPartialLocalUser,+ saveKeyAttributes,+ saveSRPAttributes,+ updateSavedLocalUser,+} from "ente-accounts-rs/services/accounts-db";+import {+ generateSRPSetupAttributes,+ getAndSaveSRPAttributes,+ getSRPAttributes,+ updateSRPAndKeyAttributes,+ type UpdatedKeyAttr,+} from "ente-accounts-rs/services/srp";+import {+ boxSealOpenBytes,+ decryptBox,+ deriveInteractiveKey,+ deriveSensitiveKey,+ encryptBox,+ generateKey,+ generateKeyPair,+ toB64URLSafe,+} from "ente-accounts-rs/services/crypto";+import {+ authenticatedRequestHeaders,+ ensureOk,+ publicRequestHeaders,+} from "ente-base/http";+import { apiURL } from "ente-base/origins";+import { ensureMasterKeyFromSession } from "ente-accounts-rs/services/session-storage";+import {+ removeAuthToken,+ saveAuthToken,+ savedAuthToken,+} from "ente-base/token";+import { ensure } from "ente-utils/ensure";+import { nullToUndefined } from "ente-utils/transform";+import { z } from "zod";+import { clearInflightPasskeySessionID } from "./passkey";+import { getUserRecoveryKey, recoveryKeyFromMnemonic } from "./recovery-key";++/**+ * The locally persisted data we have about the user after they've logged in.+ *+ * This type arguably belongs to accounts-db (since that's what persists it and+ * its shadow alias, {@link PartialLocalUser}), but since most code that will+ * need this will need this after login has completed, and will be using the+ * {@link ensureLocalUser} method below, we keep this in the same file to reduce+ * the need to import the type from a separate file.+ */+export interface LocalUser {+ /**+ * The user's ID.+ */+ id: number;+ /**+ * The email associated with the user's Ente account.+ */+ email: string;+ /**+ * The user's (plaintext) auth token.+ *+ * It is used for making API calls on their behalf, by passing this token as+ * the value of the X-Auth-Token header in the HTTP request.+ *+ * Usually you shouldn't be needing to access this property; instead use+ * {@link savedAuthToken()} which is kept in sync with this value, and lives+ * in IndexedDB and thus can also be used in web workers.+ */+ token: string;+ /**+ * `true` if the TOTP based second factor is enabled for the user.+ */+ isTwoFactorEnabled?: boolean;+}++/**+ * Return the currently logged in {@link LocalUser}, throwing it the user is not+ * logged in.+ *+ * This is a wrapper over the {@link savedLocalUser} function that throws if no+ * one is logged in. A more appropriate name for this function, keeping in line+ * with the conventions the other methods follow, would've been+ * {@link ensureSavedLocalUser}. The shorter name is for readability.+ */+export const ensureLocalUser = (): LocalUser =>+ ensureExpectedLoggedInValue(savedLocalUser());++/**+ * A function throws an error if a value that is expected to be truthy when the+ * user is logged in is instead falsey.+ *+ * This is meant as a convenience wrapper to assert that a value we expect when+ * the user is logged in is indeed there.+ */+export const ensureExpectedLoggedInValue = <T>(t: T | undefined): T => {+ if (!t) throw new Error("Not logged in");+ return t;+};++/**+ * The user's various encrypted keys and their related attributes.+ *+ * - Attributes to derive the KEK, the (master) key encryption key.+ * - Encrypted master key (with KEK)+ * - Encrypted master key (with recovery key)+ * - Encrypted recovery key (with master key).+ * - Public key and encrypted private key (with master key).+ *+ * The various "key" attributes are base64 encoded representations of the+ * underlying binary data.+ *+ * [Note: Key attribute mutability]+ *+ * The key attributes contain two subsets:+ *+ * - Attributes that changes when the user changes their password. These are the+ * {@link UpdatedKeyAttr}.+ *+ * - All other attributes never change after initial setup.+ */+export interface KeyAttributes {+ /**+ * The user's master key encrypted with the key encryption key.+ *+ * Base64 encoded.+ *+ * [Note: Key encryption key]+ *+ * The user's master key is encrypted with a "key encryption key" (lovingly+ * called a "KEK" sometimes).+ *+ * The KEK itself is derived from the user's password.+ *+ * 1. User enters password on new device.+ *+ * 2. Client derives KEK from this password (using the {@link kekSalt},+ * {@link opsLimit} and {@link memLimit} as parameters for the+ * derivation).+ *+ * 3. Client use KEK to decrypt the master key from {@link encryptedKey} and+ * {@link keyDecryptionNonce}.+ */+ encryptedKey: string;+ /**+ * The nonce used during the encryption of the master key.+ *+ * Base64 encoded.+ *+ * @see {@link encryptedKey}.+ */+ keyDecryptionNonce: string;+ /**+ * The salt used during the derivation of the KEK.+ *+ * Base64 encoded.+ *+ * [Note: KEK three tuple]+ *+ * The three tuple (kekSalt, opsLimit, memLimit) is needed (along with the+ * user's password) to rederive the KEK when the user logs in on a new+ * client (See: [Note: Key encryption key]).+ *+ * The client can obtain these three by fetching their key attributes from+ * remote, however unless {@link isEmailMFAEnabled} is enabled (which is not+ * by default), then the user's credentials are verified using SRP instead+ * of email verification. So as a convenience for this (majority) flow,+ * remote also provides this exact same three tuple as part of the+ * {@link SRPAttributes} fetched from remote.+ *+ * So on remote the KEK three tuple is the same whether it be part of key+ * attributes or SRP attributes. When the user changes their password, both+ * of them also get updated simulataneously (they use the same storage).+ *+ * However, on the client side these two sets of three tuples might diverge+ * because of the client generating interactive key attributes. When that+ * happens, the locally saved key attributes will be overwritten by the KEK+ * three tuple for the new generated interactive KEK parameters, while the+ * SRP attributes will continue to reflect the "original" KEK three tuple we+ * got from remote.+ */+ kekSalt: string;+ /**+ * The operation limit used during the derivation of the KEK.+ *+ * The {@link opsLimit} and {@link memLimit} are complementary parameters+ * that define the amount of work done by the key derivation function. See+ * the {@link deriveKey}, {@link deriveSensitiveKey} and+ * {@link deriveInteractiveKey} functions for more detail about them.+ *+ * See: [Note: Key encryption key].+ */+ opsLimit: number;+ /**+ * The memory limit used during the derivation of the KEK.+ *+ * See {@link opsLimit} for more details.+ */+ memLimit: number;+ /**+ * The user's public key (part of their public-key keypair, the other half+ * being the {@link encryptedSecretKey}).+ *+ * Base64 encoded.+ */+ publicKey: string;+ /**+ * The user's private key (part of their public-key keypair, the other half+ * being the {@link publicKey}) encrypted with their master key.+ *+ * Base64 encoded.+ *+ * [Note: privateKey and secretKey]+ *+ * The nomenclature for the key pair follows libsodium's conventions+ * (https://doc.libsodium.org/public-key_cryptography/authenticated_encryption#key-pair-generation),+ * who possibly chose public + secret instead of public + private to avoid+ * confusion with shorthand notation (pk).+ *+ * However, the library author later changed their mind on this, so while+ * libsodium itself (the C library) and the documentation uses "secretKey",+ * the JavaScript implementation (libsodium.js) uses "privateKey".+ *+ * This structure uses the term "secretKey" since that is what the remote+ * protocol already was based on. Within the web app codebase, we use+ * "privateKey" since that is what the underlying libsodium.js uses.+ */+ encryptedSecretKey: string;+ /**+ * The nonce used during the encryption of {@link encryptedSecretKey}.+ */+ secretKeyDecryptionNonce: string;+ /**+ * The user's master key after being encrypted with their recovery key.+ *+ * Base64 encoded.+ *+ * This allows the user to recover their master key if they forget their+ * password but still have their recovery key.+ *+ * Note: This value doesn't change after being initially created.+ */+ masterKeyEncryptedWithRecoveryKey?: string;+ /**+ * The nonce used during the encryption of+ * {@link masterKeyEncryptedWithRecoveryKey}.+ *+ * Base64 encoded.+ */+ masterKeyDecryptionNonce?: string;+ /**+ * The user's recovery key after being encrypted with their master key.+ *+ * Base64 encoded.+ *+ * Note: This value doesn't change after being initially created.+ */+ recoveryKeyEncryptedWithMasterKey?: string;+ /**+ * The nonce used during the encryption of+ * {@link recoveryKeyEncryptedWithMasterKey}.+ *+ * Base64 encoded.+ */+ recoveryKeyDecryptionNonce?: string;+}++/**+ * Zod schema for {@link KeyAttributes}.+ */+export const RemoteKeyAttributes = z.object({+ kekSalt: z.string(),+ encryptedKey: z.string(),+ keyDecryptionNonce: z.string(),+ publicKey: z.string(),+ encryptedSecretKey: z.string(),+ secretKeyDecryptionNonce: z.string(),+ memLimit: z.number(),+ opsLimit: z.number(),+ masterKeyEncryptedWithRecoveryKey: z+ .string()+ .nullish()+ .transform(nullToUndefined),+ masterKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),+ recoveryKeyEncryptedWithMasterKey: z+ .string()+ .nullish()+ .transform(nullToUndefined),+ recoveryKeyDecryptionNonce: z.string().nullish().transform(nullToUndefined),+});++/**+ * A variant of {@link savedKeyAttributes} that throws if keyAttributes are not+ * present in local storage.+ */+export const ensureSavedKeyAttributes = (): KeyAttributes =>+ ensureExpectedLoggedInValue(savedKeyAttributes());++export interface UserKeyPair {+ publicKey: string;+ privateKey: string;+}++export const ensureUserKeyPair = async (): Promise<UserKeyPair> => {+ const { encryptedSecretKey, secretKeyDecryptionNonce, publicKey } =+ ensureSavedKeyAttributes();+ const privateKey = await decryptBox(+ { encryptedData: encryptedSecretKey, nonce: secretKeyDecryptionNonce },+ await ensureMasterKeyFromSession(),+ );+ return { publicKey, privateKey };+};++export const getPublicKey = async (email: string) => {+ const res = await fetch(await apiURL("/users/public-key", { email }), {+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return z.object({ publicKey: z.string() }).parse(await res.json())+ .publicKey;+};++export interface GenerateKeysAndAttributesResult {+ masterKey: string;+ kek: string;+ keyAttributes: KeyAttributes;+}++/**+ * Generate a new set of key attributes.+ *+ * @param password The password to use for deriving the key encryption key.+ *+ * @returns a newly generated master key (base64 string), kek (base64 string)+ * and the key attributes associated with the combination.+ */+export async function generateKeysAndAttributes(+ password: string,+): Promise<GenerateKeysAndAttributesResult> {+ const masterKey = await generateKey();+ const recoveryKey = await generateKey();+ const {+ key: kek,+ salt: kekSalt,+ opsLimit,+ memLimit,+ } = await deriveSensitiveKey(password);++ const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =+ await encryptBox(masterKey, kek);+ const {+ encryptedData: masterKeyEncryptedWithRecoveryKey,+ nonce: masterKeyDecryptionNonce,+ } = await encryptBox(masterKey, recoveryKey);+ const {+ encryptedData: recoveryKeyEncryptedWithMasterKey,+ nonce: recoveryKeyDecryptionNonce,+ } = await encryptBox(recoveryKey, masterKey);++ const keyPair = await generateKeyPair();+ const {+ encryptedData: encryptedSecretKey,+ nonce: secretKeyDecryptionNonce,+ } = await encryptBox(keyPair.privateKey, masterKey);++ const keyAttributes: KeyAttributes = {+ encryptedKey,+ keyDecryptionNonce,+ kekSalt,+ opsLimit,+ memLimit,+ publicKey: keyPair.publicKey,+ encryptedSecretKey,+ secretKeyDecryptionNonce,+ masterKeyEncryptedWithRecoveryKey,+ masterKeyDecryptionNonce,+ recoveryKeyEncryptedWithMasterKey,+ recoveryKeyDecryptionNonce,+ };++ return { masterKey, kek, keyAttributes };+}++/**+ * Update or set the user's {@link KeyAttributes} on remote.+ */+export const putUserKeyAttributes = async (keyAttributes: KeyAttributes) =>+ ensureOk(+ await fetch(await apiURL("/users/attributes"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ keyAttributes }),+ }),+ );++export interface RecoveryKeyAttributes {+ masterKeyEncryptedWithRecoveryKey: string;+ masterKeyDecryptionNonce: string;+ recoveryKeyEncryptedWithMasterKey: string;+ recoveryKeyDecryptionNonce: string;+}++/**+ * Update the encrypted recovery key attributes for the logged in user.+ *+ * In practice, this is not expected to be called and is meant as a rare+ * fallback for very old accounts created prior to recovery key related+ * attributes being assigned on account setup. Even for these, it'll be called+ * only once.+ */+export const putUserRecoveryKeyAttributes = async (+ recoveryKeyAttributes: RecoveryKeyAttributes,+) =>+ ensureOk(+ await fetch(await apiURL("/users/recovery-key"), {+ method: "PUT",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(recoveryKeyAttributes),+ }),+ );++/**+ * Ask remote to send a OTP / OTT to the given email to verify that the user has+ * access to it. Subsequent the app will pass this OTT back via the+ * {@link verifyOTT} method.+ *+ * @param email The email to verify.+ *+ * @param purpose In which context is the email being verified. Remote applies+ * additional business rules depending on this. For example, passing the purpose+ * "login" ensures that the OTT is only sent to an already registered email.+ *+ * In cases where the purpose is ambiguous (e.g. we're not sure if it is an+ * existing login or a new signup), the purpose can be set to `undefined`.+ */+export const sendOTT = async (+ email: string,+ purpose: "change" | "signup" | "login" | undefined,+) =>+ ensureOk(+ await fetch(await apiURL("/users/ott"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify({ email, purpose }),+ }),+ );++/**+ * The response from remote on a successful user verification, either via+ * {@link verifyEmail} or {@link verifySRP}.+ *+ * The {@link id} is always present. The rest of the values are are optional+ * since only a subset of them will be returned depending on the case:+ *+ * 1. If the user has both passkeys and TOTP based second factor enabled, then+ * the following will be set:+ * - {@link passkeySessionID}, {@link accountsUrl}+ * - {@link twoFactorSessionIDV2}+ *+ * 2. If the user has only passkeys enabled, then the following will be set:+ * - {@link passkeySessionID}, {@link accountsUrl}+ *+ * 3. If the user has only TOTP based second factor enabled, then the following+ * will be set:+ * - {@link twoFactorSessionID}+ *+ * 4. If the user doesn't have any second factor, but has already setup their+ * key attributes, then the following will be set:+ * - {@link keyAttributes}+ * - {@link encryptedToken}+ *+ * 5. Finally, in the rare case that the user has not yet setup their key+ * attributes, then the following will be set:+ * - {@link token}+ */+export interface EmailOrSRPVerificationResponse {+ /**+ * The user's ID.+ */+ id: number;+ /**+ * The user's key attributes.+ *+ * These will be set (along with the {@link encryptedToken}) if the user+ * does not have a second factor.+ */+ keyAttributes?: KeyAttributes;+ /**+ * The base64 representation of an encrypted auth token, encrypted using the+ * user's public key.+ *+ * These will be set (along with the {@link keyAttributes}) if the user+ * does not have a second factor.+ */+ encryptedToken?: string;+ /**+ * The base64 representation of an auth token.+ *+ * This will be set in the rare edge case for when the user has not yet+ * setup their key attributes.+ */+ token?: string;+ /**+ * A session ID that can be used to complete the TOTP based second factor.+ *+ * This will be set if the user has enabled a TOTP based second factor but+ * has not enabled passkeys.+ */+ twoFactorSessionID?: string;+ /**+ * A session ID that can be used to complete passkey verification.+ *+ * This will be set if the user has added a passkey to their account.+ */+ passkeySessionID?: string;+ /**+ * Base URL for the accounts app where we should redirect to for passkey+ * verification.+ *+ * This will only be set if the user has setup a passkey (i.e., whenever+ * {@link passkeySessionID} is defined).+ */+ accountsUrl?: string;+ /**+ * A session ID that can be used to complete the TOTP based second fator.+ *+ * This will be set in lieu of {@link twoFactorSessionID} if the user has+ * setup both passkeys and TOTP based two factors are enabled for their+ * account.+ *+ * ---+ *+ * Historical context: {@link twoFactorSessionIDV2} is only set if user has+ * both passkey and two factor enabled. This is to ensure older clients keep+ * using passkey flow when both are set. It is intended to be removed once+ * all clients starts surfacing both options for performing 2FA.+ *+ * See also {@link useSecondFactorChoiceIfNeeded}.+ */+ twoFactorSessionIDV2?: string;+}++/**+ * Zod schema for the {@link EmailOrSRPVerificationResponse} type.+ *+ * See: [Note: Duplicated Zod schema and TypeScript type]+ */+const RemoteEmailOrSRPVerificationResponse = z.object({+ id: z.number(),+ keyAttributes: RemoteKeyAttributes.nullish().transform(nullToUndefined),+ encryptedToken: z.string().nullish().transform(nullToUndefined),+ token: z.string().nullish().transform(nullToUndefined),+ twoFactorSessionID: z.string().nullish().transform(nullToUndefined),+ passkeySessionID: z.string().nullish().transform(nullToUndefined),+ accountsUrl: z.string().nullish().transform(nullToUndefined),+ twoFactorSessionIDV2: z.string().nullish().transform(nullToUndefined),+});++/**+ * A specialization of {@link RemoteEmailOrSRPVerificationResponse} for SRP+ * verification, which results in the {@link srpM2} field in addition to the+ * other ones.+ *+ * The declaration conceptually belongs to `srp.ts`, but is here to avoid cyclic+ * dependencies.+ */+export const RemoteSRPVerificationResponse = z.object({+ ...RemoteEmailOrSRPVerificationResponse.shape,+ /**+ * The SRP M2 (evidence message), the proof that the server has the+ * verifier.+ */+ srpM2: z.string(),+});++/**+ * Verify user's access to the given {@link email} by comparing the OTT that+ * remote previously sent to that email.+ *+ * @param email The email to verify.+ *+ * @param ott The OTT that the user entered.+ *+ * @param source During signup, we ask the user the referral "source" through+ * which they heard about Ente. When present (i.e. during signup, and if the+ * user indeed provided it), that source should be passed as this parameter.+ */+export const verifyEmail = async (+ email: string,+ ott: string,+ source: string | undefined,+): Promise<EmailOrSRPVerificationResponse> => {+ const res = await fetch(await apiURL("/users/verify-email"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify({ email, ott, ...(source && { source }) }),+ });+ ensureOk(res);+ return RemoteEmailOrSRPVerificationResponse.parse(await res.json());+};++/**+ * Log the user out on remote, if possible and needed.+ */+export const remoteLogoutIfNeeded = async () => {+ if (!(await savedAuthToken())) {+ // If the logout is attempted during the login / signup flow itself,+ // then we won't have an auth token. Handle that gracefully.+ return;+ }++ const res = await fetch(await apiURL("/users/logout"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ });+ if (res.status == 401) {+ // Ignore if we get a 401 Unauthorized, this is expected to happen on+ // token expiry.+ return;+ }++ ensureOk(res);+};++/**+ * Generate a new local-only KEK (key encryption key) suitable for interactive+ * use and update the locally saved key attributes to reflect it.+ *+ * See {@link deriveInteractiveKey} for more details.+ *+ * In brief, after the initial password verification, we create a new+ * inetractive KEK derived from the same password as the original KEK, but with+ * so called interactive mem and ops limits which result in a noticeably faster+ * key derivation.+ *+ * We then overwrite the encrypted master key, encryption nonce and the KEK+ * derivation parameters (see: [Note: KEK three tuple]) in the locally persisted+ * {@link KeyAttributes} so that these interactive parameters get used+ * subsequent reauthentication.+ *+ * These are more ergonomic for the user especially in the web app where they+ * need to enter their password to access their masterKey when repopening the+ * app in a new tab (on desktop we can avoid this by using OS storage, see+ * [Note: Safe storage and interactive KEK attributes]).+ *+ * @param password The user's password.+ *+ * @param keyAttributes The existing "original" key attributes, which we+ * might've generated locally (new signup) or fetched from remote (existing+ * login).+ *+ * @param masterKey The user's master key (base64 encoded).+ *+ * @returns the update key attributes.+ */+export const generateAndSaveInteractiveKeyAttributes = async (+ password: string,+ keyAttributes: KeyAttributes,+ key: string,+): Promise<KeyAttributes> => {+ const {+ key: interactiveKEK,+ salt: kekSalt,+ opsLimit,+ memLimit,+ } = await deriveInteractiveKey(password);++ const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =+ await encryptBox(key, interactiveKEK);++ const interactiveKeyAttributes = {+ ...keyAttributes,+ encryptedKey,+ keyDecryptionNonce,+ kekSalt,+ opsLimit,+ memLimit,+ };+ saveKeyAttributes(interactiveKeyAttributes);+ return interactiveKeyAttributes;+};++/**+ * Change the email associated with the user's account (both locally and on+ * remote)+ *+ * @param email The new email.+ *+ * @param ott The verification code that was sent to the new email.+ */+export const changeEmail = async (email: string, ott: string) => {+ await postChangeEmail(email, ott);+ updateSavedLocalUser({ email });+};++/**+ * Change the email associated with the user's account on remote.+ */+const postChangeEmail = async (email: string, ott: string) =>+ ensureOk(+ await fetch(await apiURL("/users/change-email"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify({ email, ott }),+ }),+ );++/**+ * Change the user's password on both remote and locally.+ *+ * @param password The new password.+ */+export const changePassword = async (password: string) => {+ const user = ensureLocalUser();+ const masterKey = await ensureMasterKeyFromSession();+ const keyAttributes = ensureSavedKeyAttributes();++ // Generate new KEK.+ const {+ key: kek,+ salt: kekSalt,+ opsLimit,+ memLimit,+ } = await deriveSensitiveKey(password);++ // Generate new key attributes.+ const { encryptedData: encryptedKey, nonce: keyDecryptionNonce } =+ await encryptBox(masterKey, kek);+ const updatedKeyAttr: UpdatedKeyAttr = {+ encryptedKey,+ keyDecryptionNonce,+ kekSalt,+ opsLimit,+ memLimit,+ };++ // Update SRP and key attributes on remote.+ await updateSRPAndKeyAttributes(+ await generateSRPSetupAttributes(kek),+ updatedKeyAttr,+ );++ // Update SRP attributes locally.+ await getAndSaveSRPAttributes(user.email);++ const srpAttributes = await getSRPAttributes(user.email);+ saveSRPAttributes(ensure(srpAttributes));++ // Update key attributes locally, generating a new interactive kek while+ // we're at it.+ await generateAndSaveInteractiveKeyAttributes(+ password,+ { ...keyAttributes, ...updatedKeyAttr },+ masterKey,+ );+};++/**+ * Update the {@link id} and {@link encryptedToken} present in the saved partial+ * local user.+ *+ * This function removes the {@link token}, if any, present in the saved partial+ * local user and sets the provided {@link encryptedToken}.+ *+ * It is expected that the code will subsequently redirect to "/credentials",+ * which should call {@link decryptAndStoreTokenIfNeeded} which will decrypt the+ * newly set {@link encryptedToken} and write out the decrypted value as the+ * {@link token} in the saved local user.+ *+ * @param userID The ID of the user whose token this is. This is also saved to+ * the partial local user (after doing a sanity check that we're not replacing+ * partial data with a different userID).+ *+ * @param encryptedToken The newly obtained base64 encoded encrypted token from+ * remote (e.g. as a result of the user verifying their email).+ */+export const resetSavedLocalUserTokens = async (+ userID: number,+ encryptedToken: string,+) => {+ const user = savedPartialLocalUser();+ if (user?.id && user.id != userID) {+ throw new Error(`User ID mismatch (${user.id}, ${userID})`);+ }+ replaceSavedLocalUser({+ ...user,+ id: userID,+ token: undefined,+ encryptedToken,+ });+ return removeAuthToken();+};++/**+ * Decrypt the user's {@link encryptedToken}, if present, and use it to update+ * both the locally saved user and the KV DB.+ *+ * @param keyAttributes The user's key attributes.+ *+ * @param masterKey The user's master key (base64 encoded).+ */+export const decryptAndStoreTokenIfNeeded = async (+ keyAttributes: KeyAttributes,+ masterKey: string,+) => {+ const { encryptedToken } = savedPartialLocalUser() ?? {};+ if (!encryptedToken) return;++ const { encryptedSecretKey, secretKeyDecryptionNonce, publicKey } =+ keyAttributes;+ const privateKey = await decryptBox(+ { encryptedData: encryptedSecretKey, nonce: secretKeyDecryptionNonce },+ masterKey,+ );++ const token = await toB64URLSafe(+ await boxSealOpenBytes(encryptedToken, { publicKey, privateKey }),+ );++ updateSavedLocalUser({ token, encryptedToken: undefined });+ return saveAuthToken(token);+};++const TwoFactorSecret = z.object({+ /**+ * The 2FA secret code.+ */+ secretCode: z.string(),+ /**+ * A base64 encoded "image/png".+ */+ qrCode: z.string(),+});++export type TwoFactorSecret = z.infer<typeof TwoFactorSecret>;++/**+ * Start a TOTP based two factor setup process by fetching a secret code (and+ * the corresponding QR code) from remote.+ *+ * Once the user provides us with a TOTP generated using the provided secret, we+ * can finish the setup with {@link setupTwoFactorFinish}.+ */+export const setupTwoFactor = async (): Promise<TwoFactorSecret> => {+ const res = await fetch(await apiURL("/users/two-factor/setup"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ });+ ensureOk(res);+ return TwoFactorSecret.parse(await res.json());+};++/**+ * Finish the TOTP based two factor setup by provided a previously obtained+ * secret (using {@link setupTwoFactor}) and the current TOTP generated using+ * that secret.+ *+ * This updates both the state both locally and on remote.+ *+ * @param secretCode The value of {@link secretCode} from the+ * {@link TwoFactorSecret} obtained by {@link setupTwoFactor}.+ *+ * @param totp The current TOTP corresponding to {@link secretCode}.+ */+export const setupTwoFactorFinish = async (+ secretCode: string,+ totp: string,+) => {+ const box = await encryptBox(secretCode, await getUserRecoveryKey());+ await enableTwoFactor({+ code: totp,+ encryptedTwoFactorSecret: box.encryptedData,+ twoFactorSecretDecryptionNonce: box.nonce,+ });+ updateSavedLocalUser({ isTwoFactorEnabled: true });+};++interface EnableTwoFactorRequest {+ /**+ * The current value of the TOTP corresponding to the two factor {@link+ * secretCode} obtained from a previous call to {@link setupTwoFactor}.+ */+ code: string;+ /**+ * The {@link secretCode} encrypted with the user's recovery key.+ *+ * This is used in the case of second factor recovery.+ */+ encryptedTwoFactorSecret: string;+ /**+ * The nonce that was used when encrypting {@link encryptedTwoFactorSecret}.+ */+ twoFactorSecretDecryptionNonce: string;+}++/**+ * Enable the TOTP based two factor for the user by providing the current 2FA+ * code corresponding the two factor secret, and encrypted secrets for future+ * recovery (if needed).+ */+const enableTwoFactor = async (req: EnableTwoFactorRequest) =>+ ensureOk(+ await fetch(await apiURL("/users/two-factor/enable"), {+ method: "POST",+ headers: await authenticatedRequestHeaders(),+ body: JSON.stringify(req),+ }),+ );++/**+ * The result of a successful two factor verification (TOTP or passkey),+ * recovery removal (TOTP) or recovery bypass (passkey).+ */+export const TwoFactorAuthorizationResponse = z.object({+ /**+ * The user's ID.+ */+ id: z.number(),+ /**+ * The user's key attributes.+ */+ keyAttributes: RemoteKeyAttributes,+ /**+ * A encrypted auth token.+ */+ encryptedToken: z.string(),+});++export type TwoFactorAuthorizationResponse = z.infer<+ typeof TwoFactorAuthorizationResponse+>;++export const verifyTwoFactor = async (+ code: string,+ sessionID: string,+): Promise<TwoFactorAuthorizationResponse> => {+ const res = await fetch(await apiURL("/users/two-factor/verify"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify({ code, sessionID }),+ });+ ensureOk(res);+ return TwoFactorAuthorizationResponse.parse(await res.json());+};++/** The type of the second factor we're trying to act on */+export type TwoFactorType = "totp" | "passkey";++const TwoFactorRecoveryResponse = z.object({+ /**+ * The recovery secret, encrypted using the user's recovery key.+ */+ encryptedSecret: z.string(),+ /**+ * The nonce used during encryption of {@link encryptedSecret}.+ */+ secretDecryptionNonce: z.string(),+});++export type TwoFactorRecoveryResponse = z.infer<+ typeof TwoFactorRecoveryResponse+>;++/**+ * Initiate second factor reset or bypass by requesting the encrypted second+ * factor recovery secret (and nonce) from remote. The user can then decrypt+ * these using their recovery key to reset or bypass their second factor.+ *+ * @param twoFactorType The type of second factor to reset or bypass.+ *+ * @param sessionID A two factor session ID ({@link twoFactorSessionID} or+ * {@link passkeySessionID}) for the user.+ *+ * [Note: Second factor recovery]+ *+ * 1. When setting up a TOTP based second factor, client sends a (encrypted 2fa+ * recovery secret, nonce) pair to remote. This is a randomly generated+ * secret (and nonce) encrypted using the user's recovery key.+ *+ * 2. Similarly, when setting up a passkey as the second factor, the client+ * sends a encrypted recovery secret (see {@link configurePasskeyRecovery}).+ *+ * 3. When the user wishes to reset or bypass their second factor, the client+ * asks remote for these encrypted secrets (using {@link getRecoverTwoFactor}).+ *+ * 4. User then enters their recovery key, which the client uses to decrypt the+ * recovery secret and provide it back to remote for verification (using+ * {@link removeTwoFactor}).+ *+ * 5. If the recovery secret matches, then remote resets (TOTP based) or bypass+ * (passkey based) the user's second factor.+ */+export const getRecoverTwoFactor = async (+ twoFactorType: TwoFactorType,+ sessionID: string,+): Promise<TwoFactorRecoveryResponse> => {+ const res = await fetch(+ await apiURL("/users/two-factor/recover", { twoFactorType, sessionID }),+ { headers: publicRequestHeaders() },+ );+ ensureOk(res);+ return TwoFactorRecoveryResponse.parse(await res.json());+};++/**+ * Finish the second factor recovery / bypass initiated by+ * {@link getRecoverTwoFactor} using the provided recovery key mnemonic entered+ * by the user.+ *+ * See: [Note: Second factor recovery].+ *+ * This completes the recovery process both locally, and on remote.+ *+ * @param twoFactorType The second factor type (same value as what would've been+ * passed to {@link getRecoverTwoFactor} for obtaining+ * {@link recoveryResponse}).+ *+ * @param sessionID The second factor session ID (same value as what would've+ * been passed to {@link getRecoverTwoFactor} for obtaining+ * {@link recoveryResponse}).+ *+ * @param recoveryResponse The response to a previous call to+ * {@link getRecoverTwoFactor}.+ *+ * @param recoveryKeyMnemonic The 24-word BIP-39 recovery key mnemonic provided+ * by the user to complete recovery.+ */+export const recoverTwoFactorFinish = async (+ twoFactorType: TwoFactorType,+ sessionID: string,+ recoveryResponse: TwoFactorRecoveryResponse,+ recoveryKeyMnemonic: string,+) => {+ const { encryptedSecret: encryptedData, secretDecryptionNonce: nonce } =+ recoveryResponse;+ const twoFactorSecret = await decryptBox(+ { encryptedData, nonce },+ await recoveryKeyFromMnemonic(recoveryKeyMnemonic),+ );+ const { id, keyAttributes, encryptedToken } = await removeTwoFactor(+ twoFactorType,+ sessionID,+ twoFactorSecret,+ );+ await resetSavedLocalUserTokens(id, encryptedToken);+ updateSavedLocalUser({+ isTwoFactorEnabled: undefined,+ twoFactorSessionID: undefined,+ passkeySessionID: undefined,+ });+ if (twoFactorType == "passkey") clearInflightPasskeySessionID();+ saveKeyAttributes(keyAttributes);+};++const removeTwoFactor = async (+ twoFactorType: TwoFactorType,+ sessionID: string,+ secret: string,+): Promise<TwoFactorAuthorizationResponse> => {+ const res = await fetch(await apiURL("/users/two-factor/remove"), {+ method: "POST",+ headers: publicRequestHeaders(),+ body: JSON.stringify({ twoFactorType, sessionID, secret }),+ });+ ensureOk(res);+ return TwoFactorAuthorizationResponse.parse(await res.json());+};diff --git a/web/packages/accounts-rs/services/wasm.ts b/web/packages/accounts-rs/services/wasm.tsnew file mode 100644index 0000000000..50088c7b73--- /dev/null+++ b/web/packages/accounts-rs/services/wasm.ts@@ -0,0 +1,16 @@+type EnteWasmModule = typeof import("ente-wasm");++let wasmPromise: Promise<EnteWasmModule> | undefined;+let initDone = false;++export const enteWasm = async (): Promise<EnteWasmModule> => {+ wasmPromise ??= import("ente-wasm");+ return wasmPromise;+};++export const ensureCryptoInit = async () => {+ if (initDone) return;+ const wasm = await enteWasm();+ wasm.crypto_init();+ initDone = true;+};diff --git a/web/packages/accounts-rs/tsconfig.json b/web/packages/accounts-rs/tsconfig.jsonnew file mode 100644index 0000000000..15dcfedc2b--- /dev/null+++ b/web/packages/accounts-rs/tsconfig.json@@ -0,0 +1,8 @@+{+ "extends": "ente-build-config/tsconfig-next.json",+ "include": [+ ".",+ "../base/global-electron.d.ts",+ "../base/components/utils/mui-theme.d.ts"+ ]+}diff --git a/web/packages/accounts-rs/utils/password.ts b/web/packages/accounts-rs/utils/password.tsnew file mode 100644index 0000000000..6b80dd76ed--- /dev/null+++ b/web/packages/accounts-rs/utils/password.ts@@ -0,0 +1,23 @@+import zxcvbn from "zxcvbn";++export type PasswordStrength = "weak" | "moderate" | "strong";++export const estimatePasswordStrength = (+ password: string,+): PasswordStrength => {+ if (!password) {+ return "weak";+ }++ const zxcvbnResult = zxcvbn(password);+ if (zxcvbnResult.score < 2) {+ return "weak";+ } else if (zxcvbnResult.score < 3) {+ return "moderate";+ } else {+ return "strong";+ }+};++export const isWeakPassword = (password: string) =>+ estimatePasswordStrength(password) == "weak";diff --git a/web/packages/wasm/Cargo.lock b/web/packages/wasm/Cargo.lockindex e901d101b1..48ed0caf7e 100644--- a/web/packages/wasm/Cargo.lock+++ b/web/packages/wasm/Cargo.lock@@ -60,6 +60,26 @@ version = "1.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"+[[package]]+name = "bip39"+version = "2.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90dbd31c98227229239363921e60fcf5e558e43ec69094d46fc4996f08d1d5bc"+dependencies = [+ "bitcoin_hashes",+ "serde",+ "unicode-normalization",+]++[[package]]+name = "bitcoin_hashes"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26ec84b80c482df901772e931a9a681e26a1b9ee2302edeff23cb30328745c8b"+dependencies = [+ "hex-conservative",+]+[[package]]name = "bitflags"version = "2.10.0"@@ -289,6 +309,7 @@ version = "0.0.1"dependencies = ["argon2","base64",+ "bip39","blake2b_simd","crypto_secretstream","getrandom 0.2.17",@@ -313,6 +334,7 @@ name = "ente-wasm"version = "0.0.1"dependencies = ["ente-core",+ "md-5","serde-wasm-bindgen","wasm-bindgen","wasm-bindgen-futures",@@ -459,6 +481,15 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "hex-conservative"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fda06d18ac606267c40c04e41b9947729bf8b9efe74bd4e82b61a5f26a510b9f"+dependencies = [+ "arrayvec",+]+[[package]]name = "http"version = "1.4.0"@@ -1523,6 +1554,15 @@ version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"+[[package]]+name = "unicode-normalization"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"+dependencies = [+ "tinyvec",+]+[[package]]name = "universal-hash"version = "0.5.1"diff --git a/web/packages/wasm/Cargo.toml b/web/packages/wasm/Cargo.tomlindex 4f1700c9e7..38e32136ef 100644--- a/web/packages/wasm/Cargo.toml+++ b/web/packages/wasm/Cargo.toml@@ -8,6 +8,7 @@ crate-type = ["cdylib"][dependencies]ente-core = { path = "../../../rust/core", features = ["srp"] }+md-5 = "0.10"serde-wasm-bindgen = "0.6"wasm-bindgen = "0.2"wasm-bindgen-futures = "0.4"diff --git a/web/packages/wasm/src/auth.rs b/web/packages/wasm/src/auth.rsindex e6679aa9e7..4973f6fbb1 100644--- a/web/packages/wasm/src/auth.rs+++ b/web/packages/wasm/src/auth.rs@@ -34,6 +34,7 @@ impl From<core_auth::AuthError> for AuthError {E::IncorrectPassword => "incorrect_password",E::IncorrectRecoveryKey => "incorrect_recovery_key",E::InvalidKeyAttributes => "invalid_key_attributes",+ E::InsufficientMemory => "insufficient_memory",E::MissingField(_) => "missing_field",E::Crypto(_) => "crypto",E::Decode(_) => "decode",@@ -109,6 +110,71 @@ impl DecryptedSecrets {}}+/// A generated KEK and its derivation parameters.+#[wasm_bindgen]+pub struct GeneratedKek {+ key: String,+ salt: String,+ mem_limit: u32,+ ops_limit: u32,+}++#[wasm_bindgen]+impl GeneratedKek {+ /// Derived KEK (base64).+ #[wasm_bindgen(getter)]+ pub fn key(&self) -> String {+ self.key.clone()+ }++ /// Salt used for derivation (base64).+ #[wasm_bindgen(getter)]+ pub fn salt(&self) -> String {+ self.salt.clone()+ }++ /// Argon2 memory limit in bytes.+ #[wasm_bindgen(getter)]+ pub fn mem_limit(&self) -> u32 {+ self.mem_limit+ }++ /// Argon2 operations limit.+ #[wasm_bindgen(getter)]+ pub fn ops_limit(&self) -> u32 {+ self.ops_limit+ }+}++/// SRP setup payload generated from a KEK.+#[wasm_bindgen]+pub struct GeneratedSrpSetup {+ srp_salt: String,+ srp_verifier: String,+ login_sub_key: String,+}++#[wasm_bindgen]+impl GeneratedSrpSetup {+ /// SRP salt (base64).+ #[wasm_bindgen(getter)]+ pub fn srp_salt(&self) -> String {+ self.srp_salt.clone()+ }++ /// SRP verifier (base64).+ #[wasm_bindgen(getter)]+ pub fn srp_verifier(&self) -> String {+ self.srp_verifier.clone()+ }++ /// SRP login sub-key (base64, 16 bytes).+ #[wasm_bindgen(getter)]+ pub fn login_sub_key(&self) -> String {+ self.login_sub_key.clone()+ }+}+/// Derive SRP credentials (KEK + login key) from a password and SRP attributes.////// `srp_attrs` must match the shape returned by the Ente API's@@ -142,6 +208,62 @@ pub fn auth_derive_kek(Ok(core_crypto::encode_b64(&kek))}+/// Generate a KEK using the current sensitive web derivation policy.+#[wasm_bindgen]+pub fn auth_generate_sensitive_kek(password: &str) -> Result<GeneratedKek, AuthError> {+ let generated = core_auth::generate_sensitive_kek(password)?;+ Ok(GeneratedKek {+ key: core_crypto::encode_b64(&generated.key),+ salt: core_crypto::encode_b64(&generated.salt),+ mem_limit: generated.mem_limit,+ ops_limit: generated.ops_limit,+ })+}++/// Generate a KEK using the current interactive web derivation policy.+#[wasm_bindgen]+pub fn auth_generate_interactive_kek(password: &str) -> Result<GeneratedKek, AuthError> {+ let generated = core_auth::generate_interactive_kek(password)?;+ Ok(GeneratedKek {+ key: core_crypto::encode_b64(&generated.key),+ salt: core_crypto::encode_b64(&generated.salt),+ mem_limit: generated.mem_limit,+ ops_limit: generated.ops_limit,+ })+}++/// Generate the SRP setup payload for a given KEK and SRP user ID.+#[wasm_bindgen]+pub fn auth_generate_srp_setup(+ kek_b64: &str,+ srp_user_id: &str,+) -> Result<GeneratedSrpSetup, AuthError> {+ let kek = core_crypto::decode_b64(kek_b64).map_err(|e| AuthError {+ code: "decode".to_string(),+ message: format!("kek: {}", e),+ })?;++ let generated = core_auth::generate_srp_setup(&kek, srp_user_id)?;+ Ok(GeneratedSrpSetup {+ srp_salt: core_crypto::encode_b64(&generated.srp_salt),+ srp_verifier: core_crypto::encode_b64(&generated.srp_verifier),+ login_sub_key: core_crypto::encode_b64(&generated.login_sub_key),+ })+}++/// Convert a recovery key mnemonic or legacy hex string into base64 bytes.+#[wasm_bindgen]+pub fn auth_recovery_key_from_mnemonic_or_hex(input: &str) -> Result<String, AuthError> {+ let recovery_key = core_auth::recovery_key_from_mnemonic_or_hex(input)?;+ Ok(core_crypto::encode_b64(&recovery_key))+}++/// Convert a base64-encoded recovery key into its English mnemonic.+#[wasm_bindgen]+pub fn auth_recovery_key_to_mnemonic(recovery_key_b64: &str) -> Result<String, AuthError> {+ core_auth::recovery_key_to_mnemonic(recovery_key_b64).map_err(Into::into)+}+/// Decrypt the master key, secret key and auth token.////// `key_attrs` should be the `keyAttributes` object from the auth response.diff --git a/web/packages/wasm/src/crypto.rs b/web/packages/wasm/src/crypto.rsindex dc6cb16dbe..8f139a4503 100644--- a/web/packages/wasm/src/crypto.rs+++ b/web/packages/wasm/src/crypto.rs@@ -1,6 +1,7 @@//! WASM bindings for pure-Rust cryptography.use ente_core::crypto as core_crypto;+use md5::{Digest, Md5};use wasm_bindgen::prelude::*;/// Crypto error.@@ -83,12 +84,106 @@ pub fn crypto_generate_stream_key() -> String {core_crypto::encode_b64(&core_crypto::keys::generate_stream_key())}+/// Incremental chunk encryptor for large file uploads.+///+/// The browser reads the file in chunks and passes each chunk to this object,+/// which keeps the secretstream state in Rust and returns encrypted bytes for+/// the caller to upload.+#[wasm_bindgen]+pub struct CryptoStreamEncryptor {+ encryptor: core_crypto::stream::StreamEncryptor,+ key: String,+ decryption_header: String,+}++#[wasm_bindgen]+impl CryptoStreamEncryptor {+ #[wasm_bindgen(constructor)]+ pub fn new() -> Result<CryptoStreamEncryptor, CryptoError> {+ let key = core_crypto::keys::generate_stream_key();+ let encryptor = core_crypto::stream::StreamEncryptor::new(&key)?;+ let decryption_header = core_crypto::encode_b64(&encryptor.header);++ Ok(Self {+ encryptor,+ key: core_crypto::encode_b64(&key),+ decryption_header,+ })+ }++ #[wasm_bindgen(getter)]+ pub fn key(&self) -> String {+ self.key.clone()+ }++ #[wasm_bindgen(getter)]+ pub fn decryption_header(&self) -> String {+ self.decryption_header.clone()+ }++ pub fn encrypt_chunk(+ &mut self,+ plaintext: Vec<u8>,+ is_final: bool,+ ) -> Result<Vec<u8>, CryptoError> {+ self.encryptor.push(&plaintext, is_final).map_err(Into::into)+ }+}++/// Incremental chunk decryptor for large file downloads.+#[wasm_bindgen]+pub struct CryptoStreamDecryptor {+ decryptor: core_crypto::stream::StreamDecryptor,+ finalized: bool,+}++#[wasm_bindgen]+impl CryptoStreamDecryptor {+ #[wasm_bindgen(constructor)]+ pub fn new(+ decryption_header_b64: &str,+ key_b64: &str,+ ) -> Result<CryptoStreamDecryptor, CryptoError> {+ let header = core_crypto::decode_b64(decryption_header_b64)?;+ let key = core_crypto::decode_b64(key_b64)?;+ let decryptor = core_crypto::stream::StreamDecryptor::new(&header, &key)?;++ Ok(Self {+ decryptor,+ finalized: false,+ })+ }++ #[wasm_bindgen(getter)]+ pub fn decryption_chunk_size(&self) -> usize {+ core_crypto::stream::DECRYPTION_CHUNK_SIZE+ }++ #[wasm_bindgen(getter)]+ pub fn is_finalized(&self) -> bool {+ self.finalized+ }++ pub fn decrypt_chunk(&mut self, ciphertext: Vec<u8>) -> Result<Vec<u8>, CryptoError> {+ let (plaintext, tag) = self.decryptor.pull(&ciphertext)?;+ self.finalized = tag == core_crypto::stream::TAG_FINAL;+ Ok(plaintext)+ }+}+/// Generate a random 16-byte salt and return it as base64.#[wasm_bindgen]pub fn crypto_generate_salt() -> String {core_crypto::encode_b64(&core_crypto::keys::generate_salt())}+/// Compute the MD5 digest of the provided bytes and return it as base64.+#[wasm_bindgen]+pub fn crypto_md5_base64(data: Vec<u8>) -> String {+ let digest = Md5::digest(&data);+ core_crypto::encode_b64(&digest)+}+/// A X25519 public/secret keypair.#[wasm_bindgen]pub struct CryptoKeyPair {@@ -224,6 +319,47 @@ pub fn crypto_decrypt_blob(Ok(core_crypto::encode_b64(&plaintext))}+/// Legacy decrypt for SecretStream (blob) ciphertext that may not carry+/// a final tag.+///+/// Prefer using [`crypto_decrypt_blob`]. This function exists as a migration+/// fallback for older data written without the final secretstream tag.+#[wasm_bindgen]+pub fn crypto_decrypt_blob_legacy(+ encrypted_data_b64: &str,+ decryption_header_b64: &str,+ key_b64: &str,+) -> Result<String, CryptoError> {+ let ciphertext = core_crypto::decode_b64(encrypted_data_b64)?;+ let header = core_crypto::decode_b64(decryption_header_b64)?;+ let key = core_crypto::decode_b64(key_b64)?;++ let mut decryptor = core_crypto::stream::StreamDecryptor::new(&header, &key)?;+ let (plaintext, _tag) = decryptor.pull(&ciphertext)?;+ Ok(core_crypto::encode_b64(&plaintext))+}++/// Decrypt chunked SecretStream data (file content).+///+/// Unlike `crypto_decrypt_blob` which handles single-message blobs, this+/// function handles multi-chunk streaming data encrypted with 4 MB chunks+/// (the format used for encrypted file content).+///+/// Returns the plaintext as base64.+#[wasm_bindgen]+pub fn crypto_decrypt_stream(+ encrypted_data_b64: &str,+ decryption_header_b64: &str,+ key_b64: &str,+) -> Result<String, CryptoError> {+ let ciphertext = core_crypto::decode_b64(encrypted_data_b64)?;+ let header = core_crypto::decode_b64(decryption_header_b64)?;+ let key = core_crypto::decode_b64(key_b64)?;++ let plaintext = core_crypto::stream::decrypt_file_data(&ciphertext, &header, &key)?;+ Ok(core_crypto::encode_b64(&plaintext))+}+/// Seal (anonymous public-key encrypt) `data_b64` for `recipient_public_key_b64`.////// Wire format matches libsodium `crypto_box_seal`.@@ -284,6 +420,100 @@ pub fn crypto_derive_subkey(Ok(core_crypto::encode_b64(&subkey))}+/// A chunked SecretStream encryption result (for file content).+///+/// Unlike [`EncryptedBlob`] which encrypts data as a single message, this+/// encrypts data in 4 MB chunks using the streaming API β the same format used+/// for encrypted file content throughout Ente.+#[wasm_bindgen]+pub struct EncryptedStreamResult {+ encrypted_data: String,+ decryption_header: String,+ md5_hash: String,+ key: String,+}++#[wasm_bindgen]+impl EncryptedStreamResult {+ /// The encrypted ciphertext as base64.+ #[wasm_bindgen(getter)]+ pub fn encrypted_data(&self) -> String {+ self.encrypted_data.clone()+ }++ /// The decryption header as base64.+ #[wasm_bindgen(getter)]+ pub fn decryption_header(&self) -> String {+ self.decryption_header.clone()+ }++ /// MD5 hash of the encrypted data as base64.+ #[wasm_bindgen(getter)]+ pub fn md5_hash(&self) -> String {+ self.md5_hash.clone()+ }++ /// The file encryption key (32 bytes) as base64.+ ///+ /// A new random key is generated for each encryption.+ #[wasm_bindgen(getter)]+ pub fn key(&self) -> String {+ self.key.clone()+ }+}++/// Encrypt file data using chunked SecretStream (4 MB chunks) and compute MD5.+///+/// Generates a new random stream key, encrypts the data in 4 MB chunks (the+/// same format produced by the mobile and desktop clients), and computes the+/// MD5 hash of the ciphertext.+///+/// Returns the encrypted data, decryption header, MD5 hash, and generated key+/// β all as base64 strings.+#[wasm_bindgen]+pub fn crypto_encrypt_stream(data_b64: &str) -> Result<EncryptedStreamResult, CryptoError> {+ let plaintext = core_crypto::decode_b64(data_b64)?;++ let mut reader = std::io::Cursor::new(&plaintext);+ let mut writer = Vec::new();++ let (key, header, md5) =+ core_crypto::stream::encrypt_file_with_md5(&mut reader, &mut writer, None)?;++ Ok(EncryptedStreamResult {+ encrypted_data: core_crypto::encode_b64(&writer),+ decryption_header: core_crypto::encode_b64(&header),+ md5_hash: core_crypto::encode_b64(&md5),+ key: core_crypto::encode_b64(&key),+ })+}++/// Encrypt data using chunked SecretStream with an existing key.+///+/// Same as [`crypto_encrypt_stream`] but uses the provided key instead of+/// generating a new one. Useful for encrypting thumbnails with the same file key.+#[wasm_bindgen]+pub fn crypto_encrypt_stream_with_key(+ data_b64: &str,+ key_b64: &str,+) -> Result<EncryptedStreamResult, CryptoError> {+ let plaintext = core_crypto::decode_b64(data_b64)?;+ let key = core_crypto::decode_b64(key_b64)?;++ let mut reader = std::io::Cursor::new(&plaintext);+ let mut writer = Vec::new();++ let (out_key, header, md5) =+ core_crypto::stream::encrypt_file_with_md5(&mut reader, &mut writer, Some(&key))?;++ Ok(EncryptedStreamResult {+ encrypted_data: core_crypto::encode_b64(&writer),+ decryption_header: core_crypto::encode_b64(&header),+ md5_hash: core_crypto::encode_b64(&md5),+ key: core_crypto::encode_b64(&out_key),+ })+}+/// Derive the SRP login key from a 32-byte master key.////// Returns the 16-byte login key as base64.diff --git a/web/packages/wasm/tests/auth.test.ts b/web/packages/wasm/tests/auth.test.tsnew file mode 100644index 0000000000..edfc6ae767--- /dev/null+++ b/web/packages/wasm/tests/auth.test.ts@@ -0,0 +1,44 @@+import { expect, test } from "vitest";+import {+ auth_generate_interactive_kek,+ auth_generate_sensitive_kek,+ auth_generate_srp_setup,+ auth_recovery_key_from_mnemonic_or_hex,+ auth_recovery_key_to_mnemonic,+ crypto_generate_key,+} from "../pkg/ente_wasm.js";++test("generates an interactive kek bundle", () => {+ const generated = auth_generate_interactive_kek("correct horse battery staple");++ expect(Buffer.from(generated.key, "base64")).toHaveLength(32);+ expect(Buffer.from(generated.salt, "base64")).toHaveLength(16);+ expect(generated.mem_limit).toBe(67_108_864);+ expect(generated.ops_limit).toBe(2);+});++test("generates a sensitive kek bundle", () => {+ const generated = auth_generate_sensitive_kek("correct horse battery staple");++ expect(Buffer.from(generated.key, "base64")).toHaveLength(32);+ expect(Buffer.from(generated.salt, "base64")).toHaveLength(16);+ expect(generated.mem_limit).toBeGreaterThan(0);+ expect(generated.ops_limit).toBeGreaterThan(0);+});++test("generates SRP setup attributes from a kek", () => {+ const kek = crypto_generate_key();+ const generated = auth_generate_srp_setup(kek, "test-user-id");++ expect(Buffer.from(generated.srp_salt, "base64")).toHaveLength(16);+ expect(Buffer.from(generated.login_sub_key, "base64")).toHaveLength(16);+ expect(Buffer.from(generated.srp_verifier, "base64").length).toBeGreaterThan(0);+});++test("round-trips recovery key mnemonic", () => {+ const recoveryKey = crypto_generate_key();+ const mnemonic = auth_recovery_key_to_mnemonic(recoveryKey);+ const decoded = auth_recovery_key_from_mnemonic_or_hex(mnemonic);++ expect(decoded).toBe(recoveryKey);+});diff --git a/web/packages/wasm/tests/crypto.test.ts b/web/packages/wasm/tests/crypto.test.tsnew file mode 100644index 0000000000..51ba3241c6--- /dev/null+++ b/web/packages/wasm/tests/crypto.test.ts@@ -0,0 +1,40 @@+import { expect, test } from "vitest";+import {+ CryptoStreamEncryptor,+ crypto_decrypt_blob,+ crypto_decrypt_blob_legacy,+} from "../pkg/ente_wasm.js";++test("strict blob decrypt rejects non-final secretstream payloads", () => {+ const encryptor = new CryptoStreamEncryptor();+ const ciphertext = encryptor.encrypt_chunk(+ Uint8Array.from([1, 2, 3, 4]),+ false,+ );+ const encryptedData = Buffer.from(ciphertext).toString("base64");++ expect(() =>+ crypto_decrypt_blob(+ encryptedData,+ encryptor.decryption_header,+ encryptor.key,+ ),+ ).toThrow();+});++test("legacy blob decrypt accepts non-final secretstream payloads", () => {+ const encryptor = new CryptoStreamEncryptor();+ const ciphertext = encryptor.encrypt_chunk(+ Uint8Array.from([1, 2, 3, 4]),+ false,+ );+ const encryptedData = Buffer.from(ciphertext).toString("base64");++ const decrypted = crypto_decrypt_blob_legacy(+ encryptedData,+ encryptor.decryption_header,+ encryptor.key,+ );++ expect(decrypted).toBe("AQIDBA==");+});