using System;
using System.Text.Json.Serialization;
namespace CarpaNet.OAuth;
///
/// OAuth 2.0 Token Response.
///
public sealed class OAuthTokenResponse
{
///
/// The access token.
///
[JsonPropertyName("access_token")]
public string AccessToken { get; set; } = string.Empty;
///
/// The token type (always "DPoP" for ATProto).
///
[JsonPropertyName("token_type")]
public string TokenType { get; set; } = "DPoP";
///
/// The lifetime in seconds of the access token.
///
[JsonPropertyName("expires_in")]
public int? ExpiresIn { get; set; }
///
/// The refresh token.
///
[JsonPropertyName("refresh_token")]
public string? RefreshToken { get; set; }
///
/// The scope of the access token.
///
[JsonPropertyName("scope")]
public string? Scope { get; set; }
///
/// The subject (user DID) for ATProto tokens.
///
[JsonPropertyName("sub")]
public string? Sub { get; set; }
}
///
/// Internal token set with additional metadata.
///
public sealed class TokenSet
{
///
/// The authorization server issuer.
///
public string Issuer { get; set; } = string.Empty;
///
/// The subject (user DID).
///
public string Sub { get; set; } = string.Empty;
///
/// The audience (PDS URL).
///
public string Audience { get; set; } = string.Empty;
///
/// The granted scope.
///
public string Scope { get; set; } = string.Empty;
///
/// The access token.
///
public string AccessToken { get; set; } = string.Empty;
///
/// The refresh token.
///
public string? RefreshToken { get; set; }
///
/// When the access token expires.
///
public DateTimeOffset? ExpiresAt { get; set; }
///
/// Creates a TokenSet from an OAuth token response.
///
public static TokenSet FromResponse(OAuthTokenResponse response, string issuer, string audience)
{
var expiresAt = response.ExpiresIn.HasValue
? DateTimeOffset.UtcNow.AddSeconds(response.ExpiresIn.Value)
: (DateTimeOffset?)null;
return new TokenSet
{
Issuer = issuer,
Sub = response.Sub ?? string.Empty,
Audience = audience,
Scope = response.Scope ?? "atproto",
AccessToken = response.AccessToken,
RefreshToken = response.RefreshToken,
ExpiresAt = expiresAt
};
}
///
/// Whether the token is expired or will expire within the buffer time.
///
public bool IsExpired(TimeSpan buffer = default)
{
if (!ExpiresAt.HasValue)
{
return false; // No expiry info, assume valid
}
return DateTimeOffset.UtcNow >= ExpiresAt.Value - buffer;
}
}