Skip to main content

offline_protocol/
config.rs

1//! Protocol configuration.
2
3use crate::constants::DEFAULT_INITIAL_TTL;
4use crate::protocol::mesh_relay::{MeshRelayConfig, RELAY_QUEUE_MAX_OVERDUE};
5use offline_protocol_reliability::{AckConfig, DeduplicatorConfig, RetryConfig};
6use offline_protocol_router::{DorsConfig, RelayConfig};
7use serde::{Deserialize, Serialize};
8use std::sync::Arc;
9
10/// Overflow policy for bounded pending encrypted message queues.
11#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum OverflowPolicy {
14    /// Evict the oldest queued message to make room for the new message.
15    #[default]
16    DropOldest,
17    /// Drop the newly received message when capacity is reached.
18    DropNewest,
19}
20
21/// Configuration for inbound encrypted messages received before session readiness.
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct PendingQueueConfig {
24    /// Maximum number of pending encrypted messages per peer.
25    pub max_pending_per_peer: usize,
26    /// Maximum number of pending encrypted messages across all peers.
27    pub max_pending_global: usize,
28    /// Maximum total payload bytes (content plus binary content) queued per
29    /// peer.
30    ///
31    /// Encrypted media chunks are queued whole while the sender's session is
32    /// not yet ready, so the count limits alone would admit up to
33    /// `max_pending_per_peer` × chunk-size bytes of ciphertext. The default
34    /// (4 MB) covers the largest legitimate pre-session backlog: 2 concurrent
35    /// transfers × 8 in-flight chunks × 256 KB internet chunks.
36    #[serde(default = "default_max_pending_bytes_per_peer")]
37    pub max_pending_bytes_per_peer: usize,
38    /// Maximum total payload bytes queued across all peers. The default
39    /// (32 MB) bounds worst-case queue memory on mobile devices regardless of
40    /// how many peers are mid-establishment.
41    #[serde(default = "default_max_pending_bytes_global")]
42    pub max_pending_bytes_global: usize,
43    /// Time-to-live for pending encrypted messages in milliseconds.
44    pub pending_ttl_ms: u64,
45    /// Overflow policy when queue limits are reached.
46    pub overflow_policy: OverflowPolicy,
47}
48
49/// Default TTL for the pending-decryption queue (24 hours, in ms).
50///
51/// Under the deferred-ACK model an undecryptable message is no longer ACKed on
52/// receipt, so this queue is the primary recovery window before the session
53/// confirms — a 2-minute window was too short for a peer whose Welcome is slow
54/// to arrive/adopt, and 30 minutes was too short once the queue became
55/// durable: with a relay that pushes ciphertext without store-and-forward
56/// there is no second copy, so a frame that arrives while the recipient's
57/// session is still being set up has to outlive the handshake, which for a
58/// phone that is opened once a day means a day. Memory stays bounded by the
59/// per-peer/global byte caps plus the `DropOldest` overflow policy; a longer
60/// TTL only lets entries linger within those caps, it does not raise the
61/// ceiling. The TTL is measured on an `Instant` and so restarts with the
62/// process; the persisted copy is bounded separately by
63/// `PENDING_DECRYPT_PERSISTED_MAX_AGE_MS` (7 days).
64///
65/// The UniFFI `PendingQueueConfig` default mirrors this value — reference this
66/// constant there rather than re-hardcoding it.
67pub const DEFAULT_PENDING_TTL_MS: u64 = 86_400_000;
68
69fn default_max_pending_bytes_per_peer() -> usize {
70    4 * 1024 * 1024
71}
72
73fn default_max_pending_bytes_global() -> usize {
74    32 * 1024 * 1024
75}
76
77impl Default for PendingQueueConfig {
78    fn default() -> Self {
79        Self {
80            max_pending_per_peer: 64,
81            max_pending_global: 4096,
82            max_pending_bytes_per_peer: default_max_pending_bytes_per_peer(),
83            max_pending_bytes_global: default_max_pending_bytes_global(),
84            // 24 hours; see DEFAULT_PENDING_TTL_MS for the deferred-ACK
85            // rationale and the FFI-mirror contract.
86            pending_ttl_ms: DEFAULT_PENDING_TTL_MS,
87            overflow_policy: OverflowPolicy::DropOldest,
88        }
89    }
90}
91
92/// Encryption configuration for automatic MLS handling.
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub struct EncryptionConfig {
95    /// Whether automatic encryption is enabled.
96    /// When enabled, messages are automatically encrypted/decrypted using MLS.
97    pub enabled: bool,
98
99    /// Auto-exchange key packages on peer discovery.
100    /// When enabled, key packages are automatically sent when neighbors are discovered.
101    pub auto_key_exchange: bool,
102
103    /// Store pending messages when no session exists.
104    /// Messages will be sent automatically after the session is established.
105    pub store_pending: bool,
106
107    /// Require encryption for messages (default: `true`).
108    ///
109    /// When enabled, sends fail closed if encryption cannot be applied:
110    /// with MLS uninitialized every send returns [`crate::Error::EncryptFailed`],
111    /// and with no confirmed session messages are queued (when
112    /// `store_pending` is set) or fail with
113    /// [`crate::Error::SessionNotReady`] instead of ever leaving as
114    /// plaintext. Inbound plaintext content — text messages and legacy
115    /// media alike — is rejected without being surfaced to the app
116    /// (plaintext carries no sender authentication, so anyone could
117    /// inject it under a contact's name); each rejection emits a
118    /// [`crate::events::SecurityWarningCode::PlaintextReceiveRejected`]
119    /// warning, once per peer. Even under the opt-out, inbound plaintext
120    /// from a peer *known to run MLS* is rejected as a downgrade/forgery
121    /// attempt — see `OfflineProtocol::encryption_capable_peers`. A
122    /// confirmed session is not required, and deliberately so: an honest
123    /// peer queues rather than downgrading while a session is pending, so
124    /// cleartext from a peer we know speaks MLS is never legitimate.
125    /// Peers that have shown no MLS signal stay readable, which is what
126    /// makes this opt-out usable for legacy interop.
127    ///
128    /// Disable only for deployments that deliberately send cleartext
129    /// (e.g. open broadcast/mesh bootstrap without provisioned MLS
130    /// storage) — set this to `false` explicitly, or use
131    /// [`EncryptionConfig::disabled`] to turn encryption off entirely.
132    /// Every plaintext send then emits a
133    /// [`crate::events::SecurityWarningCode::PlaintextSend`] warning
134    /// (once per peer). Internal control messages (key exchange, ACKs,
135    /// service discovery) are exempt and unaffected.
136    pub require_encryption: bool,
137
138    /// Bounds and eviction policy for pending inbound encrypted messages.
139    pub pending_queue: PendingQueueConfig,
140
141    /// Whether to negotiate and emit the compact MLS envelope for encrypted
142    /// messages (base64 of the binary `EncryptedMessage` form instead of JSON
143    /// with an integer-array ciphertext — roughly 2.7x smaller).
144    ///
145    /// Defaults to `true`. It only takes effect toward recipients that
146    /// advertise support in their key package (`env_versions`), so a mixed
147    /// fleet automatically stays on the JSON envelope. Parsing of inbound
148    /// compact envelopes is always on, independent of this flag; this gates
149    /// only advertising and emitting. The end-to-end sibling of
150    /// [`TransportConfig::binary_wire_enabled`], with an independent kill
151    /// switch because the two degrade separately.
152    pub compact_envelope_enabled: bool,
153
154    /// Whether to negotiate and seal the rich `__RICH_V1__` payload for
155    /// encrypted messages: quoted-reply context, rich media metadata, and
156    /// forward attribution carried *inside* the MLS ciphertext instead of on
157    /// the relay-visible outer message.
158    ///
159    /// Defaults to `true`. It only takes effect toward recipients that
160    /// advertise support in their key package (`rich_versions`); toward
161    /// everyone else the rich extras are silently dropped — never sent
162    /// cleartext. Parsing of inbound sealed payloads is always on,
163    /// independent of this flag; this gates only advertising and sealing.
164    /// Independent kill switch from
165    /// [`EncryptionConfig::compact_envelope_enabled`] — the two degrade
166    /// separately.
167    pub rich_payload_enabled: bool,
168
169    /// Whether to recover an inbound encrypted message that failed to decrypt,
170    /// rather than silently dropping it while telling the sender it was
171    /// delivered.
172    ///
173    /// Defaults to `true`. When enabled, an inbound encrypted DM (or media
174    /// chunk) that fails to decrypt is **not delivery-ACKed** and its id is not
175    /// left dedup-marked, so the sender keeps retrying instead of marking it
176    /// delivered — and each resend of a DM is re-sealed against the peer's
177    /// current session, so a resend can actually land. A message that stays
178    /// undeliverable settles as an honest `MessageFailed` once the sender's
179    /// retry budget lapses. When disabled, every decrypt failure falls back to
180    /// the legacy drop-and-ACK behavior.
181    ///
182    /// **Only an epoch mismatch additionally triggers a re-key.** A decrypt
183    /// failure *specifically* because the two sides disagree on the MLS epoch
184    /// (e.g. after a fork) also starts a rate-limited `session_reset`
185    /// key-package exchange to rebuild the channel. Failures that are *not* an
186    /// epoch mismatch — an AEAD / authentication failure, a discarded past
187    /// ratchet generation, a malformed frame — withhold the ACK but never
188    /// re-key: widening the re-key trigger to cover them would turn every
189    /// malformed frame into a teardown, which is an unbounded churn vector.
190    /// That separation is why the two classifications stay distinct.
191    ///
192    /// One consequence worth planning for: `MessageDecryptionFailed` is
193    /// **advisory, not terminal**, and fires once per failed *attempt* rather
194    /// than once per message. Treat it as "this attempt did not decrypt", and
195    /// read `MessageFailed` (or `FileReceiveFailed` for media) as the terminal
196    /// signal.
197    ///
198    /// **The re-key trigger is unauthenticated, by construction — do not read
199    /// this switch as "only genuine peers can cause a re-key".** An MLS epoch is
200    /// checked during *framing* validation, which happens before any AEAD,
201    /// sender-data, or signature check, and a 1:1 session slot id is derivable
202    /// from two public user ids. A hand-built frame carrying a wrong epoch
203    /// therefore reaches the recoverable classification with its sender still
204    /// entirely unverified: any party who can inject a frame can drive a re-key,
205    /// with no key material, no captured ciphertext and no session
206    /// (`test_forged_frame_reaches_session_desync_without_any_key_material`
207    /// builds one from scratch). This is inherent to MLS framing, not a defect,
208    /// and cannot be authenticated away — the credential a sender check would
209    /// compare against only exists once decrypt *succeeds*.
210    ///
211    /// What makes that safe is that acting on the trigger is **harmless**, not
212    /// that it is trusted: the re-key is confined to the claimed sender's own
213    /// session slot (so one derivable id cannot be aimed at other peers), is
214    /// rate-limited to one per peer per 30 s, discards no queued message, and
215    /// emits a `SESSION_REKEY_TRIGGERED` security warning so a sustained rate —
216    /// injection rather than a real fork — is visible to the app. The residual
217    /// is bounded re-key churn on a single pair: delivery delayed, never lost.
218    /// `OfflineProtocol::schedule_session_rekey` carries the full analysis.
219    pub crypto_recovery_enabled: bool,
220}
221
222impl Default for EncryptionConfig {
223    fn default() -> Self {
224        Self {
225            enabled: true,
226            auto_key_exchange: true,
227            store_pending: true,
228            // Fail closed by default (SEC-M3): a stock-config node must never
229            // silently degrade to plaintext because MLS was left uninitialized.
230            require_encryption: true,
231            pending_queue: PendingQueueConfig::default(),
232            compact_envelope_enabled: true,
233            rich_payload_enabled: true,
234            crypto_recovery_enabled: true,
235        }
236    }
237}
238
239impl EncryptionConfig {
240    /// Creates a new encryption config with encryption disabled.
241    pub fn disabled() -> Self {
242        Self {
243            enabled: false,
244            auto_key_exchange: false,
245            store_pending: false,
246            require_encryption: false,
247            pending_queue: PendingQueueConfig::default(),
248            compact_envelope_enabled: false,
249            rich_payload_enabled: false,
250            crypto_recovery_enabled: false,
251        }
252    }
253}
254
255/// Security configuration for transport and control-message hardening.
256#[derive(Debug, Clone, Serialize, Deserialize)]
257pub struct SecurityConfig {
258    /// When `true`, control messages with no transport-level peer identity
259    /// (`transport_peer_id` is `None`) are rejected. When `false` (default),
260    /// missing transport identity emits a `SecurityWarning` but allows the
261    /// message through (best-effort / fail-open).
262    ///
263    /// # Why the default (`false`) is not the weak setting it once was
264    ///
265    /// This flag used to carry real weight, because a forged `sender` was
266    /// otherwise cheap: identities were app-chosen strings and the only thing
267    /// standing behind one was a trust-on-first-use pin, so first contact with
268    /// any peer was open to a man-in-the-middle and transport identity was the
269    /// only independent corroboration available.
270    ///
271    /// Under self-certifying addressing it is not. Every security-gated control
272    /// frame must now carry an Ed25519 signature — unconditionally, no longer
273    /// gated on this flag — and the signing key must derive to the address in
274    /// `sender`. A forged `sender` therefore requires the private key behind
275    /// that address, on first contact as much as on the thousandth. Transport
276    /// identity adds no authenticity on top of that; it only cross-checks a
277    /// claim the signature already proved.
278    ///
279    /// The strict match on frames claiming direct origin (`hop_count == 0`) runs
280    /// regardless of this flag, as it always has, and is unaffected.
281    ///
282    /// # What enabling it still does, and what it costs
283    ///
284    /// Exactly one thing: control frames arriving with **no** transport identity
285    /// at all are rejected instead of falling through to the signature gate.
286    ///
287    /// That is a real cost with no matching benefit on most deployments. Nostr
288    /// frames carry no transport identity by construction — the Nostr pubkey is
289    /// an install signing key, not the protocol id, so attaching it would fail
290    /// the strict match (see `nostr_message_received_inner`) — and relay frames
291    /// that arrive without a named sender are in the same position. Turning this
292    /// on rejects **every** control message on those paths, including the
293    /// key-package exchange that cold contact depends on. Mesh-forwarded frames
294    /// re-created by intermediate nodes legitimately lack identity too.
295    ///
296    /// Set to `true` only on a deployment that runs neither Nostr nor
297    /// sender-less relay delivery, and wants frames without transport identity
298    /// refused as a matter of policy rather than of authentication.
299    pub require_transport_identity: bool,
300
301    /// Whether a control frame is refused for being stale, and whether a peer
302    /// that has proved it signs the freshness-bound payload is held to it.
303    ///
304    /// Defaults to `true`. With it on, a control frame signed under
305    /// `offline-ctrl-v2` is checked against
306    /// [`CTRL_FRESHNESS_PAST_MS`](offline_protocol_sealed::CTRL_FRESHNESS_PAST_MS)
307    /// and its future counterpart, a peer that once verifiably signed v2 may
308    /// not fall back to v1, and a `session_reset` is honoured only on a frame
309    /// whose freshness was actually checked. With it off, this node behaves
310    /// exactly as it did before any of that existed: signatures are still
311    /// verified, and no frame is refused for its age.
312    ///
313    /// # What it is for
314    ///
315    /// The timestamp is read against *this device's* clock, so the failure
316    /// this switch exists for is a clock, not a peer. A device that comes up
317    /// with an unset clock reads every honest peer's frame as being from
318    /// decades in the future and refuses all of them, which takes out the
319    /// whole control plane — key package exchange included — for as long as
320    /// the clock is wrong. That is a self-inflicted outage a shipped app
321    /// cannot wait for a new binary to fix, which is why the lever exists and
322    /// why it reaches the bindings rather than staying internal.
323    ///
324    /// # What turning it off costs
325    ///
326    /// A captured control frame verifies forever again, and a recorded
327    /// `session_reset` is once more a repeatable way to tear down a live
328    /// session (issue 403). It is a diagnosis and recovery tool, not a
329    /// configuration a deployment should settle on.
330    pub control_freshness_enforced: bool,
331}
332
333impl Default for SecurityConfig {
334    fn default() -> Self {
335        Self {
336            // Fail-open, and safe to: see the field's own documentation for
337            // why transport identity adds no authenticity over a signature
338            // that must derive to the sender's address.
339            require_transport_identity: false,
340            // Fail-closed, like `require_encryption`: a freshness check that
341            // has to be switched on is one that is off on every install that
342            // never heard about it.
343            control_freshness_enforced: true,
344        }
345    }
346}
347
348/// Transport-specific configuration.
349#[derive(Debug, Clone, Serialize, Deserialize)]
350pub struct TransportConfig {
351    /// Whether BLE transport is enabled.
352    pub ble_enabled: bool,
353
354    /// Whether Wi-Fi Direct transport is enabled.
355    pub wifi_direct_enabled: bool,
356
357    /// Whether Internet transport is enabled.
358    pub internet_enabled: bool,
359
360    /// Whether Reticulum mesh transport is enabled.
361    /// Defaults to `false` because Reticulum requires external infrastructure
362    /// (a running Reticulum daemon or RNode hardware).
363    pub reticulum_enabled: bool,
364
365    /// Whether Nostr relay transport is enabled.
366    /// Defaults to `false` because Nostr requires relay configuration
367    /// and a secp256k1 keypair.
368    pub nostr_enabled: bool,
369
370    /// Whether outgoing Nostr frames are sealed into NIP-59 gift wraps.
371    ///
372    /// Defaults to `true`. With it off, the transport publishes the legacy
373    /// kind-4 event whose content is the whole protocol envelope in cleartext —
374    /// both usernames, the app id, the metadata map, the content type and a
375    /// millisecond timestamp, readable by every relay, permanently. Turn it off
376    /// only to interoperate with a relay that rejects kind 1059 outright.
377    ///
378    /// Send-side only, and never negotiated: inbound gift wraps are always
379    /// unsealed and inbound legacy frames always parsed, so whatever this is
380    /// set to, anything a peer sends us stays readable.
381    ///
382    /// It does still affect *outbound* reachability, in the one direction the
383    /// receive path cannot cover. A peer on a build that predates sealing
384    /// subscribes with `kinds: [4]` only, so it is never handed our kind-1059
385    /// events and has no NIP-44 layer to open one with — leaving it on makes
386    /// such a peer unreachable over Nostr (visibly: no ACK returns, so the
387    /// send fails through the retry ladder rather than vanishing). That is the
388    /// second reason to turn this off, alongside a relay that rejects
389    /// kind 1059.
390    pub nostr_sealing_enabled: bool,
391
392    /// Whether this install publishes MLS key packages to the relays and
393    /// resolves peers' published packages.
394    ///
395    /// Defaults to `true`, and takes effect only when `nostr_enabled` is on —
396    /// which is itself off by default, so nothing is published unless an app
397    /// deliberately turns Nostr on.
398    ///
399    /// Buys **cold first contact**: a peer known only by username becomes
400    /// reachable over Nostr with no prior key-package exchange over some other
401    /// transport, which is otherwise impossible. It also bounds the sealing
402    /// downgrade that follows a peer-key eviction, since a forgotten key is
403    /// re-resolved on the next send instead of waiting for a fresh exchange.
404    ///
405    /// **What it costs is worth stating plainly.** Publication is the first
406    /// thing this SDK emits to a relay unprompted: a small set of addressable
407    /// records sits at this install's routing tag and is refreshed as slots are
408    /// consumed, whether or not any message is ever sent. Their *content* is
409    /// sealed — a scraper filtering on the kind alone reads nothing, which
410    /// matters because an MLS key package carries its owner's username in the
411    /// leaf credential and cannot be stripped of it — but the existence of a
412    /// record at a given tag, and the timing of its refreshes, are visible to
413    /// every relay published to. Turn this off to keep the transport silent
414    /// until it has traffic, at the price of cold contact.
415    pub nostr_cold_contact_enabled: bool,
416
417    /// Whether this install publishes a username discovery record and can
418    /// resolve usernames to the devices claiming them.
419    ///
420    /// Defaults to **`false`**, unlike `nostr_cold_contact_enabled`, and gates
421    /// publication and resolution together. It also *requires* cold contact:
422    /// a discovery record points at an address whose key packages are what a
423    /// resolver fetches next, so with cold contact off the claim resolves and
424    /// then dead-ends one hop later. The two are hard-coupled in the transport
425    /// rather than merely documented.
426    ///
427    /// Buys back **reach by username**, which the addressing migration removed:
428    /// a stranger who knows only a name can find the addresses claiming it and
429    /// open a session. The name is published as the app's configured `profile`,
430    /// normalized to NFC and lowercase.
431    ///
432    /// **Default-off is the deliberate choice, and the reason is disclosure.**
433    /// Publishing binds a human-readable name to an address in a public place.
434    /// That is materially more than the key-package record's "an install with
435    /// this tag exists": the mapping *is* the payload. The record is sealed to
436    /// a key derived from the username, so a relay scraping by kind alone reads
437    /// nothing, but anyone who guesses the name can compute the tag, confirm a
438    /// claim exists, and read it. That is the same class of exposure a public
439    /// user directory has, and it is a decision an app should make explicitly.
440    ///
441    /// **What the directory is not: authoritative.** Anyone may publish any
442    /// claim at any name. Every record is a claim that *some key* asserts a
443    /// name, and a resolution returns the whole set of claimants with their
444    /// verification status. An app that silently picks the first result has
445    /// converted a non-authoritative directory into an authoritative-looking
446    /// one; the user must confirm out of band. See
447    /// `docs/spec/username-discovery.md`.
448    pub nostr_username_discovery_enabled: bool,
449
450    /// Whether to negotiate and emit the compact binary wire codec.
451    ///
452    /// Defaults to `true`. It only takes effect between two peers that both
453    /// advertise support (via their signed key package), so a mixed fleet
454    /// automatically stays on JSON. Decoding of binary frames is always on,
455    /// independent of this flag; this gates only advertising and emitting.
456    pub binary_wire_enabled: bool,
457}
458
459impl Default for TransportConfig {
460    fn default() -> Self {
461        Self {
462            ble_enabled: true,
463            wifi_direct_enabled: true,
464            internet_enabled: true,
465            reticulum_enabled: false,
466            nostr_enabled: false,
467            nostr_sealing_enabled: true,
468            nostr_cold_contact_enabled: true,
469            nostr_username_discovery_enabled: false,
470            binary_wire_enabled: true,
471        }
472    }
473}
474
475/// Reliability configuration combining ACK, retry, and deduplication settings.
476#[derive(Debug, Clone, Default)]
477pub struct ReliabilityConfig {
478    /// ACK manager configuration.
479    pub ack: AckConfig,
480
481    /// Retry queue configuration.
482    pub retry: RetryConfig,
483
484    /// Deduplicator configuration.
485    pub dedup: DeduplicatorConfig,
486}
487
488/// Configuration for group messaging.
489#[derive(Debug, Clone, Serialize, Deserialize)]
490pub struct GroupConfig {
491    /// Maximum number of members allowed in a single group.
492    ///
493    /// Per-member fan-out is O(N) when using mesh transports.
494    /// This cap prevents unbounded groups from overwhelming the network.
495    pub max_group_members: usize,
496
497    /// Whether to attempt relay server registration for groups.
498    ///
499    /// When `true` (default), groups are registered with the relay server
500    /// for optimized fan-out when Internet transport is available.
501    /// When `false`, groups always use per-member fan-out regardless of
502    /// transport.
503    ///
504    /// This gates *registration* only — the relay group registry is what
505    /// invite links resolve against, so it stays on independently of
506    /// [`Self::relay_broadcast_enabled`].
507    pub relay_enabled: bool,
508
509    /// Whether a relay-synced group may send via a single O(1) relay
510    /// broadcast instead of per-member fan-out.
511    ///
512    /// **Default `true`, and additionally gated on the relay's advertised
513    /// capabilities.** The flag alone does not select the broadcast: the
514    /// path is taken only when the connected relay also advertised the
515    /// `group_delivery_v3` capability in its `Authenticated` answer (v3 =
516    /// the v2 settled-report contract plus an address-aware group path —
517    /// members named in the identifier space the roster was registered in,
518    /// so the report is comparable against the MLS roster). Against
519    /// such a relay the broadcast keeps a delivery contract — the relay
520    /// answers every broadcast with a *settled* per-recipient delivery
521    /// report (`GroupMessageSent`) naming who took the message over a
522    /// socket and who took a device push, and the SDK re-sends a per-member
523    /// copy through the ordinary outbox/ACK/park ladder to every MLS roster
524    /// member the report does not account for. A lost report re-sends the
525    /// broadcast under the same logical message id (receiver and push dedup
526    /// absorb the duplicate fan-out) a bounded number of times, then
527    /// downgrades the message to full per-member fan-out. Against an older
528    /// relay the capability gate fails and every send takes per-member
529    /// fan-out — the fire-and-forget broadcast of the v1 relay (no presence
530    /// check, no push fallback, no persistence, "sent" answered before
531    /// delivery was known) is never taken, regardless of this flag.
532    ///
533    /// The one gap on the broadcast path: the tracker awaiting the report
534    /// lives in memory only, so a process death inside the report window
535    /// (up to `RELAY_BROADCAST_REPORT_TIMEOUT_SECS` per attempt) loses the
536    /// backstop with it — members the relay could not reach get no
537    /// per-member re-send, and nothing retries on restart. It needs both a
538    /// missed member and a kill in that window, and is strictly smaller than
539    /// the pre-report broadcast's exposure, but it is a real difference from
540    /// per-member fan-out, whose outbox entries persist for 7 days.
541    ///
542    /// Set `false` to force per-member fan-out even against a v2 relay —
543    /// the right choice for an app that must not lose a group message to a
544    /// mid-flight process kill.
545    /// Per-member fan-out (`__GRP_MLS_MSG__` as ordinary `SendMessage`
546    /// frames) inherits the full DM ladder end to end — outbox + ACK +
547    /// retry, relay write-ack + successor retry + offline push carrying the
548    /// ciphertext, park-on-unreachable with presence-driven flush, and
549    /// receiver-side deferred-ACK-after-decrypt — at the cost of O(N)
550    /// uplink frames per send.
551    ///
552    /// O(N) fan-out does **not** risk tripping the relay's rate limiter at
553    /// any group size. The platform bridge meters every relay-bound frame
554    /// through a client-side token bucket (`RelayRateLimiter`: 28 capacity,
555    /// 9/s refill) deliberately tighter than the relay's (30 burst, 10/s),
556    /// and a frame that cannot take a token is *deferred to a later poll
557    /// tick*, never dropped — so client spend stays at `28 + 9t` against a
558    /// server budget of `30 + 10t` and the fan-out self-paces below it
559    /// regardless of member count. Core enqueues all N frames at once; the
560    /// bridge drains that queue.
561    ///
562    /// What large groups actually cost on the per-member path is drain
563    /// latency. Frame N reaches the wire at roughly `(N - 28) / 9` seconds.
564    /// Since the ACK timer starts at local *enqueue* (`handle_send_success`)
565    /// and not at wire-confirm — `on_transport_send_confirmed` advances only
566    /// the welcome lifecycle — past roughly 118 members the tail of a single
567    /// fan-out exceeds the 10s ACK timeout and is retransmitted by the
568    /// ladder before it was ever written. That is wasted duplicate frames,
569    /// absorbed by receiver and push dedup via the stable outbox id, not
570    /// lost messages. Presence checks, typing, and receipts draw on the same
571    /// bucket and lower the threshold. This is the strongest reason to leave
572    /// the broadcast enabled for large groups.
573    pub relay_broadcast_enabled: bool,
574
575    /// Whether an incoming MLS membership commit is refused when the local
576    /// admin overlay does not authorize its committer.
577    ///
578    /// **Off by default, and turning it on is a decision about partition
579    /// risk, not a hardening toggle.** Refusing a commit means declining the
580    /// MLS merge: our epoch stays behind every member who did merge, and MLS
581    /// has no way back — the application has to re-invite us. Enforcement is
582    /// therefore fork-free only if every member reaches the *same* verdict,
583    /// and the admin overlay is replicated best-effort (role changes ride
584    /// unreconciled mesh notifications; a joiner gets a point-in-time
585    /// snapshot). Two members whose role maps merely disagree will partition
586    /// each other with no attacker involved.
587    ///
588    /// The check fails open on every *absent* input — no metadata, no admin
589    /// role stored, an unreadable roster — so the common lag case stays
590    /// harmless. It cannot detect *divergent* views, which is the residual
591    /// risk that keeps this opt-in. Enable it only for a closed deployment
592    /// that controls role distribution.
593    ///
594    /// With it off (the default), unauthorized membership changes are still
595    /// applied and reported: `group_unauthorized_membership_change` fires and
596    /// the roster events carry `authorized: false`. That reporting is
597    /// unaffected by this flag; the flag only decides whether the commit is
598    /// *also* refused.
599    ///
600    /// Rejection is receiver-local. The sender's message is still ACKed, so
601    /// a committer gets no signal that anyone refused, and members with the
602    /// flag off will apply a commit that members with it on rejected — do not
603    /// enable it on part of a fleet.
604    #[serde(default)]
605    pub enforce_admin_commits: bool,
606}
607
608impl Default for GroupConfig {
609    fn default() -> Self {
610        Self {
611            max_group_members: 256,
612            relay_enabled: true,
613            relay_broadcast_enabled: true,
614            enforce_admin_commits: false,
615        }
616    }
617}
618
619/// Configuration for the replicated-document data layer.
620///
621/// [`Self::enabled`] governs the whole layer: with it off no documents are
622/// opened, nothing is persisted, and no capability is advertised to peers.
623#[derive(Clone, Serialize, Deserialize)]
624pub struct DataConfig {
625    /// Whether the data layer accepts work at all.
626    ///
627    /// **Defaults to `true`.** It defaulted to `false` while the layer could
628    /// store documents but not replicate them: advertising a capability with
629    /// no sync behind it invites peers to expect a sync that never comes.
630    /// Both halves land in the same release, so no application ever ran
631    /// against the old default, and the switch is on.
632    ///
633    /// What being on costs an application that ignores documents entirely:
634    /// nothing at rest and nothing on the wire. The layer allocates when a
635    /// store is opened, and a capability is advertised in a key package that
636    /// is sent anyway. What it buys is that an application that *does* open a
637    /// store gets replication without discovering a flag.
638    #[serde(default = "default_data_enabled")]
639    pub enabled: bool,
640
641    /// Where documents are stored, when the application wants them somewhere
642    /// other than the store protocol state already uses.
643    ///
644    /// `None` — the default — means documents live in the same backend as the
645    /// rest of protocol state, which is what makes the layer work with zero
646    /// storage setup: every binding already ships a default provider.
647    ///
648    /// Setting it points documents at SQLite, RocksDB, files, a corporate
649    /// store, or anything else implementing the same trait, while protocol
650    /// secrets stay exactly where they are. The two concerns swap
651    /// independently and the swap is a runtime choice: no rebuild, no cargo
652    /// feature, and no change to any data API. Anything that makes this
653    /// harder than assigning this field is a design regression.
654    ///
655    /// Sealing sits above this seam. An adapter is handed sealed bytes and
656    /// never sees document content, so a custom backend cannot weaken the
657    /// at-rest posture even by accident.
658    ///
659    /// # Logout
660    ///
661    /// `wipePersistedState` clears the account directory of the *default*
662    /// provider. A custom backend is somewhere the bindings cannot know
663    /// about, so an application that sets this must call the data layer's
664    /// own wipe on logout, or documents outlive the account that made them.
665    #[serde(skip)]
666    pub storage: Option<Arc<dyn crate::protocol_state_storage::ProtocolStateStorage>>,
667}
668
669/// The default for [`DataConfig::enabled`], needed by name because `serde`
670/// cannot ask a field's type for anything other than its own default.
671fn default_data_enabled() -> bool {
672    true
673}
674
675impl Default for DataConfig {
676    fn default() -> Self {
677        Self {
678            enabled: default_data_enabled(),
679            storage: None,
680        }
681    }
682}
683
684impl std::fmt::Debug for DataConfig {
685    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
686        f.debug_struct("DataConfig")
687            .field("enabled", &self.enabled)
688            .field("storage", &self.storage.as_ref().map(|_| "<custom>"))
689            .finish()
690    }
691}
692
693/// How long a custodian holds a deposited frame by default: six hours.
694///
695/// Hours, not days, because a custodian holds ciphertext it cannot re-seal
696/// (`docs/spec/custody.md`, invariant three): the depositor survives a
697/// session re-key by re-sealing from retained plaintext, and the custodian's
698/// copy has a validity horizon it cannot observe. Strictly under the seven-day
699/// outbox lifetime by a wide margin, so the default configuration validates.
700pub const DEFAULT_CUSTODY_HOLD_MS: u64 = 6 * 60 * 60 * 1000;
701
702/// Held frames one depositor may have in custody at once, by default.
703pub const DEFAULT_CUSTODY_MAX_ENTRIES_PER_DEPOSITOR: usize = 64;
704
705/// Bytes one depositor may have in custody at once, by default: 2 MiB.
706pub const DEFAULT_CUSTODY_MAX_BYTES_PER_DEPOSITOR: usize = 2 * 1024 * 1024;
707
708/// Held frames across every depositor, by default.
709pub const DEFAULT_CUSTODY_MAX_ENTRIES: usize = 512;
710
711/// Bytes across every depositor, by default: 16 MiB.
712pub const DEFAULT_CUSTODY_MAX_BYTES: usize = 16 * 1024 * 1024;
713
714/// The smallest per-depositor byte budget that admits one replication frame at
715/// its ceiling: 64 KiB.
716///
717/// A Class A frame carries at most 32 KiB of blob
718/// (`data_sync::MAX_SYNC_BLOB_BYTES`), which base64 grows by a third, which
719/// the MLS envelope then encodes again, so a sealed frame at the ceiling is
720/// around 58 KiB of content with the outer message's addresses and metadata
721/// on top. A byte cap below this admits no such frame and refuses every
722/// deposit as `depositor_full`, which is the silent dial the `enabled` switch
723/// exists to replace.
724pub const CUSTODY_MIN_BYTES_PER_DEPOSITOR: usize = 64 * 1024;
725
726/// Custody: holding a neighbour's replication frame for hours instead of the
727/// seconds a forwarder gives it (`docs/spec/custody.md`).
728///
729/// Off by default, and every dial here is the custodian's. A device that
730/// never enables it behaves exactly as before, and a device that enables it
731/// takes on other people's ciphertext under the quotas below. The hold is
732/// validated strictly shorter than `reliability.retry.outbox_max_lifetime_ms`,
733/// because a custodian that outlived the depositor's outbox would deliver
734/// frames whose sender already reported them failed.
735#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
736pub struct CustodyConfig {
737    /// Whether this device accepts deposits. The off switch: refusing to hold
738    /// other people's traffic is this dial's job, never a zeroed budget's.
739    pub enabled: bool,
740    /// How long an accepted frame is held, in milliseconds, judged in wall
741    /// time from each record's acceptance timestamp against the value in
742    /// force at the sweep. Lowering it expires records already held.
743    pub hold_ms: u64,
744    /// Held frames one depositor with an established session may have at once.
745    pub max_entries_per_depositor: usize,
746    /// Bytes one depositor with an established session may have at once.
747    pub max_bytes_per_depositor: usize,
748    /// Held frames across every depositor.
749    pub max_entries: usize,
750    /// Bytes across every depositor.
751    pub max_bytes: usize,
752    /// Held frames one proven peer *without* an established session may have
753    /// at once. Zero, the default, means deposits are accepted only from peers
754    /// with a session, which costs a key package exchange and is what makes
755    /// the session tier resistant to an attacker who mints addresses for free.
756    pub stranger_max_entries: usize,
757    /// Bytes one proven peer without an established session may have at once.
758    pub stranger_max_bytes: usize,
759    /// What happens when a budget is full: evict the oldest held frame to
760    /// admit the new one, or refuse the new one.
761    pub overflow_policy: OverflowPolicy,
762}
763
764impl Default for CustodyConfig {
765    fn default() -> Self {
766        Self {
767            enabled: false,
768            hold_ms: DEFAULT_CUSTODY_HOLD_MS,
769            max_entries_per_depositor: DEFAULT_CUSTODY_MAX_ENTRIES_PER_DEPOSITOR,
770            max_bytes_per_depositor: DEFAULT_CUSTODY_MAX_BYTES_PER_DEPOSITOR,
771            max_entries: DEFAULT_CUSTODY_MAX_ENTRIES,
772            max_bytes: DEFAULT_CUSTODY_MAX_BYTES,
773            stranger_max_entries: 0,
774            stranger_max_bytes: 0,
775            overflow_policy: OverflowPolicy::DropOldest,
776        }
777    }
778}
779
780/// Main configuration for the Offline Protocol.
781#[derive(Debug, Clone)]
782pub struct ProtocolConfig {
783    /// Application identifier (required).
784    ///
785    /// Two jobs. It is one of the two inputs to the storage namespace, with
786    /// [`Self::profile`], so changing it selects fresh storage and a fresh
787    /// identity. And it is the id stamped on every frame this instance
788    /// originates: messages, media chunks, acknowledgements and control
789    /// traffic. A rich send may name another id for its own frame
790    /// ([`crate::SendMessageOptions::app_id`]), which is how one instance
791    /// serves several local applications behind one identity; the
792    /// acknowledgements and control frames the engine sends always carry
793    /// this one. The bindings also derive the BLE app tag from it.
794    ///
795    /// It is cleartext on the wire and covered by no signature, so every
796    /// carrier and hop can read it and rewrite it (threat model R17). It
797    /// names an application, so it is not secret, but treat it as routing
798    /// metadata only: the receive path delivers a message whatever id it
799    /// carries.
800    pub app_id: String,
801
802    /// Local profile selector (required).
803    ///
804    /// Selects which stored identity this instance runs as — one namespace per
805    /// `(app_id, profile)` pair — so an app hosting several accounts gives each
806    /// its own value, and an app hosting one can pass a constant like
807    /// `"default"`.
808    ///
809    /// It is **not** the device's identity. The wire identity is the
810    /// self-certifying address derived from the identity key held in this
811    /// profile's storage: it is minted on first start, reported by
812    /// [`crate::OfflineProtocol::local_address`], and it is what gets stamped
813    /// as `Message.sender`, what peers see as `NeighborDiscovered.peer_id`,
814    /// and what others use as `recipient`. An app cannot choose it, because
815    /// choosing it would mean claiming a key one does not hold.
816    ///
817    /// Under any configuration that reaches the wire the profile stays local.
818    /// The one exception is the explicit
819    /// [`EncryptionConfig::require_encryption`]` = false` opt-out, which lets a
820    /// plaintext send go out with MLS never initialized — no address has been
821    /// derived at that point, so the frame carries the profile as its sender
822    /// and the send emits
823    /// [`crate::events::SecurityWarningCode::PlaintextSend`]. The default
824    /// (`require_encryption = true`) fails such a send closed instead. Treat
825    /// the profile as private if that opt-out is in use.
826    pub profile: String,
827
828    /// Transport configuration.
829    pub transport: TransportConfig,
830
831    /// DORS (Dynamic Offline Relay Switch) configuration.
832    pub dors: DorsConfig,
833
834    /// Relay management configuration: whether this device carries traffic
835    /// for other people at all, and the battery floors under which it stops.
836    pub relay: RelayConfig,
837
838    /// How this device carries traffic for other people: how far frames
839    /// travel, how many neighbors each is handed to, and the ceilings that
840    /// keep forwarding from crowding the radio out.
841    ///
842    /// Whether to forward is [`Self::relay`]'s decision; this is the shape of
843    /// it once the answer is yes.
844    pub mesh_relay: MeshRelayConfig,
845
846    /// Reliability layer configuration.
847    pub reliability: ReliabilityConfig,
848
849    /// Encryption configuration for automatic MLS handling.
850    pub encryption: EncryptionConfig,
851
852    /// Initial TTL (Time-To-Live) for messages.
853    pub initial_ttl: u8,
854
855    /// Mesh group messaging configuration.
856    pub group: GroupConfig,
857
858    /// Security configuration for transport and control-message hardening.
859    pub security: SecurityConfig,
860
861    /// Replicated-document data layer configuration.
862    pub data: DataConfig,
863
864    /// Custody: holding a neighbour's replication frames for hours. Off by
865    /// default; see [`CustodyConfig`].
866    pub custody: CustodyConfig,
867}
868
869impl ProtocolConfig {
870    /// Creates a new protocol configuration.
871    ///
872    /// # Arguments
873    ///
874    /// * `app_id` - Application identifier
875    /// * `profile` - Local profile selector (storage namespace, never on the wire)
876    pub fn new(app_id: impl Into<String>, profile: impl Into<String>) -> Self {
877        Self {
878            app_id: app_id.into(),
879            profile: profile.into(),
880            transport: TransportConfig::default(),
881            dors: DorsConfig::default(),
882            relay: RelayConfig::default(),
883            mesh_relay: MeshRelayConfig::default(),
884            reliability: ReliabilityConfig::default(),
885            encryption: EncryptionConfig::default(),
886            initial_ttl: DEFAULT_INITIAL_TTL,
887            group: GroupConfig::default(),
888            security: SecurityConfig::default(),
889            data: DataConfig::default(),
890            custody: CustodyConfig::default(),
891        }
892    }
893
894    /// Creates a builder for more granular configuration.
895    pub fn builder(app_id: impl Into<String>, profile: impl Into<String>) -> ProtocolConfigBuilder {
896        ProtocolConfigBuilder::new(app_id, profile)
897    }
898
899    /// Validates the configuration.
900    ///
901    /// # Returns
902    ///
903    /// Returns `Ok(())` if valid, `Err` with a description of the problem if invalid.
904    pub fn validate(&self) -> crate::Result<()> {
905        // Both become storage keys — `app_id` and `profile` are the two inputs
906        // to the account namespace — so hold them to the same length cap and
907        // charset ban as every other identifier rather than only rejecting the
908        // empty string. Going through the core constructors keeps one policy
909        // instead of a second copy that can drift. Catching this here turns a
910        // later failure deep inside a storage backend into one clear
911        // configuration error.
912        offline_protocol_core::AppId::new(self.app_id.as_str())
913            .map_err(|e| crate::Error::InvalidConfiguration(e.to_string()))?;
914
915        offline_protocol_core::UserId::new(self.profile.as_str())
916            .map_err(|e| crate::Error::InvalidConfiguration(e.to_string()))?;
917
918        if self.initial_ttl == 0 {
919            return Err(crate::Error::InvalidConfiguration(
920                "initial_ttl must be greater than 0".to_string(),
921            ));
922        }
923
924        if !self.transport.ble_enabled
925            && !self.transport.wifi_direct_enabled
926            && !self.transport.internet_enabled
927            && !self.transport.reticulum_enabled
928            && !self.transport.nostr_enabled
929        {
930            return Err(crate::Error::InvalidConfiguration(
931                "At least one transport must be enabled".to_string(),
932            ));
933        }
934
935        if self.reliability.ack.default_timeout_ms == 0 {
936            return Err(crate::Error::InvalidConfiguration(
937                "ack.default_timeout_ms must be greater than 0".to_string(),
938            ));
939        }
940
941        if self.reliability.ack.max_pending_acks == 0 {
942            return Err(crate::Error::InvalidConfiguration(
943                "ack.max_pending_acks must be greater than 0".to_string(),
944            ));
945        }
946
947        if self.reliability.retry.initial_delay_ms == 0 {
948            return Err(crate::Error::InvalidConfiguration(
949                "retry.initial_delay_ms must be greater than 0".to_string(),
950            ));
951        }
952
953        if self.reliability.retry.max_delay_ms == 0 {
954            return Err(crate::Error::InvalidConfiguration(
955                "retry.max_delay_ms must be greater than 0".to_string(),
956            ));
957        }
958
959        if self.reliability.retry.initial_delay_ms > self.reliability.retry.max_delay_ms {
960            return Err(crate::Error::InvalidConfiguration(
961                "retry.initial_delay_ms must be <= retry.max_delay_ms".to_string(),
962            ));
963        }
964
965        if self.reliability.retry.outbox_max_lifetime_ms == 0
966            || self.reliability.retry.outbox_max_lifetime_ms > i64::MAX as u64
967        {
968            return Err(crate::Error::InvalidConfiguration(
969                "retry.outbox_max_lifetime_ms must be in 1..=i64::MAX".to_string(),
970            ));
971        }
972
973        if self.reliability.retry.pending_message_max_lifetime_ms == 0 {
974            return Err(crate::Error::InvalidConfiguration(
975                "retry.pending_message_max_lifetime_ms must be greater than 0".to_string(),
976            ));
977        }
978
979        if self.reliability.retry.pending_message_max_lifetime_ms > i64::MAX as u64 {
980            return Err(crate::Error::InvalidConfiguration(
981                "retry.pending_message_max_lifetime_ms must be <= i64::MAX".to_string(),
982            ));
983        }
984
985        if !self.reliability.retry.backoff_multiplier.is_finite()
986            || self.reliability.retry.backoff_multiplier < 1.0
987        {
988            return Err(crate::Error::InvalidConfiguration(
989                "retry.backoff_multiplier must be finite and >= 1.0".to_string(),
990            ));
991        }
992
993        // Checked outside the Bloom guard below, and that placement is the
994        // whole point: these two are the *only* dedup fields the UniFFI
995        // `DedupConfig` carries, so every constraint hidden behind
996        // `use_bloom_filter` is unreachable from a binding caller. A zero here
997        // is not a cosmetic problem — `Deduplicator` fails safe on the Bloom
998        // parameters, but nothing fails safe on these. At
999        // `max_tracked_messages == 0` the HashMap branch of `mark_seen` evicts
1000        // on every insert, so the map holds one id and duplicate suppression is
1001        // effectively off; `retention_time_secs == 0` expires every entry
1002        // immediately for the same net result.
1003        //
1004        // What this rejects is the *degenerate* value, and that is the whole of
1005        // the claim: a floor of 1 is not a floor on how well duplicates are
1006        // suppressed. `max_tracked_messages == 1` behaves indistinguishably
1007        // from `0`, and a two-second retention on a link whose retry backoff is
1008        // longer than that suppresses nothing either. Choosing a window wide
1009        // enough for the deployment is the application's call — the SDK refuses
1010        // only the values that cannot be a choice, because nothing downstream
1011        // spells them as a configuration error and the failure they produce
1012        // (silently re-delivered messages) does not look like a config bug.
1013        // Raising either floor to a policy minimum is a wider behavioural break
1014        // and would need its own decision.
1015        if self.reliability.dedup.max_tracked_messages == 0 {
1016            return Err(crate::Error::InvalidConfiguration(
1017                "reliability.dedup.max_tracked_messages must be greater than 0".to_string(),
1018            ));
1019        }
1020
1021        if self.reliability.dedup.retention_time_secs == 0 {
1022            return Err(crate::Error::InvalidConfiguration(
1023                "reliability.dedup.retention_time_secs must be greater than 0".to_string(),
1024            ));
1025        }
1026
1027        if self.reliability.dedup.use_bloom_filter {
1028            if self.reliability.dedup.bloom_filter_bits == 0 {
1029                return Err(crate::Error::InvalidConfiguration(
1030                    "reliability.dedup.bloom_filter_bits must be greater than 0".to_string(),
1031                ));
1032            }
1033
1034            if self.reliability.dedup.bloom_hash_count == 0 {
1035                return Err(crate::Error::InvalidConfiguration(
1036                    "reliability.dedup.bloom_hash_count must be greater than 0".to_string(),
1037                ));
1038            }
1039
1040            if self.reliability.dedup.bloom_filter_count == 0 {
1041                return Err(crate::Error::InvalidConfiguration(
1042                    "reliability.dedup.bloom_filter_count must be greater than 0".to_string(),
1043                ));
1044            }
1045
1046            if self.reliability.dedup.bloom_rotation_secs == 0 {
1047                return Err(crate::Error::InvalidConfiguration(
1048                    "reliability.dedup.bloom_rotation_secs must be greater than 0".to_string(),
1049                ));
1050            }
1051        }
1052
1053        if self.encryption.require_encryption && !self.encryption.enabled {
1054            return Err(crate::Error::InvalidConfiguration(
1055                "encryption.require_encryption requires encryption.enabled=true".to_string(),
1056            ));
1057        }
1058
1059        if self.encryption.pending_queue.max_pending_per_peer == 0 {
1060            return Err(crate::Error::InvalidConfiguration(
1061                "encryption.pending_queue.max_pending_per_peer must be greater than 0".to_string(),
1062            ));
1063        }
1064
1065        if self.encryption.pending_queue.max_pending_global == 0 {
1066            return Err(crate::Error::InvalidConfiguration(
1067                "encryption.pending_queue.max_pending_global must be greater than 0".to_string(),
1068            ));
1069        }
1070
1071        if self.encryption.pending_queue.max_pending_global
1072            < self.encryption.pending_queue.max_pending_per_peer
1073        {
1074            return Err(crate::Error::InvalidConfiguration(
1075                "encryption.pending_queue.max_pending_global must be >= max_pending_per_peer"
1076                    .to_string(),
1077            ));
1078        }
1079
1080        if self.encryption.pending_queue.pending_ttl_ms == 0 {
1081            return Err(crate::Error::InvalidConfiguration(
1082                "encryption.pending_queue.pending_ttl_ms must be greater than 0".to_string(),
1083            ));
1084        }
1085
1086        if self.group.max_group_members == 0 {
1087            return Err(crate::Error::InvalidConfiguration(
1088                "group.max_group_members must be greater than 0".to_string(),
1089            ));
1090        }
1091
1092        // A fan-out of zero is not a cheaper forward, it is a silent drop: the
1093        // frame has already been admitted and recorded as seen, so no copy goes
1094        // out and this node's suppression entry stops it arriving again by
1095        // another path. Same argument as `bias_min_scale` below — declining to
1096        // carry other people's traffic is `relay.allow_relay`'s job, and it is
1097        // visible. The forwarding paths clamp with `.max(1)`; rejecting zero
1098        // here keeps that clamp an unreachable defensive floor instead of a
1099        // silent rewrite of what zero means.
1100        if self.mesh_relay.fanout == 0 {
1101            return Err(crate::Error::InvalidConfiguration(
1102                "mesh_relay.fanout must be greater than 0".to_string(),
1103            ));
1104        }
1105
1106        // The same argument as fan-out, for every other dial that can reach
1107        // zero. Each of these reads like a conservative setting and is in fact
1108        // an off switch that reports nothing: the failure is total, silent, and
1109        // indistinguishable from a quiet neighborhood, which is what makes
1110        // rejecting it at construction worth more than any runtime clamp.
1111        //
1112        // A hop ceiling of zero clamps every arriving budget to nothing, so
1113        // `prepare_hop` refuses the frame before it is ever queued. Both
1114        // ceilings are checked: the dense one applies only in a crowded room,
1115        // so a zero there fails exactly where the mesh is most needed and
1116        // nowhere else — the hardest version of this bug to reproduce.
1117        if self.mesh_relay.max_ttl == 0 {
1118            return Err(crate::Error::InvalidConfiguration(
1119                "mesh_relay.max_ttl must be greater than 0".to_string(),
1120            ));
1121        }
1122
1123        if self.mesh_relay.dense_max_ttl == 0 {
1124            return Err(crate::Error::InvalidConfiguration(
1125                "mesh_relay.dense_max_ttl must be greater than 0".to_string(),
1126            ));
1127        }
1128
1129        // A queue that holds nothing refuses every admission: the length is
1130        // always at or over capacity, and eviction has no victim to find, so
1131        // each frame is rejected as queue-full. Nothing is forwarded and the
1132        // only trace is `refused_queue_full`.
1133        if self.mesh_relay.queue_capacity == 0 {
1134            return Err(crate::Error::InvalidConfiguration(
1135                "mesh_relay.queue_capacity must be greater than 0".to_string(),
1136            ));
1137        }
1138
1139        // The rate and burst dials feed token buckets that clamp their inputs
1140        // with `.max(0.0)`. That clamp makes a negative or NaN value safe in
1141        // the arithmetic sense and catastrophic in every other: the bucket
1142        // simply never yields a token, so forwarding stops for good with no
1143        // error and no counter. NaN matters on its own because `f32::max`
1144        // returns the *other* operand for it, so a NaN rate silently becomes
1145        // zero rather than propagating anywhere visible.
1146        //
1147        // Checked as a set: they are the same failure, and naming the field in
1148        // the message is what makes a rejected config actionable.
1149        for (name, value) in [
1150            ("rate_per_sec", self.mesh_relay.rate_per_sec),
1151            ("burst", self.mesh_relay.burst),
1152            ("peer_rate_per_sec", self.mesh_relay.peer_rate_per_sec),
1153            ("peer_burst", self.mesh_relay.peer_burst),
1154        ] {
1155            if !value.is_finite() || value <= 0.0 {
1156                return Err(crate::Error::InvalidConfiguration(format!(
1157                    "mesh_relay.{name} must be finite and greater than 0"
1158                )));
1159            }
1160        }
1161
1162        // Capability bias scales forwarding effort; it must never be able to
1163        // scale it to nothing. Zero would make a low-battery device stop
1164        // forwarding by the back door, which is the partition the bias design
1165        // exists to avoid — refusing to relay is `relay.allow_relay`'s job.
1166        if !self.mesh_relay.bias_min_scale.is_finite()
1167            || self.mesh_relay.bias_min_scale <= 0.0
1168            || self.mesh_relay.bias_min_scale > 1.0
1169        {
1170            return Err(crate::Error::InvalidConfiguration(
1171                "mesh_relay.bias_min_scale must be finite and in (0.0, 1.0]".to_string(),
1172            ));
1173        }
1174
1175        // An inverted jitter window is not a narrow window, it is two separate
1176        // failures. `jitter_for` raises the effective maximum to meet the
1177        // minimum, so the span collapses to a single millisecond and every
1178        // neighbor picks essentially the same delay — losing the spread that
1179        // stops a crowded room transmitting on top of itself, which is the
1180        // whole reason the delay exists. And because the check below reads
1181        // `jitter_max`, an oversized `jitter_min` would slip past the overdue
1182        // cut-off entirely: a ten-minute minimum with the default maximum
1183        // validates clean and abandons every forward.
1184        if self.mesh_relay.jitter_min > self.mesh_relay.jitter_max {
1185            return Err(crate::Error::InvalidConfiguration(format!(
1186                "mesh_relay.jitter_min ({}ms) must not exceed mesh_relay.jitter_max ({}ms)",
1187                self.mesh_relay.jitter_min.as_millis(),
1188                self.mesh_relay.jitter_max.as_millis(),
1189            )));
1190        }
1191
1192        // A forward is abandoned rather than sent once it sits
1193        // `RELAY_QUEUE_MAX_OVERDUE` past its due time, so the delay tunables
1194        // must not be able to reach that on their own. Checked at the density
1195        // the jitter span is configured for; the span also grows with neighbor
1196        // count, which is a runtime quantity this cannot see and a documented
1197        // ceiling of the mesh's venue-sized target rather than a config error.
1198        let worst_delay = self
1199            .mesh_relay
1200            .jitter_max
1201            .saturating_add(self.mesh_relay.bias_max_handicap);
1202        if worst_delay >= RELAY_QUEUE_MAX_OVERDUE {
1203            return Err(crate::Error::InvalidConfiguration(format!(
1204                "mesh_relay.jitter_max + mesh_relay.bias_max_handicap ({}ms) must stay under \
1205                 the {}ms overdue cut-off, or every biased forward is abandoned instead of sent",
1206                worst_delay.as_millis(),
1207                RELAY_QUEUE_MAX_OVERDUE.as_millis(),
1208            )));
1209        }
1210
1211        if self.mesh_relay.activity_window.is_zero() {
1212            return Err(crate::Error::InvalidConfiguration(
1213                "mesh_relay.activity_window must be greater than zero".to_string(),
1214            ));
1215        }
1216
1217        if self.mesh_relay.activity_min_forwards == 0 {
1218            return Err(crate::Error::InvalidConfiguration(
1219                "mesh_relay.activity_min_forwards must be greater than 0".to_string(),
1220            ));
1221        }
1222
1223        if self.mesh_relay.activity_idle_windows == 0 {
1224            return Err(crate::Error::InvalidConfiguration(
1225                "mesh_relay.activity_idle_windows must be greater than 0".to_string(),
1226            ));
1227        }
1228
1229        self.validate_custody()?;
1230
1231        Ok(())
1232    }
1233
1234    /// The custody dials (`docs/spec/custody.md`, "Quotas").
1235    ///
1236    /// A zero hold is refused whatever the switch says: it is not a shorter
1237    /// hold, it is a store that expires everything at the first sweep. The
1238    /// remaining bounds are checked only while custody is enabled. The
1239    /// default hold is six hours, and a disabled section that could refuse a
1240    /// configuration whose outbox lifetime is shorter than that would turn
1241    /// every such configuration, which today holds nothing, into a startup
1242    /// error for a feature it never switched on.
1243    fn validate_custody(&self) -> crate::Result<()> {
1244        let custody = &self.custody;
1245
1246        if custody.hold_ms == 0 {
1247            return Err(crate::Error::InvalidConfiguration(
1248                "custody.hold_ms must be greater than 0".to_string(),
1249            ));
1250        }
1251
1252        if !custody.enabled {
1253            return Ok(());
1254        }
1255
1256        // The inversion this refuses is silent: a custodian whose hold
1257        // outlives the depositor's outbox keeps bytes whose sender has already
1258        // reported the message failed, and delivers a frame to settle an entry
1259        // that no longer exists. Nothing at runtime would notice, because the
1260        // custodian cannot see the depositor's ladder.
1261        let outbox_lifetime_ms = self.reliability.retry.outbox_max_lifetime_ms;
1262        if custody.hold_ms >= outbox_lifetime_ms {
1263            return Err(crate::Error::InvalidConfiguration(format!(
1264                "custody.hold_ms ({}ms) must be strictly shorter than \
1265                 retry.outbox_max_lifetime_ms ({}ms): a hold that outlives the outbox \
1266                 delivers frames whose sender has already reported them failed",
1267                custody.hold_ms, outbox_lifetime_ms,
1268            )));
1269        }
1270
1271        // The session tier is the one that admits anything by default, so a
1272        // zero there is custody switched on and holding nothing: the silent
1273        // dial `enabled` exists to replace.
1274        if custody.max_entries_per_depositor == 0 || custody.max_bytes_per_depositor == 0 {
1275            return Err(crate::Error::InvalidConfiguration(
1276                "custody.max_entries_per_depositor and custody.max_bytes_per_depositor must \
1277                 both be greater than 0 while custody is enabled: zero is not a smaller \
1278                 quota, it is a store that refuses every deposit"
1279                    .to_string(),
1280            ));
1281        }
1282
1283        if custody.max_bytes_per_depositor < CUSTODY_MIN_BYTES_PER_DEPOSITOR {
1284            return Err(crate::Error::InvalidConfiguration(format!(
1285                "custody.max_bytes_per_depositor ({}) must admit one replication frame at \
1286                 its ceiling ({} bytes), or every deposit is refused as depositor_full",
1287                custody.max_bytes_per_depositor, CUSTODY_MIN_BYTES_PER_DEPOSITOR,
1288            )));
1289        }
1290
1291        if custody.max_entries < custody.max_entries_per_depositor
1292            || custody.max_bytes < custody.max_bytes_per_depositor
1293        {
1294            return Err(crate::Error::InvalidConfiguration(
1295                "custody.max_entries and custody.max_bytes must each be at least their \
1296                 per-depositor sibling, or the per-depositor dial can never be reached"
1297                    .to_string(),
1298            ));
1299        }
1300
1301        // The stranger tier is off by both dials or on by both. One at zero
1302        // with the other positive reads like a narrow allowance and is a
1303        // refusal of every stranger, which is the default said in a way an
1304        // operator would not recognise as the default.
1305        let stranger_on = custody.stranger_max_entries > 0 || custody.stranger_max_bytes > 0;
1306        if stranger_on && (custody.stranger_max_entries == 0 || custody.stranger_max_bytes == 0) {
1307            return Err(crate::Error::InvalidConfiguration(
1308                "custody.stranger_max_entries and custody.stranger_max_bytes must be both \
1309                 zero (no stranger deposits) or both greater than 0"
1310                    .to_string(),
1311            ));
1312        }
1313
1314        if stranger_on && custody.stranger_max_bytes < CUSTODY_MIN_BYTES_PER_DEPOSITOR {
1315            return Err(crate::Error::InvalidConfiguration(format!(
1316                "custody.stranger_max_bytes ({}) must admit one replication frame at its \
1317                 ceiling ({} bytes), or every stranger deposit is refused as depositor_full",
1318                custody.stranger_max_bytes, CUSTODY_MIN_BYTES_PER_DEPOSITOR,
1319            )));
1320        }
1321
1322        if custody.max_entries < custody.stranger_max_entries
1323            || custody.max_bytes < custody.stranger_max_bytes
1324        {
1325            return Err(crate::Error::InvalidConfiguration(
1326                "custody.max_entries and custody.max_bytes must each be at least the \
1327                 stranger tier's dial, or that tier can never be reached"
1328                    .to_string(),
1329            ));
1330        }
1331
1332        Ok(())
1333    }
1334}
1335
1336/// Builder for ProtocolConfig with a fluent API.
1337pub struct ProtocolConfigBuilder {
1338    config: ProtocolConfig,
1339}
1340
1341impl ProtocolConfigBuilder {
1342    /// Creates a new builder.
1343    pub fn new(app_id: impl Into<String>, profile: impl Into<String>) -> Self {
1344        Self {
1345            config: ProtocolConfig::new(app_id, profile),
1346        }
1347    }
1348
1349    /// Configures transports.
1350    pub fn transport(mut self, config: TransportConfig) -> Self {
1351        self.config.transport = config;
1352        self
1353    }
1354
1355    /// Enables or disables BLE transport.
1356    pub fn ble_enabled(mut self, enabled: bool) -> Self {
1357        self.config.transport.ble_enabled = enabled;
1358        self
1359    }
1360
1361    /// Enables or disables Wi-Fi Direct transport.
1362    pub fn wifi_direct_enabled(mut self, enabled: bool) -> Self {
1363        self.config.transport.wifi_direct_enabled = enabled;
1364        self
1365    }
1366
1367    /// Enables or disables Internet transport.
1368    pub fn internet_enabled(mut self, enabled: bool) -> Self {
1369        self.config.transport.internet_enabled = enabled;
1370        self
1371    }
1372
1373    /// Enables or disables Nostr relay transport.
1374    pub fn nostr_enabled(mut self, enabled: bool) -> Self {
1375        self.config.transport.nostr_enabled = enabled;
1376        self
1377    }
1378
1379    /// Enables or disables sealing of outgoing Nostr frames (default on).
1380    pub fn nostr_sealing_enabled(mut self, enabled: bool) -> Self {
1381        self.config.transport.nostr_sealing_enabled = enabled;
1382        self
1383    }
1384
1385    /// Enables username discovery publication and resolution
1386    /// (default **off**; see
1387    /// [`TransportConfig::nostr_username_discovery_enabled`]).
1388    pub fn nostr_username_discovery_enabled(mut self, enabled: bool) -> Self {
1389        self.config.transport.nostr_username_discovery_enabled = enabled;
1390        self
1391    }
1392
1393    /// Enables or disables Nostr key-package publication and peer resolution
1394    /// (default on; see [`TransportConfig::nostr_cold_contact_enabled`]).
1395    pub fn nostr_cold_contact_enabled(mut self, enabled: bool) -> Self {
1396        self.config.transport.nostr_cold_contact_enabled = enabled;
1397        self
1398    }
1399
1400    /// Configures DORS (Dynamic Offline Relay Switch).
1401    pub fn dors(mut self, config: DorsConfig) -> Self {
1402        self.config.dors = config;
1403        self
1404    }
1405
1406    /// Enables online-first mode (prefer Internet when available).
1407    pub fn online_first(mut self, enabled: bool) -> Self {
1408        self.config.dors.prefer_online = enabled;
1409        self
1410    }
1411
1412    /// Configures relay management.
1413    pub fn relay(mut self, config: RelayConfig) -> Self {
1414        self.config.relay = config;
1415        self
1416    }
1417
1418    /// Configures how traffic is carried for other people.
1419    pub fn mesh_relay(mut self, config: MeshRelayConfig) -> Self {
1420        self.config.mesh_relay = config;
1421        self
1422    }
1423
1424    /// Configures reliability layer.
1425    pub fn reliability(mut self, config: ReliabilityConfig) -> Self {
1426        self.config.reliability = config;
1427        self
1428    }
1429
1430    /// Sets the initial TTL for messages.
1431    pub fn initial_ttl(mut self, ttl: u8) -> Self {
1432        self.config.initial_ttl = ttl;
1433        self
1434    }
1435
1436    /// Configures encryption settings.
1437    pub fn encryption(mut self, config: EncryptionConfig) -> Self {
1438        self.config.encryption = config;
1439        self
1440    }
1441
1442    /// Enables or disables automatic encryption.
1443    pub fn encryption_enabled(mut self, enabled: bool) -> Self {
1444        self.config.encryption.enabled = enabled;
1445        self
1446    }
1447
1448    /// Enables or disables automatic key exchange on peer discovery.
1449    pub fn auto_key_exchange(mut self, enabled: bool) -> Self {
1450        self.config.encryption.auto_key_exchange = enabled;
1451        self
1452    }
1453
1454    /// Enables or disables storing pending messages for later encryption.
1455    pub fn store_pending_messages(mut self, enabled: bool) -> Self {
1456        self.config.encryption.store_pending = enabled;
1457        self
1458    }
1459
1460    /// Enables or disables strict encryption requirement.
1461    pub fn require_encryption(mut self, required: bool) -> Self {
1462        self.config.encryption.require_encryption = required;
1463        self
1464    }
1465
1466    /// Configures pending encrypted message queue bounds and overflow behavior.
1467    pub fn pending_queue(mut self, config: PendingQueueConfig) -> Self {
1468        self.config.encryption.pending_queue = config;
1469        self
1470    }
1471
1472    /// Configures group messaging settings.
1473    pub fn group(mut self, config: GroupConfig) -> Self {
1474        self.config.group = config;
1475        self
1476    }
1477
1478    /// Sets the maximum number of members allowed in a single group.
1479    pub fn max_group_members(mut self, max: usize) -> Self {
1480        self.config.group.max_group_members = max;
1481        self
1482    }
1483
1484    /// Sets whether groups should attempt relay server registration.
1485    pub fn group_relay_enabled(mut self, enabled: bool) -> Self {
1486        self.config.group.relay_enabled = enabled;
1487        self
1488    }
1489
1490    /// Sets whether relay-synced groups may send via a single relay broadcast
1491    /// instead of per-member fan-out. See
1492    /// [`GroupConfig::relay_broadcast_enabled`] — on by default, but only
1493    /// ever taken against a relay that advertised the `group_delivery_v3`
1494    /// capability, whose settled, address-space delivery report gives the
1495    /// broadcast a per-recipient delivery contract.
1496    pub fn group_relay_broadcast_enabled(mut self, enabled: bool) -> Self {
1497        self.config.group.relay_broadcast_enabled = enabled;
1498        self
1499    }
1500
1501    /// Sets whether unauthorized MLS membership commits are refused rather
1502    /// than applied-and-reported. See
1503    /// [`GroupConfig::enforce_admin_commits`] — off by default, and enabling
1504    /// it risks permanently forking members whose admin overlay disagrees.
1505    pub fn group_enforce_admin_commits(mut self, enabled: bool) -> Self {
1506        self.config.group.enforce_admin_commits = enabled;
1507        self
1508    }
1509
1510    /// Configures security settings.
1511    pub fn security(mut self, config: SecurityConfig) -> Self {
1512        self.config.security = config;
1513        self
1514    }
1515
1516    /// Sets whether transport identity is required for control messages.
1517    pub fn require_transport_identity(mut self, required: bool) -> Self {
1518        self.config.security.require_transport_identity = required;
1519        self
1520    }
1521
1522    /// Configures the replicated-document data layer.
1523    pub fn data(mut self, config: DataConfig) -> Self {
1524        self.config.data = config;
1525        self
1526    }
1527
1528    /// Sets whether the data layer accepts work. See [`DataConfig::enabled`].
1529    pub fn data_enabled(mut self, enabled: bool) -> Self {
1530        self.config.data.enabled = enabled;
1531        self
1532    }
1533
1534    /// Points documents at a storage backend of the application's choosing.
1535    ///
1536    /// The whole bring-your-own-backend path, in one call. See
1537    /// [`DataConfig::storage`], including what it means for logout.
1538    pub fn data_storage(
1539        mut self,
1540        storage: Arc<dyn crate::protocol_state_storage::ProtocolStateStorage>,
1541    ) -> Self {
1542        self.config.data.storage = Some(storage);
1543        self
1544    }
1545
1546    /// Configures custody: whether this device holds a neighbour's replication
1547    /// frames, and under what quotas. See [`CustodyConfig`].
1548    pub fn custody(mut self, config: CustodyConfig) -> Self {
1549        self.config.custody = config;
1550        self
1551    }
1552
1553    /// Builds and validates the configuration.
1554    ///
1555    /// # Returns
1556    ///
1557    /// Returns `Ok(ProtocolConfig)` if valid, `Err` otherwise.
1558    pub fn build(self) -> crate::Result<ProtocolConfig> {
1559        self.config.validate()?;
1560        Ok(self.config)
1561    }
1562}
1563
1564#[cfg(test)]
1565mod tests {
1566    use super::*;
1567
1568    #[test]
1569    fn test_config_creation() {
1570        let config = ProtocolConfig::new("test-app", "user123");
1571        assert_eq!(config.app_id, "test-app");
1572        assert_eq!(config.profile, "user123");
1573        assert_eq!(config.initial_ttl, 8);
1574    }
1575
1576    #[test]
1577    fn test_config_validation_success() {
1578        let config = ProtocolConfig::new("test-app", "user123");
1579        assert!(config.validate().is_ok());
1580    }
1581
1582    #[test]
1583    fn test_config_validation_empty_app_id() {
1584        let config = ProtocolConfig::new("", "user123");
1585        assert!(config.validate().is_err());
1586    }
1587
1588    #[test]
1589    fn test_config_validation_empty_user_id() {
1590        let config = ProtocolConfig::new("test-app", "");
1591        assert!(config.validate().is_err());
1592    }
1593
1594    #[test]
1595    fn config_validation_enforces_the_id_length_cap() {
1596        // An unbounded id becomes an unbounded storage key and an unbounded
1597        // wire field; the cap is the same one the core newtypes apply.
1598        let at_cap = "a".repeat(offline_protocol_core::MAX_ID_LEN);
1599        let over_cap = "a".repeat(offline_protocol_core::MAX_ID_LEN + 1);
1600
1601        assert!(ProtocolConfig::new("test-app", &at_cap).validate().is_ok());
1602        assert!(ProtocolConfig::new(&at_cap, "user123").validate().is_ok());
1603        assert!(ProtocolConfig::new("test-app", &over_cap)
1604            .validate()
1605            .is_err());
1606        assert!(ProtocolConfig::new(&over_cap, "user123")
1607            .validate()
1608            .is_err());
1609    }
1610
1611    #[test]
1612    fn config_validation_enforces_the_id_charset() {
1613        // Path separators and the KV namespace separator would let an id
1614        // escape or collide with another account's storage keys.
1615        for hostile in ["a/b", "a\\b", "a:b", ".", "..", "a\u{0}b", "a\nb"] {
1616            assert!(
1617                ProtocolConfig::new("test-app", hostile).validate().is_err(),
1618                "user_id {hostile:?} must be rejected"
1619            );
1620            assert!(
1621                ProtocolConfig::new(hostile, "user123").validate().is_err(),
1622                "app_id {hostile:?} must be rejected"
1623            );
1624        }
1625    }
1626
1627    #[test]
1628    fn config_validation_accepts_an_address_shaped_id() {
1629        // The self-certifying address format must pass the id policy: the
1630        // bech32m charset is plain lowercase alphanumerics.
1631        let address = "off1qysluvwl5922yctzd0u9gpr06gn3k7ldfvgtwgvn";
1632        assert!(ProtocolConfig::new("test-app", address).validate().is_ok());
1633    }
1634
1635    #[test]
1636    fn test_config_validation_zero_ttl() {
1637        let mut config = ProtocolConfig::new("test-app", "user123");
1638        config.initial_ttl = 0;
1639        assert!(config.validate().is_err());
1640    }
1641
1642    #[test]
1643    fn test_config_validation_no_transports() {
1644        let mut config = ProtocolConfig::new("test-app", "user123");
1645        config.transport.ble_enabled = false;
1646        config.transport.wifi_direct_enabled = false;
1647        config.transport.internet_enabled = false;
1648        assert!(config.validate().is_err());
1649    }
1650
1651    #[test]
1652    fn test_config_validation_retry_initial_delay_must_be_positive() {
1653        let mut config = ProtocolConfig::new("test-app", "user123");
1654        config.reliability.retry.initial_delay_ms = 0;
1655        assert!(config.validate().is_err());
1656    }
1657
1658    #[test]
1659    fn test_config_validation_retry_delay_bounds() {
1660        let mut config = ProtocolConfig::new("test-app", "user123");
1661        config.reliability.retry.initial_delay_ms = 2000;
1662        config.reliability.retry.max_delay_ms = 1000;
1663        assert!(config.validate().is_err());
1664    }
1665
1666    #[test]
1667    fn test_config_validation_retry_backoff_multiplier_bounds() {
1668        let mut config = ProtocolConfig::new("test-app", "user123");
1669        config.reliability.retry.backoff_multiplier = 0.5;
1670        assert!(config.validate().is_err());
1671    }
1672
1673    #[test]
1674    fn test_config_validation_rejects_zero_bloom_parameters() {
1675        let mutations: [fn(&mut DeduplicatorConfig); 4] = [
1676            |dedup: &mut DeduplicatorConfig| dedup.bloom_filter_bits = 0,
1677            |dedup: &mut DeduplicatorConfig| dedup.bloom_hash_count = 0,
1678            |dedup: &mut DeduplicatorConfig| dedup.bloom_filter_count = 0,
1679            |dedup: &mut DeduplicatorConfig| dedup.bloom_rotation_secs = 0,
1680        ];
1681
1682        for mutate in mutations {
1683            let mut config = ProtocolConfig::new("test-app", "user123");
1684            config.reliability.dedup.use_bloom_filter = true;
1685            mutate(&mut config.reliability.dedup);
1686            assert!(config.validate().is_err());
1687        }
1688    }
1689
1690    #[test]
1691    fn test_config_builder() {
1692        let config = ProtocolConfig::builder("test-app", "user123")
1693            .ble_enabled(true)
1694            .wifi_direct_enabled(false)
1695            .online_first(true)
1696            .initial_ttl(10)
1697            .build()
1698            .unwrap();
1699
1700        assert_eq!(config.app_id, "test-app");
1701        assert!(config.transport.ble_enabled);
1702        assert!(!config.transport.wifi_direct_enabled);
1703        assert!(config.dors.prefer_online);
1704        assert_eq!(config.initial_ttl, 10);
1705    }
1706
1707    #[test]
1708    fn test_transport_config_default() {
1709        let transport = TransportConfig::default();
1710        assert!(transport.ble_enabled);
1711        assert!(transport.wifi_direct_enabled);
1712        assert!(transport.internet_enabled);
1713    }
1714
1715    #[test]
1716    fn test_reliability_config_default() {
1717        let reliability = ReliabilityConfig::default();
1718        assert_eq!(reliability.ack.default_timeout_ms, 10000);
1719        assert_eq!(reliability.retry.max_retries, 10);
1720        // 7 days — must match the app-layer presence-flush window and the
1721        // fallback values hardcoded in the RN native bridges
1722        // (OfflineProtocolModule.kt / OfflineProtocolModule.swift).
1723        assert_eq!(reliability.retry.outbox_max_lifetime_ms, 604_800_000);
1724        // 5 min ceiling — also mirrored by the RN bridge fallbacks.
1725        assert_eq!(reliability.retry.max_delay_ms, 300_000);
1726        // Sized for the persisted seen set: see `DeduplicatorConfig::default`.
1727        assert_eq!(reliability.dedup.max_tracked_messages, 5000);
1728        assert_eq!(reliability.dedup.retention_time_secs, 604_800);
1729    }
1730
1731    #[test]
1732    fn test_encryption_config_default() {
1733        let encryption = EncryptionConfig::default();
1734        assert!(encryption.enabled);
1735        assert!(encryption.auto_key_exchange);
1736        assert!(encryption.store_pending);
1737        // SEC-M3: encryption is required by default; plaintext is an
1738        // explicit opt-out, never a silent fallback.
1739        assert!(encryption.require_encryption);
1740        assert_eq!(encryption.pending_queue.max_pending_per_peer, 64);
1741        assert_eq!(encryption.pending_queue.max_pending_global, 4096);
1742        assert_eq!(
1743            encryption.pending_queue.pending_ttl_ms,
1744            DEFAULT_PENDING_TTL_MS
1745        );
1746        assert_eq!(
1747            encryption.pending_queue.overflow_policy,
1748            OverflowPolicy::DropOldest
1749        );
1750    }
1751
1752    #[test]
1753    fn test_encryption_config_disabled() {
1754        let encryption = EncryptionConfig::disabled();
1755        assert!(!encryption.enabled);
1756        assert!(!encryption.auto_key_exchange);
1757        assert!(!encryption.store_pending);
1758        assert!(!encryption.require_encryption);
1759    }
1760
1761    #[test]
1762    fn test_config_builder_with_encryption() {
1763        let config = ProtocolConfig::builder("test-app", "user123")
1764            .encryption_enabled(true)
1765            .auto_key_exchange(true)
1766            .store_pending_messages(false)
1767            .require_encryption(true)
1768            .pending_queue(PendingQueueConfig {
1769                max_pending_per_peer: 32,
1770                max_pending_global: 512,
1771                pending_ttl_ms: 30_000,
1772                overflow_policy: OverflowPolicy::DropNewest,
1773                ..Default::default()
1774            })
1775            .build()
1776            .unwrap();
1777
1778        assert!(config.encryption.enabled);
1779        assert!(config.encryption.auto_key_exchange);
1780        assert!(!config.encryption.store_pending);
1781        assert!(config.encryption.require_encryption);
1782        assert_eq!(config.encryption.pending_queue.max_pending_per_peer, 32);
1783        assert_eq!(config.encryption.pending_queue.max_pending_global, 512);
1784        assert_eq!(config.encryption.pending_queue.pending_ttl_ms, 30_000);
1785        assert_eq!(
1786            config.encryption.pending_queue.overflow_policy,
1787            OverflowPolicy::DropNewest
1788        );
1789    }
1790
1791    #[test]
1792    fn test_config_validation_require_encryption_requires_enabled() {
1793        let mut config = ProtocolConfig::new("test-app", "user123");
1794        config.encryption.enabled = false;
1795        config.encryption.require_encryption = true;
1796        assert!(config.validate().is_err());
1797    }
1798
1799    #[test]
1800    fn test_config_validation_pending_queue_requires_positive_limits() {
1801        let mut config = ProtocolConfig::new("test-app", "user123");
1802        config.encryption.pending_queue.max_pending_per_peer = 0;
1803        assert!(config.validate().is_err());
1804
1805        let mut config = ProtocolConfig::new("test-app", "user123");
1806        config.encryption.pending_queue.max_pending_global = 0;
1807        assert!(config.validate().is_err());
1808
1809        let mut config = ProtocolConfig::new("test-app", "user123");
1810        config.encryption.pending_queue.pending_ttl_ms = 0;
1811        assert!(config.validate().is_err());
1812    }
1813
1814    #[test]
1815    fn test_config_validation_pending_queue_global_must_cover_per_peer() {
1816        let mut config = ProtocolConfig::new("test-app", "user123");
1817        config.encryption.pending_queue.max_pending_per_peer = 100;
1818        config.encryption.pending_queue.max_pending_global = 99;
1819        assert!(config.validate().is_err());
1820    }
1821
1822    #[test]
1823    fn test_group_config_default() {
1824        let group = GroupConfig::default();
1825        assert_eq!(group.max_group_members, 256);
1826        // Registration and broadcast both default on. Registration must stay
1827        // on because invite links resolve against the relay group registry.
1828        // The broadcast default is safe because the flag alone never selects
1829        // the path: it is additionally gated on the relay advertising the
1830        // `group_delivery_v3` capability, whose settled, address-space
1831        // delivery report is what gives the broadcast a per-recipient
1832        // delivery contract.
1833        assert!(group.relay_enabled);
1834        assert!(group.relay_broadcast_enabled);
1835        // Commit enforcement must stay OFF by default. On, a member whose
1836        // admin overlay merely lagged would refuse a legitimate commit and
1837        // fork itself out of a healthy group with no attacker involved —
1838        // unrecoverable without an app-level re-invite. Flipping this default
1839        // is a fleet-wide partition decision, not a hardening tweak.
1840        assert!(!group.enforce_admin_commits);
1841    }
1842
1843    #[test]
1844    fn test_group_enforce_admin_commits_builder_opt_in() {
1845        let config = ProtocolConfig::builder("test-app", "user123")
1846            .group_enforce_admin_commits(true)
1847            .build()
1848            .unwrap();
1849        assert!(config.group.enforce_admin_commits);
1850        assert!(
1851            config.group.relay_enabled && config.group.relay_broadcast_enabled,
1852            "opting into enforcement must not disturb the relay flags"
1853        );
1854    }
1855
1856    #[test]
1857    fn test_group_relay_broadcast_builder_opt_out() {
1858        let config = ProtocolConfig::builder("test-app", "user123")
1859            .group_relay_broadcast_enabled(false)
1860            .build()
1861            .unwrap();
1862        assert!(!config.group.relay_broadcast_enabled);
1863        assert!(
1864            config.group.relay_enabled,
1865            "opting out of the broadcast must not disturb registration"
1866        );
1867    }
1868
1869    #[test]
1870    fn test_config_has_default_group_config() {
1871        let config = ProtocolConfig::new("test-app", "user123");
1872        assert_eq!(config.group.max_group_members, 256);
1873    }
1874
1875    #[test]
1876    fn test_config_validation_zero_max_group_members() {
1877        let mut config = ProtocolConfig::new("test-app", "user123");
1878        config.group.max_group_members = 0;
1879        assert!(config.validate().is_err());
1880    }
1881
1882    #[test]
1883    fn test_config_validation_positive_max_group_members() {
1884        let mut config = ProtocolConfig::new("test-app", "user123");
1885        config.group.max_group_members = 1;
1886        assert!(config.validate().is_ok());
1887    }
1888
1889    /// A handicap large enough to outrun the overdue cut-off must be refused.
1890    ///
1891    /// Past that point a biased forward is not late, it is *abandoned* on
1892    /// release — so the tunable that exists to cost redundancy would be costing
1893    /// delivery, silently, on exactly the devices it is meant to spare.
1894    #[test]
1895    fn test_config_validation_rejects_a_handicap_past_the_overdue_cutoff() {
1896        let mut config = ProtocolConfig::new("test-app", "user123");
1897        config.mesh_relay.bias_max_handicap = RELAY_QUEUE_MAX_OVERDUE;
1898        assert!(config.validate().is_err());
1899
1900        // The jitter window counts toward the same budget, so a handicap that
1901        // fits on its own can still be refused alongside a wide window.
1902        config.mesh_relay.bias_max_handicap = std::time::Duration::from_millis(400);
1903        config.mesh_relay.jitter_max = RELAY_QUEUE_MAX_OVERDUE;
1904        assert!(config.validate().is_err());
1905
1906        // And the defaults must sit comfortably inside it.
1907        let defaults = ProtocolConfig::new("test-app", "user123");
1908        assert!(defaults.validate().is_ok());
1909    }
1910
1911    /// Bias must never be configurable into an off switch.
1912    ///
1913    /// A scale of zero would stop a low-battery device forwarding by the back
1914    /// door, which is the partition the whole bias design exists to avoid —
1915    /// declining to relay is `relay.allow_relay`'s job, and it is visible.
1916    #[test]
1917    fn test_config_validation_rejects_a_bias_scale_that_silences_forwarding() {
1918        for scale in [0.0, -0.5, 1.5, f32::NAN, f32::INFINITY] {
1919            let mut config = ProtocolConfig::new("test-app", "user123");
1920            config.mesh_relay.bias_min_scale = scale;
1921            assert!(
1922                config.validate().is_err(),
1923                "bias_min_scale of {scale} must be refused",
1924            );
1925        }
1926
1927        // 1.0 is the documented way to disable bias entirely, and must stay
1928        // accepted.
1929        let mut config = ProtocolConfig::new("test-app", "user123");
1930        config.mesh_relay.bias_min_scale = 1.0;
1931        assert!(config.validate().is_ok());
1932    }
1933
1934    /// A fan-out of zero must be refused rather than clamped.
1935    ///
1936    /// It reads like an off switch and is not one: the frame is already
1937    /// admitted and recorded as seen by the time fan-out is chosen, so zero
1938    /// targets is a silent drop that also suppresses the copy arriving by
1939    /// another path. The forwarding paths clamp it to one; this keeps that
1940    /// clamp a defensive floor rather than a quiet reinterpretation.
1941    #[test]
1942    fn test_config_validation_rejects_a_fanout_of_zero() {
1943        let mut config = ProtocolConfig::new("test-app", "user123");
1944        config.mesh_relay.fanout = 0;
1945        assert!(config.validate().is_err());
1946
1947        // One is a real setting — forward to a single neighbor — and must stay
1948        // accepted, or the check has swallowed the narrowest working fan-out.
1949        config.mesh_relay.fanout = 1;
1950        assert!(config.validate().is_ok());
1951    }
1952
1953    /// Every hop-budget, queue and rate dial that can silently switch
1954    /// forwarding off must be refused, not clamped.
1955    ///
1956    /// These share one failure and it is the worst kind: the device keeps
1957    /// running, reports no error, and carries nothing. Each value below is the
1958    /// one a caller would reach for meaning "be conservative", so leaving them
1959    /// legal makes an off switch out of a dial nobody thinks is one.
1960    #[test]
1961    fn test_config_validation_rejects_dials_that_silently_stop_forwarding() {
1962        // Both hop ceilings: zero clamps every arriving budget to nothing, so
1963        // the frame is refused before it can be queued. The dense one is
1964        // checked separately because it only bites in a crowded room.
1965        let mut zero_ttl = ProtocolConfig::new("test-app", "user123");
1966        zero_ttl.mesh_relay.max_ttl = 0;
1967        assert!(zero_ttl.validate().is_err());
1968
1969        let mut zero_dense_ttl = ProtocolConfig::new("test-app", "user123");
1970        zero_dense_ttl.mesh_relay.dense_max_ttl = 0;
1971        assert!(zero_dense_ttl.validate().is_err());
1972
1973        // A queue that holds nothing rejects every admission as queue-full.
1974        let mut zero_queue = ProtocolConfig::new("test-app", "user123");
1975        zero_queue.mesh_relay.queue_capacity = 0;
1976        assert!(zero_queue.validate().is_err());
1977
1978        // The token buckets clamp their inputs with `.max(0.0)`, which turns
1979        // each of these into a bucket that never yields a token. NaN is listed
1980        // on its own because `f32::max` returns the other operand for it, so it
1981        // arrives as zero rather than failing anywhere visible, and negatives
1982        // are what a bridge's own clamp hands over for validation here.
1983        for bad in [0.0_f32, -1.0, f32::NAN, f32::INFINITY] {
1984            let mut rate = ProtocolConfig::new("test-app", "user123");
1985            rate.mesh_relay.rate_per_sec = bad;
1986            assert!(
1987                rate.validate().is_err(),
1988                "rate_per_sec of {bad} must be refused",
1989            );
1990
1991            let mut burst = ProtocolConfig::new("test-app", "user123");
1992            burst.mesh_relay.burst = bad;
1993            assert!(burst.validate().is_err(), "burst of {bad} must be refused");
1994
1995            let mut peer_rate = ProtocolConfig::new("test-app", "user123");
1996            peer_rate.mesh_relay.peer_rate_per_sec = bad;
1997            assert!(
1998                peer_rate.validate().is_err(),
1999                "peer_rate_per_sec of {bad} must be refused",
2000            );
2001
2002            let mut peer_burst = ProtocolConfig::new("test-app", "user123");
2003            peer_burst.mesh_relay.peer_burst = bad;
2004            assert!(
2005                peer_burst.validate().is_err(),
2006                "peer_burst of {bad} must be refused",
2007            );
2008        }
2009
2010        // The narrowest working settings must stay accepted, or the checks have
2011        // swallowed real configurations along with the broken ones.
2012        let mut minimal = ProtocolConfig::new("test-app", "user123");
2013        minimal.mesh_relay.max_ttl = 1;
2014        minimal.mesh_relay.dense_max_ttl = 1;
2015        minimal.mesh_relay.queue_capacity = 1;
2016        minimal.mesh_relay.rate_per_sec = 0.5;
2017        minimal.mesh_relay.burst = 1.0;
2018        minimal.mesh_relay.peer_rate_per_sec = 0.5;
2019        minimal.mesh_relay.peer_burst = 1.0;
2020        assert!(minimal.validate().is_ok());
2021    }
2022
2023    /// An inverted jitter window must be refused.
2024    ///
2025    /// Two failures in one, which is why the equal case has to stay legal to
2026    /// prove the check is an ordering check and not a ban on narrow windows.
2027    /// `jitter_for` raises the effective maximum to meet the minimum, so the
2028    /// span collapses to a millisecond and neighbors stop separating in time;
2029    /// and since the overdue check reads `jitter_max`, an oversized minimum
2030    /// would otherwise validate clean and abandon every forward.
2031    #[test]
2032    fn test_config_validation_rejects_an_inverted_jitter_window() {
2033        let mut inverted = ProtocolConfig::new("test-app", "user123");
2034        inverted.mesh_relay.jitter_min = std::time::Duration::from_millis(300);
2035        inverted.mesh_relay.jitter_max = std::time::Duration::from_millis(200);
2036        assert!(inverted.validate().is_err());
2037
2038        // The case the overdue check alone would have missed: a minimum past
2039        // the 5s cut-off, with the maximum left at its default.
2040        let mut oversized_min = ProtocolConfig::new("test-app", "user123");
2041        oversized_min.mesh_relay.jitter_min = std::time::Duration::from_secs(600);
2042        assert!(oversized_min.validate().is_err());
2043
2044        // Equal is a fixed delay, not an inversion, and stays accepted.
2045        let mut equal = ProtocolConfig::new("test-app", "user123");
2046        equal.mesh_relay.jitter_min = std::time::Duration::from_millis(200);
2047        equal.mesh_relay.jitter_max = std::time::Duration::from_millis(200);
2048        assert!(equal.validate().is_ok());
2049    }
2050
2051    /// The activity window's tunables decide whether the relay standing can be
2052    /// reported at all; a zero in any of them stalls or divides it.
2053    #[test]
2054    fn test_config_validation_rejects_zero_activity_tunables() {
2055        let mut zero_window = ProtocolConfig::new("test-app", "user123");
2056        zero_window.mesh_relay.activity_window = std::time::Duration::ZERO;
2057        assert!(zero_window.validate().is_err());
2058
2059        let mut zero_forwards = ProtocolConfig::new("test-app", "user123");
2060        zero_forwards.mesh_relay.activity_min_forwards = 0;
2061        assert!(zero_forwards.validate().is_err());
2062
2063        let mut zero_idle = ProtocolConfig::new("test-app", "user123");
2064        zero_idle.mesh_relay.activity_idle_windows = 0;
2065        assert!(zero_idle.validate().is_err());
2066    }
2067
2068    #[test]
2069    fn test_config_builder_max_group_members() {
2070        let config = ProtocolConfig::builder("test-app", "user123")
2071            .max_group_members(50)
2072            .build()
2073            .unwrap();
2074        assert_eq!(config.group.max_group_members, 50);
2075    }
2076
2077    #[test]
2078    fn test_config_builder_group_config() {
2079        let config = ProtocolConfig::builder("test-app", "user123")
2080            .group(GroupConfig {
2081                max_group_members: 128,
2082                ..Default::default()
2083            })
2084            .build()
2085            .unwrap();
2086        assert_eq!(config.group.max_group_members, 128);
2087    }
2088
2089    #[test]
2090    fn test_config_builder_zero_max_group_members_rejected() {
2091        let result = ProtocolConfig::builder("test-app", "user123")
2092            .max_group_members(0)
2093            .build();
2094        assert!(result.is_err());
2095    }
2096
2097    /// The RN bridges never reach [`DEFAULT_PENDING_TTL_MS`]: each layer
2098    /// substitutes its own fallback when the app omits `pendingTtlMs`, and the
2099    /// JS layer always materializes the field before it crosses the bridge. So
2100    /// the Rust default is only the RN default for as long as these three
2101    /// literals agree with it — they silently drifted to the pre-deferred-ACK
2102    /// 2-minute window once already, which is the window this constant was
2103    /// raised to replace.
2104    ///
2105    /// The sibling guard for the ACK/retry fallbacks lives in
2106    /// `offline-protocol-reliability`; this one has to live here because that
2107    /// crate cannot depend on this one.
2108    #[test]
2109    fn rn_bridge_pending_ttl_fallbacks_match_rust_default() {
2110        let rn_root =
2111            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../bindings/react-native");
2112
2113        // Each entry is (path, the fallback that file must contain). The
2114        // pattern names the field it guards, not just the literal, so deleting
2115        // the fallback cannot be masked by the same number appearing on some
2116        // other line. Matched against the source with whitespace squeezed, so a
2117        // line wrap between the field and its `?:`/`??` doesn't hide it.
2118        let expected = [
2119            (
2120                rn_root.join("src/index.ts"),
2121                format!("pendingTtlMs ?? {DEFAULT_PENDING_TTL_MS}"),
2122            ),
2123            (
2124                rn_root.join("android/src/main/java/com/offlineprotocol/ProtocolConfigParser.kt"),
2125                format!(
2126                    "\"pending_ttl_ms\") ?: {}L",
2127                    format_underscored(DEFAULT_PENDING_TTL_MS)
2128                ),
2129            ),
2130            (
2131                rn_root.join("ios/EncryptionConfigReader.swift"),
2132                format!(
2133                    "\"pending_ttl_ms\") ?? {}",
2134                    format_underscored(DEFAULT_PENDING_TTL_MS)
2135                ),
2136            ),
2137        ];
2138
2139        // The guard only applies in the repo checkout; skip when the bindings
2140        // tree isn't present (e.g. a vendored crate). Read every file up front
2141        // so a moved or renamed bridge skips the whole guard rather than
2142        // silently dropping the checks that come after it.
2143        let Some(sources) = expected
2144            .iter()
2145            .map(|(path, _)| std::fs::read_to_string(path).ok())
2146            .collect::<Option<Vec<_>>>()
2147        else {
2148            eprintln!("bindings tree not present, skipping RN pending-TTL drift check");
2149            return;
2150        };
2151
2152        for ((path, fallback), source) in expected.iter().zip(&sources) {
2153            let squeezed = source.split_whitespace().collect::<Vec<_>>().join(" ");
2154            assert!(
2155                squeezed.contains(fallback.as_str()),
2156                "RN pending-queue TTL fallback drifted from DEFAULT_PENDING_TTL_MS: \
2157                 expected `{fallback}` in {}",
2158                path.display()
2159            );
2160        }
2161    }
2162
2163    /// Drift guard: the React Native `updateDedupConfig` fallbacks match the
2164    /// core dedup defaults. The TypeScript layer forwards only the fields the
2165    /// app set, so a `reliability.dedup` section that sets one field takes the
2166    /// other from these literals, and a fallback that disagrees with the
2167    /// documented default silently changes it for that app. The id cap sat at
2168    /// 10000 against a documented default of 1000, then 2000, that way.
2169    #[test]
2170    fn rn_bridge_dedup_fallbacks_match_rust_default() {
2171        let defaults = ProtocolConfig::new("test-app", "user123").reliability.dedup;
2172        let rn_root =
2173            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../bindings/react-native");
2174        let kotlin =
2175            rn_root.join("android/src/main/java/com/offlineprotocol/OfflineProtocolModule.kt");
2176        let swift = rn_root.join("ios/OfflineProtocolModule.swift");
2177        let expected = [
2178            (
2179                kotlin.clone(),
2180                format!(
2181                    "json.optLong(\"maxTrackedMessages\", {})",
2182                    defaults.max_tracked_messages
2183                ),
2184            ),
2185            (
2186                kotlin,
2187                format!(
2188                    "json.optLong(\"retentionTimeSecs\", {})",
2189                    defaults.retention_time_secs
2190                ),
2191            ),
2192            (
2193                swift.clone(),
2194                format!(
2195                    "(config[\"maxTrackedMessages\"] as? NSNumber)?.uint64Value ?? {}",
2196                    defaults.max_tracked_messages
2197                ),
2198            ),
2199            (
2200                swift,
2201                format!(
2202                    "(config[\"retentionTimeSecs\"] as? NSNumber)?.uint64Value ?? {}",
2203                    defaults.retention_time_secs
2204                ),
2205            ),
2206        ];
2207
2208        let Some(sources) = expected
2209            .iter()
2210            .map(|(path, _)| std::fs::read_to_string(path).ok())
2211            .collect::<Option<Vec<_>>>()
2212        else {
2213            eprintln!("bindings tree not present, skipping RN dedup fallback drift check");
2214            return;
2215        };
2216
2217        for ((path, fallback), source) in expected.iter().zip(&sources) {
2218            let squeezed = source.split_whitespace().collect::<Vec<_>>().join(" ");
2219            assert!(
2220                squeezed.contains(fallback.as_str()),
2221                "RN dedup fallback drifted from the core default: expected `{fallback}` in {}",
2222                path.display()
2223            );
2224        }
2225    }
2226
2227    /// Drift guard: every public surface that documents
2228    /// [`EncryptionConfig::crypto_recovery_enabled`] must state that the re-key
2229    /// trigger is unauthenticated, and must not carry the retired claim that it
2230    /// re-keys only on genuine peer traffic.
2231    ///
2232    /// This is guarded because it has already drifted once. The trigger was
2233    /// hardened and honestly documented in-code, but that pass corrected only
2234    /// `session.rs` and the internal architecture notes — six integrator-facing
2235    /// surfaces kept promising that an injected frame could never drive a
2236    /// re-key, and framed the residual as replay-only, while
2237    /// `test_forged_frame_reaches_session_desync_without_any_key_material` in
2238    /// `offline-protocol-mls` proved the opposite in the same workspace. Nothing
2239    /// else fails when these lag: the code stays correct and the docs quietly
2240    /// promise a guarantee it does not make, which is the worst shape for a
2241    /// security claim to fail in.
2242    #[test]
2243    fn crypto_recovery_docs_state_the_unauthenticated_trigger() {
2244        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
2245        let surfaces = [
2246            "crates/offline-protocol/src/config.rs",
2247            "crates/offline-protocol-uniffi/src/offline_protocol.udl",
2248            "bindings/react-native/src/types.ts",
2249            "docs/mls-integration.md",
2250            "docs/configuration.md",
2251            "docs/api-reference.md",
2252        ];
2253
2254        // Retired claims. Each was false for the same reason: an MLS epoch is
2255        // read during framing validation, before the sender is authenticated.
2256        // Split across `concat!` so the banned phrases never appear verbatim in
2257        // this file — belt-and-braces on top of the `#[cfg(test)]` truncation
2258        // below, so the guard survives either defense being refactored away.
2259        let retired = [
2260            concat!("never re-keys on ", "injected garbage"),
2261            concat!("injected garbage ", "can't drive"),
2262            concat!("injecting ", "garbage"),
2263        ];
2264
2265        // The marker every surface must carry, concat-split for the inverse
2266        // reason: written verbatim, this needle alone would satisfy its own
2267        // check for config.rs no matter what the rustdoc says.
2268        let marker = concat!("re-key trigger is ", "unauthenticated");
2269
2270        for surface in surfaces {
2271            let path = root.join(surface);
2272            let source = std::fs::read_to_string(&path)
2273                .unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display()));
2274            // Scan only up to the first `#[cfg(test)]` token — for config.rs,
2275            // the non-test source. This test necessarily names the marker (doc
2276            // comment, panic message), so scanning its own module would satisfy
2277            // the marker check for the file it lives in even after the rustdoc
2278            // dropped it. The other surfaces don't contain the token and pass
2279            // through whole.
2280            let scanned = source.split("#[cfg(test)]").next().unwrap_or(&source);
2281            // Squeezed so a line wrap inside a phrase cannot hide it, and
2282            // lowercased so a sentence-initial capital cannot either. Standalone
2283            // comment/markup continuation tokens (`///`, `//`, `*`, `>`) are
2284            // dropped, because these six surfaces wrap prose in four different
2285            // comment syntaxes and a reflow would otherwise wedge one into the
2286            // middle of a phrase — a guard that fails on `cargo fmt` teaches
2287            // people to delete it.
2288            let squeezed = scanned
2289                .split_whitespace()
2290                .filter(|tok| !tok.chars().all(|c| matches!(c, '/' | '*' | '>')))
2291                .collect::<Vec<_>>()
2292                .join(" ")
2293                .to_lowercase();
2294
2295            for claim in retired {
2296                assert!(
2297                    !squeezed.contains(claim),
2298                    "{surface} carries the retired claim `{claim}`. The re-key \
2299                     trigger is reachable by anyone who can inject a frame — see \
2300                     test_forged_frame_reaches_session_desync_without_any_key_material"
2301                );
2302            }
2303
2304            assert!(
2305                squeezed.contains(marker),
2306                "{surface} documents crypto_recovery_enabled but no longer states \
2307                 that the re-key trigger is unauthenticated. Say so plainly, or an \
2308                 integrator will read a sustained SESSION_REKEY_TRIGGERED rate as a \
2309                 bug rather than as the injection signal it exists to surface."
2310            );
2311        }
2312    }
2313
2314    /// Renders `86400000` as `86_400_000`, the form Kotlin and Swift use.
2315    fn format_underscored(value: u64) -> String {
2316        let digits = value.to_string();
2317        let mut out = String::new();
2318        for (i, c) in digits.chars().enumerate() {
2319            if i > 0 && (digits.len() - i) % 3 == 0 {
2320                out.push('_');
2321            }
2322            out.push(c);
2323        }
2324        out
2325    }
2326
2327    // ====================================================================
2328    // Custody
2329    // ====================================================================
2330
2331    fn enabled_custody() -> CustodyConfig {
2332        CustodyConfig {
2333            enabled: true,
2334            ..CustodyConfig::default()
2335        }
2336    }
2337
2338    #[test]
2339    fn custody_is_off_by_default_and_the_default_dials_validate_when_on() {
2340        let config = ProtocolConfig::new("app", "user");
2341        assert!(!config.custody.enabled);
2342        assert_eq!(config.custody.hold_ms, DEFAULT_CUSTODY_HOLD_MS);
2343        assert_eq!(config.custody.stranger_max_entries, 0);
2344        assert_eq!(config.custody.stranger_max_bytes, 0);
2345        config.validate().unwrap();
2346
2347        let mut on = ProtocolConfig::new("app", "user");
2348        on.custody = enabled_custody();
2349        on.validate().unwrap();
2350        // The reference defaults respect their own bounds.
2351        assert!(DEFAULT_CUSTODY_HOLD_MS < on.reliability.retry.outbox_max_lifetime_ms);
2352        assert!(DEFAULT_CUSTODY_MAX_BYTES_PER_DEPOSITOR >= CUSTODY_MIN_BYTES_PER_DEPOSITOR);
2353    }
2354
2355    #[test]
2356    fn test_config_validation_rejects_a_custody_hold_that_outlives_the_outbox() {
2357        // The silent inversion: a custodian whose hold outlives the depositor's
2358        // outbox delivers frames whose sender already reported them failed.
2359        let mut config = ProtocolConfig::new("app", "user");
2360        config.custody = enabled_custody();
2361        config.custody.hold_ms = config.reliability.retry.outbox_max_lifetime_ms;
2362        let err = config.validate().unwrap_err().to_string();
2363        assert!(err.contains("custody.hold_ms"), "{err}");
2364        assert!(err.contains("strictly shorter"), "{err}");
2365
2366        config.custody.hold_ms = config.reliability.retry.outbox_max_lifetime_ms - 1;
2367        config.validate().unwrap();
2368
2369        // Disabled, the relation is not checked: a section that is off must
2370        // not refuse a configuration for a feature it never switched on.
2371        config.custody.enabled = false;
2372        config.custody.hold_ms = config.reliability.retry.outbox_max_lifetime_ms * 2;
2373        config.validate().unwrap();
2374
2375        // A zero hold is refused whatever the switch says.
2376        config.custody.hold_ms = 0;
2377        let err = config.validate().unwrap_err().to_string();
2378        assert!(
2379            err.contains("custody.hold_ms must be greater than 0"),
2380            "{err}"
2381        );
2382    }
2383
2384    #[test]
2385    fn test_config_validation_rejects_custody_dials_that_silently_hold_nothing() {
2386        let base = {
2387            let mut config = ProtocolConfig::new("app", "user");
2388            config.custody = enabled_custody();
2389            config
2390        };
2391
2392        let mut zero_entries = base.clone();
2393        zero_entries.custody.max_entries_per_depositor = 0;
2394        assert!(zero_entries
2395            .validate()
2396            .unwrap_err()
2397            .to_string()
2398            .contains("max_entries_per_depositor"));
2399
2400        let mut zero_bytes = base.clone();
2401        zero_bytes.custody.max_bytes_per_depositor = 0;
2402        assert!(zero_bytes
2403            .validate()
2404            .unwrap_err()
2405            .to_string()
2406            .contains("max_bytes_per_depositor"));
2407
2408        let mut too_small = base.clone();
2409        too_small.custody.max_bytes_per_depositor = CUSTODY_MIN_BYTES_PER_DEPOSITOR - 1;
2410        let err = too_small.validate().unwrap_err().to_string();
2411        assert!(err.contains("one replication frame"), "{err}");
2412
2413        let mut inverted = base.clone();
2414        inverted.custody.max_entries = inverted.custody.max_entries_per_depositor - 1;
2415        assert!(inverted
2416            .validate()
2417            .unwrap_err()
2418            .to_string()
2419            .contains("per-depositor sibling"));
2420
2421        let mut inverted_bytes = base.clone();
2422        inverted_bytes.custody.max_bytes = inverted_bytes.custody.max_bytes_per_depositor - 1;
2423        assert!(inverted_bytes
2424            .validate()
2425            .unwrap_err()
2426            .to_string()
2427            .contains("per-depositor sibling"));
2428
2429        // Off, none of it is checked.
2430        let mut off = zero_entries.clone();
2431        off.custody.enabled = false;
2432        off.validate().unwrap();
2433    }
2434
2435    #[test]
2436    fn test_config_validation_holds_the_stranger_tier_to_both_dials() {
2437        let mut config = ProtocolConfig::new("app", "user");
2438        config.custody = enabled_custody();
2439
2440        config.custody.stranger_max_entries = 4;
2441        let err = config.validate().unwrap_err().to_string();
2442        assert!(err.contains("both zero"), "{err}");
2443
2444        config.custody.stranger_max_bytes = CUSTODY_MIN_BYTES_PER_DEPOSITOR - 1;
2445        let err = config.validate().unwrap_err().to_string();
2446        assert!(err.contains("stranger_max_bytes"), "{err}");
2447
2448        config.custody.stranger_max_bytes = CUSTODY_MIN_BYTES_PER_DEPOSITOR;
2449        config.validate().unwrap();
2450
2451        config.custody.stranger_max_entries = config.custody.max_entries + 1;
2452        let err = config.validate().unwrap_err().to_string();
2453        assert!(err.contains("stranger tier"), "{err}");
2454    }
2455
2456    #[test]
2457    fn the_custody_builder_setter_reaches_validation() {
2458        let err = ProtocolConfig::builder("app", "user")
2459            .custody(CustodyConfig {
2460                enabled: true,
2461                hold_ms: u64::MAX,
2462                ..CustodyConfig::default()
2463            })
2464            .build()
2465            .unwrap_err()
2466            .to_string();
2467        assert!(err.contains("custody.hold_ms"), "{err}");
2468    }
2469}