acter/api/account/
three_pid.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
use acter_core::events::three_pid::{ThreePidContent, ThreePidRecord};
use anyhow::{bail, Context, Result};
use matrix_sdk::reqwest::{ClientBuilder, StatusCode};
use matrix_sdk_base::ruma::{
    api::client::{
        account::{request_3pid_management_token_via_email, ThirdPartyIdRemovalStatus},
        uiaa::{AuthData, Password, UserIdentifier},
    },
    assign,
    thirdparty::{Medium, ThirdPartyIdentifier},
    uint, ClientSecret, MilliSecondsSinceUnixEpoch, OwnedClientSecret, SessionId,
};
use serde::Deserialize;
use std::{collections::BTreeMap, ops::Deref};

use super::Account;
use crate::{api::common::clearify_error, RUNTIME};

#[derive(Clone)]
pub struct ThreePidEmailTokenResponse {
    inner: request_3pid_management_token_via_email::v3::Response,
    client_secret: OwnedClientSecret,
}

impl ThreePidEmailTokenResponse {
    pub fn sid(&self) -> String {
        self.inner.sid.to_string()
    }

    pub fn submit_url(&self) -> Option<String> {
        self.inner.submit_url.clone()
    }

    pub fn client_secret(&self) -> String {
        self.client_secret.to_string()
    }
}

#[derive(Clone)]
pub struct ExternalId {
    address: String,
    medium: Medium,
    added_at: MilliSecondsSinceUnixEpoch,
    validated_at: MilliSecondsSinceUnixEpoch,
}

impl ExternalId {
    fn new(val: ThirdPartyIdentifier) -> Self {
        ExternalId {
            address: val.address,
            medium: val.medium,
            added_at: val.added_at,
            validated_at: val.validated_at,
        }
    }

    pub fn address(&self) -> String {
        self.address.clone()
    }

    pub fn medium(&self) -> String {
        self.medium.to_string()
    }

    pub fn added_at(&self) -> u64 {
        self.added_at.get().into()
    }

    pub fn validated_at(&self) -> u64 {
        self.validated_at.get().into()
    }
}

#[derive(Deserialize, Debug)]
struct ValidateResponse {
    pub success: bool,
}

impl Account {
    pub async fn confirmed_email_addresses(&self) -> Result<Vec<String>> {
        let account = self.account.clone();

        RUNTIME
            .spawn(async move {
                let response = account.get_3pids().await.map_err(clearify_error)?;
                let addresses = response
                    .threepids
                    .iter()
                    .filter_map(|x| {
                        if x.medium == Medium::Email {
                            Some(x.address.clone())
                        } else {
                            None
                        }
                    })
                    .collect::<Vec<String>>();
                Ok(addresses)
            })
            .await?
    }

    pub async fn requested_email_addresses(&self) -> Result<Vec<String>> {
        let account = self.account.clone();
        RUNTIME
            .spawn(async move {
                let maybe_content = account.account_data::<ThreePidContent>().await?;
                let Some(raw_content) = maybe_content else {
                    return Ok(vec![]);
                };
                let content = raw_content.deserialize()?;
                let addresses = content.via_email.iter().map(|(k, v)| k.clone()).collect();
                Ok(addresses)
            })
            .await?
    }

    pub async fn request_3pid_management_token_via_email(
        &self,
        email: String,
    ) -> Result<ThreePidEmailTokenResponse> {
        let client = self.client.deref().clone();
        let account = self.account.clone();
        let client_secret = ClientSecret::new();

        RUNTIME
            .spawn(async move {
                let capabilities = client.get_capabilities().await?;
                if !capabilities.thirdparty_id_changes.enabled {
                    bail!("Server doesn’t support change of third party identity");
                }
                let inner = account
                    .request_3pid_email_token(&client_secret, &email, uint!(0))
                    .await
                    .map_err(clearify_error)?;

                // add this record to custom data
                let record = ThreePidRecord::new(inner.sid.to_string(), client_secret.clone());
                let maybe_content = account.account_data::<ThreePidContent>().await?;
                let content = if let Some(raw_content) = maybe_content {
                    let mut content = raw_content.deserialize()?;
                    content
                        .via_email
                        .entry(email)
                        .and_modify(|x| *x = record.clone())
                        .or_insert(record);
                    content
                } else {
                    let mut via_email = BTreeMap::new();
                    via_email.insert(email, record);
                    let via_phone = BTreeMap::new();
                    ThreePidContent {
                        via_email,
                        via_phone,
                    }
                };
                account.set_account_data(content).await?;

                Ok(ThreePidEmailTokenResponse {
                    inner,
                    client_secret,
                })
            })
            .await?
    }

    // add 3pid on the homeserver for this account
    // this 3pid may be used by the homeserver to authenticate the user during sensitive operations
    #[cfg(feature = "testing")]
    pub async fn add_3pid(
        &self,
        client_secret: String,
        sid: String,
        password: String,
    ) -> Result<bool> {
        let client = self.client.deref().clone();
        let account = self.account.clone();
        let user_id = self.user_id.clone();
        let client_secret = ClientSecret::parse(&client_secret)?;
        let sid = SessionId::parse(&sid)?; // it was already related with email or msisdn

        RUNTIME
            .spawn(async move {
                let capabilities = client.get_capabilities().await?;
                if !capabilities.thirdparty_id_changes.enabled {
                    bail!("Server doesn’t support 3pid change");
                }
                if let Err(e) = account.add_3pid(&client_secret, &sid, None).await {
                    let Some(inf) = e.as_uiaa_response() else {
                        return Err(clearify_error(e));
                    };
                    let pswd = assign!(Password::new(user_id.into(), password), {
                        session: inf.session.clone(),
                    });
                    let auth_data = AuthData::Password(pswd);
                    account
                        .add_3pid(&client_secret, &sid, Some(auth_data))
                        .await
                        .map_err(clearify_error)?;
                }
                Ok(true)
            })
            .await?
    }

    pub async fn external_ids(&self) -> Result<Vec<ExternalId>> {
        let account = self.account.clone();

        RUNTIME
            .spawn(async move {
                let resp = account.get_3pids().await.map_err(clearify_error)?;
                let records = resp.threepids.into_iter().map(ExternalId::new).collect();
                Ok(records)
            })
            .await?
    }

    pub async fn try_confirm_email_status(
        &self,
        email_address: String,
        password: String,
    ) -> Result<bool> {
        let client = self.client.deref().clone();
        let account = self.account.clone();
        let user_id = self.user_id.clone();

        RUNTIME
            .spawn(async move {
                let capabilities = client.get_capabilities().await?;
                if !capabilities.thirdparty_id_changes.enabled {
                    bail!("Server doesn’t support change of third party identity");
                }
                let mut content = account
                    .account_data::<ThreePidContent>()
                    .await?
                    .context("Not found any email registration content")?
                    .deserialize()?;
                let record = content
                    .via_email
                    .get(&email_address)
                    .context("That email address was not registered")?;
                let session_id = record.session_id();
                let passphrase = record.passphrase();
                let sid = SessionId::parse(session_id.clone())?;
                let secret = ClientSecret::parse(passphrase.clone())?;
                // try again with password
                // FIXME: this shouldn’t be hardcoded but use an Actual IUAA-flow
                let auth_data = AuthData::Password(Password::new(
                    UserIdentifier::UserIdOrLocalpart(user_id.to_string()),
                    password,
                ));

                if let Err(e) = account
                    .add_3pid(&secret, &sid, Some(auth_data.clone()))
                    .await
                {
                    if let Some(a) = e.as_uiaa_response() {
                        if let Some(std_err) = &a.auth_error {
                            bail!("{:?}: {:?}", std_err.kind, std_err.message);
                        }
                    }
                    return Err(e.into());
                }

                // now email address can be removed from account data
                // because session id & passphrase are wasted
                content.via_email.remove(&email_address);
                account.set_account_data(content).await?;

                Ok(true)
            })
            .await?
    }

    pub async fn submit_token_from_email(
        &self,
        email_address: String,
        token: String,
        password: String,
    ) -> Result<bool> {
        let client = self.client.clone();
        let account = self.account.clone();
        let user_id = self.client.user_id()?;

        RUNTIME
            .spawn(async move {
                let capabilities = client.get_capabilities().await?;
                if !capabilities.thirdparty_id_changes.enabled {
                    bail!("Server doesn’t support change of third party identity");
                }
                let mut content = account
                    .account_data::<ThreePidContent>()
                    .await?
                    .context("Not found any email registration content")?
                    .deserialize()?;
                let record = content
                    .via_email
                    .get(&email_address)
                    .context("That email address was not registered")?;
                let session_id = record.session_id();
                let secret = record.passphrase();
                let sid = SessionId::parse(session_id.clone())?;
                let secret = ClientSecret::parse(secret.clone())?;
                let submit_url = format!(
                    "{}/_matrix/client/unstable/add_threepid/email/submit_token",
                    client.homeserver(),
                );

                // send confirmation
                let http_client = ClientBuilder::new().build()?;
                let submit_response = http_client
                    .get(submit_url)
                    .query(&[
                        ("token", token),
                        ("client_secret", secret.to_string()),
                        ("sid", session_id),
                    ])
                    .send()
                    .await?;
                if submit_response.status() != StatusCode::OK {
                    return Ok(false);
                }
                let text = submit_response.text().await?;
                let ValidateResponse { success } = serde_json::from_str(&text)?;
                if !success {
                    return Ok(false);
                }
                // try again with password
                // FIXME: this shouldn’t be hardcoded but use an Actual IUAA-flow
                let auth_data = AuthData::Password(Password::new(
                    UserIdentifier::UserIdOrLocalpart(user_id.to_string()),
                    password,
                ));

                if let Err(e) = account.add_3pid(&secret, &sid, Some(auth_data)).await {
                    if let Some(a) = e.as_uiaa_response() {
                        if let Some(std_err) = &a.auth_error {
                            bail!("{:?}: {:?}", std_err.kind, std_err.message);
                        }
                    }
                    return Err(e.into());
                }

                // now email address can be removed from account data
                // because session id & passphrase are wasted
                content.via_email.remove(&email_address);
                account.set_account_data(content).await?;

                Ok(true)
            })
            .await?
    }

    pub async fn remove_email_address(&self, email_address: String) -> Result<bool> {
        let client = self.client.clone();
        let account = self.account.clone();
        RUNTIME
            .spawn(async move {
                let capabilities = client.get_capabilities().await?;
                if !capabilities.thirdparty_id_changes.enabled {
                    bail!("Server doesn’t support change of third party identity");
                }
                // find it among the confirmed email addresses
                let response = account.get_3pids().await?;
                if let Some(index) = response
                    .threepids
                    .iter()
                    .position(|x| x.medium == Medium::Email && x.address == email_address)
                {
                    let response = account
                        .delete_3pid(&email_address, Medium::Email, None)
                        .await?;
                    match response.id_server_unbind_result {
                        ThirdPartyIdRemovalStatus::Success => {
                            return Ok(true);
                        }
                        _ => {
                            return Ok(false);
                        }
                    }
                }

                // find it among the unconfirmed email addresses
                let maybe_content = account.account_data::<ThreePidContent>().await?;
                let Some(raw_content) = maybe_content else {
                    return Ok(false);
                };
                let mut content = raw_content.deserialize()?;
                if content.via_email.contains_key(&email_address) {
                    content.via_email.remove(&email_address);
                    account.set_account_data(content).await?;
                    return Ok(true);
                }

                Ok(false)
            })
            .await?
    }
}