SPB Git

Repository Public

SecretStore.swift 6.9 KB 165 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/SecretStore.swift10// Description      : garde du jeton de session — trousseau du système11//                    (Keychain), lisible seulement appareil déverrouillé, lié à12//                    cet appareil, jamais synchronisé, jamais dans UserDefaults13//                    ni dans les journaux. Une variante en mémoire sert aux14//                    tests et à la base locale jetable.15// Module           : LouKaAdmin16// Repository       : https://git.spboucher.ai/lou-ka-admin-ios17// Project Website  : https://www.lou-ka.com18// Created          : 2026-11-3019// Last Modified    : 2026-11-3020//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author           : Simon-Pierre Boucher26// Position         : Professor of Finance27// Institution      : Université du Québec en Outaouais (UQO)28// Department       : Département des sciences administratives29// Organization     : SP Boucher30//31// Website          : https://spboucher.ai32// Git              : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General          : info@spboucher.ai39// Professional     : contact@spboucher.ai40// Direct           : simon@spboucher.ai41// Research         : research@spboucher.ai42// Development      : dev@spboucher.ai43// Support          : support@spboucher.ai44// Security/Admin   : admin@spboucher.ai45// Notifications    : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification   : Public72// Distribution     : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License          : None specified (no license file in this repository)86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import Foundation94import Security9596/// Petit coffre clé → octets. Le jeton de session d'administration y est rangé.97protocol SecretStore: Sendable {98    func read(_ key: String) -> Data?99    @discardableResult func write(_ key: String, _ data: Data) -> Bool100    func delete(_ key: String)101}102103extension SecretStore {104    func string(_ key: String) -> String? { read(key).flatMap { String(data: $0, encoding: .utf8) } }105    @discardableResult func set(_ key: String, _ value: String) -> Bool { write(key, Data(value.utf8)) }106}107108/// Trousseau du système : élément « mot de passe générique », `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`109/// (illisible appareil verrouillé, jamais restauré sur un autre appareil), sans synchronisation iCloud :110/// la session d'administration appartient à cet appareil.111struct KeychainStore: SecretStore {112    var service = "com.spboucher.louka.admin.session"113114    private func base(_ key: String) -> [String: Any] {115        [kSecClass as String: kSecClassGenericPassword,116         kSecAttrService as String: service,117         kSecAttrAccount as String: key,118         kSecAttrSynchronizable as String: false]119    }120121    func read(_ key: String) -> Data? {122        var q = base(key)123        q[kSecReturnData as String] = true124        q[kSecMatchLimit as String] = kSecMatchLimitOne125        var out: CFTypeRef?126        guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess else { return nil }127        return out as? Data128    }129130    @discardableResult131    func write(_ key: String, _ data: Data) -> Bool {132        let attrs: [String: Any] = [kSecValueData as String: data,133                                    kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly]134        let status = SecItemUpdate(base(key) as CFDictionary, attrs as CFDictionary)135        if status == errSecSuccess { return true }136        guard status == errSecItemNotFound else { return false }137        var q = base(key)138        attrs.forEach { q[$0.key] = $0.value }139        return SecItemAdd(q as CFDictionary, nil) == errSecSuccess140    }141142    func delete(_ key: String) {143        SecItemDelete(base(key) as CFDictionary)144    }145146    /// Classe de protection de l'élément (vérifiée par les tests).147    func accessibility(_ key: String) -> String? {148        var q = base(key)149        q[kSecReturnAttributes as String] = true150        q[kSecMatchLimit as String] = kSecMatchLimitOne151        var out: CFTypeRef?152        guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? [String: Any] else { return nil }153        return d[kSecAttrAccessible as String] as? String154    }155}156157/// Coffre en mémoire (tests).158final class MemoryStore: SecretStore, @unchecked Sendable {159    private let lock = NSLock()160    private var values: [String: Data] = [:]161    func read(_ key: String) -> Data? { lock.withLock { values[key] } }162    @discardableResult func write(_ key: String, _ data: Data) -> Bool { lock.withLock { values[key] = data }; return true }163    func delete(_ key: String) { lock.withLock { values[key] = nil } }164}165
Files main
Menu

Theme