Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr Identity9// File : sdk/swift/Sources/MacLustrIdentityCore/Models.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// Codable models of the session flow API.89//90// Decoding is tolerant on purpose: an unknown field is ignored, an unknown status or step is kept as `.unknown`,91// a missing or malformed optional field falls back to a neutral default and a malformed list element is skipped.92// A later version of the service must never make an installed app fail on a field it does not know.93import Foundation9495/// Decodes `T`, or nothing when the value has another shape.96struct Lossy<T: Decodable>: Decodable {97 let value: T?98 init(from decoder: Decoder) throws { value = try? T(from: decoder) }99}100101extension KeyedDecodingContainer {102 /// The value when it is present and well formed, else nil. Never throws.103 func lenient<T: Decodable>(_ type: T.Type, _ key: Key) -> T? {104 (try? decodeIfPresent(type, forKey: key)) ?? nil105 }106107 /// The well-formed elements of a list; malformed elements are skipped.108 func lenientList<T: Decodable>(_ type: T.Type, _ key: Key) -> [T] {109 (lenient([Lossy<T>].self, key) ?? []).compactMap(\.value)110 }111112 /// The well-formed entries of an object.113 func lenientMap<T: Decodable>(_ type: T.Type, _ key: Key) -> [String: T] {114 (lenient([String: Lossy<T>].self, key) ?? [:]).compactMapValues(\.value)115 }116}117118/// Status of a verification session.119public enum SessionStatus: Equatable, Hashable, Sendable {120 case created, awaitingConsent, awaitingDocument, awaitingSelfie, processing, manualReview121 case verified, inconclusive, rejected, expired, cancelled, revoked122 /// A status this version of the SDK does not know.123 case unknown(String)124125 private static let known: [(SessionStatus, String)] = [126 (.created, "created"), (.awaitingConsent, "awaiting_consent"), (.awaitingDocument, "awaiting_document"), (.awaitingSelfie, "awaiting_selfie"),127 (.processing, "processing"), (.manualReview, "manual_review"), (.verified, "verified"), (.inconclusive, "inconclusive"),128 (.rejected, "rejected"), (.expired, "expired"), (.cancelled, "cancelled"), (.revoked, "revoked"),129 ]130131 public init(rawValue: String) {132 self = SessionStatus.known.first { $0.1 == rawValue }?.0 ?? .unknown(rawValue)133 }134135 public var rawValue: String {136 if case .unknown(let raw) = self { return raw }137 return SessionStatus.known.first { $0.0 == self }!.1138 }139140 /// No further change is possible without a new session.141 public var isFinal: Bool {142 switch self {143 case .verified, .inconclusive, .rejected, .expired, .cancelled, .revoked: return true144 default: return false145 }146 }147148 /// The person still has something to do in the flow.149 public var isInteractive: Bool {150 switch self {151 case .created, .awaitingConsent, .awaitingDocument, .awaitingSelfie: return true152 default: return false153 }154 }155}156157extension SessionStatus: Codable {158 public init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }159 public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }160}161162/// A text provided by the service in French and in English.163public struct LocalizedText: Equatable, Sendable, Decodable {164 public var fr: String165 public var en: String166167 public init(fr: String, en: String) { self.fr = fr; self.en = en }168169 public init(from decoder: Decoder) throws {170 // A plain string (not localised) is accepted too.171 if let plain = try? decoder.singleValueContainer().decode(String.self) { fr = plain; en = plain; return }172 let c = try decoder.container(keyedBy: CodingKeys.self)173 let f = c.lenient(String.self, .fr), e = c.lenient(String.self, .en)174 fr = f ?? e ?? ""175 en = e ?? f ?? ""176 }177178 private enum CodingKeys: String, CodingKey { case fr, en }179180 public subscript(_ language: IdentityLanguage) -> String { language == .fr ? fr : en }181}182183/// The entity responsible for the personal information (MacLustr Identity).184public struct DataController: Equatable, Sendable, Decodable {185 public var name: String186 public var contact: String?187 public var site: String?188189 private enum CodingKeys: String, CodingKey { case name, contact, site }190191 public init(from decoder: Decoder) throws {192 let c = try decoder.container(keyedBy: CodingKeys.self)193 name = c.lenient(String.self, .name) ?? ""194 contact = c.lenient(String.self, .contact)195 site = c.lenient(String.self, .site)196 }197}198199/// Consent text of one method in one language. Always displayed as provided by the service.200public struct ConsentText: Equatable, Sendable, Decodable {201 /// Version to send back with the consent (`text_version`).202 public var version: String203 public var title: String204 public var body: String205 /// Label of the explicit consent checkbox.206 public var checkbox: String207 public var points: [String]208 public var controller: DataController?209210 private enum CodingKeys: String, CodingKey { case version, title, body, checkbox, points, controller }211212 public init(from decoder: Decoder) throws {213 let c = try decoder.container(keyedBy: CodingKeys.self)214 // The version is required: a consent cannot be recorded without echoing the version that was displayed.215 version = try c.decode(String.self, forKey: .version)216 title = c.lenient(String.self, .title) ?? ""217 body = c.lenient(String.self, .body) ?? ""218 checkbox = c.lenient(String.self, .checkbox) ?? ""219 points = c.lenientList(String.self, .points)220 controller = c.lenient(DataController.self, .controller)221 }222}223224public struct VerificationMethod: Equatable, Sendable, Decodable, Identifiable {225 /// `document_selfie`, `document_review` or `document_only`.226 public var id: String227 /// True when the method uses measurements of the face (express biometric consent required).228 public var biometric: Bool229 public var label: LocalizedText230 public var consent: [String: ConsentText]231232 private enum CodingKeys: String, CodingKey { case id, biometric, label, consent }233234 public init(from decoder: Decoder) throws {235 let c = try decoder.container(keyedBy: CodingKeys.self)236 id = try c.decode(String.self, forKey: .id)237 // Unknown means "treat as biometric": the express consent is then asked for, never skipped.238 biometric = c.lenient(Bool.self, .biometric) ?? true239 label = c.lenient(LocalizedText.self, .label) ?? LocalizedText(fr: id, en: id)240 consent = c.lenientMap(ConsentText.self, .consent)241 }242243 public func consentText(_ language: IdentityLanguage) -> ConsentText? {244 consent[language.rawValue] ?? consent["en"] ?? consent["fr"] ?? consent.values.first245 }246247 /// The method asks for a selfie with a liveness challenge.248 public var requiresSelfie: Bool { id == "document_selfie" }249}250251/// Branding of the application that requested the verification.252public struct ApplicationBranding: Equatable, Sendable, Decodable {253 public var name: String254 public var logoURL: String?255 /// Accent colour as a hex string (`#RRGGBB`), when the application set one.256 public var accent: String?257258 private enum CodingKeys: String, CodingKey { case name, logoURL = "logo_url", accent }259260 public init(name: String, logoURL: String? = nil, accent: String? = nil) { self.name = name; self.logoURL = logoURL; self.accent = accent }261262 public init(from decoder: Decoder) throws {263 let c = try decoder.container(keyedBy: CodingKeys.self)264 name = c.lenient(String.self, .name) ?? ""265 logoURL = c.lenient(String.self, .logoURL)266 accent = c.lenient(String.self, .accent)267 }268}269270public struct SandboxScenario: Equatable, Sendable, Decodable, Identifiable {271 public var id: String272 public var label: LocalizedText273274 private enum CodingKeys: String, CodingKey { case id, label }275276 public init(from decoder: Decoder) throws {277 let c = try decoder.container(keyedBy: CodingKeys.self)278 id = try c.decode(String.self, forKey: .id)279 label = c.lenient(LocalizedText.self, .label) ?? LocalizedText(fr: id, en: id)280 }281}282283public struct SandboxInfo: Equatable, Sendable, Decodable {284 public var scenarios: [SandboxScenario]285286 private enum CodingKeys: String, CodingKey { case scenarios }287288 public init(from decoder: Decoder) throws {289 scenarios = try decoder.container(keyedBy: CodingKeys.self).lenientList(SandboxScenario.self, .scenarios)290 }291}292293/// A reason of a decision, or of a capture to redo. Known codes include `capture_quality_insufficient`,294/// `document_expired`, `authenticity_indicators`, `engine_unavailable`, `reviewer_decision`,295/// `review_not_completed` (the review by a person was not completed in time: the person may start again) and296/// `decision_overturned` (a contested decision was set aside). The list grows: show `message`, never switch on an297/// exhaustive list of codes.298public struct DecisionReason: Equatable, Sendable, Decodable {299 public var code: String300 public var message: LocalizedText301302 public init(code: String, message: LocalizedText) { self.code = code; self.message = message }303304 private enum CodingKeys: String, CodingKey { case code, message }305306 public init(from decoder: Decoder) throws {307 let c = try decoder.container(keyedBy: CodingKeys.self)308 code = try c.decode(String.self, forKey: .code)309 message = c.lenient(LocalizedText.self, .message) ?? LocalizedText(fr: code, en: code)310 }311}312313/// What the session expects for the document (`document` of the flow state).314public struct DocumentRequirements: Equatable, Sendable, Decodable {315 /// `required`.316 public var front: String317 /// `required_for_cards`: the back is needed for the document types of `backRequiredFor` only.318 public var back: String319 /// Document types whose back must be provided, for example `driver_licence`, `id_card`.320 public var backRequiredFor: [String]321 /// Document types accepted by the policy; empty when the policy does not restrict them.322 public var accepted: [String]323324 public init(front: String = "required", back: String = "required_for_cards", backRequiredFor: [String] = [], accepted: [String] = []) {325 self.front = front; self.back = back; self.backRequiredFor = backRequiredFor; self.accepted = accepted326 }327328 private enum CodingKeys: String, CodingKey { case front, back, backRequiredFor = "back_required_for", accepted }329330 public init(from decoder: Decoder) throws {331 let c = try decoder.container(keyedBy: CodingKeys.self)332 front = c.lenient(String.self, .front) ?? "required"333 back = c.lenient(String.self, .back) ?? "required_for_cards"334 backRequiredFor = c.lenientList(String.self, .backRequiredFor)335 accepted = c.lenientList(String.self, .accepted)336 }337338 /// False only when the service says that no accepted document has a back to capture.339 public var mayNeedBack: Bool { back != "not_required" && back != "none" }340}341342public struct FlowResult: Equatable, Sendable, Decodable {343 public var status: SessionStatus344 public var reasons: [DecisionReason]345 public var verifiedAt: Date?346347 private enum CodingKeys: String, CodingKey { case status, reasons, verifiedAt = "verified_at" }348349 public init(from decoder: Decoder) throws {350 let c = try decoder.container(keyedBy: CodingKeys.self)351 status = c.lenient(SessionStatus.self, .status) ?? .unknown("")352 reasons = c.lenientList(DecisionReason.self, .reasons)353 verifiedAt = c.lenient(String.self, .verifiedAt).flatMap(Timestamp.parse)354 }355}356357/// State of the flow for the person being verified (`GET /v1/sessions/{id}`).358public struct FlowState: Equatable, Sendable, Decodable {359 public var id: String360 public var status: SessionStatus361 /// False for sandbox sessions, which never accept images.362 public var livemode: Bool363 /// Locale requested by the application's backend, for example `fr-CA`.364 public var locale: String365 public var purpose: String?366 public var returnURL: String?367 /// The method the person consented to, once chosen.368 public var method: String?369 public var expiresAt: Date?370 public var application: ApplicationBranding371 public var methods: [VerificationMethod]372 public var controller: DataController?373 public var sandbox: SandboxInfo?374 /// Sides already uploaded: `front`, `back`.375 public var uploaded: [String: Bool]376 public var selfieDone: Bool377 public var attemptsLeft: Int378 /// Captures allowed for this session (the first one included). 0 when the service did not say.379 public var maxAttempts: Int380 /// Why the previous capture has to be redone; empty when there is nothing to report. Shown as provided.381 public var lastIssue: [DecisionReason]382 /// Which sides of the document are expected.383 public var document: DocumentRequirements384 public var result: FlowResult?385386 private enum CodingKeys: String, CodingKey {387 case id, status, livemode, locale, purpose, returnURL = "return_url", method, expiresAt = "expires_at", application, methods, controller, sandbox388 case uploaded, selfieDone = "selfie_done", attemptsLeft = "attempts_left", maxAttempts = "max_attempts", lastIssue = "last_issue", document, result389 }390391 public init(from decoder: Decoder) throws {392 let c = try decoder.container(keyedBy: CodingKeys.self)393 // `id` and `status` identify a flow state; everything else has a neutral default.394 id = try c.decode(String.self, forKey: .id)395 status = try c.decode(SessionStatus.self, forKey: .status)396 // Unknown means live: the SDK then never offers the sandbox shortcuts by mistake.397 livemode = c.lenient(Bool.self, .livemode) ?? true398 locale = c.lenient(String.self, .locale) ?? "fr-CA"399 purpose = c.lenient(String.self, .purpose)400 returnURL = c.lenient(String.self, .returnURL)401 method = c.lenient(String.self, .method)402 expiresAt = c.lenient(String.self, .expiresAt).flatMap(Timestamp.parse)403 application = c.lenient(ApplicationBranding.self, .application) ?? ApplicationBranding(name: "")404 methods = c.lenientList(VerificationMethod.self, .methods)405 controller = c.lenient(DataController.self, .controller)406 sandbox = c.lenient(SandboxInfo.self, .sandbox)407 uploaded = c.lenientMap(Bool.self, .uploaded)408 selfieDone = c.lenient(Bool.self, .selfieDone) ?? false409 attemptsLeft = c.lenient(Int.self, .attemptsLeft) ?? 0410 maxAttempts = c.lenient(Int.self, .maxAttempts) ?? 0411 lastIssue = c.lenientList(DecisionReason.self, .lastIssue)412 document = c.lenient(DocumentRequirements.self, .document) ?? DocumentRequirements()413 result = c.lenient(FlowResult.self, .result)414 }415416 /// True once the session has passed its expiry time (the service then answers `expired`).417 public func isPastExpiry(now: Date = Date()) -> Bool { expiresAt.map { $0 <= now } ?? false }418419 public var chosenMethod: VerificationMethod? { methods.first { $0.id == method } }420 public func hasUploaded(_ side: DocumentSide) -> Bool { uploaded[side.rawValue] == true }421}422423public enum DocumentSide: String, Sendable, Codable { case front, back }424425/// Answer to a document upload. `accepted == false` is not an error: the image must be retaken (see `issues`).426public struct DocumentUploadResult: Equatable, Sendable, Decodable {427 public var accepted: Bool428 public var side: String429 /// Quality problems: `resolution_too_low`, `image_blurry`, `image_too_dark`, `image_overexposed`, `low_contrast`.430 public var issues: [String]431 /// Session status after the upload (present when accepted).432 public var status: SessionStatus?433434 private enum CodingKeys: String, CodingKey { case accepted, side, issues, status }435436 public init(from decoder: Decoder) throws {437 let c = try decoder.container(keyedBy: CodingKeys.self)438 accepted = try c.decode(Bool.self, forKey: .accepted)439 side = c.lenient(String.self, .side) ?? ""440 issues = c.lenientList(String.self, .issues)441 status = c.lenient(SessionStatus.self, .status)442 }443}444445public enum ChallengeStep: Equatable, Sendable, Decodable {446 /// Turn the head towards the person's own left.447 case turnLeft448 /// Turn the head towards the person's own right.449 case turnRight450 case unknown(String)451452 public init(rawValue: String) {453 switch rawValue {454 case "turn_left": self = .turnLeft455 case "turn_right": self = .turnRight456 default: self = .unknown(rawValue)457 }458 }459460 public init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }461}462463/// Single-use, time-limited liveness challenge.464public struct LivenessChallenge: Equatable, Sendable, Decodable {465 public struct FrameSpec: Equatable, Sendable, Decodable {466 public var min: Int467 public var max: Int468 public var intervalMS: Int469 private enum CodingKeys: String, CodingKey { case min, max, intervalMS = "interval_ms" }470 public init(min: Int, max: Int, intervalMS: Int) { self.min = min; self.max = max; self.intervalMS = intervalMS }471472 public init(from decoder: Decoder) throws {473 let c = try decoder.container(keyedBy: CodingKeys.self)474 let lo = c.lenient(Int.self, .min) ?? 8475 min = Swift.max(1, lo)476 max = Swift.max(min, c.lenient(Int.self, .max) ?? 24)477 intervalMS = c.lenient(Int.self, .intervalMS) ?? 250478 }479 }480481 public var challengeID: String482 /// Head turns to perform in order, with a return to the centre between each. Empty for the accessible alternative.483 public var steps: [ChallengeStep]484 public var accessible: Bool485 /// Seconds before the challenge expires.486 public var expiresIn: Int487 public var frames: FrameSpec488489 private enum CodingKeys: String, CodingKey { case challengeID = "challenge_id", steps, accessible, expiresIn = "expires_in", frames }490491 public init(challengeID: String, steps: [ChallengeStep], accessible: Bool, expiresIn: Int, frames: FrameSpec) {492 self.challengeID = challengeID; self.steps = steps; self.accessible = accessible; self.expiresIn = expiresIn; self.frames = frames493 }494495 public init(from decoder: Decoder) throws {496 let c = try decoder.container(keyedBy: CodingKeys.self)497 challengeID = try c.decode(String.self, forKey: .challengeID)498 steps = c.lenientList(ChallengeStep.self, .steps)499 accessible = c.lenient(Bool.self, .accessible) ?? false500 expiresIn = c.lenient(Int.self, .expiresIn) ?? 120501 // The frame counts always come from the service (3 at least for the accessible alternative, 8 otherwise).502 frames = c.lenient(FrameSpec.self, .frames) ?? FrameSpec(min: accessible ? 3 : 8, max: 24, intervalMS: 250)503 }504}505506public struct SelfieUploadResult: Equatable, Sendable, Decodable {507 public var accepted: Bool508 public var frames: Int509510 private enum CodingKeys: String, CodingKey { case accepted, frames }511512 public init(from decoder: Decoder) throws {513 let c = try decoder.container(keyedBy: CodingKeys.self)514 accepted = try c.decode(Bool.self, forKey: .accepted)515 frames = c.lenient(Int.self, .frames) ?? 0516 }517}518519public struct WithdrawResult: Equatable, Sendable, Decodable {520 public var id: String521 public var status: SessionStatus522 public var destroyed: Bool523524 private enum CodingKeys: String, CodingKey { case id, status, destroyed }525526 public init(from decoder: Decoder) throws {527 let c = try decoder.container(keyedBy: CodingKeys.self)528 id = c.lenient(String.self, .id) ?? ""529 status = c.lenient(SessionStatus.self, .status) ?? .cancelled530 destroyed = c.lenient(Bool.self, .destroyed) ?? false531 }532}533534public struct DisputeResult: Equatable, Sendable, Decodable {535 public var id: String536 public var status: String537538 private enum CodingKeys: String, CodingKey { case id, status }539540 public init(from decoder: Decoder) throws {541 let c = try decoder.container(keyedBy: CodingKeys.self)542 id = c.lenient(String.self, .id) ?? ""543 status = c.lenient(String.self, .status) ?? "open"544 }545}546547/// ISO 8601 timestamps as produced by the service (`2026-12-01T10:01:52.002100-05:00`).548enum Timestamp {549 static func parse(_ s: String) -> Date? {550 let withFraction = ISO8601DateFormatter()551 withFraction.formatOptions = [.withInternetDateTime, .withFractionalSeconds]552 if let d = withFraction.date(from: s) { return d }553 // Drop the fractional part and parse to the second.554 var plain = s555 if let dot = plain.firstIndex(of: ".") {556 let end = plain[dot...].firstIndex { $0 == "+" || $0 == "-" || $0 == "Z" } ?? plain.endIndex557 plain.removeSubrange(dot..<end)558 }559 let f = ISO8601DateFormatter()560 f.formatOptions = [.withInternetDateTime]561 return f.date(from: plain)562 }563}564