Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Sources/SecureStorage/SecretStore.swift10// Description : Secret storage contract and its Keychain implementation11// (shared access group, this device only, never12// synchronised). There is deliberately no UserDefaults or13// file fallback: a failure is reported.14// Module : SecureStorage15// Repository : https://git.spboucher.ai/sp-keyboard16// Created : 2026-12-0117// Last Modified : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import Security9394/// Why a secret operation failed. Never carries the secret itself.95public enum SecretStoreError: Error, Equatable, Sendable {96 /// The Keychain refused the access group: entitlement missing or wrong team prefix.97 case missingEntitlement98 /// The device is locked and the item is only readable while unlocked.99 case interactionNotAllowed100 /// The stored bytes are not valid UTF-8.101 case malformedItem102 /// Any other `OSStatus`.103 case unexpectedStatus(Int32)104105 public var diagnosticCode: String {106 switch self {107 case .missingEntitlement: "entitlement"108 case .interactionNotAllowed: "locked"109 case .malformedItem: "malformed"110 case .unexpectedStatus(let status): "osstatus:\(status)"111 }112 }113}114115/// A place where one named secret lives. Implementations must never log or persist the value elsewhere.116public protocol SecretStoring: Sendable {117 func read(_ name: String) throws -> String?118 func write(_ value: String, for name: String) throws119 func delete(_ name: String) throws120}121122public extension SecretStoring {123 /// True when a non-empty value is present. Errors count as "absent" for display purposes only.124 func contains(_ name: String) -> Bool {125 guard let value = try? read(name) else { return false }126 return !value.isEmpty127 }128}129130/// Names of the secrets SP Keyboard stores.131public enum SecretName {132 public static let anthropicAPIKey = "anthropic-api-key"133}134135/// Generic-password Keychain items shared between the app and the keyboard extension.136public struct KeychainStore: SecretStoring {137 public let service: String138 /// Full access group (`<TeamPrefix>.<group>`). `nil` uses the default group of the calling binary.139 public let accessGroup: String?140141 public init(service: String = "ai.spboucher.keyboard", accessGroup: String?) {142 self.service = service143 self.accessGroup = accessGroup144 }145146 /// Resolves the shared group from the `SPKeychainAccessGroup` Info.plist key, which the build fills with147 /// `$(AppIdentifierPrefix)ai.spboucher.keyboard.shared` so the team prefix is never hard-coded.148 public static func shared(bundle: Bundle = .main) -> KeychainStore {149 let group = bundle.object(forInfoDictionaryKey: "SPKeychainAccessGroup") as? String150 return KeychainStore(accessGroup: (group?.isEmpty == false) ? group : nil)151 }152153 private func baseQuery(_ name: String) -> [CFString: Any] {154 var query: [CFString: Any] = [155 kSecClass: kSecClassGenericPassword,156 kSecAttrService: service,157 kSecAttrAccount: name,158 kSecAttrSynchronizable: kCFBooleanFalse as Any,159 kSecUseDataProtectionKeychain: true,160 ]161 if let accessGroup { query[kSecAttrAccessGroup] = accessGroup }162 return query163 }164165 public func read(_ name: String) throws -> String? {166 var query = baseQuery(name)167 query[kSecReturnData] = true168 query[kSecMatchLimit] = kSecMatchLimitOne169 var item: CFTypeRef?170 let status = SecItemCopyMatching(query as CFDictionary, &item)171 switch status {172 case errSecSuccess:173 guard let data = item as? Data, let value = String(data: data, encoding: .utf8) else {174 throw SecretStoreError.malformedItem175 }176 return value177 case errSecItemNotFound:178 return nil179 default:180 throw Self.error(for: status)181 }182 }183184 public func write(_ value: String, for name: String) throws {185 let data = Data(value.utf8)186 let attributes: [CFString: Any] = [187 kSecValueData: data,188 kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,189 ]190 let status = SecItemUpdate(baseQuery(name) as CFDictionary, attributes as CFDictionary)191 if status == errSecSuccess { return }192 guard status == errSecItemNotFound else { throw Self.error(for: status) }193 var query = baseQuery(name)194 attributes.forEach { query[$0.key] = $0.value }195 let addStatus = SecItemAdd(query as CFDictionary, nil)196 guard addStatus == errSecSuccess else { throw Self.error(for: addStatus) }197 }198199 public func delete(_ name: String) throws {200 let status = SecItemDelete(baseQuery(name) as CFDictionary)201 guard status == errSecSuccess || status == errSecItemNotFound else { throw Self.error(for: status) }202 }203204 private static func error(for status: OSStatus) -> SecretStoreError {205 switch status {206 case errSecMissingEntitlement: .missingEntitlement207 case errSecInteractionNotAllowed: .interactionNotAllowed208 default: .unexpectedStatus(status)209 }210 }211}212213/// Volatile store for tests and previews. Never used as a fallback for the Keychain.214public final class InMemorySecretStore: SecretStoring, @unchecked Sendable {215 private let lock = NSLock()216 private var values: [String: String] = [:]217 private var failure: SecretStoreError?218219 public init(_ initial: [String: String] = [:]) { values = initial }220221 /// Makes every later call throw, to exercise failure paths.222 public func failEverything(with error: SecretStoreError?) {223 lock.withLock { failure = error }224 }225226 public func read(_ name: String) throws -> String? {227 try lock.withLock {228 if let failure { throw failure }229 return values[name]230 }231 }232233 public func write(_ value: String, for name: String) throws {234 try lock.withLock {235 if let failure { throw failure }236 values[name] = value237 }238 }239240 public func delete(_ name: String) throws {241 try lock.withLock {242 if let failure { throw failure }243 values[name] = nil244 }245 }246}247248/// Shape checks and display masking for an Anthropic key. Purely local; a well-formed key may still be invalid.249public enum APIKeyFormat {250 public static func normalized(_ raw: String) -> String {251 raw.trimmingCharacters(in: .whitespacesAndNewlines)252 }253254 public static func looksValid(_ raw: String) -> Bool {255 let key = normalized(raw)256 guard key.hasPrefix("sk-ant-"), key.count >= 40, key.count <= 512 else { return false }257 return key.unicodeScalars.allSatisfy { scalar in258 scalar.isASCII && (CharacterSet.alphanumerics.contains(scalar) || scalar == "-" || scalar == "_")259 }260 }261262 /// `sk-ant-…AAAA`: enough to recognise a key, never enough to use it.263 public static func masked(_ raw: String) -> String {264 let key = normalized(raw)265 guard key.count > 12 else { return String(repeating: "•", count: key.count) }266 return "\(key.prefix(7))…\(key.suffix(4))"267 }268269 /// Replaces anything that looks like a key in `text`, so an error message can never leak one.270 public static func redacting(_ text: String) -> String {271 text.replacing(#/sk-ant-[A-Za-z0-9_\-]{8,}/#, with: "sk-ant-[redacted]")272 }273}274