using System; using System.Collections.Generic; using System.Net.Http; using System.Text.Json; using System.Text.Json.Serialization.Metadata; using System.Threading; using System.Threading.Tasks; using CarpaNet; using CarpaNet.Auth; using CarpaNet.Http; using CarpaNet.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; namespace CarpaNet.OAuth; /// /// Represents an authenticated OAuth session. /// public sealed class ATProtoOAuthClient : IATProtoClient, IDisposable { private readonly DPoPTokenProvider _tokenProvider; private readonly HttpClient _httpClient; private readonly JsonSerializerOptions _jsonOptions; private readonly IdentityResolver? _identityResolver; private readonly ILogger _logger; private bool _disposed; private readonly OAuthSession _session; /// /// Gets the user's DID. /// public string Did { get; } /// /// Gets the PDS URL. /// public Uri BaseUrl { get; } /// /// Gets the application state that was passed to the authorize call. /// public string? AppState { get; } /// /// Gets whether the session is authenticated. /// public bool IsAuthenticated => _tokenProvider.HasValidToken; /// /// Gets the authenticated DID. /// public string? AuthenticatedDid => Did; /// /// Gets the token provider for this session. /// public ITokenProvider TokenProvider => _tokenProvider; /// public HttpClient HttpClient => _httpClient; /// /// Gets the identity resolver for handle/DID resolution. /// public IdentityResolver? IdentityResolver => _identityResolver; /// /// Gets the list of labeler DIDs whose labels should be included in responses. /// public IReadOnlyList? LabelerDids { get; } internal ATProtoOAuthClient( string did, string pdsUrl, DPoPTokenProvider tokenProvider, OAuthSession session, string? appState, IdentityResolver identityResolver, JsonSerializerOptions? jsonOptions = null, IReadOnlyList? labelerDids = null, ILoggerFactory? loggerFactory = null) { Did = did ?? throw new ArgumentNullException(nameof(did)); BaseUrl = new Uri(pdsUrl); _tokenProvider = tokenProvider ?? throw new ArgumentNullException(nameof(tokenProvider)); _session = session ?? throw new ArgumentNullException(nameof(session)); AppState = appState; LabelerDids = labelerDids; _httpClient = new HttpClient(); var factory = loggerFactory ?? NullLoggerFactory.Instance; _logger = factory.CreateLogger(); _identityResolver = identityResolver; _jsonOptions = jsonOptions ?? new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull }; } /// public async Task GetAsync( string nsid, IReadOnlyDictionary? parameters = null, CancellationToken cancellationToken = default) { ThrowIfDisposed(); _logger.LogDebug("OAuth GET {Nsid}", nsid); var url = (await XrpcHttpHandler.BuildUrlAsync(BaseUrl, nsid, parameters, _identityResolver, cancellationToken).ConfigureAwait(false)).ToString(); using var request = await _tokenProvider.CreateDPoPRequestAsync(HttpMethod.Get, url).ConfigureAwait(false); XrpcHttpHandler.AddCommonHeaders(request, null, LabelerDids); var response = await SendWithRetryAsync(request, url, cancellationToken).ConfigureAwait(false); return await XrpcHttpHandler.ProcessResponseAsync(response, _jsonOptions, cancellationToken).ConfigureAwait(false); } /// public async Task GetAsync( string nsid, string proxyServiceDid, IReadOnlyDictionary? parameters = null, CancellationToken cancellationToken = default) { ThrowIfDisposed(); var url = (await XrpcHttpHandler.BuildUrlAsync(BaseUrl, nsid, parameters, _identityResolver, cancellationToken).ConfigureAwait(false)).ToString(); using var request = await _tokenProvider.CreateDPoPRequestAsync(HttpMethod.Get, url).ConfigureAwait(false); XrpcHttpHandler.AddCommonHeaders(request, proxyServiceDid, LabelerDids); var response = await SendWithRetryAsync(request, url, cancellationToken).ConfigureAwait(false); return await XrpcHttpHandler.ProcessResponseAsync(response, _jsonOptions, cancellationToken).ConfigureAwait(false); } /// public async Task PostAsync( string nsid, TInput? input, CancellationToken cancellationToken = default) { ThrowIfDisposed(); _logger.LogDebug("OAuth POST {Nsid}", nsid); var url = XrpcHttpHandler.BuildUrl(BaseUrl, nsid).ToString(); using var request = await _tokenProvider.CreateDPoPRequestAsync(HttpMethod.Post, url).ConfigureAwait(false); XrpcHttpHandler.AddCommonHeaders(request, null, LabelerDids); if (input != null) { var typeInfo = (JsonTypeInfo)_jsonOptions.GetTypeInfo(typeof(TInput)); var json = JsonSerializer.Serialize(input, typeInfo); request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); } var response = await SendWithRetryAsync(request, url, cancellationToken).ConfigureAwait(false); return await XrpcHttpHandler.ProcessResponseAsync(response, _jsonOptions, cancellationToken).ConfigureAwait(false); } /// public async Task PostAsync( string nsid, string proxyServiceDid, TInput? input, CancellationToken cancellationToken = default) { ThrowIfDisposed(); var url = XrpcHttpHandler.BuildUrl(BaseUrl, nsid).ToString(); using var request = await _tokenProvider.CreateDPoPRequestAsync(HttpMethod.Post, url).ConfigureAwait(false); XrpcHttpHandler.AddCommonHeaders(request, proxyServiceDid, LabelerDids); if (input != null) { var typeInfo = (JsonTypeInfo)_jsonOptions.GetTypeInfo(typeof(TInput)); var json = JsonSerializer.Serialize(input, typeInfo); request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); } var response = await SendWithRetryAsync(request, url, cancellationToken).ConfigureAwait(false); return await XrpcHttpHandler.ProcessResponseAsync(response, _jsonOptions, cancellationToken).ConfigureAwait(false); } /// public IAsyncEnumerable SubscribeAsync( string nsid, IReadOnlyDictionary? parameters = null, CancellationToken cancellationToken = default) { ThrowIfDisposed(); // For now, subscriptions don't support OAuth // The EventStreamClient would need DPoP support throw new NotSupportedException("Subscriptions are not yet supported with OAuth sessions."); } /// /// Signs out of the session. /// public async Task SignOutAsync(CancellationToken cancellationToken = default) { ThrowIfDisposed(); _logger.LogInformation("Signing out OAuth session"); await _session.RevokeAsync(Did, cancellationToken).ConfigureAwait(false); Dispose(); } private async Task SendWithRetryAsync( HttpRequestMessage request, string url, CancellationToken cancellationToken) { var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); _tokenProvider.UpdateNonceFromResponse(response, url); // Handle 401 with token refresh if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { _logger.LogWarning("Received 401, refreshing DPoP token and retrying"); // Try to refresh the token await _tokenProvider.RefreshAsync(cancellationToken).ConfigureAwait(false); // Create a new request (can't reuse the old one) using var retryRequest = await _tokenProvider.CreateDPoPRequestAsync(request.Method, url).ConfigureAwait(false); if (request.Content != null) { // Clone content var contentBytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false); retryRequest.Content = new ByteArrayContent(contentBytes); foreach (var header in request.Content.Headers) { retryRequest.Content.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Copy custom headers foreach (var header in request.Headers) { if (header.Key != "Authorization" && header.Key != "DPoP") { retryRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } response.Dispose(); response = await _httpClient.SendAsync(retryRequest, cancellationToken).ConfigureAwait(false); _tokenProvider.UpdateNonceFromResponse(response, url); } return response; } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(ATProtoOAuthClient)); } } /// public void Dispose() { if (_disposed) { return; } _disposed = true; _tokenProvider.Dispose(); _identityResolver?.Dispose(); _httpClient.Dispose(); } }