Skip to main content

offline_protocol/protocol/
types.rs

1//! Type definitions, constants, and shared state for the protocol engine.
2
3use crate::events::{Event, EventCallback, PresenceStatus};
4use crate::telemetry::{
5    dispatch_protocol_event, dispatch_record, scrub_event, TelemetryContext, TelemetryRecord,
6};
7use crate::Error;
8use chrono::{DateTime, Utc};
9use offline_protocol_core::{
10    AppId, ContentType, ForwardInfo, MediaMetadata, Message, MessageId, MessagePriority,
11    ReplyContext,
12};
13use offline_protocol_transport::TransportType;
14use serde::{Deserialize, Serialize};
15use std::collections::{HashSet, VecDeque};
16use std::sync::{Arc, Mutex};
17use std::time::Instant;
18use tracing::warn;
19
20/// A carrier that speaks the gateway contract, and can therefore answer about
21/// a third party's reachability.
22///
23/// Two of the five transports qualify, and the type exists so the other three
24/// cannot be passed where a gateway answer is expected. That is not a
25/// theoretical tidiness: every effect of a presence answer is carrier-scoped,
26/// so a wrong carrier records a fact against a transport that never claimed
27/// it and pins an un-park flush to a transport that never proved anything,
28/// neither of which fails loudly.
29///
30/// - **BLE and Wi-Fi Direct** are zone carriers. A neighbour being in range
31///   is a fact about this device's own link, not a claim about a third party,
32///   and it arrives through discovery rather than through a verb.
33/// - **Nostr** structurally cannot answer: a broadcast relay reports no
34///   per-recipient delivery, so it is a carrier and never a gateway. See
35///   [ADR 0017](../../../docs/adr/0017-nostr-is-a-carrier-not-a-gateway.md).
36///   This is a permanent gap, recorded here in the type so it stops being
37///   rediscovered as a bug.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum GatewayCarrier {
40    /// The internet relay, which implemented every verb before the contract
41    /// named them.
42    Internet,
43    /// A gateway daemon reached over local IP, through the transport slot
44    /// named `Reticulum` after its reference backbone. The variant names
45    /// the carrier, not the backbone: what stands behind the daemon is the
46    /// gateway's property, and this device learns of it only as a
47    /// capability token it never reads (ADR 0026).
48    Reticulum,
49}
50
51impl GatewayCarrier {
52    /// The transport this gateway's answers are recorded against.
53    pub fn transport(self) -> TransportType {
54        match self {
55            Self::Internet => TransportType::Internet,
56            Self::Reticulum => TransportType::Reticulum,
57        }
58    }
59
60    /// How a presence answer from this gateway is labelled to the app.
61    pub fn presence_source(self) -> crate::events::PresenceSource {
62        match self {
63            Self::Internet => crate::events::PresenceSource::Internet,
64            Self::Reticulum => crate::events::PresenceSource::Reticulum,
65        }
66    }
67
68    /// The gateway behind `transport`, or `None` for a carrier that answers
69    /// no verdicts.
70    ///
71    /// Exhaustive by construction rather than by a wildcard: a sixth
72    /// transport must be classified here deliberately, and the wrong default
73    /// is the silent one. A carrier that returns `None` is not broken; it
74    /// simply never contradicts the blanket "up means reachable" assumption,
75    /// which is the residual `docs/mesh.md` records.
76    pub fn from_transport(transport: TransportType) -> Option<Self> {
77        match transport {
78            TransportType::Internet => Some(Self::Internet),
79            TransportType::Reticulum => Some(Self::Reticulum),
80            TransportType::BLE | TransportType::WiFiDirect | TransportType::Nostr => None,
81        }
82    }
83}
84
85/// Retry interval for persisting session confirmation after a transient storage error.
86pub(crate) const CONFIRMATION_RETRY_INTERVAL_SECS: i64 = 5;
87/// Probe interval for reconciling pending sessions after restart.
88pub(crate) const CONFIRMATION_PROBE_INTERVAL_SECS: i64 = 5;
89/// Minimum interval between 1:1 session re-keys for the same peer, triggered by
90/// an epoch-desync decrypt failure. A re-key is a full teardown + key-package
91/// re-exchange, so it is rate-limited well above the confirmation-probe cadence:
92/// one legit desync heals in a single round-trip, and this bounds a peer
93/// replaying stale-epoch ciphertext (or an injected wrong-epoch frame) to at
94/// most one re-key per this window rather than a storm. The floor is enforced
95/// unconditionally — a successful decrypt on the healed session does NOT reset
96/// it — so an attacker cannot defeat it by interleaving replays with legit
97/// traffic (see `schedule_session_rekey`).
98pub(crate) const REKEY_INTERVAL_SECS: i64 = 30;
99/// Minimum interval between two pushes of our key package to the same peer
100/// while no session with that peer exists.
101///
102/// The first push is fire-once over a carrier that may lose it without saying
103/// so (a superseded peer stream drops its late frames, `docs/spec/stream-framing.md`), so a
104/// push that produced no session is re-armed. The floor is what keeps the
105/// re-arm from becoming a key-package storm: discovery fires on every inbound
106/// body, and a peer that never answers (an old SDK, encryption opted out) gets
107/// one advertisement per window rather than one per frame. The window doubles
108/// with each repeat up to [`KEY_PACKAGE_RESEND_CAP_SECS`], so that peer is not
109/// sent a key package every 30 seconds for as long as it stays in range.
110pub(crate) const KEY_PACKAGE_RESEND_INTERVAL_SECS: u64 = 30;
111/// Ceiling on the doubling key-package resend window, matching
112/// [`WELCOME_UNREACHABLE_RETRY_CAP_SECS`].
113pub(crate) const KEY_PACKAGE_RESEND_CAP_SECS: u64 = 600;
114// The wait doubles at most five times (`<< min(5)`, which also keeps the
115// shift from wrapping the wait to zero); this keeps the cap reachable.
116const _: () = assert!(KEY_PACKAGE_RESEND_INTERVAL_SECS << 5 >= KEY_PACKAGE_RESEND_CAP_SECS);
117const _: () = assert!(KEY_PACKAGE_RESEND_CAP_SECS as i64 == WELCOME_UNREACHABLE_RETRY_CAP_SECS);
118
119/// Seconds to wait before repeating a key-package push that has already been
120/// repeated `repeats` times: the interval, doubled per repeat, capped.
121pub(crate) fn key_package_resend_wait_secs(repeats: u32) -> u64 {
122    (KEY_PACKAGE_RESEND_INTERVAL_SECS << repeats.min(5)).min(KEY_PACKAGE_RESEND_CAP_SECS)
123}
124/// Number of welcome retry records processed per tick.
125pub(crate) const WELCOME_RETRY_BATCH_SIZE: usize = 20;
126/// Hard TTL for outbound welcome lifecycle records.
127pub(crate) const WELCOME_LIFECYCLE_TTL_SECS: i64 = 300;
128/// Jitter ratio applied to welcome retry backoff delays.
129pub(crate) const WELCOME_RETRY_JITTER_RATIO: f64 = 0.2;
130/// Timeout waiting for explicit internet send confirmation for welcome.
131pub(crate) const WELCOME_INTERNET_CONFIRM_TIMEOUT_SECS: i64 = 10;
132/// Timeout waiting for a mesh (BLE / WiFi-Direct) welcome to be confirmed by
133/// the peer proving the session (probe / ack / welcome / decrypt). A mesh
134/// `send()` returning Ok only means the local stack accepted the bytes, not
135/// that the multi-fragment Welcome reassembled on the peer — so the lifecycle
136/// stays non-terminal and the retry queue re-sends the whole Welcome after this
137/// window, recovering from a lost fragment. Slightly longer than the internet
138/// timeout to allow a slow multi-fragment Welcome to assemble plus the probe
139/// round-trip before paying to re-fragment and re-send it.
140pub(crate) const WELCOME_MESH_CONFIRM_TIMEOUT_SECS: i64 = 15;
141/// Retry cadence for a Welcome that has no transport carrier at all (the peer is
142/// simply unreachable right now). A send is guaranteed to fail with no carrier,
143/// so we do NOT burn the speculative send/transition/event churn on it every
144/// retry tick — we park it and re-check on this slow interval instead. The
145/// primary recovery is event-driven (`on_neighbor_discovered` → re-arm fires the
146/// instant a carrier surfaces the peer); this poll is only a safety net for a
147/// carrier returning without a fresh discovery event, so it is deliberately far
148/// slower than the data-plane retry interval to keep an offline device quiet.
149/// Also the base interval for the plain-DM unreachable reachability probe
150/// (`handle_recipient_unreachable_for_message`), which shares this
151/// escalation.
152pub(crate) const WELCOME_NO_CARRIER_RETRY_SECS: i64 = 15;
153/// Cap for the escalating retry interval of a welcome repeatedly parked
154/// `PeerUnreachable`, on every carrier (see
155/// `apply_recipient_unreachable_failure`). Each consecutive unreachable park
156/// doubles the interval from [`WELCOME_NO_CARRIER_RETRY_SECS`] up to this
157/// cap: DORS may keep selecting the internet path for the timed retry, and
158/// every such round trips another relay `DeliveryError` with the attempt
159/// refunded — without escalation that is an unbounded 15s resend loop into
160/// the relay for as long as the peer stays offline. At the cap the steady
161/// state matches the presence-rescue cadence (one send per 10 min), which is
162/// cheap and self-resolving. Shared by the plain-DM unreachable probe
163/// (`handle_recipient_unreachable_for_message`, per-peer
164/// `dm_unreachable_parks` counter) for the same reason — and there the
165/// escalation carries the whole bound, since that probe runs on every carrier
166/// (see `park_unreachable_dm`), including internet-only devices.
167pub(crate) const WELCOME_UNREACHABLE_RETRY_CAP_SECS: i64 = 600;
168/// Only used when `RetryConfig::edge_driven_unreachable_dm` is opted in. How
169/// many escalating timed probes a plain DM to an unreachable peer gets before
170/// it goes edge-driven (stops being timed-probed and rests in the outbox until
171/// the peer next proves reachable). One probe (plus the original send) gives a
172/// brief blip tolerance; beyond that, recovery is the reachability edge — which
173/// in an opted-in deployment is reliable (peers interact / advertise presence
174/// on return), so more blind probes only lengthen the transient after a mass
175/// disconnect. Default-off deployments never consult this (they probe forever
176/// at the documented 15s->600s cap).
177pub(crate) const DM_UNREACHABLE_PROBE_LIMIT: u32 = 1;
178/// Only used when `RetryConfig::edge_driven_unreachable_dm` is opted in. On the
179/// startup/reconnect re-drive, a still-undelivered outbox message first sent
180/// longer ago than this is left edge-driven rather than re-driven, so a restart
181/// does not re-ramp a durably-failing backlog. Default-off deployments never
182/// consult this.
183pub(crate) const OUTBOX_DURABLE_UNREACHABLE_AGE_SECS: i64 = 300;
184/// Only used when `RetryConfig::edge_driven_unreachable_dm` is opted in.
185/// Sustained rate (per second) and burst budget for the RETRY/PROBE resend path
186/// (`process_retry_queue`). Set below the reference relay's per-connection limit
187/// (10/s sustained, 30 burst) so resends to a fleet of unreachable peers can
188/// never burst the connection into a rate-limit disconnect. Only resends are
189/// bounded; first-attempt sends, ACKs, control frames and handshakes are never
190/// throttled.
191pub(crate) const RETRY_DRAIN_RATE_PER_SEC: f64 = 8.0;
192pub(crate) const RETRY_DRAIN_BURST: f64 = 24.0;
193/// Age limit for a welcome lifecycle to keep its peer on the presence
194/// watchlist (`welcome_pending_peers`). Without it the watch set only ever
195/// grows: every offline presence answer re-parks the record and pushes its
196/// `expires_at`, so a permanently-dead peer (abandoned install) is watched —
197/// and its parked lifecycle persisted — forever, and each such peer occupies
198/// rotation slots that delay presence rescue for live peers. Once unwatched,
199/// offline answers stop, `expires_at` stops being pushed, and the record
200/// ages out through normal expiry; recovery degrades to peer-initiated
201/// contact or mesh discovery, both of which rebuild the lifecycle.
202pub(crate) const WELCOME_WATCHLIST_MAX_AGE_SECS: i64 = 14 * 24 * 60 * 60;
203/// Backoff base for presence-driven welcome rescue. The first rescue for a
204/// peer is immediate; each subsequent rescue that still fails to prove the
205/// session doubles the wait (40s, 80s, 160s, ...) up to
206/// [`WELCOME_PRESENCE_RESCUE_MAX_SECS`]. Bounds the resend loop when a peer
207/// is provably online but can never confirm (stale key package after a
208/// reinstall, incompatible peer version) — without it the platform's 20s
209/// presence watch would re-send the multi-frame MLS welcome forever.
210pub(crate) const WELCOME_PRESENCE_RESCUE_BASE_SECS: i64 = 40;
211/// Cap for the presence-rescue backoff (10 minutes). Deliberately not a
212/// terminal state: a peer that stays online but never confirms keeps getting
213/// one rescue per cap interval, forever. That steady state is cheap (one
214/// multi-frame welcome per 10 min per such peer) and self-resolving — the
215/// lifecycle disappears the moment the session confirms — so a give-up
216/// threshold would only add a way to strand a recoverable session.
217pub(crate) const WELCOME_PRESENCE_RESCUE_MAX_SECS: i64 = 600;
218/// Well-known prefix for transport send-failure reasons meaning "the carrier
219/// is up but this recipient is unreachable on it" (e.g. the internet relay
220/// answered `DeliveryError` for an offline peer). Classified in
221/// `on_transport_send_failed` as authoritative proof the frame was dropped:
222/// instead of burning a retry attempt, a welcome refunds it and parks on an
223/// escalating reachability probe (`apply_recipient_unreachable_failure`), and
224/// a plain DM parks the same way (`park_unreachable_dm`). The escalation, not
225/// a carrier guard, is what keeps those probes from becoming a resend loop
226/// into the relay.
227///
228/// Cross-layer contract: the React Native platform bridges
229/// (`InternetManager.kt` / `InternetManager.swift`) hardcode this literal when
230/// calling `internet_send_failed_with_reason` — keep them in sync.
231pub(crate) const SEND_FAIL_REASON_RECIPIENT_UNREACHABLE: &str = "recipient_unreachable";
232
233/// The relay accepted a frame for a recipient with no live socket and handed
234/// it to a push notification (`MessageSent { pushed: true }`). Not a failure:
235/// the push may deliver it. What it does establish is that the recipient is
236/// not on the relay, and that the push is the only thing carrying this frame:
237/// a relay whose mailbox also holds a copy says so with `stored: true`, which
238/// the bridges report as [`SEND_FAIL_REASON_RELAY_PUSHED_STORED`] instead.
239///
240/// Deliberately its own token rather than a `recipient_unreachable` tail.
241/// That prefix fast-fails connection requests and moves Welcomes to `Failed`,
242/// both wrong for a frame that may have arrived. This token parks plain DMs
243/// only (`park_relay_pushed_dm`), and connection requests and Welcomes stay
244/// on their ordinary path.
245///
246/// Cross-layer contract: the React Native platform bridges
247/// (`InternetManager.kt` / `InternetManager.swift`) and the Python relay
248/// client (`internet_manager.py`) pass this exact literal to
249/// `internet_send_failed_with_reason`; pinned on the React Native side by
250/// `react_native_relay_parks_a_pushed_message_sent` and on the Python side by
251/// `TestMessageSentPushed`. That call must not also score the report as a send
252/// failure; see `OfflineProtocol::send_report_is_carrier_failure`.
253pub(crate) const SEND_FAIL_REASON_RELAY_PUSHED: &str = "relay_pushed";
254
255/// The relay's mailbox holds this frame for the recipient's next connection
256/// (`DeliveryError { stored: true }`, on a relay advertising `mailbox_v1`).
257///
258/// The socket write still missed, so this is the `recipient_unreachable`
259/// verdict in every respect but one: the frame is not lost, and the relay
260/// re-sends it the moment the recipient connects. A plain DM is therefore
261/// parked *edge-driven* — no escalating reachability probe — because a probe
262/// would only rewrite the copy the relay already holds. That is what the
263/// relay's own contract asks for ("do not retry faster on its account"), and
264/// what keeps a fleet whose peers are merely asleep from paying relay traffic
265/// for a redelivery the relay is already committed to. Recovery without the
266/// probe is the reachability edge, and the relay's drain either way.
267///
268/// Everything that is not a parkable plain DM is deliberately unchanged: the
269/// token is normalized back to [`SEND_FAIL_REASON_RECIPIENT_UNREACHABLE`] in
270/// `on_transport_send_failed_via`, so connection requests still fast-fail and
271/// Welcomes still park on their own lifecycle. Both carry their own proof of
272/// arrival, and a held copy is not a reason to stop waiting for it.
273///
274/// Cross-layer contract: the React Native platform bridges
275/// (`InternetManager.kt` / `InternetManager.swift`) and the Python relay
276/// client (`internet_manager.py`) pass this exact literal, and only for the
277/// one id the relay named — `stored` is a statement about a single message,
278/// never about the recipient's other in-flight frames. Pinned on the React
279/// Native side by `react_native_relay_parks_a_stored_delivery_error`.
280pub(crate) const SEND_FAIL_REASON_RELAY_STORED: &str = "relay_stored";
281
282/// [`SEND_FAIL_REASON_RELAY_PUSHED`] for a frame the mailbox also holds
283/// (`MessageSent { pushed: true, stored: true }`).
284///
285/// Parks exactly as `relay_pushed` does — plain DMs only, no
286/// `MessageUndeliverable`, kept out of the carrier's failure accounting —
287/// except that the park schedules no reachability probe, for the reason
288/// [`SEND_FAIL_REASON_RELAY_STORED`] gives.
289///
290/// Two tokens rather than one token and a flag because the two origins differ
291/// for everything that is *not* a plain DM: a pushed frame must not fast-fail
292/// a connection request, and a missed one must. Collapsing them would trade
293/// that distinction for one fewer string.
294pub(crate) const SEND_FAIL_REASON_RELAY_PUSHED_STORED: &str = "relay_pushed_stored";
295
296/// Fallback token for a send failure that classifies as nothing more specific.
297pub(crate) const SEND_FAIL_REASON_TRANSPORT: &str = "transport_send_failed";
298/// A Welcome was written to a carrier that never confirmed it.
299pub(crate) const SEND_FAIL_REASON_CONFIRM_TIMEOUT: &str = "send_confirmation_timed_out";
300
301/// Every token [`classify_transport_send_error`] and
302/// [`send_failure_token`] can produce.
303///
304/// Membership is what makes classification idempotent: a value already drawn
305/// from this list re-classifies to itself, so a record written by one producer
306/// and re-read by the other is not degraded to the fallback. Keep it in sync
307/// with the two functions — the round-trip test
308/// `every_send_failure_token_classifies_to_itself` fails otherwise.
309pub(crate) const SEND_FAIL_REASON_TOKENS: &[&str] = &[
310    SEND_FAIL_REASON_RECIPIENT_UNREACHABLE,
311    SEND_FAIL_REASON_RELAY_PUSHED,
312    SEND_FAIL_REASON_RELAY_STORED,
313    SEND_FAIL_REASON_RELAY_PUSHED_STORED,
314    SEND_FAIL_REASON_TRANSPORT,
315    SEND_FAIL_REASON_CONFIRM_TIMEOUT,
316    "transport_not_connected",
317    "peer_not_reachable",
318    "message_too_large",
319    "serialization_failed",
320    "crypto_failed",
321    "session_not_ready",
322    "recipient_blocked",
323    "media_transfer_limit",
324    "group_not_found",
325    "invalid_request",
326    "protocol_state_invalid",
327];
328
329/// Maps a platform-supplied or previously-stored send-failure string onto a
330/// fixed local vocabulary.
331///
332/// # Why the string cannot be passed through
333///
334/// The bridges build this string from the relay's `DeliveryError.reason`
335/// (`"recipient_unreachable: <relay text>"` — the shape is a cross-layer
336/// contract, see [`SEND_FAIL_REASON_RECIPIENT_UNREACHABLE`]), and the Nostr
337/// bridge from a relay's `OK` rejection text. Both tails are remote-chosen,
338/// unbounded, and not ours. They reach `MessageUndeliverable.reason`,
339/// `ConnectionRequestUndeliverable.reason` and — through
340/// `WelcomeLifecycleRecord::last_transport_error` —
341/// `WelcomeSendFailed.transport_error`, every one of which the telemetry
342/// scrubber ships verbatim beside a `recipient`/`peer_id` it *hashes*. An
343/// identifier in the tail therefore undoes the hashing in the same record, and
344/// even the honest relay writes one: its own wording renders the peer it
345/// concerns.
346///
347/// # Why the prefix survives
348///
349/// The `recipient_unreachable` token is not decoration — core prefix-matches it
350/// to fast-fail connection requests and to park plain DMs, and the bridges
351/// hardcode it. So the classification *is* the bare token: everything the
352/// protocol reads is kept, and only the prose tail is dropped.
353///
354/// Matching is prefix-based for that one token (the bridges append to it) and
355/// exact otherwise, with a closed fallback — a bridge or relay rewording
356/// degrades to [`SEND_FAIL_REASON_TRANSPORT`], never back to shipping its text.
357/// The `&'static str` return is load-bearing the same way
358/// [`GroupErrorPayload::classify_reason`] and `MlsError::privacy_safe_reason`
359/// are: it makes interpolating the input unrepresentable rather than merely
360/// discouraged.
361///
362/// Idempotent by construction, which matters twice: a record persisted before
363/// this existed is classified when it is *read* (the stored string may be raw
364/// relay prose), and a record written after it is classified again on the way
365/// out without changing.
366pub(crate) fn classify_transport_send_error(raw: &str) -> &'static str {
367    // Prefix, not equality: this is the one token the bridges extend.
368    if raw.starts_with(SEND_FAIL_REASON_RECIPIENT_UNREACHABLE) {
369        return SEND_FAIL_REASON_RECIPIENT_UNREACHABLE;
370    }
371    // Already classified: a re-read of a record either producer wrote. Returns
372    // the entry from the table rather than `raw`, which is what keeps the
373    // signature `&'static str`.
374    if let Some(token) = SEND_FAIL_REASON_TOKENS.iter().find(|t| **t == raw) {
375        return token;
376    }
377    match raw {
378        // The fixed literals the UniFFI layer substitutes when a bridge reports
379        // a failure without a reason of its own. Locally minted, but classified
380        // here too so the vocabulary has exactly one source.
381        "Internet transport send failed"
382        | "Reticulum transport send failed"
383        | "Nostr transport send failed" => SEND_FAIL_REASON_TRANSPORT,
384        "Welcome send confirmation timed out" => SEND_FAIL_REASON_CONFIRM_TIMEOUT,
385        // Everything else, including anything a relay or bridge chose.
386        _ => SEND_FAIL_REASON_TRANSPORT,
387    }
388}
389
390/// The pending-ACK table was full, so the frame was held back instead of
391/// transmitted. Not a transport fault: the retry queue sends it as soon as an
392/// acknowledgement frees a slot. A link carrying less than the app offers
393/// produces this steadily, and it is the signal to slow down.
394pub(crate) const SEND_DEFER_REASON_ACK_CAPACITY: &str = "ack_capacity";
395
396/// The peer already had [`PEER_SEND_WINDOW`] frames over a mesh link awaiting
397/// its acknowledgement, so the frame waits in the outbox and goes out, oldest
398/// first, as acknowledgements come back. Not a fault: it is what a link
399/// carrying less than the app offers looks like.
400pub(crate) const SEND_DEFER_REASON_PEER_WINDOW: &str = "peer_window";
401
402/// How many frames this device keeps in flight to one peer over a mesh link
403/// (Bluetooth LE, Wi-Fi Direct) before it holds the next one back.
404///
405/// Without a window the sender handed the carrier every new frame, every
406/// resend and an acknowledgement per received frame, into one unbounded queue,
407/// on a timer that starts at enqueue. In the 2026-10-19 volume test (run 4)
408/// the Android side's indication path carried 12 to 16 frames a second against
409/// 15 offered: the acknowledgement round trip passed the timeout, every resend
410/// cost the receiver another acknowledgement on the saturated path, that
411/// path's rate halved, and both phones retried 50,000 times and evicted 6,000
412/// messages as "Outbox capacity exceeded". A window bounds the queue, and with
413/// it the round trip, the resends and the receiver's ratchet gap, at any link
414/// rate. It costs no throughput while it exceeds what the link carries in one
415/// unloaded round trip: about six messages on that link, counting the
416/// receiver's acknowledgement coalescing (`ACK_COALESCE_WINDOW`) and a
417/// processing tick on each side. Sixteen leaves margin, and keeps the
418/// round trip under about three seconds there, well inside the timeout.
419///
420/// Only the mesh carriers: a relay mailbox is store-and-forward, and holding
421/// a message back from it would strand it on a device the user may close.
422pub(crate) const PEER_SEND_WINDOW: usize = 16;
423
424// Every in-window frame can be re-sealed on each of its attempts, and the
425// re-seal budget must never trip under the window: past it resends go out
426// verbatim, and a verbatim copy more than the out-of-order tolerance behind
427// the receiver never decrypts (run 4: 3,308 such failures).
428const _: () = assert!(
429    (PEER_SEND_WINDOW as u64)
430        * (1 + offline_protocol_reliability::constants::DEFAULT_MAX_RETRIES as u64)
431        < RESEAL_GAP_BUDGET
432);
433
434/// The smallest forward window any receiver of a 1:1 session has: a phone's
435/// OpenMLS group (configured) or a leaf's mls-rs one (fixed by mls-rs, and
436/// smaller). The re-seal budget is a fraction of this, not of the phone's
437/// window: derived from the phone's 8192, it let a sender burn 2,048
438/// generations past a leaf that can fast-forward over 1,024.
439pub(crate) const RECEIVER_FORWARD_WINDOW_FLOOR: u64 = {
440    let phone = offline_protocol_mls::group::SENDER_RATCHET_MAXIMUM_FORWARD_DISTANCE as u64;
441    let leaf = offline_protocol_mls::group::LEAF_SENDER_RATCHET_MAXIMUM_FORWARD_DISTANCE as u64;
442    if phone < leaf {
443        phone
444    } else {
445        leaf
446    }
447};
448
449/// How many frames a sender may seal for one peer past the last one that peer
450/// acknowledged before resends stop being re-sealed and go out verbatim.
451///
452/// A receiver cannot decrypt a frame more than its forward window past the
453/// newest it has decrypted. A quarter of the smallest window any receiver has
454/// ([`RECEIVER_FORWARD_WINDOW_FLOOR`]) leaves the rest to new messages, which
455/// still seal. The per-peer window keeps unacknowledged seals growing only by
456/// resends of at most [`PEER_SEND_WINDOW`] frames, so the budget trips only on
457/// a link that has carried no acknowledgement for a whole retry ladder; the
458/// compile-time assertion above keeps it above that ladder.
459pub(crate) const RESEAL_GAP_BUDGET: u64 = RECEIVER_FORWARD_WINDOW_FLOOR / 4;
460
461/// Past [`RESEAL_GAP_BUDGET`], a resend whose bytes the receiver can no
462/// longer decrypt is still re-sealed, until the gap reaches this.
463///
464/// A verbatim copy sealed more than the out-of-order tolerance before the
465/// newest frame this device sealed is refused by a receiver that has
466/// decrypted anything since, and refused without an acknowledgement on a
467/// mesh link, so it was resent until its ladder ran out: in run 4 of the
468/// 2026-10-19 volume test, 525 such messages produced 3,308 decrypt
469/// failures and were never delivered. Re-sealing one spends a generation,
470/// which is what the budget rations, so the exception stops at half the
471/// smallest forward window ([`RECEIVER_FORWARD_WINDOW_FLOOR`]): the receiver
472/// going deaf is the failure the budget exists for, and a wasted resend is
473/// not.
474pub(crate) const RESEAL_HARD_LIMIT: u64 = RECEIVER_FORWARD_WINDOW_FLOOR / 2;
475
476/// The longest an acknowledgement timeout is postponed for a frame that is
477/// still waiting in a local transport queue, measured from the attempt.
478///
479/// Bounded so a queue that never drains (a link that died without telling
480/// the transport) still reaches the retry ladder, and through it the other
481/// carriers and the mesh, within a minute.
482pub(crate) const QUEUED_ACK_GRACE_MAX: std::time::Duration = std::time::Duration::from_secs(60);
483
484/// Classifies a locally raised send failure for an event field.
485///
486/// The sibling of [`classify_transport_send_error`] for errors this device
487/// produced rather than received. It exists for the same reason: the transport
488/// layer renders the counterparty into its own message —
489/// `PeerNotReachable("no mesh transport holds a link to {peer_id}…")`, and the
490/// same in the BLE and Wi-Fi Direct backends — so `format!("{}", err)` on a
491/// routine send failure ships the peer's address to a telemetry sink. On
492/// `MessageDeferred` that was the *only* identity in the record, since the
493/// event carried no field for the scrubber to hash.
494///
495/// The match over [`crate::Error`] is exhaustive with no `_` arm: it lives in
496/// the defining crate, so a new variant fails to compile here and forces the
497/// privacy decision where the variant is written. The transport arm delegates
498/// to `offline_protocol_transport::Error::code`, which is that crate's own
499/// exhaustive, documented-stable classifier — its doc names telemetry
500/// classification as the intended use. Matching its output needs a fallback
501/// arm (a foreign `#[non_exhaustive]` enum can grow a variant), and that
502/// fallback is closed: a new transport variant degrades to
503/// [`SEND_FAIL_REASON_TRANSPORT`], never to its rendered text.
504pub(crate) fn send_failure_token(err: &crate::Error) -> &'static str {
505    use crate::Error as E;
506    match err {
507        E::Transport(inner) => match inner.code() {
508            "TRANSPORT_NOT_AVAILABLE" => "transport_not_connected",
509            "PEER_NOT_REACHABLE" => "peer_not_reachable",
510            "MESSAGE_TOO_LARGE" => "message_too_large",
511            "SERIALIZATION_ERROR" => "serialization_failed",
512            "CRYPTO_ERROR" => "crypto_failed",
513            _ => SEND_FAIL_REASON_TRANSPORT,
514        },
515        E::NotStarted | E::AlreadyStarted | E::InvalidState(_) => "protocol_state_invalid",
516        E::InvalidConfiguration(_)
517        | E::InvalidArgument(_)
518        | E::PermissionDenied(_)
519        | E::TelemetryConfigInvalid(_) => "invalid_request",
520        E::Core(_) | E::Serialization(_) => "serialization_failed",
521        E::Router(_) | E::Reliability(_) | E::Service(_) => SEND_FAIL_REASON_TRANSPORT,
522        E::Mls(_) | E::EncryptFailed(_) => "crypto_failed",
523        E::MlsNotInitialized | E::SessionNotReady(_) | E::NoKeyPackage(_) => "session_not_ready",
524        E::UserBlocked(_) => "recipient_blocked",
525        E::MediaTransferLimit(_) => "media_transfer_limit",
526        E::GroupNotFound(_) => "group_not_found",
527        // Data-layer failures cannot reach a send path today: nothing in the
528        // data layer sends. They are classified anyway because this match is
529        // where the privacy decision is forced, and "unreachable" is a claim
530        // that stops being true the moment replication lands. Each token is
531        // locally minted and carries no identifier: the errors themselves
532        // interpolate only byte counts and a decode detail, never a space,
533        // document or peer.
534        E::DataDisabled | E::DataStorageUnavailable => "data_unavailable",
535        E::DocTooLarge { .. } => "data_doc_too_large",
536        E::DataCorrupted(_) => "data_corrupt",
537        E::Other(_) => SEND_FAIL_REASON_TRANSPORT,
538    }
539}
540/// Minimum interval between session reconciliation scans (list_sessions I/O).
541/// Keeps the expensive Keychain/Keystore I/O out of the hot path so that
542/// sendMessage() is not blocked by Mutex contention on every process tick.
543pub(crate) const RECONCILIATION_THROTTLE_MS: u64 = 2_000;
544/// Lamport clock ticks between storage persistence writes. Avoids a
545/// Keychain/Keystore write on every sent and received message. On crash
546/// recovery, at most this many ticks are lost, which is safe — the clock
547/// is only used for causal ordering and the gap is absorbed on the next
548/// merge with any peer.
549pub(crate) const LAMPORT_PERSIST_INTERVAL: u64 = 64;
550
551/// Most seen ids one `DedupSeenRecord` carries. Matches the default
552/// `max_tracked_messages`; a larger configured tracker persists its newest
553/// ids only, which are the ones a replay is most likely to repeat.
554pub(crate) const MAX_PERSISTED_DEDUP_IDS: usize = 5000;
555
556/// Seen-set changes that force a write before the time cadence elapses. A
557/// burst of inbound traffic is exactly when the set is worth having on disk,
558/// and 32 changes at ~60 bytes each is well under the cost of one write.
559pub(crate) const DEDUP_PERSIST_DIRTY_THRESHOLD: u32 = 32;
560
561/// How long a dirty seen set may wait for the next `process()` tick before it
562/// is written. Bounds what a crash loses to a few seconds of receipts.
563pub(crate) const DEDUP_PERSIST_INTERVAL: std::time::Duration = std::time::Duration::from_secs(5);
564
565/// The deduplicator's seen set as persisted under
566/// [`storage_keys::DEDUP_SEEN_IDS`].
567///
568/// The deduplicator was in-memory only, so after a restart the socket copy of
569/// a message the app had already consumed from a push injection was not
570/// recognised as a duplicate: it went to the ratchet, whose generation for
571/// that message was already spent, and surfaced as a decryption failure — a
572/// spurious signal the app counts toward its split-brain breaker, which then
573/// tears down a healthy session. Persisting the ids makes the second copy
574/// recognisable across the restart. Ids and timestamps only; nothing here is
575/// content.
576///
577/// `version` is the forward-compatibility hinge: an unknown version is dropped
578/// rather than guessed at, and the set simply starts empty.
579#[derive(Serialize, Deserialize)]
580pub(crate) struct DedupSeenRecord {
581    #[serde(default = "dedup_seen_record_version")]
582    pub(crate) version: u8,
583    pub(crate) entries: Vec<offline_protocol_reliability::SeenId>,
584}
585
586/// The only record version this build writes or reads.
587pub(crate) const DEDUP_SEEN_RECORD_VERSION: u8 = 1;
588
589fn dedup_seen_record_version() -> u8 {
590    DEDUP_SEEN_RECORD_VERSION
591}
592/// Seconds the Nostr receive watermark must advance before it is written back
593/// to protocol-state storage. Same debounce role as
594/// [`LAMPORT_PERSIST_INTERVAL`]: every inbound relay event moves the mark, and
595/// a storage write per message is exactly the I/O the Lamport debounce exists
596/// to avoid.
597///
598/// What an un-flushed gap costs is bounded and one-directional: a launch that
599/// loses up to this much advance re-fetches a slightly wider slice of relay
600/// history, which dedup absorbs. It can never *skip* messages, because the
601/// stale mark is always behind the live one.
602pub(crate) const NOSTR_WATERMARK_PERSIST_INTERVAL_SECS: i64 = 300;
603pub(crate) const MEDIA_TRANSFER_STALE_TIMEOUT_SECS: u64 = 300;
604/// Maximum number of tracked known peers for service discovery.
605pub(crate) const MAX_KNOWN_PEERS: usize = 1000;
606/// How long a known peer stays tracked without being re-seen.
607///
608/// Peers on carriers with no disconnect signal (Internet, Reticulum, Nostr,
609/// and WiFi Direct message-path senders) are only ever *added* to
610/// `known_peers`; this TTL is their eviction path, swept from the periodic
611/// `cleanup_expired_entries` tick. A second layer — least-recently-seen
612/// eviction when an insert hits `MAX_KNOWN_PEERS` — guarantees a newly
613/// discovered peer is always tracked even between sweeps.
614///
615/// Deliberately generous: a connected-but-quiet BLE peer refreshes only via
616/// platform advertisement sightings (BLE inbound messages do not route
617/// through the discovery hook), so a short TTL would evict it while still
618/// connected. Eviction is self-healing (the peer is re-tracked on its next
619/// advertisement or message), so erring long only delays hygiene.
620pub(crate) const KNOWN_PEER_TTL_SECS: u64 = 1800;
621
622/// Battery level below which a device stops carrying traffic for other
623/// people even while charging.
624///
625/// Re-exported from the router crate rather than restated here: message
626/// forwarding and the relay role apply the same floor, and a device must not
627/// keep carrying traffic at a level that would have stripped it of the role.
628/// Two copies of the number would eventually disagree, and nothing would
629/// notice.
630pub(crate) use offline_protocol_router::CRITICAL_RELAY_BATTERY_LEVEL;
631
632/// The metadata keys a signed control frame carries: the Ed25519 signature
633/// over the canonical payload, and the public key it verifies against, both
634/// base64.
635///
636/// Re-exported rather than restated because the payload they accompany is
637/// built by `offline_protocol_sealed::control_signing_payload`, which a leaf
638/// node calls too. `CTRL_SIGN_DOMAIN` lives there as well and is no longer
639/// named in this crate outside its tests: nothing here builds the payload any
640/// more. A key or a domain declared in two places is one that can differ in
641/// one of them, and the only symptom is a signature that stops verifying.
642pub(crate) use offline_protocol_sealed::{CTRL_PK_META_KEY, CTRL_SIG_META_KEY};
643
644/// Maximum number of peers retained in the encryption-capability set that gates
645/// inbound plaintext.
646///
647/// Sized to hold every legitimate source at once — the durable capability
648/// records plus the MLS session list — with room to spare, so a real deployment
649/// never reaches it. The cap exists because the set is keyed by a wire-claimed
650/// sender id and nothing else bounds it.
651///
652/// Note what does *not* bound it: requiring a signature. The control gate does
653/// now reject unsigned control frames before dispatch, so every marking path
654/// runs on a verified frame — and that changes nothing here. A signature proves
655/// the signer owns the address it claims; it does not prove the address belongs
656/// to anyone real, and minting one costs a keygen. An attacker spending keygens
657/// produces unlimited distinct well-signed peers, so "written only after a
658/// signature verifies" is not by itself a bound on anything.
659///
660/// It bounds the durable `encryption_capable_peers` storage category as well,
661/// because `OfflineProtocol::record_encryption_capable` persists only for a
662/// peer this cap admitted.
663///
664/// Unlike the other maps keyed by a wire-claimed id, this one **refuses** at
665/// capacity instead of resetting or evicting: forgetting a peer here is the
666/// fail-open direction. See `OfflineProtocol::mark_encryption_capable`.
667pub(crate) const MAX_ENCRYPTION_CAPABLE_PEERS: usize = 8192;
668
669/// Maximum number of blocked users to retain.
670pub(crate) const MAX_BLOCKED_USERS: usize = 10_000;
671
672/// Maximum number of peers tracked for once-per-peer
673/// `PlaintextReceiveRejected` warning suppression.
674///
675/// The keys are wire-claimed (attacker-controllable) sender ids, so the set
676/// resets at capacity instead of growing without bound: a flood of forged
677/// senders degrades the throttle to once-per-peer-per-generation while
678/// memory stays capped.
679pub(crate) const MAX_PLAINTEXT_RECEIVE_WARNED_PEERS: usize = 1000;
680
681/// Maximum number of peers tracked for once-per-peer-per-code control-gate
682/// warning suppression.
683///
684/// Every rejection the control gate reports is reachable from an unauthenticated
685/// frame carrying an attacker-chosen sender id — that is what a gate rejection
686/// *is* — so without a throttle an off-path injector turns the app's event
687/// stream into a flood and desensitizes operators to the one code that has no
688/// benign reading (`SENDER_ADDRESS_MISMATCH`). Bounded and reset at capacity for
689/// the same reason as [`MAX_PLAINTEXT_RECEIVE_WARNED_PEERS`]: the keys are
690/// attacker-controlled, so a forged-sender flood degrades the throttle to
691/// once-per-peer-per-generation rather than growing memory without bound.
692pub(crate) const MAX_CONTROL_GATE_WARNED_PEERS: usize = 1000;
693
694/// Maximum number of pending (received-but-unused) peer key packages retained
695/// in memory and in durable `MlsStorage`.
696///
697/// Keyed by the wire-claimed `sender`, so — like [`MAX_KNOWN_PEERS`] — an
698/// unpinned peer can flood distinct forged ids under the default config. Each
699/// entry is also written to durable secure storage (`persist_peer_key_package`,
700/// iOS Keychain / Android Keystore) and re-loaded on boot, so without this cap
701/// a flood grows durable storage without bound and re-inflates memory on every
702/// restart. At capacity a new peer evicts the soonest-to-expire entry and drops
703/// its persisted copy; the restore-on-boot loop is capped the same way.
704pub(crate) const MAX_PENDING_KEY_PACKAGES: usize = 1000;
705
706/// Maximum outbound messages waiting for one peer's MLS session.
707///
708/// This queue is durable and accepts application-controlled content, so a peer
709/// that never completes session establishment must not grow it without bound.
710/// The limit matches the default inbound pending-decryption per-peer bound.
711///
712/// A count alone does not bound memory or durable storage — message content is
713/// application-supplied — so this cap works together with
714/// [`MAX_PENDING_MESSAGE_BYTES_PER_PEER`]; whichever binds first wins.
715pub(crate) const MAX_PENDING_MESSAGES_PER_PEER: usize = 64;
716
717/// Maximum outbound messages waiting for MLS sessions across all peers.
718///
719/// At capacity the globally oldest message is settled as failed before the new
720/// message is admitted. The limit matches the default inbound pending queue.
721/// Paired with [`MAX_PENDING_MESSAGE_BYTES_GLOBAL`], as above.
722pub(crate) const MAX_PENDING_MESSAGES_GLOBAL: usize = 4096;
723
724/// Maximum pending entries expired in one `process()` tick.
725///
726/// Each expiry is a settlement *and* a durable delete, and the two have to stay
727/// paired — so what gets bounded is how many entries expire per pass, not how
728/// many deletes it may issue. Messages queued in a burst share a `queued_at` and
729/// so come due in a burst; without this, one tick of the 100 ms bindings loop
730/// could issue up to [`MAX_PENDING_MESSAGES_GLOBAL`] synchronous deletes, each a
731/// device barrier on every built-in provider.
732///
733/// The remainder is not deferred indefinitely: the entries left behind are still
734/// past their deadline, so `recompute_next_pending_message_expiry` leaves
735/// `next_pending_message_expiry` in the past and the very next tick drains
736/// another pass.
737pub(crate) const MAX_PENDING_EXPIRIES_PER_PASS: usize = 64;
738
739/// Maximum per-message records one launch writes migrating legacy queues.
740///
741/// The migration's writes are the one part of the pending restore that is not
742/// already bounded by a delete budget, and a `store` is the more expensive of
743/// the two: every built-in provider flushes the record *and* its directory. A
744/// pre-split install sitting near [`MAX_PENDING_MESSAGES_GLOBAL`] would
745/// otherwise pay thousands of device barriers inside `initialize_mls`, on the
746/// launch path, where a mobile watchdog is watching.
747///
748/// Sized to match [`crate::protocol::storage::MAX_RESTORE_PRUNE_DELETES`], so
749/// the whole walk's barrier count stays the same order of magnitude whichever
750/// half of it does the work. Checked per recipient and before its first write,
751/// so a queue is either migrated whole or left entirely on disk for the next
752/// launch — never split across the two layouts with nothing to reconcile it.
753pub(crate) const MAX_MIGRATED_PENDING_WRITES_PER_LAUNCH: usize = 512;
754
755/// Maximum terminal settlements parked by restore for `start()` to drain.
756///
757/// The restore caps already bound how many can be produced, but they bound it
758/// as a sum across every category, and nothing drains this queue until
759/// `start()` — which an application that only calls `initialize_mls`, or that
760/// retries it against a store that keeps failing, may never reach. Sized above
761/// the largest single-category restore ([`MAX_PENDING_MESSAGES_GLOBAL`], the
762/// pending queue's own global cap) so no legitimate restore is ever truncated;
763/// past that point the count is reported instead of the events.
764pub(crate) const MAX_DEFERRED_RESTORE_SETTLEMENTS: usize = 2 * MAX_PENDING_MESSAGES_GLOBAL;
765
766/// Maximum size of application-supplied message content accepted at the public
767/// send boundary, in bytes.
768///
769/// Enforced at the boundary — not at transmit time — because a message queued
770/// behind MLS session establishment never reaches the transport's
771/// `DEFAULT_MAX_MESSAGE_SIZE` (1 MiB) check: it sits in the durable pending
772/// queue first. Without a boundary cap a handful of very large sends could
773/// exhaust mobile memory and protocol-state disk while still being formally
774/// "within" the count caps above.
775///
776/// 256 KiB leaves ample headroom under the 1 MiB transport ceiling for MLS
777/// ciphertext expansion, base64, and the JSON wire envelope, so anything this
778/// path accepts can actually be delivered. Larger payloads belong on the media
779/// path (`send_media`), which chunks.
780pub(crate) const MAX_MESSAGE_CONTENT_BYTES: usize = 256 * 1024;
781
782/// Maximum total serialized bytes of one peer's pending-session queue.
783///
784/// At capacity the peer's oldest entries are settled as failed until the
785/// incoming message fits, exactly like the count cap. Deliberately larger than
786/// [`MAX_MESSAGE_CONTENT_BYTES`] plus [`MAX_RICH_EXTRAS_BYTES`] so a single
787/// boundary-legal message always fits in an empty queue and admission can never
788/// livelock (pinned by `pending_queue_byte_budgets_admit_any_boundary_legal_message`).
789///
790/// # Durable cost
791///
792/// Pending messages are persisted one record per message
793/// ([`storage_keys::PENDING_MESSAGE_ENTRIES`]), so an enqueue writes its own
794/// entry and nothing else: filling one peer to this budget costs `budget` bytes
795/// written, not `budget × entries / 2`. The per-recipient layout this replaced
796/// re-serialized the peer's whole queue on every enqueue, which made the byte
797/// cost quadratic in the entry count.
798///
799/// Bytes were never the expensive half, though, and sizing this budget off them
800/// would be reading the wrong meter. Every built-in provider pays two device
801/// barriers per `store` (the record's own flush plus its directory's) and one
802/// per `delete`, *regardless of record size* — so a 500-byte write and a 2 MiB
803/// write cost the same in the resource that actually dominates. What the
804/// per-message layout buys is not primarily speed but that a record which will
805/// not open still names the message it lost; see
806/// [`storage_keys::PENDING_MESSAGE_ENTRIES`].
807///
808/// So this budget is still sized to bound a pathological queue rather than to
809/// describe a normal one — real queues hold a handful of short messages waiting
810/// on a handshake. Lowering it below `MAX_MESSAGE_CONTENT_BYTES +
811/// MAX_RICH_EXTRAS_BYTES` breaks admission outright.
812pub(crate) const MAX_PENDING_MESSAGE_BYTES_PER_PEER: usize = 2 * 1024 * 1024;
813
814/// Maximum total serialized bytes of the pending-session queue across all
815/// peers. Bounds the whole feature's footprint on a mobile device regardless of
816/// how many peers are mid-establishment.
817pub(crate) const MAX_PENDING_MESSAGE_BYTES_GLOBAL: usize = 16 * 1024 * 1024;
818
819/// Maximum size of a single persisted protocol-state record, in bytes.
820///
821/// Enforced on both sides of [`crate::ProtocolStateStorage`]: the SDK refuses to
822/// write a larger record, and refuses to *deserialize* a larger one on restore
823/// (dropping it instead), so a corrupted or tampered state file cannot turn
824/// into an unbounded allocation during initialization.
825///
826/// Sized above [`MAX_PENDING_MESSAGE_BYTES_PER_PEER`] with room for JSON and
827/// seal overhead. That was once tight rather than generous: under the
828/// per-recipient pending layout the largest legitimate record *was* one peer's
829/// full queue, so the two constants were one bound apart. Now that pending
830/// messages are keyed per id the largest legitimate record is a single message
831/// ([`MAX_MESSAGE_CONTENT_BYTES`] plus [`MAX_RICH_EXTRAS_BYTES`]) or one outbox
832/// entry, and the headroom is real. Keep the ordering anyway — a legacy
833/// per-recipient record still has to be readable for long enough to migrate it.
834pub(crate) const MAX_PROTOCOL_STATE_RECORD_BYTES: usize = 4 * 1024 * 1024;
835
836/// Maximum number of peers remembered in `key_package_sent_to` (the peers we
837/// have pushed our key package to, with when we last did).
838///
839/// Wire-claimed ids grow this set in lockstep with a key-package flood, so it
840/// resets at capacity like [`MAX_PLAINTEXT_RECEIVE_WARNED_PEERS`]: the only cost
841/// of forgetting a peer is a one-time idempotent re-send of our key package.
842pub(crate) const MAX_KEY_PACKAGE_SENT_TO: usize = 1000;
843
844/// Maximum number of peers tracked in `rekey_due_at` (the per-peer epoch-desync
845/// re-key floor).
846///
847/// The desync classification that reaches `schedule_session_rekey` is produced
848/// by OpenMLS *before* it authenticates anything, so the peer id keying this map
849/// is wire-claimed. The envelope/sender binding in `SessionManager::decrypt_message`
850/// already confines that id to peers we hold a session with, which bounds the map
851/// on its own; this cap is the same defence-in-depth every other wire-keyed map
852/// carries. Resets at capacity like [`MAX_KEY_PACKAGE_SENT_TO`] — forgetting a
853/// peer only costs one extra re-key being allowed through early.
854pub(crate) const MAX_REKEY_TRACKED_PEERS: usize = 1000;
855
856/// Maximum lifetime (in milliseconds) honored for a *received* peer key
857/// package's cached expiry.
858///
859/// `remaining_lifetime_ms` arrives on the wire unauthenticated and becomes the
860/// eviction sort key for [`MAX_PENDING_KEY_PACKAGES`] (the soonest-to-expire
861/// entry is evicted first). Without a ceiling, a flood of forged senders
862/// claiming a maximal lifetime would pin their entries as latest-to-expire and
863/// preferentially evict legitimate peers. Key packages are minted with a 30-day
864/// lifetime (`DEFAULT_KEY_PACKAGE_LIFETIME_SECS` in `offline-protocol-mls`), so
865/// a larger value is never legitimate. This bound is purely cache bookkeeping —
866/// OpenMLS enforces real key-package validity at use time — so clamping only
867/// affects when we drop the *cached* copy, never crypto correctness.
868pub(crate) const MAX_KEY_PACKAGE_LIFETIME_MS: u64 = 30 * 24 * 60 * 60 * 1000;
869
870/// Durable record that a peer has proved it runs MLS.
871///
872/// Written whenever a control message from that peer verifies — signature
873/// valid, and the signing key derives to the address the frame claims — and
874/// read back on `initialize_mls` to reseed
875/// [`OfflineProtocol::encryption_capable_peers`](crate::OfflineProtocol).
876///
877/// The timestamp is diagnostic, not a policy input. Its predecessor
878/// (`TofuEntry.last_seen_ms`) drove LRU eviction of a bounded pin store; there
879/// is no eviction here, because there is no longer any per-peer *secret* whose
880/// size needs bounding — only the fact, which the restore walk bounds on its
881/// own terms. Keeping the field costs nothing and makes a stale store readable
882/// by a human.
883#[derive(Clone, Debug, Serialize, Deserialize)]
884pub(crate) struct EncryptionCapableEntry {
885    /// Milliseconds since epoch (UTC) when this peer last proved it runs MLS.
886    pub(crate) last_seen_ms: i64,
887    /// Whether this peer has ever presented a control-frame signature over the
888    /// freshness-bound payload (`offline-ctrl-v2`).
889    ///
890    /// A **ratchet**, and the only reason the freshness check cannot be
891    /// side-stepped: without it an attacker replays a capture from before the
892    /// peer upgraded, the older payload verifies exactly as it always did, and
893    /// the whole check is bypassed by choosing an old enough recording. Once
894    /// this is set, that peer's v1 control frames are refused.
895    ///
896    /// It rides here rather than in [`PeerCapabilities`] because the two record
897    /// different things. That one holds what a peer *advertised*, is
898    /// overwritten wholesale by each fresh key package, and answers "what
899    /// should we send them"; this one holds what a peer *proved*, must never be
900    /// cleared by anything a network attacker can cause, and answers "what will
901    /// we accept from them". Storing it in a record that is routinely
902    /// overwritten is how a ratchet silently stops being one.
903    ///
904    /// `#[serde(default)]` gives `false` for records written before the field
905    /// existed, which is correct: an install that has never verified a v2
906    /// signature from a peer has not proved anything about them.
907    #[serde(default)]
908    pub(crate) ctrl_freshness_proved: bool,
909    /// The signed timestamp of the most recent session reset acted on from
910    /// this peer, or `0` if none.
911    ///
912    /// A high-water mark, and what turns the freshness *window* into an actual
913    /// closure for the one directive that destroys state. The window alone
914    /// bounds a captured reset to thirty days; it does not stop the frame
915    /// being spent inside them, and the receive deduplicator forgets a message
916    /// id after an hour. Without this, a recording tears the pair's session
917    /// down once an hour for a month.
918    ///
919    /// Only ever read from and written by a frame whose timestamp is *inside
920    /// the signature*. On a frame signed under the older payload the timestamp
921    /// is attacker-rewritable, so honouring one here would let anyone park
922    /// this mark at `i64::MAX` and permanently deny that peer the ability to
923    /// heal a forked session, which is a worse failure than the one being
924    /// fixed.
925    #[serde(default)]
926    pub(crate) last_reset_ms: i64,
927    /// Whether this peer has ever sent us a service frame sealed inside the
928    /// 1:1 session, which proves it routes the sealed form.
929    ///
930    /// A **ratchet**, here rather than in [`PeerCapabilities`] for the reason
931    /// `ctrl_freshness_proved` is: that record is what a peer advertised and
932    /// every key package overwrites it. Kept there, one replayed key package
933    /// from before the peer upgraded would erase the proof and send that
934    /// peer's service bodies in signed plaintext again, and a key package
935    /// signed under `offline-ctrl-v1` is admitted at any age (the key-package
936    /// escape), so no freshness window bounds that replay.
937    ///
938    /// `#[serde(default)]` gives `false` for records written before the field
939    /// existed, which is correct: nothing was proved.
940    #[serde(default)]
941    pub(crate) svc_sealed_proved: bool,
942}
943
944/// Payload for key package exchange, and the compact envelope version it
945/// advertises.
946///
947/// Both live in `offline-protocol-sealed`: a leaf node builds and reads this
948/// payload with a different MLS implementation, and two ends that disagree
949/// about its shape cannot negotiate anything. Re-exported here so every
950/// existing use site is unchanged.
951pub(crate) use offline_protocol_sealed::{KeyPackagePayload, MLS_ENVELOPE_COMPACT_V1};
952
953/// Sealed rich-payload version advertised in
954/// [`KeyPackagePayload::rich_versions`]: the decrypted MLS plaintext may be
955/// `__RICH_V1__` + JSON of [`RichPayloadV1`], carrying reply context, rich
956/// media metadata, and forward attribution inside the AEAD boundary instead
957/// of on the relay-visible outer message.
958pub(crate) const RICH_PAYLOAD_V1: u8 = 1;
959
960/// Upper bound on the serialized size of the rich extras accepted by the
961/// rich send surface. Enforced at the API boundary (`send_message_with`),
962/// deliberately NOT at seal time: a message queued behind session
963/// establishment re-makes the seal decision at flush, and a seal-time
964/// failure there would re-queue the message forever. Bounding at the
965/// boundary means every queued extras blob is already known to seal.
966pub(crate) const MAX_RICH_EXTRAS_BYTES: usize = 32 * 1024;
967
968/// Replicated-document sync version advertised in
969/// [`KeyPackagePayload::data_versions`]: the decrypted MLS plaintext may be
970/// `__DATA_V1__` + JSON of a sync frame (version-vector exchange, delta
971/// push, or snapshot offer).
972///
973/// One number covers both the frame schema and the document encoding the
974/// frames carry. Splitting them would let a peer advertise a frame schema it
975/// speaks around an encoding it cannot read, and the failure would surface
976/// as an unreadable document rather than as a refused negotiation.
977pub(crate) const DATA_SYNC_V1: u8 = 1;
978
979/// Group-space replication, advertised in
980/// [`KeyPackagePayload::data_versions`] alongside [`DATA_SYNC_V1`]: the
981/// sender intercepts `__DATA_V1__` frames arriving inside a *group*
982/// ciphertext, not only inside a 1:1 one.
983///
984/// A separate entry rather than a bump, and the reason is a compatibility
985/// trap rather than tidiness. A build that speaks only [`DATA_SYNC_V1`]
986/// advertises it, holds group sessions, and has no group interception at
987/// all: every group path emits whatever decrypts as a chat message, so a
988/// group sync frame sent to one would surface to its user as literal
989/// `__DATA_V1__{...}` text. Gating group sends on this entry is what keeps
990/// that frame from ever being sent, and appending rather than replacing is
991/// what keeps 1:1 replication working with those same peers.
992pub(crate) const DATA_GROUP_V1: u8 = 2;
993
994/// Attachment and snapshot carriage over the media path, advertised in
995/// [`KeyPackagePayload::data_versions`] alongside [`DATA_SYNC_V1`]: the
996/// sender understands the `need_blob` and `blob_gone` frame kinds, and
997/// routes a media transfer marked as data-purposed into the data layer
998/// instead of surfacing it to its user as a received file.
999///
1000/// A third entry rather than a bump, for the reason the second one exists.
1001/// A build speaking only [`DATA_SYNC_V1`] replicates documents correctly and
1002/// has no arm for either new frame kind; it consumes them (the parser reads
1003/// the version first and the body second, so an unknown kind is dropped
1004/// rather than surfaced) but answers nothing, so a fetch aimed at it waits
1005/// forever. Worse, such a build receiving a data-purposed media transfer
1006/// emits `FileReceived` and hands a person a CRDT snapshot as a downloaded
1007/// file. Gating on this entry is what stops both.
1008///
1009/// v1 carries blobs on 1:1 sessions only, so this entry has no attested
1010/// sibling: group members never exchange key packages with each other, and
1011/// there is nothing about group carriage for an inviter to attest.
1012pub(crate) const DATA_MEDIA_V1: u8 = 3;
1013
1014/// Document removals, advertised in [`KeyPackagePayload::data_versions`]
1015/// alongside [`DATA_SYNC_V1`]: the sender reads the `gone` field of a
1016/// version offer, and removes what a floor covers instead of offering it
1017/// back.
1018///
1019/// A fourth entry rather than a bump, for the reason the second and third
1020/// exist, and here the compatibility story is unusually gentle. A build
1021/// without this entry ignores an unknown field on a frame kind it knows, so
1022/// it keeps its copy and re-offers it forever; this device refuses each
1023/// offer and each blob against its own floor, so the removal still holds
1024/// everywhere it is known. Nothing is surfaced wrongly and nothing loops:
1025/// the cost is one offer per exchange that is answered with nothing.
1026///
1027/// Gating the *field* on the entry is therefore a traffic decision rather
1028/// than a safety one, which is why a group carries it ungated: one
1029/// ciphertext reaches the whole roster, so there is no per-member choice to
1030/// make, and the roster-wide gate on [`DATA_GROUP_V1`] already decides
1031/// whether the frame may be sent at all.
1032pub(crate) const DATA_TOMBSTONE_V1: u8 = 4;
1033
1034/// Interest-scoped replication, advertised in
1035/// [`KeyPackagePayload::data_versions`] alongside [`DATA_SYNC_V1`]: the
1036/// sender reads the `want` field of a version offer and answers only the
1037/// documents it names.
1038///
1039/// A fifth entry rather than a bump, and like the fourth it gates traffic
1040/// rather than correctness. A peer without it ignores the field and answers
1041/// with everything it holds, and the asking side refuses what it did not ask
1042/// for on arrival, so the narrowing holds regardless; what it does not do is
1043/// save the radio. Gating means a narrowed space says so only where saying so
1044/// changes what comes back.
1045///
1046/// The half that does not depend on this entry is the local refusal, and it
1047/// is the reason interest is safe to ship before any peer speaks it.
1048pub(crate) const DATA_INTEREST_V1: u8 = 5;
1049
1050/// Attachment bytes inside a group, advertised in
1051/// [`KeyPackagePayload::data_versions`] alongside [`DATA_SYNC_V1`]: the
1052/// sender answers a `need_blob` that arrives inside a group ciphertext, and
1053/// carries the bytes back as `chunk` frames under the group key.
1054///
1055/// A sixth entry rather than a bump, and the first `data_versions` entry
1056/// since the second with an attested sibling. [`DATA_MEDIA_V1`] has none
1057/// because carriage was 1:1 and there was nothing about it for a group
1058/// inviter to attest; this one is about a group, so there is.
1059///
1060/// What it gates is a better answer to a question, not safety. A member
1061/// without it receives a `need_blob` it understands the shape of and
1062/// refuses, and receives `chunk` frames whose kind it does not know and
1063/// drops: the version is read before the body, so an unknown kind is
1064/// consumed rather than surfaced. Nothing is shown to anybody wrongly. What
1065/// the entry buys is refusing a fetch at the call instead of leaving an
1066/// application waiting out the silence timeout for an answer that was never
1067/// coming.
1068pub(crate) const DATA_GROUP_BLOB_V1: u8 = 6;
1069
1070/// The custody receipt, advertised in [`KeyPackagePayload::data_versions`]
1071/// alongside [`DATA_SYNC_V1`]: the peer parses the `__CUSTODY_RECEIPT__`
1072/// control frame, so a custodian that accepted one of its replication frames
1073/// may answer with a receipt (`docs/spec/custody.md`).
1074///
1075/// It gates one frame in one direction and nothing else. A deposit request is
1076/// a metadata key an unaware receiver ignores, so a depositor writes it toward
1077/// any neighbour, and acceptance is decided by the custodian's quotas. The
1078/// gate exists because a peer without the entry does not know the prefix as a
1079/// control frame: with encryption on it refuses the receipt as inbound
1080/// plaintext and records a security refusal, and on a plaintext-only
1081/// deployment it shows the receipt to its user as a message.
1082///
1083/// In the replication family rather than a list of its own because custody
1084/// carries replication frames only. No attested sibling: the receipt is a 1:1
1085/// control frame between neighbours, and a group inviter has nothing to say
1086/// about one.
1087pub(crate) const DATA_CUSTODY_V1: u8 = 7;
1088
1089/// Rich fields accepted by the `send_message_with` surface. Only ever
1090/// delivered inside the sealed [`RichPayloadV1`] body — toward a recipient
1091/// that did not advertise [`RICH_PAYLOAD_V1`] they are silently dropped,
1092/// never sent cleartext.
1093#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1094pub(crate) struct RichSendExtras {
1095    #[serde(default, skip_serializing_if = "Option::is_none")]
1096    pub(crate) reply_context: Option<ReplyContext>,
1097    #[serde(default, skip_serializing_if = "Option::is_none")]
1098    pub(crate) media_metadata: Option<MediaMetadata>,
1099    #[serde(default, skip_serializing_if = "Option::is_none")]
1100    pub(crate) forward_info: Option<ForwardInfo>,
1101}
1102
1103impl RichSendExtras {
1104    /// Whether any rich field is present (empty extras never seal).
1105    pub(crate) fn is_any(&self) -> bool {
1106        self.reply_context.is_some() || self.media_metadata.is_some() || self.forward_info.is_some()
1107    }
1108
1109    /// Enforces [`MAX_RICH_EXTRAS_BYTES`] on the serialized extras. Shared
1110    /// by every rich send boundary (`send_message_with`, the forward paths,
1111    /// and the group surface) — enforced there, never at seal time, so a
1112    /// queued or re-sent message is always known to seal (see the
1113    /// constant's doc). Empty extras always pass.
1114    pub(crate) fn check_size(&self) -> crate::Result<()> {
1115        if !self.is_any() {
1116            return Ok(());
1117        }
1118        let extras_len = serde_json::to_vec(self)
1119            .map_err(|e| Error::Serialization(e.to_string()))?
1120            .len();
1121        if extras_len > MAX_RICH_EXTRAS_BYTES {
1122            return Err(Error::InvalidArgument(format!(
1123                "Rich extras too large: {} bytes serialized (max {})",
1124                extras_len, MAX_RICH_EXTRAS_BYTES
1125            )));
1126        }
1127        Ok(())
1128    }
1129}
1130
1131/// Options for `OfflineProtocol::send_message_with`: priority and reply
1132/// threading (as on `send_message`), plus the rich fields introduced with
1133/// the sealed rich payload.
1134///
1135/// The rich fields (`reply_context`, `media_metadata`, `forward_info`) only
1136/// ever travel inside the MLS-sealed `__RICH_V1__` body, and only toward
1137/// recipients whose key package advertised `rich_versions` support. Toward
1138/// anyone else they are silently dropped — never sent cleartext — so the
1139/// message degrades to plain text with `reply_to_msg` threading intact.
1140#[derive(Debug, Clone, Default)]
1141pub struct SendMessageOptions {
1142    /// Message priority (defaults to Medium).
1143    pub priority: Option<MessagePriority>,
1144    /// ID of the message this is replying to.
1145    pub reply_to_msg: Option<String>,
1146    /// Content type stamped on the outer message (defaults to Text). A
1147    /// coarse rendering hint — the actual content stays MLS-sealed. Toward
1148    /// a recipient that advertised the sealed rich payload, a copy travels
1149    /// inside the sealed body — whenever extras seal, or the hint itself is
1150    /// non-Text — and the receiver treats that copy as authoritative, so a
1151    /// relay cannot rewrite the hint. Must not be
1152    /// [`ContentType::FileChunk`] (an internal transport content type; the
1153    /// receiver would route the message into its file-transfer manager and
1154    /// drop it) — rejected as `InvalidArgument`.
1155    pub content_type: Option<ContentType>,
1156    /// Quoted-reply context, delivered sealed-only.
1157    pub reply_context: Option<ReplyContext>,
1158    /// Rich media metadata (cloud attachments, stickers — including any
1159    /// `encryption_key`/`iv` secrets), delivered sealed-only.
1160    pub media_metadata: Option<MediaMetadata>,
1161    /// Forward attribution, delivered sealed-only.
1162    pub forward_info: Option<ForwardInfo>,
1163    /// Send via this specific transport (bypassing DORS selection), like
1164    /// `send_message_via_transport`.
1165    pub via_transport: Option<TransportType>,
1166    /// Application id stamped on this message, in place of the configured
1167    /// [`crate::ProtocolConfig::app_id`].
1168    ///
1169    /// For an instance that serves several local applications behind one
1170    /// identity: the receiver's `MessageReceived.app_id` reports it, so the
1171    /// receiving instance can route the message to the right client. It
1172    /// changes the stamp on this one frame only, never the storage
1173    /// namespace, the MLS session, the BLE app tag, or the id on the
1174    /// acknowledgements and control frames the engine sends for it.
1175    ///
1176    /// It travels in the clear, outside the sealed body and outside every
1177    /// signature, so any carrier can read and rewrite it (threat model
1178    /// R17). Treat it as routing metadata, never as an authorization input.
1179    /// Held to the same rules as the configured id; an invalid value fails
1180    /// the call with `InvalidArgument` before anything is queued.
1181    pub app_id: Option<String>,
1182}
1183
1184/// Options for `OfflineProtocol::send_media_with`: the chunk-0 media
1185/// metadata (as on `send_media`), plus the rich fields introduced with the
1186/// sealed rich payload and an optional caller-supplied `file_id`.
1187///
1188/// The rich fields (`caption`, `reply_to_msg`, `reply_context`,
1189/// `forward_info`) only ever travel inside the MLS-sealed chunk-0 plaintext
1190/// (v2 media envelope), and only toward recipients whose key package
1191/// advertised `rich_versions` support. Toward anyone else — including every
1192/// plaintext (encryption opt-out) transfer — they are silently dropped,
1193/// never sent cleartext, so the transfer degrades to what plain
1194/// `send_media` sends.
1195#[derive(Debug, Clone, Default)]
1196pub struct MediaSendOptions {
1197    /// Media metadata delivered with chunk 0 (as on `send_media`).
1198    pub media_metadata: Option<MediaMetadata>,
1199    /// Caption text, delivered sealed-only.
1200    pub caption: Option<String>,
1201    /// ID of the message this media replies to, delivered sealed-only.
1202    pub reply_to_msg: Option<String>,
1203    /// Quoted-reply context, delivered sealed-only.
1204    pub reply_context: Option<ReplyContext>,
1205    /// Forward attribution, delivered sealed-only.
1206    pub forward_info: Option<ForwardInfo>,
1207    /// Caller-supplied file id for the transfer (minted when absent). Must
1208    /// not collide with an active outbound transfer; bounded to the wire
1209    /// `file_id` field limit.
1210    pub file_id: Option<String>,
1211    /// Application id stamped on every chunk of this transfer, in place of
1212    /// the configured one. Same meaning, same limits and the same cleartext
1213    /// caveat as [`SendMessageOptions::app_id`].
1214    pub app_id: Option<String>,
1215}
1216
1217/// The sealed rich body: what `__RICH_V1__` + JSON carries inside the MLS
1218/// plaintext. `text` is the user-visible content; the optional fields are
1219/// restored onto the inbound message by `apply_decrypted_content` *after*
1220/// its outer-field strip, making the sealed body the sole trusted carrier
1221/// for rich data on encrypted messages.
1222#[derive(Clone, Serialize, Deserialize)]
1223pub(crate) struct RichPayloadV1 {
1224    pub(crate) text: String,
1225    #[serde(default, skip_serializing_if = "Option::is_none")]
1226    pub(crate) reply_context: Option<ReplyContext>,
1227    #[serde(default, skip_serializing_if = "Option::is_none")]
1228    pub(crate) media_metadata: Option<MediaMetadata>,
1229    #[serde(default, skip_serializing_if = "Option::is_none")]
1230    pub(crate) forward_info: Option<ForwardInfo>,
1231    /// Sealed copy of the outer `content_type` rendering hint — the last
1232    /// rich-adjacent field a relay could rewrite in transit. Additive after
1233    /// the body first shipped: absent from bodies sealed by older senders,
1234    /// in which case the outer value stands. When present it is
1235    /// authoritative on receive (except `FileChunk`, refused there like at
1236    /// the send boundary), so a relay can no longer restamp the rendering
1237    /// hint — or worse, restamp it `FileChunk` and get the decrypted
1238    /// message routed into the file-transfer manager and dropped. Fresh
1239    /// sends with a non-Text hint seal a hint-only body even without
1240    /// extras. Forwards seal their attribution and media metadata as
1241    /// extras toward capable recipients; only legacy queued forwards
1242    /// (persisted by older builds, outer-only) skip the hint-only seal,
1243    /// since a sealed body would wipe their outer copies on restore.
1244    #[serde(default, skip_serializing_if = "Option::is_none")]
1245    pub(crate) content_type: Option<ContentType>,
1246}
1247
1248impl RichPayloadV1 {
1249    /// Parses a sealed `__RICH_V1__` body out of decrypted MLS plaintext.
1250    ///
1251    /// Shared by the DM restore (`apply_decrypted_content`) and the group
1252    /// message inbound paths. Never capability-gated (mirroring envelope
1253    /// parsing): whatever a peer chose to seal, we try to read. Returns
1254    /// `None` when the prefix is absent or the body fails to parse (logged;
1255    /// callers surface the raw text rather than dropping an authenticated
1256    /// message). A sealed `FileChunk` content-type claim is refused here —
1257    /// mirroring the send boundary — so a hostile sender can never steer a
1258    /// decrypted message into the file-transfer manager, which would drop
1259    /// it.
1260    pub(crate) fn parse_sealed(plaintext: &str, sender: &str) -> Option<Self> {
1261        let sealed = plaintext.strip_prefix(super::internal_prefixes::RICH_V1)?;
1262        match serde_json::from_str::<Self>(sealed) {
1263            Ok(mut rich) => {
1264                if rich.content_type == Some(ContentType::FileChunk) {
1265                    warn!(
1266                        sender = %sender,
1267                        "Sealed rich payload claims the internal FileChunk content type, ignoring the hint"
1268                    );
1269                    rich.content_type = None;
1270                }
1271                Some(rich)
1272            }
1273            Err(e) => {
1274                warn!(
1275                    sender = %sender,
1276                    error = %e,
1277                    "Failed to parse sealed rich payload, surfacing raw text"
1278                );
1279                None
1280            }
1281        }
1282    }
1283}
1284
1285/// An outbound connection request awaiting a transport outcome (see
1286/// `OfflineProtocol::pending_connection_requests`).
1287#[derive(Debug, Clone)]
1288pub(crate) struct PendingConnectionRequest {
1289    /// Recipient the request was addressed to.
1290    pub(crate) recipient: String,
1291    /// When the request was sent — entries older than
1292    /// [`PENDING_CONNECTION_REQUEST_TTL`] are pruned on insert.
1293    pub(crate) sent_at: std::time::Instant,
1294}
1295
1296/// How long an outbound connection request stays correlatable to a
1297/// transport failure. Past this window the entry is pruned: a DeliveryError
1298/// that stale belongs to a request the app has long stopped showing a
1299/// spinner for.
1300///
1301/// Deliberately wider than the bridges' 60s `RecipientInFlightTracker` TTL:
1302/// that window anchors at the socket write, while this one anchors at
1303/// `send_connection_request` — a request can dwell in the internet outbox
1304/// (device offline, relay reconnecting) before its wire attempt, and this
1305/// window must cover that dwell plus the bridge's correlation window.
1306///
1307/// Also deliberately wider than the worst-case default ACK retry schedule
1308/// (10 retries, 1s initial delay, x2 backoff capped at 5 min, plus a 10s
1309/// ACK timeout per attempt — up to ~910s end to end): retry exhaustion is
1310/// the last settlement point that can still emit a typed undeliverable
1311/// event, so the window must outlive it with headroom.
1312pub(crate) const PENDING_CONNECTION_REQUEST_TTL: std::time::Duration =
1313    std::time::Duration::from_secs(1800);
1314
1315/// Cap on tracked outbound connection requests (oldest evicted first).
1316pub(crate) const MAX_PENDING_CONNECTION_REQUESTS: usize = 64;
1317
1318/// Upper bound (UTF-8 bytes) for `initial_message` on a connection request.
1319/// The request is a plaintext High-priority control frame; an unbounded
1320/// first message would fragment heavily over BLE and can exceed relay frame
1321/// limits after the SDK already returned a message id, so oversized input
1322/// fails loudly at the API instead.
1323pub(crate) const MAX_INITIAL_MESSAGE_BYTES: usize = 4096;
1324
1325/// Payload for a connection request message.
1326#[derive(Debug, Clone, Serialize, Deserialize)]
1327pub(crate) struct ConnectionRequestPayload {
1328    /// Display name of the sender.
1329    pub(crate) sender_name: String,
1330    /// Timestamp of the request (Unix ms).
1331    pub(crate) timestamp_ms: i64,
1332    /// Optional MLS key package data for encrypted session setup.
1333    #[serde(skip_serializing_if = "Option::is_none")]
1334    pub(crate) key_package: Option<Vec<u8>>,
1335    /// Optional first message sent along with the request (`default` keeps
1336    /// payloads from pre-initial-message senders parseable).
1337    #[serde(default, skip_serializing_if = "Option::is_none")]
1338    pub(crate) initial_message: Option<String>,
1339}
1340
1341/// Payload for a connection accepted message.
1342#[derive(Debug, Clone, Serialize, Deserialize)]
1343pub(crate) struct ConnectionAcceptedPayload {
1344    /// Display name of the accepting party.
1345    pub(crate) accepted_by_name: String,
1346    /// Timestamp of the acceptance (Unix ms).
1347    #[serde(default)]
1348    pub(crate) timestamp_ms: i64,
1349    /// Optional MLS key package data for encrypted session setup.
1350    #[serde(skip_serializing_if = "Option::is_none")]
1351    pub(crate) key_package: Option<Vec<u8>>,
1352}
1353
1354// --- Presence, typing, and read receipt payloads ---
1355
1356/// Maximum number of message IDs allowed in a single read receipt.
1357pub(crate) const MAX_READ_RECEIPT_IDS: usize = 256;
1358
1359/// Payload for a presence update message.
1360#[derive(Debug, Clone, Serialize, Deserialize)]
1361pub(crate) struct PresencePayload {
1362    /// Presence status.
1363    pub(crate) status: PresenceStatus,
1364    /// Timestamp of the update (Unix ms).
1365    pub(crate) timestamp_ms: i64,
1366}
1367
1368/// Payload for a typing indicator message.
1369#[derive(Debug, Clone, Serialize, Deserialize)]
1370pub(crate) struct TypingIndicatorPayload {
1371    /// Opaque conversation identifier chosen by the sender (conventionally a
1372    /// peer address for DMs, the group id for groups). Never parsed here.
1373    pub(crate) conversation_id: String,
1374    /// Whether the user is currently typing.
1375    pub(crate) is_typing: bool,
1376    /// Timestamp of the indicator (Unix ms).
1377    pub(crate) timestamp_ms: i64,
1378}
1379
1380/// Payload for a read receipt message.
1381#[derive(Debug, Clone, Serialize, Deserialize)]
1382pub(crate) struct ReadReceiptPayload {
1383    /// IDs of the messages that were read.
1384    pub(crate) message_ids: Vec<String>,
1385    /// Timestamp when the messages were read (Unix ms).
1386    pub(crate) timestamp_ms: i64,
1387}
1388
1389// --- Group (relay) payloads ---
1390
1391#[derive(Debug, Clone, Serialize, Deserialize)]
1392pub(crate) struct GroupCreatedPayload {
1393    pub(crate) group_id: String,
1394    pub(crate) name: String,
1395}
1396
1397#[derive(Debug, Clone, Serialize, Deserialize)]
1398pub(crate) struct GroupMessageReceivedPayload {
1399    pub(crate) group_id: String,
1400    pub(crate) sender: String,
1401    pub(crate) content: String,
1402    pub(crate) timestamp: String,
1403    pub(crate) message_id: String,
1404    #[serde(default, skip_serializing_if = "Option::is_none")]
1405    pub(crate) reply_to_msg: Option<String>,
1406    /// Forwarding attribution (present when the group message was forwarded).
1407    #[serde(default, skip_serializing_if = "Option::is_none")]
1408    pub(crate) forward_info: Option<offline_protocol_core::ForwardInfo>,
1409}
1410
1411#[derive(Debug, Clone, Serialize, Deserialize)]
1412pub(crate) struct GroupMemberAddedPayload {
1413    pub(crate) group_id: String,
1414    pub(crate) user_id: String,
1415    pub(crate) added_by: String,
1416    #[serde(skip_serializing_if = "Option::is_none")]
1417    pub(crate) group_name: Option<String>,
1418}
1419
1420#[derive(Debug, Clone, Serialize, Deserialize)]
1421pub(crate) struct GroupMemberRemovedPayload {
1422    pub(crate) group_id: String,
1423    pub(crate) user_id: String,
1424    pub(crate) removed_by: String,
1425}
1426
1427#[derive(Debug, Clone, Serialize, Deserialize)]
1428pub(crate) struct GroupInfoMemberPayload {
1429    pub(crate) user_id: String,
1430    pub(crate) role: String,
1431    pub(crate) joined_at: String,
1432}
1433
1434#[derive(Debug, Clone, Serialize, Deserialize)]
1435pub(crate) struct GroupInfoPayload {
1436    pub(crate) group_id: String,
1437    pub(crate) name: String,
1438    pub(crate) created_by: String,
1439    pub(crate) created_at: String,
1440    pub(crate) members: Vec<GroupInfoMemberPayload>,
1441}
1442
1443#[derive(Debug, Clone, Serialize, Deserialize)]
1444pub(crate) struct UserGroupSummaryPayload {
1445    pub(crate) group_id: String,
1446    pub(crate) name: String,
1447    pub(crate) created_at: String,
1448}
1449
1450#[derive(Debug, Clone, Serialize, Deserialize)]
1451pub(crate) struct UserGroupsPayload {
1452    pub(crate) groups: Vec<UserGroupSummaryPayload>,
1453}
1454
1455#[derive(Debug, Clone, Serialize, Deserialize)]
1456pub(crate) struct GroupErrorPayload {
1457    /// The relay's own wording. **Never emitted on an event** — see
1458    /// [`GroupErrorPayload::classify_reason`]. Treat every read of this
1459    /// field as a read of untrusted, unbounded wire input.
1460    pub(crate) reason: String,
1461    /// Group the error concerns, when the relay scoped it (e.g. a
1462    /// registration sync denial). Used to drop the group from
1463    /// `relay_synced` so sends fall back to per-member delivery.
1464    #[serde(default, skip_serializing_if = "Option::is_none")]
1465    pub(crate) group_id: Option<String>,
1466}
1467
1468impl GroupErrorPayload {
1469    /// Maps the relay's free-text `reason` onto a fixed local vocabulary.
1470    ///
1471    /// `__GROUP_ERROR__` is a relay answer: it rides
1472    /// `RELAY_ANSWER_PREFIXES`, so on the relay ingest shape (Internet
1473    /// arrival, no transport peer identity) it is accepted **unsigned** —
1474    /// no key material, no session, no prior contact, just a frame on that
1475    /// socket. Signed, it is reachable to any peer over any transport, since
1476    /// the handler is deliberately not gated on the Internet path the way
1477    /// the `GROUP_CREATED` ack is. Either way `reason` is whatever the
1478    /// sender wrote: arbitrary content, arbitrary length, not ours.
1479    ///
1480    /// So the text does not travel any further. Nothing downstream needs it
1481    /// — the sync revocation keys off `group_id`, and the platform bridges
1482    /// already dual-emit the raw relay frame on the server-message channel
1483    /// for apps that want the relay's exact wording. What an event carries
1484    /// is this classification instead, which an attacker can at most steer
1485    /// between three harmless codes.
1486    ///
1487    /// Even an *honest* relay makes this necessary: its `Not a member of
1488    /// group {id}` renders an identifier into prose, smuggling past a
1489    /// telemetry scrubber that hashes `group_id` fields but ships free text
1490    /// verbatim by design.
1491    ///
1492    /// The `&'static str` return is load-bearing, the same way
1493    /// `MlsError::privacy_safe_reason` is: it makes interpolating wire input
1494    /// unrepresentable rather than merely discouraged. Matching is exact and
1495    /// the fallback is closed, so a relay rewording an error degrades to
1496    /// `error` — never back to shipping its text.
1497    pub(crate) fn classify_reason(&self) -> &'static str {
1498        match self.reason.as_str() {
1499            // Relay has no such group: invite links and relay fan-out for it
1500            // are dead, not merely refused.
1501            "Group not found" => "not_found",
1502            // Relay refused to register/sync the group for this caller.
1503            "Only admins can sync this group" => "sync_denied",
1504            // Everything else, including anything a forged frame chose.
1505            _ => "error",
1506        }
1507    }
1508}
1509
1510/// A received key package awaiting use for session creation.
1511#[derive(Debug, Clone, Serialize, Deserialize)]
1512pub(crate) struct ReceivedKeyPackage {
1513    /// Raw MLS key package bytes.
1514    pub(crate) key_package_data: Vec<u8>,
1515    /// Local wall-clock deadline (ms since epoch) computed from the sender's
1516    /// `remaining_lifetime_ms`, anchored to *our* clock at receive time.
1517    pub(crate) local_expires_at_ms: u64,
1518}
1519
1520/// Delivery ACKs held for one peer until they go out as one frame (see
1521/// `OfflineProtocol::coalesced_acks_out`).
1522#[derive(Debug, Clone)]
1523pub(crate) struct CoalescedAcks {
1524    /// The carrier the answered frames arrived on, which the ACK goes back
1525    /// over. A frame from another carrier starts a new batch.
1526    pub(crate) transport: offline_protocol_transport::TransportType,
1527    /// When the first held ACK was owed.
1528    pub(crate) since: std::time::Instant,
1529    /// The first answered frame's hop count, as a single ACK reports it.
1530    pub(crate) hop_count: String,
1531    /// The answered message ids, oldest first.
1532    pub(crate) ids: Vec<String>,
1533}
1534
1535/// Durable record of the end-to-end capability versions a peer last
1536/// advertised in its key package (`env_versions` / `rich_versions`).
1537///
1538/// Persisted separately from [`ReceivedKeyPackage`] because the cached key
1539/// package is deleted once a session is established, while the capabilities
1540/// must survive restarts for exactly those peers: mobile apps restart
1541/// constantly and MLS sessions persist, so without this record a rich send
1542/// right after relaunch silently degrades to bare text (and the compact
1543/// envelope to JSON) until the next live key-package exchange.
1544///
1545/// Stores the raw advertised versions, not the config-gated subset: the kill
1546/// switches (`compact_envelope_enabled` / `rich_payload_enabled`) gate use —
1547/// live recording, restore, and send — not knowledge, so toggling one across
1548/// restarts behaves the same as toggling it live.
1549///
1550/// `wire_versions` is deliberately absent: it is hop-local (which frames a
1551/// directly-connected peer decodes), and connection setup re-exchanges key
1552/// packages on discovery anyway, so persisting it would buy nothing.
1553#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1554pub(crate) struct PeerCapabilities {
1555    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1556    pub(crate) env_versions: Vec<u8>,
1557    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1558    pub(crate) rich_versions: Vec<u8>,
1559    /// Sync versions the peer advertised, from
1560    /// [`KeyPackagePayload::data_versions`]. Persisted for the same reason
1561    /// as the two above: without it a document edited right after relaunch
1562    /// would not replicate until the next live key-package exchange, and a
1563    /// sync that silently does not happen looks exactly like a peer with
1564    /// nothing to say.
1565    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1566    pub(crate) data_versions: Vec<u8>,
1567    /// Rich-payload versions a *group inviter* attested for this peer
1568    /// (carried on the group Add commit / Welcome), as opposed to the
1569    /// direct self-advertised `rich_versions` above. Kept separate because
1570    /// the trust differs: attestation is third-party and may be stale, so a
1571    /// direct key-package exchange overwrites the whole record (clearing
1572    /// this field) — direct knowledge is always authoritative. Consulted
1573    /// only by the group seal gate, never by DM sealing or envelope
1574    /// selection.
1575    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1576    pub(crate) attested_rich_versions: Vec<u8>,
1577    /// Sync versions a *group inviter* attested for this peer, carried on
1578    /// the group Add commit / Welcome exactly like
1579    /// [`Self::attested_rich_versions`] and kept separate from the direct
1580    /// `data_versions` above for the same reason: attestation is
1581    /// third-party and may be stale, so a direct key-package exchange
1582    /// overwrites the whole record and clears this field.
1583    ///
1584    /// Group members never exchange key packages with each other, so
1585    /// without this a group would replicate only among the subset of
1586    /// members that happen to have met directly, and the rest would sit
1587    /// there editing documents nobody receives. Consulted only by the
1588    /// group replication gate, never by 1:1 sync (which always has direct
1589    /// knowledge: session establishment exchanges key packages).
1590    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1591    pub(crate) attested_data_versions: Vec<u8>,
1592
1593    /// Control-frame signing versions the peer advertised, from
1594    /// [`KeyPackagePayload::ctrl_versions`]. Persisted for the same reason as
1595    /// the lists above: without it, a peer met before a restart would be sent
1596    /// the older signing payload until the next live key-package exchange, and
1597    /// a peer that has *proved* it signs the newer one refuses that.
1598    ///
1599    /// This is the advertised half only. What the peer proved lives in
1600    /// [`EncryptionCapableEntry::ctrl_freshness_proved`], deliberately in a
1601    /// record this one's wholesale overwrite cannot reach.
1602    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1603    pub(crate) ctrl_versions: Vec<u8>,
1604
1605    /// Sealed service frame versions the peer advertised, from
1606    /// [`KeyPackagePayload::svc_versions`], recorded only from a signed key
1607    /// package. Persisted for the same reason as the lists above: without it
1608    /// a peer met before a restart would be sent its service bodies in signed
1609    /// plaintext until the next live key-package exchange.
1610    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1611    pub(crate) svc_versions: Vec<u8>,
1612
1613    /// Delivery-ACK statuses the peer reads, from
1614    /// [`KeyPackagePayload::ack_versions`]. Persisted for the same reason as
1615    /// the lists above: a peer met before a restart would otherwise get no
1616    /// `undecryptable` answer until its next key package, and a relay mailbox
1617    /// would keep redelivering its dead frames meanwhile.
1618    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1619    pub(crate) ack_versions: Vec<u8>,
1620
1621    /// The peer's Nostr public key, from [`KeyPackagePayload::nostr_pubkey`].
1622    ///
1623    /// Persisted for the same reason as the capability lists: the cached key
1624    /// package is deleted once a session is established, and a peer met before
1625    /// a restart would otherwise silently fall back to bootstrap-key sealing —
1626    /// a privacy regression with no symptom — until the next live exchange.
1627    #[serde(default, skip_serializing_if = "Option::is_none")]
1628    pub(crate) nostr_pubkey: Option<String>,
1629}
1630
1631/// Length of an x-only secp256k1 public key in lowercase hex.
1632pub(crate) const NOSTR_PUBKEY_HEX_LEN: usize = 64;
1633
1634/// Validates a wire-supplied Nostr public key before it is persisted or used
1635/// as a sealing destination.
1636///
1637/// Shape only — the value is signature-bound to the sender, so this is not an
1638/// authenticity check. It exists so a malformed or oversized string cannot
1639/// enter a durable record, and it normalizes case so the same key never
1640/// persists under two spellings.
1641pub(crate) fn normalize_nostr_pubkey(candidate: &str) -> Option<String> {
1642    if candidate.len() != NOSTR_PUBKEY_HEX_LEN || !candidate.bytes().all(|b| b.is_ascii_hexdigit())
1643    {
1644        return None;
1645    }
1646    Some(candidate.to_ascii_lowercase())
1647}
1648
1649/// Cap on how many advertised version entries persist per capability list
1650/// in a [`PeerCapabilities`] record. The lists are unauthenticated wire
1651/// input stored raw (raw so unknown future versions survive a local
1652/// upgrade), and a hostile advertiser could otherwise bloat each durable
1653/// record up to the transport message size. Truncation only hurts the
1654/// advertiser — real senders list a handful of versions.
1655pub(crate) const MAX_PERSISTED_CAPABILITY_VERSIONS: usize = 8;
1656
1657impl PeerCapabilities {
1658    /// Builds a record from the wire-advertised version lists, truncating
1659    /// each to [`MAX_PERSISTED_CAPABILITY_VERSIONS`].
1660    pub(crate) fn from_advertised(
1661        env_versions: &[u8],
1662        rich_versions: &[u8],
1663        data_versions: &[u8],
1664        ctrl_versions: &[u8],
1665        svc_versions: &[u8],
1666        ack_versions: &[u8],
1667        nostr_pubkey: Option<&str>,
1668    ) -> Self {
1669        Self {
1670            env_versions: env_versions
1671                .iter()
1672                .copied()
1673                .take(MAX_PERSISTED_CAPABILITY_VERSIONS)
1674                .collect(),
1675            rich_versions: rich_versions
1676                .iter()
1677                .copied()
1678                .take(MAX_PERSISTED_CAPABILITY_VERSIONS)
1679                .collect(),
1680            data_versions: data_versions
1681                .iter()
1682                .copied()
1683                .take(MAX_PERSISTED_CAPABILITY_VERSIONS)
1684                .collect(),
1685            ctrl_versions: ctrl_versions
1686                .iter()
1687                .copied()
1688                .take(MAX_PERSISTED_CAPABILITY_VERSIONS)
1689                .collect(),
1690            svc_versions: svc_versions
1691                .iter()
1692                .copied()
1693                .take(MAX_PERSISTED_CAPABILITY_VERSIONS)
1694                .collect(),
1695            ack_versions: ack_versions
1696                .iter()
1697                .copied()
1698                .take(MAX_PERSISTED_CAPABILITY_VERSIONS)
1699                .collect(),
1700            attested_rich_versions: Vec::new(),
1701            attested_data_versions: Vec::new(),
1702            nostr_pubkey: nostr_pubkey.and_then(normalize_nostr_pubkey),
1703        }
1704    }
1705
1706    /// Whether any capability is advertised. Empty records are deleted
1707    /// rather than stored — the durable side of the downgrade semantics.
1708    pub(crate) fn is_any(&self) -> bool {
1709        !self.env_versions.is_empty()
1710            || !self.rich_versions.is_empty()
1711            || !self.data_versions.is_empty()
1712            || !self.ctrl_versions.is_empty()
1713            || !self.svc_versions.is_empty()
1714            || !self.ack_versions.is_empty()
1715            || !self.attested_rich_versions.is_empty()
1716            || !self.attested_data_versions.is_empty()
1717            || self.nostr_pubkey.is_some()
1718    }
1719}
1720
1721/// Which canonical payload a control frame's signature verified against.
1722///
1723/// Both are legitimate: [`Self::V1`] is what every peer signed before the
1724/// freshness-bound payload existed, and refusing it outright would refuse
1725/// first contact with any peer that has not upgraded. What the distinction
1726/// buys is that the two can be treated differently once a peer has *proved* it
1727/// can produce the newer one.
1728#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1729pub(crate) enum ControlSigVersion {
1730    /// `offline-ctrl-v1`: sender, id, recipient, content. States no freshness,
1731    /// so a signature over it never expires.
1732    V1,
1733    /// `offline-ctrl-v2`: the four fields above plus the frame's timestamp.
1734    V2,
1735}
1736
1737/// What verifying a control frame's signature established.
1738#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1739pub(crate) enum ControlVerification {
1740    /// No signature metadata at all. The caller decides policy; for a
1741    /// security-gated prefix that policy is refusal.
1742    Unsigned,
1743    /// A signature verified, and the key that made it derives to the address
1744    /// the frame claims to come from.
1745    Verified(ControlSigVersion),
1746}
1747
1748/// Outcome of [`OfflineProtocol::security_gate_control_message`].
1749///
1750/// [`OfflineProtocol`]: crate::OfflineProtocol
1751/// [`OfflineProtocol::security_gate_control_message`]: crate::OfflineProtocol
1752#[derive(Debug)]
1753pub(crate) enum ControlGateOutcome {
1754    /// The message may proceed to dispatch.
1755    ///
1756    /// `signed` is `true` **only** when an Ed25519 signature was present,
1757    /// verified, and produced by the key the sender's address derives from. It
1758    /// is deliberately `false` for both of the other ways a message reaches
1759    /// dispatch — a relay-originated answer, which no peer signs
1760    /// (`RELAY_ANSWER_PREFIXES`), and a prefix the gate does not cover at all —
1761    /// so a handler that keys on it fails closed without having to know which
1762    /// case it is in.
1763    ///
1764    /// Since unsigned control traffic is now refused outright, `false` no
1765    /// longer reaches any *gated* handler; the bit survives because those two
1766    /// ungated paths still produce it, and because a handler that treats a
1767    /// payload field as authenticated should say so at the point it does.
1768    ///
1769    /// `freshness_bound` is the strictly narrower fact: the signature verified
1770    /// against the payload that covers the frame's timestamp, **and** that
1771    /// timestamp was inside the window this node allows. It is what a handler
1772    /// consults before acting on a directive that destroys state, because such
1773    /// a directive on a frame that could be a recording is a replayable way to
1774    /// destroy that state (issue 403).
1775    ///
1776    /// It is deliberately the *fact* and not the *policy*: it stays `false`
1777    /// when freshness enforcement is switched off, and the handler applies the
1778    /// switch itself. A flag that folded the config in would read as "this
1779    /// frame is fresh" while meaning "nobody looked", which is the reading that
1780    /// gets copied to the next call site.
1781    Proceed { signed: bool, freshness_bound: bool },
1782    /// The gate rejected the message; the caller must return this result
1783    /// without dispatching.
1784    Rejected(InternalMessageResult),
1785}
1786
1787/// Result of processing an internal protocol message.
1788#[derive(Debug)]
1789pub(crate) enum InternalMessageResult {
1790    /// Message was consumed internally (don't surface to app).
1791    Consumed,
1792    /// Message was rejected by the security gate (spoofed sender, bad
1793    /// signature, unsigned control traffic, or a signing key that does not
1794    /// derive to the claimed sender address). Like `Consumed`, the message is not
1795    /// surfaced to the app — but unlike `Consumed`, a delivery ACK must NOT
1796    /// be sent back, to avoid confirming to the attacker that the target is
1797    /// online and processing messages.
1798    SecurityRejected,
1799    /// Message was not delivered, but the sender can still recover it by
1800    /// resending. Unlike `Consumed`, a delivery ACK must NOT be sent and the id
1801    /// must NOT stay dedup-marked: the message is provably not delivered, so
1802    /// the receiver must leave the sender's retry lever intact. The receive
1803    /// loop responds by unmarking the id (so a resend re-enters processing
1804    /// instead of hitting the duplicate re-ACK path) and skipping the ACK.
1805    ///
1806    /// Two conditions produce it:
1807    ///
1808    /// - **Session not ready**: the MLS session/group is not established yet,
1809    ///   so the frame is queued for delayed decryption
1810    ///   (`enqueue_pending_decryption`). The queued copy is surfaced — and the
1811    ///   id re-marked — once the session confirms and the queue drains
1812    ///   (`process_pending_decryption`), which also sends the deferred delivery
1813    ///   ACK directly on the recorded arrival transport (so a sender that gave
1814    ///   up before the session confirmed still learns of delivery).
1815    /// - **Envelope parse failure** with `crypto_recovery_enabled`: the
1816    ///   `__MLS_ENC__` payload did not parse in any envelope form, so there is
1817    ///   no ciphertext to decrypt. Not queued (an unparseable frame can never
1818    ///   become parseable) and not answered, since for an injector silence
1819    ///   reveals less than an answer. Recovery is the sender's resend.
1820    ///
1821    /// See `docs/state-machines/delivery-and-acks.md` for the
1822    /// deferred-acknowledgement atom and the decrypt-failure classification.
1823    Deferred,
1824    /// The frame can never decrypt, though the message behind it may: an epoch
1825    /// desync (sealed to an epoch that is not ours, and a re-key is scheduled)
1826    /// or a crypto/transport failure with `crypto_recovery_enabled` (OpenMLS
1827    /// spent the ratchet generation on the failed attempt). Not queued.
1828    ///
1829    /// Handled like `Deferred` (id unmarked, no delivery ACK) except that
1830    /// the frame is answered with an `undecryptable` ACK
1831    /// ([`crate::constants::ACK_STATUS_UNDECRYPTABLE`]) when it arrived over
1832    /// the internet relay and its sender advertised that it reads one; any
1833    /// other frame gets no answer. Silence left a relay
1834    /// holding the frame to redeliver it on every connect, failing again each
1835    /// time; the answer lets the relay drop it and tells the sender to resend
1836    /// the message once, re-sealed under its current session when it can.
1837    Undecryptable,
1838    /// Message was decrypted, here's the plaintext.
1839    Decrypted(String),
1840}
1841
1842/// Outcome of routing an inbound file-chunk message through
1843/// [`OfflineProtocol::handle_incoming_file_chunk`]. Distinguishes chunks that
1844/// were dealt with terminally (decrypted/assembled, or dropped for a permanent
1845/// reason) from chunks queued for delayed decryption — so the receive loop can
1846/// defer the ACK for the latter, exactly like the text `Deferred` path.
1847///
1848/// [`OfflineProtocol::handle_incoming_file_chunk`]: crate::OfflineProtocol
1849///
1850/// `#[must_use]`: the ACK/defer decision hinges on this outcome. Dropping it on
1851/// the floor silently reverts to the pre-deferred-ACK behavior (always ACK,
1852/// leave dedup-marked), reintroducing the queue-path silent-loss bug — so every
1853/// caller must branch on it.
1854#[must_use]
1855#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1856pub(crate) enum ChunkOutcome {
1857    /// The chunk was decrypted/assembled or dropped for a terminal reason
1858    /// (parse failure, resource limit, permanent refusal). The sender should
1859    /// stop retrying either way, so the caller ACKs as before.
1860    Handled,
1861    /// The chunk was not delivered but the sender can still recover it by
1862    /// resending: it could not be decrypted yet (session not ready, so queued
1863    /// for delayed decryption), or it is undecryptable as it stands (epoch
1864    /// desync, or a crypto failure while `crypto_recovery_enabled`), or its
1865    /// media envelope did not decode at all (also `crypto_recovery_enabled`) —
1866    /// the latter shapes dropped without queueing. The caller must NOT ACK and
1867    /// must unmark the id, so the sender keeps retrying and the resend re-enters
1868    /// processing. For an undecryptable or undecodable chunk that recovery is
1869    /// the media outbox's `MediaResendRequired` path — chunks are re-encoded,
1870    /// never re-sealed.
1871    Deferred,
1872    /// The chunk was refused as illegitimate rather than undeliverable. Two
1873    /// shapes: an unencrypted chunk refused by the encryption policy, and an
1874    /// encrypted chunk that failed its identity binding — the envelope named
1875    /// another pair's session slot, or the MLS credential authenticated a
1876    /// different sender than the wire envelope claims.
1877    ///
1878    /// Like [`InternalMessageResult::SecurityRejected`] for text, the caller
1879    /// must NOT ACK (don't confirm to an injector that the target processes
1880    /// their messages) and must unmark the id (so a replay re-enters this gate
1881    /// instead of the duplicate re-ACK path), matching the plaintext-text
1882    /// rejection in the receive loop.
1883    Rejected,
1884}
1885
1886/// Pending message waiting for session establishment.
1887#[derive(Clone, Serialize, Deserialize)]
1888pub(crate) struct PendingMessage {
1889    /// Original plaintext content.
1890    pub(crate) content: String,
1891    /// Message priority.
1892    pub(crate) priority: MessagePriority,
1893    /// Message ID (preserved from initial creation).
1894    pub(crate) message_id: MessageId,
1895    /// Reply-to message ID if applicable.
1896    pub(crate) reply_to_msg: Option<MessageId>,
1897    /// Forwarding attribution (preserved so it survives the pending queue).
1898    #[serde(default, skip_serializing_if = "Option::is_none")]
1899    pub(crate) forwarded_from: Option<ForwardInfo>,
1900    /// Content type of the original message (preserved for forwarded non-text messages).
1901    #[serde(default)]
1902    pub(crate) content_type: ContentType,
1903    /// Media metadata (preserved for forwarded media messages).
1904    #[serde(default, skip_serializing_if = "Option::is_none")]
1905    pub(crate) media_metadata: Option<MediaMetadata>,
1906    /// Option-borne rich extras from the rich send surface. Kept separate
1907    /// from the legacy `forwarded_from`/`media_metadata` fields above: those
1908    /// flush as outer cleartext (shipped forward behavior), while these must
1909    /// flush inside the sealed rich body or be dropped — never cleartext.
1910    #[serde(default, skip_serializing_if = "Option::is_none")]
1911    pub(crate) rich: Option<RichSendExtras>,
1912    /// Per-send application id from the rich send surface, `None` for the
1913    /// configured one.
1914    ///
1915    /// Kept on the entry because the flush rebuilds the outer message from
1916    /// this record: without it, a send parked while the session was not
1917    /// ready would go out under the configured id and be routed to the
1918    /// wrong application on the receiving instance. Serde-defaulted, so a
1919    /// record queued before the field existed restores as `None`, which is
1920    /// the id it was queued with.
1921    #[serde(default, skip_serializing_if = "Option::is_none")]
1922    pub(crate) app_id: Option<String>,
1923    /// When the message *first* entered the pending queue.
1924    ///
1925    /// Drives `pending_message_max_lifetime_ms`, and is deliberately preserved
1926    /// across a re-queue (see [`PendingProvenance`]): a flush that finds the
1927    /// session still unavailable puts the entry back, and stamping a fresh
1928    /// timestamp there would let repeated reconciliation renew an "absolute"
1929    /// lifetime forever.
1930    pub(crate) queued_at: DateTime<Utc>,
1931    /// Serialized footprint of this entry, for the pending-queue byte budgets
1932    /// ([`MAX_PENDING_MESSAGE_BYTES_PER_PEER`] /
1933    /// [`MAX_PENDING_MESSAGE_BYTES_GLOBAL`]).
1934    ///
1935    /// Derived, so it is not persisted; it is (re)computed by
1936    /// [`PendingMessage::measure`] at the two points an entry comes into
1937    /// existence — admission and load-from-storage — and then simply travels
1938    /// with the entry as it is moved between the queue, a flush, and a
1939    /// re-queue.
1940    #[serde(skip)]
1941    pub(crate) serialized_bytes: usize,
1942}
1943
1944/// One persisted pending-queue record: a single queued message plus the peer
1945/// it is queued for.
1946///
1947/// The recipient rides *inside* the record because the key is the message id,
1948/// and the in-memory queue is a map keyed by recipient that has to be rebuilt
1949/// from records read in whatever order the store enumerates them. Same shape as
1950/// [`OutboxEntry`], whose recipient likewise travels in the record (inside its
1951/// `Message`) rather than in the key.
1952///
1953/// Deliberately a wrapper rather than a `recipient` field on [`PendingMessage`]:
1954/// in memory the recipient is already the map key, and a second copy there
1955/// would be free to drift from it.
1956#[derive(Serialize, Deserialize)]
1957pub(crate) struct PendingMessageRecord {
1958    pub(crate) recipient: String,
1959    pub(crate) message: PendingMessage,
1960}
1961
1962/// One inbound encrypted frame parked in the pending-decryption queue, as
1963/// persisted under [`storage_keys::PENDING_DECRYPT_ENTRIES`].
1964///
1965/// The queue itself is in-memory only (`PendingDecryptionQueue`); this record
1966/// is what lets an entry survive an app restart. Without it a frame that
1967/// arrived before its session was ready was lost the moment the process died
1968/// — and with a relay that pushes ciphertext without store-and-forward there
1969/// is no second copy to ask for, so a restart during a slow handshake was a
1970/// silently lost message.
1971///
1972/// Keyed by message id, like [`PendingMessageRecord`], so a drain, a prune or
1973/// an overflow drop deletes exactly the record it settled. `peer_id` rides
1974/// inside the record because the in-memory queue is a per-peer map rebuilt
1975/// from records the store enumerates in no particular order.
1976///
1977/// `first_received_at_ms` is wall-clock, not the `Instant` the in-memory entry
1978/// carries: an `Instant` does not survive a restart, so on restore the entry is
1979/// re-stamped with a fresh `Instant::now()` (its in-memory TTL restarts) and
1980/// this field bounds the *total* time on disk instead —
1981/// `PENDING_DECRYPT_PERSISTED_MAX_AGE_MS`.
1982///
1983/// `version` is a forward-compatibility hinge: a reader that sees a version it
1984/// does not know treats the record as corrupt and drops it rather than
1985/// guessing at fields. Records written before the field existed default to 1.
1986#[derive(Serialize, Deserialize)]
1987pub(crate) struct PendingDecryptRecord {
1988    #[serde(default = "pending_decrypt_record_version")]
1989    pub(crate) version: u8,
1990    pub(crate) peer_id: String,
1991    pub(crate) message: Message,
1992    pub(crate) first_received_at_ms: i64,
1993    #[serde(default)]
1994    pub(crate) received_via: Option<TransportType>,
1995}
1996
1997/// The only record version this build writes or reads.
1998pub(crate) const PENDING_DECRYPT_RECORD_VERSION: u8 = 1;
1999
2000fn pending_decrypt_record_version() -> u8 {
2001    PENDING_DECRYPT_RECORD_VERSION
2002}
2003
2004/// One frame in custody, persisted under [`storage_keys::CUSTODY`].
2005///
2006/// The frame as it arrived with the deposit request removed and the hop
2007/// fields as the forwarding path adjusted them; the depositor, which is both
2008/// the frame's sender and the peer it arrived from; the wall-clock acceptance
2009/// time in Unix milliseconds, never a monotonic instant; and the class token.
2010/// `version` is the same forward-compatibility hinge as
2011/// [`PendingDecryptRecord::version`].
2012#[derive(Serialize, Deserialize)]
2013pub(crate) struct CustodyRecord {
2014    #[serde(default = "custody_record_version")]
2015    pub(crate) version: u8,
2016    pub(crate) depositor: String,
2017    pub(crate) message: Message,
2018    pub(crate) accepted_at_ms: i64,
2019    pub(crate) class: String,
2020}
2021
2022/// The only custody record version this build writes or reads.
2023pub(crate) const CUSTODY_RECORD_VERSION: u8 = 1;
2024
2025fn custody_record_version() -> u8 {
2026    CUSTODY_RECORD_VERSION
2027}
2028
2029impl PendingMessage {
2030    /// Recomputes [`Self::serialized_bytes`] from the current field values.
2031    ///
2032    /// Measures what persistence actually costs (the serialized entry) rather
2033    /// than estimating from `content.len()`, so rich extras and forward
2034    /// attribution are counted. A serialization failure — which would also make
2035    /// the entry unpersistable — falls back to the content length so the entry
2036    /// still consumes budget rather than reading as free.
2037    pub(crate) fn measure(&mut self) {
2038        self.serialized_bytes = serde_json::to_vec(self)
2039            .map(|encoded| encoded.len())
2040            .unwrap_or_else(|_| self.content.len());
2041    }
2042}
2043
2044/// Identity carried by an outbound message that is re-entering the
2045/// pending-session queue rather than being queued for the first time.
2046///
2047/// Both fields exist to keep a re-queue from looking like a fresh send: the id
2048/// so `MessageSent`/`MessageDelivered`/`MessageFailed` stay correlatable with
2049/// what `send_message*` returned, and the timestamp so the absolute pending
2050/// lifetime is measured from first entry.
2051#[derive(Debug, Clone)]
2052pub(crate) struct PendingProvenance {
2053    /// The id the caller already holds.
2054    pub(crate) message_id: MessageId,
2055    /// When the message first entered the pending queue, or `None` when the
2056    /// re-queue does not come *from* that queue — the resend re-seal path
2057    /// passes an outbox id, and an entry it (all but unreachably) enqueues is
2058    /// starting its pending lifetime now.
2059    pub(crate) first_queued_at: Option<DateTime<Utc>>,
2060}
2061
2062impl PendingProvenance {
2063    /// Provenance for a message being put back into the pending queue.
2064    pub(crate) fn requeued(message: &PendingMessage) -> Self {
2065        Self {
2066            message_id: message.message_id.clone(),
2067            first_queued_at: Some(message.queued_at),
2068        }
2069    }
2070
2071    /// Provenance for a known id with no pending-queue history.
2072    pub(crate) fn for_id(message_id: MessageId) -> Self {
2073        Self {
2074            message_id,
2075            first_queued_at: None,
2076        }
2077    }
2078}
2079
2080/// Durable state for a peer MLS session.
2081#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2082pub(crate) enum SessionState {
2083    Pending,
2084    Confirmed,
2085}
2086
2087impl SessionState {
2088    pub(crate) fn as_str(&self) -> &'static str {
2089        match self {
2090            Self::Pending => "Pending",
2091            Self::Confirmed => "Confirmed",
2092        }
2093    }
2094}
2095
2096/// Durable lifecycle states for outbound Welcome delivery.
2097#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2098pub(crate) enum WelcomeDeliveryState {
2099    Created,
2100    SendAttempted,
2101    Sent,
2102    Failed,
2103    Expired,
2104}
2105
2106impl WelcomeDeliveryState {
2107    pub(crate) fn as_str(&self) -> &'static str {
2108        match self {
2109            Self::Created => "Created",
2110            Self::SendAttempted => "SendAttempted",
2111            Self::Sent => "Sent",
2112            Self::Failed => "Failed",
2113            Self::Expired => "Expired",
2114        }
2115    }
2116}
2117
2118/// Per-peer throttle for presence-driven welcome rescue (see
2119/// `OfflineProtocol::on_peer_presence`). Deliberately in-memory only: a
2120/// restart resets the backoff, and the one free rescue that buys is useful
2121/// after a restart anyway.
2122#[derive(Debug, Clone)]
2123pub(crate) struct PresenceRescueThrottle {
2124    pub(crate) next_allowed_at: DateTime<Utc>,
2125    /// Consecutive rescues without the session confirming; drives the
2126    /// exponential backoff exponent.
2127    pub(crate) rescues: u32,
2128}
2129
2130/// Durable metadata for outbound Welcome reliability handling.
2131#[derive(Debug, Clone, Serialize, Deserialize)]
2132pub(crate) struct WelcomeLifecycleRecord {
2133    pub(crate) peer_id: String,
2134    pub(crate) group_id: String,
2135    pub(crate) state: WelcomeDeliveryState,
2136    pub(crate) attempt: u32,
2137    /// Consecutive `PeerUnreachable` parks (relay `DeliveryError` verdicts)
2138    /// since the last reachability edge; drives the escalating retry
2139    /// interval capped at [`WELCOME_UNREACHABLE_RETRY_CAP_SECS`]. Reset on
2140    /// re-arm (presence online / neighbor discovered). Defaulted for
2141    /// records persisted before the field existed.
2142    #[serde(default)]
2143    pub(crate) unreachable_parks: u32,
2144    pub(crate) welcome_message: Message,
2145    pub(crate) next_retry_at: Option<DateTime<Utc>>,
2146    pub(crate) last_reason_code: Option<crate::events::WelcomeReasonCode>,
2147    pub(crate) last_transport_error: Option<String>,
2148    pub(crate) created_at: DateTime<Utc>,
2149    pub(crate) expires_at: DateTime<Utc>,
2150}
2151
2152/// Storage key types for message persistence.
2153pub(crate) mod storage_keys {
2154    /// Legacy key type for pending encrypted messages, keyed by *recipient*,
2155    /// each record holding that peer's whole queue.
2156    ///
2157    /// Superseded by [`PENDING_MESSAGE_ENTRIES`]. Nothing writes this category
2158    /// any more: `restore_pending_messages` reads it, migrates each queue into
2159    /// the per-message layout, and deletes the record. It is read-only
2160    /// migration scaffolding, and retires on the same trigger as the
2161    /// [`ADOPTABLE_STATE_KEY_TYPES`] sweep — an install that skips the
2162    /// migrating release entirely still needs it.
2163    pub const PENDING_MESSAGES: &str = "pending_messages";
2164    /// Key type for pending encrypted messages, keyed by message id — one
2165    /// record per queued message, like [`OUTBOX`].
2166    ///
2167    /// Keying by id rather than by recipient is what makes a lost record
2168    /// *individually settleable*: the id the application is holding is the key,
2169    /// so a record that will not open still names the message it destroyed. The
2170    /// per-recipient layout could only report the loss per peer, because every
2171    /// id was inside the record that would not open.
2172    pub const PENDING_MESSAGE_ENTRIES: &str = "pending_message_entries";
2173    /// Inbound ciphertext parked in the pending-decryption queue, one record
2174    /// per message keyed by message id — the receive-side mirror of
2175    /// [`PENDING_MESSAGE_ENTRIES`]. See `PendingDecryptRecord`.
2176    pub const PENDING_DECRYPT_ENTRIES: &str = "pending_decrypt_entries";
2177
2178    /// Frames held in custody for a neighbour (`docs/spec/custody.md`), one
2179    /// record per held frame keyed by its message id. Sealed like the
2180    /// pending-decrypt records: other people's ciphertext plus routing
2181    /// metadata about them, outliving the process. Post-split only, and
2182    /// absent from [`ADOPTABLE_STATE_KEY_TYPES`] for the same reason as
2183    /// [`PENDING_DECRYPT_ENTRIES`].
2184    pub const CUSTODY: &str = "custody_entries";
2185    /// Key type for persisted per-peer MLS session confirmation state.
2186    pub const SESSION_STATES: &str = "session_states";
2187    /// Key type for persisted per-peer received key packages (survives restart).
2188    pub const PEER_KEY_PACKAGES: &str = "peer_key_packages";
2189    /// Key type for persisted per-peer advertised capability versions
2190    /// (env/rich), which must outlive the key package entry above — that one
2191    /// is deleted once a session is established (see
2192    /// [`super::PeerCapabilities`]).
2193    pub const PEER_CAPABILITIES: &str = "peer_capabilities";
2194    /// Key type for persisted per-peer outbound welcome lifecycle state.
2195    pub const WELCOME_LIFECYCLES: &str = "welcome_lifecycles";
2196    /// Key type for persisted store-and-forward outbox entries, keyed by
2197    /// message id. Holds only main-outbox (non-media) entries so undelivered
2198    /// messages survive app restarts; the media (file-chunk) outbox is
2199    /// intentionally excluded because file transfers are not persisted and
2200    /// must be re-initiated by the app after a restart.
2201    pub const OUTBOX: &str = "outbox";
2202    /// Key type for persisted outbound media transfer descriptors, keyed by
2203    /// file id. Descriptor-only (never chunk bytes): a descriptor surviving
2204    /// into a restore marks a transfer the app must re-initiate, surfaced
2205    /// via `MediaResendRequired`.
2206    pub const MEDIA_DESCRIPTORS: &str = "media_descriptors";
2207    /// Key type for the Lamport clock value.
2208    pub const LAMPORT_CLOCK: &str = "lamport_clock";
2209    /// Key ID for the single Lamport clock entry.
2210    pub const LAMPORT_CLOCK_ID: &str = "current";
2211    /// The deduplicator's exact-mode seen set, one record for the whole set.
2212    /// See `DedupSeenRecord`.
2213    pub const DEDUP_SEEN_IDS: &str = "dedup_seen_ids";
2214    /// Key ID for the single seen-set record.
2215    pub const DEDUP_SEEN_IDS_ID: &str = "current";
2216    /// Key type for the durable record that a peer has proved it runs MLS.
2217    ///
2218    /// Successor to the `tofu_keys` category, which stored a pinned public key
2219    /// per peer. The pin is gone — an address *is* its key's hash, so nothing
2220    /// needs storing to check one — but the store had a second job the
2221    /// derivation does not do: it was the half of
2222    /// `OfflineProtocol::encryption_capable_peers` that survived a restart, and
2223    /// therefore what keeps the plaintext-downgrade gate shut for a peer whose
2224    /// session was torn down. That job is all this category still does, so the
2225    /// value is a timestamp and nothing else.
2226    ///
2227    /// A leftover `tofu_keys` record is left where it is, and no migration is
2228    /// written for it. Records from before the identity change are keyed by a
2229    /// username, so no live peer id can ever read them back — they are simply
2230    /// unreachable. Records written in the window *between* the identity
2231    /// change and the pin store's deletion are keyed by an address and would
2232    /// still resolve, so a peer marked capable there with no live session
2233    /// loses that durable mark across the upgrade: it falls back to the
2234    /// `is_session_confirmed` check until the next key-package exchange
2235    /// re-marks it. That is the fail-closed direction and it costs one
2236    /// exchange, which is why migrating them is not worth the code while no
2237    /// fleet is deployed.
2238    pub const ENCRYPTION_CAPABLE_PEERS: &str = "encryption_capable_peers";
2239    /// Key type for persisted blocked user entries.
2240    pub const BLOCKED_USERS: &str = "blocked_users";
2241    /// Key type for the persistent per-install telemetry scrub secret.
2242    pub const SCRUB_SECRET: &str = "scrub_secret";
2243    /// Key ID for the single scrub-secret entry.
2244    pub const SCRUB_SECRET_ID: &str = "current";
2245    /// Key type for the persistent per-install Nostr transport signing secret.
2246    pub const NOSTR_SIGNING_SECRET: &str = "nostr_signing_secret";
2247    /// Key ID for the single Nostr signing-secret entry.
2248    pub const NOSTR_SIGNING_SECRET_ID: &str = "current";
2249    /// Key type for the Nostr receive watermark: the newest event `created_at`
2250    /// (unix seconds) this install has accepted from a relay.
2251    ///
2252    /// Unlike the signing secret this is *protocol-state*, not secure storage:
2253    /// it is a coarse timestamp, not key material, and losing it costs one
2254    /// wider backfill window rather than an identity.
2255    pub const NOSTR_WATERMARK: &str = "nostr_watermark";
2256    /// Key ID for the single Nostr receive-watermark entry.
2257    pub const NOSTR_WATERMARK_ID: &str = "current";
2258    /// Key type for the Nostr key-package publication slot map: which MLS key
2259    /// package currently stands in each published addressable slot.
2260    ///
2261    /// Protocol state rather than secure storage, on the same reasoning as the
2262    /// watermark: the values are slot labels and package ids, both of which are
2263    /// already public in the published record itself. Losing it costs a round
2264    /// of republication under fresh slot ids, not an identity — the stale
2265    /// records left at the old slots expire with their key packages.
2266    pub const NOSTR_KEY_PACKAGE_SLOTS: &str = "nostr_key_package_slots";
2267    /// Key ID for the single Nostr publication-slot entry.
2268    pub const NOSTR_KEY_PACKAGE_SLOTS_ID: &str = "current";
2269    /// Key type for this install's published username discovery claim.
2270    ///
2271    /// Records *which* username was last published, so a profile change or a
2272    /// switched-off feature can retract the previous claim. Without it a
2273    /// renamed install leaves its old name standing in the directory
2274    /// indefinitely, pointing at an address that is still live — the one
2275    /// failure a directory must not have, since retraction is the only control
2276    /// a claimant holds.
2277    ///
2278    /// Protocol state rather than secure storage, on the same reasoning as the
2279    /// slot map: the value is a username that this install already published
2280    /// in a public place. Losing it costs an un-retractable stale claim, which
2281    /// expires only when a resolver's second hop fails.
2282    pub const NOSTR_DISCOVERY_CLAIM: &str = "nostr_discovery_claim";
2283    /// Key ID for the single discovery-claim entry.
2284    pub const NOSTR_DISCOVERY_CLAIM_ID: &str = "current";
2285    /// Key type for the per-install key that seals sensitive protocol-state
2286    /// records at rest.
2287    ///
2288    /// Lives in *secure* storage — it is the one piece of the protocol-state
2289    /// domain that must be credential-backed, because it is what gives the
2290    /// install-scoped container's contents their confidentiality (see
2291    /// [`crate::protocol::state_crypto`]).
2292    pub const STATE_RECORD_KEY: &str = "protocol_state_record_key";
2293    /// Key ID for the single protocol-state record key entry.
2294    pub const STATE_RECORD_KEY_ID: &str = "current";
2295    /// Key type for peers we are the both-create "owner" of and are awaiting a
2296    /// group-aware decrypt from before confirming (see
2297    /// [`crate::protocol::OfflineProtocol`]'s `both_create_awaiting_decrypt`).
2298    /// Persisted so an owner restart mid-convergence cannot let a stale plaintext
2299    /// probe/ack prematurely confirm and strand the peer on a divergent group.
2300    pub const BOTH_CREATE_AWAITING_DECRYPT: &str = "both_create_awaiting_decrypt";
2301    /// Key type for the marker recording that pre-split protocol state has been
2302    /// adopted out of secure storage (see
2303    /// `OfflineProtocol::adopt_legacy_protocol_state`). Lives in *protocol
2304    /// state* storage, so a reinstall — which drops that container — correctly
2305    /// re-runs the sweep against whatever the credential store still holds.
2306    pub const STATE_ADOPTION: &str = "protocol_state_adoption";
2307    /// Key ID for the single state-adoption marker entry.
2308    pub const STATE_ADOPTION_ID: &str = "v1";
2309
2310    /// Key type for compacted replicated documents, one record per document.
2311    ///
2312    /// Key ID is `{space}/{doc}`. The space is validated by
2313    /// `offline_protocol_data::validate_space_name` and the document by
2314    /// `validate_name`; neither charset includes the separator, so the
2315    /// composed key always parses back into the two parts it was built
2316    /// from. (The space charset additionally allows `:`, so a group space
2317    /// can be named by its `group:<uuid>` id — inert here, since keys are
2318    /// parsed by stripping the space prefix and splitting on `/`.)
2319    ///
2320    /// Post-split only: deliberately absent from
2321    /// [`ADOPTABLE_STATE_KEY_TYPES`], which has no pre-split data to inherit
2322    /// for it.
2323    pub const DATA_DOCS: &str = "data_docs";
2324    /// Key type for the uncompacted commit log of a replicated document.
2325    ///
2326    /// Key ID is `{space}/{doc}/{seq:016x}`, one record per persisted commit
2327    /// batch. Append-only by construction: a commit writes a new record and
2328    /// never rewrites an existing one, which is what keeps flash churn
2329    /// proportional to what changed rather than to document size.
2330    ///
2331    /// Post-split only: deliberately absent from
2332    /// [`ADOPTABLE_STATE_KEY_TYPES`], which has no pre-split data to inherit
2333    /// for it.
2334    pub const DATA_DELTA_LOG: &str = "data_delta_log";
2335    /// Key type for per-space document indexes and compaction bookkeeping.
2336    ///
2337    /// Key ID is the space id. Sync watermarks join this record when
2338    /// replication lands; today it carries the document list and nothing
2339    /// else. Sequence numbers and sizes are derived from the delta records
2340    /// themselves at open, so this record can never disagree with the store.
2341    ///
2342    /// Post-split only: deliberately absent from
2343    /// [`ADOPTABLE_STATE_KEY_TYPES`], which has no pre-split data to inherit
2344    /// for it.
2345    pub const DATA_SPACES: &str = "data_spaces";
2346    /// Key type for per-space replication bookkeeping.
2347    ///
2348    /// Key ID is the space id. Holds the containment state the sync path
2349    /// needs to survive a crash: the digest of the blob currently being
2350    /// handed to the document engine, and the digests of blobs that were
2351    /// in flight when a previous run died.
2352    ///
2353    /// Kept out of [`DATA_SPACES`] deliberately. That record is a cache
2354    /// reconciled from `list_keys` at open, so anything in it may be
2355    /// rebuilt from the store at any time; this one records something the
2356    /// store cannot show, and rebuilding it from the listing would silently
2357    /// answer "nothing was in flight" after exactly the crash it exists to
2358    /// remember.
2359    ///
2360    /// Post-split only: deliberately absent from
2361    /// [`ADOPTABLE_STATE_KEY_TYPES`], which has no pre-split data to inherit
2362    /// for it.
2363    pub const DATA_SYNC: &str = "data_sync";
2364    /// Key type for what a replicated document's name says after a removal.
2365    ///
2366    /// Key ID is `{space}/{doc}`, the same composition [`DATA_DOCS`] uses.
2367    /// The value carries the removal floor (the document's version at the
2368    /// moment it was removed) and whether the name currently holds a
2369    /// document again.
2370    ///
2371    /// A separate category rather than a field on [`DATA_SPACES`] for the
2372    /// reason that record is a cache: it is reconciled from `list_keys` at
2373    /// open, so a removal recorded there would be rebuilt away by exactly
2374    /// the listing that still shows the records a half-finished removal
2375    /// left behind. It is written *before* those records are deleted, so a
2376    /// crash in between leaves a name this category already calls removed,
2377    /// and the next open finishes the job. The reverse order is the
2378    /// resurrection the whole mechanism exists to prevent.
2379    ///
2380    /// An absent record means a live document that has never been removed,
2381    /// so a store written before removals existed reads correctly with no
2382    /// migration.
2383    ///
2384    /// Post-split only: deliberately absent from
2385    /// [`ADOPTABLE_STATE_KEY_TYPES`], which has no pre-split data to inherit
2386    /// for it.
2387    pub const DATA_DOC_META: &str = "data_doc_meta";
2388
2389    /// Every key type that moved from secure storage into protocol-state
2390    /// storage when the two domains were split.
2391    ///
2392    /// Unlike the MLS key-type set — which is open, because OpenMLS contributes
2393    /// its own labels through `storage_adapter.rs` — this set is closed and
2394    /// declared right here, which is what makes a one-shot bulk adoption
2395    /// possible at all (see `OfflineProtocol::adopt_legacy_protocol_state`).
2396    /// A new protocol-state category added *after* the split must NOT be added
2397    /// here: there is no pre-split data for it to inherit, and listing it would
2398    /// only cost a pointless enumeration of the credential store.
2399    ///
2400    /// # Removal
2401    ///
2402    /// This list, `OfflineProtocol::adopt_legacy_protocol_state`, and the
2403    /// `STATE_ADOPTION` marker are one-shot migration scaffolding for installs
2404    /// upgrading *across* the storage split. They stop doing anything once no
2405    /// supported install can still be running a pre-split build — an install
2406    /// that skips the split release entirely still needs them, so the trigger
2407    /// is not "one release later". Delete them only when the oldest supported
2408    /// upgrade path starts at or after the release that introduced the split,
2409    /// and delete all three together: leaving the marker behind without the
2410    /// sweep would make a later re-introduction silently skip itself.
2411    pub const ADOPTABLE_STATE_KEY_TYPES: &[&str] = &[
2412        BLOCKED_USERS,
2413        OUTBOX,
2414        PENDING_MESSAGES,
2415        SESSION_STATES,
2416        WELCOME_LIFECYCLES,
2417        PEER_KEY_PACKAGES,
2418        PEER_CAPABILITIES,
2419        MEDIA_DESCRIPTORS,
2420        BOTH_CREATE_AWAITING_DECRYPT,
2421        LAMPORT_CLOCK,
2422    ];
2423}
2424
2425/// Protocol state.
2426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2427pub enum ProtocolState {
2428    /// Protocol is not started.
2429    Stopped,
2430    /// Protocol is running.
2431    Running,
2432    /// Protocol is paused (background mode).
2433    Paused,
2434}
2435
2436/// Shared state protected by mutex.
2437pub(crate) struct SharedState {
2438    /// Current protocol state.
2439    pub(crate) state: ProtocolState,
2440
2441    /// Event handlers registered by the application.
2442    pub(crate) event_handlers: Vec<EventCallback>,
2443
2444    /// Received messages queue.
2445    pub(crate) received_messages: VecDeque<Message>,
2446
2447    /// Installed telemetry context. When present, `emit_event` additionally
2448    /// forwards every protocol event to `ctx.sink` as a
2449    /// `TelemetryRecord::Protocol`, with identifier scrubbing applied per
2450    /// `ctx.config`. Set via `OfflineProtocol::install_telemetry_sink`.
2451    pub(crate) telemetry: Option<Arc<TelemetryContext>>,
2452
2453    /// Handler calls that panicked and were isolated by [`Self::emit_event`].
2454    /// Each one is an event at least one handler never saw, after the engine
2455    /// had already acted on what it reports (#514), so it is counted where a
2456    /// test can read it rather than only logged.
2457    pub(crate) handler_panics: std::sync::atomic::AtomicU64,
2458}
2459
2460impl SharedState {
2461    pub(crate) fn new() -> Self {
2462        Self {
2463            state: ProtocolState::Stopped,
2464            event_handlers: Vec::new(),
2465            received_messages: VecDeque::new(),
2466            telemetry: None,
2467            handler_panics: std::sync::atomic::AtomicU64::new(0),
2468        }
2469    }
2470
2471    pub(crate) fn emit_event(&self, event: Event) {
2472        self.notify_handlers(&event);
2473        self.forward_to_telemetry(&event);
2474    }
2475
2476    /// [`Self::emit_event`] without the telemetry sink: the app's handlers
2477    /// see the event exactly as they always have, and the pipe never does.
2478    ///
2479    /// For engine traffic that reuses an app-facing event type but is not
2480    /// what that type's telemetry column counts. A delivery acknowledgement
2481    /// for a media chunk or an internal frame (a connection request, a key
2482    /// package, a Welcome, a data-sync frame) is one: forwarded, it counted
2483    /// as a delivered message on the dashboard, once per chunk, against a
2484    /// "sent" figure that never included any of them.
2485    pub(crate) fn emit_event_to_app(&self, event: Event) {
2486        self.notify_handlers(&event);
2487    }
2488
2489    /// A message's terminal event (`MessageDelivered` or `MessageFailed`):
2490    /// always to the app's handlers, and to telemetry only when `telemetry`
2491    /// is set, which callers derive from [`OutboxEntry::app_send`]. One
2492    /// method so every settle site applies the rule the same way.
2493    pub(crate) fn emit_settlement(&self, event: Event, telemetry: bool) {
2494        self.notify_handlers(&event);
2495        if telemetry {
2496            self.forward_to_telemetry(&event);
2497        }
2498    }
2499
2500    fn notify_handlers(&self, event: &Event) {
2501        // Legacy `EventCallback` handlers run first and receive the raw
2502        // event. This preserves the pre-telemetry contract — any app that
2503        // relied on `on_event` sees exactly what it used to.
2504        //
2505        // Each handler call is panic-isolated so a faulty handler cannot
2506        // unwind through this method while a `MutexGuard<SharedState>` is
2507        // live in the caller's frame — that would poison the shared-state
2508        // mutex and silently degrade every subsequent SDK operation.
2509        for handler in &self.event_handlers {
2510            let event_for_handler = event.clone();
2511            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2512                handler(event_for_handler);
2513            }));
2514            if result.is_err() {
2515                // Counted, and named by type only: the event's fields carry
2516                // senders, peers and message content, and an embedder's own
2517                // subscriber would print them. The event is already settled
2518                // in the engine (a received message is ACKed, a delivered one
2519                // has left the outbox), so this is a message the app will not
2520                // hear about.
2521                self.handler_panics
2522                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2523                tracing::error!(
2524                    event = event.telemetry_name(),
2525                    "EventCallback panicked; this handler missed the event. Handlers must not panic, see OfflineProtocol::on_event.",
2526                );
2527            }
2528        }
2529    }
2530
2531    fn forward_to_telemetry(&self, event: &Event) {
2532        // Sink fan-out runs after, gated on an installed context. The pipe,
2533        // the one production sink, consumes every event by reference in
2534        // `dispatch_protocol_event` and reads no identifier from it, so it
2535        // never reaches the scrub below. Only a sink that declines that
2536        // borrowed offer does: `scrub_event` hashes its identifier fields per
2537        // the installed config, or with
2538        // `TelemetryConfig::with_scrub_ids(false)` borrows the event as is.
2539        //
2540        // Dispatch goes through `dispatch_record` so a panicking sink is
2541        // caught and logged rather than unwinding through the caller's live
2542        // `MutexGuard<SharedState>` — see the helper's docstring.
2543        if let Some(ctx) = &self.telemetry {
2544            // The gate comes first so a disabled pipe stops the clone too,
2545            // and the borrowed offer comes next so a sink that collects by
2546            // name never pays for an event it drops.
2547            if !ctx.enabled() || dispatch_protocol_event(&ctx.sink, event) {
2548                return;
2549            }
2550            let scrubbed = scrub_event::scrub_event(event, &ctx.scrubber);
2551            let record = TelemetryRecord::Protocol(Box::new(scrubbed.into_owned()));
2552            dispatch_record(&ctx.sink, &record);
2553        }
2554    }
2555}
2556
2557/// Locks the shared state, recovering it if an earlier holder panicked.
2558///
2559/// Recovering rather than refusing is what keeps events flowing (#514). The
2560/// callers that emit `message_received` and `message_delivered` act first
2561/// (the ACK is sent, the outbox entry removed) and lock to emit afterwards, so
2562/// a refusal here does not undo anything: it silently drops the one event
2563/// that reports what was done, and then every later one too, since a std
2564/// mutex stays poisoned for good. Nothing under this lock is left
2565/// half-written by a panic that matters: handler and sink calls, the only
2566/// foreign code run under it, are panic-isolated in
2567/// [`SharedState::emit_event`], and the remaining writes are single pushes
2568/// and pops on a queue or a field store.
2569///
2570/// Still returns a `Result`, so the call sites' existing handling stays
2571/// valid, but never `Err`.
2572pub(crate) fn lock_shared_state(
2573    state: &Arc<Mutex<SharedState>>,
2574) -> std::result::Result<std::sync::MutexGuard<'_, SharedState>, Error> {
2575    Ok(state.lock().unwrap_or_else(|poisoned| {
2576        tracing::error!("Shared state mutex was poisoned by a panic; recovering it");
2577        state.clear_poison();
2578        poisoned.into_inner()
2579    }))
2580}
2581
2582/// Provenance kept on an outbox entry so an encrypted DM can be *re-sealed*
2583/// against the peer's current MLS session on each resend, instead of replaying
2584/// the ciphertext bytes sealed at first send (which become permanently
2585/// undecryptable once the peer re-keys to a new epoch). Mirrors the fields the
2586/// pre-send [`PendingMessage`] carries, so both re-seal through the same
2587/// `prepare_outbound_content` chokepoint. Only populated for main-outbox
2588/// (non-media) encrypted DMs; absent (`None`) means verbatim replay — the
2589/// fallback for plaintext sends and media chunks.
2590///
2591/// **Memory-only by design.** This holds the message *plaintext*, so it is never
2592/// persisted (see the `#[serde(skip)]` on [`OutboxEntry::reseal`]): persisting it
2593/// would broaden plaintext-at-rest to every sent-but-unACKed encrypted DM for the
2594/// full outbox lifetime, weakening forward secrecy in exchange for only a narrow
2595/// cross-restart reseal benefit. After a restart the restored entry replays
2596/// verbatim; if that resend hits a desync, Tier 1 (un-ACK + re-key) still keeps
2597/// delivery honest rather than silently losing the message.
2598#[derive(Debug, Clone)]
2599pub(crate) struct OutboxReseal {
2600    /// Original plaintext content.
2601    pub(crate) content: String,
2602    /// Message priority.
2603    pub(crate) priority: MessagePriority,
2604    /// Reply-to message ID if applicable.
2605    pub(crate) reply_to_msg: Option<MessageId>,
2606    /// Forwarding attribution.
2607    pub(crate) forwarded_from: Option<ForwardInfo>,
2608    /// Content type of the original message.
2609    pub(crate) content_type: ContentType,
2610    /// Media metadata (cleartext-outer fallback provenance).
2611    pub(crate) media_metadata: Option<MediaMetadata>,
2612    /// Sealed-only rich extras (reply context, rich media metadata, forward
2613    /// info) — re-evaluated against current capability at re-seal time.
2614    pub(crate) rich: Option<RichSendExtras>,
2615    /// Where the bytes currently on the ladder sit in the session's sealing
2616    /// order. An acknowledgement for this message proves the peer decrypted
2617    /// that far, which is what lets later re-seals go ahead (see
2618    /// `RESEAL_GAP_BUDGET`). Set when the message is staged and on every
2619    /// re-seal; `None` when it could not be read.
2620    pub(crate) seal_mark: Option<offline_protocol_mls::SealMark>,
2621}
2622
2623#[derive(Debug, Clone, Serialize, Deserialize)]
2624pub(crate) struct OutboxEntry {
2625    pub(crate) message: Message,
2626    pub(crate) attempt_count: u32,
2627    pub(crate) first_sent_at: DateTime<Utc>,
2628    pub(crate) last_sent_at: DateTime<Utc>,
2629    pub(crate) last_transport: Option<TransportType>,
2630    /// Re-seal provenance; `None` for verbatim-replay entries (plaintext or
2631    /// media). **Memory-only** (`#[serde(skip)]`): it carries the message
2632    /// plaintext, which must never be persisted (see [`OutboxReseal`]). A
2633    /// restored entry deserializes with `reseal: None` and therefore replays
2634    /// verbatim.
2635    #[serde(skip)]
2636    pub(crate) reseal: Option<OutboxReseal>,
2637    /// The relay has handed this frame to a device push at least once
2638    /// (`MessageSent { pushed: true }`, see [`SEND_FAIL_REASON_RELAY_PUSHED`]).
2639    ///
2640    /// Sticky for the entry's lifetime, and persisted, because of what a later
2641    /// relay verdict for the same id means. The relay remembers which
2642    /// `(sender, recipient, message_id)` triples it has pushed and answers a
2643    /// retry of one with `DeliveryError` (`already_pushed`) instead of a
2644    /// second notification, and the bridges cannot tell that verdict from a
2645    /// plain "recipient offline": both reach the core as
2646    /// `recipient_unreachable`. So the reachability probe a park schedules
2647    /// earns a `DeliveryError` fifteen seconds after every push, and without
2648    /// this flag the app would be told `MessageUndeliverable` about a message
2649    /// the push may already have delivered. With it, that verdict still
2650    /// re-parks the entry (the recipient is not on the relay) but emits
2651    /// nothing app-facing. A legacy record restores as `false`, so the first
2652    /// probe after upgrading emits once; nothing is lost.
2653    #[serde(default)]
2654    pub(crate) relay_pushed: bool,
2655    /// The application sent this message: it went through the app send path
2656    /// (`send_message`, `forward_message`, a rich send), which is the path
2657    /// that reports `MessageSent`. Internal frames share the outbox and the
2658    /// acknowledgement machinery but are never set.
2659    ///
2660    /// Read when the message is acknowledged, to decide whether the delivery
2661    /// is reported to telemetry. Telemetry's delivered count is compared with
2662    /// its sent count, so both must count the same messages; counting every
2663    /// acknowledged frame put connection requests, key packages and Welcomes
2664    /// in delivered and never in sent.
2665    ///
2666    /// Persisted. A legacy record restores as `false`, so a delivery restored
2667    /// across the upgrade still reaches `on_event` and is only left out of
2668    /// telemetry.
2669    #[serde(default)]
2670    pub(crate) app_send: bool,
2671}
2672
2673#[derive(Clone)]
2674pub(crate) struct PendingMediaMetadataEntry {
2675    pub(crate) content_type: ContentType,
2676    pub(crate) media_metadata: Option<MediaMetadata>,
2677    pub(crate) last_updated_at: Instant,
2678    /// Sender of the file transfer (used to drain partial transfers on block).
2679    pub(crate) sender: String,
2680    /// Rich extras from the sealed chunk-0 plaintext. Never populated from
2681    /// wire (legacy plaintext) chunks — the sealed body is the only trusted
2682    /// carrier.
2683    pub(crate) rich_extras: Option<crate::media_envelope::MediaRichExtras>,
2684    /// The chunk-0 outer `Message` timestamp (wall-clock ms) — the sender's
2685    /// send time, surfaced on `FileReceived` for display ordering.
2686    pub(crate) timestamp_ms: i64,
2687    /// The chunk-0 outer `Message` app id, surfaced on `FileReceived` so an
2688    /// instance serving several applications can route the file. Without
2689    /// it a per-send media app id would reach the wire and stop there.
2690    pub(crate) app_id: String,
2691    /// Set when the sealed chunk-0 plaintext said this transfer belongs to
2692    /// the replicated-document layer. Its presence is what keeps every
2693    /// file-facing event of this transfer from firing: progress, completion
2694    /// and failure alike are the data layer's business, not a person's.
2695    ///
2696    /// Never populated from a legacy plaintext chunk. The field lives inside
2697    /// the sealed body precisely so an unauthenticated chunk cannot claim it.
2698    pub(crate) data_purpose: Option<crate::media_envelope::DataPurpose>,
2699}
2700
2701#[derive(Clone)]
2702pub(crate) struct OutboundMediaTransfer {
2703    pub(crate) content_type: ContentType,
2704    pub(crate) recipient: String,
2705    pub(crate) pinned_transport: TransportType,
2706    pub(crate) total_chunks: u32,
2707    pub(crate) delivered_chunks: HashSet<u32>,
2708    pub(crate) last_updated_at: Instant,
2709    pub(crate) media_metadata: Option<MediaMetadata>,
2710    /// Rich extras sealed into chunk 0 (already capability-gated at the
2711    /// `send_media_with` boundary). Kept on the transfer because chunk
2712    /// batches are (re-)encoded via `pump_media_transfers` too.
2713    pub(crate) rich_extras: Option<crate::media_envelope::MediaRichExtras>,
2714    /// Set when this SDK started the transfer for the replicated-document
2715    /// layer rather than on an application's behalf, and kept here for the
2716    /// same reason as the extras above: `pump_media_transfers` re-encodes
2717    /// later batches and has only the transfer to read from.
2718    ///
2719    /// No public send surface can produce one.
2720    pub(crate) data_purpose: Option<crate::media_envelope::DataPurpose>,
2721    /// Per-send application id, `None` for the configured one. Kept here
2722    /// for the same reason as the extras: `pump_media_transfers` builds
2723    /// later chunks from the transfer alone, and a chunk stamped with the
2724    /// configured id would be routed to a different application than
2725    /// chunk 0 on the receiving instance.
2726    pub(crate) app_id: Option<AppId>,
2727}
2728
2729/// Crash-scoped descriptor of an in-flight outbound media transfer.
2730///
2731/// Persisted (no chunk bytes — see commit 42d1b86's rationale: resurrected
2732/// chunks can never complete, and per-chunk secure-storage writes are
2733/// expensive) when a transfer starts and deleted whenever the in-memory
2734/// transfer is removed (completed, aborted, or stale-swept). A descriptor
2735/// found on restore therefore means the app died mid-transfer:
2736/// [`crate::events::Event::MediaResendRequired`] is emitted so the app can
2737/// re-supply the bytes via `send_media_with` under the same `file_id`,
2738/// validated against `file_checksum`.
2739#[derive(Clone, Serialize, Deserialize)]
2740pub(crate) struct MediaTransferDescriptor {
2741    pub(crate) file_id: String,
2742    pub(crate) recipient: String,
2743    pub(crate) file_name: String,
2744    pub(crate) file_size: u64,
2745    /// SHA-256 hex of the plaintext file bytes (same value every chunk
2746    /// carries as `FileChunk::file_checksum`).
2747    pub(crate) file_checksum: String,
2748    pub(crate) content_type: ContentType,
2749    /// Wall-clock start of the transfer; restore prunes by
2750    /// `outbox_max_lifetime_ms` age.
2751    pub(crate) queued_at: DateTime<Utc>,
2752    /// Set when the transfer belonged to the replicated-document layer.
2753    ///
2754    /// Persisted for one reason: so restore can tell these apart and NOT ask
2755    /// an application to re-supply them. There is no public API that could
2756    /// answer such a request without stripping the purpose, and a resend
2757    /// with the purpose stripped is a document snapshot delivered to the
2758    /// peer's user as a downloaded file, which is the exact outcome the
2759    /// capability gate and the envelope version exist to prevent, reached
2760    /// through this SDK's own recovery path.
2761    ///
2762    /// Serde-defaulted, so a descriptor written before this field existed
2763    /// still parses and reads as an ordinary transfer, which is what it was.
2764    #[serde(default, skip_serializing_if = "Option::is_none")]
2765    pub(crate) data_purpose: Option<crate::media_envelope::DataPurpose>,
2766    /// Per-send application id of the interrupted transfer, `None` for the
2767    /// configured one. Persisted so `MediaResendRequired` can name the
2768    /// application that must re-supply the bytes; an instance serving
2769    /// several has no other way to know. Serde-defaulted like the purpose.
2770    #[serde(default, skip_serializing_if = "Option::is_none")]
2771    pub(crate) app_id: Option<String>,
2772}
2773
2774pub(crate) enum OutboundSendPreparation {
2775    Ready(String),
2776    Queued(MessageId),
2777}
2778
2779/// Pins that every signing domain, live or reserved, is mutually non-prefixing.
2780///
2781/// # Why this test exists here, of all places
2782///
2783/// Four domains are in production and they live in three languages and two
2784/// repositories: `offline-ctrl-v1` (this crate), `offline-disc-v1` and
2785/// `offline-invite-v1` (the MLS crate), and `offline-relay-addr-v1` (the relay
2786/// server, plus hand-mirrored copies in the iOS and Android bridges). Nothing
2787/// can import all four, so this module is the one place they can be compared at
2788/// all: it is the highest crate that can see two of them, and the fourth is
2789/// pinned as a literal.
2790///
2791/// A fifth is reserved and covered here too, for the reason reservation exists:
2792/// non-prefixing is a property of the whole set, so a domain that is specified
2793/// but not yet emitted still has to be held against every other one. A guard
2794/// that watched only live domains would happily accept a new live domain that
2795/// prefixes a reserved one, and the collision would be discovered by the
2796/// implementation that finally emits it.
2797#[cfg(test)]
2798mod signing_domain_tests {
2799    use offline_protocol_mls::discovery::DISCOVERY_SIGN_DOMAIN;
2800    use offline_protocol_mls::invite::INVITE_SIGN_DOMAIN;
2801
2802    use offline_protocol_sealed::{CTRL_SIGN_DOMAIN, CTRL_SIGN_DOMAIN_V2};
2803
2804    /// The relay's address-proof domain.
2805    ///
2806    /// A literal because it is defined in the relay-server repository and
2807    /// hand-mirrored in `AddressDeclarationPolicy.swift` and
2808    /// `AddressDeclarationPolicy.kt` — there is no Rust constant in this
2809    /// workspace to import. If it ever changes there, this test does not
2810    /// notice, which is the accepted cost of a cross-repository constant and is
2811    /// why it is spelled out with this comment attached.
2812    const RELAY_ADDR_SIGN_DOMAIN: &[u8] = b"offline-relay-addr-v1";
2813
2814    /// The gateway's address-proof domain: **reserved, not yet emitted.**
2815    ///
2816    /// Specified by `docs/spec/gateway-contract.md` and registered in the
2817    /// signing-domain table of `docs/spec/username-discovery.md`. No code signs
2818    /// under it yet, which is precisely why it is pinned before anything does:
2819    /// it must be chosen against the whole set, and it must stay distinct from
2820    /// [`RELAY_ADDR_SIGN_DOMAIN`] so a proof harvested by a hostile gateway
2821    /// cannot be replayed against the relay, or the reverse.
2822    const GATEWAY_ADDR_SIGN_DOMAIN: &[u8] = b"offline-gateway-addr-v1";
2823
2824    /// No domain, live or reserved, may be a prefix of another.
2825    ///
2826    /// The canonical payload is `domain ‖ Σ(u32be(len) ‖ field)`, and the
2827    /// **domain itself is not length-prefixed**. So if one domain were a prefix
2828    /// of another, a signature made under the shorter domain could be replayed
2829    /// as one made under the longer: an attacker chooses a first field whose
2830    /// leading bytes supply the rest of the longer domain, and the two payloads
2831    /// become byte-identical. Length-prefixing the fields does not prevent it,
2832    /// because the collision happens before the first length prefix.
2833    ///
2834    /// The concrete damage this stops is recorded in the addressing work: a
2835    /// hostile relay that could make an address-proof signature verify as a
2836    /// control-frame signature would harvest a replayable control frame from
2837    /// every device that ever authenticated to it.
2838    #[test]
2839    fn signing_domains_are_mutually_non_prefixing() {
2840        let domains: [(&str, &[u8]); 6] = [
2841            ("offline-ctrl-v1", CTRL_SIGN_DOMAIN),
2842            ("offline-ctrl-v2", CTRL_SIGN_DOMAIN_V2),
2843            ("offline-disc-v1", DISCOVERY_SIGN_DOMAIN),
2844            ("offline-invite-v1", INVITE_SIGN_DOMAIN),
2845            ("offline-relay-addr-v1", RELAY_ADDR_SIGN_DOMAIN),
2846            ("offline-gateway-addr-v1", GATEWAY_ADDR_SIGN_DOMAIN),
2847        ];
2848
2849        for (a_name, a) in domains {
2850            for (b_name, b) in domains {
2851                if a_name == b_name {
2852                    continue;
2853                }
2854                // Both the constant's name and its *value* are reported: a
2855                // failure is usually caused by an edited value, and a message
2856                // naming only the constant sends the reader to the wrong place.
2857                assert!(
2858                    !a.starts_with(b),
2859                    "signing domain {} ({:?}) is a prefix of {} ({:?}), which \
2860                     lets a signature made under one verify under the other",
2861                    b_name,
2862                    String::from_utf8_lossy(b),
2863                    a_name,
2864                    String::from_utf8_lossy(a)
2865                );
2866            }
2867        }
2868    }
2869
2870    /// The literals are what the rest of the system, and every other
2871    /// implementation, actually expects. A renamed constant that still passes
2872    /// the non-prefix test above would silently invalidate every signature in
2873    /// the field, so the spellings are pinned too.
2874    #[test]
2875    fn signing_domains_have_their_published_spellings() {
2876        assert_eq!(CTRL_SIGN_DOMAIN, b"offline-ctrl-v1");
2877        assert_eq!(CTRL_SIGN_DOMAIN_V2, b"offline-ctrl-v2");
2878        assert_eq!(DISCOVERY_SIGN_DOMAIN, b"offline-disc-v1");
2879        assert_eq!(INVITE_SIGN_DOMAIN, b"offline-invite-v1");
2880        assert_eq!(RELAY_ADDR_SIGN_DOMAIN, b"offline-relay-addr-v1");
2881        assert_eq!(GATEWAY_ADDR_SIGN_DOMAIN, b"offline-gateway-addr-v1");
2882    }
2883
2884    /// All six must be distinct, which non-prefixing already implies for
2885    /// unequal strings but not for equal ones: two identical domains are
2886    /// prefixes of each other, and the loop above skips same-name pairs.
2887    #[test]
2888    fn signing_domains_are_distinct() {
2889        let domains: [&[u8]; 6] = [
2890            CTRL_SIGN_DOMAIN,
2891            CTRL_SIGN_DOMAIN_V2,
2892            DISCOVERY_SIGN_DOMAIN,
2893            INVITE_SIGN_DOMAIN,
2894            RELAY_ADDR_SIGN_DOMAIN,
2895            GATEWAY_ADDR_SIGN_DOMAIN,
2896        ];
2897        for (i, a) in domains.iter().enumerate() {
2898            for b in domains.iter().skip(i + 1) {
2899                assert_ne!(a, b, "two signing domains are the same string");
2900            }
2901        }
2902    }
2903}
2904
2905#[cfg(test)]
2906mod send_failure_classification_tests {
2907    use super::*;
2908
2909    /// Every token either producer can mint classifies to itself.
2910    ///
2911    /// This is what lets the two functions compose. A value written by
2912    /// `send_failure_token` is later re-read from a persisted welcome
2913    /// lifecycle and passed through `classify_transport_send_error`; without
2914    /// idempotence that round trip would degrade a precise token to the
2915    /// generic fallback on every emit.
2916    #[test]
2917    fn every_send_failure_token_classifies_to_itself() {
2918        for token in SEND_FAIL_REASON_TOKENS {
2919            assert_eq!(
2920                classify_transport_send_error(token),
2921                *token,
2922                "{token} must survive a re-classification"
2923            );
2924        }
2925    }
2926
2927    /// The vocabulary table really is the vocabulary.
2928    ///
2929    /// `classify_transport_send_error` answers from the table, so it cannot
2930    /// disagree with it — but `send_failure_token` matches independently, and a
2931    /// token added there and forgotten here would classify to the fallback on
2932    /// the next round trip. Walking the transport codes catches that for the
2933    /// arm most likely to grow.
2934    #[test]
2935    fn transport_error_tokens_are_in_the_vocabulary() {
2936        use offline_protocol_transport::Error as T;
2937        let cases = [
2938            T::TransportNotAvailable("ble".into()),
2939            T::PeerNotReachable("bob".into()),
2940            T::SendFailed("x".into()),
2941            T::ReceiveFailed("x".into()),
2942            T::ConfigurationError("x".into()),
2943            T::SerializationError("x".into()),
2944            T::MessageTooLarge(2, 1),
2945            T::CryptoError("x".into()),
2946            T::Other("x".into()),
2947        ];
2948        for case in cases {
2949            let token = send_failure_token(&crate::Error::Transport(case.clone()));
2950            assert!(
2951                SEND_FAIL_REASON_TOKENS.contains(&token),
2952                "{case:?} produced {token}, which is not in SEND_FAIL_REASON_TOKENS"
2953            );
2954        }
2955    }
2956
2957    /// A relay's prose is dropped and its token kept.
2958    ///
2959    /// The prefix is a cross-layer contract the bridges hardcode and core
2960    /// prefix-matches to park a DM, so it must survive verbatim; everything
2961    /// the relay appended to it must not.
2962    #[test]
2963    fn relay_prose_is_dropped_and_the_token_kept() {
2964        assert_eq!(
2965            classify_transport_send_error(
2966                "recipient_unreachable: Recipient is offline and push notification could not be sent"
2967            ),
2968            SEND_FAIL_REASON_RECIPIENT_UNREACHABLE
2969        );
2970        // The relay's real vocabulary, all of it, collapses to one token.
2971        for prose in [
2972            "Recipient connection lost and push notification could not be sent",
2973            "Push notification already sent for this message; recipient unreachable",
2974            "Recipient unreachable and the message is too large to deliver by push",
2975            "Group delivery did not settle for this recipient in time",
2976        ] {
2977            assert_eq!(
2978                classify_transport_send_error(&format!("recipient_unreachable: {prose}")),
2979                SEND_FAIL_REASON_RECIPIENT_UNREACHABLE
2980            );
2981        }
2982    }
2983
2984    /// The relay-pushed answer is its own token, not a `recipient_unreachable`
2985    /// tail. The bridges pass this literal (pinned on their side by
2986    /// `react_native_relay_parks_a_pushed_message_sent`), and reading it under
2987    /// the unreachable prefix would fast-fail connection requests and fail
2988    /// Welcomes that the push may have delivered.
2989    #[test]
2990    fn relay_pushed_is_its_own_token() {
2991        assert_eq!(SEND_FAIL_REASON_RELAY_PUSHED, "relay_pushed");
2992        assert!(!SEND_FAIL_REASON_RELAY_PUSHED.starts_with(SEND_FAIL_REASON_RECIPIENT_UNREACHABLE));
2993        assert_eq!(
2994            classify_transport_send_error("relay_pushed"),
2995            SEND_FAIL_REASON_RELAY_PUSHED
2996        );
2997    }
2998
2999    /// The mailbox tokens are their own too, for the same reason: neither may
3000    /// be read under the `recipient_unreachable` prefix, and each must
3001    /// classify to itself so a persisted record survives a round trip.
3002    #[test]
3003    fn stored_answers_are_their_own_tokens() {
3004        assert_eq!(SEND_FAIL_REASON_RELAY_STORED, "relay_stored");
3005        assert_eq!(SEND_FAIL_REASON_RELAY_PUSHED_STORED, "relay_pushed_stored");
3006        for token in [
3007            SEND_FAIL_REASON_RELAY_STORED,
3008            SEND_FAIL_REASON_RELAY_PUSHED_STORED,
3009        ] {
3010            assert!(!token.starts_with(SEND_FAIL_REASON_RECIPIENT_UNREACHABLE));
3011            assert_eq!(classify_transport_send_error(token), token);
3012        }
3013        // `relay_pushed_stored` must not be read as `relay_pushed` with a
3014        // tail: classification is exact for these, so the longer token keeps
3015        // its own meaning rather than degrading to the shorter one.
3016        assert_ne!(
3017            classify_transport_send_error(SEND_FAIL_REASON_RELAY_PUSHED_STORED),
3018            SEND_FAIL_REASON_RELAY_PUSHED
3019        );
3020    }
3021
3022    /// A push is parked in the core but is not a failed send, so the reports
3023    /// that must stay out of a carrier's failure accounting are the two exact
3024    /// push tokens. Anything else, including relay text that merely contains
3025    /// one, still counts — and `relay_stored` counts, because it answers a
3026    /// socket write that really did miss.
3027    #[test]
3028    fn only_a_relay_push_report_is_kept_out_of_carrier_failures() {
3029        use crate::OfflineProtocol;
3030        for reason in ["relay_pushed", "relay_pushed_stored"] {
3031            assert!(
3032                !OfflineProtocol::send_report_is_carrier_failure(Some(reason)),
3033                "{reason} is a push, not a failed send"
3034            );
3035        }
3036        for reason in [
3037            Some("recipient_unreachable: Recipient is offline"),
3038            Some("Internet transport send failed"),
3039            Some("relay_pushed: extra"),
3040            Some("relay_stored"),
3041            None,
3042        ] {
3043            assert!(
3044                OfflineProtocol::send_report_is_carrier_failure(reason),
3045                "{reason:?} is a send failure"
3046            );
3047        }
3048    }
3049
3050    /// Anything unrecognized fails closed to the fallback, never to itself.
3051    #[test]
3052    fn unknown_text_falls_back_and_is_never_echoed() {
3053        for raw in [
3054            "Relay rejected event: blocked",
3055            "off1qyvh9kjj4vy8f943a22qvxsct5s9ydew35v2dl2c is not connected",
3056            "",
3057        ] {
3058            let classified = classify_transport_send_error(raw);
3059            assert_eq!(classified, SEND_FAIL_REASON_TRANSPORT);
3060            assert!(
3061                SEND_FAIL_REASON_TOKENS.contains(&classified),
3062                "the fallback must itself be a token"
3063            );
3064        }
3065    }
3066
3067    /// The literals the UniFFI layer substitutes are classified too, so the
3068    /// vocabulary has exactly one source rather than two that drift.
3069    #[test]
3070    fn uniffi_substituted_literals_are_classified() {
3071        for literal in [
3072            "Internet transport send failed",
3073            "Reticulum transport send failed",
3074            "Nostr transport send failed",
3075        ] {
3076            assert_eq!(
3077                classify_transport_send_error(literal),
3078                SEND_FAIL_REASON_TRANSPORT
3079            );
3080        }
3081        assert_eq!(
3082            classify_transport_send_error("Welcome send confirmation timed out"),
3083            SEND_FAIL_REASON_CONFIRM_TIMEOUT
3084        );
3085    }
3086}
3087
3088/// Holds the spec's conformance-vector index against the files on disk.
3089///
3090/// # Why this test exists here, of all places
3091///
3092/// `docs/spec/README.md` carries a table naming every vector file and the
3093/// chapter it pins, and that table is what a second implementer reads to find
3094/// out what they can test themselves against. It is maintained by hand and
3095/// nothing compared it to the tree, so it was correct only by attention.
3096///
3097/// The failure is quiet in both directions. A vector file added without a row
3098/// is a conformance surface nobody outside this repository knows exists. A row
3099/// left behind by a moved or renamed file sends an implementer looking for
3100/// something that is not there, and the reasonable conclusion is that the
3101/// protocol has no vectors for that chapter rather than that the index is
3102/// stale.
3103///
3104/// It lives beside the signing-domain guard for the same reason that one is
3105/// here: this is the cross-cutting registry module, and the check needs no
3106/// crate's code at all, only the repository tree.
3107#[cfg(test)]
3108mod spec_vector_index_tests {
3109    use std::path::{Path, PathBuf};
3110
3111    fn repo() -> PathBuf {
3112        Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
3113    }
3114
3115    /// The one vector file that is not a conformance surface for a chapter of
3116    /// this specification.
3117    ///
3118    /// The NIP-44 vectors are the upstream specification's own, vendored for
3119    /// the Nostr carrier's sealing and pinned to the checksum that
3120    /// specification publishes. `spec/README.md` lists them anyway, with that
3121    /// stated in place of a chapter, because a reader who finds the file in the
3122    /// tree needs to know why it is different. `spec/conformance.md` does not,
3123    /// because its table is the set of surfaces this specification defines, and
3124    /// a row for someone else's vectors would make that table mean something
3125    /// looser.
3126    ///
3127    /// Named here rather than left as a silent one-way check, because an
3128    /// exemption a test does not state is indistinguishable from a test that
3129    /// was never finished.
3130    const NOT_A_CHAPTER_SURFACE: &str = "nip44.vectors.json";
3131
3132    /// The two documents that index the vectors, and what each is not required
3133    /// to name.
3134    ///
3135    /// `spec/README.md` is the table of contents a reader lands on;
3136    /// `spec/conformance.md` repeats the list with the direction each file
3137    /// pins. The duplication is deliberate, because a conformance chapter that
3138    /// sent the reader elsewhere for the list of what to test against would be
3139    /// missing its own subject. Both are checked in both directions, so the
3140    /// duplication cannot become a disagreement.
3141    const INDEXES: [(&str, &[&str]); 2] = [
3142        ("docs/spec/README.md", &[]),
3143        ("docs/spec/conformance.md", &[NOT_A_CHAPTER_SURFACE]),
3144    ];
3145
3146    /// One index document, or `None` where the repo tree is absent:
3147    /// `cargo package` cannot carry `docs/`, so a published crate's tests must
3148    /// still build.
3149    fn index(name: &str) -> Option<String> {
3150        std::fs::read_to_string(repo().join(name)).ok().or_else(|| {
3151            eprintln!("spec tree not present, skipping the vector index checks");
3152            None
3153        })
3154    }
3155
3156    /// Every vector file either index names exists.
3157    #[test]
3158    fn every_indexed_vector_file_exists() {
3159        for (doc, _) in INDEXES {
3160            let Some(text) = index(doc) else { return };
3161
3162            let mut named = 0;
3163            for token in text.split('`') {
3164                if token.ends_with(".vectors.json") && token.starts_with("crates/") {
3165                    named += 1;
3166                    assert!(
3167                        repo().join(token).is_file(),
3168                        "{doc} names {token}, which is not in the tree"
3169                    );
3170                }
3171            }
3172            assert!(
3173                named >= 8,
3174                "the scan of {doc} found only {named} vector files, so it is no \
3175                 longer reading the table and would pass against anything"
3176            );
3177        }
3178    }
3179
3180    /// Every vector file in the tree is named by the index.
3181    ///
3182    /// This is the direction that catches a surface shipped without being
3183    /// published, which is the one a reviewer cannot see: the tests pass, the
3184    /// file is real, and only an outside implementer ever notices it is
3185    /// undocumented.
3186    #[test]
3187    fn every_vector_file_in_the_tree_is_indexed() {
3188        let mut found = Vec::new();
3189        for crate_dir in std::fs::read_dir(repo().join("crates")).expect("crates/") {
3190            let data = crate_dir.expect("an entry").path().join("tests/data");
3191            let Ok(entries) = std::fs::read_dir(&data) else {
3192                continue;
3193            };
3194            for entry in entries {
3195                let path = entry.expect("an entry").path();
3196                let name = path
3197                    .file_name()
3198                    .expect("a name")
3199                    .to_string_lossy()
3200                    .to_string();
3201                if name.ends_with(".vectors.json") {
3202                    // Compared against a path written in a markdown table, so
3203                    // the separator has to be the one the document uses, not
3204                    // the one this platform builds. `Path::join` yields
3205                    // backslashes on Windows and the table is all forward
3206                    // slashes, so without the replace, every comparison below
3207                    // fails there and passes everywhere else.
3208                    //
3209                    // Falling back to the bare file name if the prefix will not
3210                    // strip would be worse than failing: the table holds full
3211                    // paths that end in that name, so `contains` would match on
3212                    // any of them and the check would quietly degrade to
3213                    // asserting the file is mentioned somewhere.
3214                    let relative = path.strip_prefix(repo()).unwrap_or_else(|_| {
3215                        panic!("{} is not under the repo root", path.display())
3216                    });
3217                    found.push(relative.to_string_lossy().replace('\\', "/"));
3218                }
3219            }
3220        }
3221
3222        assert!(
3223            !found.is_empty(),
3224            "no vector files were found, so this test proves nothing"
3225        );
3226
3227        for (doc, exempt) in INDEXES {
3228            let Some(text) = index(doc) else { return };
3229            for path in &found {
3230                if exempt.iter().any(|name| path.ends_with(name)) {
3231                    continue;
3232                }
3233                assert!(
3234                    text.contains(path),
3235                    "{path} is a conformance surface that {doc} does not list, \
3236                     so nobody outside this repository knows it exists"
3237                );
3238            }
3239        }
3240    }
3241}