biovault 0.1.124

A bioinformatics data vault CLI tool
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
//! CLI commands for managing contacts (trusted public key bundles)
//!
//! Contacts are peers whose public keys you've imported, allowing you to send
//! encrypted messages and collaborate with them.

use crate::config::Config;
use anyhow::{Context, Result};
use clap::Subcommand;
use colored::Colorize;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

#[derive(Subcommand)]
pub enum ContactsCommands {
    #[command(about = "List your trusted contacts")]
    List {
        #[arg(long, help = "Output as JSON")]
        json: bool,
    },

    #[command(about = "Scan network for discoverable peers")]
    Scan {
        #[arg(long, help = "Output as JSON")]
        json: bool,
    },

    #[command(about = "Import a contact's public key from their datasite")]
    Import {
        #[arg(help = "Email/identity of the contact to import")]
        identity: String,
    },

    #[command(about = "Remove a contact from your trusted list")]
    Remove {
        #[arg(help = "Email/identity of the contact to remove")]
        identity: String,

        #[arg(long, help = "Skip confirmation prompt")]
        yes: bool,
    },

    #[command(about = "Trust a contact's changed key (re-import)")]
    Trust {
        #[arg(help = "Email/identity of the contact to trust")]
        identity: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContactInfo {
    pub identity: String,
    pub fingerprint: String,
    pub bundle_path: String,
    #[serde(default)]
    pub has_changed: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub local_fingerprint: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoveredPeer {
    pub identity: String,
    pub fingerprint: String,
    pub did_path: String,
    pub is_imported: bool,
    #[serde(default)]
    pub has_changed: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanResult {
    pub contacts: Vec<DiscoveredPeer>,
    pub discovered: Vec<DiscoveredPeer>,
    pub current_identity: String,
}

/// Handle contacts subcommands
pub async fn handle(command: ContactsCommands, config: &Config) -> Result<()> {
    match command {
        ContactsCommands::List { json } => list_contacts(config, json),
        ContactsCommands::Scan { json } => scan_network(config, json),
        ContactsCommands::Import { identity } => import_contact(config, &identity),
        ContactsCommands::Remove { identity, yes } => remove_contact(config, &identity, yes),
        ContactsCommands::Trust { identity } => trust_changed_key(config, &identity),
    }
}

/// Get paths for vault and datasites
fn resolve_paths(config: &Config) -> Result<(PathBuf, PathBuf)> {
    let data_dir = config.get_syftbox_data_dir()?;

    // Vault is in .biovault under data dir
    let vault_path = data_dir.join(".biovault").join("vault");

    // Datasites dir
    let datasites_dir = if data_dir
        .file_name()
        .map(|n| n == "datasites")
        .unwrap_or(false)
    {
        data_dir.clone()
    } else {
        data_dir.join("datasites")
    };

    Ok((datasites_dir, vault_path))
}

/// List all trusted contacts
fn list_contacts(config: &Config, json_output: bool) -> Result<()> {
    let (_, vault_path) = resolve_paths(config)?;
    let bundles_dir = vault_path.join("bundles");

    let mut contacts = Vec::new();

    if bundles_dir.exists() {
        for entry in std::fs::read_dir(&bundles_dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.extension().map(|e| e == "json").unwrap_or(false) {
                if let Ok(info) = crate::syftbox::syc::parse_public_bundle_file(&path) {
                    contacts.push(ContactInfo {
                        identity: info.identity,
                        fingerprint: info.fingerprint,
                        bundle_path: path.to_string_lossy().to_string(),
                        has_changed: false,
                        local_fingerprint: None,
                    });
                }
            }
        }
    }

    contacts.sort_by(|a, b| a.identity.to_lowercase().cmp(&b.identity.to_lowercase()));

    if json_output {
        println!("{}", serde_json::to_string_pretty(&contacts)?);
        return Ok(());
    }

    if contacts.is_empty() {
        println!("No trusted contacts yet.");
        println!(
            "\nUse {} to discover peers on the network.",
            "bv contacts scan".cyan()
        );
        println!(
            "Use {} to add a contact.",
            "bv contacts import <email>".cyan()
        );
        return Ok(());
    }

    println!("\n👥 {} Trusted Contacts", "Your".bold());
    println!("═══════════════════════════════════════════════════════════════\n");

    for contact in &contacts {
        let short_fp = &contact.fingerprint[..16.min(contact.fingerprint.len())];
        println!("  📧 {}", contact.identity.green());
        println!("     🔑 {}...", short_fp.dimmed());
        println!();
    }

    println!("Total: {} contact(s)", contacts.len());

    Ok(())
}

/// Scan network for discoverable peers
fn scan_network(config: &Config, json_output: bool) -> Result<()> {
    let current_email = config.email.clone();
    let (datasites_dir, vault_path) = resolve_paths(config)?;
    let bundles_dir = vault_path.join("bundles");

    let mut contacts = Vec::new();
    let mut discovered = Vec::new();

    let current_slug = syftbox_sdk::sanitize_identity(&current_email);

    if datasites_dir.exists() {
        for entry in std::fs::read_dir(&datasites_dir)? {
            let entry = entry?;
            let datasite_path = entry.path();

            if !datasite_path.is_dir() {
                continue;
            }

            let did_path = datasite_path.join("public").join("crypto").join("did.json");

            if !did_path.exists() {
                continue;
            }

            if let Ok(remote_info) = crate::syftbox::syc::parse_public_bundle_file(&did_path) {
                let slug = syftbox_sdk::sanitize_identity(&remote_info.identity);

                // Skip current identity
                if slug == current_slug {
                    continue;
                }

                let local_bundle_path = bundles_dir.join(format!("{slug}.json"));
                let is_imported = local_bundle_path.exists();

                let has_changed = if is_imported {
                    match crate::syftbox::syc::parse_public_bundle_file(&local_bundle_path) {
                        Ok(local_info) => local_info.fingerprint != remote_info.fingerprint,
                        Err(_) => false,
                    }
                } else {
                    false
                };

                let peer = DiscoveredPeer {
                    identity: remote_info.identity,
                    fingerprint: remote_info.fingerprint,
                    did_path: did_path.to_string_lossy().to_string(),
                    is_imported,
                    has_changed,
                };

                if is_imported {
                    contacts.push(peer);
                } else {
                    discovered.push(peer);
                }
            }
        }
    }

    contacts.sort_by(|a, b| a.identity.to_lowercase().cmp(&b.identity.to_lowercase()));
    discovered.sort_by(|a, b| a.identity.to_lowercase().cmp(&b.identity.to_lowercase()));

    let result = ScanResult {
        contacts,
        discovered,
        current_identity: current_email.clone(),
    };

    if json_output {
        println!("{}", serde_json::to_string_pretty(&result)?);
        return Ok(());
    }

    println!(
        "\n🔍 {} {}",
        "Network Scan for".bold(),
        current_email.cyan()
    );
    println!("═══════════════════════════════════════════════════════════════\n");

    // Show contacts with key changes
    let changed: Vec<_> = result.contacts.iter().filter(|c| c.has_changed).collect();
    if !changed.is_empty() {
        println!("⚠️  {} Key(s) Changed:", "Warning:".yellow().bold());
        for peer in changed {
            println!("   {} {}", "".yellow(), peer.identity.yellow());
            println!(
                "      Run: {} to trust the new key",
                format!("bv contacts trust {}", peer.identity).cyan()
            );
        }
        println!();
    }

    // Show trusted contacts
    println!(
        "{} Trusted Contact(s):",
        result.contacts.len().to_string().green()
    );
    if result.contacts.is_empty() {
        println!("   (none)");
    } else {
        for peer in &result.contacts {
            let status = if peer.has_changed {
                "⚠️ key changed".yellow().to_string()
            } else {
                "".green().to_string()
            };
            println!("   {} {} {}", status, peer.identity, "".dimmed());
        }
    }
    println!();

    // Show discoverable peers
    println!(
        "🌐 {} Discoverable Peer(s):",
        result.discovered.len().to_string().blue()
    );
    if result.discovered.is_empty() {
        println!("   (none found)");
    } else {
        for peer in &result.discovered {
            let short_fp = &peer.fingerprint[..16.min(peer.fingerprint.len())];
            println!("   📧 {}", peer.identity);
            println!("      🔑 {}...", short_fp.dimmed());
        }
    }
    println!();

    if !result.discovered.is_empty() {
        println!(
            "💡 To add a contact: {}",
            "bv contacts import <email>".cyan()
        );
    }

    Ok(())
}

/// Import a contact's public key bundle
fn import_contact(config: &Config, identity: &str) -> Result<()> {
    let (datasites_dir, vault_path) = resolve_paths(config)?;
    let bundles_dir = vault_path.join("bundles");

    // Ensure bundles directory exists
    if !bundles_dir.exists() {
        std::fs::create_dir_all(&bundles_dir).context("Failed to create bundles directory")?;
    }

    let did_path = datasites_dir
        .join(identity)
        .join("public")
        .join("crypto")
        .join("did.json");

    if !did_path.exists() {
        anyhow::bail!(
            "DID not found for {}. Make sure the peer's datasite is synced.",
            identity
        );
    }

    let remote_info = crate::syftbox::syc::parse_public_bundle_file(&did_path)
        .context("Failed to parse DID file")?;

    let slug = syftbox_sdk::sanitize_identity(&remote_info.identity);
    let local_bundle_path = bundles_dir.join(format!("{slug}.json"));

    let was_existing = local_bundle_path.exists();

    std::fs::copy(&did_path, &local_bundle_path).context("Failed to copy public key bundle")?;

    let action = if was_existing { "Updated" } else { "Imported" };
    let short_fp = &remote_info.fingerprint[..16.min(remote_info.fingerprint.len())];

    println!("\n{} contact: {}", action, remote_info.identity.green());
    println!("   🔑 Fingerprint: {}...", short_fp);
    println!("   📁 Saved to: {}", local_bundle_path.display());
    println!();
    println!(
        "You can now send encrypted messages with: {}",
        format!("bv message send {} \"Hello!\"", identity).cyan()
    );

    Ok(())
}

/// Remove a contact from trusted list
fn remove_contact(config: &Config, identity: &str, skip_confirm: bool) -> Result<()> {
    let (_, vault_path) = resolve_paths(config)?;
    let bundles_dir = vault_path.join("bundles");

    let slug = syftbox_sdk::sanitize_identity(identity);
    let bundle_path = bundles_dir.join(format!("{slug}.json"));

    if !bundle_path.exists() {
        anyhow::bail!("Contact '{}' not found in your trusted list.", identity);
    }

    if !skip_confirm {
        use dialoguer::Confirm;
        let confirmed = Confirm::new()
            .with_prompt(format!(
                "Remove {} from your contacts?\nYou won't be able to send encrypted messages until you re-add them.",
                identity
            ))
            .default(false)
            .interact()
            .unwrap_or(false);

        if !confirmed {
            println!("Cancelled.");
            return Ok(());
        }
    }

    std::fs::remove_file(&bundle_path).context("Failed to remove contact bundle")?;

    println!("\n🗑️  Removed contact: {}", identity.yellow());
    println!(
        "   To re-add: {}",
        format!("bv contacts import {}", identity).cyan()
    );

    Ok(())
}

/// Trust a changed key by re-importing
fn trust_changed_key(config: &Config, identity: &str) -> Result<()> {
    println!("🔄 Re-importing key for {}...", identity);
    import_contact(config, identity)?;
    println!("\n✅ New key trusted for {}", identity.green());
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn create_test_config(temp: &TempDir) -> Config {
        crate::config::set_test_syftbox_data_dir(temp.path());
        crate::config::set_test_biovault_home(temp.path().join(".biovault"));

        Config {
            email: "test@example.com".to_string(),
            syftbox_config: None,
            version: None,
            binary_paths: None,
            syftbox_credentials: None,
        }
    }

    #[test]
    fn test_list_contacts_empty() {
        let temp = TempDir::new().unwrap();
        let config = create_test_config(&temp);

        // Should not error on empty bundles
        let result = list_contacts(&config, false);
        assert!(result.is_ok());

        crate::config::clear_test_syftbox_data_dir();
        crate::config::clear_test_biovault_home();
    }

    #[test]
    fn test_scan_network_empty() {
        let temp = TempDir::new().unwrap();
        let config = create_test_config(&temp);

        // Should not error on empty datasites
        let result = scan_network(&config, false);
        assert!(result.is_ok());

        crate::config::clear_test_syftbox_data_dir();
        crate::config::clear_test_biovault_home();
    }

    #[test]
    fn test_import_contact_not_found() {
        let temp = TempDir::new().unwrap();
        let config = create_test_config(&temp);

        // Should fail gracefully for non-existent contact
        let result = import_contact(&config, "nonexistent@example.com");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("DID not found"));

        crate::config::clear_test_syftbox_data_dir();
        crate::config::clear_test_biovault_home();
    }

    #[test]
    fn test_remove_contact_not_found() {
        let temp = TempDir::new().unwrap();
        let config = create_test_config(&temp);

        // Should fail gracefully for non-existent contact
        let result = remove_contact(&config, "nonexistent@example.com", true);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));

        crate::config::clear_test_syftbox_data_dir();
        crate::config::clear_test_biovault_home();
    }
}