Skip to main content

jmap_chat_server/
push.rs

1//! `chatPush` support for RFC 8620 push subscriptions
2//! (draft-atwood-jmap-chat-push-00).
3//!
4//! The `chatPush` property lives in [`PushSubscription::extra`] as a map of
5//! accountId to `ChatPushConfig`. A backend calls [`validate_chat_push`] on
6//! every create and update, [`strip_unsupported_chat_push`] on every
7//! subscription it returns from `list_push_subscriptions`, builds
8//! notifications with [`chat_state_change_for`], and builds the
9//! `ChatMessagePush` for each new inbound message with
10//! [`build_chat_message_push`] after [`should_push`] allows it.
11
12use std::collections::{BTreeMap, HashMap};
13use std::time::{SystemTime, UNIX_EPOCH};
14
15use jmap_chat_types::{
16    BodyType, Chat, ChatContact, ChatKind, ChatMessageEntry, ChatMessagePush, ChatPushCapability,
17    ChatPushConfig, Message, Space, SpaceMember, UrgencyLevel,
18};
19use jmap_server::state_change_for;
20use jmap_types::{Id, PushSubscription, State, StateChange, UTCDate};
21use serde_json::{Map, Value};
22
23use crate::{ChatBackend, SetError, SetErrorType};
24
25/// The `PushSubscription` property this extension adds.
26const CHAT_PUSH: &str = "chatPush";
27
28/// The `ChatMessageEntry` fields a server MUST support in `properties`
29/// (draft-atwood-jmap-chat-push-00 §ChatPushConfig). `unreadCount` is not
30/// in that list and is not built, so it is rejected like any unknown name.
31const ENTRY_PROPERTIES: [&str; 13] = [
32    "messageId",
33    "chatId",
34    "chatKind",
35    "chatName",
36    "spaceId",
37    "spaceName",
38    "senderId",
39    "senderDisplayName",
40    "sentAt",
41    "hasMention",
42    "mentionScopes",
43    "encrypted",
44    "bodySnippet",
45];
46
47/// The `ChatMessageEntry` fields sent when `properties` is absent
48/// (draft-atwood-jmap-chat-push-00 §ChatPushConfig).
49const DEFAULT_ENTRY_PROPERTIES: [&str; 10] = [
50    "messageId",
51    "chatId",
52    "chatKind",
53    "senderId",
54    "senderDisplayName",
55    "sentAt",
56    "hasMention",
57    "mentionScopes",
58    "encrypted",
59    "bodySnippet",
60];
61
62/// Check the `chatPush` property in a `PushSubscription`'s `extra` map
63/// before it is stored.
64///
65/// `caps` maps each account that advertises
66/// `urn:ietf:params:jmap:chat:push` to its account-level capability object.
67/// An absent or `null` `chatPush`, and a `null` entry for an account, are
68/// accepted. Otherwise the first offending value gets an
69/// `invalidProperties` SetError naming it:
70///
71/// - `chatPush`: the value is not an object.
72/// - `chatPush/<accountId>`: the account is not in `caps`, or the entry is
73///   not a `ChatPushConfig`. draft-atwood-jmap-chat-push-00
74///   §PushSubscription Extension: "Servers MUST NOT include `chatPush`
75///   entries for accounts whose `accountCapabilities` does not include
76///   `urn:ietf:params:jmap:chat:push`."
77/// - `chatPush/<accountId>/kinds`: a value other than `"direct"`,
78///   `"group"` or `"channel"`.
79/// - `chatPush/<accountId>/properties`: a name that is not a
80///   `ChatMessageEntry` field the server supports.
81/// - `chatPush/<accountId>/urgency` and `.../mentionUrgency`: a value not
82///   in the account's `supportedUrgencyValues`. draft-atwood-jmap-chat-push-00
83///   §ChatPushConfig: "the server MUST return an `invalidProperties`
84///   SetError on `PushSubscription/set` whose `properties` names the
85///   offending path (e.g., `chatPush/<id>/urgency`)".
86#[allow(clippy::result_large_err)]
87pub fn validate_chat_push(
88    extra: &Map<String, Value>,
89    caps: &HashMap<Id, ChatPushCapability>,
90) -> Result<(), SetError> {
91    let entries = match extra.get(CHAT_PUSH) {
92        None | Some(Value::Null) => return Ok(()),
93        Some(Value::Object(entries)) => entries,
94        Some(_) => return Err(invalid(CHAT_PUSH.to_owned())),
95    };
96    for (account, entry) in entries.iter().filter(|(_, e)| !e.is_null()) {
97        let path = format!("{CHAT_PUSH}/{account}");
98        let Some(cap) = caps.get(account.as_str()) else {
99            return Err(invalid(path));
100        };
101        let cfg: ChatPushConfig =
102            serde_json::from_value(entry.clone()).map_err(|_| invalid(path.clone()))?;
103        if cfg
104            .kinds
105            .iter()
106            .flatten()
107            .any(|k| matches!(k, ChatKind::Other(_)))
108        {
109            return Err(invalid(format!("{path}/kinds")));
110        }
111        if cfg
112            .properties
113            .iter()
114            .flatten()
115            .any(|p| !ENTRY_PROPERTIES.contains(&p.as_str()))
116        {
117            return Err(invalid(format!("{path}/properties")));
118        }
119        let unsupported = |u: &Option<UrgencyLevel>| {
120            u.as_ref()
121                .is_some_and(|u| !cap.supported_urgency_values.contains(u))
122        };
123        if unsupported(&cfg.urgency) {
124            return Err(invalid(format!("{path}/urgency")));
125        }
126        if unsupported(&cfg.mention_urgency) {
127            return Err(invalid(format!("{path}/mentionUrgency")));
128        }
129    }
130    Ok(())
131}
132
133/// Remove `chatPush` entries for accounts not in `caps` from a stored
134/// subscription's `extra` map before it is returned.
135///
136/// An entry stored while the account advertised
137/// `urn:ietf:params:jmap:chat:push` stops being returned once it no longer
138/// does. draft-atwood-jmap-chat-push-00 §PushSubscription Extension:
139/// "Servers MUST NOT include `chatPush` entries for accounts whose
140/// `accountCapabilities` does not include `urn:ietf:params:jmap:chat:push`."
141pub fn strip_unsupported_chat_push(
142    extra: &mut Map<String, Value>,
143    caps: &HashMap<Id, ChatPushCapability>,
144) {
145    if let Some(Value::Object(entries)) = extra.get_mut(CHAT_PUSH) {
146        entries.retain(|account, _| caps.contains_key(account.as_str()));
147    }
148}
149
150/// The `StateChange` to push to `sub` for the types in `changed`, or `None`
151/// when nothing is left to send.
152///
153/// Wraps [`state_change_for`] (which filters by `types`) and drops the
154/// `Message` type for every account with a live `chatPush` entry: one that
155/// is non-null and whose account is in `caps`. For those accounts the
156/// `ChatMessagePush` replaces the `Message` state change.
157/// draft-atwood-jmap-chat-push-00 §PushSubscription Extension: "When
158/// present for an account, the server delivers `ChatMessagePush` payloads
159/// to the push endpoint for new inbound messages in that account that match
160/// the configuration. When absent or null for an account, the server
161/// delivers standard `StateChange` notifications for that account without
162/// inline message content."
163///
164/// A consumer falling back to a plain `StateChange` under rate limiting
165/// (§Rate Limiting and Fallback) calls [`state_change_for`] directly.
166pub fn chat_state_change_for(
167    sub: &PushSubscription,
168    changed: &BTreeMap<Id, BTreeMap<String, State>>,
169    caps: &HashMap<Id, ChatPushCapability>,
170) -> Option<StateChange> {
171    let live = |account: &Id| {
172        caps.contains_key(account)
173            && sub
174                .extra
175                .get(CHAT_PUSH)
176                .and_then(|entries| entries.get(account.as_ref()))
177                .is_some_and(|entry| !entry.is_null())
178    };
179    let filtered: BTreeMap<Id, BTreeMap<String, State>> = changed
180        .iter()
181        .map(|(account, types)| {
182            let mut types = types.clone();
183            if live(account) {
184                types.remove("Message");
185            }
186            (account.clone(), types)
187        })
188        .collect();
189    state_change_for(sub, &filtered)
190}
191
192/// The account owner's standing in the Chat at delivery time, which
193/// decides the broadcast scopes that target them.
194///
195/// draft-atwood-jmap-chat-push-00 §ChatMessageEntry `mentionScopes`:
196/// "`"here"` is included only when the owner satisfies the
197/// deployment-defined "active" predicate at delivery time; `"admins"` is
198/// included only when the owner satisfies the deployment-defined
199/// "administrative authority" predicate at delivery time." Both predicates
200/// are deployment-defined, so the caller evaluates them.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
202pub struct OwnerFlags {
203    /// The owner satisfies the deployment's "active" predicate.
204    pub active: bool,
205    /// The owner has administrative authority in the Chat.
206    pub admin: bool,
207}
208
209/// The stored records one `ChatMessageEntry` is built from.
210#[derive(Debug, Clone, Copy)]
211pub struct PushItem<'a> {
212    /// The new inbound message.
213    pub message: &'a Message,
214    /// The Chat containing the message.
215    pub chat: &'a Chat,
216    /// The sender's `ChatContact` on the account owner's contact list.
217    pub sender: &'a ChatContact,
218    /// The sender's `SpaceMember` record in the Space containing the
219    /// Chat, when the Chat is a channel and the record exists. Ignored for
220    /// other kinds.
221    pub sender_member: Option<&'a SpaceMember>,
222    /// The Space containing the Chat, when the Chat is a channel. Its
223    /// `name` becomes `spaceName`. Ignored for other kinds.
224    pub space: Option<&'a Space>,
225}
226
227/// A built `ChatMessagePush` and the Web Push urgency to deliver it with.
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct BuiltPush {
230    /// The payload to deliver to the push endpoint.
231    pub payload: ChatMessagePush,
232    /// The Web Push urgency for this delivery.
233    pub urgency: UrgencyLevel,
234}
235
236/// Build the `ChatMessagePush` for one new inbound message under one
237/// subscription's `ChatPushConfig` for `account_id`.
238///
239/// The caller decides whether to deliver at all (draft-atwood-jmap-chat-push-00
240/// §Delivery) and passes `state`, the account's `Message` state after this
241/// message was stored. §ChatMessagePush: "The server MUST set this field to
242/// the post-delivery state".
243///
244/// The entry holds exactly the fields in `cfg.properties`, or the default
245/// set when it is absent. §ChatPushConfig: "The `properties` list is
246/// authoritative: the server returns exactly the requested fields." Each
247/// field is derived as §ChatMessageEntry says, with these exceptions:
248///
249/// - `encrypted` comes from `bodyType`: `false` for `text/plain`,
250///   `text/markdown` and `application/jmap-chat-rich`, otherwise `true`
251///   (§End-to-End Encrypted Deployments). An encrypted entry never has
252///   `hasMention`, `mentionScopes` or `bodySnippet`.
253/// - `bodySnippet` is the body with control characters removed, cut to at
254///   most `cap.maxSnippetBytes` bytes on a UTF-8 character boundary.
255///   Markdown markup is left in, which misses the §ChatMessageEntry SHOULD
256///   for a plaintext approximation. For `application/jmap-chat-rich` the
257///   snippet is omitted even when requested: there is no span type to
258///   render plaintext from.
259/// - `senderDisplayName` treats an empty `login` as absent.
260///
261/// The urgency is `cfg.mentionUrgency` when it is set and the owner is
262/// mentioned directly or by a targeting broadcast scope, otherwise
263/// `cfg.urgency`, otherwise `"normal"` (§Urgency). The mention test uses
264/// the computed mention, whether or not `properties` asks for
265/// `hasMention` or `mentionScopes`.
266pub fn build_chat_message_push(
267    account_id: &Id,
268    state: State,
269    cfg: &ChatPushConfig,
270    cap: &ChatPushCapability,
271    owner: OwnerFlags,
272    item: PushItem<'_>,
273) -> BuiltPush {
274    let msg = item.message;
275    let kind = item.chat.kind.clone();
276    let body_type = msg.body_type.as_str();
277    let plaintext = is_plaintext(body_type);
278
279    let mut mentioned = false;
280    let mut entry = if plaintext {
281        let has_mention = msg.mentions.iter().any(|m| m.id == *account_id);
282        let scopes = mention_scopes(msg, owner);
283        mentioned = has_mention || !scopes.is_empty();
284        let snippet = (body_type != BodyType::Rich.as_str())
285            .then(|| snippet(&msg.body, cap.max_snippet_bytes));
286        ChatMessageEntry::plaintext(
287            msg.id.clone(),
288            msg.chat_id.clone(),
289            kind.clone(),
290            msg.sender_id.clone(),
291            msg.sent_at.clone(),
292            has_mention,
293            scopes,
294            snippet,
295        )
296    } else {
297        ChatMessageEntry::encrypted(
298            msg.id.clone(),
299            msg.chat_id.clone(),
300            kind.clone(),
301            msg.sender_id.clone(),
302            msg.sent_at.clone(),
303        )
304    };
305    if kind != ChatKind::Direct {
306        entry.chat_name = item.chat.name.clone();
307    }
308    if kind == ChatKind::Channel {
309        entry.space_id = item.chat.space_id.clone();
310        entry.space_name = item.space.map(|s| s.name.clone());
311    }
312    entry.sender_display_name = Some(sender_display_name(&kind, &item));
313
314    let wanted = |name: &str| match &cfg.properties {
315        Some(properties) => properties.iter().any(|p| p == name),
316        None => DEFAULT_ENTRY_PROPERTIES.contains(&name),
317    };
318    entry.message_id = entry.message_id.take().filter(|_| wanted("messageId"));
319    entry.chat_id = entry.chat_id.take().filter(|_| wanted("chatId"));
320    entry.chat_kind = entry.chat_kind.take().filter(|_| wanted("chatKind"));
321    entry.chat_name = entry.chat_name.take().filter(|_| wanted("chatName"));
322    entry.space_id = entry.space_id.take().filter(|_| wanted("spaceId"));
323    entry.space_name = entry.space_name.take().filter(|_| wanted("spaceName"));
324    entry.sender_id = entry.sender_id.take().filter(|_| wanted("senderId"));
325    entry.sender_display_name = entry
326        .sender_display_name
327        .take()
328        .filter(|_| wanted("senderDisplayName"));
329    entry.sent_at = entry.sent_at.take().filter(|_| wanted("sentAt"));
330    entry.has_mention = entry.has_mention.take().filter(|_| wanted("hasMention"));
331    entry.mention_scopes = entry
332        .mention_scopes
333        .take()
334        .filter(|_| wanted("mentionScopes"));
335    entry.encrypted = entry.encrypted.take().filter(|_| wanted("encrypted"));
336    entry.body_snippet = entry.body_snippet.take().filter(|_| wanted("bodySnippet"));
337
338    let urgency = cfg
339        .mention_urgency
340        .clone()
341        .filter(|_| mentioned)
342        .or_else(|| cfg.urgency.clone())
343        .unwrap_or(UrgencyLevel::Normal);
344    // ponytail: one message per payload, which §Delivery allows ("Contains
345    // exactly one entry for a single new message") and §Batching and Retry
346    // prefers ("at most one `ChatMessagePush` per message"). The upgrade
347    // path is batching, chunked by `maxMessagesPerPush`.
348    BuiltPush {
349        payload: ChatMessagePush::new(account_id.clone(), state, vec![entry]),
350        urgency,
351    }
352}
353
354/// Whether a `ChatMessagePush` for the new inbound message `msg` goes to
355/// a subscription whose `chatPush` entry for `account_id` is `cfg`.
356///
357/// `caps` maps each account that advertises
358/// `urn:ietf:params:jmap:chat:push` to its capability object; a `cfg` for
359/// an account not in `caps` counts as absent and gets `false`
360/// (draft-atwood-jmap-chat-push-00 §PushSubscription Extension). `owner`
361/// is the owner's standing at delivery time, as for
362/// [`build_chat_message_push`].
363///
364/// Returns `true` only when the Chat matches `cfg` and none of the
365/// §Delivery exclusions applies:
366///
367/// - `cfg.kinds` and `cfg.chatIds` both match when present. §ChatPushConfig:
368///   "If both `kinds` and `chatIds` are present, a Chat matches only if its
369///   id appears in `chatIds` and its kind appears in `kinds`."
370/// - The sender is not the owner: `senderId` is not `account_id`.
371/// - The owner is still a member of the Chat. The account must hold the
372///   Chat; for a group Chat its `members` must have an entry whose id is
373///   `account_id`, and for a channel Chat its Space's `members` must.
374/// - The Chat is not muted, unless the owner is targeted by one of the message's broadcast
375///   mentions. Direct mentions never bypass a mute, and neither does an
376///   encrypted message (§End-to-End Encrypted Deployments: "never bypasses
377///   mute suppression"). When `muteUntil` is set, the Chat is muted until
378///   that time whatever `muted` says, because draft-atwood-jmap-chat-00
379///   §Chat `muteUntil` says "Muting expires at this time" and clearing
380///   `muted` afterwards is only a SHOULD. Otherwise the Chat is muted when
381///   `muted` is `true`. A `muteUntil` that is not a seconds-precision
382///   UTCDate, or a system clock before 1970, counts as an active mute.
383/// - The sender's `ChatContact` is not blocked, per
384///   [`ChatBackend::is_contact_blocked`].
385///
386/// # Messages stored before the subscription
387///
388/// §Delivery: "The server MUST NOT deliver a `ChatMessagePush` in any of
389/// the following cases: The message was stored before the
390/// `PushSubscription` was created." This function cannot see creation
391/// order. The caller MUST read the set of subscriptions under the same lock
392/// or transaction as the message write, and call this function only for
393/// subscriptions in that set, including when delivery fans out
394/// asynchronously afterwards.
395///
396/// # Errors
397///
398/// Returns the backend's error if reading the Chat, its Space or the
399/// sender's blocked status fails.
400pub async fn should_push<B: ChatBackend>(
401    backend: &B,
402    caller: &B::CallerCtx,
403    account_id: &Id,
404    cfg: &ChatPushConfig,
405    caps: &HashMap<Id, ChatPushCapability>,
406    msg: &Message,
407    owner: OwnerFlags,
408) -> Result<bool, B::Error> {
409    if !caps.contains_key(account_id) || msg.sender_id == *account_id {
410        return Ok(false);
411    }
412    if cfg
413        .chat_ids
414        .as_ref()
415        .is_some_and(|ids| !ids.contains(&msg.chat_id))
416    {
417        return Ok(false);
418    }
419    let (chats, _) = backend
420        .get_objects::<Chat>(
421            caller,
422            account_id,
423            Some(std::slice::from_ref(&msg.chat_id)),
424            None,
425        )
426        .await?;
427    let Some(chat) = chats.into_iter().next() else {
428        return Ok(false);
429    };
430    if cfg
431        .kinds
432        .as_ref()
433        .is_some_and(|kinds| !kinds.contains(&chat.kind))
434    {
435        return Ok(false);
436    }
437    let is_owner = |id: &Id| id == account_id;
438    let member = match chat.kind {
439        ChatKind::Group => chat.members.iter().flatten().any(|m| is_owner(&m.id)),
440        ChatKind::Channel => match &chat.space_id {
441            Some(space_id) => backend
442                .get_objects::<Space>(
443                    caller,
444                    account_id,
445                    Some(std::slice::from_ref(space_id)),
446                    None,
447                )
448                .await?
449                .0
450                .iter()
451                .any(|space| space.members.iter().any(|m| is_owner(&m.id))),
452            None => false,
453        },
454        _ => true,
455    };
456    if !member {
457        return Ok(false);
458    }
459    let bypass = is_plaintext(&msg.body_type) && !mention_scopes(msg, owner).is_empty();
460    let muted = match &chat.mute_until {
461        Some(until) => mute_active(until),
462        None => chat.muted,
463    };
464    if muted && !bypass {
465        return Ok(false);
466    }
467    Ok(!backend
468        .is_contact_blocked(caller, account_id, &msg.sender_id)
469        .await?)
470}
471
472/// Whether a mute ending at `until` is still in effect: `until` is later
473/// than now. draft-atwood-jmap-chat-00 §Chat `muteUntil`: "Muting expires
474/// at this time." An unparseable `until` or clock counts as in effect.
475fn mute_active(until: &UTCDate) -> bool {
476    let now = SystemTime::now()
477        .duration_since(UNIX_EPOCH)
478        .ok()
479        .and_then(|d| i64::try_from(d.as_secs()).ok());
480    match (until.to_epoch_seconds(), now) {
481        (Ok(until), Some(now)) => now < until,
482        _ => true,
483    }
484}
485
486/// Whether `body_type` is one of the plaintext body types that
487/// draft-atwood-jmap-chat-push-00 §End-to-End Encrypted Deployments says
488/// "MUST set `encrypted` to `false`"; every other type is encrypted.
489fn is_plaintext(body_type: &str) -> bool {
490    [BodyType::Plain, BodyType::Markdown, BodyType::Rich]
491        .iter()
492        .any(|t| t.as_str() == body_type)
493}
494
495/// The deduplicated `Message.broadcastMentions[]` scopes that target the
496/// owner, in first-seen order. `"everyone"` always targets a Chat member;
497/// unknown scopes never do.
498fn mention_scopes(msg: &Message, owner: OwnerFlags) -> Vec<String> {
499    let mut scopes: Vec<String> = Vec::new();
500    for scope in msg.broadcast_mentions.iter().map(|b| b.scope.as_str()) {
501        let targets_owner = match scope {
502            "everyone" => true,
503            "here" => owner.active,
504            "admins" => owner.admin,
505            _ => false,
506        };
507        if targets_owner && !scopes.iter().any(|s| s == scope) {
508            scopes.push(scope.to_owned());
509        }
510    }
511    scopes
512}
513
514/// `body` without control characters, cut to at most `max_bytes` bytes on
515/// a UTF-8 character boundary.
516fn snippet(body: &str, max_bytes: u64) -> String {
517    let mut text: String = body.chars().filter(|c| !c.is_control()).collect();
518    let mut end = usize::try_from(max_bytes).map_or(text.len(), |max| max.min(text.len()));
519    while !text.is_char_boundary(end) {
520        end -= 1;
521    }
522    text.truncate(end);
523    text
524}
525
526/// The `senderDisplayName` chain from draft-atwood-jmap-chat-push-00
527/// §ChatMessageEntry: the `SpaceMember.nick` (channels only), then
528/// `ChatContact.displayName`, then a non-empty `ChatContact.login`, then
529/// `ChatContact.identity`.
530fn sender_display_name(kind: &ChatKind, item: &PushItem<'_>) -> String {
531    let nick = item
532        .sender_member
533        .filter(|_| *kind == ChatKind::Channel)
534        .and_then(|m| m.nick.clone());
535    let login = Some(&item.sender.login).filter(|l| !l.is_empty()).cloned();
536    nick.or_else(|| item.sender.display_name.clone())
537        .or(login)
538        .unwrap_or_else(|| item.sender.identity.clone())
539}
540
541/// An `invalidProperties` SetError naming `property`.
542fn invalid(property: String) -> SetError {
543    SetError::new(SetErrorType::InvalidProperties).with_properties([property])
544}