nex-pkg 0.25.6

Package manager UX for nix-darwin + homebrew
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
use std::path::PathBuf;

use anyhow::{bail, Context, Result};
use zeroize::{Zeroize, Zeroizing};

use styrene_identity::derive::{KeyDeriver, KeyPurpose};
use styrene_identity::export::AllPublicKeys;
use styrene_identity::file_signer::FileSigner;
use styrene_identity::identity::{identity_hash, identity_pubkey};
use styrene_identity::pubkey;
use styrene_identity::signer::SignerError;

use crate::output;

fn default_path() -> PathBuf {
    FileSigner::default_path()
}

/// Read a passphrase from the terminal (no echo). Rejects empty input.
/// Returns a `Zeroizing` wrapper that automatically clears memory on drop.
fn read_passphrase(prompt: &str) -> Result<Zeroizing<Vec<u8>>> {
    let passphrase = crate::input::input().password(prompt)?;
    if passphrase.is_empty() {
        bail!("passphrase must not be empty");
    }
    Ok(Zeroizing::new(passphrase.into_bytes()))
}

/// Load identity root secret with passphrase. The passphrase is wrapped in
/// `Zeroizing` so it is automatically cleared on drop — no manual zeroize needed.
fn load_root(
    path: &PathBuf,
    passphrase: &Zeroizing<Vec<u8>>,
) -> Result<styrene_identity::signer::RootSecret> {
    let signer = FileSigner::with_static_passphrase(path, passphrase);
    signer.load(passphrase).map_err(|e| match e {
        SignerError::DecryptionFailed(_) => anyhow::anyhow!("wrong passphrase"),
        e => anyhow::anyhow!("failed to load identity: {e}"),
    })
}

// ── init ────────────────────────────────────────────────────────────────────

pub fn run_init(path: Option<PathBuf>) -> Result<()> {
    let path = path.unwrap_or_else(default_path);

    if path.exists() {
        bail!(
            "identity already exists at {}\nuse `nex identity show` to inspect it",
            path.display()
        );
    }

    output::status("creating new Styrene identity");

    let passphrase = Zeroizing::new(
        crate::input::input()
            .password_with_confirm("Passphrase")?
            .into_bytes(),
    );

    if passphrase.is_empty() {
        bail!("passphrase must not be empty");
    }

    let signer = FileSigner::with_static_passphrase(&path, &passphrase);
    signer
        .generate(&passphrase)
        .context("failed to generate identity")?;

    let root = signer
        .load(&passphrase)
        .context("failed to load newly created identity")?;

    let hash = identity_hash(&root);

    eprintln!();
    output::status("identity created");
    eprintln!("  path  {}", path.display());
    eprintln!("  hash  {hash}");
    eprintln!();
    eprintln!(
        "  {}",
        console::style(
            "Back up this file with `nex identity backup <path>` — losing it means losing your identity."
        )
        .dim()
    );

    Ok(())
}

// ── show ────────────────────────────────────────────────────────────────────

pub fn run_show(path: Option<PathBuf>) -> Result<()> {
    let path = path.unwrap_or_else(default_path);

    if !path.exists() {
        bail!(
            "no identity at {}\nrun `nex identity init` to create one",
            path.display()
        );
    }

    let passphrase = read_passphrase("Passphrase")?;
    let root = load_root(&path, &passphrase)?;
    let keys = AllPublicKeys::from_root(&root);

    eprintln!();
    output::status("styrene identity");
    eprintln!("  path       {}", path.display());
    eprintln!("  hash       {}", keys.identity_hash);
    eprintln!("  pubkey     {}", keys.signing_pubkey_hex);
    eprintln!("  ssh host   {}", keys.ssh_host_fingerprint);
    eprintln!("  wireguard  {}", keys.wireguard_pubkey);
    if !keys.age_recipient.is_empty() {
        eprintln!("  age        {}", keys.age_recipient);
    }

    Ok(())
}

// ── backup ─────────────────────────────────────────────────────────────────

pub fn run_backup(output: &PathBuf) -> Result<()> {
    let path = default_path();
    if !path.exists() {
        bail!(
            "no identity at {}\nrun `nex identity init` to create one",
            path.display()
        );
    }
    validate_identity_file_shape(&path, "identity file")?;
    if output.exists() {
        bail!("backup already exists at {}", output.display());
    }
    if let Some(parent) = output.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating backup directory {}", parent.display()))?;
    }

    std::fs::copy(&path, output)
        .with_context(|| format!("copying {} to {}", path.display(), output.display()))?;
    set_identity_file_permissions(output)?;

    eprintln!();
    output::status("identity backup written");
    eprintln!("  source  {}", path.display());
    eprintln!("  backup  {}", output.display());
    eprintln!();
    eprintln!(
        "  {}",
        console::style("Keep this encrypted file somewhere durable and private.").dim()
    );

    Ok(())
}

#[cfg(unix)]
fn set_identity_file_permissions(path: &PathBuf) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;
    let mut permissions = std::fs::metadata(path)?.permissions();
    permissions.set_mode(0o600);
    std::fs::set_permissions(path, permissions)?;
    Ok(())
}

#[cfg(not(unix))]
fn set_identity_file_permissions(_path: &PathBuf) -> Result<()> {
    Ok(())
}

fn validate_identity_file_shape(path: &PathBuf, label: &str) -> Result<()> {
    let meta =
        std::fs::metadata(path).with_context(|| format!("reading {label} {}", path.display()))?;
    if !meta.is_file() {
        bail!("{label} is not a file: {}", path.display());
    }
    if meta.len() != 97 {
        bail!(
            "{label} at {} has unexpected size: {} bytes (expected 97)",
            path.display(),
            meta.len()
        );
    }
    Ok(())
}

pub fn run_restore(input: &PathBuf) -> Result<()> {
    if !input.exists() {
        bail!("identity backup not found at {}", input.display());
    }
    validate_identity_file_shape(input, "identity backup")?;

    let path = default_path();
    if path.exists() {
        bail!(
            "identity already exists at {}\nmove it aside before restoring",
            path.display()
        );
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating identity directory {}", parent.display()))?;
    }

    std::fs::copy(input, &path)
        .with_context(|| format!("copying {} to {}", input.display(), path.display()))?;
    set_identity_file_permissions(&path)?;

    eprintln!();
    output::status("identity restored");
    eprintln!("  source  {}", input.display());
    eprintln!("  path    {}", path.display());
    eprintln!();
    eprintln!(
        "  {}",
        console::style("Run `nex identity verify <path>` to verify the restored identity.").dim()
    );

    Ok(())
}

pub fn run_verify(input: &PathBuf) -> Result<()> {
    if !input.exists() {
        bail!("identity file not found at {}", input.display());
    }
    validate_identity_file_shape(input, "identity file")?;

    let passphrase = read_passphrase("Passphrase")?;
    let root = load_root(input, &passphrase)?;
    let keys = AllPublicKeys::from_root(&root);

    eprintln!();
    output::status("identity file verified");
    eprintln!("  path       {}", input.display());
    eprintln!("  hash       {}", keys.identity_hash);
    eprintln!("  pubkey     {}", keys.signing_pubkey_hex);
    eprintln!();

    Ok(())
}

// ── list ────────────────────────────────────────────────────────────────────

pub fn run_list() -> Result<()> {
    eprintln!();
    output::status("styrene identities");

    let mut found = false;

    // Default path
    let default = default_path();
    if default.is_file() {
        print_identity_metadata(&default, "default");
        found = true;
    }

    // Scan for additional .key files in ~/.config/styrene/
    if let Some(parent) = default.parent() {
        if parent.is_dir() {
            let mut extras: Vec<_> = std::fs::read_dir(parent)?
                .flatten()
                .filter(|e| {
                    let p = e.path();
                    p.extension().and_then(|x| x.to_str()) == Some("key") && p != default
                })
                .map(|e| e.path())
                .collect();
            extras.sort();
            for extra in &extras {
                let label = extra
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or("unknown");
                print_identity_metadata(extra, label);
                found = true;
            }
        }
    }

    // STYRENE_IDENTITY_PATH env var
    if let Ok(env_path) = std::env::var("STYRENE_IDENTITY_PATH") {
        let p = PathBuf::from(&env_path);
        if p.is_file() && p != default {
            print_identity_metadata(&p, "env:STYRENE_IDENTITY_PATH");
            found = true;
        }
    }

    // STYRENE_IDENTITY_HASH env var (hash-only)
    if let Ok(hash) = std::env::var("STYRENE_IDENTITY_HASH") {
        if !hash.is_empty() {
            eprintln!(
                "  {} {}  {}  {}",
                console::style("").dim(),
                console::style("env").bold(),
                hash,
                console::style("(hash-only, no signing)").dim()
            );
            found = true;
        }
    }

    if !found {
        eprintln!(
            "  {} no identities found — run {}",
            console::style("").dim(),
            console::style("nex identity init").bold()
        );
    }

    eprintln!();
    Ok(())
}

fn print_identity_metadata(path: &PathBuf, label: &str) {
    let meta = std::fs::metadata(path);
    let size_ok = meta.as_ref().map(|m| m.len() == 97).unwrap_or(false);

    #[cfg(unix)]
    let perms_ok = meta
        .as_ref()
        .map(|m| {
            use std::os::unix::fs::PermissionsExt;
            m.permissions().mode() & 0o777 == 0o600
        })
        .unwrap_or(false);
    #[cfg(not(unix))]
    let perms_ok = true;

    let status = if size_ok && perms_ok {
        console::style("").green().to_string()
    } else {
        console::style("").yellow().to_string()
    };

    eprintln!(
        "  {status} {}  {}",
        console::style(label).bold(),
        console::style(path.display()).dim()
    );

    if !size_ok {
        if let Ok(m) = &meta {
            eprintln!(
                "    {}",
                console::style(format!("unexpected size: {} bytes (expected 97)", m.len()))
                    .yellow()
            );
        }
    }
    #[cfg(unix)]
    if !perms_ok {
        if let Ok(m) = &meta {
            use std::os::unix::fs::PermissionsExt;
            eprintln!(
                "    {}",
                console::style(format!(
                    "permissions: {:#o} (should be 0o600)",
                    m.permissions().mode() & 0o777
                ))
                .yellow()
            );
        }
    }
}

// ── status ─────────────────────────────────────────────────────────────────

pub fn run_status() -> Result<()> {
    eprintln!();
    output::status("styrene identity readiness");

    let path = default_path();
    if path.exists() {
        let meta =
            std::fs::metadata(&path).with_context(|| format!("reading {}", path.display()))?;
        if meta.len() == 97 {
            status_ok("identity file", &format!("{}", path.display()));
        } else {
            status_warn(
                "identity file",
                &format!("{} bytes at {} (expected 97)", meta.len(), path.display()),
            );
        }

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = meta.permissions().mode() & 0o777;
            if mode == 0o600 {
                status_ok("identity permissions", "0600");
            } else {
                status_warn(
                    "identity permissions",
                    &format!("{mode:#o} — should be 0o600"),
                );
            }
        }
    } else {
        status_warn("identity file", "missing — run `nex identity init`");
    }

    let git_format = git_config_value("gpg.format");
    let git_signing_key = git_config_value("user.signingkey");
    let git_sign_commits = git_config_value("commit.gpgsign");
    if git_format.as_deref() == Some("ssh")
        && git_signing_key.as_deref().is_some_and(|v| !v.is_empty())
        && git_sign_commits.as_deref() == Some("true")
    {
        status_ok("git signing", "enabled with SSH signing key");
    } else {
        status_warn(
            "git signing",
            "not fully configured — run `nex identity git`",
        );
    }

    match crate::config::load_identity_config() {
        Ok(config) => {
            let labels = config.ssh.and_then(|s| s.labels).unwrap_or_default();
            if labels.is_empty() {
                status_warn(
                    "ssh labels",
                    "none registered — run `nex identity ssh --add github`",
                );
            } else {
                status_ok("ssh labels", &labels.join(", "));
            }
        }
        Err(err) => status_warn("ssh labels", &format!("could not read Nex config: {err}")),
    }

    match dirs::home_dir() {
        Some(home) => {
            let ssh_config = home.join(".ssh/config");
            match std::fs::read_to_string(&ssh_config) {
                Ok(text)
                    if text
                        .lines()
                        .any(|line| line.trim() == "Include ~/.ssh/config.d/nex.conf") =>
                {
                    status_ok("ssh materialization", "Nex include installed");
                }
                Ok(_) => status_warn(
                    "ssh materialization",
                    "Nex include not installed — apply a profile with [ssh] hosts",
                ),
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => status_warn(
                    "ssh materialization",
                    "~/.ssh/config missing — apply a profile with [ssh] hosts",
                ),
                Err(err) => status_warn(
                    "ssh materialization",
                    &format!("could not read config: {err}"),
                ),
            }

            report_styrene_ssh_agent(&home);
        }
        None => {
            status_warn("ssh materialization", "could not determine home directory");
            status_warn("styrene ssh agent", "could not determine home directory");
        }
    }

    eprintln!();
    Ok(())
}

fn git_config_value(key: &str) -> Option<String> {
    std::process::Command::new("git")
        .args(["config", "--global", key])
        .output()
        .ok()
        .filter(|output| output.status.success())
        .map(|output| {
            crate::exec::captured_text(&output.stdout)
                .trim()
                .to_string()
        })
        .filter(|value| !value.is_empty())
}

#[cfg(unix)]
fn report_styrene_ssh_agent(home: &std::path::Path) {
    use std::os::unix::fs::FileTypeExt;

    let socket = home.join(".styrene/ssh-agent.sock");
    match std::fs::metadata(&socket) {
        Ok(meta) if meta.file_type().is_socket() => {
            status_ok(
                "styrene ssh agent",
                &format!("socket at {}", socket.display()),
            );
        }
        Ok(_) => status_warn(
            "styrene ssh agent",
            &format!("{} exists but is not a socket", socket.display()),
        ),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => status_warn(
            "styrene ssh agent",
            "not detected — identity_label hosts need the Styrene SSH agent",
        ),
        Err(err) => status_warn(
            "styrene ssh agent",
            &format!("could not inspect socket: {err}"),
        ),
    }
}

#[cfg(not(unix))]
fn report_styrene_ssh_agent(home: &std::path::Path) {
    let socket = home.join(".styrene/ssh-agent.sock");
    if socket.exists() {
        status_ok(
            "styrene ssh agent",
            &format!("path at {}", socket.display()),
        );
    } else {
        status_warn(
            "styrene ssh agent",
            "not detected — identity_label hosts need the Styrene SSH agent",
        );
    }
}

fn status_ok(label: &str, detail: &str) {
    eprintln!(
        "  {} {}: {}",
        console::style("").green().bold(),
        label,
        console::style(detail).dim()
    );
}

fn status_warn(label: &str, detail: &str) {
    eprintln!(
        "  {} {}: {}",
        console::style("!").yellow().bold(),
        label,
        console::style(detail).dim()
    );
}

// ── ssh ─────────────────────────────────────────────────────────────────────

pub fn run_ssh(label: Option<String>, list: bool, add: Option<String>) -> Result<()> {
    if list {
        return run_ssh_list();
    }
    if let Some(new_label) = add {
        return run_ssh_add(&new_label);
    }
    if let Some(label) = label {
        return run_ssh_export(&label);
    }
    bail!(
        "usage: nex identity ssh <label>\n       \
         nex identity ssh --list\n       \
         nex identity ssh --add <label>"
    );
}

fn run_ssh_export(label: &str) -> Result<()> {
    let path = default_path();
    if !path.exists() {
        bail!("no identity — run `nex identity init` first");
    }

    let passphrase = read_passphrase("Passphrase")?;
    let root = load_root(&path, &passphrase)?;
    let deriver = KeyDeriver::new(root.as_bytes());

    let mut seed = deriver
        .derive_ssh_user_key(label)
        .context("invalid SSH key label")?;
    let comment = format!("styrene-ssh-user-{label}");
    let pubkey = styrene_identity::format::ssh_pubkey(&seed, &comment);
    let fingerprint = styrene_identity::format::ssh_pubkey_fingerprint(&seed);
    seed.zeroize();

    eprintln!();
    output::status(&format!("ssh key: {label}"));
    eprintln!("  fingerprint  {fingerprint}");
    eprintln!();

    // Pubkey to stdout for piping
    print!("{pubkey}");

    eprintln!();
    eprintln!(
        "  {}",
        console::style(
            "Paste this key into your SSH provider (e.g. GitHub → Settings → SSH keys)."
        )
        .dim()
    );

    Ok(())
}

fn run_ssh_list() -> Result<()> {
    let id_config = crate::config::load_identity_config()?;
    let labels = id_config.ssh.and_then(|s| s.labels).unwrap_or_default();

    if labels.is_empty() {
        eprintln!();
        eprintln!(
            "  no SSH labels registered — try {}",
            console::style("nex identity ssh --add github").bold()
        );
        eprintln!();
        return Ok(());
    }

    let path = default_path();
    if !path.exists() {
        bail!("no identity — run `nex identity init` first");
    }

    let passphrase = read_passphrase("Passphrase")?;
    let root = load_root(&path, &passphrase)?;
    let deriver = KeyDeriver::new(root.as_bytes());

    eprintln!();
    output::status("ssh keys");
    for label in &labels {
        let mut seed = deriver
            .derive_ssh_user_key(label)
            .context("invalid SSH key label")?;
        let fingerprint = styrene_identity::format::ssh_pubkey_fingerprint(&seed);
        seed.zeroize();
        eprintln!("  {}  {fingerprint}", console::style(label).bold());
    }
    eprintln!();

    Ok(())
}

fn run_ssh_add(label: &str) -> Result<()> {
    crate::config::append_to_list("identity.ssh.labels", label)?;
    eprintln!(
        "  {} registered SSH label: {}",
        console::style("").green().bold(),
        console::style(label).bold()
    );
    // Show the key immediately
    run_ssh_export(label)
}

// ── git ─────────────────────────────────────────────────────────────────────

pub fn run_git(show: bool) -> Result<()> {
    if show {
        return run_git_show();
    }
    run_git_configure()
}

fn run_git_configure() -> Result<()> {
    let id_config = crate::config::load_identity_config()?;
    let git_config = id_config.git.unwrap_or_default();

    let name = match git_config.name {
        Some(n) => n,
        None => {
            let input = crate::input::input().input_text("Full name for git commits", None)?;
            crate::config::set_nested_preference(
                "identity.git.name",
                toml::Value::String(input.clone()),
            )?;
            input
        }
    };

    let email = match git_config.email {
        Some(e) => e,
        None => {
            let input = crate::input::input().input_text("Email for git commits", None)?;
            crate::config::set_nested_preference(
                "identity.git.email",
                toml::Value::String(input.clone()),
            )?;
            input
        }
    };

    let path = default_path();
    if !path.exists() {
        bail!("no identity — run `nex identity init` first");
    }

    let passphrase = read_passphrase("Passphrase")?;
    let root = load_root(&path, &passphrase)?;
    let deriver = KeyDeriver::new(root.as_bytes());

    let mut seed = deriver.derive(KeyPurpose::Signing);
    let config_snippet = styrene_identity::format::git_signing_config(&seed);
    seed.zeroize();

    // Extract the signingkey value from the config snippet
    let signing_key = config_snippet
        .lines()
        .find(|l| l.contains("signingkey"))
        .and_then(|l| l.split("= ").nth(1))
        .context("failed to parse signing key from config")?;

    // Apply via git config --global
    let git = |args: &[&str]| -> Result<()> {
        let status = std::process::Command::new("git")
            .args(args)
            .status()
            .context("failed to run git")?;
        if !status.success() {
            bail!("git config failed");
        }
        Ok(())
    };

    git(&["config", "--global", "user.name", &name])?;
    git(&["config", "--global", "user.email", &email])?;
    git(&["config", "--global", "gpg.format", "ssh"])?;
    git(&["config", "--global", "user.signingkey", signing_key])?;
    git(&["config", "--global", "commit.gpgsign", "true"])?;

    eprintln!();
    output::status("git signing configured");
    eprintln!("  name     {name}");
    eprintln!("  email    {email}");
    eprintln!("  signing  enabled (SSH key)");
    eprintln!();

    Ok(())
}

fn run_git_show() -> Result<()> {
    let get = |key: &str| -> String {
        std::process::Command::new("git")
            .args(["config", "--global", key])
            .output()
            .ok()
            .filter(|o| o.status.success())
            .map(|o| crate::exec::captured_text(&o.stdout).trim().to_string())
            .unwrap_or_else(|| console::style("(not set)").dim().to_string())
    };

    eprintln!();
    output::status("git signing config");
    eprintln!("  user.name       {}", get("user.name"));
    eprintln!("  user.email      {}", get("user.email"));
    eprintln!("  gpg.format      {}", get("gpg.format"));
    eprintln!("  user.signingkey {}", get("user.signingkey"));
    eprintln!("  commit.gpgsign  {}", get("commit.gpgsign"));
    eprintln!();

    Ok(())
}

// ── wg ─────────────────────────────────────────────────────────────────────

pub fn run_wg() -> Result<()> {
    let path = default_path();
    if !path.exists() {
        bail!("no identity — run `nex identity init` first");
    }

    let passphrase = read_passphrase("Passphrase")?;
    let root = load_root(&path, &passphrase)?;
    let deriver = KeyDeriver::new(root.as_bytes());

    let mut seed = deriver.derive(KeyPurpose::WireGuard);
    let privkey = styrene_identity::format::wireguard_privkey(&seed);
    let pubkey = styrene_identity::format::wireguard_pubkey(&seed);
    seed.zeroize();

    eprintln!();
    output::status("wireguard key pair");
    eprintln!("  privkey  {privkey}");
    eprintln!();

    // Pubkey to stdout for piping
    print!("{pubkey}");

    eprintln!();
    eprintln!(
        "  {}",
        console::style(
            "Public key printed to stdout (pipeable). Private key shown above on stderr."
        )
        .dim()
    );

    Ok(())
}

// ── age ────────────────────────────────────────────────────────────────────

pub fn run_age() -> Result<()> {
    let path = default_path();
    if !path.exists() {
        bail!("no identity — run `nex identity init` first");
    }

    let passphrase = read_passphrase("Passphrase")?;
    let root = load_root(&path, &passphrase)?;
    let deriver = KeyDeriver::new(root.as_bytes());

    let mut seed = deriver.derive(KeyPurpose::Age);
    let pk = pubkey::x25519_public_key(&seed);

    eprintln!();
    output::status("age encryption key pair");
    eprintln!("  identity   {}", hex::encode(seed));
    eprintln!();

    // Recipient (public) to stdout for piping
    print!("{}", hex::encode(pk.as_bytes()));

    seed.zeroize();

    eprintln!();
    eprintln!(
        "  {}",
        console::style("Recipient (public) printed to stdout (pipeable). Identity (secret) shown above on stderr.").dim()
    );
    eprintln!(
        "  {}",
        console::style("Note: enable the age-format feature for Bech32-encoded AGE-SECRET-KEY-1.../age1... format.").dim()
    );

    Ok(())
}

// ── link ────────────────────────────────────────────────────────────────────

pub fn run_link(url: &str, code: Option<&str>, path: Option<PathBuf>) -> Result<()> {
    let path = path.unwrap_or_else(default_path);

    if !path.exists() {
        bail!(
            "no identity at {}\nrun `nex identity init` to create one",
            path.display()
        );
    }

    let passphrase = read_passphrase("Passphrase")?;
    let root = load_root(&path, &passphrase)?;

    let hash = identity_hash(&root);
    let pubkey_hex = hex::encode(identity_pubkey(&root));
    drop(root);

    let base_url = url.trim_end_matches('/');

    if let Some(invite_code) = code {
        output::status("linking identity to hub...");

        let body = serde_json::json!({
            "code": invite_code,
            "pubkey_hex": pubkey_hex,
        });

        let client = reqwest::blocking::Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .context("failed to build HTTP client")?;

        let resp = client
            .post(format!("{base_url}/enroll"))
            .json(&body)
            .send()
            .context("failed to connect to hub — check the URL and your network")?;

        if resp.status().is_success() {
            let data: serde_json::Value = resp.json().context("invalid response")?;
            let username = data["username"].as_str().unwrap_or("unknown");

            eprintln!();
            output::status("identity linked");
            eprintln!("  hub       {base_url}");
            eprintln!("  username  {username}");
            eprintln!("  hash      {hash}");
            eprintln!();
            eprintln!(
                "  {}",
                console::style("You can now sign in to hub services with your mesh identity.")
                    .dim()
            );
        } else {
            let status = resp.status();
            let body = resp.text().context("failed to read error response")?;
            let error: serde_json::Value =
                serde_json::from_str(&body).unwrap_or(serde_json::json!({"error": body}));
            let msg = error["error"].as_str().unwrap_or("unknown error");
            bail!("hub returned {status}: {msg}");
        }
    } else {
        eprintln!();
        output::status("identity ready to link");
        eprintln!("  hub       {base_url}");
        eprintln!("  pubkey    {pubkey_hex}");
        eprintln!("  hash      {hash}");
        eprintln!();
        eprintln!(
            "  {}",
            console::style("Paste the pubkey into the hub's admin UI (Existing Identity tab),")
                .dim()
        );
        eprintln!(
            "  {}",
            console::style(
                "or ask an admin for an invite code: nex identity link <url> --code <CODE>"
            )
            .dim()
        );
        eprintln!();

        let admin_url = format!("{base_url}/admin");
        if open::that(&admin_url).is_err() {
            eprintln!("  Open manually: {admin_url}");
        }
    }

    Ok(())
}