jmap_scene_server/backend.rs
1//! The [`SceneBackend`] trait and supporting types for the JMAP Scene method
2//! handlers.
3//!
4//! Read-side operations (`get_objects`, `get_state`, `get_changes`,
5//! `query_objects`, `query_changes`) are defined on the
6//! [`jmap_server::JmapBackend`] supertrait. This module adds the write
7//! operations and the deployment facts the handlers consult.
8//!
9//! The crate root re-exports this module's public items and the
10//! [`jmap_server`] backend types a downstream impl needs.
11
12use jmap_server::{BackendSetError, JmapBackend, JmapObject, SetObject};
13
14use jmap_scene_types::{
15 Orientation, Position, SceneAsset, SceneAvatar, SceneCapability, SceneInteractionEvent,
16 SceneObject, SceneRegion, SceneRegionEvent,
17};
18
19/// A `SceneRegion` binding property, the reference
20/// [`SceneBackend::region_binding`] is asked about
21/// (draft-atwood-jmap-scene-00 §Creating a Region, §Updating a Region).
22#[non_exhaustive]
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub enum BindingProperty {
25 /// `chatId`, a Chat (`urn:ietf:params:jmap:chat`).
26 ChatId,
27 /// `spaceId`, a Space (`urn:ietf:params:jmap:chat`).
28 SpaceId,
29 /// `channelId`, a channel of a Space (`urn:ietf:params:jmap:chat`).
30 ChannelId,
31 /// `activeCallId`, a `VTCCall` (`urn:ietf:params:jmap:vtc`).
32 ActiveCallId,
33}
34
35impl BindingProperty {
36 /// The `SceneRegion` property name, e.g. `"activeCallId"`.
37 pub fn as_str(self) -> &'static str {
38 match self {
39 Self::ChatId => "chatId",
40 Self::SpaceId => "spaceId",
41 Self::ChannelId => "channelId",
42 Self::ActiveCallId => "activeCallId",
43 }
44 }
45}
46
47/// What [`SceneBackend::region_binding`] knows about the object a
48/// `SceneRegion` binding property references.
49///
50/// `SceneRegion/set` maps it to the `SetError` the draft requires
51/// (draft-atwood-jmap-scene-00 §Creating a Region, §Updating a Region).
52#[non_exhaustive]
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum BindingTarget {
55 /// The object exists and the caller may bind it: for `activeCallId`,
56 /// the `VTCCall` is not `"ended"` and the caller is a participant in or
57 /// moderator of it, or an administrator.
58 Usable,
59 /// The object does not exist; for `activeCallId`, also a `VTCCall` in
60 /// state `"ended"`. `SceneRegion/set` returns `invalidProperties`
61 /// naming the property.
62 Missing,
63 /// The object exists but the caller cannot access it. For `chatId`,
64 /// `spaceId` and `channelId` this is `invalidProperties` naming the
65 /// property ("if the referenced object does not exist or the caller
66 /// cannot access it"); for `activeCallId` it is `forbidden` ("and
67 /// `forbidden` if the caller lacks access").
68 Inaccessible,
69}
70
71/// What [`SceneBackend::avatar_view`] lets a caller see of one
72/// `SceneAvatar` (draft-atwood-jmap-scene-00 at jmap-chat-spec 93f2258,
73/// §Avatar Visibility): "The server hides an avatar from a caller as a
74/// whole, or withholds some of its properties".
75#[non_exhaustive]
76#[derive(Debug, Clone, PartialEq, Default)]
77pub enum AvatarView {
78 /// The whole avatar, as stored. The default.
79 #[default]
80 Full,
81 /// The avatar with the [`AvatarRedaction`]'s properties withheld.
82 Redacted(AvatarRedaction),
83 /// "A hidden avatar is treated as if it did not exist:
84 /// `SceneAvatar/get` reports it in `notFound`, `SceneAvatar/query` does
85 /// not return it, and a `SceneAvatar/set` update of it returns
86 /// `notFound`."
87 Hidden,
88}
89
90/// The properties of one `SceneAvatar` withheld from a caller
91/// (jmap-chat-spec 93f2258 §Avatar Visibility): "Only `position`,
92/// `orientation`, `worldState`, and `regionState` can be withheld."
93///
94/// For `position` and `orientation` the deployment supplies the value
95/// returned instead, one "that tells the caller nothing it may not know,
96/// such as the region's `spawnPosition` and `spawnOrientation`, or the
97/// values at the time the avatar was last visible to the caller". For
98/// `worldState` and `regionState` "the server leaves out the withheld
99/// top-level keys". The default withholds nothing.
100///
101/// ```
102/// use jmap_scene_server::AvatarRedaction;
103///
104/// let mut redaction = AvatarRedaction::default();
105/// redaction.position = Some([0.0, 0.0, 5.0]);
106/// redaction.region_state_keys = vec!["money".to_owned()];
107/// assert_eq!(redaction.withheld(), ["position", "regionState"]);
108/// ```
109#[non_exhaustive]
110#[derive(Debug, Clone, PartialEq, Default)]
111pub struct AvatarRedaction {
112 /// The `position` returned instead of the stored one; `None` to
113 /// return the stored one.
114 pub position: Option<Position>,
115 /// The `orientation` returned instead of the stored one; `None` to
116 /// return the stored one.
117 pub orientation: Option<Orientation>,
118 /// The top-level `worldState` keys left out.
119 pub world_state_keys: Vec<String>,
120 /// The top-level `regionState` keys left out.
121 pub region_state_keys: Vec<String>,
122}
123
124impl AvatarRedaction {
125 /// Apply this redaction to `avatar`: replace `position` and
126 /// `orientation` where set, and remove the listed `worldState` and
127 /// `regionState` keys. A `null` or absent state object is left as it
128 /// is.
129 pub fn apply(&self, avatar: &mut SceneAvatar) {
130 if let Some(p) = self.position {
131 avatar.position = p;
132 }
133 if let Some(o) = self.orientation {
134 avatar.orientation = o;
135 }
136 if let Some(ws) = &mut avatar.world_state {
137 for k in &self.world_state_keys {
138 ws.remove(k);
139 }
140 }
141 if let Some(Some(rs)) = &mut avatar.region_state {
142 for k in &self.region_state_keys {
143 rs.remove(k);
144 }
145 }
146 }
147
148 /// The `SceneAvatar` property names this redaction withholds, in the
149 /// order `position`, `orientation`, `worldState`, `regionState`.
150 pub fn withheld(&self) -> Vec<&'static str> {
151 [
152 ("position", self.position.is_some()),
153 ("orientation", self.orientation.is_some()),
154 ("worldState", !self.world_state_keys.is_empty()),
155 ("regionState", !self.region_state_keys.is_empty()),
156 ]
157 .into_iter()
158 .filter_map(|(name, on)| on.then_some(name))
159 .collect()
160 }
161}
162
163/// Storage backend for the JMAP Scene method handlers
164/// (draft-atwood-jmap-scene-00).
165///
166/// # Permission enforcement (backend canonical)
167///
168/// Per the workspace AGENTS.md "Caller identity (foundation seam)" rule the
169/// backend re-verifies every permission atomically with the mutation. The
170/// handlers apply the draft's checks (media type, blob, size quota, the
171/// owner-or-admin rule via [`Self::may_modify_asset`]) as defense in depth.
172///
173/// # Changes
174///
175/// Unlike `/get` and `/query`, [`JmapReads::get_changes`](jmap_server::JmapReads::get_changes) is not scoped to
176/// the caller. Visibility filtering "does not change the JMAP state model:
177/// each data type has one state string per account", and `/changes` reports
178/// the account's changes (draft-atwood-jmap-scene-00 §Visibility Contract).
179/// A `/changes` result may therefore name an id that `/get` then hides: "A
180/// server MAY report an object hidden from the caller in `notFound` from
181/// `/get`". Unlike draft-atwood-jmap-graph-00, Scene does not ask `/changes`
182/// to omit what the caller may not read, with one exception: a backend
183/// that hides `SceneAvatar` records or withholds their properties to protect
184/// information ([`Self::avatar_view`]) SHOULD answer `SceneAvatar/changes`
185/// from the caller's view (jmap-chat-spec 93f2258 §Avatar Visibility).
186/// `get_changes` receives the caller for that.
187///
188/// This trait is not object-safe by design (generic methods). Use
189/// `Arc<impl SceneBackend>` when sharing across tasks.
190pub trait SceneBackend: JmapBackend {
191 /// The account-level `urn:ietf:params:jmap:scene` capability object
192 /// (draft-atwood-jmap-scene-00 §Account-Level Capability Object) the
193 /// consumer advertises for `account_id` to this caller.
194 ///
195 /// Every `SceneAsset/*` handler reads `supportsSceneAsset` from it and
196 /// returns `unknownMethod` when it is `false`; `SceneAsset/set` also
197 /// reads `supportedVisualTypes` and `maxAssetSizeBytes`. Return the value the Session object
198 /// carries; a different value makes the handler contradict the
199 /// advertised capability. `supportedVisualTypes` "MUST include at least
200 /// `\"model/gltf-binary\"`"; the handler accepts that type whether or
201 /// not it is listed.
202 fn scene_capability(
203 &self,
204 caller: &Self::CallerCtx,
205 account_id: &jmap_types::Id,
206 ) -> impl std::future::Future<Output = Result<SceneCapability, Self::Error>> + Send;
207
208 /// The size in bytes of blob `blob_id`, or `None` if no such blob was
209 /// uploaded to `account_id` (RFC 8620 §6.1).
210 ///
211 /// `SceneAsset/set` create stores the size as the asset's `size` and
212 /// refuses a missing blob with `invalidProperties` naming `blobId`
213 /// ("`blobId` does not reference a valid blob"). There is no default: a default would invent sizes or
214 /// refuse every create. Return `Err` for a transient storage failure,
215 /// never `Ok(None)`: the handler maps `Err` to `serverFail` so the
216 /// client retries.
217 fn blob_size(
218 &self,
219 caller: &Self::CallerCtx,
220 account_id: &jmap_types::Id,
221 blob_id: &jmap_types::Id,
222 ) -> impl std::future::Future<Output = Result<Option<u64>, Self::Error>> + Send;
223
224 /// Create an object.
225 ///
226 /// The handler has validated the create against
227 /// draft-atwood-jmap-scene-00 §`SceneAsset/set` and filled the server-set
228 /// properties other than `id`. The backend MUST, in one atomic step,
229 /// mint a ULID `id` ("A ULID assigned at creation"), call `build(&id)`
230 /// once for the object carrying it, and store that object.
231 ///
232 /// For a `SceneAsset` the backend also enforces the deployment-defined
233 /// rules of §`SetError` Conditions atomically with the insert: refuse
234 /// with `overQuota` for "Account asset storage quota
235 /// exceeded", and with `forbidden` when the "Deployment restricts
236 /// shared-asset creation to administrators" and the caller is not one.
237 ///
238 /// For a `SceneRegion` the backend refuses with `overQuota` when the
239 /// account already holds `maxRegionsPerAccount` regions ("The server
240 /// MUST return `overQuota` when `maxRegionsPerAccount` would be
241 /// exceeded"), counted atomically with the insert.
242 ///
243 /// For a `SceneObject` the backend sets `ownerId` to the caller's
244 /// `userId` ("The `userId` of the user who created this object"; the
245 /// handler sends `null`) and refuses with `overQuota` when the object's
246 /// region already holds `maxObjectsPerRegion` objects ("The server MUST
247 /// return `overQuota` when `maxObjectsPerRegion` would be exceeded"),
248 /// counted atomically with the insert.
249 ///
250 /// For a `SceneAvatar` (§Entering a Region) the handler has filled
251 /// `userId` from [`Self::caller_user_id`], `position`, `orientation`,
252 /// `joinedAt` (now) and `leftAt` (`null`). In one atomic step the
253 /// backend:
254 ///
255 /// 1. refuses with `alreadyExists` and `existingId` naming the record
256 /// when the user already has an avatar in the region, present or
257 /// departed ("the server MUST NOT create a second record and MUST
258 /// return an `alreadyExists` `SetError` ... with `existingId` set to
259 /// the id of that record");
260 /// 2. refuses with `overQuota` when the region already holds
261 /// `maxAvatarsPerRegion` avatars with `leftAt` `null`;
262 /// 3. sets `leftAt` to the new `joinedAt` on the user's active avatar
263 /// in any other region ("the server SHOULD set `leftAt` on the
264 /// previous avatar before creating the new one");
265 /// 4. keeps each affected region's `activeAvatarCount` ("Number of
266 /// avatars currently present in the region") equal to its avatars
267 /// with `leftAt` `null`, advancing the `SceneRegion` state.
268 ///
269 /// Returns the assigned id and the stored object. `create_id` is the
270 /// client's creation id. Error mapping, state-counter and change-log
271 /// rules are those of the canonical `jmap-mail-server` `create_object`:
272 /// the state advances only when the create commits.
273 fn create_object<O, F>(
274 &self,
275 caller: &Self::CallerCtx,
276 account_id: &jmap_types::Id,
277 create_id: &str,
278 build: F,
279 ) -> impl std::future::Future<Output = Result<(jmap_types::Id, O), BackendSetError<Self::Error>>>
280 + Send
281 where
282 O: SetObject + Send + Sync,
283 F: FnOnce(&jmap_types::Id) -> O + Send;
284
285 /// Apply an RFC 8620 §5.3 `PatchObject` to an existing object.
286 ///
287 /// `Ok(Some(o))` echoes server-changed properties; `Ok(None)` means the
288 /// patch applied verbatim. Both MUST advance the state and record an
289 /// `updated` change. Unknown `id` is `notFound`; a malformed patch is
290 /// `invalidPatch`; a result that no longer decodes is
291 /// `invalidProperties`. Apply the whole patch or none of it.
292 ///
293 /// For a `SceneAvatar` whose patch sets `leftAt` to a `UTCDate`, the
294 /// backend refuses with `invalidProperties` naming `leftAt` when the
295 /// stored `leftAt` is already non-null ("double-leave is invalid"), and
296 /// otherwise decrements the region's `activeAvatarCount` in the same
297 /// atomic step ("The server decrements the region's
298 /// `activeAvatarCount`"), advancing the `SceneRegion` state.
299 ///
300 /// A patch that sets `leftAt` to `null` re-enters the region
301 /// (§Re-entering a Region); the handler has added `joinedAt` (now),
302 /// `position` and `orientation` (the region's spawn point). In the
303 /// same atomic step the backend refuses with `invalidProperties`
304 /// naming `leftAt` when the stored `leftAt` is `null`, then applies
305 /// steps 2 to 4 of [`Self::create_object`] for a `SceneAvatar`: the
306 /// `maxAvatarsPerRegion` `overQuota`, setting `leftAt` on the user's
307 /// active avatar in any other region, and the `activeAvatarCount`
308 /// update.
309 fn update_object<O: SetObject + Send + Sync>(
310 &self,
311 caller: &Self::CallerCtx,
312 account_id: &jmap_types::Id,
313 id: &jmap_types::Id,
314 patch: O::Patch,
315 ) -> impl std::future::Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send;
316
317 /// Destroy an object by id. Unknown `id` is `notFound`; the state
318 /// advances only when the destroy commits. The handler has already
319 /// applied the permission check.
320 ///
321 /// Destroying a `SceneRegion` "removes the `SceneRegion` and all
322 /// `SceneObject` and `SceneAvatar` records in it; `SceneObject/changes` and
323 /// `SceneAvatar/changes` report those records as destroyed"
324 /// (draft-atwood-jmap-scene-00 §Destroying a Region): in the same atomic
325 /// step the backend destroys every `SceneObject` and `SceneAvatar` whose
326 /// `regionId` is `id` and records each as a destroyed change of its
327 /// type. It does not end a `VTCCall` the
328 /// region's `activeCallId` references ("the server MUST NOT
329 /// automatically end the referenced `VTCCall`").
330 ///
331 /// Destroying a `SceneObject` "removes the `SceneObject` and all its
332 /// children (objects whose `parentId` references this object,
333 /// recursively)": in the same atomic step the backend destroys every
334 /// descendant and records each as a destroyed `SceneObject` change.
335 fn destroy_object<O: SetObject + Send + Sync>(
336 &self,
337 caller: &Self::CallerCtx,
338 account_id: &jmap_types::Id,
339 id: &jmap_types::Id,
340 ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
341
342 /// `true` if the caller may update or destroy `asset`: "Only the asset
343 /// owner or an admin may modify asset metadata"
344 /// (draft-atwood-jmap-scene-00 §`SceneAsset/set` Update Errors; Destroy
345 /// Errors use the "Same permission model as update").
346 ///
347 /// `SceneAsset/set` returns `forbidden` for an update or destroy when
348 /// this is `false`.
349 ///
350 /// # Default implementation
351 ///
352 /// Returns `Ok(true)`: every caller may modify every asset. This is the
353 /// workspace's fail-open posture for permission hooks (bd:JMAP-bghk);
354 /// production backends override it.
355 fn may_modify_asset(
356 &self,
357 caller: &Self::CallerCtx,
358 account_id: &jmap_types::Id,
359 asset: &SceneAsset,
360 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
361 let _ = (caller, account_id, asset);
362 async { Ok(true) }
363 }
364
365 /// `true` if the consumer advertises the capability `uri` for
366 /// `account_id`.
367 ///
368 /// The `SceneRegion` binding properties "are present only when the
369 /// corresponding companion capability is advertised on the same
370 /// account": `chatId`, `spaceId` and `channelId` need
371 /// `urn:ietf:params:jmap:chat`, `activeCallId` needs
372 /// `urn:ietf:params:jmap:vtc`. `SceneRegion/set` refuses a non-null
373 /// binding without its capability, and `accessPolicy` `"space"`
374 /// without `urn:ietf:params:jmap:chat`, with `invalidProperties`; a
375 /// create stores `null` for the bindings whose capability is
376 /// advertised.
377 fn has_capability(
378 &self,
379 caller: &Self::CallerCtx,
380 account_id: &jmap_types::Id,
381 uri: &str,
382 ) -> bool;
383
384 /// What the binding `property` set to `id` references, for the checks of
385 /// draft-atwood-jmap-scene-00 §Creating a Region ("the server MUST
386 /// verify that the referenced object exists and the caller has access
387 /// to it") and §Updating a Region (for `activeCallId`: "(a) the
388 /// referenced `VTCCall` exists, (b) its state is not `\"ended\"`, and (c)
389 /// the caller is a participant in or moderator of the referenced call,
390 /// or has deployment-defined administrative privileges").
391 ///
392 /// `SceneRegion/set` calls this for each non-null binding a create
393 /// sets or an update patches, after the capability check. The Chat and
394 /// VTC lookups live in the binding crates; this crate depends on
395 /// RFC 8620 only.
396 ///
397 /// # Default implementation
398 ///
399 /// Returns `Ok(BindingTarget::Usable)`: every reference is accepted.
400 /// This is the workspace's fail-open posture for permission hooks
401 /// (bd:JMAP-bghk); a backend that advertises Chat or VTC overrides it.
402 fn region_binding(
403 &self,
404 caller: &Self::CallerCtx,
405 account_id: &jmap_types::Id,
406 property: BindingProperty,
407 id: &jmap_types::Id,
408 ) -> impl std::future::Future<Output = Result<BindingTarget, Self::Error>> + Send {
409 let _ = (caller, account_id, property, id);
410 async { Ok(BindingTarget::Usable) }
411 }
412
413 /// `true` if `channel_id` "is a channel of the Space named by
414 /// `spaceId`" (draft-atwood-jmap-scene-00 §Updating a Region, the
415 /// binding checks).
416 ///
417 /// `SceneRegion/set` calls this when a create or an update sets
418 /// `channelId` or `spaceId` and the region as it would be after the
419 /// write has both non-null, after [`Self::region_binding`] accepted
420 /// each. `false` fails the write with `invalidProperties` naming
421 /// `channelId`.
422 ///
423 /// # Default implementation
424 ///
425 /// Returns `Ok(true)` (fail-open, bd:JMAP-bghk); a backend that
426 /// advertises Chat overrides it.
427 fn channel_in_space(
428 &self,
429 caller: &Self::CallerCtx,
430 account_id: &jmap_types::Id,
431 channel_id: &jmap_types::Id,
432 space_id: &jmap_types::Id,
433 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
434 let _ = (caller, account_id, channel_id, space_id);
435 async { Ok(true) }
436 }
437
438 /// `true` if the caller may update `region`: "Only the owner or an
439 /// admin may modify region properties" (draft-atwood-jmap-scene-00
440 /// §`SceneRegion/set` Update Errors).
441 ///
442 /// The same owner-or-admin rule gates `SceneRegion/broadcast` and
443 /// changes to `SceneAvatar.regionState` on the region's avatars
444 /// (jmap-chat-spec 93f2258), so those handlers ask this hook too.
445 ///
446 /// # Default implementation
447 ///
448 /// Returns `Ok(true)` (fail-open, bd:JMAP-bghk); production backends
449 /// override it.
450 fn may_update_region(
451 &self,
452 caller: &Self::CallerCtx,
453 account_id: &jmap_types::Id,
454 region: &SceneRegion,
455 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
456 let _ = (caller, account_id, region);
457 async { Ok(true) }
458 }
459
460 /// `true` if the caller may destroy `region`: "Only the region owner
461 /// or an admin may destroy a region" (draft-atwood-jmap-scene-00
462 /// §`SceneRegion/set` Destroy Errors).
463 ///
464 /// # Default implementation
465 ///
466 /// Returns `Ok(true)` (fail-open, bd:JMAP-bghk); production backends
467 /// override it.
468 fn may_destroy_region(
469 &self,
470 caller: &Self::CallerCtx,
471 account_id: &jmap_types::Id,
472 region: &SceneRegion,
473 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
474 let _ = (caller, account_id, region);
475 async { Ok(true) }
476 }
477
478 /// `true` if the caller may update or destroy `object`: "Only the
479 /// object's `ownerId`, the region owner, or a deployment-admin may
480 /// modify another user's object" (draft-atwood-jmap-scene-00
481 /// §`SceneObject/set` Update Errors; Destroy Errors use the "Same
482 /// permission model as update").
483 ///
484 /// `SceneObject/set` returns `forbidden` for an update or destroy when
485 /// this is `false`.
486 ///
487 /// # Default implementation
488 ///
489 /// Returns `Ok(true)` (fail-open, bd:JMAP-bghk); production backends
490 /// override it.
491 fn may_modify_object(
492 &self,
493 caller: &Self::CallerCtx,
494 account_id: &jmap_types::Id,
495 object: &SceneObject,
496 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
497 let _ = (caller, account_id, object);
498 async { Ok(true) }
499 }
500
501 /// The caller's `userId`: "The authenticated user identity string"
502 /// (draft-atwood-jmap-scene-00 §`SceneAvatar` `userId`).
503 ///
504 /// `SceneAvatar/set` stores it as a created avatar's `userId` ("The
505 /// server sets `userId` from the authenticated identity") and compares
506 /// it with an updated avatar's `userId` ("Users MUST NOT update other
507 /// users' avatars"). There is no default: the handlers cannot know the
508 /// identity.
509 fn caller_user_id(
510 &self,
511 caller: &Self::CallerCtx,
512 account_id: &jmap_types::Id,
513 ) -> impl std::future::Future<Output = Result<String, Self::Error>> + Send;
514
515 /// The `displayName` of a new avatar for `user_id` when the create
516 /// supplies none: "the server sets it from the user profile or
517 /// `ChatContact` when {{JMAP-CHAT}} is present".
518 ///
519 /// # Default implementation
520 ///
521 /// Returns `user_id`. A Chat binding crate or a backend with user
522 /// profiles overrides it.
523 fn avatar_display_name(
524 &self,
525 caller: &Self::CallerCtx,
526 account_id: &jmap_types::Id,
527 user_id: &str,
528 ) -> impl std::future::Future<Output = Result<String, Self::Error>> + Send {
529 let _ = (caller, account_id);
530 let name = user_id.to_owned();
531 async { Ok(name) }
532 }
533
534 /// The reserved display names (draft-atwood-jmap-scene-00 §Avatar
535 /// Identity and Impersonation, jmap-chat-spec 77c3474 L2776): "The
536 /// server MAY maintain a list of reserved display names that correspond
537 /// to system roles or administrative functions and MAY reject
538 /// `SceneAvatar/set` operations that attempt to use a reserved name with
539 /// a `SetError` of type `forbidden`." This crate rejects them by choice.
540 ///
541 /// `SceneAvatar/set` refuses a create or update whose client-supplied
542 /// `displayName` equals one of these names exactly with `forbidden`.
543 /// The comparison is case-sensitive, so list each spelling to reserve.
544 /// A name set by [`Self::avatar_display_name`] is not checked.
545 ///
546 /// # Default implementation
547 ///
548 /// Returns no names (fail-open, bd:JMAP-bghk); deployments supply
549 /// their list.
550 fn reserved_display_names(
551 &self,
552 caller: &Self::CallerCtx,
553 account_id: &jmap_types::Id,
554 ) -> impl std::future::Future<Output = Result<Vec<String>, Self::Error>> + Send {
555 let _ = (caller, account_id);
556 async { Ok(Vec::new()) }
557 }
558
559 /// `true` unless the caller is barred from entering `region`, which
560 /// it already has access to: "User is banned or ejected with a
561 /// cooldown period still active" (draft-atwood-jmap-scene-00
562 /// §Create Errors). `SceneAvatar/set` create and an update that
563 /// re-enters a region return `forbidden` when this is `false`, since
564 /// "The user already knows the region exists". Access under the
565 /// region's `accessPolicy` is [`Self::may_access_region`], not this
566 /// hook: a create without it is `invalidProperties` naming
567 /// `regionId`, a re-entry `notFound`.
568 ///
569 /// # Default implementation
570 ///
571 /// Returns `Ok(true)` (fail-open, bd:JMAP-bghk); production backends
572 /// override it.
573 fn may_enter_region(
574 &self,
575 caller: &Self::CallerCtx,
576 account_id: &jmap_types::Id,
577 region: &SceneRegion,
578 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
579 let _ = (caller, account_id, region);
580 async { Ok(true) }
581 }
582
583 /// `true` if the caller may eject `avatar`, another user's avatar:
584 /// "region owners and administrators may set `leftAt` on another
585 /// user's avatar to eject them" (draft-atwood-jmap-scene-00 §Update
586 /// Errors).
587 ///
588 /// `SceneAvatar/set` calls this only for a patch of another user's
589 /// avatar that sets `leftAt` and touches nothing else ("An eject
590 /// update patches only `leftAt`", §Avatar Permissions); `false` is
591 /// `forbidden`.
592 ///
593 /// # Default implementation
594 ///
595 /// Returns `Ok(true)` (fail-open, bd:JMAP-bghk); production backends
596 /// override it.
597 fn may_eject_avatar(
598 &self,
599 caller: &Self::CallerCtx,
600 account_id: &jmap_types::Id,
601 avatar: &SceneAvatar,
602 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
603 let _ = (caller, account_id, avatar);
604 async { Ok(true) }
605 }
606
607 /// `true` if the caller has access to region `region_id`
608 /// (draft-atwood-jmap-scene-00 §Region Access): "A user has access to a
609 /// region when its `accessPolicy` admits the user, when the user is the
610 /// region owner, when the user has deployment-defined administrative
611 /// privileges, or when the user has an active `SceneAvatar` in it."
612 /// `"invite"` admits "The users whose `userIds` are listed in
613 /// `invitedUserIds`", and "Servers MAY admit users to an `\"invite\"`
614 /// region by other mechanisms as well".
615 ///
616 /// `SceneRegion/get`, `SceneObject/get` and `SceneAvatar/get` report a
617 /// region, object or avatar in a region without access as `notFound`:
618 /// "The server SHOULD treat a request from a user without access to a
619 /// region as if the region did not exist: `notFound` for
620 /// `SceneRegion/get`, `SceneObject/get`, and `SceneAvatar/get` ... and
621 /// no results from the region in `/query`" (draft-atwood-jmap-scene-00
622 /// at 29e9a41, L2606).
623 /// `SceneRegion/set`, `SceneObject/set` and `SceneAvatar/set` report an
624 /// update or destroy of such a record as `notFound` too, never
625 /// `forbidden`. A region that no longer exists
626 /// may be treated either way.
627 ///
628 /// The handlers cannot filter a `/query` page they did not cut, so
629 /// `query_objects` should omit what `/get` would hide: "The server
630 /// SHOULD NOT include a `SceneObject` in a `SceneObject/get` response or
631 /// `SceneObject/query` result if the authenticated user does not have
632 /// access to the object's containing `SceneRegion`" (§Visibility
633 /// Contract, L2577). The same applies to `SceneRegion` and `SceneAvatar`
634 /// results (L2606).
635 ///
636 /// `query_changes` is not filtered per caller: visibility filtering
637 /// "does not change the JMAP state model: each data type has one state
638 /// string per account ... and `/changes` and `/queryChanges` report
639 /// changes for the account" (L2587). An id it reports that the caller
640 /// may not see, `/get` reports in `notFound`.
641 ///
642 /// # Default implementation
643 ///
644 /// Returns `Ok(true)` (fail-open, bd:JMAP-bghk); production backends
645 /// override it.
646 fn may_access_region(
647 &self,
648 caller: &Self::CallerCtx,
649 account_id: &jmap_types::Id,
650 region_id: &jmap_types::Id,
651 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
652 let _ = (caller, account_id, region_id);
653 async { Ok(true) }
654 }
655
656 /// `true` if `object` is in the caller's visibility set: "The server
657 /// SHOULD apply visibility filtering to limit the objects returned
658 /// based on the authenticated user's avatar position within the
659 /// region. The specific visibility algorithm is deployment-defined"
660 /// (draft-atwood-jmap-scene-00 §Visibility Contract).
661 ///
662 /// Consulted only for objects in a region the caller may access
663 /// ([`Self::may_access_region`]). `SceneObject/get` reports an object
664 /// outside the set as `notFound`, and `SceneObject/set` refuses an
665 /// update or destroy of it with `notFound`: "The server SHOULD NOT
666 /// return `forbidden`, as that would confirm the object still exists"
667 /// (L2589). `query_objects` should omit such objects as well;
668 /// `query_changes` reports changes for the account (L2587).
669 ///
670 /// # Default implementation
671 ///
672 /// Returns `Ok(true)`: "A simple deployment MAY return all objects in
673 /// the region."
674 fn is_object_visible(
675 &self,
676 caller: &Self::CallerCtx,
677 account_id: &jmap_types::Id,
678 object: &SceneObject,
679 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
680 let _ = (caller, account_id, object);
681 async { Ok(true) }
682 }
683
684 /// `true` if `user_id` is blocked on the caller's own contact list
685 /// (draft-atwood-jmap-scene-00 at 33702a5 §Blocked-Contact Spatial
686 /// Presence, L2672): "`SceneAvatar` records belonging to a blocked
687 /// `ChatContact` SHOULD be excluded from `SceneAvatar/get` responses and
688 /// `SceneAvatar/query` results delivered to the blocking user".
689 ///
690 /// The list is the caller's, whatever account the request names: the
691 /// server "removes any `SceneAvatar` records whose `userId` corresponds
692 /// to a `ChatContact` with `blocked: true` on the requesting user's
693 /// contact list" (L2676). A request on a shared region names the
694 /// region's hosting account, which holds the host's contacts, not the
695 /// requester's, so the hook takes no account id; an implementation
696 /// resolves the caller's own account from `caller`.
697 ///
698 /// Consulted only for avatars in a region the caller may access:
699 /// "Blocked-contact filtering is applied AFTER the visibility
700 /// filtering". `SceneAvatar/get` reports such an avatar exactly as a
701 /// missing one, in `notFound` ("The server SHOULD NOT return an error,
702 /// a filtered-result indicator, or any other signal", L2674);
703 /// `query_objects` should omit it as well, while `query_changes`
704 /// reports changes for the account (§Visibility Contract). The
705 /// handlers leave `activeAvatarCount` the true count, which deployments
706 /// "SHOULD prefer" (L2678).
707 ///
708 /// [`crate::should_deliver`] asks this at delivery time with the
709 /// recipient as the caller, since suppression consults "the
710 /// recipient's `ChatContact` records" (draft-atwood-jmap-scene-wss-00 at
711 /// 33702a5, L793-795).
712 ///
713 /// The Chat lookup (`ChatContact.blocked`) lives in the binding crate:
714 /// "Without `urn:ietf:params:jmap:chat`, there is no blocked-contact
715 /// list and this filtering does not apply."
716 ///
717 /// # Default implementation
718 ///
719 /// Returns `Ok(false)`: no one is blocked. This is the workspace's
720 /// fail-open posture for policy hooks (bd:JMAP-bghk).
721 fn is_user_blocked(
722 &self,
723 caller: &Self::CallerCtx,
724 user_id: &str,
725 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
726 let _ = (caller, user_id);
727 async { Ok(false) }
728 }
729
730 /// `true` if the caller may see the `SceneAvatar` records of region
731 /// `region_id` (draft-atwood-jmap-scene-00 at 6bcd9d8, L2654): "When a
732 /// `SceneRegion`'s `activeCallId` references a `VTCCall` with
733 /// `e2eeEnabled` set to `true`, the server SHOULD NOT expose the
734 /// region's `SceneAvatar` records to users who are not participants in
735 /// the bound `VTCCall`: for such users it SHOULD return `notFound` for
736 /// `SceneAvatar/get`, exclude the records from `SceneAvatar/query`, and
737 /// suppress `SceneAvatarEvent` ... delivery (`entered`, `left`, and
738 /// `ejected`)."
739 ///
740 /// Consulted only for avatars in a region the caller may access
741 /// ([`Self::may_access_region`]). `SceneAvatar/get` reports the avatars
742 /// of a region answering `false` in `notFound`, and
743 /// [`crate::should_deliver`] drops their `SceneAvatarEvent`s;
744 /// `query_objects` should omit them as well, while `query_changes`
745 /// reports changes for the account (§Visibility Contract).
746 ///
747 /// The VTC lookup (`VTCCall.e2eeEnabled` and the call's participants)
748 /// lives in the binding crate, `jmap-scene-vtc-server`.
749 ///
750 /// # Default implementation
751 ///
752 /// Returns `Ok(true)`: no region hides its avatars. This is the
753 /// workspace's fail-open posture for policy hooks (bd:JMAP-bghk); a
754 /// deployment without it exposes the call's participant presence, the
755 /// limitation the draft's SHOULD leaves to it.
756 fn may_see_region_avatars(
757 &self,
758 caller: &Self::CallerCtx,
759 account_id: &jmap_types::Id,
760 region_id: &jmap_types::Id,
761 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
762 let _ = (caller, account_id, region_id);
763 async { Ok(true) }
764 }
765
766 /// What the caller may see of `avatar`, another user's avatar
767 /// (draft-atwood-jmap-scene-00 at jmap-chat-spec 93f2258, §Avatar
768 /// Visibility): "A server MAY also limit which `SceneAvatar` records, and
769 /// which of their properties, each caller sees: for example, to keep
770 /// opponents' positions from players during a competitive round". The
771 /// rule is deployment-defined.
772 ///
773 /// The handlers never ask about the caller's own avatar: "A caller
774 /// always sees their own avatar in full". The hook "SHOULD NOT hide
775 /// avatars, or withhold their properties, from the region owner and
776 /// administrators", which is the implementation's to honor. It is
777 /// consulted after region access, the blocked-contact filter and
778 /// [`Self::may_see_region_avatars`], which stay separate.
779 ///
780 /// - `SceneAvatar/get` reports an [`AvatarView::Hidden`] avatar in
781 /// `notFound` and returns a [`AvatarView::Redacted`] one with its
782 /// [`AvatarRedaction`] applied; the withheld properties are
783 /// unreadable to a draft-ietf-jmap-conditional-02 precondition.
784 /// - `SceneAvatar/set` refuses an update of a hidden avatar with
785 /// `notFound`.
786 /// - [`crate::should_deliver`] drops a `SceneAvatarEvent` about a
787 /// hidden avatar: "an event about an avatar hidden from the
788 /// recipient is not delivered to that recipient".
789 /// - `query_objects` must apply the same view, since the handlers
790 /// cannot filter a page they did not cut: leave hidden avatars out
791 /// and evaluate filters and sorts "against the values returned to
792 /// the caller, so a spatial query cannot locate an avatar whose
793 /// position is withheld".
794 /// - `get_changes` (and `query_changes`) of a backend that hides
795 /// avatars "to protect information, rather than only for blocked
796 /// contacts or end-to-end encrypted calls, SHOULD answer `/changes`
797 /// and `/queryChanges` from the caller's view": an avatar that
798 /// becomes visible is `created`, one that becomes hidden is
799 /// `destroyed`, and one is `updated` "only when a value returned to
800 /// the caller changes". The state string stays one per account and
801 /// advances "Whenever the caller's view changes", so push notifies the
802 /// caller. The handlers pass the caller to `get_changes`; the
803 /// per-caller log is the backend's.
804 ///
805 /// `activeAvatarCount` still counts hidden avatars.
806 ///
807 /// # Default implementation
808 ///
809 /// Returns `Ok(AvatarView::Full)`: every avatar is visible in full,
810 /// today's behavior (fail-open, bd:JMAP-bghk).
811 fn avatar_view(
812 &self,
813 caller: &Self::CallerCtx,
814 account_id: &jmap_types::Id,
815 avatar: &SceneAvatar,
816 ) -> impl std::future::Future<Output = Result<AvatarView, Self::Error>> + Send {
817 let _ = (caller, account_id, avatar);
818 async { Ok(AvatarView::Full) }
819 }
820
821 /// `true` if the server advertises `supportsObserve` in its
822 /// `urn:ietf:params:jmap:scene:websocket` Session capability
823 /// ([`SceneWebSocketCapability`](jmap_scene_types::SceneWebSocketCapability);
824 /// draft-atwood-jmap-scene-wss-00 at jmap-chat-spec 93f2258).
825 ///
826 /// When `true`, `SceneRegion/set` gives a created region
827 /// `allowObservers` (default `true`) and `observerCount` (`0`) and
828 /// accepts updates of `allowObservers`, and the `websocket` handler
829 /// recognizes `observe` in `SceneStreamEnable`. When `false` the two
830 /// region properties are refused with `invalidProperties` and
831 /// `observe` is ignored: "Recognized only when the server advertises
832 /// `supportsObserve`". A backend that returns `true` must also
833 /// implement [`Self::set_observing`], so `observerCount` is right.
834 ///
835 /// # Default implementation
836 ///
837 /// Returns `false`: no observer subscriptions, today's behavior.
838 fn supports_observe(&self, caller: &Self::CallerCtx) -> bool {
839 let _ = caller;
840 false
841 }
842
843 /// `true` unless the server declines observers of `region` for
844 /// deployment-defined policy: "A server MAY also decline observers of
845 /// a region for deployment-defined policy reasons even when
846 /// `allowObservers` is `true`" (jmap-chat-spec 93f2258
847 /// §`SceneStreamEnable`).
848 ///
849 /// Asked for a region the caller has access to, when a
850 /// `SceneStreamEnable` with `observe: true` lists it (`false` makes it
851 /// one of the refused `regionIds` of the `forbidden` `RequestError`)
852 /// and again at delivery time by [`crate::should_deliver`] for an
853 /// observer without an active avatar there.
854 ///
855 /// # Default implementation
856 ///
857 /// Returns `Ok(true)` (fail-open, bd:JMAP-bghk).
858 fn may_observe_region(
859 &self,
860 caller: &Self::CallerCtx,
861 account_id: &jmap_types::Id,
862 region: &SceneRegion,
863 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
864 let _ = (caller, account_id, region);
865 async { Ok(true) }
866 }
867
868 /// The accounts whose regions a `SceneStreamEnable` with
869 /// `observe: true` may name, for a connection whose own account is
870 /// `own_account_id`: "An id listed in `regionIds` matches in every
871 /// account the user can access" (draft-atwood-jmap-scene-wss-00
872 /// §`SceneStreamEnable`).
873 ///
874 /// The `websocket` handler looks each listed region up in each of
875 /// these accounts to decide which regions are refused, and reports
876 /// each listed region of each of them to [`Self::set_observing`].
877 /// Access to each region is still checked with
878 /// [`Self::may_access_region`]. These are the accounts "the server
879 /// chooses" for the enable-time checks; "delivery is not limited to
880 /// those accounts" (draft-atwood-jmap-scene-wss-00 at jmap-chat-spec
881 /// 42aed85), and the handler reports a listed region of another
882 /// account from the first event for it that reaches the connection.
883 ///
884 /// # Default implementation
885 ///
886 /// Returns `own_account_id` alone. A deployment with shared regions
887 /// overrides it with the accounts the caller can access.
888 fn observer_accounts(
889 &self,
890 caller: &Self::CallerCtx,
891 own_account_id: &jmap_types::Id,
892 ) -> impl std::future::Future<Output = Result<Vec<jmap_types::Id>, Self::Error>> + Send {
893 let _ = caller;
894 let own = vec![own_account_id.clone()];
895 async { Ok(own) }
896 }
897
898 /// Record that one connection of the caller started (`observing`
899 /// `true`) or stopped (`false`) observing region `region_id` of
900 /// `account_id` (jmap-chat-spec 93f2258, `observerCount`).
901 ///
902 /// The `websocket` handler calls it with `true` for each region a
903 /// connection's observer subscription covers, and with `false` when
904 /// the subscription stops covering it: a new `SceneStreamEnable`,
905 /// `SceneStreamDisable` or the connection closing. A region is
906 /// covered when `SceneStreamEnable` with `observe: true` lists it, in
907 /// each of [`Self::observer_accounts`], and in any other account from
908 /// the first event for it that reaches the connection, since
909 /// "delivery is not limited to those accounts". The handler reports a
910 /// covered region whether or not the caller has access to it, it
911 /// admits observers, or the caller has an avatar there at the time,
912 /// because delivery checks all three again for each event. Calls are
913 /// balanced per connection, so a caller with several observing
914 /// connections calls `true` several times.
915 ///
916 /// The backend keeps `observerCount`, counting only the reported
917 /// users that delivery reaches: "While an observer subscription
918 /// delivers events for a region to a user without an active avatar
919 /// there, the user counts toward the region's `observerCount`", and
920 /// "A user with several observing connections counts once" (jmap-chat-spec
921 /// 42aed85). That is a reported user with access to the region
922 /// ([`Self::may_access_region`]) and no active avatar in it, while its
923 /// `allowObservers` is not `false` and [`Self::may_observe_region`]
924 /// admits observers. Recount it, atomically with the change, here and
925 /// whenever any of those inputs changes: one of those users enters or
926 /// leaves the region with an avatar, gains or loses access (including
927 /// through a change outside the region, such as a Space membership),
928 /// `allowObservers` changes, or the observer policy changes. "Like
929 /// `activeAvatarCount`, a change to it is a change to the SceneRegion":
930 /// record the region as updated and advance the `SceneRegion` state,
931 /// so push sends a `StateChange`.
932 ///
933 /// # Default implementation
934 ///
935 /// Returns `Ok(())` and counts nothing. That is correct only while
936 /// [`Self::supports_observe`] is `false`, when no observer exists.
937 fn set_observing(
938 &self,
939 caller: &Self::CallerCtx,
940 account_id: &jmap_types::Id,
941 region_id: &jmap_types::Id,
942 observing: bool,
943 ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
944 let _ = (caller, account_id, region_id, observing);
945 async { Ok(()) }
946 }
947
948 /// Accept an interaction that passed the `SceneObject/interact`
949 /// checks, or refuse it for its rate (draft-atwood-jmap-scene-00
950 /// §`SceneObject/interact`).
951 ///
952 /// `event` carries the interaction and the caller's `userId` from
953 /// [`Self::caller_user_id`]. `Ok(false)` means "The caller has exceeded
954 /// a deployment-defined interaction rate" and the handler reports
955 /// `rateLimit`; draft-atwood-jmap-scene-wss-00 §Rate Limiting suggests
956 /// "no more than five events per user per region per second".
957 /// `Ok(true)` accepts it: count it against the rate and, when the
958 /// WebSocket capability is supported, hand `event` to the transport,
959 /// which "delivers a `SceneInteractionEvent` carrying the interaction
960 /// and the caller's `userId` to the WebSocket subscribers of the region",
961 /// filtered per recipient by [`crate::should_deliver`]. Counting and
962 /// delivering in this one call keeps them atomic.
963 ///
964 /// # Default implementation
965 ///
966 /// Returns `Ok(true)` and delivers nothing: no rate limit (fail-open,
967 /// bd:JMAP-bghk) and no WebSocket transport.
968 fn accept_interaction(
969 &self,
970 caller: &Self::CallerCtx,
971 account_id: &jmap_types::Id,
972 event: &SceneInteractionEvent,
973 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
974 let _ = (caller, account_id, event);
975 async { Ok(true) }
976 }
977
978 /// Accept a region event that passed the `SceneRegion/broadcast`
979 /// checks, or refuse it for its rate (draft-atwood-jmap-scene-00 at
980 /// jmap-chat-spec 93f2258, §`SceneRegion/broadcast`).
981 ///
982 /// The handler calls this only when the account's
983 /// [`SceneCapability::supports_region_broadcast`] is `true`, the caller
984 /// has access to the region ([`Self::may_access_region`]) and is its
985 /// owner or an administrator ([`Self::may_update_region`]: "Only the
986 /// region owner and users with deployment-defined administrative
987 /// privileges may broadcast to a region"). `Ok(false)` means "The
988 /// caller has exceeded a deployment-defined rate for region events" and
989 /// the handler reports `rateLimit`. `Ok(true)` accepts it: count it
990 /// against the rate and, when the WebSocket capability is supported,
991 /// hand `event` to the transport, which "delivers a `SceneRegionEvent`
992 /// to the WebSocket subscribers of the region", filtered per recipient
993 /// by [`crate::should_deliver`] (with the `websocket` feature,
994 /// `websocket::SceneEventHub::publish`).
995 ///
996 /// Server-originated region events ("The server itself MAY also
997 /// originate region events") do not pass through here; the deployment
998 /// publishes them to the transport directly.
999 ///
1000 /// # Default implementation
1001 ///
1002 /// Returns `Ok(true)` and delivers nothing: no rate limit (fail-open,
1003 /// bd:JMAP-bghk) and no WebSocket transport.
1004 fn accept_region_event(
1005 &self,
1006 caller: &Self::CallerCtx,
1007 account_id: &jmap_types::Id,
1008 event: &SceneRegionEvent,
1009 ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
1010 let _ = (caller, account_id, event);
1011 async { Ok(true) }
1012 }
1013
1014 /// Per-backend capability probe: `true` if this backend supports the
1015 /// JMAP object type `O` for `account_id`. Not called by the handlers;
1016 /// consumers use it when assembling their Session capabilities
1017 /// ("Deployments ... MAY omit support for `SceneAsset` methods").
1018 fn supports_type<O: JmapObject>(
1019 &self,
1020 caller: &Self::CallerCtx,
1021 account_id: &jmap_types::Id,
1022 ) -> bool;
1023}