1#[path = "group_mutation.rs"]
2mod group_mutation;
3pub use group_mutation::*;
4#[path = "group_detail.rs"]
5mod group_detail;
6pub use group_detail::*;
7#[path = "group_inventory.rs"]
8mod group_inventory;
9pub use group_inventory::*;
10#[path = "account.rs"]
11mod account;
12#[path = "channels.rs"]
13mod channels;
14#[path = "logout.rs"]
15mod logout;
16#[path = "revoke.rs"]
17mod revoke;
18#[path = "status_notify.rs"]
19mod status_notify;
20use crate::errors::{Service, ServiceRejected};
21pub use crate::wire::{
22 AddMessage, AvatarBytes, ContactLookup, ContactRecord, Heartbeat, InitContactPage, RoomMember,
23 RoomRoster, SyncBatch, SyncCommand, TextSendResult, VoiceChunk,
24};
25use crate::{
26 business::{self, AuthenticatedPacket, Prelogin},
27 crypto::Ecdh,
28 mmtls::{self, Session},
29 protobuf as p, wire,
30};
31pub use account::{
32 AccountIdentity, AccountLease, AccountLifecycle, AccountPersistence, AccountPersistenceFailed,
33 AccountPushConnection, AccountRequest, AccountStatus, NativeRequestNotSubmitted, PendingLogout,
34 TextSendOptions,
35};
36use anyhow::{bail, ensure, Result};
37pub use channels::{ChannelsMedia, ChannelsPage, ChannelsPost, ChannelsTicket};
38pub use logout::*;
39use openssl::{nid::Nid, pkey::PKey, rsa::Rsa};
40pub use revoke::*;
41use serde::{Deserialize, Serialize};
42pub use status_notify::*;
43use std::{fmt, time::Duration};
44use zeroize::Zeroize;
45
46#[derive(Clone, Serialize, Deserialize)]
47#[serde(deny_unknown_fields)]
48pub struct DeviceProfile {
49 pub device_id: Vec<u8>,
50 pub device_type: String,
51 pub client_version: i32,
52}
53impl fmt::Debug for DeviceProfile {
54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55 f.debug_struct("DeviceProfile")
56 .field("device_id", &"[redacted]")
57 .field("device_type", &self.device_type)
58 .field("client_version", &self.client_version)
59 .finish()
60 }
61}
62impl DeviceProfile {
63 pub fn generate(device_type: String) -> Result<Self> {
64 let bytes = crate::crypto::random::<16>()?;
65 let id = format!("l{}", hex::encode(bytes)).into_bytes()[..16].to_vec();
66 let p = Self {
67 device_id: id,
68 device_type,
69 client_version: -227271398,
70 };
71 p.validate()?;
72 Ok(p)
73 }
74 pub fn validate(&self) -> Result<()> {
75 ensure!(
76 self.device_id.len() == 16
77 && !self.device_type.is_empty()
78 && self.device_type.len() <= 1024
79 && !self.device_type.contains('\0'),
80 "Invalid native device profile"
81 );
82 ensure!(
83 self.client_version == -227271398,
84 "Unsupported native client version"
85 );
86 Ok(())
87 }
88}
89#[derive(Clone, Default, Serialize, Deserialize)]
93#[serde(deny_unknown_fields)]
94pub struct AuthSnapshot {
95 pub update_mask: u32,
96 pub response: Vec<u8>,
97 pub auth: Vec<u8>,
98 pub account: Vec<u8>,
99 pub network: Vec<u8>,
100 pub ax_auth: Vec<u8>,
101}
102impl fmt::Debug for AuthSnapshot {
103 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 f.debug_struct("AuthSnapshot")
105 .field("sections", &"[redacted]")
106 .finish()
107 }
108}
109impl Drop for AuthSnapshot {
110 fn drop(&mut self) {
111 self.response.zeroize();
112 self.auth.zeroize();
113 self.account.zeroize();
114 self.network.zeroize();
115 self.ax_auth.zeroize();
116 }
117}
118#[derive(Clone, Serialize, Deserialize)]
120#[serde(deny_unknown_fields)]
121pub struct AccountState {
122 pub schema: u32,
123 pub device: DeviceProfile,
124 pub uin: u32,
125 pub own_username: String,
126 pub cookie: Vec<u8>,
127 pub session_key: Vec<u8>,
128 pub request_key: Vec<u8>,
129 pub response_key: Vec<u8>,
130 pub auto_auth_key: Vec<u8>,
131 pub key_info: Vec<u8>,
132 #[serde(default)]
135 pub database_password: Vec<u8>,
136 #[serde(default)]
137 pub auth_snapshot: AuthSnapshot,
138 pub long_host: String,
139 pub short_host: String,
140}
141impl fmt::Debug for AccountState {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.debug_struct("AccountState")
144 .field("schema", &self.schema)
145 .field("credentials", &"[redacted]")
146 .finish()
147 }
148}
149impl Drop for AccountState {
150 fn drop(&mut self) {
151 self.cookie.zeroize();
152 self.session_key.zeroize();
153 self.request_key.zeroize();
154 self.response_key.zeroize();
155 self.auto_auth_key.zeroize();
156 self.key_info.zeroize();
157 self.database_password.zeroize();
158 }
159}
160impl AccountState {
161 pub fn validate(&self) -> Result<()> {
162 ensure!(
163 self.schema == 1
164 && self.uin != 0
165 && !self.own_username.is_empty()
166 && self.own_username.len() <= 256
167 && !self.own_username.contains('\0'),
168 "Invalid native account identity"
169 );
170 self.device.validate()?;
171 mmtls::validate_host(&self.long_host)?;
172 mmtls::validate_host(&self.short_host)?;
173 ensure!(
174 self.cookie.len() <= 15
175 && self.session_key.len() == 16
176 && ((self.request_key.is_empty() && self.response_key.is_empty())
177 || (self.request_key.len() == 24 && self.response_key.len() == 24))
178 && self.auto_auth_key.len() <= 1024 * 1024
179 && self.key_info.len() <= 1024 * 1024
180 && (self.database_password.is_empty() || self.database_password.len() == 32)
181 && [
182 &self.auth_snapshot.response,
183 &self.auth_snapshot.auth,
184 &self.auth_snapshot.account,
185 &self.auth_snapshot.network,
186 &self.auth_snapshot.ax_auth
187 ]
188 .iter()
189 .all(|v| v.len() <= 1024 * 1024),
190 "Invalid native account keys"
191 );
192 Ok(())
193 }
194}
195impl AccountState {
196 pub fn from_baseline_json(input: &[u8]) -> Result<Self> {
200 use base64::{engine::general_purpose::STANDARD, Engine};
201 ensure!(
202 input.len() <= 8 * 1024 * 1024,
203 "Baseline checkpoint too large"
204 );
205 let value: serde_json::Value = serde_json::from_slice(input)
206 .map_err(|_| anyhow::anyhow!("Invalid baseline checkpoint JSON"))?;
207 let object = value
208 .as_object()
209 .ok_or_else(|| anyhow::anyhow!("Invalid baseline checkpoint object"))?;
210 let string = |name: &str| -> Result<String> {
211 object
212 .get(name)
213 .and_then(|v| v.as_str())
214 .map(str::to_string)
215 .ok_or_else(|| anyhow::anyhow!("Missing baseline field {name}"))
216 };
217 let decode = |name: &str, required: bool| -> Result<Vec<u8>> {
218 let encoded = match object.get(name) {
219 Some(v) => v
220 .as_str()
221 .ok_or_else(|| anyhow::anyhow!("Invalid baseline field {name}"))?,
222 None if !required => "",
223 _ => bail!("Missing baseline field {name}"),
224 };
225 let bytes = STANDARD
226 .decode(encoded)
227 .map_err(|_| anyhow::anyhow!("Invalid baseline encoding {name}"))?;
228 ensure!(
229 STANDARD.encode(&bytes) == encoded,
230 "Noncanonical baseline encoding {name}"
231 );
232 Ok(bytes)
233 };
234 ensure!(
235 object.get("schema").and_then(|v| v.as_u64()) == Some(1),
236 "Unsupported baseline schema"
237 );
238 let uin = match object.get("uin") {
239 Some(serde_json::Value::String(s)) => s
240 .parse::<u32>()
241 .map_err(|_| anyhow::anyhow!("Invalid baseline UIN"))?,
242 Some(n) => u32::try_from(
243 n.as_u64()
244 .ok_or_else(|| anyhow::anyhow!("Invalid baseline UIN"))?,
245 )?,
246 None => bail!("Missing baseline UIN"),
247 };
248 let account = decode("accountSect", false)?;
249 let section_username = if account.is_empty() {
250 None
251 } else {
252 let f = p::decode(&account)?;
253 p::optional_data(&f, 1)?
254 .map(|v| std::str::from_utf8(v).map(str::to_string))
255 .transpose()
256 .map_err(|_| anyhow::anyhow!("Invalid baseline account username"))?
257 };
258 let own_username = object
259 .get("ownUsername")
260 .or_else(|| object.get("username"))
261 .map(|v| {
262 v.as_str()
263 .map(str::to_string)
264 .ok_or_else(|| anyhow::anyhow!("Invalid baseline username"))
265 })
266 .transpose()?
267 .or(section_username.clone())
268 .ok_or_else(|| anyhow::anyhow!("Missing baseline account identity"))?;
269 ensure!(
270 section_username.is_none_or(|s| s == own_username),
271 "Baseline account identity mismatch"
272 );
273 let state =
274 Self {
275 schema: 1,
276 device: DeviceProfile {
277 device_id: decode("deviceId", true)?,
278 device_type: string("deviceType")?,
279 client_version: i32::try_from(
280 object
281 .get("clientVersion")
282 .and_then(|v| v.as_i64())
283 .ok_or_else(|| anyhow::anyhow!("Invalid baseline client version"))?,
284 )?,
285 },
286 uin,
287 own_username,
288 cookie: decode("cookie", false)?,
289 session_key: decode("sessionKey", true)?,
290 request_key: decode("field23", false)?,
291 response_key: decode("field24", false)?,
292 auto_auth_key: decode("autoAuthKey", false)?,
293 key_info: decode("keyInfo", false)?,
294 database_password: decode("databasePassword", false)?,
295 auth_snapshot: AuthSnapshot {
296 update_mask: match object.get("authSections") {
297 Some(serde_json::Value::String(value)) => value.parse()?,
298 Some(value) => u32::try_from(value.as_u64().ok_or_else(|| {
299 anyhow::anyhow!("Invalid baseline auth section mask")
300 })?)?,
301 None => 0,
302 },
303 response: decode("authResponse", false)?,
304 auth: decode("authSect", false)?,
305 account,
306 network: decode("networkSect", false)?,
307 ax_auth: decode("axAuthSect", false)?,
308 },
309 long_host: object
310 .get("longHost")
311 .and_then(|v| v.as_str())
312 .unwrap_or("long.weixin.qq.com")
313 .to_string(),
314 short_host: object
315 .get("shortHost")
316 .and_then(|v| v.as_str())
317 .unwrap_or("short.weixin.qq.com")
318 .to_string(),
319 };
320 state.validate()?;
321 Ok(state)
322 }
323}
324
325#[derive(Clone, Serialize, Deserialize)]
326#[serde(deny_unknown_fields)]
327pub struct LoginAttempt {
328 pub schema: u32,
329 pub device: DeviceProfile,
330 pub computer_name: String,
331 pub qr_png: Vec<u8>,
332 pub width: u32,
333 pub height: u32,
334 pub created_at: u32,
335 pub expires_at: u32,
336 pub identifier: Vec<u8>,
337 pub notify_key: Vec<u8>,
338 pub cookie: Vec<u8>,
339 pub key_version: u16,
340 pub long_host: String,
341 pub short_host: String,
342 pub status: LoginStatus,
343 #[serde(default)]
344 key_info: Vec<u8>,
345 credential3: Option<Vec<u8>>,
346 credential4: Option<Vec<u8>>,
347 #[serde(default)]
348 lan_upload_attempted: bool,
349 #[serde(skip)]
351 lan_challenge: Option<std::sync::Arc<crate::lan_login::Challenge>>,
352}
353impl fmt::Debug for LoginAttempt {
354 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355 f.debug_struct("LoginAttempt")
356 .field("status", &self.status)
357 .field("created_at", &self.created_at)
358 .field("expires_at", &self.expires_at)
359 .field("credentials", &"[redacted]")
360 .finish()
361 }
362}
363impl Drop for LoginAttempt {
364 fn drop(&mut self) {
365 self.stop_lan_login();
366 self.identifier.zeroize();
367 self.notify_key.zeroize();
368 self.cookie.zeroize();
369 self.key_info.zeroize();
370 self.credential3.zeroize();
371 self.credential4.zeroize();
372 }
373}
374impl LoginAttempt {
375 pub fn lan_login_state(&self) -> Option<&'static str> {
376 self.lan_challenge
377 .as_ref()
378 .map(|challenge| challenge.status())
379 }
380 fn stop_lan_login(&mut self) {
381 if let Some(challenge) = self.lan_challenge.take() {
382 challenge.stop();
383 }
384 }
385 pub fn qr_svg(&self) -> Result<String> {
386 use base64::Engine;
387 ensure!(
388 !self.qr_png.is_empty(),
389 "This saved-device attempt has no QR"
390 );
391 let encoded = base64::engine::general_purpose::STANDARD.encode(&self.qr_png);
392 Ok(format!("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"530\" height=\"530\" viewBox=\"0 0 265 265\"><rect width=\"265\" height=\"265\" fill=\"white\"/><image x=\"40\" y=\"40\" width=\"185\" height=\"185\" style=\"image-rendering:pixelated\" href=\"data:image/png;base64,{encoded}\"/></svg>"))
393 }
394 fn validate(&self) -> Result<()> {
395 self.validate_at(wire::unix_time()?)
396 }
397 fn locally_expired(&self, now: u32) -> bool {
398 let hard_deadline = self.created_at.saturating_add(900);
401 let deadline = if self.qr_png.is_empty()
402 || matches!(self.status, LoginStatus::Scanned | LoginStatus::Approved)
403 {
404 hard_deadline
405 } else {
406 self.expires_at.min(hard_deadline)
407 };
408 now >= deadline
409 }
410 fn validate_at(&self, now: u32) -> Result<()> {
411 ensure!(
412 self.schema == 1 && !self.locally_expired(now),
413 "Login attempt expired"
414 );
415 self.device.validate()?;
416 ensure!(
417 !self.identifier.is_empty()
418 && self.identifier.len() <= 4096
419 && !self.notify_key.is_empty()
420 && self.notify_key.len() <= 1024
421 && self.cookie.len() <= 15
422 && self.key_info.len() <= 1024 * 1024,
423 "Invalid login attempt"
424 );
425 mmtls::validate_host(&self.long_host)?;
426 mmtls::validate_host(&self.short_host)?;
427 ensure!(
428 [10014, 50005].contains(&self.key_version),
429 "Unsupported login key version"
430 );
431 Ok(())
432 }
433 fn manual_auth_request(&self, point: &[u8]) -> Result<Vec<u8>> {
434 wire::manual_auth(
435 &self.device,
436 &self.computer_name,
437 self.credential3
438 .as_deref()
439 .ok_or_else(|| anyhow::anyhow!("Missing approval"))?,
440 self.credential4
441 .as_deref()
442 .ok_or_else(|| anyhow::anyhow!("Missing approval"))?,
443 point,
444 &self.key_info,
445 )
446 }
447}
448#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
449#[serde(rename_all = "snake_case")]
450pub enum LoginStatus {
451 Pending,
452 Scanned,
453 Approved,
454 Expired,
455 Cancelled,
456 Rejected,
457 Completed,
458}
459#[derive(Clone, Debug)]
460pub struct NativeOptions {
461 pub long_host: String,
462 pub short_host: String,
463 pub timeout: Duration,
464 pub receive_budget: usize,
465}
466impl Default for NativeOptions {
467 fn default() -> Self {
468 Self {
469 long_host: "long.weixin.qq.com".to_string(),
470 short_host: "short.weixin.qq.com".to_string(),
471 timeout: Duration::from_secs(30),
472 receive_budget: crate::MAX_MESSAGE_BYTES,
473 }
474 }
475}
476#[derive(Clone)]
485pub struct NativeClient {
486 options: NativeOptions,
487 account: Option<std::sync::Arc<account::OwnedAccount>>,
488 submission_guard: Option<std::sync::Arc<dyn Fn() -> Result<()> + Send + Sync>>,
489 call_reply_observer: Option<std::sync::Arc<CallReplyObserver>>,
490 short_link: Option<std::sync::Arc<mmtls::ShortLinkCache>>,
492}
493type CallReplyObserver = dyn Fn(&[u8]) -> Result<()> + Send + Sync;
494pub fn is_retryable_login_poll_error(error: &anyhow::Error) -> bool {
497 if crate::login_lan_error_reason(error).is_some() {
498 return false;
499 }
500 error.chain().any(|cause| {
501 if let Some(io) = cause.downcast_ref::<std::io::Error>() {
502 return matches!(
503 io.kind(),
504 std::io::ErrorKind::TimedOut
505 | std::io::ErrorKind::WouldBlock
506 | std::io::ErrorKind::ConnectionReset
507 | std::io::ErrorKind::ConnectionAborted
508 | std::io::ErrorKind::ConnectionRefused
509 | std::io::ErrorKind::UnexpectedEof
510 | std::io::ErrorKind::BrokenPipe
511 | std::io::ErrorKind::NotConnected
512 );
513 }
514 if let Some(http) = cause.downcast_ref::<reqwest::Error>() {
515 return http.is_timeout() || http.is_connect();
516 }
517 let message = cause.to_string();
518 matches!(
519 message.as_str(),
520 "MMTLS deadline exceeded" | "MMTLS connection closed"
521 ) || message
522 .strip_prefix("Native shortlink HTTP status ")
523 .and_then(|s| s.parse::<u16>().ok())
524 .is_some_and(|status| matches!(status, 408 | 429 | 500 | 502 | 503 | 504))
525 })
526}
527impl NativeClient {
528 pub fn new(options: NativeOptions) -> Result<Self> {
530 mmtls::validate_host(&options.long_host)?;
531 mmtls::validate_host(&options.short_host)?;
532 ensure!(
533 !options.timeout.is_zero() && options.timeout <= Duration::from_secs(120),
534 "Invalid native timeout"
535 );
536 ensure!(
537 (1024..=crate::MAX_MESSAGE_BYTES).contains(&options.receive_budget),
538 "Invalid receive budget"
539 );
540 Ok(Self {
541 options,
542 account: None,
543 submission_guard: None,
544 call_reply_observer: None,
545 short_link: None,
546 })
547 }
548 fn session(&self, host: &str) -> Result<Session> {
549 self.check_snapshot_transport()?;
550 Session::connect(host, self.options.timeout, self.options.receive_budget)
551 }
552 fn short_session(&self, host: &str) -> Result<mmtls::ShortSession> {
556 if let Some(short) = self.short_link.as_ref().and_then(|cache| cache.get(host)) {
557 self.check_snapshot_transport()?;
558 return Ok(short);
559 }
560 let short = self.session(host)?.short.clone();
561 if let Some(cache) = &self.short_link {
562 cache.put(host, short.clone());
563 }
564 Ok(short)
565 }
566 #[allow(clippy::too_many_arguments)]
567 fn prelogin_rpc(
568 &self,
569 long_host: &str,
570 short_host: &str,
571 cgi: u16,
572 path: &str,
573 plain: &[u8],
574 cookie: &[u8],
575 auth_key: &[u8],
576 fixed_version: Option<u16>,
577 ) -> Result<(Vec<u8>, Vec<u8>, u16)> {
578 let session = self.session(long_host)?;
579 let profile = if let Some(version) = fixed_version {
580 business::profile_for_region(if version == 50005 { 2 } else { 1 })?
581 } else {
582 business::profile_for_region(session.certificate_region)?
583 };
584 let prepared = Prelogin::prepare(plain, &profile, auth_key)?;
585 let packet = business::prelogin_packet(&prepared, cgi, profile.version, cookie)?;
586 self.check_submission()?;
587 let reply = mmtls::short_exchange(
588 &session.short,
589 short_host,
590 path,
591 &packet,
592 self.options.timeout,
593 )?;
594 let envelope = business::split(&reply)?;
595 ServiceRejected::check(Service::NativeEnvelope, envelope.return_code)?;
596 ensure!(
597 envelope.cgi == cgi as u64 && envelope.encryption == 12,
598 "Unexpected prelogin response policy"
599 );
600 let plain = prepared.decrypt_reply(&envelope.payload)?;
601 Ok((plain, envelope.cookie, profile.version))
602 }
603 pub fn start_qr_login(
607 &self,
608 device: DeviceProfile,
609 computer_name: &str,
610 ) -> Result<LoginAttempt> {
611 self.start_profile_qr_login(device, computer_name, &[])
612 }
613 pub fn start_profile_qr_login(
616 &self,
617 device: DeviceProfile,
618 computer_name: &str,
619 key_info: &[u8],
620 ) -> Result<LoginAttempt> {
621 device.validate()?;
622 ensure!(key_info.len() <= 1024 * 1024, "Invalid saved key-info");
623 let plain = wire::qr_request(&device, computer_name)?;
624 let (reply, cookie, key_version) = self.prelogin_rpc(
625 &self.options.long_host,
626 &self.options.short_host,
627 502,
628 "/cgi-bin/micromsg-bin/getloginqrcode",
629 &plain,
630 &[],
631 &[],
632 None,
633 )?;
634 let qr = wire::decode_qr(&reply)?;
635 let now = wire::unix_time()?;
636 Ok(LoginAttempt {
637 schema: 1,
638 device,
639 computer_name: computer_name.to_string(),
640 qr_png: qr.image,
641 width: qr.width,
642 height: qr.height,
643 created_at: now,
644 expires_at: now.saturating_add(240),
645 identifier: qr.identifier,
646 notify_key: qr.notify_key,
647 cookie,
648 key_version,
649 long_host: self.options.long_host.clone(),
650 short_host: self.options.short_host.clone(),
651 status: LoginStatus::Pending,
652 key_info: key_info.to_vec(),
653 credential3: None,
654 credential4: None,
655 lan_upload_attempted: false,
656 lan_challenge: None,
657 })
658 }
659 pub fn start_saved_device_login(
662 &self,
663 state: &AccountState,
664 computer_name: &str,
665 ) -> Result<LoginAttempt> {
666 state.validate()?;
667 self.start_saved_login(
668 &state.device,
669 &state.own_username,
670 &state.auto_auth_key,
671 &state.cookie,
672 &state.key_info,
673 &state.long_host,
674 &state.short_host,
675 computer_name,
676 )
677 }
678 pub fn start_profile_saved_device_login(
680 &self,
681 device: &DeviceProfile,
682 username: &str,
683 auto_auth_key: &[u8],
684 cookie: &[u8],
685 key_info: &[u8],
686 computer_name: &str,
687 ) -> Result<LoginAttempt> {
688 self.start_saved_login(
689 device,
690 username,
691 auto_auth_key,
692 cookie,
693 key_info,
694 &self.options.long_host,
695 &self.options.short_host,
696 computer_name,
697 )
698 }
699 #[allow(clippy::too_many_arguments)]
700 fn start_saved_login(
701 &self,
702 device: &DeviceProfile,
703 username: &str,
704 auto_auth_key: &[u8],
705 cookie: &[u8],
706 key_info: &[u8],
707 long_host: &str,
708 short_host: &str,
709 computer_name: &str,
710 ) -> Result<LoginAttempt> {
711 device.validate()?;
712 ensure!(
713 !username.is_empty()
714 && username.len() <= 256
715 && !username.contains('\0')
716 && !auto_auth_key.is_empty()
717 && auto_auth_key.len() <= 1024 * 1024
718 && cookie.len() <= 15
719 && key_info.len() <= 1024 * 1024,
720 "Invalid saved-device credentials"
721 );
722 let rsa = Rsa::generate(1024)?;
723 let public = PKey::from_rsa(rsa)?.public_key_to_pem()?;
724 let request = wire::push_login(device, username, auto_auth_key, &public)?;
725 let (reply, cookie, key_version) = self.prelogin_rpc(
726 long_host,
727 short_host,
728 654,
729 "/cgi-bin/micromsg-bin/pushloginurl",
730 &request,
731 cookie,
732 &[],
733 None,
734 )?;
735 let (identifier, notify_key) = wire::decode_push(&reply)?;
736 let now = wire::unix_time()?;
737 Ok(LoginAttempt {
738 schema: 1,
739 device: device.clone(),
740 computer_name: computer_name.to_string(),
741 qr_png: vec![],
742 width: 0,
743 height: 0,
744 created_at: now,
745 expires_at: now.saturating_add(240),
746 identifier,
747 notify_key,
748 cookie,
749 key_version,
750 long_host: long_host.into(),
751 short_host: short_host.into(),
752 status: LoginStatus::Pending,
753 key_info: key_info.to_vec(),
754 credential3: None,
755 credential4: None,
756 lan_upload_attempted: false,
757 lan_challenge: None,
758 })
759 }
760 pub fn poll_login(&self, attempt: &mut LoginAttempt) -> Result<LoginStatus> {
763 self.poll_login_guarded(
764 attempt,
765 std::time::Instant::now() + Duration::from_secs(900),
766 || false,
767 )
768 }
769 pub fn poll_login_guarded(
772 &self,
773 attempt: &mut LoginAttempt,
774 deadline: std::time::Instant,
775 cancelled: impl Fn() -> bool + Send + Sync + 'static,
776 ) -> Result<LoginStatus> {
777 let now = wire::unix_time()?;
778 if attempt.locally_expired(now) {
779 attempt.stop_lan_login();
780 attempt.status = LoginStatus::Expired;
781 return Ok(attempt.status);
782 }
783 attempt.validate_at(now)?;
784 ensure!(
785 !matches!(
786 attempt.status,
787 LoginStatus::Completed | LoginStatus::Cancelled | LoginStatus::Rejected
788 ),
789 "Login attempt is terminal"
790 );
791 let request = wire::poll_request(&attempt.device, &attempt.identifier)?;
792 let (reply, cookie, _) = self.prelogin_rpc(
793 &attempt.long_host,
794 &attempt.short_host,
795 503,
796 "/cgi-bin/micromsg-bin/checkloginqrcode",
797 &request,
798 &attempt.cookie,
799 &[],
800 Some(attempt.key_version),
801 )?;
802 let response = wire::decode_poll(&reply, &attempt.notify_key)?;
803 if !cookie.is_empty() {
804 attempt.cookie = cookie;
805 }
806 let remaining = attempt
807 .created_at
808 .saturating_add(900)
809 .saturating_sub(wire::unix_time()?);
810 let deadline =
811 deadline.min(std::time::Instant::now() + Duration::from_secs(u64::from(remaining)));
812 let scope = crate::lan_login::Scope::new(deadline, cancelled);
813 apply_login_notification(attempt, response, |attempt| {
814 self.start_lan_login(attempt, scope)
815 })
816 }
817 fn start_lan_login(
818 &self,
819 attempt: &mut LoginAttempt,
820 scope: crate::lan_login::Scope,
821 ) -> Result<std::sync::Arc<crate::lan_login::Challenge>> {
822 use crate::lan_login as lan;
823 let challenge = std::sync::Arc::new(lan::Challenge::bind(scope)?);
824 let random = zeroize::Zeroizing::new(crate::crypto::random::<16>()?);
825 let request = zeroize::Zeroizing::new(challenge.request(
826 &attempt.device,
827 &attempt.identifier,
828 &random,
829 )?);
830 let (reply, cookie, _) = self
831 .prelogin_rpc(
832 &attempt.long_host,
833 &attempt.short_host,
834 lan::CGI,
835 lan::PATH,
836 &request,
837 &attempt.cookie,
838 &[],
839 Some(attempt.key_version),
840 )
841 .map_err(|_| lan::failure("upload_failed"))?;
842 let reply = zeroize::Zeroizing::new(reply);
843 let token =
844 lan::response(&reply).map_err(|_| lan::failure("upload_rejected_or_invalid"))?;
845 challenge.arm(&token)?;
846 if !cookie.is_empty() {
847 attempt.cookie = cookie;
848 }
849 Ok(challenge)
850 }
851 pub fn complete_login(&self, attempt: &mut LoginAttempt) -> Result<AccountState> {
854 attempt.stop_lan_login();
855 attempt.validate()?;
856 ensure!(
857 attempt.status == LoginStatus::Approved,
858 "Login has not been approved"
859 );
860 let inner = Ecdh::generate(Nid::SECP224R1)?;
861 let request = attempt.manual_auth_request(&inner.public()?)?;
862 let mut long_host = attempt.long_host.clone();
863 let mut short_host = attempt.short_host.clone();
864 let mut cookie = attempt.cookie.clone();
865 for redirected in 0..=1 {
866 let (reply, next_cookie, _) = self.prelogin_rpc(
867 &long_host,
868 &short_host,
869 252,
870 "/cgi-bin/micromsg-bin/secmanualauth",
871 &request,
872 &cookie,
873 &[],
874 None,
875 )?;
876 let fields = p::decode(&reply)?;
877 let code = p::base_code(&fields)?;
878 if code == -301 && redirected == 0 {
879 (long_host, short_host) = redirect(&fields)?;
880 cookie = next_cookie;
881 continue;
882 }
883 ServiceRejected::check(Service::AccountAuthentication, code)?;
884 let mut state = reduce_auth(&reply, None, &inner, &attempt.device, &next_cookie)?;
885 state.long_host = long_host;
886 state.short_host = short_host;
887 state.validate()?;
888 attempt.status = LoginStatus::Completed;
889 attempt.credential3.zeroize();
890 attempt.credential4.zeroize();
891 return Ok(state);
892 }
893 bail!("Native authentication redirect limit reached")
894 }
895 pub fn refresh_qr_login(&self, attempt: &LoginAttempt) -> Result<LoginAttempt> {
897 ensure!(
898 attempt.status == LoginStatus::Expired && !attempt.qr_png.is_empty(),
899 "Only an expired QR may be refreshed"
900 );
901 let options = NativeOptions {
902 long_host: attempt.long_host.clone(),
903 short_host: attempt.short_host.clone(),
904 ..self.options.clone()
905 };
906 Self::new(options)?.start_profile_qr_login(
907 attempt.device.clone(),
908 &attempt.computer_name,
909 &attempt.key_info,
910 )
911 }
912 #[doc(hidden)]
915 pub(crate) fn renew_session_snapshot(
916 &self,
917 previous: &AccountState,
918 computer_name: &str,
919 ) -> Result<AccountState> {
920 previous.validate()?;
921 let inner = Ecdh::generate(Nid::SECP224R1)?;
922 let request = wire::auto_auth(previous, &inner.public()?, computer_name)?;
923 let mut long = previous.long_host.clone();
924 let mut short = previous.short_host.clone();
925 let mut cookie = previous.cookie.clone();
926 for redirected in 0..=1 {
927 let (reply, next_cookie, _) = self.prelogin_rpc(
928 &long,
929 &short,
930 763,
931 "/cgi-bin/micromsg-bin/secautoauth",
932 &request,
933 &cookie,
934 &previous.auto_auth_key,
935 None,
936 )?;
937 let fields = p::decode(&reply)?;
938 let code = p::base_code(&fields)?;
939 if code == -301 && redirected == 0 {
940 (long, short) = redirect(&fields)?;
941 cookie = next_cookie;
942 continue;
943 }
944 ServiceRejected::check(Service::AutomaticAuthentication, code)?;
945 let mut next = reduce_auth(
946 &reply,
947 Some(previous),
948 &inner,
949 &previous.device,
950 &next_cookie,
951 )?;
952 next.long_host = long;
953 next.short_host = short;
954 next.validate()?;
955 return Ok(next);
956 }
957 bail!("AutoAuth redirect limit reached")
958 }
959 pub(crate) fn call_rpc_snapshot_guarded(
964 &self,
965 state: &mut AccountState,
966 route: crate::calls::host_policy::CallHostRoute,
967 request: &[u8],
968 before_submit: impl FnOnce() -> Result<()>,
969 ) -> Result<Vec<u8>> {
970 self.call_rpc_with_exchange(state, route, request, before_submit, mmtls::short_exchange)
971 }
972
973 #[doc(hidden)]
977 pub(crate) fn call_live_sync_snapshot_with_wait_timeout(
978 &self,
979 state: &mut AccountState,
980 request: &[u8],
981 wait_timeout: Duration,
982 before_submit: impl FnOnce() -> Result<()>,
983 wait: impl for<'a> FnOnce(
984 std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + 'a>>,
985 ) -> Result<Vec<u8>>,
986 ) -> Result<Vec<u8>> {
987 ensure!(
988 !wait_timeout.is_zero() && wait_timeout <= Duration::from_secs(120),
989 "Invalid call poll wait timeout"
990 );
991 self.call_rpc_with_exchange(
992 state,
993 crate::calls::host_policy::CallHostRoute::LiveSync,
994 request,
995 before_submit,
996 |session, host, path, payload, _| {
997 wait(Box::pin(mmtls::short_exchange_interruptible(
998 session,
999 host,
1000 path,
1001 payload,
1002 wait_timeout,
1003 )))
1004 },
1005 )
1006 }
1007
1008 fn call_rpc_with_exchange(
1009 &self,
1010 state: &mut AccountState,
1011 route: crate::calls::host_policy::CallHostRoute,
1012 request: &[u8],
1013 before_submit: impl FnOnce() -> Result<()>,
1014 exchange: impl FnOnce(&mmtls::ShortSession, &str, &str, &[u8], Duration) -> Result<Vec<u8>>,
1015 ) -> Result<Vec<u8>> {
1016 use crate::calls::{
1017 host_policy::{selected_policy, CallHostPolicy},
1018 host_transport::{CallHostRpcError, CallHostStage},
1019 };
1020 self.check_snapshot_transport()?;
1021 mmtls::validate_short_route(route.path())
1022 .map_err(|error| CallHostRpcError::from_cause(CallHostStage::Route, &error))?;
1023 let policy = selected_policy(&state.auth_snapshot, route.command())
1024 .map_err(|_| CallHostRpcError::new(CallHostStage::Route, "policy", None))?;
1025 if policy != CallHostPolicy::Ordinary {
1026 return Err(CallHostRpcError::new(CallHostStage::Route, "ax_unsupported", None).into());
1027 }
1028 let session = Session::connect(
1029 &state.long_host,
1030 self.options.timeout,
1031 self.options.receive_budget,
1032 )
1033 .map_err(|error| CallHostRpcError::from_cause(CallHostStage::Handshake, &error))?;
1034 let packet = AuthenticatedPacket::prepare(state, route.command(), request)
1035 .map_err(|error| CallHostRpcError::from_cause(CallHostStage::Prepare, &error))?;
1036 self.check_submission()?;
1037 before_submit()?;
1038 let reply = exchange(
1039 &session.short,
1040 &state.short_host,
1041 route.path(),
1042 &packet.packet,
1043 self.options.timeout,
1044 )
1045 .map_err(|error| {
1046 if error.is::<crate::calls::host_transport::CallLiveSyncInterrupted>() {
1047 error
1048 } else {
1049 CallHostRpcError::from_cause(CallHostStage::Exchange, &error).into()
1050 }
1051 })?;
1052 self.accept_call_reply(state, route.command(), &reply)
1053 }
1054
1055 fn accept_call_reply(
1056 &self,
1057 state: &mut AccountState,
1058 command: u16,
1059 reply: &[u8],
1060 ) -> Result<Vec<u8>> {
1061 let (plain, cookie) =
1062 crate::calls::host_transport::decode_verified_reply(state, command, reply)?;
1063 if let Some(retain) = &self.call_reply_observer {
1066 retain(&plain)?;
1067 }
1068 if !cookie.is_empty() {
1069 state.cookie = cookie;
1070 }
1071 Ok(plain)
1072 }
1073
1074 pub(crate) fn authenticated_rpc(
1075 &self,
1076 state: &mut AccountState,
1077 cgi: u16,
1078 path: &str,
1079 request: &[u8],
1080 ) -> Result<Vec<u8>> {
1081 self.authenticated_rpc_guarded(state, cgi, path, request, || Ok(()))
1082 }
1083 fn authenticated_rpc_guarded(
1084 &self,
1085 state: &mut AccountState,
1086 cgi: u16,
1087 path: &str,
1088 request: &[u8],
1089 before_submit: impl FnOnce() -> Result<()>,
1090 ) -> Result<Vec<u8>> {
1091 let short = self.short_session(&state.long_host)?;
1092 let packet = AuthenticatedPacket::prepare(state, cgi, request)?;
1093 self.check_submission()?;
1094 before_submit()?;
1095 let reply = mmtls::short_exchange(
1096 &short,
1097 &state.short_host,
1098 path,
1099 &packet.packet,
1100 self.options.timeout,
1101 )
1102 .inspect_err(|_| {
1103 if let Some(cache) = &self.short_link {
1106 cache.invalidate();
1107 }
1108 })?;
1109 let (plain, cookie) = packet.decode_verified_transport_reply(&reply)?;
1110 if !cookie.is_empty() {
1111 state.cookie = cookie;
1112 }
1113 Ok(plain)
1114 }
1115 #[doc(hidden)]
1120 pub(crate) fn sync_snapshot(
1121 &self,
1122 state: &mut AccountState,
1123 cursor: &[u8],
1124 ) -> Result<SyncBatch> {
1125 self.sync_scene_snapshot(state, cursor, 6)
1126 }
1127 #[doc(hidden)]
1128 pub(crate) fn sync_scene_snapshot(
1129 &self,
1130 state: &mut AccountState,
1131 cursor: &[u8],
1132 scene: u32,
1133 ) -> Result<SyncBatch> {
1134 ensure!([6, 7].contains(&scene), "Unsupported sync scene");
1135 let wire_cursor = if cursor.is_empty() { &[0][..] } else { cursor };
1136 let request = wire::sync_request(wire_cursor, &state.device.device_type, scene)?;
1137 wire::decode_sync(
1138 &self.authenticated_rpc(state, 138, "/cgi-bin/micromsg-bin/newsync", &request)?,
1139 cursor,
1140 )
1141 }
1142 #[doc(hidden)]
1145 pub(crate) fn heartbeat_snapshot(
1146 &self,
1147 state: &mut AccountState,
1148 cursor: &[u8],
1149 ) -> Result<Heartbeat> {
1150 let request = wire::heartbeat_request(state, cursor)?;
1151 wire::decode_heartbeat(&self.authenticated_rpc(
1152 state,
1153 518,
1154 "/cgi-bin/micromsg-bin/heartbeat",
1155 &request,
1156 )?)
1157 }
1158
1159 #[doc(hidden)]
1162 pub(crate) fn lookup_contacts_snapshot(
1163 &self,
1164 state: &mut AccountState,
1165 usernames: &[String],
1166 ) -> Result<ContactLookup> {
1167 let request = wire::contact_request(state, usernames)?;
1168 wire::decode_contacts(
1169 &self.authenticated_rpc(state, 182, "/cgi-bin/micromsg-bin/getcontact", &request)?,
1170 usernames,
1171 )
1172 }
1173 #[doc(hidden)]
1174 pub(crate) fn lookup_room_snapshot(
1175 &self,
1176 state: &mut AccountState,
1177 room_id: &str,
1178 version: u32,
1179 ) -> Result<RoomRoster> {
1180 let request = wire::room_request(state, room_id, version)?;
1181 wire::decode_room(
1182 &self.authenticated_rpc(
1183 state,
1184 551,
1185 "/cgi-bin/micromsg-bin/getchatroommemberdetail",
1186 &request,
1187 )?,
1188 room_id,
1189 )
1190 }
1191 #[doc(hidden)]
1192 pub(crate) fn init_contacts_snapshot(
1193 &self,
1194 state: &mut AccountState,
1195 contact_sequence: u32,
1196 room_sequence: u32,
1197 ) -> Result<InitContactPage> {
1198 let request =
1199 wire::init_contacts_request(&state.own_username, contact_sequence, room_sequence)?;
1200 let page = wire::decode_init_contacts(&self.authenticated_rpc(
1201 state,
1202 851,
1203 "/cgi-bin/micromsg-bin/initcontact",
1204 &request,
1205 )?)?;
1206 ensure!(
1207 !page.more
1208 || page.contact_sequence != contact_sequence
1209 || page.room_sequence != room_sequence,
1210 "Contact bootstrap made no cursor progress"
1211 );
1212 Ok(page)
1213 }
1214 #[doc(hidden)]
1215 pub(crate) fn download_avatars_snapshot(
1216 &self,
1217 state: &mut AccountState,
1218 usernames: &[String],
1219 ) -> Result<Vec<AvatarBytes>> {
1220 let request = wire::avatar_request(state, usernames)?;
1221 wire::decode_avatars(
1222 &self.authenticated_rpc(
1223 state,
1224 123,
1225 "/cgi-bin/micromsg-bin/batchgetheadimg",
1226 &request,
1227 )?,
1228 usernames,
1229 )
1230 }
1231 #[doc(hidden)]
1232 pub(crate) fn download_voice_chunk_snapshot(
1233 &self,
1234 state: &mut AccountState,
1235 server_message_id: u64,
1236 total_length: u32,
1237 offset: u32,
1238 ) -> Result<VoiceChunk> {
1239 let request = wire::voice_request(state, server_message_id, total_length, offset)?;
1240 wire::decode_voice(
1241 &self.authenticated_rpc(state, 128, "/cgi-bin/micromsg-bin/downloadvoice", &request)?,
1242 server_message_id,
1243 total_length,
1244 offset,
1245 )
1246 }
1247 #[doc(hidden)]
1248 pub(crate) fn cdn_config_snapshot(
1249 &self,
1250 state: &mut AccountState,
1251 ) -> Result<crate::media::CdnConfig> {
1252 let request = p::bytes(1, &wire::base_request(&state.device, state.uin, 0)?);
1253 let reply =
1254 self.authenticated_rpc(state, 379, "/cgi-bin/micromsg-bin/getcdndns", &request)?;
1255 crate::media::decode_cdn_config(&reply, state)
1256 }
1257 #[doc(hidden)]
1258 pub(crate) fn large_cdn_config_snapshot(
1259 &self,
1260 state: &mut AccountState,
1261 route: crate::media::LargeCdnRoute,
1262 ) -> Result<crate::media::CdnConfig> {
1263 let request = p::bytes(1, &wire::base_request(&state.device, state.uin, 0)?);
1264 let reply =
1265 self.authenticated_rpc(state, 379, "/cgi-bin/micromsg-bin/getcdndns", &request)?;
1266 crate::media::decode_large_cdn_config(&reply, state, route)
1267 }
1268 #[doc(hidden)]
1271 pub(crate) fn send_share_snapshot(
1272 &self,
1273 state: &mut AccountState,
1274 destination: &str,
1275 client_id: &str,
1276 created_at: u32,
1277 content: &str,
1278 ) -> Result<crate::media_send::MediaSendResult> {
1279 let request = crate::media_send::share_send_request(
1280 state,
1281 destination,
1282 client_id,
1283 created_at,
1284 content,
1285 )?;
1286 crate::media_send::decode_file_send(
1287 &self.authenticated_rpc(state, 222, "/cgi-bin/micromsg-bin/sendappmsg", &request)?,
1288 client_id,
1289 )
1290 }
1291
1292 #[doc(hidden)]
1293 pub(crate) fn send_quote_with_source_snapshot(
1294 &self,
1295 state: &mut AccountState,
1296 destination: &str,
1297 client_id: &str,
1298 created_at: u32,
1299 content: &str,
1300 source: Option<&str>,
1301 ) -> Result<crate::media_send::MediaSendResult> {
1302 let request = crate::quote_send::quote_send_request_with_source(
1303 state,
1304 destination,
1305 client_id,
1306 created_at,
1307 content,
1308 source,
1309 )?;
1310 crate::media_send::decode_file_send(
1311 &self.authenticated_rpc(state, 222, "/cgi-bin/micromsg-bin/sendappmsg", &request)?,
1312 client_id,
1313 )
1314 }
1315 #[doc(hidden)]
1318 pub(crate) fn reserve_file_upload_snapshot(
1319 &self,
1320 state: &mut AccountState,
1321 destination: &str,
1322 progress_client_id: &str,
1323 file_name: &str,
1324 plaintext_bytes: usize,
1325 md5: &str,
1326 ) -> Result<crate::file_upload::FileUploadReservation> {
1327 let request = crate::file_upload::file_upload_request(
1328 state,
1329 destination,
1330 progress_client_id,
1331 file_name,
1332 plaintext_bytes,
1333 md5,
1334 )?;
1335 crate::file_upload::decode_file_upload_reservation(&self.authenticated_rpc(
1336 state,
1337 6691,
1338 "/cgi-bin/micromsg-bin/sendfileuploadmsg",
1339 &request,
1340 )?)
1341 }
1342
1343 #[allow(clippy::too_many_arguments)]
1344 #[doc(hidden)]
1345 pub(crate) fn send_file_with_reservation_snapshot(
1346 &self,
1347 state: &mut AccountState,
1348 destination: &str,
1349 client_id: &str,
1350 created_at: u32,
1351 upload: &crate::media::UploadedMedia,
1352 reservation: Option<&crate::file_upload::FileUploadReservation>,
1353 ) -> Result<crate::media_send::MediaSendResult> {
1354 let request = crate::media_send::file_send_request_with_reservation(
1355 state,
1356 destination,
1357 client_id,
1358 created_at,
1359 upload,
1360 reservation,
1361 )?;
1362 let reply =
1363 self.authenticated_rpc(state, 222, "/cgi-bin/micromsg-bin/sendappmsg", &request)?;
1364 if reservation.is_some() {
1365 crate::media_send::decode_file_send_correlated(
1366 &reply,
1367 client_id,
1368 &state.own_username,
1369 destination,
1370 &upload.descriptor.aes_key,
1371 )
1372 } else {
1373 crate::media_send::decode_file_send(&reply, client_id)
1374 }
1375 }
1376 #[doc(hidden)]
1377 pub(crate) fn send_image_snapshot(
1378 &self,
1379 state: &mut AccountState,
1380 destination: &str,
1381 client_id: &str,
1382 upload: &crate::media::UploadedImage,
1383 ) -> Result<crate::media_send::MediaSendResult> {
1384 let request = crate::media_send::image_send_request(state, destination, client_id, upload)?;
1385 crate::media_send::decode_image_send(
1386 &self.authenticated_rpc(state, 110, "/cgi-bin/micromsg-bin/uploadmsgimg", &request)?,
1387 client_id,
1388 &state.own_username,
1389 destination,
1390 )
1391 }
1392 #[doc(hidden)]
1393 pub(crate) fn send_video_snapshot(
1394 &self,
1395 state: &mut AccountState,
1396 destination: &str,
1397 client_id: &str,
1398 upload: &crate::media::UploadedVideo,
1399 play_seconds: u32,
1400 ) -> Result<crate::media_send::MediaSendResult> {
1401 let request = crate::media_send::video_send_request(
1402 state,
1403 destination,
1404 client_id,
1405 upload,
1406 play_seconds,
1407 )?;
1408 crate::media_send::decode_video_send(
1409 &self.authenticated_rpc(state, 149, "/cgi-bin/micromsg-bin/uploadvideo", &request)?,
1410 client_id,
1411 )
1412 }
1413 #[doc(hidden)]
1417 pub(crate) fn send_voice_snapshot(
1418 &self,
1419 state: &mut AccountState,
1420 destination: &str,
1421 client_id: &str,
1422 created_at: u32,
1423 duration_ms: u32,
1424 encoded: &[u8],
1425 ) -> Result<crate::media_send::MediaSendResult> {
1426 let mut upload = crate::media_send::VoiceUpload::new(
1427 destination,
1428 client_id,
1429 created_at,
1430 duration_ms,
1431 encoded,
1432 )?;
1433 loop {
1434 let request = upload.request(state)?;
1435 let reply =
1436 self.authenticated_rpc(state, 127, "/cgi-bin/micromsg-bin/uploadvoice", &request)?;
1437 if let Some(result) = upload.accept_reply(&reply)? {
1438 return Ok(result);
1439 }
1440 }
1441 }
1442}
1443
1444fn redirect(fields: &[p::Field]) -> Result<(String, String)> {
1445 let network = p::decode(p::data(fields, 5)?)?;
1446 let hosts = p::decode(p::data(&network, 1)?)?;
1447 let target = |source: &[u8]| -> Result<String> {
1448 let mut out = None;
1449 for f in hosts.iter().filter(|f| f.number == 2) {
1450 let p::Value::Bytes(raw) = &f.value else {
1451 bail!("Invalid redirect map");
1452 };
1453 let item = p::decode(raw)?;
1454 if p::data(&item, 1)? == source {
1455 ensure!(out.is_none(), "Ambiguous redirect");
1456 let name = std::str::from_utf8(p::data(&item, 2)?)?.to_string();
1457 mmtls::validate_host(&name)?;
1458 out = Some(name);
1459 }
1460 }
1461 out.ok_or_else(|| anyhow::anyhow!("Missing redirect mapping"))
1462 };
1463 Ok((
1464 target(b"long.weixin.qq.com")?,
1465 target(b"short.weixin.qq.com")?,
1466 ))
1467}
1468fn reduce_auth(
1469 plain: &[u8],
1470 previous: Option<&AccountState>,
1471 inner: &Ecdh,
1472 device: &DeviceProfile,
1473 cookie: &[u8],
1474) -> Result<AccountState> {
1475 let f = p::decode(plain)?;
1476 ensure!(p::base_code(&f)? == 0, "Rejected auth response");
1477 let mask = u32::try_from(p::scalar(&f, 2)?)?;
1478 for (bit, n) in [(1, 3), (2, 4), (4, 5)] {
1479 if mask & bit != 0 {
1480 p::data(&f, n)?;
1481 }
1482 }
1483 let mut state = previous.cloned().unwrap_or_else(|| AccountState {
1484 schema: 1,
1485 device: device.clone(),
1486 uin: 0,
1487 own_username: String::new(),
1488 cookie: vec![],
1489 session_key: vec![],
1490 request_key: vec![],
1491 response_key: vec![],
1492 auto_auth_key: vec![],
1493 key_info: vec![],
1494 database_password: vec![],
1495 auth_snapshot: AuthSnapshot::default(),
1496 long_host: "long.weixin.qq.com".into(),
1497 short_host: "short.weixin.qq.com".into(),
1498 });
1499 ensure!(
1500 plain.len() <= 1024 * 1024,
1501 "Auth response snapshot too large"
1502 );
1503 state.auth_snapshot.update_mask = mask;
1504 state.auth_snapshot.response = plain.to_vec();
1505 for (number, target) in [
1506 (3, &mut state.auth_snapshot.auth),
1507 (4, &mut state.auth_snapshot.account),
1508 (5, &mut state.auth_snapshot.network),
1509 (6, &mut state.auth_snapshot.ax_auth),
1510 ] {
1511 if let Some(section) = p::optional_data(&f, number)? {
1512 *target = section.to_vec();
1513 }
1514 }
1515 if let Some(account) = p::optional_data(&f, 4)? {
1516 let a = p::decode(account)?;
1517 if let Some(name) = p::optional_data(&a, 1)? {
1518 let name = std::str::from_utf8(name)?;
1519 ensure!(
1520 previous.is_none_or(|s| s.own_username == name),
1521 "Auth account identity changed"
1522 );
1523 state.own_username = name.to_string();
1524 }
1525 }
1526 if mask & 1 != 0 {
1527 let auth = p::data(&f, 3)?;
1528 let a = p::decode(auth)?;
1529 let uin = u32::try_from(p::scalar(&a, 1)?)?;
1530 ensure!(
1531 uin != 0 && previous.is_none_or(|s| s.uin == uin),
1532 "Auth UIN changed"
1533 );
1534 let (session, request, response) = business::account_keys(inner, auth)?;
1535 state.uin = uin;
1536 state.session_key = session;
1537 state.request_key = request;
1538 state.response_key = response;
1539 state.auto_auth_key = p::optional_data(&a, 4)?
1540 .map(p::unbuffer)
1541 .transpose()?
1542 .unwrap_or_default();
1543 if let Some(password) = p::optional_data(&a, 9)? {
1544 let password = p::unbuffer(password)?;
1545 ensure!(
1546 password.is_empty() || password.len() == 32,
1547 "Invalid native database password"
1548 );
1549 state.database_password.zeroize();
1550 state.database_password = password;
1551 }
1552 state.key_info = p::optional_data(&a, 10)?
1553 .map(p::unbuffer)
1554 .transpose()?
1555 .unwrap_or_default();
1556 } else {
1557 ensure!(previous.is_some(), "Initial auth has no key section");
1558 }
1559 ensure!(cookie.len() <= 15, "Invalid auth cookie");
1560 if !cookie.is_empty() {
1561 state.cookie = cookie.to_vec();
1562 }
1563 state.validate()?;
1564 Ok(state)
1565}
1566
1567fn apply_login_notification(
1568 attempt: &mut LoginAttempt,
1569 response: wire::PollResponse,
1570 start_lan: impl FnOnce(&mut LoginAttempt) -> Result<std::sync::Arc<crate::lan_login::Challenge>>,
1571) -> Result<LoginStatus> {
1572 if response.lan_challenge && matches!(response.status, Some(0..=2)) {
1573 attempt.credential3.zeroize();
1576 attempt.credential4.zeroize();
1577 attempt.credential3 = None;
1578 attempt.credential4 = None;
1579 attempt.status = LoginStatus::Scanned;
1580 if let Some(challenge) = &attempt.lan_challenge {
1581 if challenge.active() {
1582 return Ok(attempt.status);
1583 }
1584 attempt.stop_lan_login();
1585 return Err(crate::lan_login::failure("listener_stopped"));
1586 }
1587 if attempt.lan_upload_attempted {
1588 return Err(crate::lan_login::failure("upload_already_attempted"));
1589 }
1590 attempt.lan_upload_attempted = true;
1593 attempt.lan_challenge = Some(start_lan(attempt)?);
1594 return Ok(attempt.status);
1595 }
1596 if let Some(status) = response.status {
1597 attempt.status = match status {
1598 0 if attempt.status == LoginStatus::Scanned => LoginStatus::Scanned,
1599 0 => LoginStatus::Pending,
1600 1 => LoginStatus::Scanned,
1601 2 => LoginStatus::Approved,
1602 _ => LoginStatus::Rejected,
1604 };
1605 if attempt.status == LoginStatus::Approved {
1606 attempt.credential3 = response.credential3;
1607 attempt.credential4 = response.credential4;
1608 }
1609 if matches!(
1610 attempt.status,
1611 LoginStatus::Approved | LoginStatus::Rejected
1612 ) {
1613 attempt.stop_lan_login();
1614 }
1615 }
1616 if attempt
1617 .lan_challenge
1618 .as_ref()
1619 .is_some_and(|challenge| !challenge.active())
1620 {
1621 attempt.stop_lan_login();
1622 return Err(crate::lan_login::failure("listener_stopped"));
1623 }
1624 Ok(attempt.status)
1625}
1626
1627#[cfg(test)]
1628mod tests {
1629 use super::*;
1630 fn attempt(status: LoginStatus, qr: bool) -> LoginAttempt {
1631 LoginAttempt {
1632 schema: 1,
1633 device: state().device.clone(),
1634 computer_name: "synthetic desktop".into(),
1635 qr_png: if qr { vec![1] } else { Vec::new() },
1636 width: 0,
1637 height: 0,
1638 created_at: 1000,
1639 expires_at: 1240,
1640 identifier: vec![1; 16],
1641 notify_key: vec![2; 16],
1642 cookie: vec![3; 15],
1643 key_version: 10014,
1644 long_host: "long.weixin.qq.com".into(),
1645 short_host: "short.weixin.qq.com".into(),
1646 status,
1647 key_info: b"persisted installation key-info".to_vec(),
1648 credential3: Some(vec![4; 16]),
1649 credential4: Some(vec![5; 16]),
1650 lan_upload_attempted: false,
1651 lan_challenge: None,
1652 }
1653 }
1654 #[test]
1655 fn final_approval_request_restores_key_info_for_both_saved_device_and_qr() {
1656 let inner = Ecdh::generate(Nid::SECP224R1).unwrap();
1657 for qr in [false, true] {
1658 let attempt = attempt(LoginStatus::Approved, qr);
1659 let restored: LoginAttempt =
1660 serde_json::from_slice(&serde_json::to_vec(&attempt).unwrap()).unwrap();
1661 assert_eq!(restored.key_info, attempt.key_info);
1662 let request = p::decode(
1663 &restored
1664 .manual_auth_request(&inner.public().unwrap())
1665 .unwrap(),
1666 )
1667 .unwrap();
1668 let aes = p::decode(p::data(&request, 2).unwrap()).unwrap();
1669 let base = p::decode(p::data(&aes, 1).unwrap()).unwrap();
1670 assert_eq!(p::scalar(&base, 6).unwrap(), 1);
1672 let auth = p::decode(p::data(&aes, 2).unwrap()).unwrap();
1673 assert_eq!(
1674 p::unbuffer(p::data(&auth, 5).unwrap()).unwrap(),
1675 attempt.key_info
1676 );
1677 assert!(!format!("{restored:?}").contains("persisted installation"));
1678 }
1679 }
1680 #[test]
1681 fn scanned_and_saved_device_approval_outlive_image_expiry_but_remain_bounded() {
1682 let qr = attempt(LoginStatus::Pending, true);
1683 assert!(qr.validate_at(1239).is_ok());
1684 assert!(qr.validate_at(1240).is_err());
1685 for (status, qr) in [
1686 (LoginStatus::Scanned, true),
1687 (LoginStatus::Approved, true),
1688 (LoginStatus::Pending, false),
1689 ] {
1690 let attempt = attempt(status, qr);
1691 assert!(attempt.validate_at(1240).is_ok());
1692 assert!(attempt.validate_at(1899).is_ok());
1693 assert!(attempt.validate_at(1900).is_err());
1694 }
1695 }
1696 fn notification(status: u32, lan_challenge: bool) -> wire::PollResponse {
1697 wire::PollResponse {
1698 status: Some(status),
1699 lan_challenge,
1700 credential3: (status == 2).then(|| vec![4; 16]),
1701 credential4: (status == 2).then(|| vec![5; 16]),
1702 }
1703 }
1704 fn synthetic_lan() -> std::sync::Arc<crate::lan_login::Challenge> {
1705 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1706 let challenge = crate::lan_login::Challenge::from_listener(
1707 listener,
1708 vec![std::net::Ipv4Addr::LOCALHOST],
1709 crate::lan_login::Scope::new(
1710 std::time::Instant::now() + Duration::from_secs(5),
1711 || false,
1712 ),
1713 )
1714 .unwrap();
1715 challenge.arm(b"synthetic temporary token").unwrap();
1716 std::sync::Arc::new(challenge)
1717 }
1718 #[test]
1719 fn repeated_risk_notifications_upload_once_and_never_install_approval() {
1720 let mut attempt = attempt(LoginStatus::Pending, true);
1721 let challenge = synthetic_lan();
1722 assert_eq!(
1723 apply_login_notification(&mut attempt, notification(2, true), |_| Ok(
1724 challenge.clone()
1725 ))
1726 .unwrap(),
1727 LoginStatus::Scanned
1728 );
1729 assert!(attempt.credential3.is_none() && attempt.credential4.is_none());
1730 assert_eq!(attempt.lan_login_state(), Some("waiting_for_phone"));
1731 for _ in 0..3 {
1732 assert_eq!(
1733 apply_login_notification(&mut attempt, notification(1, true), |_| panic!(
1734 "duplicate upload"
1735 ))
1736 .unwrap(),
1737 LoginStatus::Scanned
1738 );
1739 }
1740 apply_login_notification(&mut attempt, notification(0, false), |_| {
1742 panic!("ordinary poll started LAN")
1743 })
1744 .unwrap();
1745 assert_eq!(attempt.status, LoginStatus::Scanned);
1746 assert!(challenge.active());
1747 let serialized = serde_json::to_string(&attempt).unwrap();
1748 assert!(!serialized.contains("synthetic temporary token"));
1749 assert!(!format!("{attempt:?}").contains("synthetic temporary token"));
1750 let restored: LoginAttempt = serde_json::from_str(&serialized).unwrap();
1751 assert!(restored.lan_login_state().is_none());
1752 assert!(restored.lan_upload_attempted); assert_eq!(
1754 apply_login_notification(&mut attempt, notification(2, false), |_| panic!(
1755 "approval started LAN"
1756 ))
1757 .unwrap(),
1758 LoginStatus::Approved
1759 );
1760 assert!(attempt.lan_login_state().is_none());
1761 assert!(!challenge.active());
1762 assert!(attempt.credential3.is_some() && attempt.credential4.is_some());
1763 }
1764 #[test]
1765 fn failed_upload_is_not_retried_by_the_repeatable_poll_path() {
1766 let mut attempt = attempt(LoginStatus::Pending, true);
1767 let error = apply_login_notification(&mut attempt, notification(1, true), |_| {
1768 Err(crate::lan_login::failure("upload_failed"))
1769 })
1770 .unwrap_err();
1771 assert!(!is_retryable_login_poll_error(&error));
1772 assert_eq!(crate::login_lan_error_reason(&error), Some("upload_failed"));
1773 assert!(attempt.lan_login_state().is_none());
1774 let error = apply_login_notification(&mut attempt, notification(1, true), |_| {
1775 panic!("resubmitted upload")
1776 })
1777 .unwrap_err();
1778 assert_eq!(
1779 crate::login_lan_error_reason(&error),
1780 Some("upload_already_attempted")
1781 );
1782 assert!(attempt.credential3.is_none() && attempt.credential4.is_none());
1783 }
1784 #[test]
1785 fn rejection_or_attempt_drop_closes_the_shared_listener() {
1786 for reject in [false, true] {
1787 let mut attempt = attempt(LoginStatus::Pending, false);
1788 let challenge = synthetic_lan();
1789 apply_login_notification(&mut attempt, notification(1, true), |_| {
1790 Ok(challenge.clone())
1791 })
1792 .unwrap();
1793 if reject {
1794 assert_eq!(
1795 apply_login_notification(&mut attempt, notification(3, true), |_| panic!(
1796 "rejection started LAN"
1797 ))
1798 .unwrap(),
1799 LoginStatus::Rejected
1800 );
1801 }
1802 drop(attempt);
1803 assert!(!challenge.active());
1804 }
1805 }
1806 #[test]
1807 fn ordinary_login_does_not_open_a_lan_listener() {
1808 let mut attempt = attempt(LoginStatus::Pending, true);
1809 for status in [0, 1, 2] {
1810 apply_login_notification(&mut attempt, notification(status, false), |_| {
1811 panic!("ordinary login opened a socket")
1812 })
1813 .unwrap();
1814 assert!(attempt.lan_login_state().is_none());
1815 assert!(!attempt.lan_upload_attempted);
1816 }
1817 }
1818 fn state() -> AccountState {
1819 AccountState {
1820 schema: 1,
1821 device: DeviceProfile {
1822 device_id: vec![1; 16],
1823 device_type: "UnifiedPCLinux synthetic x86_64".into(),
1824 client_version: -227271398,
1825 },
1826 uin: 123,
1827 own_username: "synthetic-user".into(),
1828 cookie: vec![5],
1829 session_key: vec![6; 16],
1830 request_key: vec![7; 24],
1831 response_key: vec![8; 24],
1832 auto_auth_key: vec![],
1833 key_info: vec![],
1834 database_password: vec![],
1835 auth_snapshot: AuthSnapshot::default(),
1836 long_host: "long.weixin.qq.com".into(),
1837 short_host: "short.weixin.qq.com".into(),
1838 }
1839 }
1840 #[test]
1841 fn challenge_poll_retries_only_transport_availability_failures() {
1842 use std::io::{Error, ErrorKind};
1843 for kind in [
1844 ErrorKind::TimedOut,
1845 ErrorKind::WouldBlock,
1846 ErrorKind::ConnectionReset,
1847 ErrorKind::UnexpectedEof,
1848 ] {
1849 assert!(is_retryable_login_poll_error(
1850 &anyhow::Error::new(Error::from(kind)).context("polling challenge")
1851 ));
1852 }
1853 for message in [
1854 "MMTLS deadline exceeded",
1855 "MMTLS connection closed",
1856 "Native shortlink HTTP status 503",
1857 ] {
1858 assert!(is_retryable_login_poll_error(&anyhow::anyhow!("{message}")));
1859 }
1860 for message in [
1861 "Login poll returned -13",
1862 "Native envelope returned -13",
1863 "Native shortlink HTTP status 403",
1864 "Native shortlink HTTP status 5030",
1865 "Missing authentication tag",
1866 "Unexpected MMTLS header",
1867 "Truncated structure",
1868 ] {
1869 assert!(!is_retryable_login_poll_error(&anyhow::anyhow!(
1870 "{message}"
1871 )));
1872 }
1873 assert!(!is_retryable_login_poll_error(
1874 &Error::from(ErrorKind::PermissionDenied).into()
1875 ));
1876 }
1877 #[test]
1878 fn secrets_not_debugged() {
1879 let s = state();
1880 let text = format!("{s:?}");
1881 assert!(!text.contains("synthetic-user"));
1882 assert!(!text.contains("123"));
1883 assert!(text.contains("redacted"));
1884 }
1885 #[test]
1886 fn account_state_roundtrips_without_number_loss() {
1887 let s = state();
1888 let json = serde_json::to_vec(&s).unwrap();
1889 let restored: AccountState = serde_json::from_slice(&json).unwrap();
1890 restored.validate().unwrap();
1891 assert_eq!(restored.uin, s.uin);
1892 }
1893 #[test]
1894 fn database_password_follows_auth_update_gate_and_optional_presence() {
1895 let mut old = state();
1896 old.database_password = vec![11; 32];
1897 let inner = Ecdh::generate(Nid::SECP224R1).unwrap();
1898 let response = |mask, password: Option<&[u8]>| {
1899 let mut fields = vec![
1900 p::uint(1, old.uin as u64),
1901 p::bytes(3, &p::buffer(&[1; 16])),
1902 p::uint(19, 0),
1903 ];
1904 if let Some(bytes) = password {
1905 fields.push(p::bytes(9, &p::buffer(bytes)));
1906 }
1907 p::message(&[
1908 p::bytes(1, &p::uint(1, 0)),
1909 p::uint(2, mask),
1910 p::bytes(3, &p::message(&fields).unwrap()),
1911 p::bytes(6, b"synthetic-ax"),
1912 ])
1913 .unwrap()
1914 };
1915 let gated_off = response(0, Some(&[22; 32]));
1916 let unchanged = reduce_auth(&gated_off, Some(&old), &inner, &old.device, &[]).unwrap();
1917 assert_eq!(unchanged.database_password, old.database_password);
1918 assert_eq!(unchanged.auth_snapshot.update_mask, 0);
1919 assert_eq!(unchanged.auth_snapshot.response, gated_off);
1920 assert_eq!(unchanged.auth_snapshot.ax_auth, b"synthetic-ax");
1921 let accepted = reduce_auth(
1922 &response(1, Some(&[22; 32])),
1923 Some(&old),
1924 &inner,
1925 &old.device,
1926 &[],
1927 )
1928 .unwrap();
1929 assert_eq!(accepted.database_password, vec![22; 32]);
1930 let absent = reduce_auth(
1931 &response(1, None),
1932 Some(&accepted),
1933 &inner,
1934 &old.device,
1935 &[],
1936 )
1937 .unwrap();
1938 assert_eq!(absent.database_password, accepted.database_password);
1939 let empty = reduce_auth(
1940 &response(1, Some(&[])),
1941 Some(&absent),
1942 &inner,
1943 &old.device,
1944 &[],
1945 )
1946 .unwrap();
1947 assert!(empty.database_password.is_empty());
1948 assert!(reduce_auth(
1949 &response(1, Some(&[22; 31])),
1950 Some(&old),
1951 &inner,
1952 &old.device,
1953 &[]
1954 )
1955 .is_err());
1956 let mut legacy = serde_json::to_value(&old).unwrap();
1957 legacy.as_object_mut().unwrap().remove("database_password");
1958 legacy.as_object_mut().unwrap().remove("auth_snapshot");
1959 let restored: AccountState = serde_json::from_value(legacy).unwrap();
1960 restored.validate().unwrap();
1961 assert!(restored.database_password.is_empty());
1962 }
1963 #[test]
1964 fn refresh_identity_and_clear_tokens() {
1965 let old = state();
1966 let inner = Ecdh::generate(Nid::SECP224R1).unwrap();
1967 let auth = p::message(&[
1968 p::uint(1, old.uin as u64),
1969 p::bytes(3, &p::buffer(&[1; 16])),
1970 p::uint(19, 0),
1971 ])
1972 .unwrap();
1973 let reply = p::message(&[
1974 p::bytes(1, &p::uint(1, 0)),
1975 p::uint(2, 1),
1976 p::bytes(3, &auth),
1977 p::bytes(4, &p::bytes(1, old.own_username.as_bytes())),
1978 ])
1979 .unwrap();
1980 let next = reduce_auth(&reply, Some(&old), &inner, &old.device, &[]).unwrap();
1981 assert!(next.auto_auth_key.is_empty());
1982 assert!(next.request_key.is_empty());
1983 let bad = p::message(&[
1984 p::bytes(1, &p::uint(1, 0)),
1985 p::uint(2, 0),
1986 p::bytes(4, &p::bytes(1, b"foreign")),
1987 ])
1988 .unwrap();
1989 assert!(reduce_auth(&bad, Some(&old), &inner, &old.device, &[]).is_err());
1990 }
1991}