Skip to main content

wechat_protocol/
client.rs

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