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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
//! Pair code authentication for phone number linking.
//!
//! This module implements the alternative device linking protocol used when
//! users enter an 8-character code on their phone instead of scanning a QR code.
//!
//! ## Protocol Overview
//!
//! 1. **Stage 1 (companion_hello)**: Client generates a code and sends encrypted
//!    ephemeral public key to server. Server returns a pairing ref.
//!
//! 2. **Stage 2 (companion_finish)**: When user enters code on phone, server
//!    sends notification with primary's ephemeral key. Client performs DH and
//!    sends encrypted key bundle.
//!
//! ## Cryptography
//!
//! - Code: 5 random bytes → Crockford Base32 → 8 characters
//! - Key derivation: PBKDF2-SHA256 with 131,072 iterations
//! - Ephemeral encryption: AES-256-CTR
//! - Bundle encryption: AES-256-GCM after HKDF key derivation

use crate::companion_reg::{
    CompanionWebClientType, companion_platform_display, companion_platform_display_raw,
    companion_web_client_type_for_props,
};
use crate::libsignal::crypto::{CryptoProviderError, aes_256_gcm_encrypt};
use crate::libsignal::protocol::{CurveError, KeyPair, PublicKey};
use aes::cipher::{KeyIvInit, StreamCipher};
use ctr::Ctr128BE;
use hmac::{Hmac, Mac};
use rand::RngExt;
use sha2::Sha256;
use wacore_binary::SERVER_JID;
use wacore_binary::builder::NodeBuilder;
use wacore_binary::{Node, NodeContentRef, NodeRef};
use waproto::whatsapp as wa;

// Type aliases
type Aes256Ctr = Ctr128BE<aes::Aes256>;

/// PBKDF2 iterations for pair code key derivation.
/// Matches WhatsApp Web's implementation (2^17 = 131,072).
const PAIR_CODE_PBKDF2_ITERATIONS: u32 = 131_072;

/// Salt size for PBKDF2 key derivation.
const PAIR_CODE_SALT_SIZE: usize = 32;

/// IV size for AES-CTR encryption.
const PAIR_CODE_IV_SIZE: usize = 16;

/// Crockford Base32 alphabet used for pair codes.
/// Excludes 0, I, O, U to prevent visual confusion.
const CROCKFORD_ALPHABET: &[u8; 32] = b"123456789ABCDEFGHJKLMNPQRSTVWXYZ";

/// RFC 2898 PBKDF2 using HMAC-SHA256. Replaces the `pbkdf2` crate dependency
/// which hasn't released a digest 0.11-compatible stable version yet.
fn pbkdf2_hmac_sha256(password: &[u8], salt: &[u8], rounds: u32, output: &mut [u8]) {
    use hmac::KeyInit as _;
    // Derive the HMAC key schedule (ipad/opad) once and clone that keyed state
    // per use. `new_from_slice` re-absorbs the padded key (2 SHA-256 blocks)
    // on every call, which is wasted work repeated across all PBKDF2 rounds.
    let keyed = Hmac::<Sha256>::new_from_slice(password).expect("HMAC accepts any key length");
    for (i, chunk) in output.chunks_mut(32).enumerate() {
        let mut u = {
            let mut mac = keyed.clone();
            mac.update(salt);
            mac.update(&((i as u32) + 1).to_be_bytes());
            let result: [u8; 32] = mac.finalize().into_bytes().into();
            result
        };
        chunk.copy_from_slice(&u[..chunk.len()]);
        for _ in 1..rounds {
            let mut mac = keyed.clone();
            mac.update(&u);
            u = mac.finalize().into_bytes().into();
            for (a, b) in chunk.iter_mut().zip(u.iter()) {
                *a ^= b;
            }
        }
    }
}

/// Validity duration for pair codes (approximately).
const PAIR_CODE_VALIDITY_SECS: u64 = 180;

/// Max `primary_hello` notifications processed per code before the flow is
/// abandoned. Matches WA Web `DeviceLinkingApi` (`T = 3`, `MaxPrimaryHelloError`).
const PAIR_CODE_MAX_PRIMARY_HELLO_ATTEMPTS: u32 = 3;

/// How long a `companion_finish` may go unanswered before the code is written
/// off. WA Web arms exactly this on `primary_hello_received`
/// (`Link/DevicePhoneNumberCodeScreen.react.js`, `1 * MINUTE_MILLISECONDS`) and
/// regenerates the code when it fires: the primary having read the code is no
/// guarantee it could open the key bundle, and a primary that could not simply
/// goes quiet — no error ever reaches the companion.
const PAIR_CODE_PRIMARY_HELLO_PAIR_SUCCESS_TIMEOUT_SECS: u64 = 60;

/// How long the `companion_finish` IQ waits for its own answer.
///
/// Deliberately inside
/// [`PAIR_CODE_PRIMARY_HELLO_PAIR_SUCCESS_TIMEOUT_SECS`], which is the whole
/// budget stage 2 has: a refusal that only landed after that window would be
/// reported against a flow already written off, so the request has to be able
/// to fail while the flow it belongs to is still the current one. The answer
/// itself is the server acknowledging the bundle, not the primary opening it,
/// so it arrives in one round trip or not at all.
const PAIR_CODE_COMPANION_FINISH_IQ_TIMEOUT_SECS: u64 = 30;
const _: () = assert!(
    PAIR_CODE_COMPANION_FINISH_IQ_TIMEOUT_SECS < PAIR_CODE_PRIMARY_HELLO_PAIR_SUCCESS_TIMEOUT_SECS,
    "a companion_finish refusal has to land while the flow it belongs to is still the current one"
);

fn build_id_and_display(
    id: CompanionWebClientType,
    props: &wa::DeviceProps,
) -> (CompanionWebClientType, String) {
    let os = props.os.as_deref().unwrap_or("");
    (id, companion_platform_display(id, os))
}

/// `(companion_platform_id, companion_platform_display)` per WA Web's
/// `Alt/DeviceLinkingIq.js`. Display always Browser-valid (see
/// `companion_platform_display`).
pub fn derive_companion_platform(props: &wa::DeviceProps) -> (CompanionWebClientType, String) {
    build_id_and_display(companion_web_client_type_for_props(props), props)
}

/// Honours `PairCodeOptions::platform_id` (browser) and `display_os` (OS)
/// overrides. By default the OS is canonicalized from `DeviceProps::os`; a
/// non-empty `display_os` is sent verbatim instead (advanced — see the field).
pub fn resolve_companion_platform(
    options: &PairCodeOptions,
    props: &wa::DeviceProps,
) -> (CompanionWebClientType, String) {
    let id = options
        .platform_id
        .unwrap_or_else(|| companion_web_client_type_for_props(props));
    let display = match options.display_os.as_deref().map(str::trim) {
        Some(raw) if !raw.is_empty() => companion_platform_display_raw(id, raw),
        // None, or an all-whitespace override, falls back to the safe coercion.
        _ => build_id_and_display(id, props).1,
    };
    (id, display)
}

/// Options for pair code authentication.
#[derive(Debug, Clone)]
pub struct PairCodeOptions {
    /// Phone number with country code, no leading zeros or special chars (e.g., "15551234567").
    pub phone_number: String,
    /// Whether to show push notification on phone (default `true`, matching WA Web).
    pub show_push_notification: bool,
    /// Custom pairing code (8 chars from Crockford alphabet, or None for random).
    pub custom_code: Option<String>,
    /// `None` auto-derives from `Device.device_props.platform_type`.
    pub platform_id: Option<CompanionWebClientType>,
    /// Advanced OS override for `companion_platform_display`. `None` (default)
    /// canonicalizes `DeviceProps::os` to a small server-safe set (branding →
    /// `Linux`). `Some(os)` sends `os` **verbatim**, bypassing that coercion — use
    /// it to keep a real OS name the server accepts but our canonical set drops
    /// (e.g. `"Ubuntu"`, `"Fedora"`). At your own risk: the server rejects a
    /// non-OS string with `bad-request`. An all-whitespace value is ignored.
    pub display_os: Option<String>,
}

impl Default for PairCodeOptions {
    fn default() -> Self {
        Self {
            phone_number: String::new(),
            show_push_notification: true,
            custom_code: None,
            platform_id: None,
            display_os: None,
        }
    }
}

/// Identity of one `pair_with_code` request, minted per call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PairCodeClaim(u64);

impl PairCodeClaim {
    /// A value no live claim shares. Process-wide rather than per-client: a
    /// counter is cheaper than the coordination that scoping it would need, and
    /// only equality within one client is ever asked of it.
    pub fn next() -> Self {
        use core::sync::atomic::Ordering;
        static NEXT: portable_atomic::AtomicU64 = portable_atomic::AtomicU64::new(0);
        Self(NEXT.fetch_add(1, Ordering::Relaxed))
    }
}

/// State machine for pair code authentication flow.
#[derive(Default)]
pub enum PairCodeState {
    /// Initial state - no pair code request in progress.
    #[default]
    Idle,
    /// `companion_hello` is in flight and the slot is already spoken for.
    ///
    /// Checking for a live flow and then releasing the lock across the stage-1
    /// round trip would let two concurrent callers both mint a code, and the
    /// second response would overwrite the first flow's ephemeral keypair —
    /// stranding the code that was returned first. WA Web tracks the same
    /// window as a distinct stage (`AfterSendCompanionHello` follows
    /// `Initialized` before the request resolves).
    RequestingCode {
        /// Stamped before `companion_hello`, and carried into
        /// [`Self::WaitingForPhoneConfirmation`] unchanged.
        code_generation_ts: i64,
        /// Identifies *this* request. The stamp cannot: cancel a request and
        /// start its replacement inside the same second and both carry the same
        /// number, so the first one's late response would install its code over
        /// the replacement's claim, and its failure path would release it.
        claim: PairCodeClaim,
    },
    /// Stage 1 complete - waiting for phone to confirm code entry.
    WaitingForPhoneConfirmation {
        /// Reference returned by server in stage 1.
        pairing_ref: Vec<u8>,
        /// Phone number JID (without @s.whatsapp.net).
        phone_jid: String,
        /// The 8-character pair code (needed to decrypt primary's ephemeral key).
        pair_code: String,
        /// Ephemeral keypair generated for this session.
        ephemeral_keypair: Box<KeyPair>,
        /// Unix seconds when the code was generated. Enforces the ~180s validity
        /// window: a `primary_hello` arriving later is rejected (WA Web `OldCodeError`).
        code_generation_ts: i64,
        /// Count of `primary_hello` notifications processed for this code. WA Web
        /// (`DeviceLinkingApi`) caps this at 3 per code (`MaxPrimaryHelloError`);
        /// the primary may retry, re-deriving fresh key material each time.
        primary_hello_attempt_count: u32,
    },
    /// Pairing completed (success or failure).
    Completed,
}

impl PairCodeState {
    /// The window left on a code someone may still be reading, or `None` when
    /// there is nothing left to strand.
    ///
    /// A second `companion_hello` mints a new code *and* a new ephemeral
    /// keypair, but the server keeps routing `primary_hello` by phone number —
    /// it never sees the code itself. So the holder of the superseded code
    /// still reaches stage 2, and gets a key bundle derived from key material
    /// their code cannot open: the primary fails to link with no error the
    /// companion can see. WA Web forbids the overlap outright, guarding
    /// `startAltLinkingFlow` with `invariant(stage === Initialized)`
    /// (`Alt/DeviceLinkingApi.js`) so a replacement must follow an explicit
    /// `initializeAltDeviceLinking()`.
    ///
    /// The boundary matches [`PairCodeUtils::code_validity`] as applied in
    /// stage 2, which rejects only `age > validity`.
    /// Whether a `companion_finish` is out and its `pair-success` still due.
    ///
    /// Distinct from [`Self::live_flow_remaining`], which tracks how long the
    /// *code* stays enterable. A `primary_hello` accepted near the end of that
    /// window leaves the link pending for up to
    /// [`PairCodeUtils::primary_hello_pair_success_timeout`] longer, and the adv
    /// secret its HMAC is computed over is already derived — so anything that
    /// would re-mint that secret has to wait for this, not for the code.
    pub fn awaiting_pair_success(&self) -> bool {
        matches!(
            self,
            Self::WaitingForPhoneConfirmation {
                primary_hello_attempt_count: 1..,
                ..
            }
        )
    }

    /// Whether anything would be stranded by starting a new flow now.
    ///
    /// The union of the two clocks: the code's own validity window, and the
    /// link that outlives it once the phone has answered.
    pub fn is_outstanding(&self, now: i64) -> bool {
        self.live_flow_remaining(now).is_some() || self.awaiting_pair_success()
    }

    pub fn live_flow_remaining(&self, now: i64) -> Option<std::time::Duration> {
        let (Self::RequestingCode {
            code_generation_ts, ..
        }
        | Self::WaitingForPhoneConfirmation {
            code_generation_ts, ..
        }) = self
        else {
            return None;
        };
        let validity = PairCodeUtils::code_validity();
        // A backwards clock jump reads as "no time has passed", never as an
        // expiry that would let the overlap through unreported.
        let age = now.saturating_sub(*code_generation_ts).max(0) as u64;
        (age <= validity.as_secs()).then(|| validity - std::time::Duration::from_secs(age))
    }
}

impl std::fmt::Debug for PairCodeState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Idle => write!(f, "Idle"),
            Self::RequestingCode { .. } => write!(f, "RequestingCode"),
            Self::WaitingForPhoneConfirmation { phone_jid, .. } => f
                .debug_struct("WaitingForPhoneConfirmation")
                .field("phone_jid", phone_jid)
                .finish_non_exhaustive(),
            Self::Completed => write!(f, "Completed"),
        }
    }
}

/// Core pair code cryptographic utilities.
///
/// All operations are platform-independent and can be used in `no_std` environments.
pub struct PairCodeUtils;

impl PairCodeUtils {
    /// Generates a random 8-character pair code using Crockford Base32.
    ///
    /// The code consists of characters from `123456789ABCDEFGHJKLMNPQRSTVWXYZ`,
    /// which excludes 0, I, O, and U to prevent visual confusion.
    pub fn generate_code() -> String {
        let mut bytes = [0u8; 5];
        rand::make_rng::<rand::rngs::StdRng>().fill(&mut bytes);
        Self::encode_crockford(&bytes)
    }

    /// Validates a custom pair code.
    ///
    /// Returns `true` if the code is exactly 8 characters and all characters
    /// are from the Crockford Base32 alphabet.
    pub fn validate_code(code: &str) -> bool {
        code.len() == 8
            && code
                .bytes()
                .all(|b| CROCKFORD_ALPHABET.contains(&b.to_ascii_uppercase()))
    }

    /// Encodes 5 bytes to an 8-character Crockford Base32 string.
    ///
    /// 5 bytes = 40 bits = 8 × 5-bit groups, each mapped to the alphabet.
    /// `pub(crate)` so the Shortcake passkey flow reuses the exact same encoder
    /// for its verification code (see `crate::shortcake`).
    pub(crate) fn encode_crockford(bytes: &[u8; 5]) -> String {
        // Combine 5 bytes into a 40-bit value
        let mut accumulator: u64 = 0;
        for &byte in bytes {
            accumulator = (accumulator << 8) | u64::from(byte);
        }

        // Extract 8 × 5-bit groups
        let mut result = String::with_capacity(8);
        for i in (0..8).rev() {
            let index = ((accumulator >> (i * 5)) & 0x1F) as usize;
            result.push(CROCKFORD_ALPHABET[index] as char);
        }
        result
    }

    /// Derives an encryption key from a pair code using PBKDF2-SHA256.
    ///
    /// This is a blocking operation (~100ms on modern hardware due to 131,072 iterations).
    /// Consider wrapping in `spawn_blocking` for async contexts.
    pub fn derive_key(code: &str, salt: &[u8; PAIR_CODE_SALT_SIZE]) -> [u8; 32] {
        let mut key = [0u8; 32];
        pbkdf2_hmac_sha256(code.as_bytes(), salt, PAIR_CODE_PBKDF2_ITERATIONS, &mut key);
        key
    }

    /// Encrypts the companion ephemeral public key for stage 1.
    ///
    /// Returns the wrapped ephemeral data: `salt (32) || iv (16) || ciphertext (32)` = 80 bytes.
    pub fn encrypt_ephemeral_pub(ephemeral_pub: &[u8; 32], code: &str) -> [u8; 80] {
        // Generate random salt and IV
        let mut salt = [0u8; PAIR_CODE_SALT_SIZE];
        let mut iv = [0u8; PAIR_CODE_IV_SIZE];
        rand::make_rng::<rand::rngs::StdRng>().fill(&mut salt);
        rand::make_rng::<rand::rngs::StdRng>().fill(&mut iv);

        // Derive key from code and encrypt with AES-256-CTR
        let key = Self::derive_key(code, &salt);
        let mut cipher = Aes256Ctr::new(&key.into(), &iv.into());
        let mut ciphertext = *ephemeral_pub;
        cipher.apply_keystream(&mut ciphertext);

        // Concatenate: salt (32) || iv (16) || ciphertext (32) = 80 bytes
        let mut result = [0u8; 80];
        result[..32].copy_from_slice(&salt);
        result[32..48].copy_from_slice(&iv);
        result[48..80].copy_from_slice(&ciphertext);

        result
    }

    /// Decrypts the primary device's ephemeral public key received in stage 2.
    ///
    /// The wrapped data format is: `salt (32) || iv (16) || ciphertext (32)` = 80 bytes.
    ///
    /// # Important
    ///
    /// This function extracts the salt from the wrapped data and derives a fresh
    /// encryption key using PBKDF2 with the pair code. This is necessary because
    /// the primary device encrypts with their own random salt.
    pub fn decrypt_primary_ephemeral_pub(
        wrapped: &[u8],
        pair_code: &str,
    ) -> Result<[u8; 32], PairCodeError> {
        if wrapped.len() != 80 {
            return Err(PairCodeError::InvalidWrappedData {
                expected: 80,
                got: wrapped.len(),
            });
        }

        // Extract salt, iv, and ciphertext (length validated above guarantees these succeed)
        let salt: [u8; PAIR_CODE_SALT_SIZE] = wrapped[0..32]
            .try_into()
            .expect("salt slice is exactly 32 bytes");
        let iv: [u8; PAIR_CODE_IV_SIZE] = wrapped[32..48]
            .try_into()
            .expect("iv slice is exactly 16 bytes");
        let mut plaintext: [u8; 32] = wrapped[48..80]
            .try_into()
            .expect("ciphertext slice is exactly 32 bytes");

        // Derive key using the PRIMARY's salt
        let derived_key = Self::derive_key(pair_code, &salt);

        // Decrypt with AES-256-CTR
        let mut cipher = Aes256Ctr::new((&derived_key).into(), &iv.into());
        cipher.apply_keystream(&mut plaintext);

        Ok(plaintext)
    }

    /// Builds the stage 1 (companion_hello) IQ node.
    ///
    /// `platform_id` and `platform_display` are the resolved strings — callers
    /// typically obtain them through [`resolve_companion_platform`] so that
    /// `Device.device_props` is the single source of truth.
    pub fn build_companion_hello_iq(
        phone_number: &str,
        noise_static_pub: &[u8; 32],
        wrapped_ephemeral: &[u8; 80],
        platform_id: &str,
        platform_display: &str,
        show_push_notification: bool,
        req_id: String,
    ) -> Node {
        let link_code_reg = NodeBuilder::new("link_code_companion_reg")
            .attrs([
                ("jid", format!("{}@s.whatsapp.net", phone_number)),
                ("stage", "companion_hello".to_string()),
                (
                    "should_show_push_notification",
                    show_push_notification.to_string(),
                ),
            ])
            .children([
                NodeBuilder::new("link_code_pairing_wrapped_companion_ephemeral_pub")
                    .bytes(wrapped_ephemeral.to_vec())
                    .build(),
                NodeBuilder::new("companion_server_auth_key_pub")
                    .bytes(noise_static_pub.to_vec())
                    .build(),
                NodeBuilder::new("companion_platform_id")
                    .bytes(platform_id.as_bytes().to_vec())
                    .build(),
                NodeBuilder::new("companion_platform_display")
                    .bytes(platform_display.as_bytes().to_vec())
                    .build(),
                // 0x00, not ASCII '0' (0x30): matches WA Web `new Uint8Array(1)`
                // (`Alt/DeviceLinkingIq.js`) / whatsmeow `[]byte{0}`.
                NodeBuilder::new("link_code_pairing_nonce")
                    .bytes(vec![0u8])
                    .build(),
            ])
            .build();

        NodeBuilder::new("iq")
            .attrs([
                ("xmlns", "md".to_string()),
                ("type", "set".to_string()),
                ("to", SERVER_JID.to_string()),
                ("id", req_id),
            ])
            .children([link_code_reg])
            .build()
    }

    /// Parses the stage 1 response to extract the pairing ref.
    pub fn parse_companion_hello_response(node: &NodeRef<'_>) -> Option<Vec<u8>> {
        node.get_optional_child_by_tag(&["link_code_companion_reg"])
            .and_then(|n| n.get_optional_child_by_tag(&["link_code_pairing_ref"]))
            .and_then(|n| match n.content.as_ref() {
                Some(NodeContentRef::Bytes(b)) => Some(b.to_vec()),
                _ => None,
            })
    }

    /// Builds the stage 2 (companion_finish) IQ node.
    pub fn build_companion_finish_iq(
        phone_number: &str,
        wrapped_key_bundle: Vec<u8>,
        identity_pub: &[u8; 32],
        pairing_ref: &[u8],
        req_id: String,
    ) -> Node {
        let link_code_reg = NodeBuilder::new("link_code_companion_reg")
            .attrs([
                ("jid", format!("{}@s.whatsapp.net", phone_number)),
                ("stage", "companion_finish".to_string()),
            ])
            .children([
                NodeBuilder::new("link_code_pairing_wrapped_key_bundle")
                    .bytes(wrapped_key_bundle)
                    .build(),
                NodeBuilder::new("companion_identity_public")
                    .bytes(identity_pub.to_vec())
                    .build(),
                NodeBuilder::new("link_code_pairing_ref")
                    .bytes(pairing_ref.to_vec())
                    .build(),
            ])
            .build();

        NodeBuilder::new("iq")
            .attrs([
                ("xmlns", "md".to_string()),
                ("type", "set".to_string()),
                ("to", SERVER_JID.to_string()),
                ("id", req_id),
            ])
            .children([link_code_reg])
            .build()
    }

    /// Prepares the encrypted key bundle for stage 2.
    ///
    /// This performs:
    /// 1. DH key exchange with primary's ephemeral public key
    /// 2. DH key exchange with primary's identity public key
    /// 3. HKDF to derive bundle encryption key
    /// 4. AES-GCM encryption of the key bundle
    ///
    /// Returns the wrapped bundle and a new ADV secret derived from the DH exchanges.
    /// The ADV secret should be stored to enable HMAC verification of pair-success.
    pub fn prepare_key_bundle(
        ephemeral_keypair: &KeyPair,
        primary_ephemeral_pub: &[u8; 32],
        primary_identity_pub: &[u8; 32],
        identity_key: &KeyPair,
    ) -> Result<(Vec<u8>, [u8; 32]), PairCodeError> {
        let primary_eph_pub = PublicKey::from_djb_public_key_bytes(primary_ephemeral_pub)
            .map_err(PairCodeError::InvalidPrimaryEphemeralKey)?;

        let primary_id_pub = PublicKey::from_djb_public_key_bytes(primary_identity_pub)
            .map_err(PairCodeError::InvalidPrimaryIdentityKey)?;

        let ephemeral_shared = ephemeral_keypair
            .private_key
            .calculate_agreement(&primary_eph_pub)
            .map_err(PairCodeError::EphemeralKeyAgreement)?;

        let identity_shared = identity_key
            .private_key
            .calculate_agreement(&primary_id_pub)
            .map_err(PairCodeError::IdentityKeyAgreement)?;

        // Generate random bytes for ADV secret derivation
        let mut random_bytes = [0u8; 32];
        rand::make_rng::<rand::rngs::StdRng>().fill(&mut random_bytes);

        // Derive ADV secret using HKDF
        // Combined secret = ephemeral_shared + identity_shared + random_bytes
        let mut combined_secret = Vec::with_capacity(96);
        combined_secret.extend_from_slice(&ephemeral_shared);
        combined_secret.extend_from_slice(&identity_shared);
        combined_secret.extend_from_slice(&random_bytes);

        let mut new_adv_secret = [0u8; 32];
        crate::crypto::hkdf_sha256_into(&combined_secret, None, b"adv_secret", &mut new_adv_secret)
            .map_err(|_| PairCodeError::AdvSecretKeyDerivation)?;

        // Prepare bundle: companion_identity_pub (32) + primary_identity_pub (32) + random_bytes (32) = 96 bytes
        let mut bundle = Vec::with_capacity(96);
        bundle.extend_from_slice(identity_key.public_key.public_key_bytes());
        bundle.extend_from_slice(primary_identity_pub);
        bundle.extend_from_slice(&random_bytes);

        // Generate salt for HKDF
        let mut key_bundle_salt = [0u8; 32];
        rand::make_rng::<rand::rngs::StdRng>().fill(&mut key_bundle_salt);

        // Derive bundle encryption key using HKDF
        // HKDF(IKM=ephemeral_shared, salt=random_salt, info="link_code_pairing_key_bundle_encryption_key")
        let mut enc_key = [0u8; 32];
        crate::crypto::hkdf_sha256_into(
            &ephemeral_shared,
            Some(&key_bundle_salt),
            b"link_code_pairing_key_bundle_encryption_key",
            &mut enc_key,
        )
        .map_err(|_| PairCodeError::BundleKeyDerivation)?;

        // Generate random IV for AES-GCM (12 bytes)
        let mut iv = [0u8; 12];
        rand::make_rng::<rand::rngs::StdRng>().fill(&mut iv);

        // Wrapped bundle = salt (32) + iv (12) + encrypted_bundle (96 + 16 = 112)
        let mut wrapped_bundle = Vec::with_capacity(32 + 12 + bundle.len() + 16);
        wrapped_bundle.extend_from_slice(&key_bundle_salt);
        wrapped_bundle.extend_from_slice(&iv);
        aes_256_gcm_encrypt(&enc_key, &iv, b"", &bundle, &mut wrapped_bundle)
            .map_err(PairCodeError::BundleAead)?;

        Ok((wrapped_bundle, new_adv_secret))
    }

    /// Returns the pair code validity duration.
    pub fn code_validity() -> std::time::Duration {
        std::time::Duration::from_secs(PAIR_CODE_VALIDITY_SECS)
    }

    /// Max number of `primary_hello` notifications processed per code (WA Web `T`).
    pub fn max_primary_hello_attempts() -> u32 {
        PAIR_CODE_MAX_PRIMARY_HELLO_ATTEMPTS
    }

    /// How long `companion_finish` may go unanswered before the code is written
    /// off — WA Web's one-minute `primary_hello_expire` timer.
    pub fn primary_hello_pair_success_timeout() -> std::time::Duration {
        std::time::Duration::from_secs(PAIR_CODE_PRIMARY_HELLO_PAIR_SUCCESS_TIMEOUT_SECS)
    }

    /// How long the `companion_finish` IQ waits for its answer.
    pub fn companion_finish_iq_timeout() -> std::time::Duration {
        std::time::Duration::from_secs(PAIR_CODE_COMPANION_FINISH_IQ_TIMEOUT_SECS)
    }
}

/// How the server refused a pair-code request, as a matchable status.
///
/// The five named variants are the complete set WA Web's own response parser
/// accepts (`WASmaxInMdIqMixinErrors.parseIqMixinErrors`, reached from
/// `WASmaxInMdCompanionHelloResponseError`); anything else makes its RPC throw
/// "unknown error". They exist so a consumer can branch on the refusal instead
/// of matching the formatted message, which is not a stable surface.
///
/// Both stages report through this, though they were read off `companion_hello`
/// and the `companion_finish` parser is narrower — `WASmaxInMdCompanionFinishErrors`
/// admits only `bad-request` and `internal-server-error`, and WA Web shows its
/// generic failure for anything else. A code outside that pair is still
/// classified here rather than discarded: what a consumer does about a refusal
/// follows from the code, which is one namespace across both requests, and
/// answering "nothing was refused" to a refusal we can read would be worse than
/// naming it.
///
/// The numbers are the `code` attribute, and each is the enum's whole wire form
/// — [`code()`](Self::code) is what `Serialize` emits and what `From<i32>` reads
/// back. WA Web pairs each code with a literal `text`
/// (`429`/`rate-overlimit`, `452`/`feature-not-available`, …) and rejects a
/// response whose two disagree, so construct these through
/// [`from_server`](Self::from_server) rather than from a code alone: it is the
/// only constructor that sees both attributes, and the only one that can decline
/// to classify.
///
/// WA Web branches on exactly two of them (`DevicePhoneNumberCodeScreen`, on
/// `CompanionHelloError.type.name`): [`RateOverlimit`](Self::RateOverlimit)
/// becomes "too many attempts, try again later" and
/// [`FeatureNotAvailable`](Self::FeatureNotAvailable) becomes "not available to
/// you yet, link with QR code instead". The rest share a generic "try again or
/// link with the QR code". In every case it resets the linking flow and waits
/// for the person to act — it never retries on its own, and never reads the
/// `backoff` hint, so treat that value as the server's advice rather than a
/// schedule WA Web is known to follow.
#[derive(Debug, Clone, Copy, PartialEq, Eq, crate::WireEnum)]
#[wire(kind = "int")]
pub enum PairCodeRejection {
    /// The request was malformed — **or** throttled for this phone number: the
    /// server reuses `bad-request` for its per-number pair-code limit rather
    /// than answering `rate-overlimit`. So this is not reliably a permanent
    /// failure; see [`PairCodeRejection::is_throttled`].
    #[wire = 400]
    BadRequest,
    #[wire = 403]
    Forbidden,
    /// The connection is asking for codes too fast. The server states the rate
    /// is too high; the only correct response is to slow down.
    #[wire = 429]
    RateOverlimit,
    /// Phone-number linking is not enabled for this account. Retrying will not
    /// change that — WA Web sends the user to the QR code instead.
    #[wire = 452]
    FeatureNotAvailable,
    #[wire = 500]
    InternalServerError,
    /// A `code` outside the set WA Web accepts. Its own RPC would raise
    /// "unknown error" here; we keep the number so a consumer can log it and a
    /// server-side addition is visible rather than silently reshaped.
    #[wire_fallback]
    Unknown(i32),
}

impl PairCodeRejection {
    /// Whether this refusal is the server rate-limiting the request.
    ///
    /// True for [`RateOverlimit`](Self::RateOverlimit) and
    /// [`BadRequest`](Self::BadRequest), because the server throttles pair-code
    /// requests per phone number under `bad-request` instead of
    /// `rate-overlimit`. That makes the predicate deliberately wider than the
    /// literal 429: a `bad-request` may equally be genuinely invalid content,
    /// and the two are indistinguishable on the wire. Treat a true here as
    /// "back off, then retry at most a bounded number of times" — not as proof
    /// the request would ever succeed.
    pub fn is_throttled(self) -> bool {
        matches!(self, Self::RateOverlimit | Self::BadRequest)
    }

    /// The `text` WA Web pairs with this code; `None` for
    /// [`Unknown`](Self::Unknown), which has no expected pairing.
    pub fn text(self) -> Option<&'static str> {
        Some(match self {
            Self::BadRequest => "bad-request",
            Self::Forbidden => "forbidden",
            Self::RateOverlimit => "rate-overlimit",
            Self::FeatureNotAvailable => "feature-not-available",
            Self::InternalServerError => "internal-server-error",
            Self::Unknown(_) => return None,
        })
    }

    /// Classify a server `<error>` from both of its attributes, or `None` when
    /// the two disagree and no classification is honest.
    ///
    /// WA Web asserts the pair (`literal(attrInt, …, "code", 429)` beside
    /// `literal(attrString, …, "text", "rate-overlimit")`) and drops to its
    /// generic error path when they disagree, so a changed pairing must not keep
    /// reading as the named arm.
    ///
    /// `None` rather than `Unknown(code)` for that case, because `Unknown` could
    /// not carry it: the wire form of this enum **is** `code()`, so
    /// `Unknown(429)` serializes to `429` and rehydrates as
    /// [`RateOverlimit`](Self::RateOverlimit) — a consumer that persisted or
    /// forwarded the value would get the demotion silently undone and apply
    /// throttling anyway. There is no in-band value that both records the code
    /// and refuses to alias the arm it came from. The code is not lost: the
    /// caller still has the error's own rendering, which names it.
    ///
    /// An **absent** `text` is not a contradiction, and the code alone decides.
    /// Deliberately laxer than WA Web, which would reject it: refusing to
    /// classify a bare `429` would also clear
    /// [`is_throttled`](Self::is_throttled), turning the one refusal a consumer
    /// most needs to act on back into a silent one. A missing attribute is not
    /// evidence that the code means something else.
    pub fn from_server(code: u16, text: &str) -> Option<Self> {
        let by_code = Self::from(i32::from(code));
        match by_code.text() {
            Some(expected) if !text.is_empty() && text != expected => None,
            _ => Some(by_code),
        }
    }
}

impl core::fmt::Display for PairCodeRejection {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // Rendered as the stanza it came from, so a log line reads the same way.
        match self.text() {
            Some(text) => write!(f, "{text} ({})", self.code()),
            None => write!(f, "unknown ({})", self.code()),
        }
    }
}

/// Errors raised by wacore-side pair-code validation, key derivation, and
/// protocol-bundle building. The high-level crate wraps this in
/// `whatsapp_rust::pair_code::PairError` and adds an IQ-failure variant for the
/// transport layer.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PairCodeError {
    #[error("phone number is required")]
    PhoneNumberRequired,

    #[error("phone number is too short (must be at least 7 digits)")]
    PhoneNumberTooShort,

    #[error("phone number must not start with 0 (use international format)")]
    PhoneNumberNotInternational,

    #[error("invalid custom code: must be 8 characters from Crockford Base32 alphabet")]
    InvalidCustomCode,

    /// A code is already displayed and still within its validity window.
    ///
    /// Minting a second one does not replace the first for the *phone*: the
    /// server routes `primary_hello` by number, so whoever enters the older
    /// code still reaches stage 2 and receives a key bundle their code cannot
    /// open — the phone reports a failed link and the companion sees nothing.
    /// WA Web forbids the overlap with `invariant(stage === Initialized)`.
    /// Cancel the outstanding flow first if the replacement is intentional.
    #[error("a pair code is already outstanding ({remaining:?} left of its validity window)")]
    CodeAlreadyOutstanding { remaining: std::time::Duration },

    #[error("invalid wrapped data: expected {expected} bytes, got {got}")]
    InvalidWrappedData { expected: usize, got: usize },

    #[error("primary device sent an invalid ephemeral public key")]
    InvalidPrimaryEphemeralKey(#[source] CurveError),

    #[error("primary device sent an invalid identity public key")]
    InvalidPrimaryIdentityKey(#[source] CurveError),

    #[error("ephemeral key agreement failed")]
    EphemeralKeyAgreement(#[source] CurveError),

    #[error("identity key agreement failed")]
    IdentityKeyAgreement(#[source] CurveError),

    #[error("HKDF expand failed for adv_secret")]
    AdvSecretKeyDerivation,

    #[error("HKDF expand failed for bundle encryption key")]
    BundleKeyDerivation,

    #[error("AES-GCM encryption of key bundle failed")]
    BundleAead(#[source] CryptoProviderError),

    #[error("not in waiting state for pair code notification")]
    NotWaiting,

    #[error("server response missing pairing ref")]
    MissingPairingRef,

    /// The flow was cancelled (or replaced) while `companion_hello` was in
    /// flight, so the code stage 1 produced was never installed.
    #[error("the pair-code flow was cancelled while it was being requested")]
    Cancelled,
}

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

    /// The keyed-clone PBKDF2 must produce byte-identical output to the original
    /// form that re-ran `new_from_slice` every round.
    #[test]
    fn test_pbkdf2_matches_per_iteration_reference() {
        use hmac::{KeyInit as _, Mac as _};

        fn reference(password: &[u8], salt: &[u8], rounds: u32, output: &mut [u8]) {
            for (i, chunk) in output.chunks_mut(32).enumerate() {
                let mut u = {
                    let mut mac = Hmac::<Sha256>::new_from_slice(password).unwrap();
                    mac.update(salt);
                    mac.update(&((i as u32) + 1).to_be_bytes());
                    let r: [u8; 32] = mac.finalize().into_bytes().into();
                    r
                };
                chunk.copy_from_slice(&u[..chunk.len()]);
                for _ in 1..rounds {
                    let mut mac = Hmac::<Sha256>::new_from_slice(password).unwrap();
                    mac.update(&u);
                    u = mac.finalize().into_bytes().into();
                    for (a, b) in chunk.iter_mut().zip(u.iter()) {
                        *a ^= b;
                    }
                }
            }
        }

        let cases: &[(&[u8], &[u8], u32, usize)] = &[
            (b"password", b"salt", 1, 32),
            (b"password", b"salt", 7, 32),
            (b"pw", b"NaCl", 100, 64),              // multi-block output
            (b"", b"", 50, 16),                     // empty pw/salt, partial chunk
            (&[0xffu8; 40], &[0x01u8; 13], 33, 48), // long key, odd lengths
        ];
        for &(pw, salt, rounds, len) in cases {
            let mut got = vec![0u8; len];
            let mut want = vec![0u8; len];
            pbkdf2_hmac_sha256(pw, salt, rounds, &mut got);
            reference(pw, salt, rounds, &mut want);
            assert_eq!(got, want, "pbkdf2 mismatch for rounds={rounds} len={len}");
            assert_ne!(got, vec![0u8; len], "output must not be all zeros");
        }
    }

    #[test]
    fn test_generate_code() {
        let code = PairCodeUtils::generate_code();
        assert_eq!(code.len(), 8);
        assert!(PairCodeUtils::validate_code(&code));
    }

    #[test]
    fn test_validate_code_valid() {
        assert!(PairCodeUtils::validate_code("ABCD1234"));
        assert!(PairCodeUtils::validate_code("12345678"));
        assert!(PairCodeUtils::validate_code("VWXYZ123"));
    }

    #[test]
    fn test_validate_code_invalid() {
        // Too short
        assert!(!PairCodeUtils::validate_code("ABC1234"));
        // Too long
        assert!(!PairCodeUtils::validate_code("ABCD12345"));
        // Contains invalid characters (0, O, I, L)
        assert!(!PairCodeUtils::validate_code("ABCD0123")); // 0 is invalid
        assert!(!PairCodeUtils::validate_code("ABCDOIJK")); // O is invalid
        assert!(!PairCodeUtils::validate_code("ABCDIJKL")); // I and L are invalid
    }

    #[test]
    fn test_encode_crockford() {
        // Known test vector: 5 bytes of 0 should give the first character repeated
        let zeros = [0u8; 5];
        let encoded = PairCodeUtils::encode_crockford(&zeros);
        assert_eq!(encoded, "11111111");

        // All 0xFF should give last character repeated
        let ones = [0xFFu8; 5];
        let encoded = PairCodeUtils::encode_crockford(&ones);
        assert_eq!(encoded, "ZZZZZZZZ");
    }

    #[test]
    fn test_derive_key_deterministic() {
        let salt = [0u8; 32];
        let key1 = PairCodeUtils::derive_key("ABCD1234", &salt);
        let key2 = PairCodeUtils::derive_key("ABCD1234", &salt);
        assert_eq!(key1, key2);

        // Different code should give different key
        let key3 = PairCodeUtils::derive_key("WXYZ5678", &salt);
        assert_ne!(key1, key3);
    }

    #[test]
    fn test_encrypt_ephemeral_output_size() {
        let ephemeral_pub = [0x42u8; 32];
        let wrapped = PairCodeUtils::encrypt_ephemeral_pub(&ephemeral_pub, "ABCD1234");
        assert_eq!(wrapped.len(), 80);

        // Verify structure: salt (32) || iv (16) || ciphertext (32)
        assert_eq!(wrapped[0..32].len(), 32); // salt
        assert_eq!(wrapped[32..48].len(), 16); // iv
        assert_eq!(wrapped[48..80].len(), 32); // ciphertext
    }

    #[test]
    fn test_encrypt_decrypt_roundtrip() {
        let ephemeral_pub = [0x42u8; 32];
        let code = "ABCD1234";

        let wrapped = PairCodeUtils::encrypt_ephemeral_pub(&ephemeral_pub, code);

        // Decrypt using the pair code (extracts salt from wrapped data)
        let decrypted = PairCodeUtils::decrypt_primary_ephemeral_pub(&wrapped, code)
            .expect("Decryption should succeed");

        assert_eq!(decrypted, ephemeral_pub);
    }

    #[test]
    fn test_decrypt_invalid_length() {
        let code = "ABCD1234";

        // Too short
        let result = PairCodeUtils::decrypt_primary_ephemeral_pub(&[0u8; 79], code);
        assert!(matches!(
            result,
            Err(PairCodeError::InvalidWrappedData { .. })
        ));

        // Too long
        let result = PairCodeUtils::decrypt_primary_ephemeral_pub(&[0u8; 81], code);
        assert!(matches!(
            result,
            Err(PairCodeError::InvalidWrappedData { .. })
        ));
    }

    fn props(os: Option<&str>, pt: Option<wa::device_props::PlatformType>) -> wa::DeviceProps {
        wa::DeviceProps {
            os: os.map(|s| s.to_string()),
            platform_type: pt,
            ..Default::default()
        }
    }

    #[test]
    fn derive_chrome_linux_matches_wa_web() {
        let p = props(Some("Linux"), Some(wa::device_props::PlatformType::CHROME));
        assert_eq!(
            derive_companion_platform(&p),
            (CompanionWebClientType::Chrome, "Chrome (Linux)".to_string())
        );
    }

    #[test]
    fn derive_firefox_uses_companion_web_client_wire() {
        let p = props(Some("Linux"), Some(wa::device_props::PlatformType::FIREFOX));
        let (id, display) = derive_companion_platform(&p);
        assert_eq!(id, CompanionWebClientType::Firefox);
        assert_eq!(id.wire_byte(), b'3');
        assert_eq!(display, "Firefox (Linux)");
    }

    #[test]
    fn derive_edge_uses_companion_web_client_wire() {
        let p = props(Some("Windows"), Some(wa::device_props::PlatformType::EDGE));
        let (id, display) = derive_companion_platform(&p);
        assert_eq!(id, CompanionWebClientType::Edge);
        assert_eq!(id.wire_byte(), b'2');
        assert_eq!(display, "Edge (Windows)");
    }

    #[test]
    fn derive_android_platform_types_map_to_chrome() {
        use wa::device_props::PlatformType as P;
        for pt in [P::ANDROID_PHONE, P::ANDROID_TABLET, P::ANDROID_AMBIGUOUS] {
            let (id, display) = derive_companion_platform(&props(Some("Android"), Some(pt)));
            assert_eq!(id, CompanionWebClientType::Chrome, "{pt:?}");
            assert_eq!(id.wire_byte(), b'1', "{pt:?}");
            assert_eq!(display, "Chrome (Android)", "{pt:?}");
        }
    }

    #[test]
    fn derive_ios_phone_falls_back_to_other_web_client_and_chrome() {
        let p = props(Some("iOS"), Some(wa::device_props::PlatformType::IOS_PHONE));
        let (id, display) = derive_companion_platform(&p);
        assert_eq!(id, CompanionWebClientType::OtherWebClient);
        assert_eq!(display, "Chrome (iOS)");
    }

    #[test]
    fn derive_no_os_substitutes_linux() {
        let p = props(None, Some(wa::device_props::PlatformType::CHROME));
        assert_eq!(
            derive_companion_platform(&p),
            (CompanionWebClientType::Chrome, "Chrome (Linux)".to_string())
        );
    }

    #[test]
    fn derive_empty_os_substitutes_linux() {
        let p = props(Some("   "), Some(wa::device_props::PlatformType::CHROME));
        assert_eq!(
            derive_companion_platform(&p),
            (CompanionWebClientType::Chrome, "Chrome (Linux)".to_string())
        );
    }

    #[test]
    fn derive_unknown_proto_yields_other_web_client_id_and_chrome_display() {
        let p = props(None, None);
        assert_eq!(
            derive_companion_platform(&p),
            (
                CompanionWebClientType::OtherWebClient,
                "Chrome (Linux)".to_string()
            )
        );
    }

    #[test]
    fn derive_display_uses_known_label_for_every_proto_variant() {
        use wa::device_props::PlatformType as P;
        const SERVER_ACCEPT_LIST: &[u8] = b"0123456789abcdefghijklm";
        const KNOWN_LABELS: &[&str] = &[
            "Chrome", "Edge", "Firefox", "IE", "Opera", "Safari", "Android",
        ];
        for pt in [
            P::UNKNOWN,
            P::CHROME,
            P::FIREFOX,
            P::IE,
            P::OPERA,
            P::SAFARI,
            P::EDGE,
            P::DESKTOP,
            P::IPAD,
            P::ANDROID_TABLET,
            P::OHANA,
            P::ALOHA,
            P::CATALINA,
            P::TCL_TV,
            P::IOS_PHONE,
            P::IOS_CATALYST,
            P::ANDROID_PHONE,
            P::ANDROID_AMBIGUOUS,
            P::WEAR_OS,
            P::AR_WRIST,
            P::AR_DEVICE,
            P::UWP,
            P::VR,
            P::CLOUD_API,
            P::SMARTGLASSES,
        ] {
            let p = props(Some("Linux"), Some(pt));
            let (id, display) = derive_companion_platform(&p);
            assert!(
                SERVER_ACCEPT_LIST.contains(&id.wire_byte()),
                "{pt:?} wire byte {:?} outside server accept list",
                id.wire_byte() as char,
            );
            let label = display.split(" (").next().unwrap();
            assert!(
                KNOWN_LABELS.contains(&label),
                "{pt:?} produced display {display:?} with unexpected label {label:?}"
            );
            assert!(
                display.ends_with(" (Linux)"),
                "{pt:?} produced display {display:?} without parenthesised OS"
            );
        }
    }

    #[test]
    fn resolve_explicit_id_overrides_derived() {
        let p = props(
            Some("Android"),
            Some(wa::device_props::PlatformType::ANDROID_PHONE),
        );
        let opts = PairCodeOptions {
            platform_id: Some(CompanionWebClientType::Chrome),
            ..Default::default()
        };
        assert_eq!(
            resolve_companion_platform(&opts, &p),
            (
                CompanionWebClientType::Chrome,
                "Chrome (Android)".to_string()
            )
        );
    }

    #[test]
    fn resolve_default_uses_derived() {
        let p = props(Some("Linux"), Some(wa::device_props::PlatformType::EDGE));
        assert_eq!(
            resolve_companion_platform(&PairCodeOptions::default(), &p),
            (CompanionWebClientType::Edge, "Edge (Linux)".to_string())
        );
    }

    /// `display_os` sends the OS verbatim (bypassing canonicalization), so an
    /// advanced caller can keep a real distro name the server accepts.
    #[test]
    fn resolve_display_os_override_is_verbatim() {
        let p = props(Some("Linux"), Some(wa::device_props::PlatformType::CHROME));
        let opts = PairCodeOptions {
            display_os: Some("Ubuntu".to_string()),
            ..Default::default()
        };
        assert_eq!(
            resolve_companion_platform(&opts, &p),
            (
                CompanionWebClientType::Chrome,
                "Chrome (Ubuntu)".to_string()
            )
        );
    }

    /// The override wins even over a branding `DeviceProps::os` that would
    /// otherwise coerce to Linux.
    #[test]
    fn resolve_display_os_override_beats_branding_props_os() {
        let p = props(Some("Veloz"), Some(wa::device_props::PlatformType::CHROME));
        let opts = PairCodeOptions {
            display_os: Some("Fedora".to_string()),
            ..Default::default()
        };
        assert_eq!(resolve_companion_platform(&opts, &p).1, "Chrome (Fedora)");
    }

    /// An all-whitespace override is ignored — it falls back to the safe coercion
    /// (never emits an empty OS, which the server rejects).
    #[test]
    fn resolve_display_os_override_whitespace_falls_back_to_coercion() {
        let p = props(Some("Veloz"), Some(wa::device_props::PlatformType::CHROME));
        let opts = PairCodeOptions {
            display_os: Some("   ".to_string()),
            ..Default::default()
        };
        assert_eq!(resolve_companion_platform(&opts, &p).1, "Chrome (Linux)");
    }

    // ── `PairCodeState::live_flow_remaining` ─────────────────────────────────
    //
    // A second `companion_hello` mints a fresh code and ref, and the server
    // keeps routing `primary_hello` by phone number — so whoever is still
    // holding the previous code gets a `companion_finish` derived from key
    // material their code cannot open. WA Web never reaches that state from a
    // QR rotation: `Alt/DeviceLinkingApi.js` generates the code once from the
    // user's action and only regenerates it through `refreshAltLinkingCode`,
    // `forceManualRefresh`, or the screen's own timers. This predicate is what
    // lets the overwrite be reported instead of silent.

    fn waiting_at(ts: i64) -> PairCodeState {
        PairCodeState::WaitingForPhoneConfirmation {
            pairing_ref: b"3@2:ref".to_vec(),
            phone_jid: "15551234567".to_string(),
            pair_code: "ABCD1234".to_string(),
            ephemeral_keypair: Box::new(KeyPair::generate(
                &mut rand::make_rng::<rand::rngs::StdRng>(),
            )),
            code_generation_ts: ts,
            primary_hello_attempt_count: 0,
        }
    }

    #[test]
    fn live_flow_remaining_is_none_when_no_code_is_outstanding() {
        assert_eq!(PairCodeState::Idle.live_flow_remaining(1_000), None);
        assert_eq!(PairCodeState::Completed.live_flow_remaining(1_000), None);
    }

    #[test]
    fn live_flow_remaining_counts_down_the_validity_window() {
        let validity = PairCodeUtils::code_validity().as_secs() as i64;
        assert_eq!(
            waiting_at(1_000).live_flow_remaining(1_000),
            Some(PairCodeUtils::code_validity())
        );
        assert_eq!(
            waiting_at(1_000).live_flow_remaining(1_000 + 30),
            Some(std::time::Duration::from_secs(validity as u64 - 30))
        );
    }

    /// The boundary matches `handle_primary_hello`, which rejects only
    /// `age > validity` (WA Web `OldCodeError`): at exactly the window the code
    /// is still usable, so it is still worth reporting as lost.
    #[test]
    fn live_flow_remaining_treats_the_exact_window_as_still_live() {
        let validity = PairCodeUtils::code_validity().as_secs() as i64;
        assert_eq!(
            waiting_at(1_000).live_flow_remaining(1_000 + validity),
            Some(std::time::Duration::ZERO)
        );
        assert_eq!(
            waiting_at(1_000).live_flow_remaining(1_000 + validity + 1),
            None,
            "an expired code is not a flow anyone can still complete"
        );
    }

    /// A clock that jumped backwards must not underflow into a bogus window.
    #[test]
    fn live_flow_remaining_survives_a_backwards_clock() {
        assert_eq!(
            waiting_at(1_000).live_flow_remaining(900),
            Some(PairCodeUtils::code_validity())
        );
    }

    #[test]
    fn test_code_validity_duration() {
        let duration = PairCodeUtils::code_validity();
        assert_eq!(duration.as_secs(), 180);
    }

    #[test]
    fn test_validate_code_case_insensitive() {
        // Lowercase should be valid (will be uppercased)
        assert!(PairCodeUtils::validate_code("abcd1234"));
        assert!(PairCodeUtils::validate_code("AbCd1234"));
        assert!(PairCodeUtils::validate_code("vwxyz123"));
    }

    #[test]
    fn test_validate_code_all_crockford_chars() {
        // All valid Crockford Base32 characters
        assert!(PairCodeUtils::validate_code("12345678"));
        assert!(PairCodeUtils::validate_code("9ABCDEFG"));
        assert!(PairCodeUtils::validate_code("HJKLMNPQ"));
        assert!(PairCodeUtils::validate_code("RSTVWXYZ"));
    }

    #[test]
    fn test_generate_code_uniqueness() {
        // Generate multiple codes and verify they're unique
        let codes: Vec<String> = (0..100).map(|_| PairCodeUtils::generate_code()).collect();
        let unique_codes: std::collections::HashSet<_> = codes.iter().collect();
        // Very unlikely to have duplicates in 100 codes with 40 bits of entropy
        assert!(unique_codes.len() > 95);
    }

    #[test]
    fn test_encrypt_produces_different_output_each_time() {
        // Same input should produce different output due to random salt/iv
        let ephemeral_pub = [0x42u8; 32];
        let code = "ABCD1234";

        let wrapped1 = PairCodeUtils::encrypt_ephemeral_pub(&ephemeral_pub, code);
        let wrapped2 = PairCodeUtils::encrypt_ephemeral_pub(&ephemeral_pub, code);

        // Salt and IV should be different
        assert_ne!(&wrapped1[0..32], &wrapped2[0..32]); // Salt differs
        assert_ne!(&wrapped1[32..48], &wrapped2[32..48]); // IV differs
    }

    #[test]
    fn test_decrypt_with_wrong_code_produces_garbage() {
        let ephemeral_pub = [0x42u8; 32];
        let correct_code = "ABCD1234";
        let wrong_code = "WXYZ5678";

        let wrapped = PairCodeUtils::encrypt_ephemeral_pub(&ephemeral_pub, correct_code);

        // Decrypt with wrong code - should succeed but produce garbage
        let decrypted = PairCodeUtils::decrypt_primary_ephemeral_pub(&wrapped, wrong_code)
            .expect("Decryption should succeed structurally");

        // The decrypted data should NOT match the original
        assert_ne!(decrypted, ephemeral_pub);
    }

    #[test]
    fn test_derive_key_with_different_salts() {
        let code = "ABCD1234";
        let salt1 = [0u8; 32];
        let salt2 = [1u8; 32];

        let key1 = PairCodeUtils::derive_key(code, &salt1);
        let key2 = PairCodeUtils::derive_key(code, &salt2);

        // Different salts should produce different keys
        assert_ne!(key1, key2);
    }

    /// `Default` must not carry any implicit platform identity — the `Chrome (Linux)`
    /// hardcode caused the companion_hello IQ to claim Chrome even when
    /// `DeviceProps` said Android. Keep this assertion as a regression guard.
    #[test]
    fn pair_code_options_default_has_no_platform_hardcode() {
        let options = PairCodeOptions::default();
        assert!(options.phone_number.is_empty());
        assert!(options.show_push_notification, "default must keep push on");
        assert!(options.custom_code.is_none());
        assert!(
            options.platform_id.is_none(),
            "platform_id default must be None so derivation kicks in"
        );
    }

    #[test]
    fn test_pair_code_options_with_custom_code() {
        let options = PairCodeOptions {
            phone_number: "15551234567".to_string(),
            custom_code: Some("MYCODE12".to_string()),
            ..Default::default()
        };
        assert_eq!(options.phone_number, "15551234567");
        assert_eq!(options.custom_code, Some("MYCODE12".to_string()));
    }

    #[test]
    fn test_pair_code_state_debug() {
        let idle = PairCodeState::Idle;
        assert_eq!(format!("{:?}", idle), "Idle");

        let completed = PairCodeState::Completed;
        assert_eq!(format!("{:?}", completed), "Completed");
    }

    #[test]
    fn test_pair_code_error_display() {
        let err = PairCodeError::PhoneNumberRequired;
        assert_eq!(err.to_string(), "phone number is required");

        let err = PairCodeError::PhoneNumberTooShort;
        assert_eq!(
            err.to_string(),
            "phone number is too short (must be at least 7 digits)"
        );

        let err = PairCodeError::InvalidCustomCode;
        assert_eq!(
            err.to_string(),
            "invalid custom code: must be 8 characters from Crockford Base32 alphabet"
        );

        let err = PairCodeError::InvalidWrappedData {
            expected: 80,
            got: 50,
        };
        assert_eq!(
            err.to_string(),
            "invalid wrapped data: expected 80 bytes, got 50"
        );
    }

    #[test]
    fn invalid_primary_ephemeral_key_preserves_curve_source() {
        let err = PairCodeError::InvalidPrimaryEphemeralKey(CurveError::NoKeyTypeIdentifier);
        let src = std::error::Error::source(&err).expect("source preserved");
        let curve = src
            .downcast_ref::<CurveError>()
            .expect("downcasts to CurveError");
        assert!(matches!(curve, CurveError::NoKeyTypeIdentifier));
    }

    #[test]
    fn bundle_aead_preserves_crypto_provider_source() {
        let err = PairCodeError::BundleAead(CryptoProviderError::BadInput);
        let src = std::error::Error::source(&err).expect("source preserved");
        let cpe = src
            .downcast_ref::<CryptoProviderError>()
            .expect("downcasts to CryptoProviderError");
        assert!(matches!(cpe, CryptoProviderError::BadInput));
    }

    #[test]
    fn test_crockford_encoding_boundary_values() {
        // Test specific byte patterns
        let bytes = [0x00, 0x00, 0x00, 0x00, 0x1F]; // Last 5 bits = 31 = 'Z'
        let encoded = PairCodeUtils::encode_crockford(&bytes);
        assert_eq!(encoded.chars().last().unwrap(), 'Z');

        let bytes = [0x00, 0x00, 0x00, 0x00, 0x01]; // Last 5 bits = 1 = '2'
        let encoded = PairCodeUtils::encode_crockford(&bytes);
        assert_eq!(encoded.chars().last().unwrap(), '2');
    }

    // ----- Wire format + regression tests for companion_platform_{id,display} -----

    fn child_bytes<'a>(node: &'a Node, tag: &str) -> &'a [u8] {
        let n = node
            .get_optional_child_by_tag(&[tag])
            .unwrap_or_else(|| panic!("missing <{tag}>"));
        match n.content.as_ref() {
            Some(NodeContent::Bytes(b)) => b.as_slice(),
            other => panic!("expected Bytes for <{tag}>, got {other:?}"),
        }
    }

    fn build_iq(pid: &str, pdisp: &str) -> Node {
        let noise = [0xAAu8; 32];
        let wrapped = [0xBBu8; 80];
        PairCodeUtils::build_companion_hello_iq(
            "15551234567",
            &noise,
            &wrapped,
            pid,
            pdisp,
            true,
            "req-1".to_string(),
        )
    }

    #[test]
    fn companion_hello_iq_shape() {
        let iq = build_iq("e", "Android (Android)");
        assert_eq!(iq.tag, "iq");

        let reg = iq
            .get_optional_child_by_tag(&["link_code_companion_reg"])
            .expect("link_code_companion_reg");
        let attrs: std::collections::HashMap<String, String> = reg
            .attrs
            .iter()
            .map(|(k, v)| (k.to_string(), v.as_str().into_owned()))
            .collect();
        assert_eq!(
            attrs.get("stage").map(String::as_str),
            Some("companion_hello")
        );
        assert_eq!(
            attrs.get("jid").map(String::as_str),
            Some("15551234567@s.whatsapp.net")
        );
        assert_eq!(
            attrs
                .get("should_show_push_notification")
                .map(String::as_str),
            Some("true")
        );

        // Nonce is a single zero byte (0x00), matching WA Web's
        // `new Uint8Array(1)` and whatsmeow's `[]byte{0}` — not ASCII '0'.
        assert_eq!(child_bytes(reg, "link_code_pairing_nonce"), &[0u8]);
    }

    #[test]
    fn companion_hello_iq_passes_through_explicit_android_letter() {
        let iq = build_iq("e", "Android (16)");
        let reg = iq
            .get_optional_child_by_tag(&["link_code_companion_reg"])
            .unwrap();
        assert_eq!(child_bytes(reg, "companion_platform_id"), b"e");
        assert_eq!(
            child_bytes(reg, "companion_platform_display"),
            b"Android (16)"
        );
    }

    #[test]
    fn companion_hello_iq_chrome_linux_wire_parity() {
        // Guarantees the refactor didn't shift wire bytes for the legacy web case.
        let iq = build_iq("1", "Chrome (Linux)");
        let reg = iq
            .get_optional_child_by_tag(&["link_code_companion_reg"])
            .unwrap();
        assert_eq!(child_bytes(reg, "companion_platform_id"), b"1");
        assert_eq!(
            child_bytes(reg, "companion_platform_display"),
            b"Chrome (Linux)"
        );
    }

    #[test]
    fn android_device_props_emit_server_accepted_companion_hello() {
        let props = wa::DeviceProps {
            os: Some("Android".into()),
            platform_type: Some(wa::device_props::PlatformType::ANDROID_PHONE),
            ..Default::default()
        };
        let (pid, pdisp) = resolve_companion_platform(&PairCodeOptions::default(), &props);
        assert_eq!(pid, CompanionWebClientType::Chrome);
        assert_eq!(pid.wire_byte(), b'1');
        assert_eq!(pdisp, "Chrome (Android)");

        let iq = build_iq(&pid.to_string(), &pdisp);
        let reg = iq
            .get_optional_child_by_tag(&["link_code_companion_reg"])
            .unwrap();
        assert_eq!(child_bytes(reg, "companion_platform_id"), b"1");
        assert_eq!(
            child_bytes(reg, "companion_platform_display"),
            b"Chrome (Android)"
        );
    }

    #[test]
    fn explicit_options_override_id_and_display_follows() {
        let props = wa::DeviceProps {
            os: Some("Android".into()),
            platform_type: Some(wa::device_props::PlatformType::ANDROID_PHONE),
            ..Default::default()
        };
        let opts = PairCodeOptions {
            platform_id: Some(CompanionWebClientType::Chrome),
            ..Default::default()
        };
        let (pid, pdisp) = resolve_companion_platform(&opts, &props);
        assert_eq!(pid, CompanionWebClientType::Chrome);
        assert_eq!(pdisp, "Chrome (Android)");
    }

    /// Pair-code and QR share derivation.
    #[test]
    fn pair_code_id_matches_qr_id_for_same_device_props() {
        use crate::companion_reg::companion_web_client_type_for_props;
        let p = props(Some("Linux"), Some(wa::device_props::PlatformType::EDGE));
        let (pair_code_id, _) = derive_companion_platform(&p);
        let qr_id = companion_web_client_type_for_props(&p);
        assert_eq!(pair_code_id, qr_id);
    }
}