use std::future::Future; use parking_lot::Mutex; use chrono::format::SecondsFormat; use chrono::{DateTime, Duration, Utc}; use worker::*; pub const CLAIM_COOLDOWN_DAYS: i64 = 30; pub fn utc_now_rfc3339() -> String { Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true) } pub const HANDLE_TLDS: &[&str] = &["tngl.sh"]; const DEFAULT_RESERVED_LABELS: &[&str] = &["sites"]; // the service's own label is always reserved, whatever the config lists pub fn reserved_labels(audience: &str, configured: Option<&str>) -> Vec { let service_label = audience .strip_prefix("did:web:") .and_then(|host| host.split('.').next()) .map(str::to_ascii_lowercase); let configured: Vec = match configured { Some(raw) => raw .split(',') .map(|label| label.trim().to_ascii_lowercase()) .filter(|label| !label.is_empty()) .collect(), None => DEFAULT_RESERVED_LABELS .iter() .map(|label| label.to_string()) .collect(), }; let mut labels: Vec = service_label.into_iter().chain(configured).collect(); labels.sort(); labels.dedup(); labels } fn is_reserved(domain: &str, reserved_labels: &[&str]) -> bool { domain .split('.') .next() .is_some_and(|label| reserved_labels.contains(&label)) } pub fn is_handle_domain(domain: &str) -> bool { validate_domain(domain, HANDLE_TLDS) } pub fn validate_domain(domain: &str, allowed_tlds: &[&str]) -> bool { for tld in allowed_tlds { let Some(label) = domain.strip_suffix(tld) else { continue; }; let Some(label) = label.strip_suffix('.') else { continue; }; if label.is_empty() || label.len() > 63 || label.contains('.') { continue; } let bytes = label.as_bytes(); if bytes[0] == b'-' || bytes[bytes.len() - 1] == b'-' { continue; } if bytes .iter() .all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') { return true; } } false } #[derive(Clone, Debug, PartialEq)] pub struct ClaimRow { pub did: String, pub domain: String, pub deleted: Option, } #[derive(Debug, PartialEq, Clone)] pub enum ClaimError { DomainTaken, DomainCooldown, AlreadyClaimed, InvalidSubdomain, DomainPermanent, HandleNotOwned, HandleUnknown, Store(String), } impl std::fmt::Display for ClaimError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self) } } #[derive(Default)] struct MemState { claims: Vec, } #[derive(Clone)] struct MemClaim { did: String, domain: String, deleted: Option, } enum StoreInner { D1(D1Database), Mem(Mutex), } pub struct SitesStore { inner: StoreInner, } impl SitesStore { pub fn d1(db: D1Database) -> Self { Self { inner: StoreInner::D1(db), } } pub fn mem() -> Self { Self { inner: StoreInner::Mem(Mutex::new(MemState::default())), } } pub fn d1_db(&self) -> Result<&D1Database, String> { match &self.inner { StoreInner::D1(db) => Ok(db), StoreInner::Mem(_) => Err("in-memory store has no D1 database".into()), } } pub async fn select_claim_by_domain(&self, domain: &str) -> Result, String> { match &self.inner { StoreInner::D1(db) => { #[derive(serde::Deserialize)] struct Row { did: String, domain: String, deleted: Option, } let stmt = db .prepare("SELECT did, domain, deleted FROM domain_claims WHERE domain = ?") .bind_refs(&[D1Type::Text(domain)]) .map_err(|e| e.to_string())?; Ok(stmt .first::(None) .await .map_err(|e| e.to_string())? .map(|r| ClaimRow { did: r.did, domain: r.domain, deleted: r.deleted, })) } StoreInner::Mem(mem) => { Ok(mem .lock() .claims .iter() .find(|c| c.domain == domain) .map(|c| ClaimRow { did: c.did.clone(), domain: c.domain.clone(), deleted: c.deleted.clone(), })) } } } pub async fn select_claim_by_did(&self, did: &str) -> Result, String> { match &self.inner { StoreInner::D1(db) => { #[derive(serde::Deserialize)] struct Row { did: String, domain: String, deleted: Option, } let stmt = db .prepare("SELECT did, domain, deleted FROM domain_claims WHERE did = ?") .bind_refs(&[D1Type::Text(did)]) .map_err(|e| e.to_string())?; Ok(stmt .first::(None) .await .map_err(|e| e.to_string())? .map(|r| ClaimRow { did: r.did, domain: r.domain, deleted: r.deleted, })) } StoreInner::Mem(mem) => { Ok(mem .lock() .claims .iter() .find(|c| c.did == did) .map(|c| ClaimRow { did: c.did.clone(), domain: c.domain.clone(), deleted: c.deleted.clone(), })) } } } pub async fn insert_claim(&self, did: &str, domain: &str) -> Result<(), String> { match &self.inner { StoreInner::D1(db) => { db.prepare("INSERT INTO domain_claims (did, domain) VALUES (?, ?)") .bind_refs(&[D1Type::Text(did), D1Type::Text(domain)]) .map_err(|e| e.to_string())? .run() .await .map_err(|e| e.to_string())?; Ok(()) } StoreInner::Mem(mem) => { let mut mem = mem.lock(); if mem .claims .iter() .any(|c| c.did == did || c.domain == domain) { return Err("UNIQUE constraint failed: domain_claims (did, domain)".to_string()); } mem.claims.push(MemClaim { did: did.into(), domain: domain.into(), deleted: None, }); Ok(()) } } } pub async fn undelete_claim(&self, did: &str, domain: &str) -> Result<(), String> { match &self.inner { StoreInner::D1(db) => { db.prepare("UPDATE domain_claims SET deleted = NULL WHERE did = ? AND domain = ?") .bind_refs(&[D1Type::Text(did), D1Type::Text(domain)]) .map_err(|e| e.to_string())? .run() .await .map_err(|e| e.to_string())?; Ok(()) } StoreInner::Mem(mem) => { let mut mem = mem.lock(); if let Some(c) = mem .claims .iter_mut() .find(|c| c.did == did && c.domain == domain) { c.deleted = None; } Ok(()) } } } pub async fn delete_claim_if_owned_by(&self, domain: &str, did: &str) -> Result { match &self.inner { StoreInner::D1(db) => { let result = db .prepare("DELETE FROM domain_claims WHERE domain = ? AND did = ?") .bind_refs(&[D1Type::Text(domain), D1Type::Text(did)]) .map_err(|e| e.to_string())? .run() .await .map_err(|e| e.to_string())?; Ok(result .meta() .map_err(|e| e.to_string())? .and_then(|m| m.changes) .unwrap_or(0) as u64) } StoreInner::Mem(mem) => { let mut mem = mem.lock(); let before = mem.claims.len(); mem.claims.retain(|c| !(c.domain == domain && c.did == did)); Ok((before - mem.claims.len()) as u64) } } } pub async fn switch_claim(&self, did: &str, from: &str, domain: &str) -> Result { match &self.inner { StoreInner::D1(db) => { let result = db .prepare("UPDATE domain_claims SET domain = ?, deleted = NULL WHERE did = ? AND domain = ?") .bind_refs(&[D1Type::Text(domain), D1Type::Text(did), D1Type::Text(from)]) .map_err(|e| e.to_string())? .run() .await .map_err(|e| e.to_string())?; Ok(result .meta() .map_err(|e| e.to_string())? .and_then(|m| m.changes) .unwrap_or(0) as u64) } StoreInner::Mem(mem) => { let mut mem = mem.lock(); match mem .claims .iter_mut() .find(|c| c.did == did && c.domain == from) { Some(row) => { row.domain = domain.into(); row.deleted = None; Ok(1) } None => Ok(0), } } } } pub async fn mark_domain_released( &self, did: &str, domain: &str, deleted: &str, ) -> Result { match &self.inner { StoreInner::D1(db) => { let result = db .prepare( "UPDATE domain_claims SET deleted = ? \ WHERE did = ? AND domain = ? AND deleted IS NULL", ) .bind_refs(&[ D1Type::Text(deleted), D1Type::Text(did), D1Type::Text(domain), ]) .map_err(|e| e.to_string())? .run() .await .map_err(|e| e.to_string())?; Ok(result .meta() .map_err(|e| e.to_string())? .and_then(|m| m.changes) .unwrap_or(0) as u64) } StoreInner::Mem(mem) => { let mut mem = mem.lock(); let Some(c) = mem .claims .iter_mut() .find(|c| c.did == did && c.domain == domain && c.deleted.is_none()) else { return Ok(0); }; c.deleted = Some(deleted.into()); Ok(1) } } } pub async fn active_domain_for_did(&self, did: &str) -> Result, String> { match &self.inner { StoreInner::D1(db) => { let stmt = db .prepare("SELECT domain FROM domain_claims WHERE did = ? AND deleted IS NULL") .bind_refs(&[D1Type::Text(did)]) .map_err(|e| e.to_string())?; Ok(stmt .first::(Some("domain")) .await .map_err(|e| e.to_string())?) } StoreInner::Mem(mem) => Ok(mem .lock() .claims .iter() .find(|c| c.did == did && c.deleted.is_none()) .map(|c| c.domain.clone())), } } } fn parse_deleted(deleted: &str) -> Result, ClaimError> { DateTime::parse_from_rfc3339(deleted) .map(|dt| dt.with_timezone(&Utc)) .map_err(|_| ClaimError::Store(format!("unparseable deleted timestamp {:?}", deleted))) } #[derive(Clone, Copy, Debug, PartialEq)] enum Rights { Open, Vouched, VouchedReplacingStale, OpenReplacingStale, } impl Rights { // only handle claims the zone vouched for may clear another account's row fn vouched(self) -> bool { matches!(self, Rights::Vouched | Rights::VouchedReplacingStale) } fn replaces_stale(self) -> bool { matches!( self, Rights::VouchedReplacingStale | Rights::OpenReplacingStale ) } } async fn handle_still_held(did: &str, handle: &str, vouch: &F) -> Result where F: Fn(String) -> Fut, Fut: Future, String>>, { let vouched = vouch(handle.to_string()).await.map_err(ClaimError::Store)?; Ok(title_of(did, vouched.as_deref()).holds()) } pub async fn claim_vouched( store: &SitesStore, now: DateTime, did: &str, domain: &str, allowed_tlds: &[&str], reserved_labels: &[&str], vouch: F, ) -> Result<(), ClaimError> where F: Fn(String) -> Fut, Fut: Future, String>>, { if !validate_domain(domain, allowed_tlds) || is_reserved(domain, reserved_labels) { return Err(ClaimError::InvalidSubdomain); } if !is_handle_domain(domain) { let rights = match store .select_claim_by_did(did) .await .map_err(ClaimError::Store)? { Some(row) if row.deleted.is_none() && is_handle_domain(&row.domain) => { if handle_still_held(did, &row.domain, &vouch).await? { Rights::Open } else { Rights::OpenReplacingStale } } _ => Rights::Open, }; return claim(store, now, did, domain, allowed_tlds, rights).await; } titled( did, vouch(domain.to_string()).await.map_err(ClaimError::Store)?, )?; // a renamed account's leftover handle shouldn't block claiming their new one let rights = match store .select_claim_by_did(did) .await .map_err(ClaimError::Store)? { Some(row) if row.deleted.is_none() && row.domain != domain => { if is_handle_domain(&row.domain) && handle_still_held(did, &row.domain, &vouch).await? { Rights::Vouched } else { Rights::VouchedReplacingStale } } _ => Rights::Vouched, }; claim(store, now, did, domain, allowed_tlds, rights).await } pub async fn resolve_handle(domain: String) -> Result, String> { if !is_handle_domain(&domain) { return Err(format!("{} is not a handle domain", domain)); } // the zone's origin knows every pds issuing handles under it; asked from // another zone this goes through the worker, which passes it on there let url = format!("https://{}/.well-known/atproto-did", domain); let mut resp = Fetch::Url(url.parse().map_err(|e| format!("bad handle url: {}", e))?) .send() .await .map_err(|e| format!("handle {} unreachable: {}", domain, e))?; let status = resp.status_code(); if !(200..300).contains(&status) { if !zone_denies_handle(status) { return Err(format!("handle {} answered HTTP {}", domain, status)); } return resolve_handle_by_dns(&domain).await; } let body = resp .text() .await .map_err(|e| format!("handle {} answered an unreadable body: {}", domain, e))?; let did = body.trim(); if !did.starts_with("did:") { return Err(format!( "handle {} answered something that isn't a did", domain )); } Ok(Some(did.to_string())) } async fn resolve_handle_by_dns(domain: &str) -> Result, String> { let url = format!( "https://cloudflare-dns.com/dns-query?name=_atproto.{}&type=TXT", domain ); let mut req = RequestInit::new(); req.with_headers(Headers::from_iter([("Accept", "application/dns-json")])); let request = Request::new_with_init(&url, &req).map_err(|e| format!("bad dns url: {}", e))?; let mut resp = Fetch::Request(request) .send() .await .map_err(|e| format!("dns for {} unreachable: {}", domain, e))?; let status = resp.status_code(); if status != 200 { return Err(format!("dns for {} answered HTTP {}", domain, status)); } let body = resp .text() .await .map_err(|e| format!("dns for {} answered an unreadable body: {}", domain, e))?; did_from_dns_json(&body).map_err(|e| format!("dns for {}: {}", domain, e)) } // the did of a lone `did=` txt value, none when absent or ambiguous fn did_from_dns_json(json: &str) -> Result, String> { #[derive(serde::Deserialize)] struct Reply { #[serde(rename = "Status")] status: u32, #[serde(rename = "Answer", default)] answer: Vec, } #[derive(serde::Deserialize)] struct Record { r#type: u16, data: String, } let reply: Reply = serde_json::from_str(json).map_err(|e| format!("bad dns json: {}", e))?; match reply.status { 0 => {} 3 => return Ok(None), status => return Err(format!("dns status {}", status)), } let mut dids = reply .answer .iter() .filter(|record| record.r#type == 16) .filter_map(|record| { // long txt values arrive as several quoted chunks let value: String = match record.data.starts_with('"') { true => record.data.split('"').skip(1).step_by(2).collect(), false => record.data.clone(), }; value .strip_prefix("did=") .filter(|did| did.starts_with("did:")) .map(str::to_string) }); match (dids.next(), dids.next()) { (Some(did), None) => Ok(Some(did)), _ => Ok(None), } } pub fn self_claimed_handle( did: &str, declared: Option<&str>, resolved: Option<&str>, ) -> Option { let declared = declared?; (is_handle_domain(declared) && resolved == Some(did)).then(|| declared.to_string()) } fn titled(did: &str, vouched: Option) -> Result<(), ClaimError> { match title_of(did, vouched.as_deref()) { Title::Held => Ok(()), Title::Squatted => Err(ClaimError::HandleNotOwned), Title::Unknown | Title::Unverifiable => Err(ClaimError::HandleUnknown), } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum Title { Held, Squatted, Unknown, Unverifiable, } fn zone_denies_handle(status: u16) -> bool { status == 400 || status == 404 } impl Title { pub fn holds(self) -> bool { matches!(self, Title::Held) } } pub fn title_of(did: &str, resolved: Option<&str>) -> Title { match resolved { Some(owner) if owner == did => Title::Held, Some(_) => Title::Squatted, None => Title::Unknown, } } pub async fn handle_title(domain: &str, did: &str) -> Title { match resolve_handle(domain.to_string()).await { Ok(resolved) => title_of(did, resolved.as_deref()), Err(_) => Title::Unverifiable, } } async fn claim( store: &SitesStore, now: DateTime, did: &str, domain: &str, allowed_tlds: &[&str], rights: Rights, ) -> Result<(), ClaimError> { if !validate_domain(domain, allowed_tlds) { return Err(ClaimError::InvalidSubdomain); } for _ in 0..2 { match claim_once(store, now, did, domain, rights).await { Err(ClaimError::Store(_)) => continue, other => return other, } } if let Some(row) = store .select_claim_by_domain(domain) .await .map_err(ClaimError::Store)? { if row.did == did && row.deleted.is_none() { return Ok(()); } if row.deleted.is_none() { return Err(ClaimError::DomainTaken); } } Err(ClaimError::Store( "claim could not be settled: concurrent changes".to_string(), )) } async fn claim_once( store: &SitesStore, now: DateTime, did: &str, domain: &str, rights: Rights, ) -> Result<(), ClaimError> { let cooldown = Duration::days(CLAIM_COOLDOWN_DAYS); if let Some(domain_row) = store .select_claim_by_domain(domain) .await .map_err(ClaimError::Store)? { if domain_row.did == did { match &domain_row.deleted { None => return Ok(()), Some(deleted) => { if now.signed_duration_since(parse_deleted(deleted)?) < cooldown { return Err(ClaimError::DomainCooldown); } store .undelete_claim(did, domain) .await .map_err(ClaimError::Store)?; return Ok(()); } } } match &domain_row.deleted { // clear squatted handle rows if the zone vouches for the caller None if !rights.vouched() => return Err(ClaimError::DomainTaken), None => { if store .delete_claim_if_owned_by(domain, &domain_row.did) .await .map_err(ClaimError::Store)? == 0 { return Err(ClaimError::Store(format!( "the claim on {} changed while it was being taken over", domain ))); } } Some(deleted) => { if now.signed_duration_since(parse_deleted(deleted)?) < cooldown { return Err(ClaimError::DomainCooldown); } if store .delete_claim_if_owned_by(domain, &domain_row.did) .await .map_err(ClaimError::Store)? == 0 { return Err(ClaimError::Store(format!( "the released claim on {} changed while it was being cleared", domain ))); } } } } if let Some(did_row) = store .select_claim_by_did(did) .await .map_err(ClaimError::Store)? { // switching overwrites the tombstone, so cooldown has to finish first let Some(released) = did_row.deleted.as_deref() else { if rights.replaces_stale() { if store .switch_claim(did, &did_row.domain, domain) .await .map_err(ClaimError::Store)? == 0 { return Err(ClaimError::Store(format!( "the row for {} changed while it was being replaced", did ))); } return Ok(()); } return Err(ClaimError::AlreadyClaimed); }; if now.signed_duration_since(parse_deleted(released)?) < cooldown { return Err(ClaimError::DomainCooldown); } if store .switch_claim(did, &did_row.domain, domain) .await .map_err(ClaimError::Store)? == 0 { return Err(ClaimError::Store(format!( "the row for {} changed while it was switching domains", did ))); } } else { store .insert_claim(did, domain) .await .map_err(ClaimError::Store)?; } Ok(()) } pub async fn release( store: &SitesStore, now: DateTime, did: &str, domain: &str, ) -> Result { if is_handle_domain(domain) { return Err(ClaimError::DomainPermanent); } let deleted = now.to_rfc3339_opts(SecondsFormat::Secs, true); let changes = store .mark_domain_released(did, domain, &deleted) .await .map_err(ClaimError::Store)?; Ok(changes > 0) } #[cfg(test)] mod tests { use super::*; use chrono::TimeZone; const TLDS: &[&str] = &["tngl.io", "tngl.sh"]; async fn claim_site_name( store: &SitesStore, now: DateTime, did: &str, domain: &str, tlds: &[&str], ) -> Result<(), ClaimError> { claim(store, now, did, domain, tlds, Rights::Open).await } fn t(y: i32, mo: u32, d: u32) -> DateTime { Utc.with_ymd_and_hms(y, mo, d, 0, 0, 0).unwrap() } #[tokio::test] async fn claim_then_get_returns_the_domain() { let store = SitesStore::mem(); claim_site_name(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io", TLDS) .await .unwrap(); let row = store .select_claim_by_did("did:alice") .await .unwrap() .unwrap(); assert_eq!(row.domain, "alice.tngl.io"); assert_eq!(row.deleted, None); assert_eq!( store .active_domain_for_did("did:alice") .await .unwrap() .as_deref(), Some("alice.tngl.io") ); } #[tokio::test] async fn same_did_same_domain_reclaim_is_an_idempotent_noop() { let store = SitesStore::mem(); claim_site_name(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io", TLDS) .await .unwrap(); claim_site_name(&store, t(2026, 1, 2), "did:alice", "alice.tngl.io", TLDS) .await .unwrap(); let row = store .select_claim_by_did("did:alice") .await .unwrap() .unwrap(); assert_eq!(row.domain, "alice.tngl.io"); assert_eq!(row.deleted, None); } #[tokio::test] async fn same_did_different_domain_is_already_claimed() { let store = SitesStore::mem(); claim_site_name(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io", TLDS) .await .unwrap(); let err = claim_site_name(&store, t(2026, 1, 2), "did:alice", "blog.tngl.io", TLDS) .await .unwrap_err(); assert_eq!(err, ClaimError::AlreadyClaimed); } #[tokio::test] async fn other_did_claiming_taken_domain_is_domain_taken() { let store = SitesStore::mem(); claim_site_name(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io", TLDS) .await .unwrap(); let err = claim_site_name(&store, t(2026, 1, 2), "did:bob", "alice.tngl.io", TLDS) .await .unwrap_err(); assert_eq!(err, ClaimError::DomainTaken); } #[tokio::test] async fn release_then_reclaim_within_30_days_is_cooldown() { let store = SitesStore::mem(); claim_site_name(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io", TLDS) .await .unwrap(); assert!( release(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io") .await .unwrap() ); let err = claim_site_name(&store, t(2026, 1, 11), "did:alice", "alice.tngl.io", TLDS) .await .unwrap_err(); assert_eq!(err, ClaimError::DomainCooldown); } #[tokio::test] async fn a_release_inside_the_cooldown_keeps_the_released_domain_reserved() { let store = SitesStore::mem(); claim_site_name(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io", TLDS) .await .unwrap(); assert!( release(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io") .await .unwrap() ); let err = claim_site_name(&store, t(2026, 1, 3), "did:alice", "blog.tngl.io", TLDS) .await .unwrap_err(); assert_eq!(err, ClaimError::DomainCooldown); let row = store .select_claim_by_did("did:alice") .await .unwrap() .unwrap(); assert_eq!(row.domain, "alice.tngl.io"); assert!(row.deleted.is_some()); let err = claim_site_name(&store, t(2026, 1, 3), "did:bob", "alice.tngl.io", TLDS) .await .unwrap_err(); assert_eq!(err, ClaimError::DomainCooldown); } #[tokio::test] async fn a_release_past_the_cooldown_lets_the_did_switch_and_frees_the_domain() { let store = SitesStore::mem(); claim_site_name(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io", TLDS) .await .unwrap(); assert!( release(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io") .await .unwrap() ); claim_site_name(&store, t(2026, 2, 1), "did:alice", "blog.tngl.io", TLDS) .await .unwrap(); let row = store .select_claim_by_did("did:alice") .await .unwrap() .unwrap(); assert_eq!(row.domain, "blog.tngl.io"); assert_eq!(row.deleted, None); claim_site_name(&store, t(2026, 2, 1), "did:bob", "alice.tngl.io", TLDS) .await .unwrap(); let row = store .select_claim_by_domain("alice.tngl.io") .await .unwrap() .unwrap(); assert_eq!(row.did, "did:bob"); } #[test] fn reserved_labels_are_the_service_label_plus_the_configured_ones() { let audience = "did:web:sites.next-sites.tngl.sh"; assert_eq!(reserved_labels(audience, None), ["sites"]); assert_eq!( reserved_labels(audience, Some(" Blog, ,www ")), ["blog", "sites", "www"] ); assert_eq!(reserved_labels(audience, Some("")), ["sites"]); assert_eq!( reserved_labels("did:web:api.example.com", None), ["api", "sites"] ); assert_eq!( reserved_labels("did:web:api.example.com", Some("blog")), ["api", "blog"] ); assert_eq!(reserved_labels("did:plc:sites", Some("blog")), ["blog"]); } #[tokio::test] async fn a_reserved_label_cannot_be_claimed() { let store = SitesStore::mem(); let labels = reserved_labels("did:web:sites.next-sites.tngl.io", Some("www")); let reserved: Vec<&str> = labels.iter().map(String::as_str).collect(); let tlds = &["tngl.io", "next-sites.tngl.io", "tngl.sh"]; for (did, domain) in [ ("did:alice", "sites.tngl.io"), ("did:bob", "sites.next-sites.tngl.io"), ("did:carol", "sites.tngl.sh"), ("did:dave", "www.tngl.io"), ] { let err = claim_vouched( &store, t(2026, 1, 1), did, domain, tlds, &reserved, |_domain| async move { Ok(Some(did.to_string())) }, ) .await .unwrap_err(); assert_eq!(err, ClaimError::InvalidSubdomain, "{}", domain); assert_eq!(store.select_claim_by_domain(domain).await.unwrap(), None); } claim_vouched( &store, t(2026, 1, 1), "did:erin", "blog.tngl.io", tlds, &reserved, |_domain| async { Ok(None) }, ) .await .unwrap(); assert!( store .select_claim_by_domain("blog.tngl.io") .await .unwrap() .is_some() ); } #[tokio::test] async fn a_handle_is_claimed_only_by_the_account_its_zone_resolves_it_to() { let store = SitesStore::mem(); let taken = claim_vouched( &store, t(2026, 1, 1), "did:attacker", "alice.tngl.sh", TLDS, DEFAULT_RESERVED_LABELS, |_domain| async { Ok(Some("did:alice".to_string())) }, ) .await .unwrap_err(); assert_eq!(taken, ClaimError::HandleNotOwned); assert_eq!( store.select_claim_by_domain("alice.tngl.sh").await.unwrap(), None ); let unknown = claim_vouched( &store, t(2026, 1, 1), "did:attacker", "nobody.tngl.sh", TLDS, DEFAULT_RESERVED_LABELS, |_domain| async { Ok(None) }, ) .await .unwrap_err(); assert_eq!(unknown, ClaimError::HandleUnknown); assert_eq!( store .select_claim_by_domain("nobody.tngl.sh") .await .unwrap(), None ); claim_vouched( &store, t(2026, 1, 1), "did:alice", "alice.tngl.sh", TLDS, DEFAULT_RESERVED_LABELS, |domain| async move { assert_eq!(domain, "alice.tngl.sh"); Ok(Some("did:alice".to_string())) }, ) .await .unwrap(); let row = store .select_claim_by_domain("alice.tngl.sh") .await .unwrap() .unwrap(); assert_eq!(row.did, "did:alice"); assert_eq!(row.deleted, None); } #[tokio::test] async fn a_vouched_owner_takes_over_a_squatted_handle_row() { let store = SitesStore::mem(); store .insert_claim("did:squatter", "victim.tngl.sh") .await .unwrap(); claim_vouched( &store, t(2026, 1, 1), "did:victim", "victim.tngl.sh", TLDS, DEFAULT_RESERVED_LABELS, |domain| async move { Ok(Some(format!("did:victim for {}", domain))) }, ) .await .unwrap_err(); claim_vouched( &store, t(2026, 1, 1), "did:victim", "victim.tngl.sh", TLDS, DEFAULT_RESERVED_LABELS, |_domain| async { Ok(Some("did:victim".to_string())) }, ) .await .unwrap(); let row = store .select_claim_by_domain("victim.tngl.sh") .await .unwrap() .unwrap(); assert_eq!(row.did, "did:victim"); assert_eq!(row.deleted, None); assert_eq!( store.select_claim_by_did("did:squatter").await.unwrap(), None ); } #[tokio::test] async fn a_foreign_site_name_row_is_not_taken_over() { let store = SitesStore::mem(); store .insert_claim("did:squatter", "victim.tngl.io") .await .unwrap(); let err = claim_site_name(&store, t(2026, 1, 1), "did:victim", "victim.tngl.io", TLDS) .await .unwrap_err(); assert_eq!(err, ClaimError::DomainTaken); assert_eq!( store .select_claim_by_domain("victim.tngl.io") .await .unwrap() .unwrap() .did, "did:squatter" ); } #[tokio::test] async fn a_rename_leaves_a_row_the_new_handle_replaces() { let store = SitesStore::mem(); claim_vouched( &store, t(2026, 1, 1), "did:alice", "alice.tngl.sh", TLDS, DEFAULT_RESERVED_LABELS, |_domain| async { Ok(Some("did:alice".to_string())) }, ) .await .unwrap(); claim_vouched( &store, t(2026, 1, 2), "did:alice", "bob.tngl.sh", TLDS, DEFAULT_RESERVED_LABELS, |domain| async move { match domain.as_str() { "bob.tngl.sh" => Ok(Some("did:alice".to_string())), _ => Ok(Some("did:carol".to_string())), } }, ) .await .unwrap(); let row = store .select_claim_by_did("did:alice") .await .unwrap() .unwrap(); assert_eq!(row.domain, "bob.tngl.sh"); assert_eq!(row.deleted, None); assert_eq!( store.select_claim_by_domain("alice.tngl.sh").await.unwrap(), None ); claim_vouched( &store, t(2026, 1, 2), "did:carol", "alice.tngl.sh", TLDS, DEFAULT_RESERVED_LABELS, |_domain| async { Ok(Some("did:carol".to_string())) }, ) .await .unwrap(); } #[tokio::test] async fn a_handle_the_account_still_holds_stays_its_own_claim() { let store = SitesStore::mem(); claim_vouched( &store, t(2026, 1, 1), "did:alice", "alice.tngl.sh", TLDS, DEFAULT_RESERVED_LABELS, |_domain| async { Ok(Some("did:alice".to_string())) }, ) .await .unwrap(); let err = claim_vouched( &store, t(2026, 1, 2), "did:alice", "bob.tngl.sh", TLDS, DEFAULT_RESERVED_LABELS, |_domain| async { Ok(Some("did:alice".to_string())) }, ) .await .unwrap_err(); assert_eq!(err, ClaimError::AlreadyClaimed); assert_eq!( store .select_claim_by_did("did:alice") .await .unwrap() .unwrap() .domain, "alice.tngl.sh" ); } async fn claim_with_holders( store: &SitesStore, now: DateTime, did: &str, domain: &str, holder_of: &'static [(&'static str, &'static str)], ) -> Result<(), ClaimError> { claim_vouched( store, now, did, domain, TLDS, DEFAULT_RESERVED_LABELS, |d| async move { Ok(holder_of .iter() .find(|(dom, _)| *dom == d) .map(|(_, owner)| owner.to_string())) }, ) .await } async fn active_domain(store: &SitesStore, did: &str) -> Option { store.active_domain_for_did(did).await.unwrap() } const RENAMED: &[(&str, &str)] = &[("old.tngl.sh", "did:carol")]; #[tokio::test] async fn a_renamed_account_claims_a_site_name_over_its_leftover_handle() { let store = SitesStore::mem(); store .insert_claim("did:alice", "old.tngl.sh") .await .unwrap(); claim_with_holders(&store, t(2026, 1, 2), "did:alice", "alice.tngl.io", RENAMED) .await .unwrap(); assert_eq!( active_domain(&store, "did:alice").await.as_deref(), Some("alice.tngl.io") ); assert_eq!( store.select_claim_by_domain("old.tngl.sh").await.unwrap(), None ); } #[tokio::test] async fn a_leftover_handle_with_no_vouch_is_replaced_too() { let store = SitesStore::mem(); store .insert_claim("did:alice", "old.tngl.sh") .await .unwrap(); claim_with_holders(&store, t(2026, 1, 2), "did:alice", "alice.tngl.io", &[]) .await .unwrap(); assert_eq!( active_domain(&store, "did:alice").await.as_deref(), Some("alice.tngl.io") ); } #[tokio::test] async fn a_handle_still_held_blocks_a_site_name() { let store = SitesStore::mem(); store .insert_claim("did:alice", "old.tngl.sh") .await .unwrap(); let err = claim_with_holders( &store, t(2026, 1, 2), "did:alice", "alice.tngl.io", &[("old.tngl.sh", "did:alice")], ) .await .unwrap_err(); assert_eq!(err, ClaimError::AlreadyClaimed); assert_eq!( active_domain(&store, "did:alice").await.as_deref(), Some("old.tngl.sh") ); } #[tokio::test] async fn an_unverifiable_leftover_handle_stays_put() { let store = SitesStore::mem(); store .insert_claim("did:alice", "old.tngl.sh") .await .unwrap(); let err = claim_vouched( &store, t(2026, 1, 2), "did:alice", "alice.tngl.io", TLDS, DEFAULT_RESERVED_LABELS, |_domain| async { Err("connection refused".to_string()) }, ) .await .unwrap_err(); assert!(matches!(err, ClaimError::Store(_))); assert_eq!( active_domain(&store, "did:alice").await.as_deref(), Some("old.tngl.sh") ); } #[tokio::test] async fn a_live_site_name_row_is_not_replaced() { let store = SitesStore::mem(); store .insert_claim("did:alice", "foo.tngl.io") .await .unwrap(); let err = claim_with_holders(&store, t(2026, 1, 2), "did:alice", "bar.tngl.io", &[]) .await .unwrap_err(); assert_eq!(err, ClaimError::AlreadyClaimed); assert_eq!( active_domain(&store, "did:alice").await.as_deref(), Some("foo.tngl.io") ); } #[tokio::test] async fn replacing_a_leftover_handle_never_takes_anothers_site_name() { let store = SitesStore::mem(); store .insert_claim("did:alice", "old.tngl.sh") .await .unwrap(); store .insert_claim("did:bob", "taken.tngl.io") .await .unwrap(); let err = claim_with_holders(&store, t(2026, 1, 2), "did:alice", "taken.tngl.io", RENAMED) .await .unwrap_err(); assert_eq!(err, ClaimError::DomainTaken); assert_eq!( active_domain(&store, "did:bob").await.as_deref(), Some("taken.tngl.io") ); assert_eq!( active_domain(&store, "did:alice").await.as_deref(), Some("old.tngl.sh") ); } #[tokio::test] async fn replacing_a_leftover_handle_respects_anothers_cooldown() { let store = SitesStore::mem(); store .insert_claim("did:alice", "old.tngl.sh") .await .unwrap(); store .insert_claim("did:bob", "freed.tngl.io") .await .unwrap(); release(&store, t(2026, 1, 1), "did:bob", "freed.tngl.io") .await .unwrap(); let err = claim_with_holders(&store, t(2026, 1, 2), "did:alice", "freed.tngl.io", RENAMED) .await .unwrap_err(); assert_eq!(err, ClaimError::DomainCooldown); assert_eq!( active_domain(&store, "did:alice").await.as_deref(), Some("old.tngl.sh") ); claim_with_holders( &store, t(2026, 1, 1) + Duration::days(CLAIM_COOLDOWN_DAYS + 1), "did:alice", "freed.tngl.io", RENAMED, ) .await .unwrap(); assert_eq!( active_domain(&store, "did:alice").await.as_deref(), Some("freed.tngl.io") ); } #[tokio::test] async fn replacing_a_leftover_handle_still_validates_the_name() { let store = SitesStore::mem(); store .insert_claim("did:alice", "old.tngl.sh") .await .unwrap(); for bad in ["sites.tngl.io", "not a name.tngl.io", "alice.example.com"] { let err = claim_with_holders(&store, t(2026, 1, 2), "did:alice", bad, RENAMED) .await .unwrap_err(); assert_eq!(err, ClaimError::InvalidSubdomain, "{}", bad); } assert_eq!( active_domain(&store, "did:alice").await.as_deref(), Some("old.tngl.sh") ); } #[tokio::test] async fn a_handle_target_still_needs_the_zone_after_a_site_name_switch() { let store = SitesStore::mem(); store .insert_claim("did:alice", "old.tngl.sh") .await .unwrap(); claim_with_holders(&store, t(2026, 1, 2), "did:alice", "alice.tngl.io", RENAMED) .await .unwrap(); let err = claim_with_holders(&store, t(2026, 1, 3), "did:alice", "old.tngl.sh", RENAMED) .await .unwrap_err(); assert_eq!(err, ClaimError::HandleNotOwned); assert_eq!( active_domain(&store, "did:alice").await.as_deref(), Some("alice.tngl.io") ); } #[tokio::test] async fn a_site_name_claim_never_clears_a_squatted_handle_row() { let store = SitesStore::mem(); store .insert_claim("did:alice", "old.tngl.sh") .await .unwrap(); store .insert_claim("did:bob", "squat.tngl.sh") .await .unwrap(); let err = claim_with_holders( &store, t(2026, 1, 2), "did:alice", "squat.tngl.sh", &[("old.tngl.sh", "did:carol"), ("squat.tngl.sh", "did:carol")], ) .await .unwrap_err(); assert_eq!(err, ClaimError::HandleNotOwned); assert_eq!( active_domain(&store, "did:bob").await.as_deref(), Some("squat.tngl.sh") ); } #[tokio::test] async fn a_claim_row_is_only_deleted_while_it_is_still_the_observed_owner() { let store = SitesStore::mem(); store .insert_claim("did:squatter", "victim.tngl.sh") .await .unwrap(); assert_eq!( store .delete_claim_if_owned_by("victim.tngl.sh", "did:elsewhere") .await .unwrap(), 0 ); assert!( store .select_claim_by_domain("victim.tngl.sh") .await .unwrap() .is_some() ); assert_eq!( store .delete_claim_if_owned_by("victim.tngl.sh", "did:squatter") .await .unwrap(), 1 ); assert_eq!( store .select_claim_by_domain("victim.tngl.sh") .await .unwrap(), None ); } #[tokio::test] async fn a_site_name_is_claimed_without_asking_the_handle_authority() { let store = SitesStore::mem(); claim_vouched( &store, t(2026, 1, 1), "did:alice", "anything.tngl.io", TLDS, DEFAULT_RESERVED_LABELS, |domain| async move { panic!("claimed to ask the authority about {}", domain); }, ) .await .unwrap(); assert_eq!( store .select_claim_by_domain("anything.tngl.io") .await .unwrap() .unwrap() .did, "did:alice" ); } #[tokio::test] async fn an_unreachable_handle_authority_is_not_a_claim() { let store = SitesStore::mem(); let err = claim_vouched( &store, t(2026, 1, 1), "did:alice", "alice.tngl.sh", TLDS, DEFAULT_RESERVED_LABELS, |_domain| async { Err("connection refused".to_string()) }, ) .await .unwrap_err(); assert!(matches!(err, ClaimError::Store(_))); assert_eq!( store.select_claim_by_domain("alice.tngl.sh").await.unwrap(), None ); } #[tokio::test] async fn resolving_a_domain_that_is_not_a_handle_is_refused() { for not_a_handle in ["alice.tngl.io", "example.com", "tngl.sh", ""] { let err = resolve_handle(not_a_handle.to_string()).await.unwrap_err(); assert!( err.contains("not a handle domain"), "{}: {}", not_a_handle, err ); } } const DNS_ONE: &str = r#"{"Status":0,"TC":false,"RD":true,"RA":true,"AD":false,"CD":false,"Question":[{"name":"_atproto.alecsargent.tngl.sh","type":16}],"Answer":[{"name":"_atproto.alecsargent.tngl.sh","type":16,"TTL":6400,"data":"\"did=did:plc:uvmg3kbhaohojdcdcsmbtz3u\""}]}"#; const DNS_NONE: &str = r#"{"Status":0,"TC":false,"RD":true,"RA":true,"AD":false,"CD":false,"Question":[{"name":"_atproto.linh.tngl.sh","type":16}],"Authority":[{"name":"tngl.sh","type":6,"TTL":1800,"data":"barbara.ns.cloudflare.com. dns.cloudflare.com. 2418454135 10000 2400 604800 1800"}]}"#; fn dns_answer(data: &[&str]) -> String { let answer: Vec<_> = data .iter() .map(|d| serde_json::json!({"name": "_atproto.x.tngl.sh", "type": 16, "data": d})) .collect(); serde_json::json!({"Status": 0, "Answer": answer}).to_string() } #[test] fn a_lone_did_txt_record_proves_the_handle() { assert_eq!( did_from_dns_json(DNS_ONE).unwrap().as_deref(), Some("did:plc:uvmg3kbhaohojdcdcsmbtz3u") ); let chunked = dns_answer(&[r#""did=did:plc:" "abc""#]); assert_eq!( did_from_dns_json(&chunked).unwrap().as_deref(), Some("did:plc:abc") ); } #[test] fn two_did_txt_records_prove_nothing() { let two = dns_answer(&[r#""did=did:plc:aaa""#, r#""did=did:plc:bbb""#]); assert_eq!(did_from_dns_json(&two).unwrap(), None); let repeated = dns_answer(&[r#""did=did:plc:aaa""#, r#""did=did:plc:aaa""#]); assert_eq!(did_from_dns_json(&repeated).unwrap(), None); } #[test] fn txt_values_that_are_not_a_did_are_ignored() { let other = dns_answer(&[r#""did=nope""#, r#""v=spf1 -all""#, r#""did=did:plc:aaa""#]); assert_eq!( did_from_dns_json(&other).unwrap().as_deref(), Some("did:plc:aaa") ); assert_eq!( did_from_dns_json(&dns_answer(&[r#""did=nope""#])).unwrap(), None ); } #[test] fn a_dns_name_without_a_txt_record_is_unknown() { assert_eq!(did_from_dns_json(DNS_NONE).unwrap(), None); assert_eq!(did_from_dns_json(r#"{"Status":3}"#).unwrap(), None); assert_eq!( did_from_dns_json(r#"{"Status":0,"Answer":[]}"#).unwrap(), None ); } #[test] fn a_dns_failure_is_not_a_denial() { assert!(did_from_dns_json(r#"{"Status":2}"#).is_err()); assert!(did_from_dns_json("").is_err()); assert!(did_from_dns_json("").is_err()); } #[test] fn only_a_denial_is_an_unknown_handle() { for denied in [400, 404] { assert!(zone_denies_handle(denied)); } for not_an_answer in [302, 429, 500, 502, 503] { assert!(!zone_denies_handle(not_an_answer), "{}", not_an_answer); } } #[test] fn only_a_held_title_is_a_claim_to_show_or_serve() { assert!(Title::Held.holds()); assert!(!Title::Squatted.holds()); assert!(!Title::Unknown.holds()); assert!(!Title::Unverifiable.holds()); } #[test] fn a_stored_claim_is_only_held_while_the_zone_agrees() { let did = "did:plc:alice"; assert_eq!(title_of(did, Some(did)), Title::Held); assert_eq!(title_of(did, Some("did:plc:attacker")), Title::Squatted); assert_eq!(title_of(did, None), Title::Unknown); assert_ne!(title_of(did, Some("did:plc:alice")), Title::Unverifiable); assert_eq!( titled(did, Some("did:plc:attacker".to_string())), Err(ClaimError::HandleNotOwned) ); assert_eq!(titled(did, None), Err(ClaimError::HandleUnknown)); assert_eq!(titled(did, Some(did.to_string())), Ok(())); } #[test] fn a_self_claimed_handle_needs_both_directions_to_agree() { let did = "did:plc:alice"; assert_eq!( self_claimed_handle(did, Some("alice.tngl.sh"), Some(did)).as_deref(), Some("alice.tngl.sh") ); assert_eq!( self_claimed_handle(did, Some("victim.tngl.sh"), Some("did:plc:victim")), None ); assert_eq!(self_claimed_handle(did, Some("alice.tngl.sh"), None), None); assert_eq!( self_claimed_handle(did, Some("alice.tngl.sh"), Some("did:plc:bob")), None ); assert_eq!( self_claimed_handle(did, Some("alice.tngl.io"), Some(did)), None ); assert_eq!(self_claimed_handle(did, None, Some(did)), None); } #[test] fn a_handle_is_a_single_label_under_a_handle_tld() { assert!(is_handle_domain("alice.tngl.sh")); for not_a_handle in [ "tngl.sh", "alice.tngl.io", "alice.other.tngl.sh", "alice.b.c.tngl.sh", ".tngl.sh", "ALICE.tngl.sh", "-alice.tngl.sh", "alice-.tngl.sh", "a b.tngl.sh", "alice.tngl.sh.evil.example", "", ] { assert!(!is_handle_domain(not_a_handle), "{:?}", not_a_handle); } } #[tokio::test] async fn resolving_a_nested_host_under_a_handle_zone_is_refused() { for nested in ["alice.other.tngl.sh", "alice.b.tngl.sh", ".tngl.sh"] { let err = resolve_handle(nested.to_string()).await.unwrap_err(); assert!(err.contains("not a handle domain"), "{}: {}", nested, err); } } #[tokio::test] async fn released_domain_can_be_reclaimed_after_cooldown() { let store = SitesStore::mem(); claim_site_name(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io", TLDS) .await .unwrap(); assert!( release(&store, t(2026, 1, 1), "did:alice", "alice.tngl.io") .await .unwrap() ); claim_site_name(&store, t(2026, 2, 1), "did:bob", "alice.tngl.io", TLDS) .await .unwrap(); let row = store .select_claim_by_domain("alice.tngl.io") .await .unwrap() .unwrap(); assert_eq!(row.did, "did:bob"); assert_eq!(row.deleted, None); } #[tokio::test] async fn tngl_sh_release_is_permanent() { let store = SitesStore::mem(); claim_site_name(&store, t(2026, 1, 1), "did:alice", "alice.tngl.sh", TLDS) .await .unwrap(); let err = release(&store, t(2026, 1, 1), "did:alice", "alice.tngl.sh") .await .unwrap_err(); assert_eq!(err, ClaimError::DomainPermanent); let row = store .select_claim_by_did("did:alice") .await .unwrap() .unwrap(); assert_eq!(row.deleted, None); } #[tokio::test] async fn invalid_tld_is_invalid_subdomain() { let store = SitesStore::mem(); let err = claim_site_name( &store, t(2026, 1, 1), "did:alice", "alice.example.com", TLDS, ) .await .unwrap_err(); assert_eq!(err, ClaimError::InvalidSubdomain); } #[tokio::test] async fn badly_formed_labels_are_invalid_subdomain() { let store = SitesStore::mem(); for bad in [ "-alice.tngl.io", "alice-.tngl.io", "ALICE.tngl.io", ".tngl.io", "a b.tngl.io", ] { let err = claim_site_name(&store, t(2026, 1, 1), "did:alice", bad, TLDS) .await .unwrap_err(); assert_eq!(err, ClaimError::InvalidSubdomain, "domain {:?}", bad); } } #[tokio::test] async fn release_missing_claim_is_not_found() { let store = SitesStore::mem(); assert!( !release(&store, t(2026, 1, 1), "did:alice", "nobody.tngl.io") .await .unwrap() ); } }