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