SPB Git

Repository Public

AuthService.swift 21.3 KB 479 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Claude Remote / Codex Remote9// File             : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteAuth/AuthService.swift10// Module           : ClaudeRemoteAuth11// Repository       : https://git.spboucher.ai/claude-remote-apple12// Project Website  : https://claude.spboucher.ai13// Created          : 2026-11-2914// Last Modified    : 2026-11-2915//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import ClaudeRemoteAPI89import ClaudeRemoteModels90import Foundation9192/// Why the app is signed out.93public enum SignedOutReason: Hashable, Sendable {94    /// Nothing stored (first launch) or the user signed out.95    case none96    case userSignedOut97    /// The server revoked the session (device removed, password changed) or it reached its98    /// absolute / idle limit.99    case revoked100    /// The 15-minute second-factor window elapsed.101    case secondFactorTimedOut102}103104/// A sign-in waiting for its second factor (restricted session, in memory only).105public struct SecondFactorChallenge: Hashable, Sendable {106    /// What the server suggests first.107    public var preferred: LoginNext108    public var methods: SecondFactorMethods109    public var expiresAt: Date110    public var canUseTOTP: Bool { methods.totp }111    public var canUsePasskey: Bool { methods.passkeys > 0 }112}113114/// The signed-in session, without its secret.115public struct SessionInfo: Hashable, Sendable {116    public var sessionId: String117    public var username: String?118    /// Absolute end of the session (30 days).119    public var expiresAt: Date120}121122/// Server authentication state. Local app lock (`BiometricLock`) is a separate concern.123public enum AuthState: Hashable, Sendable {124    /// `restore()` has not run yet.125    case unknown126    case signedOut(SignedOutReason)127    /// Password accepted; TOTP code or passkey needed.128    case secondFactorRequired(SecondFactorChallenge)129    /// Password accepted but the account has no second factor yet: enrol a passkey or TOTP.130    case enrollmentRequired(expiresAt: Date)131    case signedIn(SessionInfo)132133    public var isSignedIn: Bool { if case .signedIn = self { true } else { false } }134}135136/// A state with its monotonically increasing version, so observers can drop stale deliveries.137public struct AuthStateUpdate: Hashable, Sendable {138    public var version: Int139    public var state: AuthState140}141142public enum AuthFlowError: Error, Hashable, Sendable, LocalizedError {143    /// The call does not apply to the current state (e.g. `submitTOTP` while signed out).144    case invalidState145    /// The server asked for a step this build does not know.146    case unsupportedStep(String)147    /// The enrolment was accepted but the session did not become fully authenticated.148    case enrollmentNotConfirmed149    public var errorDescription: String? {150        switch self {151        case .invalidState: "This step is not available right now."152        case .unsupportedStep(let s): "The server asked for an unsupported step (\(s)). Update the app."153        case .enrollmentNotConfirmed: "The second factor was saved but the session is not active yet. Sign in again."154        }155    }156}157158/// Native authentication (docs/NATIVE-API-CONTRACT.md §2): password (+TOTP), passkey second159/// step, passkey-only sign-in, device-bound refresh, sign-out, revocation.160///161/// Token lifecycle: the access token (1 h) and session ids live in the Keychain162/// (`CredentialStore`); `APIClient` holds the token in memory and calls `refreshSession()` —163/// signing the server challenge with the device key — when it expires. A 401 `unauthenticated`164/// wipes the credential and emits `.signedOut(.revoked)`.165public actor AuthService: SessionAuthority {166    public nonisolated let profile: AgentProfile167    private let client: APIClient168    private let credentials: CredentialStore169    private let deviceKeys: any DeviceKeyStore170    private let passkeys: any PasskeyAuthenticator171    private let localAuth: any LocalAuthenticating172    private let device: DeviceDescriptor173    private let now: @Sendable () -> Date174175    private var current: StoredCredential?176    /// Restricted session of a sign-in in progress.177    private var pending: NativeSession?178    private var pendingUsername: String?179    public private(set) var state: AuthState = .unknown180    private var version = 0181    private var observers: [UUID: AsyncStream<AuthStateUpdate>.Continuation] = [:]182183    public init(profile: AgentProfile, client: APIClient, credentials: CredentialStore, deviceKeys: any DeviceKeyStore,184                passkeys: any PasskeyAuthenticator, localAuth: any LocalAuthenticating = SystemLocalAuthenticator(),185                device: DeviceDescriptor, now: @escaping @Sendable () -> Date = { Date() }) {186        self.profile = profile187        self.client = client188        self.credentials = credentials189        self.deviceKeys = deviceKeys190        self.passkeys = passkeys191        self.localAuth = localAuth192        self.device = device193        self.now = now194    }195196    // MARK: State197198    /// Current state followed by every change. Any number of observers.199    public func updates() -> AsyncStream<AuthStateUpdate> {200        let id = UUID()201        let (stream, continuation) = AsyncStream<AuthStateUpdate>.makeStream(bufferingPolicy: .bufferingNewest(16))202        observers[id] = continuation203        continuation.yield(snapshot)204        continuation.onTermination = { [weak self] _ in Task { await self?.removeObserver(id) } }205        return stream206    }207208    private func removeObserver(_ id: UUID) { observers[id] = nil }209210    private func set(_ new: AuthState) {211        guard new != state else { return }212        state = new213        version += 1214        for c in observers.values { c.yield(snapshot) }215    }216217    /// The current state and its version.218    public var snapshot: AuthStateUpdate { AuthStateUpdate(version: version, state: state) }219220    /// Loads the stored session (no network). Call once at launch.221    @discardableResult222    public func restore() async -> AuthState {223        await client.setAuthority(self)224        if let stored = credentials.load(), stored.expiresAt > now() {225            current = stored226            await client.setCredential(stored.session)227            set(.signedIn(SessionInfo(sessionId: stored.sessionId, username: stored.username, expiresAt: stored.expiresAt)))228        } else {229            credentials.clear()230            current = nil231            await client.setCredential(nil)232            set(.signedOut(.none))233        }234        return state235    }236237    /// Stable identifier of this installation.238    public nonisolated var installID: String { credentials.installID() }239240    /// `NativeDevice` sent at sign-in (creates the device key on first use).241    public func nativeDevice() throws -> NativeDevice {242        let key = try deviceKeys.loadOrCreate()243        return NativeDevice(installId: credentials.installID(), name: device.name, platform: device.platform, model: device.model,244                            appVersion: device.appVersion, publicKey: key.publicKeyBase64)245    }246247    /// Whether the device key lives in the Secure Enclave.248    public func isDeviceKeyHardwareBacked() -> Bool { (try? deviceKeys.loadOrCreate().isHardwareBacked) ?? false }249250    // MARK: Sign-in251252    /// Password step, optionally with a TOTP code. Returns the new state: `.signedIn`,253    /// `.secondFactorRequired` or `.enrollmentRequired`.254    /// - Throws: `APIError` — `.invalidCredentials` (401), `.locked` with `retryAfter` (429), network…255    @discardableResult256    public func signIn(username: String, password: String, totp: String? = nil) async throws -> AuthState {257        await client.setAuthority(self)258        let request = NativeLoginRequest(username: username, password: password, totp: totp?.isEmpty == false ? totp : nil, device: try nativeDevice())259        let response = try await client.nativeLogin(request)260        pendingUsername = username261        return try await advance(response)262    }263264    /// TOTP second step.265    /// - Throws: `APIError` `.invalidCredentials` for a wrong code (the challenge stays valid).266    @discardableResult267    public func submitTOTP(code: String) async throws -> AuthState {268        guard let pending, case .secondFactorRequired = state else { throw AuthFlowError.invalidState }269        do {270            return try await advance(try await client.nativeTotp(code: code, token: pending.token))271        } catch {272            throw await pendingFailure(error)273        }274    }275276    /// Passkey as the second step of a password sign-in (system sheet: Touch ID / Face ID).277    @discardableResult278    public func completeSecondFactorWithPasskey() async throws -> AuthState {279        guard let pending, case .secondFactorRequired = state else { throw AuthFlowError.invalidState }280        do {281            let options = try await client.nativePasskeyOptions(token: pending.token).options282            let credential = try await assertion(options)283            return try await advance(try await client.nativePasskeyVerify(NativePasskeyVerifyRequest(credential: credential), token: pending.token))284        } catch {285            throw await pendingFailure(error)286        }287    }288289    /// Passkey-only sign-in with the same passkey as the website (discoverable credential, user290    /// verification): no password, no second step.291    @discardableResult292    public func signInWithPasskey() async throws -> AuthState {293        await client.setAuthority(self)294        let device = try nativeDevice()295        let response = try await client.nativePasskeyOptions()296        guard let challengeToken = response.challengeToken else {297            throw APIError.client("bad_response", "The server did not provide a passkey challenge.")298        }299        let credential = try await assertion(response.options)300        pendingUsername = nil301        return try await advance(try await client.nativePasskeyVerify(302            NativePasskeyVerifyRequest(credential: credential, challengeToken: challengeToken, device: device)))303    }304305    /// Abandons a sign-in waiting for its second factor.306    public func cancelSignIn() async {307        guard let pending else { return }308        self.pending = nil309        try? await client.logout(token: pending.token)310        set(.signedOut(.none))311    }312313    private func assertion(_ options: PasskeyRequestOptions) async throws -> PasskeyAssertionCredential {314        guard let challenge = Base64URL.decode(options.challenge) else {315            throw APIError.client("bad_response", "The server sent an invalid passkey challenge.")316        }317        let allow = (options.allowCredentials ?? []).compactMap { Base64URL.decode($0.id) }318        return try await passkeys.assertion(relyingParty: options.rpId ?? profile.relyingPartyID, challenge: challenge, allowCredentials: allow)319    }320321    private func advance(_ response: NativeLoginResponse) async throws -> AuthState {322        let session = response.session323        switch response.next {324        case .done:325            try await install(session)326        case .totp, .passkey:327            pending = session328            let methods = response.methods ?? SecondFactorMethods(totp: response.next == .totp, passkeys: response.next == .passkey ? 1 : 0)329            set(.secondFactorRequired(SecondFactorChallenge(preferred: response.next, methods: methods, expiresAt: session.expiresAt)))330        case .enrollSecondFactor:331            pending = session332            set(.enrollmentRequired(expiresAt: session.expiresAt))333        case .unknown(let raw):334            throw AuthFlowError.unsupportedStep(raw)335        }336        return state337    }338339    private func install(_ session: NativeSession) async throws {340        let stored = StoredCredential(session: session, username: pendingUsername ?? current?.username)341        try credentials.save(stored)342        current = stored343        pending = nil344        await client.setCredential(session)345        set(.signedIn(SessionInfo(sessionId: stored.sessionId, username: stored.username, expiresAt: stored.expiresAt)))346    }347348    /// A 401 `unauthenticated` during a second-factor step means the restricted session expired.349    private func pendingFailure(_ error: Error) async -> Error {350        if let api = error as? APIError, api.kind == .unauthenticated {351            pending = nil352            set(.signedOut(.secondFactorTimedOut))353        }354        return error355    }356357    // MARK: Second-factor enrolment and passkey registration358359    /// Token of the request: the restricted one while enrolling, else the stored session.360    private var enrollmentToken: String? { pending?.token }361362    public func startTOTPEnrollment() async throws -> TotpEnrollStart {363        try await client.totpEnrollStart(token: enrollmentToken)364    }365366    /// Confirms TOTP enrolment. During `.enrollmentRequired` this completes the sign-in.367    @discardableResult368    public func finishTOTPEnrollment(code: String) async throws -> AuthState {369        let step = try await client.totpEnrollFinish(code: code, token: enrollmentToken)370        return try await promotePendingIfNeeded(step)371    }372373    /// Creates a passkey for the account on this device (system sheet) and registers it.374    /// Works with a full session (add a passkey) and during `.enrollmentRequired`.375    @discardableResult376    public func registerPasskey(label: String? = nil) async throws -> AuthState {377        let options = try await client.passkeyRegisterOptions(token: enrollmentToken)378        guard let challenge = Base64URL.decode(options.challenge), let userID = Base64URL.decode(options.user.id) else {379            throw APIError.client("bad_response", "The server sent invalid passkey options.")380        }381        let exclude = (options.excludeCredentials ?? []).compactMap { Base64URL.decode($0.id) }382        let credential = try await passkeys.registration(relyingParty: options.rp.id ?? profile.relyingPartyID, challenge: challenge,383                                                         userName: options.user.name, userID: userID, excludeCredentials: exclude)384        let step = try await client.passkeyRegisterVerify(credential, label: label ?? device.name, token: enrollmentToken)385        return try await promotePendingIfNeeded(step)386    }387388    /// An enrolment made with the restricted bearer completes the sign-in: the answer carries the389    /// rotated, full `session`. (Fallback for a server that upgrades in place without returning390    /// it: confirm through `/auth/status` before persisting anything.)391    private func promotePendingIfNeeded(_ step: LoginStep) async throws -> AuthState {392        guard var session = pending else { return state }393        if let rotated = step.session, rotated.secondFactor {394            try await install(rotated)395            return state396        }397        let status: AuthStatus = try await client.send(.get, "/auth/status", auth: .token(session.token))398        guard status.authenticated else { throw AuthFlowError.enrollmentNotConfirmed }399        session.secondFactor = true400        if let end = status.sessionExpiresAt { session.expiresAt = end }401        if pendingUsername == nil { pendingUsername = status.user?.username }402        try await install(session)403        return state404    }405406    // MARK: Refresh, revocation, sign-out (SessionAuthority)407408    /// Device-bound refresh: `refresh/challenge` → sign `cr-native-refresh:v1:<sessionId>:<challenge>`409    /// with the device key → `refresh`. The old token dies at once.410    public func refreshSession() async throws -> NativeSession {411        guard let stored = current else { throw APIError.notSignedIn }412        do {413            let challenge = try await client.nativeRefreshChallenge(sessionId: stored.sessionId)414            let key = try deviceKeys.loadOrCreate()415            let signature = try RefreshSignature.make(sessionId: stored.sessionId, challenge: challenge.challenge, key: key)416            let fresh = try await client.nativeRefresh(sessionId: stored.sessionId, signature: signature).session417            guard current?.sessionId == stored.sessionId else { throw APIError.notSignedIn } // signed out meanwhile418            let updated = StoredCredential(session: fresh, username: stored.username)419            try credentials.save(updated)420            current = updated421            CRLog.auth.info("session token refreshed")422            return fresh423        } catch let error as APIError where error.status == 401 {424            CRLog.auth.notice("refresh refused: session is gone")425            await invalidate(reason: .revoked)426            throw error427        }428    }429430431    public func sessionWasRejected(token: String) async {432        guard let current, current.token == token else { return }433        CRLog.auth.notice("session rejected by the server")434        await invalidate(reason: .revoked)435    }436437    /// The event stream or a WebSocket reported the end of the session (`auth.expired`, close 4401).438    public func sessionExpiredRemotely() async {439        guard current != nil else { return }440        await invalidate(reason: .revoked)441    }442443    private func invalidate(reason: SignedOutReason) async {444        credentials.clear()445        current = nil446        pending = nil447        await client.setCredential(nil)448        set(.signedOut(reason))449    }450451    /// Revokes the session on the server (best effort) and wipes the local credential. The452    /// device key and install id are kept so the device is recognised at the next sign-in.453    public func signOut() async {454        let token = current?.token ?? pending?.token455        if let token { try? await client.logout(token: token) }456        await invalidate(reason: .userSignedOut)457    }458459    /// Local wipe without contacting the server: credential, device key and install id.460    public func wipeLocalData() async {461        await invalidate(reason: .userSignedOut)462        deviceKeys.delete()463        credentials.resetInstallID()464    }465466    // MARK: Re-authentication gate467468    /// Verifies the device owner (Face ID / Touch ID, passcode fallback) before a destructive or469    /// sensitive action (terminate a session, delete files, revoke a device, sign out everywhere).470    /// - Throws: `LocalAuthError` (`.cancelled`, `.unavailable`, `.failed`).471    public nonisolated func reauthenticate(reason: String) async throws {472        try await localAuth.authenticate(reason: reason)473    }474475    /// False when the device has neither biometrics nor a passcode: the caller decides whether to476    /// fall back to a plain confirmation.477    public nonisolated var canReauthenticate: Bool { localAuth.canAuthenticate() }478}479
Files main
Menu

Theme