void-cli 0.0.2

CLI for void — anonymous encrypted source control
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
//! Repository context helpers for the void CLI.
//!
//! This module provides utilities for discovering and loading void repositories,
//! including finding the `.void` directory, reading encryption keys, and loading
//! configuration.

use std::cell::RefCell;
use std::fs;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use camino::Utf8PathBuf;
use ed25519_dalek::SigningKey;
use void_core::collab::manifest::{NostrPubKey, RecipientPubKey, SigningPubKey};
use void_core::collab::{decrypt_identity_keys, encrypt_identity_keys, Identity};
use void_core::crypto::KeyVault;
use void_core::support::void_context::{CryptoContext, NetworkConfig, RepoPaths, RepoMeta, SealConfig};
use void_core::{cid, config, refs, VoidContext};

use crate::output::CliError;

#[cfg(unix)]
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};

/// Result type for context operations.
pub type Result<T> = std::result::Result<T, CliError>;

const MAX_USERNAME_LEN: usize = 64;

// Thread-local override for get_void_home(), used by tests to avoid
// mutating the process-global HOME env var.
thread_local! {
    static VOID_HOME_OVERRIDE: RefCell<Option<PathBuf>> = RefCell::new(None);
}

/// RAII guard that overrides `get_void_home()` for the current thread.
///
/// Use in tests instead of `std::env::set_var("HOME", ...)` to avoid
/// race conditions in parallel test execution. Pass the user's home
/// directory; `.void` is appended automatically.
///
/// ```ignore
/// let _guard = VoidHomeGuard::new(tempdir.path());
/// // get_void_home() now returns tempdir/.void on this thread
/// ```
#[cfg(test)]
pub struct VoidHomeGuard(());

#[cfg(test)]
impl VoidHomeGuard {
    pub fn new(home_dir: impl Into<PathBuf>) -> Self {
        let void_home = home_dir.into().join(".void");
        VOID_HOME_OVERRIDE.with(|cell| {
            *cell.borrow_mut() = Some(void_home);
        });
        VoidHomeGuard(())
    }
}

#[cfg(test)]
impl Drop for VoidHomeGuard {
    fn drop(&mut self) {
        VOID_HOME_OVERRIDE.with(|cell| {
            *cell.borrow_mut() = None;
        });
    }
}

/// Find the `.void` directory by walking up from the given path.
///
/// Starts at the given path and walks up the directory tree looking for a
/// `.void` directory. Returns the path to the `.void` directory if found.
pub fn find_void_dir(path: &Path) -> Result<PathBuf> {
    let mut current = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());

    loop {
        let void_dir = current.join(".void");
        if void_dir.is_dir() {
            return Ok(void_dir);
        }

        match current.parent() {
            Some(parent) => current = parent.to_path_buf(),
            None => {
                return Err(CliError::not_initialized(
                    "not a void repository (or any parent up to mount point)",
                ))
            }
        }
    }
}

/// Build a complete `VoidContext` from the current working directory.
///
/// This is the main entry point for commands that need repository context.
/// Finds `.void`, loads encryption key via ECIES, reads config, and assembles
/// all subsystem configs into a single `VoidContext`.
pub fn build_void_context(cwd: &Path) -> Result<VoidContext> {
    let void_dir = find_void_dir(cwd)?;
    let root = void_dir
        .parent()
        .ok_or_else(|| CliError::internal("void_dir has no parent"))?
        .to_path_buf();

    // 1. Load encryption key via identity + ECIES unwrap
    let identity = load_identity_cached()?;
    let repo_key = void_core::collab::manifest::load_repo_key(&void_dir, Some(&identity))
        .map_err(void_err_to_cli)?;
    let key_bytes = *repo_key.as_bytes();
    let vault = Arc::new(
        KeyVault::new(key_bytes).map_err(|e| CliError::internal(e.to_string()))?,
    );

    // 2. Load config
    let cfg = config::load(&void_dir).map_err(|e| CliError::internal(e.to_string()))?;

    // 3. Resolve repo secret (config hex → vault-derived fallback)
    let secret = config::load_repo_secret(&void_dir, &vault)
        .map_err(|e| CliError::internal(e.to_string()))?;

    // 4. Try loading signing key non-interactively (keyring cache hit only).
    // If the keyring has cached identity keys, we get the signing key for free.
    // If not, signing_key stays None — commands that need it (commit, merge)
    // should call `load_signing_key()` themselves which will prompt for PIN.
    let signing_key = try_load_signing_key_cached();

    // 5. Build paths
    let root_utf8 =
        Utf8PathBuf::try_from(root).map_err(|e| CliError::internal(e.to_string()))?;
    let void_dir_utf8 = Utf8PathBuf::try_from(void_dir)
        .map_err(|e| CliError::internal(e.to_string()))?;
    let workspace_dir = void_dir_utf8.clone();

    Ok(VoidContext {
        paths: RepoPaths {
            root: root_utf8,
            void_dir: void_dir_utf8,
            workspace_dir,
        },
        crypto: CryptoContext {
            vault,
            epoch: 0, // default; epoch-based rotation is future work
            signing_key,
        },
        repo: RepoMeta {
            id: cfg.repo_id.clone(),
            name: cfg.repo_name.clone(),
            secret,
        },
        seal: SealConfig::from(&cfg),
        network: NetworkConfig::from(&cfg),
        user: cfg.user.clone(),
    })
}

/// Convert a void_core::VoidError into a CliError.
pub fn void_err_to_cli(err: void_core::VoidError) -> CliError {
    use void_core::VoidError;
    match err {
        VoidError::NotInitialized => {
            CliError::not_initialized("not a void repository (or any parent up to mount point)")
        }
        VoidError::NotFound(msg) => CliError::not_found(msg),
        VoidError::NothingToCommit(msg) => CliError::invalid_args(msg),
        VoidError::InvalidPattern(msg) => CliError::invalid_args(msg),
        other => CliError::internal(other.to_string()),
    }
}

/// Resolve a ref string (HEAD, branch name, tag name, or CID) to commit bytes.
///
/// Resolution order:
/// 1. "HEAD" - resolves HEAD reference
/// 2. Branch name - looks in refs/heads/
/// 3. Tag name - looks in refs/tags/
/// 4. Raw CID string - parses as CID
pub fn resolve_ref(void_dir: impl AsRef<Path>, ref_str: &str) -> Result<void_core::crypto::CommitCid> {
    let void_dir = Utf8PathBuf::try_from(void_dir.as_ref().to_path_buf())
        .map_err(|e| CliError::internal(format!("invalid path: {}", e)))?;

    // HEAD
    if ref_str == "HEAD" {
        return refs::resolve_head(&void_dir)
            .map_err(void_err_to_cli)?
            .ok_or_else(|| CliError::not_found("HEAD is not set"));
    }

    // Try as branch name
    if let Ok(Some(commit_cid)) = refs::read_branch(&void_dir, ref_str) {
        return Ok(commit_cid);
    }

    // Try as tag name
    if let Ok(Some(commit_cid)) = refs::read_tag(&void_dir, ref_str) {
        return Ok(commit_cid);
    }

    // Try as raw CID string
    cid::parse(ref_str)
        .map(|c| void_core::crypto::CommitCid::from_bytes(cid::to_bytes(&c)))
        .map_err(|_| CliError::not_found(format!("unknown reference: {}", ref_str)))
}

/// Check if a signing key exists (new format: encrypted private keys in keys.enc).
pub fn signing_key_exists() -> bool {
    get_identity_dir().join("keys.enc").exists()
}

/// Load the signing key from disk, using keyring cache when available.
///
/// Delegates to `load_identity_cached()` which checks the OS keyring first,
/// falling back to PIN prompt + decrypt on cache miss.
pub fn load_signing_key() -> Result<SigningKey> {
    let identity = load_identity_cached()?;
    Ok(identity.signing_key().clone())
}

/// Try to load the signing key from keyring cache only (no PIN prompt).
///
/// Returns `Some(key)` if the identity is already cached in the OS keyring
/// (or in-memory mock during tests). Returns `None` on cache miss — never
/// prompts the user interactively.
fn try_load_signing_key_cached() -> Option<Arc<SigningKey>> {
    let identity_dir = get_identity_dir();
    let signing_pub_path = identity_dir.join("signing.pub");
    let signing_pubkey_hex = std::fs::read_to_string(&signing_pub_path).ok()?.trim().to_string();
    let identity = crate::keyring::load_cached_keys(&signing_pubkey_hex)?;
    Some(Arc::new(identity.signing_key().clone()))
}

/// Get the void home directory (~/.void).
///
/// Uses HOME environment variable if set, otherwise falls back to dirs::home_dir().
/// In tests, a thread-local override can be set via `VoidHomeGuard`.
pub fn get_void_home() -> PathBuf {
    let overridden = VOID_HOME_OVERRIDE.with(|cell| cell.borrow().clone());
    if let Some(path) = overridden {
        return path;
    }

    std::env::var("HOME")
        .ok()
        .map(PathBuf::from)
        .or_else(dirs::home_dir)
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".void")
}

/// Get the identity directory (~/.void/identity).
pub fn get_identity_dir() -> PathBuf {
    get_void_home().join("identity")
}

/// Load the full identity, using keyring cache when available.
///
/// Flow:
/// 1. Read signing pubkey hex from `~/.void/identity/signing.pub` (no PIN needed)
/// 2. Check OS keyring for cached decrypted keys
/// 3. On cache miss: prompt for PIN, decrypt, cache in keyring, return
pub fn load_identity_cached() -> Result<Identity> {
    let identity_dir = get_identity_dir();
    let signing_pub_path = identity_dir.join("signing.pub");

    if !signing_pub_path.exists() {
        return Err(CliError::not_found(
            "identity not initialized, run 'void identity init'",
        ));
    }

    let signing_pubkey_hex = fs::read_to_string(&signing_pub_path)
        .map_err(|e| CliError::io_error(e.to_string()))?
        .trim()
        .to_string();

    // Try keyring cache first
    if let Some(identity) = crate::keyring::load_cached_keys(&signing_pubkey_hex) {
        return Ok(identity);
    }

    // Cache miss: prompt for PIN and decrypt
    let pin = prompt_pin()?;
    let identity = load_identity_with_pin(&pin)?;

    // Cache for next time (silently ignores errors)
    crate::keyring::cache_keys(&signing_pubkey_hex, &identity);

    Ok(identity)
}

/// Load the full identity (signing + recipient keys) from disk using a PIN.
///
/// Decrypts `~/.void/identity/keys.enc` using the provided PIN.
/// Returns an `Identity` suitable for signing and encryption operations.
///
/// Prefer `load_identity_cached()` for normal use — it avoids re-prompting
/// by checking the OS keyring first.
pub fn load_identity_with_pin(pin: &str) -> Result<Identity> {
    let identity_dir = get_identity_dir();
    let keys_path = identity_dir.join("keys.enc");

    if !keys_path.exists() {
        return Err(CliError::not_found(
            "identity not initialized, run 'void identity init'",
        ));
    }

    let encrypted = fs::read(&keys_path).map_err(|e| CliError::io_error(e.to_string()))?;

    let (signing_secret, recipient_secret, nostr_secret) = decrypt_identity_keys(&encrypted, pin)
        .map_err(|e| CliError::internal(format!("failed to decrypt identity: {}", e)))?;

    Ok(match nostr_secret {
        Some(nostr) => Identity::from_bytes_with_nostr(&signing_secret, &recipient_secret, nostr),
        None => Identity::from_bytes(&signing_secret, &recipient_secret),
    })
}

/// Load public identity information without requiring a PIN.
///
/// Reads `~/.void/identity/{profile.json, signing.pub, recipient.pub}`.
/// Returns the optional username and public keys.
pub fn load_public_identity(
) -> Result<(Option<String>, SigningPubKey, RecipientPubKey, Option<NostrPubKey>)> {
    let identity_dir = get_identity_dir();
    let signing_pub_path = identity_dir.join("signing.pub");
    let recipient_pub_path = identity_dir.join("recipient.pub");

    if !signing_pub_path.exists() || !recipient_pub_path.exists() {
        return Err(CliError::not_found(
            "identity not initialized, run 'void identity init'",
        ));
    }

    // Read public keys
    let signing_hex =
        fs::read_to_string(&signing_pub_path).map_err(|e| CliError::io_error(e.to_string()))?;
    let recipient_hex =
        fs::read_to_string(&recipient_pub_path).map_err(|e| CliError::io_error(e.to_string()))?;

    let signing_bytes: [u8; 32] = hex::decode(signing_hex.trim())
        .map_err(|e| CliError::internal(format!("invalid signing pubkey hex: {}", e)))?
        .try_into()
        .map_err(|_| CliError::internal("signing pubkey must be 32 bytes"))?;

    let recipient_bytes: [u8; 32] = hex::decode(recipient_hex.trim())
        .map_err(|e| CliError::internal(format!("invalid recipient pubkey hex: {}", e)))?
        .try_into()
        .map_err(|_| CliError::internal("recipient pubkey must be 32 bytes"))?;

    // Read optional nostr pubkey
    let nostr_pub_path = identity_dir.join("nostr.pub");
    let nostr_pubkey = if nostr_pub_path.exists() {
        let nostr_hex =
            fs::read_to_string(&nostr_pub_path).map_err(|e| CliError::io_error(e.to_string()))?;
        let nostr_bytes: [u8; 32] = hex::decode(nostr_hex.trim())
            .map_err(|e| CliError::internal(format!("invalid nostr pubkey hex: {}", e)))?
            .try_into()
            .map_err(|_| CliError::internal("nostr pubkey must be 32 bytes"))?;
        Some(NostrPubKey::from_bytes(nostr_bytes))
    } else {
        None
    };

    // Read optional profile
    let username = load_username(&identity_dir);

    Ok((
        username,
        SigningPubKey::from_bytes(signing_bytes),
        RecipientPubKey::from_bytes(recipient_bytes),
        nostr_pubkey,
    ))
}

/// Save an identity to disk in the new format.
///
/// Writes:
/// - `profile.json` — username metadata (world-readable)
/// - `signing.pub` — hex-encoded Ed25519 public key (world-readable)
/// - `recipient.pub` — hex-encoded X25519 public key (world-readable)
/// - `keys.enc` — Argon2id+AES-256-GCM encrypted private keys (owner-only)
pub fn save_identity(
    identity: &Identity,
    username: &str,
    pin: &str,
    email: Option<&str>,
    signal: Option<&str>,
) -> Result<()> {
    validate_identity_username(username)?;

    let identity_dir = get_identity_dir();
    fs::create_dir_all(&identity_dir).map_err(|e| CliError::io_error(e.to_string()))?;
    set_mode_if_unix(&identity_dir, 0o700)?;

    // Write public keys (world-readable)
    fs::write(
        identity_dir.join("signing.pub"),
        identity.signing_pubkey().to_hex(),
    )
    .map_err(|e| CliError::io_error(e.to_string()))?;
    set_mode_if_unix(&identity_dir.join("signing.pub"), 0o644)?;

    fs::write(
        identity_dir.join("recipient.pub"),
        identity.recipient_pubkey().to_hex(),
    )
    .map_err(|e| CliError::io_error(e.to_string()))?;
    set_mode_if_unix(&identity_dir.join("recipient.pub"), 0o644)?;

    // Write profile (world-readable) with optional contact metadata
    let mut profile = serde_json::json!({ "username": username });
    if let Some(e) = email {
        profile["email"] = serde_json::Value::String(e.to_string());
    }
    if let Some(s) = signal {
        profile["signal"] = serde_json::Value::String(s.to_string());
    }
    fs::write(
        identity_dir.join("profile.json"),
        serde_json::to_string_pretty(&profile).map_err(|e| CliError::internal(e.to_string()))?,
    )
    .map_err(|e| CliError::io_error(e.to_string()))?;
    set_mode_if_unix(&identity_dir.join("profile.json"), 0o644)?;

    // Encrypt and write private keys (owner-only: 0o600)
    let signing_secret = identity.signing_key_bytes();
    let recipient_secret = identity.recipient_key_bytes();
    // Use the identity's Nostr key if present, or generate a random one
    let nostr_secret = identity
        .nostr_key_bytes()
        .unwrap_or_else(|| void_core::collab::NostrSecretKey::from_bytes(rand::random()));

    // Also save nostr public key if available
    if let Some(nostr_pub) = identity.nostr_pubkey() {
        fs::write(
            identity_dir.join("nostr.pub"),
            nostr_pub.to_hex(),
        )
        .map_err(|e| CliError::io_error(e.to_string()))?;
        set_mode_if_unix(&identity_dir.join("nostr.pub"), 0o644)?;
    }

    let encrypted = encrypt_identity_keys(&signing_secret, &recipient_secret, &nostr_secret, pin)
        .map_err(|e| CliError::internal(format!("failed to encrypt identity: {}", e)))?;

    // Write keys.enc with restricted permissions (0o600)
    let keys_path = identity_dir.join("keys.enc");
    let mut open_opts = fs::OpenOptions::new();
    open_opts.write(true).create(true).truncate(true);
    #[cfg(unix)]
    {
        open_opts.mode(0o600);
    }
    let mut keys_file = open_opts
        .open(&keys_path)
        .map_err(|e| CliError::io_error(e.to_string()))?;
    use std::io::Write;
    keys_file
        .write_all(&encrypted)
        .map_err(|e| CliError::io_error(e.to_string()))?;
    set_mode_if_unix(&keys_path, 0o600)?;

    Ok(())
}

/// Check if an identity has been initialized.
pub fn identity_exists() -> bool {
    get_identity_dir().join("keys.enc").exists()
}

/// Prompt the user for their PIN interactively.
///
/// Requires a TTY on stdin. If no TTY is available (e.g., piped input),
/// returns an error suggesting `void identity unlock`.
pub fn prompt_pin() -> Result<String> {
    if !std::io::stdin().is_terminal() {
        return Err(CliError::io_error(
            "PIN required but no TTY available. Run 'void identity unlock' in a terminal first.",
        ));
    }

    let pin = rpassword::prompt_password("Enter PIN: ")
        .map_err(|e| CliError::io_error(format!("failed to read PIN: {}", e)))?;

    if pin.is_empty() {
        return Err(CliError::invalid_args("PIN must not be empty"));
    }

    Ok(pin)
}

/// Validate identity username format.
///
/// Allowed characters: ASCII letters, digits, `_`, `-`, `.`
/// Length: 1..=64.
pub fn validate_identity_username(username: &str) -> Result<()> {
    if !is_valid_identity_username(username) {
        return Err(CliError::invalid_args(
            "invalid username: use 1-64 characters matching [A-Za-z0-9_.-]",
        ));
    }
    Ok(())
}

fn is_valid_identity_username(username: &str) -> bool {
    !username.is_empty()
        && username.len() <= MAX_USERNAME_LEN
        && username
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
}

/// Load the username from profile.json, returning None if not found.
fn load_username(identity_dir: &Path) -> Option<String> {
    let profile_path = identity_dir.join("profile.json");
    let content = fs::read_to_string(profile_path).ok()?;
    let value: serde_json::Value = serde_json::from_str(&content).ok()?;
    let username = value.get("username")?.as_str()?;
    if !is_valid_identity_username(username) {
        return None;
    }
    Some(username.to_string())
}

#[cfg(unix)]
fn set_mode_if_unix(path: &Path, mode: u32) -> Result<()> {
    let perms = fs::Permissions::from_mode(mode);
    fs::set_permissions(path, perms).map_err(|e| CliError::io_error(e.to_string()))
}

#[cfg(not(unix))]
fn set_mode_if_unix(_path: &Path, _mode: u32) -> Result<()> {
    Ok(())
}

/// Set up a test repository with a manifest containing an ECIES-wrapped key.
/// Creates:
/// - `<home_dir>/.void/identity/` with signing.pub, recipient.pub, profile.json
/// - `<void_dir>/contributors.json` with ECIES-wrapped key for the test identity
///
/// The returned `VoidHomeGuard` overrides `get_void_home()` for this thread.
/// Also pre-caches identity in keyring so no PIN prompt is needed.
///
/// # Usage
/// ```ignore
/// let dir = tempdir().unwrap();
/// let void_dir = dir.path().join(".void");
/// fs::create_dir(&void_dir).unwrap();
/// let key = [0x42u8; 32];
/// let home = tempdir().unwrap();
/// let _guard = setup_test_manifest(&void_dir, &key, home.path());
/// // build_void_context(dir.path()) now works via manifest
/// ```
#[cfg(test)]
pub fn setup_test_manifest(void_dir: &Path, key: &[u8; 32], home_dir: &Path) -> VoidHomeGuard {
    use std::time::{SystemTime, UNIX_EPOCH};
    use void_core::collab::manifest::{
        ecies_wrap_key, save_manifest, Contributor, ContributorId, Manifest, RepoKey,
    };
    use void_core::collab::Identity;

    let identity = Identity::generate();
    let signing_pub = identity.signing_pubkey();
    let recipient_pub = identity.recipient_pubkey();

    // Write identity files to home_dir/.void/identity/
    let identity_dir = home_dir.join(".void").join("identity");
    fs::create_dir_all(&identity_dir).unwrap();
    fs::write(identity_dir.join("signing.pub"), signing_pub.to_hex()).unwrap();
    fs::write(identity_dir.join("recipient.pub"), recipient_pub.to_hex()).unwrap();
    fs::write(
        identity_dir.join("profile.json"),
        r#"{"username":"test-user"}"#,
    )
    .unwrap();

    // Encrypt and write identity keys so load_identity_with_pin() works
    let signing_secret = identity.signing_key_bytes();
    let recipient_secret = identity.recipient_key_bytes();
    let nostr_secret = identity
        .nostr_key_bytes()
        .unwrap_or_else(|| void_core::collab::NostrSecretKey::from_bytes(rand::random()));
    let pin = "test-pin";
    let encrypted =
        void_core::collab::encrypt_identity_keys(&signing_secret, &recipient_secret, &nostr_secret, pin)
            .unwrap();
    fs::write(identity_dir.join("keys.enc"), &encrypted).unwrap();

    // Set up VoidHomeGuard so get_void_home() points to our temp home
    let guard = VoidHomeGuard::new(home_dir);

    // Pre-cache identity in keyring so no PIN prompt needed
    // (In test builds, this uses an in-memory store — no OS keychain access)
    crate::keyring::cache_keys(&signing_pub.to_hex(), &identity);

    // Create manifest with ECIES-wrapped key
    let mut manifest = Manifest::new(signing_pub.clone(), None);
    let wrapped = ecies_wrap_key(&RepoKey::from_bytes(*key), &recipient_pub).unwrap();
    manifest.read_keys.wrapped.insert(signing_pub.clone(), wrapped);

    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    manifest.contributors.push(Contributor {
        identity: ContributorId::new(signing_pub.clone(), recipient_pub),
        name: Some("test-user".to_string()),
        nostr_pubkey: None,
        added_at: timestamp,
        added_by: signing_pub,
        signature: vec![],
    });

    save_manifest(void_dir, &manifest).unwrap();

    guard
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;
    use void_core::collab::Identity;

    #[test]
    fn test_save_and_load_identity() {
        let dir = tempdir().unwrap();
        let identity_dir = dir.path().join("identity");
        // Temporarily override HOME so get_identity_dir() uses our tempdir
        // Instead, we test the save/load logic directly using the internal functions

        // Generate an identity
        let identity = Identity::generate();
        let username = "alice";
        let pin = "test-pin-123";

        // Manually save using the format
        fs::create_dir_all(&identity_dir).unwrap();
        fs::write(
            identity_dir.join("signing.pub"),
            identity.signing_pubkey().to_hex(),
        )
        .unwrap();
        fs::write(
            identity_dir.join("recipient.pub"),
            identity.recipient_pubkey().to_hex(),
        )
        .unwrap();
        let profile = serde_json::json!({ "username": username });
        fs::write(
            identity_dir.join("profile.json"),
            serde_json::to_string_pretty(&profile).unwrap(),
        )
        .unwrap();

        // Encrypt and save keys
        let signing_secret = identity.signing_key_bytes();
        let recipient_secret = identity.recipient_key_bytes();
        let nostr_secret = identity
            .nostr_key_bytes()
            .unwrap_or_else(|| void_core::collab::NostrSecretKey::from_bytes([0xbb; 32]));
        let encrypted = void_core::collab::encrypt_identity_keys(
            &signing_secret,
            &recipient_secret,
            &nostr_secret,
            pin,
        )
        .unwrap();
        fs::write(identity_dir.join("keys.enc"), &encrypted).unwrap();

        // Load and decrypt
        let loaded_encrypted = fs::read(identity_dir.join("keys.enc")).unwrap();
        let (dec_signing, dec_recipient, dec_nostr) =
            void_core::collab::decrypt_identity_keys(&loaded_encrypted, pin).unwrap();
        let loaded = match dec_nostr {
            Some(nostr) => {
                Identity::from_bytes_with_nostr(&dec_signing, &dec_recipient, nostr)
            }
            None => Identity::from_bytes(&dec_signing, &dec_recipient),
        };

        assert_eq!(identity.signing_pubkey(), loaded.signing_pubkey());
        assert_eq!(identity.recipient_pubkey(), loaded.recipient_pubkey());

        // Load public identity
        let signing_hex = fs::read_to_string(identity_dir.join("signing.pub")).unwrap();
        let recipient_hex = fs::read_to_string(identity_dir.join("recipient.pub")).unwrap();
        assert_eq!(signing_hex, identity.signing_pubkey().to_hex());
        assert_eq!(recipient_hex, identity.recipient_pubkey().to_hex());

        // Load username
        let loaded_username = load_username(&identity_dir);
        assert_eq!(loaded_username, Some("alice".to_string()));
    }

    #[test]
    fn test_load_username_missing_file() {
        let dir = tempdir().unwrap();
        assert_eq!(load_username(dir.path()), None);
    }

    #[test]
    fn test_load_username_invalid_json() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("profile.json"), "not json").unwrap();
        assert_eq!(load_username(dir.path()), None);
    }

    #[test]
    fn test_load_username_invalid_format() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("profile.json"),
            r#"{"username":"alice@invalid"}"#,
        )
        .unwrap();
        assert_eq!(load_username(dir.path()), None);
    }

    #[test]
    fn test_validate_identity_username() {
        assert!(validate_identity_username("alice").is_ok());
        assert!(validate_identity_username("alice-01.dev").is_ok());
        assert!(validate_identity_username("alice@dev").is_err());
        assert!(validate_identity_username("").is_err());
    }

    #[test]
    fn test_find_void_dir_at_root() {
        let dir = tempdir().unwrap();
        let void_dir = dir.path().join(".void");
        fs::create_dir(&void_dir).unwrap();

        let found = find_void_dir(dir.path()).unwrap();
        // Canonicalize both to handle macOS /private/var vs /var symlinks
        assert_eq!(
            found.canonicalize().unwrap(),
            void_dir.canonicalize().unwrap()
        );
    }

    #[test]
    fn test_find_void_dir_from_subdir() {
        let dir = tempdir().unwrap();
        let void_dir = dir.path().join(".void");
        fs::create_dir(&void_dir).unwrap();

        let subdir = dir.path().join("src").join("lib");
        fs::create_dir_all(&subdir).unwrap();

        let found = find_void_dir(&subdir).unwrap();
        // Canonicalize both to handle macOS /private/var vs /var symlinks
        assert_eq!(
            found.canonicalize().unwrap(),
            void_dir.canonicalize().unwrap()
        );
    }

    #[test]
    fn test_find_void_dir_not_found() {
        let dir = tempdir().unwrap();
        // Don't create .void

        let result = find_void_dir(dir.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_build_void_context_success() {
        let dir = tempdir().unwrap();
        let void_dir = dir.path().join(".void");
        fs::create_dir(&void_dir).unwrap();

        // build_void_context needs a config.json
        let cfg = void_core::config::Config::default();
        void_core::config::save(&void_dir, &cfg).unwrap();

        let key = [0x42u8; 32];
        let home = tempdir().unwrap();
        let _guard = setup_test_manifest(&void_dir, &key, home.path());

        let ctx = build_void_context(dir.path()).unwrap();
        // Vault should decrypt commits sealed with the same key
        let plaintext = b"test commit data";
        let sealed = ctx.crypto.vault.seal_commit(plaintext).unwrap();
        let (decrypted, _reader) = ctx.crypto.vault.open_commit(&sealed).unwrap();
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn test_build_void_context_no_manifest() {
        let dir = tempdir().unwrap();
        let void_dir = dir.path().join(".void");
        fs::create_dir(&void_dir).unwrap();

        // Set up identity but no manifest in void_dir
        let home = tempdir().unwrap();
        let identity = Identity::generate();
        let identity_dir = home.path().join(".void").join("identity");
        fs::create_dir_all(&identity_dir).unwrap();
        fs::write(identity_dir.join("signing.pub"), identity.signing_pubkey().to_hex()).unwrap();
        fs::write(identity_dir.join("recipient.pub"), identity.recipient_pubkey().to_hex()).unwrap();
        fs::write(identity_dir.join("profile.json"), r#"{"username":"test"}"#).unwrap();
        let signing_secret = identity.signing_key_bytes();
        let recipient_secret = identity.recipient_key_bytes();
        let nostr_secret = identity.nostr_key_bytes()
            .unwrap_or_else(|| void_core::collab::NostrSecretKey::from_bytes(rand::random()));
        let encrypted = void_core::collab::encrypt_identity_keys(
            &signing_secret, &recipient_secret, &nostr_secret, "test-pin",
        ).unwrap();
        fs::write(identity_dir.join("keys.enc"), &encrypted).unwrap();
        let _guard = VoidHomeGuard::new(home.path());
        crate::keyring::cache_keys(&identity.signing_pubkey().to_hex(), &identity);

        let result = build_void_context(dir.path());
        assert!(result.is_err());
    }

}