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