vta-cli-common 0.73.0

Shared CLI command handlers and rendering helpers for VTA CLIs
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
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
//! `pnm calendar connectors …` — calendars at Google, Microsoft or a CalDAV server
//! (iCloud, Fastmail, Nextcloud) the VTA writes your events into and reads busy time from,
//! or a private iCalendar address it reads busy time from alone
//! (`vta/calendar/connectors/*/0.3`, VTI-CAL-100 – 132). `pnm calendar connect` is the guided
//! way in ([`super::calendar_connect`]).
//!
//! A connector is the principal's, not a context's: one sign-in serves every trust context it
//! is given, each written into a calendar of its own at the provider (VTI-CAL-127). So
//! `connectors list` answers each once, across contexts, and `connectors contexts add|remove|set`
//! changes which contexts one serves. Against a VTA that serves only 0.2 these fall back to it
//! where the request means the same there.
//!
//! The connection lives in the VTA, never here: for an OAuth provider this command opens a
//! one-shot listener on a loopback port (RFC 8252 §7.3), prints the provider's address to
//! open in a browser, and relays the code the provider redirects back with to the VTA — the
//! VTA alone redeems it, with a PKCE verifier only it holds (VTI-CAL-101, 102). For a
//! Microsoft device code it shows the code the VTA was given and waits while the VTA polls
//! for the grant itself (VTI-CAL-120). A CalDAV password or an iCalendar address is sealed in
//! this process to a single-use wrapping key from the VTA and never sent in the clear
//! (VTI-CAL-106, 124).

use std::io::{IsTerminal, Read};

use serde_json::{Value, json};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use vta_sdk::error::VtaError;
use vta_sdk::prelude::*;
use vta_sdk::trust_tasks as tt;

use crate::render::{BOLD, CYAN, DIM, GREEN, RESET, YELLOW, is_json_output, print_json};

type CmdResult = Result<(), Box<dyn std::error::Error>>;

/// How long the loopback listener waits for the provider's redirect: the VTA's
/// authorization request lasts 10 minutes (VTI-CAL-101).
const LISTEN_SECONDS: u64 = 600;

pub(crate) fn local_code(e: &VtaError) -> Option<&str> {
    e.rejection_code()
        .map(|c| c.rsplit_once(':').map_or(c, |(_, l)| l))
}

/// The command that fixes a refusal, when the operator's intent maps to one.
pub(crate) fn fix_for(code: &str, id: Option<&str>) -> Option<String> {
    let id = id.unwrap_or("<connector-id>");
    Some(match code {
        "providerUnavailable" => "This VTA does not offer that provider: its operator has not \
             registered an OAuth client for it, or turned it off ([calendar.connectors] in the \
             VTA's config; docs/02-vta/calendar.md). What it offers, and the operator's exact \
             fix for what it does not:\n    \
             pnm calendar connect --help-operator\nAn iCloud calendar needs no registration:\n    \
             pnm calendar connect --provider apple --username <apple-id> --context <id>"
            .to_string(),
        "flowUnavailable" => "This VTA cannot take a grant from that provider that way: Google \
             has no device code for calendars, and a Microsoft device code needs a client whose \
             app registration allows public client flows. Sign in through the browser instead:\n    \
             pnm calendar connect --provider microsoft --flow authorization-code --context <id>"
            .to_string(),
        "addressRejected" => "That address did not answer with a calendar. Copy the calendar's \
             private address in iCal format again (Google: Settings → your calendar → \
             \"Secret address in iCal format\"; Outlook: Settings → Calendar → Shared calendars \
             → Publish a calendar → ICS) and:\n    \
             pnm calendar connect --provider ics-busy --context <id>"
            .to_string(),
        "endpointInvalid" => "The address must be HTTPS at a public host this VTA may reach \
             (a webcal:// address is read as https://)."
            .to_string(),
        "authorizationDenied" => format!(
            "The provider did not grant access. If your organisation forbids signing in with a \
             code, sign in through the browser:\n    \
             pnm calendar connectors update {id} --reauthorize"
        ),
        "limitReached" => "Remove a connector you no longer use first:\n    \
             pnm calendar connectors list\n    pnm calendar connectors remove <connector-id>"
            .to_string(),
        "redirectInvalid" => "The redirect address must be one the operator registered, or a \
             loopback address; omit --redirect-uri to let this command listen on one."
            .to_string(),
        "authorizationExpired" | "stateMismatch" => format!(
            "Ask the provider again:\n    pnm calendar connectors update {id} --reauthorize"
        ),
        "credentialRejected" => format!(
            "The server refused the password. Make a new app-specific password and:\n    \
             pnm calendar connectors update {id} --password"
        ),
        "removing" => "The connector is being removed; nothing more can change on it.".to_string(),
        "notFound" => "List the connectors you may see — one serving several contexts needs \
             standing in each:\n    pnm calendar connectors list"
            .to_string(),
        "permissionDenied" => "A context added to a connector needs your standing in it \
             (VTI-CAL-128): see the contexts you have with\n    pnm contexts list"
            .to_string(),
        _ => return None,
    })
}

/// Send `newest`; where the VTA does not serve it and `older` means the same request there,
/// send that instead. Without `older`, a VTA too old for the request says so, with the fix.
pub(crate) async fn call_newest(
    client: &VtaClient,
    newest: &str,
    older: Option<&str>,
    payload: Value,
    id: Option<&str>,
) -> Result<Value, Box<dyn std::error::Error>> {
    match client
        .dispatch_trust_task(newest, payload.clone(), 30)
        .await
    {
        Ok(v) => Ok(v),
        Err(VtaError::UnsupportedTaskType { .. }) => match older {
            Some(o) => call(client, o, payload, id).await,
            None => Err(format!(
                "this VTA does not serve `{newest}`, which a calendar per context or a calendar \
                 name needs (VTI-CAL-127): ask its operator to upgrade it, or leave the \
                 connector to one context."
            )
            .into()),
        },
        Err(e) => match local_code(&e).and_then(|c| fix_for(c, id)) {
            Some(fix) => Err(format!("{e}\n  {fix}").into()),
            None => Err(Box::new(e)),
        },
    }
}

/// Whether a 0.3 request means the same at 0.2: no calendar names (0.2 has none).
pub(crate) fn same_at_v2(req: &Value) -> bool {
    !req["coverage"]
        .as_array()
        .into_iter()
        .flatten()
        .any(|c| c.get("calendarName").is_some())
}

pub(crate) async fn call(
    client: &VtaClient,
    uri: &str,
    payload: Value,
    id: Option<&str>,
) -> Result<Value, Box<dyn std::error::Error>> {
    match client.dispatch_trust_task(uri, payload, 30).await {
        Ok(v) => Ok(v),
        Err(e) => match local_code(&e).and_then(|c| fix_for(c, id)) {
            Some(fix) => Err(format!("{e}\n  {fix}").into()),
            None => Err(Box::new(e)),
        },
    }
}

/// What `create` was asked.
#[derive(Debug, Default)]
pub struct ConnectorCreate {
    pub context: String,
    pub provider: String,
    pub label: String,
    /// `busy`, `titles` or `off`, for `context`.
    pub write: String,
    /// Read busy time back.
    pub busy: bool,
    /// Contexts the busy time read counts in; default the connector's own.
    pub busy_contexts: Vec<String>,
    /// Calendars at the provider to read busy time from; default the primary (or all).
    pub busy_calendars: Vec<String>,
    /// An OAuth redirect the client handles itself; default a loopback listener here.
    pub redirect_uri: Option<String>,
    /// CalDAV.
    pub endpoint: Option<String>,
    pub username: Option<String>,
    /// Microsoft: sign in with a device code the VTA polls for, rather than through a
    /// redirect to this machine (VTI-CAL-120).
    pub device_code: bool,
    /// The name of `context`'s calendar at the provider; default `VTI — <context>`
    /// (VTI-CAL-127).
    pub calendar_name: Option<String>,
}

/// What `update` was asked.
#[derive(Debug, Default)]
pub struct ConnectorUpdate {
    pub label: Option<String>,
    /// `busy`, `titles` or `off`, for the connector's own context.
    pub write: Option<String>,
    pub busy: Option<bool>,
    pub busy_contexts: Vec<String>,
    pub reauthorize: bool,
    pub redirect_uri: Option<String>,
    /// A new app-specific password for a CalDAV connector, for this server and account
    /// (the VTA never answers them, VTI-CAL-106, so they are given again).
    pub password_for: Option<(String, String)>,
    /// With `reauthorize`: by a device code (Microsoft) rather than a redirect.
    pub device_code: bool,
    /// A new private iCalendar address for an `icsBusy` connector (VTI-CAL-124).
    pub ics_address: bool,
}

pub(crate) fn busy_choice(on: bool, contexts: &[String], calendars: &[String]) -> Value {
    let mut b = json!({ "enabled": on });
    if !contexts.is_empty() {
        b["contextIds"] = json!(contexts);
    }
    if !calendars.is_empty() {
        b["calendars"] = json!(calendars);
    }
    b
}

/// Read a secret without echo, or from stdin when piped.
pub(crate) fn read_secret(
    prompt: &str,
) -> Result<zeroize::Zeroizing<String>, Box<dyn std::error::Error>> {
    let s = zeroize::Zeroizing::new(if std::io::stdin().is_terminal() {
        dialoguer::Password::new().with_prompt(prompt).interact()?
    } else {
        let mut s = String::new();
        std::io::stdin().read_to_string(&mut s)?;
        s.trim_end_matches(['\r', '\n']).to_string()
    });
    Ok(s)
}

/// Read a password without echo (or from stdin when piped), and seal it to a fresh wrapping
/// key from the VTA, naming the server and account inside the seal.
async fn sealed_password(
    client: &VtaClient,
    endpoint: &str,
    username: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    let password = read_secret(&format!("App-specific password for {username}"))?;
    seal_password(client, endpoint, username, &password).await
}

/// Seal a CalDAV password to a fresh wrapping key from the VTA (VTI-CAL-106).
pub(crate) async fn seal_password(
    client: &VtaClient,
    endpoint: &str,
    username: &str,
    password: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    if password.is_empty() {
        return Err("no password was given".into());
    }
    let wrapping = client.get_wrapping_key().await?;
    Ok(vta_sdk::sealed_transfer::seal_calendar_credential(
        &wrapping.wrapping_key,
        endpoint,
        username,
        password,
    )
    .await?)
}

/// Seal a private iCalendar address to a fresh wrapping key from the VTA: the address reads
/// the calendar, so it never leaves this process in the clear (VTI-CAL-124).
pub(crate) async fn seal_ics_address(
    client: &VtaClient,
    address: &str,
) -> Result<String, Box<dyn std::error::Error>> {
    let address = address.trim();
    let lower = address.to_ascii_lowercase();
    if !(lower.starts_with("https://") || lower.starts_with("webcal://")) {
        return Err("a private calendar address starts with https:// or webcal://".into());
    }
    let wrapping = client.get_wrapping_key().await?;
    Ok(
        vta_sdk::sealed_transfer::seal_calendar_ics_address(&wrapping.wrapping_key, address)
            .await?,
    )
}

/// A one-shot loopback listener for the provider's redirect (RFC 8252 §7.3).
pub(crate) struct Loopback {
    listener: tokio::net::TcpListener,
    pub(crate) redirect_uri: String,
}

impl Loopback {
    pub(crate) async fn bind() -> Result<Self, Box<dyn std::error::Error>> {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
        let port = listener.local_addr()?.port();
        Ok(Self {
            listener,
            redirect_uri: format!("http://127.0.0.1:{port}/callback"),
        })
    }

    /// Wait for the redirect carrying `state`; answer the browser and return the query.
    /// Requests that are not it (a favicon, a stale tab) are answered 404 and ignored.
    async fn wait(self, state: &str) -> Result<Vec<(String, String)>, Box<dyn std::error::Error>> {
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(LISTEN_SECONDS);
        loop {
            let (mut sock, _) = tokio::time::timeout_at(deadline, self.listener.accept())
                .await
                .map_err(|_| "no redirect came back from the provider within 10 minutes")??;
            let mut buf = vec![0u8; 8192];
            let n = tokio::time::timeout(std::time::Duration::from_secs(10), sock.read(&mut buf))
                .await
                .unwrap_or(Ok(0))
                .unwrap_or(0);
            let head = String::from_utf8_lossy(&buf[..n]);
            let target = head
                .lines()
                .next()
                .and_then(|l| l.strip_prefix("GET "))
                .and_then(|l| l.split(' ').next())
                .unwrap_or("");
            let query = target
                .strip_prefix("/callback?")
                .map(|q| {
                    q.split('&')
                        .filter_map(|kv| kv.split_once('='))
                        .map(|(k, v)| (k.to_string(), percent_decode(v)))
                        .collect::<Vec<_>>()
                })
                .unwrap_or_default();
            if !query.iter().any(|(k, v)| k == "state" && v == state) {
                let _ = sock
                    .write_all(
                        b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
                    )
                    .await;
                continue;
            }
            let page = "<!doctype html><meta charset=utf-8><title>VTA</title>\
                        <p>Done. You can close this tab and return to the terminal.";
            let _ = sock
                .write_all(
                    format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\
                         Content-Length: {}\r\nConnection: close\r\n\r\n{page}",
                        page.len()
                    )
                    .as_bytes(),
                )
                .await;
            return Ok(query);
        }
    }
}

fn percent_decode(s: &str) -> String {
    let s = s.replace('+', " ");
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%'
            && i + 2 < bytes.len()
            && let Some(b) = std::str::from_utf8(&bytes[i + 1..i + 3])
                .ok()
                .and_then(|h| u8::from_str_radix(h, 16).ok())
        {
            out.push(b);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Show the device authorization the VTA opened and wait while the VTA polls for the grant
/// (VTI-CAL-120 – 122): read the connector each `checkAfterSeconds` until it leaves
/// `awaitingUser`. Answers the connector as last read.
pub(crate) async fn device_wait(
    client: &VtaClient,
    id: &str,
    device: &Value,
) -> Result<Value, Box<dyn std::error::Error>> {
    let uri = device["verificationUri"].as_str().unwrap_or("?");
    let code = device["userCode"].as_str().unwrap_or("?");
    let every = device["checkAfterSeconds"]
        .as_u64()
        .unwrap_or(5)
        .clamp(1, 300);
    let until = device["expiresAt"]
        .as_str()
        .and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok())
        .map(|t| t.with_timezone(&chrono::Utc));
    if !is_json_output() {
        println!("On any device, open {BOLD}{uri}{RESET} and enter the code:");
        println!();
        println!("    {BOLD}{CYAN}{code}{RESET}");
        println!();
        println!(
            "{DIM}Enter it only at the provider's own address, and only because this terminal \
             is showing it to you: whoever enters it grants their account to this VTA.{RESET}"
        );
        if let Some(t) = until {
            println!(
                "{DIM}Waiting for you to sign in (until {} UTC)…{RESET}",
                t.format("%H:%M")
            );
        }
    }
    loop {
        tokio::time::sleep(std::time::Duration::from_secs(every)).await;
        let shown = show(client, id).await?;
        let c = &shown["connector"];
        if c["state"] != "awaitingUser" {
            return Ok(shown);
        }
        // The VTA closes it at expiry; allow it a couple of polls past that.
        if until.is_some_and(|t| chrono::Utc::now() > t + chrono::Duration::seconds(30)) {
            return Ok(shown);
        }
    }
}

/// What a device authorization opened at `opened` (the connector's `updatedAt` in the answer
/// that opened it) ended as: connected, or the refusal and its fix. A renewal refused leaves
/// the connector active on its earlier grant (VTI-CAL-122), so a fault since `opened` is what
/// says it was refused.
pub(crate) fn device_outcome(id: &str, opened: &str, shown: &Value) -> CmdResult {
    let c = &shown["connector"];
    let refused_since = c["lastFault"]["occurredAt"]
        .as_str()
        .is_some_and(|t| t >= opened);
    if c["state"] == "active" && !refused_since {
        if !is_json_output() {
            println!("{GREEN}\u{2713}{RESET} Connected.");
        }
        return done(shown);
    }
    let fault = c["lastFault"]["code"]
        .as_str()
        .unwrap_or("authorizationExpired");
    let fix = fix_for(fault, Some(id)).unwrap_or_default();
    Err(format!("the provider did not grant access ({fault}).\n  {fix}").into())
}

/// Print where to grant access, wait on the loopback listener, and relay what came back.
pub(crate) async fn grant(
    client: &VtaClient,
    id: &str,
    provider: &str,
    authorization: &Value,
    listener: Option<Loopback>,
) -> Result<Value, Box<dyn std::error::Error>> {
    let url = authorization["url"].as_str().unwrap_or("?");
    let state = authorization["state"]
        .as_str()
        .unwrap_or_default()
        .to_string();
    println!("Open this address in your browser and grant access:");
    println!();
    println!("  {url}");
    println!();
    if provider == "microsoft" {
        println!(
            "{YELLOW}Microsoft grants more than the VTA keeps:{RESET} its narrowest calendar \
             permission (Calendars.ReadWrite) lets the VTA read and change every calendar in the \
             account. The VTA writes only to a calendar it creates and reads only start, end \
             and free/busy status (VTI-CAL-105)."
        );
        println!();
    }
    let Some(listener) = listener else {
        println!(
            "{DIM}When the provider redirects back, relay the code with:{RESET}\n    \
             pnm calendar connectors complete {id} --state {state} --code <code>"
        );
        return Ok(Value::Null);
    };
    println!("{DIM}Waiting for the provider to redirect back (10 minutes)…{RESET}");
    let query = listener.wait(&state).await?;
    let get = |k: &str| query.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
    let mut req = json!({ "connectorId": id, "state": state });
    match (get("code"), get("error")) {
        (Some(code), _) => req["code"] = json!(code),
        (None, Some(err)) => req["providerError"] = json!(err),
        (None, None) => {
            return Err("the provider redirected back with neither a code nor an error".into());
        }
    }
    call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_AUTHORIZE_COMPLETE_0_1,
        req,
        Some(id),
    )
    .await
}

fn print_connector(c: &Value) {
    let fault = c["lastFault"]["code"]
        .as_str()
        .map(|f| format!(" · last fault {f}"))
        .unwrap_or_default();
    let flow = match c["flow"].as_str() {
        Some("deviceCode") => " (device code)",
        _ => "",
    };
    println!(
        "  {CYAN}{}{RESET}  {BOLD}{}{RESET}  {DIM}{}{} · {} · context {} · {} pending{}{RESET}",
        c["connectorId"].as_str().unwrap_or("?"),
        c["label"].as_str().unwrap_or(""),
        c["provider"].as_str().unwrap_or("?"),
        flow,
        c["state"].as_str().unwrap_or("?"),
        c["contextId"].as_str().unwrap_or("?"),
        c["pendingWrites"].as_u64().unwrap_or(0),
        fault,
    );
    let calendars = c["calendars"].as_array().cloned().unwrap_or_default();
    for cov in c["coverage"].as_array().into_iter().flatten() {
        let ctx = cov["contextId"].as_str().unwrap_or("?");
        // Its calendar at the provider, by name and state (VTI-CAL-127).
        let cal = calendars
            .iter()
            .find(|x| x["contextId"] == ctx)
            .map(|x| {
                format!(
                    " into \"{}\" ({})",
                    x["name"].as_str().unwrap_or("?"),
                    x["state"].as_str().unwrap_or("?")
                )
            })
            .unwrap_or_default();
        let overrides = cov["communities"].as_array().map_or(0, Vec::len);
        println!(
            "      {DIM}context {ctx}: writes {}{cal}{}{RESET}",
            cov["write"].as_str().unwrap_or("?"),
            if overrides > 0 {
                format!(" · {overrides} community override(s)")
            } else {
                String::new()
            }
        );
    }
    // A context no longer served, its calendar still being deleted (VTI-CAL-129).
    for x in calendars.iter().filter(|x| x["state"] == "removing") {
        println!(
            "      {DIM}context {}: no longer served — deleting \"{}\"{RESET}",
            x["contextId"].as_str().unwrap_or("?"),
            x["name"].as_str().unwrap_or("?")
        );
    }
    if c["busy"]["enabled"].as_bool() == Some(true) {
        let counted: Vec<&str> = c["busy"]["contextIds"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(Value::as_str)
            .collect();
        println!(
            "      {DIM}reads busy time, counted in {}{}{RESET}",
            if counted.is_empty() {
                c["contextId"].as_str().unwrap_or("?").to_string()
            } else {
                counted.join(", ")
            },
            c["lastReadAt"]
                .as_str()
                .map(|t| format!(", last {t}"))
                .unwrap_or_default()
        );
    }
}

/// `show` at 0.3, else 0.2.
pub(crate) async fn show(
    client: &VtaClient,
    id: &str,
) -> Result<Value, Box<dyn std::error::Error>> {
    call_newest(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_SHOW_0_3,
        Some(tt::TASK_VTA_CALENDAR_CONNECTORS_SHOW_0_2),
        json!({ "connectorId": id }),
        Some(id),
    )
    .await
}

pub(crate) fn done(resp: &Value) -> CmdResult {
    if is_json_output() {
        return Ok(print_json(resp)?);
    }
    if let Some(c) = resp.get("connector") {
        print_connector(c);
    }
    Ok(())
}

/// `connectors create` → `vta/calendar/connectors/create/0.2`, then — for an OAuth provider —
/// the grant through a loopback listener and `authorize/complete`, or a device code the VTA
/// polls for.
pub async fn cmd_connectors_create(client: &VtaClient, opts: &ConnectorCreate) -> CmdResult {
    let mut req = json!({
        "contextId": opts.context,
        "provider": opts.provider,
        "label": opts.label,
        "busy": busy_choice(opts.busy, &opts.busy_contexts, &opts.busy_calendars),
    });
    if opts.provider != "icsBusy" {
        let mut cov = json!({ "contextId": opts.context, "write": opts.write });
        if let Some(n) = &opts.calendar_name {
            cov["calendarName"] = json!(n);
        }
        req["coverage"] = json!([cov]);
    }
    let mut listener = None;
    if opts.provider == "icsBusy" {
        // Busy time alone: reading is the point (VTI-CAL-123).
        req["busy"] = busy_choice(true, &opts.busy_contexts, &[]);
        let address = read_secret("Private iCal address (https:// or webcal://)")?;
        req["ics"] = json!({ "sealedAddress": seal_ics_address(client, &address).await? });
    } else if opts.device_code {
        req["flow"] = json!("deviceCode");
    } else if opts.provider == "caldav" {
        let (Some(endpoint), Some(username)) = (&opts.endpoint, &opts.username) else {
            return Err("a CalDAV connector needs --endpoint and --username".into());
        };
        let sealed = sealed_password(client, endpoint, username).await?;
        req["caldav"] =
            json!({ "endpoint": endpoint, "username": username, "sealedPassword": sealed });
    } else if let Some(r) = &opts.redirect_uri {
        req["redirectUri"] = json!(r);
    } else {
        let l = Loopback::bind().await?;
        req["redirectUri"] = json!(l.redirect_uri);
        listener = Some(l);
    }
    let older = same_at_v2(&req).then_some(tt::TASK_VTA_CALENDAR_CONNECTORS_CREATE_0_2);
    let resp = call_newest(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_CREATE_0_3,
        older,
        req,
        None,
    )
    .await?;
    let id = resp["connector"]["connectorId"]
        .as_str()
        .unwrap_or_default()
        .to_string();
    if let Some(device) = resp.get("deviceAuthorization") {
        let opened = resp["connector"]["updatedAt"].as_str().unwrap_or_default();
        let shown = device_wait(client, &id, device).await?;
        return device_outcome(&id, opened, &shown);
    }
    let Some(authorization) = resp.get("authorization") else {
        if !is_json_output() {
            println!("{GREEN}\u{2713}{RESET} Connected.");
        }
        return done(&resp);
    };
    if is_json_output() && listener.is_none() {
        return Ok(print_json(&resp)?);
    }
    let completed = grant(client, &id, &opts.provider, authorization, listener).await?;
    if completed.is_null() {
        return Ok(());
    }
    if !is_json_output() {
        println!("{GREEN}\u{2713}{RESET} Connected.");
    }
    done(&completed)
}

/// `connectors complete` → `vta/calendar/connectors/authorize/complete/0.1`, for a client that
/// caught the redirect itself.
pub async fn cmd_connectors_complete(
    client: &VtaClient,
    id: &str,
    state: &str,
    code: Option<&str>,
    error: Option<&str>,
) -> CmdResult {
    let mut req = json!({ "connectorId": id, "state": state });
    match (code, error) {
        (Some(c), _) => req["code"] = json!(c),
        (None, Some(e)) => req["providerError"] = json!(e),
        (None, None) => {
            return Err("give --code, or --error with what the provider answered".into());
        }
    }
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_AUTHORIZE_COMPLETE_0_1,
        req,
        Some(id),
    )
    .await?;
    done(&resp)
}

/// `connectors list` → `vta/calendar/connectors/list/0.3`: every connector once, across the
/// contexts it serves (VTI-CAL-130); with a context, those serving it.
pub async fn cmd_connectors_list(client: &VtaClient, context: Option<&str>) -> CmdResult {
    let mut req = json!({});
    if let Some(c) = context {
        req["contextId"] = json!(c);
    }
    let resp = call_newest(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_LIST_0_3,
        Some(tt::TASK_VTA_CALENDAR_CONNECTORS_LIST_0_2),
        req,
        None,
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    let items = resp["connectors"].as_array().cloned().unwrap_or_default();
    if items.is_empty() {
        println!("No connectors. `pnm calendar connect` makes one.");
    }
    for c in &items {
        print_connector(c);
    }
    Ok(())
}

/// `connectors show` → `vta/calendar/connectors/show/0.3`.
pub async fn cmd_connectors_show(client: &VtaClient, id: &str) -> CmdResult {
    let resp = show(client, id).await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    done(&resp)
}

/// `connectors update` → `vta/calendar/connectors/update/0.3` (and, with `--reauthorize`, the
/// grant again).
pub async fn cmd_connectors_update(
    client: &VtaClient,
    id: &str,
    opts: &ConnectorUpdate,
) -> CmdResult {
    let current = show(client, id).await?;
    let c = &current["connector"];
    let provider = c["provider"].as_str().unwrap_or_default().to_string();
    let mut req = json!({ "connectorId": id });
    if let Some(l) = &opts.label {
        req["label"] = json!(l);
    }
    if let Some(w) = &opts.write {
        // The connector's own context's mode; every other context it serves stays as it is.
        let home = c["contextId"].clone();
        let mut coverage = c["coverage"].as_array().cloned().unwrap_or_default();
        match coverage.iter_mut().find(|v| v["contextId"] == home) {
            Some(v) => v["write"] = json!(w),
            None => coverage.push(json!({ "contextId": home, "write": w })),
        }
        req["coverage"] = json!(coverage);
    }
    if let Some(on) = opts.busy {
        req["busy"] = busy_choice(on, &opts.busy_contexts, &[]);
    }
    let mut listener = None;
    if opts.reauthorize {
        if opts.device_code {
            req["reauthorize"] = json!({ "flow": "deviceCode" });
        } else if let Some(r) = &opts.redirect_uri {
            req["reauthorize"] = json!({ "redirectUri": r });
        } else {
            let l = Loopback::bind().await?;
            req["reauthorize"] = json!({ "redirectUri": l.redirect_uri });
            listener = Some(l);
        }
    }
    if let Some((endpoint, username)) = &opts.password_for {
        req["caldavPassword"] = json!(sealed_password(client, endpoint, username).await?);
    }
    if opts.ics_address {
        let address = read_secret("New private iCal address (https:// or webcal://)")?;
        req["icsAddress"] = json!(seal_ics_address(client, &address).await?);
    }
    let older = same_at_v2(&req).then_some(tt::TASK_VTA_CALENDAR_CONNECTORS_UPDATE_0_2);
    let resp = call_newest(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_UPDATE_0_3,
        older,
        req,
        Some(id),
    )
    .await?;
    if let Some(device) = resp.get("deviceAuthorization") {
        let opened = resp["connector"]["updatedAt"].as_str().unwrap_or_default();
        let shown = device_wait(client, id, device).await?;
        return device_outcome(id, opened, &shown);
    }
    match resp.get("authorization") {
        Some(a) => {
            let completed = grant(client, id, &provider, a, listener).await?;
            if completed.is_null() {
                return Ok(());
            }
            done(&completed)
        }
        None => done(&resp),
    }
}

/// `connectors remove` → `vta/calendar/connectors/remove/0.3`, which removes a connector of any
/// kind, an `icsBusy` one included, and every context's calendar it made (VTI-CAL-129).
pub async fn cmd_connectors_remove(client: &VtaClient, id: &str, keep_calendar: bool) -> CmdResult {
    let resp = call_newest(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_REMOVE_0_3,
        Some(tt::TASK_VTA_CALENDAR_CONNECTORS_REMOVE_0_2),
        json!({ "connectorId": id, "keepCalendar": keep_calendar }),
        Some(id),
    )
    .await?;
    if is_json_output() {
        return Ok(print_json(&resp)?);
    }
    // An `icsBusy` connector holds no calendar and no grant: removing it erases the address.
    if resp["connector"]["provider"].as_str() == Some("icsBusy") {
        println!(
            "{GREEN}\u{2713}{RESET} Removing. The VTA erases the calendar address and the busy \
             time read from it, and forgets the connector; `pnm calendar connectors list` \
             shows it until then."
        );
        return Ok(());
    }
    println!(
        "{GREEN}\u{2713}{RESET} Removing. The VTA {}, revokes its grant and forgets the \
         connector; `pnm calendar connectors list` shows it until then.",
        if keep_calendar {
            "leaves its calendars at the provider"
        } else {
            "deletes every calendar it made at the provider, one per context"
        }
    );
    Ok(())
}

/// What VTI-CAL-131 asks a principal to know before a context is added to a connector.
pub const SHARED_ACCOUNT_NOTICE: &str = "The provider will hold this context's entries in the \
     same account as the connector's other contexts — each in a calendar of its own, but in one \
     account — so it can relate them to one another and to everything else it holds there. Use \
     a separate connector, signed in to another account, to keep them apart.";

/// A change to which contexts a connector serves.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ContextChange {
    /// Serve `context`: write `write` (`busy`, `titles`) into a calendar of its own, named
    /// `calendar_name` (default `VTI — <context>`), optionally counting busy time there.
    Add {
        context: String,
        write: String,
        calendar_name: Option<String>,
        count_busy: bool,
    },
    /// Stop serving `context`: its calendar at the provider and everything written there are
    /// deleted, and busy time stops counting there (VTI-CAL-129).
    Remove { context: String },
    /// Change what is written for `context`, or its calendar's name.
    Set {
        context: String,
        write: Option<String>,
        calendar_name: Option<String>,
    },
}

/// The `coverage` and `busy` an update sends for `change`, from the connector as shown.
///
/// # Errors
/// A change that does not apply to this connector, naming the fix.
pub fn contexts_change(connector: &Value, change: &ContextChange) -> Result<Value, String> {
    let mut coverage = connector["coverage"]
        .as_array()
        .cloned()
        .unwrap_or_default();
    let mut busy = connector["busy"].clone();
    let at = |cov: &[Value], ctx: &str| cov.iter().position(|v| v["contextId"] == ctx);
    match change {
        ContextChange::Add {
            context,
            write,
            calendar_name,
            count_busy,
        } => {
            if at(&coverage, context).is_some() {
                return Err(format!(
                    "the connector already serves {context}; change it with\n    \
                     pnm calendar connectors contexts set <connector-id> --context {context} \
                     --write {write}"
                ));
            }
            let mut v = json!({ "contextId": context, "write": write });
            if let Some(n) = calendar_name {
                v["calendarName"] = json!(n);
            }
            coverage.push(v);
            if *count_busy && busy["enabled"] == true {
                let mut ids: Vec<Value> =
                    busy["contextIds"].as_array().cloned().unwrap_or_default();
                if ids.is_empty() {
                    // Counted in its own context until now: keep that, and add this one.
                    ids.push(connector["contextId"].clone());
                }
                if !ids.iter().any(|i| i == context) {
                    ids.push(json!(context));
                }
                busy["contextIds"] = json!(ids);
            }
        }
        ContextChange::Remove { context } => {
            let Some(i) = at(&coverage, context) else {
                return Err(format!("the connector does not serve {context}"));
            };
            coverage.remove(i);
            if let Some(ids) = busy["contextIds"].as_array_mut() {
                ids.retain(|i| i != context);
                if ids.is_empty() {
                    busy.as_object_mut().map(|o| o.remove("contextIds"));
                }
            }
        }
        ContextChange::Set {
            context,
            write,
            calendar_name,
        } => {
            let Some(i) = at(&coverage, context) else {
                return Err(format!(
                    "the connector does not serve {context}; add it with\n    \
                     pnm calendar connectors contexts add <connector-id> --context {context}"
                ));
            };
            if write.is_none() && calendar_name.is_none() {
                return Err("give --write or --calendar-name".into());
            }
            if let Some(w) = write {
                coverage[i]["write"] = json!(w);
            }
            if let Some(n) = calendar_name {
                coverage[i]["calendarName"] = json!(n);
            }
        }
    }
    Ok(json!({ "coverage": coverage, "busy": busy }))
}

/// `connectors contexts add|remove|set` → `vta/calendar/connectors/update/0.3`. Adding tells
/// the principal what one account holding several contexts means first (VTI-CAL-131) and asks,
/// unless `yes`.
pub async fn cmd_connectors_contexts(
    client: &VtaClient,
    id: &str,
    change: &ContextChange,
    yes: bool,
) -> CmdResult {
    let current = call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_SHOW_0_3,
        json!({ "connectorId": id }),
        Some(id),
    )
    .await?;
    let c = &current["connector"];
    if c["provider"] == "icsBusy" {
        return Err(
            "an icsBusy connector writes nothing; choose where its busy time counts \
                    with  pnm calendar connectors update <connector-id> --busy-context <id>"
                .into(),
        );
    }
    let body = contexts_change(c, change)?;
    match change {
        ContextChange::Add { .. } => {
            if !is_json_output() {
                println!("{YELLOW}Before you add it:{RESET} {SHARED_ACCOUNT_NOTICE}");
            }
            let go = yes
                || (std::io::stdin().is_terminal()
                    && dialoguer::Confirm::new()
                        .with_prompt("Add this context to the connector?")
                        .default(true)
                        .interact()?);
            if !go {
                return Err("not added (give --yes to add it without asking)".into());
            }
        }
        ContextChange::Remove { context } => {
            if !is_json_output() {
                println!(
                    "{DIM}The VTA stops writing {context} at once, deletes its calendar at the \
                     provider with everything written there, and stops counting its busy time \
                     there (VTI-CAL-129).{RESET}"
                );
            }
        }
        ContextChange::Set { .. } => {}
    }
    let mut req = json!({ "connectorId": id, "coverage": body["coverage"] });
    if body["busy"] != c["busy"] {
        req["busy"] = body["busy"].clone();
    }
    let resp = call(
        client,
        tt::TASK_VTA_CALENDAR_CONNECTORS_UPDATE_0_3,
        req,
        Some(id),
    )
    .await?;
    done(&resp)
}

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

    #[test]
    fn vti_cal_128_contexts_add_remove_set_change_only_their_context() {
        let c = json!({
            "contextId": "work",
            "coverage": [{ "contextId": "work", "write": "busy" }],
            "busy": { "enabled": true },
        });
        let add = ContextChange::Add {
            context: "home".into(),
            write: "titles".into(),
            calendar_name: Some("Home (VTI)".into()),
            count_busy: true,
        };
        let b = contexts_change(&c, &add).unwrap();
        assert_eq!(
            b["coverage"],
            json!([{ "contextId": "work", "write": "busy" },
                   { "contextId": "home", "write": "titles", "calendarName": "Home (VTI)" }])
        );
        assert_eq!(b["busy"]["contextIds"], json!(["work", "home"]));
        assert!(
            contexts_change(
                &c,
                &ContextChange::Add {
                    context: "work".into(),
                    write: "busy".into(),
                    calendar_name: None,
                    count_busy: false,
                }
            )
            .unwrap_err()
            .contains("contexts set")
        );

        let two = json!({ "contextId": "work", "coverage": b["coverage"], "busy": b["busy"] });
        let r = contexts_change(
            &two,
            &ContextChange::Remove {
                context: "home".into(),
            },
        )
        .unwrap();
        assert_eq!(
            r["coverage"],
            json!([{ "contextId": "work", "write": "busy" }])
        );
        assert_eq!(r["busy"]["contextIds"], json!(["work"]));

        let s = contexts_change(
            &two,
            &ContextChange::Set {
                context: "work".into(),
                write: None,
                calendar_name: Some("Work".into()),
            },
        )
        .unwrap();
        assert_eq!(s["coverage"][0]["calendarName"], "Work");
        assert_eq!(
            s["coverage"][1]["write"], "titles",
            "the other context untouched"
        );
    }

    #[test]
    fn a_calendar_name_is_a_0_3_request_alone() {
        assert!(same_at_v2(
            &json!({ "coverage": [{ "contextId": "a", "write": "busy" }] })
        ));
        assert!(!same_at_v2(
            &json!({ "coverage": [{ "contextId": "a", "write": "busy", "calendarName": "A" }] })
        ));
    }

    #[test]
    fn a_redirect_query_is_percent_decoded() {
        assert_eq!(percent_decode("4%2F0Aean%2Bx"), "4/0Aean+x");
        assert_eq!(percent_decode("access_denied"), "access_denied");
        assert_eq!(percent_decode("a+b%"), "a b%");
    }

    #[tokio::test]
    async fn the_loopback_listener_answers_only_its_own_state() {
        let l = Loopback::bind().await.unwrap();
        let addr = l.redirect_uri.trim_end_matches("/callback").to_string();
        let host = addr.trim_start_matches("http://").to_string();
        let waiter = tokio::spawn(async move { l.wait("S1").await.unwrap() });
        for target in [
            "/favicon.ico",
            "/callback?state=OTHER&code=x",
            "/callback?state=S1&code=4%2Fabc",
        ] {
            let mut s = tokio::net::TcpStream::connect(&host).await.unwrap();
            s.write_all(format!("GET {target} HTTP/1.1\r\nHost: x\r\n\r\n").as_bytes())
                .await
                .unwrap();
            let mut out = String::new();
            let _ = s.read_to_string(&mut out).await;
        }
        let q = waiter.await.unwrap();
        assert!(q.contains(&("code".to_string(), "4/abc".to_string())));
    }
}