Something went wrong. Try again.
.NET ATProtocol Library - Built for Source Gen
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net.Http;using System.Text.Json;using System.Threading;using System.Threading.Tasks;
namespace CarpaNet.BuildTasks;
/// <summary>/// Resolves ATProtocol lexicon schemas from the network./// Pipeline: DNS TXT lookup → DID resolution → PDS URL → fetch XRPC record./// </summary>internal sealed class LexiconResolver : IDisposable{ private readonly HttpClient _httpClient; private readonly LexiconDnsResolver _dnsResolver; private readonly string _plcDirectoryUrl; private readonly Action<string> _logInfo; private readonly Action<string> _logWarning;
public LexiconResolver( string plcDirectoryUrl = "https://plc.directory", string[]? dnsServers = null, Action<string>? logInfo = null, Action<string>? logWarning = null) { _httpClient = new HttpClient(); _httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); _httpClient.DefaultRequestHeaders.Add("User-Agent", "CarpaNet.BuildTasks/1.0"); _dnsResolver = new LexiconDnsResolver(dnsServers); _plcDirectoryUrl = plcDirectoryUrl.TrimEnd('/'); _logInfo = logInfo ?? (_ => { }); _logWarning = logWarning ?? (_ => { }); }
/// <summary> /// Resolves a single NSID to its lexicon JSON content. /// </summary> public async Task<string> ResolveNsidAsync(string nsid, CancellationToken cancellationToken = default) { // Step 1: DNS TXT lookup for the authority var dnsName = NsidAuthority.NsidToDnsName(nsid); _logInfo($"Looking up DNS TXT record: {dnsName}");
var did = await ResolveDnsToDidAsync(dnsName, cancellationToken).ConfigureAwait(false); if (did == null) throw new LexiconResolutionException($"No DID found in DNS TXT record for '{dnsName}' (NSID: {nsid})");
_logInfo($"Resolved DID: {did}");
// Step 2: Resolve DID to PDS endpoint var pdsUrl = await ResolveDidToPdsAsync(did, cancellationToken).ConfigureAwait(false); if (pdsUrl == null) throw new LexiconResolutionException($"No PDS endpoint found for DID '{did}' (NSID: {nsid})");
_logInfo($"Resolved PDS: {pdsUrl}");
// Step 3: Fetch the lexicon record from the PDS var lexiconJson = await FetchLexiconRecordAsync(pdsUrl, did, nsid, cancellationToken).ConfigureAwait(false);
return lexiconJson; }
/// <summary> /// Resolves multiple NSIDs, grouping by authority to minimize DNS lookups. /// Returns a dictionary of NSID → lexicon JSON. /// </summary> public async Task<Dictionary<string, string>> ResolveMultipleAsync( IEnumerable<string> nsids, CancellationToken cancellationToken = default) { var results = new Dictionary<string, string>();
// Group by authority to share DNS + DID resolution var groups = nsids.GroupBy(NsidAuthority.GetAuthority);
foreach (var group in groups) { var authority = group.Key; var dnsName = NsidAuthority.AuthorityToDnsName(authority); _logInfo($"Resolving authority '{authority}' via DNS: {dnsName}");
string? did; string? pdsUrl;
try { did = await ResolveDnsToDidAsync(dnsName, cancellationToken).ConfigureAwait(false); if (did == null) throw new LexiconResolutionException($"No DID found in DNS TXT record for '{dnsName}'");
pdsUrl = await ResolveDidToPdsAsync(did, cancellationToken).ConfigureAwait(false); if (pdsUrl == null) throw new LexiconResolutionException($"No PDS endpoint found for DID '{did}'"); } catch (Exception ex) { // Re-throw with all affected NSIDs var affectedNsids = string.Join(", ", group); throw new LexiconResolutionException( $"Failed to resolve authority '{authority}' for NSIDs: {affectedNsids}. {ex.Message}", ex); }
foreach (var nsid in group) { cancellationToken.ThrowIfCancellationRequested();
try { var json = await FetchLexiconRecordAsync(pdsUrl, did, nsid, cancellationToken).ConfigureAwait(false); results[nsid] = json; _logInfo($"Resolved lexicon: {nsid}"); } catch (Exception ex) { throw new LexiconResolutionException( $"Failed to fetch lexicon record for '{nsid}' from {pdsUrl}. {ex.Message}", ex); } } }
return results; }
/// <summary> /// Enumerates all lexicon records published by an authority using com.atproto.repo.listRecords. /// Returns a dictionary of NSID → lexicon JSON. /// </summary> public async Task<Dictionary<string, string>> ResolveAuthorityAsync( string authority, CancellationToken cancellationToken = default) { // Step 1: DNS TXT lookup for the authority var dnsName = NsidAuthority.AuthorityToDnsName(authority); _logInfo($"Looking up DNS TXT record: {dnsName}");
var did = await ResolveDnsToDidAsync(dnsName, cancellationToken).ConfigureAwait(false); if (did == null) throw new LexiconResolutionException($"No DID found in DNS TXT record for '{dnsName}' (authority: {authority})");
_logInfo($"Resolved DID: {did}");
return await ResolveDidAsync(did, cancellationToken).ConfigureAwait(false); }
/// <summary> /// Resolves an AT Protocol handle to a DID, then enumerates all lexicon records. /// Resolution strategy: DNS TXT (_atproto.{handle}) first, HTTPS well-known fallback. /// </summary> public async Task<Dictionary<string, string>> ResolveHandleAsync( string handle, CancellationToken cancellationToken = default) { _logInfo($"Resolving handle: {handle}");
var did = await ResolveHandleToDidAsync(handle, cancellationToken).ConfigureAwait(false); if (did == null) throw new LexiconResolutionException($"Could not resolve handle '{handle}' to a DID (tried DNS TXT and HTTPS well-known)");
_logInfo($"Handle '{handle}' resolved to DID: {did}");
return await ResolveDidAsync(did, cancellationToken).ConfigureAwait(false); }
/// <summary> /// Resolves an AT Protocol handle to a DID using DNS TXT first, then HTTPS fallback. /// </summary> private async Task<string?> ResolveHandleToDidAsync(string handle, CancellationToken cancellationToken) { // Try DNS TXT first: _atproto.{handle} var did = await TryResolveHandleDnsAsync(handle, cancellationToken).ConfigureAwait(false); if (did != null) { _logInfo($"Handle '{handle}' resolved via DNS TXT"); return did; }
// Fallback: HTTPS well-known did = await TryResolveHandleHttpsAsync(handle, cancellationToken).ConfigureAwait(false); if (did != null) { _logInfo($"Handle '{handle}' resolved via HTTPS well-known"); return did; }
return null; }
/// <summary> /// Attempts handle resolution via DNS TXT record at _atproto.{handle}. /// </summary> private async Task<string?> TryResolveHandleDnsAsync(string handle, CancellationToken cancellationToken) { try { var dnsName = $"_atproto.{handle}"; return await ResolveDnsToDidAsync(dnsName, cancellationToken).ConfigureAwait(false); } catch { return null; } }
/// <summary> /// Attempts handle resolution via HTTPS GET https://{handle}/.well-known/atproto-did. /// </summary> private async Task<string?> TryResolveHandleHttpsAsync(string handle, CancellationToken cancellationToken) { try { var url = $"https://{handle}/.well-known/atproto-did"; var response = await _httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false); if (!response.IsSuccessStatusCode) return null;
var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); var did = body.Trim();
if (did.StartsWith("did:", StringComparison.OrdinalIgnoreCase)) return did;
return null; } catch { return null; } }
/// <summary> /// Enumerates all lexicon records published by a DID using com.atproto.repo.listRecords. /// Skips DNS resolution and goes directly to DID → PDS → listRecords. /// </summary> public async Task<Dictionary<string, string>> ResolveDidAsync( string did, CancellationToken cancellationToken = default) { _logInfo($"Resolving DID directly: {did}");
// Resolve DID to PDS endpoint var pdsUrl = await ResolveDidToPdsAsync(did, cancellationToken).ConfigureAwait(false); if (pdsUrl == null) throw new LexiconResolutionException($"No PDS endpoint found for DID '{did}'");
_logInfo($"Resolved PDS: {pdsUrl}");
return await EnumerateLexiconRecordsAsync(pdsUrl, did, cancellationToken).ConfigureAwait(false); }
/// <summary> /// Enumerates all lexicon records from a PDS via com.atproto.repo.listRecords with pagination. /// </summary> private async Task<Dictionary<string, string>> EnumerateLexiconRecordsAsync( string pdsUrl, string did, CancellationToken cancellationToken) { var results = new Dictionary<string, string>(); string? cursor = null;
do { cancellationToken.ThrowIfCancellationRequested();
var url = $"{pdsUrl}/xrpc/com.atproto.repo.listRecords" + $"?repo={Uri.EscapeDataString(did)}" + $"&collection=com.atproto.lexicon.schema" + $"&limit=100";
if (cursor != null) url += $"&cursor={Uri.EscapeDataString(cursor)}";
var response = await _httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode();
var responseJson = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); using var doc = JsonDocument.Parse(responseJson); var root = doc.RootElement;
if (root.TryGetProperty("records", out var records) && records.ValueKind == JsonValueKind.Array) { foreach (var record in records.EnumerateArray()) { // Extract NSID from the URI (at://{did}/com.atproto.lexicon.schema/{rkey}) // The rkey is the NSID string? nsid = null; if (record.TryGetProperty("uri", out var uriProp)) { var uri = uriProp.GetString(); if (uri != null) { var lastSlash = uri.LastIndexOf('/'); if (lastSlash >= 0) nsid = uri.Substring(lastSlash + 1); } }
if (nsid != null && record.TryGetProperty("value", out var value)) { results[nsid] = value.GetRawText(); _logInfo($"Discovered lexicon: {nsid}"); } } }
// Check for next page cursor = null; if (root.TryGetProperty("cursor", out var cursorProp) && cursorProp.ValueKind == JsonValueKind.String) { cursor = cursorProp.GetString(); } } while (cursor != null);
_logInfo($"Discovered {results.Count} lexicons for DID '{did}'"); return results; }
private async Task<string?> ResolveDnsToDidAsync(string dnsName, CancellationToken cancellationToken) { var records = await _dnsResolver.GetTxtRecordsAsync(dnsName, cancellationToken).ConfigureAwait(false);
foreach (var record in records) { var trimmed = record.Trim(); if (trimmed.StartsWith("did=", StringComparison.OrdinalIgnoreCase)) { var did = trimmed.Substring(4); if (did.StartsWith("did:", StringComparison.OrdinalIgnoreCase)) return did; } }
return null; }
private async Task<string?> ResolveDidToPdsAsync(string did, CancellationToken cancellationToken) { string didDocJson;
if (did.StartsWith("did:plc:", StringComparison.OrdinalIgnoreCase)) { var url = $"{_plcDirectoryUrl}/{did}"; var response = await _httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); didDocJson = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); } else if (did.StartsWith("did:web:", StringComparison.OrdinalIgnoreCase)) { var domain = Uri.UnescapeDataString(did.Substring(8)); var url = $"https://{domain}/.well-known/did.json"; var response = await _httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); didDocJson = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); } else { throw new LexiconResolutionException($"Unsupported DID method: {did}"); }
// Parse the DID document to find the PDS service endpoint return ExtractPdsEndpoint(didDocJson); }
private static string? ExtractPdsEndpoint(string didDocJson) { using var doc = JsonDocument.Parse(didDocJson); var root = doc.RootElement;
if (!root.TryGetProperty("service", out var services) || services.ValueKind != JsonValueKind.Array) return null;
foreach (var svc in services.EnumerateArray()) { var type = svc.TryGetProperty("type", out var typeProp) ? typeProp.GetString() : null; var id = svc.TryGetProperty("id", out var idProp) ? idProp.GetString() : null;
if (type == "AtprotoPersonalDataServer" || (id != null && id.EndsWith("#atproto_pds", StringComparison.Ordinal))) { if (svc.TryGetProperty("serviceEndpoint", out var endpoint)) return endpoint.GetString()?.TrimEnd('/'); } }
return null; }
private async Task<string> FetchLexiconRecordAsync( string pdsUrl, string did, string nsid, CancellationToken cancellationToken) { var url = $"{pdsUrl}/xrpc/com.atproto.repo.getRecord" + $"?repo={Uri.EscapeDataString(did)}" + $"&collection=com.atproto.lexicon.schema" + $"&rkey={Uri.EscapeDataString(nsid)}";
var response = await _httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode();
var responseJson = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
// The lexicon JSON is inside the "value" field of the getRecord response using var doc = JsonDocument.Parse(responseJson); if (!doc.RootElement.TryGetProperty("value", out var value)) throw new LexiconResolutionException($"Response for '{nsid}' missing 'value' field");
return value.GetRawText(); }
public void Dispose() { _httpClient.Dispose(); }}
/// <summary>/// Exception thrown when lexicon resolution fails./// </summary>internal sealed class LexiconResolutionException : Exception{ public LexiconResolutionException(string message) : base(message) { } public LexiconResolutionException(string message, Exception innerException) : base(message, innerException) { }}