mailcycle 0.7.0

Rust email API client: create addresses that receive email, read and decrypt messages on your machine, send email, verify webhooks and stream events.
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
//! Pairing a device, and handing it the keys for its addresses.
//!
//! This is the account's side of pairing, as the app does it on the
//! "Add device" screen. The device opens what is sealed here with code this
//! crate never runs, so every byte follows the app: `pairingCore.ts`,
//! `api/pairingApi.ts` and `handKeysTo` in `api/fleetApi.ts`.
//!
//! # The two ways a wrap secret reaches the account
//!
//! Each device has a 64-byte wrap secret. Its address keys are sealed under
//! it, and the account keeps a copy in the device's sealed profile so it can
//! hand over keys again when an address is assigned later.
//!
//! - **Optical.** The device shows the secret in its QR code
//!   (`MC1:<code>:<wrap>`). It reaches the account without passing through
//!   Mailcycle.
//! - **Relayed.** Only the eight digits are typed, which carry no secret. The
//!   device publishes a public key with its pairing session, and the account
//!   mints a secret and seals it to that key. The server relays the key, so it
//!   could put its own in its place at pairing and read what follows. It cannot
//!   read anything passively.

use std::collections::BTreeMap;
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};

use crate::client::{is_sealed_box, new_id, open_vault_record, vault_aad, Devices};
use crate::crypto::asymmetric::{seal_to_public_key, AsymmetricBox};
use crate::crypto::cipher::{seal_json, SealedBox, SEAL_VERSION};
use crate::crypto::primitives::random_bytes;
use crate::encoding::{from_b64u, to_b64u};
use crate::error::{Error, Result};
use crate::http::path_segment;
use crate::models::Device;

const QR_PREFIX: &str = "MC1:";
const WRAP_BYTES: usize = 64;
const WORKER_RECORD: &str = "worker";

/// What a scanned pairing QR code, or a typed code, carries.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ScannedPairing {
    /// The eight digits.
    pub code: Option<String>,
    /// A pairing token, from an old deep link. Nothing can be looked up by it.
    pub token: Option<String>,
    /// The device's wrap secret, base64url. Only a QR code carries it.
    pub wrap: Option<String>,
}

/// Reads a scanned QR value or a typed code, as `parseScannedValue` does.
///
/// Accepts `MC1:<code>`, `MC1:<code>:<wrap>`, the older JSON payload, a deep
/// link with a token, or eight digits written any way. `None` if it is none
/// of those.
pub fn parse_scanned_value(raw: &str) -> Option<ScannedPairing> {
    let value = raw.trim();
    if value.is_empty() {
        return None;
    }
    if let Some(rest) = value.strip_prefix(QR_PREFIX) {
        let (code, wrap) = match rest.split_once(':') {
            Some((code, wrap)) => (code, Some(wrap)),
            None => (rest, None),
        };
        let code_ok = code.len() == 8 && code.bytes().all(|b| b.is_ascii_digit());
        let wrap_ok = wrap.map_or(true, |w| {
            !w.is_empty() && w.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
        });
        // The app falls through to reading the digits out of a malformed one,
        // which picks up the 1 in `MC1`. Refused here instead.
        if !(code_ok && wrap_ok) {
            return None;
        }
        return Some(ScannedPairing {
            code: Some(code.to_string()),
            token: None,
            wrap: wrap.map(str::to_string),
        });
    }
    // Older JSON payloads, from devices still showing a pre-update screen.
    if let Ok(parsed) = serde_json::from_str::<Value>(value) {
        if parsed["type"] == "mailcycle.pairing" {
            if let Some(token) = parsed["token"].as_str() {
                let text = |field: &str| parsed[field].as_str().filter(|s| !s.is_empty()).map(str::to_string);
                return Some(ScannedPairing {
                    token: Some(token.to_string()),
                    code: text("code"),
                    wrap: text("wrap"),
                });
            }
        }
    }
    if let Some(start) = value.find("token=") {
        let before = value[..start].chars().last();
        if matches!(before, Some('?') | Some('&')) {
            let token: String =
                value[start + 6..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
            if !token.is_empty() {
                return Some(ScannedPairing { token: Some(token), ..Default::default() });
            }
        }
    }
    let digits: String = value.chars().filter(char::is_ascii_digit).take(8).collect();
    (digits.len() == 8).then(|| ScannedPairing { code: Some(digits), ..Default::default() })
}

/// A new wrap secret: 64 random bytes, base64url.
pub fn generate_wrap_secret() -> String {
    to_b64u(&random_bytes(WRAP_BYTES))
}

/// The key a device's key bundle is sealed under: the wrap secret itself.
///
/// A secret of the wrong length is an error, never a fall back to a weaker
/// key.
pub fn wrapping_key(wrap_secret: &str) -> Result<Vec<u8>> {
    let secret = from_b64u(wrap_secret).map_err(|_| wrap_secret_error())?;
    if secret.len() != WRAP_BYTES {
        return Err(wrap_secret_error());
    }
    Ok(secret)
}

fn wrap_secret_error() -> Error {
    Error::Unsupported("That pairing secret is not usable. Pair the device again.".into())
}

/// What a relayed wrap secret is bound to.
fn wrap_seal_aad(worker_id: &str) -> String {
    format!("mailcycle/v1/pairing-wrap:{worker_id}")
}

/// Seals a freshly minted wrap secret to the key the device published.
pub fn seal_wrap_for_device(device_key: &str, wrap_secret: &str, worker_id: &str) -> Result<AsymmetricBox> {
    let public_key = from_b64u(device_key)?;
    let secret = wrapping_key(wrap_secret)?;
    seal_to_public_key(&public_key, &secret, &wrap_seal_aad(worker_id), SEAL_VERSION)
}

/// The address keys for one device. The server stores and relays it blindly.
///
/// No `Debug` derive: `keys` and `sealing_keys` hold live private key material,
/// and a derived `{:?}` would print it into any log or panic message. The
/// manual impl below redacts it, matching `Keys`.
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct KeyBundle {
    /// Address id to its symmetric key, base64url, for mail the account's own
    /// devices sealed.
    pub keys: BTreeMap<String, String>,
    /// Address id to its X25519 private key, base64url, for mail that arrived
    /// from outside.
    #[serde(rename = "sealingKeys", default)]
    pub sealing_keys: BTreeMap<String, String>,
    /// A rotated address's later epochs: address id to epoch to keys. Epoch 0
    /// stays in `keys` and `sealing_keys`, for older readers.
    #[serde(rename = "epochKeys", default, skip_serializing_if = "BTreeMap::is_empty")]
    pub epoch_keys: BTreeMap<String, BTreeMap<String, EpochKey>>,
    /// An agent's sender name.
    #[serde(rename = "senderName", default, skip_serializing_if = "Option::is_none")]
    pub sender_name: Option<String>,
    /// Address id to the name set on that address, which wins over
    /// `sender_name`.
    #[serde(rename = "senderNames", default, skip_serializing_if = "BTreeMap::is_empty")]
    pub sender_names: BTreeMap<String, String>,
    #[serde(rename = "issuedAt")]
    pub issued_at: String,
}

/// One address's keys at one epoch above 0, base64url.
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct EpochKey {
    pub key: String,
    #[serde(rename = "sealingKey")]
    pub sealing_key: String,
}

impl std::fmt::Debug for EpochKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("EpochKey(..)")
    }
}

impl std::fmt::Debug for KeyBundle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Counts, never the keys themselves.
        f.debug_struct("KeyBundle")
            .field("keys", &self.keys.len())
            .field("sealing_keys", &self.sealing_keys.len())
            .field("sender_name", &self.sender_name)
            .field("sender_names", &self.sender_names)
            .field("issued_at", &self.issued_at)
            .finish()
    }
}

/// A device's sealed profile, as `encodeWorkerProfile` writes it.
#[derive(Serialize)]
struct WorkerProfile<'a> {
    name: &'a str,
    tags: [&'a str; 0],
    notes: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    wrap: Option<&'a str>,
}

/// Now, as JavaScript's `toISOString` writes it: `2026-09-21T10:00:00.000Z`.
fn iso_now() -> String {
    let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
    iso_at(now.as_secs() as i64, now.subsec_millis())
}

fn iso_at(seconds: i64, millis: u32) -> String {
    let (days, rest) = (seconds.div_euclid(86_400), seconds.rem_euclid(86_400));
    // Days to a civil date, after Howard Hinnant's `civil_from_days`.
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + i64::from(month <= 2);
    format!(
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{millis:03}Z",
        rest / 3600,
        rest % 3600 / 60,
        rest % 60
    )
}

fn worker_path(device_id: &str) -> String {
    format!("/workers/{}", path_segment(device_id))
}

impl Devices<'_> {
    /// Pairs a device with the account, as the app's "Add device" screen does.
    ///
    /// `code_or_qr` is the eight digits the device shows, or the text of its
    /// QR code. The QR code carries the device's wrap secret, so its keys
    /// reach it without passing through Mailcycle. With the digits alone the
    /// device must publish a pairing key; a secret is minted here and sealed
    /// to it, and the server relays that key, so it could put its own in its
    /// place at pairing. Prefer the QR code where there is one.
    ///
    /// `name` is sealed on this machine. An empty one takes the name the
    /// device gave. Needs the phrase and a signed-in session.
    pub fn pair(&self, code_or_qr: &str, name: &str) -> Result<Device> {
        let keys = self.client.require_keys("pair a device")?;
        let scanned = parse_scanned_value(code_or_qr).unwrap_or_default();
        let Some(code) = scanned.code else {
            return Err(Error::api(
                400,
                "invalid_code",
                if scanned.token.is_some() {
                    "That QR code does not carry a pairing code. Enter the 8 digits shown on the device."
                } else {
                    "A pairing code is eight digits."
                },
            ));
        };
        if let Some(wrap) = &scanned.wrap {
            wrapping_key(wrap)?;
        }

        let preview: Value =
            self.client.http.request("POST", "/workers/pair/lookup", Some(&json!({ "code": code })), &[])?;
        let session_id = preview["sessionId"].as_str().unwrap_or_default().to_string();
        let device_key = preview["deviceKey"].as_str().filter(|key| !key.is_empty());
        let worker_id = new_id("wkr", 10);

        let (wrap, transport, wrap_seal) =
            match (scanned.wrap, device_key) {
                (Some(wrap), _) => (wrap, "optical", None),
                (None, Some(device_key)) => {
                    let wrap = generate_wrap_secret();
                    let seal = seal_wrap_for_device(device_key, &wrap, &worker_id)?;
                    (wrap, "relayed", Some(seal))
                }
                (None, None) => return Err(Error::Unsupported(
                    "This device publishes no pairing key, so its keys cannot be handed over from a typed \
                     code. Pass the text of its QR code instead, or pair it in the app."
                        .into(),
                )),
            };

        let name = match name.trim() {
            "" => preview["deviceName"]
                .as_str()
                .map(str::trim)
                .filter(|n| !n.is_empty())
                .unwrap_or("New device"),
            given => given,
        }
        .to_string();
        let profile = WorkerProfile { name: &name, tags: [], notes: "", wrap: Some(&wrap) };
        let sealed =
            seal_json(keys.vault_key(), &profile, &vault_aad(WORKER_RECORD, &worker_id), SEAL_VERSION)?;

        let mut body = Map::new();
        body.insert("sessionId".into(), json!(session_id));
        body.insert("workerId".into(), json!(worker_id));
        body.insert("profile".into(), serde_json::to_value(&sealed).expect("a sealed box serializes"));
        body.insert("keyTransport".into(), json!(transport));
        if let Some(seal) = wrap_seal {
            body.insert("wrapSeal".into(), serde_json::to_value(&seal).expect("a sealed box serializes"));
        }
        let result: Value =
            self.client.http.request("POST", "/workers/pair", Some(&Value::Object(body)), &[])?;

        let mut wire = result["worker"].clone();
        if !wire.is_object() {
            wire = json!({ "id": worker_id });
        }
        wire["profile"] = serde_json::to_value(&sealed).expect("a sealed box serializes");
        Ok(self.to_device(&wire))
    }

    /// Hands a device the keys for every address assigned to it.
    ///
    /// Opens the device's sealed profile for its wrap secret, seals a fresh
    /// key bundle under it, and uploads that. [`assign`](Self::assign) and
    /// [`unassign`](Self::unassign) call this themselves. Needs the phrase and
    /// a signed-in session.
    pub fn hand_over_keys(&self, device_id: &str) -> Result<()> {
        let keys = self.client.require_keys("hand a device its keys")?;
        let worker: Value = self.client.http.request("GET", &worker_path(device_id), None, &[])?;
        let worker = &worker["worker"];

        let profile = if is_sealed_box(worker.get("profile")) {
            serde_json::from_value::<SealedBox>(worker["profile"].clone())
                .ok()
                .and_then(|box_| open_vault_record(keys.vault_key(), WORKER_RECORD, device_id, &box_).ok())
                .unwrap_or(Value::Null)
        } else {
            Value::Null
        };
        let Some(wrap) = profile["wrap"].as_str().filter(|w| !w.is_empty()) else {
            let message = if worker["kind"] == "agent" {
                "This agent was connected without its key. Remove it and connect it again."
            } else {
                "This device was paired without keeping its key, so it cannot open the mail. Unpair it, \
                 pair it again, then assign the address."
            };
            return Err(Error::api(409, "no_wrap", message));
        };
        let wrap_key = wrapping_key(wrap)?;

        let inboxes: Value = self.client.http.request("GET", "/inboxes", None, &[])?;
        let mut bundle = KeyBundle {
            keys: BTreeMap::new(),
            sealing_keys: BTreeMap::new(),
            epoch_keys: BTreeMap::new(),
            sender_name: profile["senderName"].as_str().filter(|n| !n.is_empty()).map(str::to_string),
            sender_names: BTreeMap::new(),
            issued_at: iso_now(),
        };
        for inbox in inboxes["inboxes"].as_array().into_iter().flatten() {
            if inbox["assignedWorkerId"].as_str() != Some(device_id) {
                continue;
            }
            let Some(id) = inbox["id"].as_str() else { continue };
            // The name set on the address, opened from its sealed details.
            let sender_name = serde_json::from_value::<SealedBox>(inbox["meta"].clone())
                .ok()
                .and_then(|box_| open_vault_record(keys.vault_key(), "inbox", id, &box_).ok())
                .and_then(|meta| meta["senderName"].as_str().filter(|n| !n.is_empty()).map(str::to_string));
            if let Some(name) = sender_name {
                bundle.sender_names.insert(id.to_string(), name);
            }
            bundle.keys.insert(id.to_string(), to_b64u(&keys.address_symmetric_key(id)?));
            bundle.sealing_keys.insert(id.to_string(), to_b64u(&keys.address_private_key(id)?));
            // Every epoch a rotated address has reached, so the device reads
            // mail from both sides of the rotation.
            let reached = inbox["keyEpoch"].as_u64().and_then(|e| u32::try_from(e).ok()).unwrap_or(0);
            for epoch in 1..=reached {
                bundle.epoch_keys.entry(id.to_string()).or_default().insert(
                    epoch.to_string(),
                    EpochKey {
                        key: to_b64u(&keys.address_symmetric_key_at(id, epoch)?),
                        sealing_key: to_b64u(&keys.address_private_key_at(id, epoch)?),
                    },
                );
            }
        }

        let sealed = seal_json(&wrap_key, &bundle, device_id, SEAL_VERSION)?;
        let path = format!("{}/keys", worker_path(device_id));
        let _: Value = self.client.http.request("POST", &path, Some(&json!({ "keyBundle": sealed })), &[])?;
        Ok(())
    }

    /// Assigns an address to a device, then hands it the keys to open it.
    ///
    /// The address is assigned even if the handover fails, and the error
    /// says why. Needs the phrase and a signed-in session.
    pub fn assign(&self, device_id: &str, address_id: &str) -> Result<()> {
        let path = format!("{}/inboxes", worker_path(device_id));
        let _: Value =
            self.client.http.request("POST", &path, Some(&json!({ "inboxId": address_id })), &[])?;
        self.hand_over_keys(device_id)
    }

    /// Takes an address off a device, then hands it a bundle without that
    /// address's keys.
    ///
    /// The second step is best effort, as in the app: the address is already
    /// gone from the device either way.
    pub fn unassign(&self, device_id: &str, address_id: &str) -> Result<()> {
        let path = format!("{}/inboxes/{}", worker_path(device_id), path_segment(address_id));
        let _: Value = self.client.http.request("DELETE", &path, None, &[])?;
        let _ = self.hand_over_keys(device_id);
        Ok(())
    }
}

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

    #[test]
    fn reads_every_shape_the_app_reads() {
        let wrap = "a".repeat(86);
        assert_eq!(
            parse_scanned_value(&format!("MC1:12345678:{wrap}")),
            Some(ScannedPairing { code: Some("12345678".into()), token: None, wrap: Some(wrap.clone()) })
        );
        assert_eq!(
            parse_scanned_value(" MC1:12345678 "),
            Some(ScannedPairing { code: Some("12345678".into()), ..Default::default() })
        );
        assert_eq!(
            parse_scanned_value("1234 5678"),
            Some(ScannedPairing { code: Some("12345678".into()), ..Default::default() })
        );
        assert_eq!(
            parse_scanned_value("mailcycle://pair?token=pt_abc123"),
            Some(ScannedPairing { token: Some("pt_abc123".into()), ..Default::default() })
        );
        assert_eq!(
            parse_scanned_value(
                r#"{"type":"mailcycle.pairing","token":"pt_x","code":"11112222","wrap":"w"}"#
            ),
            Some(ScannedPairing {
                token: Some("pt_x".into()),
                code: Some("11112222".into()),
                wrap: Some("w".into())
            })
        );
        assert_eq!(parse_scanned_value("1234"), None);
        assert_eq!(parse_scanned_value("MC1:12345678:not base64!"), None);
        assert_eq!(parse_scanned_value(""), None);
    }

    #[test]
    fn a_wrap_secret_is_64_bytes_or_refused() {
        assert_eq!(wrapping_key(&generate_wrap_secret()).unwrap().len(), 64);
        assert!(wrapping_key(&to_b64u(&[7u8; 32])).is_err());
        assert!(wrapping_key("not base64url!").is_err());
    }

    #[test]
    fn the_time_is_written_as_javascript_writes_it() {
        // What `new Date(...).toISOString()` gives for each.
        assert_eq!(iso_at(0, 0), "1970-01-01T00:00:00.000Z");
        assert_eq!(iso_at(951_782_400, 789), "2000-02-29T00:00:00.789Z");
        assert_eq!(iso_at(1_789_986_896, 5), "2026-09-21T10:34:56.005Z");
        assert_eq!(iso_at(4_107_542_399, 999), "2100-02-28T23:59:59.999Z");
        let now = iso_now();
        assert_eq!(now.len(), 24);
        assert!(now.starts_with("20") && now.ends_with('Z'));
        assert_eq!(&now[10..11], "T");
    }
}