SPB Git

Repository Public

Keychain.swift 10.4 KB 252 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : Claude Remote / Codex Remote9// File             : Packages/ClaudeRemoteKit/Sources/ClaudeRemoteAuth/Keychain.swift10// Module           : ClaudeRemoteAuth11// Repository       : https://git.spboucher.ai/claude-remote-apple12// Project Website  : https://claude.spboucher.ai13// Created          : 2026-11-2914// Last Modified    : 2026-11-2915//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: support@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// =============================================================================8788import ClaudeRemoteModels89import Foundation90import Security9192/// Minimal secret storage, so that everything above it is testable without the real Keychain.93public protocol KeychainStoring: Sendable {94    func read(_ account: String) throws -> Data?95    func write(_ data: Data, account: String) throws96    func delete(_ account: String) throws97}9899public struct KeychainError: Error, Hashable, Sendable, CustomStringConvertible {100    public var status: OSStatus101    public var description: String { "Keychain error \(status)" }102    /// The process is not signed with the entitlements the data-protection keychain needs103    /// (`swift test`, unsigned command-line tools).104    public var isMissingEntitlement: Bool { status == errSecMissingEntitlement }105}106107/// Generic-password items, `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`: readable by the108/// app (and by background refresh) after the first unlock, never synchronised, never restored on109/// another device.110public struct SystemKeychain: KeychainStoring {111    public var service: String112    /// Optional shared access group (`<TeamID>.<group>`). Leave nil unless another target of the113    /// same team must read the items; widgets do NOT need it (they read `SharedSummaryCache`).114    public var accessGroup: String?115    /// The data-protection keychain (required on iOS, recommended on macOS for signed apps).116    public var useDataProtectionKeychain: Bool117118    public init(service: String, accessGroup: String? = nil, useDataProtectionKeychain: Bool = true) {119        self.service = service120        self.accessGroup = accessGroup121        self.useDataProtectionKeychain = useDataProtectionKeychain122    }123124    private func base(_ account: String) -> [CFString: Any] {125        var q: [CFString: Any] = [kSecClass: kSecClassGenericPassword, kSecAttrService: service, kSecAttrAccount: account]126        if let accessGroup { q[kSecAttrAccessGroup] = accessGroup }127        if useDataProtectionKeychain { q[kSecUseDataProtectionKeychain] = true }128        q[kSecAttrSynchronizable] = false129        return q130    }131132    public func read(_ account: String) throws -> Data? {133        var q = base(account)134        q[kSecReturnData] = true135        q[kSecMatchLimit] = kSecMatchLimitOne136        var out: CFTypeRef?137        let status = SecItemCopyMatching(q as CFDictionary, &out)138        if status == errSecItemNotFound { return nil }139        guard status == errSecSuccess else { throw KeychainError(status: status) }140        return out as? Data141    }142143    public func write(_ data: Data, account: String) throws {144        let update: [CFString: Any] = [kSecValueData: data, kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly]145        var status = SecItemUpdate(base(account) as CFDictionary, update as CFDictionary)146        if status == errSecItemNotFound {147            var add = base(account)148            add.merge(update) { _, new in new }149            status = SecItemAdd(add as CFDictionary, nil)150        }151        guard status == errSecSuccess else { throw KeychainError(status: status) }152    }153154    public func delete(_ account: String) throws {155        let status = SecItemDelete(base(account) as CFDictionary)156        guard status == errSecSuccess || status == errSecItemNotFound else { throw KeychainError(status: status) }157    }158}159160/// Process-local storage for tests, previews and UI tests. Nothing is persisted.161public final class InMemoryKeychain: KeychainStoring, @unchecked Sendable {162    private let lock = NSLock()163    private var items: [String: Data] = [:]164    /// When set, every write fails with this status (failure-path tests).165    public var failWritesWith: OSStatus? {166        get { lock.withLock { _failWrites } }167        set { lock.withLock { _failWrites = newValue } }168    }169    private var _failWrites: OSStatus?170171    public init() {}172    public var accounts: [String] { lock.withLock { items.keys.sorted() } }173    public func read(_ account: String) throws -> Data? { lock.withLock { items[account] } }174    public func write(_ data: Data, account: String) throws {175        try lock.withLock {176            if let _failWrites { throw KeychainError(status: _failWrites) }177            items[account] = data178        }179    }180    public func delete(_ account: String) throws { lock.withLock { _ = items.removeValue(forKey: account) } }181}182183/// What is persisted about the signed-in session. The token is a secret.184public struct StoredCredential: Codable, Hashable, Sendable {185    public var sessionId: String186    public var token: String187    public var tokenExpiresAt: Date188    public var expiresAt: Date189    public var username: String?190191    public init(session: NativeSession, username: String?) {192        sessionId = session.id193        token = session.token194        tokenExpiresAt = session.tokenExpiresAt195        expiresAt = session.expiresAt196        self.username = username197    }198199    public var session: NativeSession {200        NativeSession(id: sessionId, token: token, tokenExpiresAt: tokenExpiresAt, expiresAt: expiresAt, secondFactor: true)201    }202}203204/// Keychain-backed storage of the session credential and of the stable install id. Nothing here205/// ever goes to `UserDefaults`. Only FULL sessions are stored; a session waiting for its second206/// factor lives in memory.207public struct CredentialStore: Sendable {208    private let keychain: any KeychainStoring209    private let scope: String210211    /// - Parameter scope: distinguishes instances sharing a keychain service (use the host).212    public init(keychain: any KeychainStoring, scope: String) {213        self.keychain = keychain214        self.scope = scope215    }216217    /// Keychain service name for a profile and build flavour.218    public static func service(for profile: AgentProfile, debug: Bool = false) -> String {219        profile.bundleIdentifier + (debug ? ".dev" : "") + ".session"220    }221222    private var credentialAccount: String { "credential@\(scope)" }223    private static let installAccount = "install-id"224225    public func load() -> StoredCredential? {226        guard let data = try? keychain.read(credentialAccount) else { return nil }227        return try? CRJSON.decode(StoredCredential.self, from: data)228    }229230    public func save(_ credential: StoredCredential) throws {231        try keychain.write(try CRJSON.encode(credential), account: credentialAccount)232    }233234    public func clear() {235        try? keychain.delete(credentialAccount)236    }237238    /// Stable identifier of this installation (created once, kept across sign-outs).239    public func installID() -> String {240        if let data = try? keychain.read(Self.installAccount), let id = String(data: data, encoding: .utf8), UUID(uuidString: id) != nil {241            return id242        }243        let id = UUID().uuidString.lowercased()244        try? keychain.write(Data(id.utf8), account: Self.installAccount)245        return id246    }247248    public func resetInstallID() {249        try? keychain.delete(Self.installAccount)250    }251}252
Files main
Menu

Theme