jmap-types 0.4.1

Shared JMAP wire types (RFC 8620) for the jmap-* crate family
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
//! RFC 8620 §7 push wire types: [`StateChange`], [`PushSubscription`],
//! [`PushKeys`], and [`PushVerification`], plus the RFC 8030 §5.3 Web Push
//! [`Urgency`].
//!
//! These are shared by servers (which build and send them) and clients
//! (which receive them over SSE, WebSocket, or a push endpoint).
//!
//! # The `@type` discriminant
//!
//! [`StateChange`] and [`PushVerification`] carry an `@type` property that
//! "MUST be the string" naming the object (RFC 8620 §7.1, §7.2.2). Their
//! (De)Serialize impls are hand-written rather than derived: serialize always
//! emits the `@type` string; deserialize consumes it, rejects any other value,
//! and never leaves it in `extra`. An absent `@type` is accepted, because a
//! receiver that dispatched on `@type` (or on an SSE event name) has already
//! established what the object is.

use std::collections::BTreeMap;
use std::fmt;

use serde::de::DeserializeOwned;
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::id::{Id, State, UTCDate};

/// The Web Push `Urgency` header (RFC 8030 §5.3), shared by every crate
/// that sends or classifies a push: `urgency-option = ("very-low" / "low"
/// / "normal" / "high")`. Variants order "in order of increasing
/// urgency", so `max` picks the most urgent. "A push message without the
/// Urgency header field defaults to a value of "normal"."
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Urgency {
    /// `very-low`
    VeryLow,
    /// `low`
    Low,
    /// `normal`, the default when the header is absent.
    Normal,
    /// `high`
    High,
}

impl Urgency {
    /// The header value.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::VeryLow => "very-low",
            Self::Low => "low",
            Self::Normal => "normal",
            Self::High => "high",
        }
    }
}

impl Serialize for Urgency {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

/// Accepts only the four `urgency-option` strings: RFC 8030 §5.3 closes
/// the set, so any other string is an error rather than an `Other` value.
impl<'de> Deserialize<'de> for Urgency {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        const VARIANTS: &[&str] = &["very-low", "low", "normal", "high"];
        let s = String::deserialize(deserializer)?;
        match s.as_str() {
            "very-low" => Ok(Self::VeryLow),
            "low" => Ok(Self::Low),
            "normal" => Ok(Self::Normal),
            "high" => Ok(Self::High),
            other => Err(serde::de::Error::unknown_variant(other, VARIANTS)),
        }
    }
}

/// `@type` value of a [`StateChange`] (RFC 8620 §7.1).
const STATE_CHANGE_TYPE: &str = "StateChange";

/// `@type` value of a [`PushVerification`] (RFC 8620 §7.2.2).
const PUSH_VERIFICATION_TYPE: &str = "PushVerification";

/// Placeholder printed by the `Debug` impls in place of secret values.
const REDACTED: &str = "[REDACTED]";

/// A state change push notification (RFC 8620 §7.1).
///
/// Sent by the server over SSE, WebSocket, or to a [`PushSubscription`] URL.
/// The wire form always carries `"@type": "StateChange"` (RFC 8620 §7.1):
/// serialize always emits it; deserialize rejects any other value, accepts
/// its absence and never leaves it in `extra`.
///
/// # `extra` equality is feature-flag-dependent (bd:JMAP-6r7c.43)
///
/// The derived `PartialEq` / `Eq` impl compares `extra` as a
/// `serde_json::Map`, which is order-insensitive under the workspace default
/// (BTreeMap-backed) and order-sensitive if any crate in the dependency graph
/// enables `serde_json/preserve_order`.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StateChange {
    /// For each account that changed: maps data-type name to the new [`State`] token.
    ///
    /// Outer key: account [`Id`].  Inner key: JMAP data-type name (e.g. `"Email"`).
    /// Inner value: new opaque state string; pass to `Email/changes` etc. as `sinceState`.
    pub changed: BTreeMap<Id, BTreeMap<String, State>>,

    /// Catch-all for vendor / site / private extension fields not covered
    /// by the typed fields above. Preserves unknown fields across
    /// deserialize/serialize round-trip per workspace extras-preservation
    /// policy (see workspace AGENTS.md). Never contains `@type`.
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl StateChange {
    /// A `StateChange` with the given `changed` map and no extension fields.
    pub fn new(changed: BTreeMap<Id, BTreeMap<String, State>>) -> Self {
        Self {
            changed,
            extra: serde_json::Map::new(),
        }
    }
}

impl Serialize for StateChange {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let mut map = s.serialize_map(None)?;
        map.serialize_entry("@type", STATE_CHANGE_TYPE)?;
        map.serialize_entry("changed", &self.changed)?;
        for (k, v) in &self.extra {
            map.serialize_entry(k, v)?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for StateChange {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let mut extra = serde_json::Map::deserialize(d)?;
        take_type(&mut extra, STATE_CHANGE_TYPE)?;
        let changed = take_field(&mut extra, "changed")?;
        Ok(StateChange { changed, extra })
    }
}

/// A push subscription (RFC 8620 §7.2).
///
/// Every property other than `deviceClientId` is optional here because the
/// same type carries a create request (no `id`, `verificationCode` or
/// `expires`), a `PushSubscription/get` result (`url` and `keys` are never
/// returned, RFC 8620 §7.2.1), and the server's stored record. `None` fields
/// are omitted on serialize; a JSON `null` deserializes to `None`.
///
/// Extension properties, such as `chatPush` from
/// draft-atwood-jmap-chat-push-00, are carried in [`extra`](Self::extra).
///
/// The `Debug` impl redacts `url`, `keys.auth` and `verificationCode`.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PushSubscription {
    /// The `id` property: server-set and immutable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// The `deviceClientId` property: identifies the client and device.
    pub device_client_id: String,
    /// The `url` property: absolute URL the server POSTs pushes to. The RFC
    /// requires it to begin with `"https://"`; this type does not check that.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// The `keys` property: RFC 8291 encryption keys, or `None` for none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keys: Option<PushKeys>,
    /// The `verificationCode` property: `None` until the client echoes the
    /// code from the [`PushVerification`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub verification_code: Option<String>,
    /// The `expires` property: the server sends nothing after this time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires: Option<UTCDate>,
    /// The `types` property: data types to push; `None` means all types.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub types: Option<Vec<String>>,
    /// Catch-all for extension properties (e.g. `chatPush`) and vendor /
    /// site / private fields not covered by the typed fields above, per
    /// workspace extras-preservation policy (see workspace AGENTS.md).
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl fmt::Debug for PushSubscription {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PushSubscription")
            .field("id", &self.id)
            .field("device_client_id", &self.device_client_id)
            .field("url", &self.url.as_ref().map(|_| REDACTED))
            .field("keys", &self.keys)
            .field(
                "verification_code",
                &self.verification_code.as_ref().map(|_| REDACTED),
            )
            .field("expires", &self.expires)
            .field("types", &self.types)
            .field("extra", &self.extra)
            .finish()
    }
}

/// `PushSubscription` has no property selector enum; `PushSubscription/get`
/// takes property names directly.
impl crate::JmapObject for PushSubscription {
    const TYPE_NAME: &'static str = "PushSubscription";
    type Property = ();
}

/// Property attributes from RFC 8620 §7.2 (rfc8620.txt:3593, 3597, 3618,
/// 3623): `id` is "(immutable; server-set)"; `deviceClientId`, `url` and
/// `keys` are "(immutable)"; `verificationCode`, `expires` and `types`
/// carry no attribute.
impl crate::SetObject for PushSubscription {
    type Patch = crate::PatchObject;
    const SERVER_SET: &'static [&'static str] = &["id"];
    const CLIENT_SETTABLE: &'static [&'static str] = &[
        "deviceClientId",
        "url",
        "keys",
        "verificationCode",
        "expires",
        "types",
    ];
    const IMMUTABLE: &'static [&'static str] = &["deviceClientId", "url", "keys"];
}

/// The `keys` object of a [`PushSubscription`] (RFC 8620 §7.2).
///
/// "The object MUST have the following properties: p256dh ... auth", so both
/// are required on deserialize. The `Debug` impl redacts `auth`.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PushKeys {
    /// The `p256dh` property: the client's P-256 ECDH public key (RFC 8291),
    /// URL-safe base64.
    pub p256dh: String,
    /// The `auth` property: the RFC 8291 authentication secret, URL-safe
    /// base64.
    pub auth: String,
    /// Catch-all for vendor / site / private extension fields, per
    /// workspace extras-preservation policy (see workspace AGENTS.md).
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl fmt::Debug for PushKeys {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PushKeys")
            .field("p256dh", &self.p256dh)
            .field("auth", &REDACTED)
            .field("extra", &self.extra)
            .finish()
    }
}

/// The object pushed to a new subscription's URL (RFC 8620 §7.2.2).
///
/// The wire form always carries `"@type": "PushVerification"` (RFC 8620
/// §7.2.2): serialize always emits it; deserialize rejects any other value,
/// accepts its absence and never leaves it in `extra`. The `Debug` impl
/// redacts `verificationCode`.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq)]
pub struct PushVerification {
    /// The `pushSubscriptionId` property: the id of the new subscription.
    pub push_subscription_id: Id,
    /// The `verificationCode` property: the code the client must set on the
    /// subscription before the server sends it anything else.
    pub verification_code: String,
    /// Catch-all for vendor / site / private extension fields, per
    /// workspace extras-preservation policy (see workspace AGENTS.md).
    /// Never contains `@type`.
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl fmt::Debug for PushVerification {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PushVerification")
            .field("push_subscription_id", &self.push_subscription_id)
            .field("verification_code", &REDACTED)
            .field("extra", &self.extra)
            .finish()
    }
}

impl Serialize for PushVerification {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let mut map = s.serialize_map(None)?;
        map.serialize_entry("@type", PUSH_VERIFICATION_TYPE)?;
        map.serialize_entry("pushSubscriptionId", &self.push_subscription_id)?;
        map.serialize_entry("verificationCode", &self.verification_code)?;
        for (k, v) in &self.extra {
            map.serialize_entry(k, v)?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for PushVerification {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let mut extra = serde_json::Map::deserialize(d)?;
        take_type(&mut extra, PUSH_VERIFICATION_TYPE)?;
        let push_subscription_id = take_field(&mut extra, "pushSubscriptionId")?;
        let verification_code = take_field(&mut extra, "verificationCode")?;
        Ok(PushVerification {
            push_subscription_id,
            verification_code,
            extra,
        })
    }
}

/// Removes `@type` from `map`, failing if it is present and not `expected`.
fn take_type<E: serde::de::Error>(
    map: &mut serde_json::Map<String, serde_json::Value>,
    expected: &str,
) -> Result<(), E> {
    match map.remove("@type") {
        None => Ok(()),
        Some(serde_json::Value::String(s)) if s == expected => Ok(()),
        Some(serde_json::Value::String(_)) => {
            Err(E::custom(format!("@type must be \"{expected}\"")))
        }
        Some(other) => Err(E::custom(format!(
            "@type must be a string, found {}",
            crate::json_type_name(&other)
        ))),
    }
}

/// Removes the required property `key` from `map` and deserializes it.
fn take_field<T: DeserializeOwned, E: serde::de::Error>(
    map: &mut serde_json::Map<String, serde_json::Value>,
    key: &'static str,
) -> Result<T, E> {
    let value = map.remove(key).ok_or_else(|| E::missing_field(key))?;
    serde_json::from_value(value).map_err(E::custom)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Oracle: hand-written JSON whose `@type` carries a canary. RFC 8620
    /// §3.6.1 makes an error `description` "unstructured English text
    /// suitable for displaying to a developer", so the client value must not
    /// be echoed; only its JSON type (RFC 8259 §3 "object") is named.
    #[test]
    fn push_verification_type_error_does_not_echo_value() {
        for (raw, want) in [
            (
                r#"{"@type":{"note":"CANARY-kwqn"},"pushSubscriptionId":"p","verificationCode":"c"}"#,
                "@type must be a string, found object",
            ),
            (
                r#"{"@type":"CANARY-kwqn","pushSubscriptionId":"p","verificationCode":"c"}"#,
                "@type must be \"PushVerification\"",
            ),
        ] {
            let err = serde_json::from_str::<PushVerification>(raw)
                .unwrap_err()
                .to_string();
            assert!(!err.contains("CANARY-kwqn"), "{err}");
            assert!(err.contains(want), "{err}");
        }
    }

    /// Every `PushSubscription` property RFC 8620 §7.2 defines is classified
    /// once. The struct literal makes a new field a compile error here.
    #[test]
    fn push_subscription_properties_are_classified() {
        let sub = PushSubscription {
            id: Some(Id::from("ps1")),
            device_client_id: "dev".into(),
            url: Some("https://push.example.com/x".into()),
            keys: Some(PushKeys {
                p256dh: "p".into(),
                auth: "a".into(),
                extra: serde_json::Map::new(),
            }),
            verification_code: Some("code".into()),
            expires: Some(UTCDate::from("2026-01-01T00:00:00Z")),
            types: Some(vec!["Email".into()]),
            extra: serde_json::Map::new(),
        };
        assert_eq!(crate::check_property_classification(&sub), Ok(()));
    }
    use serde_json::json;

    /// `StateChange.extra` captures unknown fields on deserialize and
    /// flattens them on serialize (round-trip).
    #[test]
    fn state_change_preserves_vendor_extras() {
        let raw = json!({
            "changed": {
                "acc1": { "Email": "s42" }
            },
            "acmeCorpSequence": 17
        });
        let obj: StateChange = serde_json::from_value(raw).expect("StateChange must deserialize");
        assert_eq!(
            obj.extra.get("acmeCorpSequence").and_then(|v| v.as_u64()),
            Some(17)
        );

        // Round-trip: serializing back must reproduce the vendor field.
        let v = serde_json::to_value(&obj).expect("StateChange must serialize");
        assert_eq!(v["acmeCorpSequence"], json!(17));
    }

    /// bd:JMAP-6r7c.43 — regression-guard for the workspace's
    /// serde_json/preserve_order posture. Two StateChange values with the
    /// same `extra` keys inserted in different orders MUST compare equal
    /// under the workspace's default configuration (BTreeMap-backed
    /// serde_json::Map). If a future Cargo.lock or workspace-level feature
    /// change accidentally enables `preserve_order`, this assertion fails
    /// loudly and surfaces the SemVer-policy break before downstream
    /// consumers hit silently-different equality semantics.
    ///
    /// Both values are deserialized from JSON (the wire path) so the test
    /// exercises the same construction code path consumers use.
    #[test]
    fn extra_equality_is_order_insensitive_under_workspace_flags() {
        // Two equivalent JSON payloads with different key-insertion orders
        // for the vendor extras. Under BTreeMap-backed Map the keys are
        // re-sorted lexicographically on deserialize, so the resulting
        // structures compare equal.
        let raw_a = json!({
            "changed": {"acc1": {"Email": "s1"}},
            "vendorA": 1,
            "vendorB": 2
        });
        let raw_b = json!({
            "changed": {"acc1": {"Email": "s1"}},
            "vendorB": 2,
            "vendorA": 1
        });

        let a: StateChange = serde_json::from_value(raw_a).expect("a must deserialize");
        let b: StateChange = serde_json::from_value(raw_b).expect("b must deserialize");

        assert_eq!(
            a, b,
            "extra-map equality is order-insensitive under the workspace's \
             default serde_json::Map (BTreeMap-backed); if this fails, \
             check whether preserve_order has been enabled in the dep graph"
        );
    }

    /// Oracle: RFC 8030 §5.3 grammar `urgency-option = ("very-low" / "low"
    /// / "normal" / "high")`, listed "In order of increasing urgency".
    #[test]
    fn urgency_wire_values_in_increasing_order() {
        let ordered = [
            Urgency::VeryLow,
            Urgency::Low,
            Urgency::Normal,
            Urgency::High,
        ];
        let wire: Vec<&str> = ordered.iter().map(|u| u.as_str()).collect();
        assert_eq!(wire, ["very-low", "low", "normal", "high"]);
        assert!(ordered.windows(2).all(|w| w[0] < w[1]));
    }

    /// Oracle: RFC 8030 §5.3 `urgency-option = ("very-low" / "low" /
    /// "normal" / "high")`. Each string round-trips as a JSON string; a
    /// string outside the grammar, or another case, is rejected.
    #[test]
    fn urgency_serde_accepts_only_rfc8030_values() {
        for (wire, urgency) in [
            ("very-low", Urgency::VeryLow),
            ("low", Urgency::Low),
            ("normal", Urgency::Normal),
            ("high", Urgency::High),
        ] {
            let parsed: Urgency = serde_json::from_value(json!(wire)).expect(wire);
            assert_eq!(parsed, urgency);
            assert_eq!(serde_json::to_value(urgency).expect(wire), json!(wire));
        }
        for bad in ["urgent", "High", "very_low", ""] {
            assert!(
                serde_json::from_value::<Urgency>(json!(bad)).is_err(),
                "{bad:?}"
            );
        }
    }
}