use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct DidPlc(String);
impl<'de> serde::Deserialize<'de> for DidPlc {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
DidPlc::from_str_validated(&s).ok_or_else(|| {
serde::de::Error::custom(format!(
"invalid DID:PLC format: expected 'did:plc:<24-char-base32-suffix>', got '{}'",
if s.len() > 60 { &s[..60] } else { &s }
))
})
}
}
impl DidPlc {
pub const PREFIX: &'static str = "did:plc:";
pub const SUFFIX_LEN: usize = 24;
pub fn from_str_validated(s: &str) -> Option<Self> {
let suffix = s.strip_prefix(Self::PREFIX)?;
if suffix.len() != Self::SUFFIX_LEN {
return None;
}
if !suffix
.chars()
.all(|c| c.is_ascii_lowercase() || ('2'..='7').contains(&c))
{
return None;
}
Some(Self(s.to_string()))
}
pub fn from_parts(suffix: String) -> Option<Self> {
if suffix.len() != Self::SUFFIX_LEN {
return None;
}
if !suffix
.chars()
.all(|c| c.is_ascii_lowercase() || ('2'..='7').contains(&c))
{
return None;
}
Some(Self(format!("{}{}", Self::PREFIX, suffix)))
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn identifier(&self) -> &str {
&self.0[Self::PREFIX.len()..]
}
}
impl fmt::Display for DidPlc {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct DidPlcService {
pub id: String,
pub service_type: String,
pub endpoint: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct DidPlcGenesisOperation {
#[serde(rename = "type")]
pub op_type: String,
#[serde(default)]
pub rotation_keys: Vec<String>,
#[serde(default)]
pub verification_methods: Vec<String>,
#[serde(default)]
pub also_known_as: Vec<String>,
#[serde(default)]
pub services: Vec<DidPlcService>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sig: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prev: Option<String>,
}
impl DidPlcGenesisOperation {
pub const MAX_ENTRIES: usize = 100;
pub const MAX_ENTRY_LEN: usize = 4096;
pub fn validate(&self) -> Result<(), DidPlcError> {
if crate::core::has_dangerous_chars(&self.op_type) {
return Err(DidPlcError::InvalidFormat(
"op_type contains control or format characters".to_string(),
));
}
let fields: &[(&str, &[String])] = &[
("verification_methods", &self.verification_methods),
("also_known_as", &self.also_known_as),
("rotation_keys", &self.rotation_keys),
];
for &(name, vec) in fields {
if vec.len() > Self::MAX_ENTRIES {
return Err(DidPlcError::InvalidFormat(format!(
"{} count {} exceeds max {}",
name,
vec.len(),
Self::MAX_ENTRIES
)));
}
for (i, entry) in vec.iter().enumerate() {
if entry.len() > Self::MAX_ENTRY_LEN {
return Err(DidPlcError::InvalidFormat(format!(
"{}[{}] length {} exceeds max {}",
name,
i,
entry.len(),
Self::MAX_ENTRY_LEN
)));
}
if crate::core::has_dangerous_chars(entry) {
return Err(DidPlcError::InvalidFormat(format!(
"{name}[{i}] contains control or format characters",
)));
}
}
}
if self.services.len() > Self::MAX_ENTRIES {
return Err(DidPlcError::InvalidFormat(format!(
"services count {} exceeds max {}",
self.services.len(),
Self::MAX_ENTRIES
)));
}
for (i, svc) in self.services.iter().enumerate() {
if svc.id.len() > Self::MAX_ENTRY_LEN {
return Err(DidPlcError::InvalidFormat(format!(
"services[{}].id length {} exceeds max {}",
i,
svc.id.len(),
Self::MAX_ENTRY_LEN
)));
}
if crate::core::has_dangerous_chars(&svc.id) {
return Err(DidPlcError::InvalidFormat(format!(
"services[{i}].id contains control or format characters",
)));
}
if svc.service_type.len() > Self::MAX_ENTRY_LEN {
return Err(DidPlcError::InvalidFormat(format!(
"services[{}].service_type length {} exceeds max {}",
i,
svc.service_type.len(),
Self::MAX_ENTRY_LEN
)));
}
if crate::core::has_dangerous_chars(&svc.service_type) {
return Err(DidPlcError::InvalidFormat(format!(
"services[{i}].service_type contains control or format characters",
)));
}
if svc.endpoint.len() > Self::MAX_ENTRY_LEN {
return Err(DidPlcError::InvalidFormat(format!(
"services[{}].endpoint length {} exceeds max {}",
i,
svc.endpoint.len(),
Self::MAX_ENTRY_LEN
)));
}
if crate::core::has_dangerous_chars(&svc.endpoint) {
return Err(DidPlcError::InvalidFormat(format!(
"services[{i}].endpoint contains control or format characters",
)));
}
}
if let Some(ref sig) = self.sig {
if sig.len() > Self::MAX_ENTRY_LEN {
return Err(DidPlcError::InvalidFormat(format!(
"sig length {} exceeds max {}",
sig.len(),
Self::MAX_ENTRY_LEN,
)));
}
if crate::core::has_dangerous_chars(sig) {
return Err(DidPlcError::InvalidFormat(
"sig contains control or format characters".to_string(),
));
}
}
if let Some(ref prev) = self.prev {
if prev.len() > Self::MAX_ENTRY_LEN {
return Err(DidPlcError::InvalidFormat(format!(
"prev length {} exceeds max {}",
prev.len(),
Self::MAX_ENTRY_LEN,
)));
}
if crate::core::has_dangerous_chars(prev) {
return Err(DidPlcError::InvalidFormat(
"prev contains control or format characters".to_string(),
));
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DidPlcError {
InvalidFormat(String),
MissingField(String),
SigningError(String),
VerificationFailed(String),
ResolutionError(String),
}
impl fmt::Display for DidPlcError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DidPlcError::InvalidFormat(msg) => write!(f, "Invalid DID:PLC format: {msg}"),
DidPlcError::MissingField(field) => {
write!(f, "Missing required field in genesis operation: {field}")
}
DidPlcError::SigningError(msg) => write!(f, "DID:PLC signing error: {msg}"),
DidPlcError::VerificationFailed(msg) => {
write!(f, "DID:PLC verification failed: {msg}")
}
DidPlcError::ResolutionError(msg) => write!(f, "DID:PLC resolution error: {msg}"),
}
}
}
impl std::error::Error for DidPlcError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_did_plc_valid() {
let did = DidPlc::from_str_validated("did:plc:ewvi7nxsareczkwkx5pz6q6e");
assert!(did.is_some());
let did = did.expect("valid DID");
assert_eq!(did.as_str(), "did:plc:ewvi7nxsareczkwkx5pz6q6e");
assert_eq!(did.identifier(), "ewvi7nxsareczkwkx5pz6q6e");
}
#[test]
fn test_did_plc_invalid_prefix() {
assert!(DidPlc::from_str_validated("did:web:example.com").is_none());
assert!(DidPlc::from_str_validated("ewvi7nxsareczkwkx5pz6q6e").is_none());
}
#[test]
fn test_did_plc_invalid_suffix_length() {
assert!(DidPlc::from_str_validated("did:plc:tooshort").is_none());
assert!(DidPlc::from_str_validated("did:plc:waytoolongstringherexyz12345").is_none());
}
#[test]
fn test_did_plc_invalid_characters() {
assert!(DidPlc::from_str_validated("did:plc:890100000000000000000000").is_none());
assert!(DidPlc::from_str_validated("did:plc:EWVI7NXSARECZKWKX5PZ6Q6E").is_none());
}
#[test]
fn test_did_plc_from_parts() {
let did = DidPlc::from_parts("abcdefghijklmnopqrstuvwx".to_string());
assert!(did.is_some());
let did = did.unwrap();
assert_eq!(did.as_str(), "did:plc:abcdefghijklmnopqrstuvwx");
assert_eq!(did.identifier(), "abcdefghijklmnopqrstuvwx");
}
#[test]
fn test_did_plc_from_parts_invalid_rejected() {
assert!(DidPlc::from_parts("INVALID".to_string()).is_none());
assert!(DidPlc::from_parts("".to_string()).is_none());
assert!(DidPlc::from_parts("890100000000000000000000".to_string()).is_none());
}
#[test]
fn test_did_plc_display() {
let did = DidPlc::from_parts("ewvi7nxsareczkwkx5pz6q6e".to_string()).unwrap();
assert_eq!(format!("{did}"), "did:plc:ewvi7nxsareczkwkx5pz6q6e");
}
#[test]
fn test_did_plc_serde_roundtrip() {
let did = DidPlc::from_parts("ewvi7nxsareczkwkx5pz6q6e".to_string()).unwrap();
let json = serde_json::to_string(&did).expect("serialize");
let deserialized: DidPlc = serde_json::from_str(&json).expect("deserialize");
assert_eq!(did, deserialized);
}
#[test]
fn test_did_plc_serde_rejects_invalid() {
let result: Result<DidPlc, _> = serde_json::from_str("\"arbitrary-string\"");
assert!(
result.is_err(),
"Invalid DID:PLC must be rejected on deserialization"
);
}
#[test]
fn test_did_plc_genesis_operation_serde() {
let genesis = DidPlcGenesisOperation {
op_type: "plc_operation".to_string(),
rotation_keys: vec!["did:key:z123".to_string()],
verification_methods: vec!["did:key:z456".to_string()],
also_known_as: vec![],
services: vec![DidPlcService {
id: "atproto_pds".to_string(),
service_type: "AtprotoPersonalDataServer".to_string(),
endpoint: "https://pds.example.com".to_string(),
}],
sig: None,
prev: None,
};
let json = serde_json::to_string(&genesis).expect("serialize");
let deserialized: DidPlcGenesisOperation =
serde_json::from_str(&json).expect("deserialize");
assert_eq!(genesis, deserialized);
assert!(!json.contains("\"sig\""));
assert!(!json.contains("\"prev\""));
}
}