Skip to main content

vta_cli_common/commands/
contexts.rs

1use std::io::{self, Write};
2
3use ratatui::{
4    layout::Constraint,
5    style::{Color, Modifier, Style},
6    widgets::{Block, Cell, Row, Table},
7};
8use vta_sdk::client::{ContextResponse, CreateDidWebvhRequest, UpdateContextRequest};
9use vta_sdk::context_provision::{ContextProvisionBundle, ProvisionedDid};
10use vta_sdk::prelude::*;
11use vta_sdk::protocols::did_management::create::WebvhPathMode;
12use vta_sdk::sealed_transfer::SealedPayloadV1;
13
14use crate::display::{NameBook, book_from_acl, inline};
15use crate::render::{is_full_display, print_full_entry, print_full_list_title, print_widget};
16use crate::sealed_producer::{SealedRecipient, seal_for_recipient};
17
18pub struct ProvisionDidOptions {
19    pub server_id: Option<String>,
20    pub did_url: Option<String>,
21    /// Explicit path label for the DID on the hosting server. `None`
22    /// leaves the host to auto-assign one; `.well-known` selects the
23    /// reserved root slot. Mirrors `pnm did-mgmt dids create --path`.
24    pub did_path: Option<String>,
25    pub portable: bool,
26    pub add_mediator_service: bool,
27    pub pre_rotation_count: u32,
28}
29
30pub async fn cmd_context_bootstrap(
31    client: &VtaClient,
32    id: &str,
33    name: &str,
34    description: Option<String>,
35    admin_label: Option<String>,
36    recipient: SealedRecipient,
37) -> Result<(), Box<dyn std::error::Error>> {
38    let mut ctx_req = CreateContextRequest::new(id, name);
39    if let Some(desc) = description {
40        ctx_req = ctx_req.description(desc);
41    }
42    let ctx = client.create_context(ctx_req).await?;
43    println!("Context created:");
44    println!("  ID:        {}", ctx.id);
45    println!("  Name:      {}", ctx.name);
46    println!("  Base Path: {}", ctx.base_path);
47
48    // Fetch VTA config so the minted CredentialBundle carries VTA DID/URL.
49    let config = client.get_config().await?;
50    let vta_did = config
51        .vta_did()
52        .map(str::to_string)
53        .ok_or("VTA DID not configured — cannot mint admin credential")?;
54    let vta_url = config.public_url().map(str::to_string);
55
56    // Mint admin did:key locally + register ACL. The VTA never sees the
57    // private half; the full bundle reaches the recipient via sealed transfer.
58    let (admin_bundle, admin_did) = crate::local_keygen::generate_admin_did_key(vta_did, vta_url);
59    let mut acl_req =
60        vta_sdk::client::CreateAclRequest::new(&admin_did, "admin").contexts(vec![id.to_string()]);
61    if let Some(l) = admin_label {
62        acl_req = acl_req.label(l);
63    }
64    client.create_acl(acl_req).await?;
65
66    let sealed = seal_for_recipient(
67        &recipient,
68        &SealedPayloadV1::AdminCredential(Box::new(admin_bundle)),
69    )
70    .await?;
71    println!();
72    println!("Admin credential created:");
73    println!("  DID:  {admin_did}");
74    println!("  Role: admin");
75    if let Some(ref label) = recipient.label {
76        println!("  Recipient: {label}");
77    }
78    println!();
79
80    crate::sealed_producer::emit_sealed_output(&sealed, None)?;
81    Ok(())
82}
83
84/// Render a list of context records — table view by default, full
85/// `key: value` blocks when `--full-display` is set.
86///
87/// Shared by the online (`pnm contexts list`, REST) and offline
88/// (`vta contexts list`, keystore-direct) paths so both render
89/// identically.
90pub fn render_context_list(contexts: &[ContextResponse]) {
91    if contexts.is_empty() {
92        println!("No contexts found.");
93        return;
94    }
95
96    if is_full_display() {
97        print_full_list_title("Contexts", contexts.len());
98        for ctx in contexts {
99            let did = ctx.did.as_deref().unwrap_or("—");
100            let created = ctx
101                .created_at
102                .with_timezone(&chrono::Local)
103                .format("%Y-%m-%d %H:%M:%S %:z")
104                .to_string();
105            print_full_entry(&[
106                ("ID", &ctx.id),
107                ("Name", &ctx.name),
108                ("DID", did),
109                ("Base Path", &ctx.base_path),
110                ("Created", &created),
111            ]);
112        }
113        return;
114    }
115
116    let header_style = Style::default()
117        .fg(Color::White)
118        .add_modifier(Modifier::BOLD);
119    let header = Row::new(vec!["ID", "Name", "DID", "Base Path", "Created"])
120        .style(header_style)
121        .bottom_margin(1);
122
123    let rows: Vec<Row> = contexts
124        .iter()
125        .map(|ctx| {
126            let did = ctx.did.clone().unwrap_or_else(|| "\u{2014}".into());
127            let created = ctx
128                .created_at
129                .with_timezone(&chrono::Local)
130                .format("%Y-%m-%d")
131                .to_string();
132
133            Row::new(vec![
134                Cell::from(ctx.id.clone()),
135                Cell::from(ctx.name.clone()),
136                Cell::from(did).style(Style::default().fg(Color::DarkGray)),
137                Cell::from(ctx.base_path.clone()),
138                Cell::from(created),
139            ])
140        })
141        .collect();
142
143    let title = format!(" Contexts ({}) ", contexts.len());
144
145    // DID field carries full did:webvh / did:key values (40+ chars).
146    // Use `Min` so it expands on wide terminals rather than truncating
147    // at the former fixed 30-char width.
148    let table = Table::new(
149        rows,
150        [
151            Constraint::Min(16),    // ID
152            Constraint::Min(20),    // Name
153            Constraint::Min(40),    // DID
154            Constraint::Length(16), // Base Path
155            Constraint::Length(10), // Created
156        ],
157    )
158    .header(header)
159    .column_spacing(2)
160    .block(
161        Block::bordered()
162            .title(title)
163            .border_style(Style::default().fg(Color::DarkGray)),
164    );
165
166    let height = contexts.len() as u16 + 4;
167    print_widget(table, height);
168}
169
170/// Render a single context record's details, used by `get` and the
171/// success path of `update`. Shared by online + offline call sites.
172pub fn render_context_record(ctx: &ContextResponse) {
173    println!("ID:          {}", ctx.id);
174    println!("Name:        {}", ctx.name);
175    println!("DID:         {}", ctx.did.as_deref().unwrap_or("(not set)"));
176    println!(
177        "Description: {}",
178        ctx.description.as_deref().unwrap_or("(not set)")
179    );
180    println!("Base Path:   {}", ctx.base_path);
181    println!(
182        "Created At:  {}",
183        crate::duration::format_local_datetime(ctx.created_at)
184    );
185    println!(
186        "Updated At:  {}",
187        crate::duration::format_local_datetime(ctx.updated_at)
188    );
189}
190
191pub async fn cmd_context_list(client: &VtaClient) -> Result<(), Box<dyn std::error::Error>> {
192    let resp = client.list_contexts().await?;
193    if crate::render::is_json_output() {
194        crate::render::print_json(&resp.contexts)?;
195        return Ok(());
196    }
197    render_context_list(&resp.contexts);
198    Ok(())
199}
200
201pub async fn cmd_context_get(
202    client: &VtaClient,
203    id: &str,
204) -> Result<(), Box<dyn std::error::Error>> {
205    let resp = client.get_context(id).await?;
206    render_context_record(&resp);
207    Ok(())
208}
209
210/// Options for optionally creating a context-scoped admin ACL entry as
211/// part of `pnm contexts create`.
212///
213/// Omit the entire struct to create the context without touching the ACL —
214/// the historical behaviour. Supply a [`AdminAclOptions::did`] to atomically
215/// create an `admin`-role ACL entry scoped to the new context in the same
216/// CLI invocation.
217///
218/// Setting [`AdminAclOptions::expires_at`] flips the entry from **permanent**
219/// to a **setup ACL** that auto-expires (pruned by the VTA's ACL sweeper) if
220/// the admin never authenticates and rotates to a fresh did:key.
221#[derive(Debug, Default, Clone)]
222pub struct AdminAclOptions {
223    /// DID to grant admin access to. Must start with `did:`.
224    pub did: Option<String>,
225    /// Human-readable label stored on the ACL entry.
226    pub label: Option<String>,
227    /// Unix-epoch seconds at which the entry auto-expires. `None` = permanent.
228    pub expires_at: Option<u64>,
229    /// Raw `--admin-expires` input (e.g. `"1h"`). Preserved alongside the
230    /// resolved `expires_at` so conflict hints can re-emit the operator's
231    /// original duration verbatim instead of a drift-skewed seconds value.
232    pub expires_duration: Option<String>,
233}
234
235impl AdminAclOptions {
236    fn is_requested(&self) -> bool {
237        self.did.is_some()
238    }
239}
240
241pub async fn cmd_context_create(
242    client: &VtaClient,
243    id: &str,
244    name: &str,
245    description: Option<String>,
246    parent: Option<String>,
247    admin: AdminAclOptions,
248) -> Result<(), Box<dyn std::error::Error>> {
249    use crate::render::{RESET, YELLOW};
250    use vta_sdk::error::VtaError;
251
252    // The full context path the server will assign (`<parent>/<id>` when nested)
253    // — used for the conflict hint before `resp` exists.
254    let effective_id = parent
255        .as_ref()
256        .map_or_else(|| id.to_string(), |p| format!("{p}/{id}"));
257    let req = CreateContextRequest {
258        id: id.to_string(),
259        name: name.to_string(),
260        description,
261        parent,
262    };
263    let resp = match client.create_context(req).await {
264        Ok(r) => r,
265        // Friendly path when the operator's real intent was "grant this DID
266        // admin access to this context": the context already exists, so the
267        // scaffolding command is the wrong tool — point them at the ACL
268        // command and exit cleanly so repeated provisioning scripts don't
269        // choke on second runs.
270        Err(VtaError::Conflict(_)) if admin.is_requested() => {
271            let did = admin.did.as_deref().unwrap_or_default();
272            let bin = crate::render::bin_name();
273            eprintln!(
274                "{YELLOW}\u{26a0}{RESET}  Context '{effective_id}' already exists — skipping context creation."
275            );
276            eprintln!();
277            eprintln!("  The --admin-did was NOT added. To grant admin access to an existing");
278            eprintln!("  context, use the ACL command directly:");
279            eprintln!();
280            let mut hint =
281                format!("    {bin} acl create --did {did} --role admin --contexts {effective_id}");
282            if let Some(label) = admin.label.as_deref() {
283                hint.push_str(&format!(" --label '{label}'"));
284            }
285            match (admin.expires_duration.as_deref(), admin.expires_at) {
286                // Prefer the raw duration the user typed — any latency between
287                // --admin-expires being parsed and the conflict firing would
288                // otherwise drift the re-rendered seconds (e.g. `1h` → `3599s`).
289                (Some(raw), _) => hint.push_str(&format!(" --expires {raw}")),
290                (None, Some(expires_at)) => {
291                    let remaining = expires_at.saturating_sub(crate::duration::now_unix());
292                    hint.push_str(&format!(" --expires {remaining}s"));
293                }
294                (None, None) => {}
295            }
296            eprintln!("{hint}");
297            return Ok(());
298        }
299        Err(e) => return Err(e.into()),
300    };
301    println!("Context created:");
302    println!("  ID:        {}", resp.id);
303    println!("  Name:      {}", resp.name);
304    println!("  Base Path: {}", resp.base_path);
305
306    if admin.is_requested() {
307        let did = admin.did.as_deref().unwrap_or_default();
308        if !did.starts_with("did:") {
309            return Err(format!(
310                "--admin-did must start with `did:` (got {did:?}) — context was created but no ACL entry was added"
311            )
312            .into());
313        }
314        // Scope the admin grant to the **full path** the server assigned
315        // (`<parent>/<id>` for a sub-context), not the leaf.
316        let mut acl_req =
317            vta_sdk::client::CreateAclRequest::new(did, "admin").contexts(vec![resp.id.clone()]);
318        if let Some(label) = admin.label.as_deref() {
319            acl_req = acl_req.label(label);
320        }
321        if let Some(expires_at) = admin.expires_at {
322            acl_req = acl_req.expires_at(expires_at);
323        }
324        let acl = client.create_acl(acl_req).await?;
325
326        println!();
327        println!("Admin ACL entry created:");
328        println!("  DID:        {}", acl.did);
329        println!("  Role:       {}", acl.role);
330        println!("  Contexts:   {}", acl.allowed_contexts.join(", "));
331        if let Some(ref label) = acl.label {
332            println!("  Label:      {label}");
333        }
334        match acl.expires_at {
335            Some(secs) => {
336                println!(
337                    "  Expires at: {} ({}) — setup ACL",
338                    crate::duration::format_local_time(secs),
339                    crate::duration::format_remaining(secs),
340                );
341                println!();
342                println!("  The admin should authenticate before expiry. On first successful");
343                println!("  connect PNM rotates to a fresh long-lived did:key and replaces this");
344                println!("  temporary entry with a permanent one.");
345            }
346            None => println!("  Expires at: (permanent)"),
347        }
348    }
349
350    Ok(())
351}
352
353pub async fn cmd_context_update(
354    client: &VtaClient,
355    id: &str,
356    name: Option<String>,
357    did: Option<String>,
358    description: Option<String>,
359) -> Result<(), Box<dyn std::error::Error>> {
360    let req = UpdateContextRequest {
361        name,
362        did,
363        description,
364        context_policy: None,
365    };
366    let resp = client.update_context(id, req).await?;
367    println!("Context updated:");
368    render_context_record(&resp);
369    Ok(())
370}
371
372pub async fn cmd_context_update_did(
373    client: &VtaClient,
374    id: &str,
375    did: &str,
376) -> Result<(), Box<dyn std::error::Error>> {
377    let resp = client.update_context_did(id, did).await?;
378    println!("Context DID updated:");
379    println!("  ID:         {}", resp.id);
380    println!(
381        "  DID:        {}",
382        resp.did.as_deref().unwrap_or("(not set)")
383    );
384    println!(
385        "  Updated At: {}",
386        crate::duration::format_local_datetime(resp.updated_at)
387    );
388    Ok(())
389}
390
391/// Print the human-readable resource preview shown before context
392/// deletion. Returns `true` when the preview lists any resources
393/// (i.e. the caller should prompt for confirmation unless `--force`).
394///
395/// Shared by online + offline delete paths so both warn about exactly
396/// the same resource classes.
397pub fn render_delete_context_preview(
398    id: &str,
399    preview: &vta_sdk::protocols::context_management::delete::DeleteContextPreviewResultBody,
400    book: &NameBook,
401) -> bool {
402    let has_resources = !preview.keys.is_empty()
403        || !preview.webvh_dids.is_empty()
404        || !preview.acl_entries_removed.is_empty()
405        || !preview.acl_entries_updated.is_empty();
406
407    if !has_resources {
408        return false;
409    }
410
411    println!(
412        "Deleting context '{}' will remove the following resources:\n",
413        id
414    );
415
416    if !preview.keys.is_empty() {
417        println!("  Keys ({}):", preview.keys.len());
418        for key in &preview.keys {
419            println!("    - {key}");
420        }
421    }
422
423    // This is a destructive confirmation: the operator is deciding whether
424    // these principals should lose access. A list of opaque DIDs is the
425    // hardest possible form in which to make that call, so every DID here
426    // renders name-first with its identifier alongside.
427    if !preview.webvh_dids.is_empty() {
428        println!("  WebVH DIDs ({}):", preview.webvh_dids.len());
429        for did in &preview.webvh_dids {
430            println!("    - {}", inline(book, did));
431        }
432    }
433
434    if !preview.acl_entries_removed.is_empty() {
435        println!(
436            "  ACL entries removed ({}):",
437            preview.acl_entries_removed.len()
438        );
439        for did in &preview.acl_entries_removed {
440            println!("    - {}", inline(book, did));
441        }
442    }
443
444    if !preview.acl_entries_updated.is_empty() {
445        println!(
446            "  ACL entries updated (context removed from access list) ({}):",
447            preview.acl_entries_updated.len()
448        );
449        for did in &preview.acl_entries_updated {
450            println!("    - {}", inline(book, did));
451        }
452    }
453
454    println!();
455    true
456}
457
458/// Read a `[y/N]` reply from stdin. Returns `true` for `y` / `yes`,
459/// `false` otherwise. Shared by the destructive shared commands so
460/// the prompt wording stays consistent.
461pub fn confirm_destructive(prompt: &str) -> Result<bool, Box<dyn std::error::Error>> {
462    print!("{prompt} [y/N] ");
463    io::stdout().flush()?;
464    let mut input = String::new();
465    io::stdin().read_line(&mut input)?;
466    let input = input.trim().to_lowercase();
467    Ok(input == "y" || input == "yes")
468}
469
470pub async fn cmd_context_delete(
471    client: &VtaClient,
472    id: &str,
473    force: bool,
474) -> Result<(), Box<dyn std::error::Error>> {
475    // Fetch a preview of what will be removed
476    let preview = client.preview_delete_context(id).await?;
477
478    // Best-effort naming for the confirmation prompt — a failure here must
479    // never block a deletion the operator is entitled to perform.
480    let mut book = NameBook::new();
481    if let Ok(acl) = client.list_acl(None).await {
482        book_from_acl(&mut book, &acl.entries);
483    }
484
485    let has_resources = render_delete_context_preview(id, &preview, &book);
486
487    if has_resources && !force && !confirm_destructive("Proceed with deletion?")? {
488        println!("Aborted.");
489        return Ok(());
490    }
491
492    client.delete_context(id, true).await?;
493    println!("Context deleted: {id}");
494    Ok(())
495}
496
497pub async fn cmd_context_provision(
498    client: &VtaClient,
499    id: &str,
500    name: &str,
501    description: Option<String>,
502    admin_label: Option<String>,
503    did_opts: Option<ProvisionDidOptions>,
504    recipient: SealedRecipient,
505) -> Result<(), Box<dyn std::error::Error>> {
506    // 1. Create the context
507    eprintln!("Creating context '{id}'...");
508    let mut ctx_req = CreateContextRequest::new(id, name);
509    if let Some(desc) = description {
510        ctx_req = ctx_req.description(desc);
511    }
512    client.create_context(ctx_req).await?;
513
514    // 2. Fetch VTA config for URL/DID (needed to build the admin credential).
515    let config = client.get_config().await?;
516    let vta_did = config
517        .vta_did()
518        .map(str::to_string)
519        .ok_or("VTA DID not configured — cannot mint admin credential")?;
520    let vta_url = config.public_url().map(str::to_string);
521
522    // 3. Generate admin did:key locally (private key never crosses the wire)
523    //    and register it with the VTA via POST /acl. This replaces the
524    //    pre-5c6 `POST /auth/credentials` round-trip that returned a base64
525    //    CredentialBundle in a plaintext JSON body.
526    eprintln!("Minting local admin credential and registering ACL...");
527    let (admin_credential, admin_did) =
528        crate::local_keygen::generate_admin_did_key(vta_did, vta_url);
529    let mut acl_req =
530        vta_sdk::client::CreateAclRequest::new(&admin_did, "admin").contexts(vec![id.to_string()]);
531    if let Some(l) = admin_label {
532        acl_req = acl_req.label(l);
533    }
534    client.create_acl(acl_req).await?;
535
536    // 4. Optionally create a DID and collect its secrets
537    let provisioned_did = if let Some(opts) = did_opts {
538        eprintln!("Creating WebVH DID...");
539        let req = CreateDidWebvhRequest {
540            context_id: id.to_string(),
541            server_id: opts.server_id,
542            url: opts.did_url,
543            path: None,
544            // `--did-path` maps onto the canonical path-mode selector:
545            // absent → auto-assign server-side, `.well-known` → the
546            // reserved root slot, anything else → an explicit label.
547            // `WebvhPathMode::from(String)` owns that trimming/mapping
548            // so the contexts surface can't drift from `dids create`.
549            path_mode: opts.did_path.map(WebvhPathMode::from),
550            // Context-bootstrap path: no per-DID domain override.
551            // The server's caller-default → system-default resolves.
552            domain: None,
553            label: Some(id.to_string()),
554            portable: opts.portable,
555            add_mediator_service: opts.add_mediator_service,
556            additional_services: None,
557            pre_rotation_count: opts.pre_rotation_count,
558            did_document: None,
559            did_log: None,
560            set_primary: true,
561            signing_key_id: None,
562            ka_key_id: None,
563            template: None,
564            template_context: None,
565            template_vars: std::collections::HashMap::new(),
566        };
567        let did_result = client.create_did_webvh(req).await?;
568
569        // Collect secrets for the DID keys
570        eprintln!("Fetching DID key secrets...");
571        let mut secrets: Vec<SecretEntry> = Vec::new();
572        // Signing key
573        secrets.push(
574            client
575                .get_key_secret(&did_result.signing_key_id)
576                .await?
577                .into(),
578        );
579        // Key-agreement key
580        secrets.push(client.get_key_secret(&did_result.ka_key_id).await?.into());
581        // Pre-rotation keys
582        for i in 0..did_result.pre_rotation_key_count {
583            let pre_rot_id = format!("{}#pre-rotation-{i}", did_result.did);
584            secrets.push(client.get_key_secret(&pre_rot_id).await?.into());
585        }
586
587        Some(ProvisionedDid {
588            id: did_result.did,
589            did_document: did_result.did_document,
590            log_entry: did_result.log_entry,
591            secrets,
592        })
593    } else {
594        None
595    };
596
597    // 5. Build the provision bundle
598    let bundle = ContextProvisionBundle {
599        context_id: id.to_string(),
600        context_name: name.to_string(),
601        vta_url: config.public_url().map(str::to_string),
602        vta_did: config.vta_did().map(str::to_string),
603        credential: admin_credential,
604        admin_did,
605        did: provisioned_did,
606    };
607
608    // 6. Seal and emit via the shared helper
609    crate::sealed_producer::emit_context_provision_bundle(bundle, &recipient, None).await
610}
611
612/// Build a `CredentialBundle` from a VTA-stored key, deriving its `did:key`.
613///
614/// The REST fetch is transport-specific; the derivation is shared via
615/// [`CredentialBundle::from_ed25519_seed_multibase`] with the offline
616/// path in `vta-service::operations::export::credential_from_key_offline`
617/// so the `did:key` encoding and bundle shape can't drift.
618async fn credential_from_key(
619    client: &VtaClient,
620    key_id: &str,
621    vta_did: &str,
622    vta_url: Option<&str>,
623) -> Result<(CredentialBundle, String), Box<dyn std::error::Error>> {
624    let secret = client.get_key_secret(key_id).await?;
625    CredentialBundle::from_ed25519_seed_multibase(&secret.private_key_multibase, vta_did, vta_url)
626        .map_err(|e| format!("Cannot decode key secret: {e}").into())
627}
628
629pub async fn cmd_context_reprovision(
630    client: &VtaClient,
631    id: &str,
632    key_id: Option<String>,
633    admin_label: Option<String>,
634    recipient: SealedRecipient,
635) -> Result<(), Box<dyn std::error::Error>> {
636    // 1. Fetch the existing context
637    eprintln!("Fetching context '{id}'...");
638    let ctx = client.get_context(id).await?;
639
640    // 2. Fetch VTA config for URL/DID
641    let config = client.get_config().await?;
642    let vta_did = config.vta_did().ok_or("VTA DID not configured")?;
643
644    // 3. Resolve admin credential
645    let (admin_credential, admin_did) = if let Some(ref kid) = key_id {
646        // Direct key ID specified
647        eprintln!("Using key '{kid}'...");
648        credential_from_key(client, kid, vta_did, config.public_url()).await?
649    } else {
650        // Interactive: list existing Ed25519 keys and let user choose
651        let keys_resp = client.list_keys(0, 10000, Some("active"), Some(id)).await?;
652        let ed25519_keys: Vec<_> = keys_resp
653            .keys
654            .iter()
655            .filter(|k| k.key_type == KeyType::Ed25519)
656            .collect();
657
658        eprintln!();
659        eprintln!("Select an admin credential key for context '{id}':");
660        eprintln!();
661        for (i, key) in ed25519_keys.iter().enumerate() {
662            let label = key
663                .label
664                .as_deref()
665                .map(|l| format!(" ({l})"))
666                .unwrap_or_default();
667            eprintln!("  [{}] {}{}", i + 1, key.key_id, label);
668        }
669        let new_option = ed25519_keys.len() + 1;
670        eprintln!("  [{}] Create a new admin key", new_option);
671        eprintln!();
672        eprint!("Choice [{}]: ", new_option);
673        io::stderr().flush()?;
674
675        let mut input = String::new();
676        io::stdin().read_line(&mut input)?;
677        let input = input.trim();
678
679        // Default to creating a new key if empty
680        let choice: usize = if input.is_empty() {
681            new_option
682        } else {
683            input
684                .parse()
685                .map_err(|_| format!("Invalid choice: {input}"))?
686        };
687
688        if choice == new_option {
689            // Create a new Ed25519 key in VTA scoped to this context
690            eprintln!("Creating new admin key...");
691            let key_resp = client
692                .create_key(CreateKeyRequest {
693                    key_type: KeyType::Ed25519,
694                    derivation_path: None,
695                    key_id: None,
696                    mnemonic: None,
697                    label: admin_label.or_else(|| Some("admin".to_string())),
698                    context_id: Some(id.to_string()),
699                })
700                .await?;
701            credential_from_key(client, &key_resp.key_id, vta_did, config.public_url()).await?
702        } else if choice >= 1 && choice <= ed25519_keys.len() {
703            let selected = &ed25519_keys[choice - 1];
704            eprintln!("Using key '{}'...", selected.key_id);
705            credential_from_key(client, &selected.key_id, vta_did, config.public_url()).await?
706        } else {
707            return Err(format!("Invalid choice: {choice}").into());
708        }
709    };
710
711    // 4. Ensure an ACL entry exists for this admin DID
712    if client.get_acl(&admin_did).await.is_err() {
713        eprintln!("Creating ACL entry for {admin_did}...");
714        client
715            .create_acl(
716                vta_sdk::client::CreateAclRequest::new(&admin_did, "admin")
717                    .contexts(vec![id.to_string()]),
718            )
719            .await?;
720    }
721
722    // 5. Collect DID material (document, log, secrets) when the context has a DID
723    let provisioned_did = if let Some(ref did_id) = ctx.did {
724        eprintln!("Fetching DID material...");
725
726        // Fetch the DID log and extract the DID document from it
727        let log_resp = client.get_did_webvh_log(did_id).await?;
728        let (did_document, log_entry) = if let Some(ref log_str) = log_resp.log {
729            let parsed: serde_json::Value = serde_json::from_str(log_str)
730                .map_err(|e| format!("failed to parse DID log: {e}"))?;
731            let doc = parsed.get("state").cloned();
732            (doc, Some(log_str.clone()))
733        } else {
734            (None, None)
735        };
736
737        // Fetch all active key secrets for this context
738        let secrets_bundle = client.fetch_did_secrets_bundle(id).await?;
739
740        Some(ProvisionedDid {
741            id: did_id.clone(),
742            did_document,
743            log_entry,
744            secrets: secrets_bundle.secrets,
745        })
746    } else {
747        None
748    };
749
750    // 6. Build the provision bundle
751    let bundle = ContextProvisionBundle {
752        context_id: id.to_string(),
753        context_name: ctx.name.clone(),
754        vta_url: config.public_url().map(str::to_string),
755        vta_did: config.vta_did().map(str::to_string),
756        credential: admin_credential,
757        admin_did,
758        did: provisioned_did,
759    };
760
761    // 7. Seal and emit via the shared helper
762    crate::sealed_producer::emit_context_provision_bundle(bundle, &recipient, None).await
763}