atagen

macltok

public
Star0
Watch0
82d37c369846d6f0ae8845780d89d5a630e2d937
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/account.rsRust1060 lines36.7 KB
1
#[cfg(feature = "sqlite")]
2
use std::path::PathBuf;
3
#[cfg(not(target_family = "wasm"))]
4
use std::sync::atomic::{AtomicBool, Ordering};
5
use std::{collections::HashMap, sync::Arc};
6
7
use matrix_sdk::{
8
    Client, ClientBuilder, SendOutsideWasm, SessionChange, SessionMeta, SyncOutsideWasm,
9
    ThreadingSupport,
10
    authentication::{
11
        AuthSession,
12
        matrix::MatrixSession,
13
        oauth::{
14
            ClientId, ClientRegistrationData, CsrfToken, OAuthSession, PendingAuthorization,
15
            UserSession,
16
            registration::{ApplicationType, ClientMetadata, Localized, OAuthGrantType},
17
        },
18
    },
19
    cross_process_lock::CrossProcessLockConfig,
20
    encryption::{BackupDownloadStrategy, EncryptionSettings},
21
    ruma::{MilliSecondsSinceUnixEpoch, OwnedDeviceId, OwnedUserId, serde::Raw},
22
};
23
use serde::{Deserialize, Serialize};
24
use thiserror::Error;
25
use tokio::sync::{broadcast, mpsc};
26
use url::Url;
27
28
use crate::{
29
    ClientHandle, Engine, EngineConfig, EngineError, ErrorKind, EventStream, ServerError,
30
    SessionStore,
31
    engine::{Persistence, StoreLock},
32
    error::SourceError,
33
};
34
35
/// a logged in client and the `SessionStore` its record lives in. the engine it builds
36
/// saves every token rotation there, unless told `without_persistence`
37
pub struct Session {
38
    client: Client,
39
    tracking: Tracking,
40
    store_lock: StoreLock,
41
}
42
43
/// taken as soon as the client exists, since the sdk can refresh before there's an engine
44
struct Tracking {
45
    store: Arc<dyn SessionStore>,
46
    session_changes: broadcast::Receiver<SessionChange>,
47
    persistence: Option<Persistence>,
48
    #[cfg(not(target_family = "wasm"))]
49
    inline: Arc<AtomicBool>,
50
}
51
52
#[non_exhaustive]
53
pub struct PasswordLogin {
54
    pub homeserver: String,
55
    pub username: String,
56
    pub password: String,
57
    pub device_display_name: Option<String>,
58
    /// set after a soft logout so the store's keys still belong to us
59
    pub device_id: Option<OwnedDeviceId>,
60
    /// let plain http through, for loopback hosts only
61
    pub allow_insecure_loopback: bool,
62
}
63
64
impl PasswordLogin {
65
    #[must_use]
66
    pub fn new(
67
        homeserver: impl Into<String>,
68
        username: impl Into<String>,
69
        password: impl Into<String>,
70
    ) -> Self {
71
        Self {
72
            homeserver: homeserver.into(),
73
            username: username.into(),
74
            password: password.into(),
75
            device_display_name: None,
76
            device_id: None,
77
            allow_insecure_loopback: false,
78
        }
79
    }
80
81
    #[must_use]
82
    pub fn with_device_display_name(mut self, name: impl Into<String>) -> Self {
83
        self.device_display_name = Some(name.into());
84
        self
85
    }
86
87
    #[must_use]
88
    pub fn with_device_id(mut self, device_id: OwnedDeviceId) -> Self {
89
        self.device_id = Some(device_id);
90
        self
91
    }
92
93
    #[must_use]
94
    pub fn allow_insecure_loopback(mut self, allow: bool) -> Self {
95
        self.allow_insecure_loopback = allow;
96
        self
97
    }
98
}
99
100
#[non_exhaustive]
101
pub struct OAuthLogin {
102
    pub homeserver: String,
103
    pub redirect_uri: String,
104
    pub client_uri: String,
105
    pub client_name: Option<String>,
106
    pub client_id: Option<String>,
107
    pub device_id: Option<OwnedDeviceId>,
108
    pub application_type: OAuthApplicationType,
109
    /// let plain http through, for loopback hosts only
110
    pub allow_insecure_loopback: bool,
111
}
112
113
impl OAuthLogin {
114
    #[must_use]
115
    pub fn new(
116
        homeserver: impl Into<String>,
117
        redirect_uri: impl Into<String>,
118
        client_uri: impl Into<String>,
119
        application_type: OAuthApplicationType,
120
    ) -> Self {
121
        Self {
122
            homeserver: homeserver.into(),
123
            redirect_uri: redirect_uri.into(),
124
            client_uri: client_uri.into(),
125
            client_name: None,
126
            client_id: None,
127
            device_id: None,
128
            application_type,
129
            allow_insecure_loopback: false,
130
        }
131
    }
132
133
    #[must_use]
134
    pub fn with_client_name(mut self, name: impl Into<String>) -> Self {
135
        self.client_name = Some(name.into());
136
        self
137
    }
138
139
    /// a statically registered client id, skipping dynamic registration
140
    #[must_use]
141
    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
142
        self.client_id = Some(client_id.into());
143
        self
144
    }
145
146
    #[must_use]
147
    pub fn with_device_id(mut self, device_id: OwnedDeviceId) -> Self {
148
        self.device_id = Some(device_id);
149
        self
150
    }
151
152
    #[must_use]
153
    pub fn allow_insecure_loopback(mut self, allow: bool) -> Self {
154
        self.allow_insecure_loopback = allow;
155
        self
156
    }
157
}
158
159
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
160
#[non_exhaustive]
161
pub enum OAuthApplicationType {
162
    Native,
163
    Web,
164
}
165
166
pub struct PendingOAuthLogin {
167
    client: Client,
168
    sessions: Arc<dyn SessionStore>,
169
    tracking: Option<(Tracking, StoreLock)>,
170
    authorization_url: String,
171
    state: Option<CsrfToken>,
172
    previous: Option<SessionRecord>,
173
}
174
175
impl PendingOAuthLogin {
176
    #[must_use]
177
    pub fn authorization_url(&self) -> &str {
178
        &self.authorization_url
179
    }
180
181
    #[must_use]
182
    pub fn registered_client_id(&self) -> String {
183
        self.client
184
            .oauth()
185
            .client_id()
186
            .expect("OAuth client was registered before authorization")
187
            .as_str()
188
            .to_owned()
189
    }
190
191
    #[must_use]
192
    pub const fn is_pending(&self) -> bool {
193
        self.state.is_some()
194
    }
195
196
    pub async fn finish(&mut self, callback_url: &str) -> Result<Session, AccountError> {
197
        let callback_url = Url::parse(callback_url)
198
            .map_err(|error| account_error("parsing the OAuth callback URL", error))?;
199
        let state = self
200
            .state
201
            .take()
202
            .ok_or(AccountError::OAuthCallbackAlreadySubmitted)?;
203
        let oauth = self.client.oauth();
204
        if let Err(error) = oauth.finish_login(callback_url.into()).await {
205
            oauth.abort_login(&state).await;
206
            if let Some(previous) = self.previous.take() {
207
                put_back(self.sessions.as_ref(), previous).await;
208
            }
209
            return Err(account_error("OAuth login", error));
210
        }
211
        let (tracking, store_lock) = self
212
            .tracking
213
            .take()
214
            .ok_or(AccountError::OAuthCallbackAlreadySubmitted)?;
215
        Session::saved(
216
            self.client.clone(),
217
            self.sessions.clone(),
218
            tracking,
219
            store_lock,
220
        )
221
        .await
222
    }
223
224
    /// puts back what the store held before, or deletes the store if it held nothing
225
    pub async fn abort(self) {
226
        let Self {
227
            client,
228
            sessions,
229
            tracking,
230
            state,
231
            previous,
232
            ..
233
        } = self;
234
        let Some(state) = state else {
235
            return;
236
        };
237
        client.oauth().abort_login(&state).await;
238
        drop(client);
239
        match previous {
240
            Some(previous) => put_back(sessions.as_ref(), previous).await,
241
            None => {
242
                if let Err(error) = sessions.discard().await {
243
                    tracing::warn!(%error, "deleting an abandoned OAuth login's store failed");
244
                }
245
            }
246
        }
247
        drop(tracking);
248
    }
249
}
250
251
async fn put_back(sessions: &dyn SessionStore, previous: SessionRecord) {
252
    if let Err(error) = sessions.save(&previous).await {
253
        tracing::warn!(%error, "putting back the record an OAuth login replaced failed");
254
    }
255
}
256
257
pub struct StoreConfig {
258
    location: StoreLocation,
259
    passphrase: String,
260
}
261
262
enum StoreLocation {
263
    #[cfg(feature = "sqlite")]
264
    Sqlite(PathBuf),
265
    #[cfg(feature = "indexeddb")]
266
    IndexedDb(String),
267
}
268
269
impl StoreConfig {
270
    #[cfg(feature = "sqlite")]
271
    #[must_use]
272
    pub fn sqlite(path: impl Into<PathBuf>, passphrase: impl Into<String>) -> Self {
273
        Self {
274
            location: StoreLocation::Sqlite(path.into()),
275
            passphrase: passphrase.into(),
276
        }
277
    }
278
279
    #[cfg(feature = "indexeddb")]
280
    #[must_use]
281
    pub fn indexeddb(name: impl Into<String>, passphrase: impl Into<String>) -> Self {
282
        Self {
283
            location: StoreLocation::IndexedDb(name.into()),
284
            passphrase: passphrase.into(),
285
        }
286
    }
287
288
    /// delete the store's databases, once nothing has them open
289
    pub async fn delete(&self) -> Result<(), AccountError> {
290
        match &self.location {
291
            #[cfg(feature = "sqlite")]
292
            StoreLocation::Sqlite(path) => crate::session_store::delete_sqlite_store(path)
293
                .map_err(|error| account_error("deleting the Matrix store", error)),
294
            #[cfg(feature = "indexeddb")]
295
            StoreLocation::IndexedDb(name) => crate::session_store::delete_indexeddb_store(name)
296
                .await
297
                .map_err(|error| error.into_account_error("deleting the Matrix store")),
298
        }
299
    }
300
301
    /// taken before the client opens the store, and held until the engine and every
302
    /// `ClientHandle` are gone
303
    pub(crate) async fn lock(&self) -> Result<StoreLock, AccountError> {
304
        match &self.location {
305
            #[cfg(feature = "sqlite")]
306
            StoreLocation::Sqlite(path) => StoreLock::file(path),
307
            #[cfg(feature = "indexeddb")]
308
            StoreLocation::IndexedDb(name) => StoreLock::web(name).await,
309
        }
310
    }
311
312
    pub(crate) fn passphrase(&self) -> &str {
313
        &self.passphrase
314
    }
315
316
    #[cfg(feature = "sqlite")]
317
    pub(crate) fn mentions_location(&self) -> PathBuf {
318
        let StoreLocation::Sqlite(path) = &self.location;
319
        path.join("macltok-mentions.sqlite3")
320
    }
321
322
    #[cfg(feature = "indexeddb")]
323
    pub(crate) fn mentions_location(&self) -> String {
324
        format!("{}::macltok-mentions", self.indexeddb_name())
325
    }
326
327
    #[cfg(feature = "indexeddb")]
328
    pub(crate) fn indexeddb_name(&self) -> &str {
329
        let StoreLocation::IndexedDb(name) = &self.location;
330
        name
331
    }
332
}
333
334
/// Serializable authentication secrets. A `SessionStore` keeps it, and the engine
335
/// replaces it there on every token rotation.
336
#[derive(Clone, Deserialize, Serialize)]
337
pub struct SessionRecord {
338
    homeserver: String,
339
    authentication: AuthenticationRecord,
340
}
341
342
#[derive(Clone, Deserialize, Serialize)]
343
#[serde(tag = "type", content = "session", rename_all = "snake_case")]
344
enum AuthenticationRecord {
345
    Matrix(MatrixSession),
346
    OAuth {
347
        client_id: ClientId,
348
        user: UserSession,
349
    },
350
    SoftLoggedOut {
351
        meta: SessionMeta,
352
        client_id: Option<ClientId>,
353
    },
354
    /// an oauth login waiting on its redirect. `authorization` holds the pkce verifier
355
    PendingOAuth {
356
        client_id: ClientId,
357
        state: CsrfToken,
358
        authorization: Box<PendingAuthorization>,
359
        started_ms: u64,
360
        /// what the store held before, put back if the login never finishes
361
        previous: Option<Box<SessionRecord>>,
362
    },
363
}
364
365
/// authorization codes live for minutes, so a login this old was abandoned
366
const OAUTH_PENDING_FOR_MS: u64 = 60 * 60 * 1000;
367
368
/// the authorization server answers in the query, or the fragment when asked to
369
pub(crate) fn callback_state(callback: &Url) -> Option<String> {
370
    let query = callback.query_pairs();
371
    let fragment = url::form_urlencoded::parse(callback.fragment().unwrap_or_default().as_bytes());
372
    query
373
        .chain(fragment)
374
        .find(|(key, _)| key == "state")
375
        .map(|(_, state)| state.into_owned())
376
}
377
378
fn now_ms() -> u64 {
379
    MilliSecondsSinceUnixEpoch::now().get().into()
380
}
381
382
impl SessionRecord {
383
    #[must_use]
384
    pub fn homeserver(&self) -> &str {
385
        &self.homeserver
386
    }
387
388
    /// a pending oauth login is nobody yet, unless it resumes someone
389
    pub(crate) fn user_id(&self) -> Option<&OwnedUserId> {
390
        match &self.authentication {
391
            AuthenticationRecord::Matrix(session) => Some(&session.meta.user_id),
392
            AuthenticationRecord::OAuth { user, .. } => Some(&user.meta.user_id),
393
            AuthenticationRecord::SoftLoggedOut { meta, .. } => Some(&meta.user_id),
394
            AuthenticationRecord::PendingOAuth { previous, .. } => previous.as_ref()?.user_id(),
395
        }
396
    }
397
398
    /// what a login should resume. a pending oauth login stands in for the record before it
399
    pub(crate) fn resumable(self) -> Option<Self> {
400
        match self.authentication {
401
            AuthenticationRecord::PendingOAuth { previous, .. } => {
402
                previous.and_then(|previous| previous.resumable())
403
            }
404
            _ => Some(self),
405
        }
406
    }
407
408
    pub(crate) fn pending_oauth_state(&self) -> Option<&str> {
409
        match &self.authentication {
410
            AuthenticationRecord::PendingOAuth { state, .. } => Some(state.secret()),
411
            _ => None,
412
        }
413
    }
414
415
    pub(crate) fn oauth_expired(&self) -> bool {
416
        let AuthenticationRecord::PendingOAuth { started_ms, .. } = &self.authentication else {
417
            return false;
418
        };
419
        now_ms().saturating_sub(*started_ms) > OAUTH_PENDING_FOR_MS
420
    }
421
422
    pub(crate) fn soft_logout(&self) -> Option<SoftLogout> {
423
        let (meta, client_id) = match &self.authentication {
424
            AuthenticationRecord::SoftLoggedOut { meta, client_id } => (meta, client_id),
425
            AuthenticationRecord::PendingOAuth { previous, .. } => {
426
                return previous.as_ref()?.soft_logout();
427
            }
428
            _ => return None,
429
        };
430
        Some(SoftLogout {
431
            homeserver: self.homeserver.clone(),
432
            user_id: meta.user_id.clone(),
433
            device_id: meta.device_id.clone(),
434
            client_id: client_id
435
                .as_ref()
436
                .map(|client_id| client_id.as_str().to_owned()),
437
        })
438
    }
439
440
    pub(crate) fn soft_logged_out(self) -> Self {
441
        let authentication = match self.authentication {
442
            AuthenticationRecord::Matrix(session) => AuthenticationRecord::SoftLoggedOut {
443
                meta: session.meta,
444
                client_id: None,
445
            },
446
            AuthenticationRecord::OAuth { client_id, user } => {
447
                AuthenticationRecord::SoftLoggedOut {
448
                    meta: user.meta,
449
                    client_id: Some(client_id),
450
                }
451
            }
452
            soft @ AuthenticationRecord::SoftLoggedOut { .. } => soft,
453
            pending @ AuthenticationRecord::PendingOAuth { .. } => pending,
454
        };
455
        Self {
456
            homeserver: self.homeserver,
457
            authentication,
458
        }
459
    }
460
}
461
462
pub enum Restore {
463
    Resumed(Session),
464
    SoftLoggedOut(SoftLogout),
465
    /// an oauth login is waiting on its redirect. `Session::finish_oauth` takes the callback
466
    OAuthPending,
467
}
468
469
/// who to log in again as. the store keeps this device's e2ee keys, so a login
470
/// as any other device would orphan them
471
#[derive(Clone, Debug)]
472
#[non_exhaustive]
473
pub struct SoftLogout {
474
    pub homeserver: String,
475
    pub user_id: OwnedUserId,
476
    pub device_id: OwnedDeviceId,
477
    /// set when the login was OAuth, for `OAuthLogin::with_client_id`
478
    pub client_id: Option<String>,
479
}
480
481
impl SoftLogout {
482
    #[must_use]
483
    pub fn password_login(&self, password: impl Into<String>) -> PasswordLogin {
484
        PasswordLogin::new(self.homeserver.clone(), self.user_id.as_str(), password)
485
            .with_device_id(self.device_id.clone())
486
            .allow_insecure_loopback(true)
487
    }
488
489
    #[must_use]
490
    pub fn oauth_login(
491
        &self,
492
        redirect_uri: impl Into<String>,
493
        client_uri: impl Into<String>,
494
        application_type: OAuthApplicationType,
495
    ) -> OAuthLogin {
496
        let login = OAuthLogin::new(
497
            self.homeserver.clone(),
498
            redirect_uri,
499
            client_uri,
500
            application_type,
501
        )
502
        .with_device_id(self.device_id.clone())
503
        .allow_insecure_loopback(true);
504
        match &self.client_id {
505
            Some(client_id) => login.with_client_id(client_id.clone()),
506
            None => login,
507
        }
508
    }
509
}
510
511
#[derive(Debug, Error)]
512
pub enum AccountError {
513
    #[error("{context} failed")]
514
    Operation {
515
        context: &'static str,
516
        kind: ErrorKind,
517
        server: Option<ServerError>,
518
        #[source]
519
        source: Box<SourceError>,
520
    },
521
    #[error("the homeserver returned no authenticated session")]
522
    MissingSession,
523
    #[error("the SDK returned an unsupported authentication session")]
524
    UnsupportedAuthentication,
525
    #[error("the OAuth callback was already submitted")]
526
    OAuthCallbackAlreadySubmitted,
527
    /// nothing is waiting for this callback. it was finished, abandoned, expired, or begun
528
    /// somewhere else
529
    #[error("no OAuth login is waiting for this callback")]
530
    NoPendingOAuth,
531
    /// what was typed can't name a homeserver, so nothing was sent anywhere
532
    #[error("that isn't a usable homeserver, {0}")]
533
    InvalidHomeserver(&'static str),
534
    /// `Accounts` already has a live login for them. a second would be another device
535
    #[error("{0} is already logged in")]
536
    AlreadyLoggedIn(OwnedUserId),
537
    /// an IndexedDB delete is waiting on the store's other connections. it goes through
538
    /// once they close, and opening the store again waits behind it
539
    #[error("the store is still open elsewhere, it will be deleted once that closes")]
540
    StoreDeletePending,
541
    /// another engine, in this process or another, has the store. only one runs per store
542
    #[error("another engine is using this store")]
543
    StoreInUse,
544
    /// the login worked but its first record didn't save. the server already has the
545
    /// device, so retry the save rather than log in again
546
    #[error("saving the new login's record failed")]
547
    Unsaved {
548
        session: Box<UnsavedSession>,
549
        #[source]
550
        source: Box<AccountError>,
551
    },
552
    #[error(transparent)]
553
    Engine(#[from] EngineError),
554
}
555
556
impl AccountError {
557
    /// what the homeserver said, when it refused
558
    #[must_use]
559
    pub fn server(&self) -> Option<&ServerError> {
560
        match self {
561
            Self::Operation { server, .. } => server.as_ref(),
562
            Self::Unsaved { source, .. } => source.server(),
563
            _ => None,
564
        }
565
    }
566
}
567
568
/// a live login whose record never reached its `SessionStore`
569
pub struct UnsavedSession {
570
    session: Session,
571
    sessions: Arc<dyn SessionStore>,
572
}
573
574
impl UnsavedSession {
575
    pub async fn save(self) -> Result<Session, AccountError> {
576
        let saved = match session_record(&self.session.client) {
577
            Ok(record) => self.sessions.save(&record).await,
578
            Err(error) => Err(error),
579
        };
580
        match saved {
581
            Ok(()) => Ok(self.session),
582
            Err(source) => Err(AccountError::Unsaved {
583
                session: Box::new(self),
584
                source: Box::new(source),
585
            }),
586
        }
587
    }
588
589
    /// the record to keep somewhere else, if the store won't take it
590
    pub fn record(&self) -> Result<SessionRecord, AccountError> {
591
        session_record(&self.session.client)
592
    }
593
}
594
595
impl std::fmt::Debug for UnsavedSession {
596
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
597
        formatter
598
            .debug_struct("UnsavedSession")
599
            .finish_non_exhaustive()
600
    }
601
}
602
603
impl Session {
604
    pub async fn login_password(
605
        login: PasswordLogin,
606
        sessions: Arc<dyn SessionStore>,
607
    ) -> Result<Self, AccountError> {
608
        homeserver_input(&login.homeserver, login.allow_insecure_loopback)?;
609
        let store_lock = sessions.store().lock().await?;
610
        Self::login_password_locked(login, sessions, store_lock).await
611
    }
612
613
    pub(crate) async fn login_password_locked(
614
        login: PasswordLogin,
615
        sessions: Arc<dyn SessionStore>,
616
        store_lock: StoreLock,
617
    ) -> Result<Self, AccountError> {
618
        let homeserver = homeserver_input(&login.homeserver, login.allow_insecure_loopback)?;
619
        let client = matrix_client_builder(sessions.store())
620
            .server_name_or_homeserver_url(homeserver)
621
            .build()
622
            .await
623
            .map_err(|error| account_error("building the Matrix client", error))?;
624
        let tracking = Tracking::start(&client, sessions.clone())?;
625
        let mut request = client
626
            .matrix_auth()
627
            .login_username(login.username.trim(), &login.password)
628
            .request_refresh_token();
629
        if let Some(name) = login.device_display_name.as_deref() {
630
            request = request.initial_device_display_name(name);
631
        }
632
        if let Some(device_id) = login.device_id.as_deref() {
633
            request = request.device_id(device_id.as_str());
634
        }
635
        request
636
            .send()
637
            .await
638
            .map_err(|error| account_error("password login", error))?;
639
        Self::saved(client, sessions, tracking, store_lock).await
640
    }
641
642
    /// the pending login lives only in this process, so the one that begins it has to finish it
643
    pub async fn begin_oauth(
644
        login: OAuthLogin,
645
        sessions: Arc<dyn SessionStore>,
646
    ) -> Result<PendingOAuthLogin, AccountError> {
647
        homeserver_input(&login.homeserver, login.allow_insecure_loopback)?;
648
        let store_lock = sessions.store().lock().await?;
649
        Self::begin_oauth_locked(login, sessions, store_lock).await
650
    }
651
652
    pub(crate) async fn begin_oauth_locked(
653
        login: OAuthLogin,
654
        sessions: Arc<dyn SessionStore>,
655
        store_lock: StoreLock,
656
    ) -> Result<PendingOAuthLogin, AccountError> {
657
        let redirect_uri = Url::parse(login.redirect_uri.trim())
658
            .map_err(|error| account_error("parsing the OAuth redirect URI", error))?;
659
        let client_uri = Url::parse(login.client_uri.trim())
660
            .map_err(|error| account_error("parsing the OAuth client URI", error))?;
661
        let homeserver = homeserver_input(&login.homeserver, login.allow_insecure_loopback)?;
662
        let client = matrix_client_builder(sessions.store())
663
            .server_name_or_homeserver_url(homeserver)
664
            .build()
665
            .await
666
            .map_err(|error| account_error("building the Matrix client", error))?;
667
        let tracking = Tracking::start(&client, sessions.clone())?;
668
        let application_type = match login.application_type {
669
            OAuthApplicationType::Native => ApplicationType::Native,
670
            OAuthApplicationType::Web => ApplicationType::Web,
671
        };
672
        let mut metadata = ClientMetadata::new(
673
            application_type,
674
            vec![OAuthGrantType::AuthorizationCode {
675
                redirect_uris: vec![redirect_uri.clone()],
676
            }],
677
            Localized::new(client_uri, []),
678
        );
679
        metadata.client_name = login.client_name.map(|name| Localized::new(name, []));
680
        let metadata = Raw::new(&metadata)
681
            .map_err(|error| account_error("serializing OAuth client metadata", error))?;
682
        let mut registration = ClientRegistrationData::new(metadata);
683
        if let Some(client_id) = login.client_id {
684
            registration.static_registrations = Some(HashMap::from([(
685
                client.homeserver(),
686
                ClientId::new(client_id),
687
            )]));
688
        }
689
        let authorization = client
690
            .oauth()
691
            .login(redirect_uri, login.device_id, Some(registration), None)
692
            .build()
693
            .await
694
            .map_err(|error| account_error("starting OAuth login", error))?;
695
        let previous = sessions.load().await?.and_then(SessionRecord::resumable);
696
        let pending = SessionRecord {
697
            homeserver: client.homeserver().to_string(),
698
            authentication: AuthenticationRecord::PendingOAuth {
699
                client_id: client
700
                    .oauth()
701
                    .client_id()
702
                    .ok_or(AccountError::MissingSession)?
703
                    .clone(),
704
                state: authorization.state.clone(),
705
                authorization: Box::new(
706
                    client
707
                        .oauth()
708
                        .pending_authorization(&authorization.state)
709
                        .await
710
                        .ok_or(AccountError::MissingSession)?,
711
                ),
712
                started_ms: now_ms(),
713
                previous: previous.clone().map(Box::new),
714
            },
715
        };
716
        sessions.save(&pending).await?;
717
        Ok(PendingOAuthLogin {
718
            client,
719
            sessions,
720
            tracking: Some((tracking, store_lock)),
721
            authorization_url: authorization.url.to_string(),
722
            state: Some(authorization.state),
723
            previous,
724
        })
725
    }
726
727
    /// finishes a login `begin_oauth` started in another process, from the callback the
728
    /// redirect brought back. the pending login is in `sessions`, so nothing else is needed
729
    pub async fn finish_oauth(
730
        sessions: Arc<dyn SessionStore>,
731
        callback_url: &str,
732
    ) -> Result<Self, AccountError> {
733
        let store_lock = sessions.store().lock().await?;
734
        Self::finish_oauth_locked(sessions, store_lock, callback_url).await
735
    }
736
737
    pub(crate) async fn finish_oauth_locked(
738
        sessions: Arc<dyn SessionStore>,
739
        store_lock: StoreLock,
740
        callback_url: &str,
741
    ) -> Result<Self, AccountError> {
742
        let callback = Url::parse(callback_url)
743
            .map_err(|error| account_error("parsing the OAuth callback URL", error))?;
744
        let record = sessions.load().await?.ok_or(AccountError::NoPendingOAuth)?;
745
        if record.pending_oauth_state() != callback_state(&callback).as_deref() {
746
            return Err(AccountError::NoPendingOAuth);
747
        }
748
        let AuthenticationRecord::PendingOAuth {
749
            client_id,
750
            state,
751
            authorization,
752
            previous,
753
            ..
754
        } = record.authentication
755
        else {
756
            return Err(AccountError::NoPendingOAuth);
757
        };
758
        let client = matrix_client_builder(sessions.store())
759
            .homeserver_url(&record.homeserver)
760
            .build()
761
            .await
762
            .map_err(|error| account_error("reopening the Matrix store", error))?;
763
        let tracking = Tracking::start(&client, sessions.clone())?;
764
        let oauth = client.oauth();
765
        oauth.restore_registered_client(client_id);
766
        let finished = match oauth
767
            .restore_pending_authorization(state, *authorization)
768
            .await
769
        {
770
            Ok(()) => oauth.finish_login(callback.into()).await,
771
            Err(error) => Err(error.into()),
772
        };
773
        if let Err(error) = finished {
774
            match previous {
775
                Some(previous) => put_back(sessions.as_ref(), *previous).await,
776
                None => {
777
                    drop((tracking, client));
778
                    if let Err(error) = sessions.discard().await {
779
                        tracing::warn!(%error, "deleting a failed OAuth login's store failed");
780
                    }
781
                }
782
            }
783
            return Err(account_error("OAuth login", error));
784
        }
785
        Self::saved(client, sessions, tracking, store_lock).await
786
    }
787
788
    /// Restore the record `sessions` holds, or `None` when it holds none.
789
    /// The caller must also handle rejection and explicit logout.
790
    pub async fn restore(sessions: Arc<dyn SessionStore>) -> Result<Option<Restore>, AccountError> {
791
        let Some(record) = sessions.load().await? else {
792
            return Ok(None);
793
        };
794
        let authentication = match record.authentication {
795
            AuthenticationRecord::Matrix(session) => AuthSession::Matrix(session),
796
            AuthenticationRecord::OAuth { client_id, user } => {
797
                OAuthSession { client_id, user }.into()
798
            }
799
            AuthenticationRecord::PendingOAuth { .. } if record.oauth_expired() => {
800
                let previous = record.resumable();
801
                match previous {
802
                    Some(previous) => put_back(sessions.as_ref(), previous).await,
803
                    None => sessions.discard().await?,
804
                }
805
                return Box::pin(Self::restore(sessions)).await;
806
            }
807
            AuthenticationRecord::PendingOAuth { .. } => return Ok(Some(Restore::OAuthPending)),
808
            AuthenticationRecord::SoftLoggedOut { meta, client_id } => {
809
                return Ok(Some(Restore::SoftLoggedOut(SoftLogout {
810
                    homeserver: record.homeserver,
811
                    user_id: meta.user_id,
812
                    device_id: meta.device_id,
813
                    client_id: client_id.map(|client_id| client_id.as_str().to_owned()),
814
                })));
815
            }
816
        };
817
        let store_lock = sessions.store().lock().await?;
818
        let client = matrix_client_builder(sessions.store())
819
            .homeserver_url(&record.homeserver)
820
            .build()
821
            .await
822
            .map_err(|error| account_error("reopening the Matrix store", error))?;
823
        let tracking = Tracking::start(&client, sessions)?;
824
        client
825
            .restore_session(authentication)
826
            .await
827
            .map_err(|error| account_error("restoring the authenticated session", error))?;
828
        Ok(Some(Restore::Resumed(Self {
829
            client,
830
            tracking,
831
            store_lock,
832
        })))
833
    }
834
835
    /// leave the record to the host, which then saves `ClientHandle::session_record()`
836
    /// on every `SessionTokensChanged`
837
    #[must_use]
838
    pub fn without_persistence(mut self) -> Self {
839
        self.tracking.persistence = None;
840
        #[cfg(not(target_family = "wasm"))]
841
        self.tracking.inline.store(false, Ordering::Release);
842
        self
843
    }
844
845
    pub async fn build(
846
        self,
847
        config: EngineConfig,
848
    ) -> Result<(Engine, ClientHandle, EventStream), AccountError> {
849
        let account = crate::mentions::store::Account {
850
            homeserver: self.client.homeserver().to_string(),
851
            user_id: self
852
                .client
853
                .user_id()
854
                .ok_or(AccountError::MissingSession)?
855
                .to_owned(),
856
        };
857
        let opener = crate::mentions::store::Opener::new(
858
            self.tracking.store.store(),
859
            account,
860
            config.max_mentions_bytes,
861
        );
862
        let mentions = match opener.open().await {
863
            Ok(store) => Ok(store),
864
            Err(crate::mentions::store::OpenError::Unavailable(error)) => {
865
                Err(crate::mentions::service::Unopened {
866
                    error,
867
                    retry: Some(opener),
868
                })
869
            }
870
            Err(crate::mentions::store::OpenError::Newer(error)) => {
871
                Err(crate::mentions::service::Unopened { error, retry: None })
872
            }
873
        };
874
        Engine::with_persistence(
875
            self.client,
876
            config,
877
            self.tracking.session_changes,
878
            self.tracking.persistence,
879
            Some(self.store_lock),
880
            Some(mentions),
881
        )
882
        .await
883
        .map_err(AccountError::from)
884
    }
885
886
    async fn saved(
887
        client: Client,
888
        sessions: Arc<dyn SessionStore>,
889
        tracking: Tracking,
890
        store_lock: StoreLock,
891
    ) -> Result<Self, AccountError> {
892
        UnsavedSession {
893
            session: Self {
894
                client,
895
                tracking,
896
                store_lock,
897
            },
898
            sessions,
899
        }
900
        .save()
901
        .await
902
    }
903
}
904
905
impl Tracking {
906
    fn start(client: &Client, sessions: Arc<dyn SessionStore>) -> Result<Self, AccountError> {
907
        let session_changes = client.subscribe_to_session_changes();
908
        #[cfg_attr(target_family = "wasm", allow(unused_variables))]
909
        let (results, inline_results) = mpsc::unbounded_channel();
910
        #[cfg(not(target_family = "wasm"))]
911
        let inline = save_inline(client, sessions.clone(), results)?;
912
        Ok(Self {
913
            store: sessions.clone(),
914
            session_changes,
915
            persistence: Some(Persistence {
916
                save: Box::new(move |client| {
917
                    let sessions = sessions.clone();
918
                    Box::pin(async move {
919
                        let record = session_record(&client).map_err(save_failed)?;
920
                        sessions.save(&record).await.map_err(save_failed)
921
                    })
922
                }),
923
                inline: inline_results,
924
            }),
925
            #[cfg(not(target_family = "wasm"))]
926
            inline,
927
        })
928
    }
929
}
930
931
/// the sdk calls this inside its refresh, after it has the new tokens and before it uses
932
/// them, so a store that writes there and then can't lose a refresh token to a crash
933
#[cfg(not(target_family = "wasm"))]
934
fn save_inline(
935
    client: &Client,
936
    sessions: Arc<dyn SessionStore>,
937
    results: mpsc::UnboundedSender<Result<(), crate::Error>>,
938
) -> Result<Arc<AtomicBool>, AccountError> {
939
    let enabled = Arc::new(AtomicBool::new(true));
940
    let saving = enabled.clone();
941
    client
942
        .set_session_callbacks(
943
            // only asked for with the cross process refresh lock, which we never enable
944
            Box::new(|client| {
945
                client
946
                    .session_tokens()
947
                    .ok_or_else(|| AccountError::MissingSession.into())
948
            }),
949
            Box::new(move |client| {
950
                if !saving.load(Ordering::Acquire) {
951
                    return Ok(());
952
                }
953
                let record = session_record(&client)?;
954
                if let Some(result) = sessions.save_blocking(&record) {
955
                    let _ = results.send(result.map_err(save_failed));
956
                }
957
                Ok(())
958
            }),
959
        )
960
        .map_err(|error| account_error("registering the session callbacks", error))?;
961
    Ok(enabled)
962
}
963
964
fn save_failed(error: AccountError) -> crate::Error {
965
    let message = format!("saving the session record failed, {error}");
966
    crate::Error::with_source(ErrorKind::Store, message, error)
967
}
968
969
pub(crate) fn session_record(client: &Client) -> Result<SessionRecord, AccountError> {
970
    let authentication = match client.session().ok_or(AccountError::MissingSession)? {
971
        AuthSession::Matrix(session) => AuthenticationRecord::Matrix(session),
972
        AuthSession::OAuth(session) => {
973
            let OAuthSession { client_id, user } = *session;
974
            AuthenticationRecord::OAuth { client_id, user }
975
        }
976
        _ => return Err(AccountError::UnsupportedAuthentication),
977
    };
978
    Ok(SessionRecord {
979
        homeserver: client.homeserver().to_string(),
980
        authentication,
981
    })
982
}
983
984
fn encryption_settings() -> EncryptionSettings {
985
    EncryptionSettings {
986
        auto_enable_cross_signing: true,
987
        backup_download_strategy: BackupDownloadStrategy::OneShot,
988
        auto_enable_backups: true,
989
    }
990
}
991
992
/// `StoreLock` already keeps every other client off the store, and the sdk's lease would cost
993
/// a store write per locked section and a task renewing it every 50ms
994
fn matrix_client_builder(store: &StoreConfig) -> ClientBuilder {
995
    let builder = Client::builder()
996
        .with_encryption_settings(encryption_settings())
997
        .with_threading_support(ThreadingSupport::Enabled {
998
            with_subscriptions: false,
999
        })
1000
        .handle_refresh_tokens()
1001
        .cross_process_store_config(CrossProcessLockConfig::SingleProcess);
1002
    match &store.location {
1003
        #[cfg(feature = "sqlite")]
1004
        StoreLocation::Sqlite(path) => builder.sqlite_store(path, Some(&store.passphrase)),
1005
        #[cfg(feature = "indexeddb")]
1006
        StoreLocation::IndexedDb(name) => builder.indexeddb_store(name, Some(&store.passphrase)),
1007
    }
1008
}
1009
1010
/// a bare server name goes through untouched, since that's what makes the sdk try `.well-known`
1011
pub(crate) fn homeserver_input(
1012
    input: &str,
1013
    allow_insecure_loopback: bool,
1014
) -> Result<&str, AccountError> {
1015
    let input = input.trim();
1016
    let invalid = |reason| Err(AccountError::InvalidHomeserver(reason));
1017
    if input.is_empty() {
1018
        return invalid("it's empty");
1019
    }
1020
    if input.contains(char::is_whitespace) {
1021
        return invalid("it has spaces in it");
1022
    }
1023
    if !input.contains("://") {
1024
        return match <&ruma::ServerName>::try_from(input) {
1025
            Ok(_) => Ok(input),
1026
            Err(_) => invalid("it's neither a server name nor a url"),
1027
        };
1028
    }
1029
    let Ok(url) = Url::parse(input) else {
1030
        return invalid("it isn't a valid url");
1031
    };
1032
    if !url.username().is_empty() || url.password().is_some() {
1033
        return invalid("it has a username in it");
1034
    }
1035
    let loopback = match url.host() {
1036
        None => return invalid("it has no host"),
1037
        Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
1038
        Some(url::Host::Ipv4(address)) => address.is_loopback(),
1039
        Some(url::Host::Ipv6(address)) => address.is_loopback(),
1040
    };
1041
    match url.scheme() {
1042
        "https" => Ok(input),
1043
        "http" if allow_insecure_loopback && loopback => Ok(input),
1044
        "http" if allow_insecure_loopback => invalid("plain http only reaches loopback hosts"),
1045
        "http" => invalid("it isn't https"),
1046
        _ => invalid("only http and https are spoken"),
1047
    }
1048
}
1049
1050
pub(crate) fn account_error(
1051
    context: &'static str,
1052
    source: impl std::error::Error + SendOutsideWasm + SyncOutsideWasm + 'static,
1053
) -> AccountError {
1054
    AccountError::Operation {
1055
        context,
1056
        kind: crate::error::classify(&source),
1057
        server: ServerError::find(&source),
1058
        source: Box::new(source),
1059
    }
1060
}