SPB Git

Repository Public

WebAuthn.swift 11.0 KB 241 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Lou-Ka Admin iOS9// File             : LouKaAdmin/Core/WebAuthn.swift10// Description      : clés d'accès, partie pure — base64url, valeur JSON11//                    quelconque, lecture des options du serveur (format JSON de12//                    WebAuthn) et construction des objets `credential` attendus13//                    par le serveur (équivalent de `credential.toJSON()` du14//                    navigateur). Aucune dépendance à l'interface : testé sur15//                    des données fixes.16// Module           : LouKaAdmin17// Repository       : https://git.spboucher.ai/lou-ka-admin-ios18// Project Website  : https://www.lou-ka.com19// Created          : 2026-11-3020// Last Modified    : 2026-11-3021//22// =============================================================================23// AUTHOR & PROFESSIONAL AFFILIATION24// =============================================================================25//26// Author           : Simon-Pierre Boucher27// Position         : Professor of Finance28// Institution      : Université du Québec en Outaouais (UQO)29// Department       : Département des sciences administratives30// Organization     : SP Boucher31//32// Website          : https://spboucher.ai33// Git              : https://git.spboucher.ai34//35// =============================================================================36// OFFICIAL CONTACT DIRECTORY37// =============================================================================38//39// General          : info@spboucher.ai40// Professional     : contact@spboucher.ai41// Direct           : simon@spboucher.ai42// Research         : research@spboucher.ai43// Development      : dev@spboucher.ai44// Support          : support@spboucher.ai45// Security/Admin   : admin@spboucher.ai46// Notifications    : notifications@spboucher.ai47//48// Preferred Contact: support@spboucher.ai49//50// =============================================================================51// COPYRIGHT & INTELLECTUAL PROPERTY52// =============================================================================53//54// Copyright (c) 202655// Simon-Pierre Boucher56//57// All rights reserved where applicable.58//59// This file is governed by the applicable project license,60// copyright notices, institutional agreements and relevant law.61//62// Unless expressly authorized by the applicable license or63// rights holder, copying, redistribution, sublicensing,64// publication and commercial exploitation are not permitted.65//66// Existing third-party rights and notices remain unaffected.67//68// =============================================================================69// CONFIDENTIALITY & SECURITY70// =============================================================================71//72// Classification   : Public73// Distribution     : Public repository; use is governed by the project license74// Security Contact : admin@spboucher.ai75//76// Access to this source does not independently grant permission77// to redistribute or disclose confidential materials.78//79// Do not embed credentials, private keys, access tokens,80// certificates or confidential personal information.81//82// =============================================================================83// LICENSE & MAINTENANCE84// =============================================================================85//86// License          : None specified (no license file in this repository)87// Maintainer       : Simon-Pierre Boucher88// Technical Contact: dev@spboucher.ai89//90// =============================================================================91// END OF SP BOUCHER SOURCE HEADER92// =============================================================================9394import Foundation9596enum Base64URL {97    /// Sans remplissage, avec « - » et « _ ».98    static func encode(_ data: Data) -> String {99        data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")100    }101102    /// Accepte base64url avec ou sans remplissage ; nil si la chaîne n'en est pas.103    static func decode(_ value: String) -> Data? {104        let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)105        guard !trimmed.isEmpty, trimmed.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" || $0 == "=") }) else { return trimmed.isEmpty ? Data() : nil }106        var b64 = trimmed.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/").replacingOccurrences(of: "=", with: "")107        guard b64.count % 4 != 1 else { return nil }108        b64 += String(repeating: "=", count: (4 - b64.count % 4) % 4)109        return Data(base64Encoded: b64)110    }111}112113/// Valeur JSON quelconque : les `options` du serveur et le `credential` renvoyé.114enum JSONValue: Codable, Sendable, Equatable {115    case null, bool(Bool), number(Double), string(String), array([JSONValue]), object([String: JSONValue])116117    init(from decoder: Decoder) throws {118        let c = try decoder.singleValueContainer()119        if c.decodeNil() { self = .null }120        else if let b = try? c.decode(Bool.self) { self = .bool(b) }121        else if let n = try? c.decode(Double.self) { self = .number(n) }122        else if let s = try? c.decode(String.self) { self = .string(s) }123        else if let a = try? c.decode([JSONValue].self) { self = .array(a) }124        else { self = .object(try c.decode([String: JSONValue].self)) }125    }126127    func encode(to encoder: Encoder) throws {128        var c = encoder.singleValueContainer()129        switch self {130        case .null: try c.encodeNil()131        case .bool(let b): try c.encode(b)132        case .number(let n): try c.encode(n)133        case .string(let s): try c.encode(s)134        case .array(let a): try c.encode(a)135        case .object(let o): try c.encode(o)136        }137    }138139    subscript(key: String) -> JSONValue? { if case .object(let o) = self { return o[key] }; return nil }140    var string: String? { if case .string(let s) = self { return s }; return nil }141    var array: [JSONValue]? { if case .array(let a) = self { return a }; return nil }142}143144enum WebAuthnError: Error, Equatable {145    /// Les options du serveur sont illisibles (défi absent ou mal encodé…).146    case badOptions(String)147}148149/// Options de connexion (`POST /connexion/options`).150struct PasskeyAssertionOptions: Equatable, Sendable {151    var challenge: Data152    var rpID: String153    /// Clés permises ; vide : n'importe quelle clé du domaine (clé découvrable).154    var allowCredentials: [Data]155    var userVerification: String156157    /// - Parameter defaultRPID: domaine utilisé si le serveur n'en nomme pas.158    init(json: JSONValue, defaultRPID: String) throws {159        guard let c = json["challenge"]?.string, let challenge = Base64URL.decode(c), challenge.count >= 16 else { throw WebAuthnError.badOptions("challenge") }160        self.challenge = challenge161        rpID = json["rpId"]?.string ?? defaultRPID162        allowCredentials = (json["allowCredentials"]?.array ?? []).compactMap { $0["id"]?.string.flatMap(Base64URL.decode) }163        userVerification = json["userVerification"]?.string ?? "required"164    }165}166167/// Options d'enregistrement (`POST /activation/options`).168struct PasskeyRegistrationOptions: Equatable, Sendable {169    var challenge: Data170    var rpID: String171    var userID: Data172    var userName: String173    var displayName: String174    var excludeCredentials: [Data]175176    init(json: JSONValue, defaultRPID: String) throws {177        guard let c = json["challenge"]?.string, let challenge = Base64URL.decode(c), challenge.count >= 16 else { throw WebAuthnError.badOptions("challenge") }178        guard let user = json["user"], let uid = user["id"]?.string, let userID = Base64URL.decode(uid), !userID.isEmpty else { throw WebAuthnError.badOptions("user.id") }179        self.challenge = challenge180        self.userID = userID181        rpID = json["rp"]?["id"]?.string ?? defaultRPID182        userName = user["name"]?.string ?? ""183        displayName = user["displayName"]?.string ?? userName184        excludeCredentials = (json["excludeCredentials"]?.array ?? []).compactMap { $0["id"]?.string.flatMap(Base64URL.decode) }185    }186}187188/// Objets `credential` au format JSON de WebAuthn, tout en base64url.189enum WebAuthnCredential {190    /// Résultat d'une connexion (`navigator.credentials.get`).191    static func assertion(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userHandle: Data?) -> JSONValue {192        var response: [String: JSONValue] = [193            "clientDataJSON": .string(Base64URL.encode(clientDataJSON)),194            "authenticatorData": .string(Base64URL.encode(authenticatorData)),195            "signature": .string(Base64URL.encode(signature)),196        ]197        if let userHandle, !userHandle.isEmpty { response["userHandle"] = .string(Base64URL.encode(userHandle)) }198        return envelope(credentialID, response)199    }200201    /// Résultat d'un enregistrement (`navigator.credentials.create`).202    static func registration(credentialID: Data, clientDataJSON: Data, attestationObject: Data) -> JSONValue {203        envelope(credentialID, [204            "clientDataJSON": .string(Base64URL.encode(clientDataJSON)),205            "attestationObject": .string(Base64URL.encode(attestationObject)),206            "transports": .array([.string("internal"), .string("hybrid")]),207        ])208    }209210    private static func envelope(_ id: Data, _ response: [String: JSONValue]) -> JSONValue {211        let encoded = Base64URL.encode(id)212        return .object([213            "id": .string(encoded), "rawId": .string(encoded), "type": .string("public-key"),214            "response": .object(response), "clientExtensionResults": .object([:]), "authenticatorAttachment": .string("platform"),215        ])216    }217}218219/// Jeton d'une adresse d'activation : l'adresse entière `https://www.lou-ka.com/admin/activation?jeton=…`, ou le jeton seul.220enum ActivationLink {221    static func token(from input: String) -> String? {222        let text = input.trimmingCharacters(in: .whitespacesAndNewlines)223        guard !text.isEmpty else { return nil }224        if let comps = URLComponents(string: text), comps.scheme != nil || text.contains("?") {225            guard let t = comps.queryItems?.first(where: { $0.name == "jeton" || $0.name == "token" })?.value else { return nil }226            return valid(t)227        }228        return valid(text)229    }230231    private static func valid(_ t: String) -> String? {232        // jeton opaque du serveur : lettres, chiffres, « - », « _ », « . » ; rien d'autre233        let ok = t.count >= 16 && t.count <= 512 && t.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || "-_.~".contains($0)) }234        return ok ? t : nil235    }236}237238extension WebAuthnError: LocalizedError {239    var errorDescription: String? { "Le serveur a renvoyé une demande de clé d'accès illisible. Réessayez dans un instant." }240}241
Files main
Menu

Theme