SPB Git

Repository Public

AuthService.swift 10.0 KB 212 lines swift

1import Foundation23/// Identity flows of the native apps: passkey sign-in, step-up, invitation setup, passkey management, sign-out.4/// All verification happens on the server; this type only runs the ceremonies and moves the results.5public actor AuthService {6    private let api: APIClient7    private let passkeys: any PasskeyProvider8    private let device: @Sendable () -> DeviceInfo9    /// Setup-transaction token of the invitation being completed. Memory only: never persisted, never logged.10    private var setupToken: String?11    private var stepUps = 01213    public init(api: APIClient, passkeys: any PasskeyProvider, device: @escaping @Sendable () -> DeviceInfo = { DeviceInfo.current() }) {14        self.api = api15        self.passkeys = passkeys16        self.device = device17    }1819    /// Number of step-up ceremonies run (tests).20    public var stepUpCount: Int { stepUps }21    public var hasPendingInvitation: Bool { setupToken != nil }2223    private func clientInfo() async -> API.ClientInfo {24        let d = device()25        return API.ClientInfo(kind: d.kind == .macos ? .macos : .ios, label: d.label, model: d.model, osVersion: d.osVersion,26                              appVersion: d.appVersion, deviceId: await api.tokens.deviceID)27    }2829    private func install(_ auth: API.AuthResult) async throws {30        guard let access = auth.accessToken, let accessExp = auth.accessExpiresAt,31              let refresh = auth.refreshToken, let refreshExp = auth.refreshExpiresAt else {32            throw APIError(code: APIError.codeDecoding, message: "The server did not return native session tokens")33        }34        try await api.tokens.install(SessionTokens(accessToken: access, accessExpiresAt: accessExp, refreshToken: refresh, refreshExpiresAt: refreshExp),35                                     deviceID: auth.deviceId)36    }3738    // MARK: Sign-in3940    /// Usernameless passkey sign-in. Opens the session and stores its tokens.41    @discardableResult42    public func signIn() async throws -> API.AuthResult {43        do {44            let challenge = try await api.call { try await $0.beginAuthentication().ok.body.json }45            let request = try WebAuthnJSON.assertionRequest(from: JSONValue(encoding: challenge.publicKey))46            let assertion = try await passkeys.assertion(request)47            let credential = try WebAuthnJSON.credential(assertion).decode(API.AuthenticationFinishRequest.CredentialPayload.self)48            let client = await clientInfo()49            let result = try await api.call {50                try await $0.finishAuthentication(body: .json(.init(challengeId: challenge.challengeId, credential: credential, client: client))).ok.body.json51            }52            try await install(result)53            return result54        } catch {55            throw APIError.from(error)56        }57    }5859    // MARK: Step-up6061    /// Runs a passkey assertion bound to the current session; the server then accepts sensitive operations for 5 min.62    @discardableResult63    public func stepUp() async throws -> API.StepUpResult {64        do {65            let challenge = try await api.call { try await $0.beginStepUp().ok.body.json }66            let request = try WebAuthnJSON.assertionRequest(from: JSONValue(encoding: challenge.publicKey))67            let assertion = try await passkeys.assertion(request)68            let credential = try WebAuthnJSON.credential(assertion).decode(API.StepUpFinishRequest.CredentialPayload.self)69            let result = try await api.call {70                try await $0.finishStepUp(body: .json(.init(challengeId: challenge.challengeId, credential: credential))).ok.body.json71            }72            stepUps += 173            return result74        } catch {75            throw APIError.from(error)76        }77    }7879    /// Runs `operation`; if the server answers `403 step_up_required`, performs the passkey ceremony and retries the80    /// original call exactly once. The decision that a step-up is needed is always the server's.81    public func withStepUp<T: Sendable>(_ operation: @Sendable () async throws -> T) async throws -> T {82        do {83            return try await operation()84        } catch {85            let e = APIError.from(error)86            guard e.isStepUpRequired else { throw e }87            try await stepUp()88            do { return try await operation() } catch { throw APIError.from(error) }89        }90    }9192    // MARK: Invitation setup9394    /// Exchanges the invitation token of a setup link. The token is consumed by this call and is not kept.95    public func exchangeInvitation(token: String) async throws -> API.InvitationTransaction {96        let client = await clientInfo()97        let tx = try await api.call {98            try await $0.exchangeInvitation(body: .json(.init(token: token, client: client))).ok.body.json99        }100        guard let transaction = tx.transactionToken else {101            throw APIError(code: APIError.codeDecoding, message: "The server did not return a setup transaction token")102        }103        setupToken = transaction104        return tx105    }106107    private func withSetup<T: Sendable>(includeBearer: Bool, _ operation: @Sendable () async throws -> T) async throws -> T {108        guard let token = setupToken else {109            throw APIError(status: 410, code: "setup_transaction_invalid", message: "No invitation in progress")110        }111        var context = RequestContext()112        context.setupToken = token113        context.includeBearer = includeBearer114        return try await RequestContext.$current.withValue(context, operation: operation)115    }116117    public func invitationTransaction() async throws -> API.InvitationTransaction {118        try await withSetup(includeBearer: false) { [api] in119            try await api.call { try await $0.getInvitationTransaction().ok.body.json }120        }121    }122123    public func setInvitationProfile(handle: String, displayName: String) async throws -> API.InvitationTransaction {124        try await withSetup(includeBearer: false) { [api] in125            try await api.call {126                try await $0.setInvitationProfile(body: .json(.init(handle: handle, displayName: displayName))).ok.body.json127            }128        }129    }130131    /// New account (or recovery): creates the passkey, completes the invitation and opens the session.132    @discardableResult133    public func completeInvitation(passkeyLabel: String?) async throws -> API.RegistrationResult {134        do {135            let client = await clientInfo()136            let challenge = try await withSetup(includeBearer: false) { [api] in137                try await api.call { try await $0.beginRegistration(body: .json(.init(label: passkeyLabel))).ok.body.json }138            }139            let request = try WebAuthnJSON.registrationRequest(from: JSONValue(encoding: challenge.publicKey))140            let registration = try await passkeys.registration(request)141            let credential = try WebAuthnJSON.credential(registration).decode(API.RegistrationFinishRequest.CredentialPayload.self)142            let result = try await withSetup(includeBearer: false) { [api] in143                try await api.call {144                    try await $0.finishRegistration(body: .json(.init(challengeId: challenge.challengeId, credential: credential,145                                                                      label: passkeyLabel, client: client))).ok.body.json146                }147            }148            guard let auth = result.auth else {149                throw APIError(code: APIError.codeDecoding, message: "The server did not open a session after the setup")150            }151            try await install(auth)152            setupToken = nil153            return result154        } catch {155            throw APIError.from(error)156        }157    }158159    /// Invitation aimed at an existing account: requires the session of THAT account (sign in first), a step-up160    /// (run here when the server asks for it) and the explicit confirmation of the user.161    public func linkInvitation(confirmed: Bool) async throws -> API.InvitationLinkResult {162        guard confirmed else { throw APIError(status: 400, code: "validation_failed", message: "Explicit confirmation is required") }163        let result = try await withStepUp { [self] in164            try await self.withSetup(includeBearer: true) { [api] in165                try await api.call { try await $0.linkInvitationToAccount(body: .json(.init(confirm: true))).ok.body.json }166            }167        }168        setupToken = nil169        return result170    }171172    public func abandonInvitation() async {173        if setupToken != nil {174            _ = try? await withSetup(includeBearer: false) { [api] in175                try await api.call { _ = try await $0.abandonInvitationTransaction().noContent }176            }177        }178        setupToken = nil179    }180181    // MARK: Passkeys of the signed-in account182183    /// Adds a passkey to the signed-in account (the server requires a step-up, handled here).184    public func addPasskey(label: String?) async throws -> API.Passkey {185        do {186            let challenge = try await withStepUp { [api] in187                try await api.call { try await $0.beginRegistration(body: .json(.init(label: label))).ok.body.json }188            }189            let request = try WebAuthnJSON.registrationRequest(from: JSONValue(encoding: challenge.publicKey))190            let registration = try await passkeys.registration(request)191            let credential = try WebAuthnJSON.credential(registration).decode(API.RegistrationFinishRequest.CredentialPayload.self)192            let result = try await withStepUp { [api] in193                try await api.call {194                    try await $0.finishRegistration(body: .json(.init(challengeId: challenge.challengeId, credential: credential, label: label))).ok.body.json195                }196            }197            return result.passkey198        } catch {199            throw APIError.from(error)200        }201    }202203    // MARK: Sign-out204205    /// Revokes the session on the server (best effort) and wipes the local tokens in every case.206    public func signOut() async {207        _ = try? await api.call { _ = try await $0.logout().noContent }208        await api.tokens.signOut()209        setupToken = nil210    }211}212
Files main
Menu

Theme