teter 26.11.7

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
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
//! `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.
//!
//! Each login is bound to a key pair of this device (#158), made at login:
//! the relay takes the login's token only in requests the device key signs.
//! The key is kept in the keyring with the token; with no keyring, in
//! `device.key` beside `account.json` (mode 0600), never in `account.json`
//! itself, so a copy of that file alone logs nothing in.

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 private seed of the device key the login is bound to (#158),
    /// hex: never written to the account file (the keyring, or
    /// `device.key`); empty for a login from before.
    #[serde(default, skip_serializing)]
    pub(crate) device_key: String,
}

impl Saved {
    /// The device key this login is bound to.
    ///
    /// # Errors
    ///
    /// A login from before device keys, or a damaged key.
    pub(crate) fn device(&self) -> std::io::Result<account::DeviceKey> {
        teter_common::account::unhex(&self.device_key)
            .map(Zeroizing::new)
            .and_then(|seed| account::DeviceKey::from_seed(&seed))
            .ok_or_else(|| {
                std::io::Error::other(
                    "this device's login has no device key (it is from an older teter, or the key \
                     is lost): run teter login",
                )
            })
    }
}

/// The secrets a device keeps in the keyring.
#[derive(Serialize, Deserialize)]
struct Secrets {
    token: String,
    private_keys: String,
    /// The device key's seed, hex (#158); empty in an entry from before.
    #[serde(default)]
    device_key: String,
}

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

/// The file this device keeps its device key in when no keyring does
/// (#158): beside the account file, never in it.
fn device_file() -> std::io::Result<PathBuf> {
    Ok(account_file()?.with_file_name("device.key"))
}

/// The device key's seed in [`device_file`], hex; empty when there is none.
fn read_device_file() -> std::io::Result<String> {
    match std::fs::read_to_string(device_file()?) {
        Ok(text) => Ok(text.trim().to_owned()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
        Err(e) => Err(e),
    }
}

/// Removes [`device_file`], if there is one.
fn remove_device_file() -> std::io::Result<()> {
    match std::fs::remove_file(device_file()?) {
        Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
        _ => Ok(()),
    }
}

/// 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 {
        // A file that does not read (its permissions, say) is an error
        // that keeps it: removing it would leave its login live with
        // nothing to end it.
        // Damaged contents are as good as gone, as a key that does not parse.
        saved.device_key = read_device_file().map_err(|e| {
            let kind = if e.kind() == std::io::ErrorKind::InvalidData {
                std::io::ErrorKind::NotFound
            } else {
                e.kind()
            };
            std::io::Error::new(kind, format!("this device's key file does not read: {e}"))
        })?;
        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);
    saved.device_key.clone_from(&secrets.device_key);
    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);
        zeroize::Zeroize::zeroize(&mut self.device_key);
    }
}

/// 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_as(&saved, 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,
        device_key: saved.device_key.clone(),
    })
    .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_as(
        &saved,
        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_as(&saved, 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,
        device_key: saved.device_key.clone(),
    })
    .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)?;
    // A new key pair for this login: its token works only signed by it.
    let device = account::DeviceKey::generate()?;
    let request = AccountRequest::Login {
        name: name.to_owned(),
        auth_key: derived.auth_key.to_vec(),
        device_key: device.public_key(),
    };
    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,
        device_key: hex(device.seed().as_ref()),
    })
    .await?;
    if let Ok(Some(before)) = before {
        end_previous(&before, relay, ca_cert).await;
    }
    Ok(())
}

/// Ends `before`, the login a new one on `relay` (with `ca_cert`) replaces,
/// saying so when the relay does not.
async fn end_previous(before: &Saved, relay: &str, ca_cert: Option<&Path>) {
    // 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}"),
    }
}

/// 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());
    // A login from before device keys ends without a signature.
    let ask = async {
        match saved.device() {
            Ok(device) => account::request_signed(&saved.relay, ca_cert, &request, &device).await,
            Err(_) => account::request(&saved.relay, ca_cert, &request).await,
        }
    };
    tokio::time::timeout(wait, ask)
        .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()?;
    // What a killed login or token command left half written holds a token
    // and keys too (#149): gone first, whatever comes of the rest (a first
    // login killed leaves no account file, only that); the device key's too.
    for file in [
        Ok(path.clone()),
        device_file(),
        crate::approve::pending_file(),
    ] {
        if let Err(e) = file.and_then(|file| remove_leftovers(&file)) {
            eprintln!("teter: could not remove what a stopped command left: {e}");
        }
    }
    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)?;
    if let Err(e) = remove_device_file() {
        eprintln!("teter: could not remove this device's key file: {e}");
    }
    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,
        // Never in the account file.
        device_key: String::new(),
    };
    // 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(),
            device_key: saved.device_key.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(()) => {
                // A device key a file held before goes.
                if let Err(e) = remove_device_file() {
                    eprintln!("teter: could not remove the old device key file: {e}");
                }
                return Ok(());
            }
            Err(e) => eprintln!(
                "teter: no keyring took the account's keys ({e}): they are kept in {}, mode 0600",
                account_file()?.display()
            ),
        }
    }
    // The device key first, then the account file: two files, so a failure
    // between the two writes can still leave them naming different logins
    // (then `teter login` again).
    if saved.device_key.is_empty() {
        remove_device_file()?;
    } else {
        write_device_file(&saved.device_key)?;
        // Said every time: the binding to this device is only as good as
        // that file's protection (#158).
        eprintln!(
            "teter: this device's key is kept in {}, mode 0600, not in a keyring: whoever copies \
             it with {} can use this login elsewhere",
            device_file()?.display(),
            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(())
}

/// Removes the half-written copies of `path` (`<stem>.new.<pid>` or
/// `<stem>.new<pid>`, beside it) whose process is gone: one killed while it
/// wrote left it, holding what the file holds. A live one's is its own
/// write in flight (a login running beside this logout), and stays; a PID
/// reused since keeps a leftover until the next time.
pub(crate) fn remove_leftovers(path: &Path) -> std::io::Result<()> {
    let (Some(dir), Some(stem)) = (path.parent(), path.file_stem().and_then(|s| s.to_str())) else {
        return Ok(());
    };
    let prefix = format!("{stem}.new");
    let entries = match std::fs::read_dir(dir) {
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        entries => entries?,
    };
    // One that cannot be removed leaves the others to go all the same: the
    // first failure is answered at the end.
    let mut failed = None;
    for entry in entries {
        let entry = match entry {
            Ok(entry) => entry,
            Err(e) => {
                failed.get_or_insert(e);
                continue;
            }
        };
        let name = entry.file_name();
        // Plain digits only: a sign would name a process group.
        let Some(pid) = name
            .to_str()
            .and_then(|name| name.strip_prefix(&prefix))
            .map(|rest| rest.strip_prefix('.').unwrap_or(rest))
            .filter(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
            .and_then(|digits| digits.parse::<i32>().ok())
            .and_then(rustix::process::Pid::from_raw)
        else {
            continue;
        };
        if rustix::process::test_kill_process(pid) == Err(rustix::io::Errno::SRCH)
            && let Err(e) = std::fs::remove_file(entry.path())
            && e.kind() != std::io::ErrorKind::NotFound
        {
            failed.get_or_insert(e);
        }
    }
    failed.map_or(Ok(()), Err)
}

/// Writes the device key's seed `hex` to [`device_file`], closed to others.
fn write_device_file(hex: &str) -> std::io::Result<()> {
    write_private(&device_file()?, hex.as_bytes())
}

/// Writes `saved` to the account file as it is, closed to others.
fn write_file(saved: &Saved) -> std::io::Result<()> {
    let text = Zeroizing::new(serde_json::to_vec(saved).map_err(std::io::Error::other)?);
    write_private(&account_file()?, &text)
}

/// Writes `bytes` to `path`, closed to others (mode 0600, its directory 0700):
/// a new file renamed over the old one.
fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    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 written = file
        .write_all(bytes)
        .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)
}

/// [`ask`], on `saved`'s relay, signed by its device key (#158): what every
/// request with its login token takes.
pub(crate) async fn ask_as(
    saved: &Saved,
    ca_cert: Option<&Path>,
    request: &AccountRequest,
) -> std::io::Result<AccountReply> {
    let device = saved.device()?;
    let reply = account::request_signed(&saved.relay, ca_cert, request, &device)
        .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()
}