derec-library 0.0.11

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
Documentation

DeRec Rust SDK

Crates.io Docs.rs License

Rust implementation of the DeRec protocol — split a secret into shares, distribute them across independent helpers, verify possession over time, and reconstruct the secret from a threshold of shares when needed. The library is transport- and storage-agnostic, supports both native Rust and WebAssembly targets, and is the reference implementation maintained by the DeRec Alliance.

[!WARNING] This is a pre-release version. APIs may change until 0.1.0.


Contents


What is DeRec?

DeRec is a threshold secret-sharing protocol for decentralized recovery. The Owner splits a secret using Verifiable Secret Sharing, distributes the shares across trusted Helpers, and can later reconstruct the secret from any threshold-sized subset of shares.

Three roles participate:

  • Owner — the party that wants to protect a secret. Splits the secret, distributes shares, verifies that helpers still hold them, and drives recovery when needed.
  • Helper — a trusted entity that stores one share. Responds to verification challenges, returns the share during recovery, and acknowledges unpair requests.
  • Replica — a second device belonging to the same Owner that mirrors the Source's secret. Replica pairings are unidirectional, just like Owner↔Helper: one side scans as SenderKind::ReplicaSource (writes the secret), the other as SenderKind::ReplicaDestination (receives it). Pairing is confirmed out of band with a human-readable fingerprint (DeRecProtocol::get_fingerprint / verify_fingerprint), then ProtectSecret distributes the full secret (helpers + secrets + replicas) to every Destination via a ReplicaSecretPayload. Destinations surface the typed DeRecEvent::ReplicaSecretReceived. Configure via DeRecProtocolBuilder::with_replica_id.

The protocol is transport-agnostic and produces wire-compatible protobuf messages; the library never assumes a specific delivery channel.

Typical applications: cryptocurrency wallets, digital identity, secure backup, key management.


Installation

cargo add derec-library

The badge above shows the latest published version.


Cargo features

Every feature is off by default — a default build compiles no serde, no FFI layer, and no logging, so a pure-Rust consumer pays for none of them.

Feature Enables
serde serde::Serialize / Deserialize on the public store and channel types (SecretValue, PairingKeyMaterial, ChannelRecord, HelperChannel, ReplicaMember, ChannelStatus, TransportProtocol), so a store implementation can persist them with any serde format. Without it, use the byte-level accessors (e.g. PairingKeyMaterial::as_bytes / from_bytes) or your own codec. Also pulls the matching derec-proto/serde. The serde wire format of those types is not part of the public API and may change. Also enables the canonical JSON of DeRecProtocolConfig (see Configuration from a file or record), which is a stable, documented format.
logging tracing spans and events across the protocol and primitives layers. Adds no overhead when no subscriber is installed.
ffi The native C-ABI bridge for host languages that link the shared library. Implies serde + serde_json. Pure-Rust consumers do not need this.
[dependencies]
derec-library = { version = "*", features = ["serde"] }

The wasm32 target pulls serde in automatically, so WebAssembly builds need no extra feature flags.


Two API layers

The library exposes two surfaces:

  • Protocol layer (derec_library::protocol) — start here. A stateful orchestrator (DeRecProtocol) that owns your storage/transport implementations, manages session state, and drives every flow through a single start / process / accept / reject surface. Returns DeRecEvent values the application reacts to.

  • Primitives layer (derec_library::primitives) — the lower-level surface: one module per flow exposing produce / extract / process functions that build and decode individual protocol messages. Use this only when the protocol layer cannot fit (e.g. you are implementing your own orchestrator, integrating into a system whose event loop you don't control, or need to manipulate messages directly).

Most consumers should only use the protocol layer. The primitives section at the bottom of this README is provided for the cases that need it.


Quick start (Protocol layer)

Three steps: implement the storage and transport traits for your environment, build a DeRecProtocol, drive it with start / process.

use derec_library::protocol::{
    DeRecEvent, DeRecFlow, DeRecProtocolBuilder, DeRecStores, PendingAction,
};

// 1. Implement the storage and transport traits for your environment.
//    See the trait docs:
//    - DeRecChannelStore    — helper channels + replica-group members
//    - DeRecShareStore      — secret shares
//    - DeRecSecretStore     — per-channel key material (sensitive)
//    - DeRecUserSecretStore — latest user-facing secret snapshot
//    - DeRecStateStore      — in-flight orchestrator state (durable)
//    - DeRecTransport       — outbound message delivery
let my_channel_store     = /* ... */;
let my_share_store       = /* ... */;
let my_secret_store      = /* ... */;
let my_user_secret_store = /* ... */;
let my_state_store       = /* ... */;
let my_transport         = /* ... */;

// 2. Build a protocol instance for one secret. `with_stores` sets all five
//    stores at once; each `with_*_store` setter is still available, and the
//    last call for a store wins.
let mut protocol = DeRecProtocolBuilder::new(secret_id)
    .with_stores(DeRecStores {
        channels: my_channel_store,
        shares: my_share_store,
        secrets: my_secret_store,
        user_secrets: my_user_secret_store,
        state: my_state_store,
    })
    .with_transport(my_transport)
    .with_own_transports(["https://my-node.example/derec"])
    // Optional setters — see "Builder configuration" below.
    .build()?;

// 3. Drive flows.
//
//    `start` initiates an outbound flow (pairing, sharing, recovery, …).
//    `process` feeds incoming wire bytes and returns events.
//    `accept` / `reject` resolve `ActionRequired` events the app must confirm.

// Initiate a pairing flow from a contact message received out-of-band.
// `start` returns per-target `*Started` / `*Failed` events describing
// what was dispatched — for pairing that's one `PairingStarted` with
// the fresh `channel_id`. Fan-out flows (ProtectSecret, VerifyShares,
// RecoverSecret, Discovery, UpdateChannelInfo) return one event per
// targeted channel. Follow-up events (`PairingCompleted`,
// `ShareConfirmed`, `SecretRecovered`, …) still surface from
// `process()` on the peer's response.
for event in protocol
    .start(DeRecFlow::Pairing {
        kind: derec_proto::SenderKind::Helper,
        contact: contact_message,
        peer_communication_info: Default::default(),
    })
    .await?
{
    if let DeRecEvent::PairingStarted { channel_id, .. } = event {
        println!("dispatched pair on channel {}", channel_id.0);
    }
}

// Inbound message processing loop:
loop {
    let wire_bytes = my_transport_recv().await?;
    for event in protocol.process(&wire_bytes).await? {
        match event {
            DeRecEvent::ActionRequired { action, .. } => {
                // The peer asked us to do something (pair, store a share, ...).
                // Confirm with accept, refuse with reject(action, status, memo).
                protocol.accept(action).await?;
            }
            DeRecEvent::SecretRecovered { secret } => {
                // Recovery completed — `secret` is the typed `Secret` snapshot
                // the owner originally protected. The user-facing entries live
                // in `secret.secrets: Vec<UserSecret>`; `helpers`, `replicas`
                // carry the roster captured at
                // distribution time.
                for entry in &secret.secrets {
                    println!("recovered {} ({}B)", entry.name, entry.data.len());
                }
                // Nothing has been written yet: show the user what was
                // recovered, or ask them, before committing it. If
                // `secret.replicas` names live members, join that group
                // instead (see "Recover, then restore or join"). Call
                // `restore` on this same `protocol` — the one that ran
                // recovery and still holds the recovery-mode channels it
                // unpairs. `restore` commits the recovered Secret into this
                // `secret_id`'s stores, wipes the throwaway recovery-mode
                // channels and reseats canonical helper / replica state at
                // the recovered version. See `DeRecProtocol::restore`.
                protocol.restore(&secret, recovered_version).await?;
            }
            // ... handle other events the application cares about.
            _ => {}
        }
    }
}

A complete working example lives in the repository's end-to-end tests; see End-to-end test coverage.

Recover, then restore or join

SecretRecovered writes nothing, so the application decides between restore and join before committing. When secret.replicas names a group with live members other than the lost device, do not restore: tell the user and offer to join the group as a new replica — pair with a live member, confirm the fingerprint, run start(DeRecFlow::ReplicaDiscovery). With no live member, restore. The reasons:

  • Neither path gives this device the proofs of earlier versions, so it cannot verify them. Restore writes none. A joining device gets only the share map of the single version each push or catch-up carries. The live members keep the proofs they hold.
  • A restored device cannot publish, or answer a member's catch-up, until the application configures a replica_id the roster names.
  • Joining adds the device to the group as a new member. Restoring next to live replicas makes a second device claim the lost device's role.

See Restore or join.

After a restore

restore writes no owner-side tracking shares, so VerifyShares at the recovered version sends no challenge and reports every channel as VerifySharesFailed { reason: VerifyFailureReason::NoProof, .. } — this device holds no reference bytes for it. It cannot: a VerifyShare proof is SHA-384(share ‖ nonce) over the exact bytes a helper holds, and recovery cannot attribute a collected share to a canonical helper channel (the VSS x-coordinate is a random field element and GetShareResponseMessage carries no channel id).

Publish once to get verification back. start(ProtectSecret) derives recovered_version + 1 from the snapshot restore committed, writes real tracking shares as it distributes, and verification at that version behaves as it does for an owner that never recovered.

Pass the stored weights unchanged, for the Helpers restore actually restored. restore writes each reachable helpers[].weight into the restored HelperChannel.weight, so the roster's weights are the stored ones, and the weights map replaces every stored weight, so a helper left out returns to 1. A roster helper with no endpoint gets no channel — restore reports it as PeerNotRestored instead — and naming its channel_id in weights fails the call with InvalidWeight, since the key is not a paired Helper channel.

Pass no threshold. restore puts the roster's threshold (Secret.threshold) back into UserSecrets.threshold, and every later publish splits at it, whatever with_threshold says on this device. To change it, pass threshold on start(ProtectSecret). A roster written before the threshold was recorded carries none, and with_threshold applies:

let restore_events = protocol.restore(&secret, recovered_version).await?;
// A roster helper with no endpoint gets no channel and is reported here
// instead; naming it in `weights` below would fail the publish with
// `InvalidWeight`.
let not_restored: std::collections::HashSet<ChannelId> = restore_events
    .iter()
    .filter_map(|e| match e {
        DeRecEvent::PeerNotRestored { channel_id, .. } => Some(*channel_id),
        _ => None,
    })
    .collect();
// Re-publish so this device holds tracking shares of its own.
protocol.start(DeRecFlow::ProtectSecret {
    secrets: secret.secrets.clone(),
    description: None,
    // The stored (roster) weights of the Helpers restore actually paired;
    // a Helper left out would return to 1.
    weights: secret
        .helpers
        .iter()
        .filter(|h| !not_restored.contains(&ChannelId(h.channel_id)))
        .map(|h| (ChannelId(h.channel_id), h.weight.max(1)))
        .collect(),
    // Keep the restored threshold.
    threshold: None,
}).await?;
// Now verifiable, at recovered_version + 1.

If the recovered roster carries a replica group, that publish additionally needs a replica_id the roster names — restore does not adopt one, since claiming the lost device's identity is a takeover with its own convergence rules. Without it the publish fails with Error::ReplicaIdNotConfigured and no share reaches any helper.


Builder configuration

DeRecProtocolBuilder enforces that every store and the transport are set at compile time (missing one is a type error, not a runtime panic). Every data setting — including the required with_own_transports — is checked at run time inside build(), which returns Result<DeRecProtocol, crate::Error> so invalid configurations surface as Error::InvalidInput instead of panicking. Optional setters have defaults:

Setter Default Purpose
with_threshold(n) 3 The starting threshold t, the minimum subshares required to reconstruct the secret, for a secret with no threshold stored. Each paired Helper contributes one subshare unless ProtectSecret gives it more weight; see Weighted helpers. Once a publish stores a t, that t applies; see The threshold is recorded.
with_timeouts(timeouts) see Timeouts Every waiting period in one call; unspecified fields keep their default. inbound_message 300s is the staleness/replay window, sharing_round and unpair_ack 60s are liveness budgets, pairing 30s is how old a contact or pairing request may be (see Pairing lifetime), expired_channels Enabled { 300 } sweeps channels awaiting fingerprint confirmation.
with_unsafe_connection(bool) false Accept plaintext http:// and grpc:// endpoints. Development only. Loopback is accepted for your own endpoint regardless; see Transport endpoints and plaintext.
with_communication_info(map) empty Key-value identity metadata embedded in pairing messages.
with_replica_id(id) unset This device's replica identity. Required for any replica-mode pairing; application-assigned and rejected if 0.
with_auto_accept(policy) every flow off Per-flow opt-in to auto-accepting inbound requests instead of surfacing ActionRequired. Read the per-flow caveats before enabling — several are state-changing.
with_parameter_range(range) unset Advertised protocol parameter bounds, checked for overlap at pairing time. A helper also enforces its own minShareSize/maxShareSize on every inbound share (see Helper-side admission control).
with_max_subshares(max) unset (no cap) Cap on a sharing round's total subshares (the sum of the Helpers' weights). Checked at sharing only, never at recovery; must be >= threshold. See Weighted helpers.
with_auto_respond_on_failure(bool) false Who answers an inbound request whose handling failed. If true, the library sends the response itself; if false, it reports RequestFailed with a token the app passes to reject. See Failed requests.
with_unpair_ack(ack) UnpairAck::Required Whether the unpair initiator waits for the peer's Ok before dropping local state.
with_auto_reply_to(bool) false If true, every outbound request stamps replyTo = own_transport so the responder routes the reply back to this node — even if the channel's stored peer endpoint points elsewhere. Useful for replica scenarios. See Correlation and routing on the wire.

See the builder rustdoc for the full per-setter contract.

with_own_transports(endpoints) has no default: build() returns Error::InvalidInput when no endpoint was set, or the list is empty.


Configuration from a file or record

Applications usually load settings as a whole: general settings from the environment or a config file, per-user settings from a user record. DeRecProtocolConfig holds every data setting of the builder, each one optional, and with_config applies it in one call:

use derec_library::protocol::{DeRecProtocolBuilder, DeRecProtocolConfig};

let general: DeRecProtocolConfig = serde_json::from_str(&general_json)?;
let per_user: DeRecProtocolConfig = serde_json::from_str(&user_record_json)?;

let protocol = DeRecProtocolBuilder::new(secret_id)
    .with_stores(stores)
    .with_transport(my_transport)
    .with_config(general)  // 1. general settings
    .with_config(per_user) // 2. per-user settings
    .with_threshold(4)     // 3. individual setters
    .build()?;
  • Only set fields are applied. An absent field leaves whatever the builder already holds.
  • Last write wins, per field. Each set field goes through its own with_* setter, in call order. Nested objects replace the builder's value as a whole, except timeouts: each of its fields is merged separately, so a per-user config that sets only inbound_message_secs keeps the sharing_round_secs the general config set.
  • Validation happens in build(), with the same rules as the setters. A threshold of 1 from a config file fails exactly as with_threshold(1) does.
  • Stores, the transport and secret_id are not settings and are not carried in the config.

Serialization needs the serde feature. The canonical JSON, shared by every SDK, is:

{
  "threshold": 3,
  "max_subshares": "12",
  "timeouts": {
    "inbound_message_secs": 300,
    "sharing_round_secs": 60,
    "unpair_ack_secs": 60,
    "get_share_response_secs": 300,
    "pairing_secs": 30,
    "expired_channels": { "enabled": true, "timeout_in_secs": 300 }
  },
  "parameter_range": { "min_share_size": 1, "max_share_size": 4096 },
  "auto_accept": { "pairing": true, "store_share": true },
  "auto_respond_on_failure": false,
  "auto_reply_to": false,
  "unpair_ack": "required",
  "unsafe_connection": false,
  "communication_info": { "name": "alice" },
  "own_transports": [{ "uri": "https://me.example.com/derec", "protocol": "https" }],
  "replica_id": "9007199254740993"
}

Keys are snake_case and every key is optional. replica_id and max_subshares are u64 values written as decimal strings, so they survive JSON encoders whose numbers are f64. Timeouts are whole seconds. Unknown keys are rejected at every level, so a misspelled key fails to parse instead of being silently ignored. See the DeRecProtocolConfig rustdoc for every field's accepted forms.


Event-driven model

Both start and process return Vec<DeRecEvent>. The application reacts to events; the protocol owns the state.

start emits per-target dispatch events describing what was just sent — PairingStarted, DiscoveryStarted, ProtectSecretStarted, VerifySharesStarted, RecoverSecretStarted, UnpairStarted, UpdateChannelInfoStarted. Fan-out flows also surface per-target failures with the matching *Failed { channel_id, error } variant when a single target's send hits a transport / store error — those failures don't short-circuit the rest of the fan-out. Single-channel flows (Pairing, Unpair) don't have *Failed variants; a dispatch error returns Err from start instead. Programmer errors (invalid input, missing preconditions, role mismatch) always return Err up-front, before any target-level events are emitted.

process emits the settlement events driven by peer responses:

  • ActionRequired { channel_id, action } — an incoming request needs application confirmation. The app calls protocol.accept(action) or protocol.reject(action, status, memo) to complete the flow.

  • RequestFailed { channel_id, action_kind, responded, status, memo, error_code, message, action } — an inbound request failed while it was being handled; it still gets exactly one response. See Failed requests

  • ErrorResponseReceived { channel_id, status, memo } — the peer answered a message from this device with an ErrorResponseMessage (typically FORMAT_ERROR: it could not decode the body). Never answered

  • PairingRefused { channel_id, status, memo, error_code, message } — this device refused an inbound PairRequest under a protocol rule (INCOMPATIBLE_PARAMETER_RANGE or REPLICA_ID_CONFLICT) and sent the requester that status with memo, written from the requester's side. error_code and message carry the local reason, as on RequestFailed, and are never sent. No channel is created

  • PairingCompleted { channel_id, kind, peer_communication_info }

  • ShareStored { channel_id, version } / ShareConfirmed { … } / ShareRejected { … } / SharingComplete { … }

  • ShareRefused { channel_id, version, status, memo } — helper side: the library refused an inbound share instead of raising ActionRequired, and answered the owner, who sees ShareRejected with the same status and memo. status is FORMAT_ERROR (the share does not decode), VERIFICATION_FAILED (it does not verify against its commitment), SIZE_LIMIT_EXCEEDED (outside the helper's ParameterRange) or VERSION_CONFLICT (a different share is already stored at version). Nothing is stored and no version is removed. It is sent whatever auto_respond_on_failure says; a refusal from the application's own DeRecShareStore::save does not emit it

  • Verification verdicts — every challenged channel ends with exactly one of:

    • ShareVerified { channel_id, version, subshares, threshold } — the helper proved it holds the exact share. subshares: Option<u32> is how many subshares that helper holds for version and threshold: Option<u32> the threshold version was split with, both read from this device's stored share (see Judging a version's recoverability);
    • ShareVerifyInvalid { channel_id, version } — the helper answered with a proof that does not match the share this device stored (a damaged or dishonest helper). It is an event, not an error from process;
    • ShareVerifyRejected { channel_id, version, status, memo } — the helper refused the challenge with a non-OK status (e.g. UNKNOWN_SHARE_VERSION);
    • VerifySharesFailed { channel_id, version, reason, error } — no verdict could be reached on this device. reason is a VerifyFailureReason: NoSharedKey, NoProof (this device holds no proof of that channel's share at that version) or DispatchFailed. start(VerifyShares) emits it for a channel with no proof without sending a challenge.

    A response to an earlier challenge that a newer one replaced is ignored (MessageIgnored with IgnoreReason::StaleResponse) and the current challenge stays open. A response missing its result is malformed and is still an error from process. See Which versions to verify.

  • SecretsDiscovered { channel_id, secrets }

  • RecoveryShareReceived { channel_id, shares_received } — a helper's share was collected. A recovery reconstructs nothing until every helper it asked has answered, or timeouts.get_share_response_secs has passed since the requests went out (each silent helper is then reported as RecoverSecretFailed { …, error: "timeout" }). It then decides exactly once:

    • SecretRecovered { secret: Secret } (typed; secret.secrets is the list of UserSecret the owner protected, alongside the captured helper/replica roster) — one secret reconstructs and every collected share is part of it;
    • RecoveryDisputed { version, secret, supported_by, disputed_by } — one secret reconstructs, but other helpers hold valid shares of a different split that does not. Either side can be the owner's: colluding helpers can forge a complete split, and the honest ones may be too few to reconstruct theirs. Show the owner what secret holds and who stands on each side, and pass it to restore only once they confirm it;
    • RecoveryConflict { version, candidates, disputed_by } — two or more different secrets reconstruct. Each candidate carries the secret and supported_by. The library never picks: involve the owner, and pass the candidate they confirm to restore;
    • RecoveryIncomplete { secret_id, version, shares_received } — nothing reconstructs. The recovery is closed; start it again to retry.

    supported_by / disputed_by name helpers as RecoveryHelper { channel_id, communication_info }, the communication_info being what the helper advertised when it paired, so the app can tell the owner who is on each side. That is the helper's own configured communication info (with_communication_info), not the peer_communication_info the helper passed to start(Pairing): a helper that configures none is named by its channel alone.

  • RecoveryShareRefused { channel_id, version, status, memo } — a helper answered with a non-OK status (e.g. UNKNOWN_SHARE_VERSION) instead of a share; it is not collected, but it is that helper's answer

  • RecoveryShareCorrupted { channel_id, version, reason } — a helper answered with a share that cannot be part of the secret. reason is a CorruptionReason: Malformed (no decodable share for the requested secret and version, or a share bigger than this device's own configured max_share_size, rejected before it is even parsed) or InvalidProof (the share fails its own Merkle proof, e.g. a tampered value), both reported as the share arrives; or Forged (its group reconstructs under one key, but not to a secret, or a single share reconstructs alone — neither happens with an honest split), reported with the recovery's decision. The share is set aside and never blocks the recovery. An honest helper never sends one, so the app may treat it as a sign of a damaged or compromised helper — e.g. offer to unpair it. A share that only disagrees with the others is never reported here: it is a dispute, not evidence against its helper

  • Unpaired { channel_id } / UnpairRejected { channel_id, status, memo } / UnpairFailed { channel_id, error } — emitted by restore when an ephemeral recovery channel's teardown could not be delivered. The restore has already committed, so local state is dropped anyway and an Unpaired for the same channel follows; the pair means "gone locally, peer not told"

  • PeerNotRestored { channel_id, replica_id, reason } — emitted by restore for a roster entry it wrote no channel for. reason is NotRestoredReason::NoTransports: the recovered roster names no endpoint for that helper (replica_id is None) or replica member (channel_id is the group's channel). The rest of the roster is restored.

  • ChannelInfoUpdated { channel_id } / ChannelInfoUpdateRejected { channel_id, status, memo }

  • PrePairRejected { channel_id, status, memo } — the contact creator answered our PrePairRequest with a non-Ok status (scanner side, HashedKeys flow). Distinct from a cryptographic binding-hash mismatch, which surfaces as Error::Pairing(PairingError::PrePairHashMismatch) from process() rather than as an event. See Pairing modes.

  • MessageIgnored { channel_id, reason, trace_id } — an inbound message was dropped without touching any store or sending anything back. reason is IgnoreReason::PendingVerification (the channel's fingerprint is not confirmed on this device yet; see Replica fingerprint verification is mandatory), IgnoreReason::Expired (older than the inbound timeout), IgnoreReason::TimestampMismatch (the envelope and inner-message timestamps differ, or either or both are absent), IgnoreReason::StaleResponse (a verification response to a replaced challenge) or IgnoreReason::Superseded (a share request for a version older than the newest one stored on the channel, and not stored itself).

  • NoOp — emitted when an inbound message was processed but had no application-visible consequence.

See DeRecEvent for the complete enum and per-variant docs.

Which versions to verify

This device keeps a proof of each helper's share (the exact bytes it sent) so it can check that helper's answers later. A stored proof is always one of two things: confirmed by its helper (ShareConfirmed), or part of a sharing round still open. When a round settles a channel as failed — the helper rejected the share (ShareRejected) or the round timed out — that channel's proof for the round's version is deleted, and a late ShareConfirmed for it is still emitted but stores nothing.

A confirmation also deletes the proofs of versions the helper dropped. A helper that stores a version applies that round's keepVersion and deletes every other version it holds (see the owner's keep version). So when a helper confirms, this device deletes its proofs for that channel other than the confirmed version and that round's keepVersion. A helper that rejects the round or never answers keeps its older versions, and this device keeps their proofs.

A replica Destination never sees the helpers' answers, and it keeps every proof it receives: it never deletes one on its own, and freeing that storage is the application's concern. Verifying on a Destination a version that a helper refused, or later dropped under a keepVersion, gets ShareVerifyRejected (UNKNOWN_SHARE_VERSION) from that helper, where the Source reports NoProof. The application may delete such rows from the Destination's share store; verifying a version whose rows are gone then gives VerifySharesFailed with NoProof.

So verify only versions whose round completed (SharingComplete): the latest one, and the one the latest round kept. A channel with no proof at the requested version gets VerifySharesFailed with NoProof, and no challenge is sent to it.

Judging a version's recoverability

Sum subshares over the ShareVerified events for a version and compare the sum with their threshold: the version is recoverable from the verified helpers when the sum is >= threshold. Every ShareVerified for a version carries that version's own threshold, not the current one.

If either value is None on any of those events, the result is unknown. A None count is not 0 or 1: recompute it from the stored share's bytes, or treat the version's total as unknown.

The count comes from Share::subshares on this device's stored share for that channel and version, so it is the weight of the round that published the version, not the helper's current HelperChannel.weight, which a later round may have changed. The library sets Share::subshares on every share the owner side saves, including a replica Destination's mirrored copies, and always leaves it None on a helper's stored share. An owner share saved before the field existed reads back as None, and so does ShareVerified.subshares for it; the library never backfills it. Recomputing it from the stored bytes is the application's choice.

The threshold comes from Share::threshold on the same stored share, with the same rules: the owner side records the round's threshold on the shares it sends, and a replica Destination records the roster's threshold on its mirrored copies; it is None on a helper's share and on owner shares saved before the field existed.

Timestamps

Every channel message carries one timestamp, its send time, in both the outer envelope and the encrypted inner message. After decrypting, the receiver ignores a message whose two timestamps differ, or where either or both are absent, as MessageIgnored with IgnoreReason::TimestampMismatch. A peer on 0.0.8 or earlier stamps its replies separately, so they are ignored this way.

Replays and reflections

process ignores a message older than Timeouts::inbound_message, but within that window it processes every copy of a message it is handed. Both ends of a channel encrypt under one key, so a message this device sent, delivered back to it, decrypts as if the peer had sent it. Detecting both is the job of the application's transport layer, keyed on derec_message::message_id(envelope):

  • id is a SHA-256 of the envelope's encrypted message field. It is the same for every copy of one message and different for every other message. The cleartext fields around it (sequence, traceId, the protocol version) are not authenticated and an envelope can be re-encoded, so never key on a hash of the raw bytes.
  • Keep the id of every envelope this device sends, and of every envelope process accepted (it returned Ok without MessageIgnored), until max(received or sent at, timestamp) + inbound_message. Drop an inbound envelope whose id is kept, without calling process.
  • Keep the record across restarts, or hold inbound traffic for one window after starting.

A message held back and delivered late is a first delivery, so no record catches it. A StoreShareRequest for a version older than the newest one a helper stores on the channel, and not stored itself, is ignored as MessageIgnored with IgnoreReason::Superseded, so a dropped version never comes back. A contact update is the application's to order: the timestamp of the envelope that raised an UpdateChannelInfo ActionRequired is when the update was sent, and an update older than the last one accepted on the channel should be rejected. That needs AutoAcceptPolicy::update_channel_info off.

When process fails

Each process call first settles any expired deadlines (sharing-round and unpair timeouts) and saves the result, then handles the message. If the message then fails, the deadlines stay settled and are never reported again, so the error carries them: ProcessError::events holds every event the call produced before failing, and ProcessError::channel_id names the channel the message came from (None when the bytes were not a decodable envelope). Handle those events exactly as a successful call's events, then handle the error.

match protocol.process(&bytes).await {
    Ok(events) => handle(events),
    Err(error) => {
        handle(error.events);
        report(error.channel_id, error.source);
    }
}

Every SDK carries the same two fields on its process error.

An error from process is left for what cannot be answered: an envelope that does not decode, a channel with no key, a message that does not decrypt, any other failure of the pairing handshake or of a response this device received, and a store failure before the message could be authenticated. A request that arrived on an authenticated channel and then failed is not an error; see Failed requests.

A responder whose PairResponse was handed to the transport has completed the pairing on its side, so a failure of that send, or of dropping the pairing secret after it, is not an error either: process returns PairingCompleted followed by RequestFailed { action_kind: Pairing, responded: true }.

Failed requests

Every request that arrives on an authenticated channel gets exactly one response, even when handling it fails. Such a failure does not make process or accept return Err: it is reported as DeRecEvent::RequestFailed, and the call's other events (AutoAccepted included) are kept.

  • action_kind is the type of the request that failed, a PendingActionKind (PendingActionKind::Failed when its body could not be decoded, or was a request type the channel cannot carry).
  • responded is true when the library already handed the response to the transport. It is never sent twice, so a failure after that point is only reported.
  • status is the status that was sent, or would have been. It is always present. memo is the wire-safe memo sent with it, or that would have been, so reject(action, status, memo) sends exactly the response the library would have sent.
  • error_code is the error's DeRecErrorCode name and message a local description; neither goes on the wire.
  • action, when responded is false, is a PendingAction::RespondToFailure token. Pass it to reject, which sends the one response; accept returns Error::InvalidInput for it. It is None only when reject could never answer it: a request on a replica group channel that names no member and carries no reply_to, which has no reply target, or, with with_auto_respond_on_failure off, a replica copy that hands this device the group key and fails before hydrate stores that key.

with_auto_respond_on_failure decides who answers, the failure-side twin of with_auto_accept:

  • On: the library sends the request's own response type with a non-Ok status. A failure with a protocol meaning keeps its status and memo (REJECTED for a role mismatch, UNSUPPORTED_TRANSPORT_PROTOCOL when no endpoint is usable); anything else (a store backend error, an internal error) is FAIL with the generic memo "request could not be processed", so no local error text reaches the peer. If no reply target can be resolved before any send, the event carries the token anyway.
  • Off (the default): nothing is sent, and the event carries the token.
for event in protocol.process(&bytes).await? {
    if let DeRecEvent::RequestFailed { responded: false, status, memo, action: Some(token), .. } = event {
        let status = StatusEnum::try_from(status).unwrap_or(StatusEnum::Fail);
        protocol.reject(token, status, &memo).await?;
    }
}

The library never expires an unresolved PendingAction, a token included: a request the application never answers leaves its sender to time out. PendingAction is Clone, so an application can keep a copy of an action it accepts. The library is stateless, so resolving each token once is the application's part: rejecting the same token twice, or rejecting a copy of an action already accepted, sends a second response.

Before acting on a persisted action, accept checks its channel again. A channel that is gone or no longer Paired has nothing to answer on, so accept returns Error::InvalidInput and nothing is stored or sent. A peer that no longer holds the role the flow requires is a failed request with status REJECTED.

A message that decrypts under the channel key but whose body cannot be decoded, or that carries a PairRequest or PrePairRequest on a paired channel, is a request too. It is answered with an ErrorResponseMessage (FORMAT_ERROR, memo "message body could not be decoded", when the library answers it). A received ErrorResponseMessage is reported as DeRecEvent::ErrorResponseReceived and never answered.

The protocol's own refusals are answered in both modes, each with its event: a share that fails validation (ShareRefused), a replica copy that does not check (ReplicaSecretRefused), and a PairRequest outside the parameter range or announcing a replica id already in the group (PairingRefused).

Nothing is answered for a message that fails to decrypt (it carries no proof of who sent it, and replying would make this device a decryption oracle), an expired message (older than the inbound_message window, which is the library's replay bound), a message ignored as MessageIgnored, a response, the pairing handshake, or a replica-group removal notice.

Channel roles

A channel row describes the participant on the other end, so each paired channel carries the peer's role — SenderKind::Owner, SenderKind::Helper, SenderKind::ReplicaSource, or SenderKind::ReplicaDestination — fixed at pairing time and stored on HelperChannel.peer_role. The two sides of one channel therefore hold opposite values: an Owner's row for its helper reads Helper, and that helper's row for the Owner reads Owner. This node's own role is always the inverse (Owner ↔ Helper, ReplicaSource ↔ ReplicaDestination).

The orchestrator enforces flow directionality against this value:

  • Outbound: ProtectSecret, VerifyShares, Discovery, RecoverSecret, and Unpair require the peer to be a Helper (or a ReplicaDestination for ProtectSecret) on every targeted channel.
  • Inbound: a StoreShareRequest / VerifyShareRequest / GetSecretIdsVersionsRequest / GetShareRequest / UnpairRequest is only honored when it arrives from a peer recorded as Owner; the corresponding responses require a Helper peer. A StoreShareRequest on a ReplicaSource channel is decoded as a ReplicaSecretPayload and surfaces as DeRecEvent::ReplicaSecretReceived.
  • UpdateChannelInfo is symmetric — either side may initiate it, and the peer role is not consulted.

An outbound mismatch fails start with Error::RoleMismatch { channel_id, expected, actual }. An inbound request from a peer with the wrong role is a failed request with status REJECTED, reported as RequestFailed with error code role_mismatch; see Failed requests.


Helper-side admission control

The protocol enforces one limit of its own on inbound shares: size. A helper configured with with_parameter_range(range) checks every StoreShareRequest against its own minShareSize/maxShareSize (both inclusive; maxShareSize == 0 means unbounded) and answers a share outside that range with SIZE_LIMIT_EXCEEDED before any ActionRequired or auto-accept, so the user is never asked about it. Without a configured range there is no check.

Everything else — storage consumed per sharer, how often an owner may push updates or challenge the helper — is the application's to enforce, either per request as below or from its share store (see Refusing from the share store).

Where the decision belongs

Not before process(). Reading a share's size from raw wire bytes would mean decoding the envelope, resolving the channel's shared key, decrypting the inner message and parsing the protobuf — reimplementing the protocol's receive path outside the protocol.

Instead, process() does that work and hands back the decoded request in an ActionRequired event. PendingAction::StoreShare carries the already-decrypted StoreShareRequestMessage, so the application inspects the share without touching wire bytes or key material:

for event in protocol.process(&wire_bytes).await? {
    let DeRecEvent::ActionRequired { action, channel_id } = event else { continue };
    match &action {
        PendingAction::StoreShare { request, .. } => {
            // `channel_id` maps to a user in the application's own store,
            // so the limit can be per-user, per-plan, or whatever the
            // deployment needs.
            let limit = my_app.share_limit_for(channel_id);
            if request.share.len() > limit {
                protocol
                    .reject(
                        action,
                        StatusEnum::SizeLimitExceeded,
                        &format!("share exceeds the {limit}-byte limit"),
                    )
                    .await?;
            } else {
                protocol.accept(action).await?;
            }
        }
        _ => { protocol.accept(action).await?; }
    }
}

The owner receives a StoreShareResponse carrying that status and memo, surfacing as ShareRejected { channel_id, version, status, memo } on its side — so a refusal is attributable rather than a silent timeout.

Status codes for the common cases:

Status Use for
SizeLimitExceeded share too large, or storage quota for this sharer exhausted
TooFrequent rate limiting — the owner is updating faster than the helper allows
Rejected a user or operator declined the request
Fail anything else; put the detail in memo

Refusing from the share store

Frequency limits belong in the share store, which already sees every write. On a helper channel, DeRecShareStore::save (a genuinely new share version; an idempotent re-send never reaches it) and DeRecShareStore::record_verification (an accepted verification challenge, after the challenged share is found) may return Err(ShareStoreError::Refused(Refusal::TooFrequent)). The library answers the owner with the mapped status — TooFrequent → TOO_FREQUENT, SizeLimitExceeded → SIZE_LIMIT_EXCEEDED, Rejected → REJECTED — and the helper's call returns Ok([NoOp]); the owner sees ShareRejected or ShareVerifyRejected with that status. record_verification defaults to Ok(()). Any other store error is a failed request, reported as RequestFailed (see Failed requests).

auto_accept.store_share removes this gate

[!IMPORTANT] Setting AutoAcceptPolicy::store_share = true means process() accepts and stores every inbound share internally. No ActionRequired is emitted, so there is no opportunity to reject — every share from every paired Owner that passes the size check is stored, unless the share store refuses it.

Keep it false in any deployment with per-user storage limits. It is false by default; only an explicit with_auto_accept(...) turns it on, including via AutoAcceptPolicy::all().

This is policy, not DoS protection

By the time ActionRequired fires, the message has already been received, decrypted and parsed. Rejecting here protects your storage, not the CPU and memory spent getting there.

process() deliberately imposes no upper bound on inbound message size — legitimate envelopes range from tens of bytes to many megabytes, and any cap tight enough to resist abuse risks truncating a legitimate replica sync, which can render a secret unrecoverable. Applications must bound inbound message size at the transport layer (max HTTP body, WebSocket frame size) sized to their deployment's secret size, helper count and replica fan-out. The two mechanisms are complementary: the transport cap protects resources, reject enforces policy.


Protocol flows

Flow Purpose
Pairing Establish a secure channel between any two SenderKinds (Owner↔Helper or ReplicaSource↔ReplicaDestination). Two contact modes — see Pairing modes.
Share Distribution Split a secret and distribute the shares to helpers; replica destinations receive the full secret as a ReplicaSecretPayload.
Verification Challenge helpers to prove they still hold their shares.
Discovery Ask helpers which secrets and versions they store.
Recovery Re-pair, collect shares, reconstruct the secret.
Restore Commit a recovered Secret into an empty protocol — reseats canonical helper / replica channels at the recovered version and wipes the throwaway recovery-mode channels. Called once, after Recovery, via DeRecProtocol::restore. Verification needs one publish first — see After a restore.
Unpairing Tear down a paired channel and drop local state.
Update channel info Propagate post-pairing changes to communication info and/or transport endpoint.

Weighted helpers

DeRecFlow::ProtectSecret takes weights: HashMap<ChannelId, u32>, the number of subshares each paired Helper receives. with_threshold counts subshares, not Helpers: with every Helper at 1 the two coincide, but an owner who gives one Helper 2 subshares and sets threshold = 3 lets that Helper plus any one other recover, while any two of the remaining Helpers still cannot.

The map is the full assignment, not a patch. A paired Helper the map does not name receives one subshare. The intended flow:

  1. Weights are the user's choice. Before start(ProtectSecret), show the user each paired Helper's current weight, pre-filled from your channel store (HelperChannel.weight), and pass the user's final choice as the whole map. Reading the stored weights first is the normal flow.
  2. Every other start(ProtectSecret) the app makes, such as a republish after editing the secrets or the follow-up after restore, must pass the stored weights unchanged. A Helper left out returns to 1, which silently undoes the user's choice.
  3. Only the publishes the library starts on its own, after pairing and after a fingerprint is confirmed, reuse the stored weights by themselves.

Validation runs in start before anything is written or sent: every key must be a currently paired Helper channel of this secret, and every weight must satisfy 1 <= weight < threshold, so no single Helper ever holds enough subshares to recover alone. An invalid entry fails the call with no share sent and no version consumed.

Weights are recorded. Each round writes the weight it gave every paired Helper to that Helper's HelperChannel.weight, before anything is sent. The weight actually sent to each channel is also reported on ProtectSecretStarted / ProtectSecretFailed.

  • Publishes the library starts on its own — after pairing completes, after a fingerprint is confirmed — reuse the stored weights. A newly paired Helper starts at 1.
  • The weights travel in the roster (Secret.helpers[].weight). restore and replica hydration write them back into the HelperChannel records they create, so a recovered or replica device publishes with the same weights and its channel store already holds them.
  • Weights change only through start(ProtectSecret). There is no separate getter or setter: read HelperChannel.weight from your channel store.

A stored weight can become invalid. When with_threshold applies (no threshold is stored), lowering it to or below a stored weight makes the next publish fail with SharingError::InvalidWeight (invalid_weight) before anything is sent — explicit and library-initiated publishes alike. The pairing-time publish returns it from process (as a ProcessError carrying the message's events) or from accept; the fingerprint-time publish returns it from verify_fingerprint, after the channel has been promoted. Call start(ProtectSecret) with valid weights to recover.

SharingComplete.threshold_met is true when the confirmed Helpers' combined weight is >= threshold, the threshold that round split at, not when a threshold-sized count of Helpers has confirmed.

Below the threshold. When the paired Helpers' total weight is below threshold, start(ProtectSecret) skips the split: no Helper receives anything, so no ProtectSecretStarted / ProtectSecretFailed is emitted for any of them. Paired Replicas, if any, still receive their secret-only composite and report their usual events; with none paired, the call returns Ok with no events at all. This is not an error — the version still advances and the secrets/description are saved as the latest snapshot, so the next publish that reaches threshold (including one the library starts on its own, after pairing or after a fingerprint is confirmed) shares that snapshot. An app can detect the case before calling, by summing the weights it is about to assign (or the stored HelperChannel.weight of every paired Helper, for a library-initiated publish) against threshold; after calling, zero ProtectSecretStarted / ProtectSecretFailed events means nothing was split. This is more likely with weighted Helpers than with the default weight of 1: a configuration such as two Helpers at weight 2 against threshold = 3 (total weight 4) drops below threshold if a publish leaves both out of the weights map, resetting each to weight 1 under the full-assignment rule above, for a total of 2. The restore follow-up publish (see After a restore) is a typical case when it does not pass the stored weights unchanged, as that section describes.

Capping the total. Recovery time grows quadratically with the total number of subshares a round splits the secret into — measured in release mode on a laptop, about 0.2 s at 200, 5.5 s at 1,000 and 87 s at 4,000 subshares per attempt — while splitting stays cheap, so nothing warns at sharing time. with_max_subshares(max) caps that total: a round whose weights sum above it fails start(ProtectSecret) with SharingError::TooManySubshares (FFI code 66, too_many_subshares) before anything is sent and before a version is consumed. Unset means no cap. Publishes the library starts itself count the stored weights and respect the cap too. A cap below the threshold fails build() with Error::InvalidInput. The cap applies at sharing only, never at recovery: a recovering device cannot know the cap the shares were made under, and refusing there could make a secret unrecoverable.

The stateless request::split primitive takes the same weights, with the same rules, for callers working below the protocol layer — see Share Distribution.

The threshold is recorded

DeRecFlow::ProtectSecret takes threshold: Option<u32>. The t a round splits at is, in order:

  1. the explicit threshold, when Some;
  2. otherwise the stored UserSecrets::threshold;
  3. otherwise the builder's with_threshold.

Every publish stores the t it used in UserSecrets::threshold, the roster carries it (Secret.threshold), and restore and replica hydration put it back. with_threshold is therefore the starting t for a secret with nothing stored: an app that never passes threshold behaves as before until its first publish, and from then on keeps that t even if its configuration changes. Publishes the library starts on its own never pass a threshold, so they use the stored t, then the builder's.

Changing t is an explicit start(ProtectSecret) with Some(t). The new t is checked before anything is written or sent: it must be at least 2 (SharingError::InvalidThreshold), above every resolved weight (SharingError::InvalidWeight), and no greater than a with_max_subshares cap (Error::InvalidInput). A round that fails a check writes and sends nothing. Once it passes, the weights are written before anything is sent, but the new t is stored only on the round's own snapshot, saved after distribution. A snapshot never records a t its version was not split with, so a round that fails before its snapshot is saved leaves the previous t in place.

Each owner share records the t of its version (Share::threshold), which is what ShareVerified.threshold reports. There is no getter: read UserSecrets.threshold from your user-secret store.

Transport endpoints and plaintext

Every transport endpoint the protocol handles is checked in two stages.

Structure — non-empty, within the length cap, no control characters, and a scheme consistent with the declared protocol. Always applied; ws:// and file:// are refused everywhere.

Scheme policy — whether a plaintext http:// or grpc:// endpoint may actually be used. This depends on how you are deployed, so it is configuration rather than a fixed rule:

builder.with_unsafe_connection(true)   // development only; default is false
Endpoint https / grpcs plaintext loopback plaintext, any other host
Your own — with_own_transport, and the reply_to you stamp on outbound requests always always, with a warning needs with_unsafe_connection(true)
A peer's — a contact's endpoint, an UpdateChannelInfo announcement, a request's reply_to always needs with_unsafe_connection(true) needs with_unsafe_connection(true)

So a local dev server needs no configuration at all — http://localhost:8080 or grpc://localhost:50051 as your own endpoint just works. Testing across a LAN, a phone against a laptop, needs with_unsafe_connection(true) on both sides, because neither is loopback.

Loopback is free for your own endpoint because it names a service on your machine: the bytes never reach a network. It is not free for one a peer names, because there the address is chosen by somebody else and points at your machine — a peer should not be able to nominate your localhost as a reply address without you having opted into plaintext at all.

Recognition is deliberately literal: localhost, 127.0.0.1, ::1, nothing else. No DNS resolution, no private-range classification. Both would need full URI parsing, and getting that wrong in a security check is how http://127.0.0.1@evil.com/ slips past — so userinfo is refused outright and the wider case is what with_unsafe_connection is for.

This is a guardrail, not transport security. The SDK opens no sockets — delivery is your DeRecTransport. Nothing here stops an application sending plaintext; what it does is refuse to record a plaintext endpoint, refuse to propagate one to peers during pairing, and refuse to reply to one. Leaving with_unsafe_connection at its default does not by itself make a deployment secure, and turning it on does not by itself send anything in the clear.

This was a Cargo feature (unsafe-http) until it became clear a compile-time switch is unreachable for the four SDKs that install a prebuilt binary from a package manager: a .NET or Node developer has no compilation step in which to enable it. The setting is available identically in Rust, .NET, Go, Node.js and Web.

Pairing modes

DeRecProtocol::create_contact takes a ContactMode argument; the choice travels in the ContactMessage and tells the scanner which handshake to run.

ContactMode Contact carries When to use
InlineKeys Full ML-KEM encapsulation key + ECIES public key Out-of-band channel can carry ~1.7 KB (NFC, deep link, direct messaging).
HashedKeys Only a 48-byte SHA-384 commitment to the keys Out-of-band channel is size-constrained (QR codes). The scanner fetches the real keys over the wire via a plaintext PrePair round-trip and verifies them against the commitment.
NoKeys channel_id, nonce and the transport endpoint — nothing else Out-of-band channel is a human one: hand-typed, dictated over the phone, or an institutional email. Requires a caller-supplied nonce. The channel stays unusable until the fingerprint is confirmed — see below.

NoKeys is the one mode with no cryptographic binding to the keys. InlineKeys carries them in the contact; HashedKeys carries a commitment the scanner checks the fetched keys against. NoKeys carries neither, and its PrePair leg is plaintext, so an attacker who intercepts that exchange can substitute their own keys — the nonce does not prevent it, because the nonce is in the same plaintext.

The library therefore holds a NoKeys channel in ChannelStatus::Pending until verify_fingerprint succeeds: it is not a ProtectSecret target, not a recovery source, and inbound messages on it are ignored. A man-in-the-middle leaves the two sides with different shared keys and so different fingerprints, which is exactly what the comparison catches. Applications MUST also rate-limit inbound PrePairRequests per channel_id and expire outstanding NoKeys contacts on a short timer.

The library's primitives section below documents the InlineKeys and HashedKeys message-level handshakes. At the orchestrator layer, the choice is invisible to most application code after create_contact — the difference surfaces only in the events the two sides observe during the HashedKeys handshake:

  • Contact creator (the side that called create_contact): receives an ActionRequired { action_kind: "PrePair" } event when the scanner's PrePairRequest arrives. Call protocol.accept(action) to publish the keys (the orchestrator builds the response and routes it back to the scanner's transport endpoint), or protocol.reject(action, status, memo) to refuse. After accepting, the next inbound message is a regular PairRequest — its ActionRequired event is identical to the InlineKeys path.
  • Scanner (the side that called start(Pairing { contact, .. })): PrePair is silent on success. The library validates the published keys against contact.contact_binding_hash, synthesizes an InlineKeys-shaped contact, and auto-sends the regular PairRequest. The application sees PairingCompleted only after the PairResponse round-trip lands. Failure modes:
    • Contact creator rejected → DeRecEvent::PrePairRejected { channel_id, status, memo }.
    • Cryptographic binding-hash mismatch → process() returns Err(Error::Pairing(PairingError::PrePairHashMismatch)). This is a security-relevant signal — the keys published by the peer do not match the commitment the scanner originally accepted, so the contact may have been swapped or tampered between creation and scan.

Security caveat — the PrePair envelopes cross the wire plaintext. The TransportProtocol passed to create_contact (HashedKeys) MUST be an ephemeral endpoint that an observer cannot link to a long-lived identity. After pairing completes, propagate a long-term endpoint via DeRecFlow::UpdateChannelInfo; retire the ephemeral one.

This flow is covered end to end — happy path and tampered-hash — for every SDK. See End-to-end test coverage.

Pairing lifetime

A pairing is possible for Timeouts::pairing (default 30 s), measured from the contact's timestamp for the contact and from the request's timestamp for a PairRequest or PrePairRequest. Both sides enforce it, and nothing is sent when it runs out:

  • Scanner: start(Pairing) refuses a contact older than the lifetime with Error::Pairing(PairingError::Expired) (code pairing_expired), and a contact without a timestamp with PairingError::InvalidContactMessage.
  • Creator, on arrival: a request on a contact older than the lifetime, or a request older than it, is reported as MessageIgnored with IgnoreReason::Expired, before any ActionRequired, and is not answered. The creator measures its contact's age from its own stored copy, so on its own clock.
  • Creator, on accept: a request accepted after its lifetime, or on a contact that expired while the prompt waited, is refused with PairingError::Expired. No channel is recorded.

An expired contact can never pair again, so its stored material is dropped when it is next used. A request that expired on a contact still inside its lifetime leaves the contact usable, and the scanner can start again.

Pairing involves both parties, and each one checks whether it succeeded, so an expiry is a retry: tell the user to scan or share a fresh contact. Without this rule a request accepted after its scanner gave up left a channel only the creator held.

The scanner keeps its side of a pairing in flight for Timeouts::expired_channels, so that timeout should be at least Timeouts::pairing plus the time a response takes to arrive; the defaults, 300 s and 30 s, leave that margin. Ages are measured across the two devices' clocks, so clocks more than the lifetime apart cannot pair. Two starts on one contact are still the application's to reconcile: the scanner keeps only the last request's keys, so accepting the earlier one leaves a channel the scanner cannot open. Confirming a new pairing before relying on it catches both.


Replica flows

Replicas mirror the Owner's secret onto a second device so the same secrets remain accessible after device loss without going through full helper-based recovery. The model is unidirectional, exactly like Owner↔Helper:

SenderKind Role on the pair
ReplicaSource Owns the secret. Drives ProtectSecret and pushes updates.
ReplicaDestination Receives the secret. Stores Secret + share map.

Configuring replica identity

Replica pairings carry a stable per-device u64 id under the reserved derec.replica_id key in CommunicationInfo. Pass it once at builder time and the orchestrator handles injection / validation automatically:

let mut protocol = DeRecProtocolBuilder::new()
    .with_replica_id(0xAAAA_AAAA_AAAA_AAAA)
    // ... other slots ...
    .build()?;

Attempting any replica-mode flow on a protocol built without with_replica_id returns Error::ReplicaIdNotConfigured.

The reserved derec.* CommunicationInfo namespace — including derec.replica_id and its wire encoding — is documented in protocol::utils::reserved_keys. Apps should not write to this namespace; the orchestrator strips and re-injects entries at the protocol boundary.

Fingerprint confirmation

Two kinds of channel start in ChannelStatus::Pending after the handshake and are not eligible as ProtectSecret targets until both sides confirm the pair out of band:

  • Every replica channel, whatever the contact mode — admitting another device to the group is a human decision.
  • Every NoKeys channel, including owner↔helper ones. That mode commits to nothing, so the fingerprint is the only check that catches a key substituted on its plaintext PrePair leg.

A Pending channel fails closed: nothing is published to it, it is not used as a recovery source, and inbound messages on it are ignored.

The protocol derives a deterministic human-readable fingerprint from the channel key — same on both devices — that users compare visually before each side calls verify_fingerprint:

let local = source.get_fingerprint(channel_id).await?;
let peer  = destination.get_fingerprint(channel_id).await?; // out of band

source.verify_fingerprint(channel_id, &peer).await?;
destination.verify_fingerprint(channel_id, &local).await?;

verify_fingerprint succeeds on a match and transitions the channel to Paired. A mismatch fails with Error::FingerprintMismatch (code fingerprint_mismatch): the two sides hold different keys, which is what a man-in-the-middle on the pairing produces. The comparison is authoritative, so the Pending pairing is revoked — its records, channel key and pairing material are deleted — and the two devices must pair again. A channel already Paired is left as it is; removing it is an unpair.

A man-in-the-middle cannot make the two fingerprints agree by searching offline. The responder fixes every random input of the handshake key after it sees the creator's keys, so the creator draws a random fingerprint nonce, publishes a commitment to it with those keys (inline in an InlineKeys contact, in the PrePairResponse otherwise) and reveals it only in the pair response, after the handshake key is fixed. The channel key, and so the fingerprint, is derived from both. A pair response whose nonce does not open the commitment fails with PairingError::FingerprintCommitmentMismatch (code fingerprint_commitment_mismatch) and the pairing does not complete. This holds in every contact mode.

Confirmation is also the moment the peer becomes reachable, so the current snapshot is published to it then — a NoKeys helper was not an eligible target at handshake time, and the pairing-time auto-publish skipped it.

On a replica destination, confirming is also the decision to adopt the group's vault. Once the channel is Paired, the source's publish is installed into this device's stores as it arrives, with no further prompt. Ask the user whether to adopt the vault before calling verify_fingerprint; to decline, never confirm, and the channel stays Pending, unused, until expired-channel cleanup removes it together with its key.

Secret distribution

Once the destination is paired (status Paired), the source includes it as a ProtectSecret target alongside helpers. The orchestrator routes two payload shapes from the same start call:

  • Helpers receive the usual VSS share via StoreShareRequest.
  • Destinations receive a typed ReplicaSecretPayload { secret: Secret, shares: Vec<ChannelShare>, version } — the full secret plus every helper's share keyed by channel_id. This is what lets a destination act in the source's place during recovery without re-running the share collection.

On the destination, the inbound envelope decodes into DeRecEvent::ReplicaSecretReceived with secret: Secret and shares: Vec<ChannelShare> already parsed — the app just installs the secrets.

The library also writes that share map to the share store as this device's own owner-side tracking shares, at the same (channel_id, version) keys the source used. That is what makes verification work on a destination: a VerifyShare proof is SHA-384(share ‖ nonce) over the exact bytes the helper holds, so without the map a destination could challenge its helpers and receive their answers but have nothing to check them against. A destination that takes over a mirrored vault can therefore verify it exactly as the source could. The same map travels on a replica catch-up, so a member that became current by pulling is no less able to verify than one that received a push.

A destination keeps every proof it receives and never deletes one on its own; freeing them is the application's concern (see Which versions to verify).

When a mixed round reports

A round that targets both helpers and replica members reports only once both populations have settled. SharingComplete and ReplicaSyncComplete are emitted together, at that moment.

The counts on SharingComplete describe helpers only and are known the instant the helpers answer — but the event is held until every member has acknowledged, refused, or timed out. So one unreachable member delays it by up to with_timeout, even though the helpers confirmed in milliseconds.

Nothing is lost and the round always terminates: the timeout sweep closes it, and a member that never answered is reported in behind rather than failing the round. The application is simply told late, which is easy to mistake for a hang.

Two things follow for application authors:

  • Do not drive a "your secret is protected" indicator from SharingComplete alone if replicas are in play. Watch the per-peer ShareConfirmed events instead — those land as each helper answers, with no cross-population wait.
  • Call tick() on a schedule. Timeouts only advance inside process and tick, so an idle protocol with a stranded round never closes it at all.

A helpers-only round is unaffected and completes as soon as the helpers answer.

Refused copies

A member checks the whole of an incoming copy before writing any of it, so a copy is applied in full or not at all. One that does not decode or is not self-consistent (a share map naming a helper the roster does not list, a version or group key that disagrees with the request, a malformed key, id or role) is refused with FORMAT_ERROR; one whose share map carries a share that does not verify against its commitment, with VERIFICATION_FAILED. The receiving member emits ReplicaSecretRefused { channel_id, from_replica_id, secret_id, version, status, memo } and answers the publisher whatever auto_respond_on_failure says; the publisher sees ReplicaSyncRejected with the same status and memo, and the member lands in behind. A refused admission handover is answered on the group channel under the group key it carried. A copy served by a catch-up is checked the same way and reported with the same event; nothing is answered, since that copy is itself an answer.

Version conflicts: what the application must do

Every member derives the next version from the one it holds, and a newer version replaces an older one wherever it lands. Two copies of the same version collide, and the library reports the collision instead of merging:

  • the member that received a rival copy emits ReplicaVersionConflict, carrying the rival's full state in secret, and keeps its own copy;
  • the member whose copy was refused emits ReplicaSyncRejected with status VERSION_CONFLICT.

This does not need two devices to be edited at the same moment. A member that was offline while another published, and then protects a change of its own, publishes the same version as a rival copy.

From either event until the conflict is resolved, the device's copy has diverged from the group's. Do not publish from it again until the user has resolved the conflict. A further ProtectSecret writes a higher version, which every other member applies over its own copy: the change it never merged is lost, from the members and, on that round, from the helpers.

To resolve:

  1. Mark the vault as diverged and stop offering ProtectSecret on this device.
  2. Get the rival copy. ReplicaVersionConflict already carries it in secret. After ReplicaSyncRejected, run ReplicaDiscovery: the group's copy arrives as a ReplicaVersionConflict.
  3. Show the user both copies — this device's, from its own stores, and the rival's — and let them merge them or keep one.
  4. Publish the result once with ProtectSecret. It writes the next version, which every member and helper takes, and the conflict is resolved. To keep the rival's copy unchanged, publish its secrets.

A member that changes its endpoint or communication_info announces it by publishing too; see On a replica member.


Correlation and routing on the wire

Two metadata fields cut across every channel-mode exchange:

traceId — request/response correlation

DeRecMessage.traceId is an opaque uint64 correlation token on the plaintext outer envelope. The requester sets it; the responder echoes it verbatim. The orchestrator (DeRecProtocol) handles both sides automatically — every outbound request gets a fresh random token via fresh_trace_id; every response is stamped with the inbound trace id via apply_trace_id.

Consumers driving the protocol through primitives (not the orchestrator) get trace_id = 0 (the protobuf default) by default and can opt in manually using the envelope helpers:

use derec_library::derec_message::{apply_trace_id, read_trace_id};

let outbound = apply_trace_id(&envelope_bytes, my_token)?;
// …send outbound…

let inbound_token = read_trace_id(&response_bytes)?;
// match `inbound_token` against `my_token` to correlate

The same helpers are surfaced as envelope.apply_trace_id / envelope.read_trace_id on the nodejs/web packages and as apply_trace_id_to_envelope / read_trace_id_from_envelope on the FFI (plus a Envelope.ApplyTraceId / Envelope.ReadTraceId static class on the dotnet package). The encrypted inner message is never touched, so re-stamping has no crypto cost.

Matching responses to requests is the application's job

The library does not check that a response answers a request this device sent. Every response arrives on a channel authenticated with its channel key, from the peer paired on it, and the library acts on it only as far as its own state needs:

  • A response that would change stored state is applied only against the state the matching flow left behind: GetShareResponse against a recovery in progress for that secret and version, VerifyShareResponse against the outstanding challenge on that channel, UnpairResponse against an unpair this side started, and a replica discovery answer against a discovery in progress. Anything else is dropped as NoOp.
  • A sharing round counts a StoreShareResponse only while that round is open and still waiting on that helper.
  • A replica catch-up (GetShareResponse from a group member) is applied by the same rule as a pushed copy: only when it is newer than what this device holds.
  • Every other response is reported as it arrives, without being matched: ShareConfirmed and ShareRejected (whether or not a round counts them), SecretsDiscovered, ChannelInfoUpdated, ChannelInfoUpdateRejected and ErrorResponseReceived.

Keeping track of what it asked, and pairing each answer with its request, is the application's concern. An application that acts on these events should record what it started (the flow, channel, secret and version) and match each event against that record, using traceId (above) where it needs an exact pairing. In particular, decide which versions committed from SharingComplete { threshold_met }, which counts each helper of the round at most once, rather than by counting ShareConfirmed events: a helper can send the same confirmation twice, or one nobody asked for. This is the answer keep_version needs.

replyTo — ephemeral response routing

replyTo is an optional TransportProtocol on request bodies (StoreShareRequest, VerifyShareRequest, GetSecretIdsVersionsRequest, GetShareRequest, UnpairRequest). It tells the responder to route this exchange's response to an alternate endpoint — without persisting it (use UpdateChannelInfo for a permanent change).

The motivating case is replicas: when Replica A sends a request on a channel the helper paired with sibling Replica B, the helper's stored peer endpoint points at B. replyToTransports lets A say "send the response back to me," without rewriting channel state.

Two ways to set it:

  • Per call (primitives): every *::request::produce takes a trailing reply_to: &[TransportProtocol] parameter, in preference order.
  • Protocol-wide: DeRecProtocolBuilder::with_auto_reply_to(true) makes the orchestrator stamp replyToTransports = own_transports on every outbound request automatically.

The responder honours an inbound replyToTransports regardless of how it was set — the flag only governs outbound population. PairRequest, PrePairRequest, and UpdateChannelInfoRequest are intentionally excluded: each already carries its own supportedTransports field serving the same role.


Storage and transport traits

The library does not ship a default backend for storage or transport. Consumers implement six traits — five stores plus the transport. All are required to build a protocol instance. The protocol holds them by &mut self, so implementations need no internal synchronization:

Trait Stores
DeRecChannelStore Helper channels (keyed by channel_id), replica-group members (keyed by replica_id), and the channel-link graph.
DeRecShareStore Encoded share entries keyed by (secret_id, channel_id, version) — the secret_id argument, which is the partition every load filters by. Share::secret_id is a different value and routinely differs from it; see below.
DeRecSecretStore Per-channel cryptographic material (shared keys, pairing secrets, pairing contacts).
DeRecUserSecretStore The latest user-facing secret snapshot per secret_id — what a freshly-paired peer is sent.
DeRecStateStore In-flight orchestrator state: verification challenges, recovery accumulators, pending unpairs, the active sharing round and catch-up. Must be durable in any deployment that can restart mid-flow.
DeRecTransport Outbound envelope delivery to peers.

Each trait's rustdoc states its contract, idempotency expectations, and the security classification of the data it holds (DeRecSecretStore content is keychain-grade; the others need durable storage only).

Share store: secret_id is the partition, not Share::secret_id

Every DeRecShareStore method takes a secret_id. That is this device's own partition — the namespace it stores under, and the value every load filters by. Share::secret_id names the secret the bytes belong to, which on a helper is the owner's id. A helper holds shares belonging to other people's secrets, so one partition can legitimately hold several secrets at the same version, and Share::secret_id is the only thing that tells them apart.

So save must key on the argument and carry share.secret_id alongside as data. Two ways to get this wrong, both of which have shipped:

  • Keying on share.secret_id puts rows where no load looks, because the reads filter on the partition. The store silently discards everything it is given, and every helper-side verification and recovery answer fails.
  • Asserting the two are equal fires on the ordinary case of a helper holding someone else's share.

Share store: Share::subshares

Share::subshares: Option<u32> is the number of subshares the share carries, recorded on the owner side only. The library sets it on every share the owner side saves (including a replica Destination's mirrored copies) and leaves it None on every helper-side share. Persist it as given, including None (a nullable column in SQL), and return it unchanged. Owner rows written before the field existed read back as None; the library never backfills them. It is what ShareVerified.subshares reports; see Judging a version's recoverability.

Share::threshold: Option<u32> is the threshold the share's version was split with, under the same rules: set on the same owner-side shares, None on a helper's share and on rows written before it existed, never backfilled. It is what ShareVerified.threshold reports. UserSecrets::threshold: Option<u32> is the stored threshold the next publish splits at; persist it with the snapshot, including None.

Share store: the owner's keep version

Every StoreShareRequestMessage carries a keepVersion: the one version, other than the one being shared, that the helper keeps. Once the incoming share is stored, the helper deletes every other version it holds on that channel (through remove_versions). keepVersion = 0 keeps no other version, so a helper holds at most two versions of a secret.

The owner chooses it by asking its share store once per sharing round, before anything is sent, through DeRecShareStore::keep_version(secret_id, version), where version is the version about to be distributed. Every round asks, whether the application started it with ProtectSecret or the library did (the pair-completion and fingerprint-confirmation publishes), and every helper in the round receives the same answer. An answer equal to or greater than version fails the round with SharingError::InvalidKeepVersion (invalid_keep_version, code 67) before anything is sent; a helper that receives one refuses the request with FORMAT_ERROR and stores nothing.

Return the last version that is valid: the newest one whose SharingComplete reported threshold_met. The version being sent has not committed yet when keep_version is asked, and its round may never reach threshold, so the last committed version must stay. Only the application knows which versions committed; nothing in the stores records it.

For example, an owner with seven helpers:

  1. Sends v1 with keepVersion = 0. Every helper stores it and answers.
  2. Sends v2 with keepVersion = 1. Only three helpers answer, so v2 never reaches threshold. Those three hold v1 and v2.
  3. Sends v3 with keepVersion = 1, since v1 is still the last valid version. Every helper answers. The three that hold v2 delete it; the other four hold only v1, which they keep. Every helper ends with v1 and v3.

A version whose round is still open when the next one starts is deleted from every helper that stores the next one, unless it is the version returned. A helper that receives a request older than the latest version it holds on the channel never deletes a newer share: a version it still holds is an identical re-send whose keepVersion is ignored, and one it does not hold is ignored as MessageIgnored with IgnoreReason::Superseded, unanswered, so a version already deleted is not stored again.

A replica member publishing as the source cannot tell which versions it mirrored had committed on the previous source. Returning the newest version it mirrored is the closest it can get. Replica pushes never consult keep_version, and a replica Destination never deletes a version because of it.

The answer governs this device's own rows too. When a helper confirms the round, the library deletes, through remove_versions, this device's proofs for that channel other than the confirmed version and the returned one, since the helper has deleted those shares. A helper that rejects the round keeps its older versions, and so does this device.

Transport: implement SendOne, not send

DeRecTransport::send receives every endpoint a peer advertised and leaves the choice among them to you, because only your application knows which of its transports are healthy, cheap, or currently reachable. That decision stays yours. The bookkeeping around it does not: try in order, stop at the first success, fail only when none worked, never deliver twice.

Implement SendOne — deliver to one endpoint — and wrap it:

let transport = SequentialFailover::new(MyDialer);

SequentialFailover is the right default. SingleEndpointTransport uses only the first endpoint, which is what endpoints[0] written inline does — the difference is that choosing the type is visible to a reviewer, where the index reads as finished code. Every binding ships both: SequentialFailover / SingleEndpointTransport (.NET, Go), sequentialFailover(dialer) / singleEndpointTransport(dialer) (Node, web, React Native).

Do not deliver to every endpoint. They all address the same peer, so a fan-out sends one authenticated message several times.

Filtered listings

DeRecChannelStore::helpers and DeRecChannelStore::replicas take a ChannelFilter — ids, status, role and exclude, where every empty value means "do not restrict on this", so a Default filter selects everything.

Returning everything is correct. Ignore the filter and return every record under the secret_id unless you have a measured reason not to. The library re-applies the filter to every listing before acting on it and drops anything the filter excluded, so a superset is trimmed to exactly the right set.

Pushing it into your query is an optimization you opt into. A WHERE clause or a key-condition expression avoids transferring rows the caller will discard, which costs bandwidth everywhere and real money on a metered backing such as DynamoDB that bills by bytes read.

The two directions are not symmetric, which is why that is opt-in. Dropping rows enforces an upper bound, so returning too many costs only the transfer. It cannot recover a row that was never returned: a pushdown selecting too few is wrong in a way nothing can detect at runtime — no exception, no event, just a share that was never published.

So verify a pushdown. library/tests/fixtures/channel_filter.json is a table of (records, filter, expected) cases covering the clauses that are easy to get subtly wrong — empty-means-unrestricted per field, role as an optional, exclude applied after and overriding ids, and ids above 2^53. Every binding drives it; a store that pushes down should too. ChannelFilter::matches is the same predicate the library re-checks with, exported for stores that would rather filter in memory than translate.

The same filter crosses every binding: as a JSON object over the C ABI (list_helpers / list_replicas gain a filter buffer), and as a plain object on the WASM bridges.

Choosing backends at run time

DeRecProtocol is generic over all six, so by default the concrete backends are baked into its type. To pick one at run time — Postgres in production, in-memory under test — box the trait objects; the library implements every trait for Box<T> and &mut T, so an erased protocol satisfies the builder's bounds without any wrapper of your own:

type AnyProtocol = DeRecProtocol<
    Box<dyn DeRecChannelStore>,
    Box<dyn DeRecShareStore>,
    Box<dyn DeRecSecretStore>,
    Box<dyn DeRecUserSecretStore>,
    Box<dyn DeRecStateStore>,
    Arc<dyn DeRecTransport>,
>;

let protocol = DeRecProtocolBuilder::new(secret_id)
    .with_channel_store(Box::new(PostgresChannelStore::new(db)) as Box<dyn DeRecChannelStore>)
    // ...the rest of the stores, then a transport shared across requests:
    .with_transport(Arc::clone(&http))
    .build()?;

Arc<T> is implemented for DeRecTransport only. Every store has &mut self methods and Arc never yields &mut T, so a store behind an Arc cannot compile. The transport is the one &self-only trait — which is also the one worth sharing, since it is typically a pooled client.


Errors

Public errors are structured and typed:

The protocol never panics on malformed input. A message that fails to decode or decrypt before a channel key authenticates it surfaces as a typed Error::ProtobufDecode / Error::Pairing(PairingError::PairingEncryption(..)) and is never answered. A body that fails to decode after the channel key authenticated it is a failed request, answered and reported as RequestFailed; see Failed requests.


Async and executors

Storage and transport methods return type-erased futures (SecretStoreFuture and friends). No specific executor is prescribed:

  • Native targets — futures are Send, so they can be spawned on multi-threaded executors such as tokio::spawn.
  • ffi feature or wasm32 target — the Send bound is dropped because the host runs single-threaded or callbacks cross an FFI boundary.

Sync backends can implement the trait methods with Box::pin(std::future::ready(...)) at zero cost; async backends use Box::pin(async move { ... }).


WebAssembly support

The same protocol layer is exposed to JavaScript/TypeScript via wasm-bindgen. Packages:

import { primitives } from "@derec-alliance/nodejs"; // or @derec-alliance/web

const result = primitives.verification.request.produce(
  channelId, secretId, version, sharedKey,
);
// result carries the encoded DeRecMessage envelope, ready to send over transport

The TypeScript bindings expose both the protocol layer (via the DeRecProtocol class) and the primitives surface. See the package READMEs for full TypeScript examples.


Transport layer

The protocol is transport-agnostic. The TransportProtocol value carried in contact and pairing messages identifies the peer endpoint; the application's DeRecTransport implementation decides how to deliver bytes (HTTPS, gRPC, WebSocket, message queue, custom relay, …).

[!NOTE] The on-the-wire TransportProtocol.protocol enum defines two values, Https and Grpc. The library validates and propagates grpcs:// / grpc:// endpoints exactly as it does HTTPS ones, but never implements the gRPC side itself: derec-proto ships the DeRecTransport service contract (rpc Send(DeRecMessage) returns (google.protobuf.Empty)) with no generated service stubs. Consumers who want stubs run their own tonic-prost-build against the schema derec-proto carries — enable its descriptor feature on a build-dependency and pass descriptor::transport_descriptor() to compile_fds; the derec-proto README has the full recipe and smoke-tests/grpc is a complete worked reference. No .proto file or include path is involved. New transports can be added by extending the protobuf enum.

An application serving more than one transport declares them all, in preference order:

builder.with_own_transports([
    "grpcs://me.example.com:443",
    "https://me.example.com/derec",
])

The list is advertised to peers as supportedTransports on contacts and pair requests, and it is what decides which of a peer's endpoints gets used: each side independently picks, from what the other offered, the first entry matching its own order. Nothing is negotiated on the wire, so there is no extra round trip. An endpoint offered by a peer that fails structural validation or scheme policy is skipped rather than fatal; no overlap at all is Error::NoUsableEndpoint, and at pairing time it is terminal — delivery is push-only, so a peer whose transport you cannot speak cannot be sent a rejection either.

Order is meaningful and the first entry is also your primary endpoint. Because delivery is push-only, every entry must be a transport you actually serve: listing one you do not makes pairing succeed and replies vanish. The equivalents are WithOwnTransports (.NET), withOwnTransports (Node.js / Web) and Config.OwnTransports (Go).

To change the set after construction, use set_own_transports — the runtime counterpart. It validates every entry before storing any, so a malformed URI leaves the previous set intact. The equivalents are setOwnTransports (Node.js / Web / React Native) and SetOwnTransports (Go).

Serving DeRec over request/response transports

The protocol is a mailbox: every participant has an address, and answering someone means posting to their address. A reply produced while handling an inbound message is not returned to the caller — it is handed to DeRecTransport::send, addressed to the peer's endpoint, while process() returns only the DeRecEvents describing what happened.

When both sides are reachable services, that is all you need. The transport is a one-way push and an HTTP handler acknowledges rather than answers:

async fn inbound(State(app): State<App>, body: Bytes) -> StatusCode {
    let mut protocol = app.build_protocol(HttpPush(app.http.clone()));
    let events = protocol.process(&body).await.expect("process");
    app.on_events(events).await;
    StatusCode::ACCEPTED // the reply is already on its way, separately
}

A peer with no address breaks this silently. A phone, a browser tab or anything behind NAT advertised an endpoint at pairing time that nothing can actually reach, so a push-style send drops the reply on the floor. Nothing errors — process returned events and the handler looks successful — the peer just never hears back.

Those deployments must answer on the connection the request arrived on, which means capturing what the protocol emits instead of pushing it:

async fn inbound(State(app): State<App>, body: Bytes) -> Result<Bytes, StatusCode> {
    // 1. Build per request, with a transport that collects rather than sends.
    let collector = Collector::default();
    let mut protocol = app.build_protocol(collector.clone());

    let events = protocol
        .process(&body)
        .await
        .map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
    app.on_events(events).await;

    // 2. One `process` can emit several messages. Only the one echoing this
    //    request's trace_id answers the caller; the rest is real fan-out and
    //    still has to reach its own endpoint.
    let (reply, elsewhere) = split_reply(&body, collector.take());
    for (endpoint, bytes) in elsewhere {
        app.deliver_out_of_band(endpoint, bytes).await;
    }

    Ok(reply.map(Bytes::from).unwrap_or_default())
}

Two details carry this, and both are easy to miss:

  • Per-request construction. The collector's buffer must belong to exactly one exchange, or concurrent requests mix their replies. This is the same per-request pattern a stateless deployment uses anyway.
  • Correlation by trace_id. Admitting a helper also republishes to every other helper, so the buffer routinely holds messages for several peers. Responses echo the inbound envelope's trace_id; derec_message::read_trace_id tells them apart. Returning the whole buffer — or blindly returning its first entry — is the mistake to avoid.

Collector and split_reply are about twenty lines each; a complete, compiled version of both is in the DeRecTransport rustdoc.

Every SDK exposes the same correlation primitive: Envelope.ReadTraceId (.NET), envelope.ReadTraceID (Go), envelope_read_trace_id (TypeScript/WASM), read_trace_id_from_envelope (C FFI).

[!NOTE] The HTTP details above — POST to the peer's URI, the raw DeRecMessage bytes as the body with Content-Type: application/octet-stream, 202 Accepted with an empty body on a push, 200 OK with the reply as the body on a same-connection answer — are recommended HTTP conventions, not protocol requirements. Matching by trace_id applies to the 200 OK same-connection answer only: a push carries no reply to match. The protocol fixes only the envelope bytes and push delivery. See Transports in the DeRec documentation.

Updating channel info post-pairing

A peer's communication_info and transport endpoints are exchanged at pairing time. To propagate later changes, mutate local state with DeRecProtocol::set_communication_info / set_own_transports and then run start(DeRecFlow::UpdateChannelInfo { ... }) against the target channels. Per-field semantics:

  • communication_info: Option<HashMap<String, String>> — None leaves the peer's stored map untouched. Some(_) replaces it; an empty map clears it.
  • own_transports: Vec<TransportProtocol> — empty leaves the peer's stored endpoints untouched; otherwise it replaces them, in preference order.

UpdateChannelInfo reaches helper channels only. A replica member announces a change by publishing instead — see On a replica member below.

The flow is symmetric — either Owner or Helper may initiate it — and auto-applies on the receiver via the standard ActionRequired → accept path. Outcome surfaces as DeRecEvent::ChannelInfoUpdated (or ChannelInfoUpdateRejected if the peer refused).

The receiver filters the announced endpoints with its transport policy when it accepts the update, exactly as it filters a peer's endpoints at pairing. Which transports the receiver serves itself has no bearing on where the peer may listen.

[!WARNING] Endpoint changeover discipline. When transport_protocol is updated, the receiving peer sends its response to the new endpoint. The application MUST bring up the new endpoint and start listening on it before initiating the flow, and MUST keep the old endpoint operational until every targeted peer has emitted ChannelInfoUpdated / ChannelInfoUpdateRejected (plus a grace window for in-flight messages from peers not yet aware of the update). Failing to keep both endpoints reachable during this window will cause messages to be lost. See the rustdoc on set_own_transports for details.

On a replica member

Replica members do not exchange UpdateChannelInfo. A member's endpoints and communication_info travel in the group roster, and a member's own row is refreshed from its current configuration each time it publishes. Every member that receives the publish takes the roster as authoritative and records the new values. A member that changes either one therefore announces it in two steps:

  1. Publish a new version with ProtectSecret — the same secrets are fine. Every replica records the member's new row, so any of them can take over immediately, and the helpers receive a roster that is recoverable with the new values. The version is new, and so is the helper re-share round; a roster that must be recoverable has to reach the helpers anyway.
  2. Run UpdateChannelInfo against the helpers. A helper cannot read the roster — it holds an encrypted share — so it learns the new endpoint only from this flow.

The order is the application's choice: publishing first lets the replicas follow at once. Until enough peers have the update, keep the old endpoint serving:

  • Advertise only the new endpoint, keep the old one serving. A device advertises at most one endpoint per protocol, so the old one is not listed; it simply keeps answering until peers stop using it. A peer that already has the update answers on the new endpoint and drops the old one.
  • Switch endpoints before step 1. Call set_own_transports with the new endpoint before publishing: the member's roster row is taken from it. In step 1, helpers still hold the old endpoint. To have their answers come back on the new one, build the protocol with with_auto_reply_to(true): every round then carries reply_to set to the current own transports, which set_own_transports has just changed. There is no per-round reply_to on ProtectSecret; this flag is how every SDK sets it (withAutoReplyTo, WithAutoReplyTo, Go's Config.AutoReplyTo). Without it, helpers answer on the old endpoint, which is why it keeps serving.
  • Enough peers, not all. Wait until enough helpers to recover the secret, and the replicas the application relies on, have confirmed. Retry the rest, or suggest a new round later; how long the old endpoint stays up is the application's decision.
  • A member that missed step 1 still holds the old row. If it publishes before catching up, its roster carries the old values back to everyone. Its version collides with the new one, so the rule in Version conflicts applies: it must not publish until it has caught up, and the application can retry the update once it has.

Observability

The library emits structured tracing spans and events for every protocol step. Instrumentation is off by default and opt-in via the logging feature flag — enabling it adds no overhead when no subscriber is active.

Enabling

[dependencies]
derec-library = { version = "*", features = ["logging"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

Wiring up a subscriber

tracing_subscriber::fmt()
    .with_env_filter(
        tracing_subscriber::EnvFilter::from_env("DEREC_LOG")
    )
    .init();

Controlling the log level at runtime

# Protocol milestones only (contact created, pairing complete, share stored, …)
DEREC_LOG=info ./my-app

# Intermediate state — sizes, versions, channel IDs
DEREC_LOG=debug ./my-app

# Full detail including byte lengths from the cryptography layer
DEREC_LOG=trace ./my-app

# Only DeRec events, silence everything else
DEREC_LOG=derec_library=debug,derec_cryptography=debug ./my-app

What is logged

Level Content
info Protocol milestones — contact created, pairing complete, share split, share stored, verification result, secret reconstructed.
debug Intermediate state — channel IDs, versions, thresholds, response counts.
trace Low-level byte lengths from the cryptography layer.

Security guarantee: secret bytes, symmetric keys, and share content are never emitted. Only non-sensitive metadata (lengths, identifiers, roles) appears in events.


Primitives (advanced)

Use the protocol layer unless you have a specific reason not to. The primitives surface is documented here for embedders who need to construct/parse individual messages directly or are integrating into an orchestrator they already own.

Each flow has a primitives::<flow> module with request and response submodules. The general pattern is:

  • produce(...) — construct an outbound envelope, returning encoded wire bytes.
  • extract(envelope_bytes, ...) — decrypt and decode an inbound envelope into the typed inner message.
  • process(...) — interpret the decoded inner message (when there's logic beyond decoding).

Pairing

The contact message is exchanged out-of-band (QR codes, existing messaging channels, etc.). Three modes select how the initiator's public encryption material is delivered:

ContactMode What's in the contact When to use
InlineKeys (default) Full ML-KEM encapsulation key + ECIES public key Out-of-band channel can carry the keys (e.g. NFC, direct messaging).
HashedKeys Only a SHA-384 commitment to the keys (contact_binding_hash) The out-of-band channel is size-constrained (QR codes). The scanner fetches the actual keys over the wire via a PrePair round-trip, then verifies them against the hash.
NoKeys channel_id, nonce and the transport endpoint only The out-of-band channel is human — hand-typed or dictated. Nothing commits to the keys, so the channel stays Pending until the fingerprint is confirmed. See Pairing modes.

After the handshake completes, every mode rekeys the channel id. The responder includes channel_id = u64::from_be_bytes( SHA-384(u64_be(originalId) || sharedKey)[..8] ) in the encrypted PairResponseMessage; both sides switch their local channel record to that value and route all future traffic on it. Because the new id travels encrypted, a passive observer who only saw the pre-rekey traffic cannot link the long-running channel back to its pairing-time id.

InlineKeys flow

use derec_library::primitives::pairing::{request, response};
use derec_library::types::ChannelId;
use derec_proto::{ContactMode, Protocol, SenderKind, TransportProtocol};

let channel_id = ChannelId(42);

// Step 1 — Initiator creates the contact message (sent out-of-band).
let request::CreateContactResult {
    contact_message,
    secret_key: initiator_secret_key,
} = request::create_contact(
    channel_id,
    ContactMode::InlineKeys,
    TransportProtocol {
        uri: "https://relay.example/derec".to_owned(),
        protocol: Protocol::Https.into(),
    },
).unwrap();

// Step 2 — Responder decodes the contact and produces the request envelope.
let request::ProduceResult {
    envelope: pair_request_envelope,
    initiator_contact_message,
    secret_key: responder_secret_key,
} = request::produce(
    SenderKind::Helper,
    TransportProtocol {
        uri: "https://example-helper.com/derec".to_owned(),
        protocol: Protocol::Https.into(),
    },
    &contact_message,
    None, // optional CommunicationInfo
).unwrap();

// Step 3 — Initiator extracts the request and produces the response.
let request::ExtractResult { request: pair_request } =
    request::extract(
        &pair_request_envelope,
        initiator_secret_key.ecies_secret_key(),
        None, // local ParameterRange; checked against the requester's
    ).unwrap();
let response::ProduceResult {
    envelope: pair_response_envelope,
    shared_key: initiator_shared_key,
    channel_id: rekeyed_channel_id,
    ..
} = response::produce(
    channel_id,
    &pair_request,
    &initiator_secret_key,
    None,
).unwrap();

// Step 4 — Responder extracts the response and finalizes pairing.
let response::ExtractResult { response: pair_response } =
    response::extract(&pair_response_envelope, responder_secret_key.ecies_secret_key()).unwrap();
let response::ProcessResult {
    shared_key: responder_shared_key,
    channel_id: responder_rekeyed_id,
} = response::process(
    &initiator_contact_message,
    &pair_response,
    &responder_secret_key,
    None, // local ParameterRange; checked against the contact creator's
).unwrap();

// Both sides now hold the same shared key and the same rekeyed channel id;
// rename local channel state from `channel_id` to `rekeyed_channel_id`
// before sending any further traffic.
assert_eq!(initiator_shared_key, responder_shared_key);
assert_eq!(rekeyed_channel_id, responder_rekeyed_id);
assert_ne!(rekeyed_channel_id, channel_id);

To reject the request, build a PairResponseMessage with a non-Ok StatusEnum and encrypt it with DeRecMessageBuilder::pairing() against the peer's request.ecies_public_key. The protocol-layer reject method does this for you. Rejected responses do not carry a meaningful channel_id — the rekey only takes effect on Ok responses.

HashedKeys flow (PrePair)

HashedKeys adds one plaintext round-trip before the regular InlineKeys handshake. The scanner fetches the keys via PrePair, verifies them against contact.contact_binding_hash, and then runs the normal pairing flow on a synthesized ContactMessage with the keys filled in.

use derec_library::primitives::pairing::{request, response};
use derec_library::types::ChannelId;
use derec_proto::{ContactMode, ContactMessage, Protocol, SenderKind, TransportProtocol};

let channel_id = ChannelId(7);

// Initiator: HASHED_KEYS contact (no inline keys, only the binding hash).
// The transport URI MUST be ephemeral — PrePair envelopes are plaintext.
let request::CreateContactResult {
    contact_message: contact,
    secret_key: initiator_secret_key,
} = request::create_contact(
    channel_id,
    ContactMode::HashedKeys,
    TransportProtocol {
        uri: "https://relay.example/ephemeral".to_owned(),
        protocol: Protocol::Https.into(),
    },
).unwrap();

// Scanner: fetch keys via PrePair.
let request::ProducePrePairResult { envelope: pre_pair_req_env } =
    request::produce_pre_pair_request(
        TransportProtocol {
            uri: "https://relay.example/scanner-ephemeral".to_owned(),
            protocol: Protocol::Https.into(),
        },
        &contact,
    ).unwrap();
let request::PrePairExtractResult { request: pre_pair_req } =
    request::extract_pre_pair(&pre_pair_req_env).unwrap();
let response::ProducePrePairResult { envelope: pre_pair_resp_env } =
    response::produce_pre_pair(channel_id, &pre_pair_req, &initiator_secret_key).unwrap();
let response::PrePairExtractResult { response: pre_pair_resp } =
    response::extract_pre_pair(&pre_pair_resp_env).unwrap();

// Scanner validates the published keys against `contact.contact_binding_hash`;
// returns the keys, the nonce and the creator's fingerprint commitment on
// match, errors with `PairingError::PrePairHashMismatch` on mismatch.
let validated = response::process_pre_pair(&contact, &pre_pair_resp).unwrap();

// Synthesize a "filled-in" contact and run the regular pairing flow. The
// mode flip is required — `request::produce` enforces `InlineKeys` and
// rejects a contact that still advertises `HashedKeys`. The commitment
// travels with the keys: `response::process` refuses a pair response whose
// fingerprint nonce does not open it.
let filled_in_contact = ContactMessage {
    mlkem_encapsulation_key: Some(validated.mlkem_encapsulation_key),
    ecies_public_key: Some(validated.ecies_public_key),
    fingerprint_commitment: Some(validated.fingerprint_commitment),
    contact_mode: ContactMode::InlineKeys as i32,
    contact_binding_hash: None,
    ..contact.clone()
};
// ... continue with request::produce / extract / response::produce / process
// against `filled_in_contact` exactly as in the InlineKeys example.

After the PrePair exchange the application must swap the transport endpoint to a long-term one via UpdateChannelInfo. The ephemeral endpoint advertised in the HashedKeys contact is intended to be retired immediately after pairing.

Share Distribution

use derec_library::primitives::sharing::request;
use derec_library::types::{ChannelId, WeightedChannel};

let secret_id: u64 = 42;
let secret_data = b"super_secret_value";
// Every channel is listed with its weight: the number of subshares its share
// carries. An ordinary helper has weight 1; each weight must be < threshold.
let channels: [WeightedChannel; 3] = [(ChannelId(1), 1), (ChannelId(2), 1), (ChannelId(3), 2)];
let threshold = 3; // 2 <= threshold <= total subshares (the sum of the weights)
let version: u32 = 1;

let request::SplitResult { shares } = request::split(
    &channels,
    secret_id,
    version,
    secret_data,
    threshold,
).unwrap();
// shares: HashMap<ChannelId, CommittedDeRecShare>
// Pass each share to request::produce() to create encrypted delivery envelopes.

Verification

use derec_library::primitives::verification::{request, response};
use derec_library::types::ChannelId;

let channel_id = ChannelId(1);
let secret_id: u64 = 42;
let version: u32 = 7;
let shared_key = [0u8; 32]; // established during pairing

// Owner side: produce and send the verification request.
let result = request::produce(channel_id, secret_id, version, &shared_key).unwrap();
let request_wire_bytes = result.envelope;

// Helper side: decrypt and extract the inner request.
let request::ExtractResult { request: verify_request } =
    request::extract(&request_wire_bytes, &shared_key).unwrap();

// Helper side: produce the response, proving possession of the share.
let resp_result =
    response::produce(channel_id, &verify_request, &shared_key, b"example_share").unwrap();
let response_wire_bytes = resp_result.envelope;

// Owner side: decrypt and verify the proof.
let response::ExtractResult { response: verify_response } =
    response::extract(&response_wire_bytes, &shared_key).unwrap();
let ok = response::process(&verify_response, b"example_share").unwrap();

assert!(ok);

Discovery

use derec_library::primitives::discovery::{
    request,
    response::{self, SecretVersionEntry, VersionEntry},
};
use derec_library::types::ChannelId;

let channel_id = ChannelId(1);
let shared_key = [0u8; 32]; // established during pairing

// Owner side: produce the discovery request.
let request::ProduceResult { envelope: request_envelope } =
    request::produce(channel_id, &shared_key).unwrap();

// Helper side: extract the request, enumerate stored secrets, produce the response.
let _req = request::extract(&request_envelope, &shared_key).unwrap();

let stored: Vec<SecretVersionEntry> = vec![
    SecretVersionEntry {
        secret_id: 1,
        versions: vec![VersionEntry { version: 1, description: "Main wallet".to_owned() }],
    },
    SecretVersionEntry {
        secret_id: 2,
        versions: vec![
            VersionEntry { version: 1, description: "Work SSH key".to_owned() },
            VersionEntry { version: 2, description: "Work SSH key v2".to_owned() },
        ],
    },
];
let response::ProduceResult { envelope: response_envelope } =
    response::produce(channel_id, &stored, &shared_key).unwrap();

// Owner side: extract and process the response to get the secret list.
let response::ExtractResult { response } =
    response::extract(&response_envelope, &shared_key).unwrap();
let response::ProcessResult { secret_list } =
    response::process(&response).unwrap();

for entry in &secret_list {
    for v in &entry.versions {
        println!(
            "secret_id={}  version={}  description={:?}",
            entry.secret_id, v.version, v.description,
        );
    }
}

Recovery

Recovery is a three-step process: pairing (re-establish a channel with each helper in recovery mode), discovery (ask each helper which secrets it holds), and share collection (reconstruct the secret). The end-to-end flow is orchestrated by the protocol layer; the repository's end-to-end tests carry a full driver loop — see End-to-end test coverage.

Helper-side primitive surface:

use derec_library::primitives::recovery::{request, response};
use derec_library::types::ChannelId;

let channel_id = ChannelId(1);
let shared_key = [0u8; 32]; // established during pairing
// request_envelope:        outer DeRecMessage bytes carrying a GetShareRequest
// stored_share_request:    StoreShareRequestMessage the helper persisted at sharing time

let request::ExtractResult { request: get_share_request } =
    request::extract(&request_envelope, &shared_key).unwrap();
let response::ProduceResult { envelope: response_envelope } = response::produce(
    channel_id,
    &get_share_request,
    &stored_share_request,
    &shared_key,
).unwrap();

Through the protocol layer, start(DeRecFlow::RecoverSecret { .. }) asks every paired helper for its share and process tries to reconstruct as each one arrives. A corrupted share is reported per helper and set aside rather than allowed to block the recovery:

  • On arrival, each share is checked on its own: if a max_share_size is configured and the share exceeds it, it is set aside as Malformed before being parsed at all; otherwise it must decode, belong to the requested secret and version, and pass its Merkle proof. A share that fails is reported as RecoveryShareCorrupted (Malformed / InvalidProof) and never collected.
  • Nothing is reconstructed until every helper asked has answered, or get_share_response_secs has passed. Shares that are each valid can still disagree, carrying different commitment roots or ciphertexts. They are grouped by (root, ciphertext) and every group is tried; a group is a secret only if it holds shares from at least two helpers, decrypts, decodes, and fits the threshold it declares. A group that reconstructs anything else is reported as RecoveryShareCorrupted (Forged). Any other share outside the secret is a dispute: the decision is RecoveryDisputed (or RecoveryConflict when several secrets reconstruct) naming the helpers on each side, never a corruption.

Since an honest helper never sends a corrupted share, the application may take RecoveryShareCorrupted as a sign that the helper's device or storage is damaged or compromised, and offer to unpair it. A share that arrives after the recovery completed finds no open recovery and is dropped unreported.

Helpers and shares

  • Each share goes to a different helper. Threshold security depends on it: compromising one helper must yield at most one share.
  • The library hands out one share per channel per version, and every pairing produces its own channel. It cannot tell whether two channels lead to the same party; keeping helpers distinct is the application's job.
  • Discouraged: a single guardian acting as several helpers for the same owner. It is against the protocol's recommendation, since one compromise yields several shares. The library does not prevent it, but channel linking then needs the application's help (below).
  • Channel linking is expected to be one-to-one. After an owner re-pairs in recovery mode, the helper application links the new channel to the old one with DeRecChannelStore::link_channel. Linking assumes a helper holds at most one share per owner for a given secret_id and version, so each recovery channel is linked to the single old channel it replaces. On GetShare the helper answers with one share from the linked set: the first whose secret_id matches the request, in the order DeRecShareStore::load_many returns. The library imposes no order. If several channels holding shares for the same owner are linked to one recovery channel and every recovery channel is answered from the same share, the owner receives it more than once (it counts once) and can fall below the threshold. An application that runs such a helper keeps each recovery channel resolving to a distinct share: either links stay one-to-one, or its share store returns, for each requesting channel, the share intended for it first, in a deterministic order.

Owner side, at the primitive level — decrypt each helper response, reconstruct the secret once enough have arrived:

use derec_library::primitives::recovery::response;

let secret_id: u64 = 42;
let version: u32 = 1;
// responses: Vec<GetShareResponseMessage> collected from `response::extract` per helper.
let inputs: Vec<&_> = responses.iter().collect();
let recovered = response::recover(secret_id, version, &inputs).unwrap();
// recovered.secret_data contains the reconstructed payload.

Unpairing

Either party may end a channel by initiating an unpair flow. The recipient drops its state (shared key, channel record, stored shares) and acknowledges with an UnpairResponseMessage. Through the protocol layer this is one call; the primitive surface is below.

use derec_library::primitives::unpairing::{request, response};
use derec_library::types::ChannelId;

let channel_id = ChannelId(1);
let shared_key = [0u8; 32]; // established during pairing

// Initiator side: produce and send the unpair request.
let req_result = request::produce(channel_id, "decommissioning", &shared_key).unwrap();

// Responder side: extract the request, drop local state, send Ok response.
let _extracted = request::extract(&req_result.envelope, &shared_key).unwrap();
let resp_result = response::produce(channel_id, &shared_key).unwrap();

// Initiator side: extract and validate the response.
let response::ExtractResult { response: unpair_response } =
    response::extract(&resp_result.envelope, &shared_key).unwrap();
let outcome = response::process(&unpair_response).unwrap();
assert!(outcome.acknowledged);

Through the protocol layer:

use derec_library::protocol::{DeRecFlow, UnpairAck};

let mut protocol = DeRecProtocolBuilder::new(secret_id)
    .with_unpair_ack(UnpairAck::Required)
    // … other setters …
    .build()?;

protocol.start(DeRecFlow::Unpair {
    channel_id,
    memo: Some("decommissioning".to_owned()),
}).await?;

UnpairAck::Required (default) keeps local state until the peer replies Ok, or until the configured timeout elapses; the Unpaired event surfaces in either case. Meanwhile the channel is ChannelStatus::Unpairing: it keeps its key, so the reply can be read, but no flow selects it, so a publish started in that window does not hand the departing helper a share. A non-Ok reply emits UnpairRejected and returns the channel to Paired. restore unpairs its recovery channels the same way.

UnpairAck::NotRequired drops local state immediately on start(Unpair). The peer still answers, and since the channel is gone, process fails on that answer with an unknown-channel error the application can discard.

When the peer's UnpairRequest arrives on the responder side, the orchestrator emits DeRecEvent::ActionRequired { channel_id, action } with action set to PendingAction::Unpair { .. }. The application calls protocol.accept(action) to drop local state and reply Ok, or protocol.reject(action, status, memo) to keep local state and reply with a non-Ok status.


Secret format

The recoverable secret — the bytes reconstructed from a threshold of shares (recovered.secret_data in Recovery above) — is [version byte] · payload. The leading byte is the format major version; for v2 and v3 the payload is gzip (RFC 1952) compressed JSON. Within that JSON:

  • every byte-array field (shared_key, id, data, …) is standard base64 with padding (RFC 4648 §4) — never base64url;
  • every u64 field is a JSON decimal string (e.g. "1000000"), not a JSON number, to avoid precision loss;
  • object keys are snake_case.

This format is deliberately independent of the DeRec wire protocol: transport messages (DeRecMessage, StoreShareRequest, ReplicaSecretPayload, etc.) remain protobuf and are unaffected. Only the recoverable secret placed in secret_data uses this versioned envelope (v3: JSON + base64 + gzip), which makes it a self-describing, cross-application interoperability surface — any implementation can read the version byte, gunzip, parse the JSON, and base64-decode the byte fields without sharing code or a compiled schema with the producer.

The full field-by-field schema, encoding pipeline, and versioning rules are normatively defined in the crate documentation for the derec_library::protocol::types::secret module.


Protocol specification

Full protocol documentation: https://derec-alliance.gitbook.io/docs/protocol-specification/messages


Security considerations

Applications using this SDK should ensure:

  • Secure storage of secret material (DeRecSecretStore content is keychain-grade — see the trait doc).
  • Proper authentication of helpers.
  • Safe transport channels.
  • Detection of replayed and reflected messages within the inbound window, keyed on derec_message::message_id (see Replays and reflections).

The DeRec protocol assumes helpers are independent and trusted entities.

Replica destinations inherit Source trust

A ReplicaDestination receives the full Secret, which embeds every helper's channel_id and shared_key under HelperInfo. Anyone with the secret can therefore authenticate as the Source toward every helper. This is intentional — it is what makes Destination-driven recovery work — but it means a compromised Destination can impersonate the Source against every helper that was paired at the time the secret was sent. Pick Destinations with at least the trust level of the Source device itself; do not treat them as opaque backups.

The replica group also shares a single group channel key: every (secret_id, channel_id) entry in DeRecSecretStore for a paired replica channel holds the same 32-byte key, established at the first replica pair and handed over to every subsequent joiner via ReplicaSecretPayload.shared_key on its first sync round. Compromise of any one Destination therefore exposes that single key to the attacker; the protocol does not provide per-pair forward secrecy across replicas.

HashedKeys requires an ephemeral transport URI

ContactMode::HashedKeys ships only a SHA-384 binding hash in the contact and serves the actual public keys through a plaintext PrePair round-trip on the contact creator's own_transport. Any party that can reach that URI before the legitimate scanner gets the keys. Use HashedKeys only with a transport endpoint that is freshly minted for this pairing and that you can retire as soon as the PrePair leg completes. ContactMode::InlineKeys has no such constraint because the keys are embedded directly in the (already binding-hash-validated) contact bytes.

The recommended pattern is: pair on the ephemeral URI, then — as soon as the pairing completes on the contact creator side — call set_own_transport with the permanent endpoint and start an UpdateChannelInfo flow against the peer to announce the swap. Once the peer acknowledges, retire the ephemeral URI. This keeps the plaintext PrePair window tight while letting subsequent traffic ride on the long-lived endpoint.

Replica fingerprint verification is mandatory

Replica channels are created in ChannelStatus::Pending and remain there until both sides call verify_fingerprint with the value the peer derived from the shared key — confirmed out of band, the same way helper pairings are. The orchestrator enforces this: start(ProtectSecret) returns Error::InvalidInput when a target is still Pending. Treat verification as a required step in the pairing UX, not an optional confirmation — a scanner that auto-pairs without it accepts a MITM-vulnerable replica.

Until a device confirms, it ignores everything the peer sends on that channel: process changes no store, sends nothing back, and returns DeRecEvent::MessageIgnored { channel_id, reason: IgnoreReason::PendingVerification, trace_id }. This matters most for a replica destination. The source's own confirmation publishes the vault immediately, so that copy usually arrives before the destination's user has confirmed. Confirming does not replay it: once the destination's verify_fingerprint succeeds, call start(DeRecFlow::ReplicaDiscovery) to pull the copy from the source.

Until a device confirms a member, that member is not part of the group as far as the device is concerned. It is left out of every roster the device publishes (each new version, catch-up answers and the vault itself), it is not asked in a replica version check, and it cannot succeed a removed source. Every recipient installs a roster's members as paired, so listing an unconfirmed one would admit it on their behalf.

Every helper sees the vault's compressed length

The vault (the user's secrets, every helper's channel key and communication_info, and the replica group key) is compressed as one gzip stream before it is encrypted and split. Encryption keeps the length, so every helper learns the compressed length of every version. A helper also chooses part of what is compressed: its own communication_info, which it changes with UpdateChannelInfo. When that text repeats part of a secret elsewhere in the vault, the vault compresses better, so over many versions a corrupted helper could learn another helper's channel key, the group key or the user's secrets a few characters at a time (the side channel behind CRIME and BREACH). Each guess costs a new version, which only the owner creates, after a contact change the owner's application has to accept. Keep AutoAcceptPolicy::update_channel_info off, and treat a helper that keeps changing its contact details as suspect.

Decoding a recovered vault has no memory limit

In recovery the vault is decrypted from shares that nothing authenticates, so a forged recovery group can deliver any payload, including one built to exhaust memory. The decoder parses the vault while it inflates it: a payload that is not JSON is refused after its first bytes, and padding is not buffered. A payload that is valid JSON still receives the memory its largest value claims, and gzip lets a payload claim up to about 1030 times its own size. The library sets no limit. When memory runs out, a native process is killed by the operating system or aborts, with no error and no event; under WebAssembly the call fails with a trap, after which the instance must not be used. To bound it, configure parameter_range.max_share_size: a recovery share larger than that is refused before anything is decoded, so a vault can claim at most about 1030 times that size.

The derec.* namespace in CommunicationInfo is library-owned

CommunicationInfo is otherwise an opaque app-defined map, but every key under the derec. prefix is reserved for the protocol. Today the library owns derec.replica_id; future protocol additions will use the same namespace. Application code must not write any derec.* entry — the orchestrator silently overwrites or strips library-owned keys at the protocol boundary, and app-set values are lost without warning.


License

Licensed under the Apache License, Version 2.0. See the LICENSE file for details.


Contributing

Contributions are welcome. Repository: https://github.com/derecalliance/lib-derec. Please open issues or pull requests to discuss improvements.


DeRec Alliance

The DeRec Alliance is an open initiative focused on standards for decentralized secret recovery. https://derec.org