Skip to main content

wacore_binary/
jid.rs

1use crate::node::NodeStr;
2use compact_str::CompactString;
3use std::fmt;
4use std::str::FromStr;
5
6/// Intermediate result from fast JID parsing.
7/// This avoids allocations by returning byte indices into the original string.
8#[derive(Debug, Clone, Copy)]
9pub struct ParsedJidParts<'a> {
10    pub user: &'a str,
11    pub server: &'a str,
12    pub agent: u8,
13    pub device: u16,
14    pub integrator: u16,
15}
16
17/// Decimal-only `u16` parser for the device and agent fields.
18///
19/// Deliberately not `str::parse`: `from_str_radix` is generic over radix and
20/// signedness and carries the branches to prove it, which the JID scanner pays
21/// on every device it splits out. The accepted grammar is the same one
22/// `u16::from_str` accepts — an optional `+`, then decimal digits, rejecting
23/// empty input and anything that overflows — and `decimal_fast_path_matches_u16_from_str`
24/// holds the two together. A `-` is a non-digit here for the same reason it is
25/// one in std: the sign is only recognised for signed types.
26#[inline]
27fn parse_u16_decimal(s: &str) -> Option<u16> {
28    let mut bytes = s.as_bytes();
29    if bytes.first() == Some(&b'+') {
30        bytes = &bytes[1..];
31    }
32    if bytes.is_empty() {
33        return None;
34    }
35
36    let mut value = 0u16;
37    for &byte in bytes {
38        let digit = byte.wrapping_sub(b'0');
39        if digit > 9 {
40            return None;
41        }
42        value = value.checked_mul(10)?.checked_add(digit as u16)?;
43    }
44    Some(value)
45}
46
47/// Single-pass JID parser optimized for hot paths.
48/// Scans the input string once to find all relevant separators (@, :)
49/// and returns slices into the original string without allocation.
50///
51/// Returns `None` for JIDs that need full validation (edge cases, unknown servers, etc.)
52#[inline]
53pub fn parse_jid_fast(s: &str) -> Option<ParsedJidParts<'_>> {
54    parse_jid_scan(s).map(|(parts, _)| parts)
55}
56
57/// Shared scanner behind [`parse_jid_fast`] and [`parse_jid_ref`]. The resolved
58/// [`Server`] comes back alongside the borrowed parts because the scan already
59/// had to classify the server to know whether dots in the user part are agent
60/// separators — returning it lets `parse_jid_ref` skip a second lookup.
61///
62/// `None` in the second slot means the server suffix is not one we know; the
63/// parts are still filled in (with the generic agent/device rules), which is
64/// what `parse_jid_fast`'s callers rely on.
65#[inline]
66fn parse_jid_scan(s: &str) -> Option<(ParsedJidParts<'_>, Option<Server>)> {
67    let bytes = s.as_bytes();
68
69    // One pass over the *user* part only: everything after `@` is the server,
70    // which carries no separators we care about, so the scan stops there.
71    let mut at = usize::MAX;
72    let mut colon_pos: Option<usize> = None;
73    let mut last_dot_pos: Option<usize> = None;
74
75    for (i, &b) in bytes.iter().enumerate() {
76        match b {
77            b'@' => {
78                at = i;
79                break;
80            }
81            b':' => colon_pos = Some(i),
82            b'.' => last_dot_pos = Some(i),
83            _ => {}
84        }
85    }
86
87    // No `@` (server-only JID) or an empty user: let the fallback validate it.
88    if at == usize::MAX || at == 0 {
89        return None;
90    }
91
92    let user_part = &s[..at];
93    let server_str = &s[at + 1..];
94    let server = Server::parse_known(server_str);
95
96    match server {
97        // LID user parts may contain dots, which are not agent separators.
98        Some(Server::Lid) => {
99            let (user, device) = match colon_pos {
100                Some(pos) => (&s[..pos], parse_u16_decimal(&s[pos + 1..at]).unwrap_or(0)),
101                None => (user_part, 0),
102            };
103            Some((
104                ParsedJidParts {
105                    user,
106                    server: server_str,
107                    agent: 0,
108                    device,
109                    integrator: 0,
110                },
111                server,
112            ))
113        }
114        // Everything else, phone users included (and unknown servers):
115        // `user.agent:device`, one rule. The dot is the agent on every server WA
116        // Web parses and never a device, which only ever follows a colon; the
117        // phone namespace had a carve-out reading it as one, and that turned a
118        // bare user into a request addressed at a device it never named.
119        _ => {
120            let (user_before_colon, device) = match colon_pos {
121                Some(pos) => (&s[..pos], parse_u16_decimal(&s[pos + 1..at]).unwrap_or(0)),
122                None => (user_part, 0),
123            };
124            // The scan already found the last dot, so the common case needs no
125            // second pass. Only a dot before the device separator is the agent,
126            // though, and a malformed device can hold one of its own
127            // (`123.4:x.y`) -- there the scanned dot is not the agent and the
128            // earlier one still is, so that case falls back to a reverse scan
129            // of the user. Getting this wrong is not cosmetic: it would parse
130            // to a different identity than the rendered form reparses to.
131            let agent_dot = match last_dot_pos {
132                Some(pos) if pos < user_before_colon.len() => Some(pos),
133                Some(_) => user_before_colon.rfind('.'),
134                None => None,
135            };
136            let (final_user, agent) = match agent_dot {
137                Some(dot_pos) => match parse_u16_decimal(&user_before_colon[dot_pos + 1..]) {
138                    Some(agent_val) if agent_val <= u8::MAX as u16 => {
139                        (&user_before_colon[..dot_pos], agent_val as u8)
140                    }
141                    _ => (user_before_colon, 0),
142                },
143                None => (user_before_colon, 0),
144            };
145            Some((
146                ParsedJidParts {
147                    user: final_user,
148                    server: server_str,
149                    agent,
150                    device,
151                    integrator: 0,
152                },
153                server,
154            ))
155        }
156    }
157}
158
159/// Parse the allocation-free JID shapes into the same borrowed type used by
160/// the binary decoder.
161///
162/// Returns `None` when the string needs [`Jid`]'s compatibility fallback or
163/// names an unknown server. Callers that must accept those edge cases can fall
164/// back to `s.parse::<Jid>()`; normal user/group/LID/bot JIDs stay borrowed.
165#[inline]
166pub fn parse_jid_ref(s: &str) -> Option<JidRef<'_>> {
167    let (parts, server) = parse_jid_scan(s)?;
168    Some(JidRef {
169        user: NodeStr::Borrowed(parts.user),
170        server: server?,
171        agent: parts.agent,
172        device: parts.device,
173        integrator: parts.integrator,
174    })
175}
176
177/// Known WhatsApp server identifiers.
178///
179/// Maps to the wire protocol's AD_JID domain type (u8) and the `@server` suffix
180/// in JID string representation.
181///
182/// New supported namespaces may gain variants. Unknown namespaces are rejected
183/// by parsing; they are never mapped into a known identity class.
184///
185/// ```
186/// use wacore_binary::Server;
187/// let server = Server::try_from("lid").unwrap();
188/// let phone_namespace = match server {
189///     Server::Pn | Server::Hosted => true,
190///     _ => false,
191/// };
192/// assert!(!phone_namespace);
193/// assert!(Server::try_from("future.invalid").is_err());
194/// ```
195#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
196#[repr(u8)]
197#[non_exhaustive]
198pub enum Server {
199    #[default]
200    Pn = 0,
201    Lid = 1,
202    Group = 2,
203    Broadcast = 3,
204    Newsletter = 4,
205    Hosted = 5,
206    HostedLid = 6,
207    Messenger = 7,
208    Interop = 8,
209    Bot = 9,
210    // 10 was the legacy `c.us` spelling of `Pn`, which `parse_known` now
211    // resolves. The gap is left rather than closed so no existing discriminant
212    // changes meaning.
213    /// `@call` call-signaling JID; not an AD server, so it round-trips via JID_PAIR.
214    Call = 11,
215}
216
217#[cfg(feature = "serde")]
218impl serde::Serialize for Server {
219    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
220        serializer.serialize_str(self.as_str())
221    }
222}
223
224#[cfg(feature = "serde")]
225impl<'de> serde::Deserialize<'de> for Server {
226    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
227        struct ServerVisitor;
228
229        impl serde::de::Visitor<'_> for ServerVisitor {
230            type Value = Server;
231
232            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
233                formatter.write_str("a known WhatsApp server identifier")
234            }
235
236            fn visit_borrowed_str<E>(self, value: &str) -> Result<Self::Value, E>
237            where
238                E: serde::de::Error,
239            {
240                Server::try_from(value).map_err(E::custom)
241            }
242
243            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
244            where
245                E: serde::de::Error,
246            {
247                Server::try_from(value).map_err(E::custom)
248            }
249
250            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
251            where
252                E: serde::de::Error,
253            {
254                Server::try_from(value.as_str()).map_err(E::custom)
255            }
256        }
257
258        deserializer.deserialize_str(ServerVisitor)
259    }
260}
261
262impl Server {
263    #[inline]
264    pub fn as_str(self) -> &'static str {
265        match self {
266            Self::Pn => "s.whatsapp.net",
267            Self::Lid => "lid",
268            Self::Group => "g.us",
269            Self::Broadcast => "broadcast",
270            Self::Newsletter => "newsletter",
271            Self::Hosted => "hosted",
272            Self::HostedLid => "hosted.lid",
273            Self::Messenger => "msgr",
274            Self::Interop => "interop",
275            Self::Bot => "bot",
276            Self::Call => "call",
277        }
278    }
279
280    /// The account-level (non-hosted) server variant for this server:
281    /// `Hosted` -> `Pn`, `HostedLid` -> `Lid`. Other servers return themselves.
282    /// (Matches WA Web `asUserWidOrThrow` / `createUserWidOrThrow` mapping `hosted` -> `c.us` and `hosted.lid` -> `lid`).
283    #[inline]
284    pub fn user_server(self) -> Self {
285        match self {
286            Self::Hosted => Self::Pn,
287            Self::HostedLid => Self::Lid,
288            server => server,
289        }
290    }
291
292    /// Returns the hosted or non-hosted server variant within this server's addressing family:
293    /// - PN family: `is_hosted` ? `Hosted` : `Pn`
294    /// - LID family: `is_hosted` ? `HostedLid` : `Lid`
295    /// - Other: unchanged
296    #[inline]
297    pub fn with_hosting(self, is_hosted: bool) -> Self {
298        match (self, is_hosted) {
299            (Self::Pn | Self::Hosted, true) => Self::Hosted,
300            (Self::Pn | Self::Hosted, false) => Self::Pn,
301            (Self::Lid | Self::HostedLid, true) => Self::HostedLid,
302            (Self::Lid | Self::HostedLid, false) => Self::Lid,
303            (server, _) => server,
304        }
305    }
306
307    /// Phone-number-namespaced servers (`@s.whatsapp.net`, `@hosted`).
308    /// The PN side of the LID↔PN mapping treats these as a single class.
309    #[inline]
310    pub fn is_pn_family(self) -> bool {
311        matches!(self, Self::Pn | Self::Hosted)
312    }
313
314    /// LID-namespaced servers (`@lid`, `@hosted.lid`).
315    #[inline]
316    pub fn is_lid_family(self) -> bool {
317        matches!(self, Self::Lid | Self::HostedLid)
318    }
319
320    /// Whether the `agent` byte is part of the rendered JID for this server.
321    /// AD-capable servers (Pn/Lid/Hosted/HostedLid) have no agent of their own —
322    /// their wire form spells the server as a domain byte, which the decoder
323    /// resolves into `server` rather than keeping — so an agent set on one is
324    /// meaningless and stays out of the rendered form. Others (e.g. `@bot`,
325    /// `@interop`) render it. Single source of truth shared by the formatter and
326    /// `Jid::is_same_chat_as`.
327    #[inline]
328    pub fn renders_agent(self) -> bool {
329        !matches!(self, Self::Pn | Self::Lid | Self::Hosted | Self::HostedLid)
330    }
331
332    /// Whether the `user` part is (or can be) a real phone number, i.e. PII that
333    /// must be redacted in tracing fields. LID-family/group/broadcast/newsletter/
334    /// bot/call users are pseudonymous or non-personal and are safe to render raw.
335    #[inline]
336    pub fn carries_phone_number(self) -> bool {
337        matches!(
338            self,
339            Self::Pn | Self::Hosted | Self::Messenger | Self::Interop
340        )
341    }
342}
343
344impl fmt::Display for Server {
345    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        f.write_str(self.as_str())
347    }
348}
349
350impl PartialEq<str> for Server {
351    fn eq(&self, other: &str) -> bool {
352        self.as_str() == other
353    }
354}
355
356impl PartialEq<&str> for Server {
357    fn eq(&self, other: &&str) -> bool {
358        self.as_str() == *other
359    }
360}
361
362impl Server {
363    /// Allocation-free server lookup. `TryFrom<&str>` builds a `JidError` —
364    /// and therefore a `String` — for an unknown suffix, which the JID scanner
365    /// hits on every non-JID string it is asked to classify; this returns the
366    /// same answer without paying for the message nobody reads.
367    #[inline]
368    pub fn parse_known(s: &str) -> Option<Self> {
369        Some(match s {
370            "s.whatsapp.net" => Self::Pn,
371            "lid" => Self::Lid,
372            "g.us" => Self::Group,
373            "broadcast" => Self::Broadcast,
374            "newsletter" => Self::Newsletter,
375            "hosted" => Self::Hosted,
376            "hosted.lid" => Self::HostedLid,
377            "msgr" => Self::Messenger,
378            "interop" => Self::Interop,
379            "bot" => Self::Bot,
380            // `c.us` is the other spelling of the phone namespace, not a
381            // namespace. Collapsing it in this converter -- the one text, the
382            // wire and serde all resolve through, and the same place WA Web
383            // collapses it -- is what leaves no variant able to render it back
384            // out, so one person cannot become two identities.
385            "c.us" => Self::Pn,
386            "call" => Self::Call,
387            _ => return None,
388        })
389    }
390}
391
392impl TryFrom<&str> for Server {
393    type Error = JidError;
394    fn try_from(s: &str) -> Result<Self, Self::Error> {
395        Server::parse_known(s)
396            .ok_or_else(|| JidError::InvalidFormat(format!("unknown server ({} bytes)", s.len())))
397    }
398}
399
400// Keep string constants for backward compatibility and use in non-JID contexts
401pub const DEFAULT_USER_SERVER: &str = "s.whatsapp.net";
402pub const SERVER_JID: &str = "s.whatsapp.net";
403pub const GROUP_SERVER: &str = "g.us";
404pub const LEGACY_USER_SERVER: &str = "c.us";
405pub const BROADCAST_SERVER: &str = "broadcast";
406pub const HIDDEN_USER_SERVER: &str = "lid";
407pub const NEWSLETTER_SERVER: &str = "newsletter";
408pub const HOSTED_SERVER: &str = "hosted";
409pub const HOSTED_LID_SERVER: &str = "hosted.lid";
410pub const MESSENGER_SERVER: &str = "msgr";
411pub const INTEROP_SERVER: &str = "interop";
412pub const BOT_SERVER: &str = "bot";
413pub const STATUS_BROADCAST_USER: &str = "status";
414pub const PSA_USER: &str = "0";
415
416/// A message id, inline: WhatsApp ids are 20–32 hex/base64 characters, and
417/// every client-generated one is 22, so the common case pays no heap
418/// allocation per message, per receipt id and per dedup-cache key.
419///
420/// The inline budget is `size_of::<String>()`, 24 bytes on a 64-bit target.
421/// On a 32-bit target (wasm32, ESP32) it is 12, so a 22-character id still
422/// heap-allocates there: no worse than the `String` it replaced, and the
423/// `&str` surface is the same, but the allocation saving is 64-bit-only.
424pub type MessageId = CompactString;
425pub type MessageServerId = i32;
426#[derive(Debug)]
427pub enum JidError {
428    // REMOVE: #[error("...")]
429    InvalidFormat(String),
430    // REMOVE: #[error("...")]
431    Parse(std::num::ParseIntError),
432}
433
434impl fmt::Display for JidError {
435    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
436        match self {
437            JidError::InvalidFormat(s) => write!(f, "Invalid JID format: {s}"),
438            JidError::Parse(e) => write!(f, "Failed to parse component: {e}"),
439        }
440    }
441}
442
443impl std::error::Error for JidError {
444    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
445        match self {
446            JidError::Parse(e) => Some(e),
447            _ => None,
448        }
449    }
450}
451
452// Add From impl
453impl From<std::num::ParseIntError> for JidError {
454    fn from(err: std::num::ParseIntError) -> Self {
455        JidError::Parse(err)
456    }
457}
458
459pub trait JidExt {
460    fn user(&self) -> &str;
461    fn server(&self) -> Server;
462    fn device(&self) -> u16;
463    fn integrator(&self) -> u16;
464
465    fn is_ad(&self) -> bool {
466        self.device() > 0
467            && matches!(
468                self.server(),
469                Server::Pn | Server::Lid | Server::Hosted | Server::HostedLid
470            )
471    }
472
473    fn is_interop(&self) -> bool {
474        self.server() == Server::Interop && self.integrator() > 0
475    }
476
477    fn is_messenger(&self) -> bool {
478        self.server() == Server::Messenger && self.device() > 0
479    }
480
481    fn is_group(&self) -> bool {
482        self.server() == Server::Group
483    }
484
485    fn is_broadcast_list(&self) -> bool {
486        self.server() == Server::Broadcast && self.user() != STATUS_BROADCAST_USER
487    }
488
489    fn is_status_broadcast(&self) -> bool {
490        self.server() == Server::Broadcast && self.user() == STATUS_BROADCAST_USER
491    }
492
493    /// The system/announcements account (`0@s.whatsapp.net`, however spelled).
494    /// It never answers user-directed IQs, so requests must be short-circuited
495    /// client-side (WA Web excludes it via `isPSA` before hitting the server).
496    fn is_psa(&self) -> bool {
497        self.server() == Server::Pn && self.user() == PSA_USER
498    }
499
500    fn is_bot(&self) -> bool {
501        (self.server() == Server::Pn
502            && self.device() == 0
503            && (self.user().starts_with("1313555") || self.user().starts_with("131655500")))
504            || self.server() == Server::Bot
505    }
506
507    fn is_newsletter(&self) -> bool {
508        self.server() == Server::Newsletter
509    }
510
511    /// Returns true if this is a hosted/Cloud API device.
512    /// Hosted devices have device ID 99 or use @hosted/@hosted.lid server.
513    /// These devices should be excluded from group message fanout.
514    fn is_hosted(&self) -> bool {
515        self.device() == 99 || matches!(self.server(), Server::Hosted | Server::HostedLid)
516    }
517
518    fn is_empty(&self) -> bool {
519        self.user().is_empty()
520    }
521
522    fn is_same_user_as(&self, other: &impl JidExt) -> bool {
523        self.user() == other.user()
524    }
525}
526
527/// The part of `agent` that is actually part of a JID's identity.
528///
529/// `agent` is only meaningful where the server renders it. On Pn/Lid/Hosted/
530/// HostedLid the wire spells the server as a domain byte instead, so nothing
531/// encodes an agent set there (`server_to_domain_type`), nothing prints it
532/// (`renders_agent`), and nothing hashes it (`push_phash_form_to` writes a literal `0`,
533/// matching WA Web). Two JIDs differing only there address the same device.
534/// A phone user parsed from `user.<n>@...` lands here: WA Web reads that
535/// position as the agent too and drops it (`stripAgentIdFromPhoneDeviceJid`),
536/// and this is what makes keeping it inert equivalent to dropping it.
537///
538/// Letting it into equality anyway is what made a JID decoded from the wire
539/// unequal to the same JID read back from the store, which holds JIDs as text
540/// (see `read_ad_jid`). Equality and `Hash` both go through here so they cannot
541/// disagree, and `sort_dedup_by_device` keys on the same rule so the fan-out
542/// cannot treat one device as two.
543///
544/// `integrator` is deliberately NOT normalised here. It is only ever non-zero on
545/// interop, but `is_same_chat_as` and `jids_share_user_identity` compare it
546/// unconditionally — folding it in here would make `==` disagree with them.
547#[inline]
548fn identity_agent(server: Server, agent: u8) -> u8 {
549    if server.renders_agent() { agent } else { 0 }
550}
551
552/// Fixed-width identity metadata avoids four separate hasher writes. Disjoint
553/// bit ranges preserve every field that equality observes, including integrator.
554#[inline]
555fn identity_word(server: Server, agent: u8, device: u16, integrator: u16) -> u64 {
556    (server as u8 as u64)
557        | (device as u64) << 8
558        | (integrator as u64) << 24
559        | (identity_agent(server, agent) as u64) << 40
560}
561
562#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
563#[derive(Debug, Clone, Default)]
564pub struct Jid {
565    /// Inline while it fits in `size_of::<String>()`: 24 bytes on a 64-bit host,
566    /// 12 on the wasm32/32-bit builds. Phone, LID and modern group users clear
567    /// the wide budget, not the narrow one; a legacy `<creator>-<timestamp>`
568    /// group id clears neither. See `tests/jid_identity_alloc`.
569    pub user: CompactString,
570    pub server: Server,
571    pub agent: u8,
572    pub device: u16,
573    pub integrator: u16,
574}
575
576#[derive(Debug, Clone, yoke_derive::Yokeable)]
577pub struct JidRef<'a> {
578    pub user: NodeStr<'a>,
579    pub server: Server,
580    pub agent: u8,
581    pub device: u16,
582    pub integrator: u16,
583}
584
585impl JidExt for Jid {
586    fn user(&self) -> &str {
587        &self.user
588    }
589    fn server(&self) -> Server {
590        self.server
591    }
592    fn device(&self) -> u16 {
593        self.device
594    }
595    fn integrator(&self) -> u16 {
596        self.integrator
597    }
598}
599
600impl Jid {
601    pub fn new(user: impl Into<CompactString>, server: Server) -> Self {
602        Self {
603            user: user.into(),
604            server,
605            ..Default::default()
606        }
607    }
608
609    /// Create a phone number JID (s.whatsapp.net)
610    pub fn pn(user: impl Into<CompactString>) -> Self {
611        Self {
612            user: user.into(),
613            server: Server::Pn,
614            ..Default::default()
615        }
616    }
617
618    /// Create a LID JID (lid server)
619    pub fn lid(user: impl Into<CompactString>) -> Self {
620        Self {
621            user: user.into(),
622            server: Server::Lid,
623            ..Default::default()
624        }
625    }
626
627    /// Creates the `status@broadcast` JID used for status/story updates.
628    pub fn status_broadcast() -> Self {
629        Self {
630            user: CompactString::from(STATUS_BROADCAST_USER),
631            server: Server::Broadcast,
632            agent: 0,
633            device: 0,
634            integrator: 0,
635        }
636    }
637
638    /// Create a group JID (g.us).
639    pub fn group(id: impl Into<CompactString>) -> Self {
640        Self {
641            user: id.into(),
642            server: Server::Group,
643            ..Default::default()
644        }
645    }
646
647    /// Create a newsletter (channel) JID (newsletter server).
648    pub fn newsletter(id: impl Into<CompactString>) -> Self {
649        Self {
650            user: id.into(),
651            server: Server::Newsletter,
652            ..Default::default()
653        }
654    }
655
656    /// Create a phone number JID with device ID
657    pub fn pn_device(user: impl Into<CompactString>, device: u16) -> Self {
658        Self {
659            user: user.into(),
660            server: Server::Pn,
661            device,
662            ..Default::default()
663        }
664    }
665
666    /// Create a LID JID with device ID
667    pub fn lid_device(user: impl Into<CompactString>, device: u16) -> Self {
668        Self {
669            user: user.into(),
670            server: Server::Lid,
671            device,
672            ..Default::default()
673        }
674    }
675
676    /// Returns true if this is a Phone Number based JID (s.whatsapp.net)
677    #[inline]
678    pub fn is_pn(&self) -> bool {
679        self.server == Server::Pn
680    }
681
682    /// Returns true if this is a LID based JID
683    #[inline]
684    pub fn is_lid(&self) -> bool {
685        self.server == Server::Lid
686    }
687
688    /// Returns the user part without the device ID suffix (e.g., "123:4" -> "123")
689    #[inline]
690    pub fn user_base(&self) -> &str {
691        if let Some((base, _)) = self.user.split_once(':') {
692            base
693        } else {
694            &self.user
695        }
696    }
697
698    /// Helper to construct a specific device JID from this one
699    pub fn with_device(&self, device_id: u16) -> Self {
700        Self {
701            user: self.user.clone(),
702            server: self.server,
703            agent: self.agent,
704            device: device_id,
705            integrator: self.integrator,
706        }
707    }
708
709    /// Construct a device JID and select the hosted variant of PN/LID when
710    /// indicated by a device-list entry.
711    ///
712    /// Non-user namespaces are left unchanged because they have no hosted
713    /// counterpart on the wire.
714    pub fn with_device_hosting(&self, device_id: u16, is_hosted: bool) -> Self {
715        let mut jid = self.with_device(device_id);
716        jid.server = jid.server.with_hosting(is_hosted);
717        jid
718    }
719
720    pub fn to_non_ad(&self) -> Self {
721        Self {
722            user: self.user.clone(),
723            server: self.server,
724            integrator: self.integrator,
725            ..Default::default()
726        }
727    }
728
729    /// Returns the non-AD user JID representing the account for this JID,
730    /// dropping any device/agent and mapping hosted servers to their ordinary
731    /// account counterparts (`Hosted` -> `Pn`, `HostedLid` -> `Lid`).
732    /// (Matches WA Web `asUserWidOrThrow`).
733    pub fn to_user_jid(&self) -> Self {
734        Self {
735            user: self.user.clone(),
736            server: self.server.user_server(),
737            integrator: self.integrator,
738            ..Default::default()
739        }
740    }
741
742    /// Consuming `to_non_ad`: reuses the owned `user` instead of cloning it.
743    /// Prefer this when the receiver is a throwaway owned `Jid`.
744    pub fn into_non_ad(self) -> Self {
745        Self {
746            user: self.user,
747            server: self.server,
748            integrator: self.integrator,
749            agent: 0,
750            device: 0,
751        }
752    }
753
754    /// Device-insensitive "same chat" check: two JIDs address the same chat when
755    /// they render to the same string ignoring the multi-device `device`. Compares
756    /// `user`, `server`, `integrator`, and `agent` only where the server renders
757    /// the agent (`@bot`/`@interop`); Pn/Lid/Hosted suppress it in display, so a
758    /// stray decoded agent byte there must not split the chat. Allocates nothing.
759    /// Stricter than `is_same_user_as`, which ignores `server`.
760    #[inline]
761    pub fn is_same_chat_as(&self, other: &Jid) -> bool {
762        self.user == other.user
763            && self.server == other.server
764            && self.integrator == other.integrator
765            && (!self.server.renders_agent() || self.agent == other.agent)
766    }
767
768    /// Canonical non-AD string form (`user@server`, device + agent stripped)
769    /// in a single allocation. Equivalent to `to_non_ad().to_string()` but
770    /// skips the throwaway intermediate `Jid` and its `CompactString` clone.
771    pub fn to_non_ad_string(&self) -> String {
772        let mut buf = String::with_capacity(self.user.len() + 1 + self.server.as_str().len());
773        push_jid_to_string(&self.user, self.server, 0, 0, &mut buf);
774        buf
775    }
776
777    /// [`Self::to_non_ad_string`] as a shareable `Arc<str>`, in exactly one
778    /// allocation. Going through the `String` first costs two — the buffer, then
779    /// the `Arc<str>` its bytes are copied into — and the message-secret rows
780    /// build two of these per message.
781    pub fn to_non_ad_arc_str(&self) -> std::sync::Arc<str> {
782        let mut writer = JidStackWriter::new();
783        if write_jid_fallible(&mut writer, &self.user, self.server, 0, 0).is_ok() {
784            return std::sync::Arc::from(writer.as_str());
785        }
786        // A user part too long for the stack buffer (never seen on the wire)
787        // still renders, just back through the heap.
788        std::sync::Arc::from(self.to_non_ad_string())
789    }
790
791    /// Check if this JID matches the user or their LID.
792    /// Useful for checking if a participant is "us" in group messages.
793    #[inline]
794    pub fn matches_user_or_lid(&self, user: &Jid, lid: Option<&Jid>) -> bool {
795        self.is_same_user_as(user) || lid.is_some_and(|l| self.is_same_user_as(l))
796    }
797
798    /// See [`Jid::push_phash_form_to`]. Not a general JID rendering — use
799    /// `Display`/`to_string` for that.
800    pub fn to_phash_form_string(&self) -> String {
801        let mut s = String::with_capacity(self.user.len() + 20);
802        self.push_phash_form_to(&mut s);
803        s
804    }
805
806    /// Append the form the participant hash is computed over
807    /// (`user.0:device@server`) to `buf`, for callers that batch many JIDs into
808    /// one shared buffer instead of paying a heap `String` per JID (see
809    /// `participant_list_hash`).
810    ///
811    /// **This is not a general-purpose JID rendering.** The agent position is
812    /// the literal `0`, never `self.agent`, and that is deliberate: WA Web's
813    /// `formatFull` spelling hardcodes `".0"` unconditionally — there is no
814    /// per-server carve-out, and `WAWebWid` has no agent field to read one from.
815    /// The server recomputes this exact string to validate the phash, so writing
816    /// our agent would mean a rejected hash for any JID that carried one.
817    ///
818    /// If you want the JID as it is addressed, including the agent on the servers
819    /// that render it, use `Display` / [`Jid::push_to`] instead.
820    #[inline]
821    pub fn push_phash_form_to(&self, buf: &mut String) {
822        if self.user.is_empty() {
823            buf.push_str(self.server.as_str());
824            return;
825        }
826        buf.push_str(&self.user);
827        buf.push_str(".0:");
828        buf.push_str(itoa::Buffer::new().format(self.device));
829        buf.push('@');
830        buf.push_str(self.server.as_str());
831    }
832
833    /// Append the Display representation to `buf` using direct push operations,
834    /// bypassing `fmt::Display` and `dyn Write` dispatch.
835    #[inline]
836    pub fn push_to(&self, buf: &mut String) {
837        push_jid_to_string(&self.user, self.server, self.agent, self.device, buf);
838    }
839
840    /// Write the Display representation to any [`fmt::Write`] sink without an
841    /// intermediate `String`.
842    #[inline]
843    pub fn write_display_to<W: fmt::Write + ?Sized>(&self, writer: &mut W) -> fmt::Result {
844        write_jid_fallible(writer, &self.user, self.server, self.agent, self.device)
845    }
846
847    /// Compare the display representation with `other` without allocating.
848    #[inline]
849    pub fn display_eq(&self, other: &str) -> bool {
850        jid_display_eq(&self.user, self.server, self.agent, self.device, other)
851    }
852
853    /// Compare two JIDs by the representation emitted by [`fmt::Display`].
854    #[inline]
855    pub fn display_eq_jid(&self, other: &Self) -> bool {
856        jid_displays_equal(
857            (&self.user, self.server, self.agent, self.device),
858            (&other.user, other.server, other.agent, other.device),
859        )
860    }
861
862    /// Compare device identity (user, server, device) without allocation.
863    #[inline]
864    pub fn device_eq(&self, other: &Jid) -> bool {
865        self.user == other.user && self.server == other.server && self.device == other.device
866    }
867
868    /// The `agent` as far as identity is concerned: the field itself where the
869    /// server renders it (`@bot`, `@interop`), `0` where it does not.
870    ///
871    /// Exposed so callers that build their own key over a JID — sorting,
872    /// deduplicating, indexing — can key on the same rule `==` and `Hash` use
873    /// instead of on the raw field, which would split one device in two or, in
874    /// reverse, merge two real ones.
875    #[inline]
876    pub fn identity_agent(&self) -> u8 {
877        identity_agent(self.server, self.agent)
878    }
879
880    /// Get a borrowing key for O(1) HashSet lookups by device identity.
881    #[inline]
882    pub fn device_key(&self) -> DeviceKey<'_> {
883        DeviceKey {
884            user: &self.user,
885            server: self.server,
886            device: self.device,
887        }
888    }
889}
890
891/// Borrowing key for device identity (user, server, device). Use with HashSet for O(1) lookups.
892#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
893pub struct DeviceKey<'a> {
894    pub user: &'a str,
895    pub server: Server,
896    pub device: u16,
897}
898
899impl<'a> JidExt for JidRef<'a> {
900    fn user(&self) -> &str {
901        &self.user
902    }
903    fn server(&self) -> Server {
904        self.server
905    }
906    fn device(&self) -> u16 {
907        self.device
908    }
909    fn integrator(&self) -> u16 {
910        self.integrator
911    }
912}
913
914impl<'a> JidRef<'a> {
915    pub fn to_owned(&self) -> Jid {
916        Jid {
917            user: self.user.to_compact_string(),
918            server: self.server,
919            agent: self.agent,
920            device: self.device,
921            integrator: self.integrator,
922        }
923    }
924
925    /// Compare the display representation with `other` without allocating.
926    #[inline]
927    pub fn display_eq(&self, other: &str) -> bool {
928        jid_display_eq(&self.user, self.server, self.agent, self.device, other)
929    }
930
931    /// Compare two borrowed JIDs by the representation emitted by [`fmt::Display`].
932    #[inline]
933    pub fn display_eq_jid(&self, other: &Self) -> bool {
934        jid_displays_equal(
935            (&self.user, self.server, self.agent, self.device),
936            (&other.user, other.server, other.agent, other.device),
937        )
938    }
939}
940
941impl PartialEq for Jid {
942    #[inline]
943    fn eq(&self, other: &Self) -> bool {
944        self.user == other.user
945            && self.server == other.server
946            && self.device == other.device
947            && self.integrator == other.integrator
948            // Equal raw agents are already equal identity agents — the servers
949            // match by the check above, so both sides normalise the same way.
950            // Skipping the lookup in that case is worth it because it is the
951            // overwhelmingly common one: nothing off the wire carries an agent
952            // on the AD servers. Load-bearing on the `self.server == other.server`
953            // above; reordering these would make the shortcut wrong.
954            && (self.agent == other.agent
955                || identity_agent(self.server, self.agent)
956                    == identity_agent(other.server, other.agent))
957    }
958}
959
960impl Eq for Jid {}
961
962impl std::hash::Hash for Jid {
963    #[inline]
964    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
965        self.user.hash(state);
966        state.write_u64(identity_word(
967            self.server,
968            self.agent,
969            self.device,
970            self.integrator,
971        ));
972    }
973}
974
975impl PartialEq for JidRef<'_> {
976    #[inline]
977    fn eq(&self, other: &Self) -> bool {
978        self.user.as_ref() == other.user.as_ref()
979            && self.server == other.server
980            && self.device == other.device
981            && self.integrator == other.integrator
982            // See `PartialEq for Jid` for why the raw compare can short-circuit.
983            && (self.agent == other.agent
984                || identity_agent(self.server, self.agent)
985                    == identity_agent(other.server, other.agent))
986    }
987}
988
989impl Eq for JidRef<'_> {}
990
991impl std::hash::Hash for JidRef<'_> {
992    #[inline]
993    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
994        self.user.as_ref().hash(state);
995        state.write_u64(identity_word(
996            self.server,
997            self.agent,
998            self.device,
999            self.integrator,
1000        ));
1001    }
1002}
1003
1004impl PartialEq<JidRef<'_>> for Jid {
1005    #[inline]
1006    fn eq(&self, other: &JidRef<'_>) -> bool {
1007        self.user.as_str() == other.user.as_ref()
1008            && self.server == other.server
1009            && self.device == other.device
1010            && self.integrator == other.integrator
1011            // See `PartialEq for Jid`.
1012            && (self.agent == other.agent
1013                || identity_agent(self.server, self.agent)
1014                    == identity_agent(other.server, other.agent))
1015    }
1016}
1017
1018impl PartialEq<Jid> for JidRef<'_> {
1019    #[inline]
1020    fn eq(&self, other: &Jid) -> bool {
1021        other == self
1022    }
1023}
1024
1025#[cfg(feature = "serde")]
1026impl serde::Serialize for JidRef<'_> {
1027    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1028        use serde::ser::SerializeStruct;
1029        let mut s = serializer.serialize_struct("Jid", 5)?;
1030        s.serialize_field("user", &*self.user)?;
1031        s.serialize_field("server", &self.server)?;
1032        s.serialize_field("agent", &self.agent)?;
1033        s.serialize_field("device", &self.device)?;
1034        s.serialize_field("integrator", &self.integrator)?;
1035        s.end()
1036    }
1037}
1038
1039impl FromStr for Jid {
1040    type Err = JidError;
1041    fn from_str(s: &str) -> Result<Self, Self::Err> {
1042        // Try fast path first for well-formed JIDs
1043        if let Some(jid) = parse_jid_ref(s) {
1044            return Ok(jid.to_owned());
1045        }
1046
1047        // Fallback to original parsing for edge cases and validation
1048        // Keep server as &str to avoid allocation until we need it
1049        let (user_part, server) = match s.split_once('@') {
1050            Some((u, s)) => (u, s),
1051            None => ("", s),
1052        };
1053
1054        if user_part.is_empty() && Server::try_from(server).is_err() {
1055            return Err(JidError::InvalidFormat(format!(
1056                "unknown server ({} bytes)",
1057                server.len()
1058            )));
1059        }
1060
1061        // Special handling for LID JIDs, as their user part can contain dots
1062        // that should not be interpreted as agent separators.
1063        if server == HIDDEN_USER_SERVER {
1064            let (user, device) = if let Some((u, d_str)) = user_part.rsplit_once(':') {
1065                (u, d_str.parse()?)
1066            } else {
1067                (user_part, 0)
1068            };
1069            return Ok(Jid {
1070                user: CompactString::from(user),
1071                server: Server::try_from(server)?,
1072                device,
1073                agent: 0,
1074                integrator: 0,
1075            });
1076        }
1077
1078        // Fallback to existing logic for other JID types (s.whatsapp.net, etc.)
1079        let mut user = user_part;
1080        let mut device = 0;
1081        let mut agent = 0;
1082
1083        if let Some((u, d_str)) = user_part.rsplit_once(':') {
1084            user = u;
1085            device = d_str.parse()?;
1086        }
1087
1088        // No carve-out by server: the LID branch has already returned, and the
1089        // dot is the agent position on everything else. See `parse_jid_scan`.
1090        if let Some((u, last_part)) = user.rsplit_once('.')
1091            && let Ok(num_val) = last_part.parse::<u16>()
1092        {
1093            if num_val > u8::MAX as u16 {
1094                return Err(JidError::InvalidFormat(format!(
1095                    "Agent component out of range: {num_val}"
1096                )));
1097            }
1098            user = u;
1099            agent = num_val as u8;
1100        }
1101
1102        Ok(Jid {
1103            user: CompactString::from(user),
1104            server: Server::try_from(server)?,
1105            agent,
1106            device,
1107            integrator: 0,
1108        })
1109    }
1110}
1111
1112/// Core JID formatting logic used by `fmt::Display`, `push_jid_to_string`, and
1113/// `push_jid_to_compact`. Writes `{user}[.{agent}][:{device}]@{server}`.
1114///
1115/// Two flavors via `$append`:
1116/// - **fallible** (`f.write_str(s)?`): for `fmt::Formatter` which returns `fmt::Result`
1117/// - **infallible** (`$buf.push_str(s)`): for `String`/`CompactString`
1118macro_rules! write_jid {
1119    // Infallible variant: push_str/push into a growable buffer
1120    (infallible $buf:expr, $user:expr, $server:expr, $agent:expr, $device:expr) => {{
1121        let (user, server, agent, device) = ($user, $server, $agent, $device);
1122        if user.is_empty() {
1123            $buf.push_str(server.as_str());
1124            return;
1125        }
1126        $buf.push_str(user);
1127        if agent > 0 && server.renders_agent() {
1128            $buf.push('.');
1129            $buf.push_str(itoa::Buffer::new().format(agent));
1130        }
1131        if device > 0 {
1132            $buf.push(':');
1133            $buf.push_str(itoa::Buffer::new().format(device));
1134        }
1135        $buf.push('@');
1136        $buf.push_str(server.as_str());
1137    }};
1138    // Fallible variant: write_str into fmt::Formatter
1139    (fallible $f:expr, $user:expr, $server:expr, $agent:expr, $device:expr) => {{
1140        let (user, server, agent, device) = ($user, $server, $agent, $device);
1141        if user.is_empty() {
1142            return $f.write_str(server.as_str());
1143        }
1144        $f.write_str(user)?;
1145        if agent > 0 && server.renders_agent() {
1146            $f.write_str(".")?;
1147            $f.write_str(itoa::Buffer::new().format(agent))?;
1148        }
1149        if device > 0 {
1150            $f.write_str(":")?;
1151            $f.write_str(itoa::Buffer::new().format(device))?;
1152        }
1153        $f.write_str("@")?;
1154        $f.write_str(server.as_str())
1155    }};
1156}
1157
1158/// Write the JID display representation directly into a `String`,
1159/// bypassing `fmt::Display` and `dyn Write` dispatch entirely.
1160#[inline]
1161pub fn push_jid_to_string(user: &str, server: Server, agent: u8, device: u16, buf: &mut String) {
1162    write_jid!(infallible buf, user, server, agent, device);
1163}
1164
1165/// Write the JID display representation directly into a `CompactString`,
1166/// bypassing `fmt::Display` and `dyn Write` dispatch entirely.
1167#[inline]
1168pub fn push_jid_to_compact(
1169    user: &str,
1170    server: Server,
1171    agent: u8,
1172    device: u16,
1173    buf: &mut CompactString,
1174) {
1175    write_jid!(infallible buf, user, server, agent, device);
1176}
1177
1178/// Render a borrowed JID into a `CompactString` sized to what it actually
1179/// takes, so a group id or a LID that fits the 24 inline bytes never touches
1180/// the heap. Reserving `user.len() + 20` up front, as the decoder used to,
1181/// exceeded the inline budget for every user longer than four characters and
1182/// heap-allocated unconditionally — once per JID token in a device-list or
1183/// usync response.
1184pub fn jid_ref_to_compact(j: &JidRef<'_>) -> CompactString {
1185    let mut writer = JidStackWriter::new();
1186    if write_jid_fallible(&mut writer, &j.user, j.server, j.agent, j.device).is_ok() {
1187        return CompactString::from(writer.as_str());
1188    }
1189    // A user part too long for the stack buffer (never seen on the wire)
1190    // still renders, just back through the heap.
1191    let mut s = CompactString::with_capacity(j.user.len() + 20);
1192    push_jid_to_compact(&j.user, j.server, j.agent, j.device, &mut s);
1193    s
1194}
1195
1196/// Stack writer sized for any realistic JID, so `Display` can emit a single
1197/// `write_str`: a `ToString`-backed `String` then reserves once at the exact
1198/// length instead of reallocating per fragment. Overflow errors out and the
1199/// caller falls back to direct fragment writes.
1200struct JidStackWriter {
1201    buf: [u8; 64],
1202    len: usize,
1203}
1204
1205impl JidStackWriter {
1206    #[inline]
1207    fn new() -> Self {
1208        Self {
1209            buf: [0; 64],
1210            len: 0,
1211        }
1212    }
1213
1214    #[inline]
1215    fn as_str(&self) -> &str {
1216        // SAFETY: `write_str` below is the only writer, and it is all-or-nothing
1217        // — it returns `Err` before copying anything that would not fit, so it
1218        // can never leave a partial code point behind. `buf[..len]` is therefore
1219        // always a concatenation of whole `&str` fragments. Anything that writes
1220        // raw bytes here instead of going through `write_str` breaks this.
1221        unsafe { std::str::from_utf8_unchecked(&self.buf[..self.len]) }
1222    }
1223}
1224
1225impl fmt::Write for JidStackWriter {
1226    #[inline]
1227    fn write_str(&mut self, s: &str) -> fmt::Result {
1228        let end = self.len + s.len();
1229        if end > self.buf.len() {
1230            return Err(fmt::Error);
1231        }
1232        self.buf[self.len..end].copy_from_slice(s.as_bytes());
1233        self.len = end;
1234        Ok(())
1235    }
1236}
1237
1238#[inline]
1239fn write_jid_fallible<W: fmt::Write + ?Sized>(
1240    w: &mut W,
1241    user: &str,
1242    server: Server,
1243    agent: u8,
1244    device: u16,
1245) -> fmt::Result {
1246    write_jid!(fallible w, user, server, agent, device)
1247}
1248
1249struct StrEqWriter<'a> {
1250    target: &'a [u8],
1251    position: usize,
1252    matches: bool,
1253}
1254
1255impl fmt::Write for StrEqWriter<'_> {
1256    #[inline]
1257    fn write_str(&mut self, value: &str) -> fmt::Result {
1258        if self.matches {
1259            let bytes = value.as_bytes();
1260            let end = self.position + bytes.len();
1261            if end > self.target.len() || self.target[self.position..end] != *bytes {
1262                self.matches = false;
1263            }
1264            self.position = end;
1265        }
1266        Ok(())
1267    }
1268}
1269
1270#[inline]
1271fn jid_display_eq(user: &str, server: Server, agent: u8, device: u16, other: &str) -> bool {
1272    let mut writer = StrEqWriter {
1273        target: other.as_bytes(),
1274        position: 0,
1275        matches: true,
1276    };
1277    let written = write_jid_fallible(&mut writer, user, server, agent, device).is_ok();
1278    written && writer.matches && writer.position == other.len()
1279}
1280
1281#[inline]
1282fn jid_displays_equal(left: (&str, Server, u8, u16), right: (&str, Server, u8, u16)) -> bool {
1283    let (left_user, left_server, left_agent, left_device) = left;
1284    let (right_user, right_server, right_agent, right_device) = right;
1285    if left_user.is_empty() || right_user.is_empty() {
1286        return left_user.is_empty() && right_user.is_empty() && left_server == right_server;
1287    }
1288
1289    left_user == right_user
1290        && left_server == right_server
1291        && left_device == right_device
1292        && (!left_server.renders_agent() || left_agent == right_agent)
1293}
1294
1295impl fmt::Display for Jid {
1296    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1297        let mut w = JidStackWriter::new();
1298        if self.write_display_to(&mut w).is_ok() {
1299            return f.write_str(w.as_str());
1300        }
1301        self.write_display_to(f)
1302    }
1303}
1304
1305/// Privacy-aware [`Display`](fmt::Display) wrapper for a [`Jid`], for use in logs and tracing fields.
1306///
1307/// Pseudonymous (LID) and non-personal (newsletter/bot/call, modern group ids)
1308/// JIDs render in full, so the same peer/chat correlates across spans. JIDs whose
1309/// `user` is a phone number ([`Server::carries_phone_number`]) render the user as
1310/// a `pn#<token>` instead — preserving correlation without leaking the number.
1311/// Legacy group/broadcast ids of the form `<creator-phone>-<timestamp>` get only
1312/// the numeric prefix redacted (`pn#<token>-<timestamp>`), keeping the timestamp.
1313///
1314/// The token is a keyed hash (SipHash via a process-lifetime random key), not a
1315/// plain digest of the number: the phone-number search space is small, so an
1316/// unkeyed hash would be reversible by precomputation. The random key lives only
1317/// in process memory, so exported traces cannot be brute-forced back to numbers.
1318/// It is stable within a process run (correlation works) but not across restarts
1319/// (a fresh key each start). Enable the `tracing-pii` feature to render raw
1320/// numbers (local debugging only). The token is computed only while formatting an
1321/// already-enabled log or span, so it costs nothing on disabled call sites.
1322pub struct ObservedJid<'a>(ObservedSource<'a>);
1323
1324enum ObservedSource<'a> {
1325    Jid(JidRef<'a>),
1326    Text(&'a str),
1327}
1328
1329impl<'a, T: AsRef<str> + ?Sized> From<&'a T> for ObservedJid<'a> {
1330    fn from(value: &'a T) -> Self {
1331        Self(ObservedSource::Text(value.as_ref()))
1332    }
1333}
1334
1335impl JidRef<'_> {
1336    /// Borrowed privacy-aware formatting, without parsing or hashing until used.
1337    pub fn observe(&self) -> ObservedJid<'_> {
1338        ObservedJid(ObservedSource::Jid(JidRef {
1339            user: NodeStr::Borrowed(self.user.as_ref()),
1340            server: self.server,
1341            agent: self.agent,
1342            device: self.device,
1343            integrator: self.integrator,
1344        }))
1345    }
1346}
1347
1348impl Jid {
1349    /// Privacy-aware display for logs and tracing spans/fields. See [`ObservedJid`].
1350    #[inline]
1351    pub fn observe(&self) -> ObservedJid<'_> {
1352        ObservedJid(ObservedSource::Jid(JidRef {
1353            user: NodeStr::Borrowed(self.user.as_str()),
1354            server: self.server,
1355            agent: self.agent,
1356            device: self.device,
1357            integrator: self.integrator,
1358        }))
1359    }
1360}
1361
1362/// Per-process keyed token for a sensitive string: a SipHash with a random key
1363/// created once per process. Stable within a run (so the same value correlates
1364/// across spans) but not precomputable from the input, so exported traces cannot
1365/// be brute-forced back to the original (e.g. an E.164 phone number). Public so
1366/// other layers can redact non-`Jid` identifiers (e.g. a Signal `ProtocolAddress`
1367/// name, which embeds a phone number) with the same keyed scheme. On browser WASM,
1368/// unavailable entropy yields the opaque token zero for every input, disabling
1369/// correlation without falling back to a guessable key.
1370pub fn observe_token(s: &str) -> u64 {
1371    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
1372    {
1373        // std's RandomState uses allocation addresses on this target, not entropy.
1374        static KEY: std::sync::OnceLock<Option<[u8; 16]>> = std::sync::OnceLock::new();
1375        let key = KEY.get_or_init(|| {
1376            let mut key = [0; 16];
1377            getrandom::fill(&mut key).ok()?;
1378            Some(key)
1379        });
1380        observe_with_key(s, key.as_ref())
1381    }
1382    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1383    {
1384        use std::hash::BuildHasher;
1385        static KEY: std::sync::OnceLock<std::collections::hash_map::RandomState> =
1386            std::sync::OnceLock::new();
1387        KEY.get_or_init(std::collections::hash_map::RandomState::new)
1388            .hash_one(s)
1389    }
1390}
1391
1392#[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
1393fn observe_with_key(s: &str, key: Option<&[u8; 16]>) -> u64 {
1394    // Missing entropy disables correlation instead of using a guessable key.
1395    key.map_or(0, |key| {
1396        siphasher::sip::SipHasher24::new_with_key(key).hash(s.as_bytes())
1397    })
1398}
1399
1400/// Privacy-aware redaction of a JID supplied as a string (e.g. a group jid `&str`
1401/// in a span field). Parses it and applies [`Jid::observe`]; if it does not parse,
1402/// falls back to a keyed token so a raw number can never leak. Honors `tracing-pii`.
1403pub fn observe_str(s: &str) -> String {
1404    if cfg!(feature = "tracing-pii") {
1405        return s.to_string();
1406    }
1407    match s.parse::<Jid>() {
1408        Ok(jid) => jid.observe().to_string(),
1409        Err(_) => format!("?#{:016x}", observe_token(s)),
1410    }
1411}
1412
1413impl fmt::Debug for ObservedJid<'_> {
1414    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1415        fmt::Display::fmt(self, f)
1416    }
1417}
1418
1419impl fmt::Display for ObservedJid<'_> {
1420    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1421        match &self.0 {
1422            ObservedSource::Jid(jid) => fmt_observed_jid(jid, f),
1423            ObservedSource::Text(text) => match parse_jid_ref(text) {
1424                Some(jid) => fmt_observed_jid(&jid, f),
1425                None => match Server::parse_known(text) {
1426                    Some(server) => f.write_str(server.as_str()),
1427                    None => write!(f, "?#{:016x}", observe_token(text)),
1428                },
1429            },
1430        }
1431    }
1432}
1433
1434fn fmt_observed_jid(jid: &JidRef<'_>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1435    let user = jid.user.as_ref();
1436    if user.is_empty() || cfg!(feature = "tracing-pii") {
1437        return fmt::Display::fmt(jid, f);
1438    }
1439    if jid.server.carries_phone_number() {
1440        write!(f, "pn#{:016x}", observe_token(user))?;
1441    } else if matches!(jid.server, Server::Group | Server::Broadcast) {
1442        match user.find('-') {
1443            Some(i) if i > 0 && user[..i].bytes().all(|c| c.is_ascii_digit()) => {
1444                write!(f, "pn#{:016x}{}", observe_token(&user[..i]), &user[i..])?;
1445            }
1446            _ => return fmt::Display::fmt(jid, f),
1447        }
1448    } else {
1449        return fmt::Display::fmt(jid, f);
1450    }
1451    if jid.agent > 0 && jid.server.renders_agent() {
1452        write!(f, ".{}", jid.agent)?;
1453    }
1454    if jid.device > 0 {
1455        write!(f, ":{}", jid.device)?;
1456    }
1457    write!(f, "@{}", jid.server.as_str())
1458}
1459
1460impl<'a> fmt::Display for JidRef<'a> {
1461    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1462        let mut w = JidStackWriter::new();
1463        if write_jid_fallible(&mut w, &self.user, self.server, self.agent, self.device).is_ok() {
1464            return f.write_str(w.as_str());
1465        }
1466        write_jid_fallible(f, &self.user, self.server, self.agent, self.device)
1467    }
1468}
1469
1470impl From<Jid> for String {
1471    fn from(jid: Jid) -> Self {
1472        jid.to_string()
1473    }
1474}
1475
1476/// Lets `impl Into<Jid>` APIs accept `&Jid` transparently: borrow-callers pay
1477/// one cheap clone (the user part is inline for typical numeric ids), owned
1478/// callers move for free.
1479impl From<&Jid> for Jid {
1480    fn from(jid: &Jid) -> Self {
1481        jid.clone()
1482    }
1483}
1484
1485impl<'a> From<JidRef<'a>> for String {
1486    fn from(jid: JidRef<'a>) -> Self {
1487        jid.to_string()
1488    }
1489}
1490
1491impl TryFrom<String> for Jid {
1492    type Error = JidError;
1493    fn try_from(value: String) -> Result<Self, Self::Error> {
1494        Jid::from_str(&value)
1495    }
1496}
1497
1498#[cfg(test)]
1499mod tests {
1500    use super::*;
1501
1502    #[test]
1503    fn packed_identity_preserves_owned_borrowed_hashes_and_field_distinctions() {
1504        use std::collections::{HashMap, hash_map::DefaultHasher};
1505        use std::hash::{Hash, Hasher};
1506
1507        fn hash(value: &impl Hash) -> u64 {
1508            let mut state = DefaultHasher::new();
1509            value.hash(&mut state);
1510            state.finish()
1511        }
1512
1513        let servers = [
1514            Server::Pn,
1515            Server::Lid,
1516            Server::Group,
1517            Server::Broadcast,
1518            Server::Newsletter,
1519            Server::Hosted,
1520            Server::HostedLid,
1521            Server::Messenger,
1522            Server::Interop,
1523            Server::Bot,
1524            Server::Call,
1525        ];
1526        for user in ["", "5511999990000", "long-user-with-unicode-世界"] {
1527            let mut identities = HashMap::new();
1528            for server in servers {
1529                for agent in [0, 1, 128, u8::MAX] {
1530                    for device in [0, 1, 255, 256, 32768, u16::MAX] {
1531                        for integrator in [0, 1, 255, 256, 32768, u16::MAX] {
1532                            let jid = Jid {
1533                                user: user.into(),
1534                                server,
1535                                agent,
1536                                device,
1537                                integrator,
1538                            };
1539                            let borrowed = JidRef {
1540                                user: NodeStr::Borrowed(user),
1541                                server,
1542                                agent,
1543                                device,
1544                                integrator,
1545                            };
1546                            assert_eq!(hash(&jid), hash(&borrowed));
1547                            let owned_ref = JidRef {
1548                                user: NodeStr::Owned(jid.user.clone()),
1549                                ..borrowed
1550                            };
1551                            assert_eq!(hash(&jid), hash(&owned_ref));
1552                            let word = identity_word(server, agent, device, integrator);
1553                            if let Some(previous) = identities.insert(word, jid.clone()) {
1554                                // Collisions are allowed only for agents that equality ignores.
1555                                assert_eq!(previous, jid);
1556                                assert_eq!(hash(&previous), hash(&jid));
1557                            }
1558                        }
1559                    }
1560                }
1561            }
1562        }
1563    }
1564    use std::str::FromStr;
1565
1566    /// The regression the whole change is for, and the one a naive fix does not
1567    /// pass. Relaxing `==` alone -- teaching it that the two spellings of the
1568    /// phone namespace are one -- still leaves the two sides classified
1569    /// differently by `identity_agent`, because the legacy spelling was not in
1570    /// the set of servers that suppress the agent. Two JIDs equal in everything
1571    /// but the spelling would then compare unequal whenever the agent is
1572    /// non-zero, which is rare enough to pass CI and show up only on odd input
1573    /// off the wire. Collapsing at the parser instead means there is no second
1574    /// classification to get wrong.
1575    #[test]
1576    fn observation_hash_requires_a_secret_key_and_fails_closed_without_entropy() {
1577        let a = [0x17; 16];
1578        let b = [0x29; 16];
1579        assert_eq!(
1580            observe_with_key("19990000006", Some(&a)),
1581            observe_with_key("19990000006", Some(&a))
1582        );
1583        assert_ne!(
1584            observe_with_key("19990000006", Some(&a)),
1585            observe_with_key("19990000006", Some(&b))
1586        );
1587        assert_eq!(observe_with_key("19990000006", None), 0);
1588        assert_eq!(observe_with_key("19990000007", None), 0);
1589    }
1590
1591    #[test]
1592    fn the_two_spellings_agree_when_the_agent_is_not_zero() {
1593        let legacy: Jid = "12345678901.6@c.us".parse().unwrap();
1594        let modern: Jid = "12345678901.6@s.whatsapp.net".parse().unwrap();
1595
1596        assert_eq!(legacy.agent, 6, "the dotted number is read, not discarded");
1597        assert_eq!(legacy.device, 0, "and it is not a device");
1598        assert_eq!(legacy, modern);
1599        assert_eq!(hash_of(&legacy), hash_of(&modern));
1600        // ...and both are the same identity as the bare user, since the agent
1601        // is inert on the phone namespace.
1602        assert_eq!(legacy, "12345678901@s.whatsapp.net".parse::<Jid>().unwrap());
1603        assert_eq!(legacy.to_string(), "12345678901@s.whatsapp.net");
1604    }
1605
1606    /// The dotted position on a phone user is the agent, not a device. WA Web's
1607    /// `WAJids.parseJidParts` splits `user:device` then `user.agent` with no
1608    /// per-server branch, `fullFormDeviceJidString` writes it back as
1609    /// `user.<agent>:<device>@server`, and `stripAgentIdFromPhoneDeviceJid`
1610    /// drops it; its `Wid` layer has no agent field at all and accepts only a
1611    /// literal `.0` there. Reading it as a device -- which this parser did --
1612    /// turned a bare user into a request addressed at device N.
1613    #[test]
1614    fn a_dotted_number_on_a_phone_user_is_the_inert_agent() {
1615        let dotted: Jid = "5511999998888.2@s.whatsapp.net".parse().unwrap();
1616        assert_eq!(dotted.user, "5511999998888");
1617        assert_eq!(dotted.agent, 2);
1618        assert_eq!(dotted.device, 0, "a device only ever follows a colon");
1619        assert_eq!(dotted, Jid::pn("5511999998888"));
1620
1621        // The colon still is the device, and the two positions compose.
1622        let both: Jid = "5511999998888.2:3@s.whatsapp.net".parse().unwrap();
1623        assert_eq!(
1624            (both.user.as_str(), both.agent, both.device),
1625            ("5511999998888", 2, 3)
1626        );
1627        assert_eq!(both, Jid::pn_device("5511999998888", 3));
1628        assert_ne!(both, dotted);
1629
1630        // The shape WA Web actually writes, `formatFull`'s `user.0:device`.
1631        // The old phone-namespace carve-out returned early on the colon and
1632        // never looked at the dot, so the `.0` stayed inside `user` and the
1633        // result was not equal to the same device addressed without it.
1634        let full: Jid = "5511999998888.0:3@s.whatsapp.net".parse().unwrap();
1635        assert_eq!(
1636            full.user, "5511999998888",
1637            "the agent is not part of the user"
1638        );
1639        assert_eq!(full, Jid::pn_device("5511999998888", 3));
1640        assert_eq!(full.to_string(), "5511999998888:3@s.whatsapp.net");
1641    }
1642
1643    /// Text, wire and serde all resolve the server through `Server::parse_known`,
1644    /// so the collapse has to hold for all three -- and none of them may
1645    /// materialise the legacy spelling internally, because a `Server` that could
1646    /// render it is a `Server` that could reach the wire.
1647    #[test]
1648    fn every_input_direction_collapses_the_legacy_spelling() {
1649        let expected = Jid::pn("5511999998888");
1650
1651        // Text, both parsers.
1652        assert_eq!("5511999998888@c.us".parse::<Jid>().unwrap(), expected);
1653        assert_eq!(
1654            parse_jid_ref("5511999998888@c.us").unwrap().to_owned(),
1655            expected
1656        );
1657        // The fallback path (an empty user forces it) resolves it too.
1658        assert_eq!("@c.us".parse::<Jid>().unwrap().server, Server::Pn);
1659
1660        // Wire: `read_jid_pair` classifies the server string with the same
1661        // converter, so a JID_PAIR naming `c.us` decodes as a phone user.
1662        assert_eq!(Server::try_from("c.us").unwrap(), Server::Pn);
1663
1664        // No spelling of the enum renders it back out.
1665        for server in [
1666            Server::Pn,
1667            Server::Lid,
1668            Server::Group,
1669            Server::Broadcast,
1670            Server::Newsletter,
1671            Server::Hosted,
1672            Server::HostedLid,
1673            Server::Messenger,
1674            Server::Interop,
1675            Server::Bot,
1676            Server::Call,
1677        ] {
1678            assert_ne!(
1679                server.as_str(),
1680                LEGACY_USER_SERVER,
1681                "{server:?} must not render the legacy spelling"
1682            );
1683        }
1684        assert_eq!(expected.to_string(), "5511999998888@s.whatsapp.net");
1685    }
1686
1687    #[cfg(feature = "serde")]
1688    #[test]
1689    fn serde_collapses_the_legacy_spelling_too() {
1690        let server: Server = serde_json::from_str("\"c.us\"").unwrap();
1691        assert_eq!(server, Server::Pn);
1692        assert_eq!(
1693            serde_json::to_string(&server).unwrap(),
1694            "\"s.whatsapp.net\""
1695        );
1696
1697        let jid: Jid = serde_json::from_str(
1698            r#"{"user":"5511999998888","server":"c.us","agent":0,"device":0,"integrator":0}"#,
1699        )
1700        .unwrap();
1701        assert_eq!(jid, Jid::pn("5511999998888"));
1702
1703        // A server that is not a spelling of anything still fails.
1704        assert!(serde_json::from_str::<Server>("\"nope\"").is_err());
1705    }
1706
1707    /// A JID's identity must not depend on which spelling it arrived as, in any
1708    /// of the derived keys built over it.
1709    #[test]
1710    fn the_two_spellings_share_every_derived_key() {
1711        let legacy: Jid = "5511999998888:3@c.us".parse().unwrap();
1712        let modern: Jid = "5511999998888:3@s.whatsapp.net".parse().unwrap();
1713
1714        assert_eq!(legacy, modern);
1715        assert_eq!(hash_of(&legacy), hash_of(&modern));
1716        assert_eq!(legacy.device_key(), modern.device_key());
1717        assert!(legacy.is_same_chat_as(&modern));
1718        assert!(legacy.device_eq(&modern));
1719        assert!(legacy.display_eq_jid(&modern));
1720        assert_eq!(legacy.to_string(), modern.to_string());
1721        assert_eq!(legacy.to_non_ad_string(), modern.to_non_ad_string());
1722        assert_eq!(legacy.to_phash_form_string(), modern.to_phash_form_string());
1723        assert!(legacy.is_pn(), "a phone user however it is spelled");
1724
1725        // And a single map entry, which is the failure the batch is named for.
1726        let mut map = std::collections::HashMap::new();
1727        map.insert(legacy.clone(), ());
1728        assert!(map.contains_key(&modern), "one person, one entry");
1729    }
1730
1731    /// One fixed-key hasher, so two calls are comparable at all.
1732    fn hash_of(jid: &Jid) -> u64 {
1733        use std::hash::{Hash, Hasher};
1734        let mut hasher = std::collections::hash_map::DefaultHasher::new();
1735        jid.hash(&mut hasher);
1736        hasher.finish()
1737    }
1738
1739    #[test]
1740    fn is_psa_matches_system_jid_in_both_user_namespaces() {
1741        assert!(Jid::from_str("0@s.whatsapp.net").unwrap().is_psa());
1742        assert!(Jid::from_str("0@c.us").unwrap().is_psa());
1743        assert!(parse_jid_ref("0@s.whatsapp.net").unwrap().is_psa());
1744    }
1745
1746    #[test]
1747    fn is_psa_rejects_regular_and_non_pn_jids() {
1748        assert!(!Jid::from_str("10@s.whatsapp.net").unwrap().is_psa());
1749        assert!(!Jid::from_str("0@lid").unwrap().is_psa());
1750        assert!(!Jid::from_str("status@broadcast").unwrap().is_psa());
1751        assert!(!Jid::from_str("0@g.us").unwrap().is_psa());
1752    }
1753
1754    /// `JidStackWriter::as_str` reads its buffer back as UTF-8 without
1755    /// validating it, so every shape that reaches it has to be exercised
1756    /// somewhere Miri can see: multi-byte users, a user that fills the buffer
1757    /// exactly, and one that overflows it into the fallback path.
1758    #[test]
1759    fn display_reads_back_every_stack_buffer_shape() {
1760        // Multi-byte code points in the user part: a byte-wise buffer must not
1761        // be able to split one, and the readback must reproduce them exactly.
1762        let emoji = Jid::new("héllo→世界", Server::Lid);
1763        assert_eq!(emoji.to_string(), "héllo→世界@lid");
1764        assert_eq!(format!("{}", emoji.observe()), "héllo→世界@lid");
1765
1766        // Exactly at the 64-byte stack buffer: "@lid" is 4 bytes, so a 60-byte
1767        // user is the longest that still renders through it.
1768        let full = Jid::new("9".repeat(60), Server::Lid);
1769        let rendered = full.to_string();
1770        assert_eq!(rendered.len(), 64);
1771        assert!(rendered.ends_with("@lid"));
1772
1773        // One byte past it: `write_str` errors and Display falls back to
1774        // fragment writes, which must produce the same string.
1775        let over = Jid::new("9".repeat(61), Server::Lid);
1776        assert_eq!(over.to_string(), format!("{}@lid", "9".repeat(61)));
1777
1778        // The borrowed formatter and the Arc<str> builder share the writer.
1779        let borrowed = parse_jid_ref("12025550111:7@s.whatsapp.net").unwrap();
1780        assert_eq!(borrowed.to_string(), "12025550111:7@s.whatsapp.net");
1781        assert_eq!(&*emoji.to_non_ad_arc_str(), "héllo→世界@lid");
1782        assert_eq!(
1783            &*over.to_non_ad_arc_str(),
1784            &*format!("{}@lid", "9".repeat(61))
1785        );
1786    }
1787
1788    /// The phash form is recomputed and validated by the server, so
1789    /// it has to match WA Web byte for byte. WA Web writes a literal `.0` in the
1790    /// agent position (`formatFull`) and its Wid carries no agent at all, so ours
1791    /// must not leak one in either — and two JIDs that compare equal must produce
1792    /// the same string, or the phash memo (keyed by JID) can serve a hash computed
1793    /// for a different one.
1794    #[test]
1795    fn phash_form_writes_the_agent_position_as_zero_like_wa_web() {
1796        let plain = Jid {
1797            user: "5511999998888".into(),
1798            server: Server::Lid,
1799            agent: 0,
1800            device: 3,
1801            integrator: 0,
1802        };
1803        assert_eq!(plain.to_phash_form_string(), "5511999998888.0:3@lid");
1804
1805        let with_agent = Jid {
1806            agent: 7,
1807            ..plain.clone()
1808        };
1809        assert_eq!(
1810            with_agent.to_phash_form_string(),
1811            "5511999998888.0:3@lid",
1812            "the agent must not reach the hashed string"
1813        );
1814
1815        // The pairing the phash memo relies on: equal JIDs, equal AD strings.
1816        assert_eq!(plain, with_agent);
1817        assert_eq!(
1818            plain.to_phash_form_string(),
1819            with_agent.to_phash_form_string()
1820        );
1821
1822        // A server-only JID still degenerates to the server, and device still counts.
1823        assert_eq!(
1824            Jid::new("", Server::Pn).to_phash_form_string(),
1825            "s.whatsapp.net"
1826        );
1827        assert_ne!(
1828            plain.to_phash_form_string(),
1829            Jid {
1830                device: 4,
1831                ..plain.clone()
1832            }
1833            .to_phash_form_string()
1834        );
1835    }
1836
1837    /// An `agent` off an agent-rendering server is inert: nothing encodes it,
1838    /// prints it, or hashes it. Two JIDs differing only there address the same
1839    /// device, so equality and `Hash` must both say so — and must agree with each
1840    /// other, or a `HashMap<Jid, _>` gets an entry it can never look up again.
1841    ///
1842    /// `integrator` stays in identity: it is only non-zero on interop, but
1843    /// `is_same_chat_as` compares it unconditionally, and `==` must not disagree.
1844    #[test]
1845    fn inert_agent_stays_out_of_identity() {
1846        use std::collections::hash_map::DefaultHasher;
1847        use std::hash::{Hash, Hasher};
1848
1849        fn hash_of(jid: &Jid) -> u64 {
1850            let mut h = DefaultHasher::new();
1851            jid.hash(&mut h);
1852            h.finish()
1853        }
1854
1855        // The four AD servers spell the server as a domain byte, so an agent set
1856        // on one is a wire artefact, not identity.
1857        for server in [Server::Pn, Server::Lid, Server::Hosted, Server::HostedLid] {
1858            let clean = Jid {
1859                user: "123456789012345".into(),
1860                server,
1861                agent: 0,
1862                device: 7,
1863                integrator: 0,
1864            };
1865            let with_agent = Jid {
1866                agent: 1,
1867                ..clean.clone()
1868            };
1869            assert_eq!(
1870                clean, with_agent,
1871                "{server:?}: agent must not split identity"
1872            );
1873            assert_eq!(
1874                hash_of(&clean),
1875                hash_of(&with_agent),
1876                "{server:?}: Hash must agree with Eq"
1877            );
1878
1879            // integrator is NOT normalised: `is_same_chat_as` compares it always,
1880            // and `==` must not disagree with it.
1881            let with_integrator = Jid {
1882                integrator: 0xBEEF,
1883                ..clean.clone()
1884            };
1885            assert_ne!(
1886                clean, with_integrator,
1887                "{server:?}: integrator stays in identity, matching is_same_chat_as"
1888            );
1889            assert_eq!(
1890                clean.is_same_chat_as(&with_integrator),
1891                clean == with_integrator,
1892                "{server:?}: == must agree with is_same_chat_as"
1893            );
1894
1895            // The borrowed form and the cross-type comparison follow the same rule.
1896            let borrowed = JidRef {
1897                user: NodeStr::Borrowed("123456789012345"),
1898                server,
1899                agent: 1,
1900                device: 7,
1901                integrator: 0,
1902            };
1903            assert_eq!(clean, borrowed, "{server:?}: owned == borrowed");
1904            assert_eq!(borrowed, clean, "{server:?}: borrowed == owned");
1905        }
1906
1907        // Where the server DOES render the agent it is identity, and must still split.
1908        let bot = Jid {
1909            user: "123456789".into(),
1910            server: Server::Interop,
1911            agent: 4,
1912            device: 0,
1913            integrator: 0,
1914        };
1915        let other_agent = Jid {
1916            agent: 5,
1917            ..bot.clone()
1918        };
1919        assert_ne!(
1920            bot, other_agent,
1921            "interop renders the agent, so it is identity"
1922        );
1923        assert_ne!(
1924            bot,
1925            Jid {
1926                integrator: 9,
1927                ..bot.clone()
1928            },
1929            "interop is where integrator is real"
1930        );
1931
1932        // Fields that are always identity keep splitting.
1933        let pn = Jid::new("123456789012345", Server::Pn);
1934        assert_ne!(
1935            pn,
1936            Jid {
1937                device: 1,
1938                ..pn.clone()
1939            }
1940        );
1941        assert_ne!(pn, Jid::new("123456789012346", Server::Pn));
1942        assert_ne!(pn, Jid::new("123456789012345", Server::Lid));
1943    }
1944
1945    #[test]
1946    fn display_eq_matches_owned_and_borrowed_jids_without_normalizing() {
1947        let canonical = "123456789.4:17@interop";
1948        let owned = Jid::from_str(canonical).unwrap();
1949        let borrowed = parse_jid_ref(canonical).unwrap();
1950
1951        for value in [canonical, "123456789.4:16@interop", "123456789@interop", ""] {
1952            assert_eq!(owned.display_eq(value), value == canonical);
1953            assert_eq!(borrowed.display_eq(value), value == canonical);
1954        }
1955
1956        let long_user = "a".repeat(128);
1957        let long_value = format!("{long_user}@lid");
1958        let long_jid = Jid::lid(long_user);
1959        assert!(long_jid.display_eq(&long_value));
1960        assert!(!long_jid.display_eq(&format!("{long_value}x")));
1961    }
1962
1963    #[test]
1964    fn display_eq_jid_uses_only_rendered_components() {
1965        let pn = Jid {
1966            user: "12025550111".into(),
1967            server: Server::Pn,
1968            agent: 1,
1969            device: 7,
1970            integrator: 3,
1971        };
1972        let pn_same_display = Jid {
1973            agent: 2,
1974            integrator: 9,
1975            ..pn.clone()
1976        };
1977        assert_eq!(pn.to_string(), pn_same_display.to_string());
1978        assert!(pn.display_eq_jid(&pn_same_display));
1979
1980        let pn_other_device = Jid {
1981            device: 8,
1982            ..pn.clone()
1983        };
1984        assert!(!pn.display_eq_jid(&pn_other_device));
1985
1986        let bot = Jid {
1987            user: "13136555001".into(),
1988            server: Server::Bot,
1989            agent: 1,
1990            device: 0,
1991            integrator: 0,
1992        };
1993        let other_bot_agent = Jid {
1994            agent: 2,
1995            ..bot.clone()
1996        };
1997        assert!(!bot.display_eq_jid(&other_bot_agent));
1998
1999        let server_only = Jid {
2000            user: "".into(),
2001            server: Server::Pn,
2002            agent: 1,
2003            device: 7,
2004            integrator: 3,
2005        };
2006        let same_server_only = Jid {
2007            agent: 2,
2008            device: 9,
2009            integrator: 4,
2010            ..server_only.clone()
2011        };
2012        assert_eq!(server_only.to_string(), same_server_only.to_string());
2013        assert!(server_only.display_eq_jid(&same_server_only));
2014
2015        let borrowed = JidRef {
2016            user: NodeStr::Borrowed("12025550111"),
2017            server: Server::Pn,
2018            agent: 1,
2019            device: 7,
2020            integrator: 0,
2021        };
2022        let borrowed_same_display = JidRef {
2023            agent: 2,
2024            ..borrowed.clone()
2025        };
2026        assert!(borrowed.display_eq_jid(&borrowed_same_display));
2027    }
2028
2029    #[test]
2030    fn owned_and_borrowed_jids_compare_without_conversion() {
2031        let owned = Jid {
2032            user: "12025550111".into(),
2033            server: Server::Pn,
2034            agent: 0,
2035            device: 7,
2036            integrator: 0,
2037        };
2038        let borrowed = JidRef {
2039            user: NodeStr::Borrowed("12025550111"),
2040            server: Server::Pn,
2041            agent: 0,
2042            device: 7,
2043            integrator: 0,
2044        };
2045
2046        assert_eq!(owned, borrowed);
2047        assert_eq!(borrowed, owned);
2048
2049        let other_device = JidRef {
2050            device: 8,
2051            ..borrowed.clone()
2052        };
2053        assert_ne!(owned, other_device);
2054    }
2055
2056    #[cfg(feature = "serde")]
2057    #[test]
2058    fn server_deserializes_borrowed_and_owned_strings() {
2059        let borrowed: Server = serde_json::from_str("\"s.whatsapp.net\"").unwrap();
2060        let owned: Server =
2061            serde_json::from_value(serde_json::Value::String("lid".to_owned())).unwrap();
2062
2063        assert_eq!(borrowed, Server::Pn);
2064        assert_eq!(owned, Server::Lid);
2065    }
2066
2067    /// `observe()` must never leak a raw phone number, must keep pseudonymous /
2068    /// non-personal JIDs intact for correlation, and must preserve device.
2069    #[test]
2070    #[cfg(not(feature = "tracing-pii"))]
2071    fn observe_redacts_phone_but_not_lid_or_group() {
2072        let pn = Jid::from_str("5511999998888:7@s.whatsapp.net").unwrap();
2073        let shown = pn.observe().to_string();
2074        assert!(shown.starts_with("pn#"), "{shown}");
2075        assert!(
2076            !shown.contains("5511999998888"),
2077            "raw number leaked: {shown}"
2078        );
2079        assert!(shown.ends_with(":7@s.whatsapp.net"), "device lost: {shown}");
2080        // Stable within the process so the same peer correlates across spans.
2081        assert_eq!(shown, pn.observe().to_string());
2082
2083        // LID is pseudonymous and modern group ids are non-personal: rendered in full.
2084        let lid = Jid::from_str("123456789@lid").unwrap();
2085        assert_eq!(lid.observe().to_string(), lid.to_string());
2086        let group = Jid::from_str("120363012345678901@g.us").unwrap();
2087        assert_eq!(group.observe().to_string(), group.to_string());
2088
2089        // Legacy group id embeds the creator phone ("<phone>-<ts>"): redact the
2090        // numeric prefix, keep the timestamp.
2091        let legacy = Jid::from_str("123456789-1620000000@g.us").unwrap();
2092        let ls = legacy.observe().to_string();
2093        assert!(
2094            ls.starts_with("pn#") && ls.ends_with("-1620000000@g.us"),
2095            "{ls}"
2096        );
2097        // Exact no-leak invariant: the creator phone must not appear anywhere.
2098        assert!(!ls.contains("123456789"), "creator phone leaked: {ls}");
2099        // The redacted prefix is the fixed-width keyed token, not the raw number.
2100        let mid = &ls["pn#".len()..ls.find('-').unwrap()];
2101        assert_eq!(mid.len(), 16, "token width: {ls}");
2102        assert!(
2103            mid.bytes().all(|b| b.is_ascii_hexdigit()),
2104            "token hex: {ls}"
2105        );
2106    }
2107
2108    /// Helper function to test a full parsing and display round-trip.
2109    fn assert_jid_roundtrip(
2110        input: &str,
2111        expected_user: &str,
2112        expected_server: &str,
2113        expected_device: u16,
2114        expected_agent: u8,
2115    ) {
2116        assert_jid_parse_and_display(
2117            input,
2118            expected_user,
2119            expected_server,
2120            expected_device,
2121            expected_agent,
2122            input,
2123        );
2124    }
2125
2126    /// Helper function to test parsing and display with a custom expected output.
2127    fn assert_jid_parse_and_display(
2128        input: &str,
2129        expected_user: &str,
2130        expected_server: &str,
2131        expected_device: u16,
2132        expected_agent: u8,
2133        expected_output: &str,
2134    ) {
2135        // 1. Test parsing from string (FromStr trait)
2136        let jid = Jid::from_str(input).unwrap_or_else(|_| panic!("Failed to parse JID: {}", input));
2137
2138        assert_eq!(
2139            jid.user, expected_user,
2140            "User part did not match for {}",
2141            input
2142        );
2143        assert_eq!(
2144            jid.server, expected_server,
2145            "Server part did not match for {}",
2146            input
2147        );
2148        assert_eq!(
2149            jid.device, expected_device,
2150            "Device part did not match for {}",
2151            input
2152        );
2153        assert_eq!(
2154            jid.agent, expected_agent,
2155            "Agent part did not match for {}",
2156            input
2157        );
2158
2159        // 2. Test formatting back to string (Display trait)
2160        let formatted = jid.to_string();
2161        assert_eq!(
2162            formatted, expected_output,
2163            "Formatted string did not match expected output for {}",
2164            input
2165        );
2166    }
2167
2168    #[test]
2169    fn borrowed_parser_matches_owned_fast_path_and_bot_classification() {
2170        for raw in [
2171            "5511999998888:7@s.whatsapp.net",
2172            "120363012345678901@g.us",
2173            "123456789012345@lid",
2174            "assistant@bot",
2175            "13135551234@s.whatsapp.net",
2176        ] {
2177            let borrowed = parse_jid_ref(raw).expect("common JID should stay borrowed");
2178            let owned = raw.parse::<Jid>().unwrap();
2179
2180            assert!(matches!(borrowed.user, NodeStr::Borrowed(_)));
2181            assert_eq!(borrowed.to_owned(), owned);
2182            assert_eq!(borrowed.is_bot(), owned.is_bot());
2183        }
2184
2185        assert!(parse_jid_ref("g.us").is_none(), "server-only uses fallback");
2186        assert!(parse_jid_ref("user@unknown").is_none());
2187    }
2188
2189    /// `parse_u16_decimal` stands in for `u16::from_str` inside the scanner, so
2190    /// it has to accept and reject exactly what std does — including the shapes
2191    /// nobody writes on purpose but a malformed stanza can still carry.
2192    #[test]
2193    fn decimal_fast_path_matches_u16_from_str() {
2194        for raw in [
2195            "", "+", "-", "0", "7", "+7", "007", "33", "255", "256", "65535", "65536", "99999",
2196            "-0", "-1", "1x", "x1", " 1", "1 ", "1_0", "+-1", "++1", "1.0", "٣", "𝟛",
2197        ] {
2198            assert_eq!(
2199                parse_u16_decimal(raw),
2200                raw.parse::<u16>().ok(),
2201                "mismatch for {raw:?}"
2202            );
2203        }
2204    }
2205
2206    /// The scan stops at the first `@` and dispatches on the resolved `Server`,
2207    /// so every separator rule it folded together needs a case here: which
2208    /// separator wins per server, and the pathological users where the agent
2209    /// rule reads a different dot than the scan recorded.
2210    ///
2211    /// Asserted against written-out values rather than against `str::parse`,
2212    /// which would prove nothing: `FromStr` tries `parse_jid_ref` first, so for
2213    /// any server this path accepts it would be comparing the scanner with
2214    /// itself. These are the values `main` produces for the same inputs.
2215    #[test]
2216    fn fast_parse_pins_the_separator_rules_per_server() {
2217        // (input, user, agent, device)
2218        let cases = [
2219            // Generic servers read a trailing dotted number as the agent.
2220            ("123456789.4:17@interop", "123456789", 4u8, 17u16),
2221            ("123456789.4@interop", "123456789", 4, 0),
2222            // ...but an agent past u8 leaves the user whole instead.
2223            ("123.999@interop", "123.999", 0, 0),
2224            // s.whatsapp.net reads it the same way, as the agent. WA Web's
2225            // `parseJidParts` splits `.` into `agent` with no per-server
2226            // carve-out and the device only ever follows a colon; see
2227            // `a_dotted_number_on_a_phone_user_is_the_inert_agent`.
2228            ("5511999998888.2@s.whatsapp.net", "5511999998888", 2, 0),
2229            // Dots in a lid user are part of the user.
2230            ("12345.678@lid", "12345.678", 0, 0),
2231            ("12345.678:9@lid", "12345.678", 0, 9),
2232            // `hosted.lid` is NOT in the lid family here — it takes the generic
2233            // rule, so a dotted number that fits in u8 becomes the agent.
2234            ("12345.6@hosted.lid", "12345", 6, 0),
2235            ("12345.678@hosted.lid", "12345.678", 0, 0),
2236            // ...and so does the legacy spelling of the phone namespace, which
2237            // by then is the phone namespace.
2238            ("12345.6@c.us", "12345", 6, 0),
2239            // A second colon puts the last dot after the first one, which is
2240            // where reusing the scanned dot position would silently diverge.
2241            ("a:1.5:2@bot", "a:1", 5, 2),
2242            // A valid agent followed by a malformed device: the scan's last dot
2243            // is the one inside `x.y`, which is not the agent. Recovering the
2244            // earlier one matters because the device degrades to 0 rather than
2245            // rejecting the JID, so this must render and reparse to itself.
2246            ("123.4:x.y@interop", "123", 4, 0),
2247            // Unparsable device degrades to 0 rather than rejecting the JID.
2248            ("5511999998888:x@s.whatsapp.net", "5511999998888", 0, 0),
2249        ];
2250
2251        for (raw, user, agent, device) in cases {
2252            let fast =
2253                parse_jid_fast(raw).unwrap_or_else(|| panic!("{raw} should take the fast path"));
2254            assert_eq!(fast.user, user, "user for {raw}");
2255            assert_eq!(fast.agent, agent, "agent for {raw}");
2256            assert_eq!(fast.device, device, "device for {raw}");
2257        }
2258    }
2259
2260    #[test]
2261    fn test_jid_parsing_and_display_roundtrip() {
2262        // Standard cases
2263        assert_jid_roundtrip(
2264            "1234567890@s.whatsapp.net",
2265            "1234567890",
2266            "s.whatsapp.net",
2267            0,
2268            0,
2269        );
2270        assert_jid_roundtrip(
2271            "1234567890:15@s.whatsapp.net",
2272            "1234567890",
2273            "s.whatsapp.net",
2274            15,
2275            0,
2276        );
2277        assert_jid_roundtrip("123-456@g.us", "123-456", "g.us", 0, 0);
2278
2279        // Server-only JID: parsing "s.whatsapp.net" should display as "s.whatsapp.net" (no @ prefix)
2280        // This matches WhatsApp Web behavior where server-only JIDs don't have @ prefix
2281        assert_jid_roundtrip("s.whatsapp.net", "", "s.whatsapp.net", 0, 0);
2282
2283        // LID JID cases (critical for the bug)
2284        assert_jid_roundtrip("12345.6789@lid", "12345.6789", "lid", 0, 0);
2285        assert_jid_roundtrip("12345.6789:25@lid", "12345.6789", "lid", 25, 0);
2286
2287        // @call (call-signaling server) must parse and render, not be rejected.
2288        assert_jid_roundtrip("12345@call", "12345", "call", 0, 0);
2289    }
2290
2291    #[test]
2292    fn test_special_from_str_parsing() {
2293        // Test parsing of JIDs with an agent, which should be stored in the struct
2294        let jid = Jid::from_str("1234567890.2:15@hosted").expect("test hosted JID should be valid");
2295        assert_eq!(jid.user, "1234567890");
2296        assert_eq!(jid.server, "hosted");
2297        assert_eq!(jid.device, 15);
2298        assert_eq!(jid.agent, 2);
2299    }
2300
2301    #[test]
2302    fn test_manual_jid_formatting_edge_cases() {
2303        // This test directly validates the fixes for the parity failures.
2304        // We manually construct the Jid struct as the binary decoder would,
2305        // then we assert that its string representation is correct.
2306
2307        // Failure Case 1: An AD-JID for s.whatsapp.net decoded with an agent.
2308        // The Display trait MUST NOT show the agent number.
2309        let jid1 = Jid {
2310            user: "1234567890".into(),
2311            server: Server::Pn,
2312            device: 15,
2313            agent: 2,
2314            integrator: 0,
2315        };
2316        assert_eq!(jid1.to_string(), "1234567890:15@s.whatsapp.net");
2317
2318        let jid2 = Jid {
2319            user: "12345.6789".into(),
2320            server: Server::Lid,
2321            device: 25,
2322            agent: 1,
2323            integrator: 0,
2324        };
2325        assert_eq!(jid2.to_string(), "12345.6789:25@lid");
2326
2327        let jid3 = Jid {
2328            user: "1234567890".into(),
2329            server: Server::Hosted,
2330            device: 15,
2331            agent: 2,
2332            integrator: 0,
2333        };
2334        assert_eq!(jid3.to_string(), "1234567890:15@hosted");
2335
2336        // Agent SHOULD be displayed for non-AD servers (e.g., bot, interop)
2337        let jid4 = Jid {
2338            user: "user".into(),
2339            server: Server::Bot,
2340            device: 10,
2341            agent: 5,
2342            integrator: 0,
2343        };
2344        assert_eq!(jid4.to_string(), "user.5:10@bot");
2345    }
2346
2347    #[test]
2348    fn test_invalid_jids_should_fail_to_parse() {
2349        assert!(Jid::from_str("thisisnotajid").is_err());
2350        assert!(Jid::from_str("").is_err());
2351        // "@s.whatsapp.net" is now valid - it's the protocol format for server-only JIDs
2352        assert!(Jid::from_str("@s.whatsapp.net").is_ok());
2353        // But "@unknown.server" should still fail
2354        assert!(Jid::from_str("@unknown.server").is_err());
2355        // Jid::from_str("2") should not be possible due to type constraints,
2356        // but if it were, it should fail. The string must contain '@'.
2357        assert!(Jid::from_str("2").is_err());
2358    }
2359
2360    /// A device past the field's `u16` is dropped, not rejected: the fast
2361    /// scanner reads it with `parse_u16_decimal` and falls back to 0, so a bad
2362    /// attribute costs one device rather than the whole stanza. Pinned because
2363    /// `65535` and `65536` are one apart and land on opposite sides.
2364    ///
2365    /// This is the parser's boundary, not the wire's: the AD form spends one
2366    /// byte on the device, so PN/LID stop at 255 (see
2367    /// `ad_jid_device_is_one_byte_wide_unlike_interop` in `encoder`).
2368    #[test]
2369    fn out_of_range_device_parses_as_no_device() {
2370        let max = Jid::from_str("5511987650001:65535@s.whatsapp.net").unwrap();
2371        assert_eq!(max.device, 65535);
2372        assert_eq!(max.to_string(), "5511987650001:65535@s.whatsapp.net");
2373
2374        for raw in [
2375            "5511987650001:65536@s.whatsapp.net",
2376            "5511987650001:70000@s.whatsapp.net",
2377            "5511987650001:-1@s.whatsapp.net",
2378        ] {
2379            let jid = Jid::from_str(raw).unwrap_or_else(|e| panic!("{raw}: {e}"));
2380            assert_eq!(jid.device, 0, "{raw}");
2381            assert_eq!(jid.user, "5511987650001", "{raw}");
2382            assert_eq!(jid.to_string(), "5511987650001@s.whatsapp.net", "{raw}");
2383        }
2384    }
2385
2386    /// Tests for HOSTED device detection (`is_hosted()` method).
2387    ///
2388    /// # Context: What are HOSTED devices?
2389    ///
2390    /// HOSTED devices (also known as Cloud API or Meta Business API devices) are
2391    /// WhatsApp Business accounts that use Meta's server-side infrastructure instead
2392    /// of traditional end-to-end encryption with Signal protocol.
2393    ///
2394    /// ## Key characteristics:
2395    /// - Device ID is always 99 (`:99`)
2396    /// - Server is `@hosted` (phone-based) or `@hosted.lid` (LID-based)
2397    /// - They do NOT use Signal protocol prekeys
2398    /// - They should be EXCLUDED from group message fanout
2399    /// - They CAN receive 1:1 messages (but prekey fetch will fail, causing graceful skip)
2400    ///
2401    /// ## Why exclude from groups?
2402    /// WhatsApp Web explicitly filters hosted devices from group SKDM (Sender Key
2403    /// Distribution Message) distribution. From WhatsApp Web JS (`getFanOutList`):
2404    /// ```javascript
2405    /// var isHosted = e.id === 99 || e.isHosted === true;
2406    /// var includeInFanout = !isHosted || isOneToOneChat;
2407    /// ```
2408    ///
2409    /// ## JID formats:
2410    /// - Phone-based: `5511999887766:99@hosted`
2411    /// - LID-based: `100000012345678:99@hosted.lid`
2412    /// - Regular device with ID 99: `5511999887766:99@s.whatsapp.net` (also hosted!)
2413    #[test]
2414    fn test_is_hosted_device_detection() {
2415        // === HOSTED DEVICES (should return true) ===
2416
2417        // Case 1: Device ID 99 on regular server (Cloud API business account)
2418        // This is the most common case - a business using Meta's Cloud API
2419        let cloud_api_device: Jid = "5511999887766:99@s.whatsapp.net"
2420            .parse()
2421            .expect("test JID should be valid");
2422        assert!(
2423            cloud_api_device.is_hosted(),
2424            "Device ID 99 on s.whatsapp.net should be detected as hosted (Cloud API)"
2425        );
2426
2427        // Case 2: Device ID 99 on LID server
2428        let cloud_api_lid: Jid = "100000012345678:99@lid"
2429            .parse()
2430            .expect("test JID should be valid");
2431        assert!(
2432            cloud_api_lid.is_hosted(),
2433            "Device ID 99 on lid server should be detected as hosted"
2434        );
2435
2436        // Case 3: Explicit @hosted server (phone-based hosted JID)
2437        let hosted_server: Jid = "5511999887766:99@hosted"
2438            .parse()
2439            .expect("test JID should be valid");
2440        assert!(
2441            hosted_server.is_hosted(),
2442            "JID with @hosted server should be detected as hosted"
2443        );
2444
2445        // Case 4: Explicit @hosted.lid server (LID-based hosted JID)
2446        let hosted_lid_server: Jid = "100000012345678:99@hosted.lid"
2447            .parse()
2448            .expect("test JID should be valid");
2449        assert!(
2450            hosted_lid_server.is_hosted(),
2451            "JID with @hosted.lid server should be detected as hosted"
2452        );
2453
2454        // Case 5: @hosted server with different device ID (edge case)
2455        // Even with device ID != 99, if server is @hosted, it's a hosted device
2456        let hosted_server_other_device: Jid = "5511999887766:0@hosted"
2457            .parse()
2458            .expect("test JID should be valid");
2459        assert!(
2460            hosted_server_other_device.is_hosted(),
2461            "JID with @hosted server should be hosted regardless of device ID"
2462        );
2463
2464        // === NON-HOSTED DEVICES (should return false) ===
2465
2466        // Case 6: Regular phone device (primary phone, device 0)
2467        let regular_phone: Jid = "5511999887766:0@s.whatsapp.net"
2468            .parse()
2469            .expect("test JID should be valid");
2470        assert!(
2471            !regular_phone.is_hosted(),
2472            "Regular phone device (ID 0) should NOT be hosted"
2473        );
2474
2475        // Case 7: Companion device (WhatsApp Web, device 33+)
2476        let companion_device: Jid = "5511999887766:33@s.whatsapp.net"
2477            .parse()
2478            .expect("test JID should be valid");
2479        assert!(
2480            !companion_device.is_hosted(),
2481            "Companion device (ID 33) should NOT be hosted"
2482        );
2483
2484        // Case 8: Regular LID device
2485        let regular_lid: Jid = "100000012345678:0@lid"
2486            .parse()
2487            .expect("test JID should be valid");
2488        assert!(
2489            !regular_lid.is_hosted(),
2490            "Regular LID device should NOT be hosted"
2491        );
2492
2493        // Case 9: LID companion device
2494        let lid_companion: Jid = "100000012345678:33@lid"
2495            .parse()
2496            .expect("test JID should be valid");
2497        assert!(
2498            !lid_companion.is_hosted(),
2499            "LID companion device (ID 33) should NOT be hosted"
2500        );
2501
2502        // Case 10: Group JID (not a device at all)
2503        let group_jid: Jid = "120363012345678@g.us"
2504            .parse()
2505            .expect("test JID should be valid");
2506        assert!(
2507            !group_jid.is_hosted(),
2508            "Group JID should NOT be detected as hosted"
2509        );
2510
2511        // Case 11: User JID without device
2512        let user_jid: Jid = "5511999887766@s.whatsapp.net"
2513            .parse()
2514            .expect("test JID should be valid");
2515        assert!(
2516            !user_jid.is_hosted(),
2517            "User JID without device should NOT be hosted"
2518        );
2519
2520        // Case 12: Bot device
2521        let bot_jid: Jid = "13136555001:0@s.whatsapp.net"
2522            .parse()
2523            .expect("test JID should be valid");
2524        assert!(
2525            !bot_jid.is_hosted(),
2526            "Bot JID should NOT be detected as hosted (different mechanism)"
2527        );
2528    }
2529
2530    #[test]
2531    fn is_same_chat_as_matches_rendered_chat_identity() {
2532        let base: Jid = "5511999887766@s.whatsapp.net".parse().unwrap();
2533
2534        // Device is ignored.
2535        assert!(base.is_same_chat_as(&base.with_device(33)));
2536        assert!(base.with_device(5).is_same_chat_as(&base.with_device(0)));
2537
2538        // Different user or server -> different chat (server guards the
2539        // is_same_user_as looseness that ignores server).
2540        let other_user: Jid = "5521988776655@s.whatsapp.net".parse().unwrap();
2541        assert!(!base.is_same_chat_as(&other_user));
2542        let as_lid: Jid = "5511999887766@lid".parse().unwrap();
2543        assert!(!base.is_same_chat_as(&as_lid));
2544
2545        // integrator participates in identity.
2546        let other_integrator = Jid {
2547            integrator: 1,
2548            ..base.clone()
2549        };
2550        assert!(!base.is_same_chat_as(&other_integrator));
2551
2552        // Pn suppresses the agent in display, so a stray decoded agent byte must
2553        // not split the chat: same rendered string -> same chat.
2554        let pn_agent1 = Jid {
2555            agent: 1,
2556            ..base.clone()
2557        };
2558        assert_eq!(base.to_string(), pn_agent1.to_string());
2559        assert!(base.is_same_chat_as(&pn_agent1));
2560
2561        // @bot renders the agent, so distinct agents are distinct chats; device
2562        // is still ignored.
2563        let bot_a = Jid {
2564            user: "13136555001".into(),
2565            server: Server::Bot,
2566            agent: 1,
2567            device: 0,
2568            integrator: 0,
2569        };
2570        let bot_b = Jid {
2571            agent: 2,
2572            ..bot_a.clone()
2573        };
2574        assert_ne!(bot_a.to_string(), bot_b.to_string());
2575        assert!(!bot_a.is_same_chat_as(&bot_b));
2576        assert!(bot_a.is_same_chat_as(&bot_a.with_device(7)));
2577    }
2578
2579    /// Tests that document the filtering behavior for group messages.
2580    ///
2581    /// # Why this matters:
2582    /// When sending a group message, we distribute Sender Key Distribution Messages
2583    /// (SKDM) to all participant devices. However, HOSTED devices:
2584    /// 1. Don't use Signal protocol, so they can't process SKDM
2585    /// 2. WhatsApp Web explicitly excludes them from group fanout
2586    /// 3. Including them would cause unnecessary prekey fetch failures
2587    ///
2588    /// This test documents the expected behavior when filtering device lists.
2589    #[test]
2590    fn test_hosted_device_filtering_for_groups() {
2591        // Simulate a group with mixed device types
2592        let devices: Vec<Jid> = vec![
2593            // Regular devices that SHOULD receive SKDM
2594            "5511999887766:0@s.whatsapp.net"
2595                .parse()
2596                .expect("test JID should be valid"), // Phone
2597            "5511999887766:33@s.whatsapp.net"
2598                .parse()
2599                .expect("test JID should be valid"), // WhatsApp Web
2600            "5521988776655:0@s.whatsapp.net"
2601                .parse()
2602                .expect("test JID should be valid"), // Another user's phone
2603            "100000012345678:0@lid"
2604                .parse()
2605                .expect("test JID should be valid"), // LID device
2606            "100000012345678:33@lid"
2607                .parse()
2608                .expect("test JID should be valid"), // LID companion
2609            // HOSTED devices that should be EXCLUDED from group SKDM
2610            "5531977665544:99@s.whatsapp.net"
2611                .parse()
2612                .expect("test JID should be valid"), // Cloud API business
2613            "100000087654321:99@lid"
2614                .parse()
2615                .expect("test JID should be valid"), // Cloud API on LID
2616            "5541966554433:99@hosted"
2617                .parse()
2618                .expect("test JID should be valid"), // Explicit hosted
2619        ];
2620
2621        // Filter out hosted devices (this is what prepare_group_stanza does)
2622        let filtered: Vec<&Jid> = devices.iter().filter(|jid| !jid.is_hosted()).collect();
2623
2624        // Verify correct filtering
2625        assert_eq!(
2626            filtered.len(),
2627            5,
2628            "Should have 5 non-hosted devices after filtering"
2629        );
2630
2631        // All filtered devices should NOT be hosted
2632        for jid in &filtered {
2633            assert!(
2634                !jid.is_hosted(),
2635                "Filtered list should not contain hosted devices: {}",
2636                jid
2637            );
2638        }
2639
2640        // Count how many hosted devices were filtered out
2641        let hosted_count = devices.iter().filter(|jid| jid.is_hosted()).count();
2642        assert_eq!(hosted_count, 3, "Should have filtered out 3 hosted devices");
2643    }
2644
2645    #[test]
2646    fn test_jid_pn_factory() {
2647        let jid = Jid::pn("1234567890");
2648        assert_eq!(jid.user, "1234567890");
2649        assert_eq!(jid.server, DEFAULT_USER_SERVER);
2650        assert_eq!(jid.device, 0);
2651        assert!(jid.is_pn());
2652    }
2653
2654    #[test]
2655    fn test_jid_lid_factory() {
2656        let jid = Jid::lid("100000012345678");
2657        assert_eq!(jid.user, "100000012345678");
2658        assert_eq!(jid.server, HIDDEN_USER_SERVER);
2659        assert_eq!(jid.device, 0);
2660        assert!(jid.is_lid());
2661    }
2662
2663    #[test]
2664    fn test_jid_group_factory() {
2665        let jid = Jid::group("123456789-1234567890");
2666        assert_eq!(jid.user, "123456789-1234567890");
2667        assert_eq!(jid.server, GROUP_SERVER);
2668        assert!(jid.is_group());
2669    }
2670
2671    #[test]
2672    fn test_jid_pn_device_factory() {
2673        let jid = Jid::pn_device("1234567890", 5);
2674        assert_eq!(jid.user, "1234567890");
2675        assert_eq!(jid.server, DEFAULT_USER_SERVER);
2676        assert_eq!(jid.device, 5);
2677        assert!(jid.is_pn());
2678        assert!(jid.is_ad());
2679    }
2680
2681    #[test]
2682    fn test_jid_lid_device_factory() {
2683        let jid = Jid::lid_device("100000012345678", 33);
2684        assert_eq!(jid.user, "100000012345678");
2685        assert_eq!(jid.server, HIDDEN_USER_SERVER);
2686        assert_eq!(jid.device, 33);
2687        assert!(jid.is_lid());
2688        assert!(jid.is_ad());
2689    }
2690
2691    #[test]
2692    fn test_to_user_jid_maps_hosted_to_account_server() {
2693        let hosted_pn = Jid::new("5511999999999", Server::Hosted).with_device(99);
2694        let user_pn = hosted_pn.to_user_jid();
2695        assert_eq!(user_pn.server, Server::Pn);
2696        assert_eq!(user_pn.user, "5511999999999");
2697        assert_eq!(user_pn.device, 0);
2698
2699        let hosted_lid = Jid::new("100000012345678", Server::HostedLid).with_device(99);
2700        let user_lid = hosted_lid.to_user_jid();
2701        assert_eq!(user_lid.server, Server::Lid);
2702        assert_eq!(user_lid.user, "100000012345678");
2703        assert_eq!(user_lid.device, 0);
2704
2705        let regular_pn = Jid::pn_device("5511999999999", 3);
2706        let user_regular = regular_pn.to_user_jid();
2707        assert_eq!(user_regular.server, Server::Pn);
2708        assert_eq!(user_regular.device, 0);
2709    }
2710
2711    #[test]
2712    fn with_device_hosting_preserves_addressing_family() {
2713        let hosted_pn = Jid::pn("1234567890").with_device_hosting(7, true);
2714        assert_eq!(hosted_pn.server, Server::Hosted);
2715        assert_eq!(hosted_pn.device, 7);
2716
2717        let hosted_lid = Jid::lid("100000012345678").with_device_hosting(8, true);
2718        assert_eq!(hosted_lid.server, Server::HostedLid);
2719        assert_eq!(hosted_lid.device, 8);
2720
2721        let regular = Jid::pn("1234567890").with_device_hosting(9, false);
2722        assert_eq!(regular.server, Server::Pn);
2723
2724        let regular_from_hosted =
2725            Jid::new("1234567890", Server::Hosted).with_device_hosting(9, false);
2726        assert_eq!(regular_from_hosted.server, Server::Pn);
2727
2728        let group = Jid::group("123-456").with_device_hosting(10, true);
2729        assert_eq!(group.server, Server::Group);
2730    }
2731
2732    #[test]
2733    fn server_with_hosting_matrix() {
2734        assert_eq!(Server::Pn.with_hosting(true), Server::Hosted);
2735        assert_eq!(Server::Pn.with_hosting(false), Server::Pn);
2736        assert_eq!(Server::Hosted.with_hosting(true), Server::Hosted);
2737        assert_eq!(Server::Hosted.with_hosting(false), Server::Pn);
2738
2739        assert_eq!(Server::Lid.with_hosting(true), Server::HostedLid);
2740        assert_eq!(Server::Lid.with_hosting(false), Server::Lid);
2741        assert_eq!(Server::HostedLid.with_hosting(true), Server::HostedLid);
2742        assert_eq!(Server::HostedLid.with_hosting(false), Server::Lid);
2743
2744        assert_eq!(Server::Group.with_hosting(true), Server::Group);
2745        assert_eq!(Server::Group.with_hosting(false), Server::Group);
2746    }
2747
2748    #[test]
2749    fn test_status_broadcast_jid() {
2750        let jid = Jid::status_broadcast();
2751        assert_eq!(jid.user, STATUS_BROADCAST_USER);
2752        assert_eq!(jid.server, BROADCAST_SERVER);
2753        assert_eq!(jid.device, 0);
2754        assert!(jid.is_status_broadcast());
2755        assert!(!jid.is_group());
2756        assert!(!jid.is_broadcast_list());
2757        assert_eq!(jid.to_string(), "status@broadcast");
2758
2759        // Parsing round-trip
2760        let parsed: Jid = "status@broadcast".parse().expect("should parse");
2761        assert!(parsed.is_status_broadcast());
2762        assert_eq!(parsed.user, "status");
2763        assert_eq!(parsed.server, "broadcast");
2764
2765        // Regular broadcast list should NOT be status broadcast
2766        let broadcast_list = Jid::new("12345", Server::Broadcast);
2767        assert!(broadcast_list.is_broadcast_list());
2768        assert!(!broadcast_list.is_status_broadcast());
2769
2770        // A group is not a status broadcast (the send path gates addressing_mode on this).
2771        let group: Jid = "120363012345678901@g.us".parse().expect("should parse");
2772        assert!(group.is_group());
2773        assert!(!group.is_status_broadcast());
2774    }
2775
2776    #[test]
2777    fn test_jid_to_non_ad_preserves_user_server() {
2778        // Verify to_non_ad strips device but keeps user/server
2779        let device_jid = Jid::pn_device("1234567890", 33);
2780        let non_ad = device_jid.to_non_ad();
2781        assert_eq!(non_ad.user, "1234567890");
2782        assert_eq!(non_ad.server, DEFAULT_USER_SERVER);
2783        assert_eq!(non_ad.device, 0);
2784        assert!(!non_ad.is_ad());
2785
2786        // LID variant
2787        let lid_device = Jid::lid_device("100000012345678", 25);
2788        let lid_non_ad = lid_device.to_non_ad();
2789        assert_eq!(lid_non_ad.user, "100000012345678");
2790        assert_eq!(lid_non_ad.server, HIDDEN_USER_SERVER);
2791        assert_eq!(lid_non_ad.device, 0);
2792
2793        // status@broadcast stays the same
2794        let status = Jid::status_broadcast();
2795        let status_non_ad = status.to_non_ad();
2796        assert_eq!(status_non_ad.to_string(), "status@broadcast");
2797    }
2798
2799    #[test]
2800    fn test_to_non_ad_string_matches_to_non_ad_to_string() {
2801        // to_non_ad_string() must be byte-identical to to_non_ad().to_string()
2802        // across PN/LID/bot/group/status, with and without device + agent.
2803        for s in [
2804            "1234567890:33@s.whatsapp.net",
2805            "1234567890@s.whatsapp.net",
2806            "100000012345678:25@lid",
2807            "100000012345678@lid",
2808            "867051314767696:0@bot",
2809            "867051314767696@bot",
2810            "120363021033254949@g.us",
2811            "status@broadcast",
2812            "12-34@g.us",
2813        ] {
2814            let jid: Jid = s.parse().expect("parse");
2815            assert_eq!(
2816                jid.to_non_ad_string(),
2817                jid.to_non_ad().to_string(),
2818                "mismatch for {s}"
2819            );
2820        }
2821    }
2822
2823    /// The stack-buffered `Arc<str>` form must render exactly what the `String`
2824    /// form does, including for inputs that overflow the stack buffer and fall
2825    /// back to the heap, and for multibyte user parts (the buffer is bounded in
2826    /// bytes, and a split fragment would be invalid UTF-8).
2827    #[test]
2828    fn to_non_ad_arc_str_matches_to_non_ad_string() {
2829        let long_user = "9".repeat(80);
2830        let multibyte_user = "ẞünïcodé-ñ".repeat(3);
2831        let owned = [
2832            format!("{long_user}:12@s.whatsapp.net"),
2833            format!("{multibyte_user}@g.us"),
2834            format!("{multibyte_user}@s.whatsapp.net"),
2835        ];
2836        let cases = [
2837            "1234567890:33@s.whatsapp.net",
2838            "1234567890@s.whatsapp.net",
2839            "100000012345678:25@lid",
2840            "867051314767696:0@bot",
2841            // Nonzero agent on a bot JID: both forms drop the agent (matching
2842            // whatsmeow's ToNonAD), while `is_same_chat_as` still treats it as
2843            // identity-significant. Pinning it here keeps that asymmetry
2844            // deliberate rather than something a later edit can erase quietly.
2845            "867051314767696.5:10@bot",
2846            "120363021033254949@g.us",
2847            "status@broadcast",
2848        ]
2849        .into_iter()
2850        .chain(owned.iter().map(String::as_str));
2851
2852        for s in cases {
2853            let jid: Jid = s.parse().unwrap_or_else(|e| panic!("parse {s}: {e}"));
2854            assert_eq!(
2855                &*jid.to_non_ad_arc_str(),
2856                jid.to_non_ad_string().as_str(),
2857                "mismatch for {s}"
2858            );
2859        }
2860
2861        // A default (empty-user) JID has no wire form to render but must still
2862        // agree with the String path rather than panic in the stack writer.
2863        let empty = Jid::default();
2864        assert_eq!(
2865            &*empty.to_non_ad_arc_str(),
2866            empty.to_non_ad_string().as_str()
2867        );
2868    }
2869
2870    #[test]
2871    fn test_into_non_ad_matches_to_non_ad() {
2872        // into_non_ad (consuming) must produce a JID identical to to_non_ad (cloning).
2873        for s in [
2874            "1234567890.2:33@s.whatsapp.net",
2875            "1234567890@s.whatsapp.net",
2876            "100000012345678:25@lid",
2877            "user.5:10@bot",
2878            "447911123456.3@interop",
2879            "120363021033254949@g.us",
2880            "status@broadcast",
2881        ] {
2882            let jid: Jid = s.parse().expect("parse");
2883            assert_eq!(
2884                jid.clone().into_non_ad(),
2885                jid.to_non_ad(),
2886                "mismatch for {s}"
2887            );
2888        }
2889    }
2890
2891    #[test]
2892    fn test_jid_factories_with_string_types() {
2893        // Test with &str
2894        let jid1 = Jid::pn("123");
2895        assert_eq!(jid1.user, "123");
2896
2897        // Test with String
2898        let jid2 = Jid::lid(String::from("456"));
2899        assert_eq!(jid2.user, "456");
2900
2901        // Test with owned String
2902        let user = "789".to_string();
2903        let jid3 = Jid::group(user);
2904        assert_eq!(jid3.user, "789");
2905    }
2906
2907    /// Verify that all JID formatting paths produce identical output:
2908    /// `Jid::Display`, `JidRef::Display`, `push_jid_to_string`, `push_jid_to_compact`,
2909    /// `Jid::push_to`, and the generic writer. Exercises the agent-elision rules
2910    /// across server variants.
2911    #[test]
2912    fn test_jid_format_parity() {
2913        struct Case {
2914            user: &'static str,
2915            server: Server,
2916            agent: u8,
2917            device: u16,
2918        }
2919
2920        let cases = [
2921            // Empty user (server-only JID)
2922            Case {
2923                user: "",
2924                server: Server::Pn,
2925                agent: 0,
2926                device: 0,
2927            },
2928            // Basic phone, no agent/device
2929            Case {
2930                user: "5511999887766",
2931                server: Server::Pn,
2932                agent: 0,
2933                device: 0,
2934            },
2935            // Phone with device
2936            Case {
2937                user: "5511999887766",
2938                server: Server::Pn,
2939                agent: 0,
2940                device: 2,
2941            },
2942            // Phone with agent (suppressed for Pn)
2943            Case {
2944                user: "5511999887766",
2945                server: Server::Pn,
2946                agent: 3,
2947                device: 15,
2948            },
2949            // LID with agent (suppressed for Lid)
2950            Case {
2951                user: "12345.6789",
2952                server: Server::Lid,
2953                agent: 1,
2954                device: 25,
2955            },
2956            // Hosted with agent (suppressed)
2957            Case {
2958                user: "100000012345678",
2959                server: Server::Hosted,
2960                agent: 2,
2961                device: 99,
2962            },
2963            // HostedLid with agent (suppressed)
2964            Case {
2965                user: "100000012345678",
2966                server: Server::HostedLid,
2967                agent: 1,
2968                device: 99,
2969            },
2970            // Group (no agent, no device)
2971            Case {
2972                user: "120363012345678901",
2973                server: Server::Group,
2974                agent: 0,
2975                device: 0,
2976            },
2977            // Bot with agent (shown)
2978            Case {
2979                user: "user",
2980                server: Server::Bot,
2981                agent: 5,
2982                device: 10,
2983            },
2984            // Interop with agent (shown)
2985            Case {
2986                user: "447911123456",
2987                server: Server::Interop,
2988                agent: 3,
2989                device: 0,
2990            },
2991            // Messenger with device, no agent
2992            Case {
2993                user: "messenger_user",
2994                server: Server::Messenger,
2995                agent: 0,
2996                device: 50,
2997            },
2998            // Broadcast
2999            Case {
3000                user: "status",
3001                server: Server::Broadcast,
3002                agent: 0,
3003                device: 0,
3004            },
3005            // Newsletter
3006            Case {
3007                user: "newsletter_id",
3008                server: Server::Newsletter,
3009                agent: 0,
3010                device: 0,
3011            },
3012            // Max values
3013            Case {
3014                user: "447911123456789",
3015                server: Server::Pn,
3016                agent: 255,
3017                device: 65535,
3018            },
3019            // Short user
3020            Case {
3021                user: "1",
3022                server: Server::Call,
3023                agent: 0,
3024                device: 1,
3025            },
3026        ];
3027
3028        for (i, c) in cases.iter().enumerate() {
3029            let jid = Jid {
3030                user: c.user.into(),
3031                server: c.server,
3032                agent: c.agent,
3033                device: c.device,
3034                integrator: 0,
3035            };
3036
3037            // Reference: Display impl (via write_jid! fallible)
3038            let display = jid.to_string();
3039
3040            // JidRef Display
3041            let jid_ref = JidRef {
3042                user: NodeStr::Borrowed(c.user),
3043                server: c.server,
3044                agent: c.agent,
3045                device: c.device,
3046                integrator: 0,
3047            };
3048            let ref_display = jid_ref.to_string();
3049
3050            // push_jid_to_string
3051            let mut string_buf = String::new();
3052            push_jid_to_string(c.user, c.server, c.agent, c.device, &mut string_buf);
3053
3054            // push_jid_to_compact
3055            let mut compact_buf = CompactString::default();
3056            push_jid_to_compact(c.user, c.server, c.agent, c.device, &mut compact_buf);
3057
3058            // Jid::push_to
3059            let mut push_buf = String::new();
3060            jid.push_to(&mut push_buf);
3061
3062            // Generic fmt::Write path.
3063            let mut write_buf = String::new();
3064            jid.write_display_to(&mut write_buf).unwrap();
3065
3066            assert_eq!(display, ref_display, "case {i}: Display vs JidRef::Display");
3067            assert_eq!(
3068                display, string_buf,
3069                "case {i}: Display vs push_jid_to_string"
3070            );
3071            assert_eq!(
3072                display,
3073                compact_buf.as_str(),
3074                "case {i}: Display vs push_jid_to_compact"
3075            );
3076            assert_eq!(display, push_buf, "case {i}: Display vs Jid::push_to");
3077            assert_eq!(display, write_buf, "case {i}: Display vs generic writer");
3078        }
3079    }
3080}