atagen

macltok

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

Blame: src/account.rs

62fe32759529atagen2026-09-26 08:50 UTC1
#[cfg(feature = "sqlite")]
62fe32759529atagen2026-09-26 08:50 UTC2
use std::path::PathBuf;
f12377bce9b9atagen2026-09-26 12:32 UTC3
#[cfg(not(target_family = "wasm"))]
f12377bce9b9atagen2026-09-26 12:32 UTC4
use std::sync::atomic::{AtomicBool, Ordering};
713205a95af2atagen2026-09-26 09:24 UTC5
use std::{collections::HashMap, sync::Arc};
96fdf90aacd6atagen2026-09-08 08:24 UTC6
96fdf90aacd6atagen2026-09-08 08:24 UTC7
use matrix_sdk::{
f12377bce9b9atagen2026-09-26 12:32 UTC8
    Client, ClientBuilder, SendOutsideWasm, SessionChange, SessionMeta, SyncOutsideWasm,
f12377bce9b9atagen2026-09-26 12:32 UTC9
    ThreadingSupport,
96fdf90aacd6atagen2026-09-08 08:24 UTC10
    authentication::{
96fdf90aacd6atagen2026-09-08 08:24 UTC11
        AuthSession,
96fdf90aacd6atagen2026-09-08 08:24 UTC12
        matrix::MatrixSession,
96fdf90aacd6atagen2026-09-08 08:24 UTC13
        oauth::{
96fdf90aacd6atagen2026-09-08 08:24 UTC14
            ClientId, ClientRegistrationData, CsrfToken, OAuthSession, UserSession,
96fdf90aacd6atagen2026-09-08 08:24 UTC15
            registration::{ApplicationType, ClientMetadata, Localized, OAuthGrantType},
96fdf90aacd6atagen2026-09-08 08:24 UTC16
        },
96fdf90aacd6atagen2026-09-08 08:24 UTC17
    },
62fe32759529atagen2026-09-26 08:50 UTC18
    cross_process_lock::CrossProcessLockConfig,
96fdf90aacd6atagen2026-09-08 08:24 UTC19
    encryption::{BackupDownloadStrategy, EncryptionSettings},
6f1d6591c10datagen2026-09-26 09:52 UTC20
    ruma::{OwnedDeviceId, OwnedUserId, serde::Raw},
96fdf90aacd6atagen2026-09-08 08:24 UTC21
};
96fdf90aacd6atagen2026-09-08 08:24 UTC22
use serde::{Deserialize, Serialize};
96fdf90aacd6atagen2026-09-08 08:24 UTC23
use thiserror::Error;
f12377bce9b9atagen2026-09-26 12:32 UTC24
use tokio::sync::{broadcast, mpsc};
96fdf90aacd6atagen2026-09-08 08:24 UTC25
use url::Url;
96fdf90aacd6atagen2026-09-08 08:24 UTC26
713205a95af2atagen2026-09-26 09:24 UTC27
use crate::{
f12377bce9b9atagen2026-09-26 12:32 UTC28
    ClientHandle, Engine, EngineConfig, EngineError, ErrorKind, EventStream, SessionStore,
a250c7fa43fbatagen2026-09-26 13:35 UTC29
    engine::{Persistence, StoreLock},
a250c7fa43fbatagen2026-09-26 13:35 UTC30
    error::SourceError,
713205a95af2atagen2026-09-26 09:24 UTC31
};
96fdf90aacd6atagen2026-09-08 08:24 UTC32
f12377bce9b9atagen2026-09-26 12:32 UTC33
/// a logged in client and the `SessionStore` its record lives in. the engine it builds
f12377bce9b9atagen2026-09-26 12:32 UTC34
/// saves every token rotation there, unless told `without_persistence`
96fdf90aacd6atagen2026-09-08 08:24 UTC35
pub struct Session {
96fdf90aacd6atagen2026-09-08 08:24 UTC36
    client: Client,
f12377bce9b9atagen2026-09-26 12:32 UTC37
    tracking: Tracking,
a250c7fa43fbatagen2026-09-26 13:35 UTC38
    store_lock: StoreLock,
f12377bce9b9atagen2026-09-26 12:32 UTC39
}
f12377bce9b9atagen2026-09-26 12:32 UTC40
f12377bce9b9atagen2026-09-26 12:32 UTC41
/// taken as soon as the client exists, since the sdk can refresh before there's an engine
f12377bce9b9atagen2026-09-26 12:32 UTC42
struct Tracking {
f12377bce9b9atagen2026-09-26 12:32 UTC43
    session_changes: broadcast::Receiver<SessionChange>,
f12377bce9b9atagen2026-09-26 12:32 UTC44
    persistence: Option<Persistence>,
f12377bce9b9atagen2026-09-26 12:32 UTC45
    #[cfg(not(target_family = "wasm"))]
f12377bce9b9atagen2026-09-26 12:32 UTC46
    inline: Arc<AtomicBool>,
96fdf90aacd6atagen2026-09-08 08:24 UTC47
}
96fdf90aacd6atagen2026-09-08 08:24 UTC48
31ce2453c82fatagen2026-09-24 13:07 UTC49
#[non_exhaustive]
96fdf90aacd6atagen2026-09-08 08:24 UTC50
pub struct PasswordLogin {
96fdf90aacd6atagen2026-09-08 08:24 UTC51
    pub homeserver: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC52
    pub username: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC53
    pub password: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC54
    pub device_display_name: Option<String>,
fa9114fcf75fatagen2026-09-24 12:51 UTC55
    /// set after a soft logout so the store's keys still belong to us
fa9114fcf75fatagen2026-09-24 12:51 UTC56
    pub device_id: Option<OwnedDeviceId>,
96fdf90aacd6atagen2026-09-08 08:24 UTC57
}
96fdf90aacd6atagen2026-09-08 08:24 UTC58
31ce2453c82fatagen2026-09-24 13:07 UTC59
impl PasswordLogin {
31ce2453c82fatagen2026-09-24 13:07 UTC60
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC61
    pub fn new(
31ce2453c82fatagen2026-09-24 13:07 UTC62
        homeserver: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC63
        username: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC64
        password: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC65
    ) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC66
        Self {
31ce2453c82fatagen2026-09-24 13:07 UTC67
            homeserver: homeserver.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC68
            username: username.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC69
            password: password.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC70
            device_display_name: None,
31ce2453c82fatagen2026-09-24 13:07 UTC71
            device_id: None,
31ce2453c82fatagen2026-09-24 13:07 UTC72
        }
31ce2453c82fatagen2026-09-24 13:07 UTC73
    }
31ce2453c82fatagen2026-09-24 13:07 UTC74
31ce2453c82fatagen2026-09-24 13:07 UTC75
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC76
    pub fn with_device_display_name(mut self, name: impl Into<String>) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC77
        self.device_display_name = Some(name.into());
31ce2453c82fatagen2026-09-24 13:07 UTC78
        self
31ce2453c82fatagen2026-09-24 13:07 UTC79
    }
31ce2453c82fatagen2026-09-24 13:07 UTC80
31ce2453c82fatagen2026-09-24 13:07 UTC81
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC82
    pub fn with_device_id(mut self, device_id: OwnedDeviceId) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC83
        self.device_id = Some(device_id);
31ce2453c82fatagen2026-09-24 13:07 UTC84
        self
31ce2453c82fatagen2026-09-24 13:07 UTC85
    }
31ce2453c82fatagen2026-09-24 13:07 UTC86
}
31ce2453c82fatagen2026-09-24 13:07 UTC87
31ce2453c82fatagen2026-09-24 13:07 UTC88
#[non_exhaustive]
96fdf90aacd6atagen2026-09-08 08:24 UTC89
pub struct OAuthLogin {
96fdf90aacd6atagen2026-09-08 08:24 UTC90
    pub homeserver: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC91
    pub redirect_uri: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC92
    pub client_uri: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC93
    pub client_name: Option<String>,
96fdf90aacd6atagen2026-09-08 08:24 UTC94
    pub client_id: Option<String>,
96fdf90aacd6atagen2026-09-08 08:24 UTC95
    pub device_id: Option<OwnedDeviceId>,
96fdf90aacd6atagen2026-09-08 08:24 UTC96
    pub application_type: OAuthApplicationType,
96fdf90aacd6atagen2026-09-08 08:24 UTC97
}
96fdf90aacd6atagen2026-09-08 08:24 UTC98
31ce2453c82fatagen2026-09-24 13:07 UTC99
impl OAuthLogin {
31ce2453c82fatagen2026-09-24 13:07 UTC100
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC101
    pub fn new(
31ce2453c82fatagen2026-09-24 13:07 UTC102
        homeserver: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC103
        redirect_uri: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC104
        client_uri: impl Into<String>,
31ce2453c82fatagen2026-09-24 13:07 UTC105
        application_type: OAuthApplicationType,
31ce2453c82fatagen2026-09-24 13:07 UTC106
    ) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC107
        Self {
31ce2453c82fatagen2026-09-24 13:07 UTC108
            homeserver: homeserver.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC109
            redirect_uri: redirect_uri.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC110
            client_uri: client_uri.into(),
31ce2453c82fatagen2026-09-24 13:07 UTC111
            client_name: None,
31ce2453c82fatagen2026-09-24 13:07 UTC112
            client_id: None,
31ce2453c82fatagen2026-09-24 13:07 UTC113
            device_id: None,
31ce2453c82fatagen2026-09-24 13:07 UTC114
            application_type,
31ce2453c82fatagen2026-09-24 13:07 UTC115
        }
31ce2453c82fatagen2026-09-24 13:07 UTC116
    }
31ce2453c82fatagen2026-09-24 13:07 UTC117
31ce2453c82fatagen2026-09-24 13:07 UTC118
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC119
    pub fn with_client_name(mut self, name: impl Into<String>) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC120
        self.client_name = Some(name.into());
31ce2453c82fatagen2026-09-24 13:07 UTC121
        self
31ce2453c82fatagen2026-09-24 13:07 UTC122
    }
31ce2453c82fatagen2026-09-24 13:07 UTC123
31ce2453c82fatagen2026-09-24 13:07 UTC124
    /// a statically registered client id, skipping dynamic registration
31ce2453c82fatagen2026-09-24 13:07 UTC125
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC126
    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC127
        self.client_id = Some(client_id.into());
31ce2453c82fatagen2026-09-24 13:07 UTC128
        self
31ce2453c82fatagen2026-09-24 13:07 UTC129
    }
31ce2453c82fatagen2026-09-24 13:07 UTC130
31ce2453c82fatagen2026-09-24 13:07 UTC131
    #[must_use]
31ce2453c82fatagen2026-09-24 13:07 UTC132
    pub fn with_device_id(mut self, device_id: OwnedDeviceId) -> Self {
31ce2453c82fatagen2026-09-24 13:07 UTC133
        self.device_id = Some(device_id);
31ce2453c82fatagen2026-09-24 13:07 UTC134
        self
31ce2453c82fatagen2026-09-24 13:07 UTC135
    }
31ce2453c82fatagen2026-09-24 13:07 UTC136
}
31ce2453c82fatagen2026-09-24 13:07 UTC137
96fdf90aacd6atagen2026-09-08 08:24 UTC138
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
31ce2453c82fatagen2026-09-24 13:07 UTC139
#[non_exhaustive]
96fdf90aacd6atagen2026-09-08 08:24 UTC140
pub enum OAuthApplicationType {
96fdf90aacd6atagen2026-09-08 08:24 UTC141
    Native,
96fdf90aacd6atagen2026-09-08 08:24 UTC142
    Web,
96fdf90aacd6atagen2026-09-08 08:24 UTC143
}
96fdf90aacd6atagen2026-09-08 08:24 UTC144
96fdf90aacd6atagen2026-09-08 08:24 UTC145
pub struct PendingOAuthLogin {
96fdf90aacd6atagen2026-09-08 08:24 UTC146
    client: Client,
713205a95af2atagen2026-09-26 09:24 UTC147
    sessions: Arc<dyn SessionStore>,
a250c7fa43fbatagen2026-09-26 13:35 UTC148
    tracking: Option<(Tracking, StoreLock)>,
96fdf90aacd6atagen2026-09-08 08:24 UTC149
    authorization_url: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC150
    state: Option<CsrfToken>,
96fdf90aacd6atagen2026-09-08 08:24 UTC151
}
96fdf90aacd6atagen2026-09-08 08:24 UTC152
96fdf90aacd6atagen2026-09-08 08:24 UTC153
impl PendingOAuthLogin {
96fdf90aacd6atagen2026-09-08 08:24 UTC154
    #[must_use]
96fdf90aacd6atagen2026-09-08 08:24 UTC155
    pub fn authorization_url(&self) -> &str {
96fdf90aacd6atagen2026-09-08 08:24 UTC156
        &self.authorization_url
96fdf90aacd6atagen2026-09-08 08:24 UTC157
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC158
96fdf90aacd6atagen2026-09-08 08:24 UTC159
    #[must_use]
96fdf90aacd6atagen2026-09-08 08:24 UTC160
    pub fn registered_client_id(&self) -> String {
96fdf90aacd6atagen2026-09-08 08:24 UTC161
        self.client
96fdf90aacd6atagen2026-09-08 08:24 UTC162
            .oauth()
96fdf90aacd6atagen2026-09-08 08:24 UTC163
            .client_id()
96fdf90aacd6atagen2026-09-08 08:24 UTC164
            .expect("OAuth client was registered before authorization")
96fdf90aacd6atagen2026-09-08 08:24 UTC165
            .as_str()
96fdf90aacd6atagen2026-09-08 08:24 UTC166
            .to_owned()
96fdf90aacd6atagen2026-09-08 08:24 UTC167
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC168
96fdf90aacd6atagen2026-09-08 08:24 UTC169
    #[must_use]
96fdf90aacd6atagen2026-09-08 08:24 UTC170
    pub const fn is_pending(&self) -> bool {
96fdf90aacd6atagen2026-09-08 08:24 UTC171
        self.state.is_some()
96fdf90aacd6atagen2026-09-08 08:24 UTC172
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC173
96fdf90aacd6atagen2026-09-08 08:24 UTC174
    pub async fn finish(&mut self, callback_url: &str) -> Result<Session, AccountError> {
96fdf90aacd6atagen2026-09-08 08:24 UTC175
        let callback_url = Url::parse(callback_url)
96fdf90aacd6atagen2026-09-08 08:24 UTC176
            .map_err(|error| account_error("parsing the OAuth callback URL", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC177
        let state = self
96fdf90aacd6atagen2026-09-08 08:24 UTC178
            .state
96fdf90aacd6atagen2026-09-08 08:24 UTC179
            .take()
96fdf90aacd6atagen2026-09-08 08:24 UTC180
            .ok_or(AccountError::OAuthCallbackAlreadySubmitted)?;
96fdf90aacd6atagen2026-09-08 08:24 UTC181
        let oauth = self.client.oauth();
96fdf90aacd6atagen2026-09-08 08:24 UTC182
        if let Err(error) = oauth.finish_login(callback_url.into()).await {
96fdf90aacd6atagen2026-09-08 08:24 UTC183
            oauth.abort_login(&state).await;
96fdf90aacd6atagen2026-09-08 08:24 UTC184
            return Err(account_error("OAuth login", error));
96fdf90aacd6atagen2026-09-08 08:24 UTC185
        }
a250c7fa43fbatagen2026-09-26 13:35 UTC186
        let (tracking, store_lock) = self
f12377bce9b9atagen2026-09-26 12:32 UTC187
            .tracking
f12377bce9b9atagen2026-09-26 12:32 UTC188
            .take()
f12377bce9b9atagen2026-09-26 12:32 UTC189
            .ok_or(AccountError::OAuthCallbackAlreadySubmitted)?;
a250c7fa43fbatagen2026-09-26 13:35 UTC190
        Session::saved(
a250c7fa43fbatagen2026-09-26 13:35 UTC191
            self.client.clone(),
a250c7fa43fbatagen2026-09-26 13:35 UTC192
            self.sessions.clone(),
a250c7fa43fbatagen2026-09-26 13:35 UTC193
            tracking,
a250c7fa43fbatagen2026-09-26 13:35 UTC194
            store_lock,
a250c7fa43fbatagen2026-09-26 13:35 UTC195
        )
a250c7fa43fbatagen2026-09-26 13:35 UTC196
        .await
96fdf90aacd6atagen2026-09-08 08:24 UTC197
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC198
96fdf90aacd6atagen2026-09-08 08:24 UTC199
    pub async fn abort(mut self) {
96fdf90aacd6atagen2026-09-08 08:24 UTC200
        if let Some(state) = self.state.take() {
96fdf90aacd6atagen2026-09-08 08:24 UTC201
            self.client.oauth().abort_login(&state).await;
96fdf90aacd6atagen2026-09-08 08:24 UTC202
        }
96fdf90aacd6atagen2026-09-08 08:24 UTC203
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC204
}
96fdf90aacd6atagen2026-09-08 08:24 UTC205
96fdf90aacd6atagen2026-09-08 08:24 UTC206
pub struct StoreConfig {
62fe32759529atagen2026-09-26 08:50 UTC207
    location: StoreLocation,
96fdf90aacd6atagen2026-09-08 08:24 UTC208
    passphrase: String,
62fe32759529atagen2026-09-26 08:50 UTC209
}
62fe32759529atagen2026-09-26 08:50 UTC210
62fe32759529atagen2026-09-26 08:50 UTC211
enum StoreLocation {
62fe32759529atagen2026-09-26 08:50 UTC212
    #[cfg(feature = "sqlite")]
62fe32759529atagen2026-09-26 08:50 UTC213
    Sqlite(PathBuf),
62fe32759529atagen2026-09-26 08:50 UTC214
    #[cfg(feature = "indexeddb")]
62fe32759529atagen2026-09-26 08:50 UTC215
    IndexedDb(String),
96fdf90aacd6atagen2026-09-08 08:24 UTC216
}
96fdf90aacd6atagen2026-09-08 08:24 UTC217
96fdf90aacd6atagen2026-09-08 08:24 UTC218
impl StoreConfig {
62fe32759529atagen2026-09-26 08:50 UTC219
    #[cfg(feature = "sqlite")]
62fe32759529atagen2026-09-26 08:50 UTC220
    #[must_use]
62fe32759529atagen2026-09-26 08:50 UTC221
    pub fn sqlite(path: impl Into<PathBuf>, passphrase: impl Into<String>) -> Self {
62fe32759529atagen2026-09-26 08:50 UTC222
        Self {
62fe32759529atagen2026-09-26 08:50 UTC223
            location: StoreLocation::Sqlite(path.into()),
62fe32759529atagen2026-09-26 08:50 UTC224
            passphrase: passphrase.into(),
62fe32759529atagen2026-09-26 08:50 UTC225
        }
62fe32759529atagen2026-09-26 08:50 UTC226
    }
62fe32759529atagen2026-09-26 08:50 UTC227
62fe32759529atagen2026-09-26 08:50 UTC228
    #[cfg(feature = "indexeddb")]
96fdf90aacd6atagen2026-09-08 08:24 UTC229
    #[must_use]
62fe32759529atagen2026-09-26 08:50 UTC230
    pub fn indexeddb(name: impl Into<String>, passphrase: impl Into<String>) -> Self {
96fdf90aacd6atagen2026-09-08 08:24 UTC231
        Self {
62fe32759529atagen2026-09-26 08:50 UTC232
            location: StoreLocation::IndexedDb(name.into()),
96fdf90aacd6atagen2026-09-08 08:24 UTC233
            passphrase: passphrase.into(),
96fdf90aacd6atagen2026-09-08 08:24 UTC234
        }
96fdf90aacd6atagen2026-09-08 08:24 UTC235
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC236
713205a95af2atagen2026-09-26 09:24 UTC237
    /// delete the store's databases, once nothing has them open
713205a95af2atagen2026-09-26 09:24 UTC238
    pub async fn delete(&self) -> Result<(), AccountError> {
713205a95af2atagen2026-09-26 09:24 UTC239
        match &self.location {
713205a95af2atagen2026-09-26 09:24 UTC240
            #[cfg(feature = "sqlite")]
713205a95af2atagen2026-09-26 09:24 UTC241
            StoreLocation::Sqlite(path) => crate::session_store::delete_sqlite_store(path)
713205a95af2atagen2026-09-26 09:24 UTC242
                .map_err(|error| account_error("deleting the Matrix store", error)),
713205a95af2atagen2026-09-26 09:24 UTC243
            #[cfg(feature = "indexeddb")]
713205a95af2atagen2026-09-26 09:24 UTC244
            StoreLocation::IndexedDb(name) => crate::session_store::delete_indexeddb_store(name)
713205a95af2atagen2026-09-26 09:24 UTC245
                .await
6db49c0ecf71atagen2026-09-26 12:41 UTC246
                .map_err(|error| error.into_account_error("deleting the Matrix store")),
713205a95af2atagen2026-09-26 09:24 UTC247
        }
713205a95af2atagen2026-09-26 09:24 UTC248
    }
713205a95af2atagen2026-09-26 09:24 UTC249
a250c7fa43fbatagen2026-09-26 13:35 UTC250
    /// taken before the client opens the store, and held until the engine and every
a250c7fa43fbatagen2026-09-26 13:35 UTC251
    /// `ClientHandle` are gone
a250c7fa43fbatagen2026-09-26 13:35 UTC252
    pub(crate) async fn lock(&self) -> Result<StoreLock, AccountError> {
a250c7fa43fbatagen2026-09-26 13:35 UTC253
        match &self.location {
a250c7fa43fbatagen2026-09-26 13:35 UTC254
            #[cfg(feature = "sqlite")]
a250c7fa43fbatagen2026-09-26 13:35 UTC255
            StoreLocation::Sqlite(path) => StoreLock::file(path),
a250c7fa43fbatagen2026-09-26 13:35 UTC256
            #[cfg(feature = "indexeddb")]
a250c7fa43fbatagen2026-09-26 13:35 UTC257
            StoreLocation::IndexedDb(name) => StoreLock::web(name).await,
a250c7fa43fbatagen2026-09-26 13:35 UTC258
        }
a250c7fa43fbatagen2026-09-26 13:35 UTC259
    }
a250c7fa43fbatagen2026-09-26 13:35 UTC260
713205a95af2atagen2026-09-26 09:24 UTC261
    pub(crate) fn passphrase(&self) -> &str {
713205a95af2atagen2026-09-26 09:24 UTC262
        &self.passphrase
713205a95af2atagen2026-09-26 09:24 UTC263
    }
713205a95af2atagen2026-09-26 09:24 UTC264
713205a95af2atagen2026-09-26 09:24 UTC265
    #[cfg(feature = "indexeddb")]
713205a95af2atagen2026-09-26 09:24 UTC266
    pub(crate) fn indexeddb_name(&self) -> &str {
713205a95af2atagen2026-09-26 09:24 UTC267
        let StoreLocation::IndexedDb(name) = &self.location;
713205a95af2atagen2026-09-26 09:24 UTC268
        name
713205a95af2atagen2026-09-26 09:24 UTC269
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC270
}
96fdf90aacd6atagen2026-09-08 08:24 UTC271
f12377bce9b9atagen2026-09-26 12:32 UTC272
/// Serializable authentication secrets. A `SessionStore` keeps it, and the engine
f12377bce9b9atagen2026-09-26 12:32 UTC273
/// replaces it there on every token rotation.
96fdf90aacd6atagen2026-09-08 08:24 UTC274
#[derive(Clone, Deserialize, Serialize)]
96fdf90aacd6atagen2026-09-08 08:24 UTC275
pub struct SessionRecord {
96fdf90aacd6atagen2026-09-08 08:24 UTC276
    homeserver: String,
96fdf90aacd6atagen2026-09-08 08:24 UTC277
    authentication: AuthenticationRecord,
96fdf90aacd6atagen2026-09-08 08:24 UTC278
}
96fdf90aacd6atagen2026-09-08 08:24 UTC279
96fdf90aacd6atagen2026-09-08 08:24 UTC280
#[derive(Clone, Deserialize, Serialize)]
96fdf90aacd6atagen2026-09-08 08:24 UTC281
#[serde(tag = "type", content = "session", rename_all = "snake_case")]
96fdf90aacd6atagen2026-09-08 08:24 UTC282
enum AuthenticationRecord {
96fdf90aacd6atagen2026-09-08 08:24 UTC283
    Matrix(MatrixSession),
96fdf90aacd6atagen2026-09-08 08:24 UTC284
    OAuth {
96fdf90aacd6atagen2026-09-08 08:24 UTC285
        client_id: ClientId,
96fdf90aacd6atagen2026-09-08 08:24 UTC286
        user: UserSession,
96fdf90aacd6atagen2026-09-08 08:24 UTC287
    },
6f1d6591c10datagen2026-09-26 09:52 UTC288
    SoftLoggedOut {
6f1d6591c10datagen2026-09-26 09:52 UTC289
        meta: SessionMeta,
6f1d6591c10datagen2026-09-26 09:52 UTC290
        client_id: Option<ClientId>,
6f1d6591c10datagen2026-09-26 09:52 UTC291
    },
96fdf90aacd6atagen2026-09-08 08:24 UTC292
}
96fdf90aacd6atagen2026-09-08 08:24 UTC293
96fdf90aacd6atagen2026-09-08 08:24 UTC294
impl SessionRecord {
96fdf90aacd6atagen2026-09-08 08:24 UTC295
    #[must_use]
96fdf90aacd6atagen2026-09-08 08:24 UTC296
    pub fn homeserver(&self) -> &str {
96fdf90aacd6atagen2026-09-08 08:24 UTC297
        &self.homeserver
96fdf90aacd6atagen2026-09-08 08:24 UTC298
    }
6f1d6591c10datagen2026-09-26 09:52 UTC299
6f1d6591c10datagen2026-09-26 09:52 UTC300
    pub(crate) fn soft_logged_out(self) -> Self {
6f1d6591c10datagen2026-09-26 09:52 UTC301
        let authentication = match self.authentication {
6f1d6591c10datagen2026-09-26 09:52 UTC302
            AuthenticationRecord::Matrix(session) => AuthenticationRecord::SoftLoggedOut {
6f1d6591c10datagen2026-09-26 09:52 UTC303
                meta: session.meta,
6f1d6591c10datagen2026-09-26 09:52 UTC304
                client_id: None,
6f1d6591c10datagen2026-09-26 09:52 UTC305
            },
6f1d6591c10datagen2026-09-26 09:52 UTC306
            AuthenticationRecord::OAuth { client_id, user } => {
6f1d6591c10datagen2026-09-26 09:52 UTC307
                AuthenticationRecord::SoftLoggedOut {
6f1d6591c10datagen2026-09-26 09:52 UTC308
                    meta: user.meta,
6f1d6591c10datagen2026-09-26 09:52 UTC309
                    client_id: Some(client_id),
6f1d6591c10datagen2026-09-26 09:52 UTC310
                }
6f1d6591c10datagen2026-09-26 09:52 UTC311
            }
6f1d6591c10datagen2026-09-26 09:52 UTC312
            soft @ AuthenticationRecord::SoftLoggedOut { .. } => soft,
6f1d6591c10datagen2026-09-26 09:52 UTC313
        };
6f1d6591c10datagen2026-09-26 09:52 UTC314
        Self {
6f1d6591c10datagen2026-09-26 09:52 UTC315
            homeserver: self.homeserver,
6f1d6591c10datagen2026-09-26 09:52 UTC316
            authentication,
6f1d6591c10datagen2026-09-26 09:52 UTC317
        }
6f1d6591c10datagen2026-09-26 09:52 UTC318
    }
6f1d6591c10datagen2026-09-26 09:52 UTC319
}
6f1d6591c10datagen2026-09-26 09:52 UTC320
6f1d6591c10datagen2026-09-26 09:52 UTC321
pub enum Restore {
6f1d6591c10datagen2026-09-26 09:52 UTC322
    Resumed(Session),
6f1d6591c10datagen2026-09-26 09:52 UTC323
    SoftLoggedOut(SoftLogout),
6f1d6591c10datagen2026-09-26 09:52 UTC324
}
6f1d6591c10datagen2026-09-26 09:52 UTC325
6f1d6591c10datagen2026-09-26 09:52 UTC326
/// who to log in again as. the store keeps this device's e2ee keys, so a login
6f1d6591c10datagen2026-09-26 09:52 UTC327
/// as any other device would orphan them
6f1d6591c10datagen2026-09-26 09:52 UTC328
#[derive(Clone, Debug)]
6f1d6591c10datagen2026-09-26 09:52 UTC329
#[non_exhaustive]
6f1d6591c10datagen2026-09-26 09:52 UTC330
pub struct SoftLogout {
6f1d6591c10datagen2026-09-26 09:52 UTC331
    pub homeserver: String,
6f1d6591c10datagen2026-09-26 09:52 UTC332
    pub user_id: OwnedUserId,
6f1d6591c10datagen2026-09-26 09:52 UTC333
    pub device_id: OwnedDeviceId,
6f1d6591c10datagen2026-09-26 09:52 UTC334
    /// set when the login was OAuth, for `OAuthLogin::with_client_id`
6f1d6591c10datagen2026-09-26 09:52 UTC335
    pub client_id: Option<String>,
6f1d6591c10datagen2026-09-26 09:52 UTC336
}
6f1d6591c10datagen2026-09-26 09:52 UTC337
6f1d6591c10datagen2026-09-26 09:52 UTC338
impl SoftLogout {
6f1d6591c10datagen2026-09-26 09:52 UTC339
    #[must_use]
6f1d6591c10datagen2026-09-26 09:52 UTC340
    pub fn password_login(&self, password: impl Into<String>) -> PasswordLogin {
6f1d6591c10datagen2026-09-26 09:52 UTC341
        PasswordLogin::new(self.homeserver.clone(), self.user_id.as_str(), password)
6f1d6591c10datagen2026-09-26 09:52 UTC342
            .with_device_id(self.device_id.clone())
6f1d6591c10datagen2026-09-26 09:52 UTC343
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC344
}
96fdf90aacd6atagen2026-09-08 08:24 UTC345
96fdf90aacd6atagen2026-09-08 08:24 UTC346
#[derive(Debug, Error)]
96fdf90aacd6atagen2026-09-08 08:24 UTC347
pub enum AccountError {
96fdf90aacd6atagen2026-09-08 08:24 UTC348
    #[error("{context} failed")]
96fdf90aacd6atagen2026-09-08 08:24 UTC349
    Operation {
96fdf90aacd6atagen2026-09-08 08:24 UTC350
        context: &'static str,
96fdf90aacd6atagen2026-09-08 08:24 UTC351
        #[source]
62fe32759529atagen2026-09-26 08:50 UTC352
        source: Box<SourceError>,
96fdf90aacd6atagen2026-09-08 08:24 UTC353
    },
96fdf90aacd6atagen2026-09-08 08:24 UTC354
    #[error("the homeserver returned no authenticated session")]
96fdf90aacd6atagen2026-09-08 08:24 UTC355
    MissingSession,
96fdf90aacd6atagen2026-09-08 08:24 UTC356
    #[error("the SDK returned an unsupported authentication session")]
96fdf90aacd6atagen2026-09-08 08:24 UTC357
    UnsupportedAuthentication,
96fdf90aacd6atagen2026-09-08 08:24 UTC358
    #[error("the OAuth callback was already submitted")]
96fdf90aacd6atagen2026-09-08 08:24 UTC359
    OAuthCallbackAlreadySubmitted,
6db49c0ecf71atagen2026-09-26 12:41 UTC360
    /// an IndexedDB delete is waiting on the store's other connections. it goes through
6db49c0ecf71atagen2026-09-26 12:41 UTC361
    /// once they close, and opening the store again waits behind it
6db49c0ecf71atagen2026-09-26 12:41 UTC362
    #[error("the store is still open elsewhere, it will be deleted once that closes")]
6db49c0ecf71atagen2026-09-26 12:41 UTC363
    StoreDeletePending,
a250c7fa43fbatagen2026-09-26 13:35 UTC364
    /// another engine, in this process or another, has the store. only one runs per store
a250c7fa43fbatagen2026-09-26 13:35 UTC365
    #[error("another engine is using this store")]
a250c7fa43fbatagen2026-09-26 13:35 UTC366
    StoreInUse,
a250c7fa43fbatagen2026-09-26 13:35 UTC367
    /// the login worked but its first record didn't save. the server already has the
a250c7fa43fbatagen2026-09-26 13:35 UTC368
    /// device, so retry the save rather than log in again
a250c7fa43fbatagen2026-09-26 13:35 UTC369
    #[error("saving the new login's record failed")]
a250c7fa43fbatagen2026-09-26 13:35 UTC370
    Unsaved {
a250c7fa43fbatagen2026-09-26 13:35 UTC371
        session: Box<UnsavedSession>,
a250c7fa43fbatagen2026-09-26 13:35 UTC372
        #[source]
a250c7fa43fbatagen2026-09-26 13:35 UTC373
        source: Box<AccountError>,
a250c7fa43fbatagen2026-09-26 13:35 UTC374
    },
96fdf90aacd6atagen2026-09-08 08:24 UTC375
    #[error(transparent)]
96fdf90aacd6atagen2026-09-08 08:24 UTC376
    Engine(#[from] EngineError),
96fdf90aacd6atagen2026-09-08 08:24 UTC377
}
96fdf90aacd6atagen2026-09-08 08:24 UTC378
a250c7fa43fbatagen2026-09-26 13:35 UTC379
/// a live login whose record never reached its `SessionStore`
a250c7fa43fbatagen2026-09-26 13:35 UTC380
pub struct UnsavedSession {
a250c7fa43fbatagen2026-09-26 13:35 UTC381
    session: Session,
a250c7fa43fbatagen2026-09-26 13:35 UTC382
    sessions: Arc<dyn SessionStore>,
a250c7fa43fbatagen2026-09-26 13:35 UTC383
}
a250c7fa43fbatagen2026-09-26 13:35 UTC384
a250c7fa43fbatagen2026-09-26 13:35 UTC385
impl UnsavedSession {
a250c7fa43fbatagen2026-09-26 13:35 UTC386
    pub async fn save(self) -> Result<Session, AccountError> {
a250c7fa43fbatagen2026-09-26 13:35 UTC387
        let saved = match session_record(&self.session.client) {
a250c7fa43fbatagen2026-09-26 13:35 UTC388
            Ok(record) => self.sessions.save(&record).await,
a250c7fa43fbatagen2026-09-26 13:35 UTC389
            Err(error) => Err(error),
a250c7fa43fbatagen2026-09-26 13:35 UTC390
        };
a250c7fa43fbatagen2026-09-26 13:35 UTC391
        match saved {
a250c7fa43fbatagen2026-09-26 13:35 UTC392
            Ok(()) => Ok(self.session),
a250c7fa43fbatagen2026-09-26 13:35 UTC393
            Err(source) => Err(AccountError::Unsaved {
a250c7fa43fbatagen2026-09-26 13:35 UTC394
                session: Box::new(self),
a250c7fa43fbatagen2026-09-26 13:35 UTC395
                source: Box::new(source),
a250c7fa43fbatagen2026-09-26 13:35 UTC396
            }),
a250c7fa43fbatagen2026-09-26 13:35 UTC397
        }
a250c7fa43fbatagen2026-09-26 13:35 UTC398
    }
a250c7fa43fbatagen2026-09-26 13:35 UTC399
a250c7fa43fbatagen2026-09-26 13:35 UTC400
    /// the record to keep somewhere else, if the store won't take it
a250c7fa43fbatagen2026-09-26 13:35 UTC401
    pub fn record(&self) -> Result<SessionRecord, AccountError> {
a250c7fa43fbatagen2026-09-26 13:35 UTC402
        session_record(&self.session.client)
a250c7fa43fbatagen2026-09-26 13:35 UTC403
    }
a250c7fa43fbatagen2026-09-26 13:35 UTC404
}
a250c7fa43fbatagen2026-09-26 13:35 UTC405
a250c7fa43fbatagen2026-09-26 13:35 UTC406
impl std::fmt::Debug for UnsavedSession {
a250c7fa43fbatagen2026-09-26 13:35 UTC407
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
a250c7fa43fbatagen2026-09-26 13:35 UTC408
        formatter
a250c7fa43fbatagen2026-09-26 13:35 UTC409
            .debug_struct("UnsavedSession")
a250c7fa43fbatagen2026-09-26 13:35 UTC410
            .finish_non_exhaustive()
a250c7fa43fbatagen2026-09-26 13:35 UTC411
    }
a250c7fa43fbatagen2026-09-26 13:35 UTC412
}
a250c7fa43fbatagen2026-09-26 13:35 UTC413
96fdf90aacd6atagen2026-09-08 08:24 UTC414
impl Session {
96fdf90aacd6atagen2026-09-08 08:24 UTC415
    pub async fn login_password(
96fdf90aacd6atagen2026-09-08 08:24 UTC416
        login: PasswordLogin,
f12377bce9b9atagen2026-09-26 12:32 UTC417
        sessions: Arc<dyn SessionStore>,
96fdf90aacd6atagen2026-09-08 08:24 UTC418
    ) -> Result<Self, AccountError> {
a250c7fa43fbatagen2026-09-26 13:35 UTC419
        let store_lock = sessions.store().lock().await?;
713205a95af2atagen2026-09-26 09:24 UTC420
        let client = matrix_client_builder(sessions.store())
96fdf90aacd6atagen2026-09-08 08:24 UTC421
            .server_name_or_homeserver_url(login.homeserver.trim())
96fdf90aacd6atagen2026-09-08 08:24 UTC422
            .build()
96fdf90aacd6atagen2026-09-08 08:24 UTC423
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC424
            .map_err(|error| account_error("building the Matrix client", error))?;
f12377bce9b9atagen2026-09-26 12:32 UTC425
        let tracking = Tracking::start(&client, sessions.clone())?;
96fdf90aacd6atagen2026-09-08 08:24 UTC426
        let mut request = client
96fdf90aacd6atagen2026-09-08 08:24 UTC427
            .matrix_auth()
96fdf90aacd6atagen2026-09-08 08:24 UTC428
            .login_username(login.username.trim(), &login.password)
96fdf90aacd6atagen2026-09-08 08:24 UTC429
            .request_refresh_token();
96fdf90aacd6atagen2026-09-08 08:24 UTC430
        if let Some(name) = login.device_display_name.as_deref() {
96fdf90aacd6atagen2026-09-08 08:24 UTC431
            request = request.initial_device_display_name(name);
96fdf90aacd6atagen2026-09-08 08:24 UTC432
        }
fa9114fcf75fatagen2026-09-24 12:51 UTC433
        if let Some(device_id) = login.device_id.as_deref() {
fa9114fcf75fatagen2026-09-24 12:51 UTC434
            request = request.device_id(device_id.as_str());
fa9114fcf75fatagen2026-09-24 12:51 UTC435
        }
96fdf90aacd6atagen2026-09-08 08:24 UTC436
        request
96fdf90aacd6atagen2026-09-08 08:24 UTC437
            .send()
96fdf90aacd6atagen2026-09-08 08:24 UTC438
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC439
            .map_err(|error| account_error("password login", error))?;
a250c7fa43fbatagen2026-09-26 13:35 UTC440
        Self::saved(client, sessions, tracking, store_lock).await
96fdf90aacd6atagen2026-09-08 08:24 UTC441
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC442
a250c7fa43fbatagen2026-09-26 13:35 UTC443
    /// the pending login lives only in this process, so the one that begins it has to finish it
96fdf90aacd6atagen2026-09-08 08:24 UTC444
    pub async fn begin_oauth(
96fdf90aacd6atagen2026-09-08 08:24 UTC445
        login: OAuthLogin,
713205a95af2atagen2026-09-26 09:24 UTC446
        sessions: Arc<dyn SessionStore>,
96fdf90aacd6atagen2026-09-08 08:24 UTC447
    ) -> Result<PendingOAuthLogin, AccountError> {
96fdf90aacd6atagen2026-09-08 08:24 UTC448
        let redirect_uri = Url::parse(login.redirect_uri.trim())
96fdf90aacd6atagen2026-09-08 08:24 UTC449
            .map_err(|error| account_error("parsing the OAuth redirect URI", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC450
        let client_uri = Url::parse(login.client_uri.trim())
96fdf90aacd6atagen2026-09-08 08:24 UTC451
            .map_err(|error| account_error("parsing the OAuth client URI", error))?;
a250c7fa43fbatagen2026-09-26 13:35 UTC452
        let store_lock = sessions.store().lock().await?;
713205a95af2atagen2026-09-26 09:24 UTC453
        let client = matrix_client_builder(sessions.store())
96fdf90aacd6atagen2026-09-08 08:24 UTC454
            .server_name_or_homeserver_url(login.homeserver.trim())
96fdf90aacd6atagen2026-09-08 08:24 UTC455
            .build()
96fdf90aacd6atagen2026-09-08 08:24 UTC456
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC457
            .map_err(|error| account_error("building the Matrix client", error))?;
f12377bce9b9atagen2026-09-26 12:32 UTC458
        let tracking = Tracking::start(&client, sessions.clone())?;
96fdf90aacd6atagen2026-09-08 08:24 UTC459
        let application_type = match login.application_type {
96fdf90aacd6atagen2026-09-08 08:24 UTC460
            OAuthApplicationType::Native => ApplicationType::Native,
96fdf90aacd6atagen2026-09-08 08:24 UTC461
            OAuthApplicationType::Web => ApplicationType::Web,
96fdf90aacd6atagen2026-09-08 08:24 UTC462
        };
96fdf90aacd6atagen2026-09-08 08:24 UTC463
        let mut metadata = ClientMetadata::new(
96fdf90aacd6atagen2026-09-08 08:24 UTC464
            application_type,
96fdf90aacd6atagen2026-09-08 08:24 UTC465
            vec![OAuthGrantType::AuthorizationCode {
96fdf90aacd6atagen2026-09-08 08:24 UTC466
                redirect_uris: vec![redirect_uri.clone()],
96fdf90aacd6atagen2026-09-08 08:24 UTC467
            }],
96fdf90aacd6atagen2026-09-08 08:24 UTC468
            Localized::new(client_uri, []),
96fdf90aacd6atagen2026-09-08 08:24 UTC469
        );
96fdf90aacd6atagen2026-09-08 08:24 UTC470
        metadata.client_name = login.client_name.map(|name| Localized::new(name, []));
96fdf90aacd6atagen2026-09-08 08:24 UTC471
        let metadata = Raw::new(&metadata)
96fdf90aacd6atagen2026-09-08 08:24 UTC472
            .map_err(|error| account_error("serializing OAuth client metadata", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC473
        let mut registration = ClientRegistrationData::new(metadata);
96fdf90aacd6atagen2026-09-08 08:24 UTC474
        if let Some(client_id) = login.client_id {
96fdf90aacd6atagen2026-09-08 08:24 UTC475
            registration.static_registrations = Some(HashMap::from([(
96fdf90aacd6atagen2026-09-08 08:24 UTC476
                client.homeserver(),
96fdf90aacd6atagen2026-09-08 08:24 UTC477
                ClientId::new(client_id),
96fdf90aacd6atagen2026-09-08 08:24 UTC478
            )]));
96fdf90aacd6atagen2026-09-08 08:24 UTC479
        }
96fdf90aacd6atagen2026-09-08 08:24 UTC480
        let authorization = client
96fdf90aacd6atagen2026-09-08 08:24 UTC481
            .oauth()
96fdf90aacd6atagen2026-09-08 08:24 UTC482
            .login(redirect_uri, login.device_id, Some(registration), None)
96fdf90aacd6atagen2026-09-08 08:24 UTC483
            .build()
96fdf90aacd6atagen2026-09-08 08:24 UTC484
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC485
            .map_err(|error| account_error("starting OAuth login", error))?;
96fdf90aacd6atagen2026-09-08 08:24 UTC486
        Ok(PendingOAuthLogin {
96fdf90aacd6atagen2026-09-08 08:24 UTC487
            client,
713205a95af2atagen2026-09-26 09:24 UTC488
            sessions,
a250c7fa43fbatagen2026-09-26 13:35 UTC489
            tracking: Some((tracking, store_lock)),
96fdf90aacd6atagen2026-09-08 08:24 UTC490
            authorization_url: authorization.url.to_string(),
96fdf90aacd6atagen2026-09-08 08:24 UTC491
            state: Some(authorization.state),
96fdf90aacd6atagen2026-09-08 08:24 UTC492
        })
96fdf90aacd6atagen2026-09-08 08:24 UTC493
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC494
713205a95af2atagen2026-09-26 09:24 UTC495
    /// Restore the record `sessions` holds, or `None` when it holds none.
f12377bce9b9atagen2026-09-26 12:32 UTC496
    /// The caller must also handle rejection and explicit logout.
f12377bce9b9atagen2026-09-26 12:32 UTC497
    pub async fn restore(sessions: Arc<dyn SessionStore>) -> Result<Option<Restore>, AccountError> {
713205a95af2atagen2026-09-26 09:24 UTC498
        let Some(record) = sessions.load().await? else {
713205a95af2atagen2026-09-26 09:24 UTC499
            return Ok(None);
713205a95af2atagen2026-09-26 09:24 UTC500
        };
713205a95af2atagen2026-09-26 09:24 UTC501
        let authentication = match record.authentication {
96fdf90aacd6atagen2026-09-08 08:24 UTC502
            AuthenticationRecord::Matrix(session) => AuthSession::Matrix(session),
96fdf90aacd6atagen2026-09-08 08:24 UTC503
            AuthenticationRecord::OAuth { client_id, user } => {
96fdf90aacd6atagen2026-09-08 08:24 UTC504
                OAuthSession { client_id, user }.into()
96fdf90aacd6atagen2026-09-08 08:24 UTC505
            }
6f1d6591c10datagen2026-09-26 09:52 UTC506
            AuthenticationRecord::SoftLoggedOut { meta, client_id } => {
6f1d6591c10datagen2026-09-26 09:52 UTC507
                return Ok(Some(Restore::SoftLoggedOut(SoftLogout {
6f1d6591c10datagen2026-09-26 09:52 UTC508
                    homeserver: record.homeserver,
6f1d6591c10datagen2026-09-26 09:52 UTC509
                    user_id: meta.user_id,
6f1d6591c10datagen2026-09-26 09:52 UTC510
                    device_id: meta.device_id,
6f1d6591c10datagen2026-09-26 09:52 UTC511
                    client_id: client_id.map(|client_id| client_id.as_str().to_owned()),
6f1d6591c10datagen2026-09-26 09:52 UTC512
                })));
6f1d6591c10datagen2026-09-26 09:52 UTC513
            }
96fdf90aacd6atagen2026-09-08 08:24 UTC514
        };
a250c7fa43fbatagen2026-09-26 13:35 UTC515
        let store_lock = sessions.store().lock().await?;
6f1d6591c10datagen2026-09-26 09:52 UTC516
        let client = matrix_client_builder(sessions.store())
6f1d6591c10datagen2026-09-26 09:52 UTC517
            .homeserver_url(&record.homeserver)
6f1d6591c10datagen2026-09-26 09:52 UTC518
            .build()
6f1d6591c10datagen2026-09-26 09:52 UTC519
            .await
6f1d6591c10datagen2026-09-26 09:52 UTC520
            .map_err(|error| account_error("reopening the Matrix store", error))?;
f12377bce9b9atagen2026-09-26 12:32 UTC521
        let tracking = Tracking::start(&client, sessions)?;
96fdf90aacd6atagen2026-09-08 08:24 UTC522
        client
96fdf90aacd6atagen2026-09-08 08:24 UTC523
            .restore_session(authentication)
96fdf90aacd6atagen2026-09-08 08:24 UTC524
            .await
96fdf90aacd6atagen2026-09-08 08:24 UTC525
            .map_err(|error| account_error("restoring the authenticated session", error))?;
a250c7fa43fbatagen2026-09-26 13:35 UTC526
        Ok(Some(Restore::Resumed(Self {
a250c7fa43fbatagen2026-09-26 13:35 UTC527
            client,
a250c7fa43fbatagen2026-09-26 13:35 UTC528
            tracking,
a250c7fa43fbatagen2026-09-26 13:35 UTC529
            store_lock,
a250c7fa43fbatagen2026-09-26 13:35 UTC530
        })))
f12377bce9b9atagen2026-09-26 12:32 UTC531
    }
f12377bce9b9atagen2026-09-26 12:32 UTC532
f12377bce9b9atagen2026-09-26 12:32 UTC533
    /// leave the record to the host, which then saves `ClientHandle::session_record()`
f12377bce9b9atagen2026-09-26 12:32 UTC534
    /// on every `SessionTokensChanged`
f12377bce9b9atagen2026-09-26 12:32 UTC535
    #[must_use]
f12377bce9b9atagen2026-09-26 12:32 UTC536
    pub fn without_persistence(mut self) -> Self {
f12377bce9b9atagen2026-09-26 12:32 UTC537
        self.tracking.persistence = None;
f12377bce9b9atagen2026-09-26 12:32 UTC538
        #[cfg(not(target_family = "wasm"))]
f12377bce9b9atagen2026-09-26 12:32 UTC539
        self.tracking.inline.store(false, Ordering::Release);
f12377bce9b9atagen2026-09-26 12:32 UTC540
        self
96fdf90aacd6atagen2026-09-08 08:24 UTC541
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC542
96fdf90aacd6atagen2026-09-08 08:24 UTC543
    pub async fn build(
96fdf90aacd6atagen2026-09-08 08:24 UTC544
        self,
96fdf90aacd6atagen2026-09-08 08:24 UTC545
        config: EngineConfig,
96fdf90aacd6atagen2026-09-08 08:24 UTC546
    ) -> Result<(Engine, ClientHandle, EventStream), AccountError> {
f12377bce9b9atagen2026-09-26 12:32 UTC547
        Engine::with_persistence(
f12377bce9b9atagen2026-09-26 12:32 UTC548
            self.client,
f12377bce9b9atagen2026-09-26 12:32 UTC549
            config,
f12377bce9b9atagen2026-09-26 12:32 UTC550
            self.tracking.session_changes,
f12377bce9b9atagen2026-09-26 12:32 UTC551
            self.tracking.persistence,
a250c7fa43fbatagen2026-09-26 13:35 UTC552
            Some(self.store_lock),
f12377bce9b9atagen2026-09-26 12:32 UTC553
        )
f12377bce9b9atagen2026-09-26 12:32 UTC554
        .await
f12377bce9b9atagen2026-09-26 12:32 UTC555
        .map_err(AccountError::from)
96fdf90aacd6atagen2026-09-08 08:24 UTC556
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC557
f12377bce9b9atagen2026-09-26 12:32 UTC558
    async fn saved(
f12377bce9b9atagen2026-09-26 12:32 UTC559
        client: Client,
a250c7fa43fbatagen2026-09-26 13:35 UTC560
        sessions: Arc<dyn SessionStore>,
f12377bce9b9atagen2026-09-26 12:32 UTC561
        tracking: Tracking,
a250c7fa43fbatagen2026-09-26 13:35 UTC562
        store_lock: StoreLock,
f12377bce9b9atagen2026-09-26 12:32 UTC563
    ) -> Result<Self, AccountError> {
a250c7fa43fbatagen2026-09-26 13:35 UTC564
        UnsavedSession {
a250c7fa43fbatagen2026-09-26 13:35 UTC565
            session: Self {
a250c7fa43fbatagen2026-09-26 13:35 UTC566
                client,
a250c7fa43fbatagen2026-09-26 13:35 UTC567
                tracking,
a250c7fa43fbatagen2026-09-26 13:35 UTC568
                store_lock,
a250c7fa43fbatagen2026-09-26 13:35 UTC569
            },
a250c7fa43fbatagen2026-09-26 13:35 UTC570
            sessions,
a250c7fa43fbatagen2026-09-26 13:35 UTC571
        }
a250c7fa43fbatagen2026-09-26 13:35 UTC572
        .save()
a250c7fa43fbatagen2026-09-26 13:35 UTC573
        .await
f12377bce9b9atagen2026-09-26 12:32 UTC574
    }
f12377bce9b9atagen2026-09-26 12:32 UTC575
}
f12377bce9b9atagen2026-09-26 12:32 UTC576
f12377bce9b9atagen2026-09-26 12:32 UTC577
impl Tracking {
f12377bce9b9atagen2026-09-26 12:32 UTC578
    fn start(client: &Client, sessions: Arc<dyn SessionStore>) -> Result<Self, AccountError> {
f12377bce9b9atagen2026-09-26 12:32 UTC579
        let session_changes = client.subscribe_to_session_changes();
f12377bce9b9atagen2026-09-26 12:32 UTC580
        #[cfg_attr(target_family = "wasm", allow(unused_variables))]
f12377bce9b9atagen2026-09-26 12:32 UTC581
        let (results, inline_results) = mpsc::unbounded_channel();
f12377bce9b9atagen2026-09-26 12:32 UTC582
        #[cfg(not(target_family = "wasm"))]
f12377bce9b9atagen2026-09-26 12:32 UTC583
        let inline = save_inline(client, sessions.clone(), results)?;
f12377bce9b9atagen2026-09-26 12:32 UTC584
        Ok(Self {
f12377bce9b9atagen2026-09-26 12:32 UTC585
            session_changes,
f12377bce9b9atagen2026-09-26 12:32 UTC586
            persistence: Some(Persistence {
f12377bce9b9atagen2026-09-26 12:32 UTC587
                save: Box::new(move |client| {
f12377bce9b9atagen2026-09-26 12:32 UTC588
                    let sessions = sessions.clone();
f12377bce9b9atagen2026-09-26 12:32 UTC589
                    Box::pin(async move {
f12377bce9b9atagen2026-09-26 12:32 UTC590
                        let record = session_record(&client).map_err(save_failed)?;
f12377bce9b9atagen2026-09-26 12:32 UTC591
                        sessions.save(&record).await.map_err(save_failed)
f12377bce9b9atagen2026-09-26 12:32 UTC592
                    })
f12377bce9b9atagen2026-09-26 12:32 UTC593
                }),
f12377bce9b9atagen2026-09-26 12:32 UTC594
                inline: inline_results,
f12377bce9b9atagen2026-09-26 12:32 UTC595
            }),
f12377bce9b9atagen2026-09-26 12:32 UTC596
            #[cfg(not(target_family = "wasm"))]
f12377bce9b9atagen2026-09-26 12:32 UTC597
            inline,
f12377bce9b9atagen2026-09-26 12:32 UTC598
        })
96fdf90aacd6atagen2026-09-08 08:24 UTC599
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC600
}
96fdf90aacd6atagen2026-09-08 08:24 UTC601
f12377bce9b9atagen2026-09-26 12:32 UTC602
/// the sdk calls this inside its refresh, after it has the new tokens and before it uses
f12377bce9b9atagen2026-09-26 12:32 UTC603
/// them, so a store that writes there and then can't lose a refresh token to a crash
f12377bce9b9atagen2026-09-26 12:32 UTC604
#[cfg(not(target_family = "wasm"))]
f12377bce9b9atagen2026-09-26 12:32 UTC605
fn save_inline(
f12377bce9b9atagen2026-09-26 12:32 UTC606
    client: &Client,
f12377bce9b9atagen2026-09-26 12:32 UTC607
    sessions: Arc<dyn SessionStore>,
f12377bce9b9atagen2026-09-26 12:32 UTC608
    results: mpsc::UnboundedSender<Result<(), crate::Error>>,
f12377bce9b9atagen2026-09-26 12:32 UTC609
) -> Result<Arc<AtomicBool>, AccountError> {
f12377bce9b9atagen2026-09-26 12:32 UTC610
    let enabled = Arc::new(AtomicBool::new(true));
f12377bce9b9atagen2026-09-26 12:32 UTC611
    let saving = enabled.clone();
f12377bce9b9atagen2026-09-26 12:32 UTC612
    client
f12377bce9b9atagen2026-09-26 12:32 UTC613
        .set_session_callbacks(
f12377bce9b9atagen2026-09-26 12:32 UTC614
            // only asked for with the cross process refresh lock, which we never enable
f12377bce9b9atagen2026-09-26 12:32 UTC615
            Box::new(|client| {
f12377bce9b9atagen2026-09-26 12:32 UTC616
                client
f12377bce9b9atagen2026-09-26 12:32 UTC617
                    .session_tokens()
f12377bce9b9atagen2026-09-26 12:32 UTC618
                    .ok_or_else(|| AccountError::MissingSession.into())
f12377bce9b9atagen2026-09-26 12:32 UTC619
            }),
f12377bce9b9atagen2026-09-26 12:32 UTC620
            Box::new(move |client| {
f12377bce9b9atagen2026-09-26 12:32 UTC621
                if !saving.load(Ordering::Acquire) {
f12377bce9b9atagen2026-09-26 12:32 UTC622
                    return Ok(());
f12377bce9b9atagen2026-09-26 12:32 UTC623
                }
f12377bce9b9atagen2026-09-26 12:32 UTC624
                let record = session_record(&client)?;
f12377bce9b9atagen2026-09-26 12:32 UTC625
                if let Some(result) = sessions.save_blocking(&record) {
f12377bce9b9atagen2026-09-26 12:32 UTC626
                    let _ = results.send(result.map_err(save_failed));
f12377bce9b9atagen2026-09-26 12:32 UTC627
                }
f12377bce9b9atagen2026-09-26 12:32 UTC628
                Ok(())
f12377bce9b9atagen2026-09-26 12:32 UTC629
            }),
f12377bce9b9atagen2026-09-26 12:32 UTC630
        )
f12377bce9b9atagen2026-09-26 12:32 UTC631
        .map_err(|error| account_error("registering the session callbacks", error))?;
f12377bce9b9atagen2026-09-26 12:32 UTC632
    Ok(enabled)
f12377bce9b9atagen2026-09-26 12:32 UTC633
}
f12377bce9b9atagen2026-09-26 12:32 UTC634
f12377bce9b9atagen2026-09-26 12:32 UTC635
fn save_failed(error: AccountError) -> crate::Error {
f12377bce9b9atagen2026-09-26 12:32 UTC636
    let message = format!("saving the session record failed, {error}");
f12377bce9b9atagen2026-09-26 12:32 UTC637
    crate::Error::with_source(ErrorKind::Store, message, error)
f12377bce9b9atagen2026-09-26 12:32 UTC638
}
f12377bce9b9atagen2026-09-26 12:32 UTC639
96fdf90aacd6atagen2026-09-08 08:24 UTC640
pub(crate) fn session_record(client: &Client) -> Result<SessionRecord, AccountError> {
96fdf90aacd6atagen2026-09-08 08:24 UTC641
    let authentication = match client.session().ok_or(AccountError::MissingSession)? {
96fdf90aacd6atagen2026-09-08 08:24 UTC642
        AuthSession::Matrix(session) => AuthenticationRecord::Matrix(session),
96fdf90aacd6atagen2026-09-08 08:24 UTC643
        AuthSession::OAuth(session) => {
96fdf90aacd6atagen2026-09-08 08:24 UTC644
            let OAuthSession { client_id, user } = *session;
96fdf90aacd6atagen2026-09-08 08:24 UTC645
            AuthenticationRecord::OAuth { client_id, user }
96fdf90aacd6atagen2026-09-08 08:24 UTC646
        }
96fdf90aacd6atagen2026-09-08 08:24 UTC647
        _ => return Err(AccountError::UnsupportedAuthentication),
96fdf90aacd6atagen2026-09-08 08:24 UTC648
    };
96fdf90aacd6atagen2026-09-08 08:24 UTC649
    Ok(SessionRecord {
96fdf90aacd6atagen2026-09-08 08:24 UTC650
        homeserver: client.homeserver().to_string(),
96fdf90aacd6atagen2026-09-08 08:24 UTC651
        authentication,
96fdf90aacd6atagen2026-09-08 08:24 UTC652
    })
96fdf90aacd6atagen2026-09-08 08:24 UTC653
}
96fdf90aacd6atagen2026-09-08 08:24 UTC654
96fdf90aacd6atagen2026-09-08 08:24 UTC655
fn encryption_settings() -> EncryptionSettings {
96fdf90aacd6atagen2026-09-08 08:24 UTC656
    EncryptionSettings {
96fdf90aacd6atagen2026-09-08 08:24 UTC657
        auto_enable_cross_signing: true,
96fdf90aacd6atagen2026-09-08 08:24 UTC658
        backup_download_strategy: BackupDownloadStrategy::OneShot,
96fdf90aacd6atagen2026-09-08 08:24 UTC659
        auto_enable_backups: true,
96fdf90aacd6atagen2026-09-08 08:24 UTC660
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC661
}
96fdf90aacd6atagen2026-09-08 08:24 UTC662
a250c7fa43fbatagen2026-09-26 13:35 UTC663
/// `StoreLock` already keeps every other client off the store, and the sdk's lease would cost
a250c7fa43fbatagen2026-09-26 13:35 UTC664
/// a store write per locked section and a task renewing it every 50ms
96fdf90aacd6atagen2026-09-08 08:24 UTC665
fn matrix_client_builder(store: &StoreConfig) -> ClientBuilder {
a250c7fa43fbatagen2026-09-26 13:35 UTC666
    let builder = Client::builder()
96fdf90aacd6atagen2026-09-08 08:24 UTC667
        .with_encryption_settings(encryption_settings())
96fdf90aacd6atagen2026-09-08 08:24 UTC668
        .with_threading_support(ThreadingSupport::Enabled {
96fdf90aacd6atagen2026-09-08 08:24 UTC669
            with_subscriptions: false,
96fdf90aacd6atagen2026-09-08 08:24 UTC670
        })
a250c7fa43fbatagen2026-09-26 13:35 UTC671
        .handle_refresh_tokens()
a250c7fa43fbatagen2026-09-26 13:35 UTC672
        .cross_process_store_config(CrossProcessLockConfig::SingleProcess);
62fe32759529atagen2026-09-26 08:50 UTC673
    match &store.location {
62fe32759529atagen2026-09-26 08:50 UTC674
        #[cfg(feature = "sqlite")]
62fe32759529atagen2026-09-26 08:50 UTC675
        StoreLocation::Sqlite(path) => builder.sqlite_store(path, Some(&store.passphrase)),
62fe32759529atagen2026-09-26 08:50 UTC676
        #[cfg(feature = "indexeddb")]
62fe32759529atagen2026-09-26 08:50 UTC677
        StoreLocation::IndexedDb(name) => builder.indexeddb_store(name, Some(&store.passphrase)),
62fe32759529atagen2026-09-26 08:50 UTC678
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC679
}
96fdf90aacd6atagen2026-09-08 08:24 UTC680
713205a95af2atagen2026-09-26 09:24 UTC681
pub(crate) fn account_error(
96fdf90aacd6atagen2026-09-08 08:24 UTC682
    context: &'static str,
62fe32759529atagen2026-09-26 08:50 UTC683
    source: impl std::error::Error + SendOutsideWasm + SyncOutsideWasm + 'static,
96fdf90aacd6atagen2026-09-08 08:24 UTC684
) -> AccountError {
96fdf90aacd6atagen2026-09-08 08:24 UTC685
    AccountError::Operation {
96fdf90aacd6atagen2026-09-08 08:24 UTC686
        context,
96fdf90aacd6atagen2026-09-08 08:24 UTC687
        source: Box::new(source),
96fdf90aacd6atagen2026-09-08 08:24 UTC688
    }
96fdf90aacd6atagen2026-09-08 08:24 UTC689
}