Skip to main content

wechat_protocol/
quote_send.rs

1//! Quoted app-message metadata. Callers resolve the selected message and persist
2//! this reference and the final XML before submitting a send attempt.
3use crate::{protobuf as p, wire::base_request, AccountState};
4use anyhow::{ensure, Result};
5use serde::{Deserialize, Serialize};
6
7pub const MAX_QUOTE_CONTENT_BYTES: usize = 128 * 1024;
8pub const MAX_QUOTE_XML_BYTES: usize = 256 * 1024;
9
10/// A reference to the immediate selected message. App messages retain raw type
11/// 49 here; their application subtype belongs in their serialized content.
12#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(deny_unknown_fields)]
14pub struct QuoteReference {
15    pub message_type: i32,
16    pub server_id: String,
17    pub from_user: String,
18    pub chat_user: String,
19    pub display_name: String,
20    pub content: String,
21    pub created_at: u32,
22    pub msg_source: Option<String>,
23}
24
25fn valid_text(value: &str, max: usize, empty: bool) -> bool {
26    (empty || !value.is_empty())
27        && value.len() <= max
28        && value.chars().all(|c| {
29            (!c.is_control() || matches!(c, '\t' | '\n' | '\r'))
30                && !matches!(c, '\u{fffe}' | '\u{ffff}')
31        })
32}
33
34fn identity(value: &str, empty: bool) -> bool {
35    valid_text(value, 256, empty)
36        && !value
37            .chars()
38            .any(|character| character.is_control() || character.is_whitespace())
39}
40
41impl QuoteReference {
42    pub fn validate(&self) -> Result<()> {
43        let server_id = self.server_id.parse::<u64>();
44        ensure!(
45            matches!(self.message_type, 1 | 3 | 34 | 43 | 47 | 49)
46                && server_id.is_ok_and(|value| value > 0 && value.to_string() == self.server_id)
47                && self.created_at > 0
48                && self.created_at <= i32::MAX as u32
49                && identity(&self.from_user, false)
50                && identity(&self.chat_user, true)
51                && valid_text(&self.display_name, 16 * 1024, true)
52                && valid_text(&self.content, MAX_QUOTE_CONTENT_BYTES, false)
53                && self.msg_source.as_deref().is_none_or(|value| valid_text(
54                    value,
55                    16 * 1024,
56                    true
57                )),
58            "invalid_quote_reference"
59        );
60        Ok(())
61    }
62}
63
64fn tag(out: &mut String, name: &str, value: &str) {
65    out.push('<');
66    out.push_str(name);
67    out.push('>');
68    for character in value.chars() {
69        match character {
70            '&' => out.push_str("&amp;"),
71            '<' => out.push_str("&lt;"),
72            '>' => out.push_str("&gt;"),
73            '"' => out.push_str("&quot;"),
74            '\'' => out.push_str("&apos;"),
75            _ => out.push(character),
76        }
77    }
78    out.push_str("</");
79    out.push_str(name);
80    out.push('>');
81}
82
83/// Build an appmsg fragment, followed by fromusername, as required by the
84/// app-message carrier. Embedded source XML remains text inside content.
85pub fn quote_xml(sender: &str, text: &str, reference: &QuoteReference) -> Result<String> {
86    reference.validate()?;
87    ensure!(
88        identity(sender, false) && !text.trim().is_empty() && valid_text(text, 16 * 1024, false),
89        "invalid_quote_request"
90    );
91    let mut out = String::from("<appmsg appid=\"\" sdkver=\"0\">");
92    for (name, value) in [
93        ("title", text),
94        ("des", ""),
95        ("action", ""),
96        ("type", "57"),
97        ("showtype", "0"),
98        ("url", ""),
99        ("lowurl", ""),
100    ] {
101        tag(&mut out, name, value);
102    }
103    out.push_str("<refermsg>");
104    tag(&mut out, "type", &reference.message_type.to_string());
105    tag(&mut out, "svrid", &reference.server_id);
106    tag(&mut out, "fromusr", &reference.from_user);
107    tag(&mut out, "chatusr", &reference.chat_user);
108    tag(&mut out, "displayname", &reference.display_name);
109    tag(&mut out, "content", &reference.content);
110    tag(&mut out, "createtime", &reference.created_at.to_string());
111    if let Some(source) = reference
112        .msg_source
113        .as_deref()
114        .filter(|value| !value.is_empty())
115    {
116        tag(&mut out, "msgsource", source);
117    }
118    out.push_str("</refermsg></appmsg>");
119    tag(&mut out, "fromusername", sender);
120    ensure!(out.len() <= MAX_QUOTE_XML_BYTES, "invalid_quote_request");
121    Ok(out)
122}
123
124/// Submit the persisted quote XML with the reply subtype in AppMsg.Type.
125/// Reference MsgSource inside the XML is separate from outgoing MsgSource.
126pub fn quote_send_request(
127    state: &AccountState,
128    destination: &str,
129    client_id: &str,
130    created_at: u32,
131    content: &str,
132) -> Result<Vec<u8>> {
133    ensure!(
134        identity(&state.own_username, false)
135            && identity(destination, false)
136            && valid_text(client_id, 1024, false)
137            && !client_id.chars().any(char::is_control)
138            && created_at > 0
139            && valid_text(content, MAX_QUOTE_XML_BYTES, false),
140        "invalid_quote_request"
141    );
142    let app = p::message(&[
143        p::bytes(1, state.own_username.as_bytes()),
144        p::bytes(2, &[]),
145        p::uint(3, 0),
146        p::bytes(4, destination.as_bytes()),
147        p::uint(5, 57),
148        p::bytes(6, content.as_bytes()),
149        p::uint(7, u64::from(created_at)),
150        p::bytes(8, client_id.as_bytes()),
151        p::int32(10, 1),
152        p::bytes(13, &[]),
153        p::bytes(14, &[]),
154        p::bytes(15, &[]),
155    ])?;
156    p::message(&[
157        p::bytes(1, &base_request(&state.device, state.uin, 0)?),
158        p::bytes(2, &app),
159        // The supported AppMsg builder includes this field even when no
160        // attachment checksum is present.
161        p::bytes(5, &[]),
162        p::uint(9, 0),
163        p::uint(10, 0),
164        p::uint(11, 2),
165    ])
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    fn reference() -> QuoteReference {
173        QuoteReference {
174            message_type: 49,
175            server_id: u64::MAX.to_string(),
176            from_user: "example@chatroom".into(),
177            chat_user: "quoted-user".into(),
178            display_name: "Someone <A>".into(),
179            content: "<msg><appmsg><type>6</type><title>report & plan</title></appmsg></msg>"
180                .into(),
181            created_at: 1234566,
182            msg_source: Some("<msgsource><flag>1</flag></msgsource>".into()),
183        }
184    }
185
186    fn state() -> AccountState {
187        AccountState {
188            schema: 1,
189            device: crate::DeviceProfile {
190                device_id: vec![1; 16],
191                device_type: "UnifiedPCLinux synthetic x86_64".into(),
192                client_version: -227271398,
193            },
194            uin: 123,
195            own_username: "synthetic-user".into(),
196            cookie: vec![],
197            session_key: vec![1; 16],
198            request_key: vec![],
199            response_key: vec![],
200            auto_auth_key: vec![],
201            key_info: vec![],
202            database_password: vec![],
203            auth_snapshot: Default::default(),
204            long_host: "long.weixin.qq.com".into(),
205            short_host: "short.weixin.qq.com".into(),
206        }
207    }
208
209    #[test]
210    fn quote_fields_and_wire_match_independent_fixture() {
211        let fixture: serde_json::Value =
212            serde_json::from_str(include_str!("../fixtures/synthetic-quote-wire.json")).unwrap();
213        let xml = quote_xml("synthetic-user", "Reply <&> \"yes\"\n世界", &reference()).unwrap();
214        assert_eq!(xml, fixture["xml"]);
215        let request =
216            quote_send_request(&state(), "example@chatroom", "quote-client", 1234567, &xml)
217                .unwrap();
218        assert_eq!(hex::encode(&request), fixture["requestHex"]);
219        let outer = p::decode(&request).unwrap();
220        assert_eq!(
221            outer.iter().map(|field| field.number).collect::<Vec<_>>(),
222            [1, 2, 5, 9, 10, 11]
223        );
224        assert_eq!(p::data(&outer, 5).unwrap(), b"");
225        let app = p::decode(p::data(&outer, 2).unwrap()).unwrap();
226        assert_eq!(p::scalar(&app, 5).unwrap(), 57);
227        assert_eq!(p::data(&app, 6).unwrap(), xml.as_bytes());
228        assert!(p::optional_data(&app, 12).unwrap().is_none());
229        assert!(xml.contains("<msgsource>&lt;msgsource&gt;"));
230        assert!(xml.contains("<refermsg><type>49</type>"));
231        assert!(!xml.contains("<refermsg><type>6</type>"));
232    }
233
234    #[test]
235    fn content_is_encoded_as_text_without_expanding_nested_markup() {
236        let mut selected = reference();
237        selected.message_type = 1;
238        selected.chat_user.clear();
239        selected.display_name.clear();
240        selected.msg_source = Some(String::new());
241        selected.content = "literal </content><type>10002</type> &amp; ]]> ' \"".into();
242        let xml = quote_xml("synthetic-user", "comment", &selected).unwrap();
243        assert!(xml.contains("&lt;/content&gt;&lt;type&gt;10002&lt;/type&gt;"));
244        assert!(xml.contains("&amp;amp; ]]&gt; &apos; &quot;"));
245        assert!(!xml.contains("<type>10002</type>"));
246        assert!(!xml.contains("<msgsource>"));
247        assert!(xml.contains("<chatusr></chatusr><displayname></displayname>"));
248    }
249
250    #[test]
251    fn reference_validation_rejects_lossy_or_unsupported_values() {
252        for id in ["0", "01", "+1", "18446744073709551616", "1\n"] {
253            let mut selected = reference();
254            selected.server_id = id.into();
255            assert!(selected.validate().is_err(), "{id:?}");
256        }
257        for kind in [0, -1, 2, 42, 57, 10002] {
258            let mut selected = reference();
259            selected.message_type = kind;
260            assert!(selected.validate().is_err());
261        }
262        for control in ['\0', '\u{1}', '\u{fffe}', '\u{ffff}'] {
263            let mut selected = reference();
264            selected.content.push(control);
265            assert!(selected.validate().is_err());
266            assert!(quote_xml("synthetic-user", &control.to_string(), &reference()).is_err());
267        }
268        let mut selected = reference();
269        selected.created_at = 0;
270        assert!(selected.validate().is_err());
271        selected = reference();
272        selected.from_user.clear();
273        assert!(selected.validate().is_err());
274        for value in ["user name", "user\u{a0}name"] {
275            selected = reference();
276            selected.from_user = value.into();
277            assert!(selected.validate().is_err());
278            assert!(quote_xml(value, "comment", &reference()).is_err());
279            assert!(quote_send_request(&state(), value, "client", 1, "xml").is_err());
280        }
281        selected = reference();
282        selected.msg_source = Some("x".repeat(16 * 1024 + 1));
283        assert!(selected.validate().is_err());
284    }
285
286    #[test]
287    fn final_escaped_xml_and_request_size_remain_bounded() {
288        let mut selected = reference();
289        selected.content = "x".repeat(MAX_QUOTE_CONTENT_BYTES);
290        assert!(quote_xml("synthetic-user", "comment", &selected).is_ok());
291        selected.content.push('x');
292        assert!(selected.validate().is_err());
293        selected.content = "&".repeat(MAX_QUOTE_CONTENT_BYTES);
294        assert!(selected.validate().is_ok());
295        assert!(quote_xml("synthetic-user", "comment", &selected).is_err());
296        assert!(quote_xml("synthetic-user", " \n\t", &reference()).is_err());
297        assert!(quote_xml("synthetic-user", &"x".repeat(16 * 1024 + 1), &reference()).is_err());
298        assert!(quote_send_request(&state(), "dest\0", "client", 1, "xml").is_err());
299        assert!(quote_send_request(&state(), "dest", "client\n", 1, "xml").is_err());
300        assert!(quote_send_request(&state(), "dest", "client", 0, "xml").is_err());
301        assert!(quote_send_request(
302            &state(),
303            "dest",
304            "client",
305            1,
306            &"x".repeat(MAX_QUOTE_XML_BYTES + 1)
307        )
308        .is_err());
309    }
310}