Skip to main content

jmap_scene_server/
ephemeral.rs

1//! Ephemeral Scene event subscription state (draft-atwood-jmap-scene-wss-00
2//! §`SceneStreamEnable`).
3//!
4//! A WebSocket transport keeps one [`SceneEphemeralSubscription`] per
5//! connection, starting from [`SceneEphemeralSubscription::default`]
6//! (inactive). Each `SceneStreamEnable` frame goes through
7//! [`SceneEphemeralSubscription::replace_with`], which validates the frame,
8//! normalizes it, and replaces the whole subscription. A
9//! `SceneStreamDisable` frame resets it to the default, which "MUST
10//! silently succeed if no ephemeral Scene subscription is currently
11//! active" (§`SceneStreamDisable`).
12//!
13//! # Active avatars are checked at delivery
14//!
15//! `regionIds` is kept as sent. An entry naming a region in which the user
16//! has no active avatar "produces no events but is retained in the
17//! subscription record" (§`SceneStreamEnable`, Semantics), so whether a
18//! region produces events is decided per event at delivery time, not here.
19//! That lets events "begin (or resume) without a new `SceneStreamEnable`"
20//! when the user enters or re-enters a listed region.
21//!
22//! An observer subscription (`observe: true`, through
23//! [`SceneEphemeralSubscription::replace_with_observe`] on a server that
24//! advertises `supportsObserve`; jmap-chat-spec 93f2258) needs no avatar:
25//! its listed regions deliver events "while the user has access to the
26//! region", checked at delivery time as well, together with the region's
27//! `allowObservers`.
28//!
29//! # Delivery and relay
30//!
31//! Before sending an event to a connection, the transport asks
32//! [`should_deliver`] whether that connection may receive it. A
33//! `SceneInteractionEvent` frame a client sends goes through
34//! [`validate_interaction`] first; the transport silently discards it on
35//! `None` and otherwise relays the returned event, whose `userId` is the
36//! sender's, to every connection for which [`should_deliver`] holds
37//! (§Client-to-Server Submission).
38
39use jmap_scene_types::{
40    ObjectEventKind, SCENE_EVENT_TYPES, SceneAvatar, SceneEvent, SceneInteractionEvent,
41    SceneObject, SceneRegion, SceneStreamEnable,
42};
43use jmap_types::{Id, JmapError};
44
45use crate::helpers::{avatar_view, is_visible};
46use crate::region::JMAP_CHAT_URI;
47use crate::{AvatarView, SceneBackend};
48
49/// Which regions a subscription covers.
50#[non_exhaustive]
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub enum RegionScope {
53    /// The frame sent `null` or left `regionIds` out. The subscription is
54    /// dynamic: every region in which the user has an active avatar,
55    /// adjusting as the user enters and leaves regions (§Subscription
56    /// Scope).
57    All,
58    /// The frame sent an explicit list, in the order sent. The
59    /// subscription is static: only these regions, and of them only those
60    /// with an active avatar of the user at delivery time. An empty list
61    /// covers no region.
62    Only(Vec<Id>),
63}
64
65impl RegionScope {
66    /// Whether `region_id` is in scope. Always `true` for
67    /// [`RegionScope::All`]; the active-avatar check is separate.
68    pub fn covers(&self, region_id: &Id) -> bool {
69        match self {
70            RegionScope::All => true,
71            RegionScope::Only(ids) => ids.contains(region_id),
72        }
73    }
74}
75
76/// The active filters of an enabled subscription.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct SceneStreamFilter {
79    region_ids: RegionScope,
80    event_types: Option<Vec<&'static str>>,
81    observe: bool,
82}
83
84impl SceneStreamFilter {
85    /// The regions covered.
86    pub fn region_ids(&self) -> &RegionScope {
87        &self.region_ids
88    }
89
90    /// Whether this is an observer subscription (jmap-chat-spec 93f2258):
91    /// its listed regions deliver events while the user has access to
92    /// them, with or without an active avatar. Set only through
93    /// [`SceneEphemeralSubscription::replace_with_observe`]; always with a
94    /// [`RegionScope::Only`] scope.
95    pub fn observes(&self) -> bool {
96        self.observe
97    }
98
99    /// Whether `event_type` (an `@type` such as `"SceneAvatarEvent"`) was
100    /// requested. Always `true` when the frame's `eventTypes` was `null`.
101    pub fn includes(&self, event_type: &str) -> bool {
102        self.event_types
103            .as_ref()
104            .is_none_or(|types| types.contains(&event_type))
105    }
106}
107
108/// The ephemeral Scene subscription of one WebSocket connection.
109///
110/// The default value is inactive, which is the state before the first
111/// `SceneStreamEnable` and after a `SceneStreamDisable`.
112#[derive(Debug, Clone, PartialEq, Eq, Default)]
113pub struct SceneEphemeralSubscription {
114    active: Option<SceneStreamFilter>,
115}
116
117impl SceneEphemeralSubscription {
118    /// Replaces this subscription with the one in `enable`.
119    ///
120    /// The new frame "REPLACES any previous `SceneStreamEnable`
121    /// subscription in its entirety"; nothing is merged from it.
122    /// Unrecognized `eventTypes` values next to recognized ones are dropped
123    /// (draft-atwood-jmap-scene-wss-00 §`SceneStreamEnable`, Semantics).
124    ///
125    /// # Errors
126    ///
127    /// Returns an `invalidArguments` [`JmapError`] when `eventTypes` is an
128    /// empty array or holds only values outside [`SCENE_EVENT_TYPES`]. On
129    /// error `self` is unchanged, as the draft requires. The transport
130    /// sends the error as an RFC 8887 §4.3.4 `RequestError` frame whose
131    /// `type` is the full URN
132    /// `"urn:ietf:params:jmap:error:invalidArguments"` and whose
133    /// `requestId` is [`SceneStreamEnable::id`] when the client sent one;
134    /// the returned [`JmapError`] carries the short method-level name. The
135    /// connection stays open.
136    ///
137    /// This is the form for a server that does not advertise
138    /// `supportsObserve`: [`SceneStreamEnable::observe`] "is recognized
139    /// only when the server advertises `supportsObserve`", so it is
140    /// ignored here. A server that advertises it uses
141    /// [`Self::replace_with_observe`].
142    pub fn replace_with(&mut self, enable: &SceneStreamEnable) -> Result<(), JmapError> {
143        self.replace(enable, false)
144    }
145
146    /// As [`Self::replace_with`], for a server that advertises
147    /// `supportsObserve` (draft-atwood-jmap-scene-wss-00 at jmap-chat-spec
148    /// 93f2258): [`SceneStreamEnable::observe`] `true` makes the
149    /// subscription an observer subscription ([`SceneStreamFilter::observes`]).
150    ///
151    /// Whether a listed region may be observed (`allowObservers`, the
152    /// server's policy) is the transport's check before it commits the
153    /// subscription: "When `observe` is `true` and a listed region that the
154    /// user has access to has `allowObservers` set to `false`, or the
155    /// server declines observers of it by policy, the server MUST respond
156    /// with a `RequestError` ... `forbidden`". The `websocket` handler does
157    /// it.
158    ///
159    /// # Errors
160    ///
161    /// As [`Self::replace_with`], and an `invalidArguments` [`JmapError`]
162    /// when `observe` is `true` and `regionIds` is `null` or absent: "the
163    /// server MUST respond with a `RequestError` of type
164    /// `\"urn:ietf:params:jmap:error:invalidArguments\"` and MUST NOT
165    /// update the current ephemeral subscription state, because an
166    /// observer subscription names its regions". On error `self` is
167    /// unchanged.
168    pub fn replace_with_observe(&mut self, enable: &SceneStreamEnable) -> Result<(), JmapError> {
169        let observe = enable.observe == Some(true);
170        if observe && enable.region_ids.is_none() {
171            return Err(JmapError::invalid_arguments(
172                "an observer subscription (observe: true) needs regionIds",
173            ));
174        }
175        self.replace(enable, observe)
176    }
177
178    fn replace(&mut self, enable: &SceneStreamEnable, observe: bool) -> Result<(), JmapError> {
179        let event_types = match &enable.event_types {
180            None => None,
181            Some(requested) => {
182                let recognized: Vec<&'static str> = SCENE_EVENT_TYPES
183                    .iter()
184                    .copied()
185                    .filter(|t| requested.iter().any(|r| r.as_str() == *t))
186                    .collect();
187                if recognized.is_empty() {
188                    return Err(JmapError::invalid_arguments(
189                        "eventTypes contains no recognized values",
190                    ));
191                }
192                Some(recognized)
193            }
194        };
195        self.active = Some(SceneStreamFilter {
196            region_ids: enable
197                .region_ids
198                .clone()
199                .map_or(RegionScope::All, RegionScope::Only),
200            event_types,
201            observe,
202        });
203        Ok(())
204    }
205
206    /// The active filters, or `None` when no subscription is enabled.
207    pub fn filter(&self) -> Option<&SceneStreamFilter> {
208        self.active.as_ref()
209    }
210}
211
212/// Whether `event` may be delivered on a connection whose subscription is
213/// `subscription`.
214///
215/// `caller` is the connection's authenticated identity, the recipient.
216/// The transport calls this at delivery time, for each event and
217/// connection. The originating user is never told of a suppression
218/// (draft-atwood-jmap-scene-wss-00 §Blocked-Sender Suppression).
219///
220/// Delivery needs an active subscription whose `eventTypes` includes the
221/// event's `@type`; an unrecognized `@type` is never delivered. All
222/// four events are per-region (§Event Summary): the event's region must
223/// be in the subscription's [`RegionScope`], the recipient must have
224/// access to it ([`SceneBackend::may_access_region`]) and an active
225/// avatar (`leftAt` `null`) in it, or, for an observer subscription
226/// ([`SceneStreamFilter::observes`]), the region must still admit
227/// observers: `allowObservers` not `false` and
228/// [`SceneBackend::may_observe_region`] (jmap-chat-spec 93f2258: events
229/// go "to users with access to the region at delivery time"). Then:
230///
231/// - `SceneAvatarEvent` needs the recipient to see the region's avatars
232///   ([`SceneBackend::may_see_region_avatars`]): a region bound to an
233///   E2EE `VTCCall` suppresses them toward non-participants
234///   (draft-atwood-jmap-scene-00 at 6bcd9d8, L2654), through
235///   `SceneStreamEnable` and `ChatStreamEnable` alike
236///   (draft-atwood-jmap-scene-wss-00 at 6bcd9d8, L1233-1234). It is also
237///   dropped when [`SceneBackend::avatar_view`] hides the named avatar
238///   from the recipient (jmap-chat-spec 93f2258 §Visibility Filtering).
239/// - `SceneObjectEvent` and `SceneInteractionEvent` need the named object
240///   to pass the `SceneObject/get` visibility contract for the recipient
241///   ([`SceneBackend::is_object_visible`]; §Visibility Filtering). A
242///   `"destroyed"` event whose object the backend no longer returns has
243///   no record to check and needs region access only; any other event
244///   for an object the backend does not return is dropped.
245/// - `SceneRegionEvent` (jmap-chat-spec 93f2258) has no object and no
246///   originating user: it needs nothing beyond the region checks above.
247/// - When the recipient's account has `urn:ietf:params:jmap:chat`
248///   ([`SceneBackend::has_capability`]), the event is dropped if the
249///   recipient blocked its originating user
250///   ([`SceneBackend::is_user_blocked`]): the `userId` of a
251///   `SceneAvatarEvent` or `SceneInteractionEvent`, the `updatedBy` of a
252///   `SceneObjectEvent`. A `SceneObjectEvent` with `updatedBy` `null` is
253///   never suppressed. Without Chat no blocked-sender filtering applies.
254///
255/// `hosting_account_id` is the account the region, avatars and object are
256/// read from. It must be the event's `accountId`, "the id of the region's
257/// hosting account ... Other users reach that account as a shared
258/// account" (draft-atwood-jmap-scene-wss-00 at 33702a5, L178-181); an
259/// event whose `accountId` differs is not delivered, since "`SceneRegion`
260/// and `SceneObject` ids are unique only within an account".
261/// `recipient_account_id` is the recipient's own account: the Chat
262/// capability is checked there ("available for the receiving account",
263/// L791-792). `caller` is the recipient, so
264/// [`SceneBackend::is_user_blocked`] consults "the recipient's `ChatContact`
265/// records" (L793-795).
266///
267/// This function does not rate-limit; the §Rate Limiting SHOULD rules are
268/// the transport's or deployment's to apply.
269///
270/// # Errors
271///
272/// Returns the backend's error if reading the recipient's `userId`, its
273/// avatars, the object, region access, visibility, avatar visibility or
274/// block status fails.
275pub async fn should_deliver<B: SceneBackend>(
276    backend: &B,
277    caller: &B::CallerCtx,
278    hosting_account_id: &Id,
279    recipient_account_id: &Id,
280    subscription: &SceneEphemeralSubscription,
281    event: &SceneEvent,
282) -> Result<bool, B::Error> {
283    let Some(filter) = subscription.filter() else {
284        return Ok(false);
285    };
286    if !filter.includes(event.type_name()) {
287        return Ok(false);
288    }
289    let (event_account, region_id, object, origin) = match event {
290        SceneEvent::Avatar(e) => (&e.account_id, &e.region_id, None, Some(e.user_id.as_str())),
291        SceneEvent::Object(e) => (
292            &e.account_id,
293            &e.region_id,
294            Some((&e.object_id, e.event == ObjectEventKind::Destroyed)),
295            e.updated_by.as_deref(),
296        ),
297        SceneEvent::Interaction(e) => (
298            &e.account_id,
299            &e.region_id,
300            Some((&e.object_id, false)),
301            Some(e.user_id.as_str()),
302        ),
303        // "A `SceneRegionEvent` has no originating user and is not subject
304        // to blocked-sender suppression"; it "is not filtered by
305        // visibility".
306        SceneEvent::Region(e) => (&e.account_id, &e.region_id, None, None),
307        _ => return Ok(false),
308    };
309    if event_account != hosting_account_id
310        || !filter.region_ids().covers(region_id)
311        || !backend
312            .may_access_region(caller, hosting_account_id, region_id)
313            .await?
314    {
315        return Ok(false);
316    }
317    let me = backend.caller_user_id(caller, hosting_account_id).await?;
318    if !has_active_avatar(backend, caller, hosting_account_id, &me, region_id).await?
319        && !(filter.observes()
320            && observable(backend, caller, hosting_account_id, region_id).await?)
321    {
322        return Ok(false);
323    }
324    if matches!(event, SceneEvent::Avatar(_))
325        && !backend
326            .may_see_region_avatars(caller, hosting_account_id, region_id)
327            .await?
328    {
329        return Ok(false);
330    }
331    // "a `SceneAvatarEvent` about an avatar hidden from the recipient
332    // ({{JMAP-SCENE}}, Avatar Visibility) is not delivered to that
333    // recipient" (jmap-chat-spec 93f2258).
334    if let SceneEvent::Avatar(e) = event
335        && let Some(avatar) = backend
336            .get_objects::<SceneAvatar>(
337                caller,
338                hosting_account_id,
339                Some(std::slice::from_ref(&e.avatar_id)),
340                None,
341            )
342            .await?
343            .0
344            .into_iter()
345            .next()
346        && avatar_view(backend, caller, hosting_account_id, &avatar).await? == AvatarView::Hidden
347    {
348        return Ok(false);
349    }
350    if let Some((object_id, destroyed)) = object {
351        let visible = match fetch_object(backend, caller, hosting_account_id, object_id).await? {
352            Some(o) => {
353                o.region_id == *region_id
354                    && is_visible(backend, caller, hosting_account_id, &o).await?
355            }
356            None => destroyed,
357        };
358        if !visible {
359            return Ok(false);
360        }
361    }
362    Ok(match origin {
363        Some(user) if backend.has_capability(caller, recipient_account_id, JMAP_CHAT_URI) => {
364            !backend.is_user_blocked(caller, user).await?
365        }
366        _ => true,
367    })
368}
369
370/// The `SceneInteractionEvent` to relay for a frame a client sent, or
371/// `None` to discard it (draft-atwood-jmap-scene-wss-00 §Client-to-Server
372/// Submission).
373///
374/// `caller` is the sending connection's authenticated identity and
375/// `account_id` the account the region and object are read from. "The
376/// server sets `userId` on the relayed event to the authenticated user's
377/// `userId`; a `userId` supplied in the frame is ignored", so the returned
378/// event is `event` with `userId` replaced by the caller's. The frame is
379/// relayable when its `accountId` is `account_id`, the caller has an
380/// active avatar (`leftAt` `null`) "in the region identified by
381/// `accountId` and `regionId`", and its `objectId` is a `SceneObject` in that
382/// region with `interactable` `true`. On `None` the server "discards the
383/// frame and returns no error to the sender"; on `Some` it relays the
384/// returned event, filtered per recipient by [`should_deliver`].
385///
386/// The opaque `data` is not inspected; size limits on it are
387/// deployment-defined, as is the §Rate Limiting SHOULD of five events per
388/// user per region per second.
389///
390/// # Errors
391///
392/// Returns the backend's error if reading the caller's `userId`, its
393/// avatars or the object fails.
394pub async fn validate_interaction<B: SceneBackend>(
395    backend: &B,
396    caller: &B::CallerCtx,
397    account_id: &Id,
398    event: &SceneInteractionEvent,
399) -> Result<Option<SceneInteractionEvent>, B::Error> {
400    if event.account_id != *account_id {
401        return Ok(None);
402    }
403    let me = backend.caller_user_id(caller, account_id).await?;
404    if !has_active_avatar(backend, caller, account_id, &me, &event.region_id).await? {
405        return Ok(None);
406    }
407    let interactable = fetch_object(backend, caller, account_id, &event.object_id)
408        .await?
409        .is_some_and(|o| o.region_id == event.region_id && o.interactable);
410    Ok(interactable.then(|| {
411        let mut relayed = event.clone();
412        relayed.user_id = me;
413        relayed
414    }))
415}
416
417/// `true` if region `region_id` admits observers at delivery time: it
418/// exists, its `allowObservers` is not `false` (an absent value is the
419/// draft default `true`) and [`SceneBackend::may_observe_region`] does not
420/// decline. Region access has been checked by the caller.
421async fn observable<B: SceneBackend>(
422    backend: &B,
423    caller: &B::CallerCtx,
424    account_id: &Id,
425    region_id: &Id,
426) -> Result<bool, B::Error> {
427    let Some(region) = fetch_region(backend, caller, account_id, region_id).await? else {
428        return Ok(false);
429    };
430    Ok(region.allow_observers != Some(false)
431        && backend
432            .may_observe_region(caller, account_id, &region)
433            .await?)
434}
435
436/// The regions of `region_ids` an observer subscription is refused, looked
437/// up in each of `account_ids` (jmap-chat-spec 42aed85 §`SceneStreamEnable`:
438/// "the server makes the checks below in the accounts it chooses").
439///
440/// A region that does not exist in an account or that the caller has no
441/// access to there is not refused: "A listed region that the user has no
442/// access to, or that does not exist, is not refused: the entry is
443/// retained and produces no events, so the response does not reveal
444/// whether the region exists." An accessible region whose
445/// `allowObservers` is `false`, or that [`SceneBackend::may_observe_region`]
446/// declines, is refused. The refused ids are in request order, without
447/// duplicates.
448#[cfg(feature = "websocket")]
449pub(crate) async fn observer_regions<B: SceneBackend>(
450    backend: &B,
451    caller: &B::CallerCtx,
452    account_ids: &[Id],
453    region_ids: &[Id],
454) -> Result<Vec<Id>, B::Error> {
455    let mut refused: Vec<Id> = Vec::new();
456    for region_id in region_ids {
457        for account_id in account_ids {
458            let Some(region) = fetch_region(backend, caller, account_id, region_id).await? else {
459                continue;
460            };
461            if !backend
462                .may_access_region(caller, account_id, region_id)
463                .await?
464            {
465                continue;
466            }
467            let admits = region.allow_observers != Some(false)
468                && backend
469                    .may_observe_region(caller, account_id, &region)
470                    .await?;
471            if !admits && !refused.contains(region_id) {
472                refused.push(region_id.clone());
473            }
474        }
475    }
476    Ok(refused)
477}
478
479async fn fetch_region<B: SceneBackend>(
480    backend: &B,
481    caller: &B::CallerCtx,
482    account_id: &Id,
483    region_id: &Id,
484) -> Result<Option<SceneRegion>, B::Error> {
485    let (regions, _) = backend
486        .get_objects::<SceneRegion>(
487            caller,
488            account_id,
489            Some(std::slice::from_ref(region_id)),
490            None,
491        )
492        .await?;
493    Ok(regions.into_iter().next())
494}
495
496/// `true` if `user_id` has an avatar in `region_id` with `leftAt` `null`.
497///
498/// ponytail: reads every `SceneAvatar` in the account; O(avatars) per
499/// check. Upgrade: a backend hook for the user's active avatar once a
500/// deployment needs it.
501pub(crate) async fn has_active_avatar<B: SceneBackend>(
502    backend: &B,
503    caller: &B::CallerCtx,
504    account_id: &Id,
505    user_id: &str,
506    region_id: &Id,
507) -> Result<bool, B::Error> {
508    let (avatars, _) = backend
509        .get_objects::<SceneAvatar>(caller, account_id, None, None)
510        .await?;
511    Ok(avatars
512        .iter()
513        .any(|a| a.region_id == *region_id && a.user_id == user_id && a.left_at.is_none()))
514}
515
516async fn fetch_object<B: SceneBackend>(
517    backend: &B,
518    caller: &B::CallerCtx,
519    account_id: &Id,
520    object_id: &Id,
521) -> Result<Option<SceneObject>, B::Error> {
522    let (objects, _) = backend
523        .get_objects::<SceneObject>(
524            caller,
525            account_id,
526            Some(std::slice::from_ref(object_id)),
527            None,
528        )
529        .await?;
530    Ok(objects.into_iter().next())
531}