teter 26.11.6

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
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
//! `teter signup`, `teter login` and `teter logout`: the account on this
//! device. The password never leaves it: only the auth key derived from it
//! goes to the relay. The unlocked keys and the login token are kept in the
//! OS keyring (#126, `crate::keyring`), the rest in
//! `$XDG_CONFIG_HOME/teter/account.json`, mode 0600; with no keyring, all of
//! it in the file.

use std::io::Write as _;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use teter_client::account::{self, AccountKeys, DEFAULT_KDF};
use teter_common::account::{AccountReply, AccountRequest};
use zeroize::Zeroizing;

/// Make an account on a relay, and log this device in to it.
#[derive(clap::Args)]
pub struct SignupArgs {
    /// The relay, such as wss://relay.example.com.
    relay: String,

    /// The account's name.
    #[arg(long)]
    name: String,

    /// The invite the relay's admin gave (`teter-relay invite`): signup is
    /// closed without one.
    #[arg(long, env = "TETER_INVITE", hide_env_values = true, default_value = "")]
    invite: String,

    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// Log this device in to an account on a relay.
#[derive(clap::Args)]
pub struct LoginArgs {
    /// The relay, such as wss://relay.example.com.
    relay: String,

    /// The account's name.
    #[arg(long)]
    name: String,

    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// Log this device out: the relay ends its login, and the keys kept here are
/// removed.
#[derive(clap::Args)]
pub struct LogoutArgs {
    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// Change the account's password: the private keys are wrapped again under
/// the new one, and every other device's login ends.
#[derive(clap::Args)]
pub struct PasswordArgs {
    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots (else the one given at login).
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// Replace the account's keys, after a lost device or a key that may have
/// leaked: new keys, a statement signed by the old ones that the machines
/// follow, the machines approved again, and every other device's login
/// ended.
#[derive(clap::Args)]
pub struct RotateArgs {
    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots (else the one given at login).
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// What this device keeps of its account. The private keys are unlocked:
/// the file is closed to others (mode 0600), like an SSH key.
#[derive(Serialize, Deserialize)]
pub(crate) struct Saved {
    pub(crate) relay: String,
    pub(crate) name: String,
    pub(crate) token: String,
    /// The public keys, hex.
    pub(crate) public_keys: String,
    /// The private keys, hex.
    pub(crate) private_keys: String,
    /// The CA file given at login, if any: `logout` reaches the relay with
    /// it when given none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) ca_cert: Option<PathBuf>,
    /// Whether the token and private keys are in the OS keyring (#126), the
    /// file holding them empty.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub(crate) keyring: bool,
}

/// The secrets a device keeps in the keyring.
#[derive(Serialize, Deserialize)]
struct Secrets {
    token: String,
    private_keys: String,
}

impl Drop for Secrets {
    fn drop(&mut self) {
        zeroize::Zeroize::zeroize(&mut self.private_keys);
        zeroize::Zeroize::zeroize(&mut self.token);
    }
}

/// What the keyring keeps this device's secrets under: its account file.
fn keyring_key() -> std::io::Result<String> {
    Ok(account_file()?.to_string_lossy().into_owned())
}

/// `saved`, its secrets taken from the keyring when they are there.
async fn with_secrets(mut saved: Saved) -> std::io::Result<Saved> {
    if !saved.keyring {
        return Ok(saved);
    }
    let secret = crate::keyring::get(&keyring_key()?)
        .await
        .map_err(|e| std::io::Error::other(format!("the keyring: {e}")))?
        .ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "the keyring no longer holds this device's keys: run teter login",
            )
        })?;
    // Unreadable is as good as gone.
    let secrets: Secrets = serde_json::from_slice(&secret).map_err(|e| {
        std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("the keyring's entry for this device does not read ({e}): run teter login"),
        )
    })?;
    saved.token.clone_from(&secrets.token);
    saved.private_keys.clone_from(&secrets.private_keys);
    Ok(saved)
}

/// How long `logout` waits for the relay: the keys here go either way.
const LOGOUT_WAIT: std::time::Duration = std::time::Duration::from_secs(10);

/// How long a new login waits for the relay to end the one it replaces:
/// the new one works already.
const RELOGIN_WAIT: std::time::Duration = std::time::Duration::from_secs(5);

/// The account this device is logged in to.
pub(crate) async fn load() -> std::io::Result<Saved> {
    read_saved()
        .await?
        .ok_or_else(|| std::io::Error::other("this device is not logged in: run teter login"))
}

impl Drop for Saved {
    fn drop(&mut self) {
        zeroize::Zeroize::zeroize(&mut self.private_keys);
        zeroize::Zeroize::zeroize(&mut self.token);
    }
}

/// The file this device keeps its account in.
pub(crate) fn account_file() -> std::io::Result<PathBuf> {
    let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
    if let Some(config) = var("XDG_CONFIG_HOME") {
        return Ok(PathBuf::from(config).join("teter/account.json"));
    }
    let home = var("HOME").ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "neither XDG_CONFIG_HOME nor HOME is set: no place for the account",
        )
    })?;
    Ok(PathBuf::from(home).join(".config/teter/account.json"))
}

/// The password: `TETER_PASSWORD` when set (for scripts), else asked on the
/// terminal without echo; at signup, asked twice.
fn password(prompt: &str, confirm: bool) -> std::io::Result<Zeroizing<String>> {
    if let Ok(password) = std::env::var("TETER_PASSWORD") {
        if password.is_empty() {
            return Err(std::io::Error::other("TETER_PASSWORD is empty"));
        }
        return Ok(Zeroizing::new(password));
    }
    let first = Zeroizing::new(rpassword::prompt_password(prompt)?);
    if confirm {
        let again = Zeroizing::new(rpassword::prompt_password("the same password again: ")?);
        if *first != *again {
            return Err(std::io::Error::other("the two passwords differ"));
        }
    }
    if first.is_empty() {
        return Err(std::io::Error::other("an empty password"));
    }
    Ok(first)
}

/// Makes the account, then logs in.
pub async fn signup(args: SignupArgs) -> std::io::Result<()> {
    let password = password(
        &format!("password for the new account {}: ", args.name),
        true,
    )?;
    let salt = account::new_salt(DEFAULT_KDF)?;
    let derived = account::derive(&password, &salt).map_err(std::io::Error::other)?;
    let keys = AccountKeys::generate()?;
    let request = AccountRequest::Signup {
        name: args.name.clone(),
        salt,
        auth_key: derived.auth_key.to_vec(),
        public_keys: keys.public_keys(),
        wrapped_keys: keys.wrap(&derived, &args.name)?,
        invite: args.invite.clone(),
    };
    let reply = ask(&args.relay, args.ca_cert.as_deref(), &request).await?;
    let AccountReply::SignedUp = reply else {
        return Err(unexpected(&reply));
    };
    log_in(&args.relay, &args.name, &password, args.ca_cert.as_deref()).await?;
    println!("made the account {} and logged in", args.name);
    // By design (#89): the relay holds nothing that opens without it.
    println!(
        "keep the password safe: nothing can recover it. Forgotten, it means a new account and \
         registering the machines again (their sessions go on: the relay keeps none of their \
         data)"
    );
    Ok(())
}

/// This device's account, its keys, and the auth key of its password, asked
/// and checked against the relay's salt.
async fn proven(
    ca_cert: Option<&Path>,
    prompt: &str,
) -> std::io::Result<(Saved, AccountKeys, account::Derived)> {
    let saved = load().await?;
    let keys = teter_common::account::unhex(&saved.private_keys)
        .map(Zeroizing::new)
        .and_then(|private| AccountKeys::from_private_bytes(&private))
        .ok_or_else(|| std::io::Error::other("the saved account is damaged: log in again"))?;
    let password = password(&format!("{prompt} for {}: ", saved.name), false)?;
    let ca_cert = ca_cert.or(saved.ca_cert.as_deref());
    let reply = ask(
        &saved.relay,
        ca_cert,
        &AccountRequest::Salt {
            name: saved.name.clone(),
        },
    )
    .await?;
    let AccountReply::Salt { salt } = reply else {
        return Err(unexpected(&reply));
    };
    let derived = account::derive(&password, &salt).map_err(std::io::Error::other)?;
    Ok((saved, keys, derived))
}

/// `teter password`.
pub async fn change_password(args: PasswordArgs) -> std::io::Result<()> {
    let (saved, keys, current) = proven(args.ca_cert.as_deref(), "current password").await?;
    // TETER_NEW_PASSWORD for scripts, as TETER_PASSWORD is the current one.
    let new_password = match std::env::var("TETER_NEW_PASSWORD") {
        Ok(new) if !new.is_empty() => Zeroizing::new(new),
        _ => Zeroizing::new(
            rpassword::prompt_password("new password: ").and_then(|first| {
                let again = rpassword::prompt_password("the same password again: ")?;
                if first.is_empty() || first != again {
                    return Err(std::io::Error::other(
                        "the new passwords differ, or are empty",
                    ));
                }
                Ok(first)
            })?,
        ),
    };
    let salt = account::new_salt(DEFAULT_KDF)?;
    let derived = account::derive(&new_password, &salt).map_err(std::io::Error::other)?;
    let request = AccountRequest::PasswordChange {
        login: saved.token.clone(),
        auth_key: current.auth_key.to_vec(),
        salt,
        new_auth_key: derived.auth_key.to_vec(),
        wrapped_keys: keys.wrap(&derived, &saved.name)?,
    };
    let ca_cert = args.ca_cert.as_deref().or(saved.ca_cert.as_deref());
    let reply = ask(&saved.relay, ca_cert, &request).await?;
    let AccountReply::PasswordChanged { token } = reply else {
        return Err(unexpected(&reply));
    };
    // The same keys; the tokens this device made still approve machines.
    write_saved(&Saved {
        relay: saved.relay.clone(),
        name: saved.name.clone(),
        token,
        public_keys: saved.public_keys.clone(),
        private_keys: saved.private_keys.clone(),
        ca_cert: saved.ca_cert.clone(),
        keyring: false,
    })
    .await?;
    println!(
        "changed the password of {}: other devices log in again",
        saved.name
    );
    Ok(())
}

/// `teter rotate-keys`.
pub async fn rotate_keys(args: RotateArgs) -> std::io::Result<()> {
    let (saved, old, derived) = proven(args.ca_cert.as_deref(), "password").await?;
    let ca_cert = args.ca_cert.as_deref().or(saved.ca_cert.as_deref());
    let reply = ask(
        &saved.relay,
        ca_cert,
        &AccountRequest::MachineList {
            login: saved.token.clone(),
        },
    )
    .await?;
    let AccountReply::Machines { machines } = reply else {
        return Err(unexpected(&reply));
    };
    let new = AccountKeys::generate()?;
    let rekeyed = rekey(&old, &new, &machines)?;
    let at = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |since| {
            i64::try_from(since.as_secs()).unwrap_or(i64::MAX)
        });
    let request = AccountRequest::KeyRotate {
        login: saved.token.clone(),
        auth_key: derived.auth_key.to_vec(),
        rotation: account::rotation(&old, &new, at),
        wrapped_keys: new.wrap(&derived, &saved.name)?,
        machines: rekeyed,
    };
    let reply = ask(&saved.relay, ca_cert, &request).await?;
    let AccountReply::KeysRotated { token } = reply else {
        return Err(unexpected(&reply));
    };
    save(&Saved {
        relay: saved.relay.clone(),
        name: saved.name.clone(),
        token,
        public_keys: hex(&new.public_keys()),
        private_keys: hex(new.private_bytes().as_ref()),
        ca_cert: saved.ca_cert.clone(),
        keyring: false,
    })
    .await?;
    println!(
        "replaced the keys of {}: its machines follow when they connect; other devices log in \
         again; registration tokens made before no longer work",
        saved.name
    );
    Ok(())
}

/// `machines` under the `new` keys: each name the `old` keys open, sealed
/// again, and each machine the old keys approved, approved by the new ones.
/// A name that does not open (sealed by a relay, not a machine) goes empty:
/// the relay keeps it, and drops the machine's approval. Every machine is
/// named: the relay refuses a rotation that leaves one out.
fn rekey(
    old: &AccountKeys,
    new: &AccountKeys,
    machines: &[teter_common::account::MachineInfo],
) -> std::io::Result<Vec<teter_common::account::MachineRekey>> {
    let (old_public, new_public) = (old.public_keys(), new.public_keys());
    let info = crate::machine::NAME_INFO;
    let mut rekeyed = Vec::new();
    for machine in machines {
        let Ok(name) = old.open_sealed(info, &machine.sealed_name) else {
            rekeyed.push(teter_common::account::MachineRekey {
                id: machine.id.clone(),
                sealed_name: Vec::new(),
                cert: Vec::new(),
            });
            continue;
        };
        let sealed_name = account::seal_to(&new_public, info, &name)?;
        let approved = account::cert_holds(
            &old_public,
            &machine.id,
            &machine.public_key,
            &machine.sealed_name,
            &machine.cert,
        );
        let cert = if approved {
            new.sign(&teter_common::account::cert_bytes(
                &machine.id,
                &machine.public_key,
                &sealed_name,
            ))
        } else {
            Vec::new()
        };
        rekeyed.push(teter_common::account::MachineRekey {
            id: machine.id.clone(),
            sealed_name,
            cert,
        });
    }
    Ok(rekeyed)
}

/// Logs in.
pub async fn login(args: LoginArgs) -> std::io::Result<()> {
    let password = password(&format!("password for {}: ", args.name), false)?;
    log_in(&args.relay, &args.name, &password, args.ca_cert.as_deref()).await?;
    println!("logged in to {}", args.name);
    Ok(())
}

/// The salt, the keys derived from `password`, the login, and the keys
/// unwrapped and kept.
async fn log_in(
    relay: &str,
    name: &str,
    password: &str,
    ca_cert: Option<&Path>,
) -> std::io::Result<()> {
    // Absolute, before the relay makes a token: a later command may run
    // from anywhere.
    let ca_cert = ca_cert.map(std::path::absolute).transpose()?;
    let ca_cert = ca_cert.as_deref();
    let reply = ask(
        relay,
        ca_cert,
        &AccountRequest::Salt {
            name: name.to_owned(),
        },
    )
    .await?;
    let AccountReply::Salt { salt } = reply else {
        return Err(unexpected(&reply));
    };
    let derived = account::derive(password, &salt).map_err(std::io::Error::other)?;
    let request = AccountRequest::Login {
        name: name.to_owned(),
        auth_key: derived.auth_key.to_vec(),
    };
    let reply = ask(relay, ca_cert, &request).await?;
    let AccountReply::LoggedIn {
        token,
        public_keys,
        wrapped_keys,
    } = reply
    else {
        return Err(unexpected(&reply));
    };
    let keys = AccountKeys::unwrap(&derived, name, &wrapped_keys, &public_keys)
        .map_err(std::io::Error::other)?;
    // The login this one replaces is ended, not left valid on the relay.
    let before = read_saved().await;
    save(&Saved {
        relay: relay.to_owned(),
        name: name.to_owned(),
        token,
        public_keys: hex(&public_keys),
        private_keys: hex(keys.private_bytes().as_ref()),
        ca_cert: ca_cert.map(Path::to_path_buf),
        keyring: false,
    })
    .await?;
    if let Ok(Some(before)) = before {
        // The same relay: the CA that just worked, else the one kept with
        // it (a file from before kept none); another relay: its own.
        let same_relay =
            crate::endpoint(&before.relay, "account") == crate::endpoint(relay, "account");
        let ca = if same_relay {
            ca_cert.or(before.ca_cert.as_deref())
        } else {
            before.ca_cert.as_deref()
        };
        match end_login(&before, ca, RELOGIN_WAIT).await {
            Ok(AccountReply::LoggedOut) => {}
            Ok(other) => {
                eprintln!("teter: the relay did not end this device's login before: {other:?}")
            }
            Err(e) => eprintln!("teter: could not end this device's login before: {e}"),
        }
    }
    Ok(())
}

/// The account file's contents, with the secrets from the keyring, `None`
/// when there is none.
async fn read_saved() -> std::io::Result<Option<Saved>> {
    match read_file()? {
        Some(saved) => with_secrets(saved).await.map(Some),
        None => Ok(None),
    }
}

/// The account file's contents as they are, `None` when there is none.
fn read_file() -> std::io::Result<Option<Saved>> {
    match std::fs::read(account_file()?).map(Zeroizing::new) {
        Ok(bytes) => serde_json::from_slice(&bytes)
            .map(Some)
            .map_err(std::io::Error::other),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e),
    }
}

/// Asks `saved`'s relay to end its login, within `wait`, with `ca_cert`,
/// else the one given at login.
async fn end_login(
    saved: &Saved,
    ca_cert: Option<&Path>,
    wait: std::time::Duration,
) -> std::io::Result<AccountReply> {
    let request = AccountRequest::Logout {
        token: saved.token.clone(),
    };
    let ca_cert = ca_cert.or(saved.ca_cert.as_deref());
    tokio::time::timeout(wait, account::request(&saved.relay, ca_cert, &request))
        .await
        .map_err(|elapsed| std::io::Error::new(std::io::ErrorKind::TimedOut, elapsed))?
        .map_err(std::io::Error::other)
}

/// Logs out: the relay ends the login (if it can be reached), and the file
/// goes.
pub async fn logout(args: LogoutArgs) -> std::io::Result<()> {
    let path = account_file()?;
    let Some(file) = read_file()? else {
        return Err(std::io::Error::other("this device is not logged in"));
    };
    let in_keyring = file.keyring;
    // A keyring that does not answer (no session over ssh, say) keeps the
    // file: deleting it would leave the relay's login live and nothing
    // here to end it with. Keys the keyring lost still leave, the file too.
    let saved = with_secrets(file).await;
    if let Err(e) = &saved
        && e.kind() != std::io::ErrorKind::NotFound
    {
        return Err(std::io::Error::other(format!(
            "{e}; the account file stays: log out where the keyring answers (or remove {} to \
             forget the login here)",
            path.display()
        )));
    }
    let told = match &saved {
        Ok(saved) => end_login(saved, args.ca_cert.as_deref(), LOGOUT_WAIT).await,
        Err(e) => Err(std::io::Error::other(e.to_string())),
    };
    if in_keyring && let Err(e) = crate::keyring::remove(&keyring_key()?).await {
        eprintln!("teter: could not remove the keys from the keyring: {e}");
    }
    std::fs::remove_file(&path)?;
    let name = saved.map_or_else(|_| "the account".to_owned(), |saved| saved.name.clone());
    // The secrets of tokens this device made go with the login (#133).
    if let Err(e) = crate::approve::forget_all() {
        eprintln!("teter: could not remove the pending token secrets: {e}");
    }
    match told {
        Ok(AccountReply::LoggedOut) => println!("logged out of {name}"),
        Ok(other) => eprintln!(
            "teter: the relay did not end the login: {other:?}; the keys here are removed"
        ),
        Err(e) => {
            eprintln!("teter: the relay could not be reached ({e}); the keys here are removed")
        }
    }
    Ok(())
}

/// Writes `saved` to the account file, closed to others (a new file renamed
/// over the old one), forgetting the secrets of tokens made before.
async fn save(saved: &Saved) -> std::io::Result<()> {
    // Another account (or the same, again): tokens kept for the one before
    // approve nothing here.
    crate::approve::forget_all()?;
    write_saved(saved).await
}

/// Writes `saved` as [`save`], keeping the secrets of the tokens this device
/// made: its token and private keys to the keyring and the rest to the
/// account file, or all of it to the file, said, when no keyring takes them.
async fn write_saved(saved: &Saved) -> std::io::Result<()> {
    let with = |token: &str, private_keys: &str, keyring: bool| Saved {
        relay: saved.relay.clone(),
        name: saved.name.clone(),
        token: token.to_owned(),
        public_keys: saved.public_keys.clone(),
        private_keys: private_keys.to_owned(),
        ca_cert: saved.ca_cert.clone(),
        keyring,
    };
    // Whether the secrets before were in the keyring: a file that read and
    // said so.
    let before = read_file().ok().flatten().is_some_and(|file| file.keyring);
    if crate::keyring::wanted() {
        // The file first, pointing at the keyring: one that fails to write
        // leaves the keyring as it was, so the two never name different
        // logins.
        write_file(&with("", "", true))?;
        let secrets = Secrets {
            token: saved.token.clone(),
            private_keys: saved.private_keys.clone(),
        };
        let bytes = Zeroizing::new(serde_json::to_vec(&secrets).map_err(std::io::Error::other)?);
        match crate::keyring::put(&keyring_key()?, &bytes).await {
            Ok(()) => return Ok(()),
            Err(e) => eprintln!(
                "teter: no keyring took the account's keys ({e}): they are kept in {}, mode 0600",
                account_file()?.display()
            ),
        }
    }
    write_file(&with(&saved.token, &saved.private_keys, false))?;
    // Old secrets the file no longer points at go (an old private key must
    // not stay behind, after a rotation, say).
    if before && let Err(e) = crate::keyring::remove(&keyring_key()?).await {
        eprintln!("teter: could not remove the keys left in the keyring: {e}");
    }
    Ok(())
}

/// Writes `saved` to the account file as it is, closed to others.
fn write_file(saved: &Saved) -> std::io::Result<()> {
    let path = account_file()?;
    if let Some(dir) = path.parent() {
        std::fs::DirBuilder::new()
            .recursive(true)
            .mode(0o700)
            .create(dir)?;
    }
    // This process's own, so two logins at once never share it; a leftover
    // of the same name (a reused PID) would keep its mode: made anew.
    let temporary = path.with_extension(format!("new.{}", std::process::id()));
    match std::fs::remove_file(&temporary) {
        Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
        _ => {}
    }
    let mut file = std::fs::OpenOptions::new()
        .create_new(true)
        .write(true)
        .mode(0o600)
        .open(&temporary)?;
    let text = Zeroizing::new(serde_json::to_vec(saved).map_err(std::io::Error::other)?);
    let written = file
        .write_all(&text)
        .and_then(|()| file.sync_all())
        .and_then(|()| std::fs::rename(&temporary, &path));
    if written.is_err() {
        // Not left holding the keys.
        drop(std::fs::remove_file(&temporary));
    }
    written
}

/// The relay's reply to `request`; a refusal is an error, with its reason.
pub(crate) async fn ask(
    relay: &str,
    ca_cert: Option<&Path>,
    request: &AccountRequest,
) -> std::io::Result<AccountReply> {
    let reply = account::request(relay, ca_cert, request)
        .await
        .map_err(std::io::Error::other)?;
    if let AccountReply::Refused { reason } = reply {
        return Err(std::io::Error::other(reason));
    }
    Ok(reply)
}

pub(crate) fn unexpected(reply: &AccountReply) -> std::io::Error {
    std::io::Error::other(format!("the relay answered out of turn: {reply:?}"))
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}