-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBlueskyClient.cs
More file actions
1721 lines (1388 loc) · 56.6 KB
/
Copy pathBlueskyClient.cs
File metadata and controls
1721 lines (1388 loc) · 56.6 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
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using dnproto.repo;
using dnproto.log;
using dnproto.uri;
namespace dnproto.ws;
/// <summary>
/// Entry point for interacting with this SDK.
/// </summary>
public class BlueskyClient
{
public static IDnProtoLogger Logger = new Logger();
#region ACTOR
/// <summary>
/// Finds a bunch of info for a handle. (did, didDoc, pds)
///
/// Attempts the following steps:
///
/// 1. Resolve handle to did (dns or http).
/// 2. Resolve did to didDoc. (did:plc or did:web)
/// 3. Resolve didDoc to pds.
/// 4. Get handle from diddoc (if not already known).
///
/// </summary>
/// <param name="handle"></param>
/// <returns></returns>
public static ActorInfo ResolveActorInfo(string actor, ActorQueryOptions? queryOptions = null)
{
//
// If you don't specify options, you'll get the default options.
//
if (queryOptions is null) queryOptions = new ActorQueryOptions();
//
// Return value
//
var ret = new ActorInfo();
ret.Actor = actor;
//
// For logging
//
StringBuilder logLine = new StringBuilder($"[ACTOR] [BSKY] actor={actor} all={queryOptions.All} bsky={queryOptions.ResolveHandleViaBluesky} dns={queryOptions.ResolveHandleViaDns} http={queryOptions.ResolveHandleViaHttp} didDoc={queryOptions.ResolveDidDoc}");
DateTime startTime = DateTime.UtcNow;
try
{
Logger.LogTrace($"ResolveActorInfo: actor: {actor}");
if (string.IsNullOrEmpty(actor))
{
Logger.LogTrace("ResolveActorInfo: actor is null or empty. Exiting.");
return ret;
}
//
// 1. Resolve handle to did. Call all three methods (bluesky api, dns, http).
//
if(actor.StartsWith("did:", StringComparison.Ordinal))
{
if (!IsValidDid(actor))
{
Logger.LogWarning($"[SECURITY] Rejected invalid DID during actor resolution: {actor}");
return ret;
}
ret.Did = actor;
Logger.LogTrace("Actor is already a did.");
}
else
{
string normalizedHandle = actor.ToLowerInvariant();
if (!IsValidHandle(normalizedHandle))
{
Logger.LogWarning($"[SECURITY] Rejected invalid handle during actor resolution: {actor}");
return ret;
}
ret.Handle = normalizedHandle;
Logger.LogTrace("Actor is not a did, resolving to did.");
if (queryOptions.All || queryOptions.ResolveHandleViaBluesky)
{
ret.Did_Bsky = ResolveHandleToDid_ViaBlueskyApi(normalizedHandle);
}
if (queryOptions.All || queryOptions.ResolveHandleViaDns)
{
ret.Did_Dns = ResolveHandleToDid_ViaDns(normalizedHandle);
}
if (queryOptions.All || queryOptions.ResolveHandleViaHttp)
{
ret.Did_Http = ResolveHandleToDid_ViaHttp(normalizedHandle);
}
ret.Did = ret.Did_Bsky ?? ret.Did_Dns ?? ret.Did_Http;
logLine.Append($" did={ret.Did}");
}
if (string.IsNullOrEmpty(ret.Did) || !ret.Did.StartsWith("did:")) return ret;
if (!IsValidDid(ret.Did))
{
Logger.LogWarning($"[SECURITY] Rejected invalid DID syntax during actor resolution: actor={actor} did={ret.Did}");
return ret;
}
if (!ret.Did.StartsWith("did:plc:", StringComparison.Ordinal)
&& !ret.Did.StartsWith("did:web:", StringComparison.Ordinal))
{
Logger.LogWarning($"[SECURITY] Rejected unsupported DID method during actor resolution: actor={actor} did={ret.Did}");
return ret;
}
//
// 2. Resolve did to didDoc. (did:plc or did:web)
//
if (queryOptions.All || queryOptions.ResolveDidDoc)
{
ret.DidDoc = ResolveDidToDidDoc(ret.Did);
if (string.IsNullOrEmpty(ret.DidDoc)) return ret;
logLine.Append($" didDocLength={ret.DidDoc?.Length}");
}
Logger.LogTrace("didDoc length: " + ret.DidDoc?.Length);
//
// 3. Resolve didDoc to pds.
//
if(string.IsNullOrEmpty(ret.DidDoc) == false)
{
ret.Pds = BlueskyClient.ResolveDidDocToPds(ret.DidDoc);
if (string.IsNullOrEmpty(ret.Pds)) return ret;
ret.Pds = ret.Pds.Replace("https://", "");
logLine.Append($" pds={ret.Pds}");
}
//
// 4. Get handle from diddoc
//
if(string.IsNullOrEmpty(ret.DidDoc) == false)
{
JsonNode? didDocJson = JsonNode.Parse(ret.DidDoc);
if(string.IsNullOrEmpty(ret.Handle))
{
string? handleFromDidDoc = null;
handleFromDidDoc = didDocJson?["alsoKnownAs"]?.AsArray()?.FirstOrDefault()?.ToString()?.Replace("at://", "")?.Split('/')?[0];
if (!string.IsNullOrEmpty(handleFromDidDoc))
{
string normalizedHandle = handleFromDidDoc.ToLowerInvariant();
if (IsValidHandle(normalizedHandle))
{
ret.Handle = normalizedHandle;
}
else
{
Logger.LogWarning($"[SECURITY] Ignored invalid handle extracted from DID document: actor={actor} did={ret.Did} handle={handleFromDidDoc}");
}
}
}
//
// 5. Get public key from diddoc
//
if (string.IsNullOrEmpty(ret.PublicKeyMultibase))
{
foreach (var verificationMethod in didDocJson?["verificationMethod"]?.AsArray() ?? new JsonArray())
{
if (verificationMethod == null) continue;
var vmId = verificationMethod["id"]?.ToString();
if (vmId != null && vmId.EndsWith("#atproto"))
{
ret.PublicKeyMultibase = verificationMethod["publicKeyMultibase"]?.ToString();
break;
}
}
}
}
//
// return
//
return ret;
}
finally
{
DateTime endTime = DateTime.UtcNow;
TimeSpan duration = endTime - startTime;
logLine.Append($" [{duration.TotalMilliseconds:F2}ms]");
Logger.LogInfo(logLine.ToString());
}
}
/// <summary>
/// Resolves a did to a didDoc.
/// For did:plc, go to the plc directory.
/// For did:web, resolve the doc via HTTP at the .well-known endpoint.
/// </summary>
/// <param name="did">The did to resolve.</param>
/// <returns>The resolved didDoc or null if not found.</returns>
public static string? ResolveDidToDidDoc(string? did)
{
if(did == null) return null;
string? didDoc = null;
if (did.StartsWith("did:plc:", StringComparison.Ordinal))
{
didDoc = BlueskyClient.ResolveDidToDidDoc_DidPlc(did);
}
else if (did.StartsWith("did:web:", StringComparison.Ordinal))
{
didDoc = BlueskyClient.ResolveDidToDidDoc_DidWeb(did);
}
return didDoc;
}
/// <summary>
/// Resolves a handle to a did, using dns.
/// </summary>
/// <param name="handle">The handle to resolve.</param>
/// <returns>The resolved did or null if not found.</returns>
public static string? ResolveHandleToDid_ViaDns(string? handle)
{
if (string.IsNullOrEmpty(handle))
{
Logger.LogTrace("ResolveHandleToDid_ViaDns: Handle is null or empty.");
return null;
}
string? did = null;
string url = $"https://cloudflare-dns.com/dns-query?name=_atproto.{handle}&type=TXT";
Logger.LogTrace($"ResolveHandleToDid_ViaDns: handle: {handle}");
Logger.LogTrace($"ResolveHandleToDid_ViaDns: url: {url}");
JsonNode? response = BlueskyClient.SendRequest(url, HttpMethod.Get, acceptHeader: "application/dns-json");
if (response != null)
{
// print response for debugging
var options = new JsonSerializerOptions { WriteIndented = true };
Logger.LogTrace(response.ToJsonString(options));
// get did
foreach (var answer in response["Answer"]?.AsArray() ?? new JsonArray())
{
if(answer == null) continue;
var dataRaw = answer.AsObject()?["data"]?.ToString();
var data = dataRaw?.Replace("\"", "");
Logger.LogTrace($"dataRaw: {dataRaw}");
Logger.LogTrace($"data: {data}");
if (string.IsNullOrEmpty(data)) continue;
if(data.StartsWith("did="))
{
if(string.IsNullOrEmpty(did) == false)
{
Logger.LogError("Multiple DID records found in DNS TXT records.");
return did;
}
did = data.Replace("did=", "");
}
}
}
Logger.LogTrace($"ResolveHandleToDid_ViaDns: did: {did}");
return did;
}
/// <summary>
/// Resolves a handle to a did, using http.
/// </summary>
/// <param name="handle">The handle to resolve.</param>
/// <returns>The resolved did or null if not found.</returns>
public static string? ResolveHandleToDid_ViaHttp(string? handle)
{
string? did = null;
string url = $"https://{handle}/.well-known/atproto-did";
Logger.LogTrace($"ResolveHandleToDid_ViaHttp: handle: {handle}");
Logger.LogTrace($"ResolveHandleToDid_ViaHttp: url: {url}");
string? responseText = null;
try
{
responseText = BlueskyClient.SendRequestEx(url, HttpMethod.Get);
}
catch (Exception ex)
{
Exception? inner = ex;
int count = 1;
while (inner != null)
{
Logger.LogTrace($"ResolveHandleToDid_ViaHttp: Exception {count}: {inner.Message}");
Logger.LogTrace(inner.StackTrace ?? "");
inner = inner.InnerException;
count++;
}
}
if (responseText != null && responseText.StartsWith("did:"))
{
did = responseText;
}
Logger.LogTrace($"ResolveHandleToDid_ViaHttp: did: {did}");
return did;
}
/// <summary>
/// Resolves a handle to a did, using the Bluesky public api.
/// </summary>
/// <param name="handle">The handle to resolve.</param>
/// <returns>The resolved did or null if not found.</returns>
public static string? ResolveHandleToDid_ViaBlueskyApi(string? handle)
{
Logger.LogTrace($"ResolveHandleToDid_ViaBlueskyApi: handle: {handle}");
if (string.IsNullOrEmpty(handle))
{
Logger.LogTrace("ResolveHandleToDid_ViaBlueskyApi: Handle is null or empty. Exiting.");
return null;
}
string url = $"https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle={handle}";
Logger.LogTrace($"ResolveHandleToDid_ViaBlueskyApi: url: {url}");
JsonNode? response = BlueskyClient.SendRequest(url, HttpMethod.Get);
string? did = JsonData.SelectString(response, "did");
Logger.LogTrace($"ResolveHandleToDid_ViaBlueskyApi: did: {did}");
return did;
}
/// <summary>
/// Resolves a did to didDoc, for did:plc.
/// </summary>
/// <param name="did">The did to resolve.</param>
/// <returns>The resolved didDoc or null if not found.</returns>
public static string? ResolveDidToDidDoc_DidPlc(string? did)
{
Logger.LogTrace($"ResolveDidToDidDoc_DidPlc: did: {did}");
if (string.IsNullOrEmpty(did) || !did.StartsWith("did:plc"))
{
Logger.LogError($"ResolveDidToDidDoc_DidPlc: invalid did, exiting.");
return null;
}
string? didDoc = null;
string url = $"https://plc.directory/{did}";
Logger.LogTrace($"ResolveDidToDidDoc_DidPlc: url: {url}");
var response = BlueskyClient.SendRequest(url, HttpMethod.Get);
didDoc = JsonData.ConvertToJsonString(response);
return didDoc;
}
/// <summary>
/// Resolves a did to didDoc, for did:web.
/// </summary>
/// <param name="did">The did to resolve.</param>
/// <returns>The resolved didDoc or null if not found.</returns>
public static string? ResolveDidToDidDoc_DidWeb(string? did)
{
Logger.LogTrace($"ResolveDidToDidDoc_DidWeb: did: {did}");
if (string.IsNullOrEmpty(did) || !did.StartsWith("did:web:", StringComparison.Ordinal))
{
Logger.LogError($"ResolveDidToDidDoc_DidWeb: invalid did, exiting.");
return null;
}
string? url = BuildDidWebDocUrl(did);
if (string.IsNullOrEmpty(url))
{
Logger.LogWarning($"[SECURITY] Rejected invalid did:web during resolution: {did}");
return null;
}
Logger.LogTrace($"ResolveDidToDidDoc_DidWeb: url: {url}");
var response = BlueskyClient.SendRequest(url, HttpMethod.Get);
var didDoc = JsonData.ConvertToJsonString(response);
return didDoc;
}
/// <summary>
/// Resolves a didDoc to pds.
/// This is used to get the pds from the didDoc.
/// </summary>
/// <param name="didDoc">The didDoc to resolve.</param>
/// <returns>The resolved pds or null if not found.</returns>
public static string? ResolveDidDocToPds(string? didDoc)
{
Logger.LogTrace($"ResolveDidDocToPds: didDoc length: {didDoc?.Length}");
if (string.IsNullOrEmpty(didDoc))
{
Logger.LogError("DidDoc is null or empty.");
return null;
}
JsonNode? didDocJson = JsonNode.Parse(didDoc);
if (didDocJson == null) return null;
foreach (var service in didDocJson["service"]?.AsArray() ?? new JsonArray())
{
if (service == null) continue;
var serviceType = service["type"]?.ToString();
if (serviceType == "AtprotoPersonalDataServer")
{
var pds = service["serviceEndpoint"]?.ToString();
if (!string.IsNullOrEmpty(pds))
{
string? host = ExtractPdsHostFromEndpoint(pds);
if (!string.IsNullOrEmpty(host))
{
return host;
}
Logger.LogWarning($"[SECURITY] Ignored invalid PDS serviceEndpoint in DID document: {pds}");
}
}
}
return null;
}
public static bool IsValidHandle(string? handle)
{
if (string.IsNullOrEmpty(handle)) return false;
if (handle.Length > 253) return false;
if (!handle.All(static c => c <= 127)) return false;
if (handle.StartsWith('.') || handle.EndsWith('.')) return false;
string[] labels = handle.Split('.');
if (labels.Length < 2) return false;
foreach (string label in labels)
{
if (string.IsNullOrEmpty(label) || label.Length > 63) return false;
if (label.StartsWith('-') || label.EndsWith('-')) return false;
foreach (char ch in label)
{
if (!(char.IsAsciiLetterOrDigit(ch) || ch == '-')) return false;
}
}
char tldFirstChar = labels[^1][0];
if (char.IsDigit(tldFirstChar)) return false;
return true;
}
public static bool IsValidDid(string? did)
{
if (string.IsNullOrEmpty(did)) return false;
if (did.Length > 2048) return false;
if (!did.All(static c => c <= 127)) return false;
if (!did.StartsWith("did:", StringComparison.Ordinal)) return false;
string rest = did.Substring(4);
int methodSeparatorIndex = rest.IndexOf(':');
if (methodSeparatorIndex <= 0) return false;
string method = rest.Substring(0, methodSeparatorIndex);
string identifier = rest.Substring(methodSeparatorIndex + 1);
if (!method.All(static c => c is >= 'a' and <= 'z')) return false;
if (string.IsNullOrEmpty(identifier)) return false;
if (identifier.EndsWith(':') || identifier.EndsWith('%')) return false;
foreach (char ch in identifier)
{
bool isAllowed = char.IsAsciiLetterOrDigit(ch)
|| ch == '.'
|| ch == '_'
|| ch == ':'
|| ch == '%'
|| ch == '-';
if (!isAllowed) return false;
}
return true;
}
public static string? BuildDidWebDocUrl(string? did)
{
if (string.IsNullOrEmpty(did)) return null;
const string prefix = "did:web:";
if (!did.StartsWith(prefix, StringComparison.Ordinal)) return null;
string identifier = did.Substring(prefix.Length);
string[] parts = identifier.Split(':');
if (parts.Length == 0 || string.IsNullOrEmpty(parts[0])) return null;
string authority = parts[0];
if (!IsValidDidWebAuthority(authority)) return null;
var pathSegments = new List<string>();
for (int i = 1; i < parts.Length; i++)
{
string segment = parts[i];
if (!IsValidDidWebPathSegment(segment)) return null;
pathSegments.Add(segment);
}
string path = pathSegments.Count == 0
? "/.well-known/did.json"
: $"/{string.Join("/", pathSegments)}/did.json";
string url = $"https://{authority}{path}";
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? parsed)) return null;
if (parsed.Scheme != Uri.UriSchemeHttps) return null;
if (string.IsNullOrEmpty(parsed.Host)) return null;
return url;
}
public static bool IsValidDidWebAuthority(string authority)
{
if (string.IsNullOrEmpty(authority)) return false;
if (!authority.All(static c => c <= 127)) return false;
foreach (char ch in authority)
{
if (ch is '/' or '\\' or '?' or '#' or '@' or '%' or '[' or ']')
{
return false;
}
}
string host = authority;
string? portText = null;
int colonCount = authority.Count(static c => c == ':');
if (colonCount > 1)
{
return false;
}
int colonIndex = authority.LastIndexOf(':');
if (colonIndex > 0)
{
host = authority.Substring(0, colonIndex);
portText = authority.Substring(colonIndex + 1);
if (string.IsNullOrEmpty(host) || string.IsNullOrEmpty(portText)) return false;
if (!int.TryParse(portText, out int port) || port < 1 || port > 65535) return false;
}
string hostLower = host.ToLowerInvariant();
if (hostLower == "localhost" || hostLower.EndsWith(".localhost", StringComparison.Ordinal))
{
return false;
}
if (IPAddress.TryParse(hostLower, out IPAddress? ipAddress))
{
return IsPublicIp(ipAddress);
}
return IsValidHandle(hostLower);
}
public static bool IsValidDidWebPathSegment(string segment)
{
if (string.IsNullOrEmpty(segment)) return false;
if (segment == "." || segment == "..") return false;
if (!segment.All(static c => c <= 127)) return false;
for (int i = 0; i < segment.Length; i++)
{
char ch = segment[i];
if (ch == '%')
{
if (i + 2 >= segment.Length) return false;
if (!Uri.IsHexDigit(segment[i + 1]) || !Uri.IsHexDigit(segment[i + 2])) return false;
i += 2;
continue;
}
bool isAllowed = char.IsAsciiLetterOrDigit(ch)
|| ch == '-'
|| ch == '_'
|| ch == '.'
|| ch == '~';
if (!isAllowed) return false;
}
return true;
}
public static string? ExtractPdsHostFromEndpoint(string endpoint)
{
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out Uri? parsed)) return null;
if (parsed.Scheme != Uri.UriSchemeHttp && parsed.Scheme != Uri.UriSchemeHttps)
{
return null;
}
if (!string.IsNullOrEmpty(parsed.UserInfo)) return null;
if (!string.IsNullOrEmpty(parsed.Query)) return null;
if (!string.IsNullOrEmpty(parsed.Fragment)) return null;
if (parsed.AbsolutePath != "/") return null;
if (string.IsNullOrEmpty(parsed.Host)) return null;
string host = parsed.Host.ToLowerInvariant();
if (host == "localhost" || host.EndsWith(".localhost", StringComparison.Ordinal))
{
return null;
}
if (IPAddress.TryParse(host, out IPAddress? ipAddress))
{
if (!IsPublicIp(ipAddress)) return null;
}
else if (!IsValidHandle(host))
{
return null;
}
if (!parsed.IsDefaultPort)
{
return $"{host}:{parsed.Port}";
}
return host;
}
public static bool IsPublicIp(IPAddress ipAddress)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
byte[] bytes = ipAddress.GetAddressBytes();
// 10.0.0.0/8
if (bytes[0] == 10) return false;
// 172.16.0.0/12
if (bytes[0] == 172 && bytes[1] >= 16 && bytes[1] <= 31) return false;
// 192.168.0.0/16
if (bytes[0] == 192 && bytes[1] == 168) return false;
// 169.254.0.0/16 (link-local)
if (bytes[0] == 169 && bytes[1] == 254) return false;
// 127.0.0.0/8 (loopback)
if (bytes[0] == 127) return false;
// 0.0.0.0/8 (unspecified)
if (bytes[0] == 0) return false;
return true;
}
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
if (IPAddress.IsLoopback(ipAddress)) return false;
if (ipAddress.Equals(IPAddress.IPv6None)) return false;
if (ipAddress.Equals(IPAddress.IPv6Any)) return false;
if (ipAddress.IsIPv6LinkLocal) return false;
byte[] bytes = ipAddress.GetAddressBytes();
// fc00::/7 unique local
if ((bytes[0] & 0xFE) == 0xFC) return false;
return true;
}
return false;
}
#endregion
#region SENDREQ
/// <summary>
/// Many calls to the Bluesky APIs follow the same pattern. This function implements that pattern.
/// You'll see this being called in commands like "GetUnreadCount" and "ResolveHandle".
/// If user specifies an output file, the response is written to that file.
/// </summary>
/// <param name="url"></param>
/// <param name="getOrPut"></param>
/// <param name="accessJwt"></param>
/// <param name="contentType"></param>
/// <param name="content"></param>
/// <param name="outputFilePath"></param>
/// <returns></returns>
public static JsonNode? SendRequest(string url, HttpMethod getOrPut, string? accessJwt = null, string contentType = "application/json", StringContent? content = null, bool parseJsonResponse = true, string? outputFilePath = null, string? acceptHeader = null, string? userAgent = "dnproto", string? labelers = null, string? basicAuth = null, bool writeMetadataFile = false)
{
StringBuilder logLine = new StringBuilder($"[SEND REQUEST] {url}");
DateTime startTime = DateTime.UtcNow;
try
{
using (HttpClient client = new HttpClient())
{
//
// Set up request
//
var request = new HttpRequestMessage(getOrPut, url);
if (content != null)
{
request.Content = content;
request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
}
if (accessJwt != null)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessJwt);
}
if (!string.IsNullOrEmpty(basicAuth))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", basicAuth);
}
if (!string.IsNullOrEmpty(acceptHeader))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));
}
if (!string.IsNullOrEmpty(userAgent))
{
request.Headers.UserAgent.TryParseAdd(userAgent);
}
if (!string.IsNullOrEmpty(labelers))
{
request.Headers.Add("Atproto-Accept-Labelers", labelers);
}
Logger.LogTrace($"REQUEST:\n{request}");
//
// Send
//
HttpResponseMessage? response = null;
try
{
response = client.Send(request);
}
catch (Exception ex)
{
Logger.LogError($"Exception sending request: {ex.Message}");
return null;
}
if (response == null)
{
Logger.LogError("In SendRequest, response is null.");
return null;
}
Logger.LogTrace($"RESPONSE: {response}");
bool succeeded = response.StatusCode == HttpStatusCode.OK;
if (!succeeded)
{
Logger.LogError($"Request failed with status code: {response.StatusCode} url: {url}");
}
//
// If user wants json, parse that.
//
JsonNode? jsonResponse = null;
if (parseJsonResponse)
{
using (var reader = new StreamReader(response.Content.ReadAsStream()))
{
var responseText = reader.ReadToEnd();
if (string.IsNullOrEmpty(responseText) == false)
{
try
{
jsonResponse = JsonNode.Parse(responseText);
}
catch
{
//
}
}
}
}
//
// If the user has specified an output file, write the response to that file.
//
if (string.IsNullOrEmpty(outputFilePath) == false && succeeded)
{
Logger.LogTrace($"writing to: {outputFilePath}");
if (parseJsonResponse)
{
JsonData.WriteJsonToFile(jsonResponse, outputFilePath);
}
else
{
using (var responseStream = response.Content.ReadAsStream())
{
using (var fs = new FileStream(outputFilePath, FileMode.Create))
{
responseStream.CopyTo(fs);
}
}
}
}
//
// User wants metadata file?
//
if (string.IsNullOrEmpty(outputFilePath) == false
&& writeMetadataFile
&& succeeded)
{
string metadataFilePath = outputFilePath + ".metadata.json";
Logger.LogTrace($"writing metadata to: {metadataFilePath}");
var metadata = new JsonObject
{
["statusCode"] = (int)response.StatusCode,
["contentType"] = response.Content.Headers.ContentType?.ToString() ?? "",
["contentLength"] = response.Content.Headers.ContentLength ?? 0,
};
JsonData.WriteJsonToFile(metadata, metadataFilePath);
}
return jsonResponse;
}
}
finally
{
DateTime endTime = DateTime.UtcNow;
TimeSpan duration = endTime - startTime;
logLine.Append($" [{duration.TotalMilliseconds:F2}ms]");
Logger.LogInfo(logLine.ToString());
}
}
/// <summary>
/// Streaming version of SendRequest that writes to disk as data is received.
/// Useful for large file downloads where you don't want to buffer the entire response in memory.
/// </summary>
/// <param name="url">The URL to send the request to.</param>
/// <param name="getOrPut">The HTTP method to use.</param>
/// <param name="outputFilePath">The file path to write the response to.</param>
/// <param name="accessJwt">Optional access JWT for authentication.</param>
/// <param name="acceptHeader">Optional Accept header value.</param>
/// <param name="userAgent">Optional User-Agent header value.</param>
/// <param name="basicAuth">Optional Basic auth credentials (base64 encoded).</param>
/// <param name="bufferSize">Size of the buffer for streaming (default 81920 bytes).</param>
/// <returns>True if the request succeeded and file was written, false otherwise.</returns>
public static bool SendRequestStreaming(string url, HttpMethod getOrPut, string outputFilePath, string? accessJwt = null, string? acceptHeader = null, string? userAgent = "dnproto", string? basicAuth = null, int bufferSize = 81920)
{
StringBuilder logLine = new StringBuilder($"[SEND REQUEST STREAMING] {url}");
DateTime startTime = DateTime.UtcNow;
try
{
if (string.IsNullOrEmpty(outputFilePath))
{
Logger.LogError("SendRequestStreaming: outputFilePath is required.");
return false;
}
using (HttpClient client = new HttpClient())
{
//
// Set up request
//
var request = new HttpRequestMessage(getOrPut, url);
if (accessJwt != null)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessJwt);
}
if (!string.IsNullOrEmpty(basicAuth))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", basicAuth);
}
if (!string.IsNullOrEmpty(acceptHeader))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));
}
if (!string.IsNullOrEmpty(userAgent))
{
request.Headers.UserAgent.TryParseAdd(userAgent);
}
Logger.LogTrace($"REQUEST:\n{request}");
//
// Send request with ResponseHeadersRead to enable streaming
//
HttpResponseMessage? response = null;
try
{
response = client.Send(request, HttpCompletionOption.ResponseHeadersRead);
}
catch (Exception ex)
{
Logger.LogError($"Exception sending request: {ex.Message}");
return false;
}
if (response == null)
{
Logger.LogError("In SendRequestStreaming, response is null.");
return false;
}
Logger.LogTrace($"RESPONSE: {response}");
bool succeeded = response.StatusCode == HttpStatusCode.OK;
if (!succeeded)
{
Logger.LogError($"Request failed with status code: {response.StatusCode} url: {url}");
return false;
}
//
// Stream response directly to file
//
try
{
Logger.LogTrace($"Streaming to: {outputFilePath}");
long totalBytesRead = 0;
long? contentLength = response.Content.Headers.ContentLength;
using (var responseStream = response.Content.ReadAsStream())
using (var fileStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize, FileOptions.SequentialScan))
{
byte[] buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, bytesRead);