jmap-scene-server 0.6.1

JMAP Scene method handlers (draft-atwood-jmap-scene-00 SceneAsset) — backend-agnostic, plugs into jmap-server Dispatcher
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! Ephemeral Scene event subscription state (draft-atwood-jmap-scene-wss-00
//! §`SceneStreamEnable`).
//!
//! A WebSocket transport keeps one [`SceneEphemeralSubscription`] per
//! connection, starting from [`SceneEphemeralSubscription::default`]
//! (inactive). Each `SceneStreamEnable` frame goes through
//! [`SceneEphemeralSubscription::replace_with`], which validates the frame,
//! normalizes it, and replaces the whole subscription. A
//! `SceneStreamDisable` frame resets it to the default, which "MUST
//! silently succeed if no ephemeral Scene subscription is currently
//! active" (§`SceneStreamDisable`).
//!
//! # Active avatars are checked at delivery
//!
//! `regionIds` is kept as sent. An entry naming a region in which the user
//! has no active avatar "produces no events but is retained in the
//! subscription record" (§`SceneStreamEnable`, Semantics), so whether a
//! region produces events is decided per event at delivery time, not here.
//! That lets events "begin (or resume) without a new `SceneStreamEnable`"
//! when the user enters or re-enters a listed region.
//!
//! An observer subscription (`observe: true`, through
//! [`SceneEphemeralSubscription::replace_with_observe`] on a server that
//! advertises `supportsObserve`; jmap-chat-spec 93f2258) needs no avatar:
//! its listed regions deliver events "while the user has access to the
//! region", checked at delivery time as well, together with the region's
//! `allowObservers`.
//!
//! # Delivery and relay
//!
//! Before sending an event to a connection, the transport asks
//! [`should_deliver`] whether that connection may receive it. A
//! `SceneInteractionEvent` frame a client sends goes through
//! [`validate_interaction`] first; the transport silently discards it on
//! `None` and otherwise relays the returned event, whose `userId` is the
//! sender's, to every connection for which [`should_deliver`] holds
//! (§Client-to-Server Submission).

use jmap_scene_types::{
    ObjectEventKind, SCENE_EVENT_TYPES, SceneAvatar, SceneEvent, SceneInteractionEvent,
    SceneObject, SceneRegion, SceneStreamEnable,
};
use jmap_types::{Id, JmapError};

use crate::helpers::{avatar_view, is_visible};
use crate::region::JMAP_CHAT_URI;
use crate::{AvatarView, SceneBackend};

/// Which regions a subscription covers.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RegionScope {
    /// The frame sent `null` or left `regionIds` out. The subscription is
    /// dynamic: every region in which the user has an active avatar,
    /// adjusting as the user enters and leaves regions (§Subscription
    /// Scope).
    All,
    /// The frame sent an explicit list, in the order sent. The
    /// subscription is static: only these regions, and of them only those
    /// with an active avatar of the user at delivery time. An empty list
    /// covers no region.
    Only(Vec<Id>),
}

impl RegionScope {
    /// Whether `region_id` is in scope. Always `true` for
    /// [`RegionScope::All`]; the active-avatar check is separate.
    pub fn covers(&self, region_id: &Id) -> bool {
        match self {
            RegionScope::All => true,
            RegionScope::Only(ids) => ids.contains(region_id),
        }
    }
}

/// The active filters of an enabled subscription.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SceneStreamFilter {
    region_ids: RegionScope,
    event_types: Option<Vec<&'static str>>,
    observe: bool,
}

impl SceneStreamFilter {
    /// The regions covered.
    pub fn region_ids(&self) -> &RegionScope {
        &self.region_ids
    }

    /// Whether this is an observer subscription (jmap-chat-spec 93f2258):
    /// its listed regions deliver events while the user has access to
    /// them, with or without an active avatar. Set only through
    /// [`SceneEphemeralSubscription::replace_with_observe`]; always with a
    /// [`RegionScope::Only`] scope.
    pub fn observes(&self) -> bool {
        self.observe
    }

    /// Whether `event_type` (an `@type` such as `"SceneAvatarEvent"`) was
    /// requested. Always `true` when the frame's `eventTypes` was `null`.
    pub fn includes(&self, event_type: &str) -> bool {
        self.event_types
            .as_ref()
            .is_none_or(|types| types.contains(&event_type))
    }
}

/// The ephemeral Scene subscription of one WebSocket connection.
///
/// The default value is inactive, which is the state before the first
/// `SceneStreamEnable` and after a `SceneStreamDisable`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SceneEphemeralSubscription {
    active: Option<SceneStreamFilter>,
}

impl SceneEphemeralSubscription {
    /// Replaces this subscription with the one in `enable`.
    ///
    /// The new frame "REPLACES any previous `SceneStreamEnable`
    /// subscription in its entirety"; nothing is merged from it.
    /// Unrecognized `eventTypes` values next to recognized ones are dropped
    /// (draft-atwood-jmap-scene-wss-00 §`SceneStreamEnable`, Semantics).
    ///
    /// # Errors
    ///
    /// Returns an `invalidArguments` [`JmapError`] when `eventTypes` is an
    /// empty array or holds only values outside [`SCENE_EVENT_TYPES`]. On
    /// error `self` is unchanged, as the draft requires. The transport
    /// sends the error as an RFC 8887 §4.3.4 `RequestError` frame whose
    /// `type` is the full URN
    /// `"urn:ietf:params:jmap:error:invalidArguments"` and whose
    /// `requestId` is [`SceneStreamEnable::id`] when the client sent one;
    /// the returned [`JmapError`] carries the short method-level name. The
    /// connection stays open.
    ///
    /// This is the form for a server that does not advertise
    /// `supportsObserve`: [`SceneStreamEnable::observe`] "is recognized
    /// only when the server advertises `supportsObserve`", so it is
    /// ignored here. A server that advertises it uses
    /// [`Self::replace_with_observe`].
    pub fn replace_with(&mut self, enable: &SceneStreamEnable) -> Result<(), JmapError> {
        self.replace(enable, false)
    }

    /// As [`Self::replace_with`], for a server that advertises
    /// `supportsObserve` (draft-atwood-jmap-scene-wss-00 at jmap-chat-spec
    /// 93f2258): [`SceneStreamEnable::observe`] `true` makes the
    /// subscription an observer subscription ([`SceneStreamFilter::observes`]).
    ///
    /// Whether a listed region may be observed (`allowObservers`, the
    /// server's policy) is the transport's check before it commits the
    /// subscription: "When `observe` is `true` and a listed region that the
    /// user has access to has `allowObservers` set to `false`, or the
    /// server declines observers of it by policy, the server MUST respond
    /// with a `RequestError` ... `forbidden`". The `websocket` handler does
    /// it.
    ///
    /// # Errors
    ///
    /// As [`Self::replace_with`], and an `invalidArguments` [`JmapError`]
    /// when `observe` is `true` and `regionIds` is `null` or absent: "the
    /// server MUST respond with a `RequestError` of type
    /// `\"urn:ietf:params:jmap:error:invalidArguments\"` and MUST NOT
    /// update the current ephemeral subscription state, because an
    /// observer subscription names its regions". On error `self` is
    /// unchanged.
    pub fn replace_with_observe(&mut self, enable: &SceneStreamEnable) -> Result<(), JmapError> {
        let observe = enable.observe == Some(true);
        if observe && enable.region_ids.is_none() {
            return Err(JmapError::invalid_arguments(
                "an observer subscription (observe: true) needs regionIds",
            ));
        }
        self.replace(enable, observe)
    }

    fn replace(&mut self, enable: &SceneStreamEnable, observe: bool) -> Result<(), JmapError> {
        let event_types = match &enable.event_types {
            None => None,
            Some(requested) => {
                let recognized: Vec<&'static str> = SCENE_EVENT_TYPES
                    .iter()
                    .copied()
                    .filter(|t| requested.iter().any(|r| r.as_str() == *t))
                    .collect();
                if recognized.is_empty() {
                    return Err(JmapError::invalid_arguments(
                        "eventTypes contains no recognized values",
                    ));
                }
                Some(recognized)
            }
        };
        self.active = Some(SceneStreamFilter {
            region_ids: enable
                .region_ids
                .clone()
                .map_or(RegionScope::All, RegionScope::Only),
            event_types,
            observe,
        });
        Ok(())
    }

    /// The active filters, or `None` when no subscription is enabled.
    pub fn filter(&self) -> Option<&SceneStreamFilter> {
        self.active.as_ref()
    }
}

/// Whether `event` may be delivered on a connection whose subscription is
/// `subscription`.
///
/// `caller` is the connection's authenticated identity, the recipient.
/// The transport calls this at delivery time, for each event and
/// connection. The originating user is never told of a suppression
/// (draft-atwood-jmap-scene-wss-00 §Blocked-Sender Suppression).
///
/// Delivery needs an active subscription whose `eventTypes` includes the
/// event's `@type`; an unrecognized `@type` is never delivered. All
/// four events are per-region (§Event Summary): the event's region must
/// be in the subscription's [`RegionScope`], the recipient must have
/// access to it ([`SceneBackend::may_access_region`]) and an active
/// avatar (`leftAt` `null`) in it, or, for an observer subscription
/// ([`SceneStreamFilter::observes`]), the region must still admit
/// observers: `allowObservers` not `false` and
/// [`SceneBackend::may_observe_region`] (jmap-chat-spec 93f2258: events
/// go "to users with access to the region at delivery time"). Then:
///
/// - `SceneAvatarEvent` needs the recipient to see the region's avatars
///   ([`SceneBackend::may_see_region_avatars`]): a region bound to an
///   E2EE `VTCCall` suppresses them toward non-participants
///   (draft-atwood-jmap-scene-00 at 6bcd9d8, L2654), through
///   `SceneStreamEnable` and `ChatStreamEnable` alike
///   (draft-atwood-jmap-scene-wss-00 at 6bcd9d8, L1233-1234). It is also
///   dropped when [`SceneBackend::avatar_view`] hides the named avatar
///   from the recipient (jmap-chat-spec 93f2258 §Visibility Filtering).
/// - `SceneObjectEvent` and `SceneInteractionEvent` need the named object
///   to pass the `SceneObject/get` visibility contract for the recipient
///   ([`SceneBackend::is_object_visible`]; §Visibility Filtering). A
///   `"destroyed"` event whose object the backend no longer returns has
///   no record to check and needs region access only; any other event
///   for an object the backend does not return is dropped.
/// - `SceneRegionEvent` (jmap-chat-spec 93f2258) has no object and no
///   originating user: it needs nothing beyond the region checks above.
/// - When the recipient's account has `urn:ietf:params:jmap:chat`
///   ([`SceneBackend::has_capability`]), the event is dropped if the
///   recipient blocked its originating user
///   ([`SceneBackend::is_user_blocked`]): the `userId` of a
///   `SceneAvatarEvent` or `SceneInteractionEvent`, the `updatedBy` of a
///   `SceneObjectEvent`. A `SceneObjectEvent` with `updatedBy` `null` is
///   never suppressed. Without Chat no blocked-sender filtering applies.
///
/// `hosting_account_id` is the account the region, avatars and object are
/// read from. It must be the event's `accountId`, "the id of the region's
/// hosting account ... Other users reach that account as a shared
/// account" (draft-atwood-jmap-scene-wss-00 at 33702a5, L178-181); an
/// event whose `accountId` differs is not delivered, since "`SceneRegion`
/// and `SceneObject` ids are unique only within an account".
/// `recipient_account_id` is the recipient's own account: the Chat
/// capability is checked there ("available for the receiving account",
/// L791-792). `caller` is the recipient, so
/// [`SceneBackend::is_user_blocked`] consults "the recipient's `ChatContact`
/// records" (L793-795).
///
/// This function does not rate-limit; the §Rate Limiting SHOULD rules are
/// the transport's or deployment's to apply.
///
/// # Errors
///
/// Returns the backend's error if reading the recipient's `userId`, its
/// avatars, the object, region access, visibility, avatar visibility or
/// block status fails.
pub async fn should_deliver<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    hosting_account_id: &Id,
    recipient_account_id: &Id,
    subscription: &SceneEphemeralSubscription,
    event: &SceneEvent,
) -> Result<bool, B::Error> {
    let Some(filter) = subscription.filter() else {
        return Ok(false);
    };
    if !filter.includes(event.type_name()) {
        return Ok(false);
    }
    let (event_account, region_id, object, origin) = match event {
        SceneEvent::Avatar(e) => (&e.account_id, &e.region_id, None, Some(e.user_id.as_str())),
        SceneEvent::Object(e) => (
            &e.account_id,
            &e.region_id,
            Some((&e.object_id, e.event == ObjectEventKind::Destroyed)),
            e.updated_by.as_deref(),
        ),
        SceneEvent::Interaction(e) => (
            &e.account_id,
            &e.region_id,
            Some((&e.object_id, false)),
            Some(e.user_id.as_str()),
        ),
        // "A `SceneRegionEvent` has no originating user and is not subject
        // to blocked-sender suppression"; it "is not filtered by
        // visibility".
        SceneEvent::Region(e) => (&e.account_id, &e.region_id, None, None),
        _ => return Ok(false),
    };
    if event_account != hosting_account_id
        || !filter.region_ids().covers(region_id)
        || !backend
            .may_access_region(caller, hosting_account_id, region_id)
            .await?
    {
        return Ok(false);
    }
    let me = backend.caller_user_id(caller, hosting_account_id).await?;
    if !has_active_avatar(backend, caller, hosting_account_id, &me, region_id).await?
        && !(filter.observes()
            && observable(backend, caller, hosting_account_id, region_id).await?)
    {
        return Ok(false);
    }
    if matches!(event, SceneEvent::Avatar(_))
        && !backend
            .may_see_region_avatars(caller, hosting_account_id, region_id)
            .await?
    {
        return Ok(false);
    }
    // "a `SceneAvatarEvent` about an avatar hidden from the recipient
    // ({{JMAP-SCENE}}, Avatar Visibility) is not delivered to that
    // recipient" (jmap-chat-spec 93f2258).
    if let SceneEvent::Avatar(e) = event
        && let Some(avatar) = backend
            .get_objects::<SceneAvatar>(
                caller,
                hosting_account_id,
                Some(std::slice::from_ref(&e.avatar_id)),
                None,
            )
            .await?
            .0
            .into_iter()
            .next()
        && avatar_view(backend, caller, hosting_account_id, &avatar).await? == AvatarView::Hidden
    {
        return Ok(false);
    }
    if let Some((object_id, destroyed)) = object {
        let visible = match fetch_object(backend, caller, hosting_account_id, object_id).await? {
            Some(o) => {
                o.region_id == *region_id
                    && is_visible(backend, caller, hosting_account_id, &o).await?
            }
            None => destroyed,
        };
        if !visible {
            return Ok(false);
        }
    }
    Ok(match origin {
        Some(user) if backend.has_capability(caller, recipient_account_id, JMAP_CHAT_URI) => {
            !backend.is_user_blocked(caller, user).await?
        }
        _ => true,
    })
}

/// The `SceneInteractionEvent` to relay for a frame a client sent, or
/// `None` to discard it (draft-atwood-jmap-scene-wss-00 §Client-to-Server
/// Submission).
///
/// `caller` is the sending connection's authenticated identity and
/// `account_id` the account the region and object are read from. "The
/// server sets `userId` on the relayed event to the authenticated user's
/// `userId`; a `userId` supplied in the frame is ignored", so the returned
/// event is `event` with `userId` replaced by the caller's. The frame is
/// relayable when its `accountId` is `account_id`, the caller has an
/// active avatar (`leftAt` `null`) "in the region identified by
/// `accountId` and `regionId`", and its `objectId` is a `SceneObject` in that
/// region with `interactable` `true`. On `None` the server "discards the
/// frame and returns no error to the sender"; on `Some` it relays the
/// returned event, filtered per recipient by [`should_deliver`].
///
/// The opaque `data` is not inspected; size limits on it are
/// deployment-defined, as is the §Rate Limiting SHOULD of five events per
/// user per region per second.
///
/// # Errors
///
/// Returns the backend's error if reading the caller's `userId`, its
/// avatars or the object fails.
pub async fn validate_interaction<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    event: &SceneInteractionEvent,
) -> Result<Option<SceneInteractionEvent>, B::Error> {
    if event.account_id != *account_id {
        return Ok(None);
    }
    let me = backend.caller_user_id(caller, account_id).await?;
    if !has_active_avatar(backend, caller, account_id, &me, &event.region_id).await? {
        return Ok(None);
    }
    let interactable = fetch_object(backend, caller, account_id, &event.object_id)
        .await?
        .is_some_and(|o| o.region_id == event.region_id && o.interactable);
    Ok(interactable.then(|| {
        let mut relayed = event.clone();
        relayed.user_id = me;
        relayed
    }))
}

/// `true` if region `region_id` admits observers at delivery time: it
/// exists, its `allowObservers` is not `false` (an absent value is the
/// draft default `true`) and [`SceneBackend::may_observe_region`] does not
/// decline. Region access has been checked by the caller.
async fn observable<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    region_id: &Id,
) -> Result<bool, B::Error> {
    let Some(region) = fetch_region(backend, caller, account_id, region_id).await? else {
        return Ok(false);
    };
    Ok(region.allow_observers != Some(false)
        && backend
            .may_observe_region(caller, account_id, &region)
            .await?)
}

/// The regions of `region_ids` an observer subscription is refused, looked
/// up in each of `account_ids` (jmap-chat-spec 42aed85 §`SceneStreamEnable`:
/// "the server makes the checks below in the accounts it chooses").
///
/// A region that does not exist in an account or that the caller has no
/// access to there is not refused: "A listed region that the user has no
/// access to, or that does not exist, is not refused: the entry is
/// retained and produces no events, so the response does not reveal
/// whether the region exists." An accessible region whose
/// `allowObservers` is `false`, or that [`SceneBackend::may_observe_region`]
/// declines, is refused. The refused ids are in request order, without
/// duplicates.
#[cfg(feature = "websocket")]
pub(crate) async fn observer_regions<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_ids: &[Id],
    region_ids: &[Id],
) -> Result<Vec<Id>, B::Error> {
    let mut refused: Vec<Id> = Vec::new();
    for region_id in region_ids {
        for account_id in account_ids {
            let Some(region) = fetch_region(backend, caller, account_id, region_id).await? else {
                continue;
            };
            if !backend
                .may_access_region(caller, account_id, region_id)
                .await?
            {
                continue;
            }
            let admits = region.allow_observers != Some(false)
                && backend
                    .may_observe_region(caller, account_id, &region)
                    .await?;
            if !admits && !refused.contains(region_id) {
                refused.push(region_id.clone());
            }
        }
    }
    Ok(refused)
}

async fn fetch_region<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    region_id: &Id,
) -> Result<Option<SceneRegion>, B::Error> {
    let (regions, _) = backend
        .get_objects::<SceneRegion>(
            caller,
            account_id,
            Some(std::slice::from_ref(region_id)),
            None,
        )
        .await?;
    Ok(regions.into_iter().next())
}

/// `true` if `user_id` has an avatar in `region_id` with `leftAt` `null`.
///
/// ponytail: reads every `SceneAvatar` in the account; O(avatars) per
/// check. Upgrade: a backend hook for the user's active avatar once a
/// deployment needs it.
pub(crate) async fn has_active_avatar<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    user_id: &str,
    region_id: &Id,
) -> Result<bool, B::Error> {
    let (avatars, _) = backend
        .get_objects::<SceneAvatar>(caller, account_id, None, None)
        .await?;
    Ok(avatars
        .iter()
        .any(|a| a.region_id == *region_id && a.user_id == user_id && a.left_at.is_none()))
}

async fn fetch_object<B: SceneBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    object_id: &Id,
) -> Result<Option<SceneObject>, B::Error> {
    let (objects, _) = backend
        .get_objects::<SceneObject>(
            caller,
            account_id,
            Some(std::slice::from_ref(object_id)),
            None,
        )
        .await?;
    Ok(objects.into_iter().next())
}