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