SPB Git

Repository Public License

Secrets.swift 4.6 KB 97 lines swift

1import Foundation2import Security34public struct SecretError: Error, LocalizedError, Sendable, Equatable {5    public let message: String6    public init(_ message: String) { self.message = message }7    public var errorDescription: String? { message }8}910/// Where secrets live. The only production implementation is the macOS Keychain (hard rule 4).11public protocol SecretStore: Sendable {12    func secret(for account: String) throws -> String?13    func setSecret(_ value: String, for account: String) throws14    func removeSecret(for account: String) throws15}1617public enum SecretAccount {18    public static let anthropicAPIKey = "anthropic.api-key"19}2021/// Generic-password items under PRISM's own service. PRISM never queries another app's items.22public struct KeychainSecretStore: SecretStore {23    public let service: String24    public init(service: String = "ai.spboucher.prism") { self.service = service }2526    private func base(_ account: String) -> [String: Any] {27        [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account,28         kSecAttrSynchronizable as String: false]29    }3031    public func secret(for account: String) throws -> String? {32        var q = base(account)33        q[kSecReturnData as String] = true34        q[kSecMatchLimit as String] = kSecMatchLimitOne35        var out: CFTypeRef?36        let status = SecItemCopyMatching(q as CFDictionary, &out)37        if status == errSecItemNotFound { return nil }38        guard status == errSecSuccess, let data = out as? Data else { throw SecretError("The Keychain refused the read (status \(status)).") }39        return String(data: data, encoding: .utf8)40    }4142    public func setSecret(_ value: String, for account: String) throws {43        let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)44        guard !trimmed.isEmpty else { throw SecretError("The key is empty.") }45        let data = Data(trimmed.utf8)46        let update = SecItemUpdate(base(account) as CFDictionary, [kSecValueData as String: data] as CFDictionary)47        if update == errSecSuccess { return }48        guard update == errSecItemNotFound else { throw SecretError("The Keychain refused the update (status \(update)).") }49        var q = base(account)50        q[kSecValueData as String] = data51        q[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly52        q[kSecAttrLabel as String] = "PRISM — Anthropic API key"53        let add = SecItemAdd(q as CFDictionary, nil)54        guard add == errSecSuccess else { throw SecretError("The Keychain refused to store the key (status \(add)).") }55    }5657    public func removeSecret(for account: String) throws {58        let status = SecItemDelete(base(account) as CFDictionary)59        guard status == errSecSuccess || status == errSecItemNotFound else { throw SecretError("The Keychain refused the removal (status \(status)).") }60    }61}6263/// For tests and previews only.64public final class InMemorySecretStore: SecretStore, @unchecked Sendable {65    private let lock = NSLock()66    private var values: [String: String]67    public init(_ values: [String: String] = [:]) { self.values = values }68    public func secret(for account: String) throws -> String? { lock.withLock { values[account] } }69    public func setSecret(_ value: String, for account: String) throws {70        let t = value.trimmingCharacters(in: .whitespacesAndNewlines)71        guard !t.isEmpty else { throw SecretError("The key is empty.") }72        lock.withLock { values[account] = t }73    }74    public func removeSecret(for account: String) throws { lock.withLock { values[account] = nil } }75}7677/// Removes secrets from any text before it is logged, audited or exported.78public enum Redactor {79    public static let placeholder = "[redacted]"8081    public static func redact(_ text: String, known secrets: [String] = []) -> String {82        var out = text83        for s in secrets where s.count >= 8 { out = out.replacingOccurrences(of: s, with: placeholder) }84        // Anthropic-style keys and generic bearer tokens, even when the exact value is unknown.85        for pattern in [#"sk-ant-[A-Za-z0-9_\-]{8,}"#, #"(?i)(x-api-key|authorization)\s*[:=]\s*\S+"#, #"(?i)bearer\s+[A-Za-z0-9._\-]{12,}"#] {86            out = out.replacingOccurrences(of: pattern, with: placeholder, options: .regularExpression)87        }88        return out89    }9091    /// A display form that proves which key is stored without revealing it: `sk-ant-…a1b2`.92    public static func fingerprint(_ secret: String) -> String {93        guard secret.count > 12 else { return "••••" }94        return secret.prefix(7) + "…" + secret.suffix(4)95    }96}97
Files main
Menu

Theme