use crate::error::{CoreError, Result};
#[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())
}
pub(crate) 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'-'
}
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() {
return None;
}
u64::from_str_radix(digits, radix).ok()
}
pub(crate) 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)
}
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",
));
}
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,
})
}
pub fn py_space(c: char) -> bool {
c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
}
pub fn normalize_root(value: &str) -> Result<String> {
if value.is_empty() || value.trim_matches(py_space) != 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(py_space)
{
return Err(bad("not a DID"));
}
if value.starts_with("did:web:") {
parse_did_web(value)?;
}
if value.starts_with(crate::did_webvh::PREFIX) {
crate::did_webvh::parse(value).map_err(|e| bad(e.text))?;
}
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),
(
"did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:example.com",
Some("did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:example.com"),
),
("did:webvh:{SCID}:example.com", None),
(
"did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:127.0.0.1",
None,
),
(
"did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:example.com#key-1",
None,
),
] {
assert_eq!(normalize_root(root).ok().as_deref(), want, "{root:?}");
}
}
}