Commit 85830f9609

85830f9609013b40df39e56e5f183d7b1c7f554a

parent: a44f5ff9a5

Unregistered key

profww <professor@waltwood.dev> · 2026-10-06 00:25 UTC
committer: <noreply@github.com>

Add support for for native OAuth login (#767) (#768)

Layout: unified · split

Cargo.toml +1 −1
@@ -105,7 +105,7 @@ version = "0.19.0"
105 105
106[dependencies.tokio] 106[dependencies.tokio]
107version = "1.24.1" 107version = "1.24.1"
108features = ["macros", "net", "rt-multi-thread", "sync", "time"] 108features = ["io-std", "macros", "net", "rt-multi-thread", "sync", "time"]
109 109
110[dependencies.ratatui-image] 110[dependencies.ratatui-image]
111version = "11.0.8" 111version = "11.0.8"
src/base.rs +6
@@ -1071,6 +1071,12 @@ impl From<matrix_sdk::event_cache::EventCacheError> for IambError {
1071 } 1071 }
1072} 1072}
1073 1073
1074impl From<matrix_sdk::authentication::oauth::OAuthError> for IambError {
1075 fn from(value: matrix_sdk::authentication::oauth::OAuthError) -> Self {
1076 Self::from(matrix_sdk::Error::from(value))
1077 }
1078}
1079
1074impl ApplicationError for IambError {} 1080impl ApplicationError for IambError {}
1075 1081
1076/// Indicates where an [EventId] lives in the [ChatStore]. 1082/// Indicates where an [EventId] lives in the [ChatStore].
src/config/mod.rs +41 −4
@@ -1,5 +1,4 @@
1//! # Logic for loading and validating application configuration 1//! # Logic for loading and validating application configuration
2
3use std::collections::HashSet; 2use std::collections::HashSet;
4use std::env; 3use std::env;
5use std::fs::File; 4use std::fs::File;
@@ -10,11 +9,12 @@ use std::sync::Arc;
10use clap::Parser; 9use clap::Parser;
11use indexmap::IndexMap; 10use indexmap::IndexMap;
12use lazy_static::lazy_static; 11use lazy_static::lazy_static;
13use matrix_sdk::EncryptionState;
14use matrix_sdk::authentication::matrix::MatrixSession; 12use matrix_sdk::authentication::matrix::MatrixSession;
13use matrix_sdk::authentication::oauth::{ClientId, OAuthSession, UserSession};
15use matrix_sdk::media::MediaRetentionPolicy; 14use matrix_sdk::media::MediaRetentionPolicy;
16use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue}; 15use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
17use matrix_sdk::ruma::{DeviceId, OwnedDeviceId, owned_server_name}; 16use matrix_sdk::ruma::{DeviceId, OwnedDeviceId, owned_server_name};
17use matrix_sdk::{AuthSession, EncryptionState, SessionMeta, SessionTokens};
18use modalkit::crossterm; 18use modalkit::crossterm;
19use modalkit::env::vim::VimMode; 19use modalkit::env::vim::VimMode;
20use modalkit::keybindings::InputKey; 20use modalkit::keybindings::InputKey;
@@ -276,6 +276,30 @@ pub struct Session {
276 refresh_token: Option<String>, 276 refresh_token: Option<String>,
277 user_id: OwnedUserId, 277 user_id: OwnedUserId,
278 device_id: OwnedDeviceId, 278 device_id: OwnedDeviceId,
279 #[serde(skip_serializing_if = "Option::is_none")]
280 client_id: Option<ClientId>,
281}
282
283impl From<Session> for AuthSession {
284 fn from(session: Session) -> Self {
285 if let Some(client_id) = session.client_id {
286 AuthSession::OAuth(Box::new(OAuthSession {
287 client_id,
288 user: UserSession {
289 meta: SessionMeta {
290 user_id: session.user_id,
291 device_id: session.device_id,
292 },
293 tokens: SessionTokens {
294 access_token: session.access_token,
295 refresh_token: session.refresh_token,
296 },
297 },
298 }))
299 } else {
300 AuthSession::Matrix(session.into())
301 }
302 }
279} 303}
280 304
281/// A device ID saved at logout so that the next login can reuse it. 305/// A device ID saved at logout so that the next login can reuse it.
@@ -312,6 +336,19 @@ impl From<MatrixSession> for Session {
312 refresh_token: session.tokens.refresh_token, 336 refresh_token: session.tokens.refresh_token,
313 user_id: session.meta.user_id, 337 user_id: session.meta.user_id,
314 device_id: session.meta.device_id, 338 device_id: session.meta.device_id,
339 client_id: None,
340 }
341 }
342}
343
344impl From<OAuthSession> for Session {
345 fn from(session: OAuthSession) -> Self {
346 Session {
347 access_token: session.user.tokens.access_token,
348 refresh_token: session.user.tokens.refresh_token,
349 user_id: session.user.meta.user_id,
350 device_id: session.user.meta.device_id,
351 client_id: Some(session.client_id),
315 } 352 }
316 } 353 }
317} 354}
@@ -1421,10 +1458,10 @@ impl ApplicationSettings {
1421 Ok(session) 1458 Ok(session)
1422 } 1459 }
1423 1460
1424 pub fn write_session(&self, session: MatrixSession) -> Result<(), IambError> { 1461 pub fn write_session(&self, session: impl Into<Session>) -> Result<(), IambError> {
1425 let file = File::create(self.session_json.as_path())?; 1462 let file = File::create(self.session_json.as_path())?;
1426 let writer = BufWriter::new(file); 1463 let writer = BufWriter::new(file);
1427 let session = Session::from(session); 1464 let session: Session = session.into();
1428 serde_json::to_writer(writer, &session).map_err(IambError::from)?; 1465 serde_json::to_writer(writer, &session).map_err(IambError::from)?;
1429 Ok(()) 1466 Ok(())
1430 } 1467 }
src/main.rs +21 −18
@@ -66,6 +66,7 @@ mod config;
66mod keybindings; 66mod keybindings;
67mod message; 67mod message;
68mod notifications; 68mod notifications;
69mod oauth;
69mod prelude; 70mod prelude;
70mod preview; 71mod preview;
71mod util; 72mod util;
@@ -1012,14 +1013,12 @@ async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult
1012 if settings.session_json.is_file() { 1013 if settings.session_json.is_file() {
1013 let session = settings.read_session(&settings.session_json)?; 1014 let session = settings.read_session(&settings.session_json)?;
1014 worker.login(LoginStyle::SessionRestore(session.into()))?; 1015 worker.login(LoginStyle::SessionRestore(session.into()))?;
1015
1016 return Ok(()); 1016 return Ok(());
1017 } 1017 }
1018 1018
1019 if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() { 1019 if settings.session_json_old.is_file() && !settings.sled_dir.is_dir() {
1020 let session = settings.read_session(&settings.session_json_old)?; 1020 let session = settings.read_session(&settings.session_json_old)?;
1021 worker.login(LoginStyle::SessionRestore(session.into()))?; 1021 worker.login(LoginStyle::SessionRestore(session.into()))?;
1022
1023 return Ok(()); 1022 return Ok(());
1024 } 1023 }
1025 1024
@@ -1035,22 +1034,24 @@ async fn login(worker: &Requester, settings: &ApplicationSettings) -> IambResult
1035 } 1034 }
1036 1035
1037 loop { 1036 loop {
1038 let login_style = 1037 let login_style = match read_response(
1039 match read_response("Please select login type: [p]assword / [s]ingle sign on") 1038 "Please select login type: [p]assword / [s]ingle sign on / [o]auth",
1040 .chars() 1039 )
1041 .next() 1040 .chars()
1042 .map(|c| c.to_ascii_lowercase()) 1041 .next()
1043 { 1042 .map(|c| c.to_ascii_lowercase())
1044 None | Some('p') => { 1043 {
1045 let password = rpassword::prompt_password("Password: ")?; 1044 None | Some('p') => {
1046 LoginStyle::Password(password) 1045 let password = rpassword::prompt_password("Password: ")?;
1047 }, 1046 LoginStyle::Password(password)
1048 Some('s') => LoginStyle::SingleSignOn, 1047 },
1049 Some(_) => { 1048 Some('s') => LoginStyle::SingleSignOn,
1050 println!("Failed to login. Please enter 'p' or 's'"); 1049 Some('o') => LoginStyle::OAuth,
1051 continue; 1050 Some(_) => {
1052 }, 1051 println!("Failed to login. Please enter 'p', 's' or 'o'");
1053 }; 1052 continue;
1053 },
1054 };
1054 1055
1055 match worker.login(login_style) { 1056 match worker.login(login_style) {
1056 Ok(info) => { 1057 Ok(info) => {
@@ -1083,6 +1084,8 @@ async fn login_normal(
1083 println!("* Logging in for {}...", settings.profile.user_id); 1084 println!("* Logging in for {}...", settings.profile.user_id);
1084 login(worker, settings).await?; 1085 login(worker, settings).await?;
1085 println!("* Syncing..."); 1086 println!("* Syncing...");
1087 worker.spawn_sync()?;
1088 worker.setup_persistent_tokens();
1086 worker::do_first_sync(&worker.client, store) 1089 worker::do_first_sync(&worker.client, store)
1087 .await 1090 .await
1088 .map_err(IambError::from)?; 1091 .map_err(IambError::from)?;
src/oauth.rs added +163
@@ -0,0 +1,163 @@
1use std::net::{Ipv4Addr, Ipv6Addr};
2
3use matrix_sdk::authentication::oauth::OAuthAuthorizationData;
4use matrix_sdk::authentication::oauth::registration::{
5 ApplicationType,
6 ClientMetadata,
7 Localized,
8 OAuthGrantType,
9};
10use matrix_sdk::ruma;
11use matrix_sdk::ruma::UserId;
12use matrix_sdk::ruma::serde::Raw;
13use matrix_sdk::utils::UrlOrQuery;
14use matrix_sdk::utils::local_server::{LocalServerBuilder, LocalServerRedirectHandle};
15use tokio::io::AsyncBufReadExt;
16use tokio::task::JoinHandle;
17
18use crate::prelude::*;
19
20enum OAuthRedirectResponse {
21 Server(UrlOrQuery),
22 Stdin(UrlOrQuery),
23}
24
25pub async fn oauth_login(client: Client, user_hint: &UserId) -> IambResult<()> {
26 let oauth = client.oauth();
27
28 match oauth.server_metadata().await {
29 Ok(server_metadata) => {
30 tracing::info!(
31 "Found OAuth 2.0 server metadata with issuer: {}",
32 server_metadata.issuer
33 );
34
35 let (redirect_uri, server_handle) = LocalServerBuilder::new().spawn().await?;
36 let OAuthAuthorizationData { url, .. } = oauth
37 .login(redirect_uri, None, Some(client_metadata().into()), None)
38 .user_id_hint(user_hint)
39 .build()
40 .await
41 .map_err(IambError::from)?;
42
43 let opened =
44 format!("The following URL should have been opened in your browser:\n {url}");
45 tokio::task::spawn_blocking(move || open::that(url.as_str()));
46 println!("{opened}");
47 println!(
48 "\n\n\
49 If the redirect fails to connect (i.e., iamb is not reachable from your browser), \
50 the url (or just the query string) can be pasted here to complete the authorisation flow.\
51 "
52 );
53
54 let url_or_query = wait_auth_code(server_handle).await?;
55 oauth.finish_login(url_or_query).await.map_err(IambError::from)?;
56 Ok(())
57 },
58 Err(error) => {
59 if error.is_not_supported() {
60 tracing::warn!("Homeserver doesn't advertise OAuth 2.0 metadata");
61 } else {
62 tracing::warn!("Error fetching OAuth 2.0 metadata : {error:?}");
63 }
64 Err(UIError::Failure(
65 "Error fetching homeserver OAuth 2.0 metadata. \
66 Homeserver needs to support native OAuth 2.0 for oauth login to work"
67 .to_string(),
68 ))
69 },
70 }
71}
72
73async fn wait_auth_code(server_handle: LocalServerRedirectHandle) -> IambResult<UrlOrQuery> {
74 let (tx, mut rx) = tokio::sync::mpsc::channel(1);
75
76 let server_tx = tx.clone();
77
78 let server = tokio::spawn(async move {
79 let server_resp = server_handle.await;
80 match server_resp {
81 Some(query) => {
82 let _ = server_tx.try_send(OAuthRedirectResponse::Server(query.into()));
83 },
84 None => {
85 println!(
86 "Failed to read query string from browser redirect. \
87 Please paste url in here:\n"
88 );
89 },
90 }
91 });
92
93 let stdin_reader: JoinHandle<Result<(), tokio::io::Error>> = tokio::task::spawn(async move {
94 let stdin = tokio::io::stdin();
95 let mut reader = tokio::io::BufReader::new(stdin);
96 let mut line = String::new();
97
98 loop {
99 reader.read_line(&mut line).await?;
100 if let Ok(url) = Url::parse(&line) {
101 let _ = tx.try_send(OAuthRedirectResponse::Stdin(UrlOrQuery::Url(url)));
102 break;
103 } else if line.starts_with('?') {
104 let strip_qm = line.split_off(0);
105 let _ = tx.try_send(OAuthRedirectResponse::Stdin(UrlOrQuery::Query(strip_qm)));
106 break;
107 } else if line.contains("code=") {
108 let _ = tx.try_send(OAuthRedirectResponse::Stdin(UrlOrQuery::Query(line)));
109 break;
110 } else if !line.contains(char::is_whitespace) {
111 println!("Unrecognised url or query string");
112 } else {
113 break;
114 }
115 }
116 Ok(())
117 });
118
119 let received = rx.recv().await;
120
121 match received {
122 Some(OAuthRedirectResponse::Server(qry)) => {
123 println!("Received authorisation code from browser. Press Enter to continue...");
124 let _ = stdin_reader.await;
125 Ok(qry)
126 },
127 Some(OAuthRedirectResponse::Stdin(url)) => {
128 server.abort();
129 println!("Using redirect from stdin. Localhost listener will be ignored.");
130 Ok(url)
131 },
132 None => {
133 Err(UIError::Failure("Failed to receive redirect from stdin or browser".to_string()))
134 },
135 }
136}
137
138// Taken from the sdk's example
139fn client_metadata() -> Raw<ClientMetadata> {
140 let ipv4_localhost_uri = Url::parse(&format!("http://{}/", Ipv4Addr::LOCALHOST))
141 .expect("Couldn't parse IPv4 redirect URI");
142 let ipv6_localhost_uri = Url::parse(&format!("http://[{}]/", Ipv6Addr::LOCALHOST))
143 .expect("Couldn't parse IPv6 redirect URI");
144 let client_uri =
145 Localized::new(Url::parse("https://iamb.chat").expect("Couldn't parse client URI"), None);
146 let logo_uri = Localized::new(
147 Url::parse("https://iamb.chat/images/iamb.png").expect("Couldn't parse logo uri"),
148 None,
149 );
150
151 let metadata = ruma::assign!(
152 ClientMetadata::new(
153 ApplicationType::Native,
154 vec![OAuthGrantType::AuthorizationCode {
155 redirect_uris: vec![ipv4_localhost_uri, ipv6_localhost_uri],
156 }],
157 client_uri), {
158 client_name: Some(Localized::new("iamb".to_owned(), [])),
159 logo_uri: Some(logo_uri)
160 });
161
162 Raw::new(&metadata).expect("Couldn't serialize client metadata")
163}
src/worker.rs +148 −17
@@ -9,7 +9,7 @@ use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
9use futures::stream::FuturesUnordered; 9use futures::stream::FuturesUnordered;
10use futures::{FutureExt as _, StreamExt}; 10use futures::{FutureExt as _, StreamExt};
11use gethostname::gethostname; 11use gethostname::gethostname;
12use matrix_sdk::OwnedServerName; 12use matrix_sdk::AuthSession;
13use matrix_sdk::authentication::matrix::MatrixSession; 13use matrix_sdk::authentication::matrix::MatrixSession;
14use matrix_sdk::config::{RequestConfig, SyncSettings}; 14use matrix_sdk::config::{RequestConfig, SyncSettings};
15use matrix_sdk::deserialized_responses::RawSyncOrStrippedState; 15use matrix_sdk::deserialized_responses::RawSyncOrStrippedState;
@@ -72,6 +72,7 @@ use matrix_sdk::ruma::presence::PresenceState;
72use matrix_sdk::ruma::room::RoomType; 72use matrix_sdk::ruma::room::RoomType;
73use matrix_sdk::ruma::serde::Raw; 73use matrix_sdk::ruma::serde::Raw;
74use matrix_sdk::send_queue::{LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate}; 74use matrix_sdk::send_queue::{LocalEcho, LocalEchoContent, RoomSendQueueUpdate, SendQueueUpdate};
75use matrix_sdk::{AuthApi, OwnedServerName};
75use matrix_sdk::{ 76use matrix_sdk::{
76 ClientBuildError, 77 ClientBuildError,
77 Error as MatrixError, 78 Error as MatrixError,
@@ -92,6 +93,7 @@ use crate::base::{CreateRoomFlags, CreateRoomType, EchoLocation, MessageNeed};
92use crate::config::ProxyUrl; 93use crate::config::ProxyUrl;
93use crate::message::MessageId; 94use crate::message::MessageId;
94use crate::notifications::register_notifications; 95use crate::notifications::register_notifications;
96use crate::oauth::oauth_login;
95use crate::prelude::*; 97use crate::prelude::*;
96use crate::preview::{PreviewKind, PreviewManager}; 98use crate::preview::{PreviewKind, PreviewManager};
97use crate::verifications; 99use crate::verifications;
@@ -1092,9 +1094,10 @@ pub async fn do_first_sync(client: &Client, store: &AsyncProgramStore) -> Result
1092 1094
1093#[derive(Debug)] 1095#[derive(Debug)]
1094pub enum LoginStyle { 1096pub enum LoginStyle {
1095 SessionRestore(MatrixSession), 1097 SessionRestore(AuthSession),
1096 Password(String), 1098 Password(String),
1097 SingleSignOn, 1099 SingleSignOn,
1100 OAuth,
1098} 1101}
1099 1102
1100pub struct ClientResponse<T>(Receiver<T>); 1103pub struct ClientResponse<T>(Receiver<T>);
@@ -1137,6 +1140,9 @@ pub enum WorkerTask {
1137 CreateDM(OwnedUserId, ClientReply<IambResult<OwnedRoomId>>), 1140 CreateDM(OwnedUserId, ClientReply<IambResult<OwnedRoomId>>),
1138 Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>), 1141 Members(OwnedRoomId, ClientReply<IambResult<Vec<RoomMember>>>),
1139 SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>), 1142 SpaceMembers(OwnedRoomId, ClientReply<IambResult<Vec<OwnedRoomId>>>),
1143 StartSync(ClientReply<IambResult<EditInfo>>),
1144 SaveTokens,
1145 StartPersistentTokenTask(UnboundedSender<WorkerTask>),
1140 TypingNotice(OwnedRoomId), 1146 TypingNotice(OwnedRoomId),
1141 LoadImage(MediaSource, PreviewKind, Size, Arc<Picker>, Arc<Semaphore>), 1147 LoadImage(MediaSource, PreviewKind, Size, Arc<Picker>, Arc<Semaphore>),
1142} 1148}
@@ -1211,6 +1217,13 @@ impl Debug for WorkerTask {
1211 .field(&format_args!("_")) 1217 .field(&format_args!("_"))
1212 .finish() 1218 .finish()
1213 }, 1219 },
1220 WorkerTask::StartSync(_) => {
1221 f.debug_tuple("WorkerTask::StartSync").field(&format_args!("_")).finish()
1222 },
1223 WorkerTask::SaveTokens => f.debug_tuple("WorkerTask::SaveTokens").finish(),
1224 WorkerTask::StartPersistentTokenTask(tx) => {
1225 f.debug_tuple("WorkerTask::RenderImage").field(tx).finish()
1226 },
1214 } 1227 }
1215 } 1228 }
1216} 1229}
@@ -1271,6 +1284,7 @@ async fn create_client_inner(
1271 settings.sqlite_cache_dir.as_path(), 1284 settings.sqlite_cache_dir.as_path(),
1272 None, 1285 None,
1273 ) 1286 )
1287 .handle_refresh_tokens()
1274 .request_config(req_config) 1288 .request_config(req_config)
1275 .with_threading_support(matrix_sdk::ThreadingSupport::Enabled { with_subscriptions: false }) 1289 .with_threading_support(matrix_sdk::ThreadingSupport::Enabled { with_subscriptions: false })
1276 .with_encryption_settings(DEFAULT_ENCRYPTION_SETTINGS); 1290 .with_encryption_settings(DEFAULT_ENCRYPTION_SETTINGS);
@@ -1398,6 +1412,14 @@ impl Requester {
1398 return response.recv(); 1412 return response.recv();
1399 } 1413 }
1400 1414
1415 pub fn spawn_sync(&self) -> IambResult<EditInfo> {
1416 let (reply, response) = oneshot();
1417
1418 self.tx.send(WorkerTask::StartSync(reply)).unwrap();
1419
1420 return response.recv();
1421 }
1422
1401 pub fn get_inviter(&self, invite: MatrixRoom) -> IambResult<Option<RoomMember>> { 1423 pub fn get_inviter(&self, invite: MatrixRoom) -> IambResult<Option<RoomMember>> {
1402 let (reply, response) = oneshot(); 1424 let (reply, response) = oneshot();
1403 1425
@@ -1464,6 +1486,12 @@ impl Requester {
1464 return response.recv(); 1486 return response.recv();
1465 } 1487 }
1466 1488
1489 pub fn setup_persistent_tokens(&self) {
1490 self.tx
1491 .send(WorkerTask::StartPersistentTokenTask(self.tx.clone()))
1492 .unwrap();
1493 }
1494
1467 pub fn typing_notice(&self, room_id: OwnedRoomId) { 1495 pub fn typing_notice(&self, room_id: OwnedRoomId) {
1468 self.tx.send(WorkerTask::TypingNotice(room_id)).unwrap(); 1496 self.tx.send(WorkerTask::TypingNotice(room_id)).unwrap();
1469 } 1497 }
@@ -1565,7 +1593,7 @@ impl ClientWorker {
1565 }, 1593 },
1566 WorkerTask::Login(style, reply) => { 1594 WorkerTask::Login(style, reply) => {
1567 assert!(self.initialized); 1595 assert!(self.initialized);
1568 reply.send(self.login_and_sync(style).await); 1596 reply.send(self.login(style).await);
1569 }, 1597 },
1570 WorkerTask::Logout(user_id, reply) => { 1598 WorkerTask::Logout(user_id, reply) => {
1571 assert!(self.initialized); 1599 assert!(self.initialized);
@@ -1579,6 +1607,10 @@ impl ClientWorker {
1579 assert!(self.initialized); 1607 assert!(self.initialized);
1580 reply.send(self.space_members(space).await); 1608 reply.send(self.space_members(space).await);
1581 }, 1609 },
1610 WorkerTask::StartSync(reply) => {
1611 assert!(self.initialized);
1612 reply.send(self.start_sync());
1613 },
1582 WorkerTask::TypingNotice(room_id) => { 1614 WorkerTask::TypingNotice(room_id) => {
1583 assert!(self.initialized); 1615 assert!(self.initialized);
1584 self.typing_notice(room_id).await; 1616 self.typing_notice(room_id).await;
@@ -1595,6 +1627,14 @@ impl ClientWorker {
1595 size, 1627 size,
1596 )); 1628 ));
1597 }, 1629 },
1630 WorkerTask::SaveTokens => {
1631 assert!(self.initialized);
1632 self.save_tokens().await;
1633 },
1634 WorkerTask::StartPersistentTokenTask(tx) => {
1635 assert!(self.initialized);
1636 self.setup_persistent_tokens(tx);
1637 },
1598 } 1638 }
1599 } 1639 }
1600 1640
@@ -2110,12 +2150,13 @@ impl ClientWorker {
2110 self.initialized = true; 2150 self.initialized = true;
2111 } 2151 }
2112 2152
2113 async fn login_and_sync(&mut self, style: LoginStyle) -> IambResult<EditInfo> { 2153 async fn login(&mut self, style: LoginStyle) -> IambResult<EditInfo> {
2114 let client = self.client.clone(); 2154 let client = self.client.clone();
2115 2155
2116 match style { 2156 match style {
2117 LoginStyle::SessionRestore(session) => { 2157 LoginStyle::SessionRestore(session) => {
2118 client.restore_session(session).await.map_err(IambError::from)?; 2158 client.restore_session(session).await.map_err(IambError::from)?;
2159 return self.update_profile_on_login(true).await;
2119 }, 2160 },
2120 LoginStyle::Password(password) => { 2161 LoginStyle::Password(password) => {
2121 let mut login = client 2162 let mut login = client
@@ -2152,19 +2193,17 @@ impl ClientWorker {
2152 let session = MatrixSession::from(&resp); 2193 let session = MatrixSession::from(&resp);
2153 self.settings.write_session(session)?; 2194 self.settings.write_session(session)?;
2154 }, 2195 },
2196 LoginStyle::OAuth => {
2197 oauth_login(self.client.clone(), &self.settings.profile.user_id).await?;
2198 let session = self
2199 .client
2200 .oauth()
2201 .full_session()
2202 .expect("logged in client should have session");
2203 self.settings.write_session(session)?;
2204 },
2155 } 2205 }
2156 2206 self.update_profile_on_login(false).await
2157 let sync_delay = Duration::from_millis(self.settings.tunables.sync_delay_ms);
2158 self.sync_handle = tokio::spawn(async move {
2159 loop {
2160 let settings = SyncSettings::default();
2161 let _ = client.sync(settings).await;
2162 tokio::time::sleep(sync_delay).await;
2163 }
2164 })
2165 .into();
2166
2167 Ok(Some(InfoMessage::from("* Successfully logged in!")))
2168 } 2207 }
2169 2208
2170 async fn logout(&mut self, user_id: String) -> IambResult<EditInfo> { 2209 async fn logout(&mut self, user_id: String) -> IambResult<EditInfo> {
@@ -2187,7 +2226,7 @@ impl ClientWorker {
2187 } 2226 }
2188 2227
2189 // Send the logout request. 2228 // Send the logout request.
2190 if let Err(e) = self.client.matrix_auth().logout().await { 2229 if let Err(e) = self.client.logout().await {
2191 let msg = format!("Failed to logout: {e}"); 2230 let msg = format!("Failed to logout: {e}");
2192 let err = UIError::Failure(msg); 2231 let err = UIError::Failure(msg);
2193 2232
@@ -2260,4 +2299,96 @@ impl ClientWorker {
2260 let _ = room.typing_notice(true).await; 2299 let _ = room.typing_notice(true).await;
2261 } 2300 }
2262 } 2301 }
2302
2303 fn start_sync(&mut self) -> IambResult<EditInfo> {
2304 let client = self.client.clone();
2305 let sync_delay = Duration::from_millis(self.settings.tunables.sync_delay_ms);
2306 self.sync_handle = tokio::spawn(async move {
2307 loop {
2308 let settings = SyncSettings::default();
2309 let _ = client.sync(settings).await;
2310 tokio::time::sleep(sync_delay).await;
2311 }
2312 })
2313 .into();
2314 Ok(Some(InfoMessage::from("Sync task spawned")))
2315 }
2316
2317 fn setup_persistent_tokens(&self, tx: UnboundedSender<WorkerTask>) {
2318 let client = self.client.clone();
2319
2320 tokio::spawn(async move {
2321 let mut session_changes_sub = client.subscribe_to_session_changes();
2322 while let Ok(change) = session_changes_sub.recv().await {
2323 match change {
2324 matrix_sdk::SessionChange::UnknownToken(unknown_token) => {
2325 tracing::warn!(
2326 "client encountered an unknown token: soft logout = {}",
2327 unknown_token.soft_logout
2328 );
2329 },
2330 matrix_sdk::SessionChange::TokensRefreshed => {
2331 if let Err(e) = tx.send(WorkerTask::SaveTokens) {
2332 // Unable to send requests - the worker has probably ended
2333 // quit gracefully
2334 tracing::debug!(
2335 "persistent token task ending - tokens will no longer be saved: {e}"
2336 )
2337 }
2338 },
2339 }
2340 }
2341 });
2342 }
2343
2344 async fn save_tokens(&self) {
2345 let auth_api = self.client.auth_api().expect("client should be logged in");
2346 match auth_api {
2347 AuthApi::OAuth(oauth) => {
2348 let session = oauth.full_session().expect("logged in client should have session");
2349 if let Err(e) = self.settings.write_session(session) {
2350 tracing::warn!("Failed to persist oauth session: {e}");
2351 }
2352 },
2353 AuthApi::Matrix(matrix) => {
2354 let session = matrix.session().expect("logged in client should have session");
2355 if let Err(e) = self.settings.write_session(session) {
2356 tracing::warn!("Failed to persist matrix session: {e}");
2357 }
2358 },
2359 _ => {
2360 tracing::error!("Unknown login method. Cannot persist tokens");
2361 },
2362 }
2363 }
2364
2365 async fn update_profile_on_login(&mut self, restored: bool) -> IambResult<EditInfo> {
2366 let client = self.client.clone();
2367
2368 // User may login with different user than in settings, update here
2369 // If we've restored the session from an access token, check with the
2370 // homeserver who the token belongs to
2371 let user = if restored {
2372 let whoami = client.whoami().await;
2373 if whoami
2374 .as_ref()
2375 .is_err_and(|e| matches!(e, matrix_sdk::HttpError::RefreshToken(_)))
2376 {
2377 tracing::error!("Login attempt failed: invalid refresh token loaded from profile.");
2378 }
2379 &whoami.map_err(IambError::from)?.user_id
2380 } else {
2381 client.user_id().expect("logged in user should have id")
2382 };
2383
2384 let msg = format!("* Successfully logged in with {}!", user);
2385 if user != self.settings.profile.user_id {
2386 // Trace warning if this happens
2387 tracing::warn!("logged in as a different user than expected");
2388 self.settings.profile.user_id = user.to_owned();
2389 let store = self.store.as_ref().expect("initialised worker should have store");
2390 store.lock().await.application.settings.profile.user_id = user.to_owned();
2391 }
2392 Ok(Some(InfoMessage::from(msg)))
2393 }
2263} 2394}