example_cross_signing_bootstrap/
main.rs1#![recursion_limit = "256"]
2
3use std::{
4 env, io,
5 process::exit,
6 sync::atomic::{AtomicBool, Ordering},
7};
8
9use anyhow::Result;
10use matrix_sdk::{
11 Client, LoopCtrl, config::SyncSettings, encryption::CrossSigningResetAuthType,
12 ruma::OwnedUserId,
13};
14use url::Url;
15
16async fn bootstrap(client: Client, user_id: OwnedUserId, password: String) -> Result<()> {
17 println!("Bootstrapping a new cross signing identity, press enter to continue.");
18
19 let mut input = String::new();
20
21 io::stdin().read_line(&mut input).expect("error: unable to read user input");
22
23 if let Some(handle) = client.encryption().reset_cross_signing().await? {
24 match handle.auth_type() {
25 CrossSigningResetAuthType::Uiaa(uiaa) => {
26 handle.auth(uiaa.as_password_auth_data(user_id.into(), password)).await?;
27 }
28 CrossSigningResetAuthType::OAuth(oauth) => {
29 println!(
30 "To reset your end-to-end encryption cross-signing identity, \
31 you first need to approve it at {}",
32 oauth.approval_url
33 );
34
35 handle.auth(oauth.as_auth_data()).await?;
36 }
37 }
38 }
39
40 Ok(())
41}
42
43async fn login(homeserver_url: String, username: &str, password: &str) -> matrix_sdk::Result<()> {
44 let homeserver_url = Url::parse(&homeserver_url).expect("Couldn't parse the homeserver URL");
45 let client = Client::new(homeserver_url).await.unwrap();
46
47 let response = client
48 .matrix_auth()
49 .login_username(username, password)
50 .initial_device_display_name("rust-sdk")
51 .await?;
52
53 let user_id = &response.user_id;
54 let client_ref = &client;
55 let asked = AtomicBool::new(false);
56 let asked_ref = &asked;
57
58 client
59 .sync_with_callback(SyncSettings::new(), |_| async move {
60 let asked = asked_ref;
61 let client = &client_ref;
62 let user_id = &user_id;
63
64 if !asked.load(Ordering::SeqCst) {
66 tokio::spawn(bootstrap((*client).clone(), (*user_id).clone(), password.to_owned()));
67 }
68
69 asked.store(true, Ordering::SeqCst);
70 LoopCtrl::Continue
71 })
72 .await?;
73
74 Ok(())
75}
76
77#[tokio::main]
78async fn main() -> Result<()> {
79 tracing_subscriber::fmt::init();
80
81 let (Some(homeserver_url), Some(username), Some(password)) =
82 (env::args().nth(1), env::args().nth(2), env::args().nth(3))
83 else {
84 eprintln!("Usage: {} <homeserver_url> <username> <password>", env::args().next().unwrap());
85 exit(1)
86 };
87
88 login(homeserver_url, &username, &password).await?;
89
90 Ok(())
91}