biovault 0.1.117

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
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
use crate::config::Config;
use crate::syftbox::syc::{
    import_public_bundle, parse_public_bundle_file, provision_local_identity_with_options,
    restore_identity_from_mnemonic,
};
use crate::Result;
use anyhow::{anyhow, Context};
use clap::Subcommand;
use serde::Serialize;
use std::fs;
use std::path::{Path, PathBuf};
use syftbox_sdk::PublicBundleInfo;

#[derive(Subcommand, Debug)]
pub enum KeyCommands {
    /// Generate a key for an identity if missing; prints recovery mnemonic once.
    Generate {
        #[arg(long, help = "Identity email (defaults to config email)")]
        email: Option<String>,
        #[arg(
            long,
            help = "Override SyftBox data dir (defaults to BioVault SyftBox config data_dir)"
        )]
        data_dir: Option<PathBuf>,
        #[arg(
            long,
            help = "Override Syft Crypto vault path (defaults to datasites/.syc)"
        )]
        vault: Option<PathBuf>,
        #[arg(long, help = "Force overwrite existing key material")]
        force: bool,
        #[arg(long, help = "Output JSON instead of human-readable text")]
        json: bool,
    },
    /// Import a public bundle into the vault (TOFU-checked).
    Import {
        #[arg(help = "Path to public bundle (e.g., datasites/<email>/public/crypto/did.json)")]
        bundle: PathBuf,
        #[arg(
            long,
            help = "Expected identity inside bundle; default inferred from bundle"
        )]
        email: Option<String>,
        #[arg(long, help = "Skip TOFU fingerprint check if existing bundle differs")]
        ignore_tofu: bool,
        #[arg(long, help = "Override vault path")]
        vault: Option<PathBuf>,
        #[arg(long, help = "Override data dir (used for exported copy refresh)")]
        data_dir: Option<PathBuf>,
        #[arg(long, help = "Output JSON instead of human-readable text")]
        json: bool,
    },
    /// Export the public bundle for an identity.
    Export {
        #[arg(long, help = "Identity email (defaults to config email)")]
        email: Option<String>,
        #[arg(
            long,
            help = "Output path (defaults to datasites/<id>/public/crypto/did.json)"
        )]
        output: Option<PathBuf>,
        #[arg(long, help = "Override vault path")]
        vault: Option<PathBuf>,
        #[arg(long, help = "Override data dir")]
        data_dir: Option<PathBuf>,
        #[arg(long, help = "Output JSON instead of human-readable text")]
        json: bool,
    },
    /// Restore key material from a BIP-39 mnemonic.
    Restore {
        #[arg(long, help = "Identity email")]
        email: String,
        #[arg(long, help = "BIP-39 recovery phrase")]
        mnemonic: String,
        #[arg(long, help = "Override vault path")]
        vault: Option<PathBuf>,
        #[arg(long, help = "Override data dir")]
        data_dir: Option<PathBuf>,
        #[arg(long, help = "Output JSON instead of human-readable text")]
        json: bool,
    },
    /// Wipe key and bundle for an identity.
    Wipe {
        #[arg(long, help = "Identity email (defaults to config email)")]
        email: Option<String>,
        #[arg(long, help = "Override vault path")]
        vault: Option<PathBuf>,
        #[arg(long, help = "Override data dir")]
        data_dir: Option<PathBuf>,
        #[arg(long, help = "Output JSON instead of human-readable text")]
        json: bool,
    },
    /// Show key/bundle status for an identity.
    Status {
        #[arg(long, help = "Identity email (defaults to config email)")]
        email: Option<String>,
        #[arg(long, help = "Override vault path")]
        vault: Option<PathBuf>,
        #[arg(long, help = "Override data dir")]
        data_dir: Option<PathBuf>,
        #[arg(long, help = "Output JSON instead of human-readable text")]
        json: bool,
    },
    /// List identities present in the vault.
    VaultList {
        #[arg(long, help = "Override vault path")]
        vault: Option<PathBuf>,
        #[arg(long, help = "Output JSON instead of human-readable text")]
        json: bool,
    },
}

pub async fn handle(command: KeyCommands, config: &Config) -> Result<()> {
    match command {
        KeyCommands::Generate {
            email,
            data_dir,
            vault,
            force,
            json,
        } => {
            let email = resolve_email(email.as_deref(), config)?;
            let (data_root, vault_path) =
                resolve_paths(config, data_dir.as_deref(), vault.as_deref())?;
            let outcome =
                provision_local_identity_with_options(&email, &data_root, Some(&vault_path), force)
                    .with_context(|| format!("failed to generate identity {email}"))?;
            let bundle = parse_public_bundle_file(&outcome.public_bundle_path)?;
            let result = GenerateResult {
                identity: bundle.identity.clone(),
                fingerprint: bundle.fingerprint.clone(),
                vault: outcome.vault_path.to_string_lossy().to_string(),
                bundle_path: outcome.bundle_path.to_string_lossy().to_string(),
                export_path: outcome.public_bundle_path.to_string_lossy().to_string(),
                mnemonic: outcome.recovery_mnemonic.clone(),
            };
            if json {
                print_json(&result)?;
            } else {
                println!("✓ Identity: {}", bundle.identity);
                println!("  Fingerprint: {}", bundle.fingerprint);
                println!("  Vault: {}", outcome.vault_path.display());
                println!("  Bundle: {}", outcome.bundle_path.display());
                println!("  Exported: {}", outcome.public_bundle_path.display());
                if let Some(mnemonic) = outcome.recovery_mnemonic {
                    println!("  Recovery mnemonic (store securely, shown once): {mnemonic}");
                }
            }
        }
        KeyCommands::Import {
            bundle,
            email,
            ignore_tofu,
            vault,
            data_dir,
            json,
        } => {
            let info = parse_public_bundle_file(&bundle)?;
            let expected_identity = email.as_deref().unwrap_or(&info.identity);
            if info.identity != expected_identity {
                return Err(anyhow!(
                    "bundle identity mismatch: expected {}, found {}",
                    expected_identity,
                    info.identity
                )
                .into());
            }
            let (data_root, vault_path) =
                resolve_paths(config, data_dir.as_deref(), vault.as_deref())?;

            if let Some(existing) = load_existing_bundle(&vault_path, &info.identity)? {
                if existing.fingerprint != info.fingerprint && !ignore_tofu {
                    return Err(anyhow!(
                        "TOFU violation: bundle for {} already present with fingerprint {} (incoming {}) – rerun with --ignore-tofu to overwrite",
                        info.identity,
                        existing.fingerprint,
                        info.fingerprint
                    )
                    .into());
                }
            }

            let parsed = import_public_bundle(
                &bundle,
                Some(expected_identity),
                &vault_path,
                Some(&data_root),
                Some(config.email.as_str()),
            )
            .with_context(|| format!("failed to import bundle from {}", bundle.display()))?;
            let result = ImportResult {
                identity: parsed.identity.clone(),
                fingerprint: parsed.fingerprint.clone(),
                vault: vault_path.to_string_lossy().to_string(),
                bundle_path: vault_path
                    .join("bundles")
                    .join(format!(
                        "{}.json",
                        syftbox_sdk::sanitize_identity(&parsed.identity)
                    ))
                    .to_string_lossy()
                    .to_string(),
            };
            if json {
                print_json(&result)?;
            } else {
                println!("✓ Imported bundle for {}", parsed.identity);
                println!("  Fingerprint: {}", parsed.fingerprint);
                println!("  Vault: {}", vault_path.display());
            }
        }
        KeyCommands::Export {
            email,
            output,
            vault,
            data_dir,
            json,
        } => {
            let email = resolve_email(email.as_deref(), config)?;
            let (data_root, vault_path) =
                resolve_paths(config, data_dir.as_deref(), vault.as_deref())?;
            let bundle_path = output.unwrap_or_else(|| {
                data_root
                    .join("datasites")
                    .join(&email)
                    .join("public/crypto/did.json")
            });
            let info = load_existing_bundle(&vault_path, &email)?.ok_or_else(|| {
                crate::error::Error::Anyhow(anyhow!("no bundle found in vault for {email}"))
            })?;
            if let Some(parent) = bundle_path.parent() {
                fs::create_dir_all(parent)
                    .with_context(|| format!("failed to create {}", parent.display()))?;
            }
            fs::write(
                &bundle_path,
                serde_json::to_vec_pretty(&info.value)
                    .context("failed to serialise public bundle")?,
            )
            .with_context(|| format!("failed to write {}", bundle_path.display()))?;
            let result = ExportResult {
                identity: email.clone(),
                fingerprint: info.fingerprint,
                output: bundle_path.to_string_lossy().to_string(),
                vault_bundle: vault_path
                    .join("bundles")
                    .join(format!("{}.json", syftbox_sdk::sanitize_identity(&email)))
                    .to_string_lossy()
                    .to_string(),
            };
            if json {
                print_json(&result)?;
            } else {
                println!(
                    "✓ Exported bundle for {} -> {}",
                    email,
                    bundle_path.display()
                );
            }
        }
        KeyCommands::Restore {
            email,
            mnemonic,
            vault,
            data_dir,
            json,
        } => {
            let (data_root, vault_path) =
                resolve_paths(config, data_dir.as_deref(), vault.as_deref())?;
            let outcome =
                restore_identity_from_mnemonic(&email, &mnemonic, &data_root, Some(&vault_path))
                    .with_context(|| format!("failed to restore identity {}", email))?;
            let bundle = parse_public_bundle_file(&outcome.public_bundle_path)?;
            let result = GenerateResult {
                identity: bundle.identity.clone(),
                fingerprint: bundle.fingerprint.clone(),
                vault: outcome.vault_path.to_string_lossy().to_string(),
                bundle_path: outcome.bundle_path.to_string_lossy().to_string(),
                export_path: outcome.public_bundle_path.to_string_lossy().to_string(),
                mnemonic: outcome.recovery_mnemonic.clone(),
            };
            if json {
                print_json(&result)?;
            } else {
                println!("✓ Restored identity {}", bundle.identity);
                println!("  Fingerprint: {}", bundle.fingerprint);
                println!("  Vault: {}", outcome.vault_path.display());
                println!("  Bundle: {}", outcome.bundle_path.display());
            }
        }
        KeyCommands::Wipe {
            email,
            vault,
            data_dir,
            json,
        } => {
            let email = resolve_email(email.as_deref(), config)?;
            let (data_root, vault_path) =
                resolve_paths(config, data_dir.as_deref(), vault.as_deref())?;
            let slug = syftbox_sdk::sanitize_identity(&email);
            let key_path = vault_path.join("keys").join(format!("{slug}.key"));
            let bundle_path = vault_path.join("bundles").join(format!("{slug}.json"));
            let export_path = resolve_export_path(&data_root, &email);
            let mut removed_any = false;
            for path in [&key_path, &bundle_path, &export_path] {
                if path.exists() {
                    fs::remove_file(path)
                        .with_context(|| format!("failed to remove {}", path.display()))?;
                    removed_any = true;
                }
            }
            let result = WipeResult {
                identity: email.clone(),
                removed: removed_any,
                key_path: key_path.to_string_lossy().to_string(),
                bundle_path: bundle_path.to_string_lossy().to_string(),
                export_path: export_path.to_string_lossy().to_string(),
            };
            if json {
                print_json(&result)?;
            } else if removed_any {
                println!("✓ Wiped key material for {}", email);
            } else {
                println!("ℹ️ No key material found for {}", email);
            }
        }
        KeyCommands::Status {
            email,
            vault,
            data_dir,
            json,
        } => {
            let email = resolve_email(email.as_deref(), config)?;
            let (data_root, vault_path) =
                resolve_paths(config, data_dir.as_deref(), vault.as_deref())?;
            let bundle_path = vault_path
                .join("bundles")
                .join(format!("{}.json", syftbox_sdk::sanitize_identity(&email)));
            let export_path = resolve_export_path(&data_root, &email);
            let existing = load_existing_bundle(&vault_path, &email)?;

            let mut export_fp = None;
            let mut export_matches = None;
            if let Some(info) = existing.as_ref() {
                if export_path.exists() {
                    if let Ok(einfo) = parse_public_bundle_file(&export_path) {
                        export_matches = Some(einfo.fingerprint == info.fingerprint);
                        export_fp = Some(einfo.fingerprint);
                    }
                }
            }
            let result = StatusResult {
                identity: email.clone(),
                vault: vault_path.to_string_lossy().to_string(),
                bundle: bundle_path.to_string_lossy().to_string(),
                export: export_path.to_string_lossy().to_string(),
                vault_fingerprint: existing.as_ref().map(|i| i.fingerprint.clone()),
                export_fingerprint: export_fp,
                export_matches,
            };
            if json {
                print_json(&result)?;
            } else {
                println!("Identity: {}", email);
                println!("Vault: {}", vault_path.display());
                println!("Bundle: {}", bundle_path.display());
                println!("Export: {}", export_path.display());
                match existing {
                    Some(info) => {
                        println!("  Vault bundle fingerprint: {}", info.fingerprint);
                        if let Some(fp) = result.export_fingerprint {
                            println!(
                                "  Export fingerprint: {} (matches vault: {})",
                                fp,
                                result.export_matches.unwrap_or(false)
                            );
                        } else if export_path.exists() {
                            println!("  Export unreadable");
                        } else {
                            println!("  Export missing");
                        }
                    }
                    None => {
                        println!("  No bundle found in vault");
                    }
                }
            }
        }
        KeyCommands::VaultList { vault, json } => {
            let (vault_path, _) = resolve_vault_only(config, vault.as_deref())?;
            let keys_dir = vault_path.join("keys");
            if !keys_dir.exists() {
                let result = VaultListResult {
                    vault: vault_path.to_string_lossy().to_string(),
                    entries: Vec::new(),
                };
                if json {
                    print_json(&result)?;
                } else {
                    println!("(no vault at {})", vault_path.display());
                }
                return Ok(());
            }
            let mut entries = Vec::new();
            for entry in fs::read_dir(&keys_dir)? {
                let entry = entry?;
                if entry.file_type()?.is_file() {
                    if let Some(id) = entry
                        .file_name()
                        .to_str()
                        .and_then(|s| s.strip_suffix(".key"))
                    {
                        let slug = syftbox_sdk::sanitize_identity(id);
                        let bundle_path = vault_path.join("bundles").join(format!("{slug}.json"));
                        let fingerprint = parse_public_bundle_file(&bundle_path)
                            .ok()
                            .map(|info| info.fingerprint);
                        entries.push(VaultEntry {
                            identity: id.to_string(),
                            bundle: bundle_path.to_string_lossy().to_string(),
                            fingerprint,
                        });
                    }
                }
            }
            let result = VaultListResult {
                vault: vault_path.to_string_lossy().to_string(),
                entries,
            };
            if json {
                print_json(&result)?;
            } else if result.entries.is_empty() {
                println!("(vault empty at {})", vault_path.display());
            } else {
                println!("Vault at {}", vault_path.display());
                for e in &result.entries {
                    if let Some(fp) = &e.fingerprint {
                        println!("  - {} ({})", e.identity, fp);
                    } else {
                        println!("  - {}", e.identity);
                    }
                }
            }
        }
    }
    Ok(())
}

fn resolve_email<'a>(email: Option<&'a str>, config: &'a Config) -> Result<String> {
    if let Some(e) = email {
        return Ok(e.to_string());
    }
    if !config.email.trim().is_empty() {
        return Ok(config.email.clone());
    }
    Err(anyhow!("email is required").into())
}

fn resolve_paths(
    config: &Config,
    data_override: Option<&Path>,
    vault_override: Option<&Path>,
) -> Result<(PathBuf, PathBuf)> {
    let data_root = if let Some(dir) = data_override {
        dir.to_path_buf()
    } else {
        config.get_syftbox_data_dir()?
    };
    let encrypted_root = syftbox_sdk::syftbox::syc::resolve_encrypted_root(&data_root);
    let vault_path = resolve_vault_default(vault_override);
    Ok((encrypted_root, vault_path))
}

fn resolve_vault_only(
    config: &Config,
    vault_override: Option<&Path>,
) -> Result<(PathBuf, PathBuf)> {
    let data_root = config.get_syftbox_data_dir()?;
    let encrypted_root = syftbox_sdk::syftbox::syc::resolve_encrypted_root(&data_root);
    let vault_path = resolve_vault_default(vault_override);
    Ok((vault_path, encrypted_root))
}

fn load_existing_bundle(vault_path: &Path, identity: &str) -> Result<Option<PublicBundleInfo>> {
    let slug = syftbox_sdk::sanitize_identity(identity);
    let bundle_path = vault_path.join("bundles").join(format!("{slug}.json"));
    if !bundle_path.exists() {
        return Ok(None);
    }
    let info = parse_public_bundle_file(&bundle_path)?;
    Ok(Some(info))
}

fn resolve_vault_default(vault_override: Option<&Path>) -> PathBuf {
    if let Some(v) = vault_override {
        return v.to_path_buf();
    }
    if let Some(env_vault) = std::env::var_os("SYC_VAULT") {
        return PathBuf::from(env_vault);
    }
    // Keep vault colocated with BioVault home so desktop/CLI share the same keys by default.
    if let Ok(home) = crate::config::get_biovault_home() {
        let colocated = syftbox_sdk::syftbox::syc::vault_path_for_home(&home);
        if colocated.exists() {
            return colocated;
        }
        let legacy = dirs::home_dir()
            .map(|h| h.join(".syc"))
            .unwrap_or_else(|| PathBuf::from(".syc"));
        if legacy.exists() {
            return legacy;
        }
        return colocated;
    }
    // Fallback to legacy global location.
    dirs::home_dir()
        .map(|h| h.join(".syc"))
        .unwrap_or_else(|| PathBuf::from(".syc"))
}

fn resolve_export_path(data_root: &Path, identity: &str) -> PathBuf {
    let base = if data_root
        .file_name()
        .map(|n| n == "datasites")
        .unwrap_or(false)
    {
        data_root.to_path_buf()
    } else {
        data_root.join("datasites")
    };
    base.join(identity)
        .join("public")
        .join("crypto")
        .join("did.json")
}

fn print_json<T: Serialize>(value: &T) -> Result<()> {
    println!("{}", serde_json::to_string_pretty(value)?);
    Ok(())
}

#[derive(Serialize)]
struct GenerateResult {
    identity: String,
    fingerprint: String,
    vault: String,
    bundle_path: String,
    export_path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    mnemonic: Option<String>,
}

#[derive(Serialize)]
struct ImportResult {
    identity: String,
    fingerprint: String,
    vault: String,
    bundle_path: String,
}

#[derive(Serialize)]
struct ExportResult {
    identity: String,
    fingerprint: String,
    output: String,
    vault_bundle: String,
}

#[derive(Serialize)]
struct WipeResult {
    identity: String,
    removed: bool,
    key_path: String,
    bundle_path: String,
    export_path: String,
}

#[derive(Serialize, Clone)]
struct StatusResult {
    identity: String,
    vault: String,
    bundle: String,
    export: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    vault_fingerprint: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    export_fingerprint: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    export_matches: Option<bool>,
}

#[derive(Serialize)]
struct VaultListResult {
    vault: String,
    entries: Vec<VaultEntry>,
}

#[derive(Serialize)]
struct VaultEntry {
    identity: String,
    bundle: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    fingerprint: Option<String>,
}