atagen

macltok

public
Star0
Watch0
9c05b1dd327a57081652545c709cc8d7e961de15
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git
src/account.rsRust767 lines25.6 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, UserSession,
15
            registration::{ApplicationType, ClientMetadata, Localized, OAuthGrantType},
16
        },
17
    },
18
    cross_process_lock::CrossProcessLockConfig,
19
    encryption::{BackupDownloadStrategy, EncryptionSettings},
20
    ruma::{OwnedDeviceId, OwnedUserId, serde::Raw},
21
};
22
use serde::{Deserialize, Serialize};
23
use thiserror::Error;
24
use tokio::sync::{broadcast, mpsc};
25
use url::Url;
26
27
use crate::{
28
    ClientHandle, Engine, EngineConfig, EngineError, ErrorKind, EventStream, ServerError,
29
    SessionStore,
30
    engine::{Persistence, StoreLock},
31
    error::SourceError,
32
};
33
34
/// a logged in client and the `SessionStore` its record lives in. the engine it builds
35
/// saves every token rotation there, unless told `without_persistence`
36
pub struct Session {
37
    client: Client,
38
    tracking: Tracking,
39
    store_lock: StoreLock,
40
}
41
42
/// taken as soon as the client exists, since the sdk can refresh before there's an engine
43
struct Tracking {
44
    session_changes: broadcast::Receiver<SessionChange>,
45
    persistence: Option<Persistence>,
46
    #[cfg(not(target_family = "wasm"))]
47
    inline: Arc<AtomicBool>,
48
}
49
50
#[non_exhaustive]
51
pub struct PasswordLogin {
52
    pub homeserver: String,
53
    pub username: String,
54
    pub password: String,
55
    pub device_display_name: Option<String>,
56
    /// set after a soft logout so the store's keys still belong to us
57
    pub device_id: Option<OwnedDeviceId>,
58
    /// let plain http through, for loopback hosts only
59
    pub allow_insecure_loopback: bool,
60
}
61
62
impl PasswordLogin {
63
    #[must_use]
64
    pub fn new(
65
        homeserver: impl Into<String>,
66
        username: impl Into<String>,
67
        password: impl Into<String>,
68
    ) -> Self {
69
        Self {
70
            homeserver: homeserver.into(),
71
            username: username.into(),
72
            password: password.into(),
73
            device_display_name: None,
74
            device_id: None,
75
            allow_insecure_loopback: false,
76
        }
77
    }
78
79
    #[must_use]
80
    pub fn with_device_display_name(mut self, name: impl Into<String>) -> Self {
81
        self.device_display_name = Some(name.into());
82
        self
83
    }
84
85
    #[must_use]
86
    pub fn with_device_id(mut self, device_id: OwnedDeviceId) -> Self {
87
        self.device_id = Some(device_id);
88
        self
89
    }
90
91
    #[must_use]
92
    pub fn allow_insecure_loopback(mut self, allow: bool) -> Self {
93
        self.allow_insecure_loopback = allow;
94
        self
95
    }
96
}
97
98
#[non_exhaustive]
99
pub struct OAuthLogin {
100
    pub homeserver: String,
101
    pub redirect_uri: String,
102
    pub client_uri: String,
103
    pub client_name: Option<String>,
104
    pub client_id: Option<String>,
105
    pub device_id: Option<OwnedDeviceId>,
106
    pub application_type: OAuthApplicationType,
107
    /// let plain http through, for loopback hosts only
108
    pub allow_insecure_loopback: bool,
109
}
110
111
impl OAuthLogin {
112
    #[must_use]
113
    pub fn new(
114
        homeserver: impl Into<String>,
115
        redirect_uri: impl Into<String>,
116
        client_uri: impl Into<String>,
117
        application_type: OAuthApplicationType,
118
    ) -> Self {
119
        Self {
120
            homeserver: homeserver.into(),
121
            redirect_uri: redirect_uri.into(),
122
            client_uri: client_uri.into(),
123
            client_name: None,
124
            client_id: None,
125
            device_id: None,
126
            application_type,
127
            allow_insecure_loopback: false,
128
        }
129
    }
130
131
    #[must_use]
132
    pub fn with_client_name(mut self, name: impl Into<String>) -> Self {
133
        self.client_name = Some(name.into());
134
        self
135
    }
136
137
    /// a statically registered client id, skipping dynamic registration
138
    #[must_use]
139
    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
140
        self.client_id = Some(client_id.into());
141
        self
142
    }
143
144
    #[must_use]
145
    pub fn with_device_id(mut self, device_id: OwnedDeviceId) -> Self {
146
        self.device_id = Some(device_id);
147
        self
148
    }
149
150
    #[must_use]
151
    pub fn allow_insecure_loopback(mut self, allow: bool) -> Self {
152
        self.allow_insecure_loopback = allow;
153
        self
154
    }
155
}
156
157
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
158
#[non_exhaustive]
159
pub enum OAuthApplicationType {
160
    Native,
161
    Web,
162
}
163
164
pub struct PendingOAuthLogin {
165
    client: Client,
166
    sessions: Arc<dyn SessionStore>,
167
    tracking: Option<(Tracking, StoreLock)>,
168
    authorization_url: String,
169
    state: Option<CsrfToken>,
170
}
171
172
impl PendingOAuthLogin {
173
    #[must_use]
174
    pub fn authorization_url(&self) -> &str {
175
        &self.authorization_url
176
    }
177
178
    #[must_use]
179
    pub fn registered_client_id(&self) -> String {
180
        self.client
181
            .oauth()
182
            .client_id()
183
            .expect("OAuth client was registered before authorization")
184
            .as_str()
185
            .to_owned()
186
    }
187
188
    #[must_use]
189
    pub const fn is_pending(&self) -> bool {
190
        self.state.is_some()
191
    }
192
193
    pub async fn finish(&mut self, callback_url: &str) -> Result<Session, AccountError> {
194
        let callback_url = Url::parse(callback_url)
195
            .map_err(|error| account_error("parsing the OAuth callback URL", error))?;
196
        let state = self
197
            .state
198
            .take()
199
            .ok_or(AccountError::OAuthCallbackAlreadySubmitted)?;
200
        let oauth = self.client.oauth();
201
        if let Err(error) = oauth.finish_login(callback_url.into()).await {
202
            oauth.abort_login(&state).await;
203
            return Err(account_error("OAuth login", error));
204
        }
205
        let (tracking, store_lock) = self
206
            .tracking
207
            .take()
208
            .ok_or(AccountError::OAuthCallbackAlreadySubmitted)?;
209
        Session::saved(
210
            self.client.clone(),
211
            self.sessions.clone(),
212
            tracking,
213
            store_lock,
214
        )
215
        .await
216
    }
217
218
    pub async fn abort(mut self) {
219
        if let Some(state) = self.state.take() {
220
            self.client.oauth().abort_login(&state).await;
221
        }
222
    }
223
}
224
225
pub struct StoreConfig {
226
    location: StoreLocation,
227
    passphrase: String,
228
}
229
230
enum StoreLocation {
231
    #[cfg(feature = "sqlite")]
232
    Sqlite(PathBuf),
233
    #[cfg(feature = "indexeddb")]
234
    IndexedDb(String),
235
}
236
237
impl StoreConfig {
238
    #[cfg(feature = "sqlite")]
239
    #[must_use]
240
    pub fn sqlite(path: impl Into<PathBuf>, passphrase: impl Into<String>) -> Self {
241
        Self {
242
            location: StoreLocation::Sqlite(path.into()),
243
            passphrase: passphrase.into(),
244
        }
245
    }
246
247
    #[cfg(feature = "indexeddb")]
248
    #[must_use]
249
    pub fn indexeddb(name: impl Into<String>, passphrase: impl Into<String>) -> Self {
250
        Self {
251
            location: StoreLocation::IndexedDb(name.into()),
252
            passphrase: passphrase.into(),
253
        }
254
    }
255
256
    /// delete the store's databases, once nothing has them open
257
    pub async fn delete(&self) -> Result<(), AccountError> {
258
        match &self.location {
259
            #[cfg(feature = "sqlite")]
260
            StoreLocation::Sqlite(path) => crate::session_store::delete_sqlite_store(path)
261
                .map_err(|error| account_error("deleting the Matrix store", error)),
262
            #[cfg(feature = "indexeddb")]
263
            StoreLocation::IndexedDb(name) => crate::session_store::delete_indexeddb_store(name)
264
                .await
265
                .map_err(|error| error.into_account_error("deleting the Matrix store")),
266
        }
267
    }
268
269
    /// taken before the client opens the store, and held until the engine and every
270
    /// `ClientHandle` are gone
271
    pub(crate) async fn lock(&self) -> Result<StoreLock, AccountError> {
272
        match &self.location {
273
            #[cfg(feature = "sqlite")]
274
            StoreLocation::Sqlite(path) => StoreLock::file(path),
275
            #[cfg(feature = "indexeddb")]
276
            StoreLocation::IndexedDb(name) => StoreLock::web(name).await,
277
        }
278
    }
279
280
    pub(crate) fn passphrase(&self) -> &str {
281
        &self.passphrase
282
    }
283
284
    #[cfg(feature = "indexeddb")]
285
    pub(crate) fn indexeddb_name(&self) -> &str {
286
        let StoreLocation::IndexedDb(name) = &self.location;
287
        name
288
    }
289
}
290
291
/// Serializable authentication secrets. A `SessionStore` keeps it, and the engine
292
/// replaces it there on every token rotation.
293
#[derive(Clone, Deserialize, Serialize)]
294
pub struct SessionRecord {
295
    homeserver: String,
296
    authentication: AuthenticationRecord,
297
}
298
299
#[derive(Clone, Deserialize, Serialize)]
300
#[serde(tag = "type", content = "session", rename_all = "snake_case")]
301
enum AuthenticationRecord {
302
    Matrix(MatrixSession),
303
    OAuth {
304
        client_id: ClientId,
305
        user: UserSession,
306
    },
307
    SoftLoggedOut {
308
        meta: SessionMeta,
309
        client_id: Option<ClientId>,
310
    },
311
}
312
313
impl SessionRecord {
314
    #[must_use]
315
    pub fn homeserver(&self) -> &str {
316
        &self.homeserver
317
    }
318
319
    pub(crate) fn soft_logged_out(self) -> Self {
320
        let authentication = match self.authentication {
321
            AuthenticationRecord::Matrix(session) => AuthenticationRecord::SoftLoggedOut {
322
                meta: session.meta,
323
                client_id: None,
324
            },
325
            AuthenticationRecord::OAuth { client_id, user } => {
326
                AuthenticationRecord::SoftLoggedOut {
327
                    meta: user.meta,
328
                    client_id: Some(client_id),
329
                }
330
            }
331
            soft @ AuthenticationRecord::SoftLoggedOut { .. } => soft,
332
        };
333
        Self {
334
            homeserver: self.homeserver,
335
            authentication,
336
        }
337
    }
338
}
339
340
pub enum Restore {
341
    Resumed(Session),
342
    SoftLoggedOut(SoftLogout),
343
}
344
345
/// who to log in again as. the store keeps this device's e2ee keys, so a login
346
/// as any other device would orphan them
347
#[derive(Clone, Debug)]
348
#[non_exhaustive]
349
pub struct SoftLogout {
350
    pub homeserver: String,
351
    pub user_id: OwnedUserId,
352
    pub device_id: OwnedDeviceId,
353
    /// set when the login was OAuth, for `OAuthLogin::with_client_id`
354
    pub client_id: Option<String>,
355
}
356
357
impl SoftLogout {
358
    #[must_use]
359
    pub fn password_login(&self, password: impl Into<String>) -> PasswordLogin {
360
        PasswordLogin::new(self.homeserver.clone(), self.user_id.as_str(), password)
361
            .with_device_id(self.device_id.clone())
362
            .allow_insecure_loopback(true)
363
    }
364
}
365
366
#[derive(Debug, Error)]
367
pub enum AccountError {
368
    #[error("{context} failed")]
369
    Operation {
370
        context: &'static str,
371
        kind: ErrorKind,
372
        server: Option<ServerError>,
373
        #[source]
374
        source: Box<SourceError>,
375
    },
376
    #[error("the homeserver returned no authenticated session")]
377
    MissingSession,
378
    #[error("the SDK returned an unsupported authentication session")]
379
    UnsupportedAuthentication,
380
    #[error("the OAuth callback was already submitted")]
381
    OAuthCallbackAlreadySubmitted,
382
    /// what was typed can't name a homeserver, so nothing was sent anywhere
383
    #[error("that isn't a usable homeserver, {0}")]
384
    InvalidHomeserver(&'static str),
385
    /// an IndexedDB delete is waiting on the store's other connections. it goes through
386
    /// once they close, and opening the store again waits behind it
387
    #[error("the store is still open elsewhere, it will be deleted once that closes")]
388
    StoreDeletePending,
389
    /// another engine, in this process or another, has the store. only one runs per store
390
    #[error("another engine is using this store")]
391
    StoreInUse,
392
    /// the login worked but its first record didn't save. the server already has the
393
    /// device, so retry the save rather than log in again
394
    #[error("saving the new login's record failed")]
395
    Unsaved {
396
        session: Box<UnsavedSession>,
397
        #[source]
398
        source: Box<AccountError>,
399
    },
400
    #[error(transparent)]
401
    Engine(#[from] EngineError),
402
}
403
404
impl AccountError {
405
    /// what the homeserver said, when it refused
406
    #[must_use]
407
    pub fn server(&self) -> Option<&ServerError> {
408
        match self {
409
            Self::Operation { server, .. } => server.as_ref(),
410
            Self::Unsaved { source, .. } => source.server(),
411
            _ => None,
412
        }
413
    }
414
}
415
416
/// a live login whose record never reached its `SessionStore`
417
pub struct UnsavedSession {
418
    session: Session,
419
    sessions: Arc<dyn SessionStore>,
420
}
421
422
impl UnsavedSession {
423
    pub async fn save(self) -> Result<Session, AccountError> {
424
        let saved = match session_record(&self.session.client) {
425
            Ok(record) => self.sessions.save(&record).await,
426
            Err(error) => Err(error),
427
        };
428
        match saved {
429
            Ok(()) => Ok(self.session),
430
            Err(source) => Err(AccountError::Unsaved {
431
                session: Box::new(self),
432
                source: Box::new(source),
433
            }),
434
        }
435
    }
436
437
    /// the record to keep somewhere else, if the store won't take it
438
    pub fn record(&self) -> Result<SessionRecord, AccountError> {
439
        session_record(&self.session.client)
440
    }
441
}
442
443
impl std::fmt::Debug for UnsavedSession {
444
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
445
        formatter
446
            .debug_struct("UnsavedSession")
447
            .finish_non_exhaustive()
448
    }
449
}
450
451
impl Session {
452
    pub async fn login_password(
453
        login: PasswordLogin,
454
        sessions: Arc<dyn SessionStore>,
455
    ) -> Result<Self, AccountError> {
456
        let homeserver = homeserver_input(&login.homeserver, login.allow_insecure_loopback)?;
457
        let store_lock = sessions.store().lock().await?;
458
        let client = matrix_client_builder(sessions.store())
459
            .server_name_or_homeserver_url(homeserver)
460
            .build()
461
            .await
462
            .map_err(|error| account_error("building the Matrix client", error))?;
463
        let tracking = Tracking::start(&client, sessions.clone())?;
464
        let mut request = client
465
            .matrix_auth()
466
            .login_username(login.username.trim(), &login.password)
467
            .request_refresh_token();
468
        if let Some(name) = login.device_display_name.as_deref() {
469
            request = request.initial_device_display_name(name);
470
        }
471
        if let Some(device_id) = login.device_id.as_deref() {
472
            request = request.device_id(device_id.as_str());
473
        }
474
        request
475
            .send()
476
            .await
477
            .map_err(|error| account_error("password login", error))?;
478
        Self::saved(client, sessions, tracking, store_lock).await
479
    }
480
481
    /// the pending login lives only in this process, so the one that begins it has to finish it
482
    pub async fn begin_oauth(
483
        login: OAuthLogin,
484
        sessions: Arc<dyn SessionStore>,
485
    ) -> Result<PendingOAuthLogin, AccountError> {
486
        let redirect_uri = Url::parse(login.redirect_uri.trim())
487
            .map_err(|error| account_error("parsing the OAuth redirect URI", error))?;
488
        let client_uri = Url::parse(login.client_uri.trim())
489
            .map_err(|error| account_error("parsing the OAuth client URI", error))?;
490
        let homeserver = homeserver_input(&login.homeserver, login.allow_insecure_loopback)?;
491
        let store_lock = sessions.store().lock().await?;
492
        let client = matrix_client_builder(sessions.store())
493
            .server_name_or_homeserver_url(homeserver)
494
            .build()
495
            .await
496
            .map_err(|error| account_error("building the Matrix client", error))?;
497
        let tracking = Tracking::start(&client, sessions.clone())?;
498
        let application_type = match login.application_type {
499
            OAuthApplicationType::Native => ApplicationType::Native,
500
            OAuthApplicationType::Web => ApplicationType::Web,
501
        };
502
        let mut metadata = ClientMetadata::new(
503
            application_type,
504
            vec![OAuthGrantType::AuthorizationCode {
505
                redirect_uris: vec![redirect_uri.clone()],
506
            }],
507
            Localized::new(client_uri, []),
508
        );
509
        metadata.client_name = login.client_name.map(|name| Localized::new(name, []));
510
        let metadata = Raw::new(&metadata)
511
            .map_err(|error| account_error("serializing OAuth client metadata", error))?;
512
        let mut registration = ClientRegistrationData::new(metadata);
513
        if let Some(client_id) = login.client_id {
514
            registration.static_registrations = Some(HashMap::from([(
515
                client.homeserver(),
516
                ClientId::new(client_id),
517
            )]));
518
        }
519
        let authorization = client
520
            .oauth()
521
            .login(redirect_uri, login.device_id, Some(registration), None)
522
            .build()
523
            .await
524
            .map_err(|error| account_error("starting OAuth login", error))?;
525
        Ok(PendingOAuthLogin {
526
            client,
527
            sessions,
528
            tracking: Some((tracking, store_lock)),
529
            authorization_url: authorization.url.to_string(),
530
            state: Some(authorization.state),
531
        })
532
    }
533
534
    /// Restore the record `sessions` holds, or `None` when it holds none.
535
    /// The caller must also handle rejection and explicit logout.
536
    pub async fn restore(sessions: Arc<dyn SessionStore>) -> Result<Option<Restore>, AccountError> {
537
        let Some(record) = sessions.load().await? else {
538
            return Ok(None);
539
        };
540
        let authentication = match record.authentication {
541
            AuthenticationRecord::Matrix(session) => AuthSession::Matrix(session),
542
            AuthenticationRecord::OAuth { client_id, user } => {
543
                OAuthSession { client_id, user }.into()
544
            }
545
            AuthenticationRecord::SoftLoggedOut { meta, client_id } => {
546
                return Ok(Some(Restore::SoftLoggedOut(SoftLogout {
547
                    homeserver: record.homeserver,
548
                    user_id: meta.user_id,
549
                    device_id: meta.device_id,
550
                    client_id: client_id.map(|client_id| client_id.as_str().to_owned()),
551
                })));
552
            }
553
        };
554
        let store_lock = sessions.store().lock().await?;
555
        let client = matrix_client_builder(sessions.store())
556
            .homeserver_url(&record.homeserver)
557
            .build()
558
            .await
559
            .map_err(|error| account_error("reopening the Matrix store", error))?;
560
        let tracking = Tracking::start(&client, sessions)?;
561
        client
562
            .restore_session(authentication)
563
            .await
564
            .map_err(|error| account_error("restoring the authenticated session", error))?;
565
        Ok(Some(Restore::Resumed(Self {
566
            client,
567
            tracking,
568
            store_lock,
569
        })))
570
    }
571
572
    /// leave the record to the host, which then saves `ClientHandle::session_record()`
573
    /// on every `SessionTokensChanged`
574
    #[must_use]
575
    pub fn without_persistence(mut self) -> Self {
576
        self.tracking.persistence = None;
577
        #[cfg(not(target_family = "wasm"))]
578
        self.tracking.inline.store(false, Ordering::Release);
579
        self
580
    }
581
582
    pub async fn build(
583
        self,
584
        config: EngineConfig,
585
    ) -> Result<(Engine, ClientHandle, EventStream), AccountError> {
586
        Engine::with_persistence(
587
            self.client,
588
            config,
589
            self.tracking.session_changes,
590
            self.tracking.persistence,
591
            Some(self.store_lock),
592
        )
593
        .await
594
        .map_err(AccountError::from)
595
    }
596
597
    async fn saved(
598
        client: Client,
599
        sessions: Arc<dyn SessionStore>,
600
        tracking: Tracking,
601
        store_lock: StoreLock,
602
    ) -> Result<Self, AccountError> {
603
        UnsavedSession {
604
            session: Self {
605
                client,
606
                tracking,
607
                store_lock,
608
            },
609
            sessions,
610
        }
611
        .save()
612
        .await
613
    }
614
}
615
616
impl Tracking {
617
    fn start(client: &Client, sessions: Arc<dyn SessionStore>) -> Result<Self, AccountError> {
618
        let session_changes = client.subscribe_to_session_changes();
619
        #[cfg_attr(target_family = "wasm", allow(unused_variables))]
620
        let (results, inline_results) = mpsc::unbounded_channel();
621
        #[cfg(not(target_family = "wasm"))]
622
        let inline = save_inline(client, sessions.clone(), results)?;
623
        Ok(Self {
624
            session_changes,
625
            persistence: Some(Persistence {
626
                save: Box::new(move |client| {
627
                    let sessions = sessions.clone();
628
                    Box::pin(async move {
629
                        let record = session_record(&client).map_err(save_failed)?;
630
                        sessions.save(&record).await.map_err(save_failed)
631
                    })
632
                }),
633
                inline: inline_results,
634
            }),
635
            #[cfg(not(target_family = "wasm"))]
636
            inline,
637
        })
638
    }
639
}
640
641
/// the sdk calls this inside its refresh, after it has the new tokens and before it uses
642
/// them, so a store that writes there and then can't lose a refresh token to a crash
643
#[cfg(not(target_family = "wasm"))]
644
fn save_inline(
645
    client: &Client,
646
    sessions: Arc<dyn SessionStore>,
647
    results: mpsc::UnboundedSender<Result<(), crate::Error>>,
648
) -> Result<Arc<AtomicBool>, AccountError> {
649
    let enabled = Arc::new(AtomicBool::new(true));
650
    let saving = enabled.clone();
651
    client
652
        .set_session_callbacks(
653
            // only asked for with the cross process refresh lock, which we never enable
654
            Box::new(|client| {
655
                client
656
                    .session_tokens()
657
                    .ok_or_else(|| AccountError::MissingSession.into())
658
            }),
659
            Box::new(move |client| {
660
                if !saving.load(Ordering::Acquire) {
661
                    return Ok(());
662
                }
663
                let record = session_record(&client)?;
664
                if let Some(result) = sessions.save_blocking(&record) {
665
                    let _ = results.send(result.map_err(save_failed));
666
                }
667
                Ok(())
668
            }),
669
        )
670
        .map_err(|error| account_error("registering the session callbacks", error))?;
671
    Ok(enabled)
672
}
673
674
fn save_failed(error: AccountError) -> crate::Error {
675
    let message = format!("saving the session record failed, {error}");
676
    crate::Error::with_source(ErrorKind::Store, message, error)
677
}
678
679
pub(crate) fn session_record(client: &Client) -> Result<SessionRecord, AccountError> {
680
    let authentication = match client.session().ok_or(AccountError::MissingSession)? {
681
        AuthSession::Matrix(session) => AuthenticationRecord::Matrix(session),
682
        AuthSession::OAuth(session) => {
683
            let OAuthSession { client_id, user } = *session;
684
            AuthenticationRecord::OAuth { client_id, user }
685
        }
686
        _ => return Err(AccountError::UnsupportedAuthentication),
687
    };
688
    Ok(SessionRecord {
689
        homeserver: client.homeserver().to_string(),
690
        authentication,
691
    })
692
}
693
694
fn encryption_settings() -> EncryptionSettings {
695
    EncryptionSettings {
696
        auto_enable_cross_signing: true,
697
        backup_download_strategy: BackupDownloadStrategy::OneShot,
698
        auto_enable_backups: true,
699
    }
700
}
701
702
/// `StoreLock` already keeps every other client off the store, and the sdk's lease would cost
703
/// a store write per locked section and a task renewing it every 50ms
704
fn matrix_client_builder(store: &StoreConfig) -> ClientBuilder {
705
    let builder = Client::builder()
706
        .with_encryption_settings(encryption_settings())
707
        .with_threading_support(ThreadingSupport::Enabled {
708
            with_subscriptions: false,
709
        })
710
        .handle_refresh_tokens()
711
        .cross_process_store_config(CrossProcessLockConfig::SingleProcess);
712
    match &store.location {
713
        #[cfg(feature = "sqlite")]
714
        StoreLocation::Sqlite(path) => builder.sqlite_store(path, Some(&store.passphrase)),
715
        #[cfg(feature = "indexeddb")]
716
        StoreLocation::IndexedDb(name) => builder.indexeddb_store(name, Some(&store.passphrase)),
717
    }
718
}
719
720
/// a bare server name goes through untouched, since that's what makes the sdk try `.well-known`
721
fn homeserver_input(input: &str, allow_insecure_loopback: bool) -> Result<&str, AccountError> {
722
    let input = input.trim();
723
    let invalid = |reason| Err(AccountError::InvalidHomeserver(reason));
724
    if input.is_empty() {
725
        return invalid("it's empty");
726
    }
727
    if input.contains(char::is_whitespace) {
728
        return invalid("it has spaces in it");
729
    }
730
    if !input.contains("://") {
731
        return match <&ruma::ServerName>::try_from(input) {
732
            Ok(_) => Ok(input),
733
            Err(_) => invalid("it's neither a server name nor a url"),
734
        };
735
    }
736
    let Ok(url) = Url::parse(input) else {
737
        return invalid("it isn't a valid url");
738
    };
739
    if !url.username().is_empty() || url.password().is_some() {
740
        return invalid("it has a username in it");
741
    }
742
    let loopback = match url.host() {
743
        None => return invalid("it has no host"),
744
        Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
745
        Some(url::Host::Ipv4(address)) => address.is_loopback(),
746
        Some(url::Host::Ipv6(address)) => address.is_loopback(),
747
    };
748
    match url.scheme() {
749
        "https" => Ok(input),
750
        "http" if allow_insecure_loopback && loopback => Ok(input),
751
        "http" if allow_insecure_loopback => invalid("plain http only reaches loopback hosts"),
752
        "http" => invalid("it isn't https"),
753
        _ => invalid("only http and https are spoken"),
754
    }
755
}
756
757
pub(crate) fn account_error(
758
    context: &'static str,
759
    source: impl std::error::Error + SendOutsideWasm + SyncOutsideWasm + 'static,
760
) -> AccountError {
761
    AccountError::Operation {
762
        context,
763
        kind: crate::error::classify(&source),
764
        server: ServerError::find(&source),
765
        source: Box::new(source),
766
    }
767
}