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