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::JmapBackend::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#![forbid(unsafe_code)]
54// bd:JMAP-uqhn.2 — narrowing and sign-changing `as` casts are banned;
55// use `try_from`. Widening `usize as u64` stays legal (these lints do
56// not fire on it): it is lossless on every target Rust supports.
57#![warn(
58    clippy::cast_possible_truncation,
59    clippy::cast_possible_wrap,
60    clippy::cast_sign_loss
61)]
62
63use std::sync::Arc;
64
65use jmap_server::{CallContext, ClosureHandler, Dispatcher, HandlerFuture, JmapHandler};
66
67mod backend;
68mod ban;
69mod chat;
70mod contact;
71mod did_auth;
72mod emoji;
73mod ephemeral;
74mod expiry;
75mod helpers;
76mod invite;
77/// In-memory reference implementation of [`ChatBackend`].
78///
79/// Gated behind `feature = "memory"`. Not production. See [`memory`] for
80/// the full module documentation.
81#[cfg(feature = "memory")]
82pub mod memory;
83pub mod message;
84mod outbound;
85mod permissions;
86mod position;
87mod presence;
88mod push;
89mod space;
90
91pub use backend::{
92    AttachmentBlob, ChatBackend, ChatLimits, EmojiSetOp, InviteJoinRefusal, OpResult, SlowModeError,
93};
94pub use ban::{handle_ban_changes, handle_ban_get, handle_ban_set};
95pub use chat::{
96    handle_chat_changes, handle_chat_get, handle_chat_query, handle_chat_query_changes,
97    handle_chat_set, handle_chat_typing,
98};
99pub use contact::{
100    handle_contact_changes, handle_contact_get, handle_contact_query, handle_contact_query_changes,
101    handle_contact_set,
102};
103pub use did_auth::{DidAuthRejection, DidDocument, verify_did_binding};
104pub use emoji::{
105    handle_emoji_changes, handle_emoji_get, handle_emoji_query, handle_emoji_query_changes,
106    handle_emoji_set,
107};
108pub use ephemeral::{
109    CompanionStreams, EphemeralSubscription, IdScope, project_presence, should_deliver_typing,
110};
111pub use expiry::sweep_expired;
112pub use invite::{handle_invite_changes, handle_invite_get, handle_invite_set};
113pub use jmap_chat_types::{
114    ChatContactProperty, ChatProperty, MessageProperty, ReadPositionProperty, SpaceProperty,
115};
116pub use jmap_chat_types::{SpaceMetadataPatch, SpacePatchOp};
117pub use outbound::{GroupUpdateAction, OutboundEvent, ReactionAction};
118pub use permissions::{
119    RequiredPermissions, required_permissions_for_op, resolve_channel_permissions,
120};
121pub use position::{handle_position_changes, handle_position_get, handle_position_set};
122pub use presence::{handle_presence_changes, handle_presence_get, handle_presence_set};
123pub use push::{
124    BuiltPush, OwnerFlags, PushItem, build_chat_message_push, chat_state_change_for,
125    fit_chat_message_push, owner_unread_count, should_push, strip_unsupported_chat_push,
126    validate_chat_push,
127};
128pub use space::{
129    handle_space_changes, handle_space_get, handle_space_join, handle_space_query,
130    handle_space_query_changes, handle_space_set,
131};
132
133// ---------------------------------------------------------------------------
134// register_chat_handlers — the main entry point for consumers
135// ---------------------------------------------------------------------------
136
137/// Register all JMAP Chat method handlers with `dispatcher`.
138///
139/// `backend` is wrapped in [`Arc`] so it is cloned cheaply into each handler.
140/// You may pass any `Arc<B>` — the function clones it internally into each
141/// registered handler closure. Sharing the same `Arc<B>` across this call
142/// and other application-level uses of the backend is a memory
143/// optimization, not a correctness requirement; separate `Arc<B>` instances
144/// pointing at the same underlying backend would also work.
145///
146/// After this call, the dispatcher handles:
147/// `Chat/*`, `Message/*`, `Space/*`, `SpaceBan/*`, `ChatContact/*`,
148/// `ReadPosition/*`, `CustomEmoji/*`, `SpaceInvite/*`, and `PresenceStatus/*`.
149///
150/// The dispatcher's `CallerCtx` is taken from `B::CallerCtx`; every registered
151/// closure forwards it as `&ctx` into the wrapped `handle_*` function. Backends
152/// that use `type CallerCtx = ()` therefore see `&()` inside every handler.
153///
154/// # Re-registration semantics
155///
156/// This function calls [`Dispatcher::register`] once per
157/// draft-atwood-jmap-chat-00 method name. `Dispatcher::register`
158/// **silently overwrites** any pre-existing handler under the same
159/// method name (the underlying primitive is `HashMap::insert`). Three
160/// consequences callers MUST be aware of:
161///
162/// - **Double-call**: invoking this function twice on the same
163///   dispatcher loses the first set's handlers. The second call wins.
164/// - **Custom overrides go LAST**: to replace a single handler (e.g.
165///   provide a custom `Chat/get`), call this function FIRST, then
166///   `dispatcher.register("Chat/get", my_override)`. The inverse
167///   order silently undoes the custom handler.
168/// - **No collision diagnostic**: there is no error or log when a
169///   handler is overwritten. The contract is "last register wins" and
170///   the caller is responsible for ordering.
171///
172/// [`Dispatcher::register`]: jmap_server::Dispatcher::register
173pub fn register_chat_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
174where
175    B: ChatBackend + 'static,
176{
177    // Helper: register one method with a closure that takes
178    // (Arc<B>, call_id, args, ctx).
179    //
180    // `$ci` is the call_id string (echoed back to the client). Most handlers
181    // ignore it and use `_ci` as the identifier.
182    //
183    // `$ctx` is the per-request caller context (`B::CallerCtx`) forwarded
184    // by the dispatcher. Closures pass `&ctx` to the inner `handle_*` fn.
185    // Each optional trailing ident binds the `CallContext` field of that name:
186    // `created_ids`, the request-wide creation id map (RFC 8620 §5.3) that
187    // `/set` handlers use to resolve `#creationId` references, or `using`,
188    // the request's capability list (draft-ietf-jmap-metadata-04 §3).
189    macro_rules! reg {
190        ($method:expr, $backend:expr, |$b:ident, $ci:ident, $a:ident, $ctx:ident $(, $field:ident)*| $body:expr) => {{
191            let backend_arc: Arc<B> = Arc::clone(&$backend);
192            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler::new(
193                backend_arc,
194                move |$b: Arc<B>, cx: CallContext<B::CallerCtx>| {
195                    let CallContext {
196                        call_id: $ci,
197                        args: $a,
198                        caller: $ctx,
199                        $($field,)*
200                        ..
201                    } = cx;
202                    Box::pin(async move { $body }) as HandlerFuture
203                },
204            ));
205            dispatcher.register($method, h);
206        }};
207    }
208
209    // Chat
210    reg!("Chat/get", backend, |b, _ci, a, ctx, using| {
211        handle_chat_get(&*b, &ctx, a, &using).await
212    });
213    reg!("Chat/changes", backend, |b, _ci, a, ctx, using| {
214        handle_chat_changes(&*b, &ctx, a, &using).await
215    });
216    reg!("Chat/query", backend, |b, _ci, a, ctx, using| {
217        handle_chat_query(&*b, &ctx, a, &using).await
218    });
219    reg!("Chat/queryChanges", backend, |b, _ci, a, ctx, using| {
220        handle_chat_query_changes(&*b, &ctx, a, &using).await
221    });
222    reg!("Chat/set", backend, |b, _ci, a, ctx, created_ids, using| {
223        handle_chat_set(&*b, &ctx, &created_ids, a, &using).await
224    });
225    reg!("Chat/typing", backend, |b, _ci, a, ctx| {
226        handle_chat_typing(&*b, &ctx, a).await
227    });
228
229    // Message
230    reg!("Message/get", backend, |b, _ci, a, ctx, using| {
231        message::handle_message_get(&*b, &ctx, a, &using).await
232    });
233    reg!("Message/changes", backend, |b, _ci, a, ctx, using| {
234        message::handle_message_changes(&*b, &ctx, a, &using).await
235    });
236    reg!("Message/query", backend, |b, _ci, a, ctx, using| {
237        message::handle_message_query(&*b, &ctx, a, &using).await
238    });
239    reg!("Message/queryChanges", backend, |b, _ci, a, ctx, using| {
240        message::handle_message_query_changes(&*b, &ctx, a, &using).await
241    });
242    reg!(
243        "Message/set",
244        backend,
245        |b, _ci, a, ctx, created_ids, using| {
246            message::handle_message_set(&*b, &ctx, &created_ids, a, &using).await
247        }
248    );
249
250    // Space
251    reg!("Space/get", backend, |b, _ci, a, ctx, using| {
252        handle_space_get(&*b, &ctx, a, &using).await
253    });
254    reg!("Space/changes", backend, |b, _ci, a, ctx, using| {
255        handle_space_changes(&*b, &ctx, a, &using).await
256    });
257    reg!("Space/query", backend, |b, _ci, a, ctx, using| {
258        handle_space_query(&*b, &ctx, a, &using).await
259    });
260    reg!("Space/queryChanges", backend, |b, _ci, a, ctx, using| {
261        handle_space_query_changes(&*b, &ctx, a, &using).await
262    });
263    reg!(
264        "Space/set",
265        backend,
266        |b, _ci, a, ctx, created_ids, using| {
267            handle_space_set(&*b, &ctx, &created_ids, a, &using).await
268        }
269    );
270    reg!("Space/join", backend, |b, _ci, a, ctx| {
271        handle_space_join(&*b, &ctx, a).await
272    });
273
274    // ChatContact
275    reg!("ChatContact/get", backend, |b, _ci, a, ctx| {
276        handle_contact_get(&*b, &ctx, a).await
277    });
278    reg!("ChatContact/changes", backend, |b, _ci, a, ctx| {
279        handle_contact_changes(&*b, &ctx, a).await
280    });
281    reg!("ChatContact/query", backend, |b, _ci, a, ctx| {
282        handle_contact_query(&*b, &ctx, a).await
283    });
284    reg!("ChatContact/queryChanges", backend, |b, _ci, a, ctx| {
285        handle_contact_query_changes(&*b, &ctx, a).await
286    });
287    reg!("ChatContact/set", backend, |b, _ci, a, ctx| {
288        handle_contact_set(&*b, &ctx, a).await
289    });
290
291    // ReadPosition
292    reg!("ReadPosition/get", backend, |b, _ci, a, ctx| {
293        handle_position_get(&*b, &ctx, a).await
294    });
295    reg!("ReadPosition/changes", backend, |b, _ci, a, ctx| {
296        handle_position_changes(&*b, &ctx, a).await
297    });
298    reg!(
299        "ReadPosition/set",
300        backend,
301        |b, _ci, a, ctx, created_ids| handle_position_set(&*b, &ctx, &created_ids, a).await
302    );
303
304    // SpaceInvite
305    reg!("SpaceInvite/get", backend, |b, _ci, a, ctx| {
306        handle_invite_get(&*b, &ctx, a).await
307    });
308    reg!("SpaceInvite/changes", backend, |b, _ci, a, ctx| {
309        handle_invite_changes(&*b, &ctx, a).await
310    });
311    reg!("SpaceInvite/set", backend, |b, _ci, a, ctx, created_ids| {
312        handle_invite_set(&*b, &ctx, &created_ids, a).await
313    });
314
315    // SpaceBan
316    reg!("SpaceBan/get", backend, |b, _ci, a, ctx| {
317        handle_ban_get(&*b, &ctx, a).await
318    });
319    reg!("SpaceBan/changes", backend, |b, _ci, a, ctx| {
320        handle_ban_changes(&*b, &ctx, a).await
321    });
322    reg!("SpaceBan/set", backend, |b, _ci, a, ctx, created_ids| {
323        handle_ban_set(&*b, &ctx, &created_ids, a).await
324    });
325
326    // CustomEmoji
327    reg!("CustomEmoji/get", backend, |b, _ci, a, ctx| {
328        handle_emoji_get(&*b, &ctx, a).await
329    });
330    reg!("CustomEmoji/changes", backend, |b, _ci, a, ctx| {
331        handle_emoji_changes(&*b, &ctx, a).await
332    });
333    reg!("CustomEmoji/query", backend, |b, _ci, a, ctx| {
334        handle_emoji_query(&*b, &ctx, a).await
335    });
336    reg!("CustomEmoji/queryChanges", backend, |b, _ci, a, ctx| {
337        handle_emoji_query_changes(&*b, &ctx, a).await
338    });
339    reg!("CustomEmoji/set", backend, |b, _ci, a, ctx, created_ids| {
340        handle_emoji_set(&*b, &ctx, &created_ids, a).await
341    });
342
343    // PresenceStatus
344    reg!("PresenceStatus/get", backend, |b, _ci, a, ctx| {
345        handle_presence_get(&*b, &ctx, a).await
346    });
347    reg!("PresenceStatus/changes", backend, |b, _ci, a, ctx| {
348        handle_presence_changes(&*b, &ctx, a).await
349    });
350    reg!("PresenceStatus/set", backend, |b, _ci, a, ctx| {
351        handle_presence_set(&*b, &ctx, a).await
352    });
353}