offline_protocol/events.rs
1//! Event types and callbacks.
2
3use offline_protocol_core::{ContentType, MediaMetadata, Message, MessageId};
4use offline_protocol_services::ServiceEvent;
5use offline_protocol_transport::TransportType;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::fmt;
9use std::sync::Arc;
10
11/// Presence status for a peer.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum PresenceStatus {
15 /// Peer is online and available.
16 Online,
17 /// Peer is away / idle.
18 Away,
19 /// Peer is explicitly offline.
20 Offline,
21}
22
23/// Where a `PresenceUpdated` event came from.
24///
25/// Apps that render relay-style presence UI (e.g. a direct-chat header's
26/// "Online" / "Last seen …") should filter on `Internet` so a nearby peer's
27/// self-report can't flip a header that is defined as relay-observed.
28#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum PresenceSource {
31 /// Relay-observed presence: the relay's authoritative answer to
32 /// `CheckPresence` (`PresenceStatus` / `PresenceStatusWithLastSeen`),
33 /// or relay-derived reachability — the platform bridges also report
34 /// `offline` here when a relay `DeliveryError` names the recipient
35 /// unreachable, so a failed send can produce an `Internet`-sourced
36 /// offline event without any explicit presence query.
37 Internet,
38 /// Gateway-observed presence over the Reticulum daemon contract: a
39 /// `PresenceStatus` answer from the gateway this device is attached to,
40 /// whether solicited by the SDK's watchlist or pushed when a watched
41 /// peer's state changes.
42 ///
43 /// Named for the carrier rather than for "gateway", because that is what
44 /// [`Self::Internet`] names too: the relay is a gateway, and an app that
45 /// wants to know which carrier answered has to be able to tell them
46 /// apart. A claim from either has the same standing and the same decay.
47 Reticulum,
48 /// A peer-sent `__PRESENCE__` self-report. Transport-agnostic: it may
49 /// arrive over BLE, WiFi Direct, or even relay-forwarded frames — hence
50 /// "peer", not "mesh". Default for deserializing legacy events that
51 /// predate the field.
52 #[default]
53 Peer,
54}
55
56/// Event callback type for handling protocol events.
57pub type EventCallback = Arc<dyn Fn(Event) + Send + Sync>;
58
59/// Machine-readable reason taxonomy for welcome delivery failures.
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
62pub enum WelcomeReasonCode {
63 /// No transport was available or all transport sends failed.
64 TransportUnavailable,
65 /// The transport is up but this specific peer is unreachable on it
66 /// (e.g. the internet relay reported the recipient offline). Treated as
67 /// per-peer no-carrier: the welcome parks instead of aging.
68 PeerUnreachable,
69 /// Peer was disconnected or became unavailable during send.
70 PeerDisconnected,
71 /// Send operation timed out.
72 Timeout,
73 /// Local/internal error prevented send.
74 InternalError,
75 /// Retry budget or lifecycle TTL was exhausted.
76 RetryExhausted,
77}
78
79impl WelcomeReasonCode {
80 /// Returns the stable machine-readable reason code.
81 pub fn as_str(&self) -> &'static str {
82 match self {
83 Self::TransportUnavailable => "TRANSPORT_UNAVAILABLE",
84 Self::PeerUnreachable => "PEER_UNREACHABLE",
85 Self::PeerDisconnected => "PEER_DISCONNECTED",
86 Self::Timeout => "TIMEOUT",
87 Self::InternalError => "INTERNAL_ERROR",
88 Self::RetryExhausted => "RETRY_EXHAUSTED",
89 }
90 }
91
92 /// The settlement reason for a message dropped because the Welcome that
93 /// would have carried its session never arrived.
94 ///
95 /// Spelled out per variant rather than interpolated into a prefix so the
96 /// result is a `&'static str`: it becomes [`Event::message_failed`]'s
97 /// reason, which the telemetry pipe forwards to the ingest verbatim. See
98 /// that constructor for why the type is the guard.
99 pub fn welcome_failure_reason(&self) -> &'static str {
100 match self {
101 Self::TransportUnavailable => "Welcome delivery failed: TRANSPORT_UNAVAILABLE",
102 Self::PeerUnreachable => "Welcome delivery failed: PEER_UNREACHABLE",
103 Self::PeerDisconnected => "Welcome delivery failed: PEER_DISCONNECTED",
104 Self::Timeout => "Welcome delivery failed: TIMEOUT",
105 Self::InternalError => "Welcome delivery failed: INTERNAL_ERROR",
106 Self::RetryExhausted => "Welcome delivery failed: RETRY_EXHAUSTED",
107 }
108 }
109}
110
111/// Machine-readable taxonomy for [`Event::SecurityWarning`], so consumers can
112/// branch on a stable code instead of matching the human-readable `reason`
113/// string (which is for logs/UI and may change between versions).
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
115#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
116pub enum SecurityWarningCode {
117 /// A control message's signature verified, but the key that signed it does
118 /// not derive to the address the frame claims to come from.
119 ///
120 /// There is no benign reading. An address *is* the hash of its identity
121 /// key, so a legitimate peer's frames always re-derive to their own
122 /// address: a rotated key is a *different address*, i.e. a different peer,
123 /// not the same peer with new bytes. This is either an impersonation
124 /// attempt or a peer running a build with a broken derivation.
125 ///
126 /// Replaces `TOFU_KEY_MISMATCH`, whose remedy (`resetTofuForPeer`) no longer
127 /// exists because there is no pin to reset.
128 SenderAddressMismatch,
129 /// A control message's signed sender did not match its transport peer
130 /// identity.
131 TransportIdentityMismatch,
132 /// A control message's signature failed verification (invalid signature or
133 /// malformed metadata).
134 ControlSignatureInvalid,
135 /// An unsigned control message was rejected.
136 ///
137 /// All security-gated control traffic must be signed by the key its sender
138 /// address derives from. This is unconditional: it does not depend on
139 /// `require_transport_identity`, nor on whether the sender was seen before.
140 /// A peer that will not sign is making a claim that cannot be checked.
141 UnsignedControlRejected,
142 /// An encrypted media chunk's MLS group did not match the 1:1 session
143 /// group of the claimed wire sender — a valid ciphertext (from some
144 /// session) delivered under a different sender's name is a media
145 /// forgery/misattribution attempt.
146 MediaSenderGroupMismatch,
147 /// An outbound message left this node as plaintext because encryption is
148 /// disabled or MLS is uninitialized while `require_encryption` is `false`
149 /// (an explicit opt-out — the default fails closed). Emitted at most once
150 /// per peer per protocol instance.
151 PlaintextSend,
152 /// Inbound plaintext content (text or legacy media) was rejected by the
153 /// encryption policy: either `require_encryption` is enabled, or a
154 /// confirmed MLS session exists with the claimed sender and plaintext
155 /// from that peer is a downgrade/forgery attempt (plaintext carries no
156 /// sender authentication). Emitted at most once per peer; the per-peer
157 /// tracking set is bounded, so after a flood of forged sender ids a
158 /// peer may warn again.
159 PlaintextReceiveRejected,
160 /// An encrypted 1:1 envelope named an MLS group that is not the session
161 /// slot shared with the claimed wire sender. The text-path counterpart to
162 /// [`Self::MediaSenderGroupMismatch`]: it catches the same misattribution
163 /// on paths where MLS cannot, because the envelope failed before it
164 /// authenticated anything.
165 SessionSenderGroupMismatch,
166 /// A 1:1 MLS session was torn down and re-advertised after an epoch
167 /// desync. Expected occasionally (a genuine fork heals this way), but the
168 /// triggering frame is not authenticated — see `schedule_session_rekey` —
169 /// so a sustained rate of these for one peer indicates injected frames
170 /// rather than a real fork.
171 SessionRekeyTriggered,
172 /// A Nostr key-package publication slot could not be refilled, so cold
173 /// first contact over Nostr is degraded or unavailable until it succeeds.
174 ///
175 /// Slots are consumed locally — an init key leaves provider storage only
176 /// when *this* node processes a Welcome built against it — so consumption
177 /// itself is normal traffic, and a stranger can drive it only by actually
178 /// establishing sessions with us. What this warns about is the refill
179 /// failing (MLS or storage error), which is the failure the publication
180 /// design must never absorb silently: a stale published record makes every
181 /// stranger who fetches it build a Welcome that can never be processed.
182 NostrKeyPackageSlotExhausted,
183 /// The per-peer key-package pool hit its ceiling, so a peer was advertised
184 /// an init key another peer already holds.
185 ///
186 /// The push path normally gives each peer its own single-use init key. Past
187 /// the ceiling it reuses one instead of growing the pool without bound —
188 /// weakening forward secrecy at session establishment (one compromised init
189 /// key opens every Welcome built against it) and re-introducing the race
190 /// where the second peer to use a package finds it already consumed. Both
191 /// clear as packages are consumed or expire.
192 ///
193 /// Reaching it means a device has accumulated unconsumed advertisements:
194 /// many peers met that never established a session. Sustained emission is
195 /// the signal that the ceiling, not peer churn, is now the binding
196 /// constraint.
197 PushKeyPackagePoolExhausted,
198 /// The relay acknowledged an address declaration naming an address that is
199 /// not this node's.
200 ///
201 /// There is no benign reading. The bridge declares `local_address()` and
202 /// signs a proof over a per-connection challenge; the relay verifies that
203 /// the declared address derives from the key that signed it, and echoes
204 /// back what it bound. So the echo can only differ if the relay bound
205 /// something other than what it verified — a broken or hostile relay, or a
206 /// frame injected into the socket.
207 ///
208 /// Nothing is torn down: a relay that controls the socket already controls
209 /// everything a local refusal could protect, so the mitigation is that the
210 /// signal is loud rather than that the connection dies. What it means in
211 /// practice is that this connection's frames are attributed to an identity
212 /// this node cannot prove, so receivers strict-matching the sender against
213 /// the transport identity will reject its security-gated control traffic.
214 RelayAddressBindingMismatch,
215 /// The relay refused this connection's address declaration, so it stays
216 /// attributed by account name.
217 ///
218 /// Operational degradation, not an attack signal: the refusal path is
219 /// deliberately non-fatal on both sides, and the connection keeps working
220 /// exactly as it did before addresses existed. What is lost is *new* MLS
221 /// session establishment over the relay — `__MLS_KEY_PKG__` and
222 /// `__MLS_WELCOME__` are security-gated, so a receiver that strict-matches
223 /// the account name against the `off1…` sender rejects them, while already
224 /// established sessions keep working because `__MLS_ENC__` is data-plane.
225 ///
226 /// The relay's own text is **not** carried on the event. It is
227 /// remote-chosen, and this event's `reason` is shipped verbatim by the
228 /// telemetry scrubber, so the wording stays bounded in the device log
229 /// while the code above is the classification. The causes it distinguishes
230 /// range from unusable key material to this socket having been displaced
231 /// by a newer login; none of them changes what an app should do. No retry
232 /// is attempted — the next reconnect declares from scratch.
233 RelayAddressDeclarationRefused,
234 /// A group leaf carries a credential its own signature key does not derive
235 /// to — an identity claimed inside a group without the key to prove it.
236 ///
237 /// There is no benign reading, and unlike most codes here it accuses
238 /// someone the user is already in a room with. An address *is* the hash of
239 /// its identity key, so every honest leaf reproduces its own credential;
240 /// producing one that does not means deliberately building a leaf around
241 /// someone else's name.
242 ///
243 /// `peer_id` is **who the finding concerns, not always who to blame**. On
244 /// the three refusal sites it is the peer that delivered the forgery — the
245 /// Welcome's inviter, or the sender of the frame carrying the commit — and
246 /// never the address the forged leaf claimed. That attribution is worth
247 /// something because it is proved independently: `__GRP_MLS_WELCOME__`,
248 /// `__GRP_MLS_COMMIT__` and `__MLS_WELCOME__` are all security-gated, so
249 /// the sender signed with the key its own address derives from. On the
250 /// fourth site there is no delivering peer at all and `peer_id` is this
251 /// device's own id.
252 ///
253 /// `reason` is diagnostic text, must not be parsed, and deliberately
254 /// carries **no identifier** — the impersonated address appears only in
255 /// this device's logs. Telemetry scrubbing hashes `peer_id` and passes
256 /// `reason` through verbatim, and the identity at stake belongs to a third
257 /// party who is not even part of the exchange.
258 ///
259 /// Emitted from four sites. The first three refuse a claim *arriving*, so
260 /// nothing is installed and the frame is dropped:
261 ///
262 /// 1. joining a group Welcome whose ratchet tree contains such a leaf (the
263 /// invite is declined outright);
264 /// 2. processing a membership commit that would install one (the commit is
265 /// not merged, and is never buffered for retry);
266 /// 3. joining a 1:1 session Welcome whose ratchet tree contains one —
267 /// including when we already hold a session with that peer, where the
268 /// refusal is non-destructive and the existing session stays live (so a
269 /// `secure_session_failed` alongside this does *not* mean the working
270 /// session ended).
271 ///
272 /// The fourth is different in kind and needs a different response:
273 ///
274 /// 4. a roster read skipping a leaf **already seated in local group
275 /// state**. No wire gate can have admitted it, so it arrived by a direct
276 /// write to this device's secure store or via a group joined by a build
277 /// predating those gates. Such a leaf is kept out of every roster and
278 /// cannot speak — but it holds live group secrets and reads everything
279 /// sent to the group, which no later refusal undoes. The remedy is to
280 /// abandon the group, not to evict a member of it.
281 ///
282 /// Apps should treat a group that produces this as untrusted for
283 /// attribution — a message shown as coming from a member is exactly what
284 /// the forged leaf was for.
285 GroupLeafIdentityUnproven,
286 /// A control frame was refused for what its signature says about *when*:
287 /// stamped further in the past than this node accepts, further ahead of
288 /// this node's clock than it accepts, or carrying the older signing
289 /// payload from a peer that has proved it can produce the newer one.
290 ///
291 /// The three share a code because they share a remedy, and the remedy is
292 /// the first thing to check: **this device's own clock**. The signed
293 /// timestamp is compared against it, so a device whose clock is wrong
294 /// refuses honest peers in bulk, and the event stream then looks like a
295 /// coordinated attack rather than a local fault. A run of these naming
296 /// *many different* peers is a clock; a run naming *one* peer while others
297 /// are fine is that peer, either replaying captures or running a broken
298 /// build.
299 ///
300 /// It is the fresh-frame counterpart to
301 /// [`Self::UnsignedControlRejected`]: both refuse a frame whose signature
302 /// proves less than this node requires, one for what it omits and one for
303 /// what it fails to state. Recovery of last resort is
304 /// `security.control_freshness_enforced = false`, which returns this node
305 /// to accepting frames of any age (see issue 403 for what that gives back
306 /// to an attacker).
307 StaleControlFrame,
308 /// A gateway echoed an `AddressDeclared` naming an address that is not
309 /// this device's.
310 ///
311 /// The gateway twin of [`Self::RelayAddressBindingMismatch`], and it has
312 /// the same absence of a benign reading: the gateway verifies that the
313 /// declared address derives from the key that signed the proof, so an
314 /// echo naming anything else means it bound what it did not verify. A
315 /// session attached under an address this device does not control is how
316 /// another device's inbound traffic gets drawn here, and how the presence
317 /// answers given about that address are poisoned.
318 ///
319 /// Reported and not acted on, for the reason the relay case gives: a
320 /// gateway that owns the socket already owns everything a local teardown
321 /// would protect. What the bridges do act on is narrower and is not this
322 /// signal: they refuse to offer a carrier whose session was never bound.
323 GatewayAddressBindingMismatch,
324 /// A gateway refused this connection's address declaration.
325 ///
326 /// Unlike the relay case ([`Self::RelayAddressDeclarationRefused`]), this
327 /// is not a degraded-but-working connection. The relay keeps delivering
328 /// on established sessions in account-name space; a gateway has no such
329 /// space, so an unproved session can only be told verdicts and is never
330 /// registered as a recipient. The bridge therefore never reports the
331 /// carrier available, and this warning explains a transport that stays
332 /// down while its socket connects fine.
333 GatewayAddressDeclarationRefused,
334 /// A peer's key package was refused because this device's clock is
335 /// outside its validity window: the window has not started yet, or has
336 /// already closed.
337 ///
338 /// Like [`Self::StaleControlFrame`], the first thing to check is a clock,
339 /// and it is usually this device's. A package is valid from an hour before
340 /// it was minted until 30 days after, by the receiver's clock. So a device
341 /// more than an hour behind a peer cannot start a session with it, though
342 /// the peer, whose clock accepts this device's package, still can. Once
343 /// the gap passes 30 days each side refuses the other's package and no
344 /// session forms at all: messages and connection requests wait for as long
345 /// as the clocks disagree, and both sides report this. Phones that have not
346 /// been online are where this happens. Many different peers is this
347 /// device's clock; one peer while others are fine is that peer's.
348 ///
349 /// A window that has already closed is not always a clock: a relay can
350 /// hold a package for days, and the receiver anchors its cached expiry to
351 /// when the frame arrived. That package is discarded, as an expired one
352 /// is, and the `reason` says either cause; the next package the peer sends
353 /// replaces it. A window that has not started is kept, since it becomes
354 /// valid once the clocks agree.
355 ///
356 /// Raised on every route that admits a pending package: when it arrives,
357 /// and on the first send after a restart. The package has not proved its
358 /// sender when the window is checked, so the peer named is a claim, and
359 /// the event is reported at most once per peer.
360 KeyPackageOutsideValidityWindow,
361}
362
363impl SecurityWarningCode {
364 /// Returns the stable machine-readable reason code.
365 pub fn as_str(&self) -> &'static str {
366 match self {
367 Self::SenderAddressMismatch => "SENDER_ADDRESS_MISMATCH",
368 Self::TransportIdentityMismatch => "TRANSPORT_IDENTITY_MISMATCH",
369 Self::ControlSignatureInvalid => "CONTROL_SIGNATURE_INVALID",
370 Self::UnsignedControlRejected => "UNSIGNED_CONTROL_REJECTED",
371 Self::MediaSenderGroupMismatch => "MEDIA_SENDER_GROUP_MISMATCH",
372 Self::PlaintextSend => "PLAINTEXT_SEND",
373 Self::PlaintextReceiveRejected => "PLAINTEXT_RECEIVE_REJECTED",
374 Self::SessionSenderGroupMismatch => "SESSION_SENDER_GROUP_MISMATCH",
375 Self::SessionRekeyTriggered => "SESSION_REKEY_TRIGGERED",
376 Self::NostrKeyPackageSlotExhausted => "NOSTR_KEY_PACKAGE_SLOT_EXHAUSTED",
377 Self::PushKeyPackagePoolExhausted => "PUSH_KEY_PACKAGE_POOL_EXHAUSTED",
378 Self::RelayAddressBindingMismatch => "RELAY_ADDRESS_BINDING_MISMATCH",
379 Self::RelayAddressDeclarationRefused => "RELAY_ADDRESS_DECLARATION_REFUSED",
380 Self::GroupLeafIdentityUnproven => "GROUP_LEAF_IDENTITY_UNPROVEN",
381 Self::StaleControlFrame => "STALE_CONTROL_FRAME",
382 Self::GatewayAddressBindingMismatch => "GATEWAY_ADDRESS_BINDING_MISMATCH",
383 Self::GatewayAddressDeclarationRefused => "GATEWAY_ADDRESS_DECLARATION_REFUSED",
384 Self::KeyPackageOutsideValidityWindow => "KEY_PACKAGE_OUTSIDE_VALIDITY_WINDOW",
385 }
386 }
387}
388
389/// Machine-readable reason for DORS selection or switch (observability).
390#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
391#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
392pub enum DorsReasonCode {
393 /// First selection; no previous transport.
394 InitialSelection,
395 /// DORS selected primary (before send attempt).
396 PrimarySelected,
397 /// Primary send succeeded; active transport is now primary.
398 PrimarySuccess,
399 /// Primary failed; fallback send succeeded.
400 FallbackSuccess,
401 /// BLE → WiFi fallback succeeded (escalation applied).
402 EscalationApplied,
403 /// Previous transport unavailable; switched to best available.
404 CurrentUnavailable,
405}
406
407impl DorsReasonCode {
408 /// Returns the stable machine-readable reason code.
409 pub fn as_str(&self) -> &'static str {
410 match self {
411 Self::InitialSelection => "INITIAL_SELECTION",
412 Self::PrimarySelected => "PRIMARY_SELECTED",
413 Self::PrimarySuccess => "PRIMARY_SUCCESS",
414 Self::FallbackSuccess => "FALLBACK_SUCCESS",
415 Self::EscalationApplied => "ESCALATION_APPLIED",
416 Self::CurrentUnavailable => "CURRENT_UNAVAILABLE",
417 }
418 }
419}
420
421/// Phase of DORS escalation: recommendation (trigger boundary) vs actual transition (applied).
422#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
423#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
424pub enum DorsEscalationPhase {
425 /// DORS decided to escalate (typed trigger reason); fallback may not succeed.
426 Triggered,
427 /// BLE→WiFi fallback send succeeded; escalation was applied.
428 Applied,
429}
430
431impl DorsEscalationPhase {
432 /// Returns the stable string representation (TRIGGERED / APPLIED).
433 pub fn as_str(&self) -> &'static str {
434 match self {
435 Self::Triggered => "TRIGGERED",
436 Self::Applied => "APPLIED",
437 }
438 }
439}
440
441/// Machine-readable reason for DORS escalation (BLE→Wi‑Fi) observability.
442#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
443#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
444pub enum DorsEscalationReasonCode {
445 /// Fallback to WiFi succeeded after primary (BLE) send failed.
446 FallbackSuccess,
447 /// Escalation suggested due to retry threshold (e.g. ble_to_wifi_retry_threshold).
448 RetryThreshold,
449 /// Escalation suggested due to sustained poor BLE signal.
450 PoorSignal,
451 /// Escalation suggested due to congestion.
452 Congestion,
453 /// Escalation suggested due to low TTL on messages.
454 LowTtl,
455 /// Escalation suggested due to BLE success rate below configured minimum (quality degradation).
456 LowSuccessRate,
457}
458
459impl DorsEscalationReasonCode {
460 /// Returns the stable machine-readable reason code.
461 pub fn as_str(&self) -> &'static str {
462 match self {
463 Self::FallbackSuccess => "FALLBACK_SUCCESS",
464 Self::RetryThreshold => "RETRY_THRESHOLD",
465 Self::PoorSignal => "POOR_SIGNAL",
466 Self::Congestion => "CONGESTION",
467 Self::LowTtl => "LOW_TTL",
468 Self::LowSuccessRate => "LOW_SUCCESS_RATE",
469 }
470 }
471}
472
473/// Machine-readable reason taxonomy for inbound decryption failures.
474#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
475#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
476pub enum DecryptionFailureCode {
477 /// Incoming encrypted payload is malformed and cannot be parsed.
478 InvalidPayload,
479 /// MLS subsystem is not initialized locally.
480 NotInitialized,
481 /// Ciphertext is invalid or cannot be decrypted.
482 InvalidCiphertext,
483 /// Sender identity/signature verification failed.
484 IdentityMismatch,
485 /// Cryptographic operation failed.
486 CryptoFailure,
487 /// An encrypted message — a text frame or a media chunk — was evicted from
488 /// the pending-decryption queue (overflow or TTL expiry, or it aged out of
489 /// the persisted queue across restarts) before the sender's session became
490 /// ready. For a media chunk the file transfer it belongs to is currently
491 /// stalled; for a text message the message itself is gone locally.
492 ///
493 /// Under the deferred-ACK model this is **advisory, not terminal**: the
494 /// evicted frame was never ACKed, so a sender still retrying resends it and
495 /// a later resend re-enters the queue and can still complete once the
496 /// session confirms. Treat this as "at risk, may need a resend", not
497 /// "permanently failed" — the terminal failure signal for media is
498 /// `FileReceiveFailed`. It is emitted for text as well as for chunks: a
499 /// relay that pushes ciphertext without store-and-forward has no second
500 /// copy, so a silent text eviction was a lost message with no signal to the
501 /// app. The same is true of a hard decrypt failure while
502 /// `crypto_recovery_enabled`, which surfaces under its own code but is
503 /// equally un-ACKed and equally recoverable by a resend; see the
504 /// `MessageDecryptionFailed` docs.
505 PendingQueueDropped,
506 /// Failure class is unknown.
507 Unknown,
508}
509
510/// Forwarding attribution in events (mirrors `ForwardInfo` from core).
511#[derive(Debug, Clone, Serialize, Deserialize)]
512pub struct ForwardInfoEvent {
513 /// The original sender of the message.
514 pub original_sender: String,
515 /// The original message ID.
516 pub original_message_id: String,
517 /// The original timestamp (wall-clock ms).
518 pub original_timestamp: i64,
519 /// Number of times this message has been forwarded.
520 pub forward_count: u32,
521}
522
523impl From<&offline_protocol_core::ForwardInfo> for ForwardInfoEvent {
524 fn from(fwd: &offline_protocol_core::ForwardInfo) -> Self {
525 Self {
526 original_sender: fwd.original_sender.as_str().to_string(),
527 original_message_id: fwd.original_message_id.as_str(),
528 original_timestamp: fwd.original_timestamp.as_millis(),
529 forward_count: fwd.forward_count,
530 }
531 }
532}
533
534/// Quoted-reply context in events (mirrors `ReplyContext` from core).
535#[derive(Debug, Clone, Serialize, Deserialize)]
536pub struct ReplyContextEvent {
537 /// Sender of the message being replied to.
538 pub sender: String,
539 /// Text (or excerpt) of the message being replied to.
540 pub text: String,
541 /// Timestamp of the quoted message (wall-clock ms).
542 #[serde(default, skip_serializing_if = "Option::is_none")]
543 pub timestamp: Option<i64>,
544 /// Short human-readable label for quoted media (e.g. a file name).
545 #[serde(default, skip_serializing_if = "Option::is_none")]
546 pub reply_media_label: Option<String>,
547 /// Content type of the quoted message, as a display string.
548 #[serde(default, skip_serializing_if = "Option::is_none")]
549 pub reply_content_type: Option<String>,
550}
551
552impl From<&offline_protocol_core::ReplyContext> for ReplyContextEvent {
553 fn from(rc: &offline_protocol_core::ReplyContext) -> Self {
554 Self {
555 sender: rc.sender.as_str().to_string(),
556 text: rc.text.clone(),
557 timestamp: rc.timestamp.map(|t| t.as_millis()),
558 reply_media_label: rc.reply_media_label.clone(),
559 reply_content_type: rc.reply_content_type.clone(),
560 }
561 }
562}
563
564/// One device's verified claim to a username.
565///
566/// Every field here has already passed verification: the address derives from
567/// the public key, the record's signature verifies under that key, and the
568/// record was published under the Nostr key it names. What that proves is
569/// narrow and worth stating exactly — **this key asserts this name**. It does
570/// not prove the name belongs to the claimant, because nothing can: the
571/// directory is non-authoritative by design.
572#[derive(Clone, Debug, Serialize, Deserialize)]
573pub struct UsernameClaim {
574 /// The claimed address, in canonical `off1…` form.
575 ///
576 /// This is the value to keep. An app that stores the *name* has stored
577 /// something anyone can re-claim tomorrow; the address is self-certifying.
578 pub address: String,
579 /// The Ed25519 identity key the address derives from, base64.
580 pub public_key: String,
581 /// When the claimant signed the record, in milliseconds since the epoch.
582 ///
583 /// **Advisory.** A record is not a liveness signal — the key-package fetch
584 /// that follows it is. An old claim from a peer who has been offline for a
585 /// month is still perfectly valid, and rejecting it here would make them
586 /// unreachable by name while their key packages sit live on a relay. Sort
587 /// by it if that helps a user choose; do not filter on it.
588 pub issued_at_ms: i64,
589}
590
591/// Who removed a replicated document, on [`Event::DataDocRemoved`].
592///
593/// A fixed token this crate chooses, never a peer's words, which is what
594/// lets the telemetry scrubber pass it through unhashed. Serialises as
595/// `local` or `peer`, which is the contract every binding types against.
596#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
597#[serde(rename_all = "lowercase")]
598pub enum DocRemovedBy {
599 /// This device removed it.
600 Local,
601 /// A removal learned from the space.
602 Peer,
603}
604
605impl fmt::Display for DocRemovedBy {
606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607 f.write_str(match self {
608 Self::Local => "local",
609 Self::Peer => "peer",
610 })
611 }
612}
613
614/// Events that can occur in the protocol.
615///
616/// Note: This type implements a custom Debug that redacts sensitive fields
617/// (message content) to prevent accidental logging of sensitive data.
618#[derive(Clone, Serialize, Deserialize)]
619#[serde(tag = "type", rename_all = "snake_case")]
620pub enum Event {
621 /// A message was sent (queued for delivery).
622 MessageSent {
623 /// ID of the sent message.
624 message_id: String,
625 /// Sender's user ID.
626 sender: String,
627 /// Recipient's user ID.
628 recipient: String,
629 /// Content of the sent message.
630 content: String,
631 /// Priority of the message when sent.
632 priority: String,
633 /// Whether the message requires an acknowledgement.
634 requires_ack: bool,
635 /// When the message was queued for delivery (wall-clock, for display).
636 timestamp: i64,
637 /// Lamport logical clock value for causal ordering.
638 #[serde(default)]
639 lamport_clock: u64,
640 /// Forwarding attribution (present when this is a forwarded message).
641 #[serde(default, skip_serializing_if = "Option::is_none")]
642 forward_info: Option<ForwardInfoEvent>,
643 },
644
645 /// A message was received.
646 MessageReceived {
647 /// ID of the received message.
648 message_id: String,
649 /// Sender's user ID.
650 sender: String,
651 /// Recipient's user ID.
652 recipient: String,
653 /// Message content.
654 content: String,
655 /// Number of hops the message traversed.
656 hop_count: u8,
657 /// Transport used for final delivery.
658 transport: String,
659 /// When the message was received (wall-clock, for display).
660 timestamp: i64,
661 /// Lamport logical clock value for causal ordering.
662 #[serde(default)]
663 lamport_clock: u64,
664 /// ID of the message this is replying to (optional).
665 #[serde(skip_serializing_if = "Option::is_none")]
666 reply_to_msg: Option<String>,
667 /// Quoted-reply context (present when this message quotes another).
668 /// Boxed to keep the `Event` enum's by-value size in check.
669 #[serde(default, skip_serializing_if = "Option::is_none")]
670 reply_context: Option<Box<ReplyContextEvent>>,
671 /// The type of content (text, image, video, etc.).
672 #[serde(default)]
673 content_type: String,
674 /// Media metadata (present for non-text content).
675 #[serde(default, skip_serializing_if = "Option::is_none")]
676 media_metadata: Option<MediaMetadata>,
677 /// Forwarding attribution (present when this is a forwarded message).
678 #[serde(default, skip_serializing_if = "Option::is_none")]
679 forward_info: Option<ForwardInfoEvent>,
680 /// `true` when the content arrived MLS-encrypted and was decrypted by
681 /// this node; `false` for plaintext accepted under the
682 /// `require_encryption = false` opt-out.
683 #[serde(default)]
684 encrypted: bool,
685 /// Application id the sender stamped on this message: its configured
686 /// id, or the per-send id of a rich send.
687 ///
688 /// For an instance serving several local applications, this is what
689 /// routes the message to the right client. It is cleartext and
690 /// unsigned on the wire, so any carrier could have rewritten it
691 /// (threat model R17): route on it, never authorize on it. The
692 /// engine delivers every message whatever this says.
693 #[serde(default)]
694 app_id: String,
695 },
696
697 /// A message was successfully delivered (ACK received).
698 MessageDelivered {
699 /// ID of the delivered message.
700 message_id: String,
701 /// Milliseconds from the first transmit a carrier accepted to the
702 /// acknowledgement, including any time the message then waited for
703 /// the peer. Time before any carrier accepted it is not included.
704 latency_ms: u64,
705 /// Number of hops traversed.
706 hop_count: u8,
707 /// Transport used.
708 transport: String,
709 },
710
711 /// A message failed to deliver.
712 MessageFailed {
713 /// ID of the failed message.
714 message_id: String,
715 /// Reason for failure.
716 reason: String,
717 /// Number of retries attempted.
718 retry_count: u32,
719 },
720
721 /// An inbound encrypted message failed to decrypt on this attempt.
722 ///
723 /// **Advisory, not terminal, and emitted once per failed *attempt*.** While
724 /// `EncryptionConfig::crypto_recovery_enabled` is on (the default) a
725 /// message that fails to decrypt is not delivery-ACKed, so the sender keeps
726 /// retrying — and each resend of a DM is re-sealed against the peer's
727 /// current session, so a resend can actually land. Every failing attempt
728 /// reports again, bounded by the sender's ACK retry budget. Read this as
729 /// "this attempt did not decrypt"; the terminal signals are
730 /// [`Event::MessageFailed`] on the sender and `FileReceiveFailed` for
731 /// media.
732 MessageDecryptionFailed {
733 /// ID of the message that could not be decrypted.
734 message_id: String,
735 /// Sender's user ID.
736 sender: String,
737 /// Machine-readable decryption failure code.
738 code: DecryptionFailureCode,
739 /// Clear failure reason for application handling/logging.
740 reason: String,
741 /// When the sender sealed the frame (sender clock, ms), read from the
742 /// cleartext envelope. Unauthenticated: a hint for local heuristics,
743 /// never for security decisions. `None` when the failure is not a 1:1
744 /// decrypt attempt (pending-queue drop, unparseable envelope, group).
745 sealed_at_ms: Option<u64>,
746 /// When this device's current session with `sender` was created or
747 /// adopted (local clock, ms). `None` when there is no session, or it
748 /// was established by an SDK that did not record the time. A frame
749 /// sealed before this cannot have been sealed under this session, so
750 /// its failure says nothing about whether the two sides agree now.
751 session_established_at_ms: Option<u64>,
752 },
753
754 /// Transport was switched by DORS.
755 TransportSwitched {
756 /// Previous transport (if any).
757 from: Option<String>,
758 /// New transport.
759 to: String,
760 /// Reason for switch.
761 reason: String,
762 },
763
764 /// This device started acting as a relay — carrying traffic for other
765 /// devices that cannot reach each other directly.
766 ///
767 /// Reports observed behaviour, not capability: it fires because this
768 /// device has been forwarding, so it needs no battery feed and can fire on
769 /// a device that has never reported a level.
770 RelayPromoted {
771 /// Neighbors held when this device started relaying.
772 connection_count: usize,
773 /// Battery level at the time, or `None` when the host has reported
774 /// none — the standing does not depend on it.
775 battery_level: Option<u8>,
776 },
777
778 /// This device was demoted from relay role.
779 RelayDemoted {
780 /// Reason for demotion.
781 reason: String,
782 },
783
784 /// A new neighbor was discovered.
785 NeighborDiscovered {
786 /// The peer's canonical user id — the same value the peer supplied
787 /// as `ProtocolConfig.user_id`, on every transport. Valid directly
788 /// as the `recipient` of `send_message` / `send_connection_request`.
789 peer_id: String,
790 /// Transport used to discover.
791 transport: String,
792 /// RSSI signal strength (if available).
793 rssi: Option<i16>,
794 },
795
796 /// A neighbor was lost (disconnected).
797 NeighborLost {
798 /// Peer ID of the lost neighbor.
799 peer_id: String,
800 },
801
802 /// This device's own address is known: MLS storage was opened and the
803 /// identity key in it derived to `address`.
804 ///
805 /// Fires once per successful `initialize_mls`, before any frame can be
806 /// sent. `address` is this device's `Message.sender` from here on, and what
807 /// peers must be given to reach it. It is stable across restarts of the
808 /// same profile, so an app that already stored it will be handed the same
809 /// value rather than a new one.
810 IdentityReady {
811 /// This device's self-certifying address (`off1…`).
812 address: String,
813 },
814
815 /// Network metrics update.
816 NetworkMetrics {
817 /// Number of active neighbors.
818 neighbor_count: usize,
819 /// Number of active relays.
820 relay_count: usize,
821 /// Message delivery ratio (0.0-1.0).
822 delivery_ratio: f32,
823 /// Average message latency in milliseconds.
824 avg_latency_ms: u64,
825 },
826
827 /// File transfer progress update.
828 FileProgress {
829 /// File identifier.
830 file_id: String,
831 /// Number of chunks sent so far.
832 chunks_sent: u32,
833 /// Total number of chunks.
834 total_chunks: u32,
835 /// Progress percentage (0-100).
836 percentage: u8,
837 },
838
839 /// File was completely received.
840 FileReceived {
841 /// File identifier.
842 file_id: String,
843 /// File name.
844 file_name: String,
845 /// File size in bytes.
846 file_size: u64,
847 /// Sender's user ID.
848 sender: String,
849 /// The content type of the media (image, video, file, etc.).
850 content_type: String,
851 /// Media metadata from the first chunk (present for typed media).
852 #[serde(default, skip_serializing_if = "Option::is_none")]
853 media_metadata: Option<MediaMetadata>,
854 /// Base64-encoded reassembled file data.
855 file_data: String,
856 /// When the sender queued the transfer (chunk-0 outer message
857 /// timestamp, wall-clock ms) — for display ordering alongside
858 /// `MessageReceived.timestamp`. Absent only if the chunk-0 record
859 /// was evicted before completion.
860 #[serde(default, skip_serializing_if = "Option::is_none")]
861 timestamp: Option<i64>,
862 /// Caption text from the sealed chunk-0 rich extras.
863 #[serde(default, skip_serializing_if = "Option::is_none")]
864 caption: Option<String>,
865 /// ID of the message this media replies to (sealed chunk-0 extras).
866 #[serde(default, skip_serializing_if = "Option::is_none")]
867 reply_to_msg: Option<String>,
868 /// Quoted-reply context (sealed chunk-0 extras). Boxed to keep the
869 /// `Event` enum's by-value size in check.
870 #[serde(default, skip_serializing_if = "Option::is_none")]
871 reply_context: Option<Box<ReplyContextEvent>>,
872 /// Forwarding attribution (sealed chunk-0 extras).
873 #[serde(default, skip_serializing_if = "Option::is_none")]
874 forward_info: Option<ForwardInfoEvent>,
875 /// Application id the sender stamped on the transfer (chunk-0 outer
876 /// message), with the meaning and the cleartext caveat of
877 /// `MessageReceived.app_id`. Absent only if the chunk-0 record was
878 /// evicted before completion, like `timestamp`.
879 #[serde(default, skip_serializing_if = "Option::is_none")]
880 app_id: Option<String>,
881 },
882
883 /// An inbound file transfer was dropped before completion — the receiver
884 /// hit a resource limit (too many concurrent transfers, per-sender
885 /// quota, or the buffered-bytes budget), the reassembled file failed
886 /// its integrity checks, or the transfer went stale (no chunks within
887 /// the stale timeout). Terminal and fired at most once per transfer:
888 /// the failed transfer's remaining in-flight chunks are dropped
889 /// silently. No `FileReceived` will follow for this `file_id`; the
890 /// sender must re-send the file (under a fresh `file_id`) to retry.
891 FileReceiveFailed {
892 /// File identifier.
893 file_id: String,
894 /// File name from the chunk metadata.
895 file_name: String,
896 /// Sender's user ID.
897 sender: String,
898 /// Machine-readable reason the transfer was dropped.
899 reason: String,
900 },
901
902 /// All chunks of a media attachment were ACK-delivered.
903 MediaSent {
904 /// File identifier for tracking.
905 file_id: String,
906 /// The content type of the media.
907 content_type: String,
908 /// Recipient's user ID.
909 recipient: String,
910 },
911
912 /// An outbound media transfer was aborted before all chunks were
913 /// delivered — a chunk failed to encrypt, or a chunk failed terminally
914 /// in the outbox. No `MediaSent` will follow for this `file_id`; retry
915 /// with a new `send_media` call.
916 MediaSendFailed {
917 /// File identifier for tracking.
918 file_id: String,
919 /// Recipient's user ID.
920 recipient: String,
921 /// Reason the transfer was aborted.
922 reason: String,
923 },
924
925 /// A message was deferred due to network conditions.
926 /// The message will be retried automatically.
927 MessageDeferred {
928 /// ID of the deferred message.
929 message_id: String,
930 /// Recipient's user ID.
931 ///
932 /// Added when `reason` stopped rendering the transport error: the
933 /// counterparty used to reach apps only inside that prose, which put an
934 /// unhashed address on every telemetry record for a routine send
935 /// failure. Carried as a field so the scrubber hashes it like any
936 /// other actor id.
937 recipient: String,
938 /// Stable classification of the deferral, not a rendered error.
939 ///
940 /// One of a fixed local vocabulary (`peer_not_reachable`,
941 /// `transport_not_connected`, `transport_send_failed`, …). Branch on it
942 /// if you must, but do not parse it for detail: the underlying error —
943 /// which renders the peer — stays in the device log.
944 reason: String,
945 /// Current retry count.
946 retry_count: u32,
947 /// Next retry scheduled time (Unix timestamp ms).
948 next_retry_at: Option<i64>,
949 },
950
951 /// A retry for a previously deferred/unacked message was scheduled.
952 ///
953 /// Emitted each time the retry machinery re-queues a message after a
954 /// failed attempt (transport send error or ACK timeout). Non-terminal:
955 /// `MessageDelivered` or `MessageFailed` still settles the message.
956 MessageRetrying {
957 /// ID of the retrying message.
958 message_id: String,
959 /// Recipient's user ID.
960 recipient: String,
961 /// Retry count this schedule corresponds to.
962 retry_count: u32,
963 /// Absolute time the retry is scheduled for (Unix timestamp ms).
964 next_retry_at: i64,
965 },
966
967 /// The transport layer reported the recipient unreachable for an
968 /// in-flight message (e.g. the internet relay's DeliveryError).
969 ///
970 /// Non-terminal: the message stays in the outbox. A plain DM is
971 /// *parked* — its ACK retry budget stops burning while the peer is
972 /// provably offline — and is re-driven on reachability edges (transport
973 /// reconnect, peer discovery, presence-online; the SDK adds parked
974 /// recipients to the presence watchlist). It settles only via
975 /// `MessageDelivered` or, at outbox-lifetime expiry, `MessageFailed`.
976 /// Media chunks are not parked and keep the normal retry machinery.
977 /// May fire multiple times for the same `message_id` while the
978 /// recipient remains offline: a parked DM keeps an escalating
979 /// reachability probe on every carrier (15s → 600s cap), and each probe
980 /// that reaches the relay while the peer is still offline earns a fresh
981 /// verdict and re-emits this event. Apps must treat it as a repeatable
982 /// status signal, never as a terminal one. `file_id` is set when the
983 /// message is a chunk of an outbound media transfer.
984 MessageUndeliverable {
985 /// ID of the affected message.
986 message_id: String,
987 /// Recipient's user ID.
988 recipient: String,
989 /// Stable classification of the failure — `recipient_unreachable` on
990 /// the relay-verdict path this event is normally reached by.
991 ///
992 /// The transport's own wording used to be appended here verbatim, and
993 /// on the relay path that wording is written by the relay: unbounded
994 /// remote text, shipped beside a `recipient` the telemetry scrubber
995 /// hashes. It is now dropped at the boundary — kept in the device log,
996 /// and on the internet path still delivered raw to apps on the
997 /// bridges' `diagnostic` channel.
998 reason: String,
999 /// Owning media transfer when the message is a media chunk.
1000 #[serde(default, skip_serializing_if = "Option::is_none")]
1001 file_id: Option<String>,
1002 },
1003
1004 /// An outbound media transfer was in flight when the previous process
1005 /// died. The SDK persists only the transfer descriptor (never chunk
1006 /// bytes), so it cannot resume the transfer itself: the app must
1007 /// re-supply the file bytes via `send_media` with this `file_id` —
1008 /// they are checksum-validated against the original transfer.
1009 MediaResendRequired {
1010 /// File identifier of the interrupted transfer.
1011 file_id: String,
1012 /// Recipient's user ID.
1013 recipient: String,
1014 /// Original file name.
1015 file_name: String,
1016 /// Total file size in bytes.
1017 file_size: u64,
1018 /// Per-send application id the transfer was started with, absent
1019 /// when it used the configured one. An instance serving several
1020 /// applications asks this one for the bytes.
1021 #[serde(default, skip_serializing_if = "Option::is_none")]
1022 app_id: Option<String>,
1023 },
1024
1025 /// A pending ACK was evicted due to capacity constraints.
1026 AckEvicted {
1027 /// ID of the message whose ACK was evicted.
1028 message_id: String,
1029 /// Priority of the evicted message.
1030 priority: String,
1031 /// Reason for eviction.
1032 reason: String,
1033 },
1034
1035 /// A fragment assembly was evicted to make room for new fragments.
1036 FragmentAssemblyEvicted {
1037 /// ID of the message whose fragments were evicted.
1038 message_id: String,
1039 /// Completion percentage when evicted.
1040 completion_percent: u8,
1041 /// Reason for eviction.
1042 reason: String,
1043 },
1044
1045 /// Relay role was demoted due to battery constraints.
1046 RelayDemotedBattery {
1047 /// Battery level at time of demotion.
1048 battery_level: u8,
1049 /// Minimum required battery level.
1050 min_required: u8,
1051 },
1052
1053 /// A secure MLS session was successfully established.
1054 SecureSessionEstablished {
1055 /// Peer ID of the other party.
1056 peer_id: String,
1057 /// MLS group ID for the session.
1058 group_id: String,
1059 /// Whether this is a 1:1 session (true) or a multi-party group (false).
1060 is_session: bool,
1061 /// Whether the local device initiated the session (sent the Welcome).
1062 initiated_by_local: bool,
1063 },
1064
1065 /// Failed to establish a secure MLS session.
1066 ///
1067 /// Reports a failed *handshake attempt*, which is not the same as "the
1068 /// session with this peer is gone". One case makes the difference visible:
1069 /// a Welcome refused for carrying an unprovable identity
1070 /// ([`SecurityWarningCode::GroupLeafIdentityUnproven`], emitted alongside)
1071 /// is refused non-destructively, so any session already held with that peer
1072 /// stays live and usable. Apps must not tear down session state on this
1073 /// event alone.
1074 ///
1075 /// `reason` is diagnostic text and must not be parsed. It carries no
1076 /// identifier, of this peer or of anyone else: the telemetry scrubber
1077 /// hashes `peer_id` and ships `reason` verbatim, so every arm that fills it
1078 /// contributes either a fixed string or
1079 /// [`MlsError::privacy_safe_reason`](offline_protocol_mls::MlsError::privacy_safe_reason),
1080 /// never a rendered error. The full error stays in the device log at the
1081 /// refusal site. This is a classification, so apps get the failure *class*
1082 /// here and must look to the log for the specifics.
1083 SecureSessionFailed {
1084 /// Peer ID of the other party.
1085 peer_id: String,
1086 /// Reason for the failure.
1087 reason: String,
1088 },
1089
1090 /// Diagnostic breadcrumb for the 1:1 MLS convergence (Welcome receive /
1091 /// adopt / confirm) path. Emitted so the receiver side — which otherwise
1092 /// produces no event until it fully establishes or loudly fails — is
1093 /// observable in Metro. Pure instrumentation; carries no protocol effect.
1094 ConvergenceDiag {
1095 /// Fixed stage label, e.g. "welcome_received" or "welcome_branch".
1096 stage: String,
1097 /// Peer ID this breadcrumb concerns.
1098 peer_id: String,
1099 /// Free-form `key=value` context (counts, branch taken, errors).
1100 detail: String,
1101 },
1102
1103 /// Welcome send lifecycle entered attempted state.
1104 WelcomeSendAttempted {
1105 /// Peer identifier for this welcome lifecycle.
1106 peer_id: String,
1107 /// Welcome message identifier for lifecycle correlation.
1108 message_id: String,
1109 /// MLS group identifier associated with the welcome.
1110 group_id: String,
1111 /// 1-based send attempt number.
1112 attempt: u32,
1113 },
1114
1115 /// Welcome send lifecycle reached successful sent state.
1116 WelcomeSendSucceeded {
1117 /// Peer identifier for this welcome lifecycle.
1118 peer_id: String,
1119 /// Welcome message identifier for lifecycle correlation.
1120 message_id: String,
1121 /// MLS group identifier associated with the welcome.
1122 group_id: String,
1123 /// 1-based send attempt number.
1124 attempt: u32,
1125 },
1126
1127 /// Welcome send attempt failed and may be retried.
1128 WelcomeSendFailed {
1129 /// Peer identifier for this welcome lifecycle.
1130 peer_id: String,
1131 /// Welcome message identifier for lifecycle correlation.
1132 message_id: String,
1133 /// MLS group identifier associated with the welcome.
1134 group_id: String,
1135 /// 1-based send attempt number.
1136 attempt: u32,
1137 /// Machine-readable reason code.
1138 reason_code: WelcomeReasonCode,
1139 #[serde(skip_serializing_if = "Option::is_none")]
1140 /// Stable classification of the transport failure, when one was
1141 /// recorded — never the rendered error.
1142 ///
1143 /// Both feeders named an identifier: the platform-supplied string is
1144 /// the relay's own `DeliveryError` prose, and the locally raised one
1145 /// renders a transport error that interpolates the peer. `peer_id` and
1146 /// `group_id` beside it are hashed, so either would have undone that.
1147 /// Classified at the boundary, so the persisted record holds the token
1148 /// too — and again at each emit as a backstop. The second pass is
1149 /// unreachable today (every writer overwrites the field before its
1150 /// emit, so no record restored from an older build can carry raw text
1151 /// into an event) and kept because the field is persisted and has five
1152 /// writers: it holds the invariant if one of them ever becomes
1153 /// conditional.
1154 transport_error: Option<String>,
1155 /// Whether this failure will be retried.
1156 retryable: bool,
1157 #[serde(skip_serializing_if = "Option::is_none")]
1158 /// Next scheduled retry timestamp in Unix ms.
1159 next_retry_at: Option<i64>,
1160 },
1161
1162 /// Welcome send lifecycle reached terminal expiry.
1163 WelcomeSendExpired {
1164 /// Peer identifier for this welcome lifecycle.
1165 peer_id: String,
1166 /// Welcome message identifier for lifecycle correlation.
1167 message_id: String,
1168 /// Final attempt number when lifecycle expired.
1169 attempt: u32,
1170 /// Terminal machine-readable reason code.
1171 reason_code: WelcomeReasonCode,
1172 },
1173
1174 /// A connection request was received from another user.
1175 ConnectionRequestReceived {
1176 /// User ID of the sender.
1177 sender: String,
1178 /// Display name of the sender.
1179 sender_name: String,
1180 /// Timestamp of the request (Unix ms).
1181 timestamp: i64,
1182 /// MLS key package data (if provided for encrypted session setup).
1183 #[serde(skip_serializing_if = "Option::is_none")]
1184 key_package: Option<Vec<u8>>,
1185 /// Optional first message sent along with the request.
1186 #[serde(skip_serializing_if = "Option::is_none")]
1187 initial_message: Option<String>,
1188 },
1189
1190 /// An outbound connection request could not be delivered: the transport
1191 /// reported the recipient unreachable (e.g. the relay's DeliveryError
1192 /// for an offline peer), or the request exhausted its ACK retry budget
1193 /// (in which case a generic `MessageFailed` also fires for the same
1194 /// id). This is a status signal, not proof of permanent failure — the
1195 /// original request may still be delivered by the retry machinery if
1196 /// the peer comes back online. Apps typically surface "user is
1197 /// offline"; a user-initiated resend can therefore arrive alongside the
1198 /// retried original (the recipient sees the request event again, which
1199 /// accept/reject flows already tolerate).
1200 ConnectionRequestUndeliverable {
1201 /// Recipient the request was addressed to.
1202 recipient: String,
1203 /// Message id returned by `send_connection_request`.
1204 message_id: String,
1205 /// Failure reason, drawn from a fixed local vocabulary:
1206 /// `recipient_unreachable` on the transport verdict path, or
1207 /// `max_retries_exceeded` / `outbox_lifetime_exceeded` /
1208 /// `outbox_capacity_exceeded` on the give-up paths.
1209 ///
1210 /// The relay's wording is no longer appended to the first of these —
1211 /// it is remote-chosen text, and `recipient` beside it is hashed by
1212 /// the telemetry scrubber.
1213 reason: String,
1214 },
1215
1216 /// A previously sent connection request was accepted.
1217 ConnectionAccepted {
1218 /// User ID of the accepting party.
1219 accepted_by: String,
1220 /// Display name of the accepting party.
1221 accepted_by_name: String,
1222 /// Timestamp of the acceptance (Unix ms).
1223 timestamp: i64,
1224 /// MLS key package data (if provided for encrypted session setup).
1225 #[serde(skip_serializing_if = "Option::is_none")]
1226 key_package: Option<Vec<u8>>,
1227 },
1228
1229 /// A previously sent connection request was rejected.
1230 ConnectionRejected {
1231 /// User ID of the rejecting party.
1232 rejected_by: String,
1233 },
1234
1235 /// A previously sent connection request was cancelled by the sender.
1236 ConnectionRequestCancelled {
1237 /// User ID of the party who cancelled their request.
1238 cancelled_by: String,
1239 },
1240
1241 // --- Group (relay) events ---
1242 /// A group was created (from relay).
1243 GroupCreated {
1244 /// Group identifier.
1245 group_id: String,
1246 /// Human-readable group name.
1247 name: String,
1248 },
1249
1250 /// A message was received in a group (from relay).
1251 GroupMessageReceived {
1252 /// Group identifier.
1253 group_id: String,
1254 /// User ID of the sender.
1255 sender: String,
1256 /// Message content.
1257 content: String,
1258 /// ISO-8601 timestamp.
1259 timestamp: String,
1260 /// Unique message identifier.
1261 message_id: String,
1262 /// Optional reply-to message ID.
1263 #[serde(default, skip_serializing_if = "Option::is_none")]
1264 reply_to_msg: Option<String>,
1265 /// Forwarding attribution (present when this is a forwarded message).
1266 #[serde(default, skip_serializing_if = "Option::is_none")]
1267 forward_info: Option<ForwardInfoEvent>,
1268 /// Media metadata restored from the sealed `__RICH_V1__` body of a
1269 /// rich group message (cloud attachments — including the
1270 /// `encryption_key`/`iv` secrets, which only ever travel inside the
1271 /// group MLS ciphertext). Absent on plain group messages.
1272 #[serde(default, skip_serializing_if = "Option::is_none")]
1273 media_metadata: Option<MediaMetadata>,
1274 /// Content-type rendering hint from the sealed body (text, image,
1275 /// video, ...). Absent on plain group messages.
1276 #[serde(default, skip_serializing_if = "Option::is_none")]
1277 content_type: Option<String>,
1278 },
1279
1280 /// A member was added to a group (from relay).
1281 GroupMemberAdded {
1282 /// Group identifier.
1283 group_id: String,
1284 /// User ID of the added member.
1285 user_id: String,
1286 /// User ID of who performed the add.
1287 added_by: String,
1288 /// Human-readable group name (present when the invitee first joins).
1289 #[serde(skip_serializing_if = "Option::is_none")]
1290 group_name: Option<String>,
1291 /// Whether `added_by` was authorized to make this change.
1292 ///
1293 /// `Some(false)` means the change **did** happen — MLS accepted the
1294 /// commit and the roster really has changed — but the committer was
1295 /// not a known admin. The membership event is still emitted because
1296 /// the local roster must not diverge from MLS state; see
1297 /// [`Event::GroupUnauthorizedMembershipChange`] for the full signal.
1298 ///
1299 /// `None` (absent in JSON) means authorization was **not evaluated**
1300 /// on the path that produced this event: our own join accepted from
1301 /// a Welcome (there is no prior group state to judge the inviter
1302 /// against) and relay reconciliation frames (no authenticated
1303 /// committer to judge). Events from an older core also omit the
1304 /// field. Only `Some(_)` is a positive statement either way.
1305 ///
1306 /// The judgment is made against this member's **local replica** of
1307 /// role state, which replicates best-effort and can lag — a
1308 /// legitimate change may be flagged `Some(false)`, and different
1309 /// members can disagree about the same commit. Do not act on it
1310 /// automatically.
1311 #[serde(default, skip_serializing_if = "Option::is_none")]
1312 authorized: Option<bool>,
1313 },
1314
1315 /// A member was removed from a group (from relay).
1316 GroupMemberRemoved {
1317 /// Group identifier.
1318 group_id: String,
1319 /// User ID of the removed member.
1320 user_id: String,
1321 /// User ID of who performed the removal.
1322 removed_by: String,
1323 /// Whether this change was authorized (`None` = not evaluated on
1324 /// this path). See [`Event::GroupMemberAdded::authorized`]. On the
1325 /// relay reconciliation path the judgment applies to the frame's
1326 /// authenticated wire sender, which is not necessarily the
1327 /// `removed_by` named here.
1328 #[serde(default, skip_serializing_if = "Option::is_none")]
1329 authorized: Option<bool>,
1330 },
1331
1332 /// Group info was received (from relay).
1333 GroupInfo {
1334 /// Group identifier.
1335 group_id: String,
1336 /// Human-readable group name.
1337 name: String,
1338 /// User ID of the group creator.
1339 created_by: String,
1340 /// ISO-8601 creation timestamp.
1341 created_at: String,
1342 /// Group member list.
1343 members: Vec<GroupInfoMember>,
1344 },
1345
1346 /// User's groups list was received (from relay).
1347 UserGroups {
1348 /// List of group summaries.
1349 groups: Vec<UserGroupSummary>,
1350 },
1351
1352 /// A group operation failed (from relay).
1353 ///
1354 /// The relay's own wording is **not** carried here. `__GROUP_ERROR__` is
1355 /// a relay answer, accepted unsigned on the relay ingest path (the
1356 /// bridges inject it unattributed), so its text is chosen by whoever put
1357 /// the frame on that socket — arbitrary content, arbitrary length, and
1358 /// not something this SDK can vouch for. `reason` is a fixed code
1359 /// classified locally instead; the
1360 /// relay's exact text is logged on-device and reaches apps, when they
1361 /// want it, as the raw `GroupError` frame the bridges dual-emit on the
1362 /// server-message channel.
1363 GroupError {
1364 /// Why the operation failed, from a fixed set: `not_found` (the
1365 /// relay has no such group — invite links and relay fan-out for it
1366 /// are dead, not merely refused), `sync_denied` (the relay refused
1367 /// to register or sync the group for this caller), or `error` (any
1368 /// other refusal).
1369 reason: String,
1370 /// Group the error concerns, when the relay scoped it. Absent for
1371 /// unscoped errors.
1372 ///
1373 /// This is the group-scoping the free-text `reason` used to smuggle
1374 /// past the telemetry scrubber — as a real field it is hashed like
1375 /// every other `group_id` instead.
1376 #[serde(default, skip_serializing_if = "Option::is_none")]
1377 group_id: Option<String>,
1378 },
1379
1380 /// The relay-side registration state of a group changed.
1381 ///
1382 /// `synced: true` fires only on the relay's positive registration
1383 /// acknowledgment (a `GroupCreated` answering a registration this
1384 /// device actually sent, over the Internet transport) — including the
1385 /// idempotent re-sync ack after a membership change. It is the signal
1386 /// that relay-dependent server commands for the group (invite links,
1387 /// server-side fan-out) can be issued. `synced: false` fires when that
1388 /// trust is revoked; `reason` says why. Not emitted for groups the
1389 /// relay was never asked about.
1390 GroupRelaySyncChanged {
1391 /// MLS group identifier.
1392 group_id: String,
1393 /// Whether the relay currently holds a positively acknowledged
1394 /// registration for this group.
1395 synced: bool,
1396 /// Why the state changed: `registered` (relay ack), `error`
1397 /// (group-scoped relay error), `removed` (we were removed from the
1398 /// group), `left` (local leave), `internet_dropped` (Internet
1399 /// transport lost; re-registration re-arms on reconnect), or
1400 /// `ack_timeout` (relay never answered the registration — likely a
1401 /// relay without group support).
1402 reason: String,
1403 },
1404
1405 /// A username resolution finished, carrying **every** claim found.
1406 ///
1407 /// # The set is the whole point, and there is deliberately no "best" claim
1408 ///
1409 /// Anyone may publish any username claim, so a name resolves to a set of
1410 /// assertions, never to an answer. Even a single-device user is a set of
1411 /// one. This event is emitted exactly once per resolution and carries the
1412 /// complete set precisely so an app cannot accidentally treat the first
1413 /// arrival as the winner: there is no per-claim event to race, and no
1414 /// ordering field to mistake for a ranking.
1415 ///
1416 /// **An app MUST let the user choose.** Silently picking one claim converts
1417 /// a non-authoritative directory into an authoritative-looking one, which
1418 /// is worse than not shipping the feature: the user believes they are
1419 /// talking to the name, and the protocol only ever promised them a key.
1420 /// Present the claims, let a human confirm out of band (a QR code, a
1421 /// shared secret, a voice), and remember the address rather than the name.
1422 ///
1423 /// An empty `claims` list is an ordinary outcome: the name may be
1424 /// unclaimed, the claimant offline-published to relays we do not use, or
1425 /// every claim we saw failed verification.
1426 UsernameResolved {
1427 /// The normalized username that was resolved.
1428 username: String,
1429 /// Every claim that verified, in no meaningful order.
1430 claims: Vec<UsernameClaim>,
1431 /// How many records were seen but rejected.
1432 ///
1433 /// Non-zero is *normal*, not an error: the tag is public, anyone may
1434 /// publish to it, and junk arrives. Surfaced because a resolution that
1435 /// returns nothing while rejecting many records means something
1436 /// different from one that returns nothing having seen nothing, and an
1437 /// app showing "not found" may want to distinguish them.
1438 rejected: u32,
1439 /// How many *verified* claims were dropped at the accumulator's
1440 /// ceiling.
1441 ///
1442 /// Separate from `rejected` because it is the opposite statement: these
1443 /// records were good and are missing anyway. Without it a crowded name
1444 /// renders exactly like an uncrowded one, a clean set with nothing
1445 /// refused, which hides the single signal that a name is being
1446 /// squatted at volume. Non-zero means `claims` is a sample and no
1447 /// absence in it can be trusted.
1448 truncated: u32,
1449 },
1450
1451 /// A group message was sent to all members via mesh (MLS-encrypted fan-out).
1452 GroupMessageSent {
1453 /// MLS group identifier.
1454 group_id: String,
1455 /// Per-member message IDs from fan-out.
1456 message_ids: Vec<String>,
1457 /// Number of members the message was sent to.
1458 member_count: u32,
1459 },
1460
1461 /// A group message was only partially delivered (some members failed).
1462 GroupMessagePartialFailure {
1463 /// MLS group identifier.
1464 group_id: String,
1465 /// Members for whom send failed.
1466 failed_members: Vec<String>,
1467 /// Members for whom send succeeded.
1468 succeeded_members: Vec<String>,
1469 },
1470
1471 /// The relay's settled per-recipient delivery report for a group
1472 /// message sent via relay broadcast, after the SDK acted on it.
1473 ///
1474 /// Fires once per broadcast whose report arrived, seconds after
1475 /// `group_message_sent` (the relay reports only when its whole fan-out
1476 /// has settled — correlate by `message_id`, never by order). Members in
1477 /// `delivered` took the message over a live relay socket; members in
1478 /// `pushed` took a device push carrying the ciphertext. Every other
1479 /// MLS roster member — the ones the relay reported missed *and* the
1480 /// ones it did not know about at all — has already been re-sent a
1481 /// per-member copy through the ordinary outbox/ACK/park delivery
1482 /// ladder (`missed_reissued`), so no app action is required; the event
1483 /// is delivery observability, not a failure signal. Not emitted when
1484 /// the report itself is lost — the SDK then re-broadcasts (bounded)
1485 /// and finally downgrades the whole message to per-member fan-out,
1486 /// which reports per-member like any mesh send.
1487 GroupMessageDeliveryReport {
1488 /// MLS group identifier.
1489 group_id: String,
1490 /// The logical group message id, as returned by the send and echoed
1491 /// by the relay.
1492 message_id: String,
1493 /// Members whose relay socket write was confirmed (a relay-side
1494 /// write-ack, not an end-to-end delivery ACK).
1495 delivered: Vec<String>,
1496 /// Members offline at the relay who took a device push.
1497 pushed: Vec<String>,
1498 /// Members re-sent a per-member copy because the relay reached them
1499 /// neither way (or never knew them).
1500 missed_reissued: Vec<String>,
1501 },
1502
1503 /// Rich media metadata was dropped from an outbound group message
1504 /// because the group is not fully rich-capable (not every member
1505 /// advertised sealed rich payload support, or the local kill switch
1506 /// disabled it). The text was still sent; members receive it without
1507 /// the media attachment. Apps can use this to warn the sender that an
1508 /// attachment did not go through.
1509 GroupRichExtrasDropped {
1510 /// MLS group identifier.
1511 group_id: String,
1512 /// Members not known to parse the sealed rich payload — the ones
1513 /// holding the seal gate closed. Absence of knowledge and known
1514 /// non-support are indistinguishable here. Empty when the drop was
1515 /// caused by the local `rich_payload_enabled` kill switch instead.
1516 /// The SDK probes these members for their capability automatically;
1517 /// apps can retry the send once a later attempt stops dropping.
1518 unknown_members: Vec<String>,
1519 },
1520
1521 /// An MLS membership change was applied that its committer was not
1522 /// authorized to make.
1523 ///
1524 /// The change **has been applied** — MLS authenticated the committer as a
1525 /// group member and accepted the commit, and the local epoch advanced with
1526 /// it. The SDK's admin model is an application-layer overlay on top of MLS
1527 /// (RFC 9420 leaves membership access control to the application), enforced
1528 /// on the *sending* side; refusing the change on receipt would mean
1529 /// refusing the merge, which permanently forks this member away from every
1530 /// peer that accepted it. So the change stands and is reported here instead.
1531 ///
1532 /// **This signal can false-positive.** "Unauthorized" is judged against
1533 /// this member's local replica of role state, which replicates
1534 /// best-effort (a joiner receives a point-in-time snapshot, role changes
1535 /// ride unreconciled mesh notifications) and can lag — so a legitimate
1536 /// change, e.g. a voluntary leave committed by a member whose admin role
1537 /// this device has not yet learned, may be reported here, and different
1538 /// members can disagree about the same commit.
1539 ///
1540 /// Apps should treat this as a moderation signal for a *human* admin: an
1541 /// admin can undo the change with `remove_from_group` /
1542 /// `invite_to_group`. Never reverse a change automatically off a single
1543 /// member's event — corroborate first. A member added this way can read
1544 /// all subsequent group traffic until removed.
1545 ///
1546 /// Reports are rate-limited per `(group, committer)`: a repeat within a
1547 /// short window is not re-emitted (divergent role metadata would
1548 /// otherwise re-fire it on every commit), but every affected
1549 /// [`Event::GroupMemberAdded`] / [`Event::GroupMemberRemoved`] still
1550 /// carries `authorized: Some(false)`.
1551 ///
1552 /// Known limitation: the member *removed* by an unauthorized Remove does
1553 /// not receive this event — it can no longer decrypt the commit that
1554 /// removed it, and it refuses to trust a non-admin's unencrypted claim
1555 /// that it was removed. Only the remaining members report the removal.
1556 GroupUnauthorizedMembershipChange {
1557 /// MLS group identifier.
1558 group_id: String,
1559 /// The MLS-authenticated committer that made the change.
1560 committer: String,
1561 /// Members the commit added, sorted. Empty for a pure removal.
1562 added: Vec<String>,
1563 /// Members the commit removed, sorted. Empty for a pure addition.
1564 removed: Vec<String>,
1565 /// Why the change was judged unauthorized. Currently
1566 /// `"sender_not_admin"` (the committer is not a known admin) or
1567 /// `"affected_member_mismatch"` (an admin committed, but the commit's
1568 /// unencrypted framing named a different member than the MLS delta
1569 /// actually changed). Treat as an opaque string — values may be added.
1570 reason: String,
1571 /// Whether the commit was *refused* rather than applied.
1572 ///
1573 /// `false` (the default configuration) means the membership change
1574 /// happened and is being reported after the fact — `added`/`removed`
1575 /// describe real roster changes an admin can undo. `true` means
1576 /// `GroupConfig::enforce_admin_commits` was on and the commit was
1577 /// rejected before merging: no roster event accompanies this one, no
1578 /// membership changed locally, and `added`/`removed` describe what the
1579 /// commit *would* have done.
1580 ///
1581 /// A `true` here also means this device declined an epoch every
1582 /// accepting member advanced to, so it can no longer decrypt that
1583 /// group's traffic and needs re-inviting — treat it as a partition
1584 /// alarm, not just a moderation signal. Note the re-invite arrives as
1585 /// a Welcome, which is not policy-gated, so it readmits us to the
1586 /// group *including* whatever the refused commit did; the change
1587 /// itself still has to be resolved separately.
1588 enforced: bool,
1589 },
1590
1591 /// An epoch fork was detected in a group — concurrent commits caused
1592 /// members to diverge onto different MLS branches. The deterministic
1593 /// leader will attempt automatic resolution via a key-update commit.
1594 GroupEpochForkDetected {
1595 /// MLS group identifier.
1596 group_id: String,
1597 /// Our local epoch when the fork was detected, or `None` if MLS
1598 /// state was unavailable at detection time.
1599 local_epoch: Option<u64>,
1600 },
1601
1602 /// An epoch fork was successfully resolved by the leader issuing a
1603 /// resync commit that re-established a canonical epoch.
1604 ///
1605 /// Members in `failed_members` could not be reached with the resolution
1606 /// commit and may still be on a forked branch — the application layer
1607 /// should consider re-inviting them.
1608 GroupEpochForkResolved {
1609 /// MLS group identifier.
1610 group_id: String,
1611 /// The new canonical epoch after resolution.
1612 resolved_epoch: u64,
1613 /// Members to whom the resolution commit could not be sent.
1614 /// These members may still be on a forked epoch branch and
1615 /// may need a re-invite to rejoin the canonical group state.
1616 failed_members: Vec<String>,
1617 },
1618
1619 /// A member's role was changed in a group.
1620 GroupRoleChanged {
1621 /// Group identifier.
1622 group_id: String,
1623 /// User ID of the member whose role changed.
1624 user_id: String,
1625 /// New role (e.g. "admin", "member").
1626 new_role: String,
1627 /// User ID of who changed the role.
1628 changed_by: String,
1629 },
1630
1631 /// A group was renamed.
1632 GroupRenamed {
1633 /// Group identifier.
1634 group_id: String,
1635 /// New group name.
1636 new_name: String,
1637 /// Previous group name (if known).
1638 old_name: Option<String>,
1639 /// User ID of who renamed the group.
1640 renamed_by: String,
1641 },
1642
1643 // --- Service discovery ---
1644 /// A service was discovered on the mesh in response to a discovery query.
1645 ServiceDiscovered {
1646 /// Query ID that triggered this discovery.
1647 query_id: String,
1648 /// Service identifier.
1649 service_id: String,
1650 /// Service version.
1651 version: String,
1652 /// Peer user ID of the provider.
1653 provider_peer_id: String,
1654 /// Service capabilities.
1655 capabilities: HashMap<String, String>,
1656 /// Number of hops from the provider.
1657 hop_count: u8,
1658 },
1659
1660 /// A service request was received from another peer.
1661 ServiceRequestReceived {
1662 /// Unique request identifier.
1663 request_id: String,
1664 /// Service identifier being invoked.
1665 service_id: String,
1666 /// Method name or action.
1667 method: String,
1668 /// Request body (JSON or arbitrary string).
1669 body: String,
1670 /// Peer user ID of the requester.
1671 sender: String,
1672 /// Whether the request arrived sealed inside the 1:1 MLS session with
1673 /// `sender`, so no device that carried it could read the body and the
1674 /// session authenticated `sender`. `false` means it arrived as signed
1675 /// plaintext, readable by every hop (threat model R9).
1676 #[serde(default)]
1677 encrypted: bool,
1678 },
1679
1680 /// A response to a service request was received.
1681 ServiceResponseReceived {
1682 /// Request identifier this response corresponds to.
1683 request_id: String,
1684 /// Service identifier.
1685 service_id: String,
1686 /// Status: "ok", "not_found", or "error".
1687 status: String,
1688 /// Response body.
1689 body: String,
1690 /// Peer user ID of the provider.
1691 provider_peer_id: String,
1692 /// Whether the response arrived sealed inside the 1:1 MLS session
1693 /// with the provider. `false` means it arrived as signed plaintext,
1694 /// readable by every hop (threat model R9).
1695 #[serde(default)]
1696 encrypted: bool,
1697 },
1698
1699 // --- Presence, typing, and read receipts ---
1700 /// A peer's presence status was updated.
1701 PresenceUpdated {
1702 /// Peer whose presence changed.
1703 peer_id: String,
1704 /// Presence status.
1705 status: PresenceStatus,
1706 /// Timestamp of the update (Unix ms).
1707 timestamp: i64,
1708 /// When the peer was last seen (Unix ms), if the source knows it —
1709 /// e.g. the internet relay's PresenceStatusWithLastSeen. Absent for
1710 /// peer-sent `__PRESENCE__` updates.
1711 #[serde(default, skip_serializing_if = "Option::is_none")]
1712 last_seen_ms: Option<i64>,
1713 /// Which channel produced this update: the internet relay's
1714 /// authoritative answer, or a peer-sent self-report. Always
1715 /// serialized; defaults to `peer` when deserializing legacy events.
1716 #[serde(default)]
1717 source: PresenceSource,
1718 },
1719
1720 /// A typing indicator was received from a peer.
1721 TypingIndicatorReceived {
1722 /// User who is typing (or stopped typing).
1723 sender: String,
1724 /// Conversation identifier, echoed back verbatim from the sender.
1725 ///
1726 /// Opaque to the SDK — never parsed or routed on. Whatever key the
1727 /// sender chose (conventionally a peer address for a DM, the group
1728 /// id for a group) arrives here unchanged.
1729 conversation_id: String,
1730 /// Whether the user is currently typing.
1731 is_typing: bool,
1732 /// Timestamp of the indicator (Unix ms).
1733 timestamp: i64,
1734 },
1735
1736 /// A read receipt was received from a peer.
1737 ReadReceiptReceived {
1738 /// User who read the messages.
1739 sender: String,
1740 /// IDs of the messages that were read.
1741 message_ids: Vec<String>,
1742 /// Timestamp when the messages were read (Unix ms).
1743 timestamp: i64,
1744 },
1745
1746 // --- DORS observability (OFF-258) ---
1747 /// DORS scored all available transports for this decision cycle.
1748 DorsScoreUpdated {
1749 /// Transport type and score pairs (descending by score).
1750 scores: Vec<(String, f32)>,
1751 },
1752 /// DORS selected a transport for the current message.
1753 DorsTransportSelected {
1754 /// Previous transport (if any); provides decision boundary context.
1755 from: Option<String>,
1756 /// Selected transport.
1757 transport: String,
1758 /// Typed reason for selection (initial vs primary selected).
1759 reason_code: DorsReasonCode,
1760 /// Score of the selected transport (supplemental).
1761 score: f32,
1762 },
1763 /// DORS switched from one transport to another. Emitted only when active transport
1764 /// actually changes after a successful send.
1765 DorsTransportSwitched {
1766 /// Previous transport (if any).
1767 from: Option<String>,
1768 /// New transport (now active).
1769 to: String,
1770 /// Stable enum-backed reason for the transition.
1771 reason_code: DorsReasonCode,
1772 /// Optional human-readable context (e.g. "primary failed, fallback succeeded").
1773 #[serde(skip_serializing_if = "Option::is_none")]
1774 reason_detail: Option<String>,
1775 },
1776 /// DORS escalation from BLE to Wi‑Fi. Use `phase` to distinguish recommendation vs applied.
1777 DorsEscalationTriggered {
1778 /// TRIGGERED = DORS decided to escalate (reason = trigger); APPLIED = fallback succeeded.
1779 phase: DorsEscalationPhase,
1780 /// Transport we escalated from (e.g. "ble").
1781 from: String,
1782 /// Transport we escalated to (e.g. "wifiDirect").
1783 to: String,
1784 /// Stable enum-backed reason code.
1785 reason_code: DorsEscalationReasonCode,
1786 /// Optional human-readable context.
1787 #[serde(skip_serializing_if = "Option::is_none")]
1788 reason_detail: Option<String>,
1789 },
1790
1791 /// A security-relevant anomaly was detected (e.g. sender spoofing, a
1792 /// signing key that does not derive to its claimed address, an unsigned
1793 /// control message).
1794 SecurityWarning {
1795 /// Peer ID involved in the warning.
1796 peer_id: String,
1797 /// Stable machine-readable classification of the warning. Branch on
1798 /// this rather than parsing `reason`.
1799 reason_code: SecurityWarningCode,
1800 /// Human-readable description of the security issue.
1801 reason: String,
1802 },
1803
1804 /// A message was relayed (forwarded for a third party).
1805 MessageRelayed {
1806 /// ID of the relayed message.
1807 message_id: String,
1808 /// Original sender.
1809 sender: String,
1810 /// Intended recipient.
1811 recipient: String,
1812 /// Current hop count after increment.
1813 hop_count: u8,
1814 /// Remaining TTL after decrement.
1815 remaining_ttl: u8,
1816 },
1817
1818 /// A user was blocked. Emitted for local UI notification only.
1819 UserBlocked {
1820 /// User ID that was blocked.
1821 user_id: String,
1822 },
1823
1824 /// A user was unblocked. Emitted for local UI notification only.
1825 UserUnblocked {
1826 /// User ID that was unblocked.
1827 user_id: String,
1828 },
1829
1830 /// A replicated document changed and the change reached storage.
1831 ///
1832 /// Emitted after the delta is durable, never before: an application that
1833 /// re-renders on this event is then rendering state that survives a
1834 /// crash.
1835 DataChanged {
1836 /// The space the document belongs to.
1837 space_id: String,
1838 /// The document that changed.
1839 doc_id: String,
1840 /// Size of the change that was persisted.
1841 delta_bytes: u64,
1842 },
1843
1844 /// A replicated document was removed from every replica of its space.
1845 ///
1846 /// Distinct from a document merely disappearing locally: this one is a
1847 /// decision that travels. It fires when this device removes a document
1848 /// and when it learns of a removal from a peer, so an application
1849 /// holding the document open can close it either way.
1850 ///
1851 /// A removal loses to a concurrent edit, so a document may come back
1852 /// after this fires. That arrives as an ordinary `DataChanged` on a
1853 /// document the application thought was gone, which is the honest
1854 /// report: the edit won, and its contents are the contents.
1855 DataDocRemoved {
1856 /// The space the document belonged to.
1857 space_id: String,
1858 /// The document that was removed.
1859 doc_id: String,
1860 /// Who removed it: `local` for this device, `peer` for a removal
1861 /// learned from the space.
1862 by: DocRemovedBy,
1863 },
1864
1865 /// A replicated document is approaching the per-document size cap.
1866 ///
1867 /// Fires while there is still room to act. Without it the cap would be a
1868 /// cliff an application meets for the first time as a failed write.
1869 DataDocSizeWarning {
1870 /// The space the document belongs to.
1871 space_id: String,
1872 /// The document approaching the cap.
1873 doc_id: String,
1874 /// Its current compacted size.
1875 compacted_bytes: u64,
1876 /// The cap it is measured against.
1877 cap_bytes: u64,
1878 },
1879
1880 /// A peer asked for the bytes behind an attachment reference.
1881 ///
1882 /// The SDK does not hold blob bytes, so it cannot answer this on its
1883 /// own: the application either supplies them with
1884 /// `data_provide_attachment` or says it cannot with
1885 /// `data_decline_attachment`. An application that handles neither leaves
1886 /// the asking peer with a reference it can see and never open, which is
1887 /// why declining is a first-class answer rather than silence.
1888 DataAttachmentRequested {
1889 /// The space the request arrived in.
1890 space_id: String,
1891 /// The peer that asked.
1892 peer_id: String,
1893 /// Lowercase hex SHA-256 of the blob they want.
1894 hash: String,
1895 },
1896
1897 /// Attachment bytes arrived and matched the hash that asked for them.
1898 ///
1899 /// The bytes are handed over rather than stored: blobs never enter
1900 /// protocol state, so where this file lives is the application's
1901 /// decision and its storage.
1902 DataAttachmentReceived {
1903 /// The space the attachment arrived in.
1904 space_id: String,
1905 /// The peer that supplied it.
1906 peer_id: String,
1907 /// Lowercase hex SHA-256 of the blob, verified against these bytes.
1908 hash: String,
1909 /// The blob, base64.
1910 data: String,
1911 },
1912
1913 /// A fetch ended without bytes.
1914 ///
1915 /// Either the peer answered that it no longer holds the blob, or the
1916 /// transfer carrying it failed. Both are ordinary: an attachment
1917 /// reference outlives the bytes it names, because the reference
1918 /// replicates and the bytes do not.
1919 DataAttachmentUnavailable {
1920 /// The space the fetch was made in.
1921 space_id: String,
1922 /// The peer that was asked.
1923 peer_id: String,
1924 /// Lowercase hex SHA-256 that was asked for.
1925 hash: String,
1926 /// Why it ended: `declined` (the peer answered that it no longer
1927 /// holds the blob), `timeout`, `evicted` (displaced by newer
1928 /// fetches), `hash_mismatch`, `peer_gone` (the peer was blocked,
1929 /// forgotten, or came back without the replication capability), or a
1930 /// transfer
1931 /// failure reason. A fixed token this crate chooses, never a peer's
1932 /// words.
1933 reason: String,
1934 },
1935
1936 /// A document cannot be replicated, in any form this protocol has.
1937 ///
1938 /// The honest report of a real dead end rather than a warning in a log
1939 /// nobody reads. It fires when a document is too large for a sync frame
1940 /// and the peer cannot carry it over the media path either, which leaves
1941 /// two replicas that will not converge and no further rung to try.
1942 DataDocUnsyncable {
1943 /// The space the document belongs to.
1944 space_id: String,
1945 /// The document that cannot be sent.
1946 doc_id: String,
1947 /// Size of the encoding that had nowhere to go.
1948 bytes: u64,
1949 /// Why it could not be sent.
1950 reason: String,
1951 },
1952}
1953
1954/// Member entry in GroupInfo.
1955#[derive(Debug, Clone, Serialize, Deserialize)]
1956pub struct GroupInfoMember {
1957 /// User ID of the member.
1958 pub user_id: String,
1959 /// Role within the group (e.g. "admin", "member").
1960 pub role: String,
1961 /// ISO-8601 timestamp when the member joined.
1962 pub joined_at: String,
1963}
1964
1965/// Group summary in UserGroups.
1966#[derive(Debug, Clone, Serialize, Deserialize)]
1967pub struct UserGroupSummary {
1968 /// Group identifier.
1969 pub group_id: String,
1970 /// Human-readable group name.
1971 pub name: String,
1972 /// ISO-8601 creation timestamp.
1973 pub created_at: String,
1974}
1975
1976impl Event {
1977 /// Creates a MessageSent event.
1978 pub fn message_sent(message: &Message) -> Self {
1979 use offline_protocol_core::MessagePriority;
1980
1981 let priority = match message.priority {
1982 MessagePriority::Low => "low",
1983 MessagePriority::Medium => "medium",
1984 MessagePriority::High => "high",
1985 MessagePriority::Critical => "critical",
1986 };
1987
1988 let forward_info = message.forwarded_from.as_ref().map(ForwardInfoEvent::from);
1989
1990 Self::MessageSent {
1991 message_id: message.id.as_str(),
1992 sender: message.sender.as_str().to_string(),
1993 recipient: message.recipient.as_str().to_string(),
1994 content: message.content.clone(),
1995 priority: priority.to_string(),
1996 requires_ack: message.requires_ack,
1997 timestamp: message.timestamp.as_millis(),
1998 lamport_clock: message.lamport_clock.value(),
1999 forward_info,
2000 }
2001 }
2002
2003 /// Creates a MessageDelivered event.
2004 pub fn message_delivered(
2005 message_id: MessageId,
2006 latency_ms: u64,
2007 hop_count: u8,
2008 transport: TransportType,
2009 ) -> Self {
2010 Self::MessageDelivered {
2011 message_id: message_id.as_str(),
2012 latency_ms,
2013 hop_count,
2014 transport: transport.to_string(),
2015 }
2016 }
2017
2018 /// Creates a MessageFailed event.
2019 ///
2020 /// `reason` is `&'static str` for the same load-bearing reason
2021 /// [`Event::message_deferred`] is, and
2022 /// `protocol::types::classify_transport_send_error` returns one: the
2023 /// telemetry pipe forwards this field to the ingest verbatim, without the
2024 /// scrubber, because the classification taxonomy is the ingest's. A
2025 /// `String` parameter makes `format!("{err}")` at a call site
2026 /// representable, and the transport layer renders the counterparty into
2027 /// its own error text, so that one interpolation would ship a peer
2028 /// address beside identifiers the same record hashes. A static string
2029 /// cannot carry runtime data, which makes the mistake unrepresentable
2030 /// rather than merely discouraged. Callers with a classified failure pass
2031 /// the token; callers with a fixed condition pass its literal.
2032 pub fn message_failed(message_id: MessageId, reason: &'static str, retry_count: u32) -> Self {
2033 Self::MessageFailed {
2034 message_id: message_id.as_str(),
2035 reason: reason.to_string(),
2036 retry_count,
2037 }
2038 }
2039
2040 /// Creates a MessageDecryptionFailed event.
2041 pub fn message_decryption_failed(
2042 message_id: MessageId,
2043 sender: String,
2044 code: DecryptionFailureCode,
2045 reason: String,
2046 ) -> Self {
2047 Self::MessageDecryptionFailed {
2048 message_id: message_id.as_str(),
2049 sender,
2050 code,
2051 reason,
2052 sealed_at_ms: None,
2053 session_established_at_ms: None,
2054 }
2055 }
2056
2057 /// Creates a MessageDecryptionFailed event for a failed 1:1 decrypt,
2058 /// carrying the frame's seal time and the current session's
2059 /// establishment time (see the variant's fields).
2060 pub fn message_decryption_failed_for_frame(
2061 message_id: MessageId,
2062 sender: String,
2063 code: DecryptionFailureCode,
2064 reason: String,
2065 sealed_at_ms: u64,
2066 session_established_at_ms: Option<u64>,
2067 ) -> Self {
2068 Self::MessageDecryptionFailed {
2069 message_id: message_id.as_str(),
2070 sender,
2071 code,
2072 reason,
2073 sealed_at_ms: Some(sealed_at_ms),
2074 session_established_at_ms,
2075 }
2076 }
2077
2078 /// Creates a TransportSwitched event.
2079 pub fn transport_switched(
2080 from: Option<TransportType>,
2081 to: TransportType,
2082 reason: String,
2083 ) -> Self {
2084 Self::TransportSwitched {
2085 from: from.map(|t| t.to_string()),
2086 to: to.to_string(),
2087 reason,
2088 }
2089 }
2090
2091 /// Creates a RelayPromoted event.
2092 pub fn relay_promoted(connection_count: usize, battery_level: Option<u8>) -> Self {
2093 Self::RelayPromoted {
2094 connection_count,
2095 battery_level,
2096 }
2097 }
2098
2099 /// Creates a RelayDemoted event.
2100 ///
2101 /// `&'static str` for the reason given on [`Event::message_failed`]: the
2102 /// telemetry pipe forwards this field raw.
2103 pub fn relay_demoted(reason: &'static str) -> Self {
2104 Self::RelayDemoted {
2105 reason: reason.to_string(),
2106 }
2107 }
2108
2109 /// Creates a NeighborDiscovered event.
2110 pub fn neighbor_discovered(
2111 peer_id: String,
2112 transport: TransportType,
2113 rssi: Option<i16>,
2114 ) -> Self {
2115 Self::NeighborDiscovered {
2116 peer_id,
2117 transport: format!("{:?}", transport),
2118 rssi,
2119 }
2120 }
2121
2122 /// Creates a NeighborLost event.
2123 pub fn neighbor_lost(peer_id: String) -> Self {
2124 Self::NeighborLost { peer_id }
2125 }
2126
2127 /// Creates an IdentityReady event.
2128 pub fn identity_ready(address: impl Into<String>) -> Self {
2129 Self::IdentityReady {
2130 address: address.into(),
2131 }
2132 }
2133
2134 /// Creates a NetworkMetrics event.
2135 pub fn network_metrics(
2136 neighbor_count: usize,
2137 relay_count: usize,
2138 delivery_ratio: f32,
2139 avg_latency_ms: u64,
2140 ) -> Self {
2141 Self::NetworkMetrics {
2142 neighbor_count,
2143 relay_count,
2144 delivery_ratio,
2145 avg_latency_ms,
2146 }
2147 }
2148
2149 /// Creates a FileProgress event.
2150 pub fn file_progress(file_id: String, chunks_sent: u32, total_chunks: u32) -> Self {
2151 let percentage = if total_chunks > 0 {
2152 ((chunks_sent as f32 / total_chunks as f32) * 100.0) as u8
2153 } else {
2154 0
2155 };
2156
2157 Self::FileProgress {
2158 file_id,
2159 chunks_sent,
2160 total_chunks,
2161 percentage,
2162 }
2163 }
2164
2165 /// Creates a FileReceived event.
2166 #[allow(clippy::too_many_arguments)]
2167 pub fn file_received(
2168 file_id: String,
2169 file_name: String,
2170 file_size: u64,
2171 sender: String,
2172 content_type: ContentType,
2173 media_metadata: Option<MediaMetadata>,
2174 file_data: Vec<u8>,
2175 timestamp: Option<i64>,
2176 caption: Option<String>,
2177 reply_to_msg: Option<String>,
2178 reply_context: Option<&offline_protocol_core::ReplyContext>,
2179 forward_info: Option<&offline_protocol_core::ForwardInfo>,
2180 app_id: Option<String>,
2181 ) -> Self {
2182 use base64::{engine::general_purpose::STANDARD, Engine};
2183 Self::FileReceived {
2184 file_id,
2185 file_name,
2186 file_size,
2187 sender,
2188 content_type: content_type.to_string(),
2189 media_metadata,
2190 file_data: STANDARD.encode(&file_data),
2191 timestamp,
2192 caption,
2193 reply_to_msg,
2194 reply_context: reply_context.map(|rc| Box::new(ReplyContextEvent::from(rc))),
2195 forward_info: forward_info.map(ForwardInfoEvent::from),
2196 app_id,
2197 }
2198 }
2199
2200 /// Creates a FileReceiveFailed event.
2201 pub fn file_receive_failed(
2202 file_id: String,
2203 file_name: String,
2204 sender: String,
2205 reason: String,
2206 ) -> Self {
2207 Self::FileReceiveFailed {
2208 file_id,
2209 file_name,
2210 sender,
2211 reason,
2212 }
2213 }
2214
2215 /// Creates a MediaSent event.
2216 pub fn media_sent(file_id: String, content_type: ContentType, recipient: String) -> Self {
2217 Self::MediaSent {
2218 file_id,
2219 content_type: content_type.to_string(),
2220 recipient,
2221 }
2222 }
2223
2224 /// Creates a MediaSendFailed event.
2225 pub fn media_send_failed(file_id: String, recipient: String, reason: String) -> Self {
2226 Self::MediaSendFailed {
2227 file_id,
2228 recipient,
2229 reason,
2230 }
2231 }
2232
2233 /// Creates a MessageDeferred event.
2234 pub fn message_deferred(
2235 message_id: MessageId,
2236 recipient: String,
2237 reason: &'static str,
2238 retry_count: u32,
2239 next_retry_at: Option<i64>,
2240 ) -> Self {
2241 Self::MessageDeferred {
2242 message_id: message_id.as_str(),
2243 recipient,
2244 reason: reason.to_string(),
2245 retry_count,
2246 next_retry_at,
2247 }
2248 }
2249
2250 /// Creates a MessageRetrying event.
2251 pub fn message_retrying(
2252 message_id: MessageId,
2253 recipient: String,
2254 retry_count: u32,
2255 next_retry_at: i64,
2256 ) -> Self {
2257 Self::MessageRetrying {
2258 message_id: message_id.as_str(),
2259 recipient,
2260 retry_count,
2261 next_retry_at,
2262 }
2263 }
2264
2265 /// Creates a MessageUndeliverable event.
2266 pub fn message_undeliverable(
2267 message_id: MessageId,
2268 recipient: String,
2269 reason: &'static str,
2270 file_id: Option<String>,
2271 ) -> Self {
2272 Self::MessageUndeliverable {
2273 message_id: message_id.as_str(),
2274 recipient,
2275 reason: reason.to_string(),
2276 file_id,
2277 }
2278 }
2279
2280 /// Creates a MediaResendRequired event.
2281 pub fn media_resend_required(
2282 file_id: String,
2283 recipient: String,
2284 file_name: String,
2285 file_size: u64,
2286 app_id: Option<String>,
2287 ) -> Self {
2288 Self::MediaResendRequired {
2289 file_id,
2290 recipient,
2291 file_name,
2292 file_size,
2293 app_id,
2294 }
2295 }
2296
2297 /// Creates an AckEvicted event.
2298 pub fn ack_evicted(message_id: MessageId, priority: &str, reason: String) -> Self {
2299 Self::AckEvicted {
2300 message_id: message_id.as_str(),
2301 priority: priority.to_string(),
2302 reason,
2303 }
2304 }
2305
2306 /// Creates a FragmentAssemblyEvicted event.
2307 pub fn fragment_assembly_evicted(
2308 message_id: String,
2309 completion_percent: u8,
2310 reason: String,
2311 ) -> Self {
2312 Self::FragmentAssemblyEvicted {
2313 message_id,
2314 completion_percent,
2315 reason,
2316 }
2317 }
2318
2319 /// Creates a RelayDemotedBattery event.
2320 pub fn relay_demoted_battery(battery_level: u8, min_required: u8) -> Self {
2321 Self::RelayDemotedBattery {
2322 battery_level,
2323 min_required,
2324 }
2325 }
2326
2327 /// Creates a SecureSessionEstablished event.
2328 pub fn secure_session_established(
2329 peer_id: String,
2330 group_id: String,
2331 is_session: bool,
2332 initiated_by_local: bool,
2333 ) -> Self {
2334 Self::SecureSessionEstablished {
2335 peer_id,
2336 group_id,
2337 is_session,
2338 initiated_by_local,
2339 }
2340 }
2341
2342 /// Creates a SecureSessionFailed event.
2343 pub fn secure_session_failed(peer_id: String, reason: String) -> Self {
2344 Self::SecureSessionFailed { peer_id, reason }
2345 }
2346
2347 /// Creates a ConvergenceDiag event (1:1 MLS convergence instrumentation).
2348 pub fn convergence_diag(stage: String, peer_id: String, detail: String) -> Self {
2349 Self::ConvergenceDiag {
2350 stage,
2351 peer_id,
2352 detail,
2353 }
2354 }
2355
2356 /// Creates a WelcomeSendAttempted event.
2357 pub fn welcome_send_attempted(
2358 peer_id: String,
2359 message_id: String,
2360 group_id: String,
2361 attempt: u32,
2362 ) -> Self {
2363 Self::WelcomeSendAttempted {
2364 peer_id,
2365 message_id,
2366 group_id,
2367 attempt,
2368 }
2369 }
2370
2371 /// Creates a WelcomeSendSucceeded event.
2372 pub fn welcome_send_succeeded(
2373 peer_id: String,
2374 message_id: String,
2375 group_id: String,
2376 attempt: u32,
2377 ) -> Self {
2378 Self::WelcomeSendSucceeded {
2379 peer_id,
2380 message_id,
2381 group_id,
2382 attempt,
2383 }
2384 }
2385
2386 /// Creates a WelcomeSendFailed event.
2387 #[allow(clippy::too_many_arguments)]
2388 pub fn welcome_send_failed(
2389 peer_id: String,
2390 message_id: String,
2391 group_id: String,
2392 attempt: u32,
2393 reason_code: WelcomeReasonCode,
2394 transport_error: Option<&'static str>,
2395 retryable: bool,
2396 next_retry_at: Option<i64>,
2397 ) -> Self {
2398 Self::WelcomeSendFailed {
2399 peer_id,
2400 message_id,
2401 group_id,
2402 attempt,
2403 reason_code,
2404 transport_error: transport_error.map(str::to_string),
2405 retryable,
2406 next_retry_at,
2407 }
2408 }
2409
2410 /// Creates a WelcomeSendExpired event.
2411 pub fn welcome_send_expired(
2412 peer_id: String,
2413 message_id: String,
2414 attempt: u32,
2415 reason_code: WelcomeReasonCode,
2416 ) -> Self {
2417 Self::WelcomeSendExpired {
2418 peer_id,
2419 message_id,
2420 attempt,
2421 reason_code,
2422 }
2423 }
2424
2425 /// Creates a ConnectionRequestReceived event.
2426 pub fn connection_request_received(
2427 sender: String,
2428 sender_name: String,
2429 timestamp: i64,
2430 key_package: Option<Vec<u8>>,
2431 initial_message: Option<String>,
2432 ) -> Self {
2433 Self::ConnectionRequestReceived {
2434 sender,
2435 sender_name,
2436 timestamp,
2437 key_package,
2438 initial_message,
2439 }
2440 }
2441
2442 /// Creates a ConnectionRequestUndeliverable event.
2443 pub fn connection_request_undeliverable(
2444 recipient: String,
2445 message_id: String,
2446 reason: &'static str,
2447 ) -> Self {
2448 Self::ConnectionRequestUndeliverable {
2449 recipient,
2450 message_id,
2451 reason: reason.to_string(),
2452 }
2453 }
2454
2455 /// Creates a ConnectionAccepted event.
2456 pub fn connection_accepted(
2457 accepted_by: String,
2458 accepted_by_name: String,
2459 timestamp: i64,
2460 key_package: Option<Vec<u8>>,
2461 ) -> Self {
2462 Self::ConnectionAccepted {
2463 accepted_by,
2464 accepted_by_name,
2465 timestamp,
2466 key_package,
2467 }
2468 }
2469
2470 /// Creates a ConnectionRejected event.
2471 pub fn connection_rejected(rejected_by: String) -> Self {
2472 Self::ConnectionRejected { rejected_by }
2473 }
2474
2475 /// Creates a ConnectionRequestCancelled event.
2476 pub fn connection_request_cancelled(cancelled_by: String) -> Self {
2477 Self::ConnectionRequestCancelled { cancelled_by }
2478 }
2479
2480 /// Creates a PresenceUpdated event for a peer-sent `__PRESENCE__`
2481 /// self-report (`source: peer`).
2482 pub fn presence_updated(peer_id: String, status: PresenceStatus, timestamp: i64) -> Self {
2483 Self::PresenceUpdated {
2484 peer_id,
2485 status,
2486 timestamp,
2487 last_seen_ms: None,
2488 source: PresenceSource::Peer,
2489 }
2490 }
2491
2492 /// Creates a PresenceUpdated event carrying a last-seen timestamp
2493 /// (relay-sourced presence, `source: internet`).
2494 pub fn presence_updated_with_last_seen(
2495 peer_id: String,
2496 status: PresenceStatus,
2497 timestamp: i64,
2498 last_seen_ms: Option<i64>,
2499 ) -> Self {
2500 Self::presence_updated_from(
2501 peer_id,
2502 status,
2503 timestamp,
2504 last_seen_ms,
2505 PresenceSource::Internet,
2506 )
2507 }
2508
2509 /// Creates a PresenceUpdated event for a gateway answer, naming which
2510 /// carrier answered.
2511 ///
2512 /// The relay is one gateway among others now, so the source is a
2513 /// parameter rather than a constant. It is still not free-form: a
2514 /// peer-sent self-report goes through [`Self::presence_updated`], which
2515 /// is the only way to produce `PresenceSource::Peer`, so a carrier answer
2516 /// can never be mislabelled as one.
2517 pub fn presence_updated_from(
2518 peer_id: String,
2519 status: PresenceStatus,
2520 timestamp: i64,
2521 last_seen_ms: Option<i64>,
2522 source: PresenceSource,
2523 ) -> Self {
2524 Self::PresenceUpdated {
2525 peer_id,
2526 status,
2527 timestamp,
2528 last_seen_ms,
2529 source,
2530 }
2531 }
2532
2533 /// Creates a TypingIndicatorReceived event.
2534 pub fn typing_indicator_received(
2535 sender: String,
2536 conversation_id: String,
2537 is_typing: bool,
2538 timestamp: i64,
2539 ) -> Self {
2540 Self::TypingIndicatorReceived {
2541 sender,
2542 conversation_id,
2543 is_typing,
2544 timestamp,
2545 }
2546 }
2547
2548 /// Creates a ReadReceiptReceived event.
2549 pub fn read_receipt_received(sender: String, message_ids: Vec<String>, timestamp: i64) -> Self {
2550 Self::ReadReceiptReceived {
2551 sender,
2552 message_ids,
2553 timestamp,
2554 }
2555 }
2556
2557 /// Creates a GroupCreated event.
2558 pub fn group_created(group_id: String, name: String) -> Self {
2559 Self::GroupCreated { group_id, name }
2560 }
2561
2562 /// Creates a GroupMessageReceived event.
2563 #[allow(clippy::too_many_arguments)]
2564 pub fn group_message_received(
2565 group_id: String,
2566 sender: String,
2567 content: String,
2568 timestamp: String,
2569 message_id: String,
2570 reply_to_msg: Option<String>,
2571 forward_info: Option<ForwardInfoEvent>,
2572 media_metadata: Option<MediaMetadata>,
2573 content_type: Option<String>,
2574 ) -> Self {
2575 Self::GroupMessageReceived {
2576 group_id,
2577 sender,
2578 content,
2579 timestamp,
2580 message_id,
2581 reply_to_msg,
2582 forward_info,
2583 media_metadata,
2584 content_type,
2585 }
2586 }
2587
2588 /// Creates a GroupMemberAdded event.
2589 pub fn group_member_added(
2590 group_id: String,
2591 user_id: String,
2592 added_by: String,
2593 group_name: Option<String>,
2594 authorized: Option<bool>,
2595 ) -> Self {
2596 Self::GroupMemberAdded {
2597 group_id,
2598 user_id,
2599 added_by,
2600 group_name,
2601 authorized,
2602 }
2603 }
2604
2605 /// Creates a GroupMemberRemoved event.
2606 pub fn group_member_removed(
2607 group_id: String,
2608 user_id: String,
2609 removed_by: String,
2610 authorized: Option<bool>,
2611 ) -> Self {
2612 Self::GroupMemberRemoved {
2613 group_id,
2614 user_id,
2615 removed_by,
2616 authorized,
2617 }
2618 }
2619
2620 /// Creates a GroupRoleChanged event.
2621 pub fn group_role_changed(
2622 group_id: String,
2623 user_id: String,
2624 new_role: String,
2625 changed_by: String,
2626 ) -> Self {
2627 Self::GroupRoleChanged {
2628 group_id,
2629 user_id,
2630 new_role,
2631 changed_by,
2632 }
2633 }
2634
2635 /// Creates a GroupRenamed event.
2636 pub fn group_renamed(
2637 group_id: String,
2638 new_name: String,
2639 old_name: Option<String>,
2640 renamed_by: String,
2641 ) -> Self {
2642 Self::GroupRenamed {
2643 group_id,
2644 new_name,
2645 old_name,
2646 renamed_by,
2647 }
2648 }
2649
2650 /// Creates a GroupInfo event.
2651 pub fn group_info(
2652 group_id: String,
2653 name: String,
2654 created_by: String,
2655 created_at: String,
2656 members: Vec<GroupInfoMember>,
2657 ) -> Self {
2658 Self::GroupInfo {
2659 group_id,
2660 name,
2661 created_by,
2662 created_at,
2663 members,
2664 }
2665 }
2666
2667 /// Creates a UserGroups event.
2668 pub fn user_groups(groups: Vec<UserGroupSummary>) -> Self {
2669 Self::UserGroups { groups }
2670 }
2671
2672 /// Creates a GroupError event.
2673 ///
2674 /// `reason` must be a locally-minted code, never relay text — callers on
2675 /// the wire path get theirs from `GroupErrorPayload::classify_reason`.
2676 pub fn group_error(reason: String, group_id: Option<String>) -> Self {
2677 Self::GroupError { reason, group_id }
2678 }
2679
2680 /// Creates a GroupRelaySyncChanged event.
2681 pub fn group_relay_sync_changed(group_id: String, synced: bool, reason: &str) -> Self {
2682 Self::GroupRelaySyncChanged {
2683 group_id,
2684 synced,
2685 reason: reason.to_string(),
2686 }
2687 }
2688
2689 /// Creates a GroupMessageSent event.
2690 pub fn group_message_sent(
2691 group_id: String,
2692 message_ids: Vec<String>,
2693 member_count: u32,
2694 ) -> Self {
2695 Self::GroupMessageSent {
2696 group_id,
2697 message_ids,
2698 member_count,
2699 }
2700 }
2701
2702 /// Creates a GroupMessagePartialFailure event.
2703 pub fn group_message_partial_failure(
2704 group_id: String,
2705 failed_members: Vec<String>,
2706 succeeded_members: Vec<String>,
2707 ) -> Self {
2708 Self::GroupMessagePartialFailure {
2709 group_id,
2710 failed_members,
2711 succeeded_members,
2712 }
2713 }
2714
2715 /// Creates a GroupMessageDeliveryReport event.
2716 pub fn group_message_delivery_report(
2717 group_id: String,
2718 message_id: String,
2719 delivered: Vec<String>,
2720 pushed: Vec<String>,
2721 missed_reissued: Vec<String>,
2722 ) -> Self {
2723 Self::GroupMessageDeliveryReport {
2724 group_id,
2725 message_id,
2726 delivered,
2727 pushed,
2728 missed_reissued,
2729 }
2730 }
2731
2732 /// Creates a GroupRichExtrasDropped event.
2733 pub fn group_rich_extras_dropped(group_id: String, unknown_members: Vec<String>) -> Self {
2734 Self::GroupRichExtrasDropped {
2735 group_id,
2736 unknown_members,
2737 }
2738 }
2739
2740 /// Creates a GroupUnauthorizedMembershipChange event.
2741 pub fn group_unauthorized_membership_change(
2742 group_id: String,
2743 committer: String,
2744 added: Vec<String>,
2745 removed: Vec<String>,
2746 reason: String,
2747 enforced: bool,
2748 ) -> Self {
2749 Self::GroupUnauthorizedMembershipChange {
2750 group_id,
2751 committer,
2752 added,
2753 removed,
2754 reason,
2755 enforced,
2756 }
2757 }
2758
2759 /// Creates a GroupEpochForkDetected event.
2760 pub fn group_epoch_fork_detected(group_id: String, local_epoch: Option<u64>) -> Self {
2761 Self::GroupEpochForkDetected {
2762 group_id,
2763 local_epoch,
2764 }
2765 }
2766
2767 /// Creates a GroupEpochForkResolved event.
2768 pub fn group_epoch_fork_resolved(
2769 group_id: String,
2770 resolved_epoch: u64,
2771 failed_members: Vec<String>,
2772 ) -> Self {
2773 Self::GroupEpochForkResolved {
2774 group_id,
2775 resolved_epoch,
2776 failed_members,
2777 }
2778 }
2779
2780 /// Creates a ServiceDiscovered event.
2781 pub fn service_discovered(
2782 query_id: String,
2783 service_id: String,
2784 version: String,
2785 provider_peer_id: String,
2786 capabilities: HashMap<String, String>,
2787 hop_count: u8,
2788 ) -> Self {
2789 Self::ServiceDiscovered {
2790 query_id,
2791 service_id,
2792 version,
2793 provider_peer_id,
2794 capabilities,
2795 hop_count,
2796 }
2797 }
2798
2799 /// Creates a ServiceRequestReceived event for a request that arrived as
2800 /// signed plaintext (`encrypted: false`).
2801 pub fn service_request_received(
2802 request_id: String,
2803 service_id: String,
2804 method: String,
2805 body: String,
2806 sender: String,
2807 ) -> Self {
2808 Self::ServiceRequestReceived {
2809 request_id,
2810 service_id,
2811 method,
2812 body,
2813 sender,
2814 encrypted: false,
2815 }
2816 }
2817
2818 /// Creates a ServiceResponseReceived event for a response that arrived as
2819 /// signed plaintext (`encrypted: false`).
2820 pub fn service_response_received(
2821 request_id: String,
2822 service_id: String,
2823 status: String,
2824 body: String,
2825 provider_peer_id: String,
2826 ) -> Self {
2827 Self::ServiceResponseReceived {
2828 request_id,
2829 service_id,
2830 status,
2831 body,
2832 provider_peer_id,
2833 encrypted: false,
2834 }
2835 }
2836
2837 /// Creates a DorsScoreUpdated event (DORS observability).
2838 pub fn dors_score_updated(scores: Vec<(String, f32)>) -> Self {
2839 Self::DorsScoreUpdated { scores }
2840 }
2841
2842 /// Creates a DorsTransportSelected event (DORS observability).
2843 pub fn dors_transport_selected(
2844 from: Option<String>,
2845 transport: String,
2846 reason_code: DorsReasonCode,
2847 score: f32,
2848 ) -> Self {
2849 Self::DorsTransportSelected {
2850 from,
2851 transport,
2852 reason_code,
2853 score,
2854 }
2855 }
2856
2857 /// Creates a DorsTransportSwitched event (DORS observability).
2858 /// Emitted only when active transport actually changes after a successful send.
2859 pub fn dors_transport_switched(
2860 from: Option<String>,
2861 to: String,
2862 reason_code: DorsReasonCode,
2863 reason_detail: Option<String>,
2864 ) -> Self {
2865 Self::DorsTransportSwitched {
2866 from,
2867 to,
2868 reason_code,
2869 reason_detail,
2870 }
2871 }
2872
2873 /// Creates a DorsEscalationTriggered event (DORS observability).
2874 /// Use phase Triggered at the DORS trigger boundary, Applied when fallback succeeds.
2875 pub fn dors_escalation_triggered(
2876 phase: DorsEscalationPhase,
2877 from: String,
2878 to: String,
2879 reason_code: DorsEscalationReasonCode,
2880 reason_detail: Option<String>,
2881 ) -> Self {
2882 Self::DorsEscalationTriggered {
2883 phase,
2884 from,
2885 to,
2886 reason_code,
2887 reason_detail,
2888 }
2889 }
2890
2891 /// Creates a SecurityWarning event.
2892 pub fn security_warning(
2893 peer_id: String,
2894 reason_code: SecurityWarningCode,
2895 reason: String,
2896 ) -> Self {
2897 Self::SecurityWarning {
2898 peer_id,
2899 reason_code,
2900 reason,
2901 }
2902 }
2903
2904 /// Creates a MessageRelayed event.
2905 pub fn message_relayed(
2906 message_id: String,
2907 sender: String,
2908 recipient: String,
2909 hop_count: u8,
2910 remaining_ttl: u8,
2911 ) -> Self {
2912 Self::MessageRelayed {
2913 message_id,
2914 sender,
2915 recipient,
2916 hop_count,
2917 remaining_ttl,
2918 }
2919 }
2920
2921 /// Creates a UserBlocked event.
2922 pub fn user_blocked(user_id: String) -> Self {
2923 Self::UserBlocked { user_id }
2924 }
2925
2926 /// Creates a UserUnblocked event.
2927 pub fn user_unblocked(user_id: String) -> Self {
2928 Self::UserUnblocked { user_id }
2929 }
2930
2931 /// Converts the event to JSON.
2932 pub fn to_json(&self) -> Result<String, serde_json::Error> {
2933 serde_json::to_string(self)
2934 }
2935
2936 /// Parses an event from JSON.
2937 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
2938 serde_json::from_str(json)
2939 }
2940
2941 /// Returns the stable `snake.dot.case` telemetry name for this event.
2942 ///
2943 /// Names are compatible with OpenTelemetry naming conventions and are
2944 /// considered stable across minor versions of the SDK.
2945 pub fn telemetry_name(&self) -> &'static str {
2946 match self {
2947 Self::MessageSent { .. } => "protocol.message.sent",
2948 Self::MessageReceived { .. } => "protocol.message.received",
2949 Self::MessageDelivered { .. } => "protocol.message.delivered",
2950 Self::MessageFailed { .. } => "protocol.message.failed",
2951 Self::MessageDecryptionFailed { .. } => "protocol.message.decryption_failed",
2952 Self::TransportSwitched { .. } => "protocol.transport.switched",
2953 Self::RelayPromoted { .. } => "protocol.relay.promoted",
2954 Self::RelayDemoted { .. } => "protocol.relay.demoted",
2955 Self::NeighborDiscovered { .. } => "protocol.neighbor.discovered",
2956 Self::NeighborLost { .. } => "protocol.neighbor.lost",
2957 Self::IdentityReady { .. } => "protocol.identity.ready",
2958 Self::NetworkMetrics { .. } => "protocol.network.metrics",
2959 Self::FileProgress { .. } => "protocol.file.progress",
2960 Self::FileReceived { .. } => "protocol.file.received",
2961 Self::FileReceiveFailed { .. } => "protocol.file.receive_failed",
2962 Self::MediaSent { .. } => "protocol.media.sent",
2963 Self::MediaSendFailed { .. } => "protocol.media.send_failed",
2964 Self::MessageDeferred { .. } => "protocol.message.deferred",
2965 Self::MessageRetrying { .. } => "protocol.message.retrying",
2966 Self::MessageUndeliverable { .. } => "protocol.message.undeliverable",
2967 Self::MediaResendRequired { .. } => "protocol.media.resend_required",
2968 Self::AckEvicted { .. } => "protocol.ack.evicted",
2969 Self::FragmentAssemblyEvicted { .. } => "protocol.fragment.assembly_evicted",
2970 Self::RelayDemotedBattery { .. } => "protocol.relay.demoted_battery",
2971 Self::SecureSessionEstablished { .. } => "protocol.secure_session.established",
2972 Self::SecureSessionFailed { .. } => "protocol.secure_session.failed",
2973 Self::ConvergenceDiag { .. } => "protocol.convergence.diag",
2974 Self::WelcomeSendAttempted { .. } => "protocol.welcome.send_attempted",
2975 Self::WelcomeSendSucceeded { .. } => "protocol.welcome.send_succeeded",
2976 Self::WelcomeSendFailed { .. } => "protocol.welcome.send_failed",
2977 Self::WelcomeSendExpired { .. } => "protocol.welcome.send_expired",
2978 Self::ConnectionRequestReceived { .. } => "protocol.connection.request_received",
2979 Self::ConnectionRequestUndeliverable { .. } => {
2980 "protocol.connection.request_undeliverable"
2981 }
2982 Self::ConnectionAccepted { .. } => "protocol.connection.accepted",
2983 Self::ConnectionRejected { .. } => "protocol.connection.rejected",
2984 Self::ConnectionRequestCancelled { .. } => "protocol.connection.request_cancelled",
2985 Self::GroupCreated { .. } => "protocol.group.created",
2986 Self::GroupMessageReceived { .. } => "protocol.group.message_received",
2987 Self::GroupMemberAdded { .. } => "protocol.group.member_added",
2988 Self::GroupMemberRemoved { .. } => "protocol.group.member_removed",
2989 Self::GroupInfo { .. } => "protocol.group.info",
2990 Self::UserGroups { .. } => "protocol.group.user_groups",
2991 Self::GroupError { .. } => "protocol.group.error",
2992 Self::GroupRelaySyncChanged { .. } => "protocol.group.relay_sync_changed",
2993 Self::UsernameResolved { .. } => "protocol.username.resolved",
2994 Self::GroupMessageSent { .. } => "protocol.group.message_sent",
2995 Self::GroupMessagePartialFailure { .. } => "protocol.group.message_partial_failure",
2996 Self::GroupMessageDeliveryReport { .. } => "protocol.group.delivery_report",
2997 Self::GroupRichExtrasDropped { .. } => "protocol.group.rich_extras_dropped",
2998 Self::GroupUnauthorizedMembershipChange { .. } => {
2999 "protocol.group.unauthorized_membership_change"
3000 }
3001 Self::GroupEpochForkDetected { .. } => "protocol.group.epoch_fork_detected",
3002 Self::GroupEpochForkResolved { .. } => "protocol.group.epoch_fork_resolved",
3003 Self::GroupRoleChanged { .. } => "protocol.group.role_changed",
3004 Self::GroupRenamed { .. } => "protocol.group.renamed",
3005 Self::ServiceDiscovered { .. } => "protocol.service.discovered",
3006 Self::ServiceRequestReceived { .. } => "protocol.service.request_received",
3007 Self::ServiceResponseReceived { .. } => "protocol.service.response_received",
3008 Self::PresenceUpdated { .. } => "protocol.presence.updated",
3009 Self::TypingIndicatorReceived { .. } => "protocol.typing.received",
3010 Self::ReadReceiptReceived { .. } => "protocol.read_receipt.received",
3011 Self::DorsScoreUpdated { .. } => "protocol.dors.score_updated",
3012 Self::DorsTransportSelected { .. } => "protocol.dors.transport_selected",
3013 Self::DorsTransportSwitched { .. } => "protocol.dors.transport_switched",
3014 Self::DorsEscalationTriggered { .. } => "protocol.dors.escalation_triggered",
3015 Self::SecurityWarning { .. } => "protocol.security.warning",
3016 Self::MessageRelayed { .. } => "protocol.message.relayed",
3017 Self::UserBlocked { .. } => "protocol.user.blocked",
3018 Self::UserUnblocked { .. } => "protocol.user.unblocked",
3019 Self::DataChanged { .. } => "protocol.data.changed",
3020 Self::DataDocRemoved { .. } => "protocol.data.doc_removed",
3021 Self::DataDocSizeWarning { .. } => "protocol.data.doc_size_warning",
3022 Self::DataAttachmentRequested { .. } => "protocol.data.attachment_requested",
3023 Self::DataAttachmentReceived { .. } => "protocol.data.attachment_received",
3024 Self::DataAttachmentUnavailable { .. } => "protocol.data.attachment_unavailable",
3025 Self::DataDocUnsyncable { .. } => "protocol.data.doc_unsyncable",
3026 }
3027 }
3028}
3029
3030impl From<ServiceEvent> for Event {
3031 fn from(event: ServiceEvent) -> Self {
3032 match event {
3033 ServiceEvent::ServiceDiscovered {
3034 query_id,
3035 service_id,
3036 version,
3037 provider_peer_id,
3038 capabilities,
3039 hop_count,
3040 } => Self::ServiceDiscovered {
3041 query_id,
3042 service_id,
3043 version,
3044 provider_peer_id,
3045 capabilities,
3046 hop_count,
3047 },
3048 ServiceEvent::ServiceRequestReceived {
3049 request_id,
3050 service_id,
3051 method,
3052 body,
3053 sender,
3054 } => Self::ServiceRequestReceived {
3055 request_id,
3056 service_id,
3057 method,
3058 body,
3059 sender,
3060 // The service layer cannot know; the engine sets it for a
3061 // frame that arrived sealed (`handle_service_message`).
3062 encrypted: false,
3063 },
3064 ServiceEvent::ServiceResponseReceived {
3065 request_id,
3066 service_id,
3067 status,
3068 body,
3069 provider_peer_id,
3070 } => Self::ServiceResponseReceived {
3071 request_id,
3072 service_id,
3073 status,
3074 body,
3075 provider_peer_id,
3076 encrypted: false,
3077 },
3078 }
3079 }
3080}
3081
3082/// Custom Debug implementation that redacts sensitive fields to prevent
3083/// accidental logging of message content and other potentially sensitive data.
3084impl fmt::Debug for Event {
3085 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3086 match self {
3087 Self::MessageSent {
3088 message_id,
3089 sender: _,
3090 recipient: _,
3091 content,
3092 priority,
3093 requires_ack,
3094 timestamp,
3095 lamport_clock,
3096 forward_info,
3097 } => f
3098 .debug_struct("MessageSent")
3099 .field("message_id", message_id)
3100 .field("sender", &"[REDACTED]")
3101 .field("recipient", &"[REDACTED]")
3102 .field("content", &format!("[REDACTED {} bytes]", content.len()))
3103 .field("priority", priority)
3104 .field("requires_ack", requires_ack)
3105 .field("timestamp", timestamp)
3106 .field("lamport_clock", lamport_clock)
3107 .field("forward_info", &forward_info.is_some())
3108 .finish(),
3109 Self::MessageReceived {
3110 message_id,
3111 sender: _,
3112 recipient: _,
3113 content,
3114 hop_count,
3115 transport,
3116 timestamp,
3117 lamport_clock,
3118 reply_to_msg: _,
3119 reply_context,
3120 content_type,
3121 media_metadata: _,
3122 forward_info,
3123 encrypted,
3124 app_id,
3125 } => f
3126 .debug_struct("MessageReceived")
3127 .field("message_id", message_id)
3128 .field("sender", &"[REDACTED]")
3129 .field("recipient", &"[REDACTED]")
3130 .field("content", &format!("[REDACTED {} bytes]", content.len()))
3131 .field("hop_count", hop_count)
3132 .field("transport", transport)
3133 .field("timestamp", timestamp)
3134 .field("lamport_clock", lamport_clock)
3135 .field("reply_to_msg", &"[REDACTED]")
3136 .field("reply_context", &reply_context.is_some())
3137 .field("content_type", content_type)
3138 .field("forward_info", &forward_info.is_some())
3139 .field("encrypted", encrypted)
3140 .field("app_id", app_id)
3141 .finish(),
3142 Self::MessageDelivered {
3143 message_id,
3144 latency_ms,
3145 hop_count,
3146 transport,
3147 } => f
3148 .debug_struct("MessageDelivered")
3149 .field("message_id", message_id)
3150 .field("latency_ms", latency_ms)
3151 .field("hop_count", hop_count)
3152 .field("transport", transport)
3153 .finish(),
3154 Self::MessageFailed {
3155 message_id,
3156 reason,
3157 retry_count,
3158 } => f
3159 .debug_struct("MessageFailed")
3160 .field("message_id", message_id)
3161 .field("reason", reason)
3162 .field("retry_count", retry_count)
3163 .finish(),
3164 Self::MessageDecryptionFailed {
3165 message_id,
3166 sender: _,
3167 code,
3168 reason,
3169 sealed_at_ms,
3170 session_established_at_ms,
3171 } => f
3172 .debug_struct("MessageDecryptionFailed")
3173 .field("message_id", message_id)
3174 .field("sender", &"[REDACTED]")
3175 .field("code", code)
3176 .field("reason", reason)
3177 .field("sealed_at_ms", sealed_at_ms)
3178 .field("session_established_at_ms", session_established_at_ms)
3179 .finish(),
3180 Self::TransportSwitched { from, to, reason } => f
3181 .debug_struct("TransportSwitched")
3182 .field("from", from)
3183 .field("to", to)
3184 .field("reason", reason)
3185 .finish(),
3186 Self::RelayPromoted {
3187 connection_count,
3188 battery_level,
3189 } => f
3190 .debug_struct("RelayPromoted")
3191 .field("connection_count", connection_count)
3192 .field("battery_level", battery_level)
3193 .finish(),
3194 Self::RelayDemoted { reason } => f
3195 .debug_struct("RelayDemoted")
3196 .field("reason", reason)
3197 .finish(),
3198 Self::NeighborDiscovered {
3199 peer_id: _,
3200 transport,
3201 rssi,
3202 } => f
3203 .debug_struct("NeighborDiscovered")
3204 .field("peer_id", &"[REDACTED]")
3205 .field("transport", transport)
3206 .field("rssi", rssi)
3207 .finish(),
3208 Self::NeighborLost { peer_id: _ } => f
3209 .debug_struct("NeighborLost")
3210 .field("peer_id", &"[REDACTED]")
3211 .finish(),
3212 // Redacted like any other identifier: this one names *this* device,
3213 // which is the strongest correlator a log can carry.
3214 Self::IdentityReady { address: _ } => f
3215 .debug_struct("IdentityReady")
3216 .field("address", &"[REDACTED]")
3217 .finish(),
3218 Self::NetworkMetrics {
3219 neighbor_count,
3220 relay_count,
3221 delivery_ratio,
3222 avg_latency_ms,
3223 } => f
3224 .debug_struct("NetworkMetrics")
3225 .field("neighbor_count", neighbor_count)
3226 .field("relay_count", relay_count)
3227 .field("delivery_ratio", delivery_ratio)
3228 .field("avg_latency_ms", avg_latency_ms)
3229 .finish(),
3230 Self::FileProgress {
3231 file_id,
3232 chunks_sent,
3233 total_chunks,
3234 percentage,
3235 } => f
3236 .debug_struct("FileProgress")
3237 .field("file_id", file_id)
3238 .field("chunks_sent", chunks_sent)
3239 .field("total_chunks", total_chunks)
3240 .field("percentage", percentage)
3241 .finish(),
3242 Self::FileReceived {
3243 file_id,
3244 file_name,
3245 file_size,
3246 sender: _,
3247 content_type,
3248 media_metadata: _,
3249 file_data,
3250 timestamp,
3251 caption,
3252 reply_to_msg: _,
3253 reply_context,
3254 forward_info,
3255 app_id,
3256 } => f
3257 .debug_struct("FileReceived")
3258 .field("file_id", file_id)
3259 .field("file_name", file_name)
3260 .field("file_size", file_size)
3261 .field("sender", &"[REDACTED]")
3262 .field("content_type", content_type)
3263 .field("file_data", &format!("[{} bytes base64]", file_data.len()))
3264 .field("timestamp", timestamp)
3265 .field("caption", &caption.is_some())
3266 .field("reply_to_msg", &"[REDACTED]")
3267 .field("reply_context", &reply_context.is_some())
3268 .field("forward_info", &forward_info.is_some())
3269 .field("app_id", app_id)
3270 .finish(),
3271 Self::FileReceiveFailed {
3272 file_id,
3273 file_name,
3274 sender: _,
3275 reason,
3276 } => f
3277 .debug_struct("FileReceiveFailed")
3278 .field("file_id", file_id)
3279 .field("file_name", file_name)
3280 .field("sender", &"[REDACTED]")
3281 .field("reason", reason)
3282 .finish(),
3283 Self::MediaSent {
3284 file_id,
3285 content_type,
3286 recipient: _,
3287 } => f
3288 .debug_struct("MediaSent")
3289 .field("file_id", file_id)
3290 .field("content_type", content_type)
3291 .field("recipient", &"[REDACTED]")
3292 .finish(),
3293 Self::MediaSendFailed {
3294 file_id,
3295 recipient: _,
3296 reason,
3297 } => f
3298 .debug_struct("MediaSendFailed")
3299 .field("file_id", file_id)
3300 .field("recipient", &"[REDACTED]")
3301 .field("reason", reason)
3302 .finish(),
3303 Self::MessageDeferred {
3304 message_id,
3305 recipient: _,
3306 reason,
3307 retry_count,
3308 next_retry_at,
3309 } => f
3310 .debug_struct("MessageDeferred")
3311 .field("message_id", message_id)
3312 .field("recipient", &"[REDACTED]")
3313 .field("reason", reason)
3314 .field("retry_count", retry_count)
3315 .field("next_retry_at", next_retry_at)
3316 .finish(),
3317 Self::MessageRetrying {
3318 message_id,
3319 recipient: _,
3320 retry_count,
3321 next_retry_at,
3322 } => f
3323 .debug_struct("MessageRetrying")
3324 .field("message_id", message_id)
3325 .field("recipient", &"[REDACTED]")
3326 .field("retry_count", retry_count)
3327 .field("next_retry_at", next_retry_at)
3328 .finish(),
3329 Self::MessageUndeliverable {
3330 message_id,
3331 recipient: _,
3332 reason,
3333 file_id,
3334 } => f
3335 .debug_struct("MessageUndeliverable")
3336 .field("message_id", message_id)
3337 .field("recipient", &"[REDACTED]")
3338 .field("reason", reason)
3339 .field("file_id", file_id)
3340 .finish(),
3341 Self::MediaResendRequired {
3342 file_id,
3343 recipient: _,
3344 file_name,
3345 file_size,
3346 app_id,
3347 } => f
3348 .debug_struct("MediaResendRequired")
3349 .field("file_id", file_id)
3350 .field("recipient", &"[REDACTED]")
3351 .field("file_name", file_name)
3352 .field("file_size", file_size)
3353 .field("app_id", app_id)
3354 .finish(),
3355 Self::AckEvicted {
3356 message_id,
3357 priority,
3358 reason,
3359 } => f
3360 .debug_struct("AckEvicted")
3361 .field("message_id", message_id)
3362 .field("priority", priority)
3363 .field("reason", reason)
3364 .finish(),
3365 Self::FragmentAssemblyEvicted {
3366 message_id,
3367 completion_percent,
3368 reason,
3369 } => f
3370 .debug_struct("FragmentAssemblyEvicted")
3371 .field("message_id", message_id)
3372 .field("completion_percent", completion_percent)
3373 .field("reason", reason)
3374 .finish(),
3375 Self::RelayDemotedBattery {
3376 battery_level,
3377 min_required,
3378 } => f
3379 .debug_struct("RelayDemotedBattery")
3380 .field("battery_level", battery_level)
3381 .field("min_required", min_required)
3382 .finish(),
3383 Self::SecureSessionEstablished {
3384 peer_id: _,
3385 group_id,
3386 is_session,
3387 initiated_by_local,
3388 } => f
3389 .debug_struct("SecureSessionEstablished")
3390 .field("peer_id", &"[REDACTED]")
3391 .field("group_id", group_id)
3392 .field("is_session", is_session)
3393 .field("initiated_by_local", initiated_by_local)
3394 .finish(),
3395 Self::SecureSessionFailed { peer_id: _, reason } => f
3396 .debug_struct("SecureSessionFailed")
3397 .field("peer_id", &"[REDACTED]")
3398 .field("reason", reason)
3399 .finish(),
3400 Self::ConvergenceDiag {
3401 stage,
3402 peer_id: _,
3403 detail,
3404 } => f
3405 .debug_struct("ConvergenceDiag")
3406 .field("stage", stage)
3407 .field("peer_id", &"[REDACTED]")
3408 .field("detail", detail)
3409 .finish(),
3410 Self::WelcomeSendAttempted {
3411 peer_id: _,
3412 message_id,
3413 group_id,
3414 attempt,
3415 } => f
3416 .debug_struct("WelcomeSendAttempted")
3417 .field("peer_id", &"[REDACTED]")
3418 .field("message_id", message_id)
3419 .field("group_id", group_id)
3420 .field("attempt", attempt)
3421 .finish(),
3422 Self::WelcomeSendSucceeded {
3423 peer_id: _,
3424 message_id,
3425 group_id,
3426 attempt,
3427 } => f
3428 .debug_struct("WelcomeSendSucceeded")
3429 .field("peer_id", &"[REDACTED]")
3430 .field("message_id", message_id)
3431 .field("group_id", group_id)
3432 .field("attempt", attempt)
3433 .finish(),
3434 Self::WelcomeSendFailed {
3435 peer_id: _,
3436 message_id,
3437 group_id,
3438 attempt,
3439 reason_code,
3440 transport_error,
3441 retryable,
3442 next_retry_at,
3443 } => f
3444 .debug_struct("WelcomeSendFailed")
3445 .field("peer_id", &"[REDACTED]")
3446 .field("message_id", message_id)
3447 .field("group_id", group_id)
3448 .field("attempt", attempt)
3449 .field("reason_code", reason_code)
3450 .field("transport_error", transport_error)
3451 .field("retryable", retryable)
3452 .field("next_retry_at", next_retry_at)
3453 .finish(),
3454 Self::WelcomeSendExpired {
3455 peer_id: _,
3456 message_id,
3457 attempt,
3458 reason_code,
3459 } => f
3460 .debug_struct("WelcomeSendExpired")
3461 .field("peer_id", &"[REDACTED]")
3462 .field("message_id", message_id)
3463 .field("attempt", attempt)
3464 .field("reason_code", reason_code)
3465 .finish(),
3466 Self::ConnectionRequestReceived {
3467 sender: _,
3468 sender_name: _,
3469 timestamp,
3470 key_package,
3471 initial_message,
3472 } => f
3473 .debug_struct("ConnectionRequestReceived")
3474 .field("sender", &"[REDACTED]")
3475 .field("sender_name", &"[REDACTED]")
3476 .field("timestamp", timestamp)
3477 .field("has_key_package", &key_package.is_some())
3478 .field("has_initial_message", &initial_message.is_some())
3479 .finish(),
3480 Self::ConnectionRequestUndeliverable {
3481 recipient: _,
3482 message_id,
3483 reason,
3484 } => f
3485 .debug_struct("ConnectionRequestUndeliverable")
3486 .field("recipient", &"[REDACTED]")
3487 .field("message_id", message_id)
3488 .field("reason", reason)
3489 .finish(),
3490 Self::ConnectionAccepted {
3491 accepted_by: _,
3492 accepted_by_name: _,
3493 timestamp,
3494 key_package,
3495 } => f
3496 .debug_struct("ConnectionAccepted")
3497 .field("accepted_by", &"[REDACTED]")
3498 .field("accepted_by_name", &"[REDACTED]")
3499 .field("timestamp", timestamp)
3500 .field("has_key_package", &key_package.is_some())
3501 .finish(),
3502 Self::ConnectionRejected { rejected_by: _ } => f
3503 .debug_struct("ConnectionRejected")
3504 .field("rejected_by", &"[REDACTED]")
3505 .finish(),
3506 Self::ConnectionRequestCancelled { cancelled_by: _ } => f
3507 .debug_struct("ConnectionRequestCancelled")
3508 .field("cancelled_by", &"[REDACTED]")
3509 .finish(),
3510 Self::ServiceDiscovered {
3511 query_id,
3512 service_id,
3513 version,
3514 provider_peer_id: _,
3515 capabilities,
3516 hop_count,
3517 } => f
3518 .debug_struct("ServiceDiscovered")
3519 .field("query_id", query_id)
3520 .field("service_id", service_id)
3521 .field("version", version)
3522 .field("provider_peer_id", &"[REDACTED]")
3523 .field("capabilities_count", &capabilities.len())
3524 .field("hop_count", hop_count)
3525 .finish(),
3526 Self::ServiceRequestReceived {
3527 request_id,
3528 service_id,
3529 method,
3530 body,
3531 sender: _,
3532 encrypted,
3533 } => f
3534 .debug_struct("ServiceRequestReceived")
3535 .field("request_id", request_id)
3536 .field("service_id", service_id)
3537 .field("method", method)
3538 .field("body", &format!("[REDACTED {} bytes]", body.len()))
3539 .field("sender", &"[REDACTED]")
3540 .field("encrypted", encrypted)
3541 .finish(),
3542 Self::ServiceResponseReceived {
3543 request_id,
3544 service_id,
3545 status,
3546 body,
3547 provider_peer_id: _,
3548 encrypted,
3549 } => f
3550 .debug_struct("ServiceResponseReceived")
3551 .field("request_id", request_id)
3552 .field("service_id", service_id)
3553 .field("status", status)
3554 .field("body", &format!("[REDACTED {} bytes]", body.len()))
3555 .field("provider_peer_id", &"[REDACTED]")
3556 .field("encrypted", encrypted)
3557 .finish(),
3558 Self::GroupCreated { group_id, name } => f
3559 .debug_struct("GroupCreated")
3560 .field("group_id", group_id)
3561 .field("name", name)
3562 .finish(),
3563 Self::GroupMessageReceived {
3564 group_id,
3565 sender: _,
3566 content,
3567 forward_info,
3568 ..
3569 } => f
3570 .debug_struct("GroupMessageReceived")
3571 .field("group_id", group_id)
3572 .field("sender", &"[REDACTED]")
3573 .field("content", &format!("[REDACTED {} bytes]", content.len()))
3574 .field("forward_info", &forward_info.is_some())
3575 .finish(),
3576 Self::GroupMemberAdded {
3577 group_id,
3578 user_id: _,
3579 added_by: _,
3580 group_name,
3581 authorized,
3582 } => f
3583 .debug_struct("GroupMemberAdded")
3584 .field("group_id", group_id)
3585 .field("user_id", &"[REDACTED]")
3586 .field("added_by", &"[REDACTED]")
3587 .field("group_name", group_name)
3588 .field("authorized", authorized)
3589 .finish(),
3590 Self::GroupMemberRemoved {
3591 group_id,
3592 user_id: _,
3593 removed_by: _,
3594 authorized,
3595 } => f
3596 .debug_struct("GroupMemberRemoved")
3597 .field("group_id", group_id)
3598 .field("user_id", &"[REDACTED]")
3599 .field("removed_by", &"[REDACTED]")
3600 .field("authorized", authorized)
3601 .finish(),
3602 Self::GroupInfo {
3603 group_id,
3604 name,
3605 created_by: _,
3606 created_at,
3607 members,
3608 } => f
3609 .debug_struct("GroupInfo")
3610 .field("group_id", group_id)
3611 .field("name", name)
3612 .field("created_by", &"[REDACTED]")
3613 .field("created_at", created_at)
3614 .field("members_count", &members.len())
3615 .finish(),
3616 Self::UserGroups { groups } => f
3617 .debug_struct("UserGroups")
3618 .field("groups_count", &groups.len())
3619 .finish(),
3620 Self::GroupError { reason, group_id } => f
3621 .debug_struct("GroupError")
3622 .field("reason", reason)
3623 .field("group_id", group_id)
3624 .finish(),
3625 Self::GroupRelaySyncChanged {
3626 group_id,
3627 synced,
3628 reason,
3629 } => f
3630 .debug_struct("GroupRelaySyncChanged")
3631 .field("group_id", group_id)
3632 .field("synced", synced)
3633 .field("reason", reason)
3634 .finish(),
3635 // The username is redacted: it is a human-readable name for a
3636 // person, which is exactly the class of identifier this Debug
3637 // exists to keep out of logs. The counts say everything a reader
3638 // debugging a resolution needs.
3639 Self::UsernameResolved {
3640 username: _,
3641 claims,
3642 rejected,
3643 truncated,
3644 } => f
3645 .debug_struct("UsernameResolved")
3646 .field("username", &"<redacted>")
3647 .field("claim_count", &claims.len())
3648 .field("rejected", rejected)
3649 .field("truncated", truncated)
3650 .finish(),
3651 Self::GroupMessageSent {
3652 group_id,
3653 message_ids,
3654 member_count,
3655 } => f
3656 .debug_struct("GroupMessageSent")
3657 .field("group_id", group_id)
3658 .field("message_count", &message_ids.len())
3659 .field("member_count", member_count)
3660 .finish(),
3661 Self::GroupMessagePartialFailure {
3662 group_id,
3663 failed_members,
3664 succeeded_members,
3665 } => f
3666 .debug_struct("GroupMessagePartialFailure")
3667 .field("group_id", group_id)
3668 .field("failed_count", &failed_members.len())
3669 .field("succeeded_count", &succeeded_members.len())
3670 .finish(),
3671 Self::GroupMessageDeliveryReport {
3672 group_id,
3673 message_id,
3674 delivered,
3675 pushed,
3676 missed_reissued,
3677 } => f
3678 .debug_struct("GroupMessageDeliveryReport")
3679 .field("group_id", group_id)
3680 .field("message_id", message_id)
3681 .field("delivered_count", &delivered.len())
3682 .field("pushed_count", &pushed.len())
3683 .field("missed_reissued_count", &missed_reissued.len())
3684 .finish(),
3685 Self::GroupRichExtrasDropped {
3686 group_id,
3687 unknown_members,
3688 } => f
3689 .debug_struct("GroupRichExtrasDropped")
3690 .field("group_id", group_id)
3691 .field("unknown_count", &unknown_members.len())
3692 .finish(),
3693 Self::GroupUnauthorizedMembershipChange {
3694 group_id,
3695 committer: _,
3696 added,
3697 removed,
3698 reason,
3699 enforced,
3700 } => f
3701 .debug_struct("GroupUnauthorizedMembershipChange")
3702 .field("group_id", group_id)
3703 .field("committer", &"[REDACTED]")
3704 .field("added_count", &added.len())
3705 .field("removed_count", &removed.len())
3706 .field("reason", reason)
3707 .field("enforced", enforced)
3708 .finish(),
3709 Self::GroupEpochForkDetected {
3710 group_id,
3711 local_epoch,
3712 } => f
3713 .debug_struct("GroupEpochForkDetected")
3714 .field("group_id", group_id)
3715 .field("local_epoch", local_epoch)
3716 .finish(),
3717 Self::GroupEpochForkResolved {
3718 group_id,
3719 resolved_epoch,
3720 failed_members,
3721 } => f
3722 .debug_struct("GroupEpochForkResolved")
3723 .field("group_id", group_id)
3724 .field("resolved_epoch", resolved_epoch)
3725 .field("failed_members", failed_members)
3726 .finish(),
3727 Self::PresenceUpdated {
3728 peer_id: _,
3729 status,
3730 timestamp,
3731 last_seen_ms,
3732 source,
3733 } => f
3734 .debug_struct("PresenceUpdated")
3735 .field("peer_id", &"[REDACTED]")
3736 .field("status", status)
3737 .field("timestamp", timestamp)
3738 .field("last_seen_ms", last_seen_ms)
3739 .field("source", source)
3740 .finish(),
3741 Self::TypingIndicatorReceived {
3742 sender: _,
3743 conversation_id: _,
3744 is_typing,
3745 timestamp,
3746 } => f
3747 .debug_struct("TypingIndicatorReceived")
3748 .field("sender", &"[REDACTED]")
3749 .field("conversation_id", &"[REDACTED]")
3750 .field("is_typing", is_typing)
3751 .field("timestamp", timestamp)
3752 .finish(),
3753 Self::ReadReceiptReceived {
3754 sender: _,
3755 message_ids,
3756 timestamp,
3757 } => f
3758 .debug_struct("ReadReceiptReceived")
3759 .field("sender", &"[REDACTED]")
3760 .field("message_count", &message_ids.len())
3761 .field("timestamp", timestamp)
3762 .finish(),
3763 Self::DorsScoreUpdated { scores } => f
3764 .debug_struct("DorsScoreUpdated")
3765 .field("scores", scores)
3766 .finish(),
3767 Self::DorsTransportSelected {
3768 from,
3769 transport,
3770 reason_code,
3771 score,
3772 } => f
3773 .debug_struct("DorsTransportSelected")
3774 .field("from", from)
3775 .field("transport", transport)
3776 .field("reason_code", reason_code)
3777 .field("score", score)
3778 .finish(),
3779 Self::DorsTransportSwitched {
3780 from,
3781 to,
3782 reason_code,
3783 reason_detail,
3784 } => f
3785 .debug_struct("DorsTransportSwitched")
3786 .field("from", from)
3787 .field("to", to)
3788 .field("reason_code", reason_code)
3789 .field("reason_detail", reason_detail)
3790 .finish(),
3791 Self::DorsEscalationTriggered {
3792 phase,
3793 from,
3794 to,
3795 reason_code,
3796 reason_detail,
3797 } => f
3798 .debug_struct("DorsEscalationTriggered")
3799 .field("phase", phase)
3800 .field("from", from)
3801 .field("to", to)
3802 .field("reason_code", reason_code)
3803 .field("reason_detail", reason_detail)
3804 .finish(),
3805 // The one arm that used to print `peer_id` verbatim, and the worst
3806 // one to: a security warning is precisely the event an operator
3807 // dumps into a log while investigating, and the peer it names is
3808 // usually attacker-controlled — an injected frame carries whatever
3809 // sender it likes, so this field doubles as a log-injection
3810 // surface. The telemetry scrubber already hashed it; only `{:?}`
3811 // disagreed.
3812 Self::SecurityWarning {
3813 peer_id: _,
3814 reason_code,
3815 reason,
3816 } => f
3817 .debug_struct("SecurityWarning")
3818 .field("peer_id", &"[REDACTED]")
3819 .field("reason_code", reason_code)
3820 .field("reason", reason)
3821 .finish(),
3822 Self::MessageRelayed {
3823 message_id,
3824 sender: _,
3825 recipient: _,
3826 hop_count,
3827 remaining_ttl,
3828 } => f
3829 .debug_struct("MessageRelayed")
3830 .field("message_id", message_id)
3831 .field("sender", &"[REDACTED]")
3832 .field("recipient", &"[REDACTED]")
3833 .field("hop_count", hop_count)
3834 .field("remaining_ttl", remaining_ttl)
3835 .finish(),
3836 Self::UserBlocked { user_id: _ } => f
3837 .debug_struct("UserBlocked")
3838 .field("user_id", &"[REDACTED]")
3839 .finish(),
3840 Self::UserUnblocked { user_id: _ } => f
3841 .debug_struct("UserUnblocked")
3842 .field("user_id", &"[REDACTED]")
3843 .finish(),
3844 Self::DataChanged {
3845 space_id: _,
3846 doc_id: _,
3847 delta_bytes,
3848 } => f
3849 .debug_struct("DataChanged")
3850 // A space id is the peer or group the space rides on, and a
3851 // document name is application content. Both are identifiers,
3852 // so both redact.
3853 .field("space_id", &"[REDACTED]")
3854 .field("doc_id", &"[REDACTED]")
3855 .field("delta_bytes", delta_bytes)
3856 .finish(),
3857 Self::DataDocRemoved {
3858 space_id: _,
3859 doc_id: _,
3860 by,
3861 } => f
3862 .debug_struct("DataDocRemoved")
3863 .field("space_id", &"[REDACTED]")
3864 .field("doc_id", &"[REDACTED]")
3865 // A fixed token this crate chooses, never a peer's words.
3866 .field("by", by)
3867 .finish(),
3868 Self::DataDocSizeWarning {
3869 space_id: _,
3870 doc_id: _,
3871 compacted_bytes,
3872 cap_bytes,
3873 } => f
3874 .debug_struct("DataDocSizeWarning")
3875 .field("space_id", &"[REDACTED]")
3876 .field("doc_id", &"[REDACTED]")
3877 .field("compacted_bytes", compacted_bytes)
3878 .field("cap_bytes", cap_bytes)
3879 .finish(),
3880 Self::DataAttachmentRequested {
3881 space_id: _,
3882 peer_id: _,
3883 hash,
3884 } => f
3885 .debug_struct("DataAttachmentRequested")
3886 .field("space_id", &"[REDACTED]")
3887 .field("peer_id", &"[REDACTED]")
3888 // A blob hash names bytes, not a person, and it is the one
3889 // field that makes a report about a fetch actionable.
3890 .field("hash", hash)
3891 .finish(),
3892 Self::DataAttachmentReceived {
3893 space_id: _,
3894 peer_id: _,
3895 hash,
3896 data,
3897 } => f
3898 .debug_struct("DataAttachmentReceived")
3899 .field("space_id", &"[REDACTED]")
3900 .field("peer_id", &"[REDACTED]")
3901 .field("hash", hash)
3902 // The blob itself is content and never goes near a log.
3903 .field("data", &format!("[{} base64 chars]", data.len()))
3904 .finish(),
3905 Self::DataAttachmentUnavailable {
3906 space_id: _,
3907 peer_id: _,
3908 hash,
3909 reason,
3910 } => f
3911 .debug_struct("DataAttachmentUnavailable")
3912 .field("space_id", &"[REDACTED]")
3913 .field("peer_id", &"[REDACTED]")
3914 .field("hash", hash)
3915 .field("reason", reason)
3916 .finish(),
3917 Self::DataDocUnsyncable {
3918 space_id: _,
3919 doc_id: _,
3920 bytes,
3921 reason,
3922 } => f
3923 .debug_struct("DataDocUnsyncable")
3924 .field("space_id", &"[REDACTED]")
3925 .field("doc_id", &"[REDACTED]")
3926 .field("bytes", bytes)
3927 .field("reason", reason)
3928 .finish(),
3929 Self::GroupRoleChanged {
3930 group_id,
3931 user_id: _,
3932 new_role,
3933 changed_by: _,
3934 } => f
3935 .debug_struct("GroupRoleChanged")
3936 .field("group_id", group_id)
3937 .field("user_id", &"[REDACTED]")
3938 .field("new_role", new_role)
3939 .field("changed_by", &"[REDACTED]")
3940 .finish(),
3941 Self::GroupRenamed {
3942 group_id,
3943 new_name,
3944 old_name: _,
3945 renamed_by: _,
3946 } => f
3947 .debug_struct("GroupRenamed")
3948 .field("group_id", group_id)
3949 .field("new_name", new_name)
3950 .field("renamed_by", &"[REDACTED]")
3951 .finish(),
3952 }
3953 }
3954}
3955
3956#[cfg(test)]
3957mod tests {
3958 use super::*;
3959 use crate::protocol::SEND_FAIL_REASON_RECIPIENT_UNREACHABLE;
3960 use offline_protocol_core::{AppId, Message, MessagePriority, UserId};
3961
3962 #[test]
3963 fn test_message_sent_event() {
3964 let message = Message::builder(
3965 UserId::new("alice").unwrap(),
3966 UserId::new("bob").unwrap(),
3967 AppId::new("app").unwrap(),
3968 )
3969 .content("Hello")
3970 .priority(MessagePriority::High)
3971 .build();
3972
3973 let event = Event::message_sent(&message);
3974
3975 match event {
3976 Event::MessageSent {
3977 message_id,
3978 sender,
3979 recipient,
3980 content,
3981 priority,
3982 requires_ack,
3983 timestamp,
3984 lamport_clock,
3985 forward_info,
3986 } => {
3987 assert_eq!(message_id, message.id.as_str());
3988 assert_eq!(sender, message.sender.as_str());
3989 assert_eq!(recipient, message.recipient.as_str());
3990 assert_eq!(content, message.content);
3991 assert_eq!(priority, "high");
3992 assert!(requires_ack);
3993 assert_eq!(timestamp, message.timestamp.as_millis());
3994 assert_eq!(lamport_clock, message.lamport_clock.value());
3995 assert!(forward_info.is_none());
3996 }
3997 _ => panic!("Wrong event type"),
3998 }
3999 }
4000
4001 #[test]
4002 fn test_message_delivered_event() {
4003 let msg_id = MessageId::new();
4004 let event = Event::message_delivered(msg_id.clone(), 100, 3, TransportType::BLE);
4005
4006 match event {
4007 Event::MessageDelivered {
4008 message_id,
4009 latency_ms,
4010 hop_count,
4011 transport,
4012 } => {
4013 assert_eq!(message_id, msg_id.as_str());
4014 assert_eq!(latency_ms, 100);
4015 assert_eq!(hop_count, 3);
4016 assert_eq!(transport, "ble");
4017 }
4018 _ => panic!("Wrong event type"),
4019 }
4020 }
4021
4022 #[test]
4023 fn test_transport_switched_event() {
4024 let event = Event::transport_switched(
4025 Some(TransportType::BLE),
4026 TransportType::WiFiDirect,
4027 "Poor signal".to_string(),
4028 );
4029
4030 match event {
4031 Event::TransportSwitched { from, to, reason } => {
4032 assert_eq!(from.as_deref(), Some("ble"));
4033 assert_eq!(to, "wifiDirect");
4034 assert_eq!(reason, "Poor signal");
4035 }
4036 _ => panic!("Wrong event type"),
4037 }
4038 }
4039
4040 #[test]
4041 fn test_relay_promoted_event() {
4042 let event = Event::relay_promoted(5, Some(80));
4043
4044 match event {
4045 Event::RelayPromoted {
4046 connection_count,
4047 battery_level,
4048 } => {
4049 assert_eq!(connection_count, 5);
4050 assert_eq!(battery_level, Some(80));
4051 }
4052 _ => panic!("Wrong event type"),
4053 }
4054 }
4055
4056 #[test]
4057 fn test_file_progress_event() {
4058 let event = Event::file_progress("file123".to_string(), 50, 100);
4059
4060 match event {
4061 Event::FileProgress {
4062 file_id,
4063 chunks_sent,
4064 total_chunks,
4065 percentage,
4066 } => {
4067 assert_eq!(file_id, "file123");
4068 assert_eq!(chunks_sent, 50);
4069 assert_eq!(total_chunks, 100);
4070 assert_eq!(percentage, 50);
4071 }
4072 _ => panic!("Wrong event type"),
4073 }
4074 }
4075
4076 #[test]
4077 fn test_event_serialization() {
4078 let event = Event::relay_promoted(5, Some(80));
4079 let json = event.to_json().unwrap();
4080 let deserialized = Event::from_json(&json).unwrap();
4081
4082 match deserialized {
4083 Event::RelayPromoted {
4084 connection_count,
4085 battery_level,
4086 } => {
4087 assert_eq!(connection_count, 5);
4088 assert_eq!(battery_level, Some(80));
4089 }
4090 _ => panic!("Wrong event type after deserialization"),
4091 }
4092 }
4093
4094 /// Pins the JSON wire shape the RN `types.ts` declarations model
4095 /// (`ConnectionRequestUndeliverableEvent` / `initial_message` on
4096 /// `ConnectionRequestReceivedEvent`) — events cross the FFI as JSON, so
4097 /// this contract is otherwise enforced only by convention.
4098 #[test]
4099 fn test_connection_request_event_wire_shapes() {
4100 let event = Event::connection_request_undeliverable(
4101 "bob".to_string(),
4102 "m1".to_string(),
4103 SEND_FAIL_REASON_RECIPIENT_UNREACHABLE,
4104 );
4105 let json: serde_json::Value = serde_json::from_str(&event.to_json().unwrap()).unwrap();
4106 assert_eq!(json["type"], "connection_request_undeliverable");
4107 assert_eq!(json["recipient"], "bob");
4108 assert_eq!(json["message_id"], "m1");
4109 // The bare token, never the relay's `recipient_unreachable: <prose>`.
4110 assert_eq!(json["reason"], "recipient_unreachable");
4111
4112 let received = Event::connection_request_received(
4113 "alice".to_string(),
4114 "Alice".to_string(),
4115 12345,
4116 None,
4117 Some("hey".to_string()),
4118 );
4119 let json: serde_json::Value = serde_json::from_str(&received.to_json().unwrap()).unwrap();
4120 assert_eq!(json["type"], "connection_request_received");
4121 assert_eq!(json["initial_message"], "hey");
4122
4123 // None must omit the key entirely (skip_serializing_if), keeping the
4124 // event byte-shape identical to pre-initial-message builds.
4125 let received = Event::connection_request_received(
4126 "alice".to_string(),
4127 "Alice".to_string(),
4128 12345,
4129 None,
4130 None,
4131 );
4132 assert!(!received.to_json().unwrap().contains("initial_message"));
4133 }
4134
4135 /// Pins the `group_error` wire shape (#349).
4136 ///
4137 /// `group_id` is additive, so a build that never scopes an error must
4138 /// serialize byte-identically to pre-change builds — the same
4139 /// `skip_serializing_if` contract `initial_message` is pinned on above.
4140 #[test]
4141 fn test_group_error_event_wire_shape() {
4142 let scoped = Event::group_error("sync_denied".to_string(), Some("g-1".to_string()));
4143 let json: serde_json::Value = serde_json::from_str(&scoped.to_json().unwrap()).unwrap();
4144 assert_eq!(json["type"], "group_error");
4145 assert_eq!(json["reason"], "sync_denied");
4146 assert_eq!(json["group_id"], "g-1");
4147
4148 let unscoped = Event::group_error("error".to_string(), None);
4149 assert!(!unscoped.to_json().unwrap().contains("group_id"));
4150 }
4151
4152 #[test]
4153 fn test_network_metrics_event() {
4154 let event = Event::network_metrics(10, 3, 0.95, 150);
4155
4156 match event {
4157 Event::NetworkMetrics {
4158 neighbor_count,
4159 relay_count,
4160 delivery_ratio,
4161 avg_latency_ms,
4162 } => {
4163 assert_eq!(neighbor_count, 10);
4164 assert_eq!(relay_count, 3);
4165 assert_eq!(delivery_ratio, 0.95);
4166 assert_eq!(avg_latency_ms, 150);
4167 }
4168 _ => panic!("Wrong event type"),
4169 }
4170 }
4171
4172 #[test]
4173 fn test_file_received_event() {
4174 let event = Event::file_received(
4175 "file123".to_string(),
4176 "photo.jpg".to_string(),
4177 1024000,
4178 "alice".to_string(),
4179 ContentType::Image,
4180 None,
4181 vec![1, 2, 3, 4],
4182 None,
4183 None,
4184 None,
4185 None,
4186 None,
4187 None,
4188 );
4189
4190 match event {
4191 Event::FileReceived {
4192 file_id,
4193 file_name,
4194 file_size,
4195 sender,
4196 content_type,
4197 file_data,
4198 ..
4199 } => {
4200 assert_eq!(file_id, "file123");
4201 assert_eq!(file_name, "photo.jpg");
4202 assert_eq!(file_size, 1024000);
4203 assert_eq!(sender, "alice");
4204 assert_eq!(content_type, "image");
4205 assert!(!file_data.is_empty());
4206 }
4207 _ => panic!("Wrong event type"),
4208 }
4209 }
4210
4211 #[test]
4212 fn test_file_received_event_rich_fields_absent_from_json_when_none() {
4213 // The rich fields are additive on the event's JSON wire form: a
4214 // plain transfer must serialize exactly as it did before they
4215 // existed, so older consumers see no new keys.
4216 let event = Event::file_received(
4217 "file123".to_string(),
4218 "f.bin".to_string(),
4219 4,
4220 "alice".to_string(),
4221 ContentType::File,
4222 None,
4223 vec![1, 2, 3, 4],
4224 None,
4225 None,
4226 None,
4227 None,
4228 None,
4229 None,
4230 );
4231 let json = serde_json::to_value(&event).unwrap();
4232 for key in [
4233 "timestamp",
4234 "caption",
4235 "reply_to_msg",
4236 "reply_context",
4237 "forward_info",
4238 ] {
4239 assert!(json.get(key).is_none(), "{} must be absent when unset", key);
4240 }
4241 }
4242
4243 #[test]
4244 fn test_file_received_event_rich_fields_round_trip() {
4245 use offline_protocol_core::UserId;
4246 let rc = offline_protocol_core::ReplyContext {
4247 sender: UserId::new("carol").unwrap(),
4248 text: "the original".to_string(),
4249 timestamp: None,
4250 reply_media_label: None,
4251 reply_content_type: Some("text".to_string()),
4252 };
4253 let fwd = offline_protocol_core::ForwardInfo {
4254 original_sender: UserId::new("dave").unwrap(),
4255 original_message_id: offline_protocol_core::MessageId::new(),
4256 original_timestamp: offline_protocol_core::Timestamp::now(),
4257 forward_count: 1,
4258 };
4259 let event = Event::file_received(
4260 "file123".to_string(),
4261 "photo.jpg".to_string(),
4262 1024,
4263 "alice".to_string(),
4264 ContentType::Image,
4265 None,
4266 vec![1, 2, 3],
4267 Some(1_700_000_000_000),
4268 Some("look".to_string()),
4269 Some("0192aaaa-bbbb-cccc-dddd-eeeeffff0000".to_string()),
4270 Some(&rc),
4271 Some(&fwd),
4272 None,
4273 );
4274 let json = serde_json::to_string(&event).unwrap();
4275 let parsed: Event = serde_json::from_str(&json).unwrap();
4276 match parsed {
4277 Event::FileReceived {
4278 timestamp,
4279 caption,
4280 reply_to_msg,
4281 reply_context,
4282 forward_info,
4283 ..
4284 } => {
4285 assert_eq!(timestamp, Some(1_700_000_000_000));
4286 assert_eq!(caption.as_deref(), Some("look"));
4287 assert_eq!(
4288 reply_to_msg.as_deref(),
4289 Some("0192aaaa-bbbb-cccc-dddd-eeeeffff0000")
4290 );
4291 let rc = reply_context.expect("reply_context must round-trip");
4292 assert_eq!(rc.sender, "carol");
4293 assert_eq!(rc.text, "the original");
4294 let fwd = forward_info.expect("forward_info must round-trip");
4295 assert_eq!(fwd.original_sender, "dave");
4296 assert_eq!(fwd.forward_count, 1);
4297 }
4298 _ => panic!("Wrong event type"),
4299 }
4300 }
4301
4302 #[test]
4303 fn test_security_warning_code_as_str_matches_serde_wire_form() {
4304 // `SecurityWarningCode::as_str()` is hand-written, while the JSON wire
4305 // form is derived from `#[serde(rename_all = "SCREAMING_SNAKE_CASE")]`.
4306 // JS consumers branch on the wire string (e.g. keying reinstall handling
4307 // off `SENDER_ADDRESS_MISMATCH`), so the two must never drift. Pin every
4308 // variant to its serialized form — a single-variant test would let the
4309 // others rot.
4310 let all = [
4311 SecurityWarningCode::SenderAddressMismatch,
4312 SecurityWarningCode::TransportIdentityMismatch,
4313 SecurityWarningCode::ControlSignatureInvalid,
4314 SecurityWarningCode::UnsignedControlRejected,
4315 SecurityWarningCode::MediaSenderGroupMismatch,
4316 SecurityWarningCode::PlaintextSend,
4317 SecurityWarningCode::PlaintextReceiveRejected,
4318 SecurityWarningCode::SessionSenderGroupMismatch,
4319 SecurityWarningCode::SessionRekeyTriggered,
4320 SecurityWarningCode::NostrKeyPackageSlotExhausted,
4321 SecurityWarningCode::PushKeyPackagePoolExhausted,
4322 SecurityWarningCode::RelayAddressBindingMismatch,
4323 SecurityWarningCode::RelayAddressDeclarationRefused,
4324 SecurityWarningCode::GroupLeafIdentityUnproven,
4325 SecurityWarningCode::StaleControlFrame,
4326 SecurityWarningCode::GatewayAddressBindingMismatch,
4327 SecurityWarningCode::GatewayAddressDeclarationRefused,
4328 SecurityWarningCode::KeyPackageOutsideValidityWindow,
4329 ];
4330 for code in all {
4331 // serde renders a unit enum variant as a quoted JSON string.
4332 let wire = serde_json::to_string(&code).unwrap();
4333 assert_eq!(
4334 format!("\"{}\"", code.as_str()),
4335 wire,
4336 "as_str() drifted from the serde wire form for {code:?}",
4337 );
4338 // Exhaustiveness guard (no wildcard): adding a variant makes this
4339 // match fail to compile until it is also added to `all` above and
4340 // pinned to its wire form.
4341 match code {
4342 SecurityWarningCode::SenderAddressMismatch
4343 | SecurityWarningCode::TransportIdentityMismatch
4344 | SecurityWarningCode::ControlSignatureInvalid
4345 | SecurityWarningCode::UnsignedControlRejected
4346 | SecurityWarningCode::MediaSenderGroupMismatch
4347 | SecurityWarningCode::PlaintextSend
4348 | SecurityWarningCode::PlaintextReceiveRejected
4349 | SecurityWarningCode::SessionSenderGroupMismatch
4350 | SecurityWarningCode::SessionRekeyTriggered
4351 | SecurityWarningCode::NostrKeyPackageSlotExhausted
4352 | SecurityWarningCode::PushKeyPackagePoolExhausted
4353 | SecurityWarningCode::RelayAddressBindingMismatch
4354 | SecurityWarningCode::RelayAddressDeclarationRefused
4355 | SecurityWarningCode::GroupLeafIdentityUnproven
4356 | SecurityWarningCode::StaleControlFrame
4357 | SecurityWarningCode::GatewayAddressBindingMismatch
4358 | SecurityWarningCode::GatewayAddressDeclarationRefused
4359 | SecurityWarningCode::KeyPackageOutsideValidityWindow => {}
4360 }
4361 }
4362 }
4363
4364 #[test]
4365 fn test_debug_redacts_every_peer_identifying_field() {
4366 // `SecurityWarning` printed its `peer_id` verbatim while the other
4367 // twelve peer-bearing arms redacted theirs, so a single missed arm was
4368 // invisible: `{:?}` on any *other* event looked correct. Pinning one
4369 // arm would leave the next omission just as invisible, so this
4370 // enumerates every variant carrying a peer-identifying field and
4371 // asserts the sentinel never survives formatting.
4372 //
4373 // Deliberately a *value* assertion rather than a field-name one: the
4374 // question is whether the id reaches the log, not how the arm spells
4375 // its placeholder.
4376 const SENTINEL: &str = "off1qy4aspkf0u8qptc6rlpn9ra8vw5jd9ereq4cwpfs";
4377
4378 let events = vec![
4379 Event::NeighborDiscovered {
4380 peer_id: SENTINEL.to_string(),
4381 transport: "ble".to_string(),
4382 rssi: Some(-40),
4383 },
4384 Event::NeighborLost {
4385 peer_id: SENTINEL.to_string(),
4386 },
4387 Event::SecureSessionEstablished {
4388 peer_id: SENTINEL.to_string(),
4389 group_id: "session:a:b".to_string(),
4390 is_session: true,
4391 initiated_by_local: true,
4392 },
4393 Event::SecureSessionFailed {
4394 peer_id: SENTINEL.to_string(),
4395 reason: "nope".to_string(),
4396 },
4397 Event::ConvergenceDiag {
4398 stage: "stage".to_string(),
4399 peer_id: SENTINEL.to_string(),
4400 detail: "detail".to_string(),
4401 },
4402 Event::WelcomeSendAttempted {
4403 peer_id: SENTINEL.to_string(),
4404 message_id: "m1".to_string(),
4405 group_id: "g1".to_string(),
4406 attempt: 1,
4407 },
4408 Event::WelcomeSendSucceeded {
4409 peer_id: SENTINEL.to_string(),
4410 message_id: "m1".to_string(),
4411 group_id: "g1".to_string(),
4412 attempt: 1,
4413 },
4414 Event::WelcomeSendFailed {
4415 peer_id: SENTINEL.to_string(),
4416 message_id: "m1".to_string(),
4417 group_id: "g1".to_string(),
4418 attempt: 1,
4419 reason_code: WelcomeReasonCode::Timeout,
4420 transport_error: None,
4421 retryable: true,
4422 next_retry_at: None,
4423 },
4424 Event::WelcomeSendExpired {
4425 peer_id: SENTINEL.to_string(),
4426 message_id: "m1".to_string(),
4427 attempt: 3,
4428 reason_code: WelcomeReasonCode::RetryExhausted,
4429 },
4430 Event::ServiceDiscovered {
4431 query_id: "q1".to_string(),
4432 service_id: "s1".to_string(),
4433 version: "1".to_string(),
4434 provider_peer_id: SENTINEL.to_string(),
4435 capabilities: HashMap::new(),
4436 hop_count: 1,
4437 },
4438 Event::ServiceResponseReceived {
4439 request_id: "r1".to_string(),
4440 service_id: "s1".to_string(),
4441 status: "ok".to_string(),
4442 body: "body".to_string(),
4443 provider_peer_id: SENTINEL.to_string(),
4444 encrypted: true,
4445 },
4446 Event::PresenceUpdated {
4447 peer_id: SENTINEL.to_string(),
4448 status: PresenceStatus::Online,
4449 timestamp: 0,
4450 last_seen_ms: None,
4451 source: PresenceSource::Peer,
4452 },
4453 Event::SecurityWarning {
4454 peer_id: SENTINEL.to_string(),
4455 reason_code: SecurityWarningCode::SenderAddressMismatch,
4456 reason: "mismatch".to_string(),
4457 },
4458 ];
4459
4460 for event in &events {
4461 let rendered = format!("{:?}", event);
4462 assert!(
4463 !rendered.contains(SENTINEL),
4464 "Debug leaked a peer identifier: {rendered}",
4465 );
4466 }
4467 }
4468
4469 /// Mirrors serde's `rename_all = "snake_case"` rule.
4470 fn serde_snake_case(name: &str) -> String {
4471 let mut out = String::new();
4472 for (i, ch) in name.chars().enumerate() {
4473 if ch.is_ascii_uppercase() {
4474 if i > 0 {
4475 out.push('_');
4476 }
4477 out.push(ch.to_ascii_lowercase());
4478 } else {
4479 out.push(ch);
4480 }
4481 }
4482 out
4483 }
4484
4485 /// Drift guard: every `Event` variant must have a typed declaration in the
4486 /// React Native bindings. Events cross UniFFI as tagged JSON, so nothing
4487 /// else fails when `types.ts` lags — the event just arrives untyped and
4488 /// invisible to the `ProtocolEvent` union (7 variants had silently drifted
4489 /// before this guard existed).
4490 #[test]
4491 fn react_native_types_cover_all_event_variants() {
4492 use std::collections::BTreeSet;
4493
4494 let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
4495 let events_rs = std::fs::read_to_string(manifest_dir.join("src/events.rs")).unwrap();
4496 let types_ts_path = manifest_dir.join("../../bindings/react-native/src/types.ts");
4497 let types_ts = std::fs::read_to_string(&types_ts_path)
4498 .unwrap_or_else(|e| panic!("cannot read {}: {e}", types_ts_path.display()));
4499
4500 // Collect each `Event` variant's serde tag by scanning the enum block:
4501 // variant names sit at 4-space indent, brace depth 1.
4502 let mut rust_tags = BTreeSet::new();
4503 let mut in_enum = false;
4504 let mut depth = 0usize;
4505 for line in events_rs.lines() {
4506 if !in_enum {
4507 if line.starts_with("pub enum Event {") {
4508 in_enum = true;
4509 depth = 1;
4510 }
4511 continue;
4512 }
4513 let trimmed = line.trim();
4514 if trimmed.starts_with("//") || trimmed.starts_with("#[") {
4515 continue;
4516 }
4517 if depth == 1
4518 && line.starts_with(" ")
4519 && !line.starts_with(" ")
4520 && trimmed
4521 .chars()
4522 .next()
4523 .is_some_and(|c| c.is_ascii_uppercase())
4524 {
4525 let name: String = trimmed
4526 .chars()
4527 .take_while(|c| c.is_ascii_alphanumeric())
4528 .collect();
4529 rust_tags.insert(serde_snake_case(&name));
4530 }
4531 depth += line.matches('{').count();
4532 depth = depth.saturating_sub(line.matches('}').count());
4533 if depth == 0 {
4534 break;
4535 }
4536 }
4537 assert!(
4538 rust_tags.len() >= 60,
4539 "enum scan looks broken: only {} variants found",
4540 rust_tags.len()
4541 );
4542
4543 // Event interface discriminants in types.ts: ` type: '<tag>';` at
4544 // exactly 2-space indent (nested object fields sit deeper).
4545 let ts_tags: BTreeSet<String> = types_ts
4546 .lines()
4547 .filter_map(|l| l.strip_prefix(" type: '"))
4548 .filter_map(|rest| rest.strip_suffix("';"))
4549 .map(str::to_string)
4550 .collect();
4551
4552 // Emitted by the native iOS/Android bridges, not the core enum.
4553 let bridge_only: BTreeSet<String> = [
4554 "diagnostic",
4555 "internet_server_message",
4556 "internet_status_changed",
4557 "internet_session_superseded",
4558 // Android only: the mesh foreground service's notification has no
4559 // iOS counterpart.
4560 "mesh_stopped_by_user",
4561 ]
4562 .map(str::to_string)
4563 .into();
4564
4565 let missing: Vec<_> = rust_tags.difference(&ts_tags).collect();
4566 assert!(
4567 missing.is_empty(),
4568 "Event variants missing a typed declaration in bindings/react-native/src/types.ts \
4569 (add the interface AND its ProtocolEvent union entry): {missing:?}"
4570 );
4571
4572 let stale: Vec<_> = ts_tags
4573 .difference(&rust_tags)
4574 .filter(|t| !bridge_only.contains(*t))
4575 .collect();
4576 assert!(
4577 stale.is_empty(),
4578 "types.ts declares event tags with no core Event variant \
4579 (stale, or a new bridge-only event that needs allowlisting here): {stale:?}"
4580 );
4581 }
4582
4583 /// Drift guard for the *payload* side of the same seam: apps switch on
4584 /// `reason_code`, so a code with no entry in the RN union is invisible to
4585 /// exhaustive handling on the app side and silently falls into whatever
4586 /// default a `switch` has. `NOSTR_KEY_PACKAGE_SLOT_EXHAUSTED` had already
4587 /// drifted this way before this guard existed.
4588 #[test]
4589 fn react_native_types_cover_all_security_warning_codes() {
4590 use std::collections::BTreeSet;
4591
4592 let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
4593 let events_rs = std::fs::read_to_string(manifest_dir.join("src/events.rs")).unwrap();
4594 let types_ts_path = manifest_dir.join("../../bindings/react-native/src/types.ts");
4595 let types_ts = std::fs::read_to_string(&types_ts_path)
4596 .unwrap_or_else(|e| panic!("cannot read {}: {e}", types_ts_path.display()));
4597
4598 // The wire forms are exactly the string literals `as_str` maps to, and
4599 // the test above already pins those to serde's rendering.
4600 // Anchored on the impl block: several enums in this file have an
4601 // identical `as_str` signature, and the first match is a different one.
4602 let as_str_body = events_rs
4603 .split_once("impl SecurityWarningCode {")
4604 .expect("impl SecurityWarningCode not found")
4605 .1
4606 .split_once(" pub fn as_str(&self) -> &'static str {")
4607 .expect("SecurityWarningCode::as_str not found")
4608 .1
4609 .split_once("\n }")
4610 .expect("as_str body not terminated")
4611 .0;
4612 let rust_codes: BTreeSet<String> = as_str_body
4613 .lines()
4614 .filter_map(|l| l.split_once("=> \""))
4615 .filter_map(|(_, rest)| rest.split_once('"'))
4616 .map(|(code, _)| code.to_string())
4617 .collect();
4618
4619 // Negative control: a scan that silently matched nothing would make
4620 // every assertion below vacuously true. The floor tracks the variant
4621 // count loosely — it exists to catch a broken scan, not to freeze the
4622 // taxonomy, so it moves when variants are deliberately added or (as
4623 // when the TOFU codes were deleted) removed.
4624 assert!(
4625 rust_codes.len() >= 11,
4626 "as_str scan looks broken: only {} codes found",
4627 rust_codes.len()
4628 );
4629
4630 let union = types_ts
4631 .split_once("export type SecurityWarningCode =")
4632 .expect("SecurityWarningCode union not found in types.ts")
4633 .1
4634 .split_once(';')
4635 .expect("SecurityWarningCode union not terminated")
4636 .0;
4637 let ts_codes: BTreeSet<String> = union
4638 .lines()
4639 .filter_map(|l| l.trim().strip_prefix("| '"))
4640 .filter_map(|rest| rest.strip_suffix('\''))
4641 .map(str::to_string)
4642 .collect();
4643
4644 let missing: Vec<_> = rust_codes.difference(&ts_codes).collect();
4645 assert!(
4646 missing.is_empty(),
4647 "SecurityWarningCode variants missing from the union in \
4648 bindings/react-native/src/types.ts: {missing:?}"
4649 );
4650
4651 let stale: Vec<_> = ts_codes.difference(&rust_codes).collect();
4652 assert!(
4653 stale.is_empty(),
4654 "types.ts declares security warning codes with no Rust variant: {stale:?}"
4655 );
4656 }
4657
4658 /// The same drift guard for `PresenceSource`, which had none.
4659 ///
4660 /// This union is the discriminator on the one event that merges two
4661 /// unrelated streams, and the documented advice is to filter on it, so an
4662 /// app that switches exhaustively over the TS union silently drops every
4663 /// event carrying a source TypeScript has never heard of. Nothing else
4664 /// catches that: unlike `SecurityWarningCode` there is no `as_str` here,
4665 /// the wire form is serde's alone, and a new variant compiles and ships
4666 /// green on both sides of a seam that disagrees.
4667 #[test]
4668 fn react_native_types_cover_all_presence_sources() {
4669 use std::collections::BTreeSet;
4670
4671 let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
4672 let events_rs = std::fs::read_to_string(manifest_dir.join("src/events.rs")).unwrap();
4673 let types_ts_path = manifest_dir.join("../../bindings/react-native/src/types.ts");
4674 let types_ts = std::fs::read_to_string(&types_ts_path)
4675 .unwrap_or_else(|e| panic!("cannot read {}: {e}", types_ts_path.display()));
4676
4677 // Scanned from the source text rather than from a hand-kept list of
4678 // variants, because a hand-kept list is the thing that drifts.
4679 let body = events_rs
4680 .split_once("pub enum PresenceSource {")
4681 .expect("PresenceSource not found")
4682 .1
4683 .split_once(
4684 "
4685}",
4686 )
4687 .expect("PresenceSource body not terminated")
4688 .0;
4689 let rust_sources: BTreeSet<String> = body
4690 .lines()
4691 .map(str::trim)
4692 .filter(|l| !l.starts_with("//") && !l.starts_with("#["))
4693 .filter_map(|l| l.strip_suffix(','))
4694 .filter(|name| !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric()))
4695 .map(|name| serde_snake_case(name))
4696 .collect();
4697
4698 // Negative control: an empty scan would make both assertions below
4699 // vacuously true.
4700 assert!(
4701 rust_sources.len() >= 2,
4702 "PresenceSource scan looks broken: only {} found",
4703 rust_sources.len()
4704 );
4705
4706 // Pins the scan against serde itself, so a rename rule change is
4707 // caught here rather than in an app's switch statement.
4708 assert_eq!(
4709 serde_json::to_string(&PresenceSource::Internet).unwrap(),
4710 "\"internet\"",
4711 "serde's rendering of PresenceSource changed"
4712 );
4713
4714 let union = types_ts
4715 .split_once("export type PresenceSource =")
4716 .expect("PresenceSource union not found in types.ts")
4717 .1
4718 .split_once(';')
4719 .expect("PresenceSource union not terminated")
4720 .0;
4721 let ts_sources: BTreeSet<String> = union
4722 .split('|')
4723 .map(str::trim)
4724 .filter_map(|t| t.strip_prefix('\''))
4725 .filter_map(|t| t.strip_suffix('\''))
4726 .map(str::to_string)
4727 .collect();
4728
4729 let missing: Vec<_> = rust_sources.difference(&ts_sources).collect();
4730 assert!(
4731 missing.is_empty(),
4732 "PresenceSource variants missing from the union in \
4733 bindings/react-native/src/types.ts: {missing:?}"
4734 );
4735
4736 let stale: Vec<_> = ts_sources.difference(&rust_sources).collect();
4737 assert!(
4738 stale.is_empty(),
4739 "types.ts declares presence sources with no Rust variant: {stale:?}"
4740 );
4741 }
4742}