silicon-accounts-cli 0.4.0

The `silicon-accounts` command line for Silicon Accounts: sign Carbons and Silicons in, manage accounts, Silicons and apps
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
//! `silicon-accounts login`, `silicon-accounts login status`, `silicon-accounts logout`.

use serde_json::{Value, json};
use silicon_accounts_client::{
    AccountKind, AccountsClient, Contact, DevicePoll, TokenResponse, WaitEvent,
};
use time::OffsetDateTime;

use crate::cli::{LoginArgs, LoginCommand, LoginStatusArgs};
use crate::ctx::{Ctx, StoredChallenge, StoredSession};
use crate::error::{CliError, CliResult, EXIT_INTERRUPTED};
use crate::home;
use crate::output::{Outcome, json_time, kv, when};
use crate::util;

/// The status JSON shared by `login`, `login status`.
fn status_json(session: &StoredSession, verified: bool) -> Value {
    json!({
        "authenticated": true,
        "kind": session.kind.as_str(),
        "id": session.account.id,
        "uuid": session.account.uuid,
        "display_name": session.account.display_name,
        "expires_at": json_time(Some(session.expires_at)),
        "refresh_expires_at": json_time(session.refresh_expires_at),
        "url": session.url,
        "verified": verified,
    })
}

fn signed_in_text(session: &StoredSession) -> String {
    let name = if session.account.display_name.is_empty() {
        String::new()
    } else {
        format!(" ({})", session.account.display_name)
    };
    let mut text = format!(
        "Signed in as {}{name}, a {}.\n",
        session.who(),
        session.kind.title()
    );
    text.push_str(&kv(&[
        ("uuid", session.account.uuid.clone()),
        ("url", session.url.clone()),
        (
            "access token",
            format!(
                "{} (refreshed automatically)",
                when(Some(session.expires_at))
            ),
        ),
        ("session ends", when(session.refresh_expires_at)),
    ]));
    text
}

fn next_after_login(outcome: Outcome, kind: AccountKind) -> Outcome {
    match kind {
        AccountKind::Silicon => outcome
            .next(
                "silicon-accounts login --app <app_id>",
                "get a short-lived token to sign into an app",
            )
            .next("silicon-accounts whoami", "see your account and custodian"),
        AccountKind::Carbon => outcome
            .next("silicon-accounts whoami", "see your account")
            .next(
                "silicon-accounts silicon create --id si:<name>",
                "create a Silicon you are custodian of",
            )
            .next(
                "silicon-accounts custodian requests",
                "requests from Silicons that named you",
            ),
    }
}

pub async fn login(ctx: &Ctx, args: LoginArgs) -> CliResult<Outcome> {
    if let Some(LoginCommand::Status(status_args)) = &args.command {
        return status(ctx, status_args).await;
    }
    let label = util::client_label(args.label.as_deref());
    let code_mode = args.email.is_some() || args.phone.is_some() || args.challenge.is_some();
    let silicon = args.silicon.clone().or_else(|| {
        if code_mode {
            None
        } else {
            std::env::var("ACCOUNTS_SILICON")
                .ok()
                .filter(|v| !v.trim().is_empty())
        }
    });
    let federated = args.federated.is_some() || args.github_actions;
    if federated && silicon.is_none() {
        return Err(CliError::invalid(
            "--federated signs a Silicon in with an outside token, but no si:id was given.",
            "Add --silicon si:<id> (or set ACCOUNTS_SILICON): the Silicon whose trust matches this CI job.",
        ));
    }
    if args.key.is_some() && silicon.is_none() {
        return Err(CliError::invalid(
            "--key signs a Silicon in, but no si:id was given.",
            "Add --silicon si:<id> (or set ACCOUNTS_SILICON).",
        ));
    }
    if (args.stk.is_some() || args.stk_stdin) && silicon.is_none() {
        return Err(CliError::invalid(
            "--stk and --stk-stdin sign in a Silicon, but no si:id was given.",
            "Add --silicon si:<id> (or set ACCOUNTS_SILICON).",
        ));
    }
    if args.code.is_some() && !code_mode {
        return Err(CliError::invalid(
            "--code finishes a code sign-in, but no --email, --phone or --challenge was given.",
            "Run `silicon-accounts login --email you@example.com` to send a code, then `silicon-accounts login --email you@example.com --code <code>`.",
        ));
    }
    if args.no_browser && (silicon.is_some() || code_mode) {
        ctx.out.notice(
            "Note: --no-browser only matters for the browser (device) sign-in; ignoring it.",
        );
    }

    // Already signed in as the requested account: reuse the session, but only once the service
    // confirmed it is still alive. A session revoked elsewhere (`silicon-accounts sessions revoke`, an STK
    // rotation, a sign-out on another machine) is not "signed in": it falls through to a real
    // sign-in with the credentials given (or the browser or code flow).
    let explicit = silicon.is_some() || code_mode;
    if !args.force
        && let Some(current) = ctx.current_session()?
    {
        let same = match &silicon {
            Some(id) => util::with_prefix(id, AccountKind::Silicon) == current.account.id,
            None => !explicit,
        };
        if same {
            match reuse_session(ctx, args.app.as_deref()).await {
                Ok(outcome) => return Ok(outcome),
                Err(err) if err.code == "session_ended" => {
                    ctx.out
                        .notice(&format!("{} Signing in again.", err.message));
                }
                Err(err) => return Err(err),
            }
        }
    }

    let previous = ctx.load_session()?;
    let key_file = args.key.clone().or_else(|| {
        if args.stk.is_some() || args.stk_stdin {
            None
        } else {
            std::env::var("ACCOUNTS_SILICON_KEY")
                .ok()
                .filter(|v| !v.trim().is_empty())
                .map(std::path::PathBuf::from)
        }
    });
    let mut federation = None;
    let (tokens, method) = if let (true, Some(id)) = (federated, &silicon) {
        let (tokens, stored) = federated_login(ctx, &args, id).await?;
        federation = stored;
        (tokens, "federated")
    } else if let (Some(id), Some(file)) = (&silicon, &key_file) {
        (key_login(ctx, id, file, &label).await?, "silicon_key")
    } else if let Some(id) = silicon {
        (silicon_login(ctx, &args, &id, &label).await?, "silicon_stk")
    } else if code_mode {
        match code_login(ctx, &args, &label).await? {
            CodeLogin::Tokens(tokens, method) => (*tokens, method),
            CodeLogin::Pending(outcome) => return Ok(outcome),
        }
    } else {
        (device_login(ctx, &args, &label).await?, "device")
    };

    let me = if tokens.account.is_none() {
        Some(
            ctx.client()?
                .with_token(tokens.access_token.expose())
                .me()
                .await?,
        )
    } else {
        None
    };
    let mut session = ctx.store_tokens(&tokens, me.as_ref(), method)?;
    if federation.is_some() {
        session.federation = federation;
        ctx.save_session(&session)?;
    }
    let _ = home::remove_file(&ctx.home()?.file("login-challenge.json"));
    ctx.telemetry.step(
        "login.done",
        1.0,
        json!({ "method": method, "kind": session.kind.as_str() }),
    );

    if let Some(previous) = previous
        && previous.refresh_token != session.refresh_token
    {
        retire_previous(ctx, &previous, &session).await;
    }

    if let Some(app_id) = &args.app {
        return short_lived_token(ctx, &session, app_id).await;
    }
    let outcome = Outcome::new(status_json(&session, true), signed_in_text(&session));
    Ok(next_after_login(outcome, session.kind))
}

/// The stored session, checked with the service: with `app`, the short-lived token minted with it
/// (that call is the check); otherwise `GET /v1/me`. Both refresh an expired access token once.
/// Fails with `session_ended` when the session was revoked or its refresh was refused (the stored
/// session is then deleted), so the caller signs in again instead of reporting a dead session.
async fn reuse_session(ctx: &Ctx, app: Option<&str>) -> CliResult<Outcome> {
    if let Some(app_id) = app {
        let session = ctx.session().await?;
        return short_lived_token(ctx, &session, app_id).await;
    }
    let me = match crate::with_session!(ctx, |s| s.me()) {
        Ok(me) => me,
        // A 401 the refresh did not get past (e.g. a refresh that raced another process) is
        // still a session that does not work.
        Err(err) if err.status == Some(401) => {
            let stored = ctx.load_session()?;
            return Err(CliError::new(
                crate::error::EXIT_AUTH,
                "session_ended",
                format!(
                    "Your session as {} was refused: {}",
                    stored.as_ref().map_or("this account", StoredSession::who),
                    err.message
                ),
                "Sign in again with `silicon-accounts login`.",
            ));
        }
        Err(err) => return Err(err),
    };
    let mut session = ctx.session().await?;
    if session.account.id != me.id || session.account.display_name != me.display_name {
        session.account.id.clone_from(&me.id);
        session.account.display_name.clone_from(&me.display_name);
        ctx.save_session(&session)?;
    }
    let text = format!(
        "Already signed in as {} ({}); the session is active. Use `silicon-accounts login --force` to sign in again, or `silicon-accounts logout` first.",
        session.who(),
        session.kind.title()
    );
    let mut json = status_json(&session, true);
    json["reused"] = json!(true);
    Ok(next_after_login(Outcome::new(json, text), session.kind))
}

/// Best-effort revocation of the session being replaced.
async fn retire_previous(ctx: &Ctx, previous: &StoredSession, current: &StoredSession) {
    let Some(refresh) = previous.refresh_token.as_deref() else {
        return;
    };
    if previous.url != current.url {
        ctx.out.notice(&format!(
            "Replaced your session at {} ({}); it stays valid there until it is revoked from `silicon-accounts sessions list`.",
            previous.url,
            previous.who()
        ));
        return;
    }
    if let Ok(client) = ctx.client() {
        if client.revoke_first_party(refresh).await.is_err() {
            ctx.out.warn(&format!(
                "Could not revoke your previous session as {}; revoke it with `silicon-accounts sessions list` / `silicon-accounts sessions revoke`.",
                previous.who()
            ));
        } else if previous.account.uuid != current.account.uuid {
            ctx.out.notice(&format!(
                "Signed out of {} first: this home holds one session at a time (use separate homes, e.g. SILICON_HOME, to stay signed in as several accounts).",
                previous.who()
            ));
        }
    }
}

async fn silicon_login(
    ctx: &Ctx,
    args: &LoginArgs,
    id: &str,
    label: &str,
) -> CliResult<TokenResponse> {
    let id = util::with_prefix(id, AccountKind::Silicon);
    if !id.starts_with("si:") {
        return Err(CliError::invalid(
            format!("`{id}` is not a Silicon id: Silicon ids start with si: (e.g. si:scout)."),
            "Carbons sign in with `silicon-accounts login` (browser) or `--email` / `--phone`.",
        ));
    }
    let stk = if let Some(stk) = &args.stk {
        ctx.out.warn("Passing an STK as an argument exposes it to other processes and your shell history; prefer --stk-stdin or ACCOUNTS_STK.");
        stk.clone()
    } else if args.stk_stdin {
        util::read_secret_stdin("the STK")?
    } else if let Some(stk) = std::env::var("ACCOUNTS_STK")
        .ok()
        .filter(|v| !v.trim().is_empty())
    {
        stk
    } else if util::interactive(ctx.global.json) {
        util::prompt_secret(&format!("STK for {id}: "))?
    } else {
        return Err(CliError::invalid(
            format!("No STK was given for {id}."),
            "Pipe it with --stk-stdin, set ACCOUNTS_STK, or pass --stk.",
        ));
    };
    let stk = util::normalize_stk(&stk)?;
    let client = ctx.client()?;
    ctx.telemetry.step("login.silicon.started", 0.3, json!({}));
    Ok(client.silicon_login(&id, &stk, Some(label)).await?)
}

async fn key_login(
    ctx: &Ctx,
    id: &str,
    file: &std::path::Path,
    label: &str,
) -> CliResult<TokenResponse> {
    let id = util::with_prefix(id, AccountKind::Silicon);
    if !id.starts_with("si:") {
        return Err(CliError::invalid(
            format!("`{id}` is not a Silicon id: Silicon ids start with si: (e.g. si:scout)."),
            "Only Silicons sign in with a key.",
        ));
    }
    let key = silicon_accounts_client::SiliconSigningKey::from_file(file)?;
    let client = ctx.client()?;
    ctx.telemetry
        .step("login.silicon_key.started", 0.3, json!({}));
    Ok(client
        .silicon_login_with_key(&id, &key, None, Some(label))
        .await?)
}

/// Signs a Silicon in with an outside OIDC token it is trusted for: the token from
/// `--federated <TOKEN|@FILE|env:VAR>`, or from GitHub Actions with `--github-actions`. Returns
/// the tokens and, when the source can be read again, how to sign in again on expiry.
async fn federated_login(
    ctx: &Ctx,
    args: &LoginArgs,
    id: &str,
) -> CliResult<(TokenResponse, Option<crate::ctx::StoredFederation>)> {
    use silicon_accounts_client::TokenSource;
    let id = util::with_prefix(id, AccountKind::Silicon);
    let client = ctx.client()?;
    let source = if args.github_actions {
        let audience = match &args.audience {
            Some(a) if !a.trim().is_empty() => a.trim().to_owned(),
            // A trust's default audience is the service's public URL.
            _ => client
                .meta()
                .await?
                .public_url
                .trim_end_matches('/')
                .to_owned(),
        };
        TokenSource::GithubActions { audience }
    } else {
        match args.federated.as_deref().map(str::trim) {
            Some(spec) if !spec.is_empty() => TokenSource::parse(spec),
            _ => {
                return Err(CliError::invalid(
                    "--federated needs the outside token: the token itself, @<file> or env:<VARIABLE>.",
                    "In GitHub Actions use --federated --github-actions; in GitLab CI pass env:<the id_tokens variable>.",
                ));
            }
        }
    };
    if matches!(source, TokenSource::Literal(_)) {
        ctx.out.warn("Passing a token as an argument exposes it to other processes; prefer env:VAR or @file.");
    }
    ctx.telemetry.step(
        "login.federated.started",
        0.3,
        json!({ "source": source.describe() }),
    );
    let token = source.read().await?;
    let tokens = client.exchange_federated_token(&id, token.expose()).await?;
    let stored = source
        .is_rereadable()
        .then(|| crate::ctx::StoredFederation {
            silicon: id.clone(),
            source: source.describe(),
            audience: match &source {
                TokenSource::GithubActions { audience } => Some(audience.clone()),
                _ => None,
            },
        });
    Ok((tokens, stored))
}

enum CodeLogin {
    Tokens(Box<TokenResponse>, &'static str),
    Pending(Outcome),
}

async fn code_login(ctx: &Ctx, args: &LoginArgs, label: &str) -> CliResult<CodeLogin> {
    let client = ctx.client()?;
    let (url, _) = ctx.url()?;
    let challenge_path = ctx.home()?.file("login-challenge.json");
    let method = if args.phone.is_some() {
        "phone"
    } else {
        "email"
    };

    if let Some(challenge_id) = &args.challenge {
        let code = match &args.code {
            Some(code) => code.clone(),
            None if util::interactive(ctx.global.json) => util::prompt("6-digit code: ")?,
            None => {
                return Err(CliError::invalid(
                    "--challenge needs the code too.",
                    format!(
                        "Run `silicon-accounts login --challenge {challenge_id} --code <6-digit code>`."
                    ),
                ));
            }
        };
        let tokens = client
            .cli_login_verify(challenge_id, &code, Some(label))
            .await?;
        return Ok(CodeLogin::Tokens(Box::new(tokens), method));
    }

    let contact = match (&args.email, &args.phone) {
        (Some(email), _) => Contact::Email(email.trim().to_owned()),
        (None, Some(phone)) => Contact::Phone {
            phone: phone.trim().to_owned(),
            country: args.country.clone(),
        },
        (None, None) => {
            return Err(CliError::invalid(
                "A code sign-in needs --email, --phone or --challenge.",
                "Run `silicon-accounts login --email you@example.com`.",
            ));
        }
    };
    let key = contact.value().trim().to_ascii_lowercase();
    let flag = if matches!(contact, Contact::Email(_)) {
        "--email"
    } else {
        "--phone"
    };

    if let Some(code) = &args.code {
        let saved: Option<StoredChallenge> = home::read_json(&challenge_path)?;
        let Some(saved) = saved.filter(|s| s.contact == key && s.url == url) else {
            return Err(CliError::invalid(
                format!(
                    "No sign-in code is waiting for {}: --code finishes a sign-in that `silicon-accounts login {flag} {}` started.",
                    contact.value(),
                    contact.value()
                ),
                format!(
                    "Run `silicon-accounts login {flag} {}` first to send a code, then rerun with --code.",
                    contact.value()
                ),
            ));
        };
        let tokens = client
            .cli_login_verify(&saved.challenge_id, code, Some(label))
            .await?;
        return Ok(CodeLogin::Tokens(Box::new(tokens), method));
    }

    let challenge = client.cli_login_start(&contact).await?;
    ctx.telemetry
        .step("login.code.sent", 0.4, json!({ "channel": method }));
    let stored = StoredChallenge {
        challenge_id: challenge.challenge_id.clone(),
        contact: key,
        destination: challenge.destination.clone(),
        expires_at: challenge.expires_at,
        url,
    };
    home::write_json(&challenge_path, &stored)?;

    if util::interactive(ctx.global.json) {
        ctx.out.essential(
            &format!(
                "A 6-digit code was sent to {} (valid {}).",
                challenge.destination,
                until(challenge.expires_at)
            ),
            &json!({}),
        );
        for attempt in 1..=3 {
            let code = util::prompt("Code: ")?;
            match client
                .cli_login_verify(&challenge.challenge_id, &code, Some(label))
                .await
            {
                Ok(tokens) => return Ok(CodeLogin::Tokens(Box::new(tokens), method)),
                Err(err)
                    if (err.is_code("invalid_code") || err.is_code("invalid_input"))
                        && attempt < 3 =>
                {
                    ctx.out.warn(&err.message());
                }
                Err(err) => return Err(err.into()),
            }
        }
    }

    let finish = format!(
        "silicon-accounts login {flag} {} --code <code>",
        contact.value()
    );
    let text = format!(
        "A 6-digit code was sent to {} (valid {}).\nFinish signing in with:\n  {finish}",
        challenge.destination,
        until(challenge.expires_at)
    );
    let json = json!({
        "status": "code_sent",
        "authenticated": false,
        "challenge_id": challenge.challenge_id,
        "destination": challenge.destination,
        "expires_at": json_time(challenge.expires_at),
        "next": finish,
    });
    Ok(CodeLogin::Pending(Outcome::new(json, text)))
}

fn until(t: Option<OffsetDateTime>) -> String {
    match t {
        Some(t) => format!("until {}", when(Some(t))),
        None => "for 10 minutes".to_owned(),
    }
}

async fn device_login(ctx: &Ctx, args: &LoginArgs, label: &str) -> CliResult<TokenResponse> {
    let client: &AccountsClient = ctx.client()?;
    let device = client.device_authorize(Some(label)).await?;
    let expires_at = OffsetDateTime::now_utc()
        + time::Duration::seconds(i64::try_from(device.expires_in).unwrap_or(600));
    let opened = !args.no_browser && util::open_browser(device.browser_url());
    ctx.telemetry.step(
        "login.device.code_shown",
        0.3,
        json!({ "browser_opened": opened }),
    );
    let browser_note = if opened {
        "Your browser was opened; confirm the code there.".to_owned()
    } else {
        format!(
            "Open {} in a browser where you are signed in (or sign in there first).",
            device.browser_url()
        )
    };
    ctx.out.essential(
        &format!(
            "To sign in, go to {} and enter the code\n\n    {}\n\n{browser_note}\nWaiting for approval (the code expires in {} minutes; Ctrl-C to cancel)…",
            device.verification_uri,
            device.user_code,
            device.expires_in.div_ceil(60)
        ),
        &json!({
            "event": "device_code",
            "user_code": device.user_code,
            "verification_uri": device.verification_uri,
            "verification_uri_complete": device.verification_uri_complete,
            "expires_at": json_time(Some(expires_at)),
            "browser_opened": opened,
        }),
    );
    let out = ctx.out;
    let wait = client.wait_for_device_tokens(&device, |event| match event {
        WaitEvent::Polled(DevicePoll::SlowDown) => out.progress(
            "The service asked to poll more slowly; waiting a bit longer between checks.",
        ),
        WaitEvent::TransientError { error, retry_in } => {
            out.warn(&format!(
                "{} Retrying in {}s.",
                error.message(),
                retry_in.as_secs()
            ));
        }
        _ => {}
    });
    let tokens = tokio::select! {
        result = wait => result?,
        _ = tokio::signal::ctrl_c() => {
            return Err(CliError::new(
                EXIT_INTERRUPTED,
                "interrupted",
                format!("Stopped waiting for approval of code {}.", device.user_code),
                "Run `silicon-accounts login` again to get a new code.",
            ));
        }
    };
    ctx.telemetry.step("login.device.approved", 0.9, json!({}));
    Ok(tokens)
}

/// Mints a short-lived token for an app with the stored session.
pub async fn short_lived_token(
    ctx: &Ctx,
    session: &StoredSession,
    app_id: &str,
) -> CliResult<Outcome> {
    let app_id = app_id.trim().to_owned();
    let slt = crate::with_session!(ctx, |s| s.short_lived_token(&app_id))?;
    ctx.telemetry
        .step("login.slt.issued", 1.0, json!({ "app": app_id }));
    ctx.out.notice(&format!(
        "Short-lived token for {} as {}: single use, valid {}. The app exchanges it with grant_type=urn:silicon:params:oauth:grant-type:slt.",
        slt.app_id,
        session.who(),
        until(Some(slt.expires_at))
    ));
    let json = json!({ "slt": slt.slt.expose(), "app_id": slt.app_id, "expires_at": json_time(Some(slt.expires_at)) });
    Ok(Outcome::new(json, slt.slt.expose().to_owned()))
}

async fn status(ctx: &Ctx, args: &LoginStatusArgs) -> CliResult<Outcome> {
    let (url, _) = ctx.url()?;
    let not_signed_in = |json: Value, text: String| {
        Outcome::new(json, text)
            .next(
                "silicon-accounts login",
                "sign in as a Carbon (browser code)",
            )
            .next(
                "silicon-accounts login --silicon si:<id> --stk-stdin",
                "sign in as a Silicon",
            )
            .exit(if ctx.out.json { 0 } else { 1 })
    };
    let Some(stored) = ctx.load_session()? else {
        return Ok(not_signed_in(
            json!({ "authenticated": false }),
            format!("Not signed in to {url}."),
        ));
    };
    if stored.url.trim_end_matches('/') != url {
        return Ok(not_signed_in(
            json!({ "authenticated": false, "reason": "signed_in_elsewhere", "session_url": stored.url }),
            format!(
                "Not signed in to {url} (you are signed in to {} as {}).",
                stored.url,
                stored.who()
            ),
        ));
    }
    if args.offline {
        let ended = stored
            .refresh_expires_at
            .is_some_and(|t| t <= OffsetDateTime::now_utc());
        if ended {
            return Ok(not_signed_in(
                json!({ "authenticated": false, "reason": "session_ended" }),
                format!("Your session as {} has ended.", stored.who()),
            ));
        }
        return Ok(Outcome::new(
            status_json(&stored, false),
            signed_in_text(&stored),
        ));
    }
    match crate::with_session!(ctx, |s| s.me()) {
        Ok(me) => {
            let mut session = ctx.session().await?;
            if session.account.id != me.id || session.account.display_name != me.display_name {
                session.account.id.clone_from(&me.id);
                session.account.display_name.clone_from(&me.display_name);
                ctx.save_session(&session)?;
            }
            Ok(Outcome::new(
                status_json(&session, true),
                signed_in_text(&session),
            ))
        }
        Err(err) if err.code == "session_ended" => Ok(not_signed_in(
            json!({ "authenticated": false, "reason": "session_ended", "message": err.message }),
            format!(
                "{} Sign in again with `silicon-accounts login`.",
                err.message
            ),
        )),
        Err(err) if err.transport => {
            ctx.out.warn(&format!(
                "{} Reporting the stored session without checking it.",
                err.message
            ));
            let mut json = status_json(&stored, false);
            json["warning"] = json!(err.message);
            Ok(Outcome::new(json, signed_in_text(&stored)))
        }
        Err(err) => Err(err),
    }
}

pub async fn logout(ctx: &Ctx) -> CliResult<Outcome> {
    let Some(stored) = ctx.load_session()? else {
        return Ok(Outcome::new(
            json!({ "signed_out": false, "reason": "not_signed_in" }),
            "You were not signed in; nothing to do.",
        ));
    };
    let mut revoked = false;
    if let Some(refresh) = stored.refresh_token.as_deref() {
        let client = AccountsClient::builder()
            .base_url(&stored.url)
            .user_agent(format!(
                "silicon-accounts-cli/{}",
                env!("CARGO_PKG_VERSION")
            ))
            .telemetry(ctx.telemetry_setting().0)
            .allow_insecure_http(true)
            .build();
        match client {
            Ok(client) => match client.revoke_first_party(refresh).await {
                Ok(()) => revoked = true,
                Err(err) => ctx.out.warn(&format!(
                    "Could not revoke the session at {}: {} The local session is deleted anyway; revoke it later from `silicon-accounts sessions list` on another device.",
                    stored.url,
                    err.message()
                )),
            },
            Err(err) => ctx.out.warn(&err.message()),
        }
    }
    ctx.clear_session()?;
    let text = format!("Signed out of {} ({}).", stored.who(), stored.url);
    Ok(Outcome::new(
        json!({ "signed_out": true, "id": stored.account.id, "uuid": stored.account.uuid, "revoked": revoked }),
        text,
    )
    .next("silicon-accounts login", "sign in again"))
}