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
//! Device notification stanza types.
//!
//! Parses `<notification type="devices">` stanzas for device add/remove/update.
//!
//! Reference: WhatsApp Web `WAWebHandleDeviceNotification` (5Yec01dI04o.js:23109-23305)
//!
//! Key behaviors:
//! - Only ONE operation per notification (priority: remove > add > update)
//! - `key-index-list` is REQUIRED for add/remove
//! - Timestamp is REQUIRED (non-zero) for remove
//! - `hash` attribute is REQUIRED for update

use crate::WireEnum;
use crate::iq::node::{required_attr, required_child};
use crate::protocol::ProtocolNode;
use anyhow::{Result, anyhow};
use serde::Serialize;
use wacore_binary::Jid;
use wacore_binary::builder::NodeBuilder;
use wacore_binary::{Node, NodeRef};

/// Device notification operation type.
///
/// Wire format: Child element tag of `<notification type="devices">`
/// - `<add>` - Device was added
/// - `<remove>` - Device was removed
/// - `<update>` - Device info updated (hash-based lookup)
#[derive(Debug, Clone, Copy, PartialEq, Eq, WireEnum)]
pub enum DeviceNotificationType {
    #[wire = "add"]
    Add,
    #[wire = "remove"]
    Remove,
    #[wire = "update"]
    Update,
}

/// Key index information from `<key-index-list>` element.
///
/// Wire format:
/// ```xml
/// <!-- For add: has signed bytes content -->
/// <key-index-list ts="1769296600">SIGNED_BYTES</key-index-list>
/// <!-- For remove: empty, ts required -->
/// <key-index-list ts="1769296600"/>
/// ```
///
/// Required for add/remove operations per WhatsApp Web.
#[derive(Debug, Clone, Serialize)]
pub struct KeyIndexInfo {
    /// Timestamp (required for remove per WhatsApp Web)
    pub timestamp: i64,
    /// Signed key index bytes (only present for add)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signed_bytes: Option<Vec<u8>>,
}

impl ProtocolNode for KeyIndexInfo {
    fn tag(&self) -> &'static str {
        "key-index-list"
    }

    fn into_node(self) -> Node {
        let mut builder = NodeBuilder::new("key-index-list").attr("ts", self.timestamp);
        if let Some(bytes) = self.signed_bytes {
            builder = builder.bytes(bytes);
        }
        builder.build()
    }

    fn try_from_node_ref(node: &NodeRef<'_>) -> Result<Self> {
        use wacore_binary::NodeContentRef;
        if node.tag != "key-index-list" {
            return Err(anyhow!("expected <key-index-list>, got <{}>", node.tag));
        }
        let ts_u64 = node
            .attrs()
            .optional_u64("ts")
            .ok_or_else(|| anyhow!("key-index-list missing required 'ts' attribute"))?;
        let timestamp = i64::try_from(ts_u64)
            .map_err(|_| anyhow!("key-index-list 'ts' value {} exceeds i64::MAX", ts_u64))?;
        let signed_bytes = match node.content.as_ref() {
            Some(NodeContentRef::Bytes(b)) if !b.is_empty() => Some(b.to_vec()),
            _ => None,
        };
        Ok(Self {
            timestamp,
            signed_bytes,
        })
    }
}

/// Device element from notification.
///
/// Wire format:
/// ```xml
/// <device jid="185169143189667:75@lid" key-index="2" lid="..."/>
/// ```
///
/// Device ID is extracted from the JID's device part (e.g., 75 from "user:75@lid").
///
/// Per WhatsApp Web: if both `jid` and `lid` attributes are present, the device IDs
/// must match or the notification is rejected.
#[derive(Debug, Clone, Serialize)]
pub struct DeviceElement {
    /// Device JID (contains user and device ID)
    pub jid: Jid,
    /// Optional key index
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key_index: Option<u32>,
    /// Optional LID (device ID must match jid's device ID if present)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lid: Option<Jid>,
}

impl DeviceElement {
    /// Extract the device ID from the JID.
    #[inline]
    pub fn device_id(&self) -> u32 {
        self.jid.device as u32
    }
}

impl ProtocolNode for DeviceElement {
    fn tag(&self) -> &'static str {
        "device"
    }

    fn into_node(self) -> Node {
        let mut builder = NodeBuilder::new("device").attr("jid", self.jid);
        if let Some(ki) = self.key_index {
            builder = builder.attr("key-index", ki);
        }
        if let Some(lid) = self.lid {
            builder = builder.attr("lid", lid);
        }
        builder.build()
    }

    fn try_from_node_ref(node: &NodeRef<'_>) -> Result<Self> {
        if node.tag != "device" {
            return Err(anyhow!("expected <device>, got <{}>", node.tag));
        }
        let mut attrs = node.attrs();
        let jid = attrs
            .optional_jid("jid")
            .ok_or_else(|| anyhow!("device missing required 'jid' attribute"))?;

        let key_index = match attrs.optional_u64("key-index") {
            Some(v) => Some(
                u32::try_from(v)
                    .map_err(|_| anyhow!("device 'key-index' value {} exceeds u32::MAX", v))?,
            ),
            None => None,
        };

        let lid = attrs.optional_jid("lid");

        if let Some(ref lid_jid) = lid {
            let jid_device_id = jid.device;
            let lid_device_id = lid_jid.device;
            if jid_device_id != lid_device_id {
                return Err(anyhow!(
                    "device id mismatch between jid ({}) and lid ({}) attributes",
                    jid_device_id,
                    lid_device_id
                ));
            }
        }

        Ok(Self {
            jid,
            key_index,
            lid,
        })
    }
}

/// Operation content (add/remove/update child element).
///
/// Wire format per WhatsApp Web (5Yec01dI04o.js:23141-23180):
/// ```xml
/// <add>
///   <device jid="user:75@lid" key-index="2"/>
///   <key-index-list ts="...">SIGNED_BYTES</key-index-list>
/// </add>
/// <!-- OR -->
/// <remove>
///   <device jid="user:75@lid"/>
///   <key-index-list ts="..."/>  <!-- ts required for remove -->
/// </remove>
/// <!-- OR -->
/// <update hash="CONTACT_HASH"/>
/// ```
///
/// Note: WhatsApp Web does NOT read any attributes from add/remove nodes.
/// The `device_hash` attribute (if present) is not used by the official client.
#[derive(Debug, Clone, Serialize)]
pub struct DeviceOperation {
    /// Operation type (add/remove/update)
    pub operation_type: DeviceNotificationType,
    /// Contact hash (for update only) - from `hash` attribute, used for contact lookup
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contact_hash: Option<String>,
    /// Device elements (for add/remove, single device per WhatsApp Web)
    pub devices: Vec<DeviceElement>,
    /// Key index info (required for add/remove per WhatsApp Web)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key_index: Option<KeyIndexInfo>,
}

impl DeviceOperation {
    /// Parse from an add/remove/update child `NodeRef`.
    ///
    /// Per WhatsApp Web (5Yec01dI04o.js:23141-23157):
    /// - `key-index-list` is REQUIRED for add/remove operations
    /// - `ts` attribute is REQUIRED for remove operations
    pub fn try_from_child(node: &NodeRef<'_>) -> Result<Self> {
        let operation_type = DeviceNotificationType::try_from(node.tag.as_ref())
            .map_err(|_| anyhow!("unknown device operation: {}", node.tag))?;

        match operation_type {
            DeviceNotificationType::Add | DeviceNotificationType::Remove => {
                let key_index_node = required_child(node, "key-index-list")?;
                let key_index = KeyIndexInfo::try_from_node_ref(key_index_node)?;

                if operation_type == DeviceNotificationType::Remove && key_index.timestamp == 0 {
                    return Err(anyhow!(
                        "timestamp is required to handle device remove notification"
                    ));
                }

                let device_node = required_child(node, "device")?;
                let device = DeviceElement::try_from_node_ref(device_node)?;

                Ok(Self {
                    operation_type,
                    contact_hash: None,
                    devices: vec![device],
                    key_index: Some(key_index),
                })
            }
            DeviceNotificationType::Update => {
                // Per WhatsApp Web: hash attribute is REQUIRED for update
                // Uses attrString (not maybeAttrString) which throws if missing
                let contact_hash = required_attr(node, "hash")?;

                Ok(Self {
                    operation_type,
                    contact_hash: Some(contact_hash),
                    devices: Vec::new(),
                    key_index: None,
                })
            }
        }
    }

    /// Get device IDs as a Vec (convenience method for logging).
    pub fn device_ids(&self) -> Vec<u32> {
        self.devices.iter().map(|d| d.device_id()).collect()
    }
}

/// Parsed device notification stanza.
///
/// Wire format:
/// ```xml
/// <notification from="185169143189667@lid" id="..." t="..." type="devices" lid="...">
///   <remove>
///     <device jid="185169143189667:75@lid"/>
///     <key-index-list ts="1769296600"/>
///   </remove>
/// </notification>
/// ```
///
/// Reference: WhatsApp Web `WAWebHandleDeviceNotification` parser (5Yec01dI04o.js:23125-23183)
///
/// Per WhatsApp Web: Only ONE operation per notification is processed.
/// Priority order: remove > add > update
#[derive(Debug, Clone, Serialize)]
pub struct DeviceNotification {
    /// User JID (from attribute)
    pub from: Jid,
    /// Optional LID user (for LID-PN mapping learning)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lid_user: Option<Jid>,
    /// Stanza ID (for ACK)
    pub stanza_id: String,
    /// Timestamp
    pub timestamp: i64,
    /// The operation (one per notification, priority: remove > add > update)
    pub operation: DeviceOperation,
}

impl DeviceNotification {
    /// Parse from a `<notification type="devices">` NodeRef.
    ///
    /// Per WhatsApp Web: Only ONE operation per notification is processed.
    /// Priority order: remove > add > update
    /// Returns error if no operation is found.
    pub fn try_parse(node: &NodeRef<'_>) -> Result<Self> {
        if node.tag != "notification" {
            return Err(anyhow!("expected <notification>, got <{}>", node.tag));
        }
        if node
            .get_attr("type")
            .is_none_or(|v| v.as_str() != "devices")
        {
            return Err(anyhow!("expected type='devices'"));
        }

        let mut parser = node.attrs();
        let from = parser
            .optional_jid("from")
            .ok_or_else(|| anyhow!("notification missing required 'from' attribute"))?;
        let lid_user = parser.optional_jid("lid");
        let stanza_id = node
            .get_attr("id")
            .map(|v| v.as_str())
            .unwrap_or_default()
            .into_owned();
        let timestamp = match parser.optional_u64("t") {
            Some(t) => i64::try_from(t)
                .map_err(|_| anyhow!("notification timestamp {} exceeds i64::MAX", t))?,
            None => 0,
        };

        // Per WhatsApp Web: Priority order is remove > add > update
        let operation = if let Some(remove_node) = node.get_optional_child("remove") {
            DeviceOperation::try_from_child(remove_node)?
        } else if let Some(add_node) = node.get_optional_child("add") {
            DeviceOperation::try_from_child(add_node)?
        } else if let Some(update_node) = node.get_optional_child("update") {
            DeviceOperation::try_from_child(update_node)?
        } else {
            return Err(anyhow!(
                "device notification missing required operation (add/remove/update)"
            ));
        };

        Ok(Self {
            from,
            lid_user,
            stanza_id,
            timestamp,
            operation,
        })
    }

    /// Get the user string for cache operations.
    #[inline]
    pub fn user(&self) -> &str {
        &self.from.user
    }

    /// Check if this notification provides a LID-PN mapping to learn.
    ///
    /// Returns `Some((lid, pn))` if:
    /// - `lid` attribute is present and is a LID
    /// - `from` attribute is a phone number (not LID)
    ///
    /// Per WhatsApp Web: mappings are learned when both are present.
    pub fn lid_pn_mapping(&self) -> Option<(&str, &str)> {
        let lid = self.lid_user.as_ref()?;
        if !self.from.is_lid() && lid.is_lid() {
            Some((&lid.user, &self.from.user))
        } else {
            None
        }
    }
}

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

    #[test]
    fn test_device_notification_type_as_str() {
        assert_eq!(DeviceNotificationType::Add.as_str(), "add");
        assert_eq!(DeviceNotificationType::Remove.as_str(), "remove");
        assert_eq!(DeviceNotificationType::Update.as_str(), "update");
    }

    #[test]
    fn test_device_notification_type_try_from() {
        assert_eq!(
            DeviceNotificationType::try_from("add").unwrap(),
            DeviceNotificationType::Add
        );
        assert_eq!(
            DeviceNotificationType::try_from("remove").unwrap(),
            DeviceNotificationType::Remove
        );
        assert!(DeviceNotificationType::try_from("invalid").is_err());
    }

    #[test]
    fn test_parse_remove_notification() {
        let node = NodeBuilder::new("notification")
            .attr("type", "devices")
            .attr("from", "185169143189667@lid")
            .attr("id", "511477682")
            .attr("t", "1769296817")
            .children([NodeBuilder::new("remove")
                .children([
                    NodeBuilder::new("device")
                        .attr("jid", "185169143189667:75@lid")
                        .build(),
                    NodeBuilder::new("key-index-list")
                        .attr("ts", "1769296600")
                        .build(),
                ])
                .build()])
            .build();

        let parsed = DeviceNotification::try_parse(&node.as_node_ref()).unwrap();
        assert_eq!(parsed.from.user, "185169143189667");
        assert_eq!(parsed.stanza_id, "511477682");
        assert_eq!(parsed.timestamp, 1769296817);

        let op = &parsed.operation;
        assert_eq!(op.operation_type, DeviceNotificationType::Remove);
        assert_eq!(op.devices.len(), 1);
        assert_eq!(op.devices[0].device_id(), 75);
        assert_eq!(op.key_index.as_ref().unwrap().timestamp, 1769296600);
        assert!(op.key_index.as_ref().unwrap().signed_bytes.is_none());
    }

    #[test]
    fn test_parse_add_notification_with_key_bytes() {
        let node = NodeBuilder::new("notification")
            .attr("type", "devices")
            .attr("from", "15551234567@s.whatsapp.net")
            .attr("lid", "100000000000001@lid")
            .attr("id", "123")
            .attr("t", "1000")
            .children([NodeBuilder::new("add")
                .children([
                    NodeBuilder::new("device")
                        .attr("jid", "15551234567:64@s.whatsapp.net")
                        .attr("key-index", "5")
                        .build(),
                    NodeBuilder::new("key-index-list")
                        .attr("ts", "999")
                        .bytes(vec![0x01, 0x02, 0x03])
                        .build(),
                ])
                .build()])
            .build();

        let parsed = DeviceNotification::try_parse(&node.as_node_ref()).unwrap();

        // Check LID-PN mapping detection
        let (lid, pn) = parsed.lid_pn_mapping().unwrap();
        assert_eq!(lid, "100000000000001");
        assert_eq!(pn, "15551234567");

        let op = &parsed.operation;
        assert_eq!(op.operation_type, DeviceNotificationType::Add);
        assert_eq!(op.devices[0].device_id(), 64);
        assert_eq!(op.devices[0].key_index, Some(5));
        assert_eq!(
            op.key_index.as_ref().unwrap().signed_bytes,
            Some(vec![0x01, 0x02, 0x03])
        );
    }

    #[test]
    fn test_parse_update_notification() {
        let node = NodeBuilder::new("notification")
            .attr("type", "devices")
            .attr("from", "15551234567@s.whatsapp.net")
            .attr("id", "456")
            .attr("t", "2000")
            .children([NodeBuilder::new("update")
                .attr("hash", "contact_hash_value")
                .build()])
            .build();

        let parsed = DeviceNotification::try_parse(&node.as_node_ref()).unwrap();

        let op = &parsed.operation;
        assert_eq!(op.operation_type, DeviceNotificationType::Update);
        assert_eq!(op.contact_hash, Some("contact_hash_value".to_string()));
        assert!(op.devices.is_empty());
    }

    #[test]
    fn test_lid_pn_mapping_not_detected_when_from_is_lid() {
        // When from is a LID, we shouldn't learn a LID->PN mapping
        // (both are LIDs, no phone number to learn)
        let node = NodeBuilder::new("notification")
            .attr("type", "devices")
            .attr("from", "185169143189667@lid")
            .attr("lid", "185169143189667@lid")
            .attr("id", "123")
            .attr("t", "1000")
            .children([NodeBuilder::new("update").attr("hash", "test_hash").build()])
            .build();

        let parsed = DeviceNotification::try_parse(&node.as_node_ref()).unwrap();
        // No mapping should be detected when from is also a LID
        assert!(parsed.lid_pn_mapping().is_none());
    }

    #[test]
    fn test_missing_key_index_list_fails() {
        // Per WhatsApp Web: key-index-list is required for add/remove
        let node = NodeBuilder::new("notification")
            .attr("type", "devices")
            .attr("from", "15551234567@s.whatsapp.net")
            .attr("id", "123")
            .attr("t", "1000")
            .children([NodeBuilder::new("add")
                .children([NodeBuilder::new("device")
                    .attr("jid", "15551234567:64@s.whatsapp.net")
                    .build()])
                .build()])
            .build();

        let result = DeviceNotification::try_parse(&node.as_node_ref());
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("key-index-list"));
    }

    #[test]
    fn test_remove_without_timestamp_fails() {
        // Per WhatsApp Web: timestamp is required for remove
        let node = NodeBuilder::new("notification")
            .attr("type", "devices")
            .attr("from", "15551234567@s.whatsapp.net")
            .attr("id", "123")
            .attr("t", "1000")
            .children([NodeBuilder::new("remove")
                .children([
                    NodeBuilder::new("device")
                        .attr("jid", "15551234567:64@s.whatsapp.net")
                        .build(),
                    NodeBuilder::new("key-index-list")
                        .attr("ts", "0") // Zero timestamp should fail for remove
                        .build(),
                ])
                .build()])
            .build();

        let result = DeviceNotification::try_parse(&node.as_node_ref());
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("timestamp is required")
        );
    }

    #[test]
    fn test_device_id_mismatch_fails() {
        // Per WhatsApp Web: device ID must match between jid and lid attributes
        let node = NodeBuilder::new("notification")
            .attr("type", "devices")
            .attr("from", "15551234567@s.whatsapp.net")
            .attr("id", "123")
            .attr("t", "1000")
            .children([NodeBuilder::new("add")
                .children([
                    NodeBuilder::new("device")
                        .attr("jid", "15551234567:64@s.whatsapp.net")
                        .attr("lid", "100000000000001:99@lid") // Different device ID
                        .build(),
                    NodeBuilder::new("key-index-list").attr("ts", "999").build(),
                ])
                .build()])
            .build();

        let result = DeviceNotification::try_parse(&node.as_node_ref());
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("device id mismatch")
        );
    }

    #[test]
    fn test_device_with_matching_lid() {
        // Device IDs match - should succeed
        let node = NodeBuilder::new("notification")
            .attr("type", "devices")
            .attr("from", "15551234567@s.whatsapp.net")
            .attr("id", "123")
            .attr("t", "1000")
            .children([NodeBuilder::new("add")
                .children([
                    NodeBuilder::new("device")
                        .attr("jid", "15551234567:64@s.whatsapp.net")
                        .attr("lid", "100000000000001:64@lid") // Same device ID
                        .build(),
                    NodeBuilder::new("key-index-list").attr("ts", "999").build(),
                ])
                .build()])
            .build();

        let parsed = DeviceNotification::try_parse(&node.as_node_ref()).unwrap();
        assert_eq!(parsed.operation.devices[0].device_id(), 64);
        assert!(parsed.operation.devices[0].lid.is_some());
    }

    #[test]
    fn test_no_operation_fails() {
        // Per WhatsApp Web: at least one operation (add/remove/update) is required
        let node = NodeBuilder::new("notification")
            .attr("type", "devices")
            .attr("from", "15551234567@s.whatsapp.net")
            .attr("id", "123")
            .attr("t", "1000")
            .build(); // No operation children

        let result = DeviceNotification::try_parse(&node.as_node_ref());
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("missing required operation")
        );
    }

    #[test]
    fn test_remove_priority_over_add() {
        // Per WhatsApp Web: priority is remove > add > update
        // If both remove and add are present, remove should be processed
        let node = NodeBuilder::new("notification")
            .attr("type", "devices")
            .attr("from", "15551234567@s.whatsapp.net")
            .attr("id", "123")
            .attr("t", "1000")
            .children([
                NodeBuilder::new("add")
                    .children([
                        NodeBuilder::new("device")
                            .attr("jid", "15551234567:64@s.whatsapp.net")
                            .build(),
                        NodeBuilder::new("key-index-list").attr("ts", "999").build(),
                    ])
                    .build(),
                NodeBuilder::new("remove")
                    .children([
                        NodeBuilder::new("device")
                            .attr("jid", "15551234567:75@s.whatsapp.net")
                            .build(),
                        NodeBuilder::new("key-index-list").attr("ts", "888").build(),
                    ])
                    .build(),
            ])
            .build();

        let parsed = DeviceNotification::try_parse(&node.as_node_ref()).unwrap();
        // Should process remove, not add
        assert_eq!(
            parsed.operation.operation_type,
            DeviceNotificationType::Remove
        );
        assert_eq!(parsed.operation.devices[0].device_id(), 75);
    }

    #[test]
    fn test_update_without_hash_fails() {
        // Per WhatsApp Web: hash attribute is required for update
        let node = NodeBuilder::new("notification")
            .attr("type", "devices")
            .attr("from", "15551234567@s.whatsapp.net")
            .attr("id", "123")
            .attr("t", "1000")
            .children([NodeBuilder::new("update").build()]) // Missing hash attribute
            .build();

        let result = DeviceNotification::try_parse(&node.as_node_ref());
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("hash"));
    }
}