this repo has no description

further updates

+3523 -80
+104 -9
Sources/CoreATProtocol/APEnvironment.swift
··· 5 5 // Created by Thomas Rademaker on 10/10/25. 6 6 // 7 7 8 + import Foundation 8 9 import OAuthenticator 9 10 10 11 @APActor 11 12 public class APEnvironment { 12 13 public static var current: APEnvironment = APEnvironment() 13 - 14 + 15 + // MARK: - Connection Configuration 14 16 public var host: String? 17 + 18 + // MARK: - Authentication Tokens 15 19 public var accessToken: String? 16 20 public var refreshToken: String? 17 21 public var login: Login? 22 + 23 + // MARK: - DPoP Support 18 24 public var dpopProofGenerator: DPoPSigner.JWTGenerator? 19 25 public var resourceServerNonce: String? 26 + public let resourceDPoPSigner = DPoPSigner() 27 + 28 + // MARK: - OAuth Configuration (for token refresh) 29 + public var serverMetadata: ServerMetadata? 30 + public var clientId: String? 31 + public var authState: AuthenticationState? 32 + public var tokenStorage: TokenStorageProtocol? 33 + 34 + // MARK: - Identity 35 + public var resolvedIdentity: IdentityResolver.ResolvedIdentity? 36 + public let identityResolver = IdentityResolver() 37 + 38 + // MARK: - Delegates and Callbacks 20 39 public var atProtocoldelegate: CoreATProtocolDelegate? 21 40 public let routerDelegate = APRouterDelegate() 22 - public let resourceDPoPSigner = DPoPSigner() 23 - 41 + 42 + // MARK: - State Flags 43 + private var isRefreshing = false 44 + 24 45 private init() {} 25 - 26 - // func setup(apiKey: String, apiSecret: String, userAgent: String) { 27 - // self.apiKey = apiKey 28 - // self.apiSecret = apiSecret 29 - // self.userAgent = userAgent 30 - // } 46 + 47 + // MARK: - Token Refresh 48 + 49 + /// Checks if the current access token needs refresh. 50 + public var needsTokenRefresh: Bool { 51 + if let state = authState { 52 + return state.isAccessTokenExpired 53 + } 54 + // If no auth state, check login object 55 + if let login = login { 56 + return !login.accessToken.valid 57 + } 58 + return false 59 + } 60 + 61 + /// Attempts to refresh the access token if needed. 62 + /// Returns true if refresh succeeded or wasn't needed, false if refresh failed. 63 + public func refreshTokenIfNeeded() async -> Bool { 64 + guard needsTokenRefresh else { return true } 65 + 66 + // Prevent concurrent refresh attempts 67 + guard !isRefreshing else { return false } 68 + isRefreshing = true 69 + defer { isRefreshing = false } 70 + 71 + return await performTokenRefresh() 72 + } 73 + 74 + // MARK: - Configuration 75 + 76 + /// Configures the environment for OAuth with token refresh support. 77 + public func configureOAuth( 78 + serverMetadata: ServerMetadata, 79 + clientId: String, 80 + tokenStorage: TokenStorageProtocol? = nil 81 + ) { 82 + self.serverMetadata = serverMetadata 83 + self.clientId = clientId 84 + self.tokenStorage = tokenStorage 85 + } 86 + 87 + /// Stores the complete authentication state after successful login. 88 + public func setAuthenticationState(_ state: AuthenticationState) async { 89 + self.authState = state 90 + self.accessToken = state.accessToken 91 + self.refreshToken = state.refreshToken 92 + 93 + // Update host from PDS URL 94 + if let url = URL(string: state.pdsURL) { 95 + self.host = url.absoluteString 96 + } 97 + 98 + // Persist if storage is configured 99 + if let storage = tokenStorage { 100 + try? await storage.store(state) 101 + } 102 + } 103 + 104 + /// Restores authentication state from storage. 105 + public func restoreAuthenticationState() async -> Bool { 106 + guard let storage = tokenStorage else { return false } 107 + 108 + do { 109 + guard let state = try await storage.retrieve() else { 110 + return false 111 + } 112 + 113 + self.authState = state 114 + self.accessToken = state.accessToken 115 + self.refreshToken = state.refreshToken 116 + 117 + if let url = URL(string: state.pdsURL) { 118 + self.host = url.absoluteString 119 + } 120 + 121 + return true 122 + } catch { 123 + return false 124 + } 125 + } 31 126 }
+132 -3
Sources/CoreATProtocol/CoreATProtocol.swift
··· 3 3 4 4 @_exported import OAuthenticator 5 5 6 - public protocol CoreATProtocolDelegate: AnyObject {} 6 + /// Delegate protocol for receiving authentication and session lifecycle events. 7 + @MainActor 8 + public protocol CoreATProtocolDelegate: AnyObject, Sendable { 9 + /// Called when tokens have been refreshed. 10 + func tokensUpdated(accessToken: String, refreshToken: String?) async 11 + 12 + /// Called when a session has expired and re-authentication is required. 13 + func sessionExpired() async 14 + 15 + /// Called when authentication fails. 16 + func authenticationFailed(error: Error) async 7 17 18 + /// Called when DPoP nonce is updated from a server response. 19 + func dpopNonceUpdated(nonce: String) async 20 + } 21 + 22 + /// Default implementations for optional delegate methods. 23 + public extension CoreATProtocolDelegate { 24 + func tokensUpdated(accessToken: String, refreshToken: String?) async {} 25 + func sessionExpired() async {} 26 + func authenticationFailed(error: Error) async {} 27 + func dpopNonceUpdated(nonce: String) async {} 28 + } 29 + 30 + // MARK: - Setup Functions 31 + 32 + /// Configures the AT Protocol environment with basic authentication. 33 + /// - Parameters: 34 + /// - hostURL: The PDS host URL 35 + /// - accessJWT: Access token 36 + /// - refreshJWT: Refresh token 37 + /// - delegate: Optional delegate for receiving events 8 38 @APActor 9 39 public func setup(hostURL: String?, accessJWT: String?, refreshJWT: String?, delegate: CoreATProtocolDelegate? = nil) { 10 40 APEnvironment.current.host = hostURL ··· 13 43 APEnvironment.current.atProtocoldelegate = delegate 14 44 } 15 45 46 + /// Configures the AT Protocol environment with OAuth support. 47 + /// - Parameters: 48 + /// - serverMetadata: OAuth authorization server metadata 49 + /// - clientId: The client ID for this application 50 + /// - tokenStorage: Optional persistent storage for tokens 51 + /// - delegate: Optional delegate for receiving events 52 + @APActor 53 + public func setupOAuth( 54 + serverMetadata: ServerMetadata, 55 + clientId: String, 56 + tokenStorage: TokenStorageProtocol? = nil, 57 + delegate: CoreATProtocolDelegate? = nil 58 + ) { 59 + APEnvironment.current.configureOAuth( 60 + serverMetadata: serverMetadata, 61 + clientId: clientId, 62 + tokenStorage: tokenStorage 63 + ) 64 + APEnvironment.current.atProtocoldelegate = delegate 65 + } 66 + 67 + /// Sets the delegate for receiving authentication events. 16 68 @APActor 17 69 public func setDelegate(_ delegate: CoreATProtocolDelegate) { 18 70 APEnvironment.current.atProtocoldelegate = delegate 19 71 } 20 72 73 + /// Updates the stored tokens. 21 74 @APActor 22 75 public func updateTokens(access: String?, refresh: String?) { 23 76 APEnvironment.current.accessToken = access 24 77 APEnvironment.current.refreshToken = refresh 25 78 } 26 79 80 + /// Updates the host URL. 27 81 @APActor 28 82 public func update(hostURL: String?) { 29 83 APEnvironment.current.host = hostURL 30 84 } 31 85 86 + /// Applies a complete authentication context from a successful OAuth login. 87 + /// - Parameters: 88 + /// - login: The Login object from OAuthenticator 89 + /// - generator: DPoP JWT generator for signing requests 90 + /// - resourceNonce: Initial DPoP nonce from the resource server 91 + /// - serverMetadata: OAuth server metadata for token refresh 92 + /// - clientId: Client ID for token refresh 32 93 @APActor 33 - public func applyAuthenticationContext(login: Login, generator: @escaping DPoPSigner.JWTGenerator, resourceNonce: String? = nil) { 94 + public func applyAuthenticationContext( 95 + login: Login, 96 + generator: @escaping DPoPSigner.JWTGenerator, 97 + resourceNonce: String? = nil, 98 + serverMetadata: ServerMetadata? = nil, 99 + clientId: String? = nil 100 + ) { 34 101 APEnvironment.current.login = login 35 102 APEnvironment.current.accessToken = login.accessToken.value 36 103 APEnvironment.current.refreshToken = login.refreshToken?.value 37 104 APEnvironment.current.dpopProofGenerator = generator 38 105 APEnvironment.current.resourceServerNonce = resourceNonce 39 106 APEnvironment.current.resourceDPoPSigner.nonce = resourceNonce 107 + 108 + // Store OAuth configuration if provided (needed for token refresh) 109 + if let metadata = serverMetadata { 110 + APEnvironment.current.serverMetadata = metadata 111 + } 112 + if let id = clientId { 113 + APEnvironment.current.clientId = id 114 + } 40 115 } 41 116 117 + /// Clears all authentication context and tokens. 42 118 @APActor 43 - public func clearAuthenticationContext() { 119 + public func clearAuthenticationContext() async { 44 120 APEnvironment.current.login = nil 45 121 APEnvironment.current.dpopProofGenerator = nil 46 122 APEnvironment.current.resourceServerNonce = nil 47 123 APEnvironment.current.accessToken = nil 48 124 APEnvironment.current.refreshToken = nil 49 125 APEnvironment.current.resourceDPoPSigner.nonce = nil 126 + APEnvironment.current.authState = nil 127 + APEnvironment.current.resolvedIdentity = nil 128 + 129 + // Clear persistent storage if configured 130 + if let storage = APEnvironment.current.tokenStorage { 131 + try? await storage.clear() 132 + } 50 133 } 51 134 135 + /// Updates the resource server DPoP nonce. 52 136 @APActor 53 137 public func updateResourceDPoPNonce(_ nonce: String?) { 54 138 APEnvironment.current.resourceServerNonce = nonce 55 139 APEnvironment.current.resourceDPoPSigner.nonce = nonce 56 140 } 141 + 142 + // MARK: - Identity Resolution 143 + 144 + /// Resolves a handle to a complete identity with PDS and authorization server URLs. 145 + /// - Parameter handle: The handle to resolve (e.g., "alice.bsky.social") 146 + /// - Returns: Complete resolved identity information 147 + @APActor 148 + public func resolveIdentity(handle: String) async throws -> IdentityResolver.ResolvedIdentity { 149 + let identity = try await APEnvironment.current.identityResolver.resolveIdentity(handle: handle) 150 + APEnvironment.current.resolvedIdentity = identity 151 + APEnvironment.current.host = identity.pdsURL 152 + return identity 153 + } 154 + 155 + /// Resolves a DID to a complete identity with PDS and authorization server URLs. 156 + /// - Parameter did: The DID to resolve (e.g., "did:plc:abc123") 157 + /// - Returns: Complete resolved identity information 158 + @APActor 159 + public func resolveIdentity(did: String) async throws -> IdentityResolver.ResolvedIdentity { 160 + let identity = try await APEnvironment.current.identityResolver.resolveIdentity(did: did) 161 + APEnvironment.current.resolvedIdentity = identity 162 + APEnvironment.current.host = identity.pdsURL 163 + return identity 164 + } 165 + 166 + // MARK: - Session Management 167 + 168 + /// Attempts to restore a previous session from persistent storage. 169 + /// - Returns: true if a session was restored, false otherwise 170 + @APActor 171 + public func restoreSession() async -> Bool { 172 + return await APEnvironment.current.restoreAuthenticationState() 173 + } 174 + 175 + /// Checks if the current session is valid and has non-expired tokens. 176 + @APActor 177 + public var hasValidSession: Bool { 178 + if let state = APEnvironment.current.authState { 179 + return !state.isAccessTokenExpired || state.canRefresh 180 + } 181 + if let login = APEnvironment.current.login { 182 + return login.accessToken.valid || (login.refreshToken?.valid ?? false) 183 + } 184 + return APEnvironment.current.accessToken != nil 185 + }
+123
Sources/CoreATProtocol/Identity/DIDDocument.swift
··· 1 + // 2 + // DIDDocument.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Foundation 9 + 10 + /// Represents a DID Document as specified by the AT Protocol. 11 + /// DID Documents contain the public key and service endpoints for an identity. 12 + public struct DIDDocument: Codable, Sendable, Hashable { 13 + public let context: [String] 14 + public let id: String 15 + public let alsoKnownAs: [String]? 16 + public let verificationMethod: [VerificationMethod]? 17 + public let service: [Service]? 18 + 19 + enum CodingKeys: String, CodingKey { 20 + case context = "@context" 21 + case id 22 + case alsoKnownAs 23 + case verificationMethod 24 + case service 25 + } 26 + 27 + public init( 28 + context: [String] = ["https://www.w3.org/ns/did/v1"], 29 + id: String, 30 + alsoKnownAs: [String]? = nil, 31 + verificationMethod: [VerificationMethod]? = nil, 32 + service: [Service]? = nil 33 + ) { 34 + self.context = context 35 + self.id = id 36 + self.alsoKnownAs = alsoKnownAs 37 + self.verificationMethod = verificationMethod 38 + self.service = service 39 + } 40 + 41 + /// Extracts the handle from the alsoKnownAs field. 42 + /// Handles are stored as `at://handle` URIs. 43 + public var handle: String? { 44 + alsoKnownAs?.compactMap { uri -> String? in 45 + guard uri.hasPrefix("at://") else { return nil } 46 + return String(uri.dropFirst(5)) 47 + }.first 48 + } 49 + 50 + /// Extracts the PDS (Personal Data Server) endpoint from the service array. 51 + public var pdsEndpoint: String? { 52 + service?.first { $0.id == "#atproto_pds" || $0.type == "AtprotoPersonalDataServer" }?.serviceEndpoint 53 + } 54 + } 55 + 56 + /// Represents a verification method in a DID Document. 57 + public struct VerificationMethod: Codable, Sendable, Hashable { 58 + public let id: String 59 + public let type: String 60 + public let controller: String 61 + public let publicKeyMultibase: String? 62 + 63 + public init(id: String, type: String, controller: String, publicKeyMultibase: String? = nil) { 64 + self.id = id 65 + self.type = type 66 + self.controller = controller 67 + self.publicKeyMultibase = publicKeyMultibase 68 + } 69 + } 70 + 71 + /// Represents a service endpoint in a DID Document. 72 + public struct Service: Codable, Sendable, Hashable { 73 + public let id: String 74 + public let type: String 75 + public let serviceEndpoint: String 76 + 77 + public init(id: String, type: String, serviceEndpoint: String) { 78 + self.id = id 79 + self.type = type 80 + self.serviceEndpoint = serviceEndpoint 81 + } 82 + } 83 + 84 + /// Represents the response from a PLC directory lookup. 85 + public struct PLCDirectoryResponse: Codable, Sendable { 86 + public let did: String 87 + public let verificationMethods: [String: String]? 88 + public let rotationKeys: [String]? 89 + public let alsoKnownAs: [String]? 90 + public let services: [String: PLCService]? 91 + 92 + public struct PLCService: Codable, Sendable { 93 + public let type: String 94 + public let endpoint: String 95 + } 96 + 97 + /// Converts PLC response to standard DID Document format. 98 + public func toDIDDocument() -> DIDDocument { 99 + let verificationMethods = self.verificationMethods?.map { (id, key) in 100 + VerificationMethod( 101 + id: "\(did)\(id)", 102 + type: "Multikey", 103 + controller: did, 104 + publicKeyMultibase: key 105 + ) 106 + } 107 + 108 + let services = self.services?.map { (id, service) in 109 + Service( 110 + id: id, 111 + type: service.type, 112 + serviceEndpoint: service.endpoint 113 + ) 114 + } 115 + 116 + return DIDDocument( 117 + id: did, 118 + alsoKnownAs: alsoKnownAs, 119 + verificationMethod: verificationMethods, 120 + service: services 121 + ) 122 + } 123 + }
+334
Sources/CoreATProtocol/Identity/IdentityResolver.swift
··· 1 + // 2 + // IdentityResolver.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Foundation 9 + @preconcurrency import OAuthenticator 10 + 11 + /// Errors that can occur during identity resolution. 12 + public enum IdentityError: Error, Sendable { 13 + case invalidHandle(String) 14 + case invalidDID(String) 15 + case handleResolutionFailed(String) 16 + case didResolutionFailed(String) 17 + case pdsNotFound 18 + case authorizationServerNotFound 19 + case networkError(Error) 20 + case invalidURL(String) 21 + case bidirectionalVerificationFailed(handle: String, did: String) 22 + } 23 + 24 + /// Resolves AT Protocol identities (handles and DIDs) to their associated metadata. 25 + /// 26 + /// This resolver handles: 27 + /// - Handle to DID resolution via `.well-known/atproto-did` 28 + /// - DID document fetching for both `did:plc` and `did:web` methods 29 + /// - PDS (Personal Data Server) endpoint discovery 30 + /// - Authorization server metadata fetching 31 + /// - Bidirectional handle verification 32 + @APActor 33 + public final class IdentityResolver { 34 + 35 + /// Cache entry for resolved identities. 36 + private struct CacheEntry { 37 + let document: DIDDocument 38 + let timestamp: Date 39 + } 40 + 41 + private let urlSession: URLSession 42 + private var cache: [String: CacheEntry] = [:] 43 + 44 + /// Cache TTL in seconds. Default is 10 minutes as recommended by AT Protocol spec. 45 + public var cacheTTL: TimeInterval = 600 46 + 47 + /// The PLC directory URL for resolving did:plc identifiers. 48 + public var plcDirectoryURL: String = "https://plc.directory" 49 + 50 + public init(urlSession: URLSession = .shared) { 51 + self.urlSession = urlSession 52 + } 53 + 54 + // MARK: - Handle Resolution 55 + 56 + /// Resolves a handle to a DID using the `.well-known/atproto-did` endpoint. 57 + /// - Parameter handle: The handle to resolve (e.g., "alice.bsky.social") 58 + /// - Returns: The DID string (e.g., "did:plc:abc123") 59 + public func resolveHandle(_ handle: String) async throws -> String { 60 + let normalizedHandle = handle.lowercased().trimmingCharacters(in: .whitespaces) 61 + 62 + guard isValidHandle(normalizedHandle) else { 63 + throw IdentityError.invalidHandle(handle) 64 + } 65 + 66 + let urlString = "https://\(normalizedHandle)/.well-known/atproto-did" 67 + guard let url = URL(string: urlString) else { 68 + throw IdentityError.invalidURL(urlString) 69 + } 70 + 71 + do { 72 + let (data, response) = try await urlSession.data(from: url) 73 + 74 + guard let httpResponse = response as? HTTPURLResponse, 75 + (200...299).contains(httpResponse.statusCode) else { 76 + throw IdentityError.handleResolutionFailed(handle) 77 + } 78 + 79 + guard let did = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines), 80 + did.hasPrefix("did:") else { 81 + throw IdentityError.handleResolutionFailed(handle) 82 + } 83 + 84 + return did 85 + } catch let error as IdentityError { 86 + throw error 87 + } catch { 88 + throw IdentityError.networkError(error) 89 + } 90 + } 91 + 92 + // MARK: - DID Resolution 93 + 94 + /// Resolves a DID to its DID Document. 95 + /// - Parameter did: The DID to resolve (e.g., "did:plc:abc123" or "did:web:example.com") 96 + /// - Returns: The DID Document containing verification methods and service endpoints 97 + public func resolveDID(_ did: String) async throws -> DIDDocument { 98 + // Check cache first 99 + if let cached = cache[did], Date().timeIntervalSince(cached.timestamp) < cacheTTL { 100 + return cached.document 101 + } 102 + 103 + let document: DIDDocument 104 + 105 + if did.hasPrefix("did:plc:") { 106 + document = try await resolvePLCDID(did) 107 + } else if did.hasPrefix("did:web:") { 108 + document = try await resolveWebDID(did) 109 + } else { 110 + throw IdentityError.invalidDID(did) 111 + } 112 + 113 + // Cache the result 114 + cache[did] = CacheEntry(document: document, timestamp: Date()) 115 + 116 + return document 117 + } 118 + 119 + /// Resolves a did:plc identifier using the PLC directory. 120 + private func resolvePLCDID(_ did: String) async throws -> DIDDocument { 121 + let urlString = "\(plcDirectoryURL)/\(did)" 122 + guard let url = URL(string: urlString) else { 123 + throw IdentityError.invalidURL(urlString) 124 + } 125 + 126 + do { 127 + let (data, response) = try await urlSession.data(from: url) 128 + 129 + guard let httpResponse = response as? HTTPURLResponse, 130 + (200...299).contains(httpResponse.statusCode) else { 131 + throw IdentityError.didResolutionFailed(did) 132 + } 133 + 134 + // Try to decode as PLC directory response first 135 + if let plcResponse = try? JSONDecoder().decode(PLCDirectoryResponse.self, from: data) { 136 + return plcResponse.toDIDDocument() 137 + } 138 + 139 + // Fall back to standard DID document format 140 + return try JSONDecoder().decode(DIDDocument.self, from: data) 141 + } catch let error as IdentityError { 142 + throw error 143 + } catch { 144 + throw IdentityError.networkError(error) 145 + } 146 + } 147 + 148 + /// Resolves a did:web identifier. 149 + private func resolveWebDID(_ did: String) async throws -> DIDDocument { 150 + // did:web:example.com -> https://example.com/.well-known/did.json 151 + // did:web:example.com:path:to:resource -> https://example.com/path/to/resource/did.json 152 + let identifier = String(did.dropFirst("did:web:".count)) 153 + let parts = identifier.split(separator: ":").map(String.init) 154 + 155 + let urlString: String 156 + if parts.count == 1 { 157 + urlString = "https://\(parts[0])/.well-known/did.json" 158 + } else { 159 + let host = parts[0] 160 + let path = parts.dropFirst().joined(separator: "/") 161 + urlString = "https://\(host)/\(path)/did.json" 162 + } 163 + 164 + guard let url = URL(string: urlString) else { 165 + throw IdentityError.invalidURL(urlString) 166 + } 167 + 168 + do { 169 + let (data, response) = try await urlSession.data(from: url) 170 + 171 + guard let httpResponse = response as? HTTPURLResponse, 172 + (200...299).contains(httpResponse.statusCode) else { 173 + throw IdentityError.didResolutionFailed(did) 174 + } 175 + 176 + return try JSONDecoder().decode(DIDDocument.self, from: data) 177 + } catch let error as IdentityError { 178 + throw error 179 + } catch { 180 + throw IdentityError.networkError(error) 181 + } 182 + } 183 + 184 + // MARK: - PDS Discovery 185 + 186 + /// Gets the PDS endpoint for a given DID. 187 + /// - Parameter did: The DID to look up 188 + /// - Returns: The PDS service endpoint URL 189 + public func getPDSEndpoint(for did: String) async throws -> String { 190 + let document = try await resolveDID(did) 191 + 192 + guard let pds = document.pdsEndpoint else { 193 + throw IdentityError.pdsNotFound 194 + } 195 + 196 + return pds 197 + } 198 + 199 + // MARK: - Authorization Server Discovery 200 + 201 + /// Represents the OAuth Protected Resource metadata from a PDS. 202 + public struct ProtectedResourceMetadata: Codable, Sendable { 203 + public let resource: String 204 + public let authorizationServers: [String] 205 + 206 + enum CodingKeys: String, CodingKey { 207 + case resource 208 + case authorizationServers = "authorization_servers" 209 + } 210 + } 211 + 212 + /// Fetches the authorization server URL from a PDS. 213 + /// - Parameter pdsURL: The PDS base URL 214 + /// - Returns: The authorization server URL 215 + public func getAuthorizationServer(from pdsURL: String) async throws -> String { 216 + let normalizedPDS = pdsURL.hasSuffix("/") ? String(pdsURL.dropLast()) : pdsURL 217 + let urlString = "\(normalizedPDS)/.well-known/oauth-protected-resource" 218 + 219 + guard let url = URL(string: urlString) else { 220 + throw IdentityError.invalidURL(urlString) 221 + } 222 + 223 + do { 224 + let (data, response) = try await urlSession.data(from: url) 225 + 226 + guard let httpResponse = response as? HTTPURLResponse, 227 + (200...299).contains(httpResponse.statusCode) else { 228 + throw IdentityError.authorizationServerNotFound 229 + } 230 + 231 + let metadata = try JSONDecoder().decode(ProtectedResourceMetadata.self, from: data) 232 + 233 + guard let authServer = metadata.authorizationServers.first else { 234 + throw IdentityError.authorizationServerNotFound 235 + } 236 + 237 + return authServer 238 + } catch let error as IdentityError { 239 + throw error 240 + } catch { 241 + throw IdentityError.networkError(error) 242 + } 243 + } 244 + 245 + // MARK: - Full Resolution 246 + 247 + /// Result of resolving an identity including all metadata. 248 + public struct ResolvedIdentity: Sendable { 249 + public let handle: String 250 + public let did: String 251 + public let didDocument: DIDDocument 252 + public let pdsURL: String 253 + public let authorizationServerURL: String 254 + 255 + public init(handle: String, did: String, didDocument: DIDDocument, pdsURL: String, authorizationServerURL: String) { 256 + self.handle = handle 257 + self.did = did 258 + self.didDocument = didDocument 259 + self.pdsURL = pdsURL 260 + self.authorizationServerURL = authorizationServerURL 261 + } 262 + } 263 + 264 + /// Fully resolves an identity from a handle, including bidirectional verification. 265 + /// - Parameter handle: The handle to resolve 266 + /// - Returns: Complete identity information including PDS and auth server 267 + public func resolveIdentity(handle: String) async throws -> ResolvedIdentity { 268 + // Step 1: Resolve handle to DID 269 + let did = try await resolveHandle(handle) 270 + 271 + // Step 2: Resolve DID to document 272 + let document = try await resolveDID(did) 273 + 274 + // Step 3: Verify bidirectional handle claim 275 + let normalizedHandle = handle.lowercased() 276 + if let documentHandle = document.handle?.lowercased(), documentHandle != normalizedHandle { 277 + throw IdentityError.bidirectionalVerificationFailed(handle: handle, did: did) 278 + } 279 + 280 + // Step 4: Get PDS endpoint 281 + guard let pdsURL = document.pdsEndpoint else { 282 + throw IdentityError.pdsNotFound 283 + } 284 + 285 + // Step 5: Get authorization server 286 + let authServerURL = try await getAuthorizationServer(from: pdsURL) 287 + 288 + return ResolvedIdentity( 289 + handle: handle, 290 + did: did, 291 + didDocument: document, 292 + pdsURL: pdsURL, 293 + authorizationServerURL: authServerURL 294 + ) 295 + } 296 + 297 + /// Resolves identity starting from a DID. 298 + /// - Parameter did: The DID to resolve 299 + /// - Returns: Complete identity information 300 + public func resolveIdentity(did: String) async throws -> ResolvedIdentity { 301 + let document = try await resolveDID(did) 302 + 303 + guard let pdsURL = document.pdsEndpoint else { 304 + throw IdentityError.pdsNotFound 305 + } 306 + 307 + let authServerURL = try await getAuthorizationServer(from: pdsURL) 308 + 309 + return ResolvedIdentity( 310 + handle: document.handle ?? "", 311 + did: did, 312 + didDocument: document, 313 + pdsURL: pdsURL, 314 + authorizationServerURL: authServerURL 315 + ) 316 + } 317 + 318 + // MARK: - Validation 319 + 320 + /// Validates if a string is a valid handle format. 321 + private func isValidHandle(_ handle: String) -> Bool { 322 + // Basic validation: must have at least one dot, no spaces, reasonable length 323 + let parts = handle.split(separator: ".") 324 + guard parts.count >= 2 else { return false } 325 + guard handle.count >= 3 && handle.count <= 253 else { return false } 326 + guard !handle.contains(" ") else { return false } 327 + return true 328 + } 329 + 330 + /// Clears the identity cache. 331 + public func clearCache() { 332 + cache.removeAll() 333 + } 334 + }
+245
Sources/CoreATProtocol/Logging/ATLogger.swift
··· 1 + // 2 + // ATLogger.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Foundation 9 + import os.log 10 + 11 + /// Log levels for AT Protocol operations. 12 + public enum ATLogLevel: Int, Comparable, Sendable { 13 + case debug = 0 14 + case info = 1 15 + case warning = 2 16 + case error = 3 17 + case none = 100 18 + 19 + public static func < (lhs: ATLogLevel, rhs: ATLogLevel) -> Bool { 20 + lhs.rawValue < rhs.rawValue 21 + } 22 + } 23 + 24 + /// Protocol for custom log handlers. 25 + public protocol ATLogHandler: Sendable { 26 + func log(level: ATLogLevel, message: String, metadata: [String: String]?, file: String, function: String, line: Int) 27 + } 28 + 29 + /// Logger for AT Protocol operations. 30 + /// Provides structured logging with support for custom handlers. 31 + public final class ATLogger: @unchecked Sendable { 32 + 33 + /// Shared logger instance. 34 + public static let shared = ATLogger() 35 + 36 + /// Current log level. Messages below this level are not logged. 37 + public var logLevel: ATLogLevel = .info 38 + 39 + /// Custom log handler. If nil, uses OSLog on Apple platforms. 40 + public var handler: ATLogHandler? 41 + 42 + /// Whether to include request/response bodies in logs (may contain sensitive data). 43 + public var logBodies: Bool = false 44 + 45 + /// Whether to redact authorization headers and tokens. 46 + public var redactTokens: Bool = true 47 + 48 + private let osLog: OSLog 49 + 50 + private init() { 51 + self.osLog = OSLog(subsystem: "com.atprotocol.core", category: "network") 52 + } 53 + 54 + // MARK: - Logging Methods 55 + 56 + /// Logs a debug message. 57 + public func debug( 58 + _ message: @autoclosure () -> String, 59 + metadata: [String: String]? = nil, 60 + file: String = #file, 61 + function: String = #function, 62 + line: Int = #line 63 + ) { 64 + log(level: .debug, message: message(), metadata: metadata, file: file, function: function, line: line) 65 + } 66 + 67 + /// Logs an info message. 68 + public func info( 69 + _ message: @autoclosure () -> String, 70 + metadata: [String: String]? = nil, 71 + file: String = #file, 72 + function: String = #function, 73 + line: Int = #line 74 + ) { 75 + log(level: .info, message: message(), metadata: metadata, file: file, function: function, line: line) 76 + } 77 + 78 + /// Logs a warning message. 79 + public func warning( 80 + _ message: @autoclosure () -> String, 81 + metadata: [String: String]? = nil, 82 + file: String = #file, 83 + function: String = #function, 84 + line: Int = #line 85 + ) { 86 + log(level: .warning, message: message(), metadata: metadata, file: file, function: function, line: line) 87 + } 88 + 89 + /// Logs an error message. 90 + public func error( 91 + _ message: @autoclosure () -> String, 92 + metadata: [String: String]? = nil, 93 + file: String = #file, 94 + function: String = #function, 95 + line: Int = #line 96 + ) { 97 + log(level: .error, message: message(), metadata: metadata, file: file, function: function, line: line) 98 + } 99 + 100 + // MARK: - Network Logging 101 + 102 + /// Logs an outgoing request. 103 + public func logRequest(_ request: URLRequest, id: String = UUID().uuidString) { 104 + guard logLevel <= .debug else { return } 105 + 106 + var metadata: [String: String] = [ 107 + "request_id": id, 108 + "method": request.httpMethod ?? "UNKNOWN", 109 + "url": request.url?.absoluteString ?? "unknown" 110 + ] 111 + 112 + // Add headers (redacting sensitive ones) 113 + if let headers = request.allHTTPHeaderFields { 114 + for (key, value) in headers { 115 + let redactedValue = shouldRedact(header: key) ? "[REDACTED]" : value 116 + metadata["header_\(key)"] = redactedValue 117 + } 118 + } 119 + 120 + // Optionally log body 121 + if logBodies, let body = request.httpBody, let bodyString = String(data: body, encoding: .utf8) { 122 + let truncated = bodyString.count > 1000 ? String(bodyString.prefix(1000)) + "..." : bodyString 123 + metadata["body"] = truncated 124 + } 125 + 126 + debug("Request: \(request.httpMethod ?? "?") \(request.url?.absoluteString ?? "?")", metadata: metadata) 127 + } 128 + 129 + /// Logs an incoming response. 130 + public func logResponse(_ response: URLResponse, data: Data?, error: Error?, id: String = UUID().uuidString, duration: TimeInterval? = nil) { 131 + guard logLevel <= .debug else { return } 132 + 133 + var metadata: [String: String] = ["request_id": id] 134 + 135 + if let httpResponse = response as? HTTPURLResponse { 136 + metadata["status_code"] = String(httpResponse.statusCode) 137 + metadata["url"] = httpResponse.url?.absoluteString ?? "unknown" 138 + } 139 + 140 + if let duration = duration { 141 + metadata["duration_ms"] = String(format: "%.2f", duration * 1000) 142 + } 143 + 144 + if let data = data { 145 + metadata["response_size"] = String(data.count) 146 + 147 + if logBodies, let bodyString = String(data: data, encoding: .utf8) { 148 + let truncated = bodyString.count > 1000 ? String(bodyString.prefix(1000)) + "..." : bodyString 149 + metadata["body"] = truncated 150 + } 151 + } 152 + 153 + if let error = error { 154 + metadata["error"] = error.localizedDescription 155 + self.error("Response error: \(error.localizedDescription)", metadata: metadata) 156 + } else if let httpResponse = response as? HTTPURLResponse { 157 + let message = "Response: \(httpResponse.statusCode)" 158 + if httpResponse.statusCode >= 400 { 159 + warning(message, metadata: metadata) 160 + } else { 161 + debug(message, metadata: metadata) 162 + } 163 + } 164 + } 165 + 166 + /// Logs a token refresh attempt. 167 + public func logTokenRefresh(success: Bool, error: Error? = nil) { 168 + if success { 169 + info("Token refresh successful") 170 + } else if let error = error { 171 + self.error("Token refresh failed: \(error.localizedDescription)") 172 + } else { 173 + warning("Token refresh failed") 174 + } 175 + } 176 + 177 + /// Logs identity resolution. 178 + public func logIdentityResolution(handle: String? = nil, did: String? = nil, success: Bool, error: Error? = nil) { 179 + var metadata: [String: String] = [:] 180 + if let handle = handle { metadata["handle"] = handle } 181 + if let did = did { metadata["did"] = did } 182 + 183 + if success { 184 + debug("Identity resolved", metadata: metadata) 185 + } else if let error = error { 186 + self.error("Identity resolution failed: \(error.localizedDescription)", metadata: metadata) 187 + } 188 + } 189 + 190 + // MARK: - Private 191 + 192 + private func log(level: ATLogLevel, message: String, metadata: [String: String]?, file: String, function: String, line: Int) { 193 + guard level >= logLevel else { return } 194 + 195 + if let handler = handler { 196 + handler.log(level: level, message: message, metadata: metadata, file: file, function: function, line: line) 197 + } else { 198 + let fileName = (file as NSString).lastPathComponent 199 + let logMessage = "[\(fileName):\(line)] \(function) - \(message)" 200 + 201 + switch level { 202 + case .debug: 203 + os_log(.debug, log: osLog, "%{public}@", logMessage) 204 + case .info: 205 + os_log(.info, log: osLog, "%{public}@", logMessage) 206 + case .warning: 207 + os_log(.default, log: osLog, "⚠️ %{public}@", logMessage) 208 + case .error: 209 + os_log(.error, log: osLog, "%{public}@", logMessage) 210 + case .none: 211 + break 212 + } 213 + } 214 + } 215 + 216 + private func shouldRedact(header: String) -> Bool { 217 + guard redactTokens else { return false } 218 + let sensitiveHeaders = ["authorization", "dpop", "cookie", "set-cookie"] 219 + return sensitiveHeaders.contains(header.lowercased()) 220 + } 221 + } 222 + 223 + /// Console log handler for development. 224 + public struct ConsoleLogHandler: ATLogHandler { 225 + public init() {} 226 + 227 + public func log(level: ATLogLevel, message: String, metadata: [String: String]?, file: String, function: String, line: Int) { 228 + let fileName = (file as NSString).lastPathComponent 229 + let prefix: String 230 + switch level { 231 + case .debug: prefix = "🔍 DEBUG" 232 + case .info: prefix = "ℹ️ INFO" 233 + case .warning: prefix = "⚠️ WARNING" 234 + case .error: prefix = "❌ ERROR" 235 + case .none: return 236 + } 237 + 238 + var output = "\(prefix) [\(fileName):\(line)] \(message)" 239 + if let metadata = metadata, !metadata.isEmpty { 240 + let metaString = metadata.map { "\($0.key)=\($0.value)" }.joined(separator: ", ") 241 + output += " {\(metaString)}" 242 + } 243 + print(output) 244 + } 245 + }
+192 -13
Sources/CoreATProtocol/LoginService.swift
··· 8 8 import Foundation 9 9 import OAuthenticator 10 10 11 + /// Service for handling AT Protocol OAuth authentication. 11 12 @APActor 12 13 public final class LoginService { 13 - public enum Error: Swift.Error { 14 + 15 + /// Errors that can occur during login. 16 + public enum Error: Swift.Error, Sendable { 14 17 case missingStoredLogin 18 + case identityResolutionFailed(IdentityError) 19 + case serverMetadataFailed 20 + case clientMetadataFailed 21 + case authenticationFailed(Swift.Error) 22 + case subjectMismatch(expected: String, actual: String) 15 23 } 16 24 17 25 private let loginStorage: LoginStorage 18 26 private let jwtGenerator: DPoPSigner.JWTGenerator 27 + private let identityResolver: IdentityResolver 28 + private var authenticator: Authenticator? 19 29 30 + /// Creates a new login service. 31 + /// - Parameters: 32 + /// - jwtGenerator: DPoP JWT generator for signing proofs 33 + /// - loginStorage: Storage for persisting login tokens 20 34 public init(jwtGenerator: @escaping DPoPSigner.JWTGenerator, loginStorage: LoginStorage) { 21 35 self.jwtGenerator = jwtGenerator 22 36 self.loginStorage = loginStorage 37 + self.identityResolver = IdentityResolver() 23 38 } 24 39 40 + /// Performs OAuth login for an AT Protocol account. 41 + /// 42 + /// This method: 43 + /// 1. Resolves the account handle/DID to find the PDS 44 + /// 2. Discovers OAuth server metadata 45 + /// 3. Fetches client metadata 46 + /// 4. Performs PKCE + PAR + DPoP OAuth flow 47 + /// 5. Verifies the returned identity matches the expected account 48 + /// 6. Stores the tokens and updates the environment 49 + /// 50 + /// - Parameters: 51 + /// - account: Handle or DID of the account to authenticate 52 + /// - clientMetadataEndpoint: URL where the client metadata document is published 53 + /// - Returns: The Login object with access and refresh tokens 25 54 public func login(account: String, clientMetadataEndpoint: String) async throws -> Login { 26 55 let provider = URLSession.defaultProvider 27 - let host = APEnvironment.current.host ?? "" 28 - let server = if host.hasPrefix("https://") { 29 - String(host.dropFirst(8)) 30 - } else if host.hasPrefix("http://") { 31 - String(host.dropFirst(7)) 32 - } else { host } 56 + 57 + // Step 1: Resolve identity to find PDS and auth server 58 + let resolvedIdentity: IdentityResolver.ResolvedIdentity 59 + do { 60 + if account.hasPrefix("did:") { 61 + resolvedIdentity = try await identityResolver.resolveIdentity(did: account) 62 + } else { 63 + resolvedIdentity = try await identityResolver.resolveIdentity(handle: account) 64 + } 65 + } catch let error as IdentityError { 66 + ATLogger.shared.error("Identity resolution failed for \(account): \(error)") 67 + throw Error.identityResolutionFailed(error) 68 + } 69 + 70 + ATLogger.shared.info("Resolved identity: DID=\(resolvedIdentity.did), PDS=\(resolvedIdentity.pdsURL)") 71 + 72 + // Update environment with PDS 73 + APEnvironment.current.host = resolvedIdentity.pdsURL 74 + APEnvironment.current.resolvedIdentity = resolvedIdentity 75 + 76 + // Step 2: Extract server host for metadata fetch 77 + guard let serverURL = URL(string: resolvedIdentity.authorizationServerURL), 78 + let serverHost = serverURL.host else { 79 + throw Error.serverMetadataFailed 80 + } 81 + 82 + // Step 3: Fetch server metadata 83 + let serverConfig: ServerMetadata 84 + do { 85 + serverConfig = try await ServerMetadata.load(for: serverHost, provider: provider) 86 + APEnvironment.current.serverMetadata = serverConfig 87 + } catch { 88 + ATLogger.shared.error("Failed to load server metadata: \(error)") 89 + throw Error.serverMetadataFailed 90 + } 91 + 92 + // Step 4: Fetch client metadata 93 + let clientConfig: ClientMetadata 94 + do { 95 + clientConfig = try await ClientMetadata.load(for: clientMetadataEndpoint, provider: provider) 96 + APEnvironment.current.clientId = clientConfig.clientId 97 + } catch { 98 + ATLogger.shared.error("Failed to load client metadata: \(error)") 99 + throw Error.clientMetadataFailed 100 + } 101 + 102 + // Step 5: Configure and perform OAuth 103 + let tokenHandling = Bluesky.tokenHandling( 104 + account: account, 105 + server: serverConfig, 106 + jwtGenerator: jwtGenerator 107 + ) 108 + 109 + let config = Authenticator.Configuration( 110 + appCredentials: clientConfig.credentials, 111 + loginStorage: loginStorage, 112 + tokenHandling: tokenHandling, 113 + mode: .automatic 114 + ) 115 + 116 + authenticator = Authenticator(config: config) 117 + 118 + do { 119 + try await authenticator?.authenticate() 120 + } catch { 121 + ATLogger.shared.error("Authentication failed: \(error)") 122 + throw Error.authenticationFailed(error) 123 + } 124 + 125 + // Step 6: Retrieve and verify login 126 + guard let storedLogin = try await loginStorage.retrieveLogin() else { 127 + throw Error.missingStoredLogin 128 + } 129 + 130 + // Verify the subject matches expected DID 131 + if let issuer = storedLogin.issuingServer, issuer != resolvedIdentity.did { 132 + ATLogger.shared.warning("Subject mismatch: expected \(resolvedIdentity.did), got \(issuer)") 133 + // This is a security check - the token should be for the expected user 134 + throw Error.subjectMismatch(expected: resolvedIdentity.did, actual: issuer) 135 + } 136 + 137 + // Step 7: Update environment with complete authentication context 138 + applyAuthenticationContext( 139 + login: storedLogin, 140 + generator: jwtGenerator, 141 + serverMetadata: serverConfig, 142 + clientId: clientConfig.clientId 143 + ) 144 + 145 + // Store complete auth state if token storage is configured 146 + if let tokenStorage = APEnvironment.current.tokenStorage { 147 + let authState = AuthenticationState( 148 + did: resolvedIdentity.did, 149 + handle: resolvedIdentity.handle, 150 + pdsURL: resolvedIdentity.pdsURL, 151 + authServerURL: resolvedIdentity.authorizationServerURL, 152 + accessToken: storedLogin.accessToken.value, 153 + accessTokenExpiry: storedLogin.accessToken.expiry, 154 + refreshToken: storedLogin.refreshToken?.value, 155 + scope: storedLogin.scopes, 156 + dpopPrivateKeyData: nil // Key management is caller's responsibility 157 + ) 158 + try? await tokenStorage.store(authState) 159 + APEnvironment.current.authState = authState 160 + } 33 161 34 - let clientConfig = try await ClientMetadata.load(for: clientMetadataEndpoint, provider: provider) 35 - let serverConfig = try await ServerMetadata.load(for: server, provider: provider) 162 + ATLogger.shared.info("Login successful for \(resolvedIdentity.handle)") 36 163 37 - let tokenHandling = Bluesky.tokenHandling(account: account, server: serverConfig, jwtGenerator: jwtGenerator) 38 - let config = Authenticator.Configuration(appCredentials: clientConfig.credentials, loginStorage: loginStorage, tokenHandling: tokenHandling, mode: .automatic) 39 - let authenticator = Authenticator(config: config) 40 - try await authenticator.authenticate() 164 + return storedLogin 165 + } 166 + 167 + /// Performs OAuth login using pre-resolved identity and server metadata. 168 + /// Use this when you've already resolved the identity and fetched metadata. 169 + /// 170 + /// - Parameters: 171 + /// - identity: Pre-resolved identity information 172 + /// - serverMetadata: Pre-fetched OAuth server metadata 173 + /// - clientMetadata: Pre-fetched client metadata 174 + /// - Returns: The Login object with access and refresh tokens 175 + public func login( 176 + identity: IdentityResolver.ResolvedIdentity, 177 + serverMetadata: ServerMetadata, 178 + clientMetadata: ClientMetadata 179 + ) async throws -> Login { 180 + // Update environment 181 + APEnvironment.current.host = identity.pdsURL 182 + APEnvironment.current.resolvedIdentity = identity 183 + APEnvironment.current.serverMetadata = serverMetadata 184 + APEnvironment.current.clientId = clientMetadata.clientId 185 + 186 + let tokenHandling = Bluesky.tokenHandling( 187 + account: identity.handle, 188 + server: serverMetadata, 189 + jwtGenerator: jwtGenerator 190 + ) 191 + 192 + let config = Authenticator.Configuration( 193 + appCredentials: clientMetadata.credentials, 194 + loginStorage: loginStorage, 195 + tokenHandling: tokenHandling, 196 + mode: .automatic 197 + ) 198 + 199 + authenticator = Authenticator(config: config) 200 + 201 + do { 202 + try await authenticator?.authenticate() 203 + } catch { 204 + throw Error.authenticationFailed(error) 205 + } 41 206 42 207 guard let storedLogin = try await loginStorage.retrieveLogin() else { 43 208 throw Error.missingStoredLogin 44 209 } 45 210 211 + applyAuthenticationContext( 212 + login: storedLogin, 213 + generator: jwtGenerator, 214 + serverMetadata: serverMetadata, 215 + clientId: clientMetadata.clientId 216 + ) 217 + 46 218 return storedLogin 219 + } 220 + 221 + /// Logs out by clearing all stored tokens and authentication state. 222 + public func logout() async { 223 + await clearAuthenticationContext() 224 + authenticator = nil 225 + ATLogger.shared.info("Logged out") 47 226 } 48 227 }
+207 -5
Sources/CoreATProtocol/Models/ATError.swift
··· 5 5 // Created by Thomas Rademaker on 10/8/25. 6 6 // 7 7 8 - public enum AtError: Error { 8 + import Foundation 9 + 10 + /// Top-level error type for AT Protocol operations. 11 + public enum AtError: Error, Sendable { 12 + /// An error message returned by the server. 9 13 case message(ErrorMessage) 14 + 15 + /// A network-level error. 10 16 case network(NetworkError) 17 + 18 + /// An OAuth/authentication error. 19 + case oauth(OAuthError) 20 + 21 + /// An identity resolution error. 22 + case identity(IdentityError) 23 + 24 + /// A decoding error. 25 + case decoding(DecodingError) 26 + 27 + /// An unknown error. 28 + case unknown(Error) 11 29 } 12 30 31 + extension AtError: LocalizedError { 32 + public var errorDescription: String? { 33 + switch self { 34 + case .message(let msg): 35 + return msg.message ?? msg.error 36 + case .network(let err): 37 + return err.localizedDescription 38 + case .oauth(let err): 39 + return err.localizedDescription 40 + case .identity(let err): 41 + return String(describing: err) 42 + case .decoding(let err): 43 + return err.localizedDescription 44 + case .unknown(let err): 45 + return err.localizedDescription 46 + } 47 + } 48 + 49 + /// Returns true if this error indicates the user needs to re-authenticate. 50 + public var requiresReauthentication: Bool { 51 + switch self { 52 + case .message(let msg): 53 + return msg.errorType == .authenticationRequired || 54 + msg.errorType == .expiredToken || 55 + msg.errorType == .authMissing 56 + case .network(let err): 57 + if case .statusCode(let code, _) = err, code?.rawValue == 401 { 58 + return true 59 + } 60 + return false 61 + case .oauth(let err): 62 + switch err { 63 + case .accessTokenExpired, .refreshTokenExpired, .refreshTokenMissing: 64 + return true 65 + default: 66 + return false 67 + } 68 + default: 69 + return false 70 + } 71 + } 72 + 73 + /// Returns true if this error might succeed if retried. 74 + public var isRetryable: Bool { 75 + switch self { 76 + case .message(let msg): 77 + return msg.errorType == .rateLimitExceeded 78 + case .network(let err): 79 + switch err { 80 + case .statusCode(let code, _): 81 + // 5xx errors and 429 are retryable 82 + guard let status = code?.rawValue else { return false } 83 + return status >= 500 || status == 429 84 + case .tokenRefresh: 85 + return true 86 + default: 87 + return false 88 + } 89 + default: 90 + return false 91 + } 92 + } 93 + } 94 + 95 + /// Error message returned by AT Protocol servers. 13 96 public struct ErrorMessage: Codable, Sendable { 14 - #warning("Should error be type string or AtErrorType?") 97 + /// The error code/type string. 15 98 public let error: String 99 + 100 + /// Optional human-readable error message. 16 101 public let message: String? 17 - 102 + 18 103 public init(error: String, message: String?) { 19 104 self.error = error 20 105 self.message = message 21 106 } 107 + 108 + /// Attempts to parse the error string as a known error type. 109 + public var errorType: AtErrorType? { 110 + AtErrorType(rawValue: error) 111 + } 22 112 } 23 113 24 - public enum AtErrorType: String, Codable, Sendable { 114 + /// Known AT Protocol error types. 115 + public enum AtErrorType: String, Codable, Sendable, CaseIterable { 116 + // Authentication errors 25 117 case authenticationRequired = "AuthenticationRequired" 26 118 case expiredToken = "ExpiredToken" 119 + case authMissing = "AuthMissing" 120 + case invalidToken = "InvalidToken" 121 + 122 + // Request errors 27 123 case invalidRequest = "InvalidRequest" 124 + case invalidSwap = "InvalidSwap" 28 125 case methodNotImplemented = "MethodNotImplemented" 126 + 127 + // Rate limiting 29 128 case rateLimitExceeded = "RateLimitExceeded" 30 - case authMissing = "AuthMissing" 129 + 130 + // Account errors 131 + case accountTakedown = "AccountTakedown" 132 + case accountSuspended = "AccountSuspended" 133 + case accountDeactivated = "AccountDeactivated" 134 + case accountNotFound = "AccountNotFound" 135 + 136 + // Record errors 137 + case recordNotFound = "RecordNotFound" 138 + case repoNotFound = "RepoNotFound" 139 + case blobNotFound = "BlobNotFound" 140 + case blockNotFound = "BlockNotFound" 141 + 142 + // Validation errors 143 + case invalidHandle = "InvalidHandle" 144 + case handleNotAvailable = "HandleNotAvailable" 145 + case unsupportedDomain = "UnsupportedDomain" 146 + case unresolvableDid = "UnresolvableDid" 147 + 148 + // Blob errors 149 + case blobTooLarge = "BlobTooLarge" 150 + case invalidBlob = "InvalidBlob" 151 + 152 + // Content errors 153 + case duplicateCreate = "DuplicateCreate" 154 + case unknownFeed = "UnknownFeed" 155 + case unknownList = "UnknownList" 156 + case notFound = "NotFound" 157 + 158 + // Server errors 159 + case upstreamFailure = "UpstreamFailure" 160 + case upstreamTimeout = "UpstreamTimeout" 161 + case internalServerError = "InternalServerError" 162 + 163 + /// Human-readable description of the error type. 164 + public var description: String { 165 + switch self { 166 + case .authenticationRequired: return "Authentication is required" 167 + case .expiredToken: return "The access token has expired" 168 + case .authMissing: return "Authentication credentials are missing" 169 + case .invalidToken: return "The provided token is invalid" 170 + case .invalidRequest: return "The request is invalid" 171 + case .invalidSwap: return "The swap operation is invalid" 172 + case .methodNotImplemented: return "This method is not implemented" 173 + case .rateLimitExceeded: return "Rate limit exceeded" 174 + case .accountTakedown: return "Account has been taken down" 175 + case .accountSuspended: return "Account has been suspended" 176 + case .accountDeactivated: return "Account has been deactivated" 177 + case .accountNotFound: return "Account not found" 178 + case .recordNotFound: return "Record not found" 179 + case .repoNotFound: return "Repository not found" 180 + case .blobNotFound: return "Blob not found" 181 + case .blockNotFound: return "Block not found" 182 + case .invalidHandle: return "The handle is invalid" 183 + case .handleNotAvailable: return "The handle is not available" 184 + case .unsupportedDomain: return "The domain is not supported" 185 + case .unresolvableDid: return "The DID cannot be resolved" 186 + case .blobTooLarge: return "The blob is too large" 187 + case .invalidBlob: return "The blob is invalid" 188 + case .duplicateCreate: return "A record with this key already exists" 189 + case .unknownFeed: return "The feed is not known" 190 + case .unknownList: return "The list is not known" 191 + case .notFound: return "The resource was not found" 192 + case .upstreamFailure: return "An upstream service failed" 193 + case .upstreamTimeout: return "An upstream service timed out" 194 + case .internalServerError: return "Internal server error" 195 + } 196 + } 197 + } 198 + 199 + /// Rate limit information from response headers. 200 + public struct RateLimitInfo: Sendable { 201 + /// Maximum number of requests allowed in the window. 202 + public let limit: Int 203 + 204 + /// Number of requests remaining in the current window. 205 + public let remaining: Int 206 + 207 + /// Unix timestamp when the rate limit resets. 208 + public let resetTimestamp: TimeInterval 209 + 210 + /// Date when the rate limit resets. 211 + public var resetDate: Date { 212 + Date(timeIntervalSince1970: resetTimestamp) 213 + } 214 + 215 + /// Time interval until the rate limit resets. 216 + public var timeUntilReset: TimeInterval { 217 + resetTimestamp - Date().timeIntervalSince1970 218 + } 219 + 220 + /// Parses rate limit information from HTTP response headers. 221 + public static func from(response: HTTPURLResponse) -> RateLimitInfo? { 222 + guard let limitStr = response.value(forHTTPHeaderField: "RateLimit-Limit"), 223 + let remainingStr = response.value(forHTTPHeaderField: "RateLimit-Remaining"), 224 + let resetStr = response.value(forHTTPHeaderField: "RateLimit-Reset"), 225 + let limit = Int(limitStr), 226 + let remaining = Int(remainingStr), 227 + let reset = TimeInterval(resetStr) else { 228 + return nil 229 + } 230 + 231 + return RateLimitInfo(limit: limit, remaining: remaining, resetTimestamp: reset) 232 + } 31 233 }
+186 -40
Sources/CoreATProtocol/Networking.swift
··· 10 10 @preconcurrency import OAuthenticator 11 11 12 12 extension JSONDecoder { 13 + /// A JSON decoder configured for AT Protocol date formats. 14 + /// Supports ISO 8601 dates with fractional seconds and timezone. 13 15 public static var atDecoder: JSONDecoder { 14 - let dateFormatter = DateFormatter() 15 - dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX" 16 - dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) 17 - dateFormatter.locale = Locale(identifier: "en_US") 18 - 19 16 let decoder = JSONDecoder() 20 17 decoder.keyDecodingStrategy = .convertFromSnakeCase 21 - decoder.dateDecodingStrategy = .formatted(dateFormatter) 22 - 18 + decoder.dateDecodingStrategy = .custom { decoder in 19 + let container = try decoder.singleValueContainer() 20 + let dateString = try container.decode(String.self) 21 + 22 + // Try multiple date formats that AT Protocol APIs may return 23 + let formatters = Self.atDateFormatters 24 + 25 + for formatter in formatters { 26 + if let date = formatter.date(from: dateString) { 27 + return date 28 + } 29 + } 30 + 31 + // Try ISO8601 with fractional seconds 32 + let iso8601 = ISO8601DateFormatter() 33 + iso8601.formatOptions = [.withInternetDateTime, .withFractionalSeconds] 34 + if let date = iso8601.date(from: dateString) { 35 + return date 36 + } 37 + 38 + // Try without fractional seconds 39 + iso8601.formatOptions = [.withInternetDateTime] 40 + if let date = iso8601.date(from: dateString) { 41 + return date 42 + } 43 + 44 + throw DecodingError.dataCorruptedError( 45 + in: container, 46 + debugDescription: "Cannot decode date string: \(dateString)" 47 + ) 48 + } 49 + 23 50 return decoder 24 51 } 52 + 53 + /// Date formatters for various AT Protocol date formats. 54 + private static var atDateFormatters: [DateFormatter] { 55 + let formats = [ 56 + "yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXXXX", // With microseconds and timezone 57 + "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX", // With milliseconds and timezone 58 + "yyyy-MM-dd'T'HH:mm:ss.SSSX", // With milliseconds and short timezone 59 + "yyyy-MM-dd'T'HH:mm:ssXXXXX", // Without fractional seconds 60 + "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", // With Z timezone 61 + "yyyy-MM-dd'T'HH:mm:ss'Z'" // Without fractional, with Z 62 + ] 63 + 64 + return formats.map { format in 65 + let formatter = DateFormatter() 66 + formatter.dateFormat = format 67 + formatter.timeZone = TimeZone(secondsFromGMT: 0) 68 + formatter.locale = Locale(identifier: "en_US_POSIX") 69 + return formatter 70 + } 71 + } 25 72 } 26 73 74 + /// Checks if enough time has passed since last fetch to allow a new request. 75 + /// - Parameters: 76 + /// - lastFetched: Unix timestamp of last fetch (0 means never fetched) 77 + /// - timeLimit: Minimum seconds between fetches (default 1 hour) 78 + /// - Returns: true if a new request should be performed 27 79 func shouldPerformRequest(lastFetched: Double, timeLimit: Int = 3600) -> Bool { 28 80 guard lastFetched != 0 else { return true } 29 81 let currentTime = Date.now 30 82 let lastFetchTime = Date(timeIntervalSince1970: lastFetched) 31 - guard let differenceInMinutes = Calendar.current.dateComponents([.second], from: lastFetchTime, to: currentTime).second else { return false } 32 - return differenceInMinutes >= timeLimit 83 + guard let differenceInSeconds = Calendar.current.dateComponents([.second], from: lastFetchTime, to: currentTime).second else { return false } 84 + return differenceInSeconds >= timeLimit 33 85 } 34 86 35 - @MainActor 87 + @APActor 36 88 public class APRouterDelegate: NetworkRouterDelegate { 37 - private var shouldRefreshToken = false 38 - 39 - public func intercept(_ request: inout URLRequest) async { 89 + /// Maximum retry attempts for token refresh. 90 + private let maxRefreshAttempts = 2 91 + 92 + public init() {} 93 + 94 + nonisolated public func intercept(_ request: inout URLRequest) async { 95 + // Try DPoP-authenticated request first (preferred for AT Protocol) 40 96 if let generator = await APEnvironment.current.dpopProofGenerator, 41 97 let login = await APEnvironment.current.login { 42 98 let token = login.accessToken.value 43 - let tokenHash = tokenHash(for: token) 99 + let tokenHash = await tokenHash(for: token) 44 100 let signer = await APEnvironment.current.resourceDPoPSigner 45 - signer.nonce = await APEnvironment.current.resourceServerNonce 101 + await MainActor.run { 102 + signer.nonce = nil 103 + } 104 + let nonce = await APEnvironment.current.resourceServerNonce 105 + await MainActor.run { 106 + signer.nonce = nonce 107 + } 46 108 47 109 do { 48 110 try await signer.authenticateRequest( ··· 61 123 return 62 124 } 63 125 64 - if let refreshToken = await APEnvironment.current.refreshToken, shouldRefreshToken { 65 - shouldRefreshToken = false 66 - request.setValue("Bearer \(refreshToken)", forHTTPHeaderField: "Authorization") 67 - } else if let accessToken = await APEnvironment.current.accessToken { 126 + // Fall back to simple Bearer token authentication 127 + if let accessToken = await APEnvironment.current.accessToken { 68 128 request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") 69 129 } 70 130 } 71 - 72 - public func shouldRetry(error: Error, attempts: Int) async throws -> Bool { 73 - func getNewToken() async throws -> Bool { 74 - // shouldRefreshToken = true 75 - // let newSession = try await AtProtoLexicons().refresh(attempts: attempts + 1) 76 - // APEnvironment.current.accessToken = newSession.accessJwt 77 - // APEnvironment.current.refreshToken = newSession.refreshJwt 78 - // await delegate?.sessionUpdated(newSession) 79 - // 80 - // return true 81 - false 82 - } 83 - 84 - // TODO: verify this works! 131 + 132 + nonisolated public func shouldRetry(error: Error, attempts: Int) async throws -> Bool { 133 + // Don't retry more than maxRefreshAttempts times 134 + guard attempts <= maxRefreshAttempts else { return false } 135 + 136 + // Check if the error indicates we need to refresh the token 137 + let shouldAttemptRefresh = isTokenExpiredError(error) 138 + 139 + guard shouldAttemptRefresh else { return false } 140 + 141 + // Attempt token refresh 142 + let refreshed = await performTokenRefresh() 143 + 144 + return refreshed 145 + } 146 + 147 + /// Determines if an error indicates the token has expired and needs refresh. 148 + nonisolated private func isTokenExpiredError(_ error: Error) -> Bool { 149 + // Check for 401 Unauthorized status code 85 150 if case .network(let networkError) = error as? AtError, 86 151 case .statusCode(let statusCode, _) = networkError, 87 - let statusCode = statusCode?.rawValue, (400..<500).contains(statusCode), 88 - attempts == 1 { 89 - return try await getNewToken() 90 - } else if case .message(let message) = error as? AtError, 91 - message.error == AtErrorType.expiredToken.rawValue { 92 - return try await getNewToken() 152 + statusCode?.rawValue == 401 { 153 + return true 154 + } 155 + 156 + // Check for explicit expired token error message 157 + if case .message(let message) = error as? AtError, 158 + message.error == AtErrorType.expiredToken.rawValue { 159 + return true 160 + } 161 + 162 + // Check for authentication required error 163 + if case .message(let message) = error as? AtError, 164 + message.error == AtErrorType.authenticationRequired.rawValue { 165 + return true 93 166 } 94 167 95 168 return false 96 169 } 97 170 98 - private func tokenHash(for token: String) -> String { 171 + /// Performs token refresh using the configured OAuth settings. 172 + nonisolated private func performTokenRefresh() async -> Bool { 173 + let env = await APEnvironment.current 174 + 175 + // Try using the authState-based refresh first 176 + if await env.authState != nil { 177 + return await env.performTokenRefresh() 178 + } 179 + 180 + // Fall back to OAuthenticator's refresh if we have a login with refresh token 181 + guard let login = await env.login, 182 + let refreshToken = login.refreshToken, 183 + refreshToken.valid else { 184 + return false 185 + } 186 + 187 + guard let serverMetadata = await env.serverMetadata, 188 + let clientId = await env.clientId else { 189 + return false 190 + } 191 + 192 + // Use RefreshService for the actual refresh 193 + let refreshService = await RefreshService() 194 + 195 + // Create an AuthenticationState from the current login if we don't have one 196 + let state = AuthenticationState( 197 + did: login.issuingServer ?? "", 198 + handle: nil, 199 + pdsURL: await env.host ?? "", 200 + authServerURL: serverMetadata.issuer, 201 + accessToken: login.accessToken.value, 202 + accessTokenExpiry: login.accessToken.expiry, 203 + refreshToken: refreshToken.value, 204 + refreshTokenExpiry: refreshToken.expiry, 205 + scope: login.scopes, 206 + dpopPrivateKeyData: nil 207 + ) 208 + 209 + do { 210 + let newState = try await refreshService.refresh( 211 + state: state, 212 + serverMetadata: serverMetadata, 213 + clientId: clientId, 214 + dpopGenerator: await env.dpopProofGenerator 215 + ) 216 + 217 + // Update the environment 218 + await updateEnvironmentWithNewTokens(newState) 219 + 220 + return true 221 + } catch { 222 + print("Token refresh failed: \(error)") 223 + return false 224 + } 225 + } 226 + 227 + /// Updates the environment with refreshed tokens. 228 + private func updateEnvironmentWithNewTokens(_ state: AuthenticationState) async { 229 + APEnvironment.current.accessToken = state.accessToken 230 + APEnvironment.current.refreshToken = state.refreshToken 231 + APEnvironment.current.authState = state 232 + 233 + // Update login object if present 234 + if var login = APEnvironment.current.login { 235 + login.accessToken = Token(value: state.accessToken, expiry: state.accessTokenExpiry) 236 + if let newRefresh = state.refreshToken { 237 + login.refreshToken = Token(value: newRefresh, expiry: state.refreshTokenExpiry) 238 + } 239 + APEnvironment.current.login = login 240 + } 241 + } 242 + 243 + /// Computes SHA-256 hash of the access token for DPoP `ath` claim. 244 + nonisolated private func tokenHash(for token: String) -> String { 99 245 let digest = SHA256.hash(data: Data(token.utf8)) 100 246 return Data(digest).base64URLEncodedString() 101 247 }
+81 -3
Sources/CoreATProtocol/Networking/Services/HTTPTask.swift
··· 1 + import Foundation 2 + 3 + /// Describes the type of HTTP task to perform. 1 4 public enum HTTPTask: Sendable { 5 + /// A simple request with no body. 2 6 case request 3 - 7 + 8 + /// A request with encoded parameters (URL query or JSON body). 4 9 case requestParameters(encoding: ParameterEncoding) 5 - 6 - // case download, upload...etc 10 + 11 + /// A blob upload request with raw data and content type. 12 + case uploadBlob(data: Data, mimeType: String) 13 + 14 + /// A multipart form data upload. 15 + case uploadMultipart(parts: [MultipartFormData]) 16 + } 17 + 18 + /// Represents a single part in a multipart form data request. 19 + public struct MultipartFormData: Sendable { 20 + /// The field name for this part. 21 + public let name: String 22 + 23 + /// The filename for file uploads (nil for regular fields). 24 + public let filename: String? 25 + 26 + /// The content type of this part. 27 + public let mimeType: String? 28 + 29 + /// The data for this part. 30 + public let data: Data 31 + 32 + /// Creates a text field part. 33 + public static func field(name: String, value: String) -> MultipartFormData { 34 + MultipartFormData( 35 + name: name, 36 + filename: nil, 37 + mimeType: nil, 38 + data: Data(value.utf8) 39 + ) 40 + } 41 + 42 + /// Creates a file upload part. 43 + public static func file(name: String, filename: String, mimeType: String, data: Data) -> MultipartFormData { 44 + MultipartFormData( 45 + name: name, 46 + filename: filename, 47 + mimeType: mimeType, 48 + data: data 49 + ) 50 + } 51 + 52 + public init(name: String, filename: String?, mimeType: String?, data: Data) { 53 + self.name = name 54 + self.filename = filename 55 + self.mimeType = mimeType 56 + self.data = data 57 + } 58 + } 59 + 60 + /// Response from a blob upload operation. 61 + public struct BlobUploadResponse: Codable, Sendable { 62 + public let blob: BlobRef 63 + 64 + public struct BlobRef: Codable, Sendable { 65 + public let type: String 66 + public let ref: BlobLink 67 + public let mimeType: String 68 + public let size: Int 69 + 70 + enum CodingKeys: String, CodingKey { 71 + case type = "$type" 72 + case ref 73 + case mimeType 74 + case size 75 + } 76 + 77 + public struct BlobLink: Codable, Sendable { 78 + public let link: String 79 + 80 + enum CodingKeys: String, CodingKey { 81 + case link = "$link" 82 + } 83 + } 84 + } 7 85 }
+47 -5
Sources/CoreATProtocol/Networking/Services/NetworkRouter.swift
··· 1 1 import Foundation 2 2 3 - @MainActor 4 - public protocol NetworkRouterDelegate: AnyObject { 3 + /// Protocol for intercepting and handling network requests. 4 + /// Implementations can be isolated to any actor since methods are async. 5 + public protocol NetworkRouterDelegate: AnyObject, Sendable { 5 6 func intercept(_ request: inout URLRequest) async 6 7 func shouldRetry(error: Error, attempts: Int) async throws -> Bool 7 8 } ··· 87 88 } 88 89 89 90 func buildRequest(from route: Endpoint) async throws -> URLRequest { 90 - 91 + 91 92 var request = await URLRequest(url: route.baseURL.appendingPathComponent(route.path), 92 93 cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, 93 - timeoutInterval: 10.0) 94 - 94 + timeoutInterval: 30.0) 95 + 95 96 request.httpMethod = route.httpMethod.rawValue 96 97 do { 97 98 switch await route.task { 98 99 case .request: 99 100 request.setValue("application/json", forHTTPHeaderField: "Content-Type") 100 101 await addAdditionalHeaders(route.headers, request: &request) 102 + 101 103 case .requestParameters(let parameterEncoding): 102 104 await addAdditionalHeaders(route.headers, request: &request) 103 105 try configureParameters(parameterEncoding: parameterEncoding, request: &request) 106 + 107 + case .uploadBlob(let data, let mimeType): 108 + request.setValue(mimeType, forHTTPHeaderField: "Content-Type") 109 + request.setValue(String(data.count), forHTTPHeaderField: "Content-Length") 110 + request.httpBody = data 111 + await addAdditionalHeaders(route.headers, request: &request) 112 + 113 + case .uploadMultipart(let parts): 114 + let boundary = "Boundary-\(UUID().uuidString)" 115 + request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") 116 + request.httpBody = buildMultipartBody(parts: parts, boundary: boundary) 117 + await addAdditionalHeaders(route.headers, request: &request) 104 118 } 105 119 return request 106 120 } catch { 107 121 throw error 108 122 } 123 + } 124 + 125 + /// Builds a multipart form data body from parts. 126 + private func buildMultipartBody(parts: [MultipartFormData], boundary: String) -> Data { 127 + var body = Data() 128 + let lineBreak = "\r\n" 129 + 130 + for part in parts { 131 + body.append("--\(boundary)\(lineBreak)".data(using: .utf8)!) 132 + 133 + if let filename = part.filename { 134 + body.append("Content-Disposition: form-data; name=\"\(part.name)\"; filename=\"\(filename)\"\(lineBreak)".data(using: .utf8)!) 135 + } else { 136 + body.append("Content-Disposition: form-data; name=\"\(part.name)\"\(lineBreak)".data(using: .utf8)!) 137 + } 138 + 139 + if let mimeType = part.mimeType { 140 + body.append("Content-Type: \(mimeType)\(lineBreak)".data(using: .utf8)!) 141 + } 142 + 143 + body.append(lineBreak.data(using: .utf8)!) 144 + body.append(part.data) 145 + body.append(lineBreak.data(using: .utf8)!) 146 + } 147 + 148 + body.append("--\(boundary)--\(lineBreak)".data(using: .utf8)!) 149 + 150 + return body 109 151 } 110 152 111 153 private func configureParameters(parameterEncoding: ParameterEncoding, request: inout URLRequest) throws {
+263
Sources/CoreATProtocol/OAuth/ATClientMetadata.swift
··· 1 + // 2 + // ATClientMetadata.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Foundation 9 + 10 + /// AT Protocol OAuth client metadata document. 11 + /// This document must be published at the `client_id` URL for OAuth registration. 12 + /// 13 + /// See: https://atproto.com/specs/oauth 14 + public struct ATClientMetadata: Codable, Sendable, Hashable { 15 + 16 + /// The client identifier. Must be a fully-qualified HTTPS URL pointing to this metadata. 17 + public let clientId: String 18 + 19 + /// Application type: "web" or "native". 20 + public let applicationType: ApplicationType 21 + 22 + /// Supported grant types. Must include "authorization_code" and "refresh_token". 23 + public let grantTypes: [String] 24 + 25 + /// Requested scopes. Must include "atproto". 26 + public let scope: String 27 + 28 + /// Supported response types. Must include "code". 29 + public let responseTypes: [String] 30 + 31 + /// Redirect URIs for OAuth callbacks. 32 + public let redirectUris: [String] 33 + 34 + /// Whether access tokens are DPoP-bound. Must be true for AT Protocol. 35 + public let dpopBoundAccessTokens: Bool 36 + 37 + /// Token endpoint authentication method. 38 + /// "none" for public clients, "private_key_jwt" for confidential clients. 39 + public let tokenEndpointAuthMethod: String 40 + 41 + /// Human-readable application name. 42 + public let clientName: String? 43 + 44 + /// URL to the application's logo. 45 + public let logoUri: String? 46 + 47 + /// URL to the application's homepage. 48 + public let clientUri: String? 49 + 50 + /// URL to the application's terms of service. 51 + public let tosUri: String? 52 + 53 + /// URL to the application's privacy policy. 54 + public let policyUri: String? 55 + 56 + /// JWK Set for confidential clients (inline). 57 + public let jwks: JWKSet? 58 + 59 + /// URL to JWK Set for confidential clients. 60 + public let jwksUri: String? 61 + 62 + enum CodingKeys: String, CodingKey { 63 + case clientId = "client_id" 64 + case applicationType = "application_type" 65 + case grantTypes = "grant_types" 66 + case scope 67 + case responseTypes = "response_types" 68 + case redirectUris = "redirect_uris" 69 + case dpopBoundAccessTokens = "dpop_bound_access_tokens" 70 + case tokenEndpointAuthMethod = "token_endpoint_auth_method" 71 + case clientName = "client_name" 72 + case logoUri = "logo_uri" 73 + case clientUri = "client_uri" 74 + case tosUri = "tos_uri" 75 + case policyUri = "policy_uri" 76 + case jwks 77 + case jwksUri = "jwks_uri" 78 + } 79 + 80 + /// Application type for OAuth clients. 81 + public enum ApplicationType: String, Codable, Sendable, Hashable { 82 + case web 83 + case native 84 + } 85 + 86 + /// Creates a new client metadata document for a public (native) client. 87 + /// - Parameters: 88 + /// - clientId: The client_id URL where this metadata will be published 89 + /// - redirectUri: The callback URI for OAuth redirects 90 + /// - clientName: Human-readable application name 91 + /// - scope: OAuth scopes (default includes "atproto" and "transition:generic") 92 + /// - logoUri: Optional logo URL 93 + /// - clientUri: Optional homepage URL 94 + /// - tosUri: Optional terms of service URL 95 + /// - policyUri: Optional privacy policy URL 96 + public init( 97 + clientId: String, 98 + redirectUri: String, 99 + clientName: String, 100 + scope: String = "atproto transition:generic", 101 + logoUri: String? = nil, 102 + clientUri: String? = nil, 103 + tosUri: String? = nil, 104 + policyUri: String? = nil 105 + ) { 106 + self.clientId = clientId 107 + self.applicationType = .native 108 + self.grantTypes = ["authorization_code", "refresh_token"] 109 + self.scope = scope 110 + self.responseTypes = ["code"] 111 + self.redirectUris = [redirectUri] 112 + self.dpopBoundAccessTokens = true 113 + self.tokenEndpointAuthMethod = "none" 114 + self.clientName = clientName 115 + self.logoUri = logoUri 116 + self.clientUri = clientUri 117 + self.tosUri = tosUri 118 + self.policyUri = policyUri 119 + self.jwks = nil 120 + self.jwksUri = nil 121 + } 122 + 123 + /// Creates a new client metadata document for a confidential (web) client. 124 + /// - Parameters: 125 + /// - clientId: The client_id URL where this metadata will be published 126 + /// - redirectUri: The callback URI for OAuth redirects 127 + /// - clientName: Human-readable application name 128 + /// - jwksUri: URL to the JWK Set containing the client's public keys 129 + /// - scope: OAuth scopes (default includes "atproto" and "transition:generic") 130 + /// - logoUri: Optional logo URL 131 + /// - clientUri: Optional homepage URL 132 + /// - tosUri: Optional terms of service URL 133 + /// - policyUri: Optional privacy policy URL 134 + public init( 135 + clientId: String, 136 + redirectUri: String, 137 + clientName: String, 138 + jwksUri: String, 139 + scope: String = "atproto transition:generic", 140 + logoUri: String? = nil, 141 + clientUri: String? = nil, 142 + tosUri: String? = nil, 143 + policyUri: String? = nil 144 + ) { 145 + self.clientId = clientId 146 + self.applicationType = .web 147 + self.grantTypes = ["authorization_code", "refresh_token"] 148 + self.scope = scope 149 + self.responseTypes = ["code"] 150 + self.redirectUris = [redirectUri] 151 + self.dpopBoundAccessTokens = true 152 + self.tokenEndpointAuthMethod = "private_key_jwt" 153 + self.clientName = clientName 154 + self.logoUri = logoUri 155 + self.clientUri = clientUri 156 + self.tosUri = tosUri 157 + self.policyUri = policyUri 158 + self.jwks = nil 159 + self.jwksUri = jwksUri 160 + } 161 + 162 + /// Encodes this metadata as JSON suitable for publishing. 163 + public func toJSON() throws -> Data { 164 + let encoder = JSONEncoder() 165 + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] 166 + return try encoder.encode(self) 167 + } 168 + 169 + /// Encodes this metadata as a JSON string suitable for publishing. 170 + public func toJSONString() throws -> String { 171 + let data = try toJSON() 172 + guard let string = String(data: data, encoding: .utf8) else { 173 + throw OAuthError.invalidConfiguration(reason: "Failed to encode metadata as UTF-8") 174 + } 175 + return string 176 + } 177 + 178 + /// Validates this metadata against AT Protocol OAuth requirements. 179 + public func validate() throws { 180 + // Validate client_id is HTTPS 181 + guard clientId.hasPrefix("https://") || clientId.hasPrefix("http://localhost") else { 182 + throw OAuthError.invalidConfiguration(reason: "client_id must be HTTPS URL (except localhost)") 183 + } 184 + 185 + // Validate required grant types 186 + guard grantTypes.contains("authorization_code") else { 187 + throw OAuthError.invalidConfiguration(reason: "grant_types must include 'authorization_code'") 188 + } 189 + guard grantTypes.contains("refresh_token") else { 190 + throw OAuthError.invalidConfiguration(reason: "grant_types must include 'refresh_token'") 191 + } 192 + 193 + // Validate scope includes atproto 194 + guard scope.contains("atproto") else { 195 + throw OAuthError.invalidConfiguration(reason: "scope must include 'atproto'") 196 + } 197 + 198 + // Validate response types 199 + guard responseTypes.contains("code") else { 200 + throw OAuthError.invalidConfiguration(reason: "response_types must include 'code'") 201 + } 202 + 203 + // Validate redirect URIs 204 + guard !redirectUris.isEmpty else { 205 + throw OAuthError.invalidConfiguration(reason: "At least one redirect_uri is required") 206 + } 207 + 208 + // Validate DPoP requirement 209 + guard dpopBoundAccessTokens else { 210 + throw OAuthError.invalidConfiguration(reason: "dpop_bound_access_tokens must be true") 211 + } 212 + 213 + // Validate confidential client has keys 214 + if tokenEndpointAuthMethod == "private_key_jwt" { 215 + guard jwks != nil || jwksUri != nil else { 216 + throw OAuthError.invalidConfiguration(reason: "Confidential clients must provide jwks or jwks_uri") 217 + } 218 + } 219 + } 220 + } 221 + 222 + /// JWK Set structure for confidential clients. 223 + public struct JWKSet: Codable, Sendable, Hashable { 224 + public let keys: [JWK] 225 + 226 + public init(keys: [JWK]) { 227 + self.keys = keys 228 + } 229 + } 230 + 231 + /// JSON Web Key structure. 232 + public struct JWK: Codable, Sendable, Hashable { 233 + public let kty: String 234 + public let crv: String? 235 + public let x: String? 236 + public let y: String? 237 + public let kid: String? 238 + public let use: String? 239 + public let alg: String? 240 + 241 + public init( 242 + kty: String, 243 + crv: String? = nil, 244 + x: String? = nil, 245 + y: String? = nil, 246 + kid: String? = nil, 247 + use: String? = nil, 248 + alg: String? = nil 249 + ) { 250 + self.kty = kty 251 + self.crv = crv 252 + self.x = x 253 + self.y = y 254 + self.kid = kid 255 + self.use = use 256 + self.alg = alg 257 + } 258 + 259 + /// Creates an ES256 public key JWK from coordinates. 260 + public static func es256PublicKey(x: String, y: String, kid: String? = nil) -> JWK { 261 + JWK(kty: "EC", crv: "P-256", x: x, y: y, kid: kid, use: "sig", alg: "ES256") 262 + } 263 + }
+139
Sources/CoreATProtocol/OAuth/OAuthError.swift
··· 1 + // 2 + // OAuthError.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Foundation 9 + 10 + /// Errors specific to OAuth operations in AT Protocol. 11 + public enum OAuthError: Error, Sendable, Hashable { 12 + // MARK: - Token Errors 13 + case accessTokenExpired 14 + case refreshTokenExpired 15 + case refreshTokenMissing 16 + case refreshFailed(reason: String) 17 + case tokenExchangeFailed(reason: String) 18 + 19 + // MARK: - Configuration Errors 20 + case missingServerMetadata 21 + case missingClientMetadata 22 + case missingCredentials 23 + case invalidConfiguration(reason: String) 24 + 25 + // MARK: - Authorization Errors 26 + case authorizationDenied 27 + case invalidState 28 + case invalidScope 29 + case parRequestFailed(reason: String) 30 + 31 + // MARK: - DPoP Errors 32 + case dpopRequired 33 + case dpopNonceMissing 34 + case dpopSigningFailed(reason: String) 35 + case dpopKeyMissing 36 + 37 + // MARK: - Identity Errors 38 + case subjectMismatch(expected: String, received: String) 39 + case issuerMismatch(expected: String, received: String) 40 + 41 + // MARK: - Storage Errors 42 + case storageFailed(reason: String) 43 + case loginNotFound 44 + } 45 + 46 + extension OAuthError: LocalizedError { 47 + public var errorDescription: String? { 48 + switch self { 49 + case .accessTokenExpired: 50 + return "Access token has expired" 51 + case .refreshTokenExpired: 52 + return "Refresh token has expired" 53 + case .refreshTokenMissing: 54 + return "No refresh token available" 55 + case .refreshFailed(let reason): 56 + return "Token refresh failed: \(reason)" 57 + case .tokenExchangeFailed(let reason): 58 + return "Token exchange failed: \(reason)" 59 + case .missingServerMetadata: 60 + return "Server metadata is not available" 61 + case .missingClientMetadata: 62 + return "Client metadata is not available" 63 + case .missingCredentials: 64 + return "App credentials are not configured" 65 + case .invalidConfiguration(let reason): 66 + return "Invalid OAuth configuration: \(reason)" 67 + case .authorizationDenied: 68 + return "Authorization was denied by the user" 69 + case .invalidState: 70 + return "State token mismatch - possible CSRF attack" 71 + case .invalidScope: 72 + return "Requested scope was not granted" 73 + case .parRequestFailed(let reason): 74 + return "Pushed Authorization Request failed: \(reason)" 75 + case .dpopRequired: 76 + return "DPoP is required but not configured" 77 + case .dpopNonceMissing: 78 + return "DPoP nonce was not provided by server" 79 + case .dpopSigningFailed(let reason): 80 + return "DPoP JWT signing failed: \(reason)" 81 + case .dpopKeyMissing: 82 + return "DPoP private key is not available" 83 + case .subjectMismatch(let expected, let received): 84 + return "Subject mismatch: expected \(expected), received \(received)" 85 + case .issuerMismatch(let expected, let received): 86 + return "Issuer mismatch: expected \(expected), received \(received)" 87 + case .storageFailed(let reason): 88 + return "Token storage failed: \(reason)" 89 + case .loginNotFound: 90 + return "No stored login found" 91 + } 92 + } 93 + } 94 + 95 + /// Response from a token refresh request. 96 + public struct TokenRefreshResponse: Codable, Sendable { 97 + public let accessToken: String 98 + public let refreshToken: String? 99 + public let tokenType: String 100 + public let expiresIn: Int 101 + public let scope: String? 102 + public let sub: String 103 + 104 + enum CodingKeys: String, CodingKey { 105 + case accessToken = "access_token" 106 + case refreshToken = "refresh_token" 107 + case tokenType = "token_type" 108 + case expiresIn = "expires_in" 109 + case scope 110 + case sub 111 + } 112 + 113 + public init( 114 + accessToken: String, 115 + refreshToken: String?, 116 + tokenType: String, 117 + expiresIn: Int, 118 + scope: String?, 119 + sub: String 120 + ) { 121 + self.accessToken = accessToken 122 + self.refreshToken = refreshToken 123 + self.tokenType = tokenType 124 + self.expiresIn = expiresIn 125 + self.scope = scope 126 + self.sub = sub 127 + } 128 + } 129 + 130 + /// Error response from OAuth endpoints. 131 + public struct OAuthErrorResponse: Codable, Sendable { 132 + public let error: String 133 + public let errorDescription: String? 134 + 135 + enum CodingKeys: String, CodingKey { 136 + case error 137 + case errorDescription = "error_description" 138 + } 139 + }
+204
Sources/CoreATProtocol/OAuth/RefreshService.swift
··· 1 + // 2 + // RefreshService.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Foundation 9 + import CryptoKit 10 + @preconcurrency import OAuthenticator 11 + 12 + /// Handles token refresh operations for AT Protocol OAuth. 13 + @APActor 14 + public final class RefreshService { 15 + 16 + /// Request body for token refresh. 17 + struct RefreshTokenRequest: Codable, Sendable { 18 + let refreshToken: String 19 + let grantType: String 20 + let clientId: String 21 + 22 + enum CodingKeys: String, CodingKey { 23 + case refreshToken = "refresh_token" 24 + case grantType = "grant_type" 25 + case clientId = "client_id" 26 + } 27 + 28 + init(refreshToken: String, clientId: String) { 29 + self.refreshToken = refreshToken 30 + self.grantType = "refresh_token" 31 + self.clientId = clientId 32 + } 33 + } 34 + 35 + private let urlSession: URLSession 36 + 37 + public init(urlSession: URLSession = .shared) { 38 + self.urlSession = urlSession 39 + } 40 + 41 + /// Refreshes tokens using the stored authentication state. 42 + /// - Parameters: 43 + /// - state: Current authentication state with refresh token 44 + /// - serverMetadata: OAuth server metadata with token endpoint 45 + /// - clientId: The client ID for the application 46 + /// - dpopGenerator: DPoP JWT generator for signing requests 47 + /// - Returns: Updated authentication state with new tokens 48 + public func refresh( 49 + state: AuthenticationState, 50 + serverMetadata: ServerMetadata, 51 + clientId: String, 52 + dpopGenerator: DPoPSigner.JWTGenerator? 53 + ) async throws -> AuthenticationState { 54 + guard let refreshToken = state.refreshToken else { 55 + throw OAuthError.refreshTokenMissing 56 + } 57 + 58 + guard !state.isRefreshTokenExpired else { 59 + throw OAuthError.refreshTokenExpired 60 + } 61 + 62 + guard let tokenURL = URL(string: serverMetadata.tokenEndpoint) else { 63 + throw OAuthError.invalidConfiguration(reason: "Invalid token endpoint URL") 64 + } 65 + 66 + let requestBody = RefreshTokenRequest(refreshToken: refreshToken, clientId: clientId) 67 + 68 + var request = URLRequest(url: tokenURL) 69 + request.httpMethod = "POST" 70 + request.setValue("application/json", forHTTPHeaderField: "Content-Type") 71 + request.setValue("application/json", forHTTPHeaderField: "Accept") 72 + request.httpBody = try JSONEncoder().encode(requestBody) 73 + 74 + // Add DPoP header if generator is available 75 + if let generator = dpopGenerator { 76 + let dpopSigner = DPoPSigner() 77 + dpopSigner.nonce = await APEnvironment.current.resourceServerNonce 78 + 79 + try await dpopSigner.authenticateRequest( 80 + &request, 81 + isolation: APActor.shared, 82 + using: generator, 83 + token: nil, 84 + tokenHash: nil, 85 + issuer: serverMetadata.issuer 86 + ) 87 + } 88 + 89 + let (data, response) = try await urlSession.data(for: request) 90 + 91 + guard let httpResponse = response as? HTTPURLResponse else { 92 + throw OAuthError.refreshFailed(reason: "Invalid response type") 93 + } 94 + 95 + // Update DPoP nonce from response 96 + if let newNonce = httpResponse.value(forHTTPHeaderField: "DPoP-Nonce") { 97 + await APEnvironment.current.setResourceServerNonce(newNonce) 98 + } 99 + 100 + guard (200...299).contains(httpResponse.statusCode) else { 101 + if let errorResponse = try? JSONDecoder().decode(OAuthErrorResponse.self, from: data) { 102 + throw OAuthError.refreshFailed(reason: errorResponse.errorDescription ?? errorResponse.error) 103 + } 104 + throw OAuthError.refreshFailed(reason: "HTTP \(httpResponse.statusCode)") 105 + } 106 + 107 + let tokenResponse = try JSONDecoder().decode(TokenRefreshResponse.self, from: data) 108 + 109 + // Verify token type is DPoP 110 + guard tokenResponse.tokenType.lowercased() == "dpop" else { 111 + throw OAuthError.dpopRequired 112 + } 113 + 114 + // Verify subject matches 115 + guard tokenResponse.sub == state.did else { 116 + throw OAuthError.subjectMismatch(expected: state.did, received: tokenResponse.sub) 117 + } 118 + 119 + return state.withUpdatedTokens( 120 + access: tokenResponse.accessToken, 121 + refresh: tokenResponse.refreshToken, 122 + expiresIn: tokenResponse.expiresIn 123 + ) 124 + } 125 + } 126 + 127 + // MARK: - APEnvironment Extension for Refresh 128 + 129 + extension APEnvironment { 130 + /// Performs token refresh and updates the environment. 131 + /// - Returns: true if refresh succeeded, false otherwise 132 + public func performTokenRefresh() async -> Bool { 133 + guard let state = authState else { 134 + return false 135 + } 136 + 137 + guard state.canRefresh else { 138 + return false 139 + } 140 + 141 + guard let serverMetadata = serverMetadata else { 142 + return false 143 + } 144 + 145 + guard let clientId = clientId else { 146 + return false 147 + } 148 + 149 + let refreshService = RefreshService() 150 + 151 + do { 152 + let newState = try await refreshService.refresh( 153 + state: state, 154 + serverMetadata: serverMetadata, 155 + clientId: clientId, 156 + dpopGenerator: dpopProofGenerator 157 + ) 158 + 159 + // Update environment with new tokens 160 + self.authState = newState 161 + self.accessToken = newState.accessToken 162 + self.refreshToken = newState.refreshToken 163 + 164 + // Update the Login object if present 165 + if var currentLogin = login { 166 + currentLogin.accessToken = Token( 167 + value: newState.accessToken, 168 + expiry: newState.accessTokenExpiry 169 + ) 170 + if let newRefresh = newState.refreshToken { 171 + currentLogin.refreshToken = Token(value: newRefresh) 172 + } 173 + self.login = currentLogin 174 + } 175 + 176 + // Notify delegate of token update 177 + await atProtocoldelegate?.tokensUpdated( 178 + accessToken: newState.accessToken, 179 + refreshToken: newState.refreshToken 180 + ) 181 + 182 + // Persist if storage is configured 183 + if let storage = tokenStorage { 184 + try? await storage.updateTokens( 185 + access: newState.accessToken, 186 + refresh: newState.refreshToken, 187 + expiresIn: Int(newState.accessTokenExpiry?.timeIntervalSinceNow ?? 3600) 188 + ) 189 + } 190 + 191 + return true 192 + } catch { 193 + // Log the error but don't throw - let caller handle retry logic 194 + print("Token refresh failed: \(error)") 195 + return false 196 + } 197 + } 198 + 199 + /// Sets the resource server DPoP nonce. 200 + public func setResourceServerNonce(_ nonce: String?) { 201 + resourceServerNonce = nonce 202 + resourceDPoPSigner.nonce = nonce 203 + } 204 + }
+239
Sources/CoreATProtocol/OAuth/TokenStorage.swift
··· 1 + // 2 + // TokenStorage.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Foundation 9 + @preconcurrency import OAuthenticator 10 + 11 + /// Protocol for persisting authentication tokens. 12 + /// Implementations should use secure storage such as Keychain on Apple platforms. 13 + public protocol TokenStorageProtocol: Sendable { 14 + /// Stores the complete authentication state. 15 + func store(_ authState: AuthenticationState) async throws 16 + 17 + /// Retrieves the stored authentication state. 18 + func retrieve() async throws -> AuthenticationState? 19 + 20 + /// Clears all stored authentication data. 21 + func clear() async throws 22 + 23 + /// Updates only the tokens without changing other state. 24 + func updateTokens(access: String, refresh: String?, expiresIn: Int) async throws 25 + } 26 + 27 + /// Complete authentication state to be persisted. 28 + public struct AuthenticationState: Codable, Sendable { 29 + public let did: String 30 + public let handle: String? 31 + public let pdsURL: String 32 + public let authServerURL: String 33 + public let accessToken: String 34 + public let accessTokenExpiry: Date? 35 + public let refreshToken: String? 36 + public let refreshTokenExpiry: Date? 37 + public let scope: String? 38 + public let dpopPrivateKeyData: Data? 39 + public let createdAt: Date 40 + public let updatedAt: Date 41 + 42 + public init( 43 + did: String, 44 + handle: String?, 45 + pdsURL: String, 46 + authServerURL: String, 47 + accessToken: String, 48 + accessTokenExpiry: Date?, 49 + refreshToken: String?, 50 + refreshTokenExpiry: Date? = nil, 51 + scope: String?, 52 + dpopPrivateKeyData: Data?, 53 + createdAt: Date = Date(), 54 + updatedAt: Date = Date() 55 + ) { 56 + self.did = did 57 + self.handle = handle 58 + self.pdsURL = pdsURL 59 + self.authServerURL = authServerURL 60 + self.accessToken = accessToken 61 + self.accessTokenExpiry = accessTokenExpiry 62 + self.refreshToken = refreshToken 63 + self.refreshTokenExpiry = refreshTokenExpiry 64 + self.scope = scope 65 + self.dpopPrivateKeyData = dpopPrivateKeyData 66 + self.createdAt = createdAt 67 + self.updatedAt = updatedAt 68 + } 69 + 70 + /// Creates an updated state with new tokens. 71 + public func withUpdatedTokens( 72 + access: String, 73 + refresh: String?, 74 + expiresIn: Int 75 + ) -> AuthenticationState { 76 + AuthenticationState( 77 + did: did, 78 + handle: handle, 79 + pdsURL: pdsURL, 80 + authServerURL: authServerURL, 81 + accessToken: access, 82 + accessTokenExpiry: Date().addingTimeInterval(TimeInterval(expiresIn)), 83 + refreshToken: refresh ?? refreshToken, 84 + refreshTokenExpiry: refreshTokenExpiry, 85 + scope: scope, 86 + dpopPrivateKeyData: dpopPrivateKeyData, 87 + createdAt: createdAt, 88 + updatedAt: Date() 89 + ) 90 + } 91 + 92 + /// Checks if the access token is expired or about to expire. 93 + public var isAccessTokenExpired: Bool { 94 + guard let expiry = accessTokenExpiry else { return false } 95 + // Consider expired if less than 60 seconds remaining 96 + return expiry.timeIntervalSinceNow < 60 97 + } 98 + 99 + /// Checks if the refresh token is expired. 100 + public var isRefreshTokenExpired: Bool { 101 + guard let expiry = refreshTokenExpiry else { return false } 102 + return expiry.timeIntervalSinceNow < 0 103 + } 104 + 105 + /// Checks if we can attempt a token refresh. 106 + public var canRefresh: Bool { 107 + refreshToken != nil && !isRefreshTokenExpired 108 + } 109 + } 110 + 111 + /// In-memory token storage for testing or temporary use. 112 + /// Not recommended for production - use Keychain-based storage instead. 113 + @APActor 114 + public final class InMemoryTokenStorage: TokenStorageProtocol { 115 + private var state: AuthenticationState? 116 + 117 + public init() {} 118 + 119 + public func store(_ authState: AuthenticationState) async throws { 120 + self.state = authState 121 + } 122 + 123 + public func retrieve() async throws -> AuthenticationState? { 124 + return state 125 + } 126 + 127 + public func clear() async throws { 128 + state = nil 129 + } 130 + 131 + public func updateTokens(access: String, refresh: String?, expiresIn: Int) async throws { 132 + guard let current = state else { 133 + throw OAuthError.loginNotFound 134 + } 135 + state = current.withUpdatedTokens(access: access, refresh: refresh, expiresIn: expiresIn) 136 + } 137 + } 138 + 139 + #if canImport(Security) 140 + import Security 141 + 142 + /// Keychain-based token storage for secure persistence on Apple platforms. 143 + @APActor 144 + public final class KeychainTokenStorage: TokenStorageProtocol { 145 + private let service: String 146 + private let account: String 147 + private let accessGroup: String? 148 + 149 + /// Creates a new Keychain storage instance. 150 + /// - Parameters: 151 + /// - service: The service identifier (typically your app's bundle ID) 152 + /// - account: The account identifier (can be a constant or user-specific) 153 + /// - accessGroup: Optional access group for sharing between apps 154 + public init(service: String, account: String = "atproto_auth", accessGroup: String? = nil) { 155 + self.service = service 156 + self.account = account 157 + self.accessGroup = accessGroup 158 + } 159 + 160 + public func store(_ authState: AuthenticationState) async throws { 161 + let data = try JSONEncoder().encode(authState) 162 + 163 + var query: [String: Any] = [ 164 + kSecClass as String: kSecClassGenericPassword, 165 + kSecAttrService as String: service, 166 + kSecAttrAccount as String: account, 167 + kSecValueData as String: data, 168 + kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly 169 + ] 170 + 171 + if let group = accessGroup { 172 + query[kSecAttrAccessGroup as String] = group 173 + } 174 + 175 + // Delete existing item first 176 + let deleteQuery: [String: Any] = [ 177 + kSecClass as String: kSecClassGenericPassword, 178 + kSecAttrService as String: service, 179 + kSecAttrAccount as String: account 180 + ] 181 + SecItemDelete(deleteQuery as CFDictionary) 182 + 183 + let status = SecItemAdd(query as CFDictionary, nil) 184 + 185 + guard status == errSecSuccess else { 186 + throw OAuthError.storageFailed(reason: "Keychain write failed with status: \(status)") 187 + } 188 + } 189 + 190 + public func retrieve() async throws -> AuthenticationState? { 191 + var query: [String: Any] = [ 192 + kSecClass as String: kSecClassGenericPassword, 193 + kSecAttrService as String: service, 194 + kSecAttrAccount as String: account, 195 + kSecReturnData as String: true, 196 + kSecMatchLimit as String: kSecMatchLimitOne 197 + ] 198 + 199 + if let group = accessGroup { 200 + query[kSecAttrAccessGroup as String] = group 201 + } 202 + 203 + var result: AnyObject? 204 + let status = SecItemCopyMatching(query as CFDictionary, &result) 205 + 206 + guard status == errSecSuccess, let data = result as? Data else { 207 + if status == errSecItemNotFound { 208 + return nil 209 + } 210 + throw OAuthError.storageFailed(reason: "Keychain read failed with status: \(status)") 211 + } 212 + 213 + return try JSONDecoder().decode(AuthenticationState.self, from: data) 214 + } 215 + 216 + public func clear() async throws { 217 + let query: [String: Any] = [ 218 + kSecClass as String: kSecClassGenericPassword, 219 + kSecAttrService as String: service, 220 + kSecAttrAccount as String: account 221 + ] 222 + 223 + let status = SecItemDelete(query as CFDictionary) 224 + 225 + guard status == errSecSuccess || status == errSecItemNotFound else { 226 + throw OAuthError.storageFailed(reason: "Keychain delete failed with status: \(status)") 227 + } 228 + } 229 + 230 + public func updateTokens(access: String, refresh: String?, expiresIn: Int) async throws { 231 + guard let current = try await retrieve() else { 232 + throw OAuthError.loginNotFound 233 + } 234 + 235 + let updated = current.withUpdatedTokens(access: access, refresh: refresh, expiresIn: expiresIn) 236 + try await store(updated) 237 + } 238 + } 239 + #endif
+190
Tests/CoreATProtocolTests/ATErrorTests.swift
··· 1 + // 2 + // ATErrorTests.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Testing 9 + import Foundation 10 + @testable import CoreATProtocol 11 + 12 + @Suite("AT Error Tests") 13 + struct ATErrorTests { 14 + 15 + // MARK: - ErrorMessage Tests 16 + 17 + @Test("ErrorMessage parses from JSON") 18 + func testErrorMessageParsing() throws { 19 + let json = """ 20 + { 21 + "error": "ExpiredToken", 22 + "message": "The access token has expired" 23 + } 24 + """.data(using: .utf8)! 25 + 26 + let message = try JSONDecoder().decode(ErrorMessage.self, from: json) 27 + 28 + #expect(message.error == "ExpiredToken") 29 + #expect(message.message == "The access token has expired") 30 + #expect(message.errorType == .expiredToken) 31 + } 32 + 33 + @Test("ErrorMessage handles unknown error types") 34 + func testUnknownErrorType() throws { 35 + let json = """ 36 + { 37 + "error": "SomeNewError", 38 + "message": "An unknown error occurred" 39 + } 40 + """.data(using: .utf8)! 41 + 42 + let message = try JSONDecoder().decode(ErrorMessage.self, from: json) 43 + 44 + #expect(message.error == "SomeNewError") 45 + #expect(message.errorType == nil) 46 + } 47 + 48 + @Test("ErrorMessage handles missing message field") 49 + func testMissingMessage() throws { 50 + let json = """ 51 + { 52 + "error": "InvalidRequest" 53 + } 54 + """.data(using: .utf8)! 55 + 56 + let message = try JSONDecoder().decode(ErrorMessage.self, from: json) 57 + 58 + #expect(message.error == "InvalidRequest") 59 + #expect(message.message == nil) 60 + } 61 + 62 + // MARK: - AtErrorType Tests 63 + 64 + @Test("All error types have descriptions") 65 + func testErrorTypeDescriptions() { 66 + for errorType in AtErrorType.allCases { 67 + #expect(!errorType.description.isEmpty, "\(errorType) should have a description") 68 + } 69 + } 70 + 71 + @Test("Error types decode correctly") 72 + func testErrorTypeDecoding() throws { 73 + let testCases: [(String, AtErrorType)] = [ 74 + ("\"AuthenticationRequired\"", .authenticationRequired), 75 + ("\"ExpiredToken\"", .expiredToken), 76 + ("\"RateLimitExceeded\"", .rateLimitExceeded), 77 + ("\"RecordNotFound\"", .recordNotFound), 78 + ("\"BlobTooLarge\"", .blobTooLarge) 79 + ] 80 + 81 + for (json, expected) in testCases { 82 + let data = json.data(using: .utf8)! 83 + let decoded = try JSONDecoder().decode(AtErrorType.self, from: data) 84 + #expect(decoded == expected) 85 + } 86 + } 87 + 88 + // MARK: - AtError Tests 89 + 90 + @Test("AtError.requiresReauthentication identifies auth errors") 91 + func testRequiresReauthentication() { 92 + let expiredTokenError = AtError.message(ErrorMessage(error: "ExpiredToken", message: nil)) 93 + #expect(expiredTokenError.requiresReauthentication == true) 94 + 95 + let authRequiredError = AtError.message(ErrorMessage(error: "AuthenticationRequired", message: nil)) 96 + #expect(authRequiredError.requiresReauthentication == true) 97 + 98 + let notFoundError = AtError.message(ErrorMessage(error: "NotFound", message: nil)) 99 + #expect(notFoundError.requiresReauthentication == false) 100 + 101 + let unauthorized = AtError.network(NetworkError.statusCode(.unauthorized, data: Data())) 102 + #expect(unauthorized.requiresReauthentication == true) 103 + 104 + let serverError = AtError.network(NetworkError.statusCode(.internalServerError, data: Data())) 105 + #expect(serverError.requiresReauthentication == false) 106 + } 107 + 108 + @Test("AtError.isRetryable identifies retryable errors") 109 + func testIsRetryable() { 110 + let rateLimitError = AtError.message(ErrorMessage(error: "RateLimitExceeded", message: nil)) 111 + #expect(rateLimitError.isRetryable == true) 112 + 113 + let serverError = AtError.network(NetworkError.statusCode(.internalServerError, data: Data())) 114 + #expect(serverError.isRetryable == true) 115 + 116 + let badRequestError = AtError.network(NetworkError.statusCode(.badRequest, data: Data())) 117 + #expect(badRequestError.isRetryable == false) 118 + 119 + let notFoundError = AtError.message(ErrorMessage(error: "NotFound", message: nil)) 120 + #expect(notFoundError.isRetryable == false) 121 + } 122 + 123 + // MARK: - RateLimitInfo Tests 124 + 125 + @Test("RateLimitInfo parses from headers") 126 + func testRateLimitParsing() { 127 + // Create a mock response with rate limit headers 128 + let url = URL(string: "https://example.com")! 129 + let headers = [ 130 + "RateLimit-Limit": "100", 131 + "RateLimit-Remaining": "50", 132 + "RateLimit-Reset": "1704067200" 133 + ] 134 + 135 + let response = HTTPURLResponse( 136 + url: url, 137 + statusCode: 200, 138 + httpVersion: nil, 139 + headerFields: headers 140 + )! 141 + 142 + let rateLimitInfo = RateLimitInfo.from(response: response) 143 + 144 + #expect(rateLimitInfo != nil) 145 + #expect(rateLimitInfo?.limit == 100) 146 + #expect(rateLimitInfo?.remaining == 50) 147 + #expect(rateLimitInfo?.resetTimestamp == 1704067200) 148 + } 149 + 150 + @Test("RateLimitInfo returns nil for missing headers") 151 + func testRateLimitMissingHeaders() { 152 + let url = URL(string: "https://example.com")! 153 + let response = HTTPURLResponse( 154 + url: url, 155 + statusCode: 200, 156 + httpVersion: nil, 157 + headerFields: [:] 158 + )! 159 + 160 + let rateLimitInfo = RateLimitInfo.from(response: response) 161 + #expect(rateLimitInfo == nil) 162 + } 163 + 164 + @Test("RateLimitInfo calculates time until reset") 165 + func testTimeUntilReset() { 166 + let futureReset = Date().timeIntervalSince1970 + 300 // 5 minutes from now 167 + let info = RateLimitInfo(limit: 100, remaining: 0, resetTimestamp: futureReset) 168 + 169 + #expect(info.timeUntilReset > 0) 170 + #expect(info.timeUntilReset <= 300) 171 + } 172 + 173 + // MARK: - OAuthError Tests 174 + 175 + @Test("OAuthError has localized descriptions") 176 + func testOAuthErrorDescriptions() { 177 + let errors: [OAuthError] = [ 178 + .accessTokenExpired, 179 + .refreshTokenMissing, 180 + .dpopRequired, 181 + .storageFailed(reason: "Test reason"), 182 + .subjectMismatch(expected: "did:plc:a", received: "did:plc:b") 183 + ] 184 + 185 + for error in errors { 186 + #expect(error.errorDescription != nil, "\(error) should have a description") 187 + #expect(!error.errorDescription!.isEmpty) 188 + } 189 + } 190 + }
+178
Tests/CoreATProtocolTests/ClientMetadataTests.swift
··· 1 + // 2 + // ClientMetadataTests.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Testing 9 + import Foundation 10 + @testable import CoreATProtocol 11 + 12 + @Suite("Client Metadata Tests") 13 + struct ClientMetadataTests { 14 + 15 + @Test("Creates valid public client metadata") 16 + func testPublicClientMetadata() throws { 17 + let metadata = ATClientMetadata( 18 + clientId: "https://example.com/client-metadata.json", 19 + redirectUri: "com.example.app://oauth/callback", 20 + clientName: "My AT Proto App" 21 + ) 22 + 23 + #expect(metadata.clientId == "https://example.com/client-metadata.json") 24 + #expect(metadata.applicationType == .native) 25 + #expect(metadata.tokenEndpointAuthMethod == "none") 26 + #expect(metadata.dpopBoundAccessTokens == true) 27 + #expect(metadata.grantTypes.contains("authorization_code")) 28 + #expect(metadata.grantTypes.contains("refresh_token")) 29 + #expect(metadata.responseTypes.contains("code")) 30 + #expect(metadata.scope.contains("atproto")) 31 + } 32 + 33 + @Test("Creates valid confidential client metadata") 34 + func testConfidentialClientMetadata() throws { 35 + let metadata = ATClientMetadata( 36 + clientId: "https://webapp.example.com/client-metadata.json", 37 + redirectUri: "https://webapp.example.com/oauth/callback", 38 + clientName: "My Web App", 39 + jwksUri: "https://webapp.example.com/.well-known/jwks.json" 40 + ) 41 + 42 + #expect(metadata.applicationType == .web) 43 + #expect(metadata.tokenEndpointAuthMethod == "private_key_jwt") 44 + #expect(metadata.jwksUri == "https://webapp.example.com/.well-known/jwks.json") 45 + } 46 + 47 + @Test("Metadata validates HTTPS requirement") 48 + func testHTTPSValidation() { 49 + let invalidMetadata = ATClientMetadata( 50 + clientId: "http://insecure.example.com/metadata.json", 51 + redirectUri: "com.example.app://callback", 52 + clientName: "Insecure App" 53 + ) 54 + 55 + #expect(throws: OAuthError.self) { 56 + try invalidMetadata.validate() 57 + } 58 + } 59 + 60 + @Test("Metadata allows localhost for development") 61 + func testLocalhostAllowed() throws { 62 + let metadata = ATClientMetadata( 63 + clientId: "http://localhost/client-metadata.json", 64 + redirectUri: "http://127.0.0.1/callback", 65 + clientName: "Dev App" 66 + ) 67 + 68 + // Should not throw 69 + try metadata.validate() 70 + } 71 + 72 + @Test("Metadata validates atproto scope requirement") 73 + func testScopeValidation() { 74 + // Create metadata with custom scope missing atproto 75 + let json = """ 76 + { 77 + "client_id": "https://example.com/metadata.json", 78 + "application_type": "native", 79 + "grant_types": ["authorization_code", "refresh_token"], 80 + "scope": "openid profile", 81 + "response_types": ["code"], 82 + "redirect_uris": ["com.example://callback"], 83 + "dpop_bound_access_tokens": true, 84 + "token_endpoint_auth_method": "none" 85 + } 86 + """.data(using: .utf8)! 87 + 88 + do { 89 + let metadata = try JSONDecoder().decode(ATClientMetadata.self, from: json) 90 + 91 + #expect(throws: OAuthError.self) { 92 + try metadata.validate() 93 + } 94 + } catch { 95 + Issue.record("Failed to decode metadata: \(error)") 96 + } 97 + } 98 + 99 + @Test("Metadata validates DPoP requirement") 100 + func testDPoPValidation() { 101 + let json = """ 102 + { 103 + "client_id": "https://example.com/metadata.json", 104 + "application_type": "native", 105 + "grant_types": ["authorization_code", "refresh_token"], 106 + "scope": "atproto", 107 + "response_types": ["code"], 108 + "redirect_uris": ["com.example://callback"], 109 + "dpop_bound_access_tokens": false, 110 + "token_endpoint_auth_method": "none" 111 + } 112 + """.data(using: .utf8)! 113 + 114 + do { 115 + let metadata = try JSONDecoder().decode(ATClientMetadata.self, from: json) 116 + 117 + #expect(throws: OAuthError.self) { 118 + try metadata.validate() 119 + } 120 + } catch { 121 + Issue.record("Failed to decode metadata: \(error)") 122 + } 123 + } 124 + 125 + @Test("Metadata encodes to valid JSON") 126 + func testJSONEncoding() throws { 127 + let metadata = ATClientMetadata( 128 + clientId: "https://myapp.example.com/client-metadata.json", 129 + redirectUri: "com.myapp://oauth", 130 + clientName: "My App", 131 + scope: "atproto transition:generic", 132 + logoUri: "https://myapp.example.com/logo.png", 133 + clientUri: "https://myapp.example.com", 134 + tosUri: "https://myapp.example.com/tos", 135 + policyUri: "https://myapp.example.com/privacy" 136 + ) 137 + 138 + let jsonString = try metadata.toJSONString() 139 + 140 + // Verify it's valid JSON by parsing it 141 + let data = jsonString.data(using: .utf8)! 142 + let parsed = try JSONDecoder().decode(ATClientMetadata.self, from: data) 143 + 144 + #expect(parsed.clientId == metadata.clientId) 145 + #expect(parsed.clientName == metadata.clientName) 146 + #expect(parsed.logoUri == metadata.logoUri) 147 + } 148 + 149 + @Test("JWK creates ES256 public key correctly") 150 + func testJWKCreation() { 151 + let jwk = JWK.es256PublicKey( 152 + x: "base64url-x-coordinate", 153 + y: "base64url-y-coordinate", 154 + kid: "key-1" 155 + ) 156 + 157 + #expect(jwk.kty == "EC") 158 + #expect(jwk.crv == "P-256") 159 + #expect(jwk.alg == "ES256") 160 + #expect(jwk.use == "sig") 161 + #expect(jwk.kid == "key-1") 162 + } 163 + 164 + @Test("JWKSet encodes correctly") 165 + func testJWKSetEncoding() throws { 166 + let jwkSet = JWKSet(keys: [ 167 + JWK.es256PublicKey(x: "x1", y: "y1", kid: "key-1"), 168 + JWK.es256PublicKey(x: "x2", y: "y2", kid: "key-2") 169 + ]) 170 + 171 + let encoded = try JSONEncoder().encode(jwkSet) 172 + let decoded = try JSONDecoder().decode(JWKSet.self, from: encoded) 173 + 174 + #expect(decoded.keys.count == 2) 175 + #expect(decoded.keys[0].kid == "key-1") 176 + #expect(decoded.keys[1].kid == "key-2") 177 + } 178 + }
+87 -2
Tests/CoreATProtocolTests/CoreATProtocolTests.swift
··· 1 1 import Testing 2 + import Foundation 2 3 @testable import CoreATProtocol 3 4 4 - @Test func example() async throws { 5 - // Write your test here and use APIs like `#expect(...)` to check expected conditions. 5 + @Suite("CoreATProtocol Environment Tests", .serialized) 6 + struct CoreATProtocolTests { 7 + 8 + @Test("Environment singleton is accessible") 9 + func testEnvironmentSingleton() async { 10 + // Clear state first 11 + await clearAuthenticationContext() 12 + 13 + // Just verify we can access the singleton 14 + let host = await APEnvironment.current.host 15 + #expect(host == nil) // Default state should have nil host 16 + } 17 + 18 + @Test("Setup configures environment correctly") 19 + func testSetup() async { 20 + // Clear previous state 21 + await clearAuthenticationContext() 22 + 23 + await setup( 24 + hostURL: "https://bsky.social", 25 + accessJWT: "test-access", 26 + refreshJWT: "test-refresh" 27 + ) 28 + 29 + let host = await APEnvironment.current.host 30 + let access = await APEnvironment.current.accessToken 31 + let refresh = await APEnvironment.current.refreshToken 32 + 33 + #expect(host == "https://bsky.social") 34 + #expect(access == "test-access") 35 + #expect(refresh == "test-refresh") 36 + 37 + // Clean up 38 + await clearAuthenticationContext() 39 + } 40 + 41 + @Test("Clear authentication context removes all tokens") 42 + func testClearContext() async { 43 + await setup( 44 + hostURL: "https://test.social", 45 + accessJWT: "access", 46 + refreshJWT: "refresh" 47 + ) 48 + 49 + await clearAuthenticationContext() 50 + 51 + let access = await APEnvironment.current.accessToken 52 + let refresh = await APEnvironment.current.refreshToken 53 + let login = await APEnvironment.current.login 54 + 55 + #expect(access == nil) 56 + #expect(refresh == nil) 57 + #expect(login == nil) 58 + } 59 + 60 + @Test("Update tokens modifies existing tokens") 61 + func testUpdateTokens() async { 62 + await setup(hostURL: nil, accessJWT: "old-access", refreshJWT: "old-refresh") 63 + await updateTokens(access: "new-access", refresh: "new-refresh") 64 + 65 + let access = await APEnvironment.current.accessToken 66 + let refresh = await APEnvironment.current.refreshToken 67 + 68 + #expect(access == "new-access") 69 + #expect(refresh == "new-refresh") 70 + 71 + await clearAuthenticationContext() 72 + } 73 + 74 + @Test("DPoP nonce update works correctly") 75 + func testDPoPNonceUpdate() async { 76 + await updateResourceDPoPNonce("test-nonce-123") 77 + 78 + let nonce = await APEnvironment.current.resourceServerNonce 79 + 80 + #expect(nonce == "test-nonce-123") 81 + 82 + await updateResourceDPoPNonce(nil) 83 + } 84 + 85 + @Test("hasValidSession returns false when no session") 86 + func testNoValidSession() async { 87 + await clearAuthenticationContext() 88 + let valid = await hasValidSession 89 + #expect(valid == false) 90 + } 6 91 }
+51
Tests/CoreATProtocolTests/DPoPJWTGeneratorTests.swift
··· 1 + // 2 + // DPoPJWTGeneratorTests.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Testing 9 + import Foundation 10 + import JWTKit 11 + @testable import CoreATProtocol 12 + 13 + @Suite("DPoP JWT Generator Tests", .serialized) 14 + struct DPoPJWTGeneratorTests { 15 + 16 + @Test("DPoP JWT Generator can be created with ES256 key") 17 + func testGeneratorCreation() async throws { 18 + let privateKey = ES256PrivateKey() 19 + let generator = try await DPoPJWTGenerator(privateKey: privateKey) 20 + 21 + // Verify we can get a JWT generator function 22 + _ = await generator.jwtGenerator() 23 + // If we get here without throwing, the test passes 24 + } 25 + 26 + @Test("DPoPKeyMaterialError cases exist") 27 + func testKeyMaterialErrors() { 28 + // Test error cases exist and are equatable 29 + let error1 = DPoPKeyMaterialError.publicKeyUnavailable 30 + let error2 = DPoPKeyMaterialError.invalidCoordinate 31 + 32 + #expect(error1 != error2) 33 + #expect(error1 == DPoPKeyMaterialError.publicKeyUnavailable) 34 + } 35 + 36 + @Test("Resource server nonce can be updated") 37 + func testResourceServerNonce() async { 38 + // Clear state first 39 + await updateResourceDPoPNonce(nil) 40 + 41 + // Set nonce using the public function 42 + await updateResourceDPoPNonce("test-nonce-value") 43 + let nonce = await APEnvironment.current.resourceServerNonce 44 + #expect(nonce == "test-nonce-value") 45 + 46 + // Clear it 47 + await updateResourceDPoPNonce(nil) 48 + let clearedNonce = await APEnvironment.current.resourceServerNonce 49 + #expect(clearedNonce == nil) 50 + } 51 + }
+119
Tests/CoreATProtocolTests/DateDecodingTests.swift
··· 1 + // 2 + // DateDecodingTests.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Testing 9 + import Foundation 10 + @testable import CoreATProtocol 11 + 12 + @Suite("Date Decoding Tests") 13 + struct DateDecodingTests { 14 + 15 + struct DateContainer: Decodable { 16 + let date: Date 17 + } 18 + 19 + @Test("Decodes ISO 8601 with milliseconds and Z timezone") 20 + func testMillisecondsWithZ() throws { 21 + let json = """ 22 + {"date": "2024-01-15T10:30:00.123Z"} 23 + """.data(using: .utf8)! 24 + 25 + let container = try JSONDecoder.atDecoder.decode(DateContainer.self, from: json) 26 + 27 + let calendar = Calendar(identifier: .gregorian) 28 + let components = calendar.dateComponents(in: TimeZone(identifier: "UTC")!, from: container.date) 29 + 30 + #expect(components.year == 2024) 31 + #expect(components.month == 1) 32 + #expect(components.day == 15) 33 + #expect(components.hour == 10) 34 + #expect(components.minute == 30) 35 + } 36 + 37 + @Test("Decodes ISO 8601 with offset timezone") 38 + func testWithOffset() throws { 39 + let json = """ 40 + {"date": "2024-06-20T15:45:30.000+00:00"} 41 + """.data(using: .utf8)! 42 + 43 + let container = try JSONDecoder.atDecoder.decode(DateContainer.self, from: json) 44 + 45 + let calendar = Calendar(identifier: .gregorian) 46 + let components = calendar.dateComponents(in: TimeZone(identifier: "UTC")!, from: container.date) 47 + 48 + #expect(components.year == 2024) 49 + #expect(components.month == 6) 50 + #expect(components.day == 20) 51 + #expect(components.hour == 15) 52 + #expect(components.minute == 45) 53 + } 54 + 55 + @Test("Decodes ISO 8601 without fractional seconds") 56 + func testWithoutFractional() throws { 57 + let json = """ 58 + {"date": "2024-03-10T08:00:00Z"} 59 + """.data(using: .utf8)! 60 + 61 + let container = try JSONDecoder.atDecoder.decode(DateContainer.self, from: json) 62 + 63 + let calendar = Calendar(identifier: .gregorian) 64 + let components = calendar.dateComponents(in: TimeZone(identifier: "UTC")!, from: container.date) 65 + 66 + #expect(components.year == 2024) 67 + #expect(components.month == 3) 68 + #expect(components.day == 10) 69 + } 70 + 71 + @Test("Decodes microseconds precision") 72 + func testMicroseconds() throws { 73 + let json = """ 74 + {"date": "2024-12-25T12:00:00.123456+00:00"} 75 + """.data(using: .utf8)! 76 + 77 + let container = try JSONDecoder.atDecoder.decode(DateContainer.self, from: json) 78 + 79 + // Just verify it parses without error 80 + #expect(container.date != Date.distantPast) 81 + } 82 + 83 + @Test("Multiple date formats in same response") 84 + func testMultipleFormats() throws { 85 + struct MultipleDates: Decodable { 86 + let createdAt: Date 87 + let indexedAt: Date 88 + let updatedAt: Date 89 + } 90 + 91 + let json = """ 92 + { 93 + "createdAt": "2024-01-01T00:00:00.000Z", 94 + "indexedAt": "2024-01-01T00:00:00Z", 95 + "updatedAt": "2024-01-01T00:00:00.000+00:00" 96 + } 97 + """.data(using: .utf8)! 98 + 99 + let dates = try JSONDecoder.atDecoder.decode(MultipleDates.self, from: json) 100 + 101 + // All should parse to the same time (within a small margin) 102 + let interval1 = abs(dates.createdAt.timeIntervalSince(dates.indexedAt)) 103 + let interval2 = abs(dates.createdAt.timeIntervalSince(dates.updatedAt)) 104 + 105 + #expect(interval1 < 1, "Dates should be within 1 second of each other") 106 + #expect(interval2 < 1, "Dates should be within 1 second of each other") 107 + } 108 + 109 + @Test("Throws on invalid date format") 110 + func testInvalidFormat() { 111 + let json = """ 112 + {"date": "not-a-date"} 113 + """.data(using: .utf8)! 114 + 115 + #expect(throws: DecodingError.self) { 116 + _ = try JSONDecoder.atDecoder.decode(DateContainer.self, from: json) 117 + } 118 + } 119 + }
+166
Tests/CoreATProtocolTests/IdentityResolverTests.swift
··· 1 + // 2 + // IdentityResolverTests.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Testing 9 + import Foundation 10 + @testable import CoreATProtocol 11 + 12 + @Suite("Identity Resolver Tests") 13 + struct IdentityResolverTests { 14 + 15 + // MARK: - DID Document Tests 16 + 17 + @Test("DID Document parses correctly") 18 + func testDIDDocumentParsing() throws { 19 + let json = """ 20 + { 21 + "@context": ["https://www.w3.org/ns/did/v1"], 22 + "id": "did:plc:abc123", 23 + "alsoKnownAs": ["at://alice.bsky.social"], 24 + "verificationMethod": [{ 25 + "id": "#atproto", 26 + "type": "Multikey", 27 + "controller": "did:plc:abc123", 28 + "publicKeyMultibase": "zDnae..." 29 + }], 30 + "service": [{ 31 + "id": "#atproto_pds", 32 + "type": "AtprotoPersonalDataServer", 33 + "serviceEndpoint": "https://bsky.social" 34 + }] 35 + } 36 + """.data(using: .utf8)! 37 + 38 + let document = try JSONDecoder().decode(DIDDocument.self, from: json) 39 + 40 + #expect(document.id == "did:plc:abc123") 41 + #expect(document.handle == "alice.bsky.social") 42 + #expect(document.pdsEndpoint == "https://bsky.social") 43 + #expect(document.verificationMethod?.count == 1) 44 + #expect(document.service?.count == 1) 45 + } 46 + 47 + @Test("DID Document extracts handle from alsoKnownAs") 48 + func testHandleExtraction() throws { 49 + let document = DIDDocument( 50 + id: "did:plc:test", 51 + alsoKnownAs: ["at://user.example.com", "https://other.url"], 52 + verificationMethod: nil, 53 + service: nil 54 + ) 55 + 56 + #expect(document.handle == "user.example.com") 57 + } 58 + 59 + @Test("DID Document returns nil handle when missing") 60 + func testMissingHandle() throws { 61 + let document = DIDDocument( 62 + id: "did:plc:test", 63 + alsoKnownAs: nil, 64 + verificationMethod: nil, 65 + service: nil 66 + ) 67 + 68 + #expect(document.handle == nil) 69 + } 70 + 71 + @Test("PLC Directory response converts to DID Document") 72 + func testPLCResponseConversion() throws { 73 + let json = """ 74 + { 75 + "did": "did:plc:xyz789", 76 + "alsoKnownAs": ["at://bob.test.com"], 77 + "verificationMethods": { 78 + "#atproto": "did:key:zDnae..." 79 + }, 80 + "services": { 81 + "#atproto_pds": { 82 + "type": "AtprotoPersonalDataServer", 83 + "endpoint": "https://pds.example.com" 84 + } 85 + } 86 + } 87 + """.data(using: .utf8)! 88 + 89 + let plcResponse = try JSONDecoder().decode(PLCDirectoryResponse.self, from: json) 90 + let document = plcResponse.toDIDDocument() 91 + 92 + #expect(document.id == "did:plc:xyz789") 93 + #expect(document.alsoKnownAs?.contains("at://bob.test.com") == true) 94 + } 95 + 96 + // MARK: - Identity Error Tests 97 + 98 + @Test("Identity errors are properly typed") 99 + func testIdentityErrors() { 100 + let handleError = IdentityError.invalidHandle("bad handle") 101 + let pdsError = IdentityError.pdsNotFound 102 + 103 + // Test error descriptions 104 + #expect(String(describing: handleError).contains("invalidHandle")) 105 + #expect(String(describing: pdsError).contains("pdsNotFound")) 106 + } 107 + 108 + // MARK: - Handle Validation Tests 109 + 110 + @Test("Valid handles are accepted") 111 + func testValidHandles() async throws { 112 + // These should be valid handle formats 113 + let validHandles = [ 114 + "alice.bsky.social", 115 + "user.example.com", 116 + "test.subdomain.domain.tld" 117 + ] 118 + 119 + for handle in validHandles { 120 + // Just testing the format is accepted 121 + let normalized = handle.lowercased() 122 + #expect(normalized.contains("."), "\(handle) should contain a dot") 123 + } 124 + } 125 + 126 + // MARK: - Cache Tests 127 + 128 + @Test("Cache is cleared correctly") 129 + func testCacheClear() async { 130 + let resolver = await IdentityResolver() 131 + await resolver.clearCache() 132 + // Should not throw 133 + } 134 + 135 + @Test("Cache TTL is configurable") 136 + func testCacheTTL() async { 137 + let resolver = await IdentityResolver() 138 + let defaultTTL = await resolver.cacheTTL 139 + #expect(defaultTTL == 600, "Default cache TTL should be 600 seconds") 140 + 141 + await MainActor.run { 142 + // Note: Need to access through proper isolation 143 + } 144 + } 145 + 146 + // MARK: - Protected Resource Metadata Tests 147 + 148 + @Test("Protected resource metadata parses correctly") 149 + func testProtectedResourceMetadata() throws { 150 + let json = """ 151 + { 152 + "resource": "https://bsky.social", 153 + "authorization_servers": ["https://bsky.social"] 154 + } 155 + """.data(using: .utf8)! 156 + 157 + let metadata = try JSONDecoder().decode( 158 + IdentityResolver.ProtectedResourceMetadata.self, 159 + from: json 160 + ) 161 + 162 + #expect(metadata.resource == "https://bsky.social") 163 + #expect(metadata.authorizationServers.count == 1) 164 + #expect(metadata.authorizationServers.first == "https://bsky.social") 165 + } 166 + }
+236
Tests/CoreATProtocolTests/TokenStorageTests.swift
··· 1 + // 2 + // TokenStorageTests.swift 3 + // CoreATProtocol 4 + // 5 + // Created by Claude on 2026-01-02. 6 + // 7 + 8 + import Testing 9 + import Foundation 10 + @testable import CoreATProtocol 11 + 12 + @Suite("Token Storage Tests") 13 + struct TokenStorageTests { 14 + 15 + // MARK: - AuthenticationState Tests 16 + 17 + @Test("AuthenticationState initializes correctly") 18 + func testAuthStateInit() { 19 + let state = AuthenticationState( 20 + did: "did:plc:test123", 21 + handle: "test.bsky.social", 22 + pdsURL: "https://bsky.social", 23 + authServerURL: "https://bsky.social", 24 + accessToken: "access-token-value", 25 + accessTokenExpiry: Date().addingTimeInterval(3600), 26 + refreshToken: "refresh-token-value", 27 + scope: "atproto transition:generic", 28 + dpopPrivateKeyData: nil 29 + ) 30 + 31 + #expect(state.did == "did:plc:test123") 32 + #expect(state.handle == "test.bsky.social") 33 + #expect(state.accessToken == "access-token-value") 34 + #expect(state.refreshToken == "refresh-token-value") 35 + } 36 + 37 + @Test("AuthenticationState detects expired access token") 38 + func testAccessTokenExpiry() { 39 + let expiredState = AuthenticationState( 40 + did: "did:plc:test", 41 + handle: nil, 42 + pdsURL: "https://pds.example.com", 43 + authServerURL: "https://auth.example.com", 44 + accessToken: "expired", 45 + accessTokenExpiry: Date().addingTimeInterval(-100), // Already expired 46 + refreshToken: nil, 47 + scope: nil, 48 + dpopPrivateKeyData: nil 49 + ) 50 + 51 + #expect(expiredState.isAccessTokenExpired == true) 52 + 53 + let validState = AuthenticationState( 54 + did: "did:plc:test", 55 + handle: nil, 56 + pdsURL: "https://pds.example.com", 57 + authServerURL: "https://auth.example.com", 58 + accessToken: "valid", 59 + accessTokenExpiry: Date().addingTimeInterval(3600), // Valid for 1 hour 60 + refreshToken: nil, 61 + scope: nil, 62 + dpopPrivateKeyData: nil 63 + ) 64 + 65 + #expect(validState.isAccessTokenExpired == false) 66 + } 67 + 68 + @Test("AuthenticationState.canRefresh checks refresh token") 69 + func testCanRefresh() { 70 + let withRefresh = AuthenticationState( 71 + did: "did:plc:test", 72 + handle: nil, 73 + pdsURL: "https://pds.example.com", 74 + authServerURL: "https://auth.example.com", 75 + accessToken: "access", 76 + accessTokenExpiry: nil, 77 + refreshToken: "refresh-token", 78 + refreshTokenExpiry: Date().addingTimeInterval(86400), // Valid for 1 day 79 + scope: nil, 80 + dpopPrivateKeyData: nil 81 + ) 82 + 83 + #expect(withRefresh.canRefresh == true) 84 + 85 + let withoutRefresh = AuthenticationState( 86 + did: "did:plc:test", 87 + handle: nil, 88 + pdsURL: "https://pds.example.com", 89 + authServerURL: "https://auth.example.com", 90 + accessToken: "access", 91 + accessTokenExpiry: nil, 92 + refreshToken: nil, 93 + scope: nil, 94 + dpopPrivateKeyData: nil 95 + ) 96 + 97 + #expect(withoutRefresh.canRefresh == false) 98 + } 99 + 100 + @Test("AuthenticationState updates tokens correctly") 101 + func testUpdateTokens() { 102 + let original = AuthenticationState( 103 + did: "did:plc:test", 104 + handle: "test.user", 105 + pdsURL: "https://pds.example.com", 106 + authServerURL: "https://auth.example.com", 107 + accessToken: "old-access", 108 + accessTokenExpiry: Date(), 109 + refreshToken: "old-refresh", 110 + scope: "atproto", 111 + dpopPrivateKeyData: nil 112 + ) 113 + 114 + let updated = original.withUpdatedTokens( 115 + access: "new-access", 116 + refresh: "new-refresh", 117 + expiresIn: 1800 118 + ) 119 + 120 + #expect(updated.accessToken == "new-access") 121 + #expect(updated.refreshToken == "new-refresh") 122 + #expect(updated.did == original.did) // DID should not change 123 + #expect(updated.handle == original.handle) // Handle should not change 124 + #expect(updated.updatedAt > original.updatedAt) 125 + } 126 + 127 + // MARK: - InMemoryTokenStorage Tests 128 + 129 + @Test("InMemoryTokenStorage stores and retrieves") 130 + func testInMemoryStorage() async throws { 131 + let storage = await InMemoryTokenStorage() 132 + 133 + let state = AuthenticationState( 134 + did: "did:plc:memory", 135 + handle: "memory.test", 136 + pdsURL: "https://pds.example.com", 137 + authServerURL: "https://auth.example.com", 138 + accessToken: "memory-token", 139 + accessTokenExpiry: Date().addingTimeInterval(3600), 140 + refreshToken: "memory-refresh", 141 + scope: "atproto", 142 + dpopPrivateKeyData: nil 143 + ) 144 + 145 + try await storage.store(state) 146 + let retrieved = try await storage.retrieve() 147 + 148 + #expect(retrieved != nil) 149 + #expect(retrieved?.did == "did:plc:memory") 150 + #expect(retrieved?.accessToken == "memory-token") 151 + } 152 + 153 + @Test("InMemoryTokenStorage clears correctly") 154 + func testInMemoryClear() async throws { 155 + let storage = await InMemoryTokenStorage() 156 + 157 + let state = AuthenticationState( 158 + did: "did:plc:clear", 159 + handle: nil, 160 + pdsURL: "https://pds.example.com", 161 + authServerURL: "https://auth.example.com", 162 + accessToken: "token", 163 + accessTokenExpiry: nil, 164 + refreshToken: nil, 165 + scope: nil, 166 + dpopPrivateKeyData: nil 167 + ) 168 + 169 + try await storage.store(state) 170 + try await storage.clear() 171 + let retrieved = try await storage.retrieve() 172 + 173 + #expect(retrieved == nil) 174 + } 175 + 176 + @Test("InMemoryTokenStorage updates tokens") 177 + func testInMemoryUpdate() async throws { 178 + let storage = await InMemoryTokenStorage() 179 + 180 + let state = AuthenticationState( 181 + did: "did:plc:update", 182 + handle: nil, 183 + pdsURL: "https://pds.example.com", 184 + authServerURL: "https://auth.example.com", 185 + accessToken: "original", 186 + accessTokenExpiry: Date(), 187 + refreshToken: "original-refresh", 188 + scope: nil, 189 + dpopPrivateKeyData: nil 190 + ) 191 + 192 + try await storage.store(state) 193 + try await storage.updateTokens(access: "updated", refresh: "updated-refresh", expiresIn: 3600) 194 + 195 + let retrieved = try await storage.retrieve() 196 + #expect(retrieved?.accessToken == "updated") 197 + #expect(retrieved?.refreshToken == "updated-refresh") 198 + } 199 + 200 + @Test("InMemoryTokenStorage throws when updating without stored state") 201 + func testInMemoryUpdateWithoutState() async { 202 + let storage = await InMemoryTokenStorage() 203 + 204 + await #expect(throws: OAuthError.self) { 205 + try await storage.updateTokens(access: "new", refresh: nil, expiresIn: 3600) 206 + } 207 + } 208 + 209 + // MARK: - AuthenticationState Codable Tests 210 + 211 + @Test("AuthenticationState encodes and decodes") 212 + func testAuthStateCodable() throws { 213 + let original = AuthenticationState( 214 + did: "did:plc:codable", 215 + handle: "codable.test", 216 + pdsURL: "https://pds.example.com", 217 + authServerURL: "https://auth.example.com", 218 + accessToken: "codable-access", 219 + accessTokenExpiry: Date().addingTimeInterval(3600), 220 + refreshToken: "codable-refresh", 221 + refreshTokenExpiry: Date().addingTimeInterval(86400), 222 + scope: "atproto transition:generic", 223 + dpopPrivateKeyData: Data([1, 2, 3, 4]) 224 + ) 225 + 226 + let encoded = try JSONEncoder().encode(original) 227 + let decoded = try JSONDecoder().decode(AuthenticationState.self, from: encoded) 228 + 229 + #expect(decoded.did == original.did) 230 + #expect(decoded.handle == original.handle) 231 + #expect(decoded.accessToken == original.accessToken) 232 + #expect(decoded.refreshToken == original.refreshToken) 233 + #expect(decoded.scope == original.scope) 234 + #expect(decoded.dpopPrivateKeyData == original.dpopPrivateKeyData) 235 + } 236 + }