-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbluesky_client.rs
More file actions
1520 lines (1297 loc) · 51.7 KB
/
Copy pathbluesky_client.rs
File metadata and controls
1520 lines (1297 loc) · 51.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Bluesky client for resolving actor information.
//!
//! This module provides functionality to resolve handles to DIDs,
//! fetch DID documents, and extract PDS endpoints.
use std::net::IpAddr;
use std::time::Instant;
use crate::log::{logger};
use crate::ws::{ActorInfo, ActorQueryOptions, OptionalResult};
use reqwest::Client;
use serde_json::Value;
use thiserror::Error;
/// Errors that can occur during actor resolution.
#[derive(Error, Debug)]
pub enum BlueskyClientError {
#[error("HTTP request failed: {0}")]
HttpError(#[from] reqwest::Error),
#[error("JSON parsing failed: {0}")]
JsonError(#[from] serde_json::Error),
#[error("Invalid actor: {0}")]
InvalidActor(String),
#[error("Resolution failed: {0}")]
ResolutionFailed(String),
}
/// Default App View host name for the Bluesky public API.
pub const DEFAULT_APP_VIEW_HOST_NAME: &str = "public.api.bsky.app";
/// Client for interacting with Bluesky/AT Protocol services.
pub struct BlueskyClient {
client: Client,
app_view_host_name: String,
}
impl Default for BlueskyClient {
fn default() -> Self {
Self::new(DEFAULT_APP_VIEW_HOST_NAME)
}
}
impl BlueskyClient {
/// Creates a new BlueskyClient with default settings.
pub fn new(app_view_host_name: &str) -> Self {
Self {
client: Client::builder()
.user_agent("rustproto")
.build()
.expect("Failed to create HTTP client"),
app_view_host_name: app_view_host_name.to_string(),
}
}
/// Creates a new BlueskyClient with a custom reqwest Client.
pub fn with_client(client: Client, app_view_host_name: &str) -> Self {
Self { client, app_view_host_name: app_view_host_name.to_string() }
}
/// Resolves actor information for a handle or DID.
///
/// Attempts the following steps:
/// 1. Resolve handle to DID (dns, http, or bluesky api)
/// 2. Resolve DID to DID document (did:plc or did:web)
/// 3. Extract PDS endpoint from DID document
/// 4. Extract handle from DID document (if not already known)
/// 5. Extract public key from DID document
///
/// # Arguments
///
/// * `actor` - A handle (e.g., "alice.bsky.social") or DID (e.g., "did:plc:abc123")
/// * `options` - Optional query options to control resolution behavior
///
pub async fn resolve_actor_info(
&self,
actor: &str,
options: Option<ActorQueryOptions>,
) -> Result<ActorInfo, BlueskyClientError> {
let start_time = Instant::now();
let options = options.unwrap_or_default();
let mut info = ActorInfo::with_actor(actor);
// Empty actor check
if actor.is_empty() {
return Err(BlueskyClientError::InvalidActor(
"Actor is null or empty".to_string(),
));
}
//
// Step 1: Resolve handle to DID
//
if actor.starts_with("did:") {
// check that it is a valid did
if !Self::is_valid_did(actor) {
logger().warning(&format!(
"[SECURITY] Rejected invalid DID during actor resolution: {}",
actor
));
return Err(BlueskyClientError::InvalidActor(format!(
"Invalid DID: {}",
actor
)));
}
info.did = Some(actor.to_string());
} else {
let normalized_handle = actor.to_ascii_lowercase();
// check that it is a valid handle
if !Self::is_valid_handle(&normalized_handle) {
logger().warning(&format!(
"[SECURITY] Rejected invalid handle during actor resolution: {}",
actor
));
return Err(BlueskyClientError::InvalidActor(format!(
"Invalid handle: {}",
actor
)));
}
info.handle = Some(normalized_handle.clone());
// Try different resolution methods
if options.should_resolve_via_bluesky() {
info.did_bsky = self
.resolve_handle_to_did_via_bluesky(&normalized_handle)
.await;
}
if options.should_resolve_via_dns() {
info.did_dns = self
.resolve_handle_to_did_via_dns(&normalized_handle)
.await;
}
if options.should_resolve_via_http() {
info.did_http = self
.resolve_handle_to_did_via_http(&normalized_handle)
.await;
}
// Use first successful resolution
info.did = info
.did_bsky
.success()
.or_else(|| info.did_dns.success())
.or_else(|| info.did_http.success())
.cloned();
}
// Early exit if no DID resolved
let did = match &info.did {
Some(d) if d.starts_with("did:") => d.clone(),
_ => {
let elapsed_ms = start_time.elapsed().as_secs_f64() * 1000.0;
logger().info(&format!(
"[ACTOR] [BSKY] actor={} all={} bsky={} dns={} http={} didDoc={} did=None appview={} [{:.2}ms]",
actor, options.all, options.resolve_handle_via_bluesky,
options.resolve_handle_via_dns, options.resolve_handle_via_http,
options.resolve_did_doc, self.app_view_host_name, elapsed_ms
));
return Ok(info);
}
};
if !Self::is_valid_did(&did) {
logger().warning(&format!(
"[SECURITY] Rejected invalid DID syntax during actor resolution: actor={} did={}",
actor, did
));
return Err(BlueskyClientError::InvalidActor(format!(
"Invalid DID: {}",
did
)));
}
// Allow only did:plc and did:web methods.
if !did.starts_with("did:plc:") && !did.starts_with("did:web:") {
logger().warning(&format!(
"[SECURITY] Rejected unsupported DID method during actor resolution: actor={} did={}",
actor, did
));
return Err(BlueskyClientError::InvalidActor(format!(
"Unsupported DID method: {}",
did
)));
}
//
// Step 2: Resolve DID to DID document
//
if options.should_resolve_did_doc() {
if let Ok(did_doc) = self.resolve_did_to_did_doc(&did).await {
info.did_doc = Some(did_doc);
}
}
//
// Step 3: Extract PDS from DID document
//
if let Some(ref did_doc) = info.did_doc {
if let Ok(pds) = Self::extract_pds_from_did_doc(did_doc) {
info.pds = Some(pds);
}
//
// Step 4: Extract handle from DID document if not known
//
if info.handle.is_none() {
if let Ok(handle) = Self::extract_handle_from_did_doc(did_doc) {
let normalized_handle = handle.to_ascii_lowercase();
if Self::is_valid_handle(&normalized_handle) {
info.handle = Some(normalized_handle);
} else {
logger().warning(&format!(
"[SECURITY] Ignored invalid handle extracted from DID document: actor={} did={} handle={}",
actor, did, handle
));
}
}
}
//
// Step 5: Extract public key from DID document
//
if let Ok(pubkey) = Self::extract_public_key_from_did_doc(did_doc) {
info.public_key_multibase = Some(pubkey);
}
}
// Log the resolution result
let elapsed_ms = start_time.elapsed().as_secs_f64() * 1000.0;
let did_doc_length = info.did_doc.as_ref().map(|d| d.len()).unwrap_or(0);
logger().info(&format!(
"[ACTOR] [BSKY] actor={} all={} bsky={} dns={} http={} didDoc={} did={} didDocLength={} pds={} appview={} [{:.2}ms]",
actor, options.all, options.resolve_handle_via_bluesky,
options.resolve_handle_via_dns, options.resolve_handle_via_http,
options.resolve_did_doc,
info.did.as_deref().unwrap_or("None"),
did_doc_length,
info.pds.as_deref().unwrap_or("None"),
self.app_view_host_name,
elapsed_ms
));
Ok(info)
}
/// Resolves a handle to a DID using the Bluesky public API.
///
/// Calls `com.atproto.identity.resolveHandle` on the public API.
pub async fn resolve_handle_to_did_via_bluesky(
&self,
handle: &str,
) -> OptionalResult<String, String> {
let url = format!(
"https://{}/xrpc/com.atproto.identity.resolveHandle?handle={}",
self.app_view_host_name, handle
);
// trace log the url
logger().trace(&format!("[ACTOR] [BSKY] Resolving handle via Bluesky API: handle={} url={}", handle, url));
let response = match self.client.get(&url).send().await {
Ok(r) => r,
Err(e) => return OptionalResult::Failure(e.to_string()),
};
let json: Value = match response.json().await {
Ok(j) => j,
Err(e) => return OptionalResult::Failure(e.to_string()),
};
match json["did"].as_str() {
Some(did) => OptionalResult::Success(did.to_string()),
None => OptionalResult::Failure(format!("No DID in response: {}", json).to_string()),
}
}
/// Resolves a handle to a DID using DNS TXT records.
///
/// Queries `_atproto.{handle}` TXT record via Cloudflare DNS-over-HTTPS.
pub async fn resolve_handle_to_did_via_dns(
&self,
handle: &str,
) -> OptionalResult<String, String> {
let url = format!(
"https://cloudflare-dns.com/dns-query?name=_atproto.{}&type=TXT",
handle
);
let response = match self
.client
.get(&url)
.header("Accept", "application/dns-json")
.send()
.await
{
Ok(r) => r,
Err(e) => return OptionalResult::Failure(e.to_string()),
};
let json: Value = match response.json().await {
Ok(j) => j,
Err(e) => return OptionalResult::Failure(e.to_string()),
};
// Parse DNS response and look for did= in TXT records
if let Some(answers) = json["Answer"].as_array() {
for answer in answers {
if let Some(data) = answer["data"].as_str() {
let data = data.trim_matches('"');
if let Some(did) = data.strip_prefix("did=") {
logger().trace(&format!("[ACTOR] [BSKY] Resolved handle via DNS: handle={} did={}", handle, did));
return OptionalResult::Success(did.to_string());
}
}
}
}
logger().trace(&format!("[ACTOR] [BSKY] Failed to resolve handle via DNS: handle={}", handle));
OptionalResult::Failure("No DID found in DNS TXT records".to_string())
}
/// Resolves a handle to a DID using HTTP well-known endpoint.
///
/// Fetches `https://{handle}/.well-known/atproto-did`.
pub async fn resolve_handle_to_did_via_http(
&self,
handle: &str,
) -> OptionalResult<String, String> {
let url = format!("https://{}/.well-known/atproto-did", handle);
logger().trace(&format!("[ACTOR] [BSKY] Resolving handle via HTTP: handle={} url={}", handle, url));
let response = match self.client.get(&url).send().await {
Ok(r) => r,
Err(e) => return OptionalResult::Failure(e.to_string()),
};
let text = match response.text().await {
Ok(t) => t,
Err(e) => return OptionalResult::Failure(e.to_string()),
};
let did = text.trim();
if did.starts_with("did:") {
logger().trace(&format!("[ACTOR] [BSKY] Resolved handle via HTTP: handle={} did={}", handle, did));
OptionalResult::Success(did.to_string())
} else {
logger().trace(&format!("[ACTOR] [BSKY] Failed to resolve handle via HTTP: handle={} response={}", handle, text));
OptionalResult::Failure("Invalid DID in HTTP response".to_string())
}
}
/// Resolves a DID to its DID document.
///
/// Supports both did:plc (via plc.directory) and did:web (via .well-known/did.json).
pub async fn resolve_did_to_did_doc(&self, did: &str) -> Result<String, BlueskyClientError> {
if did.starts_with("did:plc:") {
self.resolve_did_to_did_doc_plc(did).await
} else if did.starts_with("did:web:") {
self.resolve_did_to_did_doc_web(did).await
} else {
Err(BlueskyClientError::InvalidActor(format!(
"Unsupported DID method: {}",
did
)))
}
}
/// Resolves a did:plc to its DID document via plc.directory.
async fn resolve_did_to_did_doc_plc(&self, did: &str) -> Result<String, BlueskyClientError> {
let url = format!("https://plc.directory/{}", did);
let response = self.client.get(&url).send().await?;
let text = response.text().await?;
logger().trace(&format!("[ACTOR] [BSKY] Resolved did:plc to DID document: did={} didDocLength={}", did, text.len()));
Ok(text)
}
/// Resolves a did:web to its DID document via .well-known/did.json.
async fn resolve_did_to_did_doc_web(&self, did: &str) -> Result<String, BlueskyClientError> {
let url = Self::build_did_web_doc_url(did)?;
logger().trace(&format!("[ACTOR] [BSKY] Resolving did:web to DID document: did={} url={}", did, url));
let response = self.client.get(&url).send().await?;
let text = response.text().await?;
logger().trace(&format!("[ACTOR] [BSKY] Resolved did:web to DID document: did={} didDocLength={}", did, text.len()));
Ok(text)
}
/// Builds a canonical did:web document URL after method-specific validation.
///
/// did:web examples:
/// - did:web:example.com => https://example.com/.well-known/did.json
/// - did:web:example.com:users:alice => https://example.com/users/alice/did.json
fn build_did_web_doc_url(did: &str) -> Result<String, BlueskyClientError> {
let identifier = did
.strip_prefix("did:web:")
.ok_or_else(|| BlueskyClientError::InvalidActor("Invalid did:web format".to_string()))?;
let parts: Vec<&str> = identifier.split(':').collect();
if parts.is_empty() || parts[0].is_empty() {
return Err(BlueskyClientError::InvalidActor(
"Invalid did:web identifier".to_string(),
));
}
let authority = parts[0];
if !Self::is_valid_did_web_authority(authority) {
return Err(BlueskyClientError::InvalidActor(format!(
"Invalid did:web authority: {}",
authority
)));
}
let mut path_segments = Vec::new();
for segment in parts.iter().skip(1) {
if !Self::is_valid_did_web_path_segment(segment) {
return Err(BlueskyClientError::InvalidActor(format!(
"Invalid did:web path segment: {}",
segment
)));
}
path_segments.push(*segment);
}
let path = if path_segments.is_empty() {
"/.well-known/did.json".to_string()
} else {
format!("/{}/did.json", path_segments.join("/"))
};
let url = format!("https://{}{}", authority, path);
let parsed = reqwest::Url::parse(&url).map_err(|_| {
BlueskyClientError::InvalidActor("Invalid did:web URL after parsing".to_string())
})?;
if parsed.host_str().is_none() {
return Err(BlueskyClientError::InvalidActor(
"Invalid did:web URL host".to_string(),
));
}
Ok(url)
}
fn is_valid_did_web_authority(authority: &str) -> bool {
if authority.is_empty() || !authority.is_ascii() {
return false;
}
if authority
.bytes()
.any(|b| matches!(b, b'/' | b'\\' | b'?' | b'#' | b'@' | b'%'))
{
return false;
}
let (host, port) = match authority.rsplit_once(':') {
Some((host, port)) if !host.is_empty() && !port.is_empty() => {
if !port.bytes().all(|b| b.is_ascii_digit()) {
return false;
}
if port.parse::<u16>().is_err() {
return false;
}
(host, Some(port))
}
Some((_, _)) => return false,
None => (authority, None),
};
let _ = port;
let host_lower = host.to_ascii_lowercase();
if host_lower == "localhost" || host_lower.ends_with(".localhost") {
return false;
}
if let Ok(ip) = host_lower.parse::<IpAddr>() {
return Self::is_public_ip(ip);
}
Self::is_valid_handle(&host_lower)
}
fn is_public_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => {
!(v4.is_private()
|| v4.is_loopback()
|| v4.is_link_local()
|| v4.is_broadcast()
|| v4.is_unspecified())
}
IpAddr::V6(v6) => {
!(v6.is_loopback()
|| v6.is_unspecified()
|| v6.is_unique_local()
|| v6.is_unicast_link_local())
}
}
}
fn is_valid_did_web_path_segment(segment: &str) -> bool {
if segment.is_empty() || segment == "." || segment == ".." {
return false;
}
if !segment.is_ascii() {
return false;
}
let bytes = segment.as_bytes();
let mut i = 0;
while i < bytes.len() {
let b = bytes[i];
if b == b'%' {
if i + 2 >= bytes.len()
|| !bytes[i + 1].is_ascii_hexdigit()
|| !bytes[i + 2].is_ascii_hexdigit()
{
return false;
}
i += 3;
continue;
}
if !(b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~')) {
return false;
}
i += 1;
}
true
}
/// Extracts the PDS endpoint from a DID document.
///
/// Looks for a service entry with type "AtprotoPersonalDataServer".
pub fn extract_pds_from_did_doc(did_doc: &str) -> Result<String, BlueskyClientError> {
let doc: Value = serde_json::from_str(did_doc)?;
if let Some(services) = doc["service"].as_array() {
for service in services {
if service["type"].as_str() == Some("AtprotoPersonalDataServer") {
if let Some(endpoint) = service["serviceEndpoint"].as_str() {
return Self::extract_pds_host_from_endpoint(endpoint);
}
}
}
}
Err(BlueskyClientError::ResolutionFailed(
"No PDS found in DID document".to_string(),
))
}
/// Parses and validates a PDS serviceEndpoint URL, returning normalized host[:port].
fn extract_pds_host_from_endpoint(endpoint: &str) -> Result<String, BlueskyClientError> {
let parsed = reqwest::Url::parse(endpoint).map_err(|_| {
BlueskyClientError::ResolutionFailed("Invalid PDS serviceEndpoint URL".to_string())
})?;
if parsed.scheme() != "https" && parsed.scheme() != "http" {
return Err(BlueskyClientError::ResolutionFailed(
"PDS serviceEndpoint must use http or https".to_string(),
));
}
if !parsed.username().is_empty() || parsed.password().is_some() {
return Err(BlueskyClientError::ResolutionFailed(
"PDS serviceEndpoint must not contain user info".to_string(),
));
}
if parsed.query().is_some() || parsed.fragment().is_some() {
return Err(BlueskyClientError::ResolutionFailed(
"PDS serviceEndpoint must not contain query or fragment".to_string(),
));
}
if parsed.path() != "/" {
return Err(BlueskyClientError::ResolutionFailed(
"PDS serviceEndpoint must not contain a path".to_string(),
));
}
let host = parsed
.host_str()
.ok_or_else(|| {
BlueskyClientError::ResolutionFailed(
"PDS serviceEndpoint must include a host".to_string(),
)
})?
.to_ascii_lowercase();
if host == "localhost" || host.ends_with(".localhost") {
return Err(BlueskyClientError::ResolutionFailed(
"PDS hostname must not be localhost".to_string(),
));
}
if let Ok(ip) = host.parse::<IpAddr>() {
if !Self::is_public_ip(ip) {
return Err(BlueskyClientError::ResolutionFailed(
"PDS hostname must not be a local/private IP".to_string(),
));
}
} else if !Self::is_valid_handle(&host) {
return Err(BlueskyClientError::ResolutionFailed(
"PDS hostname is invalid".to_string(),
));
}
Ok(match parsed.port() {
Some(port) => format!("{}:{}", host, port),
None => host,
})
}
/// Extracts the handle from a DID document.
///
/// Looks for the first entry in "alsoKnownAs" with at:// prefix.
pub fn extract_handle_from_did_doc(did_doc: &str) -> Result<String, BlueskyClientError> {
let doc: Value = serde_json::from_str(did_doc)?;
if let Some(aliases) = doc["alsoKnownAs"].as_array() {
if let Some(first) = aliases.first() {
if let Some(uri) = first.as_str() {
let handle = uri.trim_start_matches("at://").split('/').next();
if let Some(h) = handle {
return Ok(h.to_string());
}
}
}
}
Err(BlueskyClientError::ResolutionFailed(
"No handle found in DID document".to_string(),
))
}
/// Extracts the public key (multibase) from a DID document.
///
/// Looks for a verification method with id ending in "#atproto".
pub fn extract_public_key_from_did_doc(did_doc: &str) -> Result<String, BlueskyClientError> {
let doc: Value = serde_json::from_str(did_doc)?;
if let Some(methods) = doc["verificationMethod"].as_array() {
for method in methods {
if let Some(id) = method["id"].as_str() {
if id.ends_with("#atproto") {
if let Some(pubkey) = method["publicKeyMultibase"].as_str() {
return Ok(pubkey.to_string());
}
}
}
}
}
Err(BlueskyClientError::ResolutionFailed(
"No public key found in DID document".to_string(),
))
}
/// Validates whether a string is a syntactically valid ATProto handle.
///
/// This follows the handle syntax rules from the ATProto specification:
/// ASCII only, dot-separated labels, 2+ labels, per-label charset/length
/// constraints, and top-level label must not start with a digit.
pub fn is_valid_handle(handle: &str) -> bool {
if handle.is_empty() || !handle.is_ascii() || handle.len() > 253 {
return false;
}
if handle.starts_with('.') || handle.ends_with('.') {
return false;
}
let labels: Vec<&str> = handle.split('.').collect();
if labels.len() < 2 {
return false;
}
for label in &labels {
if label.is_empty() || label.len() > 63 {
return false;
}
if label.starts_with('-') || label.ends_with('-') {
return false;
}
if !label
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-')
{
return false;
}
}
if labels
.last()
.and_then(|tld| tld.as_bytes().first())
.is_some_and(u8::is_ascii_digit)
{
return false;
}
true
}
/// Validates whether a string is a syntactically valid DID in ATProto context.
///
/// Rules implemented:
/// - ASCII only and max length 2048
/// - Must start with `did:`
/// - Method is one or more lowercase letters, followed by `:`
/// - Identifier uses only `[A-Za-z0-9._:%-]`
/// - Identifier must not end with `:` or `%`
pub fn is_valid_did(did: &str) -> bool {
if did.is_empty() || !did.is_ascii() || did.len() > 2048 {
return false;
}
let rest = match did.strip_prefix("did:") {
Some(rest) => rest,
None => return false,
};
let method_sep = match rest.find(':') {
Some(idx) => idx,
None => return false,
};
let method = &rest[..method_sep];
let identifier = &rest[method_sep + 1..];
if method.is_empty() || !method.chars().all(|c| c.is_ascii_lowercase()) {
return false;
}
if identifier.is_empty() || identifier.ends_with(':') || identifier.ends_with('%') {
return false;
}
identifier.bytes().all(|b| {
b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'%' | b'-')
})
}
/// Gets the PLC audit log (history) for a DID.
///
/// Calls `https://plc.directory/{did}/log/audit`.
pub async fn get_plc_history(&self, did: &str) -> Result<Value, BlueskyClientError> {
if !did.starts_with("did:plc:") {
return Err(BlueskyClientError::InvalidActor(format!(
"'{}' is not a did:plc",
did
)));
}
let url = format!("https://plc.directory/{}/log/audit", did);
let response = self.client.get(&url).send().await?;
let json: Value = response.json().await?;
Ok(json)
}
/// Gets the repo status for a DID from a PDS.
///
/// Calls `com.atproto.sync.getRepoStatus` on the PDS.
pub async fn get_repo_status(
&self,
pds: &str,
did: &str,
) -> Result<Value, BlueskyClientError> {
let url = format!(
"https://{}/xrpc/com.atproto.sync.getRepoStatus?did={}",
pds, did
);
let response = self.client.get(&url).send().await?;
let json: Value = response.json().await?;
Ok(json)
}
/// Gets health status for a PDS.
///
/// Calls `_health` on the PDS.
pub async fn pds_health(&self, pds: &str) -> Result<Value, BlueskyClientError> {
let url = format!("https://{}/xrpc/_health", pds);
logger().trace(&format!("[SEND REQUEST] {}", url));
let response = self.client.get(&url).send().await?;
let json: Value = response.json().await?;
Ok(json)
}
/// Gets server description for a PDS.
///
/// Calls `com.atproto.server.describeServer` on the PDS.
pub async fn pds_describe_server(&self, pds: &str) -> Result<Value, BlueskyClientError> {
let url = format!("https://{}/xrpc/com.atproto.server.describeServer", pds);
logger().trace(&format!("[SEND REQUEST] {}", url));
let response = self.client.get(&url).send().await?;
let json: Value = response.json().await?;
Ok(json)
}
/// Lists repos on a PDS.
///
/// Calls `com.atproto.sync.listRepos` on the PDS.
pub async fn list_repos(&self, pds: &str, limit: u32) -> Result<Vec<Value>, BlueskyClientError> {
let mut repos = Vec::new();
let mut cursor: Option<String> = None;
loop {
let url = match &cursor {
Some(c) => format!(
"https://{}/xrpc/com.atproto.sync.listRepos?limit={}&cursor={}",
pds, limit, c
),
None => format!(
"https://{}/xrpc/com.atproto.sync.listRepos?limit={}",
pds, limit
),
};
logger().trace(&format!("[SEND REQUEST] {}", url));
let response = self.client.get(&url).send().await?;
let json: Value = response.json().await?;
if let Some(repos_array) = json["repos"].as_array() {
for repo in repos_array {
repos.push(repo.clone());
}
}
cursor = json["cursor"].as_str().map(|s| s.to_string());
if cursor.is_none() {
break;
}
// Small delay between requests
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
}
Ok(repos)
}
/// Gets posts by URI.
///
/// Calls `app.bsky.feed.getPosts` on the public API.
pub async fn get_posts(&self, uris: &[&str]) -> Result<Value, BlueskyClientError> {
let uris_param = uris.join(",");
let url = format!(
"https://{}/xrpc/app.bsky.feed.getPosts?uris={}",
self.app_view_host_name, uris_param
);
logger().trace(&format!("[SEND REQUEST] {}", url));
let response = self.client.get(&url).send().await?;
let json: Value = response.json().await?;
Ok(json)
}
/// Resolves a lexicon schema by NSID using authoritative DNS + DID + PDS routing.
///
/// Resolution flow:
/// 1. Convert NSID to authority domain (drop final name segment, then reverse labels)
/// 2. Resolve `_lexicon.{authority}` TXT and read `did=...`
/// 3. Resolve DID doc, extract PDS service endpoint
/// 4. Fetch `com.atproto.lexicon.schema/{nsid}` via `com.atproto.repo.getRecord`
pub async fn resolve_lexicon_schema(&self, nsid: &str) -> Result<Value, BlueskyClientError> {
let authority = Self::lexicon_authority_from_nsid(nsid)?;
let dns_name = format!("_lexicon.{}", authority);
let txt_values = self.resolve_dns_txt_values(&dns_name).await?;
let did = Self::extract_did_from_dns_txt_values(&txt_values).ok_or_else(|| {
BlueskyClientError::ResolutionFailed(format!(
"No DID found in TXT records for {}",
dns_name
))
})?;
let did_doc = self.resolve_did_to_did_doc(&did).await?;
let pds = Self::extract_pds_from_did_doc(&did_doc)?;
self.repo_get_record_json(&pds, &did, "com.atproto.lexicon.schema", nsid)
.await
}
async fn repo_get_record_json(
&self,
pds: &str,
repo: &str,
collection: &str,
rkey: &str,
) -> Result<Value, BlueskyClientError> {
if pds.is_empty() || repo.is_empty() || collection.is_empty() || rkey.is_empty() {
return Err(BlueskyClientError::InvalidActor(
"PDS, repo, collection, and rkey are required".to_string(),
));
}
let url = format!(
"https://{}/xrpc/com.atproto.repo.getRecord?repo={}&collection={}&rkey={}",
pds,
urlencoding::encode(repo),
urlencoding::encode(collection),
urlencoding::encode(rkey)
);
logger().trace(&format!("[SEND REQUEST] {}", url));
let response = self.client.get(&url).send().await?;
if !response.status().is_success() {
let status = response.status();
let body = response.text().await.unwrap_or_default();
return Err(BlueskyClientError::ResolutionFailed(format!(
"HTTP {} from PDS: {}",
status, body
)));
}
let json: Value = response.json().await?;
Ok(json)
}
async fn resolve_dns_txt_values(
&self,
name: &str,
) -> Result<Vec<String>, BlueskyClientError> {
let url = format!(
"https://cloudflare-dns.com/dns-query?name={}&type=TXT",
name
);
logger().trace(&format!("[SEND REQUEST] {}", url));
let response = self
.client
.get(&url)
.header("Accept", "application/dns-json")
.send()
.await?;
if !response.status().is_success() {
return Err(BlueskyClientError::ResolutionFailed(format!(
"DNS query failed for {} with HTTP {}",
name,
response.status()
)));
}
let json: Value = response.json().await?;
let mut txt_values = Vec::new();
if let Some(answers) = json["Answer"].as_array() {
for answer in answers {
if let Some(data) = answer["data"].as_str() {
txt_values.push(data.to_string());
}
}
}
if txt_values.is_empty() {
return Err(BlueskyClientError::ResolutionFailed(format!(
"No TXT answers found for {}",
name
)));
}
Ok(txt_values)
}
fn extract_did_from_dns_txt_values(values: &[String]) -> Option<String> {
for value in values {
let raw = value.trim().trim_matches('"');
for token in raw.split_whitespace() {
let candidate = token.strip_prefix("did=").unwrap_or(token);
if candidate.starts_with("did:") && Self::is_valid_did(candidate) {
return Some(candidate.to_string());
}
}