vouch-core 4.3.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
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
//! Data Integrity proofs, cryptosuite `eddsa-jcs-2022`.
//!
//! Signing input follows the W3C Data Integrity hashing algorithm, so proofs
//! issued here verify under any conformant `eddsa-jcs-2022` implementation:
//!   1. Build the proof configuration (the unsigned proof plus the document's
//!      `@context`) and JCS-canonicalize it (RFC 8785).
//!   2. JCS-canonicalize the unsecured document (the credential with no proof).
//!   3. hashData = SHA-256(canonical proof configuration)
//!      || SHA-256(canonical document)   (64 bytes, config first).
//!   4. Ed25519-sign hashData.
//!   5. proofValue = "z" + base58btc(signature).
//!
//! Verification also accepts the pre-alignment signing input (a single SHA-256
//! over the JCS form of the credential with the unsigned proof attached) so
//! credentials issued before this alignment keep verifying. See
//! [`legacy_proof_digest`].

#[allow(unused_imports)]
use crate::prelude::*;

use serde_json::{Map, Value};
use sha2::{Digest, Sha256};

use crate::error::{CoreError, Result};
use crate::jcs;
use crate::keys::{self, Ed25519KeyPair};

pub const CRYPTOSUITE_ID: &str = "eddsa-jcs-2022";
pub const PROOF_TYPE: &str = "DataIntegrityProof";

/// Options for building a proof. `created` is supplied by the caller (an
/// ISO-8601 instant such as "2026-04-26T10:00:00Z") so proofs are deterministic
/// and reproducible across implementations.
#[derive(Debug, Clone)]
pub struct BuildProofOptions {
    pub verification_method: String,
    pub proof_purpose: String,
    pub created: String,
}

impl BuildProofOptions {
    pub fn new(verification_method: impl Into<String>, created: impl Into<String>) -> Self {
        Self {
            verification_method: verification_method.into(),
            proof_purpose: "assertionMethod".to_string(),
            created: created.into(),
        }
    }
}

fn unsigned_proof(opts: &BuildProofOptions) -> Map<String, Value> {
    // Field insertion order matches the reference SDK so the emitted proof is
    // byte-identical. JCS sorts keys for signing, so order is irrelevant to the
    // signature, but it keeps the stored document stable across SDKs.
    let mut proof = Map::new();
    proof.insert("type".into(), Value::String(PROOF_TYPE.into()));
    proof.insert("cryptosuite".into(), Value::String(CRYPTOSUITE_ID.into()));
    proof.insert("created".into(), Value::String(opts.created.clone()));
    proof.insert(
        "verificationMethod".into(),
        Value::String(opts.verification_method.clone()),
    );
    proof.insert(
        "proofPurpose".into(),
        Value::String(opts.proof_purpose.clone()),
    );
    proof
}

/// Strip any `proof` member, yielding the unsecured document.
fn unsecured_document(credential: &Value) -> Result<Value> {
    let mut doc = credential.clone();
    doc.as_object_mut()
        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
        .remove("proof");
    Ok(doc)
}

/// Build the proof configuration, per the Data Integrity proof configuration
/// algorithm: the unsigned proof with its own `@context` when it carries one
/// (checked by [`proof_context_matches`]), otherwise the document's.
fn proof_configuration(
    document: &Value,
    unsigned: &Map<String, Value>,
) -> Result<Map<String, Value>> {
    let mut config = unsigned.clone();
    config.remove("proofValue");
    if !config.contains_key("@context") {
        if let Some(ctx) = document.get("@context") {
            config.insert("@context".into(), ctx.clone());
        }
    }
    Ok(config)
}

/// Give the proof options a copy of the document's `@context`, as
/// eddsa-jcs-2022 (and every JCS cryptosuite) describes, so the attached proof
/// carries it. The context goes first; the rest keep their order. A document
/// with no `@context` leaves the proof as it is. The signing input is the same
/// either way: the proof configuration always holds the document's context.
pub fn add_document_context(document: &Value, proof: &mut Map<String, Value>) {
    crate::nesting::deep_guard!((); document, proof);
    let Some(ctx) = document.get("@context") else {
        return;
    };
    let mut out = Map::new();
    out.insert("@context".into(), ctx.clone());
    for (k, v) in core::mem::take(proof) {
        if k != "@context" {
            out.insert(k, v);
        }
    }
    *proof = out;
}

/// Compute the 64-byte W3C Data Integrity signing input for a JCS cryptosuite:
/// SHA-256 of the canonical proof configuration, joined with SHA-256 of the
/// canonical unsecured document. This is the value that gets signed.
pub fn hash_data(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 64]> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, unsigned);
    let document = unsecured_document(credential)?;
    let config = proof_configuration(&document, unsigned)?;

    let config_hash = Sha256::digest(jcs::canonicalize(&Value::Object(config)));
    let document_hash = Sha256::digest(jcs::canonicalize(&document));

    let mut out = [0u8; 64];
    out[..32].copy_from_slice(&config_hash);
    out[32..].copy_from_slice(&document_hash);
    Ok(out)
}

/// The pre-alignment signing input: a single SHA-256 over the JCS canonical form
/// of the credential with the unsigned proof attached. Retained so credentials
/// issued before the Data Integrity alignment continue to verify. Never used for
/// new proofs.
pub fn legacy_proof_digest(credential: &Value, unsigned: &Map<String, Value>) -> Result<[u8; 32]> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, unsigned);
    let mut with_proof = credential.clone();
    with_proof
        .as_object_mut()
        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
        .insert("proof".into(), Value::Object(unsigned.clone()));
    let canonical = jcs::canonicalize(&with_proof);
    let digest = Sha256::digest(&canonical);
    Ok(digest.into())
}

/// Build an `eddsa-jcs-2022` proof for `credential` using a raw 32-byte Ed25519
/// seed. Returns the proof object (the caller attaches it, or use `sign`).
pub fn build_proof(
    credential: &Value,
    raw_private_seed: &[u8],
    opts: &BuildProofOptions,
) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
    let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
    let mut proof = unsigned_proof(opts);
    add_document_context(&unsecured_document(credential)?, &mut proof);
    let signing_input = hash_data(credential, &proof)?;
    let signature = kp.sign(&signing_input);
    let proof_value = format!("z{}", bs58::encode(signature).into_string());
    proof.insert("proofValue".into(), Value::String(proof_value));
    Ok(Value::Object(proof))
}

/// Sign a credential: build the proof and return the credential with `proof`
/// attached.
pub fn sign(
    credential: &Value,
    raw_private_seed: &[u8],
    opts: &BuildProofOptions,
) -> Result<Value> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
    let proof = build_proof(credential, raw_private_seed, opts)?;
    let mut signed = credential.clone();
    signed
        .as_object_mut()
        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?
        .insert("proof".into(), proof);
    Ok(signed)
}

/// Verify an `eddsa-jcs-2022` proof attached to `credential` against a raw
/// 32-byte Ed25519 public key. Returns Ok(true) on a valid signature, Ok(false)
/// on a signature mismatch, Err on a malformed proof.
///
/// SECURITY: this checks the signature against the key you pass, NOT that the
/// key belongs to the `verificationMethod` the proof claims. Resolve the key
/// from [`proof_verification_method`] (or otherwise confirm the key-to-method
/// binding) so a credential cannot claim one method while being signed by
/// another key you happen to trust.
pub fn verify_proof(credential: &Value, raw_public_key: &[u8]) -> Result<bool> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
    let obj = credential
        .as_object()
        .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
    let proof = obj
        .get("proof")
        .and_then(|p| p.as_object())
        .ok_or_else(|| CoreError::Json("credential has no proof object".into()))?;

    match proof.get("type").and_then(|v| v.as_str()) {
        Some(PROOF_TYPE) => {}
        other => return Err(CoreError::Json(format!("unexpected proof type: {other:?}"))),
    }
    match proof.get("cryptosuite").and_then(|v| v.as_str()) {
        Some(CRYPTOSUITE_ID) => {}
        other => {
            return Err(CoreError::Json(format!(
                "unexpected cryptosuite: {other:?}"
            )))
        }
    }
    let proof_value = proof
        .get("proofValue")
        .and_then(|v| v.as_str())
        .ok_or_else(|| CoreError::Json("missing proofValue".into()))?;
    let signature = decode_ed25519_proof_value(proof_value)?;
    if !proof_context_matches(credential, proof) {
        return Ok(false);
    }

    let mut unsigned = proof.clone();
    unsigned.remove("proofValue");

    let signing_input = hash_data(credential, &unsigned)?;
    if keys::verify(raw_public_key, &signing_input, &signature)? {
        return Ok(true);
    }
    // Fall back to the pre-alignment signing input so credentials issued before
    // the Data Integrity alignment still verify.
    let legacy = legacy_proof_digest(credential, &unsigned)?;
    keys::verify(raw_public_key, &legacy, &signature)
}

/// Decode an `eddsa-jcs-2022` proofValue strictly: multibase base58btc ('z')
/// that decodes to exactly 64 bytes.
pub fn decode_ed25519_proof_value(proof_value: &str) -> Result<Vec<u8>> {
    let body = proof_value
        .strip_prefix('z')
        .ok_or_else(|| CoreError::Json("proofValue must be multibase base58btc (z)".into()))?;
    let signature = crate::multikey::decode_base58_bounded(body)?;
    if signature.len() != keys::ED25519_SIGNATURE_LEN {
        return Err(CoreError::InvalidSignatureLength {
            expected: keys::ED25519_SIGNATURE_LEN,
            got: signature.len(),
        });
    }
    Ok(signature)
}

/// The values of an `@context`: an array is its members, any other value is
/// one value. None for a context that names nothing (null or an empty array).
fn context_values(ctx: &Value) -> Option<&[Value]> {
    match ctx {
        Value::Null => None,
        Value::Array(items) if items.is_empty() => None,
        Value::Array(items) => Some(items.as_slice()),
        one => Some(core::slice::from_ref(one)),
    }
}

/// A proof may carry its own `@context` (eddsa-jcs-2022 and the other JCS
/// cryptosuites copy the document's into it). It is accepted only when the
/// document's `@context` starts with every value of the proof's, in the same
/// order; the signing input then uses the proof's context. A proof with no
/// `@context` is checked as before, under the document's.
pub fn proof_context_matches(document: &Value, proof: &Map<String, Value>) -> bool {
    crate::nesting::deep_guard!(false; document, proof);
    let Some(ctx) = proof.get("@context") else {
        return true;
    };
    let (Some(want), Some(have)) = (
        context_values(ctx),
        document.get("@context").and_then(context_values),
    ) else {
        return false;
    };
    have.len() >= want.len() && have[..want.len()] == *want
}

/// Convenience: derive the public key from a seed and verify (for self-checks).
pub fn verify_with_seed(credential: &Value, raw_private_seed: &[u8]) -> Result<bool> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
    let kp = Ed25519KeyPair::from_seed_slice(raw_private_seed)?;
    verify_proof(credential, &kp.public_key())
}

/// Return the `verificationMethod` declared by the credential's proof. Callers
/// should resolve the verification key from THIS identifier before verifying, so
/// the key is bound to the method the proof claims (see the SECURITY note on
/// [`verify_proof`]).
pub fn proof_verification_method(credential: &Value) -> Result<String> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
    credential
        .as_object()
        .and_then(|o| o.get("proof"))
        .and_then(|p| p.as_object())
        .and_then(|p| p.get("verificationMethod"))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string())
        .ok_or_else(|| CoreError::Json("proof has no verificationMethod".into()))
}

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

    /// A credential issued before the Data Integrity alignment, whose signature
    /// covers the pre-alignment signing input, MUST still verify.
    #[test]
    fn verifies_pre_alignment_credential() {
        let public_key = [
            0x4c, 0xb5, 0xab, 0xf6, 0xad, 0x79, 0xfb, 0xf5, 0xab, 0xbc, 0xca, 0xfc, 0xc2, 0x69,
            0xd8, 0x5c, 0xd2, 0x65, 0x1e, 0xd4, 0xb8, 0x85, 0xb5, 0x86, 0x9f, 0x24, 0x1a, 0xed,
            0xf0, 0xa5, 0xba, 0x29,
        ];
        let credential = json!({
            "@context": [
                "https://www.w3.org/ns/credentials/v2",
                "https://vouch-protocol.com/contexts/v1"
            ],
            "type": ["VerifiableCredential", "VouchCredential"],
            "issuer": "did:web:test.example.com",
            "validFrom": "2026-04-26T10:00:00Z",
            "validUntil": "2026-04-26T10:05:00Z",
            "credentialSubject": {
                "id": "did:web:test.example.com",
                "vouchVersion": "1.0",
                "intent": {
                    "action": "read_database",
                    "target": "users_table",
                    "resource": "https://api.example.com/v1/users"
                }
            },
            "proof": {
                "type": "DataIntegrityProof",
                "cryptosuite": "eddsa-jcs-2022",
                "created": "2026-04-26T10:00:00Z",
                "verificationMethod": "did:web:test.example.com#key-1",
                "proofPurpose": "assertionMethod",
                "proofValue": "z24FsZHuADF9uwHAfsjW3okmynrNCCN4QkQirEPfEy5MtcXzg4uhFqz4o3RVH57cFvVXg9oarC4m51YEmNu5UQRLQ"
            }
        });
        assert!(verify_proof(&credential, &public_key).expect("verification error"));
    }

    fn sample_credential() -> Value {
        json!({
            "@context": ["https://www.w3.org/ns/credentials/v2"],
            "type": ["VerifiableCredential", "VouchCredential"],
            "issuer": "did:web:agent.example.com",
            "validFrom": "2026-04-26T10:00:00Z",
            "validUntil": "2026-04-26T10:05:00Z",
            "credentialSubject": {
                "id": "did:web:agent.example.com",
                "vouchVersion": "1.0",
                "intent": {
                    "action": "read_database",
                    "target": "users_table",
                    "resource": "https://api.example.com/v1/users"
                }
            }
        })
    }

    #[test]
    fn sign_then_verify_roundtrip() {
        let seed = [9u8; 32];
        let cred = sample_credential();
        let opts =
            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
        let signed = sign(&cred, &seed, &opts).unwrap();
        assert!(verify_with_seed(&signed, &seed).unwrap());
    }

    #[test]
    fn tamper_fails_verification() {
        let seed = [9u8; 32];
        let cred = sample_credential();
        let opts =
            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
        let mut signed = sign(&cred, &seed, &opts).unwrap();
        signed["credentialSubject"]["intent"]["action"] = json!("delete_database");
        assert!(!verify_with_seed(&signed, &seed).unwrap());
    }

    #[test]
    fn exposes_proof_verification_method() {
        let seed = [9u8; 32];
        let opts =
            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
        let signed = sign(&sample_credential(), &seed, &opts).unwrap();
        assert_eq!(
            proof_verification_method(&signed).unwrap(),
            "did:web:agent.example.com#key-1"
        );
        assert!(proof_verification_method(&sample_credential()).is_err());
    }

    #[test]
    fn deterministic_proof_value() {
        let seed = [9u8; 32];
        let cred = sample_credential();
        let opts =
            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
        let a = build_proof(&cred, &seed, &opts).unwrap();
        let b = build_proof(&cred, &seed, &opts).unwrap();
        assert_eq!(a["proofValue"], b["proofValue"]);
    }

    fn did_key_signed(seed: &[u8; 32]) -> Value {
        let kp = Ed25519KeyPair::from_seed(seed);
        let did = kp.did_key();
        let mut cred = sample_credential();
        cred["issuer"] = json!(did);
        cred["@context"] = json!([
            "https://www.w3.org/ns/credentials/v2",
            "https://vouch-protocol.com/contexts/v1"
        ]);
        let opts = BuildProofOptions::new(
            crate::verification_method::ed25519_method(&did),
            "2026-04-26T10:00:00Z",
        );
        sign(&cred, seed, &opts).unwrap()
    }

    #[test]
    fn a_proof_carries_a_copy_of_the_document_context_first() {
        let signed = did_key_signed(&[9u8; 32]);
        let proof = signed["proof"].as_object().unwrap();
        assert_eq!(proof.keys().next().map(String::as_str), Some("@context"));
        assert_eq!(proof["@context"], signed["@context"]);
        assert!(verify_with_seed(&signed, &[9u8; 32]).unwrap());
    }

    #[test]
    fn a_document_without_context_gives_a_proof_without_one() {
        let mut cred = sample_credential();
        cred.as_object_mut().unwrap().remove("@context");
        let opts =
            BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
        let proof = build_proof(&cred, &[9u8; 32], &opts).unwrap();
        assert!(proof.get("@context").is_none());
    }

    /// The proof @context is covered by the signing input: the signature is
    /// the same with or without the copy, and a proof signed before proofs
    /// carried it still verifies.
    #[test]
    fn a_proof_without_context_still_verifies() {
        let seed = [9u8; 32];
        let signed = did_key_signed(&seed);
        let mut older = signed.clone();
        older["proof"].as_object_mut().unwrap().remove("@context");
        assert!(verify_with_seed(&older, &seed).unwrap());
        assert_eq!(older["proof"]["proofValue"], signed["proof"]["proofValue"]);
    }

    #[test]
    fn a_tampered_proof_context_fails() {
        let seed = [9u8; 32];
        let signed = did_key_signed(&seed);
        for ctx in [
            json!(["https://other.example"]),
            json!([
                "https://vouch-protocol.com/contexts/v1",
                "https://www.w3.org/ns/credentials/v2"
            ]),
            json!([
                "https://www.w3.org/ns/credentials/v2",
                "https://vouch-protocol.com/contexts/v1",
                "https://x"
            ]),
            json!([]),
            Value::Null,
            json!({}),
        ] {
            let mut bad = signed.clone();
            bad["proof"]["@context"] = ctx.clone();
            assert!(!verify_with_seed(&bad, &seed).unwrap(), "{ctx}");
        }
        // The document's first value alone is a prefix, so it is not refused
        // as unbound, but the signature covers the full context.
        let mut prefix = signed.clone();
        prefix["proof"]["@context"] = json!(["https://www.w3.org/ns/credentials/v2"]);
        assert!(!verify_with_seed(&prefix, &seed).unwrap());
    }

    #[test]
    fn a_prefix_proof_context_signed_over_it_verifies() {
        let seed = [9u8; 32];
        let cred = sample_credential();
        let mut unsigned = unsigned_proof(&BuildProofOptions::new(
            "did:web:agent.example.com#key-1",
            "2026-04-26T10:00:00Z",
        ));
        unsigned.insert(
            "@context".into(),
            json!(["https://www.w3.org/ns/credentials/v2"]),
        );
        let mut doc = cred.clone();
        doc["@context"] = json!(["https://www.w3.org/ns/credentials/v2", "https://x.example"]);
        let input = hash_data(&doc, &unsigned).unwrap();
        let sig = Ed25519KeyPair::from_seed(&seed).sign(&input);
        unsigned.insert(
            "proofValue".into(),
            json!(format!("z{}", bs58::encode(sig).into_string())),
        );
        doc["proof"] = Value::Object(unsigned);
        assert!(verify_with_seed(&doc, &seed).unwrap());
        // The document must start with the proof's context.
        doc["@context"] = json!(["https://x.example", "https://www.w3.org/ns/credentials/v2"]);
        assert!(!verify_with_seed(&doc, &seed).unwrap());
    }

    #[test]
    fn context_prefix_rule() {
        let doc = json!({"@context": ["a", "b"]});
        let ok = |ctx: Value| {
            let mut p = Map::new();
            p.insert("@context".into(), ctx);
            proof_context_matches(&doc, &p)
        };
        assert!(proof_context_matches(&doc, &Map::new()));
        assert!(ok(json!(["a", "b"])));
        assert!(ok(json!(["a"])));
        assert!(ok(json!("a")));
        assert!(!ok(json!("b")));
        assert!(!ok(json!(["b", "a"])));
        assert!(!ok(json!(["a", "b", "c"])));
        assert!(!ok(json!([])));
        assert!(!ok(Value::Null));
        assert!(!proof_context_matches(&json!({}), &{
            let mut p = Map::new();
            p.insert("@context".into(), json!(["a"]));
            p
        }));
    }
}