auths-verifier 0.1.2

Minimal-dependency attestation verification library for Auths - supports FFI and WASM
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
use crate::clock::{ClockProvider, SystemClock};
use crate::core::{
    Attestation, DevicePublicKey, MAX_ATTESTATION_JSON_SIZE, MAX_FILE_HASH_HEX_LEN,
    MAX_JSON_BATCH_SIZE, MAX_PUBLIC_KEY_HEX_LEN, MAX_SIGNATURE_HEX_LEN,
};
use crate::error::{AttestationError, AuthsErrorInfo};
use crate::types::VerificationReport;
use crate::verify;
use crate::witness::WitnessVerifyConfig;
use auths_crypto::{CryptoProvider, CurveType, WebCryptoProvider};
use auths_keri::witness::SignedReceipt;
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;

/// Decode a hex-encoded public key and infer its curve from length.
///
/// Accepts 32 bytes (Ed25519), 33 or 65 bytes (P-256).
fn pk_from_hex_wasm(pk_hex: &str) -> Result<DevicePublicKey, AttestationError> {
    let bytes = hex::decode(pk_hex)
        .map_err(|e| AttestationError::InvalidInput(format!("Invalid public key hex: {}", e)))?;
    let curve = match bytes.len() {
        32 => auths_crypto::CurveType::Ed25519,
        33 | 65 => auths_crypto::CurveType::P256,
        n => {
            return Err(AttestationError::InvalidInput(format!(
                "Invalid public key length: expected 32 (Ed25519) or 33/65 (P-256), got {n}"
            )));
        }
    };
    DevicePublicKey::try_new(curve, &bytes)
        .map_err(|e| AttestationError::InvalidInput(e.to_string()))
}

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);
}
macro_rules! console_log { ($($t:tt)*) => (log(&format_args!($($t)*).to_string())) }

fn provider() -> WebCryptoProvider {
    WebCryptoProvider
}

/// Result of a WASM attestation verification operation.
#[derive(Serialize, Deserialize)]
pub struct WasmVerificationResult {
    /// Whether the attestation verified successfully.
    pub valid: bool,
    /// Human-readable error message if verification failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Structured error code for programmatic handling.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_code: Option<String>,
}

/// Verifies an attestation provided as a JSON string against an explicit issuer public key hex string.
#[wasm_bindgen(js_name = verifyAttestationJson)]
pub async fn wasm_verify_attestation_json(
    attestation_json_str: &str,
    issuer_pk_hex: &str,
) -> Result<(), JsValue> {
    console_log!("WASM: Verifying attestation...");

    if attestation_json_str.len() > MAX_ATTESTATION_JSON_SIZE {
        return Err(JsValue::from_str(&format!(
            "Attestation JSON too large: {} bytes, max {}",
            attestation_json_str.len(),
            MAX_ATTESTATION_JSON_SIZE
        )));
    }

    let issuer_pk =
        pk_from_hex_wasm(issuer_pk_hex).map_err(|e| JsValue::from_str(&e.to_string()))?;

    let att: Attestation = serde_json::from_str(attestation_json_str)
        .map_err(|e| JsValue::from_str(&format!("Failed to parse attestation JSON: {}", e)))?;

    match verify::verify_with_keys_at(&att, &issuer_pk, SystemClock.now(), true, &provider()).await
    {
        Ok(()) => {
            console_log!("WASM: Verification successful.");
            Ok(())
        }
        Err(e) => {
            console_log!("WASM: Verification failed: {}", e);
            Err(JsValue::from_str(&format!("[{}] {}", e.error_code(), e)))
        }
    }
}

/// Verifies an attestation and returns a JSON result object.
#[wasm_bindgen(js_name = verifyAttestationWithResult)]
pub async fn wasm_verify_attestation_with_result(
    attestation_json_str: &str,
    issuer_pk_hex: &str,
) -> String {
    let result =
        match verify_attestation_internal(attestation_json_str, issuer_pk_hex, &provider()).await {
            Ok(()) => WasmVerificationResult {
                valid: true,
                error: None,
                error_code: None,
            },
            Err(e) => WasmVerificationResult {
                valid: false,
                error: Some(e.to_string()),
                error_code: Some(e.error_code().to_string()),
            },
        };
    serde_json::to_string(&result)
        .unwrap_or_else(|_| r#"{"valid":false,"error":"Serialization failed"}"#.to_string())
}

async fn verify_attestation_internal(
    attestation_json_str: &str,
    issuer_pk_hex: &str,
    provider: &dyn CryptoProvider,
) -> Result<(), AttestationError> {
    if attestation_json_str.len() > MAX_ATTESTATION_JSON_SIZE {
        return Err(AttestationError::InputTooLarge(format!(
            "Attestation JSON too large: {} bytes, max {}",
            attestation_json_str.len(),
            MAX_ATTESTATION_JSON_SIZE
        )));
    }

    let issuer_pk = pk_from_hex_wasm(issuer_pk_hex)?;

    let att: Attestation = serde_json::from_str(attestation_json_str).map_err(|e| {
        AttestationError::SerializationError(format!("Failed to parse attestation JSON: {}", e))
    })?;

    verify::verify_with_keys_at(&att, &issuer_pk, SystemClock.now(), true, provider).await
}

/// Verifies a detached signature over a file hash (all inputs hex-encoded).
///
/// Args:
/// * `file_hash_hex`: Hex-encoded file hash.
/// * `signature_hex`: Hex-encoded signature.
/// * `public_key_hex`: Hex-encoded public key.
/// * `curve`: Curve name ("ed25519" or "p256"). Defaults to P-256.
#[wasm_bindgen(js_name = verifyArtifactSignature)]
pub async fn wasm_verify_artifact_signature(
    file_hash_hex: &str,
    signature_hex: &str,
    public_key_hex: &str,
    curve: Option<String>,
) -> bool {
    if file_hash_hex.len() > MAX_FILE_HASH_HEX_LEN
        || signature_hex.len() > MAX_SIGNATURE_HEX_LEN
        || public_key_hex.len() > MAX_PUBLIC_KEY_HEX_LEN
    {
        return false;
    }

    let Ok(hash_bytes) = hex::decode(file_hash_hex) else {
        return false;
    };
    let Ok(sig_bytes) = hex::decode(signature_hex) else {
        return false;
    };
    let Ok(pk_bytes) = hex::decode(public_key_hex) else {
        return false;
    };

    let curve_type = match curve.as_deref() {
        Some("ed25519") | Some("Ed25519") => CurveType::Ed25519,
        _ => CurveType::P256,
    };

    if sig_bytes.len() != 64 {
        return false;
    }

    let Ok(typed_pk) = DevicePublicKey::try_new(curve_type, &pk_bytes) else {
        return false;
    };

    typed_pk
        .verify(&hash_bytes, &sig_bytes, &provider())
        .await
        .is_ok()
}

/// Verifies a chain of attestations and returns a VerificationReport as JSON.
#[wasm_bindgen(js_name = verifyChainJson)]
pub async fn wasm_verify_chain_json(attestations_json_array: &str, root_pk_hex: &str) -> String {
    match verify_chain_internal(attestations_json_array, root_pk_hex, &provider()).await {
        Ok(report) => serde_json::to_string(&report)
            .unwrap_or_else(|_| r#"{"status":{"type":"BrokenChain","missingLink":"Serialization failed"},"chain":[],"warnings":[]}"#.to_string()),
        Err(e) => {
            let error_response = serde_json::json!({
                "status": { "type": "BrokenChain", "missing_link": e.to_string() },
                "chain": [],
                "warnings": [],
                "error_code": e.error_code(),
            });
            error_response.to_string()
        }
    }
}

async fn verify_chain_internal(
    attestations_json_array: &str,
    root_pk_hex: &str,
    provider: &dyn CryptoProvider,
) -> Result<VerificationReport, AttestationError> {
    if attestations_json_array.len() > MAX_JSON_BATCH_SIZE {
        return Err(AttestationError::InputTooLarge(format!(
            "Attestations JSON too large: {} bytes, max {}",
            attestations_json_array.len(),
            MAX_JSON_BATCH_SIZE
        )));
    }

    let root_pk = pk_from_hex_wasm(root_pk_hex)?;

    let attestations: Vec<Attestation> =
        serde_json::from_str(attestations_json_array).map_err(|e| {
            AttestationError::SerializationError(format!(
                "Failed to parse attestations JSON array: {}",
                e
            ))
        })?;

    verify::verify_chain_inner(&attestations, &root_pk, provider, SystemClock.now()).await
}

/// Verifies a chain of attestations with witness quorum checking.
#[wasm_bindgen(js_name = verifyChainWithWitnesses)]
pub async fn wasm_verify_chain_with_witnesses_json(
    chain_json: &str,
    root_pk_hex: &str,
    receipts_json: &str,
    witness_keys_json: &str,
    threshold: u32,
) -> String {
    match verify_chain_with_witnesses_internal(
        chain_json,
        root_pk_hex,
        receipts_json,
        witness_keys_json,
        threshold,
        &provider(),
    )
    .await
    {
        Ok(report) => serde_json::to_string(&report)
            .unwrap_or_else(|_| r#"{"status":{"type":"BrokenChain","missing_link":"Serialization failed"},"chain":[],"warnings":[]}"#.to_string()),
        Err(e) => {
            let error_response = serde_json::json!({
                "status": { "type": "BrokenChain", "missing_link": e.to_string() },
                "chain": [],
                "warnings": [],
                "error_code": e.error_code(),
            });
            error_response.to_string()
        }
    }
}

async fn verify_chain_with_witnesses_internal(
    chain_json: &str,
    root_pk_hex: &str,
    receipts_json: &str,
    witness_keys_json: &str,
    threshold: u32,
    provider: &dyn CryptoProvider,
) -> Result<VerificationReport, AttestationError> {
    if chain_json.len() > MAX_JSON_BATCH_SIZE {
        return Err(AttestationError::InputTooLarge(format!(
            "Chain JSON too large: {} bytes, max {}",
            chain_json.len(),
            MAX_JSON_BATCH_SIZE
        )));
    }
    if receipts_json.len() > MAX_JSON_BATCH_SIZE {
        return Err(AttestationError::InputTooLarge(format!(
            "Receipts JSON too large: {} bytes, max {}",
            receipts_json.len(),
            MAX_JSON_BATCH_SIZE
        )));
    }
    if witness_keys_json.len() > MAX_JSON_BATCH_SIZE {
        return Err(AttestationError::InputTooLarge(format!(
            "Witness keys JSON too large: {} bytes, max {}",
            witness_keys_json.len(),
            MAX_JSON_BATCH_SIZE
        )));
    }

    let root_pk = pk_from_hex_wasm(root_pk_hex)?;

    let attestations: Vec<Attestation> = serde_json::from_str(chain_json).map_err(|e| {
        AttestationError::SerializationError(format!("Failed to parse attestations JSON: {}", e))
    })?;

    let receipts: Vec<SignedReceipt> = serde_json::from_str(receipts_json).map_err(|e| {
        AttestationError::SerializationError(format!("Failed to parse receipts JSON: {}", e))
    })?;

    #[derive(Deserialize)]
    struct WitnessKeyEntry {
        did: String,
        pk_hex: String,
    }
    let key_entries: Vec<WitnessKeyEntry> =
        serde_json::from_str(witness_keys_json).map_err(|e| {
            AttestationError::SerializationError(format!(
                "Failed to parse witness keys JSON: {}",
                e
            ))
        })?;

    let witness_keys: Vec<(String, Vec<u8>)> = key_entries
        .into_iter()
        .map(|e| {
            hex::decode(&e.pk_hex).map(|pk| (e.did, pk)).map_err(|err| {
                AttestationError::InvalidInput(format!("Invalid witness key hex: {}", err))
            })
        })
        .collect::<Result<Vec<_>, _>>()?;

    let config = WitnessVerifyConfig {
        receipts: &receipts,
        witness_keys: &witness_keys,
        threshold: threshold as usize,
    };

    let mut report =
        verify::verify_chain_inner(&attestations, &root_pk, provider, SystemClock.now()).await?;

    if report.is_valid() {
        let quorum = crate::witness::verify_witness_receipts(&config, provider).await;
        if quorum.verified < quorum.required {
            report.status = crate::types::VerificationStatus::InsufficientWitnesses {
                required: quorum.required,
                verified: quorum.verified,
            };
            report.warnings.push(format!(
                "Witness quorum not met: {}/{} verified",
                quorum.verified, quorum.required
            ));
        }
        report.witness_quorum = Some(quorum);
    }

    Ok(report)
}

/// Verifies a KERI Key Event Log and returns the resulting key state as JSON.
///
/// Args:
/// * `kel_json`: JSON array of KEL events (inception, rotation, interaction).
///
/// Usage:
/// ```ignore
/// let key_state_json = validateKelJson("[{\"v\":\"KERI10JSON\",\"t\":\"icp\",...}]").await?;
/// ```
#[wasm_bindgen(js_name = validateKelJson)]
pub async fn wasm_validate_kel_json(kel_json: &str) -> Result<String, JsValue> {
    console_log!("WASM: Verifying KEL...");

    if kel_json.len() > MAX_JSON_BATCH_SIZE {
        return Err(JsValue::from_str(&format!(
            "KEL JSON too large: {} bytes, max {}",
            kel_json.len(),
            MAX_JSON_BATCH_SIZE
        )));
    }

    let events = auths_keri::parse_kel_json(kel_json)
        .map_err(|e| JsValue::from_str(&format!("Failed to parse KEL JSON: {}", e)))?;

    let key_state = auths_keri::validate_kel(&events)
        .map_err(|e| JsValue::from_str(&format!("KEL verification failed: {}", e)))?;

    console_log!(
        "WASM: KEL verification successful, sequence: {}",
        key_state.sequence
    );

    serde_json::to_string(&key_state)
        .map_err(|e| JsValue::from_str(&format!("Failed to serialize key state: {}", e)))
}

/// Verifies that a device is cryptographically linked to a KERI identity.
///
/// Composes KEL verification, attestation signature verification, device DID matching,
/// and seal anchoring. Returns a JSON result (never throws for verification failures).
///
/// Args:
/// * `kel_json`: JSON array of KEL events.
/// * `attestation_json`: JSON attestation linking identity to device.
/// * `device_did`: Expected device DID string (e.g. `"did:key:z6Mk..."`).
///
/// Usage:
/// ```ignore
/// let result = verifyDeviceLink(kelJson, attestationJson, "did:key:z6Mk...").await;
/// // result: {"valid": true, "key_state": {...}, "seal_sequence": 2}
/// // or:     {"valid": false, "error": "..."}
/// ```
#[wasm_bindgen(js_name = verifyDeviceLink)]
pub async fn wasm_verify_device_link(
    kel_json: &str,
    attestation_json: &str,
    device_did: &str,
) -> Result<String, JsValue> {
    console_log!("WASM: Verifying device link for {}", device_did);

    if kel_json.len() > MAX_JSON_BATCH_SIZE {
        return Err(JsValue::from_str(&format!(
            "KEL JSON too large: {} bytes, max {}",
            kel_json.len(),
            MAX_JSON_BATCH_SIZE
        )));
    }
    if attestation_json.len() > MAX_ATTESTATION_JSON_SIZE {
        return Err(JsValue::from_str(&format!(
            "Attestation JSON too large: {} bytes, max {}",
            attestation_json.len(),
            MAX_ATTESTATION_JSON_SIZE
        )));
    }

    let events = auths_keri::parse_kel_json(kel_json)
        .map_err(|e| JsValue::from_str(&format!("Failed to parse KEL JSON: {}", e)))?;

    let attestation: Attestation = serde_json::from_str(attestation_json)
        .map_err(|e| JsValue::from_str(&format!("Failed to parse attestation JSON: {}", e)))?;

    let result = crate::verify::verify_device_link(
        &events,
        &attestation,
        device_did,
        SystemClock.now(),
        &provider(),
    )
    .await;

    console_log!(
        "WASM: Device link verification result: valid={}",
        result.valid
    );

    serde_json::to_string(&result)
        .map_err(|e| JsValue::from_str(&format!("Failed to serialize result: {}", e)))
}

/// Verify a credential **presentation** from a bundled JSON request (the fn-153.3 contract),
/// returning the tagged discriminated-union verdict as a JSON string.
///
/// Synchronous by construction: the verify core (fn-153.1/.3) runs the pure-Rust
/// `software_verify` path, so there is no `block_on`/executor — which is mandatory in
/// single-threaded browser WASM. Keys travel CESR-tagged inside the request JSON; there is
/// no raw-pubkey argument and no byte-length curve dispatch (`pk_from_hex_wasm` is not used).
///
/// Args:
/// * `bundle_json`: A `VerifyPresentationRequest` JSON document (see `contract` module docs).
///
/// Usage (TypeScript):
/// ```ignore
/// import { verifyPresentationJson } from "auths-verifier";
/// import type { PresentationVerdictEnvelope } from "auths-verifier/ts/verdict";
/// const verdict = JSON.parse(verifyPresentationJson(bundle)) as PresentationVerdictEnvelope;
/// if (verdict.kind === "valid") {
///   // verdict.subject and verdict.caps are now available, fully typed
/// }
/// ```
#[wasm_bindgen(js_name = verifyPresentationJson)]
pub fn wasm_verify_presentation_json(bundle_json: &str) -> String {
    crate::contract::verify_presentation_json(bundle_json)
}

/// Verify an issued **credential** from a bundled JSON request (the fn-153.3 contract),
/// returning the tagged discriminated-union verdict as a JSON string. Same synchronous,
/// executor-free, CESR-tagged-key contract as [`wasm_verify_presentation_json`].
///
/// Args:
/// * `bundle_json`: A `VerifyCredentialRequest` JSON document (see `contract` module docs).
#[wasm_bindgen(js_name = verifyCredentialJson)]
pub fn wasm_verify_credential_json(bundle_json: &str) -> String {
    crate::contract::verify_credential_json(bundle_json)
}