vouch-core 3.2.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
//! JSON facade for [`crate::recovery`] (Shamir root-identity recovery).
//!
//! Identity shares are "vouch-recovery-2:" strings that carry the whole
//! identity with a check value; shares in the earlier seed-only format (plain
//! base64) still recover when the caller gives the DID.
//!
//! Presents the recovery core as JSON-in / JSON-out with binary fields as
//! standard base64 strings, matching the convention the rest of the
//! FFI-facing core uses (see [`crate::threshold_json`]), so UniFFI, the C
//! ABI, and WASM all share one implementation instead of re-deriving the
//! plumbing per language.

use base64::{engine::general_purpose::STANDARD, Engine};
use serde_json::{json, Value};

use crate::error::{CoreError, Result};
use crate::recovery as r;

fn b64(bytes: &[u8]) -> String {
    STANDARD.encode(bytes)
}

fn unb64(s: &str) -> Result<Vec<u8>> {
    STANDARD
        .decode(s)
        .map_err(|e| CoreError::Json(format!("base64: {e}")))
}

fn share_strings(shares_json: &str) -> Result<Vec<String>> {
    let v: Value =
        serde_json::from_str(shares_json).map_err(|e| CoreError::Json(format!("json: {e}")))?;
    let arr = v
        .as_array()
        .ok_or_else(|| CoreError::Json("expected a JSON array of shares".into()))?;
    arr.iter()
        .map(|item| {
            item.as_str()
                .map(str::to_string)
                .ok_or_else(|| CoreError::Json("each share must be a string".into()))
        })
        .collect()
}

fn shares_from_json(shares_json: &str) -> Result<Vec<Vec<u8>>> {
    share_strings(shares_json)?
        .iter()
        .map(|item| {
            r::strict_base64(r::trim_share(item)).ok_or_else(|| {
                CoreError::Crypto("a recovery share is damaged: it is not canonical base64".into())
            })
        })
        .collect()
}

fn shares_to_json(shares: &[Vec<u8>]) -> String {
    json!(shares.iter().map(|s| b64(s)).collect::<Vec<_>>()).to_string()
}

/// Splits `secret_b64` (a base64-encoded byte string) into `shares` pieces;
/// any `threshold` of them reconstruct it. Returns a JSON array of
/// base64-encoded shares.
pub fn split_secret(secret_b64: &str, threshold: u16, shares: u16) -> Result<String> {
    let secret = unb64(secret_b64)?;
    let out = r::split_secret(&secret, threshold, shares)?;
    Ok(shares_to_json(&out))
}

/// Reconstructs a secret from a JSON array of base64-encoded shares. Returns
/// the base64-encoded secret.
pub fn combine_shares(shares_json: &str) -> Result<String> {
    let shares = shares_from_json(shares_json)?;
    let secret = r::combine_shares(&shares)?;
    Ok(b64(&secret))
}

/// Splits a root identity's base64-encoded Ed25519 seed into backup shares
/// ("vouch-recovery-2:" strings, see [`crate::recovery::split_backup`]).
/// Returns a JSON array of shares. Use [`split_identity_keys`] to carry the
/// DID and further keys too.
pub fn split_identity(seed_b64: &str, threshold: u16, shares: u16) -> Result<String> {
    let seed = unb64(seed_b64)?;
    let out = r::split_backup(&seed, None, &[], threshold, shares)?;
    Ok(json!(out).to_string())
}

/// Splits a whole identity into backup shares. `identity_json` is
/// `{"did"?: string, "seed": b64, "keys"?: [{"id", "alg", "public_key", "private_key": b64}]}`,
/// for example `{"did": "did:web:root.example", "seed": "...", "keys": [{"id": "#key-2",
/// "alg": "ML-DSA-44", "public_key": "z...", "private_key": "..."}]}`. Returns a
/// JSON array of "vouch-recovery-2:" shares.
pub fn split_identity_keys(identity_json: &str, threshold: u16, shares: u16) -> Result<String> {
    let v: Value =
        serde_json::from_str(identity_json).map_err(|e| CoreError::Json(format!("json: {e}")))?;
    let seed = unb64(
        v.get("seed")
            .and_then(|s| s.as_str())
            .ok_or_else(|| CoreError::Json("identity needs a base64 \"seed\"".into()))?,
    )?;
    let did = match v.get("did") {
        None | Some(Value::Null) => None,
        Some(Value::String(d)) => Some(d.as_str()),
        Some(_) => return Err(CoreError::Json("\"did\" must be a string".into())),
    };
    let mut keys = Vec::new();
    if let Some(rows) = v.get("keys") {
        let rows = rows
            .as_array()
            .ok_or_else(|| CoreError::Json("\"keys\" must be a list".into()))?;
        for row in rows {
            let text = |name: &str| {
                row.get(name)
                    .and_then(|x| x.as_str())
                    .map(str::to_string)
                    .ok_or_else(|| CoreError::Json(format!("each key needs a string \"{name}\"")))
            };
            keys.push(r::BackupKey {
                id: text("id")?,
                alg: text("alg")?,
                public_key: text("public_key")?,
                private_key: unb64(&text("private_key")?)?,
            });
        }
    }
    let out = r::split_backup(&seed, did, &keys, threshold, shares)?;
    Ok(json!(out).to_string())
}

/// Recovers an identity from a JSON array of recovery shares, in the backup
/// format or the earlier seed-only format. Pass `did` (or an empty string) to
/// name the identity when the shares do not; when they do, it must match.
/// Backup-format shares with no DID from either give a did:key of the
/// recovered public key. Shares in the earlier format do not hold the DID, so
/// they need `did`; with an empty one they are refused.
/// Returns JSON `{"did": string, "seed": b64, "public_key": b64, "keys": [{"id",
/// "alg", "public_key", "private_key": b64}]}`.
pub fn recover_identity(shares_json: &str, did: &str) -> Result<String> {
    let texts = share_strings(shares_json)?;
    if texts.is_empty() {
        return Err(CoreError::Crypto("no recovery shares were given".into()));
    }
    let backup_format = texts.iter().filter(|s| r::is_backup_share(s)).count();
    if backup_format == 0 {
        // These shares do not say which DID they belong to, so the caller
        // must, before the shares are read.
        if did.is_empty() {
            return Err(CoreError::Crypto(r::OLD_SHARES_NEED_DID.into()));
        }
        let shares = shares_from_json(shares_json)?;
        let recovered = r::recover_identity(&shares, Some(did))?;
        let out = json!({
            "did": recovered.did,
            "seed": b64(&recovered.seed),
            "public_key": b64(&recovered.public_key),
            "keys": [],
        });
        return Ok(out.to_string());
    }
    if backup_format != texts.len() {
        return Err(CoreError::Crypto(
            "these shares come from different backups; use shares from one backup".into(),
        ));
    }
    let recovered = r::recover_backup(&texts)?;
    let chosen = match (&recovered.did, did.is_empty()) {
        (Some(saved), false) if saved != did => {
            return Err(CoreError::Crypto(format!(
                "these shares are for {saved}, not {did}"
            )))
        }
        (Some(saved), _) => saved.clone(),
        (None, false) => did.to_string(),
        (None, true) => crate::keys::ed25519_to_did_key(&recovered.public_key)?,
    };
    let keys: Vec<Value> = recovered
        .keys
        .iter()
        .map(|k| {
            json!({
                "id": k.id,
                "alg": k.alg,
                "public_key": k.public_key,
                "private_key": b64(&k.private_key),
            })
        })
        .collect();
    let out = json!({
        "did": chosen,
        "seed": b64(&recovered.seed),
        "public_key": b64(&recovered.public_key),
        "keys": keys,
    });
    Ok(out.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::{engine::general_purpose::STANDARD, Engine};

    #[test]
    fn split_and_combine_round_trips_through_json() {
        let secret = [5u8; 32];
        let secret_b64 = STANDARD.encode(secret);
        let shares_json = split_secret(&secret_b64, 3, 5).unwrap();
        let shares: Vec<String> = serde_json::from_str(&shares_json).unwrap();
        assert_eq!(shares.len(), 5);

        let subset = json!([shares[0], shares[2], shares[4]]).to_string();
        let combined_b64 = combine_shares(&subset).unwrap();
        assert_eq!(combined_b64, secret_b64);
    }

    #[test]
    fn split_and_recover_identity_round_trips_through_json() {
        let keypair = crate::keys::Ed25519KeyPair::generate().unwrap();
        let seed_b64 = STANDARD.encode(keypair.seed());
        let did = keypair.did_key();

        let shares_json = split_identity(&seed_b64, 2, 3).unwrap();
        let shares: Vec<String> = serde_json::from_str(&shares_json).unwrap();
        let subset = json!([shares[0], shares[1]]).to_string();

        let recovered_json = recover_identity(&subset, &did).unwrap();
        let recovered: Value = serde_json::from_str(&recovered_json).unwrap();
        assert_eq!(recovered["did"], did);
        assert_eq!(recovered["seed"], seed_b64);
    }

    #[test]
    fn earlier_format_shares_need_the_did() {
        let keypair = crate::keys::Ed25519KeyPair::generate().unwrap();
        let seed_b64 = STANDARD.encode(keypair.seed());
        let shares: Vec<String> =
            serde_json::from_str(&split_secret(&seed_b64, 2, 3).unwrap()).unwrap();
        let subset = json!([shares[0], shares[2]]).to_string();
        let err = recover_identity(&subset, "").unwrap_err();
        assert!(
            err.to_string().contains(
                "these shares come from an older backup that does not hold the DID; \
                 pass the DID to recover them"
            ),
            "unexpected error: {err}"
        );
        // Asked for before the shares are read.
        let err = recover_identity(&json!(["%%%%", "!!"]).to_string(), "").unwrap_err();
        assert!(err.to_string().contains("pass the DID"), "{err}");
        // With the DID they recover, and the DID is the one given.
        let back: Value =
            serde_json::from_str(&recover_identity(&subset, "did:web:old.example").unwrap())
                .unwrap();
        assert_eq!(back["did"], "did:web:old.example");
        assert_eq!(back["seed"], json!(seed_b64));
        assert_eq!(back["keys"], json!([]));
    }

    #[test]
    fn backup_shares_with_no_did_give_the_did_key() {
        let keypair = crate::keys::Ed25519KeyPair::generate().unwrap();
        let seed_b64 = STANDARD.encode(keypair.seed());
        let shares: Vec<String> =
            serde_json::from_str(&split_identity(&seed_b64, 2, 3).unwrap()).unwrap();
        let back: Value = serde_json::from_str(
            &recover_identity(&json!([shares[1], shares[2]]).to_string(), "").unwrap(),
        )
        .unwrap();
        assert_eq!(back["did"], json!(keypair.did_key()));
    }

    #[test]
    fn no_shares_is_an_error() {
        let err = recover_identity("[]", "did:web:x.example").unwrap_err();
        assert!(err.to_string().contains("no recovery shares were given"));
    }
}