derec-library 0.0.1-alpha.8

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

use crate::derec_message::{DeRecMessageBuilder, current_timestamp};
use crate::primitives::pairing::PairingError;
use crate::protocol_version::ProtocolVersion;
use crate::types::ChannelId;
use crate::utils::verify_timestamps;
use derec_cryptography::pairing::{
    self as cryptography_pairing, PairingSecretKeyMaterial, PairingSharedKey,
};
use derec_proto::{
    CommunicationInfo, ContactMessage, ContactMode, DeRecMessage, DeRecResult, MessageBody,
    PairRequestMessage, PairResponseMessage, PrePairRequestMessage, PrePairResponseMessage,
    StatusEnum, TransportProtocol,
};
use prost::Message;
use sha2::{Digest, Sha384};
use subtle::ConstantTimeEq;

pub struct ProduceResult {
    /// Serialized outer [`derec_proto::DeRecMessage`] wire bytes carrying an encrypted inner
    /// [`derec_proto::PairResponseMessage`]. Ready to send over transport.
    pub envelope: Vec<u8>,
    pub peer_transport_protocol: TransportProtocol,
    pub shared_key: PairingSharedKey,
    /// Channel identifier the responder is committing to for all future
    /// traffic on this channel — derived from the pre-rekey id and the
    /// freshly negotiated `shared_key` via a deterministic hash. Callers
    /// MUST rename their local channel record from the old id to this
    /// value once they finish handling this response.
    pub channel_id: ChannelId,
}

pub struct ExtractResult {
    pub response: PairResponseMessage,
}

pub struct ProcessResult {
    pub shared_key: PairingSharedKey,
    /// Channel identifier both peers MUST switch to for all future traffic
    /// on this channel. Already validated against the local derivation; the
    /// caller's only remaining job is to atomically rename its channel
    /// record from the old id to this value.
    pub channel_id: ChannelId,
}

pub struct ProducePrePairResult {
    /// Serialized outer [`derec_proto::DeRecMessage`] wire bytes carrying a **plaintext**
    /// inner [`derec_proto::PrePairResponseMessage`]. Ready to send over transport.
    pub envelope: Vec<u8>,
}

pub struct ProducePrePairNoKeysResult {
    /// Serialized outer [`derec_proto::DeRecMessage`] wire bytes carrying a
    /// **plaintext** inner [`derec_proto::PrePairResponseMessage`] whose
    /// key fields are populated with freshly-generated material. Ready to
    /// send over transport.
    pub envelope: Vec<u8>,
    /// Initiator-side [`PairingSecretKeyMaterial`] generated on the fly
    /// for this response. The caller MUST persist this — the incoming
    /// [`derec_proto::PairRequestMessage`] will be encrypted to the
    /// embedded ECIES public key, and finalization needs the matching
    /// secret key material.
    pub pairing_secret_key_material: PairingSecretKeyMaterial,
}

pub struct PrePairExtractResult {
    pub response: PrePairResponseMessage,
}

pub struct ProcessPrePairResult {
    pub mlkem_encapsulation_key: Vec<u8>,
    pub ecies_public_key: Vec<u8>,
    pub nonce: u64,
}

/// Produces a pairing response envelope and derives the final pairing shared key on the
/// **Initiator** side (the party that originally created the contact message).
///
/// After receiving the responder's pairing request, the initiator:
///
/// 1. Validates the provided [`derec_proto::PairRequestMessage`] contents
/// 2. Finalizes the initiator-side pairing computation using its previously stored
///    [`derec_cryptography::pairing::PairingSecretKeyMaterial`]
/// 3. Derives the final 256-bit [`derec_cryptography::pairing::PairingSharedKey`]
/// 4. Constructs a [`derec_proto::PairResponseMessage`] with an `Ok` status
/// 5. Encrypts the serialized inner response message to the responder's ECIES public key
/// 6. Wraps the encrypted inner bytes into a plain [`derec_proto::DeRecMessage`] envelope
///
/// Because the pairing flow does not yet rely on the final shared symmetric key for
/// transport, this function uses the pairing-specific **asymmetric** encryption mechanism
/// for the inner response message.
///
/// To signal rejection instead of acceptance, callers build the
/// [`derec_proto::PairResponseMessage`] themselves (with a non-`Ok`
/// [`derec_proto::StatusEnum`]) and encrypt it with [`crate::derec_message::DeRecMessageBuilder::pairing`].
///
/// # Arguments
///
/// * `request` - The decoded [`derec_proto::PairRequestMessage`] previously returned by
///   [`super::request::extract`].
/// * `pairing_secret_key_material` - Initiator-side pairing secret state previously returned
///   by [`super::request::create_contact`]. Must be the
///   [`derec_cryptography::pairing::PairingSecretKeyMaterial::Initiator`] variant; passing the
///   `Responder` variant will return [`PairingError::Invariant`].
/// * `communication_info` - Optional application-level identity metadata to advertise to the
///   peer (free-form key/value pairs). Pass `None` to send no metadata; the protocol treats
///   this as opaque.
///
/// # Returns
///
/// On success returns [`ProduceResult`] containing:
///
/// - `envelope`: serialized outer [`derec_proto::DeRecMessage`] envelope bytes carrying
///   the encrypted inner [`derec_proto::PairResponseMessage`]
/// - `shared_key`: the initiator-side derived pairing shared key
/// - `peer_transport_protocol`: peer transport information extracted from the
///   validated [`derec_proto::PairRequestMessage`]
///
/// # Errors
///
/// Returns [`crate::Error`] (specifically `Error::Pairing(...)`) in the following cases:
///
/// - [`PairingError::InvalidPairRequestMessage`] if the request is malformed or missing fields
/// - [`PairingError::EmptyTransportUri`] if the request transport information is missing or empty
/// - [`PairingError::Invariant`] if `pairing_secret_key_material` is not the `Initiator` variant
/// - [`PairingError::FinishPairingInitiator`] if pairing finalization fails
/// - [`PairingError::PairingEncryption`] if inner-message encryption fails
///
/// # Security Notes
///
/// - The derived shared key should be treated as sensitive material.
/// - The returned `peer_transport_protocol` is peer-provided data; apply any
///   caller-side validation required by the selected transport layer before using it.
///
/// # Channel id rekey
///
/// After the handshake completes both sides switch from the pre-rekey
/// `channel_id` (the contact-time value) to a post-handshake id derived
/// deterministically from the pre-rekey id and the freshly-negotiated
/// `shared_key` via a SHA-384 hash. This response is the
/// **only** place the new id crosses the wire, and it travels inside the
/// encrypted inner message; a passive observer who saw only pre-rekey
/// traffic cannot link the long-running channel back to its pairing-time
/// id without the shared key.
///
/// The outer envelope still routes on the pre-rekey id — the requester has
/// no way to know the new id until it has decrypted the inner message and
/// derived its own copy of the shared key.
///
/// # Example
///
/// ```
/// use derec_library::primitives::pairing::{request, response};
/// use derec_library::types::ChannelId;
/// use derec_proto::{ContactMode, Protocol, SenderKind, TransportProtocol};
///
/// // Initiator side: create the out-of-band contact message.
/// let request::CreateContactResult {
///     contact_message,
///     secret_key: initiator_key,
/// } = request::create_contact(
///     ChannelId(42),
///     ContactMode::InlineKeys,
///     TransportProtocol {
///         uri: "https://relay.example/initiator".to_owned(),
///         protocol: Protocol::Https.into(),
///     },
///     None,
/// ).expect("create_contact failed");
///
/// // Responder side: build and send the pairing request envelope.
/// let request::ProduceResult { envelope: request_envelope, .. } = request::produce(
///     SenderKind::Helper,
///     TransportProtocol {
///         uri: "https://relay.example/responder".to_owned(),
///         protocol: Protocol::Https.into(),
///     },
///     &contact_message,
///     None,
///     None,
/// ).expect("produce failed");
///
/// // Initiator side: extract the pairing request, then produce the response.
/// let request::ExtractResult { request: pair_request } = request::extract(
///     &request_envelope,
///     initiator_key.as_ref().unwrap().ecies_secret_key(),
/// ).expect("extract failed");
///
/// let response::ProduceResult { envelope, shared_key, .. } = response::produce(
///     ChannelId(42),
///     &pair_request,
///     initiator_key.as_ref().unwrap(),
///     None,
///     None,
/// ).expect("produce failed");
///
/// assert!(!envelope.is_empty());
/// let _ = shared_key;
/// ```
#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = channel_id.0))
)]
pub fn produce(
    channel_id: ChannelId,
    request: &PairRequestMessage,
    pairing_secret_key_material: &PairingSecretKeyMaterial,
    communication_info: Option<CommunicationInfo>,
    parameter_range: Option<derec_proto::ParameterRange>,
) -> Result<ProduceResult, crate::Error> {
    validate_produce_inputs(request)?;

    let peer_transport_protocol = extract_peer_transport_protocol(request)?;

    let pairing_request = cryptography_pairing::PairingRequestMessageMaterial {
        mlkem_ciphertext: request.mlkem_ciphertext.clone(),
        ecies_public_key: request.ecies_public_key.clone(),
    };

    let initiator_material = match pairing_secret_key_material {
        cryptography_pairing::PairingSecretKeyMaterial::Initiator(m) => m,
        _ => {
            return Err(PairingError::Invariant(
                "expected Initiator key material for pairing response",
            )
            .into());
        }
    };

    let shared_key =
        cryptography_pairing::finish_pairing_initiator(initiator_material, &pairing_request)
            .map_err(|e| PairingError::FinishPairingInitiator { source: e })?;

    let rekeyed_channel_id = derive_rekeyed_channel_id(channel_id, &shared_key);

    let timestamp = current_timestamp();
    let response = PairResponseMessage {
        result: Some(DeRecResult {
            status: StatusEnum::Ok as i32,
            memo: String::new(),
        }),
        nonce: request.nonce,
        communication_info,
        parameter_range,
        timestamp: Some(timestamp),
        channel_id: rekeyed_channel_id.into(),
    };

    let envelope = DeRecMessageBuilder::pairing()
        .channel_id(channel_id)
        .timestamp(timestamp)
        .message_body(MessageBody::PairResponse(response))
        .encrypt_pairing(&request.ecies_public_key)?
        .build()?
        .encode_to_vec();

    #[cfg(feature = "logging")]
    tracing::info!("pairing response envelope produced; initiator shared key derived");

    Ok(ProduceResult {
        envelope,
        shared_key,
        peer_transport_protocol,
        channel_id: rekeyed_channel_id,
    })
}

/// Produces a `PrePairResponseMessage` envelope on the **contact creator** side,
/// the second leg of the [`derec_proto::ContactMode::HashedKeys`] pairing flow.
///
/// In `HASHED_KEYS` mode the contact carries only a SHA-384 commitment to the
/// initiator's public keys (not the keys themselves), so before the scanner can
/// build a [`PairRequestMessage`] it must ask the contact creator for the actual
/// keys. This function builds the reply.
///
/// The inner [`PrePairResponseMessage`] is **plaintext** — no shared key exists yet
/// — so the outer [`DeRecMessage`] envelope is constructed directly rather than
/// through the encryption-enforcing [`DeRecMessageBuilder`]. The envelope's
/// `channelId` is the local pairing channel (the same one the request arrived on),
/// and the response echoes the request's `nonce` so the scanner can correlate it
/// with the original contact and reject stale or spoofed replies.
///
/// # Arguments
///
/// * `channel_id` - Identifier of the local pairing channel this response belongs
///   to. Echoed on the outer envelope so the peer can route the reply.
/// * `request` - The decoded [`PrePairRequestMessage`] previously returned by
///   [`super::request::extract_pre_pair`]. Only its `nonce` is consumed.
/// * `pairing_secret_key_material` - Initiator-side pairing secret state previously
///   returned by [`super::request::create_contact`]. Must be the
///   [`PairingSecretKeyMaterial::Initiator`] variant; the responder variant cannot
///   serve a `PrePairResponse` because it doesn't own the keys.
///
/// # Returns
///
/// On success returns [`ProducePrePairResult`] containing the serialized outer
/// [`DeRecMessage`] envelope bytes.
///
/// # Errors
///
/// Returns [`crate::Error`] (specifically `Error::Pairing(...)`) in the following cases:
///
/// - [`PairingError::Invariant`] if `pairing_secret_key_material` is not the
///   `Initiator` variant
///
/// # Security Notes
///
/// - The envelope is plaintext; any passive observer can read the public keys
///   advertised here. The keys are public material, but the transport endpoint
///   used for this exchange MUST be ephemeral (see the security note on
///   `PrePairRequestMessage`) so the keys cannot be linked to a long-term
///   identity by a passive observer.
#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = channel_id.0))
)]
pub fn produce_pre_pair(
    channel_id: ChannelId,
    request: &PrePairRequestMessage,
    pairing_secret_key_material: &PairingSecretKeyMaterial,
) -> Result<ProducePrePairResult, crate::Error> {
    let initiator_material = match pairing_secret_key_material {
        PairingSecretKeyMaterial::Initiator(m) => m,
        _ => {
            #[cfg(feature = "logging")]
            tracing::warn!("expected Initiator key material for PrePair response");

            return Err(PairingError::Invariant(
                "expected Initiator key material for PrePair response",
            )
            .into());
        }
    };

    let timestamp = current_timestamp();
    let response = PrePairResponseMessage {
        result: Some(DeRecResult {
            status: StatusEnum::Ok as i32,
            memo: String::new(),
        }),
        mlkem_encapsulation_key: Some(initiator_material.mlkem_encapsulation_key.clone()),
        ecies_public_key: Some(initiator_material.ecies_public_key.clone()),
        nonce: request.nonce,
        timestamp: Some(timestamp),
    };

    let protocol_version = ProtocolVersion::current();
    let envelope = DeRecMessage {
        protocol_version_major: protocol_version.major,
        protocol_version_minor: protocol_version.minor,
        sequence: 0,
        channel_id: channel_id.into(),
        timestamp: Some(timestamp),
        message: MessageBody::PrePairResponse(response).encode_to_vec(),
        trace_id: 0,
    }
    .encode_to_vec();

    #[cfg(feature = "logging")]
    tracing::info!("PrePair response envelope produced");

    Ok(ProducePrePairResult { envelope })
}

/// Produces a [`derec_proto::PrePairResponseMessage`] envelope on the
/// **contact creator** side, for the [`ContactMode::NoKeys`] flow.
///
/// Unlike [`produce_pre_pair`], no pre-existing
/// [`PairingSecretKeyMaterial`] is required — this function **generates
/// fresh ML-KEM and ECIES key material on the fly** and returns both the
/// on-the-wire envelope and the new [`PairingSecretKeyMaterial`] so the
/// caller can persist it. The subsequent
/// [`derec_proto::PairRequestMessage`] the scanner sends will be encrypted
/// to the embedded ECIES public key; finalization needs the matching
/// secret key material returned here.
///
/// The inner [`PrePairResponseMessage`] is plaintext (same as the
/// HashedKeys leg) — no shared key exists yet — and the `nonce` from the
/// request is echoed for session correlation on the scanner side.
///
/// # Security
///
/// This response carries no cryptographic binding to any prior contact
/// (no hash to verify against). Its safety derives entirely from the
/// out-of-band delivery having established that the incoming
/// `PrePairRequest` came from the intended, already-trusted recipient of
/// the corresponding `ContactMessage`. The handler MUST authenticate the
/// incoming request by matching `request.nonce` against the stored
/// contact's `nonce` before calling this function.
///
/// # Arguments
///
/// * `channel_id` — Local pairing channel identifier this response
///   belongs to. Echoed on the outer envelope so the scanner can route
///   the reply.
/// * `request` — The decoded [`PrePairRequestMessage`] previously
///   returned by [`super::request::extract_pre_pair`]. Only its `nonce`
///   is consumed here (echoed into the response); nonce verification is
///   the caller's responsibility.
///
/// # Returns
///
/// On success returns [`ProducePrePairNoKeysResult`] containing the
/// serialized envelope AND the freshly-generated
/// [`PairingSecretKeyMaterial`]. The caller MUST persist the secret
/// material — it's the only place ML-KEM decapsulation / ECIES decrypt
/// keys exist for this channel.
///
/// # Errors
///
/// Returns [`crate::Error::Pairing`] wrapping
/// [`PairingError::ContactMessageKeygen`] if key generation fails.
#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = channel_id.0))
)]
pub fn produce_pre_pair_no_keys(
    channel_id: ChannelId,
    request: &PrePairRequestMessage,
) -> Result<ProducePrePairNoKeysResult, crate::Error> {
    let seed = crate::utils::generate_seed::<32>();
    let (pk, secret_key) = cryptography_pairing::contact_message(*seed)
        .map_err(|e| PairingError::ContactMessageKeygen { source: e })?;

    let timestamp = current_timestamp();
    let response = PrePairResponseMessage {
        result: Some(DeRecResult {
            status: StatusEnum::Ok as i32,
            memo: String::new(),
        }),
        mlkem_encapsulation_key: Some(pk.mlkem_encapsulation_key.clone()),
        ecies_public_key: Some(pk.ecies_public_key.clone()),
        nonce: request.nonce,
        timestamp: Some(timestamp),
    };

    let protocol_version = ProtocolVersion::current();
    let envelope = DeRecMessage {
        protocol_version_major: protocol_version.major,
        protocol_version_minor: protocol_version.minor,
        sequence: 0,
        channel_id: channel_id.into(),
        timestamp: Some(timestamp),
        message: MessageBody::PrePairResponse(response).encode_to_vec(),
        trace_id: 0,
    }
    .encode_to_vec();

    #[cfg(feature = "logging")]
    tracing::info!("NoKeys PrePair response envelope produced with fresh key material");

    Ok(ProducePrePairNoKeysResult {
        envelope,
        pairing_secret_key_material: PairingSecretKeyMaterial::Initiator(secret_key),
    })
}

/// Decrypts and decodes an incoming [`derec_proto::PairResponseMessage`] from an outer
/// [`derec_proto::DeRecMessage`] envelope.
///
/// Because pairing happens *before* a shared symmetric key exists, the inner message is
/// decrypted using the pairing-specific **asymmetric** ECIES decryption mechanism.
///
/// This function:
///
/// 1. Decodes the outer [`derec_proto::DeRecMessage`] envelope from `envelope_bytes`
/// 2. Decrypts the inner message bytes using `ecies_secret_key`
/// 3. Decodes the decrypted bytes as a [`derec_proto::PairResponseMessage`]
/// 4. Validates the invariant `envelope.timestamp == response.timestamp`
///
/// # Arguments
///
/// * `envelope_bytes` - Serialized outer [`derec_proto::DeRecMessage`] bytes carrying an
///   asymmetrically-encrypted inner [`derec_proto::PairResponseMessage`], as produced by
///   [`produce`].
/// * `ecies_secret_key` - The responder's ECIES secret key. Must correspond to the
///   `ecies_public_key` the responder embedded in their [`derec_proto::PairRequestMessage`],
///   which is the key used by [`produce`] to encrypt the inner response.
///
/// # Returns
///
/// On success returns [`ExtractResult`] containing:
///
/// - `response`: the decrypted inner [`derec_proto::PairResponseMessage`]
///
/// # Errors
///
/// Returns [`crate::Error`] if:
///
/// - `envelope_bytes` cannot be decoded as a valid [`derec_proto::DeRecMessage`]
/// - ECIES decryption fails
/// - the decrypted bytes cannot be decoded as a [`derec_proto::PairResponseMessage`]
/// - `envelope.timestamp != response.timestamp`
/// - the inner message is not a [`derec_proto::PairResponseMessage`]
///
/// # Security: no freshness or replay protection
///
/// The timestamp check enforced here only binds the envelope to the
/// inner body (`envelope.timestamp == body.timestamp`). It does NOT
/// enforce a freshness window against the receiver's clock and does
/// NOT detect replays of a previously-captured ciphertext. Pairing
/// has a small extra mitigation (the per-channel `ContactMessage`
/// nonce is one-shot, so a replayed PairResponse cannot complete a
/// fresh pairing once the original session is over), but a recorded
/// envelope can still be re-decoded and inspected later. Callers
/// MUST add a freshness window and per-channel anti-replay
/// (monotonic counter or nonce log) on top before driving any
/// side-effecting state off the parsed body.
///
/// # Example
///
/// ```
/// use derec_library::primitives::pairing::{request, response};
/// use derec_library::types::ChannelId;
/// use derec_proto::{ContactMode, Protocol, SenderKind, TransportProtocol};
///
/// // Initiator: create the out-of-band contact message.
/// let request::CreateContactResult {
///     contact_message,
///     secret_key: initiator_key,
/// } = request::create_contact(
///     ChannelId(42),
///     ContactMode::InlineKeys,
///     TransportProtocol {
///         uri: "https://relay.example/initiator".to_owned(),
///         protocol: Protocol::Https.into(),
///     },
///     None,
/// ).expect("create_contact failed");
///
/// // Responder: build the pairing request envelope.
/// let request::ProduceResult {
///     envelope: request_envelope,
///     secret_key: responder_key,
///     ..
/// } = request::produce(
///     SenderKind::Helper,
///     TransportProtocol {
///         uri: "https://relay.example/responder".to_owned(),
///         protocol: Protocol::Https.into(),
///     },
///     &contact_message,
///     None,
///     None,
/// ).expect("produce failed");
///
/// // Initiator: extract the pairing request, then produce the response.
/// let request::ExtractResult { request: pair_request } = request::extract(
///     &request_envelope,
///     initiator_key.as_ref().unwrap().ecies_secret_key(),
/// ).expect("extract request failed");
/// let response::ProduceResult { envelope: response_envelope, .. } =
///     response::produce(ChannelId(42), &pair_request, initiator_key.as_ref().unwrap(), None, None)
///         .expect("produce failed");
///
/// // Responder: decrypt the pairing response.
/// let response::ExtractResult { response } =
///     response::extract(&response_envelope, responder_key.ecies_secret_key())
///         .expect("extract response failed");
///
/// assert_eq!(response.nonce, pair_request.nonce);
/// ```
#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(envelope_len = envelope_bytes.len()))
)]
pub fn extract(
    envelope_bytes: &[u8],
    ecies_secret_key: &[u8],
) -> Result<ExtractResult, crate::Error> {
    let envelope = DeRecMessage::decode(envelope_bytes).map_err(crate::Error::ProtobufDecode)?;

    let plaintext =
        derec_cryptography::pairing::envelope::decrypt(&envelope.message, ecies_secret_key)
            .map_err(PairingError::PairingEncryption)?;

    let response = match MessageBody::decode_from_vec(plaintext.as_slice())
        .map_err(crate::Error::ProtobufDecode)?
    {
        MessageBody::PairResponse(r) => r,
        _ => {
            #[cfg(feature = "logging")]
            tracing::warn!("unexpected message type; expected PairResponseMessage");

            return Err(crate::Error::Invariant(
                "Invalid message. Expected: PairResponseMessage",
            ));
        }
    };

    verify_timestamps(envelope.timestamp, response.timestamp)?;

    #[cfg(feature = "logging")]
    tracing::info!("pairing response extracted and validated");

    Ok(ExtractResult { response })
}

/// Decodes a plaintext [`PrePairResponseMessage`] from an outer
/// [`DeRecMessage`] envelope produced by [`produce_pre_pair`].
///
/// Like its request-side counterpart [`super::request::extract_pre_pair`],
/// the `PrePair` flow carries its inner message **in plaintext** inside the
/// envelope (no shared key exists yet, and the keys the response is delivering
/// cannot themselves be used for encryption). This function performs no
/// decryption — it decodes the envelope, decodes the inner [`MessageBody`],
/// and validates the envelope-vs-body timestamp invariant.
///
/// Status and content validation (confirming `result.status == OK` and
/// recomputing the SHA-384 binding hash against
/// [`derec_proto::ContactMessage::contact_binding_hash`]) is the caller's
/// responsibility — see the receiver checklist on
/// [`derec_proto::PrePairResponseMessage`].
///
/// # Arguments
///
/// * `envelope_bytes` - Serialized outer [`DeRecMessage`] wire bytes, as
///   produced by [`produce_pre_pair`].
///
/// # Returns
///
/// On success returns [`PrePairExtractResult`] containing the decoded inner
/// [`PrePairResponseMessage`]. The caller can recover the routing
/// `channel_id` by decoding the envelope separately if it is not already
/// known from context.
///
/// # Errors
///
/// Returns [`crate::Error`] if:
///
/// - `envelope_bytes` cannot be decoded as a valid [`DeRecMessage`]
/// - the inner [`MessageBody`] cannot be decoded
/// - the inner [`MessageBody`] is not a [`PrePairResponseMessage`]
/// - `envelope.timestamp != response.timestamp`
///
/// # Security: no freshness or replay protection
///
/// The timestamp check enforced here only binds the envelope to the
/// inner body (`envelope.timestamp == body.timestamp`). It does NOT
/// enforce a freshness window against the receiver's clock and does
/// NOT detect replays of a previously-captured envelope. PrePair
/// envelopes are plaintext (no shared key yet), so a recorded
/// envelope can be replayed verbatim by anyone on path. Callers
/// MUST add a freshness window and per-channel anti-replay
/// (monotonic counter or nonce log) on top before driving any
/// side-effecting state off the parsed body.
#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(envelope_len = envelope_bytes.len()))
)]
pub fn extract_pre_pair(envelope_bytes: &[u8]) -> Result<PrePairExtractResult, crate::Error> {
    let envelope = DeRecMessage::decode(envelope_bytes).map_err(crate::Error::ProtobufDecode)?;

    let response = match crate::derec_message::extract_inner_plaintext_message(&envelope.message)? {
        MessageBody::PrePairResponse(r) => r,
        _ => {
            #[cfg(feature = "logging")]
            tracing::warn!("unexpected message type; expected PrePairResponseMessage");

            return Err(crate::Error::Invariant(
                "Invalid message. Expected: PrePairResponseMessage",
            ));
        }
    };

    verify_timestamps(envelope.timestamp, response.timestamp)?;

    #[cfg(feature = "logging")]
    tracing::info!("PrePair response envelope decoded and validated");

    Ok(PrePairExtractResult { response })
}

/// Processes a decrypted pairing response and derives the final pairing shared key on the
/// **Responder** side.
///
/// This function is executed by the party that:
///
/// 1. Received the initiator's contact out-of-band
/// 2. Produced and sent a pairing request using [`super::request::produce`]
///
/// After receiving the initiator's decrypted pairing response, the responder:
///
/// 1. Validates the response status and binds it to the same pairing session using the nonce
/// 2. Uses the responder's previously stored [`derec_cryptography::pairing::PairingSecretKeyMaterial`]
///    together with the initiator's original public pairing material from the contact message
///    to finalize the responder side
/// 3. Derives the final 256-bit [`derec_cryptography::pairing::PairingSharedKey`]
///
/// Both parties should derive the same shared key if the pairing flow completed successfully.
///
/// # Arguments
///
/// * `contact_message` - Decoded [`derec_proto::ContactMessage`] previously returned as
///   `initiator_contact_message` by [`super::request::produce`].
/// * `response` - The decrypted [`derec_proto::PairResponseMessage`] previously returned
///   by [`extract`].
/// * `pairing_secret_key_material` - Responder-side secret state previously returned by
///   [`super::request::produce`]. Must be the
///   [`derec_cryptography::pairing::PairingSecretKeyMaterial::Responder`] variant; passing the
///   `Initiator` variant will return [`PairingError::Invariant`].
///
/// # Returns
///
/// On success returns [`ProcessResult`] containing:
///
/// - `shared_key`: the responder-side derived pairing shared key
///
/// # Errors
///
/// Returns [`crate::Error`] (specifically `Error::Pairing(...)`) in the following cases:
///
/// - [`PairingError::NonOkStatus`] if `result.status != Ok`, carrying the peer's status code
///   and memo string
/// - [`PairingError::InvalidPairResponseMessage`] if the response is malformed (e.g. missing result)
/// - [`PairingError::InvalidContactMessage`] if the contact message is missing required fields
/// - [`PairingError::ProtocolViolation`] if the response does not match the pairing session
///   (for example, nonce mismatch)
/// - [`PairingError::Invariant`] if `pairing_secret_key_material` is not the `Responder` variant
/// - [`PairingError::FinishPairingResponder`] if final pairing derivation fails
///
/// # Security Notes
///
/// - The nonce check is a critical session-binding validation.
/// - The derived shared key should be treated as sensitive material and stored securely.
///
/// # Example
///
/// ```
/// use derec_library::primitives::pairing::{request, response};
/// use derec_library::types::ChannelId;
/// use derec_proto::{ContactMode, Protocol, SenderKind, TransportProtocol};
///
/// // Initiator side: create the out-of-band contact message.
/// let request::CreateContactResult {
///     contact_message,
///     secret_key: initiator_key,
/// } = request::create_contact(
///     ChannelId(42),
///     ContactMode::InlineKeys,
///     TransportProtocol {
///         uri: "https://relay.example/initiator".to_owned(),
///         protocol: Protocol::Https.into(),
///     },
///     None,
/// ).expect("create_contact failed");
///
/// // Responder side: build and send the pairing request envelope.
/// let request::ProduceResult {
///     envelope: request_envelope,
///     initiator_contact_message,
///     secret_key: responder_key,
/// } = request::produce(
///     SenderKind::Helper,
///     TransportProtocol {
///         uri: "https://relay.example/responder".to_owned(),
///         protocol: Protocol::Https.into(),
///     },
///     &contact_message,
///     None,
///     None,
/// ).expect("produce failed");
///
/// // Initiator side: extract the pairing request and produce the response.
/// let request::ExtractResult { request: pair_request } = request::extract(
///     &request_envelope,
///     initiator_key.as_ref().unwrap().ecies_secret_key(),
/// ).expect("extract request failed");
///
/// let response::ProduceResult { envelope: response_envelope, shared_key: initiator_shared_key, .. } =
///     response::produce(ChannelId(42), &pair_request, initiator_key.as_ref().unwrap(), None, None)
///         .expect("produce failed");
///
/// // Responder side: extract the pairing response and derive the shared key.
/// let response::ExtractResult { response: pair_response } = response::extract(
///     &response_envelope,
///     responder_key.ecies_secret_key(),
/// ).expect("extract response failed");
///
/// let response::ProcessResult { shared_key: responder_shared_key, .. } =
///     response::process(&initiator_contact_message, &pair_response, &responder_key)
///         .expect("process failed");
///
/// assert_eq!(initiator_shared_key, responder_shared_key);
/// ```
#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = contact_message.channel_id))
)]
pub fn process(
    contact_message: &ContactMessage,
    response: &PairResponseMessage,
    pairing_secret_key_material: &PairingSecretKeyMaterial,
) -> Result<ProcessResult, crate::Error> {
    let responder_material =
        validate_process_inputs(contact_message, response, pairing_secret_key_material)?;

    let pairing_contact_key_material = build_pairing_contact_material(contact_message);

    let shared_key = cryptography_pairing::finish_pairing_responder(
        responder_material,
        &pairing_contact_key_material,
    )
    .map_err(|e| PairingError::FinishPairingResponder { source: e })?;

    let expected_channel_id =
        validate_rekeyed_channel_id(response, ChannelId(contact_message.channel_id), &shared_key)?;

    #[cfg(feature = "logging")]
    tracing::info!("pairing complete; responder shared key derived");

    Ok(ProcessResult {
        shared_key,
        channel_id: expected_channel_id,
    })
}

/// Validates an incoming [`PrePairResponseMessage`] against the original
/// [`ContactMessage`] and, on success, hands back the initiator's public
/// keys ready to be used to construct a normal [`PairRequestMessage`].
///
/// This is the **scanner**-side check that closes the
/// [`derec_proto::ContactMode::HashedKeys`] pre-pair leg. Per the receiver
/// checklist on [`derec_proto::PrePairResponseMessage`], a conforming
/// implementation MUST:
///
/// 1. confirm `result.status == OK`;
/// 2. recompute `SHA-384(mlkemEncapsulationKey || eciesPublicKey
///    || u64_be(nonce) || u64_be(channelId))` and verify it matches the
///    original [`ContactMessage::contact_binding_hash`];
/// 3. only on match, proceed to construct a normal [`PairRequestMessage`].
///
/// This function performs all three checks. The recomputation uses the
/// `nonce` and `channelId` from the **contact** — the trusted out-of-band
/// values — so a tampered response that swapped them cannot mask a hash
/// mismatch by tampering them in parallel.
///
/// # Arguments
///
/// * `contact_message` - The decoded [`ContactMessage`] received out-of-band.
///   Its [`ContactMode`] must be [`ContactMode::HashedKeys`] and it must
///   carry a non-empty `contact_binding_hash`.
/// * `response` - The decoded [`PrePairResponseMessage`] previously returned
///   by [`extract_pre_pair`].
///
/// # Returns
///
/// On success returns [`ProcessPrePairResult`] containing the validated
/// `mlkem_encapsulation_key`, `ecies_public_key`, and the echoed `nonce`.
///
/// # Errors
///
/// Returns [`crate::Error`] (specifically `Error::Pairing(...)`) in the following cases:
///
/// - [`PairingError::InvalidPairResponseMessage`] if the response is malformed
///   (missing result, missing/empty keys)
/// - [`PairingError::NonOkStatus`] if `result.status != Ok`, carrying the
///   peer's status code and memo string
/// - [`PairingError::InvalidContactMessage`] if the contact is not in
///   [`ContactMode::HashedKeys`] or lacks a `contact_binding_hash`
/// - [`PairingError::ProtocolViolation`] if `response.nonce` does not match
///   `contact_message.nonce` (session correlation failure) or if the
///   recomputed binding hash does not match `contact_binding_hash`
///   (potential MITM on the plaintext pre-pair leg)
#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = contact_message.channel_id))
)]
pub fn process_pre_pair(
    contact_message: &ContactMessage,
    response: &PrePairResponseMessage,
) -> Result<ProcessPrePairResult, crate::Error> {
    validate_process_pre_pair_inputs(contact_message, response, ContactMode::HashedKeys)?;

    let (mlkem_encapsulation_key, ecies_public_key) =
        validate_contact_binding_hash(contact_message, response)?;

    #[cfg(feature = "logging")]
    tracing::info!("PrePair response validated against contact binding hash");

    Ok(ProcessPrePairResult {
        mlkem_encapsulation_key,
        ecies_public_key,
        nonce: response.nonce,
    })
}

/// Processes an incoming [`derec_proto::PrePairResponseMessage`] on the
/// **scanner** side, for the [`ContactMode::NoKeys`] flow.
///
/// Unlike [`process_pre_pair`], this variant performs **no cryptographic
/// verification** of the published keys against the original contact —
/// there is no binding hash to compare, by design. The scanner accepts
/// the ML-KEM and ECIES public keys returned by the contact creator at
/// face value; the trust anchor is the out-of-band delivery channel,
/// not the wire.
///
/// The shared invariants are still enforced: the response status must be
/// `Ok`, the two key fields must be non-empty, the echoed `nonce` must
/// match the contact's, and the contact itself must be structurally
/// consistent with [`ContactMode::NoKeys`] (no inline keys, no binding
/// hash).
///
/// # Arguments
///
/// * `contact_message` — The original [`ContactMode::NoKeys`] contact
///   the scanner is pairing against. Used for the `contact_mode`
///   invariant check and the `nonce` correlation.
/// * `response` — Decoded [`PrePairResponseMessage`] as returned by
///   [`extract_pre_pair`].
///
/// # Errors
///
/// - [`PairingError::NonOkStatus`] on a non-`Ok` status (surface as
///   `PrePairRejected` on the caller side).
/// - [`PairingError::InvalidPairResponseMessage`] if either published
///   key field is empty.
/// - [`PairingError::InvalidContactMessage`] if the contact's declared
///   mode is not [`ContactMode::NoKeys`] or the shape is invalid.
/// - [`PairingError::ProtocolViolation`] on a `nonce` mismatch.
#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = contact_message.channel_id))
)]
pub fn process_pre_pair_no_keys(
    contact_message: &ContactMessage,
    response: &PrePairResponseMessage,
) -> Result<ProcessPrePairResult, crate::Error> {
    validate_process_pre_pair_inputs(contact_message, response, ContactMode::NoKeys)?;

    let mlkem_encapsulation_key = response
        .mlkem_encapsulation_key
        .clone()
        .expect("validate_process_pre_pair_inputs guarantees mlkem_encapsulation_key is Some");
    let ecies_public_key = response
        .ecies_public_key
        .clone()
        .expect("validate_process_pre_pair_inputs guarantees ecies_public_key is Some");

    #[cfg(feature = "logging")]
    tracing::info!("NoKeys PrePair response accepted without hash verification");

    Ok(ProcessPrePairResult {
        mlkem_encapsulation_key,
        ecies_public_key,
        nonce: response.nonce,
    })
}

fn validate_produce_inputs(request: &PairRequestMessage) -> Result<(), crate::Error> {
    if request.mlkem_ciphertext.is_empty() {
        #[cfg(feature = "logging")]
        tracing::warn!("pair request missing mlkem_ciphertext");

        return Err(PairingError::InvalidPairRequestMessage("mlkem_ciphertext is empty").into());
    }

    if request.ecies_public_key.is_empty() {
        #[cfg(feature = "logging")]
        tracing::warn!("pair request missing ecies_public_key");

        return Err(PairingError::InvalidPairRequestMessage("ecies_public_key is empty").into());
    }

    Ok(())
}

fn extract_peer_transport_protocol(
    request: &PairRequestMessage,
) -> Result<TransportProtocol, crate::Error> {
    let peer_transport_protocol = request
        .transport_protocol
        .clone()
        .ok_or(PairingError::EmptyTransportUri)?;

    if peer_transport_protocol.uri.trim().is_empty() {
        #[cfg(feature = "logging")]
        tracing::warn!("peer transport URI is empty");

        return Err(PairingError::EmptyTransportUri.into());
    }

    let _ = crate::transport::TransportProtocol::try_from(&peer_transport_protocol)?;

    Ok(peer_transport_protocol)
}

fn validate_process_inputs<'a>(
    contact_message: &ContactMessage,
    response: &PairResponseMessage,
    pairing_secret_key_material: &'a PairingSecretKeyMaterial,
) -> Result<&'a cryptography_pairing::ResponderSecretKeyMaterial, crate::Error> {
    let res = response
        .result
        .as_ref()
        .ok_or(PairingError::InvalidPairResponseMessage("missing result"))?;

    if res.status != StatusEnum::Ok as i32 {
        #[cfg(feature = "logging")]
        tracing::warn!(status = res.status, memo = %res.memo, "pair response status is not Ok");

        return Err(PairingError::NonOkStatus {
            status: res.status,
            memo: res.memo.to_owned(),
        }
        .into());
    }

    let mlkem_present = contact_message
        .mlkem_encapsulation_key
        .as_ref()
        .is_some_and(|v| !v.is_empty());
    if !mlkem_present {
        #[cfg(feature = "logging")]
        tracing::warn!("contact message missing mlkem_encapsulation_key");
        return Err(PairingError::InvalidContactMessage("mlkem_encapsulation_key is empty").into());
    }

    let ecies_present = contact_message
        .ecies_public_key
        .as_ref()
        .is_some_and(|v| !v.is_empty());
    if !ecies_present {
        #[cfg(feature = "logging")]
        tracing::warn!("contact message missing ecies_public_key");
        return Err(PairingError::InvalidContactMessage("ecies_public_key is empty").into());
    }

    if response.nonce != contact_message.nonce {
        #[cfg(feature = "logging")]
        tracing::warn!("nonce mismatch; possible replay or wrong pairing session");
        return Err(PairingError::ProtocolViolation("nonce mismatch").into());
    }

    match pairing_secret_key_material {
        PairingSecretKeyMaterial::Responder(m) => Ok(m),
        PairingSecretKeyMaterial::Initiator(_) => Err(PairingError::Invariant(
            "expected Responder key material for pairing process",
        )
        .into()),
    }
}

fn build_pairing_contact_material(
    contact_message: &ContactMessage,
) -> cryptography_pairing::PairingContactMessageMaterial {
    let mlkem_encapsulation_key = contact_message
        .mlkem_encapsulation_key
        .as_ref()
        .expect("validate_process_inputs guarantees mlkem_encapsulation_key is Some")
        .clone();
    let ecies_public_key = contact_message
        .ecies_public_key
        .as_ref()
        .expect("validate_process_inputs guarantees ecies_public_key is Some")
        .clone();
    cryptography_pairing::PairingContactMessageMaterial {
        mlkem_encapsulation_key,
        ecies_public_key,
    }
}

fn validate_rekeyed_channel_id(
    response: &PairResponseMessage,
    original_channel_id: ChannelId,
    shared_key: &PairingSharedKey,
) -> Result<ChannelId, crate::Error> {
    let expected_channel_id = derive_rekeyed_channel_id(original_channel_id, shared_key);
    if response.channel_id != u64::from(expected_channel_id) {
        #[cfg(feature = "logging")]
        tracing::warn!(
            advertised = response.channel_id,
            expected = u64::from(expected_channel_id),
            "channel id rekey mismatch"
        );
        return Err(PairingError::ProtocolViolation("channel_id rekey mismatch").into());
    }
    Ok(expected_channel_id)
}

fn validate_process_pre_pair_inputs(
    contact_message: &ContactMessage,
    response: &PrePairResponseMessage,
    expected_mode: ContactMode,
) -> Result<(), crate::Error> {
    let res = response
        .result
        .as_ref()
        .ok_or(PairingError::InvalidPairResponseMessage("missing result"))?;

    if res.status != StatusEnum::Ok as i32 {
        #[cfg(feature = "logging")]
        tracing::warn!(
            status = res.status,
            memo = %res.memo,
            "PrePair response status is not Ok"
        );

        return Err(PairingError::NonOkStatus {
            status: res.status,
            memo: res.memo.to_owned(),
        }
        .into());
    }

    // Shape + mode invariants for the contact. Catches an attacker who
    // tampered with `contact_mode` between the out-of-band exchange and
    // this validation point, and rejects malformed contacts that carry
    // both inline keys and a binding hash.
    super::validate_contact_for_mode(contact_message, expected_mode)?;

    let mlkem_present = response
        .mlkem_encapsulation_key
        .as_ref()
        .is_some_and(|v| !v.is_empty());
    if !mlkem_present {
        #[cfg(feature = "logging")]
        tracing::warn!("PrePair response missing mlkem_encapsulation_key");
        return Err(
            PairingError::InvalidPairResponseMessage("mlkem_encapsulation_key is empty").into(),
        );
    }

    let ecies_present = response
        .ecies_public_key
        .as_ref()
        .is_some_and(|v| !v.is_empty());
    if !ecies_present {
        #[cfg(feature = "logging")]
        tracing::warn!("PrePair response missing ecies_public_key");
        return Err(PairingError::InvalidPairResponseMessage("ecies_public_key is empty").into());
    }

    if response.nonce != contact_message.nonce {
        #[cfg(feature = "logging")]
        tracing::warn!("nonce mismatch; possible replay or wrong pairing session");
        return Err(PairingError::ProtocolViolation("nonce mismatch").into());
    }

    Ok(())
}

fn derive_rekeyed_channel_id(
    original_channel_id: ChannelId,
    shared_key: &PairingSharedKey,
) -> ChannelId {
    let mut hasher = Sha384::new();
    hasher.update(u64::from(original_channel_id).to_be_bytes());
    hasher.update(shared_key.as_slice());
    let digest = hasher.finalize();
    let prefix: [u8; 8] = digest[..8]
        .try_into()
        .expect("SHA-384 digest has at least 8 bytes");
    ChannelId(u64::from_be_bytes(prefix))
}

fn validate_contact_binding_hash(
    contact_message: &ContactMessage,
    response: &PrePairResponseMessage,
) -> Result<(Vec<u8>, Vec<u8>), crate::Error> {
    let mlkem_encapsulation_key = response
        .mlkem_encapsulation_key
        .clone()
        .expect("validate_process_pre_pair_inputs guarantees mlkem_encapsulation_key is Some");
    let ecies_public_key = response
        .ecies_public_key
        .clone()
        .expect("validate_process_pre_pair_inputs guarantees ecies_public_key is Some");
    let expected_hash = contact_message
        .contact_binding_hash
        .as_ref()
        .expect("validate_process_pre_pair_inputs guarantees contact_binding_hash is Some");

    let recomputed = derec_cryptography::pairing::contact_binding_hash(
        &mlkem_encapsulation_key,
        &ecies_public_key,
        contact_message.nonce,
        contact_message.channel_id,
    );

    let matched: bool = recomputed.as_slice().ct_eq(expected_hash.as_slice()).into();
    if !matched {
        #[cfg(feature = "logging")]
        tracing::warn!(
            "contact binding hash mismatch; published keys do not match the contact commitment"
        );
        return Err(PairingError::PrePairHashMismatch.into());
    }

    Ok((mlkem_encapsulation_key, ecies_public_key))
}