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