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