wacore 0.7.0

Core WhatsApp protocol implementation without runtime dependencies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! Trusted Contact (tcToken) privacy token lifecycle.
//!
//! Implements the complete tcToken lifecycle matching WhatsApp Web behavior
//! (WAWebTrustedContactsUtils / WAWebPrivacyTokenJob).
//!
//! ## Wire Formats
//!
//! ### Issue Privacy Tokens (IQ set)
//! ```xml
//! <!-- Request -->
//! <iq xmlns="privacy" type="set" to="s.whatsapp.net" id="...">
//!   <tokens>
//!     <token jid="user@lid" t="1707000000" type="trusted_contact"/>
//!   </tokens>
//! </iq>
//!
//! <!-- Response -->
//! <iq from="s.whatsapp.net" id="..." type="result">
//!   <tokens>
//!     <token jid="user@lid" t="1707000000" type="trusted_contact">
//!       <!-- token bytes -->
//!     </token>
//!   </tokens>
//! </iq>
//! ```
//!
//! ### Incoming Token Notification
//! ```xml
//! <notification type="privacy_token" from="user@s.whatsapp.net">
//!   <tokens>
//!     <token type="trusted_contact" t="1707000000"><!-- bytes --></token>
//!   </tokens>
//! </notification>
//! ```
//!
//! ### Message Stanza
//! ```xml
//! <tctoken><!-- raw token bytes --></tctoken>
//! ```

use crate::iq::spec::IqSpec;
use crate::request::InfoQuery;
use wacore_binary::builder::NodeBuilder;
use wacore_binary::{Jid, Server};
use wacore_binary::{Node, NodeContent, NodeRef};

use super::privacy::PRIVACY_NAMESPACE;

/// Default bucket duration in seconds — WA Web AB prop `tctoken_duration` (default 604800 = 7 days).
pub const TC_TOKEN_BUCKET_DURATION: i64 = 604_800;

/// Default number of buckets — WA Web AB prop `tctoken_num_buckets` (default 4).
pub const TC_TOKEN_NUM_BUCKETS: i64 = 4;

/// Maximum allowed bucket duration (180 days) — matches WA Web's cap.
pub const TC_TOKEN_MAX_DURATION: i64 = 15_552_000;

/// Runtime-configurable tctoken timing from AB props.
/// All fields must be >= 1 (division-by-zero guard in bucket math).
#[derive(Debug, Clone, Copy)]
pub struct TcTokenConfig {
    pub bucket_duration: i64,
    pub num_buckets: i64,
    pub sender_bucket_duration: i64,
    pub sender_num_buckets: i64,
}

impl TcTokenConfig {
    /// Clamp fields to safe ranges: durations to [1, MAX], counts to >= 1.
    pub fn clamped(self) -> Self {
        Self {
            bucket_duration: self.bucket_duration.clamp(1, TC_TOKEN_MAX_DURATION),
            num_buckets: self.num_buckets.max(1),
            sender_bucket_duration: self.sender_bucket_duration.clamp(1, TC_TOKEN_MAX_DURATION),
            sender_num_buckets: self.sender_num_buckets.max(1),
        }
    }
}

impl Default for TcTokenConfig {
    fn default() -> Self {
        Self {
            bucket_duration: TC_TOKEN_BUCKET_DURATION,
            num_buckets: TC_TOKEN_NUM_BUCKETS,
            sender_bucket_duration: TC_TOKEN_BUCKET_DURATION,
            sender_num_buckets: TC_TOKEN_NUM_BUCKETS,
        }
    }
}

/// Get the current unix timestamp in seconds.
fn unix_now() -> i64 {
    crate::time::now_secs()
}

/// Check if a tcToken has expired using configurable receiver-side timing.
pub fn is_tc_token_expired_with(token_timestamp: i64, config: &TcTokenConfig) -> bool {
    is_tc_token_expired_with_at(token_timestamp, config, unix_now())
}

/// Same as [`is_tc_token_expired_with`], but against a caller-supplied `now`.
pub fn is_tc_token_expired_with_at(token_timestamp: i64, config: &TcTokenConfig, now: i64) -> bool {
    let cfg = config.clamped();
    is_tc_token_expired_at(token_timestamp, now, cfg.bucket_duration, cfg.num_buckets)
}

/// Check if a sender-side timestamp has expired using sender-specific timing.
pub fn is_sender_tc_token_expired(sender_timestamp: i64, config: &TcTokenConfig) -> bool {
    let cfg = config.clamped();
    is_tc_token_expired_at(
        sender_timestamp,
        unix_now(),
        cfg.sender_bucket_duration,
        cfg.sender_num_buckets,
    )
}

fn is_tc_token_expired_at(
    token_timestamp: i64,
    now: i64,
    bucket_duration: i64,
    num_buckets: i64,
) -> bool {
    token_timestamp < expiration_cutoff_at(now, bucket_duration, num_buckets)
}

/// Compute the bucket index for a given timestamp.
fn bucket_index(timestamp: i64, bucket_duration: i64) -> i64 {
    timestamp / bucket_duration
}

/// Bucket-aligned expiration cutoff matching WA Web's `tokenExpirationCutoff`.
fn expiration_cutoff_at(now: i64, bucket_duration: i64, num_buckets: i64) -> i64 {
    let current_bucket = bucket_index(now, bucket_duration);
    let expired_bucket = current_bucket - (num_buckets - 1);
    expired_bucket * bucket_duration
}

/// Check if we should issue a new tcToken using configurable sender bucket duration.
pub fn should_send_new_tc_token_with(
    sender_timestamp: Option<i64>,
    config: &TcTokenConfig,
) -> bool {
    should_send_new_tc_token_with_at(sender_timestamp, config, unix_now())
}

/// Same as [`should_send_new_tc_token_with`], but against a caller-supplied `now`.
pub fn should_send_new_tc_token_with_at(
    sender_timestamp: Option<i64>,
    config: &TcTokenConfig,
    now: i64,
) -> bool {
    let cfg = config.clamped();
    should_send_new_tc_token_at(sender_timestamp, now, cfg.sender_bucket_duration)
}

fn should_send_new_tc_token_at(
    sender_timestamp: Option<i64>,
    now: i64,
    bucket_duration: i64,
) -> bool {
    match sender_timestamp {
        None => true,
        Some(ts) => bucket_index(now, bucket_duration) > bucket_index(ts, bucket_duration),
    }
}

/// Compute the expiration cutoff timestamp for pruning (default constants).
///
/// For AB-prop-aware cutoff, use [`tc_token_expiration_cutoff_with`].
pub fn tc_token_expiration_cutoff() -> i64 {
    expiration_cutoff_at(unix_now(), TC_TOKEN_BUCKET_DURATION, TC_TOKEN_NUM_BUCKETS)
}

/// Compute the receiver-side expiration cutoff using configurable timing.
pub fn tc_token_expiration_cutoff_with(config: &TcTokenConfig) -> i64 {
    let cfg = config.clamped();
    expiration_cutoff_at(unix_now(), cfg.bucket_duration, cfg.num_buckets)
}

/// Compute the sender-side expiration cutoff using configurable timing.
///
/// Sender state (issuance rate-limit) lives in a different bucket window than the
/// received token, so pruning must evaluate it against this cutoff rather than
/// the receiver one.
pub fn sender_tc_token_expiration_cutoff_with(config: &TcTokenConfig) -> i64 {
    let cfg = config.clamped();
    expiration_cutoff_at(
        unix_now(),
        cfg.sender_bucket_duration,
        cfg.sender_num_buckets,
    )
}

/// A token received from the server in an IQ response or notification.
#[derive(Debug, Clone)]
pub struct ReceivedTcToken {
    /// The JID this token belongs to.
    pub jid: Jid,
    /// Raw token bytes.
    pub token: Vec<u8>,
    /// Timestamp from the `t` attribute.
    pub timestamp: i64,
}

/// Token data parsed from a notification (JID resolved by caller).
#[derive(Debug, Clone)]
pub struct ParsedTokenData {
    /// Raw token bytes.
    pub token: Vec<u8>,
    /// Timestamp from the `t` attribute.
    pub timestamp: i64,
}

/// Issues privacy tokens to one or more contacts.
///
/// Sends our token to the specified JIDs and receives their tokens back.
pub struct IssuePrivacyTokensSpec {
    /// JIDs to issue tokens for (should be LID JIDs).
    pub jids: Vec<Jid>,
    /// Current timestamp to use for the token issuance.
    pub timestamp: i64,
}

impl IssuePrivacyTokensSpec {
    pub fn new(jids: &[Jid]) -> Self {
        Self {
            jids: jids.to_vec(),
            timestamp: unix_now(),
        }
    }

    /// Create a spec with a specific timestamp (for identity change re-issuance).
    ///
    /// WA Web passes the stored senderTimestamp when re-issuing after identity change
    /// (`sendTcTokenWhenDeviceIdentityChange`), preserving the original issuance epoch.
    pub fn with_timestamp(jids: &[Jid], timestamp: i64) -> Self {
        Self {
            jids: jids.to_vec(),
            timestamp,
        }
    }
}

/// Response from issuing privacy tokens.
#[derive(Debug, Clone, Default)]
pub struct IssuePrivacyTokensResponse {
    /// Tokens received back from the server.
    pub tokens: Vec<ReceivedTcToken>,
}

impl IqSpec for IssuePrivacyTokensSpec {
    type Response = IssuePrivacyTokensResponse;

    fn build_iq(&self) -> InfoQuery<'static> {
        let token_nodes: Vec<Node> = self
            .jids
            .iter()
            .map(|jid| {
                NodeBuilder::new("token")
                    .attr("jid", jid)
                    .attr("t", self.timestamp)
                    .attr("type", "trusted_contact")
                    .build()
            })
            .collect();

        InfoQuery::set(
            PRIVACY_NAMESPACE,
            Jid::new("", Server::Pn),
            Some(NodeContent::Nodes(vec![
                NodeBuilder::new("tokens").children(token_nodes).build(),
            ])),
        )
    }

    fn parse_response(&self, response: &NodeRef<'_>) -> Result<Self::Response, anyhow::Error> {
        let tokens_node = match response.get_optional_child("tokens") {
            Some(n) => n,
            None => return Ok(IssuePrivacyTokensResponse::default()),
        };

        let mut tokens = Vec::new();
        for token_node in tokens_node.get_children_by_tag("token") {
            let jid: Jid = token_node
                .attrs()
                .optional_jid("jid")
                .ok_or_else(|| anyhow::anyhow!("missing required attribute jid"))?;
            let t_str = token_node
                .get_attr("t")
                .map(|v| v.as_str())
                .ok_or_else(|| anyhow::anyhow!("missing required attribute t"))?;
            let timestamp: i64 = t_str
                .parse()
                .map_err(|e| anyhow::anyhow!("invalid timestamp '{}': {}", t_str, e))?;

            let Some(token_data) = token_node.content_bytes() else {
                log::warn!(target: "TcToken", "Token node for {} has no binary content, skipping", jid);
                continue;
            };

            tokens.push(ReceivedTcToken {
                jid,
                token: token_data.to_vec(),
                timestamp,
            });
        }

        Ok(IssuePrivacyTokensResponse { tokens })
    }
}

/// Parse incoming privacy_token notification.
///
/// Extracts token data from a `<notification type="privacy_token">` stanza.
/// Returns `ParsedTokenData` items without JID — the caller is responsible for
/// resolving the sender JID from the notification's `sender_lid` / `from` attributes.
pub fn parse_privacy_token_notification(
    notification: &NodeRef<'_>,
) -> Result<Vec<ParsedTokenData>, anyhow::Error> {
    let tokens_node = notification
        .get_optional_child("tokens")
        .ok_or_else(|| anyhow::anyhow!("<tokens> child not found"))?;

    let mut tokens = Vec::new();
    for token_node in tokens_node.get_children_by_tag("token") {
        let token_type = token_node
            .get_attr("type")
            .map(|v| v.as_str())
            .unwrap_or_default();
        if token_type != "trusted_contact" {
            continue;
        }

        let t_str = token_node
            .get_attr("t")
            .map(|v| v.as_str())
            .ok_or_else(|| anyhow::anyhow!("missing required attribute t"))?;
        let timestamp: i64 = t_str.parse().map_err(|e| {
            anyhow::anyhow!(
                "invalid timestamp '{}' in privacy_token notification: {}",
                t_str,
                e
            )
        })?;

        let Some(token_data) = token_node.content_bytes() else {
            log::warn!(target: "TcToken", "Notification token node has no binary content, skipping");
            continue;
        };

        tokens.push(ParsedTokenData {
            token: token_data.to_vec(),
            timestamp,
        });
    }

    Ok(tokens)
}

/// Compute a cstoken (client-side token / NCT) for a recipient.
///
/// This is the fallback token used when no tctoken exists for the recipient.
/// Matches WA Web: `genCsTokenBody` in `MsgCreateFanoutStanza.js`.
///
/// `salt` — NCT salt from app state sync (raw bytes, not base64).
/// `recipient_lid` — The recipient's bare account LID string (e.g. `"12345@lid"`).
pub fn compute_cs_token(salt: &[u8], recipient_lid: &str) -> Vec<u8> {
    use hmac::{Hmac, KeyInit, Mac};
    use sha2::Sha256;

    let mut mac = Hmac::<Sha256>::new_from_slice(salt).expect("HMAC-SHA256 accepts any key length");
    mac.update(recipient_lid.as_bytes());
    mac.finalize().into_bytes().to_vec()
}

/// Build a `<cstoken>` stanza child for including in outgoing messages.
pub fn build_cs_token_node(token: &[u8]) -> Node {
    NodeBuilder::new("cstoken").bytes(token.to_vec()).build()
}

/// Build a `<tctoken>` stanza child for including in outgoing messages.
pub fn build_tc_token_node(token: &[u8]) -> Node {
    NodeBuilder::new("tctoken").bytes(token.to_vec()).build()
}

/// Which privacy token (if any) to attach to an outgoing 1:1 message stanza.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrivacyTokenChoice {
    /// Attach the stored trusted-contact token bytes.
    TcToken,
    /// Attach an NCT `cstoken` fallback.
    CsToken,
    /// Attach nothing.
    None,
}

/// Decide which privacy token to attach, mirroring WA Web's
/// `Re = R(te) ?? D(te, s)` in `MsgCreateFanoutStanza.js`.
///
/// `tc_send_enabled` (`privacy_token_sending_on_all_1_on_1_messages`) gates the
/// tctoken only — WA Web's `R`. The cstoken is gated independently on
/// `nct_send_enabled` (`wa_nct_token_send_enabled`) — WA Web's `D` — and is NOT
/// nested behind the 1:1 prop: when `R` yields nothing (prop off, or token
/// missing/expired), `D` still runs.
pub fn choose_privacy_token(
    tc_send_enabled: bool,
    nct_send_enabled: bool,
    has_valid_tc_token: bool,
    can_build_cs_token: bool,
) -> PrivacyTokenChoice {
    if tc_send_enabled && has_valid_tc_token {
        PrivacyTokenChoice::TcToken
    } else if nct_send_enabled && can_build_cs_token {
        PrivacyTokenChoice::CsToken
    } else {
        PrivacyTokenChoice::None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const DUR: i64 = TC_TOKEN_BUCKET_DURATION;
    const BUCKETS: i64 = TC_TOKEN_NUM_BUCKETS;

    #[test]
    fn test_bucket_index() {
        assert_eq!(bucket_index(0, DUR), 0);
        assert_eq!(bucket_index(604799, DUR), 0);
        assert_eq!(bucket_index(604800, DUR), 1);
        assert_eq!(bucket_index(1209599, DUR), 1);
        assert_eq!(bucket_index(1209600, DUR), 2);
    }

    /// The send path hands one instant to both privacy-token decisions instead
    /// of letting each read the clock. Pin the boundary they land on.
    #[test]
    fn supplied_instant_decides_the_same_bucket_boundary() {
        let config = TcTokenConfig::default().clamped();
        let issued = 10 * config.sender_bucket_duration;

        let last_second_of_bucket = issued + config.sender_bucket_duration - 1;
        assert!(!should_send_new_tc_token_with_at(
            Some(issued),
            &config,
            last_second_of_bucket
        ));
        assert!(should_send_new_tc_token_with_at(
            Some(issued),
            &config,
            last_second_of_bucket + 1
        ));

        let stamped = 10 * config.bucket_duration;
        let still_valid = stamped + (config.num_buckets - 1) * config.bucket_duration;
        assert!(!is_tc_token_expired_with_at(stamped, &config, still_valid));
        assert!(is_tc_token_expired_with_at(
            stamped,
            &config,
            still_valid + config.bucket_duration
        ));
    }

    #[test]
    fn test_should_send_new_tc_token_none() {
        assert!(should_send_new_tc_token_at(None, 1_000_000, DUR));
    }

    #[test]
    fn test_should_send_new_tc_token_same_bucket() {
        let now = 2 * DUR + 100;
        let same_bucket_ts = 2 * DUR;
        assert!(!should_send_new_tc_token_at(Some(same_bucket_ts), now, DUR));
    }

    #[test]
    fn test_should_send_new_tc_token_different_bucket() {
        let now = 3 * DUR + 100;
        let old_ts = DUR + 50;
        assert!(should_send_new_tc_token_at(Some(old_ts), now, DUR));
    }

    #[test]
    fn test_should_send_new_tc_token_clock_backward_no_reissue() {
        let future_ts = 5 * DUR + 100;
        let now = 3 * DUR + 100;
        assert!(!should_send_new_tc_token_at(Some(future_ts), now, DUR));
    }

    #[test]
    fn test_is_tc_token_expired() {
        let now = 10 * DUR;
        // cutoff = (10 - 3) * dur = 7 * dur — buckets 7..=10 are valid

        assert!(!is_tc_token_expired_at(now - 100, now, DUR, BUCKETS));
        assert!(!is_tc_token_expired_at(7 * DUR, now, DUR, BUCKETS));
        assert!(is_tc_token_expired_at(7 * DUR - 1, now, DUR, BUCKETS));
        assert!(is_tc_token_expired_at(6 * DUR, now, DUR, BUCKETS));
    }

    #[test]
    fn test_is_tc_token_expired_mid_bucket() {
        let now = 10 * DUR + DUR / 2;
        // cutoff = (10 - 3) * dur = 7 * dur (bucket-aligned, doesn't change mid-bucket)

        assert!(!is_tc_token_expired_at(7 * DUR, now, DUR, BUCKETS));
        assert!(is_tc_token_expired_at(7 * DUR - 1, now, DUR, BUCKETS));
    }

    #[test]
    fn test_expiration_cutoff_is_bucket_aligned() {
        let now = 10 * DUR + 12345;
        let cutoff = expiration_cutoff_at(now, DUR, BUCKETS);
        assert_eq!(cutoff % DUR, 0);
        assert_eq!(cutoff, 7 * DUR);
    }

    #[test]
    fn test_tc_token_expiration_cutoff() {
        let now = unix_now();
        let cutoff = tc_token_expiration_cutoff();
        let expected = expiration_cutoff_at(now, DUR, BUCKETS);
        assert!((cutoff - expected).abs() <= 1);
    }

    #[test]
    fn test_custom_config_shorter_duration() {
        let config = TcTokenConfig {
            bucket_duration: 3600, // 1 hour
            num_buckets: 3,
            sender_bucket_duration: 3600,
            sender_num_buckets: 3,
        };
        let now = 10 * 3600;
        // cutoff = (10 - 2) * 3600 = 8 * 3600
        assert!(!is_tc_token_expired_at(
            8 * 3600,
            now,
            config.bucket_duration,
            config.num_buckets
        ));
        assert!(is_tc_token_expired_at(
            8 * 3600 - 1,
            now,
            config.bucket_duration,
            config.num_buckets
        ));
    }

    #[test]
    fn test_issue_privacy_tokens_spec_build_iq() {
        let jid1: Jid = "100000000000001@lid".parse().unwrap();
        let jid2: Jid = "100000000000002@lid".parse().unwrap();
        let spec = IssuePrivacyTokensSpec {
            jids: vec![jid1, jid2],
            timestamp: 1707000000,
        };
        let iq = spec.build_iq();

        assert_eq!(iq.namespace, PRIVACY_NAMESPACE);
        assert_eq!(iq.query_type, crate::request::InfoQueryType::Set);

        if let Some(NodeContent::Nodes(nodes)) = &iq.content {
            assert_eq!(nodes.len(), 1);
            assert_eq!(nodes[0].tag, "tokens");
            let token_children: Vec<_> = nodes[0].get_children_by_tag("token").collect();
            assert_eq!(token_children.len(), 2);
        } else {
            panic!("Expected NodeContent::Nodes");
        }
    }

    #[test]
    fn test_issue_privacy_tokens_spec_parse_response() {
        let spec = IssuePrivacyTokensSpec {
            jids: vec!["100000000000001@lid".parse().unwrap()],
            timestamp: 1707000000,
        };

        let response = NodeBuilder::new("iq")
            .attr("type", "result")
            .children([NodeBuilder::new("tokens")
                .children([NodeBuilder::new("token")
                    .attr("jid", "100000000000001@lid")
                    .attr("t", "1707000000")
                    .attr("type", "trusted_contact")
                    .bytes(vec![0xDE, 0xAD, 0xBE, 0xEF])
                    .build()])
                .build()])
            .build();

        let result = spec.parse_response(&response.as_node_ref()).unwrap();
        assert_eq!(result.tokens.len(), 1);
        assert_eq!(result.tokens[0].jid.to_string(), "100000000000001@lid");
        assert_eq!(result.tokens[0].token, vec![0xDE, 0xAD, 0xBE, 0xEF]);
        assert_eq!(result.tokens[0].timestamp, 1707000000);
    }

    #[test]
    fn test_issue_privacy_tokens_spec_parse_skips_empty_token() {
        let spec = IssuePrivacyTokensSpec {
            jids: vec!["100000000000001@lid".parse().unwrap()],
            timestamp: 1707000000,
        };

        // Token node without binary content should be skipped
        let response = NodeBuilder::new("iq")
            .attr("type", "result")
            .children([NodeBuilder::new("tokens")
                .children([NodeBuilder::new("token")
                    .attr("jid", "100000000000001@lid")
                    .attr("t", "1707000000")
                    .attr("type", "trusted_contact")
                    .build()])
                .build()])
            .build();

        let result = spec.parse_response(&response.as_node_ref()).unwrap();
        assert!(result.tokens.is_empty());
    }

    #[test]
    fn test_parse_privacy_token_notification() {
        let notification = NodeBuilder::new("notification")
            .attr("type", "privacy_token")
            .children([NodeBuilder::new("tokens")
                .children([NodeBuilder::new("token")
                    .attr("type", "trusted_contact")
                    .attr("t", "1707000000")
                    .bytes(vec![0xCA, 0xFE])
                    .build()])
                .build()])
            .build();

        let tokens = parse_privacy_token_notification(&notification.as_node_ref()).unwrap();
        assert_eq!(tokens.len(), 1);
        assert_eq!(tokens[0].token, vec![0xCA, 0xFE]);
        assert_eq!(tokens[0].timestamp, 1707000000);
    }

    #[test]
    fn test_parse_privacy_token_notification_skips_non_trusted_contact() {
        let notification = NodeBuilder::new("notification")
            .children([NodeBuilder::new("tokens")
                .children([
                    NodeBuilder::new("token")
                        .attr("type", "other_type")
                        .attr("t", "1000")
                        .build(),
                    NodeBuilder::new("token")
                        .attr("type", "trusted_contact")
                        .attr("t", "2000")
                        .bytes(vec![0x01])
                        .build(),
                ])
                .build()])
            .build();

        let tokens = parse_privacy_token_notification(&notification.as_node_ref()).unwrap();
        assert_eq!(tokens.len(), 1);
        assert_eq!(tokens[0].timestamp, 2000);
    }

    #[test]
    fn test_parse_privacy_token_notification_skips_empty_content() {
        let notification = NodeBuilder::new("notification")
            .children([NodeBuilder::new("tokens")
                .children([NodeBuilder::new("token")
                    .attr("type", "trusted_contact")
                    .attr("t", "1707000000")
                    .build()])
                .build()])
            .build();

        let tokens = parse_privacy_token_notification(&notification.as_node_ref()).unwrap();
        assert!(tokens.is_empty());
    }

    #[test]
    fn test_build_tc_token_node() {
        let node = build_tc_token_node(&[0x01, 0x02, 0x03]);
        assert_eq!(node.tag, "tctoken");
        match &node.content {
            Some(NodeContent::Bytes(data)) => assert_eq!(data, &[0x01, 0x02, 0x03]),
            _ => panic!("Expected binary content"),
        }
    }

    #[test]
    fn test_issue_privacy_tokens_spec_empty_response() {
        let spec = IssuePrivacyTokensSpec {
            jids: vec![],
            timestamp: 1707000000,
        };

        let response = NodeBuilder::new("iq").attr("type", "result").build();

        let result = spec.parse_response(&response.as_node_ref()).unwrap();
        assert!(result.tokens.is_empty());
    }

    #[test]
    fn test_issue_privacy_tokens_spec_new_from_slice() {
        let jid1: Jid = "alice@lid".parse().unwrap();
        let jid2: Jid = "bob@lid".parse().unwrap();
        let jids = [jid1.clone(), jid2.clone()];
        let spec = IssuePrivacyTokensSpec::new(&jids);
        assert_eq!(spec.jids.len(), 2);
        assert_eq!(spec.jids[0], jid1);
        assert_eq!(spec.jids[1], jid2);
    }

    #[test]
    fn test_compute_cs_token_deterministic() {
        let salt = b"test_salt_bytes_16";
        let lid = "alice@lid";
        let token1 = compute_cs_token(salt, lid);
        let token2 = compute_cs_token(salt, lid);
        assert_eq!(token1, token2);
        assert_eq!(token1.len(), 32); // HMAC-SHA256 output is 32 bytes
    }

    #[test]
    fn test_compute_cs_token_different_lids() {
        let salt = b"test_salt_bytes_16";
        let token1 = compute_cs_token(salt, "alice@lid");
        let token2 = compute_cs_token(salt, "bob@lid");
        assert_ne!(token1, token2);
    }

    #[test]
    fn test_compute_cs_token_different_salts() {
        let lid = "alice@lid";
        let token1 = compute_cs_token(b"salt_a", lid);
        let token2 = compute_cs_token(b"salt_b", lid);
        assert_ne!(token1, token2);
    }

    #[test]
    fn test_compute_cs_token_known_answer() {
        // Pre-computed HMAC-SHA256 to catch accidental algorithm changes
        // (e.g., if someone swaps key/data arguments).
        let salt = b"whatsapp_nct_salt_example";
        let lid = "alice@lid";
        let expected: [u8; 32] = [
            0x7c, 0x6a, 0xfc, 0x32, 0x57, 0x85, 0xac, 0x3c, 0x4f, 0x57, 0x1e, 0x64, 0x8a, 0x3b,
            0xb8, 0x22, 0xf0, 0xe2, 0xe4, 0x94, 0x34, 0x81, 0x2e, 0xd2, 0x80, 0x9a, 0xea, 0x2e,
            0x70, 0x43, 0xb5, 0x76,
        ];
        assert_eq!(compute_cs_token(salt, lid), expected);
    }

    #[test]
    fn test_build_cs_token_node() {
        let node = build_cs_token_node(&[0xAA, 0xBB, 0xCC]);
        assert_eq!(node.tag, "cstoken");
        match &node.content {
            Some(NodeContent::Bytes(data)) => assert_eq!(data, &[0xAA, 0xBB, 0xCC]),
            _ => panic!("Expected binary content"),
        }
    }

    #[test]
    fn choose_prefers_valid_tc_token() {
        assert_eq!(
            choose_privacy_token(true, true, true, true),
            PrivacyTokenChoice::TcToken
        );
    }

    #[test]
    fn choose_falls_back_to_cs_token_when_tc_missing() {
        // tctoken prop on, but no valid token → cstoken fallback runs.
        assert_eq!(
            choose_privacy_token(true, true, false, true),
            PrivacyTokenChoice::CsToken
        );
    }

    #[test]
    fn choose_cs_token_when_tc_send_disabled() {
        // Regression: the cstoken is gated only on nct_send_enabled and must be
        // attached even when privacy_token_sending_on_all_1_on_1_messages is off.
        assert_eq!(
            choose_privacy_token(false, true, false, true),
            PrivacyTokenChoice::CsToken
        );
        // A valid tc token is ignored while its own prop is off; cstoken still wins.
        assert_eq!(
            choose_privacy_token(false, true, true, true),
            PrivacyTokenChoice::CsToken
        );
    }

    #[test]
    fn choose_none_when_cs_token_unbuildable() {
        assert_eq!(
            choose_privacy_token(true, true, false, false),
            PrivacyTokenChoice::None
        );
        assert_eq!(
            choose_privacy_token(false, true, false, false),
            PrivacyTokenChoice::None
        );
    }

    #[test]
    fn choose_none_when_all_disabled() {
        assert_eq!(
            choose_privacy_token(false, false, true, true),
            PrivacyTokenChoice::None
        );
    }
}