SPB Git

Repository Public

SessionTokenStore.swift 2.4 KB 59 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/API/SessionTokenStore.swift3// Description: Where the session cookie value lives between launches: the Keychain (this device only, readable only while unlocked).4//              The value is the server's opaque session token; it is not a key and cannot sign anything.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Security1011public protocol SessionTokenStoring: Sendable {12    func load() -> String?13    func save(_ token: String?)14}1516public final class InMemoryTokenStore: SessionTokenStoring, @unchecked Sendable {17    private let lock = NSLock()18    private var token: String?19    public init(_ token: String? = nil) { self.token = token }20    public func load() -> String? { lock.withLock { token } }21    public func save(_ token: String?) { lock.withLock { self.token = token } }22}2324public struct KeychainTokenStore: SessionTokenStoring {25    private let service: String26    private let account: String27    private let accessGroup: String?2829    public init(service: String, account: String = "session", accessGroup: String? = nil) {30        self.service = service; self.account = account; self.accessGroup = accessGroup31    }3233    private var base: [String: Any] {34        var q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account,35                                kSecUseDataProtectionKeychain as String: true]36        if let accessGroup { q[kSecAttrAccessGroup as String] = accessGroup }37        return q38    }3940    public func load() -> String? {41        var q = base42        q[kSecReturnData as String] = true43        q[kSecMatchLimit as String] = kSecMatchLimitOne44        var out: CFTypeRef?45        guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? Data else { return nil }46        return String(data: d, encoding: .utf8)47    }4849    public func save(_ token: String?) {50        SecItemDelete(base as CFDictionary)51        guard let token, let data = token.data(using: .utf8) else { return }52        var q = base53        q[kSecValueData as String] = data54        // never in a backup, never on another device, unreadable while the device is locked55        q[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly56        SecItemAdd(q as CFDictionary, nil)57    }58}59
Files main
Menu

Theme