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`] in [`permissions`]
37//! maps each [`SpacePatchOp`] variant to its required permission strings
38//! 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 via [`jmap_server::JmapBackend::principal_id`].
41//! Handlers MUST NOT consume the helper for gating — backends are the
42//! single source of truth. This mirrors the workspace-wide rule
43//! documented in workspace AGENTS.md "Caller identity (foundation
44//! seam)" (bd:JMAP-ga0q):
45//!
46//! - Handlers do NO permission checking.
47//! - Defense-in-depth handler pre-checks are allowed but the backend
48//!   MUST re-verify atomically with the mutation.
49//! - A `None` return from `JmapBackend::principal_id` means the
50//!   deployment has not wired identity; chat permission semantics
51//!   cannot be honored and the backend MUST reject the patch rather
52//!   than fail open.
53
54#![forbid(unsafe_code)]
55
56use std::sync::Arc;
57
58use jmap_server::{Dispatcher, HandlerFuture, JmapHandler};
59
60pub mod backend;
61pub mod ban;
62pub mod chat;
63pub mod contact;
64pub mod emoji;
65mod helpers;
66pub mod invite;
67/// In-memory reference implementation of [`ChatBackend`].
68///
69/// Gated behind `feature = "memory"`. Not production. See [`memory`] for
70/// the full module documentation.
71#[cfg(feature = "memory")]
72pub mod memory;
73pub mod message;
74pub mod permissions;
75pub mod position;
76pub mod presence;
77pub mod space;
78
79pub use backend::{
80    AddedItem, BackendChangesError, BackendSetError, ChangesResult, ChatBackend, ChatLimits,
81    EmojiSetOp, GetObject, JmapBackend, JmapObject, OpResult, QueryChangesResult, QueryObject,
82    QueryResult, SetError, SetErrorType, SetObject, SlowModeError, SpacePatchOp,
83};
84pub use ban::{handle_ban_changes, handle_ban_get, handle_ban_set};
85pub use chat::{
86    handle_chat_changes, handle_chat_get, handle_chat_query, handle_chat_query_changes,
87    handle_chat_set, handle_chat_typing,
88};
89pub use contact::{
90    handle_contact_changes, handle_contact_get, handle_contact_query, handle_contact_query_changes,
91    handle_contact_set,
92};
93pub use emoji::{
94    handle_emoji_changes, handle_emoji_get, handle_emoji_query, handle_emoji_query_changes,
95    handle_emoji_set,
96};
97pub use invite::{handle_invite_changes, handle_invite_get, handle_invite_set};
98pub use message::{
99    handle_message_changes, handle_message_get, handle_message_query, handle_message_query_changes,
100    handle_message_set,
101};
102pub use permissions::{
103    required_permissions_for_op, MANAGE_CHANNELS, MANAGE_MEMBERS, MANAGE_ROLES, MANAGE_SPACE,
104};
105pub use position::{handle_position_changes, handle_position_get, handle_position_set};
106pub use presence::{handle_presence_changes, handle_presence_get, handle_presence_set};
107pub use space::{
108    handle_space_changes, handle_space_get, handle_space_join, handle_space_query,
109    handle_space_query_changes, handle_space_set,
110};
111
112// ---------------------------------------------------------------------------
113// register_chat_handlers — the main entry point for consumers
114// ---------------------------------------------------------------------------
115
116/// Register all JMAP Chat method handlers with `dispatcher`.
117///
118/// `backend` is wrapped in [`Arc`] so it is cloned cheaply into each handler.
119/// Pass the same `Arc<B>` to both this function and any application-level code
120/// that needs to access the backend.
121///
122/// After this call, the dispatcher handles:
123/// `Chat/*`, `Message/*`, `Space/*`, `SpaceBan/*`, `ChatContact/*`,
124/// `ReadPosition/*`, `CustomEmoji/*`, `SpaceInvite/*`, and `PresenceStatus/*`.
125///
126/// The dispatcher's `CallerCtx` is taken from `B::CallerCtx`; every registered
127/// closure forwards it as `&ctx` into the wrapped `handle_*` function. Backends
128/// that use `type CallerCtx = ()` therefore see `&()` inside every handler.
129pub fn register_chat_handlers<B>(dispatcher: &mut Dispatcher<B::CallerCtx>, backend: Arc<B>)
130where
131    B: ChatBackend + 'static,
132{
133    // Helper: register one method with a closure that takes
134    // (Arc<B>, call_id, args, ctx).
135    //
136    // `$ci` is the call_id string (echoed back to the client). Most handlers
137    // ignore it and use `_ci` as the identifier.
138    //
139    // `$ctx` is the per-request caller context (`B::CallerCtx`) forwarded
140    // by the dispatcher. Closures pass `&ctx` to the inner `handle_*` fn.
141    macro_rules! reg {
142        ($method:expr, $backend:expr, |$b:ident, $ci:ident, $a:ident, $ctx:ident| $body:expr) => {{
143            let backend_arc: Arc<B> = Arc::clone(&$backend);
144            let h: Arc<dyn JmapHandler<B::CallerCtx>> = Arc::new(ClosureHandler {
145                backend: backend_arc,
146                call_fn: Box::new(
147                    move |$b: Arc<B>, $ci: String, $a: serde_json::Value, $ctx: B::CallerCtx| {
148                        Box::pin(async move { $body }) as HandlerFuture
149                    },
150                ),
151            });
152            dispatcher.register($method, h);
153        }};
154    }
155
156    // Chat
157    reg!("Chat/get", backend, |b, _ci, a, ctx| {
158        handle_chat_get(&*b, &ctx, a).await
159    });
160    reg!("Chat/changes", backend, |b, _ci, a, ctx| {
161        handle_chat_changes(&*b, &ctx, a).await
162    });
163    reg!("Chat/query", backend, |b, _ci, a, ctx| {
164        handle_chat_query(&*b, &ctx, a).await
165    });
166    reg!("Chat/queryChanges", backend, |b, _ci, a, ctx| {
167        handle_chat_query_changes(&*b, &ctx, a).await
168    });
169    reg!("Chat/set", backend, |b, _ci, a, ctx| {
170        handle_chat_set(&*b, &ctx, a).await
171    });
172    reg!("Chat/typing", backend, |b, _ci, a, ctx| {
173        handle_chat_typing(&*b, &ctx, a).await
174    });
175
176    // Message
177    reg!("Message/get", backend, |b, _ci, a, ctx| {
178        handle_message_get(&*b, &ctx, a).await
179    });
180    reg!("Message/changes", backend, |b, _ci, a, ctx| {
181        handle_message_changes(&*b, &ctx, a).await
182    });
183    reg!("Message/query", backend, |b, _ci, a, ctx| {
184        handle_message_query(&*b, &ctx, a).await
185    });
186    reg!("Message/queryChanges", backend, |b, _ci, a, ctx| {
187        handle_message_query_changes(&*b, &ctx, a).await
188    });
189    reg!("Message/set", backend, |b, _ci, a, ctx| {
190        handle_message_set(&*b, &ctx, a).await
191    });
192
193    // Space
194    reg!("Space/get", backend, |b, _ci, a, ctx| {
195        handle_space_get(&*b, &ctx, a).await
196    });
197    reg!("Space/changes", backend, |b, _ci, a, ctx| {
198        handle_space_changes(&*b, &ctx, a).await
199    });
200    reg!("Space/query", backend, |b, _ci, a, ctx| {
201        handle_space_query(&*b, &ctx, a).await
202    });
203    reg!("Space/queryChanges", backend, |b, _ci, a, ctx| {
204        handle_space_query_changes(&*b, &ctx, a).await
205    });
206    reg!("Space/set", backend, |b, _ci, a, ctx| {
207        handle_space_set(&*b, &ctx, a).await
208    });
209    reg!("Space/join", backend, |b, _ci, a, ctx| {
210        handle_space_join(&*b, &ctx, a).await
211    });
212
213    // ChatContact
214    reg!("ChatContact/get", backend, |b, _ci, a, ctx| {
215        handle_contact_get(&*b, &ctx, a).await
216    });
217    reg!("ChatContact/changes", backend, |b, _ci, a, ctx| {
218        handle_contact_changes(&*b, &ctx, a).await
219    });
220    reg!("ChatContact/query", backend, |b, _ci, a, ctx| {
221        handle_contact_query(&*b, &ctx, a).await
222    });
223    reg!("ChatContact/queryChanges", backend, |b, _ci, a, ctx| {
224        handle_contact_query_changes(&*b, &ctx, a).await
225    });
226    reg!("ChatContact/set", backend, |b, _ci, a, ctx| {
227        handle_contact_set(&*b, &ctx, a).await
228    });
229
230    // ReadPosition
231    reg!("ReadPosition/get", backend, |b, _ci, a, ctx| {
232        handle_position_get(&*b, &ctx, a).await
233    });
234    reg!("ReadPosition/changes", backend, |b, _ci, a, ctx| {
235        handle_position_changes(&*b, &ctx, a).await
236    });
237    reg!("ReadPosition/set", backend, |b, _ci, a, ctx| {
238        handle_position_set(&*b, &ctx, a).await
239    });
240
241    // SpaceInvite
242    reg!("SpaceInvite/get", backend, |b, _ci, a, ctx| {
243        handle_invite_get(&*b, &ctx, a).await
244    });
245    reg!("SpaceInvite/changes", backend, |b, _ci, a, ctx| {
246        handle_invite_changes(&*b, &ctx, a).await
247    });
248    reg!("SpaceInvite/set", backend, |b, _ci, a, ctx| {
249        handle_invite_set(&*b, &ctx, a).await
250    });
251
252    // SpaceBan
253    reg!("SpaceBan/get", backend, |b, _ci, a, ctx| {
254        handle_ban_get(&*b, &ctx, a).await
255    });
256    reg!("SpaceBan/changes", backend, |b, _ci, a, ctx| {
257        handle_ban_changes(&*b, &ctx, a).await
258    });
259    reg!("SpaceBan/set", backend, |b, _ci, a, ctx| {
260        handle_ban_set(&*b, &ctx, a).await
261    });
262
263    // CustomEmoji
264    reg!("CustomEmoji/get", backend, |b, _ci, a, ctx| {
265        handle_emoji_get(&*b, &ctx, a).await
266    });
267    reg!("CustomEmoji/changes", backend, |b, _ci, a, ctx| {
268        handle_emoji_changes(&*b, &ctx, a).await
269    });
270    reg!("CustomEmoji/query", backend, |b, _ci, a, ctx| {
271        handle_emoji_query(&*b, &ctx, a).await
272    });
273    reg!("CustomEmoji/queryChanges", backend, |b, _ci, a, ctx| {
274        handle_emoji_query_changes(&*b, &ctx, a).await
275    });
276    reg!("CustomEmoji/set", backend, |b, _ci, a, ctx| {
277        handle_emoji_set(&*b, &ctx, a).await
278    });
279
280    // PresenceStatus
281    reg!("PresenceStatus/get", backend, |b, _ci, a, ctx| {
282        handle_presence_get(&*b, &ctx, a).await
283    });
284    reg!("PresenceStatus/changes", backend, |b, _ci, a, ctx| {
285        handle_presence_changes(&*b, &ctx, a).await
286    });
287    reg!("PresenceStatus/set", backend, |b, _ci, a, ctx| {
288        handle_presence_set(&*b, &ctx, a).await
289    });
290}
291
292pub use jmap_server::ClosureHandler;