atagen

macltok

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