atagen

macltok

public
Star0
Watch0
d5d8097c3afd94c250affd252a3e9ea63ecec8a5
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git

Blame: src/account.rs

62fe32759529atagen2026-09-26 08:50 UTC1
use std::collections::HashMap;
62fe32759529atagen2026-09-26 08:50 UTC2
#[cfg(feature = "sqlite")]
62fe32759529atagen2026-09-26 08:50 UTC3
use std::path::PathBuf;
96fdf90aacd6atagen2026-09-08 08:24 UTC4
96fdf90aacd6atagen2026-09-08 08:24 UTC5
use matrix_sdk::{
62fe32759529atagen2026-09-26 08:50 UTC6
    Client, ClientBuilder, SendOutsideWasm, SyncOutsideWasm, ThreadingSupport,
96fdf90aacd6atagen2026-09-08 08:24 UTC7
    authentication::{
96fdf90aacd6atagen2026-09-08 08:24 UTC8
        AuthSession,
96fdf90aacd6atagen2026-09-08 08:24 UTC9
        matrix::MatrixSession,
96fdf90aacd6atagen2026-09-08 08:24 UTC10
        oauth::{
96fdf90aacd6atagen2026-09-08 08:24 UTC11
            ClientId, ClientRegistrationData, CsrfToken, OAuthSession, UserSession,
96fdf90aacd6atagen2026-09-08 08:24 UTC12
            registration::{ApplicationType, ClientMetadata, Localized, OAuthGrantType},
96fdf90aacd6atagen2026-09-08 08:24 UTC13
        },
96fdf90aacd6atagen2026-09-08 08:24 UTC14
    },
62fe32759529atagen2026-09-26 08:50 UTC15
    cross_process_lock::CrossProcessLockConfig,
96fdf90aacd6atagen2026-09-08 08:24 UTC16
    encryption::{BackupDownloadStrategy, EncryptionSettings},
96fdf90aacd6atagen2026-09-08 08:24 UTC17
    ruma::{OwnedDeviceId, serde::Raw},
96fdf90aacd6atagen2026-09-08 08:24 UTC18
};
96fdf90aacd6atagen2026-09-08 08:24 UTC19
use serde::{Deserialize, Serialize};
96fdf90aacd6atagen2026-09-08 08:24 UTC20
use thiserror::Error;
96fdf90aacd6atagen2026-09-08 08:24 UTC21
use url::Url;
96fdf90aacd6atagen2026-09-08 08:24 UTC22
62fe32759529atagen2026-09-26 08:50 UTC23
use crate::{ClientHandle, Engine, EngineConfig, EngineError, EventStream, error::SourceError};
96fdf90aacd6atagen2026-09-08 08:24 UTC24
96fdf90aacd6atagen2026-09-08 08:24 UTC25
pub struct Session {
96fdf90aacd6atagen2026-09-08 08:24 UTC26
    client: Client,
96fdf90aacd6atagen2026-09-08 08:24 UTC27
    record: SessionRecord,
96fdf90aacd6atagen2026-09-08 08:24 UTC28
}
96fdf90aacd6atagen2026-09-08 08:24 UTC29
31ce2453c82fatagen2026-09-24 13:07 UTC30
#[non_exhaustive]
96fdf90aacd6atagen2026-09-08 08:24 UTC31
pub struct PasswordLogin {
96fdf90aacd6atagen2026-09-08 08:24 UTC32
    pub homeserver: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC33
    pub username: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC34
    pub password: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC35
    pub device_display_name: Option<String>,
fa9114fcf75fatagen2026-09-24 12:51 UTC36
    /// set after a soft logout so the store's keys still belong to us
fa9114fcf75fatagen2026-09-24 12:51 UTC37
    pub device_id: Option<OwnedDeviceId>,
96fdf90aacd6atagen2026-09-08 08:24 UTC38
}
96fdf90aacd6atagen2026-09-08 08:24 UTC39
31ce2453c82fatagen2026-09-24 13:07 UTC40
impl PasswordLogin {
31ce2453c82fatagen2026-09-24 13:07 UTC41
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC42
    pub fn new(
31ce2453c82fatagen2026-09-24 13:07 UTC43
        homeserver: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC44
        username: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC45
        password: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC46
    ) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC47
        Self {
31ce2453c82fatagen2026-09-24 13:07 UTC48
            homeserver: homeserver.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC49
            username: username.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC50
            password: password.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC51
            device_display_name: None,
31ce2453c82fatagen2026-09-24 13:07 UTC52
            device_id: None,
31ce2453c82fatagen2026-09-24 13:07 UTC53
        }
31ce2453c82fatagen2026-09-24 13:07 UTC54
    }
31ce2453c82fatagen2026-09-24 13:07 UTC55
31ce2453c82fatagen2026-09-24 13:07 UTC56
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC57
    pub fn with_device_display_name(mut self, name: impl Into<String>) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC58
        self.device_display_name = Some(name.into());
31ce2453c82fatagen2026-09-24 13:07 UTC59
        self
31ce2453c82fatagen2026-09-24 13:07 UTC60
    }
31ce2453c82fatagen2026-09-24 13:07 UTC61
31ce2453c82fatagen2026-09-24 13:07 UTC62
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC63
    pub fn with_device_id(mut self, device_id: OwnedDeviceId) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC64
        self.device_id = Some(device_id);
31ce2453c82fatagen2026-09-24 13:07 UTC65
        self
31ce2453c82fatagen2026-09-24 13:07 UTC66
    }
31ce2453c82fatagen2026-09-24 13:07 UTC67
}
31ce2453c82fatagen2026-09-24 13:07 UTC68
31ce2453c82fatagen2026-09-24 13:07 UTC69
#[non_exhaustive]
96fdf90aacd6atagen2026-09-08 08:24 UTC70
pub struct OAuthLogin {
96fdf90aacd6atagen2026-09-08 08:24 UTC71
    pub homeserver: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC72
    pub redirect_uri: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC73
    pub client_uri: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC74
    pub client_name: Option<String>,
96fdf90aacd6atagen2026-09-08 08:24 UTC75
    pub client_id: Option<String>,
96fdf90aacd6atagen2026-09-08 08:24 UTC76
    pub device_id: Option<OwnedDeviceId>,
96fdf90aacd6atagen2026-09-08 08:24 UTC77
    pub application_type: OAuthApplicationType,
96fdf90aacd6atagen2026-09-08 08:24 UTC78
}
96fdf90aacd6atagen2026-09-08 08:24 UTC79
31ce2453c82fatagen2026-09-24 13:07 UTC80
impl OAuthLogin {
31ce2453c82fatagen2026-09-24 13:07 UTC81
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC82
    pub fn new(
31ce2453c82fatagen2026-09-24 13:07 UTC83
        homeserver: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC84
        redirect_uri: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC85
        client_uri: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC86
        application_type: OAuthApplicationType,
31ce2453c82fatagen2026-09-24 13:07 UTC87
    ) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC88
        Self {
31ce2453c82fatagen2026-09-24 13:07 UTC89
            homeserver: homeserver.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC90
            redirect_uri: redirect_uri.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC91
            client_uri: client_uri.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC92
            client_name: None,
31ce2453c82fatagen2026-09-24 13:07 UTC93
            client_id: None,
31ce2453c82fatagen2026-09-24 13:07 UTC94
            device_id: None,
31ce2453c82fatagen2026-09-24 13:07 UTC95
            application_type,
31ce2453c82fatagen2026-09-24 13:07 UTC96
        }
31ce2453c82fatagen2026-09-24 13:07 UTC97
    }
31ce2453c82fatagen2026-09-24 13:07 UTC98
31ce2453c82fatagen2026-09-24 13:07 UTC99
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC100
    pub fn with_client_name(mut self, name: impl Into<String>) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC101
        self.client_name = Some(name.into());
31ce2453c82fatagen2026-09-24 13:07 UTC102
        self
31ce2453c82fatagen2026-09-24 13:07 UTC103
    }
31ce2453c82fatagen2026-09-24 13:07 UTC104
31ce2453c82fatagen2026-09-24 13:07 UTC105
    /// a statically registered client id, skipping dynamic registration
31ce2453c82fatagen2026-09-24 13:07 UTC106
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC107
    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC108
        self.client_id = Some(client_id.into());
31ce2453c82fatagen2026-09-24 13:07 UTC109
        self
31ce2453c82fatagen2026-09-24 13:07 UTC110
    }
31ce2453c82fatagen2026-09-24 13:07 UTC111
31ce2453c82fatagen2026-09-24 13:07 UTC112
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC113
    pub fn with_device_id(mut self, device_id: OwnedDeviceId) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC114
        self.device_id = Some(device_id);
31ce2453c82fatagen2026-09-24 13:07 UTC115
        self
31ce2453c82fatagen2026-09-24 13:07 UTC116
    }
31ce2453c82fatagen2026-09-24 13:07 UTC117
}
31ce2453c82fatagen2026-09-24 13:07 UTC118
96fdf90aacd6atagen2026-09-08 08:24 UTC119
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
31ce2453c82fatagen2026-09-24 13:07 UTC120
#[non_exhaustive]
96fdf90aacd6atagen2026-09-08 08:24 UTC121
pub enum OAuthApplicationType {
96fdf90aacd6atagen2026-09-08 08:24 UTC122
    Native,
96fdf90aacd6atagen2026-09-08 08:24 UTC123
    Web,
96fdf90aacd6atagen2026-09-08 08:24 UTC124
}
96fdf90aacd6atagen2026-09-08 08:24 UTC125
96fdf90aacd6atagen2026-09-08 08:24 UTC126
pub struct PendingOAuthLogin {
96fdf90aacd6atagen2026-09-08 08:24 UTC127
    client: Client,
96fdf90aacd6atagen2026-09-08 08:24 UTC128
    authorization_url: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC129
    state: Option<CsrfToken>,
96fdf90aacd6atagen2026-09-08 08:24 UTC130
}
96fdf90aacd6atagen2026-09-08 08:24 UTC131
96fdf90aacd6atagen2026-09-08 08:24 UTC132
impl PendingOAuthLogin {
96fdf90aacd6atagen2026-09-08 08:24 UTC133
    #[must_use]
96fdf90aacd6atagen2026-09-08 08:24 UTC134
    pub fn authorization_url(&self) -> &str {
96fdf90aacd6atagen2026-09-08 08:24 UTC135
        &self.authorization_url
96fdf90aacd6atagen2026-09-08 08:24 UTC136
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC137
96fdf90aacd6atagen2026-09-08 08:24 UTC138
    #[must_use]
96fdf90aacd6atagen2026-09-08 08:24 UTC139
    pub fn registered_client_id(&self) -> String {
96fdf90aacd6atagen2026-09-08 08:24 UTC140
        self.client
96fdf90aacd6atagen2026-09-08 08:24 UTC141
            .oauth()
96fdf90aacd6atagen2026-09-08 08:24 UTC142
            .client_id()
96fdf90aacd6atagen2026-09-08 08:24 UTC143
            .expect("OAuth client was registered before authorization")
96fdf90aacd6atagen2026-09-08 08:24 UTC144
            .as_str()
96fdf90aacd6atagen2026-09-08 08:24 UTC145
            .to_owned()
96fdf90aacd6atagen2026-09-08 08:24 UTC146
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC147
96fdf90aacd6atagen2026-09-08 08:24 UTC148
    #[must_use]
96fdf90aacd6atagen2026-09-08 08:24 UTC149
    pub const fn is_pending(&self) -> bool {
96fdf90aacd6atagen2026-09-08 08:24 UTC150
        self.state.is_some()
96fdf90aacd6atagen2026-09-08 08:24 UTC151
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC152
96fdf90aacd6atagen2026-09-08 08:24 UTC153
    pub async fn finish(&mut self, callback_url: &str) -> Result<Session, AccountError> {
96fdf90aacd6atagen2026-09-08 08:24 UTC154
        let callback_url = Url::parse(callback_url)
96fdf90aacd6atagen2026-09-08 08:24 UTC155
            .map_err(|error| account_error("parsing the OAuth callback URL", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC156
        let state = self
96fdf90aacd6atagen2026-09-08 08:24 UTC157
            .state
96fdf90aacd6atagen2026-09-08 08:24 UTC158
            .take()
96fdf90aacd6atagen2026-09-08 08:24 UTC159
            .ok_or(AccountError::OAuthCallbackAlreadySubmitted)?;
96fdf90aacd6atagen2026-09-08 08:24 UTC160
        let oauth = self.client.oauth();
96fdf90aacd6atagen2026-09-08 08:24 UTC161
        if let Err(error) = oauth.finish_login(callback_url.into()).await {
96fdf90aacd6atagen2026-09-08 08:24 UTC162
            oauth.abort_login(&state).await;
96fdf90aacd6atagen2026-09-08 08:24 UTC163
            return Err(account_error("OAuth login", error));
96fdf90aacd6atagen2026-09-08 08:24 UTC164
        }
96fdf90aacd6atagen2026-09-08 08:24 UTC165
        Session::from_client(self.client.clone())
96fdf90aacd6atagen2026-09-08 08:24 UTC166
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC167
96fdf90aacd6atagen2026-09-08 08:24 UTC168
    pub async fn abort(mut self) {
96fdf90aacd6atagen2026-09-08 08:24 UTC169
        if let Some(state) = self.state.take() {
96fdf90aacd6atagen2026-09-08 08:24 UTC170
            self.client.oauth().abort_login(&state).await;
96fdf90aacd6atagen2026-09-08 08:24 UTC171
        }
96fdf90aacd6atagen2026-09-08 08:24 UTC172
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC173
}
96fdf90aacd6atagen2026-09-08 08:24 UTC174
96fdf90aacd6atagen2026-09-08 08:24 UTC175
pub struct StoreConfig {
62fe32759529atagen2026-09-26 08:50 UTC176
    location: StoreLocation,
96fdf90aacd6atagen2026-09-08 08:24 UTC177
    passphrase: String,
62fe32759529atagen2026-09-26 08:50 UTC178
    lock_holder: Option<String>,
62fe32759529atagen2026-09-26 08:50 UTC179
}
62fe32759529atagen2026-09-26 08:50 UTC180
62fe32759529atagen2026-09-26 08:50 UTC181
enum StoreLocation {
62fe32759529atagen2026-09-26 08:50 UTC182
    #[cfg(feature = "sqlite")]
62fe32759529atagen2026-09-26 08:50 UTC183
    Sqlite(PathBuf),
62fe32759529atagen2026-09-26 08:50 UTC184
    #[cfg(feature = "indexeddb")]
62fe32759529atagen2026-09-26 08:50 UTC185
    IndexedDb(String),
96fdf90aacd6atagen2026-09-08 08:24 UTC186
}
96fdf90aacd6atagen2026-09-08 08:24 UTC187
96fdf90aacd6atagen2026-09-08 08:24 UTC188
impl StoreConfig {
62fe32759529atagen2026-09-26 08:50 UTC189
    #[cfg(feature = "sqlite")]
62fe32759529atagen2026-09-26 08:50 UTC190
    #[must_use]
62fe32759529atagen2026-09-26 08:50 UTC191
    pub fn sqlite(path: impl Into<PathBuf>, passphrase: impl Into<String>) -> Self {
62fe32759529atagen2026-09-26 08:50 UTC192
        Self {
62fe32759529atagen2026-09-26 08:50 UTC193
            location: StoreLocation::Sqlite(path.into()),
62fe32759529atagen2026-09-26 08:50 UTC194
            passphrase: passphrase.into(),
62fe32759529atagen2026-09-26 08:50 UTC195
            lock_holder: None,
62fe32759529atagen2026-09-26 08:50 UTC196
        }
62fe32759529atagen2026-09-26 08:50 UTC197
    }
62fe32759529atagen2026-09-26 08:50 UTC198
62fe32759529atagen2026-09-26 08:50 UTC199
    #[cfg(feature = "indexeddb")]
96fdf90aacd6atagen2026-09-08 08:24 UTC200
    #[must_use]
62fe32759529atagen2026-09-26 08:50 UTC201
    pub fn indexeddb(name: impl Into<String>, passphrase: impl Into<String>) -> Self {
96fdf90aacd6atagen2026-09-08 08:24 UTC202
        Self {
62fe32759529atagen2026-09-26 08:50 UTC203
            location: StoreLocation::IndexedDb(name.into()),
96fdf90aacd6atagen2026-09-08 08:24 UTC204
            passphrase: passphrase.into(),
62fe32759529atagen2026-09-26 08:50 UTC205
            lock_holder: None,
96fdf90aacd6atagen2026-09-08 08:24 UTC206
        }
96fdf90aacd6atagen2026-09-08 08:24 UTC207
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC208
62fe32759529atagen2026-09-26 08:50 UTC209
    /// the sdk names every client `main`, so two tabs on one store would both think they hold its lock
96fdf90aacd6atagen2026-09-08 08:24 UTC210
    #[must_use]
62fe32759529atagen2026-09-26 08:50 UTC211
    pub fn with_lock_holder(mut self, holder: impl Into<String>) -> Self {
62fe32759529atagen2026-09-26 08:50 UTC212
        self.lock_holder = Some(holder.into());
62fe32759529atagen2026-09-26 08:50 UTC213
        self
96fdf90aacd6atagen2026-09-08 08:24 UTC214
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC215
}
96fdf90aacd6atagen2026-09-08 08:24 UTC216
96fdf90aacd6atagen2026-09-08 08:24 UTC217
/// Serializable authentication secrets. Store this separately from the
62fe32759529atagen2026-09-26 08:50 UTC218
/// encrypted store in protected, preferably encrypted storage.
96fdf90aacd6atagen2026-09-08 08:24 UTC219
/// A saved record must be replaced when `Event::SessionTokensChanged` arrives.
96fdf90aacd6atagen2026-09-08 08:24 UTC220
#[derive(Clone, Deserialize, Serialize)]
96fdf90aacd6atagen2026-09-08 08:24 UTC221
pub struct SessionRecord {
96fdf90aacd6atagen2026-09-08 08:24 UTC222
    homeserver: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC223
    authentication: AuthenticationRecord,
96fdf90aacd6atagen2026-09-08 08:24 UTC224
}
96fdf90aacd6atagen2026-09-08 08:24 UTC225
96fdf90aacd6atagen2026-09-08 08:24 UTC226
#[derive(Clone, Deserialize, Serialize)]
96fdf90aacd6atagen2026-09-08 08:24 UTC227
#[serde(tag = "type", content = "session", rename_all = "snake_case")]
96fdf90aacd6atagen2026-09-08 08:24 UTC228
enum AuthenticationRecord {
96fdf90aacd6atagen2026-09-08 08:24 UTC229
    Matrix(MatrixSession),
96fdf90aacd6atagen2026-09-08 08:24 UTC230
    OAuth {
96fdf90aacd6atagen2026-09-08 08:24 UTC231
        client_id: ClientId,
96fdf90aacd6atagen2026-09-08 08:24 UTC232
        user: UserSession,
96fdf90aacd6atagen2026-09-08 08:24 UTC233
    },
96fdf90aacd6atagen2026-09-08 08:24 UTC234
}
96fdf90aacd6atagen2026-09-08 08:24 UTC235
96fdf90aacd6atagen2026-09-08 08:24 UTC236
impl SessionRecord {
96fdf90aacd6atagen2026-09-08 08:24 UTC237
    #[must_use]
96fdf90aacd6atagen2026-09-08 08:24 UTC238
    pub fn homeserver(&self) -> &str {
96fdf90aacd6atagen2026-09-08 08:24 UTC239
        &self.homeserver
96fdf90aacd6atagen2026-09-08 08:24 UTC240
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC241
}
96fdf90aacd6atagen2026-09-08 08:24 UTC242
96fdf90aacd6atagen2026-09-08 08:24 UTC243
#[derive(Debug, Error)]
96fdf90aacd6atagen2026-09-08 08:24 UTC244
pub enum AccountError {
96fdf90aacd6atagen2026-09-08 08:24 UTC245
    #[error("{context} failed")]
96fdf90aacd6atagen2026-09-08 08:24 UTC246
    Operation {
96fdf90aacd6atagen2026-09-08 08:24 UTC247
        context: &'static str,
96fdf90aacd6atagen2026-09-08 08:24 UTC248
        #[source]
62fe32759529atagen2026-09-26 08:50 UTC249
        source: Box<SourceError>,
96fdf90aacd6atagen2026-09-08 08:24 UTC250
    },
96fdf90aacd6atagen2026-09-08 08:24 UTC251
    #[error("the homeserver returned no authenticated session")]
96fdf90aacd6atagen2026-09-08 08:24 UTC252
    MissingSession,
96fdf90aacd6atagen2026-09-08 08:24 UTC253
    #[error("the SDK returned an unsupported authentication session")]
96fdf90aacd6atagen2026-09-08 08:24 UTC254
    UnsupportedAuthentication,
96fdf90aacd6atagen2026-09-08 08:24 UTC255
    #[error("the OAuth callback was already submitted")]
96fdf90aacd6atagen2026-09-08 08:24 UTC256
    OAuthCallbackAlreadySubmitted,
96fdf90aacd6atagen2026-09-08 08:24 UTC257
    #[error(transparent)]
96fdf90aacd6atagen2026-09-08 08:24 UTC258
    Engine(#[from] EngineError),
96fdf90aacd6atagen2026-09-08 08:24 UTC259
}
96fdf90aacd6atagen2026-09-08 08:24 UTC260
96fdf90aacd6atagen2026-09-08 08:24 UTC261
impl Session {
96fdf90aacd6atagen2026-09-08 08:24 UTC262
    pub async fn login_password(
96fdf90aacd6atagen2026-09-08 08:24 UTC263
        login: PasswordLogin,
96fdf90aacd6atagen2026-09-08 08:24 UTC264
        store: StoreConfig,
96fdf90aacd6atagen2026-09-08 08:24 UTC265
    ) -> Result<Self, AccountError> {
96fdf90aacd6atagen2026-09-08 08:24 UTC266
        let client = matrix_client_builder(&store)
96fdf90aacd6atagen2026-09-08 08:24 UTC267
            .server_name_or_homeserver_url(login.homeserver.trim())
96fdf90aacd6atagen2026-09-08 08:24 UTC268
            .build()
96fdf90aacd6atagen2026-09-08 08:24 UTC269
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC270
            .map_err(|error| account_error("building the Matrix client", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC271
        let mut request = client
96fdf90aacd6atagen2026-09-08 08:24 UTC272
            .matrix_auth()
96fdf90aacd6atagen2026-09-08 08:24 UTC273
            .login_username(login.username.trim(), &login.password)
96fdf90aacd6atagen2026-09-08 08:24 UTC274
            .request_refresh_token();
96fdf90aacd6atagen2026-09-08 08:24 UTC275
        if let Some(name) = login.device_display_name.as_deref() {
96fdf90aacd6atagen2026-09-08 08:24 UTC276
            request = request.initial_device_display_name(name);
96fdf90aacd6atagen2026-09-08 08:24 UTC277
        }
fa9114fcf75fatagen2026-09-24 12:51 UTC278
        if let Some(device_id) = login.device_id.as_deref() {
fa9114fcf75fatagen2026-09-24 12:51 UTC279
            request = request.device_id(device_id.as_str());
fa9114fcf75fatagen2026-09-24 12:51 UTC280
        }
96fdf90aacd6atagen2026-09-08 08:24 UTC281
        request
96fdf90aacd6atagen2026-09-08 08:24 UTC282
            .send()
96fdf90aacd6atagen2026-09-08 08:24 UTC283
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC284
            .map_err(|error| account_error("password login", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC285
        Self::from_client(client)
96fdf90aacd6atagen2026-09-08 08:24 UTC286
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC287
96fdf90aacd6atagen2026-09-08 08:24 UTC288
    pub async fn begin_oauth(
96fdf90aacd6atagen2026-09-08 08:24 UTC289
        login: OAuthLogin,
96fdf90aacd6atagen2026-09-08 08:24 UTC290
        store: StoreConfig,
96fdf90aacd6atagen2026-09-08 08:24 UTC291
    ) -> Result<PendingOAuthLogin, AccountError> {
96fdf90aacd6atagen2026-09-08 08:24 UTC292
        let redirect_uri = Url::parse(login.redirect_uri.trim())
96fdf90aacd6atagen2026-09-08 08:24 UTC293
            .map_err(|error| account_error("parsing the OAuth redirect URI", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC294
        let client_uri = Url::parse(login.client_uri.trim())
96fdf90aacd6atagen2026-09-08 08:24 UTC295
            .map_err(|error| account_error("parsing the OAuth client URI", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC296
        let client = matrix_client_builder(&store)
96fdf90aacd6atagen2026-09-08 08:24 UTC297
            .server_name_or_homeserver_url(login.homeserver.trim())
96fdf90aacd6atagen2026-09-08 08:24 UTC298
            .build()
96fdf90aacd6atagen2026-09-08 08:24 UTC299
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC300
            .map_err(|error| account_error("building the Matrix client", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC301
        let application_type = match login.application_type {
96fdf90aacd6atagen2026-09-08 08:24 UTC302
            OAuthApplicationType::Native => ApplicationType::Native,
96fdf90aacd6atagen2026-09-08 08:24 UTC303
            OAuthApplicationType::Web => ApplicationType::Web,
96fdf90aacd6atagen2026-09-08 08:24 UTC304
        };
96fdf90aacd6atagen2026-09-08 08:24 UTC305
        let mut metadata = ClientMetadata::new(
96fdf90aacd6atagen2026-09-08 08:24 UTC306
            application_type,
96fdf90aacd6atagen2026-09-08 08:24 UTC307
            vec![OAuthGrantType::AuthorizationCode {
96fdf90aacd6atagen2026-09-08 08:24 UTC308
                redirect_uris: vec![redirect_uri.clone()],
96fdf90aacd6atagen2026-09-08 08:24 UTC309
            }],
96fdf90aacd6atagen2026-09-08 08:24 UTC310
            Localized::new(client_uri, []),
96fdf90aacd6atagen2026-09-08 08:24 UTC311
        );
96fdf90aacd6atagen2026-09-08 08:24 UTC312
        metadata.client_name = login.client_name.map(|name| Localized::new(name, []));
96fdf90aacd6atagen2026-09-08 08:24 UTC313
        let metadata = Raw::new(&metadata)
96fdf90aacd6atagen2026-09-08 08:24 UTC314
            .map_err(|error| account_error("serializing OAuth client metadata", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC315
        let mut registration = ClientRegistrationData::new(metadata);
96fdf90aacd6atagen2026-09-08 08:24 UTC316
        if let Some(client_id) = login.client_id {
96fdf90aacd6atagen2026-09-08 08:24 UTC317
            registration.static_registrations = Some(HashMap::from([(
96fdf90aacd6atagen2026-09-08 08:24 UTC318
                client.homeserver(),
96fdf90aacd6atagen2026-09-08 08:24 UTC319
                ClientId::new(client_id),
96fdf90aacd6atagen2026-09-08 08:24 UTC320
            )]));
96fdf90aacd6atagen2026-09-08 08:24 UTC321
        }
96fdf90aacd6atagen2026-09-08 08:24 UTC322
        let authorization = client
96fdf90aacd6atagen2026-09-08 08:24 UTC323
            .oauth()
96fdf90aacd6atagen2026-09-08 08:24 UTC324
            .login(redirect_uri, login.device_id, Some(registration), None)
96fdf90aacd6atagen2026-09-08 08:24 UTC325
            .build()
96fdf90aacd6atagen2026-09-08 08:24 UTC326
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC327
            .map_err(|error| account_error("starting OAuth login", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC328
        Ok(PendingOAuthLogin {
96fdf90aacd6atagen2026-09-08 08:24 UTC329
            client,
96fdf90aacd6atagen2026-09-08 08:24 UTC330
            authorization_url: authorization.url.to_string(),
96fdf90aacd6atagen2026-09-08 08:24 UTC331
            state: Some(authorization.state),
96fdf90aacd6atagen2026-09-08 08:24 UTC332
        })
96fdf90aacd6atagen2026-09-08 08:24 UTC333
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC334
96fdf90aacd6atagen2026-09-08 08:24 UTC335
    /// Restore a saved record with the same store location and passphrase.
96fdf90aacd6atagen2026-09-08 08:24 UTC336
    /// The caller must also handle refresh, rejection, and explicit logout.
96fdf90aacd6atagen2026-09-08 08:24 UTC337
    pub async fn restore(record: SessionRecord, store: StoreConfig) -> Result<Self, AccountError> {
96fdf90aacd6atagen2026-09-08 08:24 UTC338
        let client = matrix_client_builder(&store)
96fdf90aacd6atagen2026-09-08 08:24 UTC339
            .homeserver_url(&record.homeserver)
96fdf90aacd6atagen2026-09-08 08:24 UTC340
            .build()
96fdf90aacd6atagen2026-09-08 08:24 UTC341
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC342
            .map_err(|error| account_error("reopening the Matrix store", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC343
        let authentication = match record.authentication.clone() {
96fdf90aacd6atagen2026-09-08 08:24 UTC344
            AuthenticationRecord::Matrix(session) => AuthSession::Matrix(session),
96fdf90aacd6atagen2026-09-08 08:24 UTC345
            AuthenticationRecord::OAuth { client_id, user } => {
96fdf90aacd6atagen2026-09-08 08:24 UTC346
                OAuthSession { client_id, user }.into()
96fdf90aacd6atagen2026-09-08 08:24 UTC347
            }
96fdf90aacd6atagen2026-09-08 08:24 UTC348
        };
96fdf90aacd6atagen2026-09-08 08:24 UTC349
        client
96fdf90aacd6atagen2026-09-08 08:24 UTC350
            .restore_session(authentication)
96fdf90aacd6atagen2026-09-08 08:24 UTC351
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC352
            .map_err(|error| account_error("restoring the authenticated session", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC353
        Ok(Self { client, record })
96fdf90aacd6atagen2026-09-08 08:24 UTC354
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC355
96fdf90aacd6atagen2026-09-08 08:24 UTC356
    /// Initial login credentials only. This snapshot does not track later
96fdf90aacd6atagen2026-09-08 08:24 UTC357
    /// token rotations; use `ClientHandle::session_record` after building.
96fdf90aacd6atagen2026-09-08 08:24 UTC358
    #[must_use]
96fdf90aacd6atagen2026-09-08 08:24 UTC359
    pub fn record(&self) -> SessionRecord {
96fdf90aacd6atagen2026-09-08 08:24 UTC360
        self.record.clone()
96fdf90aacd6atagen2026-09-08 08:24 UTC361
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC362
96fdf90aacd6atagen2026-09-08 08:24 UTC363
    pub async fn build(
96fdf90aacd6atagen2026-09-08 08:24 UTC364
        self,
96fdf90aacd6atagen2026-09-08 08:24 UTC365
        config: EngineConfig,
96fdf90aacd6atagen2026-09-08 08:24 UTC366
    ) -> Result<(Engine, ClientHandle, EventStream), AccountError> {
96fdf90aacd6atagen2026-09-08 08:24 UTC367
        Engine::from_client(self.client, config)
96fdf90aacd6atagen2026-09-08 08:24 UTC368
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC369
            .map_err(AccountError::from)
96fdf90aacd6atagen2026-09-08 08:24 UTC370
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC371
96fdf90aacd6atagen2026-09-08 08:24 UTC372
    fn from_client(client: Client) -> Result<Self, AccountError> {
96fdf90aacd6atagen2026-09-08 08:24 UTC373
        let record = session_record(&client)?;
96fdf90aacd6atagen2026-09-08 08:24 UTC374
        Ok(Self { client, record })
96fdf90aacd6atagen2026-09-08 08:24 UTC375
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC376
}
96fdf90aacd6atagen2026-09-08 08:24 UTC377
96fdf90aacd6atagen2026-09-08 08:24 UTC378
pub(crate) fn session_record(client: &Client) -> Result<SessionRecord, AccountError> {
96fdf90aacd6atagen2026-09-08 08:24 UTC379
    let authentication = match client.session().ok_or(AccountError::MissingSession)? {
96fdf90aacd6atagen2026-09-08 08:24 UTC380
        AuthSession::Matrix(session) => AuthenticationRecord::Matrix(session),
96fdf90aacd6atagen2026-09-08 08:24 UTC381
        AuthSession::OAuth(session) => {
96fdf90aacd6atagen2026-09-08 08:24 UTC382
            let OAuthSession { client_id, user } = *session;
96fdf90aacd6atagen2026-09-08 08:24 UTC383
            AuthenticationRecord::OAuth { client_id, user }
96fdf90aacd6atagen2026-09-08 08:24 UTC384
        }
96fdf90aacd6atagen2026-09-08 08:24 UTC385
        _ => return Err(AccountError::UnsupportedAuthentication),
96fdf90aacd6atagen2026-09-08 08:24 UTC386
    };
96fdf90aacd6atagen2026-09-08 08:24 UTC387
    Ok(SessionRecord {
96fdf90aacd6atagen2026-09-08 08:24 UTC388
        homeserver: client.homeserver().to_string(),
96fdf90aacd6atagen2026-09-08 08:24 UTC389
        authentication,
96fdf90aacd6atagen2026-09-08 08:24 UTC390
    })
96fdf90aacd6atagen2026-09-08 08:24 UTC391
}
96fdf90aacd6atagen2026-09-08 08:24 UTC392
96fdf90aacd6atagen2026-09-08 08:24 UTC393
fn encryption_settings() -> EncryptionSettings {
96fdf90aacd6atagen2026-09-08 08:24 UTC394
    EncryptionSettings {
96fdf90aacd6atagen2026-09-08 08:24 UTC395
        auto_enable_cross_signing: true,
96fdf90aacd6atagen2026-09-08 08:24 UTC396
        backup_download_strategy: BackupDownloadStrategy::OneShot,
96fdf90aacd6atagen2026-09-08 08:24 UTC397
        auto_enable_backups: true,
96fdf90aacd6atagen2026-09-08 08:24 UTC398
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC399
}
96fdf90aacd6atagen2026-09-08 08:24 UTC400
96fdf90aacd6atagen2026-09-08 08:24 UTC401
fn matrix_client_builder(store: &StoreConfig) -> ClientBuilder {
62fe32759529atagen2026-09-26 08:50 UTC402
    let mut builder = Client::builder()
96fdf90aacd6atagen2026-09-08 08:24 UTC403
        .with_encryption_settings(encryption_settings())
96fdf90aacd6atagen2026-09-08 08:24 UTC404
        .with_threading_support(ThreadingSupport::Enabled {
96fdf90aacd6atagen2026-09-08 08:24 UTC405
            with_subscriptions: false,
96fdf90aacd6atagen2026-09-08 08:24 UTC406
        })
62fe32759529atagen2026-09-26 08:50 UTC407
        .handle_refresh_tokens();
62fe32759529atagen2026-09-26 08:50 UTC408
    if let Some(holder) = &store.lock_holder {
62fe32759529atagen2026-09-26 08:50 UTC409
        builder = builder.cross_process_store_config(CrossProcessLockConfig::multi_process(holder));
62fe32759529atagen2026-09-26 08:50 UTC410
    }
62fe32759529atagen2026-09-26 08:50 UTC411
    match &store.location {
62fe32759529atagen2026-09-26 08:50 UTC412
        #[cfg(feature = "sqlite")]
62fe32759529atagen2026-09-26 08:50 UTC413
        StoreLocation::Sqlite(path) => builder.sqlite_store(path, Some(&store.passphrase)),
62fe32759529atagen2026-09-26 08:50 UTC414
        #[cfg(feature = "indexeddb")]
62fe32759529atagen2026-09-26 08:50 UTC415
        StoreLocation::IndexedDb(name) => builder.indexeddb_store(name, Some(&store.passphrase)),
62fe32759529atagen2026-09-26 08:50 UTC416
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC417
}
96fdf90aacd6atagen2026-09-08 08:24 UTC418
96fdf90aacd6atagen2026-09-08 08:24 UTC419
fn account_error(
96fdf90aacd6atagen2026-09-08 08:24 UTC420
    context: &'static str,
62fe32759529atagen2026-09-26 08:50 UTC421
    source: impl std::error::Error + SendOutsideWasm + SyncOutsideWasm + 'static,
96fdf90aacd6atagen2026-09-08 08:24 UTC422
) -> AccountError {
96fdf90aacd6atagen2026-09-08 08:24 UTC423
    AccountError::Operation {
96fdf90aacd6atagen2026-09-08 08:24 UTC424
        context,
96fdf90aacd6atagen2026-09-08 08:24 UTC425
        source: Box::new(source),
96fdf90aacd6atagen2026-09-08 08:24 UTC426
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC427
}