mailcycle 0.4.1

Rust client for the Mailcycle API. Create addresses that receive mail, read and decrypt it on your machine, send, and listen for 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
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
//! A client for one Mailcycle account.
//!
//! Signed in with the recovery phrase, it can do everything the app can: open
//! mail, create addresses that receive it, and read the labels and names the
//! app seals. With an API key alone it manages addresses, devices and
//! metadata; add the phrase to open mail too.
//!
//! The phrase never leaves this machine, and nothing derived from it is sent
//! anywhere. What reaches the API is an account id, a public key, and a proof
//! that this machine holds the matching private one.

use std::time::{Duration, Instant};

use serde_json::{json, Map, Value};

use crate::crypto::authproof::{prove_account, DELETE_DOMAIN, DOMAIN};
use crate::crypto::cipher::{open_json, seal_json, SealedBox, SEAL_VERSION};
use crate::crypto::mnemonic::generate_phrase;
use crate::encoding::to_b64;
use crate::error::{Error, Result};
use crate::events::{EventStream, Hooks};
use crate::http::{path_segment, Http, DEFAULT_API_URL, DEFAULT_TIMEOUT_SECONDS};
use crate::keys::Keys;
use crate::mail::{open_attachment_bytes_at, to_message};
use crate::manage::{ApiKeys, Sessions, Webhooks};
use crate::models::{
    Account, ActivityEntry, ActivityPage, Address, Device, Domain, Message, MessagePage, NameStyle, Plan,
    SendResult, Subscription,
};

const ID_ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
/// How long `wait_for` gives the event stream to come up before it polls.
const STREAM_OPEN: Duration = Duration::from_secs(10);
/// The API's limits on what a message can carry. It is the authority; these
/// only refuse early what it would refuse anyway.
const MAX_ATTACHMENTS: usize = 10;
const MAX_ATTACHMENT_BYTES: usize = 7 * 1024 * 1024 / 2;

pub(crate) fn new_id(prefix: &str, length: usize) -> String {
    let random = crate::crypto::primitives::random_bytes(length * 2);
    let mut out = String::with_capacity(length);
    // Rejection sampling, so every character is equally likely. 252 is the
    // largest multiple of 36 below 256.
    for byte in random {
        if out.len() == length {
            break;
        }
        if byte < 252 {
            out.push(ID_ALPHABET[(byte % 36) as usize] as char);
        }
    }
    while out.len() < length {
        let extra = crate::crypto::primitives::random_bytes(1)[0];
        if extra < 252 {
            out.push(ID_ALPHABET[(extra % 36) as usize] as char);
        }
    }
    format!("{prefix}_{out}")
}

/// What a record sealed under the vault key is bound to.
///
/// The kind of record as well as its id, so a box from one kind cannot be read
/// as another. Records sealed before that change carry the bare id, and still
/// open; [`open_vault_record`] tries both.
pub(crate) fn vault_aad(kind: &str, id: &str) -> String {
    format!("mailcycle/v1/{kind}:{id}")
}

pub(crate) fn open_vault_record(vault_key: &[u8], kind: &str, id: &str, box_: &SealedBox) -> Result<Value> {
    match open_json::<Value>(vault_key, box_, &vault_aad(kind, id)) {
        Ok(value) => Ok(value),
        Err(_) => open_json(vault_key, box_, id),
    }
}

pub(crate) fn is_sealed_box(value: Option<&Value>) -> bool {
    value.is_some_and(|v| v.get("c").is_some() && v.get("epk").is_none())
}

/// How to reach the API. `Default` is the live one with a 30-second timeout.
pub struct Options {
    pub api_url: String,
    pub passphrase: String,
    pub timeout_seconds: u64,
}

impl Default for Options {
    fn default() -> Self {
        Options {
            api_url: DEFAULT_API_URL.into(),
            passphrase: String::new(),
            timeout_seconds: DEFAULT_TIMEOUT_SECONDS,
        }
    }
}

/// What a new address should look like. `Default` leaves every choice to the
/// server except the domain, which falls back to the first the account can use.
#[derive(Default)]
pub struct NewAddress {
    /// A domain from `domains().list()`. Defaults to the first one available.
    pub domain: Option<String>,
    /// The start of the address; the server adds a random ending.
    pub prefix: Option<String>,
    /// The whole part before the `@`. A name from `roll_names` works on
    /// every plan; any other name needs Scale and up.
    pub local_part: Option<String>,
    /// The kind of name the server rolls. Used only when neither
    /// `local_part` nor `prefix` is set. The server picks neutral by default.
    pub style: Option<NameStyle>,
    /// A private label, sealed on this machine.
    pub label: Option<String>,
    /// 1 to 90 days. Defaults to 7.
    pub retention_days: Option<u32>,
}

/// What to send. Build it with [`Outgoing::new`].
pub struct Outgoing<'a> {
    pub from: &'a str,
    pub to: &'a str,
    pub subject: &'a str,
    pub text: &'a str,
    pub html: Option<&'a str>,
    pub from_name: Option<&'a str>,
    /// Reply to a message, and the threading headers are filled in from it.
    pub reply_to: Option<&'a Message>,
    /// Up to ten files, 3.5 MB between them.
    pub attachments: &'a [OutgoingAttachment<'a>],
}

impl<'a> Outgoing<'a> {
    pub fn new(from: &'a str, to: &'a str, subject: &'a str, text: &'a str) -> Self {
        Outgoing { from, to, subject, text, html: None, from_name: None, reply_to: None, attachments: &[] }
    }
}

/// A file to send with a message. Build it with [`OutgoingAttachment::new`].
pub struct OutgoingAttachment<'a> {
    /// What the recipient saves it as. Program and script files (.exe, .js,
    /// .ps1 and the like) are refused.
    pub filename: &'a str,
    pub content: &'a [u8],
    /// Defaults to application/octet-stream.
    pub mime_type: Option<&'a str>,
    /// Makes the file inline, shown where the HTML says `cid:<content_id>`.
    pub content_id: Option<&'a str>,
}

impl<'a> OutgoingAttachment<'a> {
    pub fn new(filename: &'a str, content: &'a [u8]) -> Self {
        OutgoingAttachment { filename, content, mime_type: None, content_id: None }
    }
}

fn attachments_body(attachments: &[OutgoingAttachment<'_>]) -> Result<Value> {
    if attachments.len() > MAX_ATTACHMENTS {
        return Err(Error::api(
            0,
            "too_many_attachments",
            format!("A message can have at most {MAX_ATTACHMENTS} attachments."),
        ));
    }
    if attachments.iter().map(|a| a.content.len()).sum::<usize>() > MAX_ATTACHMENT_BYTES {
        return Err(Error::api(0, "attachments_too_large", "Attachments can add up to 3.5 MB per message."));
    }
    let items = attachments
        .iter()
        .map(|a| {
            let mut item = Map::new();
            item.insert("filename".into(), json!(a.filename));
            item.insert("content".into(), json!(to_b64(a.content)));
            if let Some(mime_type) = a.mime_type {
                item.insert("mimeType".into(), json!(mime_type));
            }
            if let Some(content_id) = a.content_id {
                item.insert("contentId".into(), json!(content_id));
            }
            Value::Object(item)
        })
        .collect();
    Ok(Value::Array(items))
}

/// What to wait for. `Default` matches any message, for 60 seconds.
pub struct WaitFor<'a> {
    /// Only mail to this address id. Needed when the stream is unavailable.
    pub address_id: Option<&'a str>,
    /// Only mail whose From contains this, case-insensitive.
    pub from: Option<&'a str>,
    /// Only mail whose subject contains this, case-insensitive.
    pub subject: Option<&'a str>,
    pub timeout: Duration,
    pub poll_every: Duration,
    /// How long to give the stream before polling instead.
    pub stream_open: Duration,
}

impl Default for WaitFor<'_> {
    fn default() -> Self {
        WaitFor {
            address_id: None,
            from: None,
            subject: None,
            timeout: Duration::from_secs(60),
            poll_every: Duration::from_secs(5),
            stream_open: STREAM_OPEN,
        }
    }
}

/// The client.
pub struct Mailcycle {
    pub(crate) http: Http,
    pub(crate) keys: Option<Keys>,
    /// Built with an API key rather than a session.
    api_key: bool,
}

impl Mailcycle {
    /// A new twelve-word recovery phrase, generated on this machine.
    pub fn generate_phrase() -> String {
        generate_phrase().join(" ")
    }

    /// Signs in with the recovery phrase.
    ///
    /// The same challenge-response the app uses, in which nothing secret
    /// crosses the wire. Sessions last 30 days; keep [`session_token`] and
    /// pass it to [`resume`] rather than deriving the keys again every run.
    ///
    /// [`session_token`]: Mailcycle::session_token
    /// [`resume`]: Mailcycle::resume
    pub fn sign_in(phrase: &str, options: Options) -> Result<Self> {
        let keys = Keys::from_phrase(phrase, &options.passphrase)?;
        let mut http = Http::new(&options.api_url, None, options.timeout_seconds);

        let challenge: Value = http.request(
            "POST",
            "/accounts/challenge",
            Some(&json!({ "accountId": keys.account_id() })),
            &[],
        )?;
        let nonce = challenge["nonce"].as_str().unwrap_or_default();
        let challenge_key = challenge["challengeKey"].as_str().unwrap_or_default();
        let proof = prove_account(keys.auth_key(), challenge_key, nonce, keys.account_id(), DOMAIN)?;

        let session: Value = http.request(
            "POST",
            "/accounts/verify",
            Some(&json!({ "accountId": keys.account_id(), "nonce": nonce, "proof": proof })),
            &[],
        )?;
        http.set_token(session["token"].as_str().map(str::to_string));
        Ok(Mailcycle { http, keys: Some(keys), api_key: false })
    }

    /// Picks up a session from an earlier [`sign_in`](Mailcycle::sign_in).
    ///
    /// The phrase is still needed to open mail, and is checked against the
    /// session's account before it is used.
    pub fn resume(session_token: &str, phrase: &str, options: Options) -> Result<Self> {
        let keys = Keys::from_phrase(phrase, &options.passphrase)?;
        let http = Http::new(&options.api_url, Some(session_token.to_string()), options.timeout_seconds);
        let client = Mailcycle { http, keys: Some(keys), api_key: false };
        client.check_phrase_matches("session")?;
        Ok(client)
    }

    /// Uses an API key, `mak_…`. Operator plan and up.
    ///
    /// With the phrase as well, the client can open mail and create addresses
    /// that receive it; the phrase is checked against the key's account first.
    pub fn with_api_key(api_key: &str, phrase: Option<&str>, options: Options) -> Result<Self> {
        let keys = phrase.map(|p| Keys::from_phrase(p, &options.passphrase)).transpose()?;
        let http = Http::new(&options.api_url, Some(api_key.to_string()), options.timeout_seconds);
        let client = Mailcycle { http, keys, api_key: true };
        if client.keys.is_some() {
            client.check_phrase_matches("API key")?;
        }
        Ok(client)
    }

    /// Creates an account and signs in. Returns the client and its phrase.
    ///
    /// Keep the phrase. Nothing can recover the account without it, and nobody
    /// at Mailcycle can help.
    pub fn create_account(phrase: Option<&str>, options: Options) -> Result<(Self, String)> {
        let words = phrase.map(str::to_string).unwrap_or_else(Self::generate_phrase);
        let keys = Keys::from_phrase(&words, &options.passphrase)?;
        let mut http = Http::new(&options.api_url, None, options.timeout_seconds);
        let session: Value = http.request(
            "POST",
            "/accounts",
            Some(&json!({
                "accountId": keys.account_id(),
                "authVerifier": keys.auth_verifier(),
                "authPublicKey": keys.auth_public_key(),
            })),
            &[],
        )?;
        http.set_token(session["token"].as_str().map(str::to_string));
        Ok((Mailcycle { http, keys: Some(keys), api_key: false }, words))
    }

    fn check_phrase_matches(&self, what: &str) -> Result<()> {
        let keys = self.keys.as_ref().expect("checked by the caller");
        if self.account()?.id != keys.account_id() {
            return Err(Error::Unsupported(format!(
                "That phrase belongs to a different account from the {what}."
            )));
        }
        Ok(())
    }

    // -- the account ----------------------------------------------------

    /// The account id, when the phrase is known. Public, and safe to log.
    pub fn account_id(&self) -> Option<&str> {
        self.keys.as_ref().map(Keys::account_id)
    }

    /// The bearer this client uses: the session from `sign_in`, or the API key.
    pub fn session_token(&self) -> Option<&str> {
        self.http.token()
    }

    /// Whether this client can open mail and create addresses that receive it.
    pub fn can_decrypt(&self) -> bool {
        self.keys.is_some()
    }

    pub fn account(&self) -> Result<Account> {
        let result: Value = self.http.request("GET", "/accounts/me", None, &[])?;
        let operator = &result["operator"];
        Ok(Account {
            id: operator["id"].as_str().unwrap_or_default().to_string(),
            plan_id: operator["planId"].as_str().unwrap_or_default().to_string(),
            created_at: operator["createdAt"].as_str().unwrap_or_default().to_string(),
            plan: serde_json::from_value(result["plan"].clone()).unwrap_or(Plan {
                id: String::new(),
                name: String::new(),
                extra: Default::default(),
            }),
        })
    }

    /// Recent account events, newest first: ids and times, never content.
    pub fn activity(&self, limit: u32) -> Result<Vec<ActivityEntry>> {
        Ok(self.activity_page(Some(limit), None)?.activity)
    }

    /// One page of account events, newest first.
    ///
    /// `cursor` is the `next_cursor` of the page before, passed back as it is.
    /// It is opaque: do not build one or read a time out of it.
    pub fn activity_page(&self, limit: Option<u32>, cursor: Option<&str>) -> Result<ActivityPage> {
        let mut query: Vec<(&str, String)> = Vec::new();
        if let Some(limit) = limit {
            query.push(("limit", limit.to_string()));
        }
        if let Some(cursor) = cursor {
            query.push(("cursor", cursor.to_string()));
        }
        let result: Value = self.http.request("GET", "/activity", None, &query)?;
        Ok(ActivityPage {
            activity: serde_json::from_value(result["activity"].clone()).unwrap_or_default(),
            next_cursor: result["nextCursor"].as_str().map(str::to_string),
        })
    }

    /// Every event the server still holds (the last 90 days), newest first,
    /// walking the pages.
    pub fn all_activity(&self) -> Result<Vec<ActivityEntry>> {
        let mut out = Vec::new();
        let mut cursor: Option<String> = None;
        loop {
            let page = self.activity_page(Some(200), cursor.as_deref())?;
            out.extend(page.activity);
            match page.next_cursor {
                Some(next) => cursor = Some(next),
                None => return Ok(out),
            }
        }
    }

    /// What the account has used, against what its plan allows.
    pub fn usage(&self) -> Result<Value> {
        self.http.request("GET", "/usage", None, &[])
    }

    /// Ends this session.
    ///
    /// Does nothing for a client built with an API key: a key is not a
    /// session, and it keeps working until it is revoked with
    /// `api_keys().revoke()` or in the app.
    pub fn sign_out(&mut self) -> Result<()> {
        if self.api_key {
            return Ok(());
        }
        let _: Value = self.http.request("POST", "/accounts/signout", Some(&json!({})), &[])?;
        self.http.set_token(None);
        Ok(())
    }

    /// Erases the account and everything in it, at once. Session only.
    ///
    /// There is no undo and no grace period. Its addresses are retired and
    /// never issued again.
    ///
    /// It answers a fresh challenge with the phrase, so a copied session
    /// token alone cannot erase the account.
    pub fn delete_account(&mut self) -> Result<()> {
        let mut body = None;
        if let (Some(keys), false) = (&self.keys, self.api_key) {
            let challenge: Value = self.http.request(
                "POST",
                "/accounts/challenge",
                Some(&json!({ "accountId": keys.account_id() })),
                &[],
            )?;
            let nonce = challenge["nonce"].as_str().unwrap_or_default();
            let challenge_key = challenge["challengeKey"].as_str().unwrap_or_default();
            let proof =
                prove_account(keys.auth_key(), challenge_key, nonce, keys.account_id(), DELETE_DOMAIN)?;
            body = Some(json!({ "nonce": nonce, "proof": proof }));
        }
        let _: Value = self.http.request("DELETE", "/accounts/me", body.as_ref(), &[])?;
        self.http.set_token(None);
        Ok(())
    }

    /// The account's subscription and balance.
    pub fn subscription(&self) -> Result<Subscription> {
        let result: Value = self.http.request("GET", "/subscription", None, &[])?;
        let subscription = &result["subscription"];
        let text = |key: &str| subscription[key].as_str().unwrap_or_default().to_string();
        Ok(Subscription {
            id: text("id"),
            plan_id: text("planId"),
            status: text("status"),
            renewal_date: text("renewalDate"),
            pending_plan_id: subscription["pendingPlanId"].as_str().map(str::to_string),
            balance_minor: result["balanceMinor"].as_i64().unwrap_or(0),
            pause: Some(result["pause"].clone()).filter(|value| !value.is_null()),
        })
    }

    /// Every plan, with what each includes and costs.
    pub fn plans(&self) -> Result<Vec<Plan>> {
        let result: Value = self.http.request("GET", "/plans", None, &[])?;
        Ok(serde_json::from_value(result["plans"].clone()).unwrap_or_default())
    }

    pub fn addresses(&self) -> Addresses<'_> {
        Addresses { client: self }
    }

    pub fn messages(&self) -> Messages<'_> {
        Messages { client: self }
    }

    pub fn devices(&self) -> Devices<'_> {
        Devices { client: self }
    }

    pub fn domains(&self) -> Domains<'_> {
        Domains { client: self }
    }

    pub fn events(&self) -> Events<'_> {
        Events { client: self }
    }

    /// API keys. Session only.
    pub fn api_keys(&self) -> ApiKeys<'_> {
        ApiKeys { client: self }
    }

    /// Webhooks, Operator and up.
    pub fn webhooks(&self) -> Webhooks<'_> {
        Webhooks { client: self }
    }

    /// The account's signed-in sessions. Session only.
    pub fn sessions(&self) -> Sessions<'_> {
        Sessions { client: self }
    }

    pub(crate) fn require_keys(&self, what: &str) -> Result<&Keys> {
        self.keys.as_ref().ok_or_else(|| {
            Error::Unsupported(format!(
                "The recovery phrase is needed to {what}. Pass it when building the client."
            ))
        })
    }
}

/// Email addresses on the account.
pub struct Addresses<'a> {
    client: &'a Mailcycle,
}

impl Addresses<'_> {
    fn to_address(&self, wire: &Value) -> Address {
        let id = wire["id"].as_str().unwrap_or_default().to_string();
        let mut meta = Value::Null;
        if let (Some(keys), true) = (self.client.keys.as_ref(), is_sealed_box(wire.get("meta"))) {
            if let Ok(box_) = serde_json::from_value::<SealedBox>(wire["meta"].clone()) {
                meta = open_vault_record(keys.vault_key(), "inbox", &id, &box_).unwrap_or(Value::Null);
            }
        }
        let text = |field: &str| meta[field].as_str().filter(|text| !text.is_empty()).map(str::to_string);
        let (label, sender_name) = (text("label"), text("senderName"));
        Address {
            id,
            email_address: wire["emailAddress"].as_str().unwrap_or_default().to_string(),
            status: wire["status"].as_str().unwrap_or_default().to_string(),
            created_at: wire["createdAt"].as_str().unwrap_or_default().to_string(),
            retention_days: wire["retentionDays"].as_u64().unwrap_or(0) as u32,
            assigned_worker_id: wire["assignedWorkerId"].as_str().map(str::to_string),
            paused_at: wire["pausedAt"].as_str().map(str::to_string),
            label,
            sender_name,
            receives: wire["receives"].as_bool().unwrap_or(true),
        }
    }

    /// The first domain the account can create addresses on.
    fn default_domain(&self) -> Result<String> {
        self.client
            .domains()
            .list()?
            .into_iter()
            .next()
            .map(|domain| domain.domain)
            .ok_or_else(|| Error::Unsupported("The account has no domain to create addresses on.".into()))
    }

    pub fn list(&self) -> Result<Vec<Address>> {
        let result: Value = self.client.http.request("GET", "/inboxes", None, &[])?;
        Ok(result["inboxes"]
            .as_array()
            .map(|items| items.iter().map(|item| self.to_address(item)).collect())
            .unwrap_or_default())
    }

    /// Up to eight names in one style that are free on the domain right now.
    ///
    /// Pass one to `create` as `local_part`. Somebody may take it first, and
    /// then `create` is refused. `domain` defaults to the one `create` would
    /// use.
    pub fn roll_names(&self, style: NameStyle, domain: Option<&str>) -> Result<Vec<String>> {
        let domain = match domain {
            Some(domain) => domain.to_string(),
            None => self.default_domain()?,
        };
        let query = [("style", style.as_str().to_string()), ("domain", domain)];
        let result: Value = self.client.http.request("GET", "/inboxes/names", None, &query)?;
        Ok(result["names"]
            .as_array()
            .map(|items| items.iter().filter_map(Value::as_str).map(str::to_string).collect())
            .unwrap_or_default())
    }

    /// Creates an address that can receive mail.
    ///
    /// Needs the phrase: the address's public key is derived from it here, and
    /// only the public half is uploaded. Mail sealed to it opens nowhere else.
    pub fn create(&self, wanted: NewAddress) -> Result<Address> {
        let keys = self.client.require_keys("create an address that receives mail")?;
        let id = new_id("ibx", 12);

        let domain = match wanted.domain {
            Some(domain) => domain,
            None => self.default_domain()?,
        };

        let meta = match &wanted.label {
            Some(label) => seal_json(
                keys.vault_key(),
                &json!({ "label": label }),
                &vault_aad("inbox", &id),
                SEAL_VERSION,
            )?,
            None => seal_json(keys.vault_key(), &json!({}), &vault_aad("inbox", &id), SEAL_VERSION)?,
        };

        let mut body = Map::new();
        body.insert("id".into(), json!(id));
        body.insert("domain".into(), json!(domain));
        body.insert("meta".into(), serde_json::to_value(&meta).unwrap());
        // The public half only. Mail is sealed to it and opens only with the phrase.
        body.insert("publicKey".into(), json!(keys.address_public_key(&id)?));
        if let Some(local_part) = &wanted.local_part {
            body.insert("localPart".into(), json!(local_part));
        } else if let Some(prefix) = &wanted.prefix {
            body.insert("prefix".into(), json!(prefix));
        } else if let Some(style) = wanted.style {
            body.insert("style".into(), json!(style.as_str()));
        }
        if let Some(days) = wanted.retention_days {
            body.insert("retentionDays".into(), json!(days));
        }

        let result: Value = self.client.http.request("POST", "/inboxes", Some(&Value::Object(body)), &[])?;
        Ok(self.to_address(&result["inbox"]))
    }

    /// Changes a label, a retention window, or both. An empty label clears it.
    pub fn update(
        &self,
        address_id: &str,
        label: Option<Option<&str>>,
        retention_days: Option<u32>,
    ) -> Result<Address> {
        let mut body = Map::new();
        if let Some(days) = retention_days {
            body.insert("retentionDays".into(), json!(days));
        }
        if let Some(wanted) = label {
            let keys = self.client.require_keys("change a label")?;
            let value = match wanted.filter(|text| !text.is_empty()) {
                Some(text) => json!({ "label": text }),
                None => json!({}),
            };
            let box_ = seal_json(keys.vault_key(), &value, &vault_aad("inbox", address_id), SEAL_VERSION)?;
            body.insert("meta".into(), serde_json::to_value(&box_).unwrap());
        }
        let path = format!("/inboxes/{}", path_segment(address_id));
        let result: Value = self.client.http.request("PATCH", &path, Some(&Value::Object(body)), &[])?;
        Ok(self.to_address(&result["inbox"]))
    }

    /// Deletes the address and its mail. It is never issued again.
    pub fn delete(&self, address_id: &str) -> Result<()> {
        let path = format!("/inboxes/{}", path_segment(address_id));
        let _: Value = self.client.http.request("DELETE", &path, None, &[])?;
        Ok(())
    }

    /// How many addresses the plan allows and how many are left.
    pub fn allocation(&self) -> Result<Value> {
        self.client.http.request("GET", "/inboxes/allocation", None, &[])
    }
}

/// Mail: list, read, organise, send, and wait for new mail.
pub struct Messages<'a> {
    client: &'a Mailcycle,
}

impl Messages<'_> {
    /// One page of a folder, newest first.
    ///
    /// `cursor` is the `next_cursor` of the page before, passed back as it is.
    /// It is opaque: do not build one or read a time out of it.
    pub fn list(
        &self,
        address_id: &str,
        folder: Option<&str>,
        limit: Option<u32>,
        cursor: Option<&str>,
    ) -> Result<MessagePage> {
        let mut query: Vec<(&str, String)> = Vec::new();
        if let Some(folder) = folder {
            query.push(("folder", folder.to_string()));
        }
        if let Some(limit) = limit {
            query.push(("limit", limit.to_string()));
        }
        if let Some(cursor) = cursor {
            query.push(("cursor", cursor.to_string()));
        }
        let path = format!("/inboxes/{}/messages", path_segment(address_id));
        let result: Value = self.client.http.request("GET", &path, None, &query)?;
        Ok(MessagePage {
            messages: result["messages"]
                .as_array()
                .map(|items| items.iter().map(|item| to_message(self.client.keys.as_ref(), item)).collect())
                .unwrap_or_default(),
            next_cursor: result["nextCursor"].as_str().map(str::to_string),
        })
    }

    /// Every message in a folder, walking the pages.
    pub fn all(&self, address_id: &str, folder: Option<&str>) -> Result<Vec<Message>> {
        let mut out = Vec::new();
        let mut cursor: Option<String> = None;
        loop {
            let page = self.list(address_id, folder, Some(100), cursor.as_deref())?;
            out.extend(page.messages);
            match page.next_cursor {
                Some(next) => cursor = Some(next),
                None => return Ok(out),
            }
        }
    }

    pub fn get(&self, message_id: &str) -> Result<Message> {
        let path = format!("/messages/{}", path_segment(message_id));
        let result: Value = self.client.http.request("GET", &path, None, &[])?;
        Ok(to_message(self.client.keys.as_ref(), &result["message"]))
    }

    /// The attachment's bytes, opened on this machine. Needs the phrase.
    pub fn attachment(&self, message: &Message, index: usize) -> Result<Vec<u8>> {
        let keys = self.client.require_keys("open an attachment")?;
        let path = format!("/messages/{}/attachments/{index}", path_segment(&message.id));
        let data = self.client.http.request_bytes("GET", &path)?;
        open_attachment_bytes_at(keys, &message.address_id, &message.id, index, message.key_epoch, &data)
    }

    pub fn mark_read(&self, message_id: &str, read: bool) -> Result<()> {
        let path = format!("/messages/{}/read", path_segment(message_id));
        let _: Value = self.client.http.request("POST", &path, Some(&json!({ "read": read })), &[])?;
        Ok(())
    }

    pub fn star(&self, message_id: &str, starred: bool) -> Result<()> {
        let path = format!("/messages/{}/star", path_segment(message_id));
        let _: Value = self.client.http.request("POST", &path, Some(&json!({ "starred": starred })), &[])?;
        Ok(())
    }

    /// Moves to `inbox`, `junk` or `trash`, or `restore` to put it back.
    pub fn move_to(&self, message_id: &str, folder: &str) -> Result<()> {
        let path = format!("/messages/{}/move", path_segment(message_id));
        let _: Value = self.client.http.request("POST", &path, Some(&json!({ "folder": folder })), &[])?;
        Ok(())
    }

    pub fn delete(&self, message_id: &str) -> Result<()> {
        let path = format!("/messages/{}", path_segment(message_id));
        let _: Value = self.client.http.request("DELETE", &path, None, &[])?;
        Ok(())
    }

    pub fn empty_trash(&self) -> Result<u64> {
        let result: Value =
            self.client.http.request("POST", "/messages/empty-trash", Some(&json!({})), &[])?;
        Ok(result["deleted"].as_u64().unwrap_or(0))
    }

    /// Sends mail from an address on this account.
    ///
    /// Returns the Message-ID the sending service gave it, and the id of the
    /// copy kept in Sent.
    pub fn send(&self, outgoing: Outgoing<'_>) -> Result<SendResult> {
        let mut body = Map::new();
        body.insert("from".into(), json!(outgoing.from));
        body.insert("to".into(), json!(outgoing.to));
        body.insert("subject".into(), json!(outgoing.subject));
        body.insert("text".into(), json!(outgoing.text));
        if let Some(html) = outgoing.html {
            body.insert("html".into(), json!(html));
        }
        if let Some(name) = outgoing.from_name {
            body.insert("fromName".into(), json!(name));
        }
        if let Some(original) = outgoing.reply_to {
            body.insert("inReplyTo".into(), json!(original.id));
            if !original.message_id.is_empty() {
                body.insert("inReplyToHeader".into(), json!(original.message_id));
            }
        }
        if !outgoing.attachments.is_empty() {
            body.insert("attachments".into(), attachments_body(outgoing.attachments)?);
        }
        let result: Value =
            self.client.http.request("POST", "/messages/send", Some(&Value::Object(body)), &[])?;
        Ok(SendResult {
            message_id: result["messageId"].as_str().unwrap_or_default().to_string(),
            sent_copy_id: result["sentCopyId"].as_str().map(str::to_string),
        })
    }

    /// The next message that arrives and matches, opened.
    ///
    /// Listens on the event stream where it is available, and polls
    /// `address_id` otherwise: a build without the `events` feature cannot open
    /// the stream.
    pub fn wait_for(&self, wanted: WaitFor<'_>) -> Result<Message> {
        let deadline = Instant::now() + wanted.timeout;

        if let Some(found) = self.wait_on_stream(&wanted, deadline)? {
            return Ok(found);
        }
        if Instant::now() >= deadline {
            return Err(Error::api(0, "timeout", "No matching mail arrived in time."));
        }
        self.wait_by_polling(&wanted, deadline)
    }

    fn matches(&self, wanted: &WaitFor<'_>, message: &Message) -> bool {
        if wanted.address_id.is_some_and(|id| message.address_id != id) {
            return false;
        }
        if let Some(from) = wanted.from {
            let haystack = format!("{} {}", message.from_name, message.from_address).to_lowercase();
            if !haystack.contains(&from.to_lowercase()) {
                return false;
            }
        }
        if let Some(subject) = wanted.subject {
            if !message.subject.to_lowercase().contains(&subject.to_lowercase()) {
                return false;
            }
        }
        true
    }

    /// Watches the event stream until the deadline, or gives up early.
    ///
    /// `Ok(None)` means "not on the stream": either it was never available, or
    /// the server ended it for good, in which case the caller falls back to
    /// polling rather than failing. Only the deadline is fatal.
    fn wait_on_stream(&self, wanted: &WaitFor<'_>, deadline: Instant) -> Result<Option<Message>> {
        let Ok(stream) = self.client.events().stream() else { return Ok(None) };

        // Connecting is retried in the background forever, so a stream that
        // cannot open is indistinguishable from a quiet one. Give it a few
        // seconds and then go and poll instead.
        let opening = wanted.stream_open.min(deadline.saturating_duration_since(Instant::now()));
        if !stream.wait_until_open(opening) || stream.ended() {
            return Ok(None);
        }

        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Ok(None);
            }
            let Some(event) = stream.next_event(Some(remaining)) else {
                // The deadline, or a stream that ended and will not come back.
                return Ok(None);
            };
            if event.event_type != "message.received" {
                continue;
            }
            if let Some(id) = wanted.address_id {
                if event.payload.get("inboxId").and_then(Value::as_str) != Some(id) {
                    continue;
                }
            }
            let message_id = event.payload.get("messageId").and_then(Value::as_str).unwrap_or_default();
            match self.get(message_id) {
                Ok(message) if self.matches(wanted, &message) => return Ok(Some(message)),
                // A message that would not fetch is not a reason to give up on
                // the wait; polling is the documented fallback.
                Ok(_) | Err(_) => continue,
            }
        }
    }

    fn wait_by_polling(&self, wanted: &WaitFor<'_>, deadline: Instant) -> Result<Message> {
        let Some(address_id) = wanted.address_id else {
            return Err(Error::Unsupported(
                "The event stream is not available here. Pass address_id to wait by polling instead.".into(),
            ));
        };

        // Only what is newer than the newest seen: each message read is
        // metered, and asking for the page again every few seconds spent a
        // small plan's hourly reads in minutes while nothing arrived.
        let mut newest: Option<String> = self
            .list(address_id, None, Some(50), None)?
            .messages
            .first()
            .map(|m| format!("{}~{}", m.received_at, m.id));
        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Err(Error::api(0, "timeout", "No matching mail arrived in time."));
            }
            std::thread::sleep(wanted.poll_every.min(remaining));
            let mut query = vec![
                ("inboxIds", address_id.to_string()),
                ("folder", "inbox".to_string()),
                ("limit", "50".to_string()),
            ];
            if let Some(marker) = &newest {
                query.push(("newer", marker.clone()));
            }
            let result: Value = self.client.http.request("GET", "/messages", None, &query)?;
            let arrived: Vec<Message> = result["messages"]
                .as_array()
                .map(|items| items.iter().map(|item| to_message(self.client.keys.as_ref(), item)).collect())
                .unwrap_or_default();
            let Some(top) = arrived.first() else { continue };
            newest = Some(format!("{}~{}", top.received_at, top.id));
            // Oldest first, so the first match is the first to arrive.
            if let Some(found) = arrived.into_iter().rev().find(|m| self.matches(wanted, m)) {
                return Ok(found);
            }
        }
    }
}

/// Paired devices and AI agents.
pub struct Devices<'a> {
    pub(crate) client: &'a Mailcycle,
}

impl Devices<'_> {
    pub(crate) fn to_device(&self, wire: &Value) -> Device {
        let id = wire["id"].as_str().unwrap_or_default().to_string();
        let mut profile = Value::Null;
        if let (Some(keys), true) = (self.client.keys.as_ref(), is_sealed_box(wire.get("profile"))) {
            if let Ok(box_) = serde_json::from_value::<SealedBox>(wire["profile"].clone()) {
                profile = open_vault_record(keys.vault_key(), "worker", &id, &box_).unwrap_or(Value::Null);
            }
        }
        Device {
            id,
            platform: wire["platform"].as_str().unwrap_or_default().to_string(),
            kind: wire["kind"].as_str().unwrap_or("device").to_string(),
            send_mode: wire["sendMode"].as_str().unwrap_or("full").to_string(),
            status: wire["status"].as_str().unwrap_or_default().to_string(),
            created_at: wire["createdAt"].as_str().unwrap_or_default().to_string(),
            last_active_at: wire["lastActiveAt"].as_str().map(str::to_string),
            paused_at: wire["pausedAt"].as_str().map(str::to_string),
            name: profile.get("name").and_then(Value::as_str).map(str::to_string),
            tags: profile
                .get("tags")
                .and_then(Value::as_array)
                .map(|items| items.iter().filter_map(Value::as_str).map(str::to_string).collect())
                .unwrap_or_default(),
        }
    }

    pub fn list(&self) -> Result<Vec<Device>> {
        let mut out = Vec::new();
        let mut cursor: Option<String> = None;
        loop {
            let mut query = vec![("limit", "200".to_string())];
            if let Some(value) = &cursor {
                query.push(("cursor", value.clone()));
            }
            let page: Value = self.client.http.request("GET", "/workers", None, &query)?;
            if let Some(items) = page["workers"].as_array() {
                out.extend(items.iter().map(|item| self.to_device(item)));
            }
            match page["nextCursor"].as_str() {
                Some(next) => cursor = Some(next.to_string()),
                None => return Ok(out),
            }
        }
    }

    pub fn get(&self, device_id: &str) -> Result<Device> {
        let path = format!("/workers/{}", path_segment(device_id));
        let result: Value = self.client.http.request("GET", &path, None, &[])?;
        Ok(self.to_device(&result["worker"]))
    }
}

/// Domains the account can create addresses on.
pub struct Domains<'a> {
    client: &'a Mailcycle,
}

impl Domains<'_> {
    pub fn list(&self) -> Result<Vec<Domain>> {
        let result: Value = self.client.http.request("GET", "/domains", None, &[])?;
        Ok(serde_json::from_value(result["domains"].clone()).unwrap_or_default())
    }
}

/// The live event stream.
pub struct Events<'a> {
    client: &'a Mailcycle,
}

impl Events<'_> {
    /// Every account event as it happens.
    ///
    /// Sessions on any plan; API keys on Operator and up.
    pub fn stream(&self) -> Result<EventStream> {
        self.stream_with(Hooks::default())
    }

    pub fn stream_with(&self, hooks: Hooks) -> Result<EventStream> {
        let token = self.client.http.token().ok_or_else(|| Error::Unsupported("Sign in first.".into()))?;
        EventStream::open(self.client.http.base_url(), token, hooks)
    }
}