pidge-client 1.5.0

Microsoft 365 / Graph client and OAuth flows for the pidge CLI
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
//! Microsoft Graph API client.

pub mod batch;
mod calendars;
pub mod delta;
pub mod events;
mod mail;
mod me;
mod people;

pub use calendars::list_calendars;
pub use events::{
    EventsPage, NewEvent, ProposedTime, RsvpKind, cancel_event, create_event, delete_event,
    get_event, list_calendar_view, list_events_at, move_event_to_calendar, move_time, rsvp_event,
    update_event,
};
pub use mail::{
    InboxPage, MailFolder, Outgoing, add_attachment, create_child_folder, create_draft,
    create_forward_draft, create_mail_folder, create_reply_all_draft, create_reply_draft,
    delete_attachment, delete_mail_folder, delete_message, fetch_message_headers, forward_message,
    get_attachment_bytes, get_categories, get_message, list_attachments, list_child_folders,
    list_drafts, list_folder_messages, list_inbox, list_mail_folders, list_messages_at, mark_read,
    mark_unread, move_message, reply_all_message, reply_message, search_folder_messages,
    search_messages, send_draft, send_mail, set_categories, set_flag, unsubscribe_one_click,
    update_draft, update_draft_recipients,
};
pub use me::{Me, get_me};
pub use people::{Person, list_people};

use crate::auth::AuthClient;
use crate::auth::config;
use crate::error::ClientError;
use pidge_core::Message;

/// Maximum attempts for a single Graph request (1 initial + 3 retries).
const MAX_ATTEMPTS: u32 = 4;

/// Statuses worth retrying: throttling and transient gateway failures.
fn is_transient(status: reqwest::StatusCode) -> bool {
    matches!(status.as_u16(), 429 | 503 | 504)
}

/// Send a Graph request with retry/backoff.
///
/// Honors `Retry-After` (seconds) on 429/503/504; otherwise backs off
/// exponentially (1s·2^attempt) with 0–250 ms jitter. After the attempts are
/// exhausted a throttling status becomes [`ClientError::Throttled`] so
/// callers (and agents, via exit code 5) can distinguish it. All other
/// responses (success or error) are returned for the caller to interpret.
///
/// The request must be clonable (all pidge requests carry buffered JSON/text
/// bodies); a non-clonable request is sent once without retry.
pub(crate) async fn send_with_retry(
    req: reqwest::RequestBuilder,
) -> Result<reqwest::Response, ClientError> {
    let mut attempt: u32 = 0;
    loop {
        let this_try = match req.try_clone() {
            Some(clone) => clone,
            None => return Ok(req.send().await?),
        };
        let resp = this_try.send().await?;
        let status = resp.status();
        if !is_transient(status) {
            return Ok(resp);
        }
        let retry_after = resp
            .headers()
            .get(reqwest::header::RETRY_AFTER)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse::<u64>().ok());
        attempt += 1;
        if attempt >= MAX_ATTEMPTS {
            return Err(ClientError::Throttled { retry_after });
        }
        let backoff = retry_after
            .map(std::time::Duration::from_secs)
            .unwrap_or_else(|| {
                let jitter = std::time::Duration::from_millis(u64::from(attempt) * 83 % 250);
                std::time::Duration::from_secs(1u64 << attempt.min(4)) / 2 + jitter
            });
        tracing::debug!(
            status = status.as_u16(),
            attempt,
            ?backoff,
            "retrying Graph request"
        );
        tokio::time::sleep(backoff).await;
    }
}

/// Refuses a continuation link (`@odata.nextLink`) that doesn't lead back to
/// Microsoft Graph, so a forged or corrupted link can never carry the bearer
/// token elsewhere. The origin (scheme, host, port) must be
/// `https://graph.microsoft.com`'s or, for a client built with
/// [`GraphClient::for_test`], that of its `base_url`.
pub(crate) fn check_continuation(url: &str, base_url: &str) -> Result<(), ClientError> {
    let origin = |u: &str| url::Url::parse(u).ok().map(|u| u.origin());
    let allowed = origin(url).is_some_and(|o| {
        o.is_tuple()
            && (Some(&o) == origin(config::GRAPH_BASE).as_ref()
                || Some(&o) == origin(base_url).as_ref())
    });
    if allowed {
        Ok(())
    } else {
        Err(ClientError::Graph {
            status: 400,
            message: "refusing to follow a continuation link off graph.microsoft.com".into(),
        })
    }
}

/// Stateful Microsoft Graph client. Holds an AuthClient and a shared HTTP client.
pub struct GraphClient {
    auth: AuthClient,
    http: reqwest::Client,
    base_url: String,
    /// Test clients may POST one-click unsubscribes to a loopback mock.
    one_click: mail::OneClickPolicy,
}

impl GraphClient {
    pub fn new(auth: AuthClient) -> Result<Self, ClientError> {
        Ok(Self {
            auth,
            http: reqwest::Client::builder()
                .user_agent(format!("pidge/{}", env!("CARGO_PKG_VERSION")))
                .build()?,
            base_url: config::GRAPH_BASE.to_string(),
            one_click: mail::OneClickPolicy::PublicOnly,
        })
    }

    pub fn for_test(auth: AuthClient, base_url: impl Into<String>) -> Self {
        Self {
            auth,
            http: reqwest::Client::new(),
            base_url: base_url.into(),
            one_click: mail::OneClickPolicy::AllowLoopback,
        }
    }

    pub fn auth(&self) -> &AuthClient {
        &self.auth
    }

    /// GET /me. Used right after sign-in to learn the user's email.
    pub async fn me(&self, access_token: &str) -> Result<Me, ClientError> {
        get_me(&self.http, &self.base_url, access_token).await
    }

    /// GET /me/mailFolders/inbox/messages for a given account email.
    /// Acquires/refreshes a token transparently via `AuthClient::get_valid_token`.
    pub async fn list_inbox(
        &self,
        account: &str,
        limit: usize,
        skip: usize,
        unread_only: bool,
    ) -> Result<InboxPage, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        list_inbox(
            &self.http,
            &self.base_url,
            &token,
            account,
            limit,
            skip,
            unread_only,
        )
        .await
    }

    /// GET /me/mailFolders/{folder_id}/messages: list a custom folder.
    pub async fn list_folder(
        &self,
        account: &str,
        folder_id: &str,
        limit: usize,
        skip: usize,
        unread_only: bool,
    ) -> Result<InboxPage, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        list_folder_messages(
            &self.http,
            &self.base_url,
            &token,
            account,
            folder_id,
            limit,
            skip,
            unread_only,
        )
        .await
    }

    /// GET /me/messages with `$search="<query>"` for a given account.
    /// Bootstrap a mail delta stream for a folder: (current messages, deltaLink).
    pub async fn mail_delta_bootstrap(
        &self,
        account: &str,
        folder: &str,
    ) -> Result<(Vec<Message>, String), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        delta::mail_delta_bootstrap(&self.http, &self.base_url, &token, account, folder).await
    }

    /// Poll a mail deltaLink for changes.
    pub async fn mail_delta(
        &self,
        account: &str,
        delta_link: &str,
    ) -> Result<(Vec<delta::MailDeltaEvent>, String), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        delta::mail_delta(&self.http, &token, account, delta_link).await
    }

    /// Bootstrap a calendar delta stream over a window: (current events, deltaLink).
    pub async fn calendar_delta_bootstrap(
        &self,
        account: &str,
        start: chrono::DateTime<chrono::Utc>,
        end: chrono::DateTime<chrono::Utc>,
    ) -> Result<(Vec<pidge_core::Event>, String), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        delta::calendar_delta_bootstrap(&self.http, &self.base_url, &token, account, start, end)
            .await
    }

    /// Poll a calendar deltaLink for changes.
    pub async fn calendar_delta(
        &self,
        account: &str,
        delta_link: &str,
    ) -> Result<(Vec<delta::CalendarDeltaEvent>, String), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        delta::calendar_delta(&self.http, &token, account, delta_link).await
    }

    /// Run a set of batch sub-requests for one account.
    pub async fn batch_all(
        &self,
        account: &str,
        requests: Vec<batch::BatchRequest>,
    ) -> Result<Vec<batch::BatchResponse>, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        batch::batch_all(&self.http, &self.base_url, &token, requests).await
    }

    /// Fetch every message in a conversation (thread), oldest first.
    pub async fn list_conversation(
        &self,
        account: &str,
        conversation_id: &str,
    ) -> Result<Vec<Message>, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::list_conversation(&self.http, &self.base_url, &token, account, conversation_id).await
    }

    /// Fetch a page of messages at an absolute Graph continuation URL.
    pub async fn list_messages_at(
        &self,
        account: &str,
        url: &str,
    ) -> Result<InboxPage, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        list_messages_at(&self.http, &self.base_url, &token, account, url).await
    }

    pub async fn search_messages(
        &self,
        account: &str,
        query: &str,
        limit: usize,
    ) -> Result<InboxPage, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        search_messages(&self.http, &self.base_url, &token, account, query, limit).await
    }

    /// `$search` within one folder (well-known name or folder id).
    pub async fn search_folder(
        &self,
        account: &str,
        folder: &str,
        query: &str,
        limit: usize,
    ) -> Result<InboxPage, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        search_folder_messages(
            &self.http,
            &self.base_url,
            &token,
            account,
            folder,
            query,
            limit,
        )
        .await
    }

    /// PATCH /me/messages/{id} with `{ "isRead": false }`.
    pub async fn mark_unread(&self, account: &str, message_id: &str) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::mark_unread(&self.http, &self.base_url, &token, message_id).await
    }

    /// PATCH /me/messages/{id} with `{ "flag": { "flagStatus": "flagged"|"notFlagged" } }`.
    pub async fn set_flag(
        &self,
        account: &str,
        message_id: &str,
        flagged: bool,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::set_flag(&self.http, &self.base_url, &token, message_id, flagged).await
    }

    /// GET /me/messages/{id}?$select=categories.
    pub async fn get_categories(
        &self,
        account: &str,
        message_id: &str,
    ) -> Result<Vec<String>, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::get_categories(&self.http, &self.base_url, &token, message_id).await
    }

    /// PATCH /me/messages/{id} categories.
    pub async fn set_categories(
        &self,
        account: &str,
        message_id: &str,
        categories: &[String],
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::set_categories(&self.http, &self.base_url, &token, message_id, categories).await
    }

    /// POST /me/messages/{id}/move: move to a folder by ID or well-known name.
    pub async fn move_message(
        &self,
        account: &str,
        message_id: &str,
        destination: &str,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::move_message(&self.http, &self.base_url, &token, message_id, destination).await
    }

    /// GET /me/mailFolders: list the account's top-level folders.
    pub async fn list_mail_folders(&self, account: &str) -> Result<Vec<MailFolder>, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::list_mail_folders(&self.http, &self.base_url, &token).await
    }

    /// POST /me/mailFolders: create a top-level folder, returning it.
    pub async fn create_mail_folder(
        &self,
        account: &str,
        display_name: &str,
    ) -> Result<MailFolder, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::create_mail_folder(&self.http, &self.base_url, &token, display_name).await
    }

    /// GET /me/mailFolders/{parent_id}/childFolders: list a folder's children.
    pub async fn list_child_folders(
        &self,
        account: &str,
        parent_id: &str,
    ) -> Result<Vec<MailFolder>, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::list_child_folders(&self.http, &self.base_url, &token, parent_id).await
    }

    /// POST /me/mailFolders/{parent_id}/childFolders: create a child folder.
    pub async fn create_child_folder(
        &self,
        account: &str,
        parent_id: &str,
        display_name: &str,
    ) -> Result<MailFolder, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::create_child_folder(&self.http, &self.base_url, &token, parent_id, display_name).await
    }

    /// DELETE /me/mailFolders/{id}: delete a folder (contents move to
    /// Deleted Items).
    pub async fn delete_mail_folder(
        &self,
        account: &str,
        folder_id: &str,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::delete_mail_folder(&self.http, &self.base_url, &token, folder_id).await
    }

    /// POST /me/sendMail: compose-and-send a new message.
    pub async fn send_mail(&self, account: &str, message: &Outgoing) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::send_mail(&self.http, &self.base_url, &token, message).await
    }

    /// POST /me/messages/{id}/reply.
    pub async fn reply_message(
        &self,
        account: &str,
        message_id: &str,
        comment: &str,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::reply_message(&self.http, &self.base_url, &token, message_id, comment).await
    }

    /// POST /me/messages/{id}/replyAll.
    pub async fn reply_all_message(
        &self,
        account: &str,
        message_id: &str,
        comment: &str,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::reply_all_message(&self.http, &self.base_url, &token, message_id, comment).await
    }

    /// POST /me/messages/{id}/forward.
    pub async fn forward_message(
        &self,
        account: &str,
        message_id: &str,
        to: &[String],
        comment: &str,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::forward_message(&self.http, &self.base_url, &token, message_id, to, comment).await
    }

    /// GET /me/mailFolders/drafts/messages.
    pub async fn list_drafts(
        &self,
        account: &str,
        limit: usize,
        skip: usize,
    ) -> Result<InboxPage, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::list_drafts(&self.http, &self.base_url, &token, account, limit, skip).await
    }

    /// POST /me/messages: create a draft, returning its new message ID.
    pub async fn create_draft(
        &self,
        account: &str,
        message: &Outgoing,
    ) -> Result<String, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::create_draft(&self.http, &self.base_url, &token, message).await
    }

    /// POST /me/messages/{id}/createReply.
    pub async fn create_reply_draft(
        &self,
        account: &str,
        message_id: &str,
        comment: &str,
    ) -> Result<String, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::create_reply_draft(&self.http, &self.base_url, &token, message_id, comment).await
    }

    /// POST /me/messages/{id}/createReplyAll.
    pub async fn create_reply_all_draft(
        &self,
        account: &str,
        message_id: &str,
        comment: &str,
    ) -> Result<String, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::create_reply_all_draft(&self.http, &self.base_url, &token, message_id, comment).await
    }

    /// POST /me/messages/{id}/createForward.
    pub async fn create_forward_draft(
        &self,
        account: &str,
        message_id: &str,
        to: &[String],
        comment: &str,
    ) -> Result<String, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::create_forward_draft(&self.http, &self.base_url, &token, message_id, to, comment)
            .await
    }

    /// POST /me/messages/{id}/send: send an existing draft.
    pub async fn send_draft(&self, account: &str, message_id: &str) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::send_draft(&self.http, &self.base_url, &token, message_id).await
    }

    /// PATCH /me/messages/{id}: overwrite a draft's editable fields.
    pub async fn update_draft(
        &self,
        account: &str,
        message_id: &str,
        message: &Outgoing,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::update_draft(&self.http, &self.base_url, &token, message_id, message).await
    }

    /// PATCH /me/messages/{id}: replace only the given recipient lists.
    pub async fn update_draft_recipients(
        &self,
        account: &str,
        message_id: &str,
        to: Option<&[String]>,
        cc: Option<&[String]>,
        bcc: Option<&[String]>,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::update_draft_recipients(&self.http, &self.base_url, &token, message_id, to, cc, bcc)
            .await
    }

    /// DELETE /me/messages/{id}: moves to Deleted Items. Works for both
    /// drafts and inbox messages.
    pub async fn delete_message(&self, account: &str, message_id: &str) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::delete_message(&self.http, &self.base_url, &token, message_id).await
    }

    /// POST /me/messages/{id}/attachments: attach a file (simple upload).
    pub async fn add_attachment(
        &self,
        account: &str,
        message_id: &str,
        name: &str,
        content_type: &str,
        bytes: &[u8],
    ) -> Result<String, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::add_attachment(
            &self.http,
            &self.base_url,
            &token,
            message_id,
            name,
            content_type,
            bytes,
        )
        .await
    }

    /// DELETE /me/messages/{id}/attachments/{att_id}.
    pub async fn delete_attachment(
        &self,
        account: &str,
        message_id: &str,
        attachment_id: &str,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::delete_attachment(
            &self.http,
            &self.base_url,
            &token,
            message_id,
            attachment_id,
        )
        .await
    }

    /// GET /me/messages/{id} for a given account email.
    pub async fn get_message(
        &self,
        account: &str,
        message_id: &str,
    ) -> Result<pidge_core::FullMessage, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::get_message(&self.http, &self.base_url, &token, account, message_id).await
    }

    /// GET /me/messages/{id}?$select=internetMessageHeaders.
    pub async fn fetch_message_headers(
        &self,
        account: &str,
        message_id: &str,
    ) -> Result<Vec<(String, String)>, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::fetch_message_headers(&self.http, &self.base_url, &token, message_id).await
    }

    /// GET /me/messages/{id}/attachments.
    pub async fn list_attachments(
        &self,
        account: &str,
        message_id: &str,
    ) -> Result<Vec<pidge_core::Attachment>, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::list_attachments(&self.http, &self.base_url, &token, message_id).await
    }

    /// POST a `List-Unsubscribe=One-Click` form body (RFC 8058) to a
    /// third-party unsubscribe URL. No bearer token; the URL belongs to
    /// the sender, not Microsoft.
    ///
    /// Only https to a public host; see [`mail::unsubscribe_one_click`].
    /// A [`Self::for_test`] client also reaches a loopback mock server.
    pub async fn unsubscribe_one_click(&self, url: &str) -> Result<(), ClientError> {
        mail::post_one_click(url, self.one_click).await
    }

    /// GET /me/people?$top={top}&$select=displayName,scoredEmailAddresses:
    /// Outlook's ranked "people I interact with" list.
    pub async fn list_people(
        &self,
        account: &str,
        top: usize,
    ) -> Result<Vec<people::Person>, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        people::list_people(&self.http, &self.base_url, &token, top).await
    }

    /// GET /me/messages/{id}/attachments/{att_id} returning decoded bytes.
    pub async fn get_attachment_bytes(
        &self,
        account: &str,
        message_id: &str,
        attachment_id: &str,
    ) -> Result<Vec<u8>, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::get_attachment_bytes(
            &self.http,
            &self.base_url,
            &token,
            message_id,
            attachment_id,
        )
        .await
    }

    /// PATCH /me/messages/{id} with isRead: true.
    pub async fn mark_read(&self, account: &str, message_id: &str) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        mail::mark_read(&self.http, &self.base_url, &token, message_id).await
    }

    // -------- Calendar surface --------

    /// GET /me/calendars.
    pub async fn list_calendars(
        &self,
        account: &str,
    ) -> Result<Vec<pidge_core::Calendar>, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        calendars::list_calendars(&self.http, &self.base_url, &token, account).await
    }

    /// GET /me/calendarView (or /me/calendars/{id}/calendarView).
    pub async fn list_calendar_view(
        &self,
        account: &str,
        calendar_id: Option<&str>,
        start: chrono::DateTime<chrono::Utc>,
        end: chrono::DateTime<chrono::Utc>,
        limit: usize,
    ) -> Result<events::EventsPage, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        events::list_calendar_view(
            &self.http,
            &self.base_url,
            &token,
            account,
            calendar_id,
            start,
            end,
            limit,
        )
        .await
    }

    /// Fetch a page of calendar events at an absolute Graph continuation URL.
    pub async fn list_events_at(
        &self,
        account: &str,
        url: &str,
    ) -> Result<EventsPage, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        list_events_at(&self.http, &self.base_url, &token, account, url).await
    }

    /// GET /me/events/{id}.
    pub async fn get_event(
        &self,
        account: &str,
        event_id: &str,
    ) -> Result<pidge_core::Event, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        events::get_event(&self.http, &self.base_url, &token, account, event_id).await
    }

    /// POST /me/calendar/events (or /me/calendars/{id}/events).
    pub async fn create_event(
        &self,
        account: &str,
        calendar_id: Option<&str>,
        new_event: &events::NewEvent,
    ) -> Result<String, ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        events::create_event(&self.http, &self.base_url, &token, calendar_id, new_event).await
    }

    /// PATCH /me/events/{id}: overwrite editable fields.
    pub async fn update_event(
        &self,
        account: &str,
        event_id: &str,
        new_event: &events::NewEvent,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        events::update_event(&self.http, &self.base_url, &token, event_id, new_event).await
    }

    /// PATCH /me/events/{id}: change only start + end.
    pub async fn move_time(
        &self,
        account: &str,
        event_id: &str,
        start: chrono::DateTime<chrono::Utc>,
        end: chrono::DateTime<chrono::Utc>,
        tz: &str,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        events::move_time(&self.http, &self.base_url, &token, event_id, start, end, tz).await
    }

    /// DELETE /me/events/{id}: silent removal.
    pub async fn delete_event(&self, account: &str, event_id: &str) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        events::delete_event(&self.http, &self.base_url, &token, event_id).await
    }

    /// POST /me/events/{id}/cancel: organizer-only.
    pub async fn cancel_event(
        &self,
        account: &str,
        event_id: &str,
        comment: &str,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        events::cancel_event(&self.http, &self.base_url, &token, event_id, comment).await
    }

    /// POST /me/events/{id}/accept | /tentativelyAccept | /decline.
    ///
    /// `proposed` carries a counter-proposed time; Graph only honors it on
    /// `tentativelyAccept` and `decline` (ignored for `Accept`).
    #[allow(clippy::too_many_arguments)]
    pub async fn rsvp_event(
        &self,
        account: &str,
        event_id: &str,
        kind: events::RsvpKind,
        comment: &str,
        send_response: bool,
        proposed: Option<&events::ProposedTime>,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        events::rsvp_event(
            &self.http,
            &self.base_url,
            &token,
            event_id,
            kind,
            comment,
            send_response,
            proposed,
        )
        .await
    }

    /// PATCH /me/events/{id} with `calendar@odata.bind`: move between calendars.
    pub async fn move_event_to_calendar(
        &self,
        account: &str,
        event_id: &str,
        destination_calendar_id: &str,
    ) -> Result<(), ClientError> {
        let token = self.auth.get_valid_token(account).await?;
        events::move_event_to_calendar(
            &self.http,
            &self.base_url,
            &token,
            event_id,
            destination_calendar_id,
        )
        .await
    }
}

#[cfg(test)]
mod retry_tests {
    use super::*;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};

    /// Responds 429 for the first N requests, then 200.
    struct FlakyResponder {
        failures: std::sync::atomic::AtomicU32,
    }

    impl Respond for FlakyResponder {
        fn respond(&self, _req: &Request) -> ResponseTemplate {
            let n = self
                .failures
                .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
            if n > 0 {
                ResponseTemplate::new(429).insert_header("Retry-After", "0")
            } else {
                ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok": true}))
            }
        }
    }

    #[tokio::test]
    async fn retries_transient_429_until_success() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/thing"))
            .respond_with(FlakyResponder {
                failures: std::sync::atomic::AtomicU32::new(2),
            })
            .expect(3)
            .mount(&server)
            .await;

        let http = reqwest::Client::new();
        let resp = send_with_retry(http.get(format!("{}/thing", server.uri())))
            .await
            .unwrap();
        assert_eq!(resp.status(), 200);
    }

    #[tokio::test]
    async fn persistent_429_becomes_throttled_after_max_attempts() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/thing"))
            .respond_with(ResponseTemplate::new(429).insert_header("Retry-After", "0"))
            .expect(4)
            .mount(&server)
            .await;

        let http = reqwest::Client::new();
        let err = send_with_retry(http.get(format!("{}/thing", server.uri())))
            .await
            .unwrap_err();
        match err {
            ClientError::Throttled { retry_after } => assert_eq!(retry_after, Some(0)),
            other => panic!("expected Throttled, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn non_transient_errors_pass_through_without_retry() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/thing"))
            .respond_with(ResponseTemplate::new(400).set_body_string("bad"))
            .expect(1)
            .mount(&server)
            .await;

        let http = reqwest::Client::new();
        let resp = send_with_retry(http.get(format!("{}/thing", server.uri())))
            .await
            .unwrap();
        assert_eq!(resp.status(), 400);
    }
}

#[cfg(test)]
mod continuation_tests {
    use super::*;
    use wiremock::matchers::method;
    use wiremock::{Mock, MockServer, ResponseTemplate};

    const REFUSAL: &str = "refusing to follow a continuation link off graph.microsoft.com";

    fn refused(r: Result<(), ClientError>) -> bool {
        matches!(r, Err(ClientError::Graph { status: 400, ref message }) if message == REFUSAL)
    }

    #[test]
    fn graph_links_are_followed_and_others_refused_in_production() {
        let base = config::GRAPH_BASE;
        assert!(
            check_continuation(
                "https://graph.microsoft.com/v1.0/me/messages?$skiptoken=x",
                base
            )
            .is_ok()
        );
        for url in [
            "https://evil.example.com/v1.0/me/messages",
            "http://graph.microsoft.com/v1.0/me/messages",
            "https://graph.microsoft.com.evil.example.com/v1.0",
            "https://graph.microsoft.com:8443/v1.0",
            "not a url",
        ] {
            assert!(refused(check_continuation(url, base)), "{url}");
        }
    }

    #[test]
    fn a_test_base_url_allows_its_own_origin_only() {
        let base = "http://127.0.0.1:4000/v1.0";
        assert!(check_continuation("http://127.0.0.1:4000/v1.0/page-2", base).is_ok());
        assert!(refused(check_continuation(
            "http://127.0.0.1:4001/v1.0/page-2",
            base
        )));
    }

    /// The link points at a second server (same host, other port): both
    /// helpers refuse it without sending it anything, bearer token included.
    #[tokio::test]
    async fn off_graph_next_links_are_refused_without_a_request() {
        let graph = MockServer::start().await;
        let other = MockServer::start().await;
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "value": []
            })))
            .expect(0)
            .mount(&other)
            .await;
        let http = reqwest::Client::new();
        let base = format!("{}/v1.0", graph.uri());
        let link = format!("{}/v1.0/page-2", other.uri());

        let Err(err) = events::list_events_at(&http, &base, "tok", "a@b.se", &link).await else {
            panic!("list_events_at followed an off-Graph link");
        };
        assert!(refused(Err(err)));
        let Err(err) = mail::list_messages_at(&http, &base, "tok", "a@b.se", &link).await else {
            panic!("list_messages_at followed an off-Graph link");
        };
        assert!(refused(Err(err)));
        assert!(other.received_requests().await.unwrap().is_empty());
    }
}