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