Skip to main content

jmap_chat_server/
message.rs

1//! Message/* method handlers (draft-atwood-jmap-chat-00 §Message).
2//!
3//! # Wire-shape contract
4//!
5//! Every `handle_*` function in this module conforms to the canonical JMAP
6//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
7//! Object whose fields match the corresponding RFC 8620 §5 method shape
8//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3,
9//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
10//! arguments defined by draft-atwood-jmap-chat-00 §Message. The
11//! returned `Value` is the corresponding method-response object per the
12//! same section refs.
13//!
14//! The returned `HandlerOutput::extra_invocations` carries any invocations
15//! that this handler injected into the request stream (RFC 8620 §6.3);
16//! for the handlers in this module the vector is **always empty**.
17//!
18//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
19//! §3.6.2 and §5):
20//!
21//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
22//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
23//!   `maxObjectsInSet`;
24//! - `/set`: `stateMismatch`;
25//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
26//! - `/queryChanges`: `tooManyChanges`;
27//! - `/query`, `/queryChanges`: `unsupportedFilter`;
28//! - `/query`: `unsupportedSort`, `anchorNotFound`.
29//!
30//! Per-target failures inside `/set` (including the `slow_mode_check`
31//! `rateLimit` and reaction-patch `invalidPatch` paths) surface in the
32//! `notCreated` / `notUpdated` / `notDestroyed` maps within `Ok((Value, ...))`,
33//! not as `Err`.
34
35use jmap_chat_types::{
36    Attachment, AttachmentCreate, BROADCAST_MENTION_SCOPES, BroadcastMention, Chat, DeliveryState,
37    Mention, Message, MessageAction, PresenceStatus, ReadPosition, Space,
38};
39use jmap_chat_types::{Filter, MessageComparator, MessageFilter, MessageFilterCondition};
40use jmap_types::{Id, JmapError, PatchObject, UTCDate};
41use serde::Deserialize;
42use serde_json::{Map, Value, json};
43
44use crate::chat::record_unread_count_changes;
45use crate::outbound::{OutboundEvent, ReactionAction};
46use crate::{ChatBackend, ChatLimits};
47use jmap_server::{BackendSetError, SetError, SetErrorType};
48use std::collections::{BTreeMap, HashMap, HashSet};
49use subtle::ConstantTimeEq;
50
51use crate::helpers::{
52    PropType, check_metadata_entry, create_metadata, is_metadata_key, mistyped_create_props,
53};
54use crate::helpers::{
55    SetAccumulators, default_sort, enforce_max_objects_in_get, enforce_max_objects_in_set,
56    extract_account_id, filter_properties, finalize_set_response, iso8601_before, not_found_json,
57    now_utc_string, optional_arg, reject_unsupported_sort, serialize_value, strip_read_only_patch,
58};
59use crate::helpers::{parents_first, resolve_entry_refs, resolved_create};
60use jmap_server::{
61    HandlerOutput, MetadataProjection, QueryParams, backend_set_error_value, bool_arg, filter_arg,
62    is_client_updatable, query_anchor_args, reject_server_set, server_fail_from_backend,
63    server_fail_value_from_backend,
64};
65
66// ---------------------------------------------------------------------------
67// Message/get
68// ---------------------------------------------------------------------------
69
70/// Handle a `Message/get` method call (draft-atwood-jmap-chat-00 §Message).
71///
72/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
73/// `ids`, optional `properties`); the returned `Value` is the §5.1
74/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
75///
76/// `using` is the request's capability list (pass
77/// [`jmap_server::CallContext::using`]). When the backend lists Message for
78/// draft-ietf-jmap-metadata-05 ([`JmapAccounts::metadata_info`](jmap_server::JmapAccounts::metadata_info)),
79/// `metadata` is returned as an object, by default only with
80/// `urn:ietf:params:jmap:metadata` in `using`, and with that capability
81/// `properties` may hold `metadata/<namespace>` subselectors (-05 §2,
82/// §3.1); see
83/// [`jmap_server::MetadataProjection`].
84///
85/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
86pub async fn handle_message_get<B: ChatBackend>(
87    backend: &B,
88    caller: &B::CallerCtx,
89    args: Value,
90    using: &[String],
91) -> Result<HandlerOutput, JmapError> {
92    let (account_id, mut args) = extract_account_id(args)?;
93
94    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
95    if !backend
96        .account_exists(caller, &account_id)
97        .await
98        .map_err(|e| server_fail_from_backend(&e))?
99    {
100        return Err(JmapError::account_not_found());
101    }
102    enforce_max_objects_in_get(&args, backend.max_objects_in_get(caller, &account_id))?;
103
104    let ids: Option<Vec<Id>> = match args.remove("ids") {
105        None | Some(Value::Null) => None,
106        Some(v) => Some(
107            serde_json::from_value(v)
108                .map_err(|_| JmapError::invalid_arguments("ids must be an Id array"))?,
109        ),
110    };
111
112    // RFC 8620 §5.1: when `properties` is specified, return only those fields
113    // (plus `id` which is always included). `None` means return all fields.
114    let properties: Option<Vec<String>> = match args.remove("properties") {
115        None | Some(Value::Null) => None,
116        Some(v) => Some(
117            serde_json::from_value(v)
118                .map_err(|_| JmapError::invalid_arguments("properties must be a string array"))?,
119        ),
120    };
121
122    let projection = MetadataProjection::new(
123        properties.as_deref(),
124        true,
125        using,
126        backend
127            .metadata_info::<Message>(caller, &account_id)
128            .as_ref(),
129    )?;
130
131    let ids_slice = ids.as_deref();
132    let (fetched, mut not_found) = backend
133        .get_objects::<Message>(caller, &account_id, ids_slice, properties.as_deref())
134        .await
135        .map_err(|e| server_fail_from_backend(&e))?;
136
137    // draft-atwood-jmap-chat-00 §Message/query (jmap-chat-spec 77c3474
138    // L1301): "messages in channels the caller cannot view SHOULD be
139    // omitted" from `Message/get`; done by choice. A hidden
140    // message is reported like a missing one: a requested id goes to
141    // notFound, and a full fetch drops it (RFC 8620 §5.1 notFound lists
142    // only requested ids).
143    let mut viewable: HashMap<Id, bool> = HashMap::new();
144    let mut list = Vec::with_capacity(fetched.len());
145    for msg in fetched {
146        let visible = match viewable.get(&msg.chat_id) {
147            Some(&v) => v,
148            None => {
149                let v = backend
150                    .may_view_chat(caller, &account_id, &msg.chat_id)
151                    .await
152                    .map_err(|e| server_fail_from_backend(&e))?;
153                viewable.insert(msg.chat_id.clone(), v);
154                v
155            }
156        };
157        if visible {
158            list.push(msg);
159        } else if ids_slice.is_some() {
160            not_found.push(msg.id);
161        }
162    }
163
164    // Edit-history retention gate (draft-atwood-jmap-chat-00 commit
165    // `0783fc4` + §Message editHistory). When the backend does not
166    // retain edit history, the `editHistory` field MUST be omitted
167    // from every returned Message. Setting `edit_history = None`
168    // here causes serde's `skip_serializing_if = "Option::is_none"`
169    // to collapse it on the wire, satisfying the spec MUST.
170    //
171    // `Message/changes` per RFC 8620 §5.2 returns id arrays only
172    // (no Message objects), so the spec's "omit from /changes" has
173    // no wire-level effect — only `Message/get` needs this gate.
174    if !backend.retains_edit_history() {
175        for msg in list.iter_mut() {
176            msg.edit_history = None;
177        }
178    }
179
180    let wants_counts = properties.as_ref().is_none_or(|p| {
181        p.iter()
182            .any(|k| k == "replyCount" || k == "unreadReplyCount")
183    });
184    if wants_counts && backend.limits(caller, &account_id).supports_threads {
185        fill_reply_counts(backend, caller, &account_id, &mut list).await?;
186    }
187
188    let state = backend
189        .get_state::<Message>(caller, &account_id)
190        .await
191        .map_err(|e| server_fail_from_backend(&e))?;
192
193    let prop_set: Option<HashSet<&str>> = properties.as_ref().map(|props| {
194        let mut set: HashSet<&str> = props.iter().map(|s| s.as_str()).collect();
195        set.insert("id");
196        set
197    });
198    let list_json: Vec<Value> = list
199        .iter()
200        .map(|obj| {
201            let val = serialize_value(obj)?;
202            let mut out = match &prop_set {
203                Some(set) => filter_properties(&val, set),
204                None => val.clone(),
205            };
206            projection.apply(&val, &mut out);
207            Ok(out)
208        })
209        .collect::<Result<Vec<_>, JmapError>>()?;
210
211    Ok(HandlerOutput::new(json!({
212        "accountId": account_id.as_ref(),
213        "state": state.as_ref(),
214        "list": list_json,
215        "notFound": not_found_json(&not_found),
216    })))
217}
218
219/// Set the server-computed thread counts on each Message in `list`
220/// (draft-atwood-jmap-chat-00 §Message, used when `supportsThreads` is
221/// `true`).
222///
223/// `replyCount`: "Count of messages in this chat with `replyTo` equal to
224/// this message's `id`." `unreadReplyCount`, only on a thread root
225/// (`threadRootId` absent): "Count of replies to this message received
226/// after the owner's `ReadPosition.lastReadMessageId` in this Chat".
227/// Message ids are ULIDs "lexicographically ordered by time" (§Message
228/// IDs), so a reply counts as unread when its `id` sorts after
229/// `lastReadMessageId`, or always when that is absent, and the owner did
230/// not send it (`senderId` is not the accountId), as for
231/// `Chat.unreadCount`.
232// ponytail: scans every Message and ReadPosition in the account per
233// call (O(messages) per Message/get); a backend with many messages
234// needs a reply-count index behind a ChatBackend hook.
235async fn fill_reply_counts<B: ChatBackend>(
236    backend: &B,
237    caller: &B::CallerCtx,
238    account_id: &Id,
239    list: &mut [Message],
240) -> Result<(), JmapError> {
241    if list.is_empty() {
242        return Ok(());
243    }
244    let (all, _) = backend
245        .get_objects::<Message>(caller, account_id, None, None)
246        .await
247        .map_err(|e| server_fail_from_backend(&e))?;
248    let (positions, _) = backend
249        .get_objects::<ReadPosition>(caller, account_id, None, None)
250        .await
251        .map_err(|e| server_fail_from_backend(&e))?;
252    for msg in list.iter_mut() {
253        let replies = || {
254            all.iter()
255                .filter(|r| r.chat_id == msg.chat_id && r.reply_to.as_ref() == Some(&msg.id))
256        };
257        let reply_count = replies().count() as u64;
258        msg.unread_reply_count = if msg.thread_root_id.is_none() {
259            let last_read = positions
260                .iter()
261                .find(|p| p.chat_id == msg.chat_id)
262                .and_then(|p| p.last_read_message_id.as_ref());
263            let unread = replies()
264                .filter(|r| r.sender_id != *account_id)
265                .filter(|r| last_read.is_none_or(|l| r.id.as_ref() > l.as_ref()))
266                .count();
267            Some(unread as u64)
268        } else {
269            None
270        };
271        msg.reply_count = Some(reply_count);
272    }
273    Ok(())
274}
275
276// ---------------------------------------------------------------------------
277// Message/changes
278// ---------------------------------------------------------------------------
279
280/// Handle a `Message/changes` method call (draft-atwood-jmap-chat-00 §Message).
281///
282/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
283/// `sinceState`, optional `maxChanges`); the returned `Value` is the
284/// §5.2 `/changes` response shape (`accountId`, `oldState`, `newState`,
285/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
286///
287/// `using` is the request's capability list (pass
288/// [`jmap_server::CallContext::using`]); with
289/// `urn:ietf:params:jmap:metadata` the request may set
290/// draft-ietf-jmap-metadata-05 §3.3 `ignoreMetadataOnlyChanges`, and
291/// without it metadata-only changes are left out (-05 §3).
292///
293/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
294pub async fn handle_message_changes<B: ChatBackend>(
295    backend: &B,
296    caller: &B::CallerCtx,
297    args: Value,
298    using: &[String],
299) -> Result<HandlerOutput, JmapError> {
300    jmap_server::handle_changes::<Message, B>(backend, caller, args, using).await
301}
302
303// ---------------------------------------------------------------------------
304// Message/query
305// ---------------------------------------------------------------------------
306
307/// Handle a `Message/query` method call (draft-atwood-jmap-chat-00 §Message).
308///
309/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`, optional
310/// `filter`, optional `sort`, optional `position` / `anchor` /
311/// `anchorOffset`, optional `limit`, optional `calculateTotal`); the
312/// returned `Value` is the §5.5 `/query` response shape (`accountId`,
313/// `queryState`, `canCalculateChanges`, `position`, `ids`, optional
314/// `total`, optional `limit`).
315///
316/// Unknown filter clauses and sort properties are refused with
317/// `unsupportedFilter` / `unsupportedSort` (RFC 8620 §5.5).
318///
319/// `using` is the request's capability list (pass
320/// [`jmap_server::CallContext::using`]); without
321/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
322/// filter condition is `unsupportedFilter` (-05 §3). A JMAP Search
323/// `where` (crate-jmap docs/specs/jmap-search.md) needs
324/// `urn:ietf:params:jmap:search` in `using` and `"Message"` in
325/// [`ChatSettings::search_capability`](crate::ChatSettings::search_capability), else `unsupportedFilter`; it is
326/// checked with [`jmap_search::check_where_filter`] and makes
327/// `canCalculateChanges` `false`. It does not lift the `chatId` /
328/// `hasMention: true` rule.
329///
330/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
331pub async fn handle_message_query<B: ChatBackend>(
332    backend: &B,
333    caller: &B::CallerCtx,
334    args: Value,
335    using: &[String],
336) -> Result<HandlerOutput, JmapError> {
337    jmap_server::reject_metadata_filter_arg(
338        &args,
339        jmap_chat_types::MessageFilterCondition::has_metadata_condition,
340        using,
341    )?;
342    let (account_id, mut args) = extract_account_id(args)?;
343
344    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe).
345    if !backend
346        .account_exists(caller, &account_id)
347        .await
348        .map_err(|e| server_fail_from_backend(&e))?
349    {
350        return Err(JmapError::account_not_found());
351    }
352
353    let searched =
354        check_message_search(backend, caller, &account_id, args.get("filter"), using).await?;
355
356    let calculate_total: bool = bool_arg(&args, "calculateTotal", false);
357
358    let limit: Option<u64> = match args.remove("limit") {
359        None | Some(Value::Null) => None,
360        Some(v) => match v.as_u64() {
361            Some(n) => Some(n),
362            None => {
363                return Err(JmapError::invalid_arguments(format!(
364                    "limit: expected a non-negative integer, got {}",
365                    jmap_server::json_type_name(&v)
366                )));
367            }
368        },
369    };
370
371    let position: i64 = match args.remove("position") {
372        None | Some(Value::Null) => 0,
373        Some(v) => v.as_i64().ok_or_else(|| {
374            JmapError::invalid_arguments(format!(
375                "position: expected an integer, got {}",
376                jmap_server::json_type_name(&v)
377            ))
378        })?,
379    };
380
381    let (anchor, anchor_offset) = query_anchor_args(&args)?;
382
383    reject_unsupported_sort::<MessageComparator>(args.get("sort"))?;
384    let filter: Option<MessageFilter> = filter_arg(&mut args)?;
385
386    let supports_threads = backend.limits(caller, &account_id).supports_threads;
387    let top = check_message_filter(filter.as_ref(), supports_threads)?;
388
389    // §Message/query: "Default sort: `receivedAt` ascending when `chatId`
390    // is present; `receivedAt` descending when `chatId` is absent."
391    let in_one_chat = top.chat_id.is_some();
392    default_sort(
393        &mut args,
394        json!([{ "property": "receivedAt", "isAscending": in_one_chat }]),
395    );
396    let sort: Option<Vec<MessageComparator>> = optional_arg(&mut args, "sort", || {
397        JmapError::invalid_arguments("sort must be an array")
398    })?;
399
400    // draft-atwood-jmap-chat-00 §Message/query (jmap-chat-spec 77c3474
401    // L1301): "messages in channels the caller cannot view SHOULD be
402    // omitted"; done by choice. A query scoped to one Chat the
403    // caller cannot view matches nothing; a query without `chatId` relies
404    // on the backend (see `ChatAccessPolicy::may_view_chat`).
405    let hidden = match top.chat_id.as_ref() {
406        Some(chat_id) => !backend
407            .may_view_chat(caller, &account_id, chat_id)
408            .await
409            .map_err(|e| server_fail_from_backend(&e))?,
410        None => false,
411    };
412
413    let result = backend
414        .query_objects::<Message>(
415            caller,
416            &account_id,
417            QueryParams::new()
418                .filter(filter.as_ref())
419                .sort(sort.as_deref())
420                .limit(limit)
421                .position(position)
422                .anchor(anchor.as_ref())
423                .anchor_offset(anchor_offset),
424        )
425        .await
426        .map_err(JmapError::from)?;
427    let (ids, position, total) = if hidden {
428        (Vec::new(), 0, Some(0))
429    } else {
430        (result.ids, result.position, result.total)
431    };
432
433    let mut resp = json!({
434        "accountId": account_id.as_ref(),
435        "queryState": result.query_state.as_ref(),
436        "canCalculateChanges": result.can_calculate_changes && !searched,
437        "position": position,
438        "ids": ids.iter().map(|id| id.as_ref()).collect::<Vec<_>>(),
439    });
440    if calculate_total && let Some(t) = total {
441        resp["total"] = json!(t);
442    }
443
444    Ok(HandlerOutput::new(resp))
445}
446
447/// Check the JMAP Search `where` of the undecoded Message `filter`
448/// against `using` and [`ChatSettings::search_capability`](crate::ChatSettings::search_capability), and return
449/// whether there was one (crate-jmap docs/specs/jmap-search.md §Errors,
450/// §Opting In a Data Type). The capability is read only for a filter with
451/// `where`.
452///
453/// # Errors
454///
455/// As [`jmap_search::check_where_filter`] for the `"Message"` data type,
456/// and `serverFail` when the backend fails.
457async fn check_message_search<B: ChatBackend>(
458    backend: &B,
459    caller: &B::CallerCtx,
460    account_id: &Id,
461    filter: Option<&Value>,
462    using: &[String],
463) -> Result<bool, JmapError> {
464    if !filter.is_some_and(jmap_search::filter_uses_where) {
465        return Ok(false);
466    }
467    let cap = backend
468        .search_capability(caller, account_id)
469        .await
470        .map_err(|e| server_fail_from_backend(&e))?;
471    jmap_search::check_where_filter(filter, "Message", using, cap.as_ref())
472}
473
474/// Apply the draft-atwood-jmap-chat-00 §Message/query `unsupportedFilter`
475/// refusals and return the top-level filter condition.
476///
477/// Shared by `Message/query` and `Message/queryChanges`, whose filter is
478/// that of the original query (RFC 8620 §5.6).
479///
480/// # Errors
481///
482/// `unsupportedFilter` when the filter is not a top-level condition with
483/// `chatId` or `hasMention: true` ("Servers MUST return an
484/// `unsupportedFilter` error for any request that omits `chatId` without
485/// also including `hasMention: true`"), sets `text` ("Servers that do not
486/// support full-text search MUST return `unsupportedFilter`"), or sets
487/// `threadRootId` while `supports_threads` is `false` ("Valid only when
488/// `supportsThreads` is `true`; otherwise servers MUST return
489/// `unsupportedFilter`").
490///
491/// ponytail: no backend implements `text`, so it is refused for every
492/// backend; a backend that adds it needs a ChatBackend capability hook to
493/// lift the refusal.
494fn check_message_filter(
495    filter: Option<&MessageFilter>,
496    supports_threads: bool,
497) -> Result<&MessageFilterCondition, JmapError> {
498    let unsupported = |description: &str| {
499        let mut err = JmapError::unsupported_filter();
500        err.description = Some(description.to_owned());
501        err
502    };
503    let Some(Filter::Condition(c)) = filter else {
504        return Err(unsupported(
505            "the filter must be a single condition with chatId or hasMention: true",
506        ));
507    };
508    if c.chat_id.is_none() && c.has_mention != Some(true) {
509        return Err(unsupported(
510            "the filter must set chatId or hasMention: true",
511        ));
512    }
513    if c.text.is_some() {
514        return Err(unsupported("full-text search (text) is not supported"));
515    }
516    if c.thread_root_id.is_some() && !supports_threads {
517        return Err(unsupported(
518            "threadRootId is valid only when supportsThreads is true",
519        ));
520    }
521    Ok(c)
522}
523
524// ---------------------------------------------------------------------------
525// Message/queryChanges
526// ---------------------------------------------------------------------------
527
528/// Handle a `Message/queryChanges` method call (draft-atwood-jmap-chat-00 §Message).
529///
530/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
531/// optional `filter`, optional `sort`, `sinceQueryState`, optional
532/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
533/// returned `Value` is the §5.6 `/queryChanges` response shape
534/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
535/// `removed`, `added`).
536///
537/// A query scoped to one Chat the caller cannot view fails with
538/// `cannotCalculateChanges`, so the client re-runs `Message/query`, which
539/// returns nothing for that Chat (see [`handle_message_query`]).
540///
541/// `using` is the request's capability list (pass
542/// [`jmap_server::CallContext::using`]); without
543/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
544/// filter condition is `unsupportedFilter` (-05 §3). A filter with a
545/// JMAP Search `where` is checked as for [`handle_message_query`] and then
546/// answered with `cannotCalculateChanges` (jmap-search §Query Changes).
547///
548/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
549pub async fn handle_message_query_changes<B: ChatBackend>(
550    backend: &B,
551    caller: &B::CallerCtx,
552    mut args: Value,
553    using: &[String],
554) -> Result<HandlerOutput, JmapError> {
555    jmap_server::reject_metadata_filter_arg(
556        &args,
557        jmap_chat_types::MessageFilterCondition::has_metadata_condition,
558        using,
559    )?;
560    // RFC 8620 §5.6: the `filter` and `sort` are those of the original
561    // query, so the §Message/query default sort applies here too.
562    let chat_id = args
563        .get("filter")
564        .and_then(|f| f.get("chatId"))
565        .and_then(Value::as_str)
566        .map(Id::from);
567    if let Value::Object(map) = &mut args {
568        default_sort(
569            map,
570            json!([{ "property": "receivedAt", "isAscending": chat_id.is_some() }]),
571        );
572    }
573    reject_unsupported_sort::<MessageComparator>(args.get("sort"))?;
574
575    // RFC 8620 §5.6: the filter is that of the original query, so the
576    // §Message/query `unsupportedFilter` refusals apply here too.
577    let account_id = args.get("accountId").and_then(Value::as_str).map(Id::from);
578    if let Some(account_id) = &account_id {
579        // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-dtpe), before the
580        // may_view_chat read below.
581        if !backend
582            .account_exists(caller, account_id)
583            .await
584            .map_err(|e| server_fail_from_backend(&e))?
585        {
586            return Err(JmapError::account_not_found());
587        }
588        let mut probe = serde_json::Map::new();
589        if let Some(f) = args.get("filter") {
590            probe.insert("filter".into(), f.clone());
591        }
592        let filter: Option<MessageFilter> = filter_arg(&mut probe)?;
593        let supports_threads = backend.limits(caller, account_id).supports_threads;
594        check_message_filter(filter.as_ref(), supports_threads)?;
595        // jmap-search §Query Changes: "Servers MAY return
596        // `cannotCalculateChanges` for any `/queryChanges` call whose
597        // filter uses `where`".
598        if check_message_search(backend, caller, account_id, args.get("filter"), using).await? {
599            return Err(JmapError::cannot_calculate_changes());
600        }
601    }
602
603    // §Message/query (jmap-chat-spec 77c3474 L1301): "messages in channels
604    // the caller cannot view SHOULD be omitted"; by choice, changes to such
605    // a Chat's messages are not reported.
606    if let (Some(account_id), Some(chat_id)) = (account_id, chat_id)
607        && !backend
608            .may_view_chat(caller, &account_id, &chat_id)
609            .await
610            .map_err(|e| server_fail_from_backend(&e))?
611    {
612        return Err(JmapError::cannot_calculate_changes());
613    }
614    jmap_server::handle_query_changes::<Message, B>(backend, caller, args).await
615}
616
617// ---------------------------------------------------------------------------
618// BroadcastMention validation
619// ---------------------------------------------------------------------------
620
621/// Validate broadcast mentions against spec §4.4.1 / §4.16 constraints.
622///
623/// Returns the SetError value on failure, None on success. §BroadcastMention:
624/// "Servers MUST reject a BroadcastMention with an unrecognized `scope`
625/// value; in `Message/set` the rejection is an `invalidProperties` SetError
626/// naming `broadcastMentions`." A missing or non-string `scope` takes the
627/// §Input Validation default, which is the same SetError.
628fn validate_broadcast_mentions(broadcast_mentions: &[serde_json::Value]) -> Option<Value> {
629    let invalid_properties = |desc: String| {
630        json!({
631            "type": "invalidProperties",
632            "properties": ["broadcastMentions"],
633            "description": desc,
634        })
635    };
636    for (i, bm) in broadcast_mentions.iter().enumerate() {
637        // scope validation
638        let scope = match bm.get("scope").and_then(|v| v.as_str()) {
639            Some(s) => s,
640            None => {
641                return Some(invalid_properties(format!(
642                    "broadcastMentions[{i}]: missing or non-string scope"
643                )));
644            }
645        };
646        if !BROADCAST_MENTION_SCOPES.contains(&scope) {
647            return Some(invalid_properties(format!(
648                "broadcastMentions[{i}]: unrecognized scope \"{scope}\""
649            )));
650        }
651    }
652    None
653}
654
655// ---------------------------------------------------------------------------
656// Optional create properties
657// ---------------------------------------------------------------------------
658
659/// Default `bodyType` values that indicate an end-to-end encrypted body:
660/// the one type draft-atwood-jmap-chat-00 §Message `body` names. A backend
661/// adds others, such as `"application/mimi-fanout"`
662/// (draft-atwood-jmap-chat-mimi-00 §MLS Messages), through
663/// [`ChatLimits::encrypted_body_types`](crate::ChatLimits::encrypted_body_types).
664pub const ENCRYPTED_BODY_TYPES: &[&str] = &["application/mls-ciphertext"];
665
666/// Default `bodyType` values this server accepts, advertised as the
667/// `supportedBodyTypes` capability (draft-atwood-jmap-chat-00
668/// §Account-Level Capability Object). A backend lists other types through
669/// [`ChatLimits::supported_body_types`](crate::ChatLimits::supported_body_types).
670pub const SUPPORTED_BODY_TYPES: &[&str] = &[
671    "text/plain",
672    "text/markdown",
673    "application/jmap-chat-rich",
674    "application/mls-ciphertext",
675];
676
677/// draft-atwood-jmap-chat-00 §Fields Inside the Ciphertext: Message fields
678/// that "MUST be empty or absent" when `bodyType` indicates an encrypted type.
679const CIPHERTEXT_ONLY_FIELDS: [&str; 8] = [
680    "mentions",
681    "broadcastMentions",
682    "attachments",
683    "actions",
684    "replyTo",
685    "threadRootId",
686    "topicId",
687    "subject",
688];
689
690/// Check the create fields that `bodyType` requires to be empty: all of
691/// [`CIPHERTEXT_ONLY_FIELDS`] when `body_type` is one of the account's
692/// `encrypted` types (§Fields Inside the Ciphertext).
693///
694/// Returns every offending field, in [`CIPHERTEXT_ONLY_FIELDS`] order, for
695/// an `invalidProperties` SetError "whose `properties` lists each such
696/// field"; empty on success.
697fn body_type_field_conflicts(
698    obj: &Value,
699    body_type: &str,
700    encrypted: &[&str],
701) -> Vec<&'static str> {
702    if !encrypted.contains(&body_type) {
703        return Vec::new();
704    }
705    let non_empty = |key: &str| {
706        obj.get(key)
707            .is_some_and(|v| !(v.is_null() || v == "" || v.as_array().is_some_and(Vec::is_empty)))
708    };
709    CIPHERTEXT_ONLY_FIELDS
710        .into_iter()
711        .filter(|&k| non_empty(k))
712        .collect()
713}
714
715/// Check a `Message/set` edit `patch` of the stored `msg` against
716/// `maxBodyBytes` and the encrypted-`bodyType` empty-field rule, which
717/// apply to updates as well as creates.
718///
719/// draft-atwood-jmap-chat-00 §Account-Level Capability Object
720/// `maxBodyBytes`: "in `Message/set` the rejection is a `tooLarge`
721/// SetError." §Fields Inside the Ciphertext (jmap-chat-spec 77c3474
722/// L1823): "Servers SHOULD reject a `Message/set` create or update that has
723/// an encrypted `bodyType` and any of these fields non-empty"; this crate
724/// performs the recommended rejection by choice. The field rule runs on the Message as it
725/// would be after the patch, so a `bodyType`-only patch to an encrypted
726/// type is rejected when the stored Message keeps such a field.
727///
728/// Returns the SetError, or `None` when the edit passes.
729fn edit_limit_error(msg: &Message, patch: &Value, limits: &ChatLimits) -> Option<Value> {
730    if let Some(body) = patch.get("body").and_then(Value::as_str)
731        && u64::try_from(body.len()).map_or(true, |n| n > limits.max_body_bytes)
732    {
733        return Some(json!({
734            "type": "tooLarge",
735            "description": format!("body exceeds maxBodyBytes ({})", limits.max_body_bytes),
736        }));
737    }
738    let mut merged = serde_json::to_value(msg).ok()?;
739    if let (Some(dst), Some(src)) = (merged.as_object_mut(), patch.as_object()) {
740        dst.extend(src.iter().map(|(k, v)| (k.clone(), v.clone())));
741    }
742    let body_type = merged.get("bodyType").and_then(Value::as_str)?.to_owned();
743    let conflicts = body_type_field_conflicts(&merged, &body_type, limits.encrypted_body_types);
744    (!conflicts.is_empty()).then(|| {
745        json!({
746            "type": "invalidProperties",
747            "properties": conflicts,
748            "description": format!("must be empty or absent when bodyType is {body_type}"),
749        })
750    })
751}
752
753/// Implementation-defined maximum byte length of `subject`
754/// (draft-atwood-jmap-chat-00 §Input Validation).
755const MAX_SUBJECT_BYTES: usize = 1024;
756
757/// RFC 8620 §1.3 UnsignedInt upper bound, 2^53 - 1.
758const MAX_UNSIGNED_INT: u64 = (1 << 53) - 1;
759
760/// Parse the optional `Message/set` create properties `mentions`,
761/// `broadcastMentions`, `actions`, `topicId`, `subject` and
762/// `expiresAfterReadSeconds` from `obj`, applying the
763/// draft-atwood-jmap-chat-00 §Input Validation checks, and return a
764/// function that copies them onto a Message. An absent or `null`
765/// property keeps the default. `broadcastMentions` must already have
766/// passed [`validate_broadcast_mentions`].
767///
768/// On error, returns the wire name of the first offending property, for an
769/// `invalidProperties` SetError.
770fn apply_create_optionals(
771    obj: &Value,
772) -> Result<impl FnOnce(&mut Message) + Send + use<>, &'static str> {
773    let get = |key: &str| obj.get(key).filter(|v| !v.is_null());
774    let mentions = get("mentions")
775        .map(|v| Vec::<Mention>::deserialize(v).map_err(|_| "mentions"))
776        .transpose()?;
777    let broadcast_mentions = get("broadcastMentions")
778        .map(|v| Vec::<BroadcastMention>::deserialize(v).map_err(|_| "broadcastMentions"))
779        .transpose()?;
780    // §MessageAction: "Servers MUST store and forward MessageAction
781    // records without inspection or transformation."
782    let actions = get("actions")
783        .map(|v| Vec::<MessageAction>::deserialize(v).map_err(|_| "actions"))
784        .transpose()?;
785    let topic_id = match get("topicId") {
786        None => None,
787        Some(v) => match v.as_str() {
788            Some(s) if !s.is_empty() && s.len() <= 255 => Some(s.to_owned()),
789            _ => return Err("topicId"),
790        },
791    };
792    let subject = match get("subject") {
793        None => None,
794        Some(v) => match v.as_str() {
795            Some(s) if topic_id.is_some() && s.len() <= MAX_SUBJECT_BYTES => Some(s.to_owned()),
796            _ => return Err("subject"),
797        },
798    };
799    let expires_after_read_seconds = match get("expiresAfterReadSeconds") {
800        None => None,
801        Some(v) => match v.as_u64() {
802            Some(n) if n <= MAX_UNSIGNED_INT => Some(n),
803            _ => return Err("expiresAfterReadSeconds"),
804        },
805    };
806    Ok(move |msg: &mut Message| {
807        if let Some(v) = mentions {
808            msg.mentions = v;
809        }
810        if let Some(v) = broadcast_mentions {
811            msg.broadcast_mentions = v;
812        }
813        if let Some(v) = actions {
814            msg.actions = v;
815        }
816        if topic_id.is_some() {
817            msg.topic_id = topic_id;
818        }
819        if subject.is_some() {
820            msg.subject = subject;
821        }
822        if expires_after_read_seconds.is_some() {
823            msg.expires_after_read_seconds = expires_after_read_seconds;
824        }
825    })
826}
827
828/// Build a `Message/set` create's `attachments` from its wire value `v`
829/// for target Chat `chat`; `Err` holds the SetError value.
830///
831/// draft-atwood-jmap-chat-00 §Denial of Service: "Enforce
832/// `maxAttachmentsPerMessage` at creation and update time"; it is checked
833/// first, so no entry is resolved past the cap, and is `tooLarge`, the
834/// error §Account-Level Capability Object names for `maxBodyBytes`. An
835/// entry with `filenodeId` goes to [`ChatResolvers::filenode_attachment`](crate::ChatResolvers::filenode_attachment)
836/// (draft-atwood-jmap-chat-filenode-00 §filenodeId). Any other entry, or
837/// one the hook leaves unresolved, must carry every Attachment field. Each
838/// result must pass [`valid_attachment`]. A malformed entry is
839/// `invalidProperties` naming `attachments`.
840async fn create_attachments<B: ChatBackend>(
841    backend: &B,
842    caller: &B::CallerCtx,
843    account_id: &Id,
844    limits: &ChatLimits,
845    chat: &Chat,
846    v: &Value,
847) -> Result<Vec<Attachment>, Value> {
848    let invalid = || json!({ "type": "invalidProperties", "properties": ["attachments"] });
849    let entries = v.as_array().ok_or_else(invalid)?;
850    if u64::try_from(entries.len()).map_or(true, |n| n > limits.max_attachments_per_message) {
851        return Err(json!({
852            "type": "tooLarge",
853            "description": format!(
854                "attachments exceed maxAttachmentsPerMessage ({})",
855                limits.max_attachments_per_message
856            ),
857        }));
858    }
859    let mut attachments = Vec::with_capacity(entries.len());
860    for entry in entries {
861        let requested = AttachmentCreate::deserialize(entry).map_err(|_| invalid())?;
862        let filled = if requested.filenode_id.is_some() {
863            match backend
864                .filenode_attachment(caller, account_id, chat, &requested)
865                .await
866            {
867                Ok(Ok(filled)) => filled,
868                Ok(Err(set_err)) => return Err(serde_json::Value::from(&set_err)),
869                Err(e) => return Err(server_fail_value_from_backend(&e)),
870            }
871        } else {
872            None
873        };
874        let attachment = match filled {
875            Some(a) => a,
876            None => Attachment::deserialize(entry).map_err(|_| invalid())?,
877        };
878        if !valid_attachment(&attachment) {
879            return Err(invalid());
880        }
881        attachments.push(attachment);
882    }
883    Ok(attachments)
884}
885
886/// draft-atwood-jmap-chat-00 §Attachment and §Input Validation:
887/// `filename` holds no `/`, `\` or null byte and `contentType` is a
888/// syntactically valid MIME type. `sha256` is lowercase hex by its type.
889///
890/// `size` and `sha256` are checked against the blob in [`check_attachments`].
891fn valid_attachment(a: &Attachment) -> bool {
892    !a.filename.contains(['/', '\\', '\0']) && valid_media_type(&a.content_type)
893}
894
895/// Enforce the size limit and blob checks on a `Message/set` create's
896/// `attachments` from [`create_attachments`]; `None` on success, else the
897/// SetError value.
898///
899/// draft-atwood-jmap-chat-00 §Denial of Service: "Enforce `maxBodyBytes`
900/// and `maxAttachmentBytes` at parse time, before any fetch or storage."
901/// The limit is `tooLarge`, the error §Account-Level Capability Object
902/// names for `maxBodyBytes`. Then each Attachment's `size` and `sha256` are
903/// checked against [`ChatResolvers::attachment_blob`](crate::ChatResolvers::attachment_blob); a mismatch is
904/// `invalidProperties` naming `attachments` (§Input Validation).
905async fn check_attachments<B: ChatBackend>(
906    backend: &B,
907    caller: &B::CallerCtx,
908    account_id: &Id,
909    limits: &ChatLimits,
910    attachments: &[Attachment],
911) -> Option<Value> {
912    if attachments
913        .iter()
914        .any(|a| a.size > limits.max_attachment_bytes)
915    {
916        return Some(json!({
917            "type": "tooLarge",
918            "description": format!(
919                "an attachment exceeds maxAttachmentBytes ({})",
920                limits.max_attachment_bytes
921            ),
922        }));
923    }
924    for a in attachments {
925        match backend
926            .attachment_blob(caller, account_id, &a.blob_id)
927            .await
928        {
929            Ok(Ok(None)) => {}
930            Ok(Ok(Some(blob))) => {
931                // Constant-time digest comparison (compliance tests §14.13:
932                // "Verify that blob hash comparison uses constant-time
933                // comparison").
934                if blob.size != a.size || !bool::from(a.sha256.to_bytes().ct_eq(&blob.sha256)) {
935                    return Some(json!({
936                        "type": "invalidProperties",
937                        "properties": ["attachments"],
938                        "description": format!(
939                            "attachment {} does not match the blob's size or sha256",
940                            a.blob_id
941                        ),
942                    }));
943                }
944            }
945            Ok(Err(set_err)) => return Some(serde_json::Value::from(&set_err)),
946            Err(e) => return Some(server_fail_value_from_backend(&e)),
947        }
948    }
949    None
950}
951
952/// RFC 2045 §5.1 `type "/" subtype`, each an RFC 2045 `token`.
953///
954/// ponytail: parameters after `;` are not parsed; add an RFC 2045
955/// parameter parser if they ever need validating.
956fn valid_media_type(s: &str) -> bool {
957    let is_token = |t: &str| {
958        !t.is_empty()
959            && t.bytes()
960                .all(|b| b.is_ascii_graphic() && !b"()<>@,;:\\\"/[]?=".contains(&b))
961    };
962    let essence = s.split(';').next().unwrap_or_default().trim();
963    essence
964        .split_once('/')
965        .is_some_and(|(t, sub)| is_token(t) && is_token(sub))
966}
967
968// ---------------------------------------------------------------------------
969// Message/set
970// ---------------------------------------------------------------------------
971
972/// Create the owner's ReadPosition for each Chat in `chat_ids` that has
973/// none yet. draft-atwood-jmap-chat-00 §ReadPosition: "For direct and
974/// group Chats, a ReadPosition is created when the first message is
975/// delivered. For channel Chats, a ReadPosition is created when the
976/// owner joins the containing Space." Called by `Message/set` and by
977/// `Space/join` ([`crate::space::handle_space_join`]).
978///
979/// Best effort: the Messages are already stored, so a backend failure
980/// here must not become a method-level error (RFC 8620 §3.6.2: "the
981/// externally visible state of the server MUST NOT have changed if an
982/// error is returned at the method level"). A record missed here is
983/// created by the next delivery to that Chat. `alreadyExists` means a
984/// concurrent delivery created it first (see the ReadPosition uniqueness
985/// contract on `ChatStore::create_object`).
986///
987/// ponytail: does not look up the Chat's kind, so `Message/set` also
988/// fills in a missing channel position (for example a channel added
989/// after the owner joined). One full ReadPosition scan per `Message/set` call that created a
990/// message; a backend with a `(account, chatId)` index can replace it.
991pub(crate) async fn ensure_read_positions<B: ChatBackend>(
992    backend: &B,
993    caller: &B::CallerCtx,
994    account_id: &Id,
995    mut chat_ids: Vec<Id>,
996) {
997    if chat_ids.is_empty() {
998        return;
999    }
1000    let Ok((existing, _)) = backend
1001        .get_objects::<ReadPosition>(caller, account_id, None, None)
1002        .await
1003    else {
1004        return;
1005    };
1006    chat_ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
1007    chat_ids.dedup();
1008    chat_ids.retain(|c| !existing.iter().any(|p| p.chat_id == *c));
1009    for chat_id in chat_ids {
1010        let _ = backend
1011            .create_object(caller, account_id, chat_id.as_ref(), |id: &Id| {
1012                ReadPosition::new(id.clone(), chat_id.clone())
1013            })
1014            .await;
1015    }
1016}
1017
1018/// Find the Message in `chat_id` whose `senderMsgId` is `sender_msg_id`.
1019///
1020/// draft-atwood-jmap-chat-00 §Message: "Servers MUST maintain a durable
1021/// index of `senderMsgId` values per chat to support idempotent
1022/// delivery, `Peer/retract` lookup, and resolution of `replyTo` /
1023/// `threadRootId` references." The same `senderMsgId` in another Chat is
1024/// a different Message.
1025///
1026/// ponytail: one full Message scan of the account per call, not an
1027/// index. A backend with a `(chatId, senderMsgId)` index can serve the
1028/// same contract from it once this becomes a hot path.
1029///
1030/// # Errors
1031///
1032/// Returns the backend error if reading the account's Messages fails.
1033pub async fn find_message_by_sender_msg_id<B: ChatBackend>(
1034    backend: &B,
1035    caller: &B::CallerCtx,
1036    account_id: &Id,
1037    chat_id: &Id,
1038    sender_msg_id: &Id,
1039) -> Result<Option<Message>, B::Error> {
1040    let (messages, _) = backend
1041        .get_objects::<Message>(caller, account_id, None, None)
1042        .await?;
1043    Ok(messages
1044        .into_iter()
1045        .find(|m| m.chat_id == *chat_id && m.sender_msg_id == *sender_msg_id))
1046}
1047
1048/// The result of [`store_server_message`].
1049#[derive(Debug, Clone, PartialEq, Eq)]
1050#[non_exhaustive]
1051pub enum StoreOutcome {
1052    /// The Message was stored under this server-assigned id.
1053    Stored(Id),
1054    /// The Chat already holds a Message with the same `senderMsgId`; this
1055    /// is its id, and nothing was written.
1056    Duplicate(Id),
1057}
1058
1059/// Store a Message that the server, not a client, creates: for example a
1060/// MIMI fanout Message (draft-atwood-jmap-chat-mimi-00
1061/// §application/mimi-fanout) or a federation `Peer/deliver` Message.
1062///
1063/// `build` makes the Message for the id the backend assigns, as for
1064/// [`ChatStore::create_object`](crate::ChatStore::create_object). It sets every other field, including
1065/// the server-set `senderMsgId`, `senderId`, `sentAt` and `receivedAt` and
1066/// a body type that [`ChatLimits::server_reserved_body_types`] keeps out
1067/// of `Message/set`. Its `chatId` and `senderMsgId` are then overwritten
1068/// with `chat_id` and `sender_msg_id`, so the stored Message always matches
1069/// the duplicate check. None of the `Message/set` client-input checks run.
1070///
1071/// Before storing, `chat_id` is searched for `sender_msg_id` with
1072/// [`find_message_by_sender_msg_id`]. A hit returns
1073/// [`StoreOutcome::Duplicate`] and writes nothing. The mimi draft
1074/// requires this: "The server MUST NOT store a FanoutMessage whose
1075/// `senderMsgId` it has already stored in the Chat". After a store, the
1076/// owner's ReadPosition for the Chat is created if missing and the
1077/// Chat's `unreadCount` is recomputed, as for `Message/set`
1078/// (draft-atwood-jmap-chat-00 §ReadPosition: "For direct and group
1079/// Chats, a ReadPosition is created when the first message is
1080/// delivered.").
1081///
1082/// ponytail: the duplicate check and the create are separate backend
1083/// calls. Two concurrent calls with one `senderMsgId` can both store, so
1084/// a caller that can race (such as parallel `/notify` deliveries)
1085/// serializes calls per Chat.
1086///
1087/// # Errors
1088///
1089/// Returns the backend's error from the lookup (as
1090/// [`BackendSetError::Other`]) or from
1091/// [`ChatStore::create_object`](crate::ChatStore::create_object), unchanged.
1092// Same error type as `ChatStore::create_object`, passed through unboxed.
1093pub async fn store_server_message<B, F>(
1094    backend: &B,
1095    caller: &B::CallerCtx,
1096    account_id: &Id,
1097    chat_id: &Id,
1098    sender_msg_id: &Id,
1099    build: F,
1100) -> Result<StoreOutcome, BackendSetError<B::Error>>
1101where
1102    B: ChatBackend,
1103    F: FnOnce(&Id) -> Message + Send,
1104{
1105    if let Some(existing) =
1106        find_message_by_sender_msg_id(backend, caller, account_id, chat_id, sender_msg_id)
1107            .await
1108            .map_err(BackendSetError::Other)?
1109    {
1110        return Ok(StoreOutcome::Duplicate(existing.id));
1111    }
1112    let (chat, smid) = (chat_id.clone(), sender_msg_id.clone());
1113    let (id, stored) = backend
1114        .create_object(
1115            caller,
1116            account_id,
1117            sender_msg_id.as_ref(),
1118            move |id: &Id| {
1119                let mut m = build(id);
1120                m.chat_id = chat;
1121                m.sender_msg_id = smid;
1122                m
1123            },
1124        )
1125        .await?;
1126    ensure_read_positions(backend, caller, account_id, vec![stored.chat_id.clone()]).await;
1127    record_unread_count_changes(backend, caller, account_id, vec![stored.chat_id]).await;
1128    Ok(StoreOutcome::Stored(id))
1129}
1130
1131/// The owner's effective receipt-sharing preference for `chat_id`.
1132///
1133/// draft-atwood-jmap-chat-federation-00 §Peer/receipt "Sender Behavior":
1134/// "if `Chat.receiptSharing` is present for the relevant Chat, that value
1135/// is used; otherwise the account-level `PresenceStatus.receiptSharing`
1136/// applies". A missing PresenceStatus takes the draft-atwood-jmap-chat-00
1137/// default, `true`. A failed lookup yields `false`: the read has already
1138/// been written, and a receipt not shown to be permitted is not sent.
1139async fn shares_receipts<B: ChatBackend>(
1140    backend: &B,
1141    caller: &B::CallerCtx,
1142    account_id: &Id,
1143    chat_id: &Id,
1144) -> bool {
1145    let chat_override = match backend
1146        .get_objects::<Chat>(
1147            caller,
1148            account_id,
1149            Some(std::slice::from_ref(chat_id)),
1150            None,
1151        )
1152        .await
1153    {
1154        Ok((found, _not_found)) => found.first().and_then(|c| c.receipt_sharing),
1155        Err(_) => return false,
1156    };
1157    if let Some(shares) = chat_override {
1158        return shares;
1159    }
1160    match backend
1161        .get_objects::<PresenceStatus>(caller, account_id, None, None)
1162        .await
1163    {
1164        Ok((found, _not_found)) => found.first().is_none_or(|p| p.receipt_sharing),
1165        Err(_) => false,
1166    }
1167}
1168
1169/// The Message create properties that hold the id of another record, which a
1170/// client may set to a `#creationId` reference (RFC 8620 §5.3).
1171const MESSAGE_ID_PROPERTIES: &[&str] = &["chatId", "replyTo", "threadRootId"];
1172
1173/// A Mention `id`, a ChatContact id (draft-atwood-jmap-chat-00 §Mention),
1174/// as `(property, entry field, property named on failure)` for
1175/// [`resolve_entry_refs`].
1176const MENTION_ID: (&str, &str, &str) = ("mentions", "id", "mentions");
1177
1178/// An Attachment `filenodeId`, a FileNode id; failed validation names
1179/// `filenodeId` (draft-atwood-jmap-chat-filenode-00 §filenodeId).
1180const ATTACHMENT_FILENODE_ID: (&str, &str, &str) = ("attachments", "filenodeId", "filenodeId");
1181
1182/// Handle a `Message/set` method call (draft-atwood-jmap-chat-00 §Message).
1183///
1184/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
1185/// `ifInState`, optional `create` / `update` / `destroy` maps); the
1186/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
1187/// `oldState`, `newState`, plus the per-operation `created` /
1188/// `notCreated` / `updated` / `notUpdated` / `destroyed` / `notDestroyed`
1189/// maps).
1190///
1191/// Validation enforced here (not in the backend):
1192/// - `chatId` and `body` are required on create.
1193/// - `id`, `senderMsgId`, `senderId`, `sentAt`, `receivedAt`, `deliveryState`
1194///   are server-set and rejected in updates.
1195///
1196/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
1197///
1198/// A `chatId`, `replyTo` or `threadRootId` that is a `#creationId`
1199/// reference names a record created earlier in the request and resolves
1200/// against `created_ids` (pass [`jmap_server::CallContext::created_ids`]) or
1201/// against a create of this call, which runs replied-to messages first (RFC
1202/// 8620 §5.3). So does a Mention `id` in a create or an edit, and an
1203/// Attachment `filenodeId` in a create. An unknown reference is
1204/// `invalidProperties` naming the property (`filenodeId` for an
1205/// Attachment).
1206///
1207/// `using` is the request's capability list (pass
1208/// [`jmap_server::CallContext::using`]): a write to `metadata` or
1209/// `privateMetadata` without `urn:ietf:params:jmap:metadata` is
1210/// `invalidProperties` (draft-ietf-jmap-metadata-05 §3), as is `null` for
1211/// either in a create (-05 §3.2). The backend validates the rest.
1212pub async fn handle_message_set<B: ChatBackend>(
1213    backend: &B,
1214    caller: &B::CallerCtx,
1215    created_ids: &BTreeMap<Id, Id>,
1216    mut args: Value,
1217    using: &[String],
1218) -> Result<HandlerOutput, JmapError> {
1219    // A `#creationId` blob reference names a blob created earlier in the
1220    // request (RFC 8620 §5.3; draft-ietf-jmap-blobext-03 §8); an unknown one
1221    // is left for the Id checks below.
1222    jmap_server::resolve_blob_refs(&mut args, &["blobId", "thumbnailBlobId"], created_ids);
1223    let (account_id, mut args) = extract_account_id(args)?;
1224
1225    // RFC 8620 §3.6.2 accountNotFound (bd:JMAP-fo38).
1226    if !backend
1227        .account_exists(caller, &account_id)
1228        .await
1229        .map_err(|e| server_fail_from_backend(&e))?
1230    {
1231        return Err(JmapError::account_not_found());
1232    }
1233
1234    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.3). Reject
1235    // unbounded /set batches before touching the storage layer.
1236    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
1237
1238    let old_state = backend
1239        .get_state::<Message>(caller, &account_id)
1240        .await
1241        .map_err(|e| server_fail_from_backend(&e))?;
1242
1243    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
1244        && if_in_state != old_state.as_ref()
1245    {
1246        return Err(JmapError::state_mismatch());
1247    }
1248
1249    let mut created = serde_json::Map::new();
1250    let mut not_created = serde_json::Map::new();
1251    let mut updated = serde_json::Map::new();
1252    let mut not_updated = serde_json::Map::new();
1253    let mut destroyed_list: Vec<Value> = Vec::new();
1254    let mut not_destroyed = serde_json::Map::new();
1255    let mut mutated = false;
1256    let limits = backend.limits(caller, &account_id);
1257
1258    // -----------------------------------------------------------------------
1259    // create
1260    // -----------------------------------------------------------------------
1261    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
1262        let mut delivered_chat_ids: Vec<Id> = Vec::new();
1263        // RFC 8620 §5.3: creates of this call join the request-wide map so
1264        // later creates in this call can reference them.
1265        let mut created_ids = created_ids.clone();
1266        for (create_id, obj_val) in parents_first(create_map, &["replyTo", "threadRootId"]) {
1267            let resolved = match resolved_create(obj_val, MESSAGE_ID_PROPERTIES, &created_ids)
1268                .and_then(|mut v| {
1269                    resolve_entry_refs(&mut v, &[MENTION_ID, ATTACHMENT_FILENODE_ID], &created_ids)
1270                        .map(|()| v)
1271                }) {
1272                Ok(v) => v,
1273                Err(err) => {
1274                    not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
1275                    continue;
1276                }
1277            };
1278            let obj_val = &resolved;
1279            if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Message>) {
1280                not_created.insert(create_id.clone(), serde_json::Value::from(&err));
1281                continue;
1282            }
1283            if let Some(Err(err)) = obj_val
1284                .as_object()
1285                .map(|o| check_metadata_entry(o, true, using))
1286            {
1287                not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
1288                continue;
1289            }
1290            // draft-ietf-jmap-metadata-05 §3.2: the create sets the
1291            // metadata properties; the backend validates them.
1292            let (metadata, private_metadata) = match create_metadata(obj_val) {
1293                Ok(maps) => maps,
1294                Err(err) => {
1295                    not_created.insert(create_id.clone(), err);
1296                    continue;
1297                }
1298            };
1299            // Optional properties: a wrongly-typed value is invalidProperties
1300            // (RFC 8620 §5.3), not a silent absence.
1301            if let Some(err) = mistyped_create_props(
1302                obj_val,
1303                &[
1304                    ("broadcastMentions", PropType::Array),
1305                    ("replyTo", PropType::Str),
1306                    ("threadRootId", PropType::Str),
1307                    ("senderExpiresAt", PropType::Str),
1308                    ("burnOnRead", PropType::Bool),
1309                ],
1310            ) {
1311                not_created.insert(create_id.clone(), err);
1312                continue;
1313            }
1314            let Some(chat_id_str) = obj_val.get("chatId").and_then(|v| v.as_str()) else {
1315                not_created.insert(
1316                    create_id.clone(),
1317                    json!({ "type": "invalidProperties", "properties": ["chatId"] }),
1318                );
1319                continue;
1320            };
1321            let chat_id = match jmap_server::parse_wire_id(chat_id_str, "chatId") {
1322                Ok(id) => id,
1323                Err(err) => {
1324                    not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
1325                    continue;
1326                }
1327            };
1328
1329            let Some(body) = obj_val
1330                .get("body")
1331                .and_then(|v| v.as_str())
1332                .map(str::to_owned)
1333            else {
1334                not_created.insert(
1335                    create_id.clone(),
1336                    json!({ "type": "invalidProperties", "properties": ["body"] }),
1337                );
1338                continue;
1339            };
1340            // §Account-Level Capability Object `maxBodyBytes`: "Servers
1341            // MUST reject messages exceeding this limit; in `Message/set`
1342            // the rejection is a `tooLarge` SetError."
1343            if u64::try_from(body.len()).map_or(true, |n| n > limits.max_body_bytes) {
1344                not_created.insert(
1345                    create_id.clone(),
1346                    json!({
1347                        "type": "tooLarge",
1348                        "description": format!("body exceeds maxBodyBytes ({})", limits.max_body_bytes),
1349                    }),
1350                );
1351                continue;
1352            }
1353
1354            // sentAt is a UTCDate per RFC 8620 §1.4 (20-char
1355            // YYYY-MM-DDTHH:MM:SSZ). Validate the wire shape via
1356            // UTCDate::new_validated; a malformed value produces
1357            // invalidProperties rather than silently flowing through
1358            // to storage where downstream lex-compares and slice ops
1359            // (helpers::iso8601_before) assume a validated 20-byte
1360            // ASCII shape.
1361            let Some(sent_at_str) = obj_val.get("sentAt").and_then(|v| v.as_str()) else {
1362                not_created.insert(
1363                    create_id.clone(),
1364                    json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
1365                );
1366                continue;
1367            };
1368            let Ok(sent_at) = UTCDate::new_validated(sent_at_str) else {
1369                not_created.insert(
1370                    create_id.clone(),
1371                    json!({ "type": "invalidProperties", "properties": ["sentAt"] }),
1372                );
1373                continue;
1374            };
1375
1376            // §Input Validation: "`bodyType`: reject a value not listed in
1377            // `supportedBodyTypes`; in `Message/set` create, also reject a
1378            // type that a companion specification reserves for
1379            // server-created Messages."
1380            let Some(body_type) = obj_val
1381                .get("bodyType")
1382                .filter(|v| !v.is_null())
1383                .map_or(Some("text/plain"), Value::as_str)
1384                .filter(|s| limits.supported_body_types.contains(s))
1385            else {
1386                not_created.insert(
1387                    create_id.clone(),
1388                    json!({ "type": "invalidProperties", "properties": ["bodyType"] }),
1389                );
1390                continue;
1391            };
1392            // draft-atwood-jmap-chat-mimi-00 §application/mimi-fanout, the
1393            // one reserving companion: "the server MUST reject a
1394            // `Message/set` create with this body type with an
1395            // `invalidProperties` SetError naming `bodyType`."
1396            if limits.server_reserved_body_types.contains(&body_type) {
1397                not_created.insert(
1398                    create_id.clone(),
1399                    json!({
1400                        "type": "invalidProperties",
1401                        "properties": ["bodyType"],
1402                        "description": format!("bodyType {body_type} is reserved for server-created Messages")
1403                    }),
1404                );
1405                continue;
1406            }
1407            let body_type = body_type.to_owned();
1408
1409            // §Fields Inside the Ciphertext: "an `invalidProperties`
1410            // SetError whose `properties` lists each such field".
1411            let conflicts =
1412                body_type_field_conflicts(obj_val, &body_type, limits.encrypted_body_types);
1413            if !conflicts.is_empty() {
1414                not_created.insert(
1415                    create_id.clone(),
1416                    json!({
1417                        "type": "invalidProperties",
1418                        "properties": conflicts,
1419                        "description": format!("must be empty or absent when bodyType is {body_type}"),
1420                    }),
1421                );
1422                continue;
1423            }
1424
1425            // BroadcastMention structural validation (§4.4.1 / §4.16).
1426            let broadcast_mentions_val: Vec<Value> = obj_val
1427                .get("broadcastMentions")
1428                .and_then(|v| v.as_array())
1429                .cloned()
1430                .unwrap_or_default();
1431            if let Some(err) = validate_broadcast_mentions(&broadcast_mentions_val) {
1432                not_created.insert(create_id.clone(), err);
1433                continue;
1434            }
1435
1436            // draft-atwood-jmap-chat-00 §Input Validation: "`chatId`:
1437            // verify per {{chat-id}} — confirm match with stored id"; a
1438            // failed check is "an `invalidProperties` SetError ... whose
1439            // `properties` names the offending property".
1440            let chat = match backend
1441                .get_objects::<Chat>(
1442                    caller,
1443                    &account_id,
1444                    Some(std::slice::from_ref(&chat_id)),
1445                    None,
1446                )
1447                .await
1448            {
1449                Ok((found, _)) => match found.into_iter().next() {
1450                    Some(chat) => chat,
1451                    None => {
1452                        not_created.insert(
1453                            create_id.clone(),
1454                            json!({
1455                                "type": "invalidProperties",
1456                                "properties": ["chatId"],
1457                                "description": format!("no Chat with id {chat_id}"),
1458                            }),
1459                        );
1460                        continue;
1461                    }
1462                },
1463                Err(e) => {
1464                    not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
1465                    continue;
1466                }
1467            };
1468
1469            match backend.may_create_message(caller, &account_id, &chat).await {
1470                Ok(Ok(())) => {}
1471                Ok(Err(set_err)) => {
1472                    not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
1473                    continue;
1474                }
1475                Err(e) => {
1476                    not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
1477                    continue;
1478                }
1479            }
1480
1481            // draft-atwood-jmap-chat-00 §Chat `closedAt`: "After it is
1482            // set, the server MUST reject with a `forbidden` SetError
1483            // every `Message/set` create in this Chat".
1484            if chat.closed_at.is_some() {
1485                not_created.insert(
1486                    create_id.clone(),
1487                    json!({ "type": "forbidden", "description": "the group is closed" }),
1488                );
1489                continue;
1490            }
1491
1492            // draft-atwood-jmap-chat-00 §Space `closedAt`: "After it is
1493            // set, the Space's channels are read-only: the server MUST
1494            // reject every `Message/set` create in them with a
1495            // `forbidden` SetError."
1496            if let Some(sid) = &chat.space_id {
1497                match backend
1498                    .get_objects::<Space>(
1499                        caller,
1500                        &account_id,
1501                        Some(std::slice::from_ref(sid)),
1502                        None,
1503                    )
1504                    .await
1505                {
1506                    Ok((spaces, _)) if spaces.first().is_some_and(|s| s.closed_at.is_some()) => {
1507                        not_created.insert(
1508                            create_id.clone(),
1509                            json!({ "type": "forbidden", "description": "the Space is closed" }),
1510                        );
1511                        continue;
1512                    }
1513                    Ok(_) => {}
1514                    Err(e) => {
1515                        not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
1516                        continue;
1517                    }
1518                }
1519            }
1520
1521            // draft-atwood-jmap-chat-00 §Message/set: the sender MUST be a
1522            // current member of the target Chat and, in a channel, hold
1523            // `"send"`; otherwise `forbidden`.
1524            match backend
1525                .may_send_message(caller, &account_id, &chat_id)
1526                .await
1527            {
1528                Ok(Ok(())) => {}
1529                Ok(Err(set_err)) => {
1530                    not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
1531                    continue;
1532                }
1533                Err(e) => {
1534                    not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
1535                    continue;
1536                }
1537            }
1538
1539            // BroadcastMention permission check (§4.4.1).
1540            // Non-empty broadcastMentions in a Space-backed channel
1541            // requires mention_broadcast permission; rich-body spans are
1542            // display-only and never consulted (§Rich Body Format).
1543            // Group/direct chats (no spaceId) are unrestricted per spec.
1544            if let Some(sid) = chat
1545                .space_id
1546                .as_ref()
1547                .filter(|_| !broadcast_mentions_val.is_empty())
1548            {
1549                match backend
1550                    .may_broadcast_mention(caller, &account_id, sid, &chat_id)
1551                    .await
1552                {
1553                    Ok(Ok(())) => {}
1554                    Ok(Err(set_err)) => {
1555                        not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
1556                        continue;
1557                    }
1558                    Err(e) => {
1559                        not_created.insert(create_id.clone(), server_fail_value_from_backend(&e));
1560                        continue;
1561                    }
1562                }
1563            }
1564
1565            let reply_to: Option<Id> = match obj_val.get("replyTo").and_then(|v| v.as_str()) {
1566                Some(s) => match jmap_server::parse_wire_id(s, "replyTo") {
1567                    Ok(id) => Some(id),
1568                    Err(err) => {
1569                        not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
1570                        continue;
1571                    }
1572                },
1573                None => None,
1574            };
1575
1576            let supplied_root: Option<Id> =
1577                match obj_val.get("threadRootId").and_then(|v| v.as_str()) {
1578                    Some(s) => match jmap_server::parse_wire_id(s, "threadRootId") {
1579                        Ok(id) => Some(id),
1580                        Err(err) => {
1581                            not_created.insert(create_id.clone(), serde_json::Value::from(&*err));
1582                            continue;
1583                        }
1584                    },
1585                    None => None,
1586                };
1587
1588            // §Message `replyTo`: "Servers MUST validate that this ID
1589            // exists in the same Chat before storing." §Thread Model:
1590            // the root of a reply is the referenced message's
1591            // `threadRootId`, or the referenced message itself when that
1592            // is absent; a message with no `replyTo` has no root.
1593            // "Servers SHOULD validate them and MAY correct
1594            // `threadRootId`": a wrong value is rejected and an omitted
1595            // one is filled in. §Input Validation names no other error,
1596            // so both failures are `invalidProperties`.
1597            let expected_root: Option<Id> = match reply_to.as_ref() {
1598                None => None,
1599                Some(parent_id) => {
1600                    let parent = match backend
1601                        .get_objects::<Message>(
1602                            caller,
1603                            &account_id,
1604                            Some(std::slice::from_ref(parent_id)),
1605                            None,
1606                        )
1607                        .await
1608                    {
1609                        Ok((found, _)) => found.into_iter().find(|m| m.chat_id == chat_id),
1610                        Err(e) => {
1611                            not_created
1612                                .insert(create_id.clone(), server_fail_value_from_backend(&e));
1613                            continue;
1614                        }
1615                    };
1616                    let Some(parent) = parent else {
1617                        not_created.insert(
1618                            create_id.clone(),
1619                            json!({
1620                                "type": "invalidProperties",
1621                                "properties": ["replyTo"],
1622                                "description": "replyTo is not a Message in this Chat",
1623                            }),
1624                        );
1625                        continue;
1626                    };
1627                    Some(parent.thread_root_id.unwrap_or(parent.id))
1628                }
1629            };
1630            if supplied_root.is_some() && supplied_root != expected_root {
1631                not_created.insert(
1632                    create_id.clone(),
1633                    json!({
1634                        "type": "invalidProperties",
1635                        "properties": ["threadRootId"],
1636                        "description": "threadRootId does not match the thread of replyTo",
1637                    }),
1638                );
1639                continue;
1640            }
1641            let thread_root_id = expected_root;
1642
1643            // senderExpiresAt is a UTCDate per RFC 8620 §1.4 (20-char
1644            // YYYY-MM-DDTHH:MM:SSZ). Validate the wire shape via
1645            // UTCDate::new_validated; a malformed value produces
1646            // invalidProperties rather than silently flowing through to
1647            // a downstream string compare with undefined ordering.
1648            let sender_expires_at: Option<UTCDate> =
1649                if let Some(s) = obj_val.get("senderExpiresAt").and_then(|v| v.as_str()) {
1650                    let Ok(d) = UTCDate::new_validated(s) else {
1651                        not_created.insert(
1652                            create_id.clone(),
1653                            json!({
1654                                "type": "invalidProperties",
1655                                "properties": ["senderExpiresAt"],
1656                            }),
1657                        );
1658                        continue;
1659                    };
1660                    Some(d)
1661                } else {
1662                    None
1663                };
1664
1665            let burn_on_read: Option<bool> = obj_val.get("burnOnRead").and_then(|v| v.as_bool());
1666
1667            if let Some(ref expires_at) = sender_expires_at {
1668                let now = now_utc_string();
1669                if !iso8601_before(&now, expires_at) {
1670                    not_created.insert(
1671                        create_id.clone(),
1672                        json!({ "type": "invalidProperties", "properties": ["senderExpiresAt"] }),
1673                    );
1674                    continue;
1675                }
1676            }
1677
1678            let now_str = now_utc_string();
1679            let received_at: UTCDate = UTCDate::from(now_str.as_ref());
1680
1681            let mut attachments = Vec::new();
1682            if let Some(v) = obj_val.get("attachments").filter(|v| !v.is_null()) {
1683                match create_attachments(backend, caller, &account_id, &limits, &chat, v).await {
1684                    Ok(a) => attachments = a,
1685                    Err(err) => {
1686                        not_created.insert(create_id.clone(), err);
1687                        continue;
1688                    }
1689                }
1690            }
1691            let apply_optionals = match apply_create_optionals(obj_val) {
1692                Ok(f) => f,
1693                Err(property) => {
1694                    not_created.insert(
1695                        create_id.clone(),
1696                        json!({ "type": "invalidProperties", "properties": [property] }),
1697                    );
1698                    continue;
1699                }
1700            };
1701            if let Some(err) =
1702                check_attachments(backend, caller, &account_id, &limits, &attachments).await
1703            {
1704                not_created.insert(create_id.clone(), err);
1705                continue;
1706            }
1707
1708            // Slow-mode rate-limit gate (draft-atwood-jmap-chat-00
1709            // §Chat `slowModeSeconds` + spec commit `de60acb`).
1710            //
1711            // Runs AFTER wire-format validation so malformed requests
1712            // don't consume rate-tracker slots, and BEFORE the
1713            // `create_object` call so a throttled sender never sees the
1714            // message touch storage. On a Throttled return the backend
1715            // tells us when the caller may retry; we surface that
1716            // verbatim as the `serverRetryAfter` extra field on the
1717            // `rateLimit` SetError, built via the typed
1718            // `SetError::with_extra` builder added in bd:JMAP-dha0.
1719            // The spec requires "a `rateLimit` SetError ({{RFC8620,
1720            // Section 5.3}}) on the offending `Message/set` create",
1721            // not the method-level `rateLimited` (which is reserved
1722            // for the Peer/* methods). `serverRetryAfter` is a
1723            // workspace extension field. The reference `MemoryBackend`
1724            // never returns an Err here.
1725            if let Err(slow_err) = backend.slow_mode_check(caller, &account_id, &chat_id).await {
1726                let retry_after_str: String = slow_err.retry_after.as_ref().to_owned();
1727                let set_err = SetError::new(SetErrorType::RateLimit)
1728                    .with_description("Slow mode is active for this chat")
1729                    .with_extra("serverRetryAfter", json!(retry_after_str));
1730                not_created.insert(create_id.clone(), serde_json::Value::from(&set_err));
1731                continue;
1732            }
1733
1734            // draft-atwood-jmap-chat-00 §Message `senderMsgId`: "Equals
1735            // `id` for messages composed by the owner."
1736            let build = |id: &Id| {
1737                let mut msg = Message::new(
1738                    id.clone(),
1739                    id.clone(),
1740                    account_id.clone(),
1741                    chat_id,
1742                    body,
1743                    body_type,
1744                    sent_at,
1745                    received_at,
1746                    DeliveryState::Pending,
1747                );
1748                msg.reply_to = reply_to;
1749                msg.thread_root_id = thread_root_id;
1750                msg.sender_expires_at = sender_expires_at;
1751                msg.burn_on_read = burn_on_read;
1752                msg.attachments = attachments;
1753                msg.metadata = metadata;
1754                msg.private_metadata = private_metadata;
1755                apply_optionals(&mut msg);
1756                msg
1757            };
1758            // draft-atwood-jmap-chat-00 §Message/set: the server sets the
1759            // server-assigned fields "then enqueues the message for
1760            // outbound delivery"; `create_message` does both as one unit.
1761            match backend
1762                .create_message(caller, &account_id, create_id, build)
1763                .await
1764            {
1765                Ok((server_id, created_obj)) => {
1766                    mutated = true;
1767                    created_ids.insert(Id::from(create_id.as_str()), server_id);
1768                    delivered_chat_ids.push(created_obj.chat_id.clone());
1769                    created.insert(
1770                        create_id.clone(),
1771                        jmap_server::serialize_value(&created_obj)?,
1772                    );
1773                }
1774                Err(e) => {
1775                    not_created.insert(create_id.clone(), backend_set_error_value(e));
1776                }
1777            }
1778        }
1779        ensure_read_positions(backend, caller, &account_id, delivered_chat_ids.clone()).await;
1780        record_unread_count_changes(backend, caller, &account_id, delivered_chat_ids).await;
1781    }
1782
1783    // -----------------------------------------------------------------------
1784    // update
1785    // -----------------------------------------------------------------------
1786    // RFC 8620 §5.3: update keys and destroy ids may name this call's creates.
1787    jmap_server::resolve_set_id_refs(&mut args, created_ids, &created);
1788    if let Some(Value::Object(update_map)) = args.remove("update") {
1789        for (id_str, mut patch_val) in update_map {
1790            let id = match jmap_server::parse_wire_id(&id_str, "id") {
1791                Ok(id) => id,
1792                Err(err) => {
1793                    not_updated.insert(id_str, serde_json::Value::from(&*err));
1794                    continue;
1795                }
1796            };
1797            // An edit may replace `mentions`; `attachments` is immutable.
1798            if let Err(err) = resolve_entry_refs(&mut patch_val, &[MENTION_ID], created_ids) {
1799                not_updated.insert(id_str, serde_json::Value::from(&*err));
1800                continue;
1801            }
1802
1803            // RFC 8620 §5.3: "There MUST NOT be two patches in the
1804            // PatchObject where the pointer of one is the prefix of the
1805            // pointer of the other" or the update "MUST be rejected with an
1806            // "invalidPatch" error".
1807            if patch_val.get("reactions").is_some()
1808                && patch_val
1809                    .as_object()
1810                    .is_some_and(|obj| obj.keys().any(|k| k.starts_with("reactions/")))
1811            {
1812                not_updated.insert(
1813                    id_str,
1814                    json!({
1815                        "type": "invalidPatch",
1816                        "description":
1817                            "patch must not combine top-level `reactions` with `reactions/{id}` entries",
1818                    }),
1819                );
1820                continue;
1821            }
1822
1823            // draft-ietf-jmap-metadata-05 §3.2: patch errors "that can be
1824            // determined from the request alone ... MUST be reported with
1825            // "invalidPatch"" before `notFound`.
1826            if let Some(Err(err)) = patch_val
1827                .as_object()
1828                .map(|o| check_metadata_entry(o, false, using))
1829            {
1830                not_updated.insert(id_str, serde_json::Value::from(&*err));
1831                continue;
1832            }
1833            if let Some(Err(e)) = patch_val.as_object().map(jmap_server::check_patch_paths) {
1834                not_updated.insert(
1835                    id_str,
1836                    json!({ "type": "invalidPatch", "description": e.to_string() }),
1837                );
1838                continue;
1839            }
1840
1841            // The stored Message and its Chat, read once for every check
1842            // below.
1843            let stored = match backend
1844                .get_objects::<Message>(caller, &account_id, Some(std::slice::from_ref(&id)), None)
1845                .await
1846            {
1847                Ok((found, _)) => found.into_iter().next(),
1848                Err(e) => {
1849                    not_updated.insert(id_str, server_fail_value_from_backend(&e));
1850                    continue;
1851                }
1852            };
1853            let Some(stored) = stored else {
1854                not_updated.insert(id_str, Value::from(&SetError::new(SetErrorType::NotFound)));
1855                continue;
1856            };
1857            let stored_chat = match backend
1858                .get_objects::<Chat>(
1859                    caller,
1860                    &account_id,
1861                    Some(std::slice::from_ref(&stored.chat_id)),
1862                    None,
1863                )
1864                .await
1865            {
1866                Ok((found, _)) => found.into_iter().next(),
1867                Err(e) => {
1868                    not_updated.insert(id_str, server_fail_value_from_backend(&e));
1869                    continue;
1870                }
1871            };
1872
1873            // RFC 8620 §5.3: "Any server-set properties MAY be included in
1874            // the patch if their value is identical to the current server
1875            // value ... Otherwise, the update MUST be rejected with an
1876            // "invalidProperties" SetError." Identical values are dropped
1877            // here, so the checks below see only the client changes.
1878            //
1879            // Existence and permission come before shape (DECISIONS.md 44):
1880            // the shape errors below are held in `shape_err` and reported
1881            // only after the `forbidden` checks, which look at patch keys
1882            // and values the read-only check does not touch.
1883            let mut shape_err: Option<Value> = None;
1884            if let Value::Object(map) = &mut patch_val
1885                && let Err(err) = strip_read_only_patch::<Message>(map, &stored)
1886            {
1887                shape_err = Some(err);
1888            }
1889            // A whole `reactions` identical to the stored map changes
1890            // nothing: drop it, as an identical server-set value is
1891            // (RFC 8620 §5.3), so only a real whole-map write is rejected
1892            // below (bd:JMAP-t8ej.32 item 4).
1893            if let Value::Object(map) = &mut patch_val
1894                && map.get("reactions").is_some_and(|r| {
1895                    serde_json::to_value(&stored)
1896                        .ok()
1897                        .is_some_and(|s| s.get("reactions").unwrap_or(&Value::Null) == r)
1898                })
1899            {
1900                map.remove("reactions");
1901            }
1902
1903            // draft-atwood-jmap-chat-00 §Message/set defines the only
1904            // client updates: Editing (`body`, `bodyType`, `mentions`,
1905            // `broadcastMentions`), Adding and Removing Reactions
1906            // (`reactions/<senderReactionId>` JSON Pointer keys), Deleting
1907            // (`deletedAt`, `deletedForAll`) and Marking as Read (`readAt`,
1908            // `readDisposition`): the client-settable Message properties
1909            // that are not immutable, with `reactions` changed only per
1910            // entry. Every other key names a server-set or immutable
1911            // property, so it is rejected with RFC 8620 §5.3
1912            // `invalidProperties`. draft-ietf-jmap-metadata-05 §3.2 adds
1913            // `metadata` and `privateMetadata`, written whole or by patch
1914            // path.
1915            let defined = |k: &str| {
1916                k.starts_with("reactions/")
1917                    || is_metadata_key(k)
1918                    || (k != "reactions" && is_client_updatable::<Message>(k))
1919            };
1920            let bad_props: Vec<&str> = patch_val
1921                .as_object()
1922                .map(|obj| {
1923                    obj.keys()
1924                        .map(String::as_str)
1925                        .filter(|k| !defined(k))
1926                        .collect()
1927                })
1928                .unwrap_or_default();
1929            if shape_err.is_none() && !bad_props.is_empty() {
1930                shape_err = Some(json!({ "type": "invalidProperties", "properties": bad_props }));
1931            }
1932
1933            // draft-atwood-jmap-chat-00 §Message `readDisposition`: "the
1934            // server MUST reject an update that sets `readDisposition`
1935            // without `readAt` with an `invalidProperties` SetError naming
1936            // `readDisposition`." A null `readAt` clears it, not sets it.
1937            let sets = |field: &str| patch_val.get(field).is_some_and(|v| !v.is_null());
1938            if shape_err.is_none() && sets("readDisposition") && !sets("readAt") {
1939                shape_err =
1940                    Some(json!({ "type": "invalidProperties", "properties": ["readDisposition"] }));
1941            }
1942
1943            // §Input Validation: "`bodyType`: reject a value not listed in
1944            // `supportedBodyTypes`".
1945            if shape_err.is_none()
1946                && patch_val.get("bodyType").is_some_and(|v| {
1947                    !v.as_str()
1948                        .is_some_and(|s| limits.supported_body_types.contains(&s))
1949                })
1950            {
1951                shape_err =
1952                    Some(json!({ "type": "invalidProperties", "properties": ["bodyType"] }));
1953            }
1954
1955            // Per-Chat restrictions of extension-bound Chats; see
1956            // `ChatRestrictions::may_update_message`. It sees only the keys
1957            // the update may change.
1958            if let Some(chat) = &stored_chat {
1959                let patch_keys: Vec<&str> = patch_val
1960                    .as_object()
1961                    .map(|obj| {
1962                        obj.keys()
1963                            .map(String::as_str)
1964                            .filter(|k| defined(k))
1965                            .collect()
1966                    })
1967                    .unwrap_or_default();
1968                match backend
1969                    .may_update_message(caller, &account_id, chat, &stored, &patch_keys)
1970                    .await
1971                {
1972                    Ok(Ok(())) => {}
1973                    Ok(Err(set_err)) => {
1974                        not_updated.insert(id_str, serde_json::Value::from(&set_err));
1975                        continue;
1976                    }
1977                    Err(e) => {
1978                        not_updated.insert(id_str, server_fail_value_from_backend(&e));
1979                        continue;
1980                    }
1981                }
1982            }
1983
1984            // draft-atwood-jmap-chat-00 §Deleting a Message: servers MUST
1985            // reject `deletedForAll: true` when `senderId` is not the
1986            // accountId. §Editing a Message: an edit of `body`, `bodyType`,
1987            // `mentions` or `broadcastMentions` is only permitted where
1988            // `senderId` is the accountId and `deletedAt` is absent; any other edit is
1989            // `forbidden`.
1990            let deletes_for_all =
1991                patch_val.get("deletedForAll").and_then(|v| v.as_bool()) == Some(true);
1992            let edits = ["body", "bodyType", "mentions", "broadcastMentions"]
1993                .iter()
1994                .any(|&field| patch_val.get(field).is_some());
1995            // The event for `ChatEvents::on_outbound_event`, built from
1996            // the stored Message once the checks below pass.
1997            let mut outbound: Option<OutboundEvent> = None;
1998            if deletes_for_all || edits {
1999                let description = if deletes_for_all && stored.sender_id != account_id {
2000                    Some(
2001                        "deletedForAll is only permitted on messages whose senderId is the accountId",
2002                    )
2003                } else if edits && (stored.sender_id != account_id || stored.deleted_at.is_some()) {
2004                    Some(
2005                        "edits are only permitted on messages whose senderId is the accountId and deletedAt is absent",
2006                    )
2007                } else {
2008                    None
2009                };
2010                if let Some(description) = description {
2011                    not_updated.insert(
2012                        id_str,
2013                        json!({ "type": "forbidden", "description": description }),
2014                    );
2015                    continue;
2016                }
2017                if let Some(err) = shape_err.take() {
2018                    not_updated.insert(id_str, err);
2019                    continue;
2020                }
2021                if let Some(err) = edit_limit_error(&stored, &patch_val, &limits) {
2022                    not_updated.insert(id_str, err);
2023                    continue;
2024                }
2025                outbound = Some({
2026                    let (chat_id, message_id, sender_msg_id) = (
2027                        stored.chat_id.clone(),
2028                        stored.id.clone(),
2029                        stored.sender_msg_id.clone(),
2030                    );
2031                    if deletes_for_all {
2032                        OutboundEvent::Retract {
2033                            chat_id,
2034                            message_id,
2035                            sender_msg_id,
2036                        }
2037                    } else {
2038                        OutboundEvent::Edit {
2039                            chat_id,
2040                            message_id,
2041                            sender_msg_id,
2042                        }
2043                    }
2044                });
2045            }
2046
2047            // Every `forbidden` check has run: report a held shape error.
2048            if let Some(err) = shape_err.take() {
2049                not_updated.insert(id_str, err);
2050                continue;
2051            }
2052
2053            // Nothing left once identical values are dropped (or a literal
2054            // `{}`): a no-op success with no write (RFC 8620 §5.3).
2055            if patch_val.as_object().is_some_and(Map::is_empty) {
2056                updated.insert(id_str, Value::Null);
2057                continue;
2058            }
2059
2060            // Build augmented patch with server-side timestamps.
2061            let mut augmented = patch_val;
2062            if augmented.get("body").is_some()
2063                && let Some(obj) = augmented.as_object_mut()
2064            {
2065                obj.insert("editedAt".to_owned(), json!(now_utc_string()));
2066            }
2067            // draft-atwood-jmap-chat-00 §Message deletedAt: a deleted
2068            // Message has an empty `body`, empty `attachments`, and no
2069            // `editHistory`, whether the deletion is local or for all. The
2070            // merge-patch null purges the stored revisions rather than
2071            // merely hiding them.
2072            let deletes =
2073                deletes_for_all || augmented.get("deletedAt").is_some_and(|v| !v.is_null());
2074            if deletes && let Some(obj) = augmented.as_object_mut() {
2075                if deletes_for_all {
2076                    obj.insert("deletedAt".to_owned(), json!(now_utc_string()));
2077                }
2078                obj.insert("body".to_owned(), json!(""));
2079                obj.insert("attachments".to_owned(), json!([]));
2080                obj.insert("editHistory".to_owned(), Value::Null);
2081            }
2082            // Spec §557 + §1029: when readAt is set without readDisposition, default to "displayed".
2083            // draft-atwood-jmap-chat-00 §Message `readDisposition`: "Absent
2084            // when `readAt` is not set." so clearing readAt clears it too.
2085            if let Some(obj) = augmented.as_object_mut() {
2086                match obj.get("readAt") {
2087                    Some(Value::Null) => {
2088                        obj.insert("readDisposition".to_owned(), Value::Null);
2089                    }
2090                    Some(_) if !obj.contains_key("readDisposition") => {
2091                        obj.insert("readDisposition".to_owned(), json!("displayed"));
2092                    }
2093                    _ => {}
2094                }
2095            }
2096
2097            // Reaction patch processing
2098            // (draft-atwood-jmap-chat-00 §Message/set, §Reaction).
2099            //
2100            // Reactions are added/removed by patching
2101            // `reactions/{senderReactionId}` as RFC 8620 §5.3 JSON
2102            // Pointer entries:
2103            //
2104            // - value is an object: add or modify the reaction
2105            // - value is `null`: remove the reaction
2106            //
2107            // The backend applies these paths into the stored
2108            // `reactions` map. Before forwarding, the handler:
2109            //
2110            // 1. Rejects `reactions/{id}` keys containing `/` or `~`
2111            //    (RFC 6901 escape characters — the chat-client also
2112            //    rejects them; this is defense-in-depth).
2113            // 2. Rejects non-null non-object values as `invalidPatch`.
2114            // 3. Pre-fetches the Message and rejects with `forbidden`
2115            //    if the patched key targets an existing reaction whose
2116            //    `senderId` is not the accountId — per spec, only the
2117            //    original sender may modify their own reactions.
2118            // 4. Server-overrides `senderId` to the accountId on every add
2119            //    (spec MUST; defense-in-depth).
2120            // 5. Server-injects `sentAt` to the current time on adds
2121            //    that lack it, so the resulting `Reaction` round-trips
2122            //    through the typed shape (which requires `sentAt`).
2123            let reaction_pointer_keys: Vec<String> = augmented
2124                .as_object()
2125                .map(|obj| {
2126                    obj.keys()
2127                        .filter(|k| k.starts_with("reactions/"))
2128                        .cloned()
2129                        .collect()
2130                })
2131                .unwrap_or_default();
2132
2133            // One `OutboundEvent::ReactionUpdate` per patched key, built
2134            // from the pre-fetched Message and reported after the write.
2135            let mut reaction_events: Vec<OutboundEvent> = Vec::new();
2136            if !reaction_pointer_keys.is_empty() {
2137                // Validate each pointer key + value shape. The
2138                // `.collect::<Result<Vec<_>, _>>()` form short-circuits
2139                // on the first Err and is the idiomatic Rust expression
2140                // of "validate-or-fail" over an iterator. A future
2141                // contributor adding a new validation rule appends an
2142                // `if ... { return Err(...) }` inside the closure; the
2143                // short-circuit behavior is structural, not a hand-coded
2144                // flag invariant.
2145                let decoded: Result<Vec<(String, String)>, String> = reaction_pointer_keys
2146                    .iter()
2147                    .map(|raw_key| {
2148                        let suffix = &raw_key["reactions/".len()..];
2149                        if suffix.is_empty() || suffix.contains('/') || suffix.contains('~') {
2150                            return Err(format!(
2151                                "reactions/{{id}} pointer key {raw_key:?} has empty or forbidden suffix; '/' and '~' are reserved by RFC 6901",
2152                            ));
2153                        }
2154                        let val = augmented.get(raw_key).unwrap_or(&Value::Null);
2155                        if !val.is_null() {
2156                            let ok = val.as_object().is_some_and(|m| {
2157                                m.get("emoji")
2158                                    .and_then(|v| v.as_str())
2159                                    .is_some_and(|s| !s.is_empty())
2160                            });
2161                            if !ok {
2162                                return Err(format!(
2163                                    "reaction value for {raw_key:?} must be null or an object with a non-empty `emoji` string",
2164                                ));
2165                            }
2166                        }
2167                        Ok((raw_key.clone(), suffix.to_owned()))
2168                    })
2169                    .collect();
2170                let decoded = match decoded {
2171                    Ok(d) => d,
2172                    Err(desc) => {
2173                        not_updated.insert(
2174                            id_str,
2175                            json!({ "type": "invalidPatch", "description": desc }),
2176                        );
2177                        continue;
2178                    }
2179                };
2180
2181                // Inspect the stored Message's existing reactions.
2182                let mut forbidden: Vec<String> = Vec::new();
2183                for (raw_key, suffix) in &decoded {
2184                    let existing = stored.reactions.get(suffix);
2185                    if existing.is_some_and(|r| r.sender_id != account_id) {
2186                        forbidden.push(suffix.clone());
2187                    }
2188                    // A null on a key with no stored reaction
2189                    // removes nothing, so nothing propagates.
2190                    let action = match augmented.get(raw_key) {
2191                        Some(Value::Object(_)) => Some(ReactionAction::Add),
2192                        _ => existing.map(|r| ReactionAction::Remove { removed: r.clone() }),
2193                    };
2194                    if let Some(action) = action {
2195                        reaction_events.push(OutboundEvent::ReactionUpdate {
2196                            chat_id: stored.chat_id.clone(),
2197                            message_id: stored.id.clone(),
2198                            sender_msg_id: stored.sender_msg_id.clone(),
2199                            sender_reaction_id: suffix.clone(),
2200                            action,
2201                        });
2202                    }
2203                }
2204                if !forbidden.is_empty() {
2205                    not_updated.insert(
2206                        id_str,
2207                        json!({
2208                            "type": "forbidden",
2209                            "description": format!(
2210                                "cannot modify reactions authored by another sender: {}",
2211                                forbidden.join(", "),
2212                            ),
2213                        }),
2214                    );
2215                    continue;
2216                }
2217
2218                // Server-override `senderId` and inject `sentAt` where
2219                // absent on every `reactions/{key}` add, so the stored
2220                // Reaction round-trips through the typed shape.
2221                let now_str = now_utc_string();
2222                if let Some(obj) = augmented.as_object_mut() {
2223                    for (raw_key, _) in &decoded {
2224                        if let Some(Value::Object(map)) = obj.get_mut(raw_key) {
2225                            // Spec MUST: server overrides senderId to
2226                            // the accountId on every add, regardless of
2227                            // what the client supplied.
2228                            map.insert("senderId".to_owned(), json!(account_id));
2229                            map.entry("sentAt").or_insert_with(|| json!(now_str));
2230                        }
2231                    }
2232                }
2233            }
2234
2235            // Detect a non-null readAt assignment in the patch. A
2236            // `readAt: null` is a PatchObject clear (RFC 8620 §5.3), not a
2237            // "mark as read" event, so it does not trigger burn-on-read.
2238            // draft-atwood-jmap-chat-00 §Message `burnOnRead` (jmap-chat-spec
2239            // 77c3474 L750): the receiving server SHOULD hard-delete
2240            // immediately after setting readAt on a message whose
2241            // `burnOnRead` is `true`; this crate does so by choice.
2242            let patch_sets_read_at = augmented.get("readAt").is_some_and(|v| !v.is_null());
2243
2244            // If the patch sets readAt, the stored Message decides whether
2245            // it is burn-on-read. We deliberately consult the pre-patch
2246            // state: a recipient setting readAt for the first time should
2247            // fire the burn. draft-atwood-jmap-chat-00 §Message
2248            // `burnOnRead`: "Applies only to the receiving mailbox; the
2249            // sender's own copy is not affected."
2250            let pre_patch_read: Option<Message> = if patch_sets_read_at {
2251                Some(stored.clone())
2252            } else {
2253                None
2254            };
2255            let pre_patch_burn_on_read = pre_patch_read
2256                .as_ref()
2257                .is_some_and(|m| m.burn_on_read == Some(true) && m.sender_id != account_id);
2258
2259            // BroadcastMention validation and permission check on edit
2260            // (§4.4.1 / §4.16). The post-patch broadcastMentions fall back
2261            // to the stored message where the patch leaves them unchanged,
2262            // so an edit that retains a broadcast mention is gated like one
2263            // that adds it.
2264            if edits {
2265                let current_has_bm = !stored.broadcast_mentions.is_empty();
2266                // Structural validation only when broadcastMentions is part
2267                // of the patch.
2268                let has_bm = match augmented.get("broadcastMentions") {
2269                    Some(bm) => {
2270                        let bm_arr: Vec<Value> = bm.as_array().cloned().unwrap_or_default();
2271                        if let Some(err) = validate_broadcast_mentions(&bm_arr) {
2272                            not_updated.insert(id_str, err);
2273                            continue;
2274                        }
2275                        !bm_arr.is_empty()
2276                    }
2277                    None => current_has_bm,
2278                };
2279
2280                // BroadcastMention permission check on update (§4.4.1).
2281                // A post-patch broadcastMentions entry in a Space-backed
2282                // channel requires mention_broadcast permission; rich-body
2283                // spans are display-only and never consulted. Group/direct
2284                // chats (no spaceId) are unrestricted per spec.
2285                // A Chat not found is left for update_object to surface
2286                // downstream.
2287                let channel = stored_chat
2288                    .as_ref()
2289                    .and_then(|c| Some((c.space_id.as_ref()?, &c.id)));
2290                if let (true, Some((sid, chat_id))) = (has_bm, channel) {
2291                    match backend
2292                        .may_broadcast_mention(caller, &account_id, sid, chat_id)
2293                        .await
2294                    {
2295                        Ok(Ok(())) => {}
2296                        Ok(Err(set_err)) => {
2297                            not_updated.insert(id_str, serde_json::Value::from(&set_err));
2298                            continue;
2299                        }
2300                        Err(e) => {
2301                            not_updated.insert(id_str, server_fail_value_from_backend(&e));
2302                            continue;
2303                        }
2304                    }
2305                }
2306            }
2307
2308            // draft-atwood-jmap-chat-federation-00 §Peer/receipt: the
2309            // owner read a Message another participant sent. The read
2310            // fields come from the patch, since a burned Message is gone.
2311            let receipt = pre_patch_read
2312                .filter(|m| m.sender_id != account_id)
2313                .and_then(|m| {
2314                    let read_at =
2315                        serde_json::from_value::<UTCDate>(augmented.get("readAt")?.clone()).ok()?;
2316                    let read_disposition = augmented
2317                        .get("readDisposition")
2318                        .and_then(|v| serde_json::from_value(v.clone()).ok());
2319                    Some(OutboundEvent::Receipt {
2320                        chat_id: m.chat_id,
2321                        message_id: m.id,
2322                        sender_msg_id: m.sender_msg_id,
2323                        sender_id: m.sender_id,
2324                        read_at,
2325                        read_disposition,
2326                    })
2327                });
2328            // Convert the augmented wire-format Value into a typed
2329            // PatchObject (RFC 8620 §5.3). Non-object values yield
2330            // invalidPatch.
2331            let patch = match serde_json::from_value::<PatchObject>(augmented) {
2332                Ok(p) => p,
2333                Err(e) => {
2334                    not_updated.insert(
2335                        id_str,
2336                        json!({ "type": "invalidPatch", "description": e.to_string() }),
2337                    );
2338                    continue;
2339                }
2340            };
2341            // draft-atwood-jmap-chat-00 §Message `burnOnRead` (jmap-chat-spec
2342            // 77c3474 L750): "SHOULD permanently hard-delete this message
2343            // (row removal, not tombstone) immediately after setting
2344            // `readAt`." Done by choice, as one atomic
2345            // backend call, so a failure commits nothing and a retry
2346            // burns again.
2347            let burns = patch_sets_read_at && pre_patch_burn_on_read;
2348            let update_outcome = if burns {
2349                backend
2350                    .read_and_burn_message(caller, &account_id, &id, patch)
2351                    .await
2352                    .map(|()| None)
2353            } else {
2354                backend
2355                    .update_object::<Message>(caller, &account_id, &id, patch)
2356                    .await
2357            };
2358            let maybe_updated_obj = match update_outcome {
2359                Ok(maybe_obj) => maybe_obj,
2360                Err(e) => {
2361                    not_updated.insert(id_str, backend_set_error_value(e));
2362                    continue;
2363                }
2364            };
2365
2366            // Update (or burn) succeeded.
2367            mutated = true;
2368            // draft-atwood-jmap-chat-federation-00 §Peer/retract "Sender
2369            // Behavior": an update that sets `deletedForAll: true` "MUST
2370            // send `Peer/retract` to the server of every other participant
2371            // in the Chat". Reported only once the update is written, so a
2372            // failed write retracts nothing on peers.
2373            if let Some(event @ OutboundEvent::Retract { .. }) = &outbound {
2374                backend.on_outbound_event(caller, &account_id, event).await;
2375            }
2376            // draft-atwood-jmap-chat-00 §Editing a Message: "Send
2377            // `Peer/deliver` carrying an `edit` payload to all
2378            // recipients". A patch that also deletes or burns the Message
2379            // leaves nothing to deliver.
2380            if let Some(event @ OutboundEvent::Edit { .. }) = &outbound
2381                && !deletes
2382                && !burns
2383            {
2384                backend.on_outbound_event(caller, &account_id, event).await;
2385            }
2386            // draft-atwood-jmap-chat-00 §Adding and Removing Reactions:
2387            // propagate each add and removal "via `Peer/deliver`
2388            // `reactionUpdate` payload". As for edits, a patch that also
2389            // deletes or burns the Message leaves nothing to deliver.
2390            if !deletes && !burns {
2391                for event in &reaction_events {
2392                    backend.on_outbound_event(caller, &account_id, event).await;
2393                }
2394            }
2395            // §Peer/receipt "Sender Behavior": "If the effective preference
2396            // is `false`, the server SHOULD NOT invoke `Peer/receipt`". A
2397            // burned Message was still read, so its receipt is reported.
2398            if let Some(event @ OutboundEvent::Receipt { chat_id, .. }) = &receipt
2399                && shares_receipts(backend, caller, &account_id, chat_id).await
2400            {
2401                backend.on_outbound_event(caller, &account_id, event).await;
2402            }
2403            match maybe_updated_obj {
2404                Some(obj) => {
2405                    updated.insert(id_str, jmap_server::serialize_value(&obj)?);
2406                }
2407                None => {
2408                    updated.insert(id_str, Value::Null);
2409                }
2410            }
2411        }
2412    }
2413
2414    // -----------------------------------------------------------------------
2415    // destroy
2416    // -----------------------------------------------------------------------
2417    if let Some(destroy_arr) = args.get("destroy").and_then(|v| v.as_array()) {
2418        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
2419        // Reject the whole request if any element is non-string rather than
2420        // silently skipping it, which would produce a misleading response.
2421        let id_strs: Vec<&str> = destroy_arr
2422            .iter()
2423            .map(|v| {
2424                v.as_str().ok_or_else(|| {
2425                    JmapError::invalid_arguments(format!(
2426                        "destroy: every element must be a string Id; got {}",
2427                        jmap_server::json_type_name(v)
2428                    ))
2429                })
2430            })
2431            .collect::<Result<_, _>>()?;
2432        // The destroyed Messages' Chats, read before the destroy, for
2433        // `record_unread_count_changes` (§Chat `unreadCount`).
2434        // A malformed id is skipped here and rejected per entry below.
2435        let destroy_ids: Vec<Id> = destroy_arr
2436            .iter()
2437            .filter_map(Value::as_str)
2438            .filter_map(|s| Id::new_validated(s).ok())
2439            .collect();
2440        let chat_of: HashMap<Id, Id> = backend
2441            .get_objects::<Message>(caller, &account_id, Some(&destroy_ids), None)
2442            .await
2443            .map(|(found, _)| found.into_iter().map(|m| (m.id, m.chat_id)).collect())
2444            .unwrap_or_default();
2445        let mut destroyed_chat_ids: Vec<Id> = Vec::new();
2446        for id_str in id_strs {
2447            let id = match jmap_server::parse_wire_id(id_str, "id") {
2448                Ok(id) => id,
2449                Err(err) => {
2450                    not_destroyed.insert(id_str.to_owned(), serde_json::Value::from(&*err));
2451                    continue;
2452                }
2453            };
2454
2455            match backend
2456                .destroy_object::<Message>(caller, &account_id, &id)
2457                .await
2458            {
2459                Ok(()) => {
2460                    mutated = true;
2461                    destroyed_chat_ids.extend(chat_of.get(&id).cloned());
2462                    destroyed_list.push(Value::String(id_str.to_owned()));
2463                }
2464                Err(e) => {
2465                    not_destroyed.insert(id_str.to_owned(), backend_set_error_value(e));
2466                }
2467            }
2468        }
2469        record_unread_count_changes(backend, caller, &account_id, destroyed_chat_ids).await;
2470    }
2471
2472    finalize_set_response::<B, Message>(
2473        backend,
2474        caller,
2475        &account_id,
2476        old_state,
2477        mutated,
2478        SetAccumulators {
2479            created,
2480            updated,
2481            destroyed: destroyed_list,
2482            not_created,
2483            not_updated,
2484            not_destroyed,
2485        },
2486    )
2487    .await
2488}
2489
2490#[cfg(test)]
2491mod tests {
2492    use super::*;
2493    use crate::memory::MemoryBackend;
2494    use serde_json::json;
2495
2496    const ACCOUNT_ID: &str = "a1";
2497
2498    // Oracles in this module are hand-built per workspace test-integrity
2499    // policy. Each test asserts the wire shape of a known-invalid or
2500    // known-valid broadcastMentions payload against the validation rules
2501    // from spec §4.4.1 / §4.16. The independent oracle is the spec text
2502    // itself; no assertion uses the code under test as its own reference.
2503
2504    /// §BroadcastMention: "Servers MUST reject a BroadcastMention with an
2505    /// unrecognized `scope` value; in `Message/set` the rejection is an
2506    /// `invalidProperties` SetError naming `broadcastMentions`."
2507    #[tokio::test]
2508    async fn broadcast_mention_validation_rejects_unknown_scope() {
2509        let backend = MemoryBackend::<()>::default();
2510        backend.register_account(&Id::from(ACCOUNT_ID));
2511        let HandlerOutput { primary: resp, .. } = handle_message_set(
2512            &backend,
2513            &(),
2514            &std::collections::BTreeMap::new(),
2515            json!({
2516                "accountId": ACCOUNT_ID,
2517                "create": {
2518                    "m0": {
2519                        "chatId": "c1",
2520                        "body": "Hello @channel",
2521                        "sentAt": "2024-01-01T00:00:00Z",
2522                        "broadcastMentions": [
2523                            { "scope": "channel", "offset": 6, "length": 8 }
2524                        ]
2525                    }
2526                }
2527            }),
2528            &[],
2529        )
2530        .await
2531        .expect("handle_message_set");
2532
2533        assert!(resp["notCreated"]["m0"].is_object());
2534        assert_eq!(resp["notCreated"]["m0"]["type"], "invalidProperties");
2535        assert_eq!(
2536            resp["notCreated"]["m0"]["properties"],
2537            json!(["broadcastMentions"])
2538        );
2539        let desc = resp["notCreated"]["m0"]["description"]
2540            .as_str()
2541            .expect("description");
2542        assert!(
2543            desc.contains("unrecognized scope"),
2544            "expected 'unrecognized scope' in description, got: {desc}"
2545        );
2546    }
2547
2548    /// A valid @everyone mention at the correct body offset succeeds.
2549    #[tokio::test]
2550    async fn broadcast_mention_validation_accepts_valid() {
2551        let backend = MemoryBackend::<()>::default();
2552        let chat_id = make_group_chat(&backend).await;
2553        let body = "Hello @everyone!";
2554        let HandlerOutput { primary: resp, .. } = handle_message_set(
2555            &backend,
2556            &(),
2557            &std::collections::BTreeMap::new(),
2558            json!({
2559                "accountId": ACCOUNT_ID,
2560                "create": {
2561                    "m0": {
2562                        "chatId": chat_id,
2563                        "body": body,
2564                        "sentAt": "2024-01-01T00:00:00Z",
2565                        "broadcastMentions": [
2566                            { "scope": "everyone", "offset": 6, "length": 9 }
2567                        ]
2568                    }
2569                }
2570            }),
2571            &[],
2572        )
2573        .await
2574        .expect("handle_message_set");
2575
2576        assert!(
2577            resp["created"]["m0"].is_object(),
2578            "expected created, got notCreated: {}",
2579            resp["notCreated"]["m0"]
2580        );
2581    }
2582
2583    /// An empty broadcastMentions array is always valid.
2584    #[tokio::test]
2585    async fn broadcast_mention_validation_accepts_empty() {
2586        let backend = MemoryBackend::<()>::default();
2587        let chat_id = make_group_chat(&backend).await;
2588        let HandlerOutput { primary: resp, .. } = handle_message_set(
2589            &backend,
2590            &(),
2591            &std::collections::BTreeMap::new(),
2592            json!({
2593                "accountId": ACCOUNT_ID,
2594                "create": {
2595                    "m0": {
2596                        "chatId": chat_id,
2597                        "body": "Hello, world!",
2598                        "sentAt": "2024-01-01T00:00:00Z",
2599                        "broadcastMentions": []
2600                    }
2601                }
2602            }),
2603            &[],
2604        )
2605        .await
2606        .expect("handle_message_set");
2607
2608        assert!(
2609            resp["created"]["m0"].is_object(),
2610            "expected created, got notCreated: {}",
2611            resp["notCreated"]["m0"]
2612        );
2613    }
2614
2615    // -----------------------------------------------------------------------
2616    // BroadcastMention permission-check tests (§4.4.1 mention_broadcast)
2617    //
2618    // Oracle: the spec text itself. Group/direct chats without a spaceId
2619    // are unrestricted; channel chats with a spaceId must pass the
2620    // mention_broadcast gate. The channel fixture's owner role holds
2621    // mention_broadcast, so these tests verify the handler CODE PATH is
2622    // wired correctly and that the gate is skipped or invoked in the
2623    // right circumstances; tests/message_broadcast_permission_memory.rs
2624    // covers denial.
2625    // -----------------------------------------------------------------------
2626
2627    /// Helper: create a group Chat (no spaceId) via handle_chat_set and
2628    /// return its server-assigned id.
2629    async fn make_group_chat(backend: &MemoryBackend<()>) -> String {
2630        backend.register_account(&Id::from(ACCOUNT_ID));
2631        let HandlerOutput { primary: resp, .. } = crate::chat::handle_chat_set(
2632            backend,
2633            &(),
2634            &std::collections::BTreeMap::new(),
2635            json!({
2636                "accountId": ACCOUNT_ID,
2637                "create": { "c0": { "kind": "group", "name": "test-group" } }
2638            }),
2639            &[],
2640        )
2641        .await
2642        .expect("make_group_chat");
2643        resp["created"]["c0"]["id"]
2644            .as_str()
2645            .expect("group chat id")
2646            .to_owned()
2647    }
2648
2649    /// Helper: seed a Space whose owner member (the accountId, per
2650    /// §SpaceMember `id`) holds `manage_channels` and `send` (§Message/set,
2651    /// jmap-chat-spec 77c3474 L1220: "For channel Chats, the server SHOULD
2652    /// verify the sender holds the `"send"` permission"), then create a channel Chat inside it, and
2653    /// return the channel's server-assigned id.
2654    async fn make_channel_chat(backend: &MemoryBackend<()>) -> String {
2655        let space_id = "s0";
2656        backend.insert_object_for_test(
2657            "Space",
2658            ACCOUNT_ID,
2659            space_id,
2660            json!({
2661                "id": space_id,
2662                "name": "test-space",
2663                "createdAt": "2026-01-01T00:00:00Z",
2664                "memberCount": 1,
2665                "categories": [],
2666                "uncategorizedChannelIds": [],
2667                "isPublic": false,
2668                "isPubliclyPreviewable": false,
2669                "roles": [{ "id": "r-owner", "name": "Owner", "permissions": ["manage_channels", "mention_broadcast", "send"], "position": 10 }],
2670                "members": [{ "id": ACCOUNT_ID, "roleIds": ["r-owner"], "joinedAt": "2026-01-01T00:00:00Z" }],
2671            }),
2672        );
2673
2674        // Create a channel Chat in that Space. §Chat/set: "Channel Chats
2675        // are created exclusively via the `addChannels` patch key in
2676        // `Space/set`." §Space/set `addChannels`: "Requires
2677        // `"manage_channels"`."
2678        crate::space::handle_space_set(
2679            backend,
2680            &(),
2681            &std::collections::BTreeMap::new(),
2682            json!({
2683                "accountId": ACCOUNT_ID,
2684                "update": { space_id: { "addChannels": [{ "name": "general" }] } }
2685            }),
2686            &[],
2687        )
2688        .await
2689        .expect("make_channel_chat: addChannels");
2690        let HandlerOutput {
2691            primary: get_resp, ..
2692        } = crate::space::handle_space_get(
2693            backend,
2694            &(),
2695            json!({ "accountId": ACCOUNT_ID, "ids": [space_id] }),
2696            &[],
2697        )
2698        .await
2699        .expect("make_channel_chat: Space/get");
2700        get_resp["list"][0]["uncategorizedChannelIds"][0]
2701            .as_str()
2702            .expect("channel chat id")
2703            .to_owned()
2704    }
2705
2706    /// Create a Message with broadcastMentions in a group chat (no spaceId).
2707    /// The permission check must be SKIPPED (unrestricted per spec),
2708    /// and the message must succeed.
2709    #[tokio::test]
2710    async fn broadcast_mention_create_without_space_unrestricted() {
2711        let backend = MemoryBackend::<()>::default();
2712        let chat_id = make_group_chat(&backend).await;
2713
2714        let body = "Hello @everyone!";
2715        let HandlerOutput { primary: resp, .. } = handle_message_set(
2716            &backend,
2717            &(),
2718            &std::collections::BTreeMap::new(),
2719            json!({
2720                "accountId": ACCOUNT_ID,
2721                "create": {
2722                    "m0": {
2723                        "chatId": chat_id,
2724                        "body": body,
2725                        "sentAt": "2024-01-01T00:00:00Z",
2726                        "broadcastMentions": [
2727                            { "scope": "everyone", "offset": 6, "length": 9 }
2728                        ]
2729                    }
2730                }
2731            }),
2732            &[],
2733        )
2734        .await
2735        .expect("handle_message_set");
2736
2737        assert!(
2738            resp["created"]["m0"].is_object(),
2739            "expected created in group chat (no spaceId), got notCreated: {}",
2740            resp["notCreated"]["m0"]
2741        );
2742    }
2743
2744    /// Create a Message with broadcastMentions in a channel chat (has spaceId).
2745    /// The owner holds mention_broadcast in the Space, so the message
2746    /// must succeed.
2747    #[tokio::test]
2748    async fn broadcast_mention_create_in_channel_succeeds() {
2749        let backend = MemoryBackend::<()>::default();
2750        let chat_id = make_channel_chat(&backend).await;
2751
2752        let body = "Hello @everyone!";
2753        let HandlerOutput { primary: resp, .. } = handle_message_set(
2754            &backend,
2755            &(),
2756            &std::collections::BTreeMap::new(),
2757            json!({
2758                "accountId": ACCOUNT_ID,
2759                "create": {
2760                    "m0": {
2761                        "chatId": chat_id,
2762                        "body": body,
2763                        "sentAt": "2024-01-01T00:00:00Z",
2764                        "broadcastMentions": [
2765                            { "scope": "everyone", "offset": 6, "length": 9 }
2766                        ]
2767                    }
2768                }
2769            }),
2770            &[],
2771        )
2772        .await
2773        .expect("handle_message_set");
2774
2775        assert!(
2776            resp["created"]["m0"].is_object(),
2777            "expected created in channel chat, got notCreated: {}",
2778            resp["notCreated"]["m0"]
2779        );
2780    }
2781
2782    /// Create a Message with empty broadcastMentions in a channel chat.
2783    /// The permission check must NOT fire (empty array skips the gate).
2784    #[tokio::test]
2785    async fn broadcast_mention_create_empty_skips_permission_check() {
2786        let backend = MemoryBackend::<()>::default();
2787        let chat_id = make_channel_chat(&backend).await;
2788
2789        let HandlerOutput { primary: resp, .. } = handle_message_set(
2790            &backend,
2791            &(),
2792            &std::collections::BTreeMap::new(),
2793            json!({
2794                "accountId": ACCOUNT_ID,
2795                "create": {
2796                    "m0": {
2797                        "chatId": chat_id,
2798                        "body": "Hello, world!",
2799                        "sentAt": "2024-01-01T00:00:00Z",
2800                        "broadcastMentions": []
2801                    }
2802                }
2803            }),
2804            &[],
2805        )
2806        .await
2807        .expect("handle_message_set");
2808
2809        assert!(
2810            resp["created"]["m0"].is_object(),
2811            "expected created with empty broadcastMentions, got notCreated: {}",
2812            resp["notCreated"]["m0"]
2813        );
2814    }
2815
2816    /// Update a Message to retain non-empty broadcastMentions in a channel chat.
2817    /// The owner holds mention_broadcast in the Space, so the update
2818    /// must succeed.
2819    #[tokio::test]
2820    async fn broadcast_mention_update_retaining_broadcast_succeeds() {
2821        let backend = MemoryBackend::<()>::default();
2822        let chat_id = make_channel_chat(&backend).await;
2823
2824        // Create a message with broadcastMentions first.
2825        let body = "Hello @everyone!";
2826        let HandlerOutput {
2827            primary: create_resp,
2828            ..
2829        } = handle_message_set(
2830            &backend,
2831            &(),
2832            &std::collections::BTreeMap::new(),
2833            json!({
2834                "accountId": ACCOUNT_ID,
2835                "create": {
2836                    "m0": {
2837                        "chatId": chat_id,
2838                        "body": body,
2839                        "sentAt": "2024-01-01T00:00:00Z",
2840                        "broadcastMentions": [
2841                            { "scope": "everyone", "offset": 6, "length": 9 }
2842                        ]
2843                    }
2844                }
2845            }),
2846            &[],
2847        )
2848        .await
2849        .expect("create message");
2850        let msg_id = create_resp["created"]["m0"]["id"]
2851            .as_str()
2852            .expect("message id");
2853
2854        // Update the message, retaining a non-empty broadcastMentions.
2855        let new_body = "Hey @here now!";
2856        let HandlerOutput {
2857            primary: update_resp,
2858            ..
2859        } = handle_message_set(
2860            &backend,
2861            &(),
2862            &std::collections::BTreeMap::new(),
2863            json!({
2864                "accountId": ACCOUNT_ID,
2865                "update": {
2866                    (msg_id): {
2867                        "body": new_body,
2868                        "broadcastMentions": [
2869                            { "scope": "here", "offset": 4, "length": 5 }
2870                        ]
2871                    }
2872                }
2873            }),
2874            &[],
2875        )
2876        .await
2877        .expect("update message");
2878
2879        assert!(
2880            update_resp["updated"][msg_id].is_null() || update_resp["updated"][msg_id].is_object(),
2881            "expected updated, got notUpdated: {}",
2882            update_resp["notUpdated"][msg_id]
2883        );
2884        assert!(
2885            update_resp["notUpdated"].is_null()
2886                || !update_resp["notUpdated"]
2887                    .as_object()
2888                    .is_some_and(|m| m.contains_key(msg_id)),
2889            "message should not be in notUpdated"
2890        );
2891    }
2892}