SPB Git

Repository Public

IdentityClient.swift 15.6 KB 319 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/IdentityClient.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// Async client of the session flow endpoints (authenticated with the session client secret).89import Foundation9091/// Sends one HTTP request. Replaceable in tests.92public protocol IdentityTransport: Sendable {93    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)94}9596/// Default transport: an ephemeral `URLSession` (no cookies, no cache, nothing written to disk).97public struct URLSessionTransport: IdentityTransport {98    private let session: URLSession99100    public init(timeout: TimeInterval = 30, uploadTimeout: TimeInterval = 120) {101        let cfg = URLSessionConfiguration.ephemeral102        cfg.urlCache = nil103        cfg.httpCookieStorage = nil104        cfg.httpShouldSetCookies = false105        cfg.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData106        cfg.timeoutIntervalForRequest = timeout107        cfg.timeoutIntervalForResource = uploadTimeout108        cfg.waitsForConnectivity = false109        session = URLSession(configuration: cfg)110    }111112    public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {113        let (data, response) = try await session.data(for: request)114        guard let http = response as? HTTPURLResponse else { throw IdentityError.invalidResponse(status: 0) }115        return (data, http)116    }117}118119/// Automatic retries of one call: network failures, 429 `rate_limited` and 5xx only, with a capped exponential120/// backoff and jitter. `Retry-After` is honoured when it is short enough to wait for inside an interactive flow.121public struct IdentityRetryPolicy: Equatable, Sendable {122    /// Retries after the first attempt.123    public var maxRetries: Int124    /// Delay before the first retry; doubled for each following one.125    public var initialDelay: TimeInterval126    /// Ceiling of the exponential delay.127    public var maxDelay: TimeInterval128    /// Longest `Retry-After` the client waits for by itself. A longer one is not retried: the error is returned with129    /// its `retryAfter`, so that the screen can tell the person instead of freezing.130    public var maxRetryAfter: TimeInterval131    /// Per-attempt deadline of a JSON call, and of an image upload.132    public var requestTimeout: TimeInterval133    public var uploadTimeout: TimeInterval134135    public init(maxRetries: Int = 2, initialDelay: TimeInterval = 0.5, maxDelay: TimeInterval = 8, maxRetryAfter: TimeInterval = 15,136                requestTimeout: TimeInterval = 20, uploadTimeout: TimeInterval = 120) {137        self.maxRetries = max(0, maxRetries); self.initialDelay = initialDelay; self.maxDelay = maxDelay; self.maxRetryAfter = maxRetryAfter138        self.requestTimeout = requestTimeout; self.uploadTimeout = uploadTimeout139    }140141    public static let `default` = IdentityRetryPolicy()142    /// A single attempt.143    public static let none = IdentityRetryPolicy(maxRetries: 0)144145    /// Delay before retry number `attempt` (0-based): a random value in [50 %, 100 %] of `min(maxDelay, initialDelay × 2^attempt)`.146    public func backoff(attempt: Int, random: Double = Double.random(in: 0...1)) -> TimeInterval {147        let ceiling = min(maxDelay, initialDelay * pow(2, Double(min(max(attempt, 0), 16))))148        return ceiling * (0.5 + min(max(random, 0), 1) * 0.5)149    }150151    /// Delay to wait before retrying after `error`, or nil when the call must not be retried.152    public func delay(after error: IdentityError, attempt: Int, random: Double = Double.random(in: 0...1)) -> TimeInterval? {153        guard attempt < maxRetries, error.isRetryable else { return nil }154        if let ra = error.retryAfter { return ra <= maxRetryAfter ? ra : nil }155        return backoff(attempt: attempt, random: random)156    }157}158159/// Client of the flow endpoints of one session. Holds the client secret in memory only.160public struct IdentityClient: Sendable {161    public typealias Sleeper = @Sendable (TimeInterval) async throws -> Void162163    public let session: IdentitySession164    public let retryPolicy: IdentityRetryPolicy165    private let transport: IdentityTransport166    private let sleeper: Sleeper167168    public static let sdkVersion = "1.1.0"169170    /// - Parameters:171    ///   - retryPolicy: automatic retries and per-attempt deadlines; `.none` for a single attempt.172    ///   - sleeper: waits between retries; replaceable in tests.173    public init(session: IdentitySession, transport: IdentityTransport = URLSessionTransport(), retryPolicy: IdentityRetryPolicy = .default,174                sleeper: @escaping Sleeper = { try await Task.sleep(nanoseconds: UInt64(max(0, $0) * 1_000_000_000)) }) {175        self.session = session176        self.transport = transport177        self.retryPolicy = retryPolicy178        self.sleeper = sleeper179    }180181    public init(baseURL: URL = IdentitySession.defaultBaseURL, sessionID: String, clientSecret: String, transport: IdentityTransport = URLSessionTransport(),182                retryPolicy: IdentityRetryPolicy = .default) throws {183        self.init(session: try IdentitySession(baseURL: baseURL, sessionID: sessionID, clientSecret: clientSecret), transport: transport, retryPolicy: retryPolicy)184    }185186    // MARK: Endpoints187188    /// `GET /v1/sessions/{id}` — state of the flow.189    public func flowState() async throws -> FlowState {190        try await call("GET", "")191    }192193    /// `POST /v1/sessions/{id}/consent` — records the chosen method and the explicit consent.194    /// - Parameters:195    ///   - textVersion: `version` of the consent text that was displayed.196    ///   - biometricConsent: express consent to the one-time use of facial measurements; required for biometric methods.197    public func consent(method: String, textVersion: String, biometricConsent: Bool, locale: String? = nil) async throws -> FlowState {198        var body: [String: Any] = ["method": method, "accepted": true, "text_version": textVersion]199        if biometricConsent { body["biometric_consent"] = true }200        if let locale { body["locale"] = locale }201        return try await call("POST", "/consent", json: body)202    }203204    /// `POST /v1/sessions/{id}/document` — uploads one side of the document (live sessions only).205    /// A result with `accepted == false` lists quality issues; it is not thrown as an error.206    public func uploadDocument(side: DocumentSide, image: Data) async throws -> DocumentUploadResult {207        var form = MultipartForm()208        form.addField(name: "side", value: side.rawValue)209        let type = sniffImageContentType(image) ?? "application/octet-stream"210        form.addFile(name: "file", filename: "\(side.rawValue).\(type == "image/png" ? "png" : type == "image/webp" ? "webp" : "jpg")", contentType: type, data: image)211        return try await call("POST", "/document", form: form)212    }213214    /// `POST /v1/sessions/{id}/selfie/challenge` — a single-use liveness challenge.215    /// - Parameter accessible: true for the alternative without head movements (always reviewed by a person).216    public func selfieChallenge(accessible: Bool = false) async throws -> LivenessChallenge {217        try await call("POST", "/selfie/challenge", json: accessible ? ["accessible": true] : [:])218    }219220    /// `POST /v1/sessions/{id}/selfie` — uploads the frames answering the challenge, in capture order, unmirrored JPEG.221    public func uploadSelfie(challengeID: String, frames: [Data]) async throws -> SelfieUploadResult {222        var form = MultipartForm()223        form.addField(name: "challenge_id", value: challengeID)224        for (i, frame) in frames.enumerated() {225            form.addFile(name: "frames", filename: String(format: "f%02d.jpg", i), contentType: "image/jpeg", data: frame)226        }227        return try await call("POST", "/selfie", form: form)228    }229230    /// `POST /v1/sessions/{id}/submit` — submits the session for analysis.231    public func submit() async throws -> FlowState {232        try await call("POST", "/submit")233    }234235    /// `POST /v1/sessions/{id}/sandbox` — sandbox only: completes the session with a simulated scenario.236    public func sandbox(scenario: String) async throws -> FlowState {237        try await call("POST", "/sandbox", json: ["scenario": scenario])238    }239240    /// `POST /v1/sessions/{id}/withdraw` — withdraws consent; everything is destroyed immediately.241    public func withdraw() async throws -> WithdrawResult {242        try await call("POST", "/withdraw")243    }244245    /// `POST /v1/sessions/{id}/dispute` — contests a decision (5 to 2000 characters); reviewed by a person.246    public func dispute(message: String) async throws -> DisputeResult {247        try await call("POST", "/dispute", json: ["message": message])248    }249250    // MARK: Plumbing251252    func makeRequest(_ method: String, _ path: String, json: [String: Any]? = nil, form: MultipartForm? = nil) throws -> URLRequest {253        guard let url = URL(string: session.baseURL.absoluteString + "/v1/sessions/" + session.id + path) else { throw IdentityError.invalidSessionURL }254        var req = URLRequest(url: url)255        req.httpMethod = method256        req.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData257        req.httpShouldHandleCookies = false258        req.setValue("Bearer " + session.clientSecret, forHTTPHeaderField: "Authorization")259        req.setValue("application/json", forHTTPHeaderField: "Accept")260        req.setValue("MacLustrIdentity-Swift/" + IdentityClient.sdkVersion, forHTTPHeaderField: "User-Agent")261        req.timeoutInterval = form != nil ? retryPolicy.uploadTimeout : retryPolicy.requestTimeout262        if let form {263            req.setValue(form.contentType, forHTTPHeaderField: "Content-Type")264            req.httpBody = form.finalized()265        } else if let json {266            req.setValue("application/json", forHTTPHeaderField: "Content-Type")267            req.httpBody = try JSONSerialization.data(withJSONObject: json, options: [.sortedKeys])268        }269        return req270    }271272    /// One call with its retries. The request is built once: a retried upload re-sends the very same bytes held in memory.273    private func call<T: Decodable>(_ method: String, _ path: String, json: [String: Any]? = nil, form: MultipartForm? = nil) async throws -> T {274        let request = try makeRequest(method, path, json: json, form: form)275        let deadline = form != nil ? retryPolicy.uploadTimeout : retryPolicy.requestTimeout276        var attempt = 0277        while true {278            do {279                try Task.checkCancellation()280                return try await attemptOnce(request, deadline: deadline)281            } catch {282                let e = IdentityError.wrap(error)283                guard e != .cancelled, let wait = retryPolicy.delay(after: e, attempt: attempt) else { throw e }284                do { try await sleeper(wait) } catch { throw IdentityError.cancelled }285                attempt += 1286            }287        }288    }289290    private func attemptOnce<T: Decodable>(_ request: URLRequest, deadline: TimeInterval) async throws -> T {291        let (data, response) = try await IdentityClient.withDeadline(deadline) { try await self.transport.send(request) }292        guard (200..<300).contains(response.statusCode) else {293            throw IdentityError.from(status: response.statusCode, body: data, headers: response.allHeaderFields)294        }295        do {296            return try JSONDecoder().decode(T.self, from: data)297        } catch {298            throw IdentityError.invalidResponse(status: response.statusCode)299        }300    }301302    /// Runs `operation` and gives up with a network error when it has not finished after `seconds`, whatever the303    /// transport does. Cancelling the caller cancels the operation.304    static func withDeadline<R: Sendable>(_ seconds: TimeInterval, _ operation: @escaping @Sendable () async throws -> R) async throws -> R {305        guard seconds > 0, seconds.isFinite else { return try await operation() }306        return try await withThrowingTaskGroup(of: R?.self) { group in307            group.addTask { try await operation() }308            group.addTask {309                try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))310                return nil311            }312            defer { group.cancelAll() }313            guard let first = try await group.next() else { throw IdentityError.cancelled }314            guard let value = first else { throw IdentityError.network("timeout") }315            return value316        }317    }318}319
Files main
Menu

Theme