1//! Identity resolution utilities: DID and handle resolution, DID document fetch,
2//! and helpers for PDS endpoint discovery. See `identity::resolver` for details.
3//! Identity resolution: handle → DID and DID → document, with smart fallbacks.
4//!
5//! Fallback order (default):
6//! - Handle → DID: DNS TXT (if `dns` feature) → HTTPS well-known → PDS XRPC
7//! `resolveHandle` (when `pds_fallback` is configured) → public API fallback → Slingshot `resolveHandle` (if configured).
8//! - DID → Doc: did:web well-known → PLC/Slingshot HTTP → PDS XRPC `resolveDid` (when configured),
9//! then Slingshot mini‑doc (partial) if configured.
10//!
11//! Parsing returns a `DidDocResponse` so callers can borrow from the response buffer
12//! and optionally validate the document `id` against the requested DID.
13
14// use crate::CowStr; // not currently needed directly here
15pub mod resolver;
16
17use crate::resolver::{
18 DidDocResponse, DidStep, HandleStep, IdentityError, IdentityResolver, MiniDoc, PlcSource,
19 ResolverOptions,
20};
21use bytes::Bytes;
22use jacquard_api::com_atproto::identity::resolve_did;
23use jacquard_api::com_atproto::identity::resolve_handle::ResolveHandle;
24use jacquard_common::error::TransportError;
25use jacquard_common::http_client::HttpClient;
26use jacquard_common::types::did::Did;
27use jacquard_common::types::did_doc::DidDocument;
28use jacquard_common::types::ident::AtIdentifier;
29use jacquard_common::types::xrpc::XrpcExt;
30use jacquard_common::{IntoStatic, types::string::Handle};
31use percent_encoding::percent_decode_str;
32use reqwest::StatusCode;
33use url::{ParseError, Url};
34
35#[cfg(feature = "dns")]
36use hickory_resolver::{TokioAsyncResolver, config::ResolverConfig};
37
38/// Default resolver implementation with configurable fallback order.
39pub struct JacquardResolver {
40 http: reqwest::Client,
41 opts: ResolverOptions,
42 #[cfg(feature = "dns")]
43 dns: Option<TokioAsyncResolver>,
44}
45
46impl JacquardResolver {
47 /// Create a new instance of the default resolver with all options (except DNS) up front
48 pub fn new(http: reqwest::Client, opts: ResolverOptions) -> Self {
49 Self {
50 http,
51 opts,
52 #[cfg(feature = "dns")]
53 dns: None,
54 }
55 }
56
57 #[cfg(feature = "dns")]
58 /// Create a new instance of the default resolver with all options, plus default DNS, up front
59 pub fn new_dns(http: reqwest::Client, opts: ResolverOptions) -> Self {
60 Self {
61 http,
62 opts,
63 dns: Some(TokioAsyncResolver::tokio(
64 ResolverConfig::default(),
65 Default::default(),
66 )),
67 }
68 }
69
70 #[cfg(feature = "dns")]
71 /// Add default DNS resolution to the resolver
72 pub fn with_system_dns(mut self) -> Self {
73 self.dns = Some(TokioAsyncResolver::tokio(
74 ResolverConfig::default(),
75 Default::default(),
76 ));
77 self
78 }
79
80 /// Set PLC source (PLC directory or Slingshot)
81 pub fn with_plc_source(mut self, source: PlcSource) -> Self {
82 self.opts.plc_source = source;
83 self
84 }
85
86 /// Enable/disable public unauthenticated fallback for resolveHandle
87 pub fn with_public_fallback_for_handle(mut self, enable: bool) -> Self {
88 self.opts.public_fallback_for_handle = enable;
89 self
90 }
91
92 /// Enable/disable doc id validation
93 pub fn with_validate_doc_id(mut self, enable: bool) -> Self {
94 self.opts.validate_doc_id = enable;
95 self
96 }
97
98 /// Construct the well-known HTTPS URL for a `did:web` DID.
99 ///
100 /// - `did:web:example.com` → `https://example.com/.well-known/did.json`
101 /// - `did:web:example.com:user:alice` → `https://example.com/user/alice/did.json`
102 fn did_web_url(&self, did: &Did<'_>) -> Result<Url, IdentityError> {
103 // did:web:example.com[:path:segments]
104 let s = did.as_str();
105 let rest = s
106 .strip_prefix("did:web:")
107 .ok_or_else(|| IdentityError::UnsupportedDidMethod(s.to_string()))?;
108 let mut parts = rest.split(':');
109 let host = parts
110 .next()
111 .ok_or_else(|| IdentityError::UnsupportedDidMethod(s.to_string()))?;
112 let mut url = Url::parse(&format!("https://{host}/")).map_err(IdentityError::Url)?;
113 let path: Vec<&str> = parts.collect();
114 if path.is_empty() {
115 url.set_path(".well-known/did.json");
116 } else {
117 // Append path segments and did.json
118 let mut segments = url
119 .path_segments_mut()
120 .map_err(|_| IdentityError::Url(ParseError::SetHostOnCannotBeABaseUrl))?;
121 for seg in path {
122 // Minimally percent-decode each segment per spec guidance
123 let decoded = percent_decode_str(seg).decode_utf8_lossy();
124 segments.push(&decoded);
125 }
126 segments.push("did.json");
127 // drop segments
128 }
129 Ok(url)
130 }
131
132 #[cfg(test)]
133 fn test_did_web_url_raw(&self, s: &str) -> String {
134 let did = Did::new(s).unwrap();
135 self.did_web_url(&did).unwrap().to_string()
136 }
137
138 async fn get_json_bytes(&self, url: Url) -> Result<(Bytes, StatusCode), IdentityError> {
139 let resp = self
140 .http
141 .get(url)
142 .send()
143 .await
144 .map_err(TransportError::from)?;
145 let status = resp.status();
146 let buf = resp.bytes().await.map_err(TransportError::from)?;
147 Ok((buf, status))
148 }
149
150 async fn get_text(&self, url: Url) -> Result<String, IdentityError> {
151 let resp = self
152 .http
153 .get(url)
154 .send()
155 .await
156 .map_err(TransportError::from)?;
157 if resp.status() == StatusCode::OK {
158 Ok(resp.text().await.map_err(TransportError::from)?)
159 } else {
160 Err(IdentityError::Http(
161 resp.error_for_status().unwrap_err().into(),
162 ))
163 }
164 }
165
166 #[cfg(feature = "dns")]
167 async fn dns_txt(&self, name: &str) -> Result<Vec<String>, IdentityError> {
168 let Some(dns) = &self.dns else {
169 return Ok(vec![]);
170 };
171 let fqdn = format!("_atproto.{name}.");
172 let response = dns.txt_lookup(fqdn).await?;
173 let mut out = Vec::new();
174 for txt in response.iter() {
175 for data in txt.txt_data().iter() {
176 out.push(String::from_utf8_lossy(data).to_string());
177 }
178 }
179 Ok(out)
180 }
181
182 fn parse_atproto_did_body(body: &str) -> Result<Did<'static>, IdentityError> {
183 let line = body
184 .lines()
185 .find(|l| !l.trim().is_empty())
186 .ok_or(IdentityError::InvalidWellKnown)?;
187 let did = Did::new(line.trim()).map_err(|_| IdentityError::InvalidWellKnown)?;
188 Ok(did.into_static())
189 }
190}
191
192impl JacquardResolver {
193 /// Resolve handle to DID via a PDS XRPC call (stateless, unauth by default)
194 pub async fn resolve_handle_via_pds(
195 &self,
196 handle: &Handle<'_>,
197 ) -> Result<Did<'static>, IdentityError> {
198 let pds = match &self.opts.pds_fallback {
199 Some(u) => u.clone(),
200 None => return Err(IdentityError::InvalidWellKnown),
201 };
202 let req = ResolveHandle::new().handle((*handle).clone()).build();
203 let resp = self
204 .http
205 .xrpc(pds)
206 .send(&req)
207 .await
208 .map_err(|e| IdentityError::Xrpc(e.to_string()))?;
209 let out = resp
210 .into_output()
211 .map_err(|e| IdentityError::Xrpc(e.to_string()))?;
212 Did::new_owned(out.did.as_str())
213 .map(|d| d.into_static())
214 .map_err(|_| IdentityError::InvalidWellKnown)
215 }
216
217 /// Fetch DID document via PDS resolveDid (returns owned DidDocument)
218 pub async fn fetch_did_doc_via_pds_owned(
219 &self,
220 did: &Did<'_>,
221 ) -> Result<DidDocument<'static>, IdentityError> {
222 let pds = match &self.opts.pds_fallback {
223 Some(u) => u.clone(),
224 None => return Err(IdentityError::InvalidWellKnown),
225 };
226 let req = resolve_did::ResolveDid::new().did(did.clone()).build();
227 let resp = self
228 .http
229 .xrpc(pds)
230 .send(&req)
231 .await
232 .map_err(|e| IdentityError::Xrpc(e.to_string()))?;
233 let out = resp
234 .into_output()
235 .map_err(|e| IdentityError::Xrpc(e.to_string()))?;
236 let doc_json = serde_json::to_value(&out.did_doc)?;
237 let s = serde_json::to_string(&doc_json)?;
238 let doc_borrowed: DidDocument<'_> = serde_json::from_str(&s)?;
239 Ok(doc_borrowed.into_static())
240 }
241
242 /// Fetch a minimal DID document via a Slingshot mini-doc endpoint, if your PlcSource uses Slingshot.
243 /// Returns the raw response wrapper for borrowed parsing and validation.
244 pub async fn fetch_mini_doc_via_slingshot(
245 &self,
246 did: &Did<'_>,
247 ) -> Result<DidDocResponse, IdentityError> {
248 let base = match &self.opts.plc_source {
249 PlcSource::Slingshot { base } => base.clone(),
250 _ => {
251 return Err(IdentityError::UnsupportedDidMethod(
252 "mini-doc requires Slingshot source".into(),
253 ));
254 }
255 };
256 let mut url = base;
257 url.set_path("/xrpc/com.bad-example.identity.resolveMiniDoc");
258 if let Ok(qs) =
259 serde_html_form::to_string(&resolve_did::ResolveDid::new().did(did.clone()).build())
260 {
261 url.set_query(Some(&qs));
262 }
263 let (buf, status) = self.get_json_bytes(url).await?;
264 Ok(DidDocResponse {
265 buffer: buf,
266 status,
267 requested: Some(did.clone().into_static()),
268 })
269 }
270}
271
272#[async_trait::async_trait]
273impl IdentityResolver for JacquardResolver {
274 fn options(&self) -> &ResolverOptions {
275 &self.opts
276 }
277 async fn resolve_handle(&self, handle: &Handle<'_>) -> Result<Did<'static>, IdentityError> {
278 let host = handle.as_str();
279 for step in &self.opts.handle_order {
280 match step {
281 HandleStep::DnsTxt => {
282 #[cfg(feature = "dns")]
283 {
284 if let Ok(txts) = self.dns_txt(host).await {
285 for txt in txts {
286 if let Some(did_str) = txt.strip_prefix("did=") {
287 if let Ok(did) = Did::new(did_str) {
288 return Ok(did.into_static());
289 }
290 }
291 }
292 }
293 }
294 }
295 HandleStep::HttpsWellKnown => {
296 let url = Url::parse(&format!("https://{host}/.well-known/atproto-did"))?;
297 if let Ok(text) = self.get_text(url).await {
298 if let Ok(did) = Self::parse_atproto_did_body(&text) {
299 return Ok(did);
300 }
301 }
302 }
303 HandleStep::PdsResolveHandle => {
304 // Prefer PDS XRPC via stateless client
305 if let Ok(did) = self.resolve_handle_via_pds(handle).await {
306 return Ok(did);
307 }
308 // Public unauth fallback
309 if self.opts.public_fallback_for_handle {
310 if let Ok(mut url) = Url::parse("https://public.api.bsky.app") {
311 url.set_path("/xrpc/com.atproto.identity.resolveHandle");
312 if let Ok(qs) = serde_html_form::to_string(
313 &ResolveHandle::new().handle((*handle).clone()).build(),
314 ) {
315 url.set_query(Some(&qs));
316 } else {
317 continue;
318 }
319 if let Ok((buf, status)) = self.get_json_bytes(url).await {
320 if status.is_success() {
321 if let Ok(val) =
322 serde_json::from_slice::<serde_json::Value>(&buf)
323 {
324 if let Some(did_str) =
325 val.get("did").and_then(|v| v.as_str())
326 {
327 if let Ok(did) = Did::new_owned(did_str) {
328 return Ok(did.into_static());
329 }
330 }
331 }
332 }
333 }
334 }
335 }
336 // Non-auth path: if PlcSource is Slingshot, use its resolveHandle endpoint.
337 if let PlcSource::Slingshot { base } = &self.opts.plc_source {
338 let mut url = base.clone();
339 url.set_path("/xrpc/com.atproto.identity.resolveHandle");
340 if let Ok(qs) = serde_html_form::to_string(
341 &ResolveHandle::new().handle((*handle).clone()).build(),
342 ) {
343 url.set_query(Some(&qs));
344 } else {
345 continue;
346 }
347 if let Ok((buf, status)) = self.get_json_bytes(url).await {
348 if status.is_success() {
349 if let Ok(val) = serde_json::from_slice::<serde_json::Value>(&buf) {
350 if let Some(did_str) = val.get("did").and_then(|v| v.as_str()) {
351 if let Ok(did) = Did::new_owned(did_str) {
352 return Ok(did.into_static());
353 }
354 }
355 }
356 }
357 }
358 }
359 }
360 }
361 }
362 Err(IdentityError::InvalidWellKnown)
363 }
364
365 async fn resolve_did_doc(&self, did: &Did<'_>) -> Result<DidDocResponse, IdentityError> {
366 let s = did.as_str();
367 for step in &self.opts.did_order {
368 match step {
369 DidStep::DidWebHttps if s.starts_with("did:web:") => {
370 let url = self.did_web_url(did)?;
371 if let Ok((buf, status)) = self.get_json_bytes(url).await {
372 return Ok(DidDocResponse {
373 buffer: buf,
374 status,
375 requested: Some(did.clone().into_static()),
376 });
377 }
378 }
379 DidStep::PlcHttp if s.starts_with("did:plc:") => {
380 let url = match &self.opts.plc_source {
381 PlcSource::PlcDirectory { base } => {
382 // this is odd, the join screws up with the plc directory but NOT slingshot
383 Url::parse(&format!("{}{}", base, did.as_str())).expect("Invalid URL")
384 }
385 PlcSource::Slingshot { base } => base.join(did.as_str())?,
386 };
387 println!("Fetching DID document from {}", url);
388 if let Ok((buf, status)) = self.get_json_bytes(url).await {
389 return Ok(DidDocResponse {
390 buffer: buf,
391 status,
392 requested: Some(did.clone().into_static()),
393 });
394 }
395 }
396 DidStep::PdsResolveDid => {
397 // Try PDS XRPC for full DID doc
398 if let Ok(doc) = self.fetch_did_doc_via_pds_owned(did).await {
399 let buf = serde_json::to_vec(&doc).unwrap_or_default();
400 return Ok(DidDocResponse {
401 buffer: Bytes::from(buf),
402 status: StatusCode::OK,
403 requested: Some(did.clone().into_static()),
404 });
405 }
406 // Fallback: if Slingshot configured, return mini-doc response (partial doc)
407 if let PlcSource::Slingshot { base } = &self.opts.plc_source {
408 let url = self.slingshot_mini_doc_url(base, did.as_str())?;
409 let (buf, status) = self.get_json_bytes(url).await?;
410 return Ok(DidDocResponse {
411 buffer: buf,
412 status,
413 requested: Some(did.clone().into_static()),
414 });
415 }
416 }
417 _ => {}
418 }
419 }
420 Err(IdentityError::UnsupportedDidMethod(s.to_string()))
421 }
422}
423
424impl HttpClient for JacquardResolver {
425 async fn send_http(
426 &self,
427 request: http::Request<Vec<u8>>,
428 ) -> core::result::Result<http::Response<Vec<u8>>, Self::Error> {
429 self.http.send_http(request).await
430 }
431
432 type Error = reqwest::Error;
433}
434
435/// Warnings produced during identity checks that are not fatal
436#[derive(Debug, Clone, PartialEq, Eq)]
437pub enum IdentityWarning {
438 /// The DID doc did not contain the expected handle alias under alsoKnownAs
439 HandleAliasMismatch {
440 #[allow(missing_docs)]
441 expected: Handle<'static>,
442 },
443}
444
445impl JacquardResolver {
446 /// Resolve a handle to its DID, fetch the DID document, and return doc plus any warnings.
447 /// This applies the default equality check on the document id (error with doc if mismatch).
448 pub async fn resolve_handle_and_doc(
449 &self,
450 handle: &Handle<'_>,
451 ) -> Result<(Did<'static>, DidDocResponse, Vec<IdentityWarning>), IdentityError> {
452 let did = self.resolve_handle(handle).await?;
453 let resp = self.resolve_did_doc(&did).await?;
454 let resp_for_parse = resp.clone();
455 let doc_borrowed = resp_for_parse.parse()?;
456 if self.opts.validate_doc_id && doc_borrowed.id.as_str() != did.as_str() {
457 return Err(IdentityError::DocIdMismatch {
458 expected: did.clone().into_static(),
459 doc: doc_borrowed.clone().into_static(),
460 });
461 }
462 let mut warnings = Vec::new();
463 // Check handle alias presence (soft warning)
464 let expected_alias = format!("at://{}", handle.as_str());
465 let has_alias = doc_borrowed
466 .also_known_as
467 .as_ref()
468 .map(|v| v.iter().any(|s| s.as_ref() == expected_alias))
469 .unwrap_or(false);
470 if !has_alias {
471 warnings.push(IdentityWarning::HandleAliasMismatch {
472 expected: handle.clone().into_static(),
473 });
474 }
475 Ok((did, resp, warnings))
476 }
477
478 /// Build Slingshot mini-doc URL for an identifier (handle or DID)
479 fn slingshot_mini_doc_url(&self, base: &Url, identifier: &str) -> Result<Url, IdentityError> {
480 let mut url = base.clone();
481 url.set_path("/xrpc/com.bad-example.identity.resolveMiniDoc");
482 url.set_query(Some(&format!(
483 "identifier={}",
484 urlencoding::Encoded::new(identifier)
485 )));
486 Ok(url)
487 }
488
489 /// Fetch a minimal DID document via Slingshot's mini-doc endpoint using a generic at-identifier
490 pub async fn fetch_mini_doc_via_slingshot_identifier(
491 &self,
492 identifier: &AtIdentifier<'_>,
493 ) -> Result<MiniDocResponse, IdentityError> {
494 let base = match &self.opts.plc_source {
495 PlcSource::Slingshot { base } => base.clone(),
496 _ => {
497 return Err(IdentityError::UnsupportedDidMethod(
498 "mini-doc requires Slingshot source".into(),
499 ));
500 }
501 };
502 let url = self.slingshot_mini_doc_url(&base, identifier.as_str())?;
503 let (buf, status) = self.get_json_bytes(url).await?;
504 Ok(MiniDocResponse {
505 buffer: buf,
506 status,
507 })
508 }
509}
510
511/// Slingshot mini-doc JSON response wrapper
512#[derive(Clone)]
513pub struct MiniDocResponse {
514 buffer: Bytes,
515 status: StatusCode,
516}
517
518impl MiniDocResponse {
519 /// Parse borrowed MiniDoc
520 pub fn parse<'b>(&'b self) -> Result<MiniDoc<'b>, IdentityError> {
521 if self.status.is_success() {
522 serde_json::from_slice::<MiniDoc<'b>>(&self.buffer).map_err(IdentityError::from)
523 } else {
524 Err(IdentityError::HttpStatus(self.status))
525 }
526 }
527}
528
529/// Resolver specialized for unauthenticated/public flows using reqwest and stateless XRPC
530pub type PublicResolver = JacquardResolver;
531
532impl Default for PublicResolver {
533 /// Build a resolver with:
534 /// - reqwest HTTP client
535 /// - Public fallbacks enabled for handle resolution
536 /// - default options (DNS enabled if compiled, public fallback for handles enabled)
537 ///
538 /// Example
539 /// ```ignore
540 /// use jacquard::identity::resolver::PublicResolver;
541 /// let resolver = PublicResolver::default();
542 /// ```
543 fn default() -> Self {
544 let http = reqwest::Client::new();
545 let opts = ResolverOptions::default();
546 let resolver = JacquardResolver::new(http, opts);
547 #[cfg(feature = "dns")]
548 let resolver = resolver.with_system_dns();
549 resolver
550 }
551}
552
553/// Build a resolver configured to use Slingshot (`https://slingshot.microcosm.blue`) for PLC and
554/// mini-doc fallbacks, unauthenticated by default.
555pub fn slingshot_resolver_default() -> PublicResolver {
556 let http = reqwest::Client::new();
557 let mut opts = ResolverOptions::default();
558 opts.plc_source = PlcSource::slingshot_default();
559 let resolver = JacquardResolver::new(http, opts);
560 #[cfg(feature = "dns")]
561 let resolver = resolver.with_system_dns();
562 resolver
563}
564
565#[cfg(test)]
566mod tests {
567 use super::*;
568
569 #[test]
570 fn did_web_urls() {
571 let r = JacquardResolver::new(reqwest::Client::new(), ResolverOptions::default());
572 assert_eq!(
573 r.test_did_web_url_raw("did:web:example.com"),
574 "https://example.com/.well-known/did.json"
575 );
576 assert_eq!(
577 r.test_did_web_url_raw("did:web:example.com:user:alice"),
578 "https://example.com/user/alice/did.json"
579 );
580 }
581
582 #[test]
583 fn slingshot_mini_doc_url_build() {
584 let r = JacquardResolver::new(reqwest::Client::new(), ResolverOptions::default());
585 let base = Url::parse("https://slingshot.microcosm.blue").unwrap();
586 let url = r.slingshot_mini_doc_url(&base, "bad-example.com").unwrap();
587 assert_eq!(
588 url.as_str(),
589 "https://slingshot.microcosm.blue/xrpc/com.bad-example.identity.resolveMiniDoc?identifier=bad-example.com"
590 );
591 }
592
593 #[test]
594 fn slingshot_mini_doc_parse_success() {
595 let buf = Bytes::from_static(
596 br#"{
597 "did": "did:plc:hdhoaan3xa3jiuq4fg4mefid",
598 "handle": "bad-example.com",
599 "pds": "https://porcini.us-east.host.bsky.network",
600 "signing_key": "zQ3shpq1g134o7HGDb86CtQFxnHqzx5pZWknrVX2Waum3fF6j"
601}"#,
602 );
603 let resp = MiniDocResponse {
604 buffer: buf,
605 status: StatusCode::OK,
606 };
607 let doc = resp.parse().expect("parse mini-doc");
608 assert_eq!(doc.did.as_str(), "did:plc:hdhoaan3xa3jiuq4fg4mefid");
609 assert_eq!(doc.handle.as_str(), "bad-example.com");
610 assert_eq!(
611 doc.pds.as_ref(),
612 "https://porcini.us-east.host.bsky.network"
613 );
614 assert!(doc.signing_key.as_ref().starts_with('z'));
615 }
616
617 #[test]
618 fn slingshot_mini_doc_parse_error_status() {
619 let buf = Bytes::from_static(
620 br#"{
621 "error": "RecordNotFound",
622 "message": "This record was deleted"
623}"#,
624 );
625 let resp = MiniDocResponse {
626 buffer: buf,
627 status: StatusCode::BAD_REQUEST,
628 };
629 match resp.parse() {
630 Err(IdentityError::HttpStatus(s)) => assert_eq!(s, StatusCode::BAD_REQUEST),
631 other => panic!("unexpected: {:?}", other),
632 }
633 }
634}