SPB Git

Repository Public

VerificationFlowModel.swift 21.7 KB 527 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Sources/MacLustrIdentityCore/VerificationFlowModel.swift10// Module           : MacLustrIdentityCore11// Repository       : https://git.spboucher.ai/maclustr-identity12// Project Website  : https://identity.spboucher.ai13// Created          : 2026-12-0114// Last Modified    : 2026-12-0115//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: admin@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// =============================================================================8788// State machine of the verification flow, independent of any UI.89import Combine90import Foundation9192/// Outcome reported to the integrating app. It is for user experience only: the app must trust only its own93/// backend (webhook or `GET /v1/verifications/{id}`) for the actual result.94public enum IdentityVerificationResult: Equatable, Sendable {95    /// The flow reached its end. `status` is the session status last seen by the SDK, typically96    /// `.verified`, `.manualReview`, `.processing`, `.inconclusive`, `.rejected` or `.expired`.97    case completed(status: SessionStatus)98    /// The person left the flow or withdrew consent.99    case canceled100    /// The flow could not run (invalid session, network failure at start, camera unavailable…).101    case failed(IdentityError)102}103104public enum FlowStep: Equatable, Sendable {105    case loading106    case intro107    case method108    case consent(methodID: String)109    /// Sandbox sessions only: choice of the simulated scenario (no image is ever captured).110    case sandbox111    case documentFront112    case documentBack113    case selfie114    case submitting115    /// Waiting for the analysis; the model polls the service with a backoff.116    case processing117    case result(SessionStatus)118    /// The flow cannot continue. `start()` can be called again when the error is retryable.119    case failed(IdentityError)120}121122public enum DocumentUploadOutcome: Equatable, Sendable {123    case accepted124    /// The service refused the image for quality reasons; it must be retaken.125    case rejected(issues: [String])126    /// The upload failed; see `lastError`.127    case failed128}129130/// Drives a verification session from the first screen to the result.131///132/// The model owns no image: captured data is passed through to the upload calls and released.133@MainActor134public final class VerificationFlowModel: ObservableObject {135    public typealias Sleeper = @Sendable (TimeInterval) async throws -> Void136137    @Published public private(set) var step: FlowStep = .loading138    @Published public private(set) var state: FlowState?139    /// A request is in flight.140    @Published public private(set) var isBusy = false141    /// Last recoverable error (network failure, rate limit…). Cleared when the next action starts.142    @Published public private(set) var lastError: IdentityError?143    /// True after the service asked for a new capture (analysis inconclusive, attempts left).144    @Published public private(set) var retryRequested = false145    /// True when the analysis has been running for longer than `slowProcessingAfter`.146    @Published public private(set) var processingIsSlow = false147    @Published public private(set) var disputeSent = false148    /// Language of the SDK texts. Defaults to the session locale once the state is loaded.149    @Published public var language: IdentityLanguage150151    public let client: IdentityClient152    /// Delays between two polls while processing: starts at `pollInitialDelay`, multiplied by `pollBackoff`, capped at `pollMaxDelay`.153    public var pollInitialDelay: TimeInterval = 1.0154    public var pollBackoff = 1.5155    public var pollMaxDelay: TimeInterval = 8.0156    /// Random spread of each polling delay (0.2 = ±20 %), so that many devices do not poll in step.157    public var pollJitter = 0.2158    /// Longest wait accepted from a `Retry-After` answer while polling.159    public var pollMaxRetryAfter: TimeInterval = 60160    public var slowProcessingAfter: TimeInterval = 90161162    private let sleeper: Sleeper163    private let languageIsFixed: Bool164    private var pollTask: Task<Void, Never>?165    private var withdrew = false166    private var stopped = false167168    /// - Parameters:169    ///   - language: forces the language; by default it follows the session locale.170    ///   - sleeper: waits between polls; replaceable in tests.171    public init(client: IdentityClient, language: IdentityLanguage? = nil,172                sleeper: @escaping Sleeper = { try await Task.sleep(nanoseconds: UInt64($0 * 1_000_000_000)) }) {173        self.client = client174        self.language = language ?? IdentityLanguage(localeIdentifier: Locale.preferredLanguages.first ?? "en")175        self.languageIsFixed = language != nil176        self.sleeper = sleeper177    }178179    deinit { pollTask?.cancel() }180181    // MARK: Derived values182183    public var applicationName: String { state?.application.name ?? "" }184    public var methods: [VerificationMethod] { state?.methods ?? [] }185    public var isSandbox: Bool { state.map { !$0.livemode } ?? false }186    public var chosenMethod: VerificationMethod? { state?.chosenMethod }187188    /// Consent can be withdrawn (everything destroyed) until a decision is made, including while a person reviews the file.189    public var canWithdraw: Bool {190        guard let s = state?.status else { return false }191        return (s == .awaitingDocument || s == .awaitingSelfie || s == .processing || s == .manualReview) && !isBusy192    }193194    /// The method can still be changed: nothing is submitted yet and the session offers more than one method.195    /// Choosing again resets what was uploaded (the service destroys it).196    public var canChangeMethod: Bool {197        guard let s = state, s.livemode, s.methods.count > 1, !isBusy else { return false }198        guard s.status == .awaitingDocument || s.status == .awaitingSelfie else { return false }199        switch step {200        case .documentFront, .documentBack, .selfie: return true201        default: return false202        }203    }204205    /// Reasons given by the service for the capture to redo (empty when there is none).206    public var lastIssue: [DecisionReason] { state?.lastIssue ?? [] }207208    /// A decision exists and can be contested.209    public var canDispute: Bool {210        guard let s = state, s.result != nil, !disputeSent else { return false }211        return s.status == .rejected || s.status == .inconclusive212    }213214    /// Value to hand to the app when the flow is dismissed in its current state.215    public var resultForDismissal: IdentityVerificationResult {216        if withdrew { return .canceled }217        switch step {218        case .result(let status): return status == .cancelled ? .canceled : .completed(status: status)219        case .processing, .submitting: return .completed(status: .processing)220        case .failed(let error): return .failed(error)221        default: return .canceled222        }223    }224225    // MARK: Actions226227    /// Loads the session and positions the flow (also resumes a session already under way).228    public func start() async {229        pollTask?.cancel()230        stopped = false231        step = .loading232        lastError = nil233        do {234            let s = try await client.flowState()235            apply(s, initial: true)236        } catch {237            let e = IdentityError.wrap(error)238            if e != .cancelled { step = .failed(e) }239        }240    }241242    /// Intro → method choice, or directly the consent when a single method is offered.243    public func continueFromIntro() {244        guard step == .intro, let s = state else { return }245        if s.methods.count == 1 { step = .consent(methodID: s.methods[0].id) } else { step = .method }246    }247248    public func selectMethod(_ id: String) {249        guard methods.contains(where: { $0.id == id }) else { return }250        step = .consent(methodID: id)251    }252253    /// Consent → back to the method choice (or the intro when there is only one method).254    /// When the person was changing method after having consented, declining returns to the capture under way.255    public func declineConsent() {256        guard case .consent = step else { return }257        if let s = state, s.status == .awaitingDocument || s.status == .awaitingSelfie, methods.count <= 1 {258            apply(s)259        } else {260            step = methods.count > 1 ? .method : .intro261        }262    }263264    /// Capture → method choice, while nothing is submitted. Accepting the consent of the newly chosen method resets265    /// the uploads on the service; `resumeCapture()` goes back without changing anything.266    public func changeMethod() {267        guard canChangeMethod else { return }268        step = .method269    }270271    /// Method choice opened by `changeMethod()` → back to the capture under way, nothing changed.272    public func resumeCapture() {273        guard step == .method, let s = state, s.status == .awaitingDocument || s.status == .awaitingSelfie else { return }274        apply(s)275    }276277    /// Records the explicit consent the person just gave by ticking the checkbox of the displayed text.278    public func acceptConsent() async {279        guard case .consent(let id) = step, let method = methods.first(where: { $0.id == id }), let text = method.consentText(language) else { return }280        await perform {281            let s = try await self.client.consent(method: id, textVersion: text.version, biometricConsent: method.biometric, locale: self.language == .fr ? "fr-CA" : "en-CA")282            self.retryRequested = false283            self.apply(s)284        }285    }286287    /// Uploads one side of the document. The image exists only in memory.288    @discardableResult289    public func uploadDocument(side: DocumentSide, image: Data) async -> DocumentUploadOutcome {290        var outcome = DocumentUploadOutcome.failed291        await perform {292            let r = try await self.client.uploadDocument(side: side, image: image)293            guard r.accepted else { outcome = .rejected(issues: r.issues); return }294            outcome = .accepted295            self.retryRequested = false296            self.state?.uploaded[side.rawValue] = true297            if let status = r.status { self.state?.status = status }298            if side == .front { self.step = .documentBack } else { await self.afterDocument() }299        }300        return outcome301    }302303    /// The document has no back (passport): move on.304    public func skipDocumentBack() async {305        guard step == .documentBack else { return }306        await afterDocument()307    }308309    /// Asks for a liveness challenge. Throws so that the capture screen can react (for example to `too_many_challenges`).310    public func requestChallenge(accessible: Bool) async throws -> LivenessChallenge {311        lastError = nil312        do {313            return try await client.selfieChallenge(accessible: accessible)314        } catch {315            let e = IdentityError.wrap(error)316            await handle(e)317            throw e318        }319    }320321    /// Uploads the selfie frames (unmirrored JPEG, capture order), then submits the session.322    /// Returns false when the upload failed; the capture must then restart with a new challenge.323    @discardableResult324    public func uploadSelfie(challengeID: String, frames: [Data]) async -> Bool {325        var ok = false326        await perform {327            do {328                ok = try await self.client.uploadSelfie(challengeID: challengeID, frames: frames).accepted329            } catch {330                // A retried upload whose first answer was lost finds its challenge already used: when the service331                // holds the frames, the upload did succeed.332                guard IdentityError.wrap(error).code == "invalid_challenge", let s = try? await self.client.flowState(), s.selfieDone,333                      s.status == .awaitingSelfie || s.status == .awaitingDocument else { throw error }334                self.state = s335                ok = true336            }337            if ok {338                self.state?.selfieDone = true339                try await self.submitNow()340            }341        }342        return ok343    }344345    /// Submits the session for analysis and starts polling.346    public func submit() async {347        await perform { try await self.submitNow() }348    }349350    /// Sandbox only: completes the session with a simulated scenario.351    public func runSandboxScenario(_ id: String) async {352        await perform {353            let s = try await self.client.sandbox(scenario: id)354            self.apply(s)355        }356    }357358    /// Withdraws consent: the service destroys everything immediately and cancels the session.359    public func withdraw() async {360        pollTask?.cancel()361        await perform {362            _ = try await self.client.withdraw()363            self.withdrew = true364            self.state?.status = .cancelled365            self.step = .result(.cancelled)366        }367        if case .processing = step { startPolling() }368    }369370    /// Contests the decision. Returns true when the dispute was recorded.371    @discardableResult372    public func dispute(message: String) async -> Bool {373        var ok = false374        await perform {375            do {376                _ = try await self.client.dispute(message: message.trimmingCharacters(in: .whitespacesAndNewlines))377            } catch {378                // Already recorded (retry after a lost answer, or sent from another device): nothing more to do.379                guard IdentityError.wrap(error).code == "dispute_exists" else { throw error }380            }381            self.disputeSent = true382            ok = true383        }384        return ok385    }386387    /// Reloads the state from the service and repositions the flow.388    public func refresh() async {389        await perform { self.apply(try await self.client.flowState()) }390    }391392    /// Stops polling. Call when the flow is dismissed. An answer still in flight no longer restarts it.393    public func stop() {394        stopped = true395        pollTask?.cancel()396        pollTask = nil397    }398399    // MARK: Internals400401    private func afterDocument() async {402        if state?.chosenMethod?.requiresSelfie == true {403            step = .selfie404        } else {405            await submit()406        }407    }408409    private func submitNow() async throws {410        let previous = step411        step = .submitting412        do {413            apply(try await client.submit())414        } catch {415            if step == .submitting { step = previous }416            throw error417        }418    }419420    private func perform(_ operation: @escaping () async throws -> Void) async {421        isBusy = true422        lastError = nil423        defer { isBusy = false }424        do {425            try await operation()426        } catch {427            await handle(IdentityError.wrap(error))428        }429    }430431    private func handle(_ error: IdentityError) async {432        switch error {433        case .cancelled:434            return435        case .api(let e) where e.status == 401:436            pollTask?.cancel()437            step = .failed(error)438        case _ where error.isSessionStateConflict:439            // The session moved on without us (expired, cancelled by the application, decided): resynchronise.440            if let s = try? await client.flowState() { apply(s) } else { lastError = error }441        default:442            lastError = error443        }444    }445446    /// Positions the flow on the step matching the state returned by the service.447    private func apply(_ s: FlowState, initial: Bool = false) {448        let wasProcessing = step == .processing449        state = s450        if !languageIsFixed, initial { language = IdentityLanguage(localeIdentifier: s.locale) }451        // Resuming a session whose last capture has to be redone: say why, as when it happens under our eyes.452        if initial, s.livemode, !s.lastIssue.isEmpty, s.status == .awaitingDocument, !s.hasUploaded(.front) { retryRequested = true }453        switch s.status {454        case .created, .awaitingConsent:455            if initial || !isBeforeConsent { step = .intro }456        case .awaitingDocument, .awaitingSelfie:457            if !s.livemode {458                step = .sandbox459            } else if wasProcessing {460                // Inconclusive capture with attempts left: the service destroyed the images and asks for new ones.461                retryRequested = true462                step = .documentFront463            } else if s.status == .awaitingSelfie {464                if s.selfieDone { Task { await self.submit() } } else { step = .selfie }465            } else {466                step = s.hasUploaded(.front) ? .documentBack : .documentFront467            }468        case .processing:469            step = .processing470            startPolling()471        default:472            pollTask?.cancel()473            step = .result(s.status)474        }475    }476477    private var isBeforeConsent: Bool {478        switch step {479        case .intro, .method, .consent: return true480        default: return false481        }482    }483484    private func startPolling() {485        pollTask?.cancel()486        guard !stopped else { return }487        processingIsSlow = false488        let initialDelay = pollInitialDelay, backoff = pollBackoff, maxDelay = pollMaxDelay, slowAfter = slowProcessingAfter489        let jitter = min(max(pollJitter, 0), 0.9), maxRetryAfter = pollMaxRetryAfter490        // The task keeps no strong reference to the model while it waits, so a dismissed flow stops polling.491        pollTask = Task { [weak self, sleeper, client] in492            var delay = initialDelay493            var waited: TimeInterval = 0494            var askedToWait: TimeInterval?495            while !Task.isCancelled {496                // The service's own Retry-After wins over the local backoff; otherwise the delay is spread randomly.497                let pause = askedToWait.map { min(max($0, delay), maxRetryAfter) } ?? (jitter > 0 ? delay * (1 + Double.random(in: -jitter...jitter)) : delay)498                askedToWait = nil499                do { try await sleeper(pause) } catch { return }500                waited += pause501                delay = min(delay * backoff, maxDelay)502                let outcome: Result<FlowState, IdentityError>503                do { outcome = .success(try await client.flowState()) } catch { outcome = .failure(IdentityError.wrap(error)) }504                guard let self, !Task.isCancelled else { return }505                if waited >= slowAfter { self.processingIsSlow = true }506                switch outcome {507                case .success(let s) where s.status == .processing:508                    self.state = s509                    self.lastError = nil510                case .success(let s):511                    self.pollTask = nil512                    self.apply(s)513                    return514                case .failure(.cancelled):515                    return516                case .failure(let e) where e.isAuthenticationFailure:517                    self.step = .failed(e)518                    return519                case .failure(let e):520                    self.lastError = e      // transient: keep polling521                    askedToWait = e.retryAfter522                }523            }524        }525    }526}527
Files main
Menu

Theme