derec-library 0.1.0

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

//! Pairing handshake: contact → pair request → pair response, plus the
//! PrePair leg used by [`derec_proto::ContactMode::HashedKeys`] contacts.
//!
//! # The two legs
//!
//! [`pair`] is the handshake proper; [`pre_pair`] is the round that fetches
//! key material a contact did not carry. Which one a contact takes is decided
//! by [`handle`] and [`start`] here, not by whoever asked to pair, and the
//! helpers both legs share stay in this module.
//!
//! The legs answer the same questions, so they use the same names —
//! [`pair::accept`] and [`pre_pair::accept`] both accept what arrived on their
//! leg. Callers name the leg they mean rather than reading a suffix.
//!
//! [`handle`] below covers both legs, because a `PrePairRequest` can arrive
//! encrypted like any other body. It is not the only way into [`pre_pair`]:
//! PrePair normally travels in **plaintext**, and that path is dispatched by
//! [`DeRecProtocol::process`](crate::protocol::DeRecProtocol::process) before
//! any decryption is attempted, straight into
//! [`pre_pair::on_request`] and [`pre_pair::on_response`].
//!
//! # Reserved `CommunicationInfo` handling
//!
//! Outbound envelopes carry the local `replica_id` under the reserved
//! `derec.replica_id` key on replica-mode pairings only; any entry the
//! application supplied under the `derec.*` namespace is silently
//! dropped before serialization, since the namespace belongs to the
//! library. Inbound, the reserved entry is pulled out as a typed
//! `Option<u64>` and **stripped from the map handed to the application**
//! so it can neither be observed nor re-transmitted by accident.
//!
//! Presence is validated against the peer's kind:
//!
//! - replica kinds (`ReplicaSource`, `ReplicaDestination`) MUST carry the
//!   key and it MUST parse as a hex `u64` —
//!   [`PairingError::MissingReplicaId`] or [`Error::InvalidInput`]
//!   otherwise.
//! - non-replica kinds (`Owner`, `Helper`) MUST NOT carry it —
//!   [`PairingError::UnexpectedReplicaId`] otherwise. A non-replica
//!   pairing has no business carrying replica identity.
//!
//! Absent `CommunicationInfo` implies no reserved entries; replica
//! pairings are refused up-front by the missing-id check.

use super::super::{
    DeRecChannelStore, DeRecEvent, DeRecSecretStore, IgnoreReason, SecretKind, SecretValue,
    now_secs,
};
use crate::error_codes::classify;
use crate::extensions::advertised_endpoints::AdvertisedEndpoints as _;
use crate::extensions::channel_store::ChannelStoreExt as _;
use crate::extensions::contact_message::ContactMessageExt as _;
use crate::extensions::sender_kind::SenderKindExt as _;
use crate::primitives::pairing::request::check_parameter_range;
use crate::protocol::context::{Local, PairingConfig};
use crate::protocol::stores::{StoreSet, Stores};
use crate::protocol::types::{ChannelQuery, ChannelStatus, ReplicaFilter, ReplicaRole};
use crate::protocol::{PendingActionKind, obligation};
use crate::types::ReplicaId;
use crate::{
    Error, Result, primitives::pairing::PairingError, protocol::utils::reserved_keys,
    types::ChannelId,
};
use derec_cryptography::pairing::PairingSecretKeyMaterial;
use derec_proto::communication_info_key_value::Value;
use derec_proto::{
    CommunicationInfo, CommunicationInfoKeyValue, ContactMessage, MessageBody, PairRequestMessage,
    SenderKind, StatusEnum, TransportProtocol,
};
use prost_types::Timestamp;
use std::collections::HashMap;
use std::time::Duration;

pub(in crate::protocol) mod pair;
pub(in crate::protocol) mod pre_pair;
#[cfg(test)]
mod tests;

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(trace_id = inbound_trace_id, channel_id = channel_id.0))
)]
pub(in crate::protocol) async fn handle<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    pairing: &PairingConfig<'_>,
    message: &MessageBody,
    channel_id: ChannelId,
    pairing_secret: &PairingSecretKeyMaterial,
    inbound_trace_id: u64,
) -> Result<Vec<DeRecEvent>> {
    match message {
        MessageBody::PairRequest(request) => {
            if let Some(events) = ignored_if_expired(
                stores,
                local,
                pairing,
                channel_id,
                request.timestamp.as_ref(),
                inbound_trace_id,
            )
            .await?
            {
                return Ok(events);
            }
            if let Err(err) = check_parameter_range(request, pairing.parameter_range) {
                let memo = parameter_range_memo(&err);
                return refuse(
                    stores,
                    local,
                    channel_id,
                    request,
                    StatusEnum::IncompatibleParameterRange,
                    &memo,
                    &Error::from(err),
                    inbound_trace_id,
                )
                .await;
            }
            // A colliding id is refused before the application is asked to
            // confirm anything: the pairing cannot complete, so surfacing an
            // ActionRequired for it would only waste a user's decision.
            let peer_kind = request_sender_kind(request)?;
            if peer_kind.is_replica() {
                let (_, peer_replica_id) =
                    extract_communication_info(&request.communication_info, peer_kind)?;
                if let Some(peer_replica_id) = peer_replica_id
                    && replica_id_is_taken(stores, local, peer_replica_id).await?
                {
                    return refuse(
                        stores,
                        local,
                        channel_id,
                        request,
                        StatusEnum::ReplicaIdConflict,
                        "replica id already in use by a member of this group",
                        &Error::ReplicaIdConflict {
                            replica_id: peer_replica_id,
                        },
                        inbound_trace_id,
                    )
                    .await;
                }
            }
            pair::on_request(local, channel_id, request, inbound_trace_id)
        }
        MessageBody::PairResponse(response) => {
            pair::on_response(stores, local, pairing, channel_id, response, pairing_secret).await
        }
        MessageBody::PrePairRequest(request) => {
            if let Some(events) = ignored_if_expired(
                stores,
                local,
                pairing,
                channel_id,
                request.timestamp.as_ref(),
                inbound_trace_id,
            )
            .await?
            {
                return Ok(events);
            }
            pre_pair::on_request(channel_id, request, inbound_trace_id)
        }
        _ => Err(Error::Invariant(
            "unexpected MessageBody variant in pairing message",
        )),
    }
}

/// Why a pairing on `channel_id` can no longer go on, or `None` while it can.
///
/// The contact is judged by the timestamp this device wrote into it, read
/// from its own stored copy, so its age is measured on this device's clock
/// alone. The request is judged by its own timestamp. A missing timestamp,
/// or no stored contact, cannot show the pairing is fresh and counts as
/// expired.
///
/// An expired contact can never pair again, so its material is dropped here.
/// An expired request leaves the contact in place: the scanner may start
/// again on it.
pub(in crate::protocol) async fn expiry<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    pairing: &PairingConfig<'_>,
    channel_id: ChannelId,
    request_timestamp: Option<&Timestamp>,
) -> Result<Option<PairingError>> {
    let contact_timestamp = match stores
        .secrets
        .load(local.secret_id, channel_id, SecretKind::PairingContact)
        .await?
    {
        Some(SecretValue::PairingContact(contact)) => contact.timestamp,
        _ => None,
    };
    if outlived(contact_timestamp.as_ref(), pairing.lifetime) {
        stores
            .secrets
            .remove(local.secret_id, channel_id, SecretKind::PairingSecret)
            .await?;
        stores
            .secrets
            .remove(local.secret_id, channel_id, SecretKind::PairingContact)
            .await?;
        return Ok(Some(PairingError::Expired(
            "the contact is older than the pairing lifetime",
        )));
    }
    if outlived(request_timestamp, pairing.lifetime) {
        return Ok(Some(PairingError::Expired(
            "the pairing request is older than the pairing lifetime",
        )));
    }
    Ok(None)
}

/// [`expiry`] for a request that just arrived: an expired one is reported as
/// ignored, before the application is asked anything, and is not answered.
pub(in crate::protocol) async fn ignored_if_expired<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    pairing: &PairingConfig<'_>,
    channel_id: ChannelId,
    request_timestamp: Option<&Timestamp>,
    trace_id: u64,
) -> Result<Option<Vec<DeRecEvent>>> {
    let Some(_reason) = expiry(stores, local, pairing, channel_id, request_timestamp).await? else {
        return Ok(None);
    };
    #[cfg(feature = "logging")]
    tracing::warn!(
        channel_id = channel_id.0,
        reason = %_reason,
        "pairing request ignored"
    );
    Ok(Some(vec![DeRecEvent::MessageIgnored {
        channel_id,
        reason: IgnoreReason::Expired,
        trace_id,
    }]))
}

/// Whether `timestamp` is missing or more than `lifetime` in the past.
fn outlived(timestamp: Option<&Timestamp>, lifetime: Duration) -> bool {
    timestamp.is_none_or(|ts| {
        let created = u64::try_from(ts.seconds).unwrap_or(0);
        now_secs().saturating_sub(created) > lifetime.as_secs()
    })
}

/// The memo sent with an `INCOMPATIBLE_PARAMETER_RANGE` refusal.
///
/// The requester reads it, so its own range (`peer` here) is named first and
/// this device's range is the accepted one.
fn parameter_range_memo(err: &PairingError) -> String {
    match err {
        PairingError::IncompatibleParameterRange {
            field,
            local_min,
            local_max,
            peer_min,
            peer_max,
        } => format!(
            "`{field}` range [{peer_min}, {peer_max}] does not overlap \
             the accepted range [{local_min}, {local_max}]"
        ),
        _ => "parameter range does not overlap the accepted range".to_owned(),
    }
}

/// Refuse a `PairRequest` under a protocol rule: send the requester a
/// `PairResponse` carrying `status` and `memo`, and report the refusal as
/// [`DeRecEvent::PairingRefused`]. No channel is created.
///
/// `error` is the local reason for the refusal. Its code and description
/// are reported on the event and never sent to the requester.
///
/// Once the refusal was handed to the transport it is reported as sent. A
/// failure of that send, or of dropping the pairing secret after it, follows
/// as a [`DeRecEvent::RequestFailed`] with `responded: true`.
#[allow(clippy::too_many_arguments)]
async fn refuse<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    channel_id: ChannelId,
    request: &PairRequestMessage,
    status: StatusEnum,
    memo: &str,
    error: &Error,
    trace_id: u64,
) -> Result<Vec<DeRecEvent>> {
    let after =
        pair::send_refusal(stores, local, channel_id, request, status, memo, trace_id).await?;
    let mut events = vec![DeRecEvent::PairingRefused {
        channel_id,
        status: status as i32,
        memo: memo.to_owned(),
        error_code: classify(error).1.name().to_owned(),
        message: error.to_string(),
    }];
    if let Some(error) = after {
        events.push(obligation::request_failed(
            channel_id,
            PendingActionKind::Pairing,
            true,
            status as i32,
            memo,
            &error,
            None,
        ));
    }
    Ok(events)
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(trace_id = trace_id, channel_id = contact.channel_id))
)]
pub(in crate::protocol) async fn start<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    pairing: &PairingConfig<'_>,
    kind: SenderKind,
    contact: ContactMessage,
    peer_communication_info: HashMap<String, String>,
    trace_id: u64,
) -> Result<u64> {
    let replica_id_to_inject = require_replica_id_for_kind(kind, local.replica_id)?;

    if contact.timestamp.is_none() {
        return Err(PairingError::InvalidContactMessage("contact carries no timestamp").into());
    }
    if outlived(contact.timestamp.as_ref(), pairing.lifetime) {
        return Err(PairingError::Expired("the contact is older than the pairing lifetime").into());
    }

    let channel_id = ChannelId(contact.channel_id);

    let endpoints = local
        .policy
        .admit_peer_endpoints(contact.advertised_endpoints())?;

    if contact.requires_pre_pair() {
        pre_pair::start(
            stores,
            local,
            channel_id,
            contact,
            peer_communication_info,
            endpoints,
            kind,
            trace_id,
        )
        .await
    } else {
        pair::start(
            stores,
            local,
            pairing,
            channel_id,
            contact,
            peer_communication_info,
            endpoints,
            kind,
            replica_id_to_inject,
            trace_id,
        )
        .await
    }
}

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)| CommunicationInfoKeyValue {
            key: k.to_owned(),
            value: Some(Value::StringValue(v.to_owned())),
        })
        .collect();

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

    if entries.is_empty() {
        return None;
    }

    Some(CommunicationInfo {
        communication_info_entries: entries,
    })
}

fn extract_communication_info(
    info: &Option<CommunicationInfo>,
    peer_kind: SenderKind,
) -> Result<(HashMap<String, String>, Option<u64>)> {
    let Some(info) = info.as_ref() else {
        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(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) {
            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)),
    }
}

fn is_reserved_key(key: &str) -> bool {
    key.starts_with("derec.")
}

/// This device's `communication_info` as its own roster row carries it.
///
/// The same entries a peer keeps after [`extract_communication_info`]: the
/// reserved keys and blank values a peer would drop never reach the roster.
pub(in crate::protocol) fn own_communication_info(local: &Local<'_>) -> HashMap<String, String> {
    local
        .communication_info
        .iter()
        .filter(|(k, v)| !is_reserved_key(k) && !v.trim().is_empty())
        .map(|(k, v)| (k.to_owned(), v.trim().to_owned()))
        .collect()
}

/// Record a pairing this device *initiates*, until its response arrives.
///
/// Every kind writes the same `Pending` [`HelperChannel`] placeholder at the
/// contact's channel, carrying the peer's role, the endpoints and the
/// `communication_info` to record for it. That is all the response handler
/// needs: the local kind is the counterpart of the peer's, and a replica
/// peer's `replica_id`, unknown until the response, goes on the row written
/// then. Nothing is put in the replica roster: a pairing in flight is not
/// group membership, and this device's own row is written only when a
/// replica pairing is confirmed (see [`claim_own_member`]).
async fn persist_start_record<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    channel_id: ChannelId,
    peer_endpoints: Vec<TransportProtocol>,
    peer_communication_info: HashMap<String, String>,
    own_kind: SenderKind,
) -> Result<()> {
    use crate::protocol::types::{ChannelRecord, HelperChannel};
    stores
        .channels
        .save(
            local.secret_id,
            ChannelRecord::Helper(HelperChannel {
                channel_id,
                transports: peer_endpoints,
                communication_info: peer_communication_info,
                peer_role: own_kind.counterparty(),
                status: ChannelStatus::Pending,
                created_at: now_secs(),
                weight: 1,
            }),
        )
        .await?;
    Ok(())
}

/// Write this device's own row into the replica roster, on the group channel
/// `channel_id`, as `role`.
///
/// Called when a replica pairing is confirmed: the first confirmed pairing
/// fixes the group's channel. A device that already holds a `Paired` own row
/// is in a group, and keeps that row — a later pairing admits a joiner on an
/// ephemeral channel, and moving this row onto it would redefine the group's
/// channel, and with it the group key, on every admission. Any other own row
/// is replaced.
pub(in crate::protocol) async fn claim_own_member<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    channel_id: ChannelId,
    role: ReplicaRole,
) -> Result<()> {
    use crate::protocol::types::{ChannelRecord, ReplicaMember};
    let replica_id = ReplicaId::try_from(local.replica_id.ok_or(Error::ReplicaIdNotConfigured)?)?;

    let holds_a_group = stores
        .channels
        .replicas_matching(
            local.secret_id,
            ReplicaFilter {
                ids: vec![replica_id],
                status: vec![ChannelStatus::Paired],
                ..Default::default()
            },
        )
        .await?
        .into_iter()
        .next()
        .is_some();
    if holds_a_group {
        return Ok(());
    }

    stores
        .channels
        .save(
            local.secret_id,
            ChannelRecord::Replica(ReplicaMember {
                channel_id,
                replica_id,
                transports: local.own_transports.to_vec(),
                communication_info: own_communication_info(local),
                role,
                status: ChannelStatus::Paired,
                created_at: now_secs(),
                handover_channel: None,
            }),
        )
        .await?;
    Ok(())
}

/// Refuse to start a pairing on a channel this device already uses.
///
/// The channel identifier is chosen by whoever created the contact, and a
/// replica group's identifier travels in the clear on every envelope of the
/// group. A channel is in use while it holds a key, while any replica member
/// is recorded on it, or while a helper record on it is past `Pending`. A
/// `Pending` helper record alone is an unfinished pairing on the same
/// contact, which a new start replaces.
async fn reject_start_on_channel_in_use<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    channel_id: ChannelId,
) -> Result<()> {
    let helper_in_use = stores
        .channels
        .load(local.secret_id, ChannelQuery::Helper { channel_id })
        .await?
        .is_some_and(|record| record.status() != ChannelStatus::Pending);
    let replica_in_use = stores
        .channels
        .replicas_matching(local.secret_id, ReplicaFilter::default())
        .await?
        .iter()
        .any(|member| member.channel_id == channel_id);
    let key_in_use = stores
        .secrets
        .load(local.secret_id, channel_id, SecretKind::SharedKey)
        .await?
        .is_some();

    if helper_in_use || replica_in_use || key_in_use {
        return Err(Error::ChannelAlreadyPaired { channel_id });
    }
    Ok(())
}

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)
}

/// Whether `candidate` is already held by a member of this group.
///
/// The roster includes this device's own row, so a peer that announced the
/// same id as us collides too — the common case, since both ends of a first
/// pairing are usually configured by the same person.
async fn replica_id_is_taken<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    candidate: u64,
) -> Result<bool> {
    Ok(!stores
        .channels
        .replicas_matching(
            local.secret_id,
            ReplicaFilter {
                ids: vec![ReplicaId(candidate)],
                ..Default::default()
            },
        )
        .await?
        .is_empty())
}

fn request_sender_kind(request: &PairRequestMessage) -> Result<SenderKind> {
    SenderKind::try_from(request.sender_kind).map_err(|_| {
        PairingError::InvalidPairRequestMessage("unknown sender_kind on PairRequest").into()
    })
}