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
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

use super::super::{
    DeRecChannelStore, DeRecEvent, DeRecSecretStore, DeRecTransport, PairingKeyMaterial,
    PendingAction, SecretKind, SecretValue, now_secs,
};
use crate::{
    Error, Result,
    derec_message::{DeRecMessageBuilder, current_timestamp},
    primitives::pairing::{PairingError, request, response},
    protocol::reserved_keys,
    types::ChannelId,
    utils::{ContactMessageExt as _, SenderKindExt as _},
};
use derec_cryptography::pairing::PairingSecretKeyMaterial;
use derec_proto::{
    CommunicationInfo, ContactMessage, ContactMode, DeRecResult, MessageBody, PairRequestMessage,
    PairResponseMessage, PrePairRequestMessage, PrePairResponseMessage, SenderKind, StatusEnum,
    TransportProtocol,
};
use prost::Message;
use std::collections::HashMap;

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = channel_id.0))
)]
#[allow(clippy::too_many_arguments)]
pub(in crate::protocol) async fn handle<
    Ch: DeRecChannelStore,
    Ss: DeRecSecretStore,
    T: DeRecTransport,
>(
    channel_store: &mut Ch,
    secret_store: &mut Ss,
    transport: &T,
    communication_info: &HashMap<String, String>,
    message: &MessageBody,
    secret_id: u64,
    channel_id: ChannelId,
    pairing_secret: &PairingSecretKeyMaterial,
    inbound_trace_id: u64,
    replica_id: Option<u64>,
    parameter_range: Option<&derec_proto::ParameterRange>,
) -> Result<Vec<DeRecEvent>> {
    match message {
        MessageBody::PairRequest(request) => {
            if let Err(err) = crate::primitives::pairing::parameter_range::check_compatibility(
                parameter_range,
                request.parameter_range.as_ref(),
            ) {
                reject(
                    secret_store,
                    transport,
                    communication_info,
                    secret_id,
                    channel_id,
                    request,
                    StatusEnum::IncompatibleParameterRange,
                    &err.to_string(),
                    inbound_trace_id,
                )
                .await?;
                return Err(err.into());
            }
            on_request(channel_id, request, inbound_trace_id, replica_id)
        }
        MessageBody::PairResponse(response) => {
            on_response(
                channel_store,
                secret_store,
                secret_id,
                channel_id,
                response,
                pairing_secret,
                replica_id,
                parameter_range,
            )
            .await
        }
        MessageBody::PrePairRequest(request) => {
            on_pre_pair_request(channel_id, request, inbound_trace_id)
        }
        _ => Err(Error::Invariant(
            "unexpected MessageBody variant in pairing message",
        )),
    }
}

/// Scanner-side entry point for the pairing flow. Branches on
/// `contact.contact_mode` to either send a regular [`PairRequest`]
/// ([`ContactMode::InlineKeys`]) or kick off the PrePair leg first
/// ([`ContactMode::HashedKeys`]).
#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = contact.channel_id))
)]
#[allow(clippy::too_many_arguments)]
pub(in crate::protocol) async fn start<
    Ch: DeRecChannelStore,
    Ss: DeRecSecretStore,
    T: DeRecTransport,
>(
    channel_store: &mut Ch,
    secret_store: &mut Ss,
    transport: &T,
    own_transport: &TransportProtocol,
    communication_info: &HashMap<String, String>,
    secret_id: u64,
    kind: SenderKind,
    contact: ContactMessage,
    peer_communication_info: HashMap<String, String>,
    replica_id: Option<u64>,
    parameter_range: Option<derec_proto::ParameterRange>,
) -> Result<u64> {
    let replica_id_to_inject = require_replica_id_for_kind(kind, replica_id)?;

    let channel_id = ChannelId(contact.channel_id);

    let endpoint = contact
        .transport_protocol
        .clone()
        .ok_or(Error::InvalidInput(
            "contact message has no transport endpoint",
        ))?;
    let _ = crate::transport::TransportProtocol::try_from(&endpoint)?;

    if contact.requires_pre_pair() {
        start_pre_pair(
            channel_store,
            secret_store,
            transport,
            own_transport,
            secret_id,
            channel_id,
            contact,
            peer_communication_info,
            endpoint,
            kind,
        )
        .await
    } else {
        start_inlined_keys(
            channel_store,
            secret_store,
            transport,
            own_transport,
            communication_info,
            secret_id,
            channel_id,
            contact,
            peer_communication_info,
            endpoint,
            kind,
            replica_id_to_inject,
            parameter_range,
        )
        .await
    }
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = channel_id.0))
)]
#[allow(clippy::too_many_arguments)]
pub(in crate::protocol) async fn accept<
    Ch: DeRecChannelStore,
    Ss: DeRecSecretStore,
    T: DeRecTransport,
>(
    channel_store: &mut Ch,
    secret_store: &mut Ss,
    transport: &T,
    communication_info: &HashMap<String, String>,
    secret_id: u64,
    channel_id: ChannelId,
    request: &PairRequestMessage,
    kind: SenderKind,
    trace_id: u64,
    replica_id: Option<u64>,
    parameter_range: Option<derec_proto::ParameterRange>,
) -> Result<Vec<DeRecEvent>> {
    let replica_id_to_inject = require_replica_id_for_kind(kind, replica_id)?;

    let Some(SecretValue::PairingSecret(pairing_secret)) = secret_store
        .load(secret_id, channel_id, SecretKind::PairingSecret)
        .await?
    else {
        return Err(Error::Invariant(
            "Pair accept: missing PairingSecret (initiator state lost)",
        ));
    };
    let pairing_secret = pairing_secret.to_secret()?;

    let comm_info = build_communication_info(communication_info, replica_id_to_inject);
    let resp = response::produce(
        channel_id,
        request,
        &pairing_secret,
        comm_info,
        parameter_range,
    )?;
    // Long-term id both peers atomically switch to. `channel_id` is the
    // transient pairing id from the ContactMessage and remains only as
    // the envelope route for the outgoing PairResponse.
    let new_channel_id = resp.channel_id;

    secret_store
        .save(
            secret_id,
            new_channel_id,
            SecretValue::SharedKey(resp.shared_key),
        )
        .await?;

    let peer_transport = resp.peer_transport_protocol.clone();

    let status = if kind.is_replica() {
        crate::protocol::types::ChannelStatus::Pending
    } else {
        crate::protocol::types::ChannelStatus::Paired
    };

    let peer_sender_kind = request_sender_kind(request)?;
    let (peer_communication_info, peer_replica_id) =
        extract_communication_info(&request.communication_info, peer_sender_kind)?;

    channel_store
        .save(
            secret_id,
            crate::protocol::types::Channel {
                id: new_channel_id,
                transport: peer_transport,
                communication_info: peer_communication_info.clone(),
                status,
                created_at: now_secs(),
                role: kind,
                replica_id: peer_replica_id,
            },
        )
        .await?;

    // Send on the transient id — the peer still routes on it and will
    // rotate to `new_channel_id` on receipt.
    let envelope = super::apply_trace_id(resp.envelope, trace_id)?;
    transport
        .send(&resp.peer_transport_protocol, envelope)
        .await?;

    // Drop the transient channel state after the wire message is out.
    // Any inbound message routed to `channel_id` from this point is
    // rejected as unknown.
    secret_store
        .remove(secret_id, channel_id, SecretKind::PairingSecret)
        .await?;
    channel_store.remove(secret_id, channel_id).await?;

    #[cfg(feature = "logging")]
    tracing::info!(
        old_channel_id = channel_id.0,
        new_channel_id = new_channel_id.0,
        "pairing complete (responder side); rotated to long-term channel_id"
    );

    Ok(pair_completion_events(
        new_channel_id,
        channel_id,
        kind,
        peer_communication_info,
        peer_replica_id,
    ))
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = channel_id.0))
)]
#[allow(clippy::too_many_arguments)]
pub(in crate::protocol) async fn reject<Ss: DeRecSecretStore, T: DeRecTransport>(
    secret_store: &mut Ss,
    transport: &T,
    _communication_info: &HashMap<String, String>,
    secret_id: u64,
    channel_id: ChannelId,
    request: &PairRequestMessage,
    status: StatusEnum,
    memo: &str,
    trace_id: u64,
) -> Result<()> {
    let peer_transport_protocol = request
        .transport_protocol
        .clone()
        .ok_or(Error::InvalidInput(
            "pair request missing transport endpoint",
        ))?;
    let _ = crate::transport::TransportProtocol::try_from(&peer_transport_protocol)?;

    let timestamp = current_timestamp();

    let response = PairResponseMessage {
        result: Some(DeRecResult {
            status: status as i32,
            memo: memo.to_owned(),
        }),
        nonce: request.nonce,
        communication_info: None,
        parameter_range: None,
        timestamp: Some(timestamp),
        channel_id: 0,
    };

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

    transport.send(&peer_transport_protocol, envelope).await?;

    secret_store
        .remove(secret_id, channel_id, SecretKind::PairingSecret)
        .await?;

    #[cfg(feature = "logging")]
    tracing::info!("pairing request rejected");

    Ok(())
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = channel_id.0))
)]
fn on_request(
    channel_id: ChannelId,
    request: &PairRequestMessage,
    trace_id: u64,
    replica_id: Option<u64>,
) -> Result<Vec<DeRecEvent>> {
    let peer_kind = request_sender_kind(request)?;

    let (peer_communication_info, _peer_replica_id) =
        extract_communication_info(&request.communication_info, peer_kind)?;

    let kind = peer_kind.derive_peer();
    let _ = require_replica_id_for_kind(kind, replica_id)?;

    let action = PendingAction::Pairing {
        channel_id,
        request: request.clone(),
        kind,
        peer_communication_info,
        trace_id,
    };

    Ok(vec![DeRecEvent::ActionRequired { channel_id, action }])
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(channel_id = channel_id.0))
)]
#[allow(clippy::too_many_arguments)]
async fn on_response<Ch: DeRecChannelStore, Ss: DeRecSecretStore>(
    channel_store: &mut Ch,
    secret_store: &mut Ss,
    secret_id: u64,
    channel_id: ChannelId,
    response: &derec_proto::PairResponseMessage,
    pairing_secret: &PairingSecretKeyMaterial,
    replica_id: Option<u64>,
    parameter_range: Option<&derec_proto::ParameterRange>,
) -> Result<Vec<DeRecEvent>> {
    crate::primitives::pairing::parameter_range::check_compatibility(
        parameter_range,
        response.parameter_range.as_ref(),
    )?;

    let contact = match secret_store
        .load(secret_id, channel_id, SecretKind::PairingContact)
        .await?
    {
        Some(SecretValue::PairingContact(c)) => c,
        _ => {
            return Err(Error::InvalidInput(
                "no pairing contact stored for channel — start must be called first",
            ));
        }
    };

    let result = response::process(&contact, response, pairing_secret)?;
    // Long-term id the peer already rotated to on its side; both peers
    // derive it independently from `original_channel_id || shared_key`.
    // `channel_id` remains only as the (already-consumed) envelope route.
    let new_channel_id = result.channel_id;

    let channel = channel_store
        .load(secret_id, channel_id)
        .await?
        .ok_or(Error::Invariant(
            "channel record missing on pair response — start must be called first",
        ))?;
    let kind = channel.role;

    let status = if kind.is_replica() {
        crate::protocol::types::ChannelStatus::Pending
    } else {
        crate::protocol::types::ChannelStatus::Paired
    };

    let peer_kind = kind.derive_peer();
    let _ = require_replica_id_for_kind(kind, replica_id)?;
    let (peer_communication_info, peer_replica_id) =
        extract_communication_info(&response.communication_info, peer_kind)?;

    let mut channel = channel;
    channel.id = new_channel_id;
    channel.status = status;
    channel.replica_id = peer_replica_id;
    for (k, v) in &peer_communication_info {
        channel.communication_info.insert(k.clone(), v.clone());
    }
    channel_store.save(secret_id, channel).await?;

    secret_store
        .save(
            secret_id,
            new_channel_id,
            SecretValue::SharedKey(result.shared_key),
        )
        .await?;

    // Drop the transient channel's records after the long-term ones are
    // in place. Any inbound message routed to `channel_id` from this
    // point is rejected as unknown.
    channel_store.remove(secret_id, channel_id).await?;
    secret_store
        .remove(secret_id, channel_id, SecretKind::PairingSecret)
        .await?;
    secret_store
        .remove(secret_id, channel_id, SecretKind::PairingContact)
        .await?;

    #[cfg(feature = "logging")]
    tracing::info!(
        old_channel_id = channel_id.0,
        new_channel_id = new_channel_id.0,
        "pairing complete (initiator side); rotated to long-term channel_id"
    );

    Ok(pair_completion_events(
        new_channel_id,
        channel_id,
        kind,
        peer_communication_info,
        peer_replica_id,
    ))
}

/// Inbound `PrePairResponse` on the **scanner side**. Validates the
/// published keys against the stored contact's `contact_binding_hash`,
/// synthesizes a filled-in `InlineKeys`-shaped contact, and auto-proceeds
/// to a regular `PairRequest`.
///
/// PrePair success is invisible to the application on this side — the
/// next event the app sees is `PairingCompleted` once the PairResponse
/// round-trip lands. Failure surfaces as either a [`PrePairRejected`]
/// event (non-Ok status on the response) or a
/// [`crate::primitives::pairing::PairingError::PrePairHashMismatch`]
/// error (binding-hash mismatch).
#[allow(clippy::too_many_arguments)]
pub(in crate::protocol) async fn on_pre_pair_response<
    Ch: DeRecChannelStore,
    Ss: DeRecSecretStore,
    T: DeRecTransport,
>(
    channel_store: &mut Ch,
    secret_store: &mut Ss,
    transport: &T,
    own_transport: &TransportProtocol,
    communication_info: &HashMap<String, String>,
    secret_id: u64,
    channel_id: ChannelId,
    original_contact: &ContactMessage,
    response: &PrePairResponseMessage,
    replica_id: Option<u64>,
    parameter_range: Option<derec_proto::ParameterRange>,
) -> Result<Vec<DeRecEvent>> {
    let processed = if original_contact.contact_mode == ContactMode::NoKeys as i32 {
        response::process_pre_pair_no_keys(original_contact, response)
    } else {
        response::process_pre_pair(original_contact, response)
    };
    let validated = match processed {
        Ok(v) => v,
        Err(Error::Pairing(crate::primitives::pairing::PairingError::NonOkStatus {
            status,
            memo,
        })) => {
            #[cfg(feature = "logging")]
            tracing::warn!(
                channel_id = channel_id.0,
                status,
                memo = %memo,
                "PrePair rejected by initiator"
            );

            return Ok(vec![DeRecEvent::PrePairRejected {
                channel_id,
                status,
                memo,
            }]);
        }
        Err(e) => return Err(e),
    };

    let filled_in_contact = ContactMessage {
        mlkem_encapsulation_key: Some(validated.mlkem_encapsulation_key),
        ecies_public_key: Some(validated.ecies_public_key),
        contact_mode: ContactMode::InlineKeys as i32,
        contact_binding_hash: None,
        ..original_contact.clone()
    };

    let role = channel_store
        .load(secret_id, channel_id)
        .await?
        .ok_or(Error::Invariant(
            "channel record missing on PrePair response — start must be called first",
        ))?
        .role;

    let replica_id_to_inject = require_replica_id_for_kind(role, replica_id)?;
    let comm_info = build_communication_info(communication_info, replica_id_to_inject);
    let result = request::produce(
        role,
        own_transport.clone(),
        &filled_in_contact,
        comm_info,
        parameter_range,
    )?;

    // Persist the scanner's pairing secret + overwrite the stored
    // contact with the filled-in version. `pair_response::process`
    // later reads back the InlineKeys-shaped contact to verify keys.
    secret_store
        .save(
            secret_id,
            channel_id,
            SecretValue::PairingSecret(PairingKeyMaterial::from_secret(&result.secret_key)),
        )
        .await?;
    secret_store
        .save(
            secret_id,
            channel_id,
            SecretValue::PairingContact(result.initiator_contact_message),
        )
        .await?;

    let endpoint = original_contact
        .transport_protocol
        .clone()
        .ok_or(Error::Invariant(
            "stored contact missing transport_protocol on PrePair response",
        ))?;
    let envelope = super::apply_trace_id(result.envelope, super::fresh_trace_id())?;
    transport.send(&endpoint, envelope).await?;

    #[cfg(feature = "logging")]
    tracing::info!(
        channel_id = channel_id.0,
        "PrePair validated; PairRequest sent (HASHED_KEYS scanner side)"
    );

    Ok(vec![])
}

/// `accept` arm for [`PendingAction::PrePair`]. Branches on the stored
/// contact's mode:
///
/// - `HashedKeys`: loads the previously-generated `PairingSecret` and
///   publishes its keys (the scanner will match them against the
///   contact's binding hash).
/// - `NoKeys`: no `PairingSecret` exists yet — the contact was created
///   without any key material. Generates fresh key material on the fly,
///   persists it as `PairingSecret`, and publishes the keys. First
///   authenticates the request by matching `request.nonce` against the
///   stored contact's `nonce`.
pub(in crate::protocol) async fn accept_pre_pair<Ss: DeRecSecretStore, T: DeRecTransport>(
    secret_store: &mut Ss,
    transport: &T,
    secret_id: u64,
    channel_id: ChannelId,
    request: &PrePairRequestMessage,
    trace_id: u64,
) -> Result<Vec<DeRecEvent>> {
    // NoKeys: no PairingSecret exists at accept time. Load the stored
    // contact, verify the incoming nonce, and generate keys on the fly.
    if let Some(SecretValue::PairingContact(contact)) = secret_store
        .load(secret_id, channel_id, SecretKind::PairingContact)
        .await?
        && contact.contact_mode == ContactMode::NoKeys as i32
    {
        if request.nonce != contact.nonce {
            #[cfg(feature = "logging")]
            tracing::warn!(
                channel_id = channel_id.0,
                "NoKeys PrePair nonce mismatch — rejecting"
            );
            return Err(crate::primitives::pairing::PairingError::ProtocolViolation(
                "NoKeys PrePair nonce mismatch",
            )
            .into());
        }

        let result = response::produce_pre_pair_no_keys(channel_id, request)?;
        secret_store
            .save(
                secret_id,
                channel_id,
                SecretValue::PairingSecret(PairingKeyMaterial::from_secret(
                    &result.pairing_secret_key_material,
                )),
            )
            .await?;

        let envelope = super::apply_trace_id(result.envelope, trace_id)?;
        let endpoint = request
            .transport_protocol
            .clone()
            .ok_or(Error::InvalidInput(
                "PrePair request missing transport endpoint",
            ))?;
        let _ = crate::transport::TransportProtocol::try_from(&endpoint)?;
        transport.send(&endpoint, envelope).await?;

        #[cfg(feature = "logging")]
        tracing::info!(
            channel_id = channel_id.0,
            "NoKeys PrePair accepted; fresh keys generated and sent to scanner"
        );

        return Ok(vec![]);
    }

    let Some(SecretValue::PairingSecret(pairing_secret)) = secret_store
        .load(secret_id, channel_id, SecretKind::PairingSecret)
        .await?
    else {
        return Err(Error::Invariant(
            "PrePair accept: missing PairingSecret (initiator state lost)",
        ));
    };
    let pairing_secret = pairing_secret.to_secret()?;

    let result = response::produce_pre_pair(channel_id, request, &pairing_secret)?;
    let envelope = super::apply_trace_id(result.envelope, trace_id)?;

    let endpoint = request
        .transport_protocol
        .clone()
        .ok_or(Error::InvalidInput(
            "PrePair request missing transport endpoint",
        ))?;
    let _ = crate::transport::TransportProtocol::try_from(&endpoint)?;
    transport.send(&endpoint, envelope).await?;

    #[cfg(feature = "logging")]
    tracing::info!(
        channel_id = channel_id.0,
        "PrePair accepted; published keys sent to scanner"
    );

    Ok(vec![])
}

/// `reject` arm for [`PendingAction::PrePair`]. Builds a non-Ok
/// `PrePairResponse` (no keys) and sends it to the scanner's `replyTo`.
/// Does NOT load `PairingSecret` — rejection carries no crypto material.
#[allow(clippy::too_many_arguments)]
pub(in crate::protocol) async fn reject_pre_pair<T: DeRecTransport>(
    transport: &T,
    channel_id: ChannelId,
    request: &PrePairRequestMessage,
    status: StatusEnum,
    memo: &str,
    trace_id: u64,
) -> Result<()> {
    let endpoint = request
        .transport_protocol
        .clone()
        .ok_or(Error::InvalidInput(
            "PrePair request missing transport endpoint",
        ))?;
    let _ = crate::transport::TransportProtocol::try_from(&endpoint)?;

    let timestamp = current_timestamp();
    let response = PrePairResponseMessage {
        result: Some(DeRecResult {
            status: status as i32,
            memo: memo.to_owned(),
        }),
        // Non-Ok responses MUST NOT carry keys (per `prepair.proto`).
        mlkem_encapsulation_key: None,
        ecies_public_key: None,
        nonce: request.nonce,
        timestamp: Some(timestamp),
    };

    // PrePair envelopes are plaintext — wrap the inner body directly.
    use crate::protocol_version::ProtocolVersion;
    use derec_proto::DeRecMessage;
    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,
    }
    .encode_to_vec();

    transport.send(&endpoint, envelope).await?;

    #[cfg(feature = "logging")]
    tracing::info!(
        channel_id = channel_id.0,
        status = status as i32,
        "PrePair rejected by initiator"
    );

    Ok(())
}

/// Scanner-side `InlineKeys` branch of [`start`]. The responder has the
/// initiator's public keys inline on the contact, so it can go straight
/// to building the encrypted `PairRequest` envelope.
#[allow(clippy::too_many_arguments)]
async fn start_inlined_keys<Ch: DeRecChannelStore, Ss: DeRecSecretStore, T: DeRecTransport>(
    channel_store: &mut Ch,
    secret_store: &mut Ss,
    transport: &T,
    own_transport: &TransportProtocol,
    communication_info: &HashMap<String, String>,
    secret_id: u64,
    channel_id: ChannelId,
    contact: ContactMessage,
    peer_communication_info: HashMap<String, String>,
    endpoint: TransportProtocol,
    kind: SenderKind,
    replica_id_to_inject: Option<u64>,
    parameter_range: Option<derec_proto::ParameterRange>,
) -> Result<u64> {
    reject_start_on_paired_channel(channel_store, secret_id, channel_id).await?;

    let comm_info = build_communication_info(communication_info, replica_id_to_inject);
    let result = request::produce(
        kind,
        own_transport.clone(),
        &contact,
        comm_info,
        parameter_range,
    )?;

    secret_store
        .save(
            secret_id,
            channel_id,
            SecretValue::PairingSecret(PairingKeyMaterial::from_secret(&result.secret_key)),
        )
        .await?;
    secret_store
        .save(
            secret_id,
            channel_id,
            SecretValue::PairingContact(result.initiator_contact_message),
        )
        .await?;

    channel_store
        .save(
            secret_id,
            crate::protocol::types::Channel {
                id: channel_id,
                transport: endpoint.clone(),
                communication_info: peer_communication_info,
                status: crate::protocol::types::ChannelStatus::Pending,
                created_at: now_secs(),
                role: kind,
                replica_id: None,
            },
        )
        .await?;

    #[cfg(feature = "logging")]
    tracing::info!("pairing request sent");

    let envelope = super::apply_trace_id(result.envelope, super::fresh_trace_id())?;
    transport.send(&endpoint, envelope).await?;

    Ok(channel_id.0)
}

/// Scanner-side `HashedKeys` branch of [`start`]. Saves the original
/// contact via `PairingContact` (we'll re-read it when the
/// `PrePairResponse` arrives to validate the binding hash), sends a
/// plaintext `PrePairRequest`, and leaves the channel `Pending`. No
/// `PairingSecret` is saved yet — the scanner has no responder-side
/// key material until the PrePair leg completes and the regular
/// PairRequest is produced.
#[allow(clippy::too_many_arguments)]
/// Scanner-side entry point shared by `HashedKeys` and `NoKeys`: sends a
/// [`PrePairRequestMessage`] and persists the original contact so
/// `on_pre_pair_response` can later branch on `contact.contact_mode` to
/// decide whether to verify a binding hash (HashedKeys) or skip
/// verification (NoKeys).
async fn start_pre_pair<Ch: DeRecChannelStore, Ss: DeRecSecretStore, T: DeRecTransport>(
    channel_store: &mut Ch,
    secret_store: &mut Ss,
    transport: &T,
    own_transport: &TransportProtocol,
    secret_id: u64,
    channel_id: ChannelId,
    contact: ContactMessage,
    peer_communication_info: HashMap<String, String>,
    endpoint: TransportProtocol,
    kind: SenderKind,
) -> Result<u64> {
    reject_start_on_paired_channel(channel_store, secret_id, channel_id).await?;

    let result = request::produce_pre_pair_request(own_transport.clone(), &contact)?;

    secret_store
        .save(secret_id, channel_id, SecretValue::PairingContact(contact))
        .await?;

    channel_store
        .save(
            secret_id,
            crate::protocol::types::Channel {
                id: channel_id,
                transport: endpoint.clone(),
                communication_info: peer_communication_info,
                status: crate::protocol::types::ChannelStatus::Pending,
                created_at: now_secs(),
                role: kind,
                replica_id: None,
            },
        )
        .await?;

    #[cfg(feature = "logging")]
    tracing::info!("PrePair request sent (scanner side)");

    let envelope = super::apply_trace_id(result.envelope, super::fresh_trace_id())?;
    transport.send(&endpoint, envelope).await?;

    Ok(channel_id.0)
}

/// Inbound `PrePairRequest` on the **initiator side**. Handled either by
/// the party that:
///
/// - created a `HashedKeys` contact and saved its `PairingSecret`, or
/// - created a `NoKeys` contact and saved only its `PairingContact`.
///
/// Pure function — surfaces an [`DeRecEvent::ActionRequired`] event. The
/// application decides whether to accept (publish the keys — for NoKeys
/// keys are generated on the fly at accept time) or reject (refuse to
/// participate) by calling [`super::super::DeRecProtocol::accept`] or
/// [`super::super::DeRecProtocol::reject`] with the carried
/// [`PendingAction::PrePair`].
pub(in crate::protocol) fn handle_pre_pair_request(
    message: &MessageBody,
    channel_id: ChannelId,
    trace_id: u64,
) -> Result<Vec<DeRecEvent>> {
    let MessageBody::PrePairRequest(request) = message else {
        return Err(Error::Invariant(
            "handle_pre_pair_request called with non-PrePairRequest MessageBody",
        ));
    };
    on_pre_pair_request(channel_id, request, trace_id)
}

fn on_pre_pair_request(
    channel_id: ChannelId,
    request: &PrePairRequestMessage,
    trace_id: u64,
) -> Result<Vec<DeRecEvent>> {
    Ok(vec![DeRecEvent::ActionRequired {
        channel_id,
        action: PendingAction::PrePair {
            channel_id,
            request: request.clone(),
            trace_id,
        },
    }])
}

/// Build a `CommunicationInfo` proto from the app's free-form key-value
/// map, optionally injecting the reserved `derec.replica_id` entry.
///
/// Callers pass `Some(id)` when the **local** kind on this pairing is
/// `Replica` (and the protocol was built with `with_replica_id`), `None`
/// otherwise. The orchestrator-level gate at `start`/`accept`/`process`
/// entry refuses replica-mode pairings before reaching this helper, so by
/// the time we get here `replica_id` being `None` always means "no
/// injection needed."
///
/// Any entry the app supplied under the reserved `derec.*` namespace is
/// **silently dropped** before serialization — the namespace is owned by
/// the library, not application territory.
fn build_communication_info(
    info: &HashMap<String, String>,
    replica_id_to_inject: Option<u64>,
) -> Option<CommunicationInfo> {
    let mut entries: Vec<_> = info
        .iter()
        .filter(|(k, _)| !is_reserved_key(k))
        .filter(|(_, v)| !v.trim().is_empty())
        .map(|(k, v)| derec_proto::CommunicationInfoKeyValue {
            key: k.to_owned(),
            value: Some(
                derec_proto::communication_info_key_value::Value::StringValue(v.to_owned()),
            ),
        })
        .collect();

    if let Some(id) = replica_id_to_inject {
        entries.push(derec_proto::CommunicationInfoKeyValue {
            key: reserved_keys::DEREC_REPLICA_ID_KEY.to_owned(),
            value: Some(
                derec_proto::communication_info_key_value::Value::StringValue(
                    reserved_keys::encode_replica_id(id),
                ),
            ),
        });
    }

    if entries.is_empty() {
        return None;
    }

    Some(CommunicationInfo {
        communication_info_entries: entries,
    })
}

/// Extract the app-level free-form `CommunicationInfo` into a flat map AND
/// pull the reserved `derec.replica_id` entry out as a typed `Option<u64>`.
///
/// The reserved key is **stripped from the returned map** so apps can't
/// accidentally observe it (or, in subsequent broadcasts, re-transmit it).
///
/// Validation against `peer_kind` (via [`SenderKindExt::is_replica`]):
/// - replica kinds (`ReplicaSource`, `ReplicaDestination`): the reserved
///   key MUST be present and parse as a valid hex `u64` (error:
///   [`PairingError::MissingReplicaId`] or [`Error::InvalidInput`]).
/// - non-replica kinds (`Owner`, `Helper`): the reserved key MUST NOT be
///   present (error: [`PairingError::UnexpectedReplicaId`]). Non-replica
///   pairings have no business carrying replica identity.
fn extract_communication_info(
    info: &Option<CommunicationInfo>,
    peer_kind: SenderKind,
) -> Result<(HashMap<String, String>, Option<u64>)> {
    let Some(info) = info.as_ref() else {
        // No comm_info means no reserved entries either; replica pairings
        // are rejected up-front by the missing-id check below.
        if peer_kind.is_replica() {
            return Err(PairingError::MissingReplicaId {
                sender_kind: peer_kind,
            }
            .into());
        }
        return Ok((HashMap::new(), None));
    };

    let mut free_form: HashMap<String, String> = HashMap::new();
    let mut peer_replica_id: Option<u64> = None;

    for e in &info.communication_info_entries {
        let Some(derec_proto::communication_info_key_value::Value::StringValue(s)) = &e.value
        else {
            continue;
        };
        let trimmed = s.trim();
        if trimmed.is_empty() {
            continue;
        }

        if e.key == reserved_keys::DEREC_REPLICA_ID_KEY {
            peer_replica_id = Some(reserved_keys::decode_replica_id(trimmed)?);
            continue;
        }
        if is_reserved_key(&e.key) {
            // The library owns the `derec.*` namespace. `derec.replica_id`
            // is the only recognized entry today; any other `derec.*` key
            // is foreign and silently dropped so peers can't smuggle
            // application-scoped keys through the reserved prefix.
            continue;
        }
        free_form.insert(e.key.to_owned(), trimmed.to_owned());
    }

    match (peer_kind.is_replica(), peer_replica_id.is_some()) {
        (true, false) => Err(PairingError::MissingReplicaId {
            sender_kind: peer_kind,
        }
        .into()),
        (false, true) => Err(PairingError::UnexpectedReplicaId {
            sender_kind: peer_kind,
        }
        .into()),
        _ => Ok((free_form, peer_replica_id)),
    }
}

/// `true` for any key in the reserved `derec.*` namespace (library-owned).
/// Apps that set such keys themselves are silently overridden.
fn is_reserved_key(key: &str) -> bool {
    key.starts_with("derec.")
}

/// Build the event stream a pair-handshake-completing handler returns.
///
/// Always emits `PairingCompleted` (the universal "handshake done" signal,
/// observed by every kind of pairing). For replica pairings, also emits
/// `ReplicaPaired` carrying the peer's replica id. The local side's role
/// (Source / Destination) is already on the saved `Channel.role`, so
/// the event doesn't repeat it.
///
/// `peer_replica_id.is_some()` and [`SenderKindExt::is_replica`] are equivalent at
/// this point — [`extract_communication_info`] rejects inconsistent
/// combinations upstream — so we branch on the `Option` directly and
/// emit `ReplicaPaired` iff a peer id is present.
fn pair_completion_events(
    channel_id: ChannelId,
    pairing_channel_id: ChannelId,
    kind: SenderKind,
    peer_communication_info: HashMap<String, String>,
    peer_replica_id: Option<u64>,
) -> Vec<DeRecEvent> {
    let mut events = vec![DeRecEvent::PairingCompleted {
        channel_id,
        pairing_channel_id,
        kind,
        peer_communication_info,
    }];
    if let Some(peer_replica_id) = peer_replica_id {
        events.push(DeRecEvent::ReplicaPaired {
            channel_id,
            peer_replica_id,
        });
    }
    events
}

/// Gate for replica-mode pairings on the local side.
///
/// Returns `Some(id)` when `kind` is `ReplicaSource` or
/// `ReplicaDestination` (and the protocol was configured with a replica
/// id), `None` for non-replica pairings, or
/// [`Error::ReplicaIdNotConfigured`] when a replica-mode pairing was
/// attempted without local identity. The returned `Option<u64>` is exactly
/// what [`build_communication_info`] expects.
fn require_replica_id_for_kind(
    local_kind: SenderKind,
    configured_replica_id: Option<u64>,
) -> Result<Option<u64>> {
    if !local_kind.is_replica() {
        return Ok(None);
    }
    configured_replica_id
        .map(Some)
        .ok_or(Error::ReplicaIdNotConfigured)
}

/// Parse the `sender_kind` field of an incoming `PairRequestMessage` into
/// the typed [`SenderKind`] enum. The raw field is an `i32` on the wire;
/// unknown values surface as
/// [`PairingError::InvalidPairRequestMessage`].
fn request_sender_kind(request: &PairRequestMessage) -> Result<SenderKind> {
    SenderKind::try_from(request.sender_kind).map_err(|_| {
        PairingError::InvalidPairRequestMessage("unknown sender_kind on PairRequest").into()
    })
}

async fn reject_start_on_paired_channel<Ch: DeRecChannelStore>(
    channel_store: &Ch,
    secret_id: u64,
    channel_id: ChannelId,
) -> Result<()> {
    if let Some(channel) = channel_store.load(secret_id, channel_id).await? {
        if channel.status == crate::protocol::types::ChannelStatus::Paired {
            return Err(Error::ChannelAlreadyPaired { channel_id });
        }
    }
    Ok(())
}

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

    fn entries_of(c: &CommunicationInfo) -> Vec<(String, String)> {
        c.communication_info_entries
            .iter()
            .filter_map(|e| match &e.value {
                Some(derec_proto::communication_info_key_value::Value::StringValue(s)) => {
                    Some((e.key.clone(), s.clone()))
                }
                _ => None,
            })
            .collect()
    }

    #[test]
    fn build_omits_reserved_key_when_no_replica_id_to_inject() {
        let mut info = HashMap::new();
        info.insert("name".to_owned(), "Alice".to_owned());

        let built = build_communication_info(&info, None).expect("entries present");
        let pairs = entries_of(&built);
        assert_eq!(pairs.len(), 1);
        assert_eq!(pairs[0], ("name".to_owned(), "Alice".to_owned()));
    }

    #[test]
    fn build_injects_reserved_key_when_replica_id_supplied() {
        let mut info = HashMap::new();
        info.insert("name".to_owned(), "Alice".to_owned());

        let built = build_communication_info(&info, Some(0xDEAD_BEEFu64)).expect("entries present");
        let pairs = entries_of(&built);

        let replica_entry = pairs
            .iter()
            .find(|(k, _)| k == reserved_keys::DEREC_REPLICA_ID_KEY)
            .expect("derec.replica_id should be injected");
        assert_eq!(replica_entry.1, "3735928559");

        // The app's free-form `name` is preserved alongside the reserved entry.
        assert!(pairs.iter().any(|(k, v)| k == "name" && v == "Alice"));
    }

    #[test]
    fn build_drops_app_supplied_entries_in_reserved_namespace() {
        let mut info = HashMap::new();
        info.insert("name".to_owned(), "Alice".to_owned());
        // App tries to shadow the reserved key — should be silently dropped.
        info.insert(
            reserved_keys::DEREC_REPLICA_ID_KEY.to_owned(),
            "ffffffffffff".to_owned(),
        );
        // App tries any other derec.* key — also dropped (namespace owned).
        info.insert("derec.foo".to_owned(), "bar".to_owned());

        let built = build_communication_info(&info, Some(1)).expect("entries present");
        let pairs = entries_of(&built);

        // Only the LIBRARY-injected derec.replica_id and the free-form `name`.
        assert_eq!(pairs.len(), 2);
        let replica_entry = pairs
            .iter()
            .find(|(k, _)| k == reserved_keys::DEREC_REPLICA_ID_KEY)
            .unwrap();
        assert_eq!(replica_entry.1, "1");
        assert!(!pairs.iter().any(|(k, _)| k == "derec.foo"));
    }

    #[test]
    fn extract_strips_reserved_key_and_returns_typed_id() {
        let info = Some(CommunicationInfo {
            communication_info_entries: vec![
                derec_proto::CommunicationInfoKeyValue {
                    key: "name".to_owned(),
                    value: Some(
                        derec_proto::communication_info_key_value::Value::StringValue(
                            "Bob".to_owned(),
                        ),
                    ),
                },
                derec_proto::CommunicationInfoKeyValue {
                    key: reserved_keys::DEREC_REPLICA_ID_KEY.to_owned(),
                    value: Some(
                        derec_proto::communication_info_key_value::Value::StringValue(
                            "3405691582".to_owned(),
                        ),
                    ),
                },
            ],
        });

        let (map, replica_id) =
            extract_communication_info(&info, SenderKind::ReplicaSource).unwrap();
        // Map carries only the free-form entry; reserved key is gone.
        assert_eq!(map.len(), 1);
        assert_eq!(map.get("name").map(String::as_str), Some("Bob"));
        assert!(!map.contains_key(reserved_keys::DEREC_REPLICA_ID_KEY));
        assert_eq!(replica_id, Some(0xCAFE_BABEu64));
    }

    #[test]
    fn extract_rejects_replica_pairing_missing_reserved_key() {
        let info = Some(CommunicationInfo {
            communication_info_entries: vec![derec_proto::CommunicationInfoKeyValue {
                key: "name".to_owned(),
                value: Some(
                    derec_proto::communication_info_key_value::Value::StringValue("Bob".to_owned()),
                ),
            }],
        });

        let err =
            extract_communication_info(&info, SenderKind::ReplicaSource).expect_err("must reject");
        assert!(
            matches!(
                err,
                Error::Pairing(PairingError::MissingReplicaId { sender_kind })
                    if sender_kind == SenderKind::ReplicaSource
            ),
            "expected MissingReplicaId, got {err:?}"
        );
    }

    #[test]
    fn extract_rejects_non_replica_pairing_carrying_reserved_key() {
        let info = Some(CommunicationInfo {
            communication_info_entries: vec![derec_proto::CommunicationInfoKeyValue {
                key: reserved_keys::DEREC_REPLICA_ID_KEY.to_owned(),
                value: Some(
                    derec_proto::communication_info_key_value::Value::StringValue(
                        "12345".to_owned(),
                    ),
                ),
            }],
        });

        // Helper-side extraction of a peer pretending to be Owner with replica id.
        let err = extract_communication_info(&info, SenderKind::Owner).expect_err("must reject");
        assert!(
            matches!(
                err,
                Error::Pairing(PairingError::UnexpectedReplicaId { sender_kind })
                    if sender_kind == SenderKind::Owner
            ),
            "expected UnexpectedReplicaId, got {err:?}"
        );
    }

    #[test]
    fn extract_rejects_replica_pairing_with_no_communication_info() {
        // A replica peer that sent no CommunicationInfo at all — no place to
        // carry the required `derec.replica_id`.
        let err =
            extract_communication_info(&None, SenderKind::ReplicaSource).expect_err("must reject");
        assert!(matches!(
            err,
            Error::Pairing(PairingError::MissingReplicaId { .. })
        ));
    }

    #[test]
    fn extract_accepts_non_replica_pairing_with_no_communication_info() {
        let (map, id) = extract_communication_info(&None, SenderKind::Helper).unwrap();
        assert!(map.is_empty());
        assert_eq!(id, None);
    }

    #[test]
    fn require_replica_id_for_kind_short_circuits_non_replica() {
        assert_eq!(
            require_replica_id_for_kind(SenderKind::Owner, None).unwrap(),
            None
        );
        assert_eq!(
            require_replica_id_for_kind(SenderKind::Helper, Some(123)).unwrap(),
            None,
            "Helper kind ignores configured replica id"
        );
    }

    #[test]
    fn require_replica_id_for_kind_passes_through_for_replica() {
        assert_eq!(
            require_replica_id_for_kind(SenderKind::ReplicaSource, Some(42)).unwrap(),
            Some(42)
        );
    }

    #[test]
    fn require_replica_id_for_kind_errors_when_replica_unconfigured() {
        let err = require_replica_id_for_kind(SenderKind::ReplicaSource, None).unwrap_err();
        assert!(matches!(err, Error::ReplicaIdNotConfigured));
    }

    use crate::protocol::traits::ChannelStoreFuture;
    use crate::protocol::types::{Channel, ChannelStatus};

    /// Single-channel mock that returns whatever record was seeded at
    /// construction. All mutating methods are stubbed because the
    /// helper under test only ever calls `load`.
    struct FixedChannelStore {
        seeded: Option<Channel>,
    }

    impl DeRecChannelStore for FixedChannelStore {
        fn load(&self, _: u64, _: ChannelId) -> ChannelStoreFuture<'_, Option<Channel>> {
            let v = self.seeded.clone();
            Box::pin(std::future::ready(Ok(v)))
        }
        fn save(&mut self, _: u64, _: Channel) -> ChannelStoreFuture<'_, ()> {
            Box::pin(std::future::ready(Ok(())))
        }
        fn remove(&mut self, _: u64, _: ChannelId) -> ChannelStoreFuture<'_, bool> {
            Box::pin(std::future::ready(Ok(false)))
        }
        fn channels(&self, _: u64) -> ChannelStoreFuture<'_, Vec<Channel>> {
            Box::pin(std::future::ready(Ok(Vec::new())))
        }
        fn link_channel(
            &mut self,
            _: u64,
            _: ChannelId,
            _: ChannelId,
        ) -> ChannelStoreFuture<'_, ()> {
            Box::pin(std::future::ready(Ok(())))
        }
        fn linked_channels(
            &self,
            _: u64,
            cid: ChannelId,
        ) -> ChannelStoreFuture<'_, Vec<ChannelId>> {
            Box::pin(std::future::ready(Ok(vec![cid])))
        }
    }

    fn fake_channel(status: ChannelStatus, role: SenderKind) -> Channel {
        Channel {
            id: ChannelId(1),
            transport: TransportProtocol {
                uri: "https://example.com".to_owned(),
                protocol: 0,
            },
            communication_info: HashMap::new(),
            status,
            created_at: 1_700_000_000,
            role,
            replica_id: None,
        }
    }

    /// Spin up a single-threaded tokio runtime and drive an async
    /// closure to completion. Library tests can't use `#[tokio::test]`
    /// because the crate pulls tokio in with `default-features = false,
    /// features = ["rt"]` — no `macros` feature.
    fn run_async<F: std::future::Future<Output = ()>>(f: F) {
        tokio::runtime::Builder::new_current_thread()
            .build()
            .expect("test runtime")
            .block_on(f)
    }

    #[test]
    fn reject_start_on_paired_channel_errors_when_channel_already_paired() {
        run_async(async {
            let store = FixedChannelStore {
                seeded: Some(fake_channel(ChannelStatus::Paired, SenderKind::Helper)),
            };
            let err = reject_start_on_paired_channel(&store, 42, ChannelId(1))
                .await
                .unwrap_err();
            assert!(
                matches!(err, Error::ChannelAlreadyPaired { channel_id } if channel_id == ChannelId(1)),
                "expected Error::ChannelAlreadyPaired for ChannelId(1), got {err:?}"
            );
        });
    }

    /// `Pending` is a legitimate retry state (handshake never finished) —
    /// re-running `start` must be allowed so the caller can resend a
    /// PairRequest with fresh secret material.
    #[test]
    fn reject_start_on_paired_channel_allows_pending_retry() {
        run_async(async {
            let store = FixedChannelStore {
                seeded: Some(fake_channel(ChannelStatus::Pending, SenderKind::Helper)),
            };
            reject_start_on_paired_channel(&store, 42, ChannelId(1))
                .await
                .expect("Pending channel must be accepted as a retry candidate");
        });
    }

    /// First-time pairing — no record exists yet.
    #[test]
    fn reject_start_on_paired_channel_allows_when_no_channel_record() {
        run_async(async {
            let store = FixedChannelStore { seeded: None };
            reject_start_on_paired_channel(&store, 42, ChannelId(1))
                .await
                .expect("absent channel record must be accepted");
        });
    }

    /// Replica `Paired` is also rejected — replica pairings transition
    /// to `Paired` after fingerprint verification, and once they're
    /// there the same overwrite-corruption applies.
    #[test]
    fn reject_start_on_paired_channel_errors_for_paired_replica() {
        run_async(async {
            let store = FixedChannelStore {
                seeded: Some(fake_channel(
                    ChannelStatus::Paired,
                    SenderKind::ReplicaSource,
                )),
            };
            let err = reject_start_on_paired_channel(&store, 42, ChannelId(1))
                .await
                .unwrap_err();
            assert!(matches!(err, Error::ChannelAlreadyPaired { .. }));
        });
    }
}