Skip to content

armgit / ente

Public Imported from GitHub
0

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

Share authentication payload protections across clients

Neeraj Guptafd99e16f4821
diff --cc cli/internal/api/auth_payload_test.go
index 0000000000,0000000000..9ac7870569
new file mode 100644
--- /dev/null
+++ b/cli/internal/api/auth_payload_test.go
@@@ -1,0 -1,0 +1,38 @@@
++package api
++
++import (
++ "bytes"
++ "testing"
++)
++
++func TestValidateAuthToken(t *testing.T) {
++ for _, endpoint := range []struct {
++ origin string
++ strict bool
++ }{
++ {"https://api.ente.com", true},
++ {"https://api.ente.in:443/prefix", true},
++ {"http://localhost:8080", true},
++ {"https://API.ENTE.COM", true},
++ {"https://self-hosted.example", false},
++ {"http://127.0.0.1:8080", false},
++ {"https://api.ente.com.example", false},
++ {"https://[email protected]", false},
++ } {
++ client := NewClient(Params{Host: endpoint.origin})
++ for _, test := range []struct {
++ token []byte
++ tagged bool
++ }{
++ {append([]byte("auth-token"), bytes.Repeat([]byte{1}, 32)...), true},
++ {bytes.Repeat([]byte{1}, 32), false},
++ {append([]byte("auth-token"), bytes.Repeat([]byte{1}, 31)...), false},
++ {append([]byte("auth-token"), bytes.Repeat([]byte{1}, 33)...), false},
++ {[]byte("delete-jwtheader.payload.signature"), false},
++ } {
++ if (client.ValidateAuthToken(test.token) == nil) != (!endpoint.strict || test.tagged) {
++ t.Errorf("unexpected validation result for %s, length %d", endpoint.origin, len(test.token))
++ }
++ }
++ }
++}
diff --cc cli/internal/api/client.go
index 1ea75b59e9,1ea75b59e9..095b92480d
--- a/cli/internal/api/client.go
+++ b/cli/internal/api/client.go
@@@ -1,9 -1,9 +1,13 @@@
package api
import (
++ "bytes"
"context"
++ "fmt"
"github.com/go-resty/resty/v2"
"log"
++ "net/url"
++ "strings"
"time"
)
@@@ -20,7 -20,7 +24,7 @@@ var
var tokenMap map[string]string = make(map[string]string)
type Client struct {
-- restClient *resty.Client
++ restClient *resty.Client
downloadClient *resty.Client
}
@@@ -97,3 -97,3 +101,17 @@@ func attachToken(req *resty.Request)
func (c *Client) AddToken(id string, token string) {
tokenMap[id] = token
}
++
++func (c *Client) ValidateAuthToken(token []byte) error {
++ endpoint, err := url.Parse(c.restClient.BaseURL)
++ if err != nil {
++ return err
++ }
++ switch strings.ToLower(endpoint.Hostname()) {
++ case "api.ente.com", "api.ente.in", "localhost":
++ if len(token) != len("auth-token")+32 || !bytes.HasPrefix(token, []byte("auth-token")) {
++ return fmt.Errorf("invalid login token")
++ }
++ }
++ return nil
++}
diff --cc cli/pkg/sign_in.go
index 31b93126c5,09c68da626..f4d854600a
--- a/cli/pkg/sign_in.go
+++ b/cli/pkg/sign_in.go
@@@ -108,9 -107,6 +107,9 @@@ func (c *ClICtrl) decryptAccSecretInfo
fmt.Printf("error decrypting token: %v", err)
return nil, err
}
- if len(tokenKey) != len("auth-token")+32 || !bytes.HasPrefix(tokenKey, []byte("auth-token")) {
- return nil, fmt.Errorf("invalid login token: the server may need upgrading")
++ if err := c.Client.ValidateAuthToken(tokenKey); err != nil {
++ return nil, err
+ }
break
}
return &model.AccSecretInfo{
diff --cc rust/bindings/frb/lib/src/accounts/types.rs
index 0000000000,7655dc5115..205617cf43
mode 000000,100644..100644
--- a/rust/bindings/frb/lib/src/accounts/types.rs
+++ b/rust/bindings/frb/lib/src/accounts/types.rs
@@@ -1,0 -1,473 +1,473 @@@
+ use ente_accounts::{AccountsClient as InnerClient, Error, auth, lifecycle, login, signup};
+ pub use ente_accounts::{
+ auth::KeyAttributes,
+ models::{
+ AuthResponse, TwoFactorAuthorizationResponse, TwoFactorRecoveryResponse, TwoFactorSecret,
+ TwoFactorType,
+ },
+ };
+ use ente_core::{b64, crypto::SecretVec};
+ use flutter_rust_bridge::frb;
+
+ #[frb(non_opaque)]
+ pub enum AccountsError {
+ NotRegistered,
+ AlreadyRegistered,
+ SignupIncomplete,
+ EmailAlreadyInUse,
+ SrpNotConfigured,
+ IncorrectPassword,
+ IncorrectRecoveryKey,
+ IncorrectEmailCode,
+ EmailCodeExpired,
+ EmailCodeRateLimited,
+ IncorrectTotp,
+ TotpRateLimited,
+ SessionExpired,
+ KeyDerivation,
+ Network { timeout: bool },
+ Other { message: String },
+ }
+
+ impl From<Error> for AccountsError {
+ fn from(error: Error) -> Self {
+ match error {
+ Error::NotRegistered => Self::NotRegistered,
+ Error::AlreadyRegistered => Self::AlreadyRegistered,
+ Error::SignupIncomplete => Self::SignupIncomplete,
+ Error::EmailAlreadyInUse => Self::EmailAlreadyInUse,
+ Error::SrpNotConfigured => Self::SrpNotConfigured,
+ Error::IncorrectPassword => Self::IncorrectPassword,
+ Error::IncorrectRecoveryKey => Self::IncorrectRecoveryKey,
+ Error::IncorrectEmailVerificationCode => Self::IncorrectEmailCode,
+ Error::EmailVerificationCodeExpired => Self::EmailCodeExpired,
+ Error::EmailVerificationRateLimited => Self::EmailCodeRateLimited,
+ Error::IncorrectTotp => Self::IncorrectTotp,
+ Error::TotpRateLimited => Self::TotpRateLimited,
+ Error::SecondFactorSessionExpired => Self::SessionExpired,
+ Error::InsufficientMemory
+ | Error::Crypto(ente_core::crypto::Error::KeyDerivationFailed)
+ | Error::Crypto(ente_core::crypto::Error::InvalidKeyDerivationParams(_)) => {
+ Self::KeyDerivation
+ }
+ Error::Http(ref error) if error.is_connect() || error.is_timeout() => Self::Network {
+ timeout: error.is_timeout(),
+ },
+ _ => Self::Other {
+ message: ente_core::error::chain(&error),
+ },
+ }
+ }
+ }
+
+ #[frb(non_opaque)]
+ pub struct AccountsClientConfig {
+ pub origin: String,
+ pub client_package: String,
+ pub client_version: Option<String>,
+ pub user_agent: Option<String>,
+ }
+
+ #[frb(opaque)]
+ pub struct AccountsClient(pub(crate) InnerClient);
+
+ impl AccountsClient {
+ pub async fn send_otp(
+ &self,
+ email: String,
+ purpose: String,
+ mobile: bool,
+ ) -> Result<(), AccountsError> {
+ self.0
+ .send_otp(&email, &purpose, mobile)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn verify_email(
+ &self,
+ email: String,
+ code: String,
+ source: Option<String>,
+ ) -> Result<AuthResponse, AccountsError> {
+ self.0
+ .verify_email(&email, &code, source.as_deref())
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn get_srp_attributes(&self, email: String) -> Result<SrpAttributes, AccountsError> {
+ self.0
+ .get_srp_attributes(&email)
+ .await
+ .map(SrpAttributes::from)
+ .map_err(Into::into)
+ }
+
+ pub async fn login_with_password(
+ &self,
+ attributes: SrpAttributes,
+ password: String,
+ ) -> Result<PasswordLogin, AccountsError> {
+ let (response, kek) = self
+ .0
+ .login_with_srp(&password, &attributes.try_into()?)
+ .await?;
+ Ok(PasswordLogin {
+ response,
+ key_encryption_key: kek.into_vec(),
+ })
+ }
+
+ pub async fn verify_totp(
+ &self,
+ session_id: String,
+ code: String,
+ ) -> Result<AuthResponse, AccountsError> {
+ self.0
+ .verify_totp(&session_id, &code)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn poll_passkey(
+ &self,
+ session_id: String,
+ ) -> Result<Option<AuthResponse>, AccountsError> {
+ self.0
+ .check_passkey_status(&session_id)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub fn generate_signup_keys(
+ &self,
+ password: String,
+ srp_user_id: String,
+ ) -> Result<SignupKeys, AccountsError> {
+ let (keys, srp) = signup::generate_keys(&password, &srp_user_id)?;
+ Ok(SignupKeys {
+ key_attributes: keys.key_attributes,
+ master_key: keys.private_key_attributes.key.into_string(),
+ secret_key: keys.private_key_attributes.secret_key.into_string(),
+ recovery_key: keys.private_key_attributes.recovery_key.into_string(),
+ srp: SrpSetup {
+ srp_user_id,
+ srp_salt: srp.srp_salt,
+ srp_verifier: srp.srp_verifier,
+ login_key: srp.login_sub_key.into_vec(),
+ },
+ })
+ }
+
+ pub async fn complete_signup(
+ &self,
+ email: String,
+ token: String,
+ key_attributes: KeyAttributes,
+ srp: SrpSetup,
+ ) -> Result<(), AccountsError> {
+ let client = self.0.with_auth_token(token);
+ let srp_user_id = srp
+ .srp_user_id
+ .parse()
+ .map_err(|_| Error::InvalidInput("Invalid SRP user ID".into()))?;
+ signup::complete_signup(
+ &client,
+ &email,
+ &key_attributes,
+ srp_user_id,
+ &srp.into_core(),
+ )
+ .await
+ .map(|_| ())
+ .map_err(Into::into)
+ }
+
+ pub async fn setup_srp(
+ &self,
+ token: String,
+ srp_user_id: String,
+ login_key: Vec<u8>,
+ ) -> Result<(), AccountsError> {
+ let client = self.0.with_auth_token(token);
+ let srp = auth::generate_srp_setup_with_login_key(&login_key, &srp_user_id)?;
+ let srp_user_id = srp_user_id
+ .parse()
+ .map_err(|_| Error::InvalidInput("Invalid SRP user ID".into()))?;
+ signup::setup_srp(&client, srp_user_id, &srp)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub fn unlock(
+ &self,
+ response: AuthResponse,
+ password: String,
+ key_encryption_key: Option<Vec<u8>>,
+ ) -> Result<UnlockedAccount, AccountsError> {
+ let attributes = response
+ .key_attributes
+ .as_ref()
+ .ok_or(Error::MissingKeyAttributes)?;
+ let kek = match key_encryption_key {
+ Some(key) => SecretVec::new(key),
+ None => auth::derive_kek(
+ &password,
+ &attributes.kek_salt,
+ attributes.mem_limit,
+ attributes.ops_limit,
+ )?,
+ };
- let account = login::unlock(&response, &kek)?;
++ let account = login::unlock(&self.0, &response, &kek)?;
+ Ok(UnlockedAccount {
+ master_key: b64::encode(&account.secrets.master_key),
+ secret_key: b64::encode(&account.secrets.secret_key),
+ token: b64::encode_url_safe(&account.secrets.token),
+ login_key: auth::derive_srp_login_key(&kek)?.into_vec(),
+ })
+ }
+
+ pub fn recover_account(
+ &self,
+ response: AuthResponse,
+ recovery_key: String,
+ ) -> Result<RecoveredAccount, AccountsError> {
- let account = login::recover_account(&response, &recovery_key)?;
++ let account = login::recover_account(&self.0, &response, &recovery_key)?;
+ Ok(RecoveredAccount {
+ master_key: b64::encode(&account.secrets.master_key),
+ secret_key: b64::encode(&account.secrets.secret_key),
+ token: b64::encode_url_safe(&account.secrets.token),
+ })
+ }
+
+ pub async fn change_password(
+ &self,
+ token: String,
+ email: String,
+ password: String,
+ master_key: Vec<u8>,
+ key_attributes: KeyAttributes,
+ log_out_other_devices: bool,
+ ) -> Result<KeyAttributes, AccountsError> {
+ let result = lifecycle::change_password(
+ &self.0.with_auth_token(token),
+ lifecycle::ChangePasswordParams {
+ email,
+ password: password.into(),
+ master_key: SecretVec::new(master_key),
+ key_attributes,
+ log_out_other_devices,
+ },
+ )
+ .await?;
+ Ok(result.key_attributes)
+ }
+
+ pub async fn setup_two_factor(&self, token: String) -> Result<TwoFactorSecret, AccountsError> {
+ self.0
+ .with_auth_token(token)
+ .setup_two_factor()
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn enable_two_factor(
+ &self,
+ token: String,
+ secret: String,
+ recovery_key: String,
+ code: String,
+ ) -> Result<(), AccountsError> {
+ lifecycle::enable_two_factor(
+ &self.0.with_auth_token(token),
+ &secret,
+ &recovery_key,
+ &code,
+ )
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn passkey_management_url(
+ &self,
+ token: String,
+ recovery_key: String,
+ ) -> Result<String, AccountsError> {
+ lifecycle::passkey_management_url(&self.0.with_auth_token(token), &recovery_key)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn get_two_factor_recovery(
+ &self,
+ two_factor_type: TwoFactorType,
+ session_id: String,
+ ) -> Result<TwoFactorRecoveryResponse, AccountsError> {
+ self.0
+ .get_two_factor_recovery(&session_id, two_factor_type)
+ .await
+ .map_err(Into::into)
+ }
+
+ pub async fn recover_two_factor(
+ &self,
+ two_factor_type: TwoFactorType,
+ session_id: String,
+ recovery_response: TwoFactorRecoveryResponse,
+ recovery_key: String,
+ ) -> Result<TwoFactorAuthorizationResponse, AccountsError> {
+ lifecycle::recover_two_factor(
+ &self.0,
+ two_factor_type,
+ &session_id,
+ &recovery_response,
+ &recovery_key,
+ )
+ .await
+ .map_err(Into::into)
+ }
+ }
+
+ #[frb(non_opaque)]
+ pub struct SrpAttributes {
+ pub srp_user_id: String,
+ pub srp_salt: String,
+ pub mem_limit: u64,
+ pub ops_limit: u32,
+ pub kek_salt: String,
+ pub is_email_mfa_enabled: bool,
+ }
+
+ impl From<auth::SrpAttributes> for SrpAttributes {
+ fn from(value: auth::SrpAttributes) -> Self {
+ Self {
+ srp_user_id: value.srp_user_id.to_string(),
+ srp_salt: value.srp_salt,
+ mem_limit: value.mem_limit,
+ ops_limit: value.ops_limit,
+ kek_salt: value.kek_salt,
+ is_email_mfa_enabled: value.is_email_mfa_enabled,
+ }
+ }
+ }
+
+ impl TryFrom<SrpAttributes> for auth::SrpAttributes {
+ type Error = ente_accounts::Error;
+
+ fn try_from(value: SrpAttributes) -> Result<Self, Self::Error> {
+ Ok(Self {
+ srp_user_id: value
+ .srp_user_id
+ .parse()
+ .map_err(|_| Error::InvalidInput("Invalid SRP user ID".into()))?,
+ srp_salt: value.srp_salt,
+ mem_limit: value.mem_limit,
+ ops_limit: value.ops_limit,
+ kek_salt: value.kek_salt,
+ is_email_mfa_enabled: value.is_email_mfa_enabled,
+ })
+ }
+ }
+
+ #[frb(non_opaque)]
+ pub struct PasswordLogin {
+ pub response: AuthResponse,
+ pub key_encryption_key: Vec<u8>,
+ }
+
+ #[frb(non_opaque)]
+ pub struct SrpSetup {
+ pub srp_user_id: String,
+ pub srp_salt: Vec<u8>,
+ pub srp_verifier: Vec<u8>,
+ pub login_key: Vec<u8>,
+ }
+
+ impl SrpSetup {
+ fn into_core(self) -> auth::GeneratedSrpSetup {
+ auth::GeneratedSrpSetup {
+ srp_salt: self.srp_salt,
+ srp_verifier: self.srp_verifier,
+ login_sub_key: SecretVec::new(self.login_key),
+ }
+ }
+ }
+
+ #[frb(non_opaque)]
+ pub struct SignupKeys {
+ pub key_attributes: KeyAttributes,
+ pub master_key: String,
+ pub secret_key: String,
+ pub recovery_key: String,
+ pub srp: SrpSetup,
+ }
+
+ #[frb(non_opaque)]
+ pub struct UnlockedAccount {
+ pub master_key: String,
+ pub secret_key: String,
+ pub token: String,
+ pub login_key: Vec<u8>,
+ }
+
+ #[frb(mirror(AuthResponse))]
+ pub struct _AuthResponse {
+ pub id: i64,
+ pub key_attributes: Option<KeyAttributes>,
+ pub encrypted_token: Option<String>,
+ pub token: Option<String>,
+ pub two_factor_session_id: Option<String>,
+ pub two_factor_session_id_v2: Option<String>,
+ pub passkey_session_id: Option<String>,
+ pub srp_m2: Option<String>,
+ pub accounts_url: Option<String>,
+ }
+
+ #[frb(mirror(TwoFactorType))]
+ pub enum _TwoFactorType {
+ Totp,
+ Passkey,
+ }
+
+ #[frb(mirror(TwoFactorRecoveryResponse))]
+ pub struct _TwoFactorRecoveryResponse {
+ pub encrypted_secret: String,
+ pub secret_decryption_nonce: String,
+ }
+
+ #[frb(mirror(TwoFactorAuthorizationResponse))]
+ pub struct _TwoFactorAuthorizationResponse {
+ pub id: i64,
+ pub key_attributes: KeyAttributes,
+ pub encrypted_token: String,
+ }
+
+ #[frb(mirror(KeyAttributes))]
+ pub struct _KeyAttributes {
+ pub kek_salt: String,
+ pub encrypted_key: String,
+ pub key_decryption_nonce: String,
+ pub public_key: String,
+ pub encrypted_secret_key: String,
+ pub secret_key_decryption_nonce: String,
+ pub mem_limit: u64,
+ pub ops_limit: u32,
+ pub master_key_encrypted_with_recovery_key: Option<String>,
+ pub master_key_decryption_nonce: Option<String>,
+ pub recovery_key_encrypted_with_master_key: Option<String>,
+ pub recovery_key_decryption_nonce: Option<String>,
+ }
+
+ #[frb(non_opaque)]
+ pub struct RecoveredAccount {
+ pub master_key: String,
+ pub secret_key: String,
+ pub token: String,
+ }
+
+ #[frb(mirror(TwoFactorSecret))]
+ pub struct _TwoFactorSecret {
+ pub secret_code: String,
+ pub qr_code: String,
+ }
diff --cc rust/bindings/wasm/lib/src/accounts/client.rs
index 0000000000,56d55a7960..a67a7edfa3
mode 000000,100644..100644
--- a/rust/bindings/wasm/lib/src/accounts/client.rs
+++ b/rust/bindings/wasm/lib/src/accounts/client.rs
@@@ -1,0 -1,333 +1,340 @@@
+ use ente_accounts::{auth, lifecycle, login, signup};
+ use ente_core::{b64, crypto::SecretVec};
+ use serde::{Deserialize, Serialize};
+ use serde_wasm_bindgen as swb;
+ use tsify::{Ts, Tsify};
+ use wasm_bindgen::prelude::*;
+
+ use super::Error;
+
+ #[derive(Deserialize, Tsify)]
+ #[serde(rename_all = "camelCase")]
+ pub struct AccountsClientConfig {
+ origin: String,
+ client_package: String,
+ #[tsify(optional)]
+ client_version: Option<String>,
+ }
+
+ #[wasm_bindgen]
+ pub struct AccountsClient(ente_accounts::AccountsClient);
+
+ #[wasm_bindgen(js_name = createAccountsClient)]
+ pub fn create_accounts_client(config: Ts<AccountsClientConfig>) -> Result<AccountsClient, Error> {
+ let config = config.to_rust()?;
+ Ok(AccountsClient(ente_accounts::AccountsClient::new(
+ ente_accounts::AccountsClientConfig {
+ origin: config.origin,
+ client_package: config.client_package,
+ client_version: config.client_version,
+ user_agent: None,
+ auth_token: None,
+ },
+ )?))
+ }
+
+ #[wasm_bindgen(js_name = getSRPAttributes, unchecked_return_type = "unknown")]
+ pub async fn get_srp_attributes(client: &AccountsClient, email: &str) -> Result<JsValue, Error> {
+ let attributes = client.0.get_srp_attributes(email).await?;
+ swb::to_value(&attributes).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = sendOTP)]
+ pub async fn send_otp(client: &AccountsClient, email: &str, purpose: &str) -> Result<(), Error> {
+ client.0.send_otp(email, purpose, false).await?;
+ Ok(())
+ }
+
+ #[wasm_bindgen(js_name = verifyEmail, unchecked_return_type = "unknown")]
+ pub async fn verify_email(
+ client: &AccountsClient,
+ email: &str,
+ code: &str,
+ source: Option<String>,
+ ) -> Result<JsValue, Error> {
+ let response = client
+ .0
+ .verify_email(email, code, source.as_deref())
+ .await?;
+ swb::to_value(&response).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = verifySRP, unchecked_return_type = "unknown")]
+ pub async fn verify_srp(
+ client: &AccountsClient,
+ #[wasm_bindgen(unchecked_param_type = "unknown")] attributes: JsValue,
+ kek: &str,
+ ) -> Result<JsValue, Error> {
+ let response = client
+ .0
+ .verify_srp(&swb::from_value(attributes)?, &decode(kek)?)
+ .await?;
+ swb::to_value(&response).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = verifyTwoFactor, unchecked_return_type = "unknown")]
+ pub async fn verify_two_factor(
+ client: &AccountsClient,
+ session_id: &str,
+ code: &str,
+ ) -> Result<JsValue, Error> {
+ let response = client.0.verify_totp(session_id, code).await?;
+ swb::to_value(&response).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = checkPasskeyVerificationStatus, unchecked_return_type = "unknown")]
+ pub async fn check_passkey_verification_status(
+ client: &AccountsClient,
+ session_id: &str,
+ ) -> Result<JsValue, Error> {
+ let response = client.0.check_passkey_status(session_id).await?;
+ swb::to_value(&response).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = getSessionValidity, unchecked_return_type = "unknown")]
+ pub async fn get_session_validity(
+ client: &AccountsClient,
+ token: String,
+ ) -> Result<JsValue, Error> {
+ let response = client
+ .0
+ .with_auth_token(token)
+ .get_session_validity()
+ .await?;
+ swb::to_value(&response).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = setKeyAttributes)]
+ pub async fn set_key_attributes(
+ client: &AccountsClient,
+ token: String,
+ #[wasm_bindgen(unchecked_param_type = "unknown")] attributes: JsValue,
+ ) -> Result<(), Error> {
+ client
+ .0
+ .with_auth_token(token)
+ .set_user_key_attributes(swb::from_value(attributes)?)
+ .await?;
+ Ok(())
+ }
+
+ #[derive(Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ struct SrpSetup {
+ #[serde(rename = "srpUserID")]
+ srp_user_id: String,
+ srp_salt: String,
+ srp_verifier: String,
+ login_sub_key: String,
+ }
+
+ impl SrpSetup {
+ fn decode(&self) -> Result<auth::GeneratedSrpSetup, Error> {
+ Ok(auth::GeneratedSrpSetup {
+ srp_salt: decode(&self.srp_salt)?,
+ srp_verifier: decode(&self.srp_verifier)?,
+ login_sub_key: SecretVec::new(decode(&self.login_sub_key)?),
+ })
+ }
+ }
+
+ #[wasm_bindgen(js_name = setupSRP)]
+ pub async fn setup_srp(
+ client: &AccountsClient,
+ token: String,
+ #[wasm_bindgen(unchecked_param_type = "unknown")] setup: JsValue,
+ ) -> Result<(), Error> {
+ let setup: SrpSetup = swb::from_value(setup)?;
+ signup::setup_srp(
+ &client.0.with_auth_token(token),
+ setup
+ .srp_user_id
+ .parse()
+ .map_err(|_| ente_accounts::Error::InvalidInput("Invalid SRP user ID".into()))?,
+ &setup.decode()?,
+ )
+ .await?;
+ Ok(())
+ }
+
+ #[wasm_bindgen(js_name = completeSignup, unchecked_return_type = "unknown")]
+ pub async fn complete_signup(
+ client: &AccountsClient,
+ email: &str,
+ token: String,
+ #[wasm_bindgen(unchecked_param_type = "unknown")] attributes: JsValue,
+ #[wasm_bindgen(unchecked_param_type = "unknown")] setup: JsValue,
+ ) -> Result<JsValue, Error> {
+ let setup: SrpSetup = swb::from_value(setup)?;
+ let attributes = signup::complete_signup(
+ &client.0.with_auth_token(token),
+ email,
+ &swb::from_value(attributes)?,
+ setup
+ .srp_user_id
+ .parse()
+ .map_err(|_| ente_accounts::Error::InvalidInput("Invalid SRP user ID".into()))?,
+ &setup.decode()?,
+ )
+ .await?;
+ swb::to_value(&attributes).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = unlockAccount, unchecked_return_type = "unknown")]
+ pub fn unlock_account(
++ client: &AccountsClient,
+ #[wasm_bindgen(unchecked_param_type = "unknown")] response: JsValue,
+ kek: &str,
+ ) -> Result<JsValue, Error> {
- let account = login::unlock(&swb::from_value(response)?, &decode(kek)?)?;
++ let account = login::unlock(&client.0, &swb::from_value(response)?, &decode(kek)?)?;
+ unlocked_account(account)
+ }
+
+ #[wasm_bindgen(js_name = unlockAccountWithMasterKey, unchecked_return_type = "unknown")]
+ pub fn unlock_account_with_master_key(
++ client: &AccountsClient,
+ #[wasm_bindgen(unchecked_param_type = "unknown")] response: JsValue,
+ master_key: &str,
+ ) -> Result<JsValue, Error> {
- let account = login::unlock_with_master_key(&swb::from_value(response)?, &decode(master_key)?)?;
++ let account = login::unlock_with_master_key(
++ &client.0,
++ &swb::from_value(response)?,
++ &decode(master_key)?,
++ )?;
+ unlocked_account(account)
+ }
+
+ #[derive(Serialize)]
+ #[serde(rename_all = "camelCase")]
+ struct UnlockedAccount {
+ master_key: String,
+ token: String,
+ }
+
+ fn unlocked_account(account: ente_accounts::AuthenticatedAccount) -> Result<JsValue, Error> {
+ swb::to_value(&UnlockedAccount {
+ master_key: b64::encode(&account.secrets.master_key),
+ token: b64::encode_url_safe(&account.secrets.token),
+ })
+ .map_err(Into::into)
+ }
+
+ fn decode(value: &str) -> Result<Vec<u8>, Error> {
+ b64::decode(value).map_err(|error| ente_accounts::Error::Decode(error.to_string()).into())
+ }
+
+ #[wasm_bindgen(js_name = getTwoFactorRecovery, unchecked_return_type = "unknown")]
+ pub async fn get_two_factor_recovery(
+ client: &AccountsClient,
+ two_factor_type: &str,
+ session_id: &str,
+ ) -> Result<JsValue, Error> {
+ let response = client
+ .0
+ .get_two_factor_recovery(
+ session_id,
+ swb::from_value(JsValue::from_str(two_factor_type))?,
+ )
+ .await?;
+ swb::to_value(&response).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = recoverTwoFactor, unchecked_return_type = "unknown")]
+ pub async fn recover_two_factor(
+ client: &AccountsClient,
+ two_factor_type: &str,
+ session_id: &str,
+ #[wasm_bindgen(unchecked_param_type = "unknown")] recovery_response: JsValue,
+ recovery_key: &str,
+ ) -> Result<JsValue, Error> {
+ let response = lifecycle::recover_two_factor(
+ &client.0,
+ swb::from_value(JsValue::from_str(two_factor_type))?,
+ session_id,
+ &swb::from_value(recovery_response)?,
+ recovery_key,
+ )
+ .await?;
+ swb::to_value(&response).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = recoverAccount, unchecked_return_type = "unknown")]
+ pub fn recover_account(
++ client: &AccountsClient,
+ #[wasm_bindgen(unchecked_param_type = "unknown")] response: JsValue,
+ recovery_key: &str,
+ ) -> Result<JsValue, Error> {
- let account = login::recover_account(&swb::from_value(response)?, recovery_key)?;
++ let account = login::recover_account(&client.0, &swb::from_value(response)?, recovery_key)?;
+ unlocked_account(account)
+ }
+
+ #[wasm_bindgen(js_name = changePassword, unchecked_return_type = "unknown")]
+ pub async fn change_password(
+ client: &AccountsClient,
+ token: String,
+ email: String,
+ password: String,
+ master_key: &str,
+ #[wasm_bindgen(unchecked_param_type = "unknown")] key_attributes: JsValue,
+ ) -> Result<JsValue, Error> {
+ let result = lifecycle::change_password(
+ &client.0.with_auth_token(token),
+ lifecycle::ChangePasswordParams {
+ email,
+ password: password.into(),
+ master_key: SecretVec::new(decode(master_key)?),
+ key_attributes: swb::from_value(key_attributes)?,
+ log_out_other_devices: false,
+ },
+ )
+ .await?;
+ swb::to_value(&result).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = setupTwoFactor, unchecked_return_type = "unknown")]
+ pub async fn setup_two_factor(client: &AccountsClient, token: String) -> Result<JsValue, Error> {
+ let response = client.0.with_auth_token(token).setup_two_factor().await?;
+ swb::to_value(&response).map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = enableTwoFactor)]
+ pub async fn enable_two_factor(
+ client: &AccountsClient,
+ token: String,
+ secret: &str,
+ recovery_key: &str,
+ code: &str,
+ ) -> Result<(), Error> {
+ lifecycle::enable_two_factor(&client.0.with_auth_token(token), secret, recovery_key, code)
+ .await?;
+ Ok(())
+ }
+
+ #[wasm_bindgen(js_name = passkeyManagementURL)]
+ pub async fn passkey_management_url(
+ client: &AccountsClient,
+ token: String,
+ recovery_key: &str,
+ ) -> Result<String, Error> {
+ lifecycle::passkey_management_url(&client.0.with_auth_token(token), recovery_key)
+ .await
+ .map_err(Into::into)
+ }
+
+ #[wasm_bindgen(js_name = checkSessionValidity, unchecked_return_type = "unknown")]
+ pub async fn check_session_validity(
+ client: &AccountsClient,
+ token: String,
+ email: String,
+ #[wasm_bindgen(unchecked_param_type = "unknown")] local_srp_attributes: JsValue,
+ ) -> Result<JsValue, Error> {
+ let result = lifecycle::check_session_validity(
+ &client.0.with_auth_token(token),
+ lifecycle::CheckSessionValidityParams {
+ email,
+ local_srp_attributes: swb::from_value(local_srp_attributes)?,
+ },
+ )
+ .await?;
+ swb::to_value(&result).map_err(Into::into)
+ }
diff --cc rust/crates/accounts/src/auth/mod.rs
index edbf133a21,791a245300..3c828633eb
--- a/rust/crates/accounts/src/auth/mod.rs
+++ b/rust/crates/accounts/src/auth/mod.rs
@@@ -1,6 -1,5 +1,6 @@@
mod api;
mod key_gen;
- mod payload;
++pub(crate) mod payload;
mod recovery;
mod srp;
mod types;
diff --cc rust/crates/accounts/src/auth/payload.rs
index 823a7aa572,0000000000..005c4867ad
mode 100644,000000..100644
--- a/rust/crates/accounts/src/auth/payload.rs
+++ b/rust/crates/accounts/src/auth/payload.rs
@@@ -1,93 -1,0 +1,72 @@@
- use ente_core::b64;
- use hmac::{Hmac, KeyInit, Mac};
- use sha2::Sha256;
- use zeroize::Zeroizing;
++use ente_core::{b64, crypto::hash::hmac_sha256, http::Api};
+
+use crate::{Error, Result, models::TwoFactorType};
+
- pub fn validate_auth_token(token: &[u8]) -> Result<()> {
- if token.len() != b"auth-token".len() + 32 || !token.starts_with(b"auth-token") {
- return Err(Error::Protocol(
- "Invalid login token. The server may need upgrading.".into(),
- ));
++pub(crate) fn enforce_auth_payloads(api: &Api) -> bool {
++ matches!(
++ api.origin_host().as_deref(),
++ Some("api.ente.com" | "api.ente.in" | "localhost")
++ )
++}
++
++pub(crate) fn validate_auth_token(api: &Api, token: &[u8]) -> Result<()> {
++ if enforce_auth_payloads(api)
++ && (token.len() != b"auth-token".len() + 32 || !token.starts_with(b"auth-token"))
++ {
++ return Err(Error::Protocol("Invalid login token".into()));
+ }
+ Ok(())
+}
+
- pub fn parse_delete_account_challenge(plaintext: &[u8]) -> Result<String> {
- let challenge = plaintext
- .strip_prefix(b"delete-jwt")
- .filter(|challenge| !challenge.is_empty())
- .ok_or_else(|| {
- Error::Protocol("Invalid deletion challenge. The server may need upgrading.".into())
- })?;
- String::from_utf8(challenge.to_vec())
- .map_err(|_| Error::Protocol("Invalid deletion challenge encoding".into()))
++pub(crate) fn deletion_challenge<'a>(api: &Api, plaintext: &'a str) -> Result<&'a str> {
++ match plaintext.strip_prefix("delete-jwt") {
++ Some(challenge) if !challenge.is_empty() => Ok(challenge),
++ None if !enforce_auth_payloads(api) => Ok(plaintext),
++ _ => Err(Error::Protocol("Invalid deletion challenge".into())),
++ }
+}
+
- pub fn two_factor_recovery_proof(
- secret: &[u8],
- two_factor_type: TwoFactorType,
++pub(crate) fn recovery_proof(
++ secret: &str,
++ factor: TwoFactorType,
+ session_id: &str,
+) -> Result<String> {
- let secret = Zeroizing::new(b64::encode(secret).into_bytes());
- let factor = match two_factor_type {
++ let factor = match factor {
+ TwoFactorType::Totp => "totp",
+ TwoFactorType::Passkey => "passkey",
+ };
- let mut mac =
- Hmac::<Sha256>::new_from_slice(&secret).map_err(|_| Error::IncorrectRecoveryKey)?;
- mac.update(format!("ente-two-factor-recovery:v1\0{factor}\0{session_id}").as_bytes());
- Ok(b64::encode(&mac.finalize().into_bytes()))
++ Ok(b64::encode(&hmac_sha256(
++ secret.as_bytes(),
++ format!("recovery:{factor}:{session_id}").as_bytes(),
++ )?))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
++ use crate::test_support::make_client;
+
+ #[test]
- fn deletion_requires_its_prefix_and_valid_utf8() {
- assert_eq!(
- parse_delete_account_challenge(b"delete-jwtheader.payload.signature").unwrap(),
- "header.payload.signature",
- );
- for payload in [
- vec![7; 32],
- [b"auth-token".as_slice(), &[7; 32]].concat(),
- b"header.payload.signature".to_vec(),
- b"delete-jwt".to_vec(),
- b"delete-jwt\xff".to_vec(),
- ] {
- assert!(parse_delete_account_challenge(&payload).is_err());
- }
- }
-
- #[test]
- fn recovery_proofs_bind_the_session_and_factor() {
- use TwoFactorType::{Passkey, Totp};
- let totp_secret = "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP";
- let totp_proof = "GLPadofZrER+5+7OLkqiNxlmyS6XzaKGdsMeHg1lnvU=";
- for (factor, plaintext, expected) in [
- (Totp, b64::decode(totp_secret).unwrap(), totp_proof),
- (
- Passkey,
- (0..32).collect(),
- "PxcSH0NrKUX3u330jU6TtYp/I/mT4087vajBXIdPh0I=",
- ),
++ fn enforcement_uses_the_configured_hostname() {
++ for (origin, expected) in [
++ ("https://api.ente.com", true),
++ ("https://api.ente.in:443/prefix", true),
++ ("http://localhost:8080", true),
++ ("https://API.ENTE.COM", true),
++ ("https://self-hosted.example", false),
++ ("http://127.0.0.1:8080", false),
++ ("http://[::1]:8080", false),
++ ("https://api.ente.com.example", false),
++ ("https://[email protected]", false),
++ ("https://example.org/api.ente.com", false),
+ ] {
++ let client = make_client(origin.into());
++ assert_eq!(enforce_auth_payloads(&client.api), expected, "{origin}");
+ assert_eq!(
- two_factor_recovery_proof(&plaintext, factor, "recovery-session").unwrap(),
- expected
- );
- assert_ne!(
- two_factor_recovery_proof(&plaintext, factor, "other-session").unwrap(),
- expected
- );
- let other_factor = if factor == Totp { Passkey } else { Totp };
- assert_ne!(
- two_factor_recovery_proof(&plaintext, other_factor, "recovery-session").unwrap(),
- expected
++ deletion_challenge(&client.api, "delete-jwtjwt").unwrap(),
++ "jwt"
+ );
++ assert_eq!(deletion_challenge(&client.api, "jwt").is_err(), expected);
+ }
+ }
+}
diff --cc rust/crates/accounts/src/deletion.rs
index 0000000000,41cc4926bf..23be1f1cb1
mode 000000,100644..100644
--- a/rust/crates/accounts/src/deletion.rs
+++ b/rust/crates/accounts/src/deletion.rs
@@@ -1,0 -1,71 +1,72 @@@
+ use ente_core::{Session, b64, crypto::sealed, http};
+ use serde::{Deserialize, Serialize};
+
-use crate::{Error, Result};
++use crate::{Error, Result, auth::payload};
+
+ #[derive(Debug, Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ pub struct AccountDeletionSummary {
+ pub photos_and_videos_count: i64,
+ pub authenticator_codes_count: i64,
+ pub locker_records_count: i64,
+ }
+
+ pub async fn get_deletion_summary(session: &Session) -> Result<Option<AccountDeletionSummary>> {
+ let response = send_request(session.api.get("/users/deletion-summary")).await;
+ match response {
+ Ok(response) => Ok(Some(response.json().await?)),
+ Err(error) if error.status_code() == Some(404) => Ok(None),
+ Err(error) => Err(error.into()),
+ }
+ }
+
+ pub async fn get_delete_challenge(session: &Session) -> Result<String> {
+ #[derive(Deserialize)]
+ #[serde(rename_all = "camelCase")]
+ struct Response {
+ encrypted_challenge: String,
+ }
+
+ let response: Response = send_request(session.api.get("/users/delete-challenge"))
+ .await?
+ .json()
+ .await?;
+ Ok(response.encrypted_challenge)
+ }
+
+ pub async fn delete_account(
+ session: &Session,
+ encrypted_challenge: &str,
+ reason: &str,
+ feedback: Option<&str>,
+ ) -> Result<()> {
+ #[derive(Serialize)]
+ #[serde(rename_all = "camelCase")]
+ struct Request<'a> {
- challenge: String,
++ challenge: &'a str,
+ reason_category: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ feedback: Option<&'a str>,
+ }
+
+ let challenge = sealed::open(
+ &b64::decode(encrypted_challenge)?,
+ &session.secret_key.public_key(),
+ &session.secret_key,
+ )?;
+ let challenge = String::from_utf8(challenge).map_err(|e| Error::Decode(e.to_string()))?;
++ let challenge = payload::deletion_challenge(&session.api, &challenge)?;
+ send_request(session.api.delete("/users/delete").json(&Request {
+ challenge,
+ reason_category: reason,
+ feedback: feedback.filter(|value| !value.is_empty()),
+ }))
+ .await?;
+ Ok(())
+ }
+
+ async fn send_request(
+ request: http::RequestBuilder,
+ ) -> std::result::Result<http::SuccessResponse, http::Error> {
+ request.send().await?.error_for_code().await
+ }
diff --cc rust/crates/accounts/src/lifecycle.rs
index d091f5047a,8392342e40..b142b6ffd9
--- a/rust/crates/accounts/src/lifecycle.rs
+++ b/rust/crates/accounts/src/lifecycle.rs
@@@ -253,17 -264,15 +264,29 @@@ pub async fn recover_two_factor
let recovery_key = auth::recovery_key_from_mnemonic_or_hex(recovery_key_mnemonic_or_hex)?;
let encrypted_secret = b64::decode(&recovery_response.encrypted_secret)?;
let nonce = b64::decode(&recovery_response.secret_decryption_nonce)?;
- let secret = SecretVec::new(
- secretbox::decrypt(
- &encrypted_secret,
- &crypto::Nonce::try_from_slice(&nonce)?,
- &crypto::Key::try_from_slice(&recovery_key)?,
+ let secret = secretbox::decrypt(
+ &encrypted_secret,
+ &crypto::Nonce::try_from_slice(&nonce)?,
+ &crypto::Key::try_from_slice(&recovery_key)?,
+ )
+ .map_err(|_| Error::IncorrectRecoveryKey)?;
++ let secret = Zeroizing::new(b64::encode(&secret));
++ let (secret, proof) = if auth::payload::enforce_auth_payloads(&client.api) {
++ (
++ None,
++ Some(auth::payload::recovery_proof(
++ &secret,
++ two_factor_type,
++ session_id,
++ )?),
+ )
- .map_err(|_| Error::IncorrectRecoveryKey)?,
- );
++ } else {
++ (Some(secret.to_string()), None)
++ };
let request = RemoveTwoFactorRequest {
session_id: session_id.to_string(),
- proof: auth::two_factor_recovery_proof(&secret, two_factor_type, session_id)?,
- secret: b64::encode(&secret),
++ secret,
++ proof,
two_factor_type,
};
client.remove_two_factor(&request).await
diff --cc rust/crates/accounts/src/lifecycle/tests.rs
index 4f86564f4e,5d861ba602..842e97fdfb
--- a/rust/crates/accounts/src/lifecycle/tests.rs
+++ b/rust/crates/accounts/src/lifecycle/tests.rs
@@@ -166,65 -166,57 +166,72 @@@ async fn two_factor_recovery_preserves_
let recovery_key =
crypto::Key::try_from_slice(&hex::decode(&recovery_key_hex).unwrap()).unwrap();
let mut server = Server::new_async().await;
-- let client = make_client(server.url());
--
- for (factor, secret, proof) in [
- (
- TwoFactorType::Totp,
- TOTP_SECRET,
- "GLPadofZrER+5+7OLkqiNxlmyS6XzaKGdsMeHg1lnvU=",
- ),
- (
- TwoFactorType::Passkey,
- PASSKEY_SECRET,
- "PxcSH0NrKUX3u330jU6TtYp/I/mT4087vajBXIdPh0I=",
- ),
- for (factor, secret) in [
- (TwoFactorType::Totp, TOTP_SECRET),
- (TwoFactorType::Passkey, PASSKEY_SECRET),
-- ] {
-- let encrypted = secretbox::encrypt(&b64::decode(secret).unwrap(), &recovery_key);
- for status in [200, 400] {
- let sent = Arc::new(Mutex::new(None));
- let captured = Arc::clone(&sent);
- let remove = server
- .mock("POST", "/users/two-factor/remove")
- .match_body(Matcher::Json(serde_json::json!({
- "sessionID": "recovery-session",
- "secret": secret,
- "twoFactorType": factor,
- })))
- .with_status(200)
- .with_body(
- serde_json::json!({
- "id": 1,
- "keyAttributes": keys.key_attributes,
- "encryptedToken": "encrypted-token",
- })
- .to_string(),
- )
- .create_async()
- .await;
-
- let envelope = TwoFactorRecoveryResponse {
- encrypted_secret: b64::encode(&encrypted.encrypted_data),
- secret_decryption_nonce: b64::encode(encrypted.nonce.as_bytes()),
++ for strict in [false, true] {
++ let origin = if strict {
++ server.url().replace("127.0.0.1", "localhost")
++ } else {
++ server.url()
+ };
- assert!(matches!(
++ let client = make_client(origin);
++
++ for (factor, secret, proof) in [
++ (
++ TwoFactorType::Totp,
++ TOTP_SECRET,
++ "CBPrRdwiN5FRHBSQfTRIaEAN8Psf46H3iA3IugLVPqw=",
++ ),
++ (
++ TwoFactorType::Passkey,
++ PASSKEY_SECRET,
++ "f+nF2g7+BGieMdZ8uJLndOcDP5GX2ffGgLk5DhHqKFI=",
++ ),
++ ] {
++ let encrypted = secretbox::encrypt(&b64::decode(secret).unwrap(), &recovery_key);
+ let remove = server
+ .mock("POST", "/users/two-factor/remove")
- .match_request(move |request| {
- *captured.lock().unwrap() =
- Some(parse_request_body::<serde_json::Value>(request));
- true
- })
- .with_status(status)
++ .match_body(Matcher::Json(serde_json::json!({
++ "sessionID": "recovery-session",
++ if strict { "proof" } else { "secret" }: if strict { proof } else { secret },
++ "twoFactorType": factor,
++ })))
++ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "id": 1,
+ "keyAttributes": keys.key_attributes,
+ "encryptedToken": "encrypted-token",
+ })
+ .to_string(),
+ )
- .expect(1)
+ .create_async()
+ .await;
+
- let result = recover_two_factor(
++ let envelope = TwoFactorRecoveryResponse {
++ encrypted_secret: b64::encode(&encrypted.encrypted_data),
++ secret_decryption_nonce: b64::encode(encrypted.nonce.as_bytes()),
++ };
++ assert!(matches!(
++ recover_two_factor(
++ &client,
++ factor,
++ "recovery-session",
++ &envelope,
++ &hex::encode(crypto::Key::generate().as_bytes()),
++ )
++ .await,
++ Err(Error::IncorrectRecoveryKey)
++ ));
+ recover_two_factor(
&client,
factor,
"recovery-session",
- &TwoFactorRecoveryResponse {
- encrypted_secret: b64::encode(&encrypted.encrypted_data),
- secret_decryption_nonce: b64::encode(encrypted.nonce.as_bytes()),
- },
+ &envelope,
- &hex::encode(crypto::Key::generate().as_bytes()),
+ &recovery_key_hex,
)
- .await;
- assert_eq!(result.is_ok(), status == 200, "{factor:?}: {result:?}");
- assert_eq!(
- *sent.lock().unwrap(),
- Some(serde_json::json!({
- "sessionId": "recovery-session", "twoFactorType": factor,
- "proof": proof,
- }))
- );
- .await,
- Err(Error::IncorrectRecoveryKey)
- ));
- recover_two_factor(
- &client,
- factor,
- "recovery-session",
- &envelope,
- &recovery_key_hex,
- )
- .await
- .unwrap();
- remove.assert_async().await;
++ .await
++ .unwrap();
+ remove.assert_async().await;
+ }
}
}
diff --cc rust/crates/accounts/src/login.rs
index 76e559ebfd,51ff91bd57..7f366c0b56
--- a/rust/crates/accounts/src/login.rs
+++ b/rust/crates/accounts/src/login.rs
@@@ -2,7 -5,7 +5,7 @@@ use ente_core::
use crate::{
AccountSecrets, AccountsClient, AuthenticatedAccount, Error, Result,
- auth::{self, DecryptedSecrets, KeyAttributes, SrpAttributes, derive_kek, get_recovery_key},
- auth::{self, KeyAttributes, SrpAttributes, derive_kek, get_recovery_key},
++ auth::{self, KeyAttributes, SrpAttributes, derive_kek, get_recovery_key, payload},
models::AuthResponse,
};
@@@ -64,22 -71,16 +71,16 @@@ impl LoginFlow
return Err(Error::InvalidInput("Password is not expected".into()));
};
if let Some(response) = response {
- let attributes = response
- .key_attributes
- .as_ref()
- .ok_or(Error::MissingKeyAttributes)?;
- let kek = derive_kek(
- password,
- &attributes.kek_salt,
- attributes.mem_limit,
- attributes.ops_limit,
- )?;
- let account = build_authenticated_account(response, &kek)?;
- let account = unlock_with_password(response, password)?;
++ let account = unlock_with_password(client, response, password)?;
self.state = State::Complete;
Ok(LoginStep::Complete(Box::new(account)))
} else {
- let (response, kek) = client.login_with_srp(password, &self.attributes).await?;
- self.advance(response, Some(kek))
+ let attributes = self
+ .attributes
+ .as_ref()
+ .ok_or(Error::MissingField("SRP attributes"))?;
+ let (response, kek) = client.login_with_srp(password, attributes).await?;
- self.advance(response, Some(kek))
++ self.advance(client, response, Some(kek))
}
}
@@@ -102,7 -103,7 +103,7 @@@
));
}
};
-- self.advance(response, kek)
++ self.advance(client, response, kek)
}
pub async fn resend_code(&self, client: &AccountsClient) -> Result<()> {
@@@ -142,7 -143,7 +143,7 @@@
State::SecondFactor { kek, .. } => kek.as_ref().map(|key| SecretVec::new(key.to_vec())),
_ => None,
};
-- self.advance(verified, kek).map(Some)
++ self.advance(client, verified, kek).map(Some)
}
fn passkey_response(&self) -> Result<&AuthResponse> {
@@@ -152,7 -153,7 +153,12 @@@
}
}
-- fn advance(&mut self, response: AuthResponse, kek: Option<SecretVec>) -> Result<LoginStep> {
++ fn advance(
++ &mut self,
++ client: &AccountsClient,
++ response: AuthResponse,
++ kek: Option<SecretVec>,
++ ) -> Result<LoginStep> {
let totp = response.is_mfa_required();
let passkey = response.is_passkey_required();
if totp || passkey {
@@@ -160,7 -161,7 +166,7 @@@
return Ok(LoginStep::SecondFactor { totp, passkey });
}
if let Some(kek) = kek {
- let account = build_authenticated_account(&response, &kek)?;
- let account = unlock(&response, &kek)?;
++ let account = unlock(client, &response, &kek)?;
self.state = State::Complete;
Ok(LoginStep::Complete(Box::new(account)))
} else {
@@@ -195,24 -196,109 +201,131 @@@ pub fn build_passkey_verification_url
format!("{accounts_url}/passkeys/verify?{query}")
}
- fn build_authenticated_account(
+ pub fn unlock_with_password(
++ client: &AccountsClient,
+ auth_response: &AuthResponse,
+ password: &str,
+ ) -> Result<AuthenticatedAccount> {
+ let attributes = auth_response
+ .key_attributes
+ .as_ref()
+ .ok_or(Error::MissingKeyAttributes)?;
+ let kek = derive_kek(
+ password,
+ &attributes.kek_salt,
+ attributes.mem_limit,
+ attributes.ops_limit,
+ )?;
- unlock(auth_response, &kek)
++ unlock(client, auth_response, &kek)
+ }
+
-pub fn unlock(auth_response: &AuthResponse, kek: &[u8]) -> Result<AuthenticatedAccount> {
++pub fn unlock(
++ client: &AccountsClient,
+ auth_response: &AuthResponse,
+ kek: &[u8],
+) -> Result<AuthenticatedAccount> {
let key_attributes = auth_response
.key_attributes
- .clone()
+ .as_ref()
.ok_or(Error::MissingKeyAttributes)?;
- let secrets = decrypt_auth_response(auth_response, &key_attributes, kek)?;
+ let (master_key, secret_key) = auth::decrypt_keys_only(kek, key_attributes)?;
- finish_unlock(auth_response, key_attributes, master_key, secret_key)
++ finish_unlock(
++ client,
++ auth_response,
++ key_attributes,
++ master_key,
++ secret_key,
++ )
+ }
+
+ pub fn recover_account(
++ client: &AccountsClient,
+ auth_response: &AuthResponse,
+ recovery_key: &str,
+ ) -> Result<AuthenticatedAccount> {
+ let attributes = auth_response
+ .key_attributes
+ .as_ref()
+ .ok_or(Error::MissingKeyAttributes)?;
+ let recovery_key = auth::recovery_key_from_mnemonic_or_hex(recovery_key)?;
+ let encrypted = attributes
+ .master_key_encrypted_with_recovery_key
+ .as_ref()
+ .ok_or(Error::MissingField(
+ "master_key_encrypted_with_recovery_key",
+ ))?;
+ let nonce = attributes
+ .master_key_decryption_nonce
+ .as_ref()
+ .ok_or(Error::MissingField("master_key_decryption_nonce"))?;
+ let master_key = SecretVec::new(
+ ente_core::crypto::secretbox::decrypt(
+ &b64::decode(encrypted)?,
+ &ente_core::crypto::Nonce::try_from_slice(&b64::decode(nonce)?)?,
+ &Key::try_from_slice(&recovery_key)?,
+ )
+ .map_err(|_| Error::IncorrectRecoveryKey)?,
+ );
- unlock_with_master_key(auth_response, &master_key)
++ unlock_with_master_key(client, auth_response, &master_key)
+ }
+
+ pub fn unlock_with_master_key(
++ client: &AccountsClient,
+ auth_response: &AuthResponse,
+ master_key: &[u8],
+ ) -> Result<AuthenticatedAccount> {
+ let key_attributes = auth_response
+ .key_attributes
+ .as_ref()
+ .ok_or(Error::MissingKeyAttributes)?;
+ let master_key = Key::try_from_slice(master_key)?;
+ let secret_key = auth::decrypt_secret_key(&master_key, key_attributes)?;
- finish_unlock(auth_response, key_attributes, master_key, secret_key)
++ finish_unlock(
++ client,
++ auth_response,
++ key_attributes,
++ master_key,
++ secret_key,
++ )
+ }
+
+ fn finish_unlock(
++ client: &AccountsClient,
+ auth_response: &AuthResponse,
+ key_attributes: &KeyAttributes,
+ master_key: Key,
+ secret_key: SecretKey,
+ ) -> Result<AuthenticatedAccount> {
+ if auth_response.is_mfa_required() || auth_response.is_passkey_required() {
+ return Err(Error::InvalidInput(
+ "Second factor verification is required".into(),
+ ));
+ }
+ let token = if let Some(encrypted_token) = &auth_response.encrypted_token {
- SecretVec::new(
++ let token = SecretVec::new(
+ sealed::open(
+ &b64::decode(encrypted_token)?,
+ &secret_key.public_key(),
+ &secret_key,
+ )
+ .map_err(|_| Error::InvalidKeyAttributes)?,
- )
++ );
++ payload::validate_auth_token(&client.api, &token)?;
++ token
+ } else if let Some(token) = &auth_response.token {
+ decode_plain_token(token)?
+ } else {
+ return Err(Error::Protocol("No token in response".into()));
+ };
let public_key = b64::decode(&key_attributes.public_key)?;
- let recovery_key = get_recovery_key(&secrets.master_key, &key_attributes).ok();
+ let recovery_key = get_recovery_key(&master_key, key_attributes)?;
Ok(AuthenticatedAccount {
user_id: auth_response.id,
- key_attributes,
+ key_attributes: key_attributes.clone(),
secrets: AccountSecrets {
- token: secrets.token.into_vec(),
- master_key: secrets.master_key.as_bytes().to_vec(),
- secret_key: secrets.secret_key.as_bytes().to_vec(),
+ token: token.into_vec(),
+ master_key: master_key.as_bytes().to_vec(),
+ secret_key: secret_key.as_bytes().to_vec(),
public_key,
},
recovery_key,
diff --cc rust/crates/accounts/src/login/tests.rs
index 62a9aea790,39331d47f6..cb58dbbc9c
--- a/rust/crates/accounts/src/login/tests.rs
+++ b/rust/crates/accounts/src/login/tests.rs
@@@ -373,3 -390,36 +390,98 @@@ async fn passkey_expiry_is_preserved()
));
status.assert_async().await;
}
+
+ #[test]
+ fn recovery_unlocks_the_same_account_for_hex_and_mnemonic() {
+ let keys = auth::generate_keys_with_strength("pw", KeyDerivationStrength::Interactive).unwrap();
- let token = [42; 32];
++ let token = [b"auth-token".as_slice(), &[42; 32]].concat();
+ let public_key =
+ crypto::PublicKey::try_from_slice(&b64::decode(&keys.key_attributes.public_key).unwrap())
+ .unwrap();
+ let response: AuthResponse = serde_json::from_value(json!({
+ "id": 77,
+ "keyAttributes": keys.key_attributes,
+ "encryptedToken": b64::encode(&crypto::sealed::seal(&token, &public_key).unwrap()),
+ }))
+ .unwrap();
+ let recovery_key = &*keys.private_key_attributes.recovery_key;
+ let mnemonic = auth::recovery_key_to_mnemonic(&hex::decode(recovery_key).unwrap()).unwrap();
+ for value in [recovery_key, mnemonic.as_str()] {
- let account = recover_account(&response, value).unwrap();
++ let account = recover_account(
++ &make_client("https://api.ente.com".into()),
++ &response,
++ value,
++ )
++ .unwrap();
+ assert_eq!(account.secrets.token, token);
+ assert_eq!(
+ b64::encode(&account.secrets.master_key),
+ &*keys.private_key_attributes.key
+ );
+ assert_eq!(
+ b64::encode(&account.secrets.secret_key),
+ &*keys.private_key_attributes.secret_key
+ );
+ }
+ assert!(matches!(
- recover_account(&response, &hex::encode([0; 32])),
++ recover_account(
++ &make_client("https://api.ente.com".into()),
++ &response,
++ &hex::encode([0; 32])
++ ),
+ Err(Error::IncorrectRecoveryKey)
+ ));
+ }
++
++#[test]
++fn encrypted_tokens_require_the_login_tag_on_enforced_endpoints() {
++ let keys = auth::generate_keys_with_strength("pw", KeyDerivationStrength::Interactive).unwrap();
++ let attributes = &keys.key_attributes;
++ let kek = derive_kek(
++ "pw",
++ &attributes.kek_salt,
++ attributes.mem_limit,
++ attributes.ops_limit,
++ )
++ .unwrap();
++ let master_key = b64::decode(&keys.private_key_attributes.key).unwrap();
++ let public_key =
++ crypto::PublicKey::try_from_slice(&b64::decode(&attributes.public_key).unwrap()).unwrap();
++ for origin in ["http://localhost:8080", "https://self-hosted.example"] {
++ let client = make_client(origin.into());
++ for (token, tagged) in [
++ ([b"auth-token".as_slice(), &[1; 32]].concat(), true),
++ (vec![1; 32], false),
++ ([b"auth-token".as_slice(), &[1; 31]].concat(), false),
++ ([b"auth-token".as_slice(), &[1; 33]].concat(), false),
++ (b"delete-jwtheader.payload.signature".to_vec(), false),
++ ] {
++ let mut response: AuthResponse = serde_json::from_value(json!({
++ "id": 77, "keyAttributes": attributes,
++ "encryptedToken": b64::encode(&crypto::sealed::seal(&token, &public_key).unwrap()),
++ }))
++ .unwrap();
++ for result in [
++ unlock(&client, &response, &kek),
++ unlock_with_master_key(&client, &response, &master_key),
++ recover_account(
++ &client,
++ &response,
++ &keys.private_key_attributes.recovery_key,
++ ),
++ ] {
++ if tagged || origin == "https://self-hosted.example" {
++ assert_eq!(result.unwrap().secrets.token, token);
++ } else {
++ assert!(matches!(result, Err(Error::Protocol(_))));
++ }
++ }
++ response.encrypted_token = None;
++ response.token = Some(b64::encode_url_safe(&token));
++ assert_eq!(
++ unlock(&client, &response, &kek).unwrap().secrets.token,
++ token
++ );
++ }
++ }
++}
diff --cc rust/crates/accounts/src/models.rs
index 9a22f535e7,bdf7ef062c..99ef13cf6a
--- a/rust/crates/accounts/src/models.rs
+++ b/rust/crates/accounts/src/models.rs
@@@ -343,8 -346,9 +346,12 @@@ pub struct TwoFactorRecoveryResponse
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoveTwoFactorRequest {
+ #[serde(rename = "sessionID")]
pub session_id: String,
- pub proof: String,
- pub secret: String,
++ #[serde(skip_serializing_if = "Option::is_none")]
++ pub secret: Option<String>,
++ #[serde(skip_serializing_if = "Option::is_none")]
++ pub proof: Option<String>,
pub two_factor_type: TwoFactorType,
}
diff --cc rust/crates/accounts/tests/accounts.rs
index 8ee0c41931,f950b04b99..bb1a84cc32
--- a/rust/crates/accounts/tests/accounts.rs
+++ b/rust/crates/accounts/tests/accounts.rs
@@@ -18,7 -23,7 +23,7 @@@ fn accounts() -> TestResult
}
async fn run(endpoint: String) -> TestResult {
-- let endpoint = &endpoint;
++ let endpoint = &endpoint.replace("127.0.0.1", "localhost");
let email = format!(
"accounts-e2e-{}{HARDCODED_OTT_EMAIL_SUFFIX}",
Uuid::new_v4()
@@@ -81,7 -85,117 +85,136 @@@
)
.await?;
assert_eq!(recovered.id, created.user_id);
- assert!(!client.get_two_factor_status().await?);
+ let response = recovered.into();
- let recovered = ente_accounts::login::unlock_with_password(&response, &password)?;
- let restored =
- ente_accounts::login::unlock_with_master_key(&response, &created.secrets.master_key)?;
++ let recovered =
++ ente_accounts::login::unlock_with_password(&recovery_client, &response, &password)?;
++ let restored = ente_accounts::login::unlock_with_master_key(
++ &recovery_client,
++ &response,
++ &created.secrets.master_key,
++ )?;
+ assert_eq!(restored.secrets.token, recovered.secrets.token);
+ assert_eq!(restored.recovery_key, recovered.recovery_key);
+ let recovery_client =
+ recovery_client.with_auth_token(b64::encode_url_safe(&recovered.secrets.token));
+ assert_eq!(recovery_client.email().await?, email);
+ assert!(!recovery_client.get_two_factor_status().await?);
+ assert_eq!(recovered.secrets.master_key, created.secrets.master_key);
+
+ let original_srp_attributes = client.get_srp_attributes(&email).await?;
+ let new_password = format!("Changed-{}!", Uuid::new_v4().simple());
+ let changed = change_password(
+ &recovery_client,
+ ChangePasswordParams {
+ email: email.clone(),
+ password: Zeroizing::new(new_password.clone()),
+ master_key: SecretVec::new(recovered.secrets.master_key.clone()),
+ key_attributes: recovered.key_attributes.clone(),
+ log_out_other_devices: false,
+ },
+ )
+ .await?;
+ let validity = check_session_validity(
+ &client,
+ CheckSessionValidityParams {
+ email: email.clone(),
+ local_srp_attributes: original_srp_attributes,
+ },
+ )
+ .await?;
+ let SessionValidity::ValidButPasswordChanged {
+ updated_key_attributes,
+ updated_srp_attributes,
+ } = validity
+ else {
+ panic!("existing session did not detect the password change");
+ };
+ assert_eq!(
+ updated_key_attributes.kek_salt,
+ changed.key_attributes.kek_salt
+ );
+ assert_eq!(
+ updated_srp_attributes.srp_user_id,
+ changed.srp_attributes.srp_user_id
+ );
+
+ let login_client = accounts_client(endpoint);
+ assert!(matches!(
+ login_client
+ .login_with_srp(&password, &changed.srp_attributes)
+ .await,
+ Err(Error::IncorrectPassword)
+ ));
+ let (response, kek) = login_client
+ .login_with_srp(&new_password, &changed.srp_attributes)
+ .await?;
- let changed_login = unlock(&response, &kek)?;
++ let changed_login = unlock(&login_client, &response, &kek)?;
+ assert_eq!(changed_login.secrets.master_key, created.secrets.master_key);
+ login_client.send_otp(&email, "login", false).await?;
+ let response = login_client
+ .verify_email(&email, HARDCODED_OTT, None)
+ .await?;
- let recovered = recover_account(&response, &created.recovery_key)?;
++ let recovered = recover_account(&login_client, &response, &created.recovery_key)?;
+ assert_eq!(recovered.secrets.secret_key, created.secrets.secret_key);
+ let recovered_client =
+ login_client.with_auth_token(b64::encode_url_safe(&recovered.secrets.token));
+ assert_eq!(recovered_client.email().await?, email);
+
+ let reset_password = format!("Reset-{}!", Uuid::new_v4().simple());
+ let reset = change_password(
+ &recovered_client,
+ ChangePasswordParams {
+ email: email.clone(),
+ password: Zeroizing::new(reset_password.clone()),
+ master_key: SecretVec::new(recovered.secrets.master_key.clone()),
+ key_attributes: recovered.key_attributes.clone(),
+ log_out_other_devices: true,
+ },
+ )
+ .await?;
+ assert!(matches!(
+ check_session_validity(
+ &client,
+ CheckSessionValidityParams {
+ email: email.clone(),
+ local_srp_attributes: changed.srp_attributes,
+ },
+ )
+ .await?,
+ SessionValidity::Invalid
+ ));
+ assert_eq!(recovered_client.email().await?, email);
+ let (response, kek) = login_client
+ .login_with_srp(&reset_password, &reset.srp_attributes)
+ .await?;
+ assert_eq!(
- unlock(&response, &kek)?.secrets.master_key,
++ unlock(&login_client, &response, &kek)?.secrets.master_key,
+ created.secrets.master_key
+ );
+
+ let passkey_url = passkey_management_url(&recovered_client, &created.recovery_key).await?;
+ assert!(passkey_url.contains("/passkeys?token="));
+ assert!(
+ recovered_client
+ .get_two_factor_recovery_status()
+ .await?
+ .is_passkey_recovery_enabled
+ );
++ let session = ente_core::Session::new(
++ ente_core::http::ApiConfig {
++ auth: Some(ente_core::http::Auth::User(b64::encode_url_safe(
++ &recovered.secrets.token,
++ ))),
++ client_package: Some("io.ente.photos".into()),
++ ..ente_core::http::ApiConfig::new(endpoint.clone())
++ },
++ recovered.user_id,
++ ente_core::crypto::Key::try_from_slice(&recovered.secrets.master_key)?,
++ ente_core::crypto::Key::try_from_slice(&hex::decode(&recovered.recovery_key)?)?,
++ ente_core::crypto::SecretKey::try_from_slice(&recovered.secrets.secret_key)?,
++ )?;
++ let challenge = ente_accounts::deletion::get_delete_challenge(&session).await?;
++ ente_accounts::deletion::delete_account(&session, &challenge, "not_listed", None).await?;
Ok(())
}
diff --cc rust/crates/core/src/crypto/error.rs
index 87ed4ff3f7,87ed4ff3f7..5ebdb2c277
--- a/rust/crates/core/src/crypto/error.rs
+++ b/rust/crates/core/src/crypto/error.rs
@@@ -23,6 -23,6 +23,9 @@@ pub enum Error
#[error("Key derivation failed")]
KeyDerivationFailed,
++ #[error("MAC initialization failed")]
++ MacInitFailed,
++
#[error("Encryption failed")]
EncryptionFailed,
diff --cc rust/crates/core/src/crypto/hash.rs
index e1c3c1836c,e1c3c1836c..a5019793b3
--- a/rust/crates/core/src/crypto/hash.rs
+++ b/rust/crates/core/src/crypto/hash.rs
@@@ -2,6 -2,6 +2,8 @@@
// `crypto_generichash`.
use blake2b_simd::{Params as Blake2bParams, State as Blake2bState};
++use hmac::{Hmac, KeyInit, Mac};
++use sha2::Sha256;
use crate::crypto::{Error, Result};
@@@ -16,6 -16,6 +18,12 @@@ pub const KEY_BYTES_MIN: usize = 16
pub const KEY_BYTES_MAX: usize = 64;
++pub fn hmac_sha256(key: &[u8], data: &[u8]) -> Result<[u8; 32]> {
++ let mut mac = Hmac::<Sha256>::new_from_slice(key).map_err(|_| Error::MacInitFailed)?;
++ mac.update(data);
++ Ok(mac.finalize().into_bytes().into())
++}
++
pub fn hash(data: &[u8], out_len: Option<usize>, key: Option<&[u8]>) -> Result<Vec<u8>> {
let mut state = HashState::new(out_len, key)?;
state.update(data);
diff --cc rust/crates/core/src/http.rs
index d0a7ea69db,d0a7ea69db..43ab5464f3
--- a/rust/crates/core/src/http.rs
+++ b/rust/crates/core/src/http.rs
@@@ -247,6 -247,6 +247,13 @@@ impl Api
&self.http
}
++ pub fn origin_host(&self) -> Option<String> {
++ reqwest::Url::parse(&self.origin)
++ .ok()?
++ .host_str()
++ .map(str::to_owned)
++ }
++
pub fn set_auth(&self, auth: Option<Auth>) {
*self.auth.write().unwrap_or_else(PoisonError::into_inner) = auth;
}
diff --cc web/packages/accounts/services/user.ts
index f47eb3a97f,123e34d1c7..40f3f0bedb
--- a/web/packages/accounts/services/user.ts
+++ b/web/packages/accounts/services/user.ts
@@@ -311,6 -250,34 +250,44 @@@ export const resetSavedLocalUserTokens
return removeAuthToken();
};
+ const UnlockedAccount = z.object({ masterKey: z.string(), token: z.string() });
+
+ export const unlockAccountWithKEK = async (
+ response: EmailOrSRPVerificationResponse,
+ kek: string,
-) => UnlockedAccount.parse(await unlockAccount(response, kek));
++) =>
++ UnlockedAccount.parse(
++ await withAccountsClient((client) =>
++ unlockAccount(client, response, kek),
++ ),
++ );
+
+ export const unlockAccountWithKey = async (
+ response: EmailOrSRPVerificationResponse,
+ masterKey: string,
+ ) =>
+ UnlockedAccount.parse(
- await unlockAccountWithMasterKey(response, masterKey),
++ await withAccountsClient((client) =>
++ unlockAccountWithMasterKey(client, response, masterKey),
++ ),
+ );
+
+ export const recoverAccount = async (
+ keyAttributes: KeyAttributes,
+ recoveryKey: string,
+ ) => {
+ const user = savedPartialLocalUser()!;
+ return UnlockedAccount.parse(
- await rustRecoverAccount(
- { ...user, id: user.id!, keyAttributes },
- recoveryKey,
++ await withAccountsClient((client) =>
++ rustRecoverAccount(
++ client,
++ { ...user, id: user.id!, keyAttributes },
++ recoveryKey,
++ ),
+ ),
+ );
+ };
+
export const decryptAndStoreTokenIfNeeded = async (
keyAttributes: KeyAttributes,
masterKey: string,
diff --cc web/packages/wasm/prelogin/index.ts
index 852fee5b9b,e5f2345845..e6a4b51e73
--- a/web/packages/wasm/prelogin/index.ts
+++ b/web/packages/wasm/prelogin/index.ts
@@@ -21,20 -23,123 +23,125 @@@ export const deriveKey = async
) =>
(await wasm()).authDeriveKek(password, saltB64, BigInt(memLimit), opsLimit);
- export const deriveSensitiveKey = async (password: string) =>
- (await wasm()).authGenerateSensitiveKek(password);
+ export const generateSRPSetup = async (kekB64: string, srpUserID: string) =>
+ (await wasm()).authGenerateSrpSetup(kekB64, srpUserID);
- export const deriveInteractiveKey = async (password: string) =>
- (await wasm()).authGenerateInteractiveKek(password);
+ export const createAccountsClient = async (config: AccountsClientConfig) =>
+ (await wasm()).createAccountsClient(config);
+
+ export const getSRPAttributes = async (
+ client: AccountsClient,
+ email: string,
+ ): Promise<unknown> => (await wasm()).getSRPAttributes(client, email);
+
+ export const sendOTP = async (
+ client: AccountsClient,
+ email: string,
+ purpose: string,
+ ) => (await wasm()).sendOTP(client, email, purpose);
+
+ export const verifyEmail = async (
+ client: AccountsClient,
+ email: string,
+ code: string,
+ source?: string,
+ ): Promise<unknown> => (await wasm()).verifyEmail(client, email, code, source);
+
+ export const verifySRP = async (
+ client: AccountsClient,
+ attributes: unknown,
+ kek: string,
+ ): Promise<unknown> => (await wasm()).verifySRP(client, attributes, kek);
+
+ export const verifyTwoFactor = async (
+ client: AccountsClient,
+ sessionID: string,
+ code: string,
+ ): Promise<unknown> => (await wasm()).verifyTwoFactor(client, sessionID, code);
- export const deriveSRPLoginKey = async (kekB64: string) =>
- (await wasm()).authDeriveSrpLoginKey(kekB64);
+ export const checkPasskeyVerificationStatus = async (
+ client: AccountsClient,
+ sessionID: string,
+ ): Promise<unknown> =>
+ (await wasm()).checkPasskeyVerificationStatus(client, sessionID);
+
+ export const setKeyAttributes = async (
+ client: AccountsClient,
+ token: string,
+ attributes: unknown,
+ ) => (await wasm()).setKeyAttributes(client, token, attributes);
+
+ export const getSessionValidity = async (
+ client: AccountsClient,
+ token: string,
+ ): Promise<unknown> => (await wasm()).getSessionValidity(client, token);
+
+ export const setupSRP = async (
+ client: AccountsClient,
+ token: string,
+ setup: unknown,
+ ) => (await wasm()).setupSRP(client, token, setup);
+
+ export const completeSignup = async (
+ client: AccountsClient,
+ email: string,
+ token: string,
+ attributes: unknown,
+ setup: unknown,
+ ): Promise<unknown> =>
+ (await wasm()).completeSignup(client, email, token, attributes, setup);
+
+ export const unlockAccount = async (
++ client: AccountsClient,
+ response: unknown,
+ kek: string,
-): Promise<unknown> => (await wasm()).unlockAccount(response, kek);
++): Promise<unknown> => (await wasm()).unlockAccount(client, response, kek);
+
+ export const unlockAccountWithMasterKey = async (
++ client: AccountsClient,
+ response: unknown,
+ masterKey: string,
+ ): Promise<unknown> =>
- (await wasm()).unlockAccountWithMasterKey(response, masterKey);
++ (await wasm()).unlockAccountWithMasterKey(client, response, masterKey);
+
+ export const generateSignupKeys = async (password: string, srpUserID: string) =>
+ (await wasm()).authGenerateSignupKeys(password, srpUserID);
+
+ export const generateInteractiveKeyAttributes = async (
+ password: string,
+ attributes: unknown,
+ masterKey: string,
+ ): Promise<unknown> =>
+ (await wasm()).authGenerateInteractiveKeyAttributes(
+ password,
+ attributes,
+ masterKey,
+ );
- export const generateSRPSetup = async (kekB64: string, srpUserID: string) =>
- (await wasm()).authGenerateSrpSetup(kekB64, srpUserID);
+ export const getTwoFactorRecovery = async (
+ client: AccountsClient,
+ twoFactorType: "totp" | "passkey",
+ sessionID: string,
+ ): Promise<unknown> =>
+ (await wasm()).getTwoFactorRecovery(client, twoFactorType, sessionID);
- export const recoveryKeyFromMnemonicOrHex = async (value: string) =>
- (await wasm()).authRecoveryKeyFromMnemonicOrHex(value);
+ export const recoverTwoFactor = async (
+ client: AccountsClient,
+ twoFactorType: "totp" | "passkey",
+ sessionID: string,
+ recoveryResponse: {
+ encryptedSecret: string;
+ secretDecryptionNonce: string;
+ },
+ recoveryKey: string,
+ ): Promise<unknown> =>
+ (await wasm()).recoverTwoFactor(
+ client,
+ twoFactorType,
+ sessionID,
+ recoveryResponse,
+ recoveryKey,
+ );
export const recoveryKeyToMnemonic = async (recoveryKeyB64: string) =>
(await wasm()).authRecoveryKeyToMnemonic(recoveryKeyB64);
@@@ -94,3 -165,57 +167,59 @@@ const toB64String = (value: Uint8Array
for (const byte of value) binary += String.fromCharCode(byte);
return btoa(binary);
};
+
+ export const recoverAccount = async (
++ client: AccountsClient,
+ response: unknown,
+ recoveryKey: string,
-): Promise<unknown> => (await wasm()).recoverAccount(response, recoveryKey);
++): Promise<unknown> =>
++ (await wasm()).recoverAccount(client, response, recoveryKey);
+
+ export const changePassword = async (
+ client: AccountsClient,
+ token: string,
+ email: string,
+ password: string,
+ masterKey: string,
+ keyAttributes: unknown,
+ ): Promise<unknown> =>
+ (await wasm()).changePassword(
+ client,
+ token,
+ email,
+ password,
+ masterKey,
+ keyAttributes,
+ );
+
+ export const setupTwoFactor = async (
+ client: AccountsClient,
+ token: string,
+ ): Promise<unknown> => (await wasm()).setupTwoFactor(client, token);
+
+ export const enableTwoFactor = async (
+ client: AccountsClient,
+ token: string,
+ secret: string,
+ recoveryKey: string,
+ code: string,
+ ) => (await wasm()).enableTwoFactor(client, token, secret, recoveryKey, code);
+
+ export const passkeyManagementURL = async (
+ client: AccountsClient,
+ token: string,
+ recoveryKey: string,
+ ) => (await wasm()).passkeyManagementURL(client, token, recoveryKey);
+
+ export const checkSessionValidity = async (
+ client: AccountsClient,
+ token: string,
+ email: string,
+ localSRPAttributes: unknown,
+ ): Promise<unknown> =>
+ (await wasm()).checkSessionValidity(
+ client,
+ token,
+ email,
+ localSRPAttributes,
+ );
diff --cc web/packages/wasm/prelogin/tests/auth.test.ts
index 3d911cc6ef,828e97866e..9524d8c964
--- a/web/packages/wasm/prelogin/tests/auth.test.ts
+++ b/web/packages/wasm/prelogin/tests/auth.test.ts
@@@ -1,8 -1,13 +1,14 @@@
- import { expect, test } from "vitest";
- import { deriveKey } from "../index";
++import { createHmac } from "node:crypto";
+ import { expect, test, vi } from "vitest";
+ import {
+ createAccountsClient,
+ deriveKey,
+ encryptBox,
+ getTwoFactorRecovery,
+ recoverTwoFactor,
+ recoveryKeyToMnemonic,
+ } from "../index";
import {
- authDeriveSrpLoginKey,
- authGenerateInteractiveKek,
authGenerateSrpSetup,
cryptoGenerateKey,
} from "../pkg/ente_prelogin_wasm.js";
@@@ -40,3 -29,116 +30,118 @@@ test("generates SRP setup attributes fr
0,
);
});
+
-test("recovers TOTP and passkey through Rust with the existing wire format", async () => {
++test("recovers TOTP and passkey through Rust with session-bound recovery proofs", async () => {
+ const recoveryKey = cryptoGenerateKey();
+ const recoveryKeyHex = Buffer.from(recoveryKey, "base64").toString("hex");
+ const authorization = {
+ id: 123,
+ encryptedToken: "sealed-token",
+ keyAttributes: {
+ kekSalt: "salt",
+ encryptedKey: "key",
+ keyDecryptionNonce: "nonce",
+ publicKey: "public-key",
+ encryptedSecretKey: "private-key",
+ secretKeyDecryptionNonce: "private-key-nonce",
+ memLimit: 67_108_864,
+ opsLimit: 2,
+ },
+ };
+ const factors = [
+ ["totp", "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP"],
+ ["passkey", cryptoGenerateKey()],
+ ] as const;
+ try {
+ for (const [factor, secret] of factors) {
+ const clientVersion = factor == "totp" ? undefined : "test";
+ const client = await createAccountsClient({
+ origin: "http://localhost",
+ clientPackage: "io.ente.auth.web",
+ ...(clientVersion && { clientVersion }),
+ });
+ const encrypted = await encryptBox(secret, recoveryKey);
+ const envelope = {
+ encryptedSecret: encrypted.encryptedData,
+ secretDecryptionNonce: encrypted.nonce,
+ };
+ let status = 200;
+ const fetch = vi.fn(async (request: Request) => {
+ const url = new URL(request.url);
+ expect(url.origin).toBe("http://localhost");
+ expect(request.headers.get("X-Client-Package")).toBe(
+ "io.ente.auth.web",
+ );
+ expect(request.headers.get("X-Client-Version")).toBe(
+ clientVersion ?? null,
+ );
+ expect(request.headers.get("X-Auth-Token")).toBeNull();
+ if (request.method == "GET") {
+ expect(url.pathname).toBe("/users/two-factor/recover");
+ expect(Object.fromEntries(url.searchParams)).toStrictEqual({
+ sessionID: "recovery-session",
+ twoFactorType: factor,
+ });
+ } else {
+ expect(request.method).toBe("POST");
+ expect(url.pathname).toBe("/users/two-factor/remove");
+ expect(await request.json()).toStrictEqual({
+ sessionID: "recovery-session",
+ twoFactorType: factor,
- secret,
++ proof: createHmac("sha256", secret)
++ .update(`recovery:${factor}:recovery-session`)
++ .digest("base64"),
+ });
+ }
+ const response = Response.json(
+ request.method == "GET" ? envelope : authorization,
+ { status },
+ );
+ Object.defineProperty(response, "url", { value: request.url });
+ return response;
+ });
+ vi.stubGlobal("fetch", fetch);
+ const get = () =>
+ getTwoFactorRecovery(client, factor, "recovery-session");
+ expect(await get()).toStrictEqual(envelope);
+ const recover = (key: string) =>
+ recoverTwoFactor(
+ client,
+ factor,
+ "recovery-session",
+ envelope,
+ key,
+ );
+ await expect(recover("ff".repeat(32))).rejects.toMatchObject({
+ name: "incorrect_recovery_key",
+ });
+ expect(fetch).toHaveBeenCalledTimes(1);
+ const key =
+ factor == "totp"
+ ? recoveryKeyHex
+ : await recoveryKeyToMnemonic(recoveryKey);
+ await expect(recover(key)).resolves.toStrictEqual(authorization);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ status = 404;
+ await expect(get()).rejects.toMatchObject({
+ name: "session_expired",
+ });
+ status = 400;
+ await expect(get()).rejects.toMatchObject({
+ name:
+ factor == "passkey"
+ ? "two_factor_recovery_not_configured"
+ : "Error",
+ });
+ status = 403;
+ await expect(get()).rejects.toMatchObject({ name: "Error" });
+ status = 500;
+ const calls = fetch.mock.calls.length;
+ await expect(recover(key)).rejects.toMatchObject({ name: "Error" });
+ expect(fetch).toHaveBeenCalledTimes(calls + 1);
+ client.free();
+ }
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
diff --cc web/packages/wasm/tests/bindings.test.ts
index 7144d0b906,5cd2d23c1e..ed0f3f886b
--- a/web/packages/wasm/tests/bindings.test.ts
+++ b/web/packages/wasm/tests/bindings.test.ts
@@@ -14,6 -11,75 +11,88 @@@ import
afterEach(() => vi.unstubAllGlobals());
+ test("Photos deletion keeps summary fallback and decrypts the challenge in Rust", async () => {
+ const masterKey = await generateKey();
+ const input = await sessionKeyAttributes(masterKey);
+ const encryptedChallenge = cryptoBoxSeal(
- Buffer.from("deletion-jwt").toString("base64"),
++ Buffer.from("delete-jwtdeletion-jwt").toString("base64"),
+ input.keyAttributes.publicKey,
+ );
+ const summary = {
+ photosAndVideosCount: 12,
+ authenticatorCodesCount: 3,
+ lockerRecordsCount: 4,
+ };
+ let summaryStatus = 404;
+ let feedback: string | undefined;
+ let deletions = 0;
+ mockFetch(async (request) => {
+ expect(request.headers.get("X-Auth-Token")).toBe("test-token");
+ switch (new URL(request.url).pathname) {
+ case "/users/deletion-summary":
+ return summaryStatus == 200
+ ? Response.json(summary)
+ : new Response(null, { status: summaryStatus });
+ case "/users/delete-challenge":
+ return Response.json({ encryptedChallenge });
+ case "/users/delete":
+ expect(request.method).toBe("DELETE");
+ expect(await request.json()).toStrictEqual({
+ challenge: "deletion-jwt",
+ reasonCategory: "not_listed",
+ ...(feedback && { feedback }),
+ });
+ deletions++;
+ return Response.json({});
+ default:
+ throw new Error(`Unexpected request: ${request.url}`);
+ }
+ });
+ const session = await photos.openSession({
+ baseUrl: "http://localhost",
+ authToken: "test-token",
+ masterKeyB64: masterKey,
+ ...input,
+ });
+ try {
+ expect(await photos.getAccountDeletionSummary(session)).toBeUndefined();
+ summaryStatus = 200;
+ expect(await photos.getAccountDeletionSummary(session)).toStrictEqual(
+ summary,
+ );
+ summaryStatus = 500;
+ await expect(photos.getAccountDeletionSummary(session)).rejects.toThrow(
+ "HTTP 500",
+ );
+ const challenge = await photos.getAccountDeleteChallenge(session);
+ expect(challenge).toBe(encryptedChallenge);
+ for (feedback of ["Feedback", undefined]) {
+ await photos.deleteAccount(
+ session,
+ challenge,
+ "not_listed",
+ feedback,
+ );
+ }
++ for (const plaintext of [
++ "deletion-jwt",
++ "delete-jwt",
++ "auth-token" + "a".repeat(32),
++ ]) {
++ const substituted = cryptoBoxSeal(
++ Buffer.from(plaintext).toString("base64"),
++ input.keyAttributes.publicKey,
++ );
++ await expect(
++ photos.deleteAccount(session, substituted, "not_listed"),
++ ).rejects.toThrow("Invalid deletion challenge");
++ }
+ expect(deletions).toBe(2);
+ } finally {
+ session.free();
+ }
+ });
+
test.each(["classical", "post-quantum"])(
"Photos %s Cast payloads round-trip and enforce safe collection IDs",
async (encryption) => {