noosphere_cli/native/commands/
key.rs

1//! Concrete implementations of subcommands to manage device keys
2use anyhow::Result;
3use noosphere::key::KeyStorage;
4use serde_json::json;
5use ucan::crypto::KeyMaterial;
6
7use crate::native::workspace::Workspace;
8
9/// Create a device key, identified by the given name
10pub async fn key_create(name: &str, workspace: &Workspace) -> Result<()> {
11    let key = workspace.key_storage().create_key(name).await?;
12    let did = key.get_did().await?;
13
14    info!(
15        "Created key {:?} in {:?}",
16        name,
17        workspace.key_storage().storage_path()
18    );
19    info!("Public identity {did}");
20
21    Ok(())
22}
23
24/// List all device keys, optionally in JSON format
25pub async fn key_list(as_json: bool, workspace: &Workspace) -> Result<()> {
26    let keys = workspace.key_storage().get_discoverable_keys().await?;
27    let max_name_length = keys
28        .iter()
29        .fold(7, |length, (key_name, _)| key_name.len().max(length));
30
31    if as_json {
32        info!("{}", serde_json::to_string_pretty(&json!(keys))?);
33    } else {
34        info!("{:1$}  IDENTITY", "NAME", max_name_length);
35        for (name, did) in keys {
36            info!("{name:max_name_length$}  {did}");
37        }
38    }
39
40    Ok(())
41}