Skip to main content

jmap_chat_server/
lib.rs

1//! JMAP Chat extension method handlers.
2//!
3//! # Usage
4//!
5//! Implement [`ChatBackend`] for your storage layer, then call
6//! [`register_chat_handlers`] to wire all method names into a
7//! [`jmap_server::Dispatcher`]:
8//!
9//! ```rust,no_run
10//! # use std::sync::Arc;
11//! # use jmap_chat_server::{ChatBackend, register_chat_handlers};
12//! # use jmap_server::Dispatcher;
13//! # fn example<B: ChatBackend<CallerCtx = ()> + 'static>(backend: B) {
14//! let mut dispatcher: Dispatcher<()> = Dispatcher::new();
15//! register_chat_handlers(&mut dispatcher, Arc::new(backend));
16//! # }
17//! ```
18//!
19//! # `memory` feature (reference implementation)
20//!
21//! Enable the `memory` feature to expose the `memory::MemoryBackend`
22//! reference implementation of [`ChatBackend`]. This is the same
23//! backend used by this crate's own integration tests, intended for
24//! downstream contributors to study and for smoke tests / examples
25//! that do not want to stand up a real database. **Not production.**
26//! API stability is opt-in via this feature and may break across minor
27//! versions while the crate is pre-1.0.
28//!
29//! # Permission enforcement: backend canonical
30//!
31//! All Space/set permission gates live in the backend's
32//! `apply_space_patch` implementation (see `memory::MemoryBackend`
33//! under the `memory` feature for the reference impl). The handler
34//! [`handle_space_set`] does NOT permission-check.
35//!
36//! The pure helper [`required_permissions_for_op`]
37//! maps each [`SpacePatchOp`] variant to its required
38//! [`ChatPermission`](jmap_chat_types::ChatPermission)s per draft-atwood-jmap-chat-00 §Space/set. Backends consume this
39//! helper inside `apply_space_patch` after resolving the caller's
40//! effective permissions from the Space `members` entry whose `id` is
41//! the `accountId` (the owner, per draft §Terminology). The gates apply
42//! whether or not [`jmap_server::JmapAccounts::principal_id`] resolves a
43//! caller identity.
44//! Handlers MUST NOT consume the helper for gating — backends are the
45//! single source of truth. This mirrors the workspace-wide rule
46//! documented in workspace AGENTS.md "Caller identity (foundation
47//! seam)":
48//!
49//! - Handlers do NO permission checking.
50//! - Defense-in-depth handler pre-checks are allowed but the backend
51//!   MUST re-verify atomically with the mutation.
52
53#![cfg_attr(docsrs, feature(doc_cfg))]
54#![forbid(unsafe_code)]
55// bd:JMAP-uqhn.2 — narrowing and sign-changing `as` casts are banned;
56// use `try_from`. Widening `usize as u64` stays legal (these lints do
57// not fire on it): it is lossless on every target Rust supports.
58#![warn(
59    clippy::cast_possible_truncation,
60    clippy::cast_possible_wrap,
61    clippy::cast_sign_loss
62)]
63
64use std::sync::Arc;
65
66use jmap_server::{
67    CallContext, ClosureHandler, ConditionalBackend, Dispatcher, HandlerFuture, JmapHandler,
68    RegistrationError, SetSupport,
69};
70
71mod backend;
72mod ban;
73mod chat;
74mod chat_ban;
75mod contact;
76mod did_auth;
77mod emoji;
78mod ephemeral;
79mod expiry;
80mod helpers;
81mod history;
82mod invite;
83/// In-memory reference implementation of [`ChatBackend`].
84///
85/// Gated behind `feature = "memory"`. Not production. See [`memory`] for
86/// the full module documentation.
87#[cfg(feature = "memory")]
88pub mod memory;
89pub mod message;
90mod outbound;
91mod permissions;
92mod position;
93mod presence;
94mod push;
95mod space;
96#[cfg(feature = "testkit")]
97pub mod testkit;
98
99pub use backend::{
100    AttachmentBlob, ChatAccessPolicy, ChatBackend, ChatEvents, ChatLimits, ChatMessageLifecycle,
101    ChatModeration, ChatResolvers, ChatRestrictions, ChatSettings, ChatSpaces, ChatStore,
102    EmojiSetOp, InviteJoinRefusal, OpResult, SlowModeError, SpacePolicy,
103};
104pub use backend::{
105    DelegateChatAccessPolicy, DelegateChatEvents, DelegateChatMessageLifecycle,
106    DelegateChatModeration, DelegateChatResolvers, DelegateChatRestrictions, DelegateChatSettings,
107    DelegateChatSpaces, DelegateChatStore, DelegateSpacePolicy,
108};
109pub use ban::{handle_ban_changes, handle_ban_get, handle_ban_set};
110pub use chat::{
111    handle_chat_changes, handle_chat_get, handle_chat_query, handle_chat_query_changes,
112    handle_chat_set, handle_chat_typing,
113};
114pub use chat_ban::{handle_chat_ban_changes, handle_chat_ban_get, handle_chat_ban_set};
115pub use contact::{
116    handle_contact_changes, handle_contact_get, handle_contact_query, handle_contact_query_changes,
117    handle_contact_set,
118};
119pub use did_auth::{DidAuthRejection, DidDocument, verify_did_binding};
120pub use emoji::{
121    handle_emoji_changes, handle_emoji_get, handle_emoji_query, handle_emoji_query_changes,
122    handle_emoji_set,
123};
124pub use ephemeral::{
125    CompanionStreams, EphemeralSubscription, IdScope, project_presence, should_deliver_typing,
126};
127pub use expiry::sweep_expired;
128pub use history::register_chat_handlers_with_history;
129pub use invite::{handle_invite_changes, handle_invite_get, handle_invite_set};
130pub use jmap_chat_types::{
131    ChatContactProperty, ChatProperty, MessageProperty, ReadPositionProperty, SpaceProperty,
132};
133pub use jmap_chat_types::{SpaceMetadataPatch, SpacePatchOp};
134pub use outbound::{GroupUpdateAction, OutboundEvent, ReactionAction};
135pub use permissions::{
136    RequiredPermissions, required_permissions_for_op, resolve_channel_permissions,
137};
138pub use position::{handle_position_changes, handle_position_get, handle_position_set};
139pub use presence::{handle_presence_changes, handle_presence_get, handle_presence_set};
140pub use push::{
141    BuiltPush, OwnerFlags, PushItem, build_chat_message_push, chat_state_change_for,
142    fit_chat_message_push, owner_unread_count, should_push, strip_unsupported_chat_push,
143    validate_chat_push,
144};
145pub use space::{
146    handle_space_changes, handle_space_get, handle_space_join, handle_space_query,
147    handle_space_query_changes, handle_space_set,
148};
149
150// ---------------------------------------------------------------------------
151// register_chat_handlers — the main entry point for consumers
152// ---------------------------------------------------------------------------
153
154/// Register all JMAP Chat method handlers with `dispatcher`.
155///
156/// `backend` is wrapped in [`Arc`] so it is cloned cheaply into each handler.
157/// You may pass any `Arc<B>` — the function clones it internally into each
158/// registered handler closure. Sharing the same `Arc<B>` across this call
159/// and other application-level uses of the backend is a memory
160/// optimization, not a correctness requirement; separate `Arc<B>` instances
161/// pointing at the same underlying backend would also work.
162///
163/// After this call, the dispatcher handles:
164/// `Chat/*`, `Message/*`, `Space/*`, `SpaceBan/*`, `ChatBan/*`, `ChatContact/*`,
165/// `ReadPosition/*`, `CustomEmoji/*`, `SpaceInvite/*`, and `PresenceStatus/*`.
166///
167/// The dispatcher's `CallerCtx` is taken from `B::CallerCtx`; every registered
168/// closure forwards it as `&ctx` into the wrapped `handle_*` function. Backends
169/// that use `type CallerCtx = ()` therefore see `&()` inside every handler.
170///
171/// # Re-registration semantics
172///
173/// This function calls [`Dispatcher::register`] once per
174/// draft-atwood-jmap-chat-00 method name. `Dispatcher::register`
175/// **silently overwrites** any pre-existing handler under the same
176/// method name (the underlying primitive is `HashMap::insert`). Three
177/// consequences callers MUST be aware of:
178///
179/// - **Double-call**: invoking this function twice on the same
180///   dispatcher loses the first set's handlers. The second call wins.
181/// - **Custom overrides go LAST**: to replace a single handler (e.g.
182///   provide a custom `Chat/get`), call this function FIRST, then
183///   `dispatcher.register("Chat/get", my_override)`. The inverse
184///   order silently undoes the custom handler.
185/// - **No collision diagnostic**: there is no error or log when a
186///   handler is overwritten. The contract is "last register wins" and
187///   the caller is responsible for ordering.
188///
189/// [`Dispatcher::register`]: jmap_server::Dispatcher::register
190pub fn register_chat_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
191where
192    B: ChatBackend + 'static,
193{
194    // Helper: register one method with a closure that takes
195    // (Arc<B>, call_id, args, ctx).
196    //
197    // `$ci` is the call_id string (echoed back to the client). Most handlers
198    // ignore it and use `_ci` as the identifier.
199    //
200    // `$ctx` is the per-request caller context (`B::CallerCtx`) forwarded
201    // by the dispatcher. Closures pass `&ctx` to the inner `handle_*` fn.
202    // Each optional trailing ident binds the `CallContext` field of that name:
203    // `created_ids`, the request-wide creation id map (RFC 8620 §5.3) that
204    // `/set` handlers use to resolve `#creationId` references, or `using`,
205    // the request's capability list (draft-ietf-jmap-metadata-05 §3).
206    macro_rules! reg {
207        ($method:expr, $backend:expr, |$b:ident, $ci:ident, $a:ident, $ctx:ident $(, $field:ident)*| $body:expr) => {{
208            let backend_arc: Arc<B> = Arc::clone(&$backend);
209            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
210                backend_arc,
211                move |$b: Arc<B>, cx: CallContext<B::CallerCtx>| {
212                    let CallContext {
213                        call_id: $ci,
214                        args: $a,
215                        caller: $ctx,
216                        $($field,)*
217                        ..
218                    } = cx;
219                    Box::pin(async move { $body }) as HandlerFuture
220                },
221            ));
222            dispatcher.register($method, h);
223        }};
224    }
225
226    // Chat
227    reg!("Chat/get", backend, |b, _ci, a, ctx, using| {
228        handle_chat_get(&*b, &ctx, a, &using).await
229    });
230    reg!("Chat/changes", backend, |b, _ci, a, ctx, using| {
231        handle_chat_changes(&*b, &ctx, a, &using).await
232    });
233    reg!("Chat/query", backend, |b, _ci, a, ctx, using| {
234        handle_chat_query(&*b, &ctx, a, &using).await
235    });
236    reg!("Chat/queryChanges", backend, |b, _ci, a, ctx, using| {
237        handle_chat_query_changes(&*b, &ctx, a, &using).await
238    });
239    reg!("Chat/set", backend, |b, _ci, a, ctx, created_ids, using| {
240        handle_chat_set(&*b, &ctx, &created_ids, a, &using).await
241    });
242    reg!("Chat/typing", backend, |b, _ci, a, ctx| {
243        handle_chat_typing(&*b, &ctx, a).await
244    });
245
246    // Message
247    reg!("Message/get", backend, |b, _ci, a, ctx, using| {
248        message::handle_message_get(&*b, &ctx, a, &using).await
249    });
250    reg!("Message/changes", backend, |b, _ci, a, ctx, using| {
251        message::handle_message_changes(&*b, &ctx, a, &using).await
252    });
253    reg!("Message/query", backend, |b, _ci, a, ctx, using| {
254        message::handle_message_query(&*b, &ctx, a, &using).await
255    });
256    reg!("Message/queryChanges", backend, |b, _ci, a, ctx, using| {
257        message::handle_message_query_changes(&*b, &ctx, a, &using).await
258    });
259    reg!(
260        "Message/set",
261        backend,
262        |b, _ci, a, ctx, created_ids, using| {
263            message::handle_message_set(&*b, &ctx, &created_ids, a, &using).await
264        }
265    );
266
267    // Space
268    reg!("Space/get", backend, |b, _ci, a, ctx, using| {
269        handle_space_get(&*b, &ctx, a, &using).await
270    });
271    reg!("Space/changes", backend, |b, _ci, a, ctx, using| {
272        handle_space_changes(&*b, &ctx, a, &using).await
273    });
274    reg!("Space/query", backend, |b, _ci, a, ctx, using| {
275        handle_space_query(&*b, &ctx, a, &using).await
276    });
277    reg!("Space/queryChanges", backend, |b, _ci, a, ctx, using| {
278        handle_space_query_changes(&*b, &ctx, a, &using).await
279    });
280    reg!(
281        "Space/set",
282        backend,
283        |b, _ci, a, ctx, created_ids, using| {
284            handle_space_set(&*b, &ctx, &created_ids, a, &using).await
285        }
286    );
287    reg!("Space/join", backend, |b, _ci, a, ctx| {
288        handle_space_join(&*b, &ctx, a).await
289    });
290
291    // ChatContact
292    reg!("ChatContact/get", backend, |b, _ci, a, ctx| {
293        handle_contact_get(&*b, &ctx, a).await
294    });
295    reg!("ChatContact/changes", backend, |b, _ci, a, ctx| {
296        handle_contact_changes(&*b, &ctx, a).await
297    });
298    reg!("ChatContact/query", backend, |b, _ci, a, ctx| {
299        handle_contact_query(&*b, &ctx, a).await
300    });
301    reg!("ChatContact/queryChanges", backend, |b, _ci, a, ctx| {
302        handle_contact_query_changes(&*b, &ctx, a).await
303    });
304    reg!("ChatContact/set", backend, |b, _ci, a, ctx| {
305        handle_contact_set(&*b, &ctx, a).await
306    });
307
308    // ReadPosition
309    reg!("ReadPosition/get", backend, |b, _ci, a, ctx| {
310        handle_position_get(&*b, &ctx, a).await
311    });
312    reg!("ReadPosition/changes", backend, |b, _ci, a, ctx| {
313        handle_position_changes(&*b, &ctx, a).await
314    });
315    reg!(
316        "ReadPosition/set",
317        backend,
318        |b, _ci, a, ctx, created_ids| handle_position_set(&*b, &ctx, &created_ids, a).await
319    );
320
321    // SpaceInvite
322    reg!("SpaceInvite/get", backend, |b, _ci, a, ctx| {
323        handle_invite_get(&*b, &ctx, a).await
324    });
325    reg!("SpaceInvite/changes", backend, |b, _ci, a, ctx| {
326        handle_invite_changes(&*b, &ctx, a).await
327    });
328    reg!("SpaceInvite/set", backend, |b, _ci, a, ctx, created_ids| {
329        handle_invite_set(&*b, &ctx, &created_ids, a).await
330    });
331
332    // SpaceBan
333    reg!("SpaceBan/get", backend, |b, _ci, a, ctx| {
334        handle_ban_get(&*b, &ctx, a).await
335    });
336    reg!("SpaceBan/changes", backend, |b, _ci, a, ctx| {
337        handle_ban_changes(&*b, &ctx, a).await
338    });
339    reg!("SpaceBan/set", backend, |b, _ci, a, ctx, created_ids| {
340        handle_ban_set(&*b, &ctx, &created_ids, a).await
341    });
342
343    // ChatBan
344    reg!("ChatBan/get", backend, |b, _ci, a, ctx| {
345        handle_chat_ban_get(&*b, &ctx, a).await
346    });
347    reg!("ChatBan/changes", backend, |b, _ci, a, ctx| {
348        handle_chat_ban_changes(&*b, &ctx, a).await
349    });
350    reg!("ChatBan/set", backend, |b, _ci, a, ctx, created_ids| {
351        handle_chat_ban_set(&*b, &ctx, &created_ids, a).await
352    });
353
354    // CustomEmoji
355    reg!("CustomEmoji/get", backend, |b, _ci, a, ctx| {
356        handle_emoji_get(&*b, &ctx, a).await
357    });
358    reg!("CustomEmoji/changes", backend, |b, _ci, a, ctx| {
359        handle_emoji_changes(&*b, &ctx, a).await
360    });
361    reg!("CustomEmoji/query", backend, |b, _ci, a, ctx| {
362        handle_emoji_query(&*b, &ctx, a).await
363    });
364    reg!("CustomEmoji/queryChanges", backend, |b, _ci, a, ctx| {
365        handle_emoji_query_changes(&*b, &ctx, a).await
366    });
367    reg!("CustomEmoji/set", backend, |b, _ci, a, ctx, created_ids| {
368        handle_emoji_set(&*b, &ctx, &created_ids, a).await
369    });
370
371    // PresenceStatus
372    reg!("PresenceStatus/get", backend, |b, _ci, a, ctx| {
373        handle_presence_get(&*b, &ctx, a).await
374    });
375    reg!("PresenceStatus/changes", backend, |b, _ci, a, ctx| {
376        handle_presence_changes(&*b, &ctx, a).await
377    });
378    reg!("PresenceStatus/set", backend, |b, _ci, a, ctx| {
379        handle_presence_set(&*b, &ctx, a).await
380    });
381}
382
383/// Opt this crate's registered Foo/set methods in to
384/// draft-ietf-jmap-conditional-02 (`ifUnchangedBy` and `atomic`;
385/// docs/design/DECISIONS.md decisions 1 and 17).
386///
387/// Call after [`register_chat_handlers`]. Attaches [`SetSupport`] to each
388/// of `Chat/set`, `Message/set`, `Space/set`, `ChatContact/set`,
389/// `ReadPosition/set`, `SpaceInvite/set`, `SpaceBan/set`, `ChatBan/set`,
390/// `CustomEmoji/set` and `PresenceStatus/set` that is registered, and skips
391/// the rest; no handler is re-registered. For `PushSubscription/set`, call
392/// [`jmap_server::register_push_subscription_conditional`] too.
393///
394/// The dispatcher reads preconditions through each type's `/get` and runs
395/// each call in the scope `backend` opens
396/// ([`ConditionalBackend::begin_set`]). Under `atomic` that scope must hold
397/// back outbound federation and lifecycle effects until commit and check
398/// cross-object constraints (CustomEmoji names, the push subscription cap)
399/// against the final state; the memory backend does. Advertise
400/// `urn:ietf:params:jmap:conditional` only once
401/// [`Dispatcher::conditional_ready`] is true for the whole dispatcher.
402pub fn register_chat_conditional<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
403where
404    B: ChatBackend + ConditionalBackend + 'static,
405{
406    fn attach<C: Clone + Send + 'static>(
407        dispatcher: &mut Dispatcher<C>,
408        method: &str,
409        support: SetSupport<C>,
410    ) {
411        match dispatcher.attach_set_support(method, support) {
412            Ok(()) | Err(RegistrationError::NotRegistered(_)) => {}
413            Err(e) => unreachable!("{method} pairs with its own data type: {e}"),
414        }
415    }
416    macro_rules! attach {
417        ($($t:ident),*) => {$(
418            attach(
419                dispatcher,
420                concat!(stringify!($t), "/set"),
421                SetSupport::new::<jmap_chat_types::$t, B>(Arc::clone(&backend)),
422            );
423        )*};
424    }
425    attach!(
426        Chat,
427        Message,
428        Space,
429        ChatContact,
430        ReadPosition,
431        SpaceInvite,
432        SpaceBan,
433        ChatBan,
434        CustomEmoji,
435        PresenceStatus
436    );
437}