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
//! did:web identifiers and trusted-root shorthand, parsed strictly and the same
//! way as the Python reference (`vouch.did_web.parse_did_web` and
//! `vouch.trusted_roots.normalize_root`).
//!
//! The core never fetches a DID document; these rules only decide whether an
//! identifier is well formed and which DID a trusted root names.

use crate::error::{CoreError, Result};

/// A did:web identifier split into its host, optional port and path segments.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DidWeb {
    pub host: String,
    pub port: Option<u16>,
    pub segments: Vec<String>,
}

fn bad(msg: &str) -> CoreError {
    CoreError::InvalidDid(msg.to_string())
}

/// One LDH label: 1 to 63 ASCII letters, digits or hyphens, with no leading or
/// trailing hyphen (punycode "xn--" labels are LDH).
fn is_ldh_label(label: &str) -> bool {
    let b = label.as_bytes();
    !b.is_empty()
        && b.len() <= 63
        && b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
        && b[0] != b'-'
        && b[b.len() - 1] != b'-'
}

/// A number the way C's `strtoul(.., 0)` reads one inside `inet_aton`: "0x"
/// hex, a leading "0" octal, else decimal. None when it is not a number.
fn c_number(part: &str) -> Option<u64> {
    let (digits, radix) =
        if let Some(h) = part.strip_prefix("0x").or_else(|| part.strip_prefix("0X")) {
            (h, 16)
        } else if part.len() > 1 && part.starts_with('0') {
            (&part[1..], 8)
        } else {
            (part, 10)
        };
    if digits.is_empty() {
        // "0x" alone is not a number; "0" is handled as decimal above.
        return None;
    }
    u64::from_str_radix(digits, radix).ok()
}

/// True when `host` is an IPv4 address in any form `inet_aton` accepts
/// ("127.0.0.1", "127.1", "0x7f000001", "017700000001", ...).
fn is_inet_aton_address(host: &str) -> bool {
    let parts: Vec<&str> = host.split('.').collect();
    if parts.is_empty() || parts.len() > 4 {
        return false;
    }
    let mut values = Vec::with_capacity(parts.len());
    for p in &parts {
        match c_number(p) {
            Some(v) => values.push(v),
            None => return false,
        }
    }
    let (last, head) = values.split_last().expect("non-empty");
    if head.iter().any(|v| *v > 255) {
        return false;
    }
    let bits = 8 * (5 - parts.len() as u32);
    *last < (1u64 << bits)
}

fn hex_val(c: u8) -> Option<u8> {
    (c as char).to_digit(16).map(|d| d as u8)
}

/// Split a did:web identifier into host, port and path segments, strictly:
///
/// - the host is one or more LDH labels, at most 253 characters, with no empty
///   label (so no trailing dot) and no non-ASCII character;
/// - the host is not an IP address in any form;
/// - the only percent-encoding allowed in the host part is "%3A" before a port,
///   and the port is 1 to 65535 with no leading zero;
/// - every path segment is non-empty, is not "." or "..", and holds no "/",
///   "?", "#", "\\", "%", control character or space, raw or percent-encoded.
pub fn parse_did_web(did: &str) -> Result<DidWeb> {
    let rest = did
        .strip_prefix("did:web:")
        .ok_or_else(|| bad("not a did:web identifier"))?;
    let mut parts = rest.split(':');
    let mut host_part = parts.next().unwrap_or("");
    let segments: Vec<&str> = parts.collect();

    let mut port = None;
    if host_part.contains('%') {
        let lower = host_part.to_ascii_lowercase();
        let idx = lower
            .find("%3a")
            .ok_or_else(|| bad("a did:web host may only percent-encode the colon before a port"))?;
        let (h, p) = (&host_part[..idx], &host_part[idx + 3..]);
        if h.contains('%') || p.contains('%') {
            return Err(bad(
                "a did:web host may only percent-encode the colon before a port",
            ));
        }
        let pb = p.as_bytes();
        if pb.is_empty() || pb.len() > 5 || pb[0] == b'0' || !pb.iter().all(|c| c.is_ascii_digit())
        {
            return Err(bad("a did:web port must be 1 to 65535"));
        }
        let n: u32 = p
            .parse()
            .map_err(|_| bad("a did:web port must be 1 to 65535"))?;
        if n > 65535 {
            return Err(bad("a did:web port must be 1 to 65535"));
        }
        port = Some(n as u16);
        host_part = h;
    }
    let host = host_part;
    if host.is_empty() || host.len() > 253 {
        return Err(bad("a did:web host must be 1 to 253 characters"));
    }
    let labels: Vec<&str> = host.split('.').collect();
    if !labels.iter().all(|l| is_ldh_label(l)) {
        return Err(bad(
            "a did:web host must be letters, digits, hyphens and dots",
        ));
    }
    if labels
        .last()
        .is_some_and(|l| l.bytes().all(|c| c.is_ascii_digit()))
        || is_inet_aton_address(host)
    {
        return Err(bad(
            "a did:web host must be a domain name, not an IP address",
        ));
    }

    let mut out = Vec::with_capacity(segments.len());
    for segment in segments {
        let sb = segment.as_bytes();
        let allowed = |c: u8| c.is_ascii_alphanumeric() || b"._~!$&'()*+,;=@%-".contains(&c);
        if sb.is_empty() || !sb.iter().all(|c| allowed(*c)) {
            return Err(bad(
                "a did:web path segment is empty or holds a forbidden character",
            ));
        }
        // Decode %XX escapes; a '%' that does not start one is refused.
        let mut decoded: Vec<u32> = Vec::with_capacity(sb.len());
        let mut i = 0;
        while i < sb.len() {
            if sb[i] == b'%' {
                match (
                    sb.get(i + 1).and_then(|c| hex_val(*c)),
                    sb.get(i + 2).and_then(|c| hex_val(*c)),
                ) {
                    (Some(a), Some(b)) => {
                        decoded.push(u32::from(a * 16 + b));
                        i += 3;
                    }
                    _ => return Err(bad("a did:web path segment holds a broken percent-escape")),
                }
            } else {
                decoded.push(u32::from(sb[i]));
                i += 1;
            }
        }
        let forbidden = |c: u32| c <= 0x20 || c == 0x7f || "/\\?#%".contains(char::from(c as u8));
        let is_dots = decoded == [u32::from(b'.')] || decoded == [u32::from(b'.'), u32::from(b'.')];
        if is_dots || decoded.iter().any(|c| *c < 0x80 && forbidden(*c)) {
            return Err(bad("a did:web path segment holds a forbidden character"));
        }
        out.push(segment.to_string());
    }
    Ok(DidWeb {
        host: host.to_string(),
        port,
        segments: out,
    })
}

/// The DID a trusted root names, exactly as the Python reference reads it:
/// a full DID is kept as it is (a did:web must parse); a bare domain
/// ("yourcompany.com", or "yourcompany.com:8443" with a port) becomes its
/// did:web identifier ("did:web:yourcompany.com%3A8443"). Anything else, such
/// as an IP literal, a non-punycode international name, a trailing dot, a bad
/// port, a URL or a path, is refused.
pub fn normalize_root(value: &str) -> Result<String> {
    if value.is_empty() || value.trim() != value {
        return Err(bad("a trusted root is a DID or a domain name"));
    }
    if value.starts_with("did:") {
        let mut parts = value.splitn(3, ':');
        let (_, method, id) = (parts.next(), parts.next(), parts.next());
        if method.is_none_or(|m| m.is_empty())
            || id.is_none_or(|i| i.is_empty())
            || value.chars().any(char::is_whitespace)
        {
            return Err(bad("not a DID"));
        }
        if value.starts_with("did:web:") {
            parse_did_web(value)?;
        }
        return Ok(value.to_string());
    }
    let did = format!("did:web:{}", value.replace(':', "%3A"));
    parse_did_web(&did)
        .map_err(|_| bad("not a DID or a domain name (for example yourcompany.com)"))?;
    Ok(did)
}

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

    #[test]
    fn shorthand_matches_the_reference_rules() {
        for (root, want) in [
            ("example.com", Some("did:web:example.com")),
            ("Example.com", Some("did:web:Example.com")),
            ("example.com:8443", Some("did:web:example.com%3A8443")),
            (
                "xn--bcher-kva.example",
                Some("did:web:xn--bcher-kva.example"),
            ),
            (
                "did:web:example.com:users",
                Some("did:web:example.com:users"),
            ),
            ("did:example:123", Some("did:example:123")),
            ("example.com.", None),
            ("bücher.example", None),
            ("127.0.0.1", None),
            ("localhost", Some("did:web:localhost")),
            ("[::1]", None),
            ("example.com/users", None),
            ("https://example.com", None),
            ("example.com:0", None),
            ("example.com:65536", None),
            ("example.com:08443", None),
            ("example.com:users", None),
            ("example.com:8443:users", None),
            ("-example.com", None),
            (" example.com", None),
            ("", None),
            ("did:web:", None),
            ("did::x", None),
            ("did:web:example.com:..", None),
            ("did:web:example.com:%2e%2e", None),
            ("did:web:example.com:us%20ers", None),
            ("0x7f000001", None),
            ("did:web:例え.jp", None),
        ] {
            assert_eq!(normalize_root(root).ok().as_deref(), want, "{root:?}");
        }
    }
}