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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
//
// ferogram: async Telegram MTProto client in Rust
// https://github.com/ankit-chaubey/ferogram
//
// Licensed under either the MIT License or the Apache License 2.0.
// See the LICENSE-MIT or LICENSE-APACHE file in this repository:
// https://github.com/ankit-chaubey/ferogram
//
// Feel free to use, modify, and share this code.
// Please keep this notice when redistributing.
use crate::*;
#[allow(unused_imports)]
use crate::{
InputMessage, InvocationError, PeerRef, SendCodeOptions, SendCodeOutcome,
dialog::{Dialog, DialogIter, MessageIter},
inline_iter, media, participants, search, update,
};
use ferogram_tl_types::{Cursor, Deserializable};
impl Client {
/// Sign in as a bot.
pub async fn bot_sign_in(&self, token: &str) -> Result<String, InvocationError> {
tracing::info!("[ferogram::auth] not signed in; authenticating with bot token");
let req = tl::functions::auth::ImportBotAuthorization {
flags: 0,
api_id: self.inner.api_id,
api_hash: self.inner.api_hash.clone(),
bot_auth_token: token.to_string(),
};
let result = self.invoke(&req).await?;
let name = match result {
tl::enums::auth::Authorization::Authorization(a) => {
self.cache_user(&a.user).await;
Self::extract_user_name(&a.user)
}
tl::enums::auth::Authorization::SignUpRequired(_) => {
return Err(InvocationError::Deserialize(
"unexpected SignUpRequired during bot sign-in".into(),
));
}
};
tracing::info!("[ferogram::auth] bot signed in: {name}");
self.inner
.is_bot
.store(true, std::sync::atomic::Ordering::Relaxed);
self.inner
.signed_in
.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = self.sync_pts_state().await;
Ok(name)
}
/// Request a login code for a user account.
///
/// Returns [`SendCodeOutcome::CodeRequired`] in the normal case, the user
/// must enter the received code and pass the bundled [`LoginToken`] to
/// [`Client::sign_in`].
///
/// Returns [`SendCodeOutcome::AlreadyAuthorized`] when Telegram recognizes
/// a logout token supplied via [`SendCodeOptions::logout_tokens`] and
/// authorizes the session immediately. In that case the client is already
/// signed in and no code entry is needed.
///
/// For standard usage with default delivery settings:
///
/// ```rust,no_run
/// # use ferogram::{Client, SendCodeOutcome};
/// # async fn ex(client: Client) -> Result<(), Box<dyn std::error::Error>> {
/// match client.request_login_code("+1234567890").await? {
/// SendCodeOutcome::CodeRequired(token) => {
/// // prompt user for code, then call client.sign_in(&token, code).await
/// }
/// SendCodeOutcome::AlreadyAuthorized(name) => {
/// println!("Welcome back, {name}!");
/// }
/// }
/// # Ok(()) }
/// ```
///
/// To pass logout tokens or configure alternative delivery methods use
/// [`Client::request_login_code_with_options`].
pub async fn request_login_code(
&self,
phone: &str,
) -> Result<SendCodeOutcome, InvocationError> {
self.request_login_code_with_options(phone, SendCodeOptions::default())
.await
}
/// Like [`Client::request_login_code`] but with full control over
/// `auth.sendCode` delivery settings.
///
/// The most important field is [`SendCodeOptions::logout_tokens`]: supply
/// future auth tokens from a previous `auth.loggedOut` response and
/// Telegram may return [`SendCodeOutcome::AlreadyAuthorized`] without
/// requiring any code entry.
///
/// ```rust,no_run
/// # use ferogram::{Client, SendCodeOptions, SendCodeOutcome};
/// # async fn ex(client: Client, stored_token: Vec<u8>) -> Result<(), Box<dyn std::error::Error>> {
/// let opts = SendCodeOptions {
/// logout_tokens: Some(vec![stored_token]),
/// ..Default::default()
/// };
/// match client.request_login_code_with_options("+1234567890", opts).await? {
/// SendCodeOutcome::AlreadyAuthorized(name) => {
/// println!("Welcome back, {name}!");
/// }
/// SendCodeOutcome::CodeRequired(token) => {
/// // prompt for code, then call client.sign_in(&token, code).await
/// }
/// }
/// # Ok(()) }
/// ```
pub async fn request_login_code_with_options(
&self,
phone: &str,
mut opts: SendCodeOptions,
) -> Result<SendCodeOutcome, InvocationError> {
// Auto-replay a future_auth_token captured by a previous sign_out()
// on this session, unless the caller already supplied their own.
if opts.logout_tokens.is_none()
&& let Some(token) = self.inner.future_auth_token.lock().clone()
{
tracing::debug!(
"[ferogram::auth] replaying stored future_auth_token from a previous sign_out"
);
opts.logout_tokens = Some(vec![token]);
}
tracing::info!("[ferogram::auth] not signed in; requesting login code from Telegram");
let req = self.make_send_code_req(phone, opts);
let body: Vec<u8> = self.rpc_call_raw(&req).await?;
self.handle_sent_code(phone, &body).await
}
/// Ask Telegram to resend the login code via a different delivery method.
///
/// `token` is the [`LoginToken`] from the original [`Client::request_login_code`]
/// call. `reason` is an optional client-side diagnostic string Telegram
/// may log (e.g. `"user did not receive code"`); pass `None` for the
/// default.
///
/// Like [`Client::request_login_code`], this can return
/// [`SendCodeOutcome::AlreadyAuthorized`] instead of a new code if
/// Telegram authorizes the session outright.
pub async fn resend_code(
&self,
token: &LoginToken,
reason: Option<&str>,
) -> Result<SendCodeOutcome, InvocationError> {
tracing::info!("[ferogram::auth] requesting a resend of the login code");
let req = tl::functions::auth::ResendCode {
phone_number: token.phone.clone(),
phone_code_hash: token.phone_code_hash.clone(),
reason: reason.map(str::to_string),
};
let body: Vec<u8> = self.rpc_call_raw(&req).await?;
self.handle_sent_code(&token.phone, &body).await
}
/// Decode an `auth.SentCode` response body and turn it into a
/// [`SendCodeOutcome`]. Shared by [`Client::request_login_code_with_options`]
/// and [`Client::resend_code`], both of which get this same response type
/// back from Telegram.
async fn handle_sent_code(
&self,
phone: &str,
body: &[u8],
) -> Result<SendCodeOutcome, InvocationError> {
use tl::enums::auth::{SentCode, SentCodeType};
let mut cur = Cursor::from_slice(body);
match tl::enums::auth::SentCode::deserialize(&mut cur)? {
SentCode::SentCode(s) => {
let sent_via = match &s.r#type {
SentCodeType::App(_) => {
"a Telegram message on another already-logged-in device/app \
(not SMS)"
}
SentCodeType::Sms(_) => "SMS",
SentCodeType::Call(_) => "a voice call reading out the code",
SentCodeType::FlashCall(_) => "a flash call (read the caller ID digits)",
SentCodeType::MissedCall(_) => "a missed call (read the last digits)",
SentCodeType::FragmentSms(_) => "Fragment SMS (fragment.com anonymous number)",
SentCodeType::FirebaseSms(_) => "SMS (Firebase-verified)",
SentCodeType::SmsWord(_) => "SMS (word code)",
SentCodeType::SmsPhrase(_) => "SMS (phrase code)",
SentCodeType::EmailCode(_) => "email",
SentCodeType::SetUpEmailRequired(_) => "email (setup required first)",
};
tracing::info!("[ferogram::auth] login code sent via {sent_via}");
tracing::debug!(
"[ferogram::auth] phone_code_hash acquired (len={})",
s.phone_code_hash.len()
);
Ok(SendCodeOutcome::CodeRequired(LoginToken {
phone: phone.to_string(),
phone_code_hash: s.phone_code_hash,
}))
}
SentCode::Success(s) => {
// Telegram recognized a logout token and authorized the session
// immediately, no code entry is needed.
tracing::info!(
"[ferogram::auth] sentCodeSuccess: session authorized via logout token"
);
// Consume the token: Telegram issues a fresh one on the next
// real sign_out, and holding onto a used one risks it being
// stale or rejected on a later attempt.
*self.inner.future_auth_token.lock() = None;
self.mark_session_snapshot_dirty();
match s.authorization {
tl::enums::auth::Authorization::Authorization(a) => {
self.cache_user(&a.user).await;
let name = Self::extract_user_name(&a.user);
tracing::info!(
"[ferogram::auth] fast re-auth complete; signed in: welcome, {name}"
);
self.inner
.signed_in
.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = self.sync_pts_state().await;
Ok(SendCodeOutcome::AlreadyAuthorized(name))
}
tl::enums::auth::Authorization::SignUpRequired(_) => {
Err(InvocationError::Deserialize(
"sentCodeSuccess returned SignUpRequired; account not registered"
.into(),
))
}
}
}
SentCode::PaymentRequired(_) => Err(InvocationError::Deserialize(
"payment required to send code".into(),
)),
}
}
/// Complete sign-in with the code sent to the phone.
pub async fn sign_in(&self, token: &LoginToken, code: &str) -> Result<String, SignInError> {
tracing::debug!("[ferogram::auth] submitting auth.signIn");
let req = tl::functions::auth::SignIn {
phone_number: token.phone.clone(),
phone_code_hash: token.phone_code_hash.clone(),
phone_code: Some(code.trim().to_string()),
email_verification: None,
};
let body = match self.rpc_call_raw(&req).await {
Ok(b) => b,
Err(e) if e.is("SESSION_PASSWORD_NEEDED") => {
tracing::info!("[ferogram::auth] 2FA password required");
let t = self.get_password_info().await.map_err(SignInError::Other)?;
return Err(SignInError::PasswordRequired(Box::new(t)));
}
Err(e) if e.is("PHONE_CODE_*") => {
tracing::warn!("[ferogram::auth] login code rejected: {e}");
return Err(SignInError::InvalidCode);
}
Err(e) => return Err(SignInError::Other(e)),
};
let mut cur = Cursor::from_slice(&body);
match tl::enums::auth::Authorization::deserialize(&mut cur)
.map_err(|e| SignInError::Other(e.into()))?
{
tl::enums::auth::Authorization::Authorization(a) => {
self.cache_user(&a.user).await;
let name = Self::extract_user_name(&a.user);
tracing::info!("[ferogram::auth] signed in: welcome, {name}");
self.inner
.signed_in
.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = self.sync_pts_state().await;
Ok(name)
}
tl::enums::auth::Authorization::SignUpRequired(_) => {
tracing::warn!(
"[ferogram::auth] phone number not registered on Telegram; sign-up required"
);
Err(SignInError::SignUpRequired)
}
}
}
/// Complete 2FA login.
pub async fn check_password(
&self,
token: PasswordToken,
password: impl AsRef<[u8]>,
) -> Result<String, InvocationError> {
tracing::debug!("[ferogram::auth] computing SRP 2FA proof");
let pw = token.password;
let algo = pw
.current_algo
.ok_or_else(|| InvocationError::Deserialize("no current_algo".into()))?;
let (salt1, salt2, p, g) = extract_password_params(&algo)?;
let g_b = pw
.srp_b
.ok_or_else(|| InvocationError::Deserialize("no srp_b".into()))?;
let a = pw.secure_random;
let srp_id = pw
.srp_id
.ok_or_else(|| InvocationError::Deserialize("no srp_id".into()))?;
let (m1, g_a) =
two_factor_auth::calculate_2fa(salt1, salt2, p, g, &g_b, &a, password.as_ref())
.map_err(|e| InvocationError::Deserialize(e.to_string()))?;
let req = tl::functions::auth::CheckPassword {
password: tl::enums::InputCheckPasswordSrp::InputCheckPasswordSrp(
tl::types::InputCheckPasswordSrp {
srp_id,
a: g_a.to_vec(),
m1: m1.to_vec(),
},
),
};
tracing::debug!("[ferogram::auth] submitting auth.checkPassword");
let body: Vec<u8> = self.rpc_call_raw(&req).await?;
let mut cur = Cursor::from_slice(&body);
match tl::enums::auth::Authorization::deserialize(&mut cur)? {
tl::enums::auth::Authorization::Authorization(a) => {
self.cache_user(&a.user).await;
let name = Self::extract_user_name(&a.user);
tracing::info!("[ferogram::auth] 2FA verified; signed in: welcome, {name}");
self.inner
.signed_in
.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = self.sync_pts_state().await;
Ok(name)
}
tl::enums::auth::Authorization::SignUpRequired(_) => Err(InvocationError::Deserialize(
"unexpected SignUpRequired after 2FA".into(),
)),
}
}
/// Sign out and invalidate the current session.
///
/// If Telegram returns a `future_auth_token`, it is stored in-memory and
/// included in the persisted session on the next [`Client::save_session`]
/// call. It is then included automatically on the next
/// [`Client::request_login_code`] call to skip code entry for this
/// device. Telegram omits the token when the account has 2FA enabled.
pub async fn sign_out(&self) -> Result<bool, InvocationError> {
let req = tl::functions::auth::LogOut {};
match self.rpc_call_raw(&req).await {
Ok(body) => {
let mut cur = Cursor::from_slice(&body);
match tl::enums::auth::LoggedOut::deserialize(&mut cur) {
Ok(tl::enums::auth::LoggedOut::LoggedOut(lo)) => {
if lo.future_auth_token.is_some() {
tracing::debug!(
"[ferogram::auth] received future_auth_token on logout"
);
}
*self.inner.future_auth_token.lock() = lo.future_auth_token;
self.mark_session_snapshot_dirty();
}
Err(e) => {
tracing::debug!(
"[ferogram::auth] could not parse auth.LoggedOut ({e}); \
future_auth_token unavailable this session"
);
}
}
tracing::info!("[ferogram::auth] signed out");
// Clear all pooled connections and cached auth keys so that
// stale sockets cannot survive logout/reset.
self.inner.dc_pool.lock().await.conns.clear();
self.inner.transfer_pool.lock().await.conns.clear();
{
let mut opts: tokio::sync::MutexGuard<
'_,
std::collections::HashMap<i32, DcEntry>,
> = self.inner.dc_options.lock().await;
for entry in opts.values_mut() {
entry.auth_key = None;
entry.first_salt = 0;
}
}
// Clear per-DC connect gates so fresh connections can be made after re-login.
self.inner.dc_connect_gates.lock().clear();
Ok(true)
}
Err(e) if e.is("AUTH_KEY_UNREGISTERED") => Ok(false),
Err(e) => Err(e),
}
}
/// Fetch user info by ID. Returns `None` for each ID that is not found.
///
/// Used internally by [`update::IncomingMessage::sender_user`].
pub async fn get_users_by_id(
&self,
ids: &[i64],
) -> Result<Vec<Option<crate::types::User>>, InvocationError> {
let cache: tokio::sync::RwLockReadGuard<'_, crate::PeerCache> =
self.inner.peer_cache.read().await;
let input_ids: Vec<tl::enums::InputUser> = ids
.iter()
.map(|&id| {
if id == 0 {
tl::enums::InputUser::UserSelf
} else {
let hash = cache.users.get(&id).copied().unwrap_or(0);
tl::enums::InputUser::InputUser(tl::types::InputUser {
user_id: id,
access_hash: hash,
})
}
})
.collect();
drop(cache);
let req = tl::functions::users::GetUsers { id: input_ids };
let body: Vec<u8> = self.rpc_call_raw(&req).await?;
let mut cur = Cursor::from_slice(&body);
let users = Vec::<tl::enums::User>::deserialize(&mut cur)?;
self.cache_users_slice(&users).await;
Ok(users
.into_iter()
.map(crate::types::User::from_raw)
.collect())
}
/// Resolve a user by message context (no access_hash required).
/// Returns `None` if Telegram returns no matching user.
pub async fn get_user_from_message(
&self,
peer: tl::enums::InputPeer,
msg_id: i32,
user_id: i64,
) -> Result<Option<tl::types::User>, InvocationError> {
let req = tl::functions::users::GetUsers {
id: vec![tl::enums::InputUser::FromMessage(
tl::types::InputUserFromMessage {
peer,
msg_id,
user_id,
},
)],
};
let body: Vec<u8> = self.rpc_call_raw(&req).await?;
let mut cur = Cursor::from_slice(&body);
let users = Vec::<tl::enums::User>::deserialize(&mut cur)?;
self.cache_users_slice(&users).await;
Ok(users.into_iter().find_map(|u| match u {
tl::enums::User::User(u) => Some(u),
_ => None,
}))
}
/// The logged-in account's numeric user ID, if already known.
///
/// This is a cheap, synchronous, no-network lookup of a value captured
/// automatically the first time a `User` object with `is_self == true`
/// was cached (sign-in, `get_me()`, etc.). Returns `None` only if neither
/// has happened yet in this session - call `my_id_or_fetch()` for a
/// version that falls back to a network call in that case.
pub fn my_id(&self) -> Option<i64> {
match self
.inner
.self_user_id
.load(std::sync::atomic::Ordering::Relaxed)
{
0 => None,
id => Some(id),
}
}
/// Like [`my_id`](Self::my_id), but performs a one-time `get_me()` call
/// to populate the cache if it isn't already known.
pub async fn my_id_or_fetch(&self) -> Result<i64, InvocationError> {
if let Some(id) = self.my_id() {
return Ok(id);
}
Ok(self.get_me().await?.id)
}
/// Fetch information about the logged-in user.
pub async fn get_me(&self) -> Result<tl::types::User, InvocationError> {
let req = tl::functions::users::GetUsers {
id: vec![tl::enums::InputUser::UserSelf],
};
let body: Vec<u8> = self.rpc_call_raw(&req).await?;
let mut cur = Cursor::from_slice(&body);
let users = Vec::<tl::enums::User>::deserialize(&mut cur)?;
self.cache_users_slice(&users).await;
users
.into_iter()
.find_map(|u| match u {
tl::enums::User::User(u) => Some(u),
_ => None,
})
.ok_or_else(|| InvocationError::Deserialize("getUsers returned no user".into()))
}
async fn get_password_info(&self) -> Result<PasswordToken, InvocationError> {
tracing::debug!("[ferogram::auth] fetching 2FA password parameters");
let body = self
.rpc_call_raw(&tl::functions::account::GetPassword {})
.await?;
let mut cur = Cursor::from_slice(&body);
let tl::enums::account::Password::Password(pw) =
tl::enums::account::Password::deserialize(&mut cur)?;
Ok(PasswordToken { password: pw })
}
fn make_send_code_req(
&self,
phone: &str,
opts: SendCodeOptions,
) -> tl::functions::auth::SendCode {
tl::functions::auth::SendCode {
phone_number: phone.to_string(),
api_id: self.inner.api_id,
api_hash: self.inner.api_hash.clone(),
settings: tl::enums::CodeSettings::CodeSettings(tl::types::CodeSettings {
allow_flashcall: opts.allow_flashcall,
current_number: opts.current_number,
allow_app_hash: opts.allow_app_hash,
allow_missed_call: opts.allow_missed_call,
allow_firebase: opts.allow_firebase,
unknown_number: opts.unknown_number,
logout_tokens: opts.logout_tokens,
token: opts.token,
app_sandbox: opts.app_sandbox,
}),
}
}
fn extract_user_name(user: &tl::enums::User) -> String {
match user {
tl::enums::User::User(u) => format!(
"{} {}",
u.first_name.as_deref().unwrap_or(""),
u.last_name.as_deref().unwrap_or("")
)
.trim()
.to_string(),
tl::enums::User::Empty(_) => "(unknown)".into(),
}
}
/// Generate a QR-code login token.
///
/// Returns `(token_bytes, expires_unix_ts)`. Encode `token_bytes` as a
/// `tg://login?token=<base64url>` URL and present as a QR code.
///
/// Call `import_qr_token` once the user scans it, then poll until you
/// receive `Update::Raw` with `updateLoginToken` (constructor `0x564fe691`),
/// or call `export_login_token` again to check.
///
/// # Example
/// ```rust,no_run
/// # use ferogram::Client;
/// # async fn ex(client: Client) -> Result<(), Box<dyn std::error::Error>> {
/// let (token, expires) = client.export_login_token().await?;
/// // base64url-encode `token` and make a QR code
/// # Ok(()) }
/// ```
pub async fn export_login_token(&self) -> Result<(Vec<u8>, i32), InvocationError> {
use ferogram_tl_types::{Cursor, Deserializable};
let req = tl::functions::auth::ExportLoginToken {
api_id: self.inner.api_id,
api_hash: self.inner.api_hash.clone(),
except_ids: vec![],
};
let body: Vec<u8> = self.rpc_call_raw(&req).await?;
let mut cur = Cursor::from_slice(&body);
match tl::enums::auth::LoginToken::deserialize(&mut cur)? {
tl::enums::auth::LoginToken::LoginToken(t) => Ok((t.token, t.expires)),
tl::enums::auth::LoginToken::MigrateTo(m) => {
// Migrate and retry
self.migrate_to(m.dc_id).await?;
let req2 = tl::functions::auth::ImportLoginToken { token: m.token };
let body2 = self.rpc_call_raw(&req2).await?;
let mut cur2 = Cursor::from_slice(&body2);
match tl::enums::auth::LoginToken::deserialize(&mut cur2)? {
tl::enums::auth::LoginToken::LoginToken(t) => Ok((t.token, t.expires)),
_ => Err(InvocationError::Deserialize(
"QR login: unexpected token state after migration".into(),
)),
}
}
tl::enums::auth::LoginToken::Success(s) => {
// Already authorised (user scanned before we called this)
if let tl::enums::auth::Authorization::Authorization(a) = s.authorization {
self.cache_user(&a.user).await;
Self::extract_user_name(&a.user);
self.inner
.signed_in
.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = self.sync_pts_state().await;
}
Ok((vec![], 0))
}
}
}
/// Check whether a QR-code token has been scanned.
///
/// Returns `Some(username)` if the user has scanned and confirmed the QR
/// code, or `None` if still pending.
pub async fn check_qr_login(&self, token: Vec<u8>) -> Result<Option<String>, InvocationError> {
use ferogram_tl_types::{Cursor, Deserializable};
let req = tl::functions::auth::ImportLoginToken { token };
let body: Vec<u8> = self.rpc_call_raw(&req).await?;
let mut cur = Cursor::from_slice(&body);
match tl::enums::auth::LoginToken::deserialize(&mut cur)? {
tl::enums::auth::LoginToken::Success(s) => {
if let tl::enums::auth::Authorization::Authorization(a) = s.authorization {
self.cache_user(&a.user).await;
let name = Self::extract_user_name(&a.user);
self.inner
.signed_in
.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = self.sync_pts_state().await;
Ok(Some(name))
} else {
Ok(None)
}
}
_ => Ok(None),
}
}
}
// Helper: extract SRP parameters from a PasswordKdfAlgo.
#[allow(clippy::type_complexity)]
fn extract_password_params(
algo: &tl::enums::PasswordKdfAlgo,
) -> Result<(&[u8], &[u8], &[u8], i32), InvocationError> {
// Match the SHA256^2 + PBKDF2 + ModPow variant (only non-Unknown variant)
match algo {
tl::enums::PasswordKdfAlgo::Sha256Sha256Pbkdf2Hmacsha512iter100000Sha256ModPow(a) => {
Ok((&a.salt1, &a.salt2, &a.p, a.g))
}
_ => Err(InvocationError::Deserialize("unknown 2FA algo".into())),
}
}