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