vouch-core 4.1.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
//! Robotics builders for a signer the core does not hold.
//!
//! Every robotics builder takes an Ed25519 seed and signs inside the core. A
//! host whose key lives elsewhere (a KMS, a secure element, a signing
//! service) uses [`prepare`] and [`finish`] instead:
//!
//! 1. [`prepare`] runs the builder with the caller's public key in place of a
//!    seed and answers the unsigned credential (its `proof` has every member
//!    but `proofValue`) and the 64-byte eddsa-jcs-2022 signing input.
//! 2. The host signs the signing input with its key.
//! 3. [`finish`] attaches the signature and checks the proof under the public
//!    key, so a wrong key or a wrong signature never leaves the core as a
//!    signed credential.
//!
//! How [`prepare`] builds without the seed: it runs the builder twice, each
//! time with a fresh random stand-in seed, and puts the caller's key wherever
//! the stand-in's public key appears (its multikey, so its did:key and
//! verification method too). The two runs must then agree exactly apart from
//! the signature. A builder whose output depends on its key in any other way
//! (a hash of the key, a value derived from the signature) gives two
//! different answers and is refused, as is any other trace of a stand-in key
//! in the output.

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

use crate::data_integrity;
use crate::error::{CoreError, Result};
use crate::keys::Ed25519KeyPair;
use crate::multikey;
use crate::robotics_call;

fn err(msg: &str) -> CoreError {
    CoreError::Json(msg.into())
}

/// One run of the builder under a random stand-in seed, with the stand-in's
/// key replaced by the caller's.
fn build_once(
    name: &str,
    seed_field: &str,
    request: &Map<String, Value>,
    real_mb: &str,
    host_now: &str,
) -> Result<Value> {
    let mut seed = Zeroizing::new([0u8; 32]);
    getrandom::getrandom(&mut seed[..]).map_err(|e| CoreError::Crypto(format!("rng: {e}")))?;
    let stand_in = Ed25519KeyPair::from_seed(&seed);
    let public = stand_in.public_key();
    let stand_in_mb = multikey::encode_ed25519_public(&public)?;

    let mut req = request.clone();
    req.insert(seed_field.into(), Value::String(STANDARD.encode(&seed[..])));
    let text = Zeroizing::new(Value::Object(req).to_string());
    let out = robotics_call::call(name, &text, host_now)?;

    // Every trace of the stand-in key, in the encodings a builder could use.
    let traces = [
        STANDARD.encode(public),
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public),
        bs58::encode(public).into_string(),
        public
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect::<String>(),
    ];
    let swapped = out.replace(&stand_in_mb, real_mb);
    if traces.iter().any(|t| swapped.contains(t.as_str())) {
        return Err(err(
            "this builder derives values from its key; it needs the seed",
        ));
    }
    serde_json::from_str(&swapped).map_err(|e| CoreError::Json(format!("json: {e}")))
}

/// Remove the top-level proof's `proofValue`; the proof must be one
/// eddsa-jcs-2022 proof object.
fn strip(mut doc: Value) -> Result<(Value, Map<String, Value>)> {
    let obj = doc
        .as_object_mut()
        .ok_or_else(|| err("the builder did not answer a credential"))?;
    let mut proof = match obj.remove("proof") {
        Some(Value::Object(p)) => p,
        _ => return Err(err("the builder's answer has no single proof")),
    };
    if proof.get("cryptosuite").and_then(Value::as_str) != Some(data_integrity::CRYPTOSUITE_ID) {
        return Err(err("the builder's proof is not eddsa-jcs-2022"));
    }
    proof.remove("proofValue");
    Ok((doc, proof))
}

/// Run builder `name` for a signer the core does not hold. The request is the
/// builder's [`robotics_call`] request with `publicKey` (the signer's 32-byte
/// Ed25519 public key, standard base64) in place of the seed. Answers
/// `{credential, signingInput}`: the credential with its proof minus
/// `proofValue`, and the 64-byte signing input (standard base64).
pub fn prepare(name: &str, request_json: &str, host_now: &str) -> Result<String> {
    let seed_field = robotics_call::SEED_FIELDS
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, f)| *f)
        .ok_or_else(|| CoreError::Json(format!("{name:?} is not a robotics builder")))?;
    let request: Value =
        serde_json::from_str(request_json).map_err(|e| CoreError::Json(format!("json: {e}")))?;
    let mut request = match request {
        Value::Object(o) => o,
        _ => return Err(err("the request must be a JSON object")),
    };
    if request.get(seed_field).is_some_and(|v| !v.is_null()) {
        return Err(CoreError::Json(format!(
            "a prepare request carries no {seed_field}"
        )));
    }
    let public = match request.remove("publicKey") {
        Some(Value::String(s)) => STANDARD
            .decode(s)
            .map_err(|_| err("publicKey must be standard base64"))?,
        _ => return Err(err("publicKey is required")),
    };
    let real_mb = multikey::encode_ed25519_public(&public)?;
    if public.len() != 32 {
        return Err(err("publicKey must be 32 bytes"));
    }

    let (first, proof) = strip(build_once(name, seed_field, &request, &real_mb, host_now)?)?;
    let (second, proof2) = strip(build_once(name, seed_field, &request, &real_mb, host_now)?)?;
    if first != second || proof != proof2 {
        return Err(err(
            "this builder's output depends on its key or signature; it needs the seed",
        ));
    }
    let signing_input = data_integrity::hash_data(&first, &proof)?;
    let mut credential = first;
    if let Some(o) = credential.as_object_mut() {
        o.insert("proof".into(), Value::Object(proof));
    }
    Ok(json!({
        "credential": credential,
        "signingInput": STANDARD.encode(signing_input),
    })
    .to_string())
}

/// Attach the host's signature to a prepared credential: `{credential,
/// signature, publicKey}` (signature and key in standard base64). The proof
/// must verify under `publicKey`, or the call fails. Answers the signed
/// credential.
pub fn finish(request_json: &str) -> Result<String> {
    let request: Value =
        serde_json::from_str(request_json).map_err(|e| CoreError::Json(format!("json: {e}")))?;
    let b64 = |k: &str| -> Result<Vec<u8>> {
        match request.get(k) {
            Some(Value::String(s)) => STANDARD
                .decode(s)
                .map_err(|_| CoreError::Json(format!("{k} must be standard base64"))),
            _ => Err(CoreError::Json(format!("{k} is required"))),
        }
    };
    let signature = b64("signature")?;
    let public = b64("publicKey")?;
    if signature.len() != 64 {
        return Err(err("signature must be 64 bytes"));
    }
    let mut credential = request
        .get("credential")
        .cloned()
        .ok_or_else(|| err("credential is required"))?;
    let proof = credential
        .get_mut("proof")
        .and_then(Value::as_object_mut)
        .ok_or_else(|| err("credential has no proof"))?;
    if proof.contains_key("proofValue") {
        return Err(err("credential is already signed"));
    }
    proof.insert(
        "proofValue".into(),
        Value::String(format!("z{}", bs58::encode(&signature).into_string())),
    );
    if !data_integrity::verify_proof(&credential, &public)? {
        return Err(err("the signature does not verify under publicKey"));
    }
    Ok(credential.to_string())
}

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

    const NOW: &str = "2026-06-01T00:00:00Z";

    fn seed_request(seed: &[u8; 32]) -> (Ed25519KeyPair, Value) {
        let kp = Ed25519KeyPair::from_seed(seed);
        let did = kp.did_key();
        (
            kp,
            json!({
                "params": {
                    "issuerDid": did,
                    "subjectDid": "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK",
                    "maxForceN": 50,
                    "validFrom": NOW,
                }
            }),
        )
    }

    #[test]
    fn prepare_then_finish_equals_signing_with_the_seed() {
        let seed = [7u8; 32];
        let (kp, mut req) = seed_request(&seed);
        let mut with_seed = req.clone();
        with_seed["signerSeed"] = json!(STANDARD.encode(seed));
        let direct: Value = serde_json::from_str(
            &robotics_call::call(
                "build_physical_scope_credential",
                &with_seed.to_string(),
                NOW,
            )
            .unwrap(),
        )
        .unwrap();

        req["publicKey"] = json!(STANDARD.encode(kp.public_key()));
        let prepared: Value = serde_json::from_str(
            &prepare("build_physical_scope_credential", &req.to_string(), NOW).unwrap(),
        )
        .unwrap();
        let input = STANDARD
            .decode(prepared["signingInput"].as_str().unwrap())
            .unwrap();
        let sig = kp.sign(&input);
        let signed: Value = serde_json::from_str(
            &finish(
                &json!({
                    "credential": prepared["credential"],
                    "signature": STANDARD.encode(sig),
                    "publicKey": STANDARD.encode(kp.public_key()),
                })
                .to_string(),
            )
            .unwrap(),
        )
        .unwrap();
        assert_eq!(signed, direct);
    }

    #[test]
    fn a_key_derived_issuer_takes_the_callers_key() {
        // The halos builder names its issuer after the signing key.
        let kp = Ed25519KeyPair::from_seed(&[9u8; 32]);
        let req = json!({
            "publicKey": STANDARD.encode(kp.public_key()),
            "params": {
                "blackboxHead": "uAAAA", "entryCount": 1,
                "halosStack": {"layer": "x"},
                "window": {"from": NOW, "to": NOW},
                "validFrom": NOW, "created": NOW,
            }
        });
        let out = prepare("build_safety_evidence", &req.to_string(), NOW).unwrap();
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v["credential"]["issuer"], json!(kp.did_key()));
        let input = STANDARD
            .decode(v["signingInput"].as_str().unwrap())
            .unwrap();
        let signed = finish(
            &json!({
                "credential": v["credential"],
                "signature": STANDARD.encode(kp.sign(&input)),
                "publicKey": STANDARD.encode(kp.public_key()),
            })
            .to_string(),
        );
        assert!(signed.is_ok());
    }

    #[test]
    fn finish_refuses_a_wrong_signature_or_key() {
        let seed = [7u8; 32];
        let (kp, mut req) = seed_request(&seed);
        req["publicKey"] = json!(STANDARD.encode(kp.public_key()));
        let prepared: Value = serde_json::from_str(
            &prepare("build_physical_scope_credential", &req.to_string(), NOW).unwrap(),
        )
        .unwrap();
        let other = Ed25519KeyPair::from_seed(&[8u8; 32]);
        let input = STANDARD
            .decode(prepared["signingInput"].as_str().unwrap())
            .unwrap();
        let bad = other.sign(&input);
        let r = finish(
            &json!({
                "credential": prepared["credential"],
                "signature": STANDARD.encode(bad),
                "publicKey": STANDARD.encode(kp.public_key()),
            })
            .to_string(),
        );
        assert!(r.is_err());
    }

    #[test]
    fn prepare_refuses_a_seed_and_a_non_builder() {
        let (kp, mut req) = seed_request(&[7u8; 32]);
        req["publicKey"] = json!(STANDARD.encode(kp.public_key()));
        req["signerSeed"] = json!(STANDARD.encode([7u8; 32]));
        assert!(prepare("build_physical_scope_credential", &req.to_string(), NOW).is_err());
        assert!(prepare("verify_robot_identity", "{}", NOW).is_err());
    }
}