Add complete OAuth 2.0 Authorization Code Flow with PKCE as alternative to API token authentication, with automatic server detection and graceful fallback to classic login. **OAuth Core (RFC 7636 PKCE):** - PKCEGenerator: S256 challenge generation for secure code exchange - OAuth DTOs: Client registration, token request/response models - OAuthClient, OAuthToken, AuthenticationMethod domain models - API.swift: registerOAuthClient() and exchangeOAuthToken() endpoints - OAuthRepository + POAuthRepository protocol **Browser Integration (ASWebAuthenticationSession):** - OAuthSession: Wraps native authentication session - OAuthFlowCoordinator: Orchestrates 5-phase OAuth flow - readeck:// URL scheme for OAuth callback handling - State verification for CSRF protection - User cancellation handling **Token Management:** - KeychainHelper: OAuth token storage alongside API tokens - TokenProvider: getOAuthToken(), setOAuthToken(), getAuthMethod() - AuthenticationMethod enum to distinguish token types - AuthRepository: loginWithOAuth(), getAuthenticationMethod() - Endpoint persistence in both Keychain and Settings **Server Feature Detection:** - ServerInfo extended with features array and supportsOAuth flag - GET /api/info endpoint integration (backward compatible) - GetServerInfoUseCase with optional endpoint parameter **User Profile Integration:** - ProfileApiClient: Fetch user data via GET /api/profile - UserProfileDto with username, email, provider information - GetUserProfileUseCase: Extract username from profile - Username saved and displayed for OAuth users (like classic auth) **Automatic OAuth Flow (No User Selection):** - OnboardingServerView: 2-phase flow (endpoint → auto-OAuth or classic) - OAuth attempted automatically if server supports it - Fallback to username/password on OAuth failure or unsupported - SettingsServerViewModel: checkServerOAuthSupport(), loginWithOAuth() **Cleanup & Refactoring:** - Remove all #if os(iOS) && !APP_EXTENSION conditionals - Remove LoginMethodSelectionView (no longer needed) - Remove switchToClassicLogin() method - Factories updated with OAuth dependencies **Testing:** - PKCEGeneratorTests: Verify RFC 7636 compliance - ServerInfoTests: Feature detection and backward compatibility - Mock implementations for all OAuth components **Documentation:** - docs/OAuth2-Implementation-Plan.md: Complete implementation guide - openapi.json: Readeck API specification **Scopes Requested:** - bookmarks:read, bookmarks:write, profile:read OAuth users now have full feature parity with classic authentication. Server auto-detects OAuth support via /info endpoint. Seamless UX with browser-based login and automatic fallback.
49 lines
1.9 KiB
Swift
49 lines
1.9 KiB
Swift
//
|
|
// PKCEGenerator.swift
|
|
// readeck
|
|
//
|
|
// Created by Ilyas Hallak on 15.12.25.
|
|
//
|
|
|
|
import Foundation
|
|
import CryptoKit
|
|
|
|
/// Generates PKCE (Proof Key for Code Exchange) verifier and challenge for OAuth 2.0
|
|
/// According to RFC 7636: https://datatracker.ietf.org/doc/html/rfc7636
|
|
struct PKCEGenerator {
|
|
|
|
/// Generates a cryptographically random code verifier
|
|
/// - Returns: A 64-character random alphanumeric string
|
|
static func generateCodeVerifier() -> String {
|
|
var buffer = [UInt8](repeating: 0, count: 64)
|
|
_ = SecRandomCopyBytes(kSecRandomDefault, buffer.count, &buffer)
|
|
|
|
let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
|
|
return buffer.map { String(alphabet[Int($0) % alphabet.count]) }.joined()
|
|
}
|
|
|
|
/// Generates a code challenge from a verifier using SHA-256 and base64url encoding
|
|
/// - Parameter verifier: The code verifier string
|
|
/// - Returns: Base64url-encoded SHA-256 hash (without padding)
|
|
static func generateCodeChallenge(from verifier: String) -> String {
|
|
guard let data = verifier.data(using: .utf8) else { return "" }
|
|
let hash = SHA256.hash(data: data)
|
|
let base64 = Data(hash).base64EncodedString()
|
|
|
|
// Convert to base64url (RFC 7636 Section 4.2)
|
|
// Replace '+' with '-', '/' with '_', and remove '=' padding
|
|
return base64
|
|
.replacingOccurrences(of: "+", with: "-")
|
|
.replacingOccurrences(of: "/", with: "_")
|
|
.replacingOccurrences(of: "=", with: "")
|
|
}
|
|
|
|
/// Generates both verifier and challenge in one call
|
|
/// - Returns: Tuple containing (verifier, challenge)
|
|
static func generate() -> (verifier: String, challenge: String) {
|
|
let verifier = generateCodeVerifier()
|
|
let challenge = generateCodeChallenge(from: verifier)
|
|
return (verifier, challenge)
|
|
}
|
|
}
|