Skip to main content

wechat_protocol/
wire.rs

1//! Typed numbered business messages for the supported native profile.
2use crate::errors::{Service, ServiceRejected};
3use crate::{crypto::random, protobuf as p, AccountState, DeviceProfile};
4use anyhow::{bail, ensure, Result};
5use serde::{Deserialize, Serialize};
6use std::{
7    collections::{BTreeMap, HashSet},
8    time::{SystemTime, UNIX_EPOCH},
9};
10
11pub fn unix_time() -> Result<u32> {
12    Ok(u32::try_from(
13        SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(),
14    )?)
15}
16fn text(value: &str, max: usize, empty: bool) -> Result<&[u8]> {
17    ensure!(
18        (empty || !value.is_empty()) && !value.contains('\0') && value.len() <= max,
19        "Invalid text input"
20    );
21    Ok(value.as_bytes())
22}
23pub fn base_request(profile: &DeviceProfile, uin: u32, task: u32) -> Result<Vec<u8>> {
24    profile.validate()?;
25    p::message(&[
26        p::bytes(1, &[0]),
27        p::uint(2, uin as u64),
28        p::bytes(3, &profile.device_id),
29        p::int32(4, profile.client_version),
30        p::bytes(5, text(&profile.device_type, 1024, false)?),
31        p::uint(6, task as u64),
32    ])
33}
34pub fn qr_request(profile: &DeviceProfile, computer_name: &str) -> Result<Vec<u8>> {
35    p::message(&[
36        p::bytes(1, &base_request(profile, 0, 0)?),
37        p::bytes(2, &p::buffer(&random::<16>()?)),
38        p::uint(3, 0),
39        p::bytes(4, text(computer_name, 255, false)?),
40    ])
41}
42pub fn poll_request(profile: &DeviceProfile, identifier: &[u8]) -> Result<Vec<u8>> {
43    ensure!(
44        !identifier.is_empty() && identifier.len() <= 4096,
45        "Invalid login identifier"
46    );
47    let ms = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
48    let timestamp = ((ms & 0xffffffff) / 1000) as u64;
49    p::message(&[
50        p::bytes(1, &base_request(profile, 0, 0)?),
51        p::bytes(2, &p::buffer(&random::<16>()?)),
52        p::bytes(3, identifier),
53        p::uint(4, timestamp),
54        p::uint(5, 0),
55    ])
56}
57pub struct QrResponse {
58    pub image: Vec<u8>,
59    pub identifier: Vec<u8>,
60    pub notify_key: Vec<u8>,
61    pub width: u32,
62    pub height: u32,
63}
64pub fn decode_qr(input: &[u8]) -> Result<QrResponse> {
65    let f = p::decode(input)?;
66    let code = p::base_code(&f)?;
67    ServiceRejected::check(Service::QrLogin, code)?;
68    let image = p::unbuffer(p::data(&f, 2)?)?;
69    let identifier = p::data(&f, 3)?.to_vec();
70    p::scalar(&f, 4)?;
71    let notify_key = p::unbuffer(p::data(&f, 5)?)?;
72    ensure!(
73        !identifier.is_empty()
74            && identifier.len() <= 4096
75            && !notify_key.is_empty()
76            && notify_key.len() <= 1024,
77        "Invalid QR state"
78    );
79    ensure!(
80        image.len() >= 33 && image[..8] == *b"\x89PNG\r\n\x1a\n" && image[12..16] == *b"IHDR",
81        "Invalid QR image"
82    );
83    let width = u32::from_be_bytes(image[16..20].try_into()?);
84    let height = u32::from_be_bytes(image[20..24].try_into()?);
85    ensure!(
86        (21..=4096).contains(&width) && (21..=4096).contains(&height),
87        "QR image dimensions invalid"
88    );
89    Ok(QrResponse {
90        image,
91        identifier,
92        notify_key,
93        width,
94        height,
95    })
96}
97pub struct PollResponse {
98    pub status: Option<u32>,
99    pub credential3: Option<Vec<u8>>,
100    pub credential4: Option<Vec<u8>>,
101    pub lan_challenge: bool,
102}
103pub fn decode_poll(input: &[u8], notify_key: &[u8]) -> Result<PollResponse> {
104    let f = p::decode(input)?;
105    let code = p::base_code(&f)?;
106    ServiceRejected::check(Service::LoginPoll, code)?;
107    let Some(pkg) = p::optional_data(&f, 3)? else {
108        return Ok(PollResponse {
109            status: None,
110            credential3: None,
111            credential4: None,
112            lan_challenge: false,
113        });
114    };
115    let pkg = p::decode(pkg)?;
116    let ciphertext = p::unbuffer(p::data(&pkg, 1)?)?;
117    p::scalar(&pkg, 2)?;
118    let plain = crate::crypto::cbc(&ciphertext, notify_key, openssl::symm::Mode::Decrypt)?;
119    let notify = p::decode(&plain)?;
120    // LoginQRCodeNotifyData.f17 is an SKBuffer containing
121    // LoginQRCodeNonStoreExtNotifyData; its f1 is the risk state.
122    let lan_challenge = match p::optional_data(&notify, 17)? {
123        Some(buffer) => {
124            ensure!(buffer.len() <= 4096, "Login risk extension too large");
125            let extension = p::unbuffer(buffer)?;
126            let extension = p::decode(&extension)?;
127            match p::optional(&extension, 1)? {
128                Some(p::Value::Varint(state)) => *state == 11,
129                None => false,
130                _ => bail!("Invalid login risk state"),
131            }
132        }
133        None => false,
134    };
135    let status = u32::try_from(p::scalar(&notify, 2)?)?;
136    let credential3 = p::optional_data(&notify, 3)?.map(Vec::from);
137    let credential4 = p::optional_data(&notify, 4)?.map(Vec::from);
138    if status == 2 && !lan_challenge {
139        ensure!(
140            credential3
141                .as_ref()
142                .is_some_and(|b| !b.is_empty() && b.len() <= 65536)
143                && credential4
144                    .as_ref()
145                    .is_some_and(|b| !b.is_empty() && b.len() <= 65536),
146            "Approved login lacks credentials"
147        );
148    }
149    Ok(PollResponse {
150        status: Some(status),
151        credential3,
152        credential4,
153        lan_challenge,
154    })
155}
156pub fn manual_auth(
157    profile: &DeviceProfile,
158    computer_name: &str,
159    c3: &[u8],
160    c4: &[u8],
161    point: &[u8],
162    key_info: &[u8],
163) -> Result<Vec<u8>> {
164    ensure!(
165        !c3.is_empty()
166            && !c4.is_empty()
167            && c3.len() <= 65536
168            && c4.len() <= 65536
169            && point.len() == 57
170            && point[0] == 4
171            && key_info.len() <= 1024 * 1024,
172        "Invalid manual auth inputs"
173    );
174    let rsa = p::message(&[
175        p::bytes(1, &p::buffer(&random::<16>()?)),
176        p::bytes(
177            2,
178            &p::message(&[p::int32(1, 713), p::bytes(2, &p::buffer(point))])?,
179        ),
180        p::bytes(3, c3),
181        p::bytes(4, c4),
182        p::bytes(5, &[]),
183    ])?;
184    let wt = p::message(&[p::bytes(1, &[]), p::bytes(4, &p::buffer(&[0]))])?;
185    let mut base = vec![p::bytes(2, &wt)];
186    if !key_info.is_empty() {
187        base.push(p::bytes(5, &p::buffer(key_info)));
188    }
189    let aes = p::message(&[
190        p::bytes(1, &base_request(profile, 0, 1)?),
191        p::bytes(2, &p::message(&base)?),
192        p::uint(5, 0),
193        p::bytes(8, text(computer_name, 255, false)?),
194        p::bytes(9, profile.device_type.as_bytes()),
195        p::bytes(11, &[]),
196        p::int32(13, 1000),
197        p::bytes(19, b"0"),
198        p::uint(22, 2),
199    ])?;
200    p::message(&[p::bytes(1, &rsa), p::bytes(2, &aes)])
201}
202pub fn auto_auth(state: &AccountState, point: &[u8], computer_name: &str) -> Result<Vec<u8>> {
203    state.validate()?;
204    ensure!(point.len() == 57 && point[0] == 4, "Invalid P224 point");
205    let token = p::decode(&state.auto_auth_key)?;
206    let part1 = p::unbuffer(p::data(&token, 1)?)?;
207    let part2 = p::unbuffer(p::data(&token, 2)?)?;
208    ensure!(
209        part1.len() == 32 && !part2.is_empty(),
210        "Unsupported saved auto-auth token"
211    );
212    let wt = p::message(&[p::bytes(4, &p::buffer(&[0]))])?;
213    let mut base_auth = vec![p::bytes(2, &wt)];
214    if !state.key_info.is_empty() {
215        base_auth.push(p::bytes(5, &p::buffer(&state.key_info)));
216    }
217    let aes = p::message(&[
218        p::bytes(1, &base_request(&state.device, state.uin, 12)?),
219        p::bytes(2, &p::message(&base_auth)?),
220        p::bytes(3, &p::buffer(&state.auto_auth_key)),
221        p::uint(6, 0),
222        p::bytes(9, text(computer_name, 255, true)?),
223        p::bytes(10, state.device.device_type.as_bytes()),
224        p::bytes(11, b"en"),
225        p::bytes(12, &[]),
226        p::bytes(19, state.device.device_type.as_bytes()),
227    ])?;
228    let rsa = p::message(&[
229        p::bytes(2, &p::buffer(&part1)),
230        p::bytes(
231            3,
232            &p::message(&[p::int32(1, 713), p::bytes(2, &p::buffer(point))])?,
233        ),
234    ])?;
235    p::message(&[p::bytes(1, &rsa), p::bytes(2, &aes)])
236}
237pub fn push_login(
238    profile: &DeviceProfile,
239    username: &str,
240    token: &[u8],
241    public_key: &[u8],
242) -> Result<Vec<u8>> {
243    ensure!(
244        !token.is_empty() && token.len() <= 1024 * 1024,
245        "Missing saved token"
246    );
247    p::message(&[
248        p::bytes(1, &base_request(profile, 0, 0)?),
249        p::bytes(2, text(username, 128, false)?),
250        p::bytes(4, &random::<32>()?),
251        p::bytes(5, &p::buffer(&random::<16>()?)),
252        p::uint(6, 3),
253        p::bytes(8, &p::buffer(token)),
254        p::bytes(10, &p::buffer(public_key)),
255        p::uint(12, 1),
256        p::bytes(13, b"en"),
257        p::uint(14, 0),
258        p::uint(15, 0),
259    ])
260}
261pub fn decode_push(input: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
262    let f = p::decode(input)?;
263    let code = p::base_code(&f)?;
264    ServiceRejected::check(Service::SavedDeviceLogin, code)?;
265    let id = p::data(&f, 2)?.to_vec();
266    let key = p::unbuffer(p::data(&f, 3)?)?;
267    ensure!(
268        id.len() == 20 && key.len() == 16,
269        "Unsupported saved-device login state"
270    );
271    Ok((id, key))
272}
273
274#[derive(Clone, Serialize, Deserialize)]
275pub struct SyncCommand {
276    pub id: i32,
277    pub payload: Vec<u8>,
278}
279#[derive(Clone, Serialize, Deserialize)]
280pub struct SyncBatch {
281    pub code: i32,
282    pub flags: u32,
283    pub cursor: Vec<u8>,
284    pub commands: Vec<SyncCommand>,
285    pub continuation: bool,
286}
287pub fn sync_request(cursor: &[u8], device_type: &str, scene: u32) -> Result<Vec<u8>> {
288    ensure!(
289        !cursor.is_empty() && cursor.len() <= 65536,
290        "Invalid sync cursor"
291    );
292    p::message(&[
293        p::bytes(1, &p::uint(1, 0)),
294        p::uint(2, 7),
295        p::bytes(3, &p::buffer(cursor)),
296        p::uint(4, scene as u64),
297        p::bytes(5, text(device_type, 1024, false)?),
298        p::uint(9, 0),
299    ])
300}
301pub fn decode_sync(input: &[u8], prior: &[u8]) -> Result<SyncBatch> {
302    let f = p::decode(input)?;
303    let code = p::scalar(&f, 1)? as u32 as i32;
304    if code != -2006 {
305        ServiceRejected::check(Service::Sync, code)?;
306    }
307    let list = p::decode(p::data(&f, 2)?)?;
308    let flags = u32::try_from(p::scalar(&f, 3)?)?;
309    let incoming = p::unbuffer(p::data(&f, 4)?)?;
310    if !incoming.is_empty() {
311        decode_cursor(&incoming)?;
312    }
313    let mut commands = vec![];
314    for field in list.iter().filter(|f| f.number == 2) {
315        let p::Value::Bytes(v) = &field.value else {
316            bail!("Invalid sync command");
317        };
318        let item = p::decode(v)?;
319        commands.push(SyncCommand {
320            id: p::scalar(&item, 1)? as u32 as i32,
321            payload: p::unbuffer(p::data(&item, 2)?)?,
322        });
323    }
324    ensure!(
325        p::scalar(&list, 1)? == commands.len() as u64,
326        "Sync command count mismatch"
327    );
328    let cursor = apply_cursor(prior, &incoming, code)?;
329    let sent = if prior.is_empty() { &[0][..] } else { prior };
330    let continuation = flags & 7 != 0 && incoming != sent;
331    Ok(SyncBatch {
332        code,
333        flags,
334        cursor,
335        commands,
336        continuation,
337    })
338}
339#[derive(Clone, Serialize, Deserialize)]
340pub struct AddMessage {
341    pub from: String,
342    pub to: String,
343    pub peer: String,
344    pub sender_id: Option<String>,
345    pub outgoing: bool,
346    pub server_message_id: Option<String>,
347    pub numbered1: i32,
348    pub message_type: i32,
349    pub content: Vec<u8>,
350    pub content_text: Option<String>,
351    pub numbered6: u32,
352    pub numbered7: u32,
353    pub inline_data: Vec<u8>,
354    pub created_at: u32,
355    pub msgsource: Option<Vec<u8>>,
356    pub opaque11: Option<Vec<u8>>,
357    pub numbered13: Option<u32>,
358    /// Present field 13 correlated to official server_seq on the supported
359    /// profile (319 exact joined records). Missing remains unsupported for
360    /// official-store projection, never a fabricated sequence zero.
361    pub server_sequence: Option<u32>,
362    pub raw: Vec<u8>,
363}
364/// Decode AddMsg command 5. Fields 6/7 remain numbered. Present field 13 has a
365/// bounded official server_seq correlation; this does not enable every message
366/// class for official writes. A room's actual sender requires separate, validated
367/// group-envelope/member resolution and is deliberately unresolved here.
368pub fn decode_add_message(input: &[u8], own_username: &str) -> Result<AddMessage> {
369    let f = p::decode(input)?;
370    let sk = |n| -> Result<Vec<u8>> {
371        let nested = p::decode(p::data(&f, n)?)?;
372        Ok(p::optional_data(&nested, 1)?.unwrap_or_default().to_vec())
373    };
374    let from = String::from_utf8(sk(2)?)?;
375    let to = String::from_utf8(sk(3)?)?;
376    ensure!(
377        !from.is_empty()
378            && !to.is_empty()
379            && from.len() <= 512
380            && to.len() <= 512
381            && !own_username.is_empty(),
382        "Invalid message identities"
383    );
384    let message_type = p::scalar(&f, 4)? as u32 as i32;
385    let peer = if message_type == 10000 {
386        from.clone()
387    } else if from == own_username {
388        to.clone()
389    } else {
390        from.clone()
391    };
392    ensure!(
393        from == own_username || to == own_username || peer.ends_with("@chatroom"),
394        "Message does not match account"
395    );
396    let content = sk(5)?;
397    let content_text = String::from_utf8(content.clone()).ok();
398    let server_message_id = match p::optional(&f, 12)? {
399        Some(p::Value::Varint(v)) => {
400            if *v == 0 {
401                None
402            } else {
403                Some(v.to_string())
404            }
405        }
406        None => None,
407        _ => bail!("Invalid message server ID"),
408    };
409    let numbered13 = match p::optional(&f, 13)? {
410        Some(p::Value::Varint(v)) => Some(u32::try_from(*v)?),
411        None => None,
412        _ => bail!("Invalid numbered field13"),
413    };
414    Ok(AddMessage {
415        sender_id: (!from.ends_with("@chatroom")).then(|| from.clone()),
416        outgoing: from == own_username,
417        from,
418        to,
419        peer,
420        server_message_id,
421        numbered1: p::scalar(&f, 1)? as u32 as i32,
422        message_type,
423        content,
424        content_text,
425        numbered6: u32::try_from(p::scalar(&f, 6)?)?,
426        numbered7: u32::try_from(p::scalar(&f, 7)?)?,
427        inline_data: p::unbuffer(p::data(&f, 8)?)?,
428        created_at: u32::try_from(p::scalar(&f, 9)?)?,
429        msgsource: p::optional_data(&f, 10)?.map(Vec::from),
430        opaque11: p::optional_data(&f, 11)?.map(Vec::from),
431        numbered13,
432        server_sequence: numbered13,
433        raw: input.to_vec(),
434    })
435}
436pub fn decode_cursor(input: &[u8]) -> Result<Vec<(u32, u32)>> {
437    let f = p::decode(input)?;
438    u32::try_from(p::scalar(&f, 1)?)?;
439    let mut out = vec![];
440    for item in f.iter().filter(|f| f.number == 2) {
441        let p::Value::Bytes(v) = &item.value else {
442            bail!("Invalid cursor entry");
443        };
444        let nested = p::decode(v)?;
445        out.push((
446            u32::try_from(p::scalar(&nested, 1)?)?,
447            u32::try_from(p::scalar(&nested, 2)?)?,
448        ));
449    }
450    Ok(out)
451}
452pub fn apply_cursor(prior: &[u8], incoming: &[u8], code: i32) -> Result<Vec<u8>> {
453    if code == -2006 {
454        return Ok(incoming.to_vec());
455    }
456    ensure!(code == 0, "Unsupported sync status");
457    if incoming.is_empty() {
458        return Ok(prior.to_vec());
459    }
460    if prior.is_empty() {
461        return Ok(incoming.to_vec());
462    }
463    let mut merged = BTreeMap::new();
464    for (k, v) in decode_cursor(prior)? {
465        merged.entry(k).or_insert(v);
466    }
467    for (k, v) in decode_cursor(incoming)? {
468        let value = merged.entry(k).or_insert(0);
469        *value = (*value).max(v);
470    }
471    let mut out = vec![p::uint(1, merged.len() as u64)];
472    for (k, v) in merged {
473        out.push(p::bytes(
474            2,
475            &p::message(&[p::uint(1, k as u64), p::uint(2, v as u64)])?,
476        ));
477    }
478    p::message(&out)
479}
480#[derive(Clone, Serialize, Deserialize, Debug)]
481pub struct Heartbeat {
482    pub next_interval: u32,
483    pub selector: u32,
484}
485pub fn heartbeat_request(state: &AccountState, cursor: &[u8]) -> Result<Vec<u8>> {
486    p::message(&[
487        p::bytes(1, &base_request(&state.device, state.uin, 0)?),
488        p::uint(2, unix_time()? as u64),
489        p::bytes(3, &p::buffer(cursor)),
490    ])
491}
492pub fn decode_heartbeat(input: &[u8]) -> Result<Heartbeat> {
493    let f = p::decode(input)?;
494    let code = p::base_code(&f)?;
495    ServiceRejected::check(Service::Heartbeat, code)?;
496    Ok(Heartbeat {
497        next_interval: u32::try_from(p::scalar(&f, 2)?)?,
498        selector: u32::try_from(p::scalar(&f, 3)?)?,
499    })
500}
501
502pub fn text_send_request(
503    destination: &str,
504    content: &str,
505    created_at: u32,
506    client_id: u32,
507) -> Result<Vec<u8>> {
508    text_send_request_with_source(destination, content, created_at, client_id, None)
509}
510
511pub fn text_send_request_with_source(
512    destination: &str,
513    content: &str,
514    created_at: u32,
515    client_id: u32,
516    source: Option<&str>,
517) -> Result<Vec<u8>> {
518    ensure!(
519        created_at > 0 && client_id > 0,
520        "Invalid send timestamp/client ID"
521    );
522    let mut fields = vec![
523        p::bytes(1, &p::bytes(1, text(destination, 256, false)?)),
524        p::bytes(2, text(content, 64 * 1024, false)?),
525        p::uint(3, 1),
526        p::uint(4, created_at as u64),
527        p::uint(5, client_id as u64),
528    ];
529    if let Some(source) = source.filter(|value| !value.is_empty()) {
530        fields.push(p::bytes(6, text(source, 256 * 1024, false)?));
531    }
532    let item = p::message(&fields)?;
533    p::message(&[p::uint(1, 1), p::bytes(2, &item)])
534}
535/// Native SuperFastHash of the persisted task client-ID string. Tail bytes have
536/// signed int8 semantics in the supported AMD64 profile. This is not a hash of
537/// message content and is not a server idempotency guarantee.
538pub fn client_message_id(data: &[u8]) -> u32 {
539    if data.is_empty() || data.len() > i32::MAX as usize {
540        return 0;
541    }
542    let word = |i| u16::from_le_bytes([data[i], data[i + 1]]) as u32;
543    let signed = |i| data[i] as i8 as i32 as u32;
544    let mut h = data.len() as u32;
545    let mut p = 0;
546    for _ in 0..data.len() / 4 {
547        h = h.wrapping_add(word(p));
548        let tmp = (word(p + 2) << 11) ^ h;
549        h = (h << 16) ^ tmp;
550        p += 4;
551        h = h.wrapping_add(h >> 11);
552    }
553    match data.len() & 3 {
554        3 => {
555            h = h.wrapping_add(word(p));
556            h = (h << 16) ^ h ^ (signed(p + 2) << 18);
557            h = h.wrapping_add(h >> 11);
558        }
559        2 => {
560            h = h.wrapping_add(word(p));
561            h ^= h << 11;
562            h = h.wrapping_add(h >> 17);
563        }
564        1 => {
565            h = h.wrapping_add(signed(p));
566            h ^= h << 10;
567            h = h.wrapping_add(h >> 1);
568        }
569        _ => {}
570    }
571    h ^= h << 3;
572    h = h.wrapping_add(h >> 5);
573    h ^= h << 4;
574    h = h.wrapping_add(h >> 17);
575    h ^= h << 25;
576    h.wrapping_add(h >> 6)
577}
578#[derive(Clone, Serialize, Deserialize, Debug)]
579pub struct TextSendResult {
580    pub accepted: bool,
581    pub outer_code: i32,
582    pub item_code: Option<i32>,
583    pub server_message_id: Option<String>,
584    pub returned_destination_matches: bool,
585    pub returned_client_id_matches: bool,
586}
587pub fn decode_text_send(input: &[u8], destination: &str, client_id: u32) -> Result<TextSendResult> {
588    let f = p::decode(input)?;
589    let code = p::base_code(&f)?;
590    let declared = p::scalar(&f, 2)?;
591    if code != 0 {
592        return Ok(TextSendResult {
593            accepted: false,
594            outer_code: code,
595            item_code: None,
596            server_message_id: None,
597            returned_destination_matches: false,
598            returned_client_id_matches: false,
599        });
600    }
601    let list: Vec<_> = f.iter().filter(|f| f.number == 3).collect();
602    ensure!(
603        declared == 1 && list.len() == 1,
604        "Send response cardinality differs"
605    );
606    let p::Value::Bytes(raw) = &list[0].value else {
607        bail!("Invalid send response");
608    };
609    let item = p::decode(raw)?;
610    let item_code = p::scalar(&item, 1)? as u32 as i32;
611    let returned = p::decode(p::data(&item, 2)?)?;
612    let dest = p::data(&returned, 1)?;
613    for n in 3..=7 {
614        u32::try_from(p::scalar(&item, n)?)?;
615    }
616    let id = if item_code == 0 {
617        let id = p::scalar(&item, 8)?;
618        ensure!(id != 0, "Accepted send has no server ID");
619        Some(id.to_string())
620    } else {
621        None
622    };
623    Ok(TextSendResult {
624        accepted: item_code == 0,
625        outer_code: code,
626        item_code: Some(item_code),
627        server_message_id: id,
628        returned_destination_matches: dest == destination.as_bytes(),
629        returned_client_id_matches: p::scalar(&item, 4)? == client_id as u64,
630    })
631}
632
633#[derive(Clone, Serialize, Deserialize)]
634pub struct ContactRecord {
635    pub username: String,
636    pub nickname: Option<String>,
637    pub remark: Option<String>,
638    pub alias: Option<String>,
639    pub large_avatar_url: Option<String>,
640    pub small_avatar_url: Option<String>,
641    pub raw: Vec<u8>,
642}
643pub fn contact_request(state: &AccountState, usernames: &[String]) -> Result<Vec<u8>> {
644    ensure!(
645        !usernames.is_empty() && usernames.len() <= 2,
646        "Supported contact batch is 1 or 2 identities"
647    );
648    let mut seen = HashSet::new();
649    let mut fields = vec![
650        p::bytes(1, &base_request(&state.device, state.uin, 0)?),
651        p::uint(2, usernames.len() as u64),
652    ];
653    for user in usernames {
654        ensure!(seen.insert(user), "Duplicate requested contact");
655        fields.push(p::bytes(3, &p::bytes(1, text(user, 256, false)?)));
656    }
657    fields.extend([p::uint(4, 0), p::uint(6, 0)]);
658    p::message(&fields)
659}
660fn raw_text(bytes: &[u8]) -> Result<String> {
661    Ok(std::str::from_utf8(bytes)?.to_string())
662}
663fn skstring(f: &[p::Field], n: u32) -> Result<Option<String>> {
664    let Some(v) = p::optional_data(f, n)? else {
665        return Ok(None);
666    };
667    let nested = p::decode(v)?;
668    Ok(Some(raw_text(
669        p::optional_data(&nested, 1)?.unwrap_or_default(),
670    )?))
671}
672pub fn decode_contact_record(raw: &[u8]) -> Result<ContactRecord> {
673    let f = p::decode(raw)?;
674    let username = skstring(&f, 1)?.ok_or_else(|| anyhow::anyhow!("Contact has no identity"))?;
675    ensure!(!username.is_empty(), "Empty contact identity");
676    let direct =
677        |n| -> Result<Option<String>> { p::optional_data(&f, n)?.map(raw_text).transpose() };
678    Ok(ContactRecord {
679        username,
680        nickname: skstring(&f, 2)?,
681        remark: skstring(&f, 10)?,
682        alias: direct(30)?,
683        large_avatar_url: direct(39)?,
684        small_avatar_url: direct(40)?,
685        raw: raw.to_vec(),
686    })
687}
688#[derive(Clone, Serialize, Deserialize)]
689pub struct ContactLookup {
690    pub contacts: Vec<ContactRecord>,
691    pub results: Vec<i32>,
692}
693fn contact_result_code(value: u64) -> Result<i32> {
694    let signed = value as u32 as i32;
695    ensure!(
696        value <= u32::MAX as u64 || (signed < 0 && value == signed as i64 as u64),
697        "Invalid per-contact int32 result"
698    );
699    Ok(signed)
700}
701pub fn decode_contacts(input: &[u8], requested: &[String]) -> Result<ContactLookup> {
702    ensure!(
703        input.len() <= crate::MAX_MESSAGE_BYTES,
704        "Contact response exceeds bound"
705    );
706    let f = p::decode(input)?;
707    let code = p::base_code(&f)?;
708    ServiceRejected::check(Service::Contact, code)?;
709    let mut slots = vec![];
710    let mut results = vec![];
711    for field in &f {
712        match (field.number, &field.value) {
713            (3, p::Value::Bytes(raw)) => slots.push(raw.as_slice()),
714            (4, p::Value::Varint(n)) => results.push(contact_result_code(*n)?),
715            (4, p::Value::Bytes(raw)) => {
716                let mut offset = 0;
717                while offset < raw.len() {
718                    results.push(contact_result_code(p::read_varint(raw, &mut offset)?)?);
719                }
720            }
721            (3 | 4, _) => bail!("Invalid contact response field"),
722            _ => {}
723        }
724    }
725    // The declared count includes default ModContact placeholders for rejected
726    // slots. Count the wire slots before interpreting their contact identities.
727    ensure!(
728        p::scalar(&f, 2)? == slots.len() as u64 && slots.len() <= requested.len(),
729        "Contact count mismatch"
730    );
731    ensure!(
732        results.is_empty() || results.len() == requested.len(),
733        "Contact result count mismatch"
734    );
735    let aligned = slots.len() == requested.len() && results.len() == requested.len();
736    let mut contacts = vec![];
737    let mut seen = HashSet::new();
738    let mut omitted_unavailable = false;
739    for (index, raw) in slots.iter().enumerate() {
740        let fields = p::decode(raw)?;
741        let identity = p::optional_data(&fields, 1)?;
742        // Observed service code1 accompanies an explicitly present, empty
743        // SKString slot. It rejects this lookup; it does not prove deletion or
744        // permanent unavailability. Other empty/missing/unknown cases fail.
745        if identity == Some(&[][..]) && aligned && results[index] == 1 {
746            omitted_unavailable = true;
747            continue;
748        }
749        let record = decode_contact_record(raw)?;
750        ensure!(
751            requested.contains(&record.username) && seen.insert(record.username.clone()),
752            "Unrequested or duplicate contact"
753        );
754        contacts.push((index, record));
755    }
756    if omitted_unavailable {
757        ensure!(
758            contacts
759                .iter()
760                .all(|(index, record)| requested.get(*index) == Some(&record.username)),
761            "Unavailable contact slot alignment mismatch"
762        );
763    }
764    Ok(ContactLookup {
765        contacts: contacts.into_iter().map(|(_, record)| record).collect(),
766        results,
767    })
768}
769
770#[derive(Clone, Serialize, Deserialize)]
771pub struct RoomMember {
772    pub username: String,
773    pub nickname: Option<String>,
774    pub room_display_name: Option<String>,
775    pub raw: Vec<u8>,
776    #[serde(default)]
777    pub flags: u32,
778    #[serde(default)]
779    pub opaque: Option<Vec<u8>>,
780}
781#[derive(Clone, Serialize, Deserialize)]
782pub struct RoomRoster {
783    pub room_id: String,
784    pub version: u32,
785    pub members: Vec<RoomMember>,
786    #[serde(default)]
787    pub full_member_ids: Option<Vec<String>>,
788    #[serde(default)]
789    pub owner: Option<String>,
790    /// None preserves the cached list; Some replaces it, including an empty list.
791    #[serde(default)]
792    pub administrator_ids: Option<Vec<String>>,
793}
794pub fn room_request(state: &AccountState, room_id: &str, version: u32) -> Result<Vec<u8>> {
795    ensure!(room_id.ends_with("@chatroom"), "Invalid room identity");
796    p::message(&[
797        p::bytes(1, &base_request(&state.device, state.uin, 0)?),
798        p::bytes(2, text(room_id, 256, false)?),
799        p::uint(3, version as u64),
800    ])
801}
802pub fn decode_room(input: &[u8], room_id: &str) -> Result<RoomRoster> {
803    let f = p::decode(input)?;
804    let code = p::base_code(&f)?;
805    ServiceRejected::check(Service::Room, code)?;
806    if let Some(echo) = p::optional_data(&f, 2)? {
807        ensure!(echo == room_id.as_bytes(), "Foreign room reply");
808    }
809    let version = u32::try_from(p::scalar(&f, 3)?)?;
810    let member_data = p::decode(p::data(&f, 4)?)?;
811    let mut members = vec![];
812    let mut seen = HashSet::new();
813    for field in member_data.iter().filter(|f| f.number == 2) {
814        let p::Value::Bytes(raw) = &field.value else {
815            bail!("Invalid member field");
816        };
817        let m = p::decode(raw)?;
818        let username = raw_text(p::data(&m, 1)?)?;
819        ensure!(
820            !username.is_empty() && seen.insert(username.clone()),
821            "Invalid member identity"
822        );
823        members.push(RoomMember {
824            username,
825            nickname: p::optional_data(&m, 2)?.map(raw_text).transpose()?,
826            room_display_name: p::optional_data(&m, 3)?.map(raw_text).transpose()?,
827            raw: raw.clone(),
828            flags: u32::try_from(p::scalar(&m, 6)?)?,
829            opaque: p::optional_data(&m, 7)?.map(Vec::from),
830        });
831    }
832    match p::optional(&member_data, 1)? {
833        Some(p::Value::Varint(n)) => ensure!(*n == members.len() as u64, "Member count mismatch"),
834        None => {}
835        _ => bail!("Invalid member count"),
836    }
837    let mut full_ids = vec![];
838    let mut full_seen = HashSet::new();
839    for field in f.iter().filter(|v| v.number == 7) {
840        let p::Value::Bytes(raw) = &field.value else {
841            bail!("Invalid full member identity");
842        };
843        let name = raw_text(p::data(&p::decode(raw)?, 1)?)?;
844        ensure!(
845            !name.is_empty()
846                && name.len() <= 256
847                && !name.chars().any(|c| c.is_control() || c.is_whitespace())
848                && full_seen.insert(name.clone())
849                && full_ids.len() < 10000,
850            "Invalid full member identity"
851        );
852        full_ids.push(name);
853    }
854    let full_member_ids = match p::optional(&f, 6)? {
855        Some(p::Value::Varint(n)) => {
856            ensure!(
857                u32::try_from(*n)? as usize == full_ids.len(),
858                "Full member count mismatch"
859            );
860            Some(full_ids)
861        }
862        None if full_ids.is_empty() => None,
863        _ => bail!("Invalid full member count"),
864    };
865    let administrator_control = match p::optional(&f, 8)? {
866        None => 0,
867        Some(p::Value::Varint(value)) => u32::try_from(*value)?,
868        _ => bail!("Invalid administrator control"),
869    };
870    let mut administrator_ids = vec![];
871    let mut administrator_seen = HashSet::new();
872    for (index, field) in f.iter().filter(|v| v.number == 9).enumerate() {
873        ensure!(index < 10000, "Excessive administrator identities");
874        let p::Value::Bytes(raw) = &field.value else {
875            bail!("Invalid administrator identity");
876        };
877        let nested = p::decode(raw)?;
878        let name = raw_text(p::optional_data(&nested, 1)?.unwrap_or_default())?;
879        // Empty SKString entries are sentinels, not administrator identities.
880        if name.is_empty() {
881            continue;
882        }
883        ensure!(
884            name.len() <= 256
885                && !name.chars().any(|c| c.is_control() || c.is_whitespace())
886                && administrator_seen.insert(name.clone()),
887            "Invalid administrator identity"
888        );
889        administrator_ids.push(name);
890    }
891    // The supported native consumer uses field 8 as a nonzero replacement
892    // control, not as a count of the field 9 SKString entries.
893    let administrator_ids = (administrator_control != 0).then_some(administrator_ids);
894    let owner = p::optional_data(&f, 5)?
895        .map(raw_text)
896        .transpose()?
897        .filter(|s| !s.is_empty());
898    Ok(RoomRoster {
899        room_id: room_id.to_string(),
900        version,
901        members,
902        full_member_ids,
903        owner,
904        administrator_ids,
905    })
906}
907
908#[derive(Clone, Serialize, Deserialize)]
909pub struct InitContactPage {
910    pub contact_sequence: u32,
911    pub room_sequence: u32,
912    pub more: bool,
913    pub usernames: Vec<String>,
914}
915pub fn init_contacts_request(
916    username: &str,
917    contact_sequence: u32,
918    room_sequence: u32,
919) -> Result<Vec<u8>> {
920    p::message(&[
921        p::bytes(1, text(username, 256, false)?),
922        p::uint(2, contact_sequence as u64),
923        p::uint(3, room_sequence as u64),
924    ])
925}
926pub fn decode_init_contacts(input: &[u8]) -> Result<InitContactPage> {
927    let f = p::decode(input)?;
928    let code = p::base_code(&f)?;
929    ServiceRejected::check(Service::ContactBootstrap, code)?;
930    let optional_scalar = |n| -> Result<u32> {
931        match p::optional(&f, n)? {
932            Some(p::Value::Varint(v)) => Ok(u32::try_from(*v)?),
933            None => Ok(0),
934            _ => bail!("Invalid contact cursor field"),
935        }
936    };
937    let mut seen = HashSet::new();
938    let mut usernames = vec![];
939    for field in f.iter().filter(|f| f.number == 5) {
940        let p::Value::Bytes(raw) = &field.value else {
941            bail!("Invalid contact identifier");
942        };
943        let user = raw_text(raw)?;
944        ensure!(
945            !user.is_empty()
946                && user.len() <= 512
947                && !user.chars().any(|c| c.is_control() || c.is_whitespace())
948                && seen.insert(user.clone())
949                && usernames.len() < 10000,
950            "Invalid contact bootstrap identity"
951        );
952        usernames.push(user);
953    }
954    Ok(InitContactPage {
955        contact_sequence: optional_scalar(2)?,
956        room_sequence: optional_scalar(3)?,
957        more: optional_scalar(4)? != 0,
958        usernames,
959    })
960}
961#[derive(Clone, Serialize, Deserialize)]
962pub struct AvatarBytes {
963    pub username: String,
964    pub bytes: Vec<u8>,
965}
966pub fn avatar_request(state: &AccountState, usernames: &[String]) -> Result<Vec<u8>> {
967    ensure!(
968        !usernames.is_empty() && usernames.len() <= 2,
969        "Supported avatar batch is 1 or 2 identities"
970    );
971    let mut parts = vec![
972        p::bytes(1, &base_request(&state.device, state.uin, 0)?),
973        p::uint(2, usernames.len() as u64),
974    ];
975    let mut seen = HashSet::new();
976    for user in usernames {
977        ensure!(seen.insert(user), "Duplicate avatar identity");
978        parts.push(p::bytes(3, &p::bytes(1, text(user, 256, false)?)));
979    }
980    p::message(&parts)
981}
982/// Returns exact bounded bytes. The service must fully decode the image before
983/// treating this response as a displayable avatar or storing an image mime type.
984pub fn decode_avatars(input: &[u8], requested: &[String]) -> Result<Vec<AvatarBytes>> {
985    let f = p::decode(input)?;
986    let code = p::base_code(&f)?;
987    ServiceRejected::check(Service::Avatar, code)?;
988    let mut out = vec![];
989    let mut seen = HashSet::new();
990    for field in f.iter().filter(|f| f.number == 3) {
991        let p::Value::Bytes(raw) = &field.value else {
992            bail!("Invalid avatar item");
993        };
994        let pair = p::decode(raw)?;
995        let username =
996            skstring(&pair, 2)?.ok_or_else(|| anyhow::anyhow!("Missing avatar identity"))?;
997        ensure!(
998            requested.contains(&username) && seen.insert(username.clone()),
999            "Foreign or duplicate avatar"
1000        );
1001        let bytes = p::unbuffer(p::data(&pair, 1)?)?;
1002        ensure!(
1003            !bytes.is_empty() && bytes.len() <= 2 * 1024 * 1024,
1004            "Avatar bytes outside limit"
1005        );
1006        out.push(AvatarBytes { username, bytes });
1007    }
1008    ensure!(
1009        p::scalar(&f, 2)? == out.len() as u64 && out.len() <= requested.len(),
1010        "Avatar count mismatch"
1011    );
1012    Ok(out)
1013}
1014#[derive(Clone, Serialize, Deserialize)]
1015pub struct VoiceChunk {
1016    pub offset: u32,
1017    pub next_offset: u32,
1018    pub total_length: u32,
1019    pub complete: bool,
1020    pub bytes: Vec<u8>,
1021    pub echoed_server_id: Option<String>,
1022    pub offset_matches: bool,
1023}
1024fn voice_range(total: u32, offset: u32) -> Result<u32> {
1025    ensure!(
1026        total > 0 && total <= crate::MAX_MESSAGE_BYTES as u32 && offset < total,
1027        "Invalid voice range"
1028    );
1029    Ok((total - offset).min(32768))
1030}
1031pub fn voice_request(
1032    state: &AccountState,
1033    server_id: u64,
1034    total: u32,
1035    offset: u32,
1036) -> Result<Vec<u8>> {
1037    ensure!(server_id != 0, "Missing voice server ID");
1038    let length = voice_range(total, offset)?;
1039    p::message(&[
1040        p::uint(1, 0),
1041        p::uint(2, offset as u64),
1042        p::uint(3, length as u64),
1043        p::bytes(5, &base_request(&state.device, state.uin, 0)?),
1044        p::uint(6, server_id),
1045    ])
1046}
1047pub fn decode_voice(input: &[u8], server_id: u64, total: u32, offset: u32) -> Result<VoiceChunk> {
1048    let requested = voice_range(total, offset)?;
1049    let f = p::decode(input)?;
1050    let base = p::decode(p::data(&f, 9)?)?;
1051    let code = p::scalar(&base, 1)? as u32 as i32;
1052    ServiceRejected::check(Service::Voice, code)?;
1053    for n in [1, 2, 3, 5, 8] {
1054        u32::try_from(p::scalar(&f, n)?)?;
1055    }
1056    let bytes = p::unbuffer(p::data(&f, 7)?)?;
1057    ensure!(
1058        p::scalar(&f, 3)? == bytes.len() as u64
1059            && !bytes.is_empty()
1060            && bytes.len() <= requested as usize,
1061        "Voice response length invalid"
1062    );
1063    let echoed = match p::optional(&f, 11)? {
1064        Some(p::Value::Varint(id)) => Some(*id),
1065        None => None,
1066        _ => bail!("Invalid voice server ID echo"),
1067    };
1068    ensure!(
1069        echoed.is_none_or(|id| id == server_id),
1070        "Foreign voice server ID"
1071    );
1072    let next_offset = offset + bytes.len() as u32;
1073    ensure!(next_offset <= total, "Voice chunk overflow");
1074    Ok(VoiceChunk {
1075        offset,
1076        next_offset,
1077        total_length: total,
1078        complete: next_offset == total,
1079        bytes,
1080        echoed_server_id: echoed.map(|v| v.to_string()),
1081        offset_matches: p::scalar(&f, 2)? == offset as u64,
1082    })
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087    use super::*;
1088    #[test]
1089    fn room_delta_count_is_independent_of_complete_identity_list() {
1090        let member = p::message(&[
1091            p::bytes(1, b"changed"),
1092            p::uint(6, 0x2000),
1093            p::bytes(7, b"opaque"),
1094        ])
1095        .unwrap();
1096        let roster = |nested: Vec<u8>, extra: Vec<Vec<u8>>| {
1097            let mut fields = vec![
1098                p::bytes(1, &p::uint(1, 0)),
1099                p::uint(3, 7),
1100                p::bytes(4, &nested),
1101            ];
1102            fields.extend(extra);
1103            p::message(&fields).unwrap()
1104        };
1105        let nested = p::message(&[p::uint(1, 1), p::bytes(2, &member)]).unwrap();
1106        let full = vec![
1107            p::uint(6, 2),
1108            p::bytes(7, &p::bytes(1, b"changed")),
1109            p::bytes(7, &p::bytes(1, b"unchanged")),
1110        ];
1111        let decoded = decode_room(&roster(nested.clone(), full.clone()), "room@chatroom").unwrap();
1112        assert_eq!(decoded.members.len(), 1);
1113        assert_eq!(decoded.members[0].flags, 0x2000);
1114        assert_eq!(
1115            decoded.members[0].opaque.as_deref(),
1116            Some(b"opaque".as_slice())
1117        );
1118        assert_eq!(decoded.full_member_ids.unwrap(), ["changed", "unchanged"]);
1119        assert!(decode_room(
1120            &roster(nested.clone(), vec![p::uint(6, 2)]),
1121            "room@chatroom"
1122        )
1123        .is_err());
1124        assert!(decode_room(&roster(p::bytes(1, b"wrong type"), vec![]), "room@chatroom").is_err());
1125        assert!(decode_room(
1126            &roster(p::bytes(2, &p::bytes(1, b"missing-flags")), vec![]),
1127            "room@chatroom"
1128        )
1129        .is_err());
1130        let mut administrator_clear = full;
1131        administrator_clear.push(p::uint(8, 1));
1132        assert_eq!(
1133            decode_room(
1134                &roster(nested.clone(), administrator_clear),
1135                "room@chatroom"
1136            )
1137            .unwrap()
1138            .administrator_ids,
1139            Some(vec![])
1140        );
1141        assert!(decode_room(&roster(nested, vec![]), "room@chatroom")
1142            .unwrap()
1143            .full_member_ids
1144            .is_none());
1145    }
1146
1147    fn room_administrator_fixture(extra: &[u8]) -> Vec<u8> {
1148        // CGI551 response: BaseResponse{ret=0}, version=7,
1149        // ChatRoomMemberData{member_count=0}. These tags are independent of
1150        // the codec under test and retain an empty changed-member list.
1151        let mut raw = vec![0x0a, 0x02, 0x08, 0x00, 0x18, 0x07, 0x22, 0x02, 0x08, 0x00];
1152        raw.extend_from_slice(extra);
1153        raw
1154    }
1155
1156    #[test]
1157    fn room_administrator_control_replaces_list_without_count_semantics() {
1158        // Field 8=42; repeated field 9 SKString values: alice, empty, bob.
1159        // The native consumer filters empty strings and replaces the list
1160        // whenever field 8 is nonzero, without comparing it to a count.
1161        let raw = room_administrator_fixture(&[
1162            0x40, 0x2a, 0x4a, 0x07, 0x0a, 0x05, b'a', b'l', b'i', b'c', b'e', 0x4a, 0x00, 0x4a,
1163            0x05, 0x0a, 0x03, b'b', b'o', b'b',
1164        ]);
1165        let roster = decode_room(&raw, "room@chatroom").unwrap();
1166        assert_eq!(roster.administrator_ids.unwrap(), ["alice", "bob"]);
1167        assert!(roster.members.is_empty());
1168        assert!(roster.full_member_ids.is_none());
1169    }
1170
1171    #[test]
1172    fn room_administrator_absent_or_zero_control_preserves_list() {
1173        for extra in [
1174            vec![],
1175            vec![0x40, 0x00],
1176            vec![0x4a, 0x07, 0x0a, 0x05, b'a', b'l', b'i', b'c', b'e'],
1177            vec![
1178                0x40, 0x00, 0x4a, 0x07, 0x0a, 0x05, b'a', b'l', b'i', b'c', b'e',
1179            ],
1180        ] {
1181            assert!(
1182                decode_room(&room_administrator_fixture(&extra), "room@chatroom")
1183                    .unwrap()
1184                    .administrator_ids
1185                    .is_none()
1186            );
1187        }
1188        // Persisted metadata receipts from before this field was understood
1189        // preserve the cached administrator list when deserialized.
1190        let old: RoomRoster = serde_json::from_value(serde_json::json!({
1191            "room_id":"room@chatroom", "version":7, "members":[]
1192        }))
1193        .unwrap();
1194        assert!(old.administrator_ids.is_none());
1195    }
1196
1197    #[test]
1198    fn room_administrator_control_clears_absent_and_empty_entries() {
1199        for extra in [
1200            vec![0x40, 0x01],
1201            vec![0x40, 0x01, 0x4a, 0x00],
1202            vec![0x40, 0x01, 0x4a, 0x02, 0x0a, 0x00],
1203        ] {
1204            assert_eq!(
1205                decode_room(&room_administrator_fixture(&extra), "room@chatroom")
1206                    .unwrap()
1207                    .administrator_ids,
1208                Some(vec![])
1209            );
1210        }
1211    }
1212
1213    #[test]
1214    fn room_administrator_fields_reject_malformed_and_unbounded_values() {
1215        let string = |value: &[u8]| p::bytes(9, &p::bytes(1, value));
1216        let repeated = string(b"alice");
1217        for extra in [
1218            p::bytes(8, &[]),
1219            p::uint(8, u64::from(u32::MAX) + 1),
1220            [p::uint(8, 1), p::uint(8, 1)].concat(),
1221            p::uint(9, 1),
1222            p::bytes(9, &[0x0a, 0x01]),
1223            p::bytes(9, &p::uint(1, 1)),
1224            p::bytes(9, &[p::bytes(1, b"a"), p::bytes(1, b"b")].concat()),
1225            string(&[0xff]),
1226            string(b"alice bob"),
1227            string(b"alice\n"),
1228            string(&[b'a'; 257]),
1229            [repeated.clone(), repeated].concat(),
1230            p::bytes(9, &[]).repeat(10001),
1231        ] {
1232            assert!(decode_room(&room_administrator_fixture(&extra), "room@chatroom").is_err());
1233        }
1234    }
1235    fn cursor(k: u64, v: u64) -> Vec<u8> {
1236        p::message(&[
1237            p::uint(1, 1),
1238            p::bytes(2, &p::message(&[p::uint(1, k), p::uint(2, v)]).unwrap()),
1239        ])
1240        .unwrap()
1241    }
1242    #[test]
1243    fn explicit_code1_contact_slot_does_not_hide_successful_neighbor() {
1244        let requested = vec!["unavailable".into(), "available".into()];
1245        let empty = p::bytes(1, &[]);
1246        let available = p::bytes(1, &p::bytes(1, b"available"));
1247        for codes in [
1248            p::bytes(4, &[1, 0]),
1249            p::message(&[p::uint(4, 1), p::uint(4, 0)]).unwrap(),
1250        ] {
1251            let raw = p::message(&[
1252                p::bytes(1, &p::uint(1, 0)),
1253                p::uint(2, 2),
1254                p::bytes(3, &empty),
1255                p::bytes(3, &available),
1256                codes,
1257            ])
1258            .unwrap();
1259            let result = decode_contacts(&raw, &requested).unwrap();
1260            assert_eq!(result.results, vec![1, 0]);
1261            assert_eq!(result.contacts.len(), 1);
1262            assert_eq!(result.contacts[0].username, "available");
1263            assert!(decode_contact_record(&empty).is_err());
1264        }
1265    }
1266    #[test]
1267    fn contact_result_overflow_cannot_alias_success_or_unavailable() {
1268        let requested = vec!["unavailable".into(), "available".into()];
1269        let empty = p::bytes(1, &[]);
1270        let available = p::bytes(1, &p::bytes(1, b"available"));
1271        for overflow in [1u64 << 32, (1u64 << 32) + 1, (1u64 << 32) + u32::MAX as u64] {
1272            let packed = p::uint(1, overflow)[1..].to_vec();
1273            for codes in [
1274                p::message(&[p::uint(4, overflow), p::uint(4, 0)]).unwrap(),
1275                p::bytes(4, &[packed.as_slice(), &[0]].concat()),
1276            ] {
1277                let raw = p::message(&[
1278                    p::bytes(1, &p::uint(1, 0)),
1279                    p::uint(2, 2),
1280                    p::bytes(3, &empty),
1281                    p::bytes(3, &available),
1282                    codes,
1283                ])
1284                .unwrap();
1285                assert!(decode_contacts(&raw, &requested).is_err());
1286            }
1287        }
1288        assert_eq!(contact_result_code(0).unwrap(), 0);
1289        assert_eq!(contact_result_code(1).unwrap(), 1);
1290        assert_eq!(contact_result_code(u32::MAX as u64).unwrap(), -1);
1291        assert_eq!(contact_result_code(u64::MAX).unwrap(), -1);
1292        assert_eq!(
1293            contact_result_code(i32::MIN as i64 as u64).unwrap(),
1294            i32::MIN
1295        );
1296    }
1297    #[test]
1298    fn unexplained_empty_contact_slots_and_unproved_alignment_remain_errors() {
1299        let ids = vec!["unavailable".into(), "available".into()];
1300        let empty = p::bytes(1, &[]);
1301        let available = p::bytes(1, &p::bytes(1, b"available"));
1302        for codes in [vec![], p::bytes(4, &[0, 0]), p::bytes(4, &[2, 0])] {
1303            let raw = p::message(&[
1304                p::bytes(1, &p::uint(1, 0)),
1305                p::uint(2, 2),
1306                p::bytes(3, &empty),
1307                p::bytes(3, &available),
1308                codes,
1309            ])
1310            .unwrap();
1311            assert!(decode_contacts(&raw, &ids).is_err());
1312        }
1313        let partial = p::message(&[
1314            p::bytes(1, &p::uint(1, 0)),
1315            p::uint(2, 1),
1316            p::bytes(3, &empty),
1317            p::bytes(4, &[1, 0]),
1318        ])
1319        .unwrap();
1320        assert!(decode_contacts(&partial, &ids).is_err());
1321        let wrong = p::message(&[
1322            p::bytes(1, &p::uint(1, 0)),
1323            p::uint(2, 2),
1324            p::bytes(3, &empty),
1325            p::bytes(3, &p::bytes(1, &p::bytes(1, b"unavailable"))),
1326            p::bytes(4, &[1, 0]),
1327        ])
1328        .unwrap();
1329        assert!(decode_contacts(&wrong, &ids).is_err());
1330        let absent = p::message(&[
1331            p::bytes(1, &p::uint(1, 0)),
1332            p::uint(2, 2),
1333            p::bytes(3, &[]),
1334            p::bytes(3, &available),
1335            p::bytes(4, &[1, 0]),
1336        ])
1337        .unwrap();
1338        assert!(decode_contacts(&absent, &ids).is_err());
1339    }
1340    #[test]
1341    fn cursor_merge_and_reset() {
1342        assert_eq!(
1343            decode_cursor(&apply_cursor(&cursor(1, 9), &cursor(1, 2), 0).unwrap()).unwrap(),
1344            vec![(1, 9)]
1345        );
1346        assert_eq!(
1347            apply_cursor(&cursor(1, 9), &cursor(1, 2), -2006).unwrap(),
1348            cursor(1, 2)
1349        );
1350        assert!(apply_cursor(&[], &[], 3).is_err());
1351    }
1352    #[test]
1353    fn send_u64_ids_lossless() {
1354        let item = p::message(&[
1355            p::uint(1, 0),
1356            p::bytes(2, &p::bytes(1, b"filehelper")),
1357            p::uint(3, 0),
1358            p::uint(4, 99),
1359            p::uint(5, 0),
1360            p::uint(6, 0),
1361            p::uint(7, 0),
1362            p::uint(8, u64::MAX),
1363        ])
1364        .unwrap();
1365        let response = p::message(&[
1366            p::bytes(1, &p::uint(1, 0)),
1367            p::uint(2, 1),
1368            p::bytes(3, &item),
1369        ])
1370        .unwrap();
1371        assert_eq!(
1372            decode_text_send(&response, "filehelper", 99)
1373                .unwrap()
1374                .server_message_id,
1375            Some(u64::MAX.to_string())
1376        );
1377    }
1378    #[test]
1379    fn foreign_room_rejected() {
1380        let response = p::message(&[
1381            p::bytes(1, &p::uint(1, 0)),
1382            p::bytes(2, b"foreign@chatroom"),
1383            p::uint(3, 0),
1384            p::bytes(4, &p::uint(1, 0)),
1385        ])
1386        .unwrap();
1387        assert!(decode_room(&response, "known@chatroom").is_err());
1388    }
1389    #[test]
1390    fn native_client_id_vectors_include_signed_tail_bytes() {
1391        for (data, expected) in [
1392            (b"".to_vec(), 0),
1393            (b"a".to_vec(), 291415938),
1394            (b"abc".to_vec(), 3535673738),
1395            (b"native_test_0123456789".to_vec(), 483784200),
1396            (vec![255], 0),
1397            (vec![1, 2, 255], 2571803832),
1398            ((0..=255).collect(), 3840866583),
1399        ] {
1400            assert_eq!(client_message_id(&data), expected);
1401        }
1402    }
1403    #[test]
1404    fn text_source_is_optional_length_delimited_item_field_six() {
1405        let request = text_send_request_with_source("r", "x", 1, 2, Some("<msgsource/>")).unwrap();
1406        // One outer item; its nested destination is field 1, scalars 3/4/5
1407        // remain varints, and the source uses tag 0x32 (field 6, wire 2).
1408        assert_eq!(
1409            hex::encode(request),
1410            "0801121c0a030a0172120178180120012802320c3c6d7367736f757263652f3e"
1411        );
1412        let plain = text_send_request("r", "x", 1, 2).unwrap();
1413        assert_eq!(
1414            plain,
1415            text_send_request_with_source("r", "x", 1, 2, None).unwrap()
1416        );
1417        assert_eq!(
1418            plain,
1419            text_send_request_with_source("r", "x", 1, 2, Some("")).unwrap()
1420        );
1421        assert!(
1422            text_send_request_with_source("r", "x", 1, 2, Some(&"x".repeat(256 * 1024 + 1)))
1423                .is_err()
1424        );
1425    }
1426    #[test]
1427    fn addmsg_preserves_numbered_fields_and_opaque_source() {
1428        let payload = p::message(&[
1429            p::uint(1, 7),
1430            p::bytes(2, &p::bytes(1, b"room@chatroom")),
1431            p::bytes(3, &p::bytes(1, b"synthetic-self")),
1432            p::uint(4, 1),
1433            p::bytes(5, &p::bytes(1, b"synthetic content")),
1434            p::uint(6, 123),
1435            p::uint(7, 456),
1436            p::bytes(8, &p::buffer(&[])),
1437            p::uint(9, 999),
1438            p::bytes(10, b"<msgsource/>"),
1439            p::bytes(11, &[255, 0]),
1440            p::uint(12, u64::MAX),
1441            p::uint(13, 789),
1442        ])
1443        .unwrap();
1444        let decoded = decode_add_message(&payload, "synthetic-self").unwrap();
1445        assert_eq!(decoded.peer, "room@chatroom");
1446        assert!(decoded.sender_id.is_none());
1447        assert_eq!(decoded.server_message_id, Some(u64::MAX.to_string()));
1448        assert_eq!(decoded.numbered13, Some(789));
1449        assert_eq!(decoded.opaque11, Some(vec![255, 0]));
1450        assert_eq!(decoded.raw, payload);
1451    }
1452}