Repository Public
1// ORIX DJ2// File: App/Sources/Features/ClaudeStudio/ClaudeAccess.swift3// Description: Access to the user's Anthropic API key (Keychain only) for Claude Studio and Settings. The interface4// only ever sees the masked form. Debug builds can replace the network transport with a local stub.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Observation10import ORIXDJCore1112@MainActor @Observable13final class ClaudeAccess {14 static let shared = ClaudeAccess()1516 /// "sk-ant-…abcd" when a key is stored, nil otherwise. Never the key itself.17 private(set) var maskedKey: String?18 /// True when requests are answered by the local debug stub instead of api.anthropic.com.19 private(set) var isStub = false2021 @ObservationIgnored private var service = APIKeyStore.defaultService22 @ObservationIgnored private var configured = false23 @ObservationIgnored private var stubClient: AnthropicClient?2425 var hasKey: Bool { isStub || maskedKey != nil }2627 /// Call once per screen that uses the key. Isolated instances (tests, screenshots) use their own Keychain item.28 func configure(_ model: AppModel) {29 guard !configured else { return }30 configured = true31 if model.options.dataDirectory != nil { service = APIKeyStore.defaultService + ".test" }32 #if DEBUG33 if UserDefaults.standard.bool(forKey: "ORIXClaudeStub") { isStub = true; stubClient = ClaudeStub.client() }34 #endif35 refresh()36 }3738 func refresh() { maskedKey = isStub ? nil : APIKeyStore.load(service: service).map(APIKeyStore.masked) }3940 func client(_ model: AppModel) -> AnthropicClient { stubClient ?? model.anthropic }4142 /// The key for a request header. Not for display, logs or storage anywhere else.43 func keyForRequest() -> String? {44 #if DEBUG45 if isStub { return ClaudeStub.placeholderKey }46 #endif47 return APIKeyStore.load(service: service)48 }4950 @discardableResult func save(_ key: String) -> Bool {51 let trimmed = key.trimmingCharacters(in: .whitespacesAndNewlines)52 guard !trimmed.isEmpty else { return false }53 let ok = APIKeyStore.save(trimmed, service: service)54 refresh()55 return ok56 }5758 @discardableResult func remove() -> Bool {59 let ok = APIKeyStore.delete(service: service)60 refresh()61 return ok62 }63}64