Skip to main content

jmap_chat_server/
backend.rs

1//! ChatBackend trait and supporting types for JMAP Chat method handlers.
2//!
3//! Consumers implement [`ChatBackend`] for their storage system. The method
4//! handlers in sibling modules call into the backend through this trait.
5//!
6//! The read-side operations (`get_objects`, `get_state`, `get_changes`,
7//! `query_objects`, `query_changes`) are defined on the [`jmap_server::JmapBackend`]
8//! supertrait. Only write operations are here.
9//!
10//! Marker traits and property selector enums live in `jmap-types` and
11//! `jmap-chat-types` respectively; they are re-exported here for convenience.
12
13pub use jmap_chat_types::backend::{
14    ChatContactProperty, ChatProperty, MessageProperty, ReadPositionProperty, SpaceProperty,
15};
16pub use jmap_chat_types::space_set::SpacePatchOp;
17pub use jmap_server::{
18    AddedItem, BackendChangesError, BackendSetError, ChangesResult, GetObject, JmapBackend,
19    JmapObject, QueryChangesResult, QueryObject, QueryResult, SetError, SetErrorType, SetObject,
20};
21
22// ---------------------------------------------------------------------------
23// Space/set structural-mutation result
24// ---------------------------------------------------------------------------
25
26/// The outcome of a single [`SpacePatchOp`] applied by
27/// [`ChatBackend::apply_space_patch`].
28///
29/// `op_index` is the zero-based index of the op within the input `Vec`, used
30/// by handlers to construct a descriptive error message identifying which
31/// per-key entry failed (e.g. `addRoles[2] failed: ...`).
32///
33/// `outcome` is:
34/// - `Ok(Some(id))` — the op produced a new server-assigned id (e.g.
35///   [`SpacePatchOp::AddRole`], [`SpacePatchOp::AddChannel`],
36///   [`SpacePatchOp::AddCategory`]). The handler reports this id back to
37///   the client via the `/set` response.
38/// - `Ok(None)` — the op completed but produced no id (every `Remove*` and
39///   `Update*` variant).
40/// - `Err(SetError)` — the op was rejected (e.g. permission denied, target
41///   id not found, role hierarchy violation, count limit exceeded).
42///
43/// Per RFC 8620 §5.3 `/set`, an update target is per-target atomic on the
44/// wire: it appears in exactly one of `updated` or `notUpdated`. If **any**
45/// `OpResult` in the returned `Vec` has an `Err`, the handler reports the
46/// containing update target in `notUpdated`. The handler is free to choose
47/// which `Err` to surface; the reference handler surfaces the first.
48///
49/// This type lives in `jmap-chat-server` (not `jmap-chat-types`) because
50/// [`SetError`] is defined in `jmap-server` and `jmap-chat-types` cannot
51/// depend on it (per the workspace dependency rule: types crates depend
52/// only on `jmap-types`, `serde`, `serde_json`).
53#[derive(Debug)]
54pub struct OpResult {
55    /// Zero-based index of the originating op in the input `Vec<SpacePatchOp>`.
56    pub op_index: usize,
57    /// The outcome of applying that op.
58    pub outcome: Result<Option<jmap_types::Id>, SetError>,
59}
60
61// ---------------------------------------------------------------------------
62// Per-Space content limits
63// ---------------------------------------------------------------------------
64
65/// Implementation-defined per-Space content limits enforced by
66/// `Space/set` handlers.
67///
68/// Per draft-atwood-jmap-chat-00 §Space/set (spec commit `80d5e11`,
69/// 2026-05-11), each `add*` op on a Space MUST return an `overQuota`
70/// SetError (RFC 8620 §5.3) when the resulting count would exceed a
71/// server-defined limit. The spec does not name or normatively define
72/// the cap values; they are implementation-defined and may vary per
73/// account or per tenant.
74///
75/// Backends override [`ChatBackend::limits`] to supply their own values.
76/// The default impl returns conservative reference-impl-grade values
77/// suitable for tests and single-tenant dev servers; production
78/// deployments are expected to override.
79///
80/// Client visibility of these caps (when desired) is via JMAP Quotas
81/// (`urn:ietf:params:jmap:quotas`, RFC 9425), not via this struct.
82/// The `urn:ietf:params:jmap:chat` session capability does NOT advertise
83/// these caps (the previous cap-advertising fields `maxRolesPerSpace`,
84/// `maxSpaceMembers`, `maxChannelsPerSpace`, `maxCategoriesPerSpace`
85/// were removed from the draft in spec commit `80d5e11`).
86///
87/// See the workspace `AGENTS.md` "Backend caps and limits" section for
88/// the cross-extension pattern this struct establishes for JMAP Chat.
89#[non_exhaustive]
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub struct ChatLimits {
92    /// Maximum number of roles per Space. Enforced against the
93    /// resulting count after applying every `addRoles` entry in a
94    /// `Space/set` update patch.
95    pub max_roles_per_space: u32,
96    /// Maximum number of members per Space. Enforced against the
97    /// resulting count after applying every `addMembers` entry in a
98    /// `Space/set` update patch.
99    pub max_space_members: u32,
100    /// Maximum number of channels per Space. Enforced against the
101    /// resulting count after applying every `addChannels` entry in a
102    /// `Space/set` update patch. The current channel count is the sum
103    /// of `space.uncategorizedChannelIds.len()` and every
104    /// `space.categories[].channelIds.len()`.
105    pub max_channels_per_space: u32,
106    /// Maximum number of categories per Space. Enforced against the
107    /// resulting count after applying every `addCategories` entry in
108    /// a `Space/set` update patch.
109    pub max_categories_per_space: u32,
110}
111
112impl Default for ChatLimits {
113    fn default() -> Self {
114        Self {
115            max_roles_per_space: 50,
116            max_space_members: 10_000,
117            max_channels_per_space: 500,
118            max_categories_per_space: 100,
119        }
120    }
121}
122
123impl ChatLimits {
124    /// Construct a [`ChatLimits`] with the four cap fields specified
125    /// in declaration order: roles, members, channels, categories.
126    ///
127    /// The struct is `#[non_exhaustive]` so external callers (tests
128    /// using `MemoryBackend::set_limits_for_test`, production backends
129    /// overriding [`ChatBackend::limits`]) need a constructor to build
130    /// one. Future cap-field additions to [`ChatLimits`] are an
131    /// additive non-breaking change because the constructor stays
132    /// stable; callers wanting to override the new field combine
133    /// `ChatLimits::new(..)` with [`Self::with_max_roles_per_space`]
134    /// / [`Self::with_max_space_members`] /
135    /// [`Self::with_max_channels_per_space`] /
136    /// [`Self::with_max_categories_per_space`] and a future analogous
137    /// setter.
138    pub fn new(
139        max_roles_per_space: u32,
140        max_space_members: u32,
141        max_channels_per_space: u32,
142        max_categories_per_space: u32,
143    ) -> Self {
144        Self {
145            max_roles_per_space,
146            max_space_members,
147            max_channels_per_space,
148            max_categories_per_space,
149        }
150    }
151
152    /// Builder-style setter for [`Self::max_roles_per_space`].
153    #[must_use]
154    pub fn with_max_roles_per_space(mut self, max: u32) -> Self {
155        self.max_roles_per_space = max;
156        self
157    }
158
159    /// Builder-style setter for [`Self::max_space_members`].
160    #[must_use]
161    pub fn with_max_space_members(mut self, max: u32) -> Self {
162        self.max_space_members = max;
163        self
164    }
165
166    /// Builder-style setter for [`Self::max_channels_per_space`].
167    #[must_use]
168    pub fn with_max_channels_per_space(mut self, max: u32) -> Self {
169        self.max_channels_per_space = max;
170        self
171    }
172
173    /// Builder-style setter for [`Self::max_categories_per_space`].
174    #[must_use]
175    pub fn with_max_categories_per_space(mut self, max: u32) -> Self {
176        self.max_categories_per_space = max;
177        self
178    }
179}
180
181// ---------------------------------------------------------------------------
182// Custom emoji authorization gate
183// ---------------------------------------------------------------------------
184
185/// Identifies the kind of `CustomEmoji/set` operation being authorized by
186/// [`ChatBackend::may_set_custom_emoji`].
187///
188/// Per draft-atwood-jmap-chat-00 commit `9344aec` (2026-05-11, "refactor:
189/// implementation-defined emoji authorization"), authorization for
190/// `CustomEmoji/set` is fully implementation-defined for both server-global
191/// and Space-scoped emoji. The kit forwards the op kind so the backend can
192/// apply different policies per op (e.g. allow create+update but require
193/// elevated rights for destroy).
194#[non_exhaustive]
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum EmojiSetOp {
197    /// `CustomEmoji/set` `create` — a new emoji is being added.
198    Create,
199    /// `CustomEmoji/set` `update` — an existing emoji's mutable fields
200    /// (currently `name` and `blobId`) are being patched.
201    Update,
202    /// `CustomEmoji/set` `destroy` — an existing emoji is being removed.
203    Destroy,
204}
205
206// ---------------------------------------------------------------------------
207// Slow-mode rate-limit gate
208// ---------------------------------------------------------------------------
209
210/// Outcome of a [`ChatBackend::slow_mode_check`] rejection.
211///
212/// Per draft-atwood-jmap-chat-00 §Chat `slowModeSeconds` plus spec commit
213/// `de60acb` (2026-05-11) which softened the manage-channels exemption to
214/// SHOULD: a non-exempt member who sends faster than the configured rate
215/// MUST be rejected with a `rateLimited` SetError carrying a
216/// `serverRetryAfter` UTCDate that tells the client when it may retry.
217///
218/// `retry_after` is a fully-formed [`jmap_types::UTCDate`] — the backend
219/// has already done the arithmetic (typically "now + remaining slow-mode
220/// window"). The handler serialises it verbatim onto the wire as the
221/// `serverRetryAfter` SetError extra field.
222#[derive(Debug, Clone)]
223pub struct SlowModeError {
224    /// When the rate-limited sender may retry.
225    pub retry_after: jmap_types::UTCDate,
226}
227
228// ---------------------------------------------------------------------------
229// ChatBackend trait
230// ---------------------------------------------------------------------------
231
232/// Storage backend for JMAP Chat method handlers.
233///
234/// Implementors provide the actual data access; the method handler modules
235/// in this crate translate between JMAP wire protocol and backend calls.
236///
237/// Read-side operations (`get_objects`, `get_state`, `get_changes`,
238/// `query_objects`, `query_changes`) are defined on the [`JmapBackend`]
239/// supertrait. Only write operations and type introspection are here.
240///
241/// This trait is not object-safe by design (generic methods). Use
242/// `Arc<impl ChatBackend>` when sharing across tasks.
243pub trait ChatBackend: JmapBackend {
244    /// Create a new object.
245    ///
246    /// Returns `(assigned_id, created_object)` on success. `create_id` is the
247    /// client-side creation id used in the `/set` request.
248    fn create_object<O: SetObject + Send + Sync>(
249        &self,
250        caller: &Self::CallerCtx,
251        account_id: &jmap_types::Id,
252        create_id: &str,
253        obj: O,
254    ) -> impl std::future::Future<Output = Result<(jmap_types::Id, O), BackendSetError<Self::Error>>>
255           + Send;
256
257    /// Apply a partial update (patch) to an existing object.
258    ///
259    /// Returns `Some(updated_object)` if the backend modified any properties
260    /// beyond what the client requested (RFC 8620 §5.3 server-set field echo),
261    /// or `None` if the patch was applied verbatim.
262    fn update_object<O: SetObject + Send + Sync>(
263        &self,
264        caller: &Self::CallerCtx,
265        account_id: &jmap_types::Id,
266        id: &jmap_types::Id,
267        patch: O::Patch,
268    ) -> impl std::future::Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send;
269
270    /// Destroy an existing object by id.
271    fn destroy_object<O: SetObject + Send + Sync>(
272        &self,
273        caller: &Self::CallerCtx,
274        account_id: &jmap_types::Id,
275        id: &jmap_types::Id,
276    ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
277
278    /// Returns true if this account supports the given JMAP object type.
279    /// Called by the server consumer (e.g. the session capability builder) —
280    /// NOT called internally by the handler library. Backends that support all
281    /// types unconditionally can return `true` always.
282    fn supports_type<O: JmapObject>(&self) -> bool;
283
284    /// Generate a cryptographically random invite code.
285    ///
286    /// Implementations MUST use a CSPRNG seeded from OS entropy. The
287    /// recommended choices are [`rand::rngs::OsRng`] or the [`getrandom`]
288    /// crate directly. Do NOT use `rand::thread_rng()` for security-relevant
289    /// output: although current `rand` versions document `ThreadRng` as
290    /// cryptographically secure, its underlying algorithm is
291    /// implementation-defined and has changed across releases, and the
292    /// `rand` book explicitly routes security-sensitive callers to `OsRng`.
293    ///
294    /// The returned string must be unguessable — do NOT use timestamps,
295    /// sequential counters, or non-CSPRNG sources.
296    ///
297    /// # Constant-time comparison contract
298    ///
299    /// Consumers of the returned code (notably `Space/join` invite-code
300    /// lookup) MUST compare it against attacker-supplied values in
301    /// constant time using `subtle::ConstantTimeEq::ct_eq` or equivalent.
302    /// The reference handler in `space::handle_space_join` already does
303    /// this; backends that build their own invite-redemption paths must
304    /// preserve the invariant. A plain `String == String` short-circuits
305    /// at the first mismatched byte and exposes a byte-by-byte timing
306    /// oracle for credential recovery. See bd:JMAP-sc1b.89.
307    ///
308    /// [`rand::rngs::OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
309    /// [`getrandom`]: https://docs.rs/getrandom
310    fn generate_invite_code(&self) -> String;
311
312    /// Implementation-defined per-Space content limits for this caller
313    /// and account.
314    ///
315    /// Called by `handle_space_set` once per request, before
316    /// dispatching to [`Self::apply_space_patch`], to enforce
317    /// per-aggregate caps on roles, members, channels, and categories
318    /// per Space (draft-atwood-jmap-chat-00 §Space/set, spec commit
319    /// `80d5e11`).
320    ///
321    /// The default implementation returns [`ChatLimits::default`],
322    /// which carries conservative reference-impl-grade values. The
323    /// `caller` and `account_id` arguments are plumbed even though the
324    /// default impl ignores them, so production backends can vary caps
325    /// per-account (Free vs. Pro tier, multi-tenant SaaS, etc.)
326    /// without a future API break. Implementations SHOULD return
327    /// quickly (in-process struct construction, possibly off a cached
328    /// per-account record) — this method is called on the hot
329    /// `Space/set` path.
330    ///
331    /// Workspace cross-extension pattern: see `AGENTS.md` "Backend
332    /// caps and limits".
333    fn limits(&self, _caller: &Self::CallerCtx, _account_id: &jmap_types::Id) -> ChatLimits {
334        ChatLimits::default()
335    }
336
337    /// Apply a sequence of structural mutations to a Space
338    /// (draft-atwood-jmap-chat-00 §Space/set).
339    ///
340    /// `Space/set` `update` operations use semantic mutation keys
341    /// (`addRoles`, `removeRoles`, `addMembers`, …) rather than RFC 8620
342    /// JSON Pointer patches. The handler in `space::handle_space_set`
343    /// parses the wire object, unfolds each array entry into a
344    /// [`SpacePatchOp`] value, then calls this method with the resulting
345    /// ordered `Vec`.
346    ///
347    /// # Ordering and atomicity
348    ///
349    /// Implementations SHOULD apply ops in input order and SHOULD provide
350    /// best-effort transactional semantics so that a partial failure does
351    /// not leave the Space in a half-updated state. The reference
352    /// in-memory implementation locks the entire backend for the duration
353    /// of the call. A database-backed implementation should wrap the
354    /// sequence in a single transaction.
355    ///
356    /// # Permission and limit checks
357    ///
358    /// Handler-side permission gates (`manage_space`, `manage_roles`,
359    /// `manage_members`, `manage_channels`) are tracked in
360    /// `bd:JMAP-g7wu.2.4.7` and are NOT yet applied by the reference
361    /// handler; the backend is responsible for rejecting any op the
362    /// caller is not authorized to perform.
363    ///
364    /// Per-aggregate count limits on roles, members, channels, and
365    /// categories per Space are applied by `handle_space_set` *before*
366    /// it calls this method (bd:JMAP-g7wu.2.4.8). The handler queries
367    /// the backend's [`ChatBackend::limits`] once per request,
368    /// fetches the current Space, and rejects the whole update target
369    /// with an `overQuota` SetError (RFC 8620 §5.3) if any aggregate
370    /// would exceed its cap. This means an `apply_space_patch` call
371    /// that originates from `handle_space_set` will not contain
372    /// `Add*` ops that push the Space over cap. Backends called
373    /// directly (bypassing the handler) MAY enforce caps a second
374    /// time for defense in depth; the reference `MemoryBackend` does
375    /// not. Per draft-atwood-jmap-chat-00 §Space/set (spec commit
376    /// `80d5e11`, 2026-05-11), this behavior is normative.
377    ///
378    /// The role-position hierarchy check (members may only add or modify
379    /// roles whose `position` is strictly less than their own
380    /// highest-position role — draft §Space/set lines 1096, 1102) MUST
381    /// be enforced by the backend because it is atomic with the
382    /// mutation and depends on the current Space state. See
383    /// `bd:JMAP-g7wu.2.4.3`.
384    ///
385    /// # Return value
386    ///
387    /// On success, returns a `Vec<OpResult>` of the same length as `ops`,
388    /// in input order. Each entry reports the outcome of one op (id
389    /// assignment for `Add*` variants, error for rejections). The
390    /// handler maps per-op errors back into the `/set` response shape
391    /// per [`OpResult`]'s documentation.
392    ///
393    /// Returns [`BackendSetError::Other`] only for backend-level failures
394    /// (the storage layer is unreachable, the account does not exist,
395    /// `space_id` is unknown, etc.) — i.e. failures that prevent any op
396    /// from being attempted. Per-op rejections (permission denied,
397    /// invalid id, role hierarchy violation, etc.) go in the `outcome`
398    /// field of the returned [`OpResult`] vector, not in an error return.
399    fn apply_space_patch(
400        &self,
401        caller: &Self::CallerCtx,
402        account_id: &jmap_types::Id,
403        space_id: &jmap_types::Id,
404        ops: Vec<SpacePatchOp>,
405    ) -> impl std::future::Future<Output = Result<Vec<OpResult>, BackendSetError<Self::Error>>> + Send;
406
407    /// Apply a JSON Merge Patch to a Space's top-level metadata fields
408    /// (draft-atwood-jmap-chat-00 §Space/set, `name`, `description`,
409    /// `iconBlobId`, `isPublic`, `isPubliclyPreviewable`).
410    ///
411    /// `Space/set` `update` operations carrying *only* top-level
412    /// metadata fields (and not the semantic-mutation keys
413    /// `addRoles` / `addMembers` / `addChannels` / `addCategories`
414    /// etc.) route through this method instead of the generic
415    /// [`Self::update_object`]. Mixed patches carrying both top-level
416    /// metadata AND semantic-mutation keys call
417    /// [`Self::apply_space_patch`] first (for the structural ops) and
418    /// this method second (for the metadata). The handler at
419    /// `space::handle_space_set` is responsible for the split and for
420    /// stripping non-metadata keys before calling this method.
421    ///
422    /// # Permission and atomicity
423    ///
424    /// Per draft-atwood-jmap-chat-00, every top-level metadata field
425    /// carries the marker "Mutable by members with `manage_space`
426    /// permission". Implementations MUST gate the mutation on the
427    /// caller's effective permissions in the target Space:
428    ///
429    /// - If [`JmapBackend::principal_id`] returns `Some(caller_id)`,
430    ///   verify the caller holds `manage_space` (resolved through the
431    ///   Space's role hierarchy). Reject the patch with
432    ///   [`SetErrorType::Forbidden`] if not.
433    /// - If [`JmapBackend::principal_id`] returns `None` (single-user
434    ///   mode — the backend has not wired identity), the gate is
435    ///   skipped. This is consistent with the workspace AGENTS.md
436    ///   "Caller identity (foundation seam)" section: a backend that
437    ///   does not honor identity-dependent semantics opts out.
438    ///
439    /// The check fires inside this method atomically with the
440    /// mutation: snapshot the Space's role/member state, evaluate
441    /// the permission gate, and apply the merge patch in one
442    /// critical section. Backend canonical per workspace AGENTS.md.
443    ///
444    /// # `patch_map` shape
445    ///
446    /// The handler builds `patch_map` by walking the wire patch and
447    /// keeping only the keys in `METADATA_FIELDS` (`name`,
448    /// `description`, `iconBlobId`, `isPublic`,
449    /// `isPubliclyPreviewable`). Backends MAY validate the values
450    /// further (e.g. reject `iconBlobId` referencing a non-existent
451    /// blob) and surface those as [`SetError`] returns.
452    ///
453    /// # Return value
454    ///
455    /// `Ok(Some(updated_space))` if the backend modified any
456    /// properties beyond what the client requested (RFC 8620 §5.3
457    /// server-set field echo, e.g. a normalised `name` or a derived
458    /// `iconBlobId`). `Ok(None)` if the patch was applied verbatim.
459    /// `Err(BackendSetError::SetError(SetError::new(Forbidden)))`
460    /// when the caller fails the `manage_space` gate.
461    ///
462    /// History: this method landed in bd:JMAP-g7wu.2.4.13 to close the
463    /// gate gap on the top-level metadata path. Before this method
464    /// existed, `Space/set` `update` routed top-level metadata
465    /// through the generic `update_object::<Space>`, which has no
466    /// permission gate. A caller without `manage_space` could
467    /// successfully mutate a Space's `name` / `description` /
468    /// `isPublic` / etc.
469    fn apply_space_metadata_patch(
470        &self,
471        caller: &Self::CallerCtx,
472        account_id: &jmap_types::Id,
473        space_id: &jmap_types::Id,
474        patch_map: serde_json::Map<String, serde_json::Value>,
475    ) -> impl std::future::Future<
476        Output = Result<Option<jmap_chat_types::Space>, BackendSetError<Self::Error>>,
477    > + Send;
478
479    /// Whether the backend should reject `RemoveMember` ops that would
480    /// leave the target Space with zero members holding either
481    /// `manage_members` or `manage_space` permission.
482    ///
483    /// # Why this exists
484    ///
485    /// The 2026-05-12 design reversal dropped the `Space.ownerId` field
486    /// (bd:JMAP-g7wu.2.4.12): "who controls a Space" is now fully
487    /// implementation-defined / out-of-band per draft-atwood-jmap-chat-00.
488    /// Without a normative owner identity, the kit cannot enforce the
489    /// previous "owner cannot be removed" rule. Instead the kit exposes
490    /// this purely permission-graph-based knob: production backends that
491    /// want to prevent the "no admin left" failure mode return `true`
492    /// (the trait default); deployments with their own designated
493    /// controller principal or external admin-tracking system can opt
494    /// out by returning `false`.
495    ///
496    /// # Default implementation
497    ///
498    /// Returns `true` — production-safe by default. A third-party
499    /// backend that does not override this method gets last-admin
500    /// protection automatically.
501    ///
502    /// # Why the reference `MemoryBackend` overrides this to `false`
503    ///
504    /// The reference impl flips the default to keep existing
505    /// integration tests (which do not seed admin memberships) passing
506    /// unchanged. Tests that exercise the protection path opt in via
507    /// `MemoryBackend::set_protect_last_admin_for_test(true)`. See
508    /// `bd:JMAP-g7wu.2.4.3`.
509    ///
510    /// # Atomicity
511    ///
512    /// The check fires inside [`Self::apply_space_patch`] atomically
513    /// with the candidate `RemoveMember` mutation: the backend
514    /// snapshots the Space's member/role state, projects the post-
515    /// removal admin count, and rejects the whole update target with
516    /// a `forbidden` SetError if zero admins would remain.
517    fn protect_last_admin(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> bool {
518        let _ = (caller, account_id);
519        true
520    }
521
522    /// Whether the backend retains edit history for messages.
523    ///
524    /// Per draft-atwood-jmap-chat-00 commit `0783fc4` ("condition
525    /// MessageRevision push on edit-history retention") +
526    /// `§Message editHistory`: servers MAY limit retained
527    /// MessageRevisions, and when the server does not retain edit
528    /// history, the `editHistory` field MUST be omitted from
529    /// `Message/get` and (in principle) `Message/changes` responses.
530    /// `Message/changes` per RFC 8620 §5.2 returns only id arrays,
531    /// not Message objects, so the spec's "omit from /changes" is
532    /// a no-op at the wire level — the kit only enforces the
533    /// `Message/get` projection.
534    ///
535    /// # When the handler calls this
536    ///
537    /// `handle_message_get` consults this predicate once per call.
538    /// When `false`, every returned `Message` has its
539    /// `edit_history` field set to `None` before serialization,
540    /// which serde's `skip_serializing_if = "Option::is_none"`
541    /// collapses to a wire-absent field per spec.
542    ///
543    /// # Why sync, not async
544    ///
545    /// This is a static deployment-policy flag, not a per-call
546    /// decision — it does not consult per-account state, principal
547    /// identity, or per-message bounds. Production backends that
548    /// need to vary retention per-account would file a follow-up
549    /// bead for a parallel `retains_edit_history_for_account` hook
550    /// rather than reshaping this method.
551    ///
552    /// # Default implementation
553    ///
554    /// Returns `false` — no retention. This matches the workspace's
555    /// "kit defines the hook; consumer enforces the policy" posture.
556    /// Production backends that retain edit history MUST override
557    /// this to `true`; the reference `MemoryBackend` exposes a
558    /// test-only setter for tests that need the retain-on path.
559    fn retains_edit_history(&self) -> bool {
560        false
561    }
562
563    /// Predicate consulted by typing/presence fan-out paths: is the
564    /// requesting caller blocked by the given contact?
565    ///
566    /// Per draft-atwood-jmap-chat-00 commit `d68b4e3` (2026-05-11,
567    /// "close blocked-sender suppression gaps for typing/presence"):
568    /// when the requesting account corresponds to a [`ChatContact`]
569    /// whose `blocked` is `true` on the recipient's contact list, the
570    /// server MUST silently suppress the ephemeral event for that
571    /// recipient. The sender is NOT informed.
572    ///
573    /// [`ChatContact`]: jmap_chat_types::ChatContact
574    ///
575    /// # When the handler calls this
576    ///
577    /// `handle_chat_typing` consults this predicate when the target
578    /// `Chat` is direct (a single recipient identified by
579    /// `Chat.contact_id`). The kit does not implement transport-layer
580    /// fan-out (push events to subscribers) — that is the consumer's
581    /// responsibility — so the consultation result does not change
582    /// the handler's wire response. The call site is the documented
583    /// integration point: production transport that fans typing
584    /// events out to subscribers SHOULD consult this predicate
585    /// before each per-recipient event.
586    ///
587    /// Group / channel chats are skipped on the kit side. The kit
588    /// handler has no way to enumerate fan-out recipients; that work
589    /// belongs to the consumer's transport layer, which must call
590    /// this predicate per recipient.
591    ///
592    /// # Default implementation
593    ///
594    /// Returns `Ok(false)` — no one is blocked. This is appropriate
595    /// for backends that have not yet implemented contact lists, and
596    /// it matches the workspace's "kit defines the hook; consumer
597    /// enforces the policy" posture.
598    fn is_contact_blocked(
599        &self,
600        _caller: &Self::CallerCtx,
601        _account_id: &jmap_types::Id,
602        _contact_id: &jmap_types::Id,
603    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
604        async { Ok(false) }
605    }
606
607    /// Authorization gate consulted by `handle_emoji_set` before every
608    /// `CustomEmoji/set` create, update, or destroy.
609    ///
610    /// Per draft-atwood-jmap-chat-00 commit `9344aec` (2026-05-11,
611    /// "refactor: implementation-defined emoji authorization"):
612    /// authorization for `CustomEmoji/set` is fully
613    /// implementation-defined, for both server-global and Space-scoped
614    /// emoji. When the caller is not authorized, the handler emits a
615    /// `forbidden` SetError (RFC 8620 §5.3).
616    ///
617    /// # `target_space_id` semantics
618    ///
619    /// `target_space_id` is the **actual scope of the emoji this op
620    /// targets**:
621    ///
622    /// - `None` — the emoji is server-global (its `spaceId` field is
623    ///   absent / null).
624    /// - `Some(id)` — the emoji is scoped to that Space (its `spaceId`
625    ///   field equals `id`).
626    ///
627    /// For `Create`, the handler reads the scope from the create
628    /// payload. For `Update` and `Destroy`, the handler pre-fetches
629    /// the existing emoji via `get_objects` and passes its current
630    /// `spaceId`. If the pre-fetch reports the id as not found, the
631    /// handler skips this gate entirely and lets `update_object` /
632    /// `destroy_object` surface a `notFound` SetError naturally — a
633    /// non-existent target consumes no authorization decision.
634    ///
635    /// # When the handler calls this
636    ///
637    /// Exactly once per create/update/destroy entry in the request,
638    /// AFTER wire-format validation has succeeded and BEFORE the
639    /// corresponding `create_object` / `update_object` /
640    /// `destroy_object` call. On `Ok(false)` the handler maps to a
641    /// `forbidden` SetError and skips the underlying mutation.
642    /// On `Err(e)` the handler maps to a `serverFail` SetError.
643    ///
644    /// # Default implementation
645    ///
646    /// The default returns `Ok(true)` — every op is permitted. This
647    /// matches the workspace's "kit defines the hook; consumer
648    /// enforces the policy" posture (see the parallel design of
649    /// [`Self::slow_mode_check`]). Production backends SHOULD override
650    /// this method to apply the deployment's permission model — e.g.
651    /// "only members of `target_space_id` may modify a Space-scoped
652    /// emoji" or "only `manage_emoji` permission-holders may modify
653    /// server-global emoji."
654    ///
655    /// # Foundation seam
656    ///
657    /// Backends that wish to identify the caller call
658    /// [`jmap_server::JmapBackend::principal_id`] on `caller` and
659    /// compare against the Space's `members` list, ACLs, or whatever
660    /// permission model the deployment uses. Backends whose
661    /// `principal_id` returns `None` (the workspace default, see the
662    /// "Caller identity (foundation seam)" section of the workspace
663    /// `AGENTS.md`) cannot meaningfully implement identity-scoped
664    /// authorization — they should either override `principal_id`
665    /// first or return `Ok(true)` to match the reference posture.
666    fn may_set_custom_emoji(
667        &self,
668        _caller: &Self::CallerCtx,
669        _account_id: &jmap_types::Id,
670        _target_space_id: Option<&jmap_types::Id>,
671        _op: EmojiSetOp,
672    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
673        async { Ok(true) }
674    }
675
676    /// Throttle gate consulted before a `Message/set` create lands on
677    /// the rate-limited path.
678    ///
679    /// Per draft-atwood-jmap-chat-00 §Chat `slowModeSeconds` plus spec
680    /// commit `de60acb` (2026-05-11, "soften slow-mode exemption to
681    /// SHOULD with rationale"): a `Chat` with `slowModeSeconds > 0`
682    /// throttles the rate at which a member may post messages. The
683    /// spec SHOULD-exempts members holding the `manage_channels`
684    /// permission, and servers MAY define additional exempt
685    /// principals. The kit does not opine on the exemption set — the
686    /// backend implements the policy.
687    ///
688    /// When the caller is throttled, the backend returns
689    /// `Err(`[`SlowModeError`]`)` with `retry_after` set to a UTCDate
690    /// the rate-limited sender may use to schedule a retry. The
691    /// `Message/set` create handler maps the error onto a
692    /// `rateLimited` SetError (RFC 8620 §5.3 `SetError.type`) whose
693    /// `serverRetryAfter` extra field carries the UTCDate verbatim.
694    ///
695    /// # When the handler calls this
696    ///
697    /// `handle_message_set` invokes `slow_mode_check` once per create
698    /// entry, after wire-format validation has succeeded and before
699    /// `create_object`. A throttle rejection short-circuits to
700    /// `notCreated[create_id] = { type: "rateLimited",
701    /// serverRetryAfter: <UTCDate> }` and the create_object call is
702    /// never made.
703    ///
704    /// # Default implementation
705    ///
706    /// The default returns `Ok(())` — no throttle. This is appropriate
707    /// for backends that have not yet implemented rate-tracking and
708    /// for single-tenant dev servers where no abuse path exists.
709    /// Production backends SHOULD override this method with their own
710    /// per-(account, chat, caller) rate tracker.
711    ///
712    /// # No state on the kit
713    ///
714    /// The kit deliberately does not provide a reference rate-tracker
715    /// — that is deployment territory. The reference `MemoryBackend`
716    /// keeps the default no-op behaviour for the same reason.
717    fn slow_mode_check(
718        &self,
719        _caller: &Self::CallerCtx,
720        _account_id: &jmap_types::Id,
721        _chat_id: &jmap_types::Id,
722    ) -> impl std::future::Future<Output = Result<(), SlowModeError>> + Send {
723        async { Ok(()) }
724    }
725
726    /// Hard-delete a message ("expire" it) due to a per-message expiry
727    /// event.
728    ///
729    /// Called by the kit from two places:
730    ///
731    /// 1. The `Message/set` update handler when a patch sets `readAt` on
732    ///    a message whose pre-patch `burnOnRead` is `true`
733    ///    (draft-atwood-jmap-chat-00 §Message `burnOnRead`).
734    /// 2. A deployment-provided scheduler when a message's
735    ///    `senderExpiresAt` fires (draft-atwood-jmap-chat-00 §Message
736    ///    `senderExpiresAt`). The kit does NOT run a scheduler;
737    ///    consumers wire one in and call this method directly when a
738    ///    timer fires.
739    ///
740    /// # Contract
741    ///
742    /// Per draft-atwood-jmap-chat-00, an expiry MUST hard-delete the
743    /// row (not tombstone) and the message MUST appear in the
744    /// `destroyed` set of subsequent `Message/changes` results.
745    /// Implementations therefore SHOULD:
746    ///
747    /// - Remove the underlying record so a subsequent `Message/get`
748    ///   does not find it.
749    /// - Bump the per-account `Message` state token and record the id
750    ///   in the change log so `Message/changes` sees it as destroyed.
751    ///
752    /// # Idempotency
753    ///
754    /// If the message no longer exists — because a previous
755    /// `expire_message` call or an atomic `update_object`
756    /// implementation has already deleted it — this method SHOULD
757    /// return `Ok(())` rather than
758    /// `BackendSetError::SetError(SetError::NotFound)`. Expiry events
759    /// are inherently retry-friendly (a scheduler may re-fire if it
760    /// crashed mid-batch) and the burn-on-read handler integration
761    /// also treats a not-found backend response as a no-op.
762    ///
763    /// # Atomicity with `Message/set` update
764    ///
765    /// The reference burn-on-read handler integration calls
766    /// `update_object` to apply the `readAt` patch and then calls
767    /// `expire_message` as a separate step. A backend that wants
768    /// strict atomicity between the `readAt` write and the hard-delete
769    /// SHOULD override `update_object` to perform both inside a
770    /// single transaction; in that case `expire_message` becomes
771    /// idempotent for this code path (the message is already gone
772    /// when the handler calls it).
773    ///
774    /// # Default implementation
775    ///
776    /// The default returns `Ok(())` without doing anything. This is
777    /// appropriate for backends that have not yet implemented expiry
778    /// or that handle the burn-on-read flow atomically inside their
779    /// own `update_object`. Production backends that need expiry
780    /// SHOULD override this method.
781    fn expire_message(
782        &self,
783        _caller: &Self::CallerCtx,
784        _account_id: &jmap_types::Id,
785        _message_id: &jmap_types::Id,
786    ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send {
787        async { Ok(()) }
788    }
789}