diff --git a/README.md b/README.md index f19f96e..f3c8447 100644 --- a/README.md +++ b/README.md @@ -100,15 +100,16 @@ item after you install an update. Signing and notarization are planned after 0.1 Every provider starts **disabled**. TokenBar reads nothing until you enable one, and it shows what will be read before you confirm. -- **Claude** reads Claude Code's sign-in from your Keychain on each refresh. macOS asks - for permission the first time; choose **Always Allow** so it does not ask on every - refresh. If you deny it, TokenBar stops asking until you refresh manually. +- **Claude** reads Claude Code's sign-in from your Keychain and keeps it in memory while + TokenBar runs. It reads it again only when Claude Code renews it or it expires, so macOS + asks at most then; choose **Always Allow** so it does not ask at all. If you deny it, + TokenBar stops asking until you refresh manually. - **Codex** reads `~/.codex/auth.json` (or `$CODEX_HOME/auth.json`). Codex installations that keep their sign-in in the Keychain (`cli_auth_credentials_store = "keyring"`) are not supported yet. If a sign-in expires, run Claude Code or Codex once and TokenBar picks up the renewed -sign-in on its next refresh. TokenBar never renews or copies tokens itself. +sign-in on its next refresh. TokenBar never renews tokens or writes them to disk. ## Privacy @@ -119,8 +120,9 @@ sign-in on its next refresh. TokenBar never renews or copies tokens itself. - No analytics, telemetry, crash reporting, tracking, or update checks. - No database or history: usage is kept in memory and never written to disk. Network responses are not cached and cookies are not stored. -- Sign-ins are read when a refresh happens. TokenBar never stores, copies, or refreshes - them, and never logs tokens, account identifiers, or response bodies. +- Sign-ins are read when a refresh needs them. TokenBar keeps the Claude Code token in + memory only, never writes sign-ins to disk or refreshes them, and never logs tokens, + account identifiers, or response bodies. - Preferences (refresh interval, enabled providers, menu bar mode) are stored in the usual macOS preferences file. diff --git a/SECURITY.md b/SECURITY.md index 3d37408..8e36d9c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -18,9 +18,10 @@ Only the latest release receives security fixes while TokenBar is in `0.x`. ## What TokenBar promises - Usage data stays on your Mac. There is no TokenBar server. -- Credentials owned by other apps are read when a refresh happens and are never - copied, refreshed, transmitted anywhere except to the provider they belong to, - or written to disk. +- Credentials owned by other apps are read when a refresh needs them and are never + refreshed, transmitted anywhere except to the provider they belong to, or written + to disk or to another Keychain item. A Claude Code token may stay in memory while + TokenBar runs, so the Keychain is not read on every refresh. - Credentials TokenBar stores itself live only in the macOS Keychain. - Tokens, cookies, account identifiers, authenticated URLs, and response bodies are never logged. diff --git a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/ClaudeCodeCredentials.swift b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/ClaudeCodeCredentials.swift index 3226885..9de5a1d 100644 --- a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/ClaudeCodeCredentials.swift +++ b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/ClaudeCodeCredentials.swift @@ -2,10 +2,11 @@ import Foundation import Security import TokenBarCore -/// The parts of Claude Code's sign-in that TokenBar needs, read fresh for every refresh. +/// The parts of Claude Code's sign-in that TokenBar needs. /// -/// Never stored, copied, refreshed, or logged by TokenBar. The description is redacted so the -/// token cannot leak through string interpolation. +/// Kept only in memory by ``ClaudeCredentialCache``; never written to disk, copied to another Keychain +/// item, refreshed, or logged by TokenBar. The description is redacted so the token cannot leak through +/// string interpolation. struct ClaudeCodeCredentials: Sendable, CustomStringConvertible { let accessToken: String let expiresAt: Date? @@ -47,7 +48,11 @@ struct ClaudeCodeCredentials: Sendable, CustomStringConvertible { /// Where ``ClaudeProvider`` gets Claude Code's sign-in. protocol ClaudeCredentialSource: Sendable { + /// Reads the sign-in itself. macOS may ask the user for permission. func credentials() throws -> ClaudeCodeCredentials + /// When Claude Code last wrote its sign-in, read without the secret so macOS does not ask. + /// Throws ``ProviderError/notConnected`` when there is no sign-in; `nil` when it is unknown. + func modificationDate() throws -> Date? } /// Reads the generic password item Claude Code keeps in the login Keychain. @@ -79,4 +84,25 @@ struct ClaudeCodeKeychain: ClaudeCredentialSource { throw ProviderError.unknown } } + + func modificationDate() throws -> Date? { + // Attributes only: the item's data, and with it the permission prompt, is not touched. + let query: [CFString: Any] = [ + kSecClass: kSecClassGenericPassword, + kSecAttrService: service, + kSecReturnAttributes: true, + kSecMatchLimit: kSecMatchLimitOne, + ] + var result: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &result) + switch status { + case errSecSuccess: + return (result as? [CFString: Any])?[kSecAttrModificationDate] as? Date + case errSecItemNotFound: + throw ProviderError.notConnected + default: + // Keychain locked or unavailable: the cache falls back to its own retry limit. + return nil + } + } } diff --git a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/ClaudeCredentialCache.swift b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/ClaudeCredentialCache.swift new file mode 100644 index 0000000..b10989d --- /dev/null +++ b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/ClaudeCredentialCache.swift @@ -0,0 +1,115 @@ +import Foundation +import TokenBarCore +import os + +/// Keeps Claude Code's sign-in in memory so the Keychain item, and the macOS permission prompt that +/// can come with it, is not read on every refresh. +/// +/// The item's data is read again only when: +/// - nothing usable is cached and no read happened yet, +/// - Claude Code wrote the item since the last read (its modification date changed), or +/// - the cached token expired or was rejected, at most once per ``retryInterval``, in case Claude +/// Code renewed it without the modification date changing. +/// +/// Memory only: nothing is written to disk, `UserDefaults`, or another Keychain item, and everything +/// is gone when TokenBar quits. Being an actor, reads are serialized: concurrent refreshes share one +/// Keychain read, and an invalidation can never be undone by an older read finishing later. +actor ClaudeCredentialCache { + /// A token this close to `expiresAt` is treated as expired, so it does not expire mid-request. + static let expiryMargin: TimeInterval = 60 + /// Minimum time between reads while the item has not changed. Bounds how often macOS can ask. + static let retryInterval: TimeInterval = 15 * 60 + + private let source: any ClaudeCredentialSource + private let now: @Sendable () -> Date + private let logger = Logger(subsystem: Log.subsystem, category: "claude") + + private var cached: ClaudeCodeCredentials? + /// The item's modification date when it was last read. + private var readVersion: Date? + /// When the item was last read, or its token last rejected. Starts the ``retryInterval``. + private var lastAttempt: Date? + /// Why the cached sign-in cannot be used, reported until the next read. + private var failure: ProviderError? + /// Token the endpoint rejected. Never sent again, even if the Keychain returns it again. + private var rejectedToken: String? + + init(source: any ClaudeCredentialSource, now: @escaping @Sendable () -> Date) { + self.source = source + self.now = now + } + + /// A sign-in that is not expired and was not rejected, from memory when possible. + func credentials() throws -> ClaudeCodeCredentials { + let version: Date? + do { + version = try source.modificationDate() + } catch { + // Claude Code signed out: forget the old sign-in instead of sending it. + clear() + throw error + } + + if let cached, isUsable(cached), version == nil || version == readVersion { + logger.debug("Reusing Claude Code sign-in from memory") + return cached + } + + let changed = version != nil && version != readVersion + if !changed, let lastAttempt, now().timeIntervalSince(lastAttempt) < Self.retryInterval { + // The Keychain would most likely return the same sign-in; do not ask macOS again yet. + throw failure ?? .unauthorized + } + return try read(version: version) + } + + /// Marks `accessToken` as rejected by the endpoint. Ignored if a newer token is cached. + func reject(_ accessToken: String) { + guard cached?.accessToken == accessToken else { return } + rejectedToken = accessToken + failure = .unauthorized + lastAttempt = now() + } + + private func read(version: Date?) throws -> ClaudeCodeCredentials { + logger.debug("Reading Claude Code sign-in from the Keychain") + lastAttempt = now() + readVersion = version + let credentials: ClaudeCodeCredentials + do { + credentials = try source.credentials() + } catch ProviderError.accessDenied { + // The user declined. Only a manual refresh asks again (see `ProviderState.shouldRefresh`), + // and it must not be held back by the retry interval. + clear() + throw ProviderError.accessDenied + } catch { + cached = nil + failure = ProviderError(error) + throw error + } + + cached = credentials + guard isUsable(credentials) else { + logger.info("Claude Code sign-in expired or rejected; not calling the endpoint") + failure = .unauthorized + throw ProviderError.unauthorized + } + failure = nil + rejectedToken = nil + return credentials + } + + private func isUsable(_ credentials: ClaudeCodeCredentials) -> Bool { + credentials.accessToken != rejectedToken + && !credentials.isExpired(at: now().addingTimeInterval(Self.expiryMargin)) + } + + private func clear() { + cached = nil + readVersion = nil + lastAttempt = nil + failure = nil + rejectedToken = nil + } +} diff --git a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/ClaudeProvider.swift b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/ClaudeProvider.swift index e933f5d..3e3fe61 100644 --- a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/ClaudeProvider.swift +++ b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Claude/ClaudeProvider.swift @@ -8,10 +8,11 @@ import os /// not document it for other apps, so it can change or disappear. Everything Claude-specific lives /// in this folder; removing the provider means removing it from the app's provider registry. /// -/// Per refresh: read Claude Code's Keychain item → `GET /api/oauth/usage` → map windows. -/// The token is never stored, copied, refreshed, or logged. An expired token is reported as -/// ``ProviderError/unauthorized`` without calling the endpoint; Claude Code renews it the next time -/// it is used. +/// Per refresh: Claude Code's sign-in (from memory, or its Keychain item when needed, see +/// ``ClaudeCredentialCache``) → `GET /api/oauth/usage` → map windows. +/// The token is kept in memory only, and never written to disk, refreshed, or logged. An expired or +/// rejected token is reported as ``ProviderError/unauthorized`` without calling the endpoint; Claude +/// Code renews it the next time it is used. public struct ClaudeProvider: UsageProvider { public let descriptor = ProviderDescriptor( id: "claude", @@ -28,9 +29,10 @@ public struct ClaudeProvider: UsageProvider { ), accessDescription: String( localized: """ - Requires Claude Code signed in on this Mac. On each refresh TokenBar reads Claude Code's \ - sign-in from your Keychain (macOS asks for permission) and sends it only to api.anthropic.com. \ - It is never stored, copied, or refreshed by TokenBar. + Requires Claude Code signed in on this Mac. TokenBar reads Claude Code's sign-in from your \ + Keychain (macOS asks for permission) when it starts and when Claude Code renews it, keeps it \ + in memory only while TokenBar runs, and sends it only to api.anthropic.com. It is never \ + written to disk or refreshed by TokenBar. """, bundle: .module ) @@ -38,7 +40,7 @@ public struct ClaudeProvider: UsageProvider { static let usageURL = URL(string: "https://api.anthropic.com/api/oauth/usage")! - private let credentials: any ClaudeCredentialSource + private let credentials: ClaudeCredentialCache private let http: any HTTPClient private let now: @Sendable () -> Date private let logger = Logger(subsystem: Log.subsystem, category: "claude") @@ -52,21 +54,20 @@ public struct ClaudeProvider: UsageProvider { http: any HTTPClient, now: @escaping @Sendable () -> Date = { Date() } ) { - self.credentials = credentials + self.credentials = ClaudeCredentialCache(source: credentials, now: now) self.http = http self.now = now } public func fetchUsage() async throws -> UsageSnapshot { - let credentials = try credentials.credentials() - guard !credentials.isExpired(at: now()) else { - logger.info("Claude Code sign-in expired; not calling the endpoint") - throw ProviderError.unauthorized - } + let credentials = try await credentials.credentials() let (data, response) = try await http.send(Self.request(token: credentials.accessToken)) // Only the status code is logged: the body and headers identify the account. logger.debug("Usage request finished with HTTP \(response.statusCode, privacy: .public)") + if Self.isTokenRejected(status: response.statusCode, body: data) { + await self.credentials.reject(credentials.accessToken) + } if let error = ProviderError(httpStatus: response.statusCode, retryAfter: response.retryAfter(now: now())) { throw error } @@ -90,6 +91,19 @@ public struct ClaudeProvider: UsageProvider { return request } + /// True when the endpoint refused the token itself, as opposed to the account or organization. + /// + /// Matches Claude Code: every invalid or expired token gets HTTP 401 (`authentication_error`); a + /// revoked one can get 403 with "OAuth token has been revoked". Other 403s (for example an + /// organization that does not allow OAuth) keep the token. + static func isTokenRejected(status: Int, body: Data) -> Bool { + switch status { + case 401: true + case 403: String(decoding: body, as: UTF8.self).contains("OAuth token has been revoked") + default: false + } + } + /// Display name for Claude Code's `subscriptionType`. Unknown values are not shown. static func planName(_ subscriptionType: String?) -> String? { switch subscriptionType?.lowercased() { diff --git a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Resources/pt-BR.lproj/Localizable.strings b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Resources/pt-BR.lproj/Localizable.strings index be99a71..7e082e8 100644 --- a/apps/macos/TokenBarKit/Sources/TokenBarProviders/Resources/pt-BR.lproj/Localizable.strings +++ b/apps/macos/TokenBarKit/Sources/TokenBarProviders/Resources/pt-BR.lproj/Localizable.strings @@ -1,6 +1,6 @@ /* Portuguese (Brazil). Keys are the English source strings used in code. */ -"Requires Claude Code signed in on this Mac. On each refresh TokenBar reads Claude Code's sign-in from your Keychain (macOS asks for permission) and sends it only to api.anthropic.com. It is never stored, copied, or refreshed by TokenBar." = "Requer o Claude Code conectado neste Mac. A cada atualização, o TokenBar lê o login do Claude Code nas suas Chaves (o macOS pede permissão) e o envia apenas para api.anthropic.com. O TokenBar nunca o armazena, copia ou renova."; +"Requires Claude Code signed in on this Mac. TokenBar reads Claude Code's sign-in from your Keychain (macOS asks for permission) when it starts and when Claude Code renews it, keeps it in memory only while TokenBar runs, and sends it only to api.anthropic.com. It is never written to disk or refreshed by TokenBar." = "Requer o Claude Code conectado neste Mac. O TokenBar lê o login do Claude Code nas suas Chaves (o macOS pede permissão) ao iniciar e quando o Claude Code o renova, mantém-no apenas na memória enquanto está aberto e o envia apenas para api.anthropic.com. O TokenBar nunca o grava em disco nem o renova."; "TokenBar reads Claude usage from the endpoint behind Claude Code's /usage command. Anthropic does not document it for other apps: it may change or stop working at any time, and Anthropic's terms may not cover this use." = "O TokenBar lê o uso do Claude pelo endpoint usado pelo comando /usage do Claude Code. A Anthropic não o documenta para outros apps: ele pode mudar ou deixar de funcionar a qualquer momento, e os termos da Anthropic podem não cobrir este uso."; "Requires Codex signed in with ChatGPT on this Mac. On each refresh TokenBar reads Codex's sign-in from ~/.codex/auth.json and sends it only to chatgpt.com. It is never stored, copied, or refreshed by TokenBar." = "Requer o Codex conectado com o ChatGPT neste Mac. A cada atualização, o TokenBar lê o login do Codex em ~/.codex/auth.json e o envia apenas para chatgpt.com. O TokenBar nunca o armazena, copia ou renova."; "TokenBar reads Codex usage from the endpoint the Codex apps use to show your plan's limits. OpenAI does not document it for other apps: it may change or stop working at any time, and OpenAI's terms may not cover this use. It shows Codex limits, not ChatGPT message limits." = "O TokenBar lê o uso do Codex pelo endpoint que os apps do Codex usam para mostrar os limites do seu plano. A OpenAI não o documenta para outros apps: ele pode mudar ou deixar de funcionar a qualquer momento, e os termos da OpenAI podem não cobrir este uso. Mostra limites do Codex, não limites de mensagens do ChatGPT."; diff --git a/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/ClaudeCredentialCacheTests.swift b/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/ClaudeCredentialCacheTests.swift new file mode 100644 index 0000000..0255577 --- /dev/null +++ b/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/ClaudeCredentialCacheTests.swift @@ -0,0 +1,258 @@ +import Foundation +import Testing +import TokenBarCore + +@testable import TokenBarProviders + +/// How often ``ClaudeProvider`` reads Claude Code's Keychain item across refreshes. +struct ClaudeCredentialCacheTests { + let clock = TestClock(Date(timeIntervalSince1970: 1_800_000_000)) + + private func provider( + _ source: FakeCredentials, + reply: FakeHTTPClient.Reply? = nil + ) throws -> (ClaudeProvider, FakeHTTPClient) { + let http = FakeHTTPClient(try reply ?? .response(status: 200, body: Fixture.data("usage-pro"))) + return (ClaudeProvider(credentials: source, http: http, now: { [clock] in clock.now }), http) + } + + private static let rejected = FakeHTTPClient.Reply.response( + status: 401, + body: Data( + #"{"type":"error","error":{"type":"authentication_error","message":"OAuth access token is invalid."}}"#.utf8 + ) + ) + + @Test func readsTheKeychainOnFirstFetch() async throws { + let source = FakeCredentials.valid() + let (provider, http) = try provider(source) + + _ = try await provider.fetchUsage() + + #expect(source.reads == 1) + #expect(http.requests.count == 1) + } + + @Test func reusesTheSignInOnLaterFetches() async throws { + let source = FakeCredentials.valid(expiresAt: clock.now.addingTimeInterval(3600)) + let (provider, http) = try provider(source) + + for _ in 0..<3 { + _ = try await provider.fetchUsage() + clock.advance(by: 5 * 60) + } + + #expect(source.reads == 1) + #expect(http.requests.count == 3) + #expect(http.requests.allSatisfy { $0.value(forHTTPHeaderField: "Authorization") == "Bearer test-token" }) + } + + @Test func readsAgainWhenClaudeCodeWritesTheItem() async throws { + let source = FakeCredentials.valid() + let (provider, http) = try provider(source) + _ = try await provider.fetchUsage() + + source.renew() + _ = try await provider.fetchUsage() + + #expect(source.reads == 2) + #expect(http.requests.last?.value(forHTTPHeaderField: "Authorization") == "Bearer renewed-token") + } + + @Test func expiredSignInIsReadOnceThenRetriedAfterTheInterval() async throws { + let source = FakeCredentials.valid(expiresAt: clock.now.addingTimeInterval(60 * 60)) + let (provider, http) = try provider(source) + _ = try await provider.fetchUsage() + + // Expired, item unchanged: one read in case Claude Code renewed it in place. + clock.advance(by: 60 * 60) + await #expect(throws: ProviderError.unauthorized) { try await provider.fetchUsage() } + #expect(source.reads == 2) + + // Still expired: no read, no request, until the retry interval passed. + clock.advance(by: 5 * 60) + await #expect(throws: ProviderError.unauthorized) { try await provider.fetchUsage() } + #expect(source.reads == 2) + #expect(http.requests.count == 1) + + // Renewed without the modification date changing: picked up after the interval. + source.result = .success(.fake(token: "renewed-token", expiresAt: clock.now.addingTimeInterval(3600))) + clock.advance(by: ClaudeCredentialCache.retryInterval) + _ = try await provider.fetchUsage() + #expect(source.reads == 3) + #expect(http.requests.count == 2) + } + + @Test func treatsTokenCloseToExpiryAsExpired() async throws { + let source = FakeCredentials.valid(expiresAt: clock.now.addingTimeInterval(30)) + let (provider, http) = try provider(source) + + await #expect(throws: ProviderError.unauthorized) { try await provider.fetchUsage() } + #expect(http.requests.isEmpty) + } + + @Test func rejectedTokenIsNotSentAgain() async throws { + let source = FakeCredentials.valid() + let (provider, http) = try provider(source, reply: Self.rejected) + + await #expect(throws: ProviderError.unauthorized) { try await provider.fetchUsage() } + await #expect(throws: ProviderError.unauthorized) { try await provider.fetchUsage() } + #expect(source.reads == 1) + #expect(http.requests.count == 1) + + // Item rewritten with the same token: read, but still not sent. + source.version = .success(Date(timeIntervalSince1970: 42)) + await #expect(throws: ProviderError.unauthorized) { try await provider.fetchUsage() } + #expect(source.reads == 2) + #expect(http.requests.count == 1) + + // A new token recovers. + source.renew() + http.reply = .response(status: 200, body: try Fixture.data("usage-pro")) + _ = try await provider.fetchUsage() + #expect(source.reads == 3) + #expect(http.requests.count == 2) + } + + @Test func rejectedTokenRecoversAfterTheIntervalWhenTheItemLooksUnchanged() async throws { + let source = FakeCredentials.valid() + let (provider, http) = try provider(source, reply: Self.rejected) + await #expect(throws: ProviderError.unauthorized) { try await provider.fetchUsage() } + + source.result = .success(.fake(token: "renewed-token")) + http.reply = .response(status: 200, body: try Fixture.data("usage-pro")) + clock.advance(by: ClaudeCredentialCache.retryInterval) + _ = try await provider.fetchUsage() + + #expect(source.reads == 2) + #expect(http.requests.last?.value(forHTTPHeaderField: "Authorization") == "Bearer renewed-token") + } + + @Test func revoked403RejectsTheToken() async throws { + let source = FakeCredentials.valid() + let (provider, http) = try provider( + source, + reply: .response(status: 403, body: Data("OAuth token has been revoked".utf8)) + ) + await #expect(throws: ProviderError.unauthorized) { try await provider.fetchUsage() } + await #expect(throws: ProviderError.unauthorized) { try await provider.fetchUsage() } + #expect(http.requests.count == 1) + } + + @Test func other403KeepsTheToken() async throws { + let body = + #"{"type":"error","error":{"type":"permission_error","message":"OAuth authentication is currently not allowed for this organization."}}"# + let source = FakeCredentials.valid() + let (provider, http) = try provider(source, reply: .response(status: 403, body: Data(body.utf8))) + + await #expect(throws: ProviderError.unauthorized) { try await provider.fetchUsage() } + await #expect(throws: ProviderError.unauthorized) { try await provider.fetchUsage() } + #expect(source.reads == 1) + #expect(http.requests.count == 2) + } + + @Test func rejectingAnOlderTokenKeepsTheNewerOne() async throws { + let source = FakeCredentials.valid() + let cache = ClaudeCredentialCache(source: source, now: { [clock] in clock.now }) + _ = try await cache.credentials() + source.renew() + _ = try await cache.credentials() + + await cache.reject("test-token") + + #expect(try await cache.credentials().accessToken == "renewed-token") + #expect(source.reads == 2) + } + + @Test func concurrentFetchesShareOneRead() async throws { + let source = FakeCredentials.valid() + let (provider, http) = try provider(source) + + try await withThrowingTaskGroup(of: Void.self) { group in + for _ in 0..<10 { + group.addTask { _ = try await provider.fetchUsage() } + } + try await group.waitForAll() + } + + #expect(source.reads == 1) + #expect(http.requests.count == 10) + } + + @Test func signOutDropsTheCachedSignIn() async throws { + let source = FakeCredentials.valid() + let (provider, http) = try provider(source) + _ = try await provider.fetchUsage() + + source.version = .failure(.notConnected) + await #expect(throws: ProviderError.notConnected) { try await provider.fetchUsage() } + #expect(http.requests.count == 1) + + // Signed in again (possibly another account): read fresh. + source.renew() + _ = try await provider.fetchUsage() + #expect(source.reads == 2) + } + + @Test func declinedAccessIsNotCachedSoAManualRefreshCanAskAgain() async throws { + let source = FakeCredentials(result: .failure(.accessDenied)) + let (provider, http) = try provider(source) + + await #expect(throws: ProviderError.accessDenied) { try await provider.fetchUsage() } + await #expect(throws: ProviderError.accessDenied) { try await provider.fetchUsage() } + #expect(source.reads == 2) + + source.result = .success(.fake()) + _ = try await provider.fetchUsage() + #expect(http.requests.count == 1) + } + + @Test func failedReadIsRetriedOncePerInterval() async throws { + let source = FakeCredentials(result: .failure(.unknown)) + let (provider, http) = try provider(source) + + await #expect(throws: ProviderError.unknown) { try await provider.fetchUsage() } + await #expect(throws: ProviderError.unknown) { try await provider.fetchUsage() } + #expect(source.reads == 1) + + source.result = .success(.fake()) + clock.advance(by: ClaudeCredentialCache.retryInterval) + _ = try await provider.fetchUsage() + #expect(source.reads == 2) + #expect(http.requests.count == 1) + } + + @Test func unknownModificationDateReusesTheCachedSignIn() async throws { + let source = FakeCredentials(result: .success(.fake()), version: .success(nil)) + let (provider, http) = try provider(source) + + for _ in 0..<3 { _ = try await provider.fetchUsage() } + + #expect(source.reads == 1) + #expect(http.requests.count == 3) + } + + @Test func unknownModificationDateWithoutSignInReadsOncePerInterval() async throws { + let source = FakeCredentials(result: .failure(.unknown), version: .success(nil)) + let (provider, _) = try provider(source) + + await #expect(throws: ProviderError.unknown) { try await provider.fetchUsage() } + await #expect(throws: ProviderError.unknown) { try await provider.fetchUsage() } + #expect(source.reads == 1) + + // The Keychain answers again: its modification date counts as a change and is read at once. + source.result = .success(.fake()) + source.version = .success(Date(timeIntervalSince1970: 1)) + _ = try await provider.fetchUsage() + #expect(source.reads == 2) + } + + @Test func cacheLivesOnlyAsLongAsTheProvider() async throws { + let source = FakeCredentials.valid() + _ = try await provider(source).0.fetchUsage() + _ = try await provider(source).0.fetchUsage() + + // A new provider (as after relaunching the app) starts with nothing cached. + #expect(source.reads == 2) + } +} diff --git a/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/ClaudeProviderTests.swift b/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/ClaudeProviderTests.swift index 960aefb..4e0b13b 100644 --- a/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/ClaudeProviderTests.swift +++ b/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/ClaudeProviderTests.swift @@ -111,7 +111,7 @@ struct ClaudeProviderTests { @Test func sendsTokenThatIsStillValid() async throws { let (provider, http) = provider( .response(status: 200, body: try Fixture.data("usage-pro")), - credentials: .valid(expiresAt: now.addingTimeInterval(60)) + credentials: .valid(expiresAt: now.addingTimeInterval(5 * 60)) ) _ = try await provider.fetchUsage() #expect(http.requests.count == 1) diff --git a/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/Support/Fakes.swift b/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/Support/Fakes.swift index 4bc3818..aa89e80 100644 --- a/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/Support/Fakes.swift +++ b/apps/macos/TokenBarKit/Tests/TokenBarProvidersTests/Support/Fakes.swift @@ -21,15 +21,21 @@ final class FakeHTTPClient: HTTPClient { case failure(URLError.Code) } - private let reply: Reply + private let scripted: OSAllocatedUnfairLock private let recorded = OSAllocatedUnfairLock(initialState: [URLRequest]()) init(_ reply: Reply) { - self.reply = reply + scripted = OSAllocatedUnfairLock(initialState: reply) } var requests: [URLRequest] { recorded.withLock { $0 } } + /// Reply to the next requests. + var reply: Reply { + get { scripted.withLock { $0 } } + set { scripted.withLock { $0 = newValue } } + } + func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { recorded.withLock { $0.append(request) } switch reply { @@ -47,19 +53,79 @@ final class FakeHTTPClient: HTTPClient { } } -struct FakeCredentials: ClaudeCredentialSource { - var result: Result +/// Claude Code sign-in source with a scripted result and modification date. Counts Keychain reads. +final class FakeCredentials: ClaudeCredentialSource { + private struct State { + var result: Result + var version: Result + var reads = 0 + } + + private let state: OSAllocatedUnfairLock + + init( + result: Result, + version: Result = .success(Date(timeIntervalSince1970: 0)) + ) { + state = OSAllocatedUnfairLock(initialState: State(result: result, version: version)) + } static func valid(expiresAt: Date? = nil, plan: String? = "pro") -> FakeCredentials { - FakeCredentials( - result: .success( - ClaudeCodeCredentials(accessToken: "test-token", expiresAt: expiresAt, subscriptionType: plan) - ) - ) + FakeCredentials(result: .success(.fake(expiresAt: expiresAt, plan: plan))) + } + + /// Data reads so far: the reads that can show a macOS permission prompt. + var reads: Int { state.withLock { $0.reads } } + + var result: Result { + get { state.withLock { $0.result } } + set { state.withLock { $0.result = newValue } } + } + + var version: Result { + get { state.withLock { $0.version } } + set { state.withLock { $0.version = newValue } } + } + + /// Simulates Claude Code writing a new sign-in. + func renew(token: String = "renewed-token", expiresAt: Date? = nil) { + state.withLock { + $0.result = .success(.fake(token: token, expiresAt: expiresAt)) + let current = (try? $0.version.get()) ?? nil + $0.version = .success((current ?? Date(timeIntervalSince1970: 0)).addingTimeInterval(1)) + } } func credentials() throws -> ClaudeCodeCredentials { - try result.get() + try state.withLock { + $0.reads += 1 + return try $0.result.get() + } + } + + func modificationDate() throws -> Date? { + try version.get() + } +} + +/// A clock that tests move forward. +final class TestClock: Sendable { + private let current: OSAllocatedUnfairLock + + init(_ start: Date) { + current = OSAllocatedUnfairLock(initialState: start) + } + + var now: Date { current.withLock { $0 } } + + func advance(by seconds: TimeInterval) { + current.withLock { $0 = $0.addingTimeInterval(seconds) } + } +} + +extension ClaudeCodeCredentials { + static func fake(token: String = "test-token", expiresAt: Date? = nil, plan: String? = "pro") -> Self { + ClaudeCodeCredentials(accessToken: token, expiresAt: expiresAt, subscriptionType: plan) } } diff --git a/docs/architecture.md b/docs/architecture.md index 357cabe..1a3e9b4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -180,8 +180,10 @@ builds, and the popover labels demo data with a "Demo" badge. ## Security boundaries -- Third-party credentials (Claude Code, Codex) are **read at fetch time** and never - copied, refreshed, or persisted by TokenBar. +- Third-party credentials (Claude Code, Codex) are read from their owner's storage and never + refreshed or persisted by TokenBar. Codex is read at fetch time; Claude Code's token is kept + in memory (`ClaudeCredentialCache`) and read again only when its Keychain item changes or the + token expires or is rejected, so macOS does not ask on every refresh. - Credentials TokenBar owns go through `CredentialStore`: generic password items in the login Keychain, scoped to TokenBar's service, `AfterFirstUnlockThisDeviceOnly`, never synced to iCloud. Nothing sensitive goes in `UserDefaults`, files, or logs. diff --git a/docs/providers.md b/docs/providers.md index 2de3ced..736116d 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -37,20 +37,21 @@ Verified against live responses on 2026-10-22 (Claude Code 2.1.116, Pro plan). | Question | Answer | |---|---| | Where does authentication originate? | Claude Code's own OAuth sign-in (`claude auth login`). TokenBar has no sign-in flow. | -| Does TokenBar read the Keychain? | Yes, **one item**: generic password, service `Claude Code-credentials`, owned by Claude Code. Read-only, with `SecItemCopyMatching`, on every refresh while the provider is enabled. Never before the user enables the provider. | +| Does TokenBar read the Keychain? | Yes, **one item**: generic password, service `Claude Code-credentials`, owned by Claude Code. Read-only, with `SecItemCopyMatching`, while the provider is enabled; never before the user enables it. Each refresh reads only the item's **attributes** (modification date), which does not touch the secret and shows no prompt (checked with an ad-hoc-signed binary outside the item's access list). The item's **data** is read when nothing is cached, when the modification date changed (Claude Code renewed the token, signed in to another account), or when the cached token expired or was rejected — then at most once every 15 minutes, so a token renewed without a new modification date is still picked up. See `ClaudeCredentialCache`. | | What exactly is read? | The item holds JSON with an access token, refresh token, expiries, scopes, plan, and organization ID. TokenBar decodes **only** `claudeAiOauth.accessToken`, `expiresAt`, and `subscriptionType` (shown as the plan badge). The refresh token and organization ID are never decoded. | -| Do credentials enter TokenBar's memory? | Yes, the access token, for the duration of one refresh: it is parsed, put in one request header to `api.anthropic.com`, and released. Its `description` is redacted so it cannot leak through logging or string interpolation. | -| Is anything persisted? | No. No copy in TokenBar's Keychain, `UserDefaults`, or files. Requests use an ephemeral `URLSession` with no URL cache, cookies, or credential storage, so the response never reaches the disk either. | +| Do credentials enter TokenBar's memory? | Yes, the access token, plan, and expiry, kept in memory while TokenBar runs so the Keychain is not read on every refresh. The token is only put in one request header to `api.anthropic.com`. Its `description` is redacted so it cannot leak through logging or string interpolation. The memory copy is gone when TokenBar quits. | +| Is anything persisted? | No. The in-memory copy is never written anywhere: no copy in TokenBar's Keychain, `UserDefaults`, or files. Requests use an ephemeral `URLSession` with no URL cache, cookies, or credential storage, so the response never reaches the disk either. | | Who grants access? | macOS. The first read shows "TokenBar wants to use your confidential information stored in 'Claude Code-credentials'". *Deny* → TokenBar shows "Access was not allowed" and does not ask again until the user refreshes manually. *Always Allow* is tied to TokenBar's code signature: Developer ID builds keep it across updates; ad-hoc local builds are asked again after each rebuild. | -| Claude Code logged out? | The item is gone → "Not connected". Old numbers are cleared. | -| Credentials expired? | TokenBar checks `expiresAt` and does **not** call the endpoint with an expired token; it shows "Sign-in expired". TokenBar never refreshes the token (that would rotate Claude Code's refresh token and could sign it out). Claude Code renews it the next time it runs, and TokenBar picks up the new token on its next refresh. | -| Credentials changed? | Claude Code updates the item in place (creation date unchanged), so the user's Keychain decision survives; the new token is read on the next refresh. | +| Claude Code logged out? | The item is gone (seen by the attribute read) → the in-memory copy is dropped, "Not connected". Old numbers are cleared. | +| Credentials expired? | TokenBar checks `expiresAt` (with a 60-second margin) and does **not** call the endpoint with an expired token; it shows "Sign-in expired". TokenBar never refreshes the token (that would rotate Claude Code's refresh token and could sign it out). Claude Code renews it the next time it runs, and TokenBar picks up the new token on its next refresh (or within 15 minutes if the item's modification date did not change). | +| Token rejected? | Checked against the live endpoint and Claude Code 2.1.116 (2026-10-27): an invalid, expired, or missing token gets **HTTP 401** `authentication_error`. Claude Code also treats **403** with "OAuth token has been revoked" as a bad token; other 401/403 bodies cover organization policy ("OAuth authentication is currently not allowed for this organization"). TokenBar drops the cached token on 401 or a revoked 403 and never sends that token again; other 403s keep it. All show "Sign-in expired". A real 403 has not been observed. | +| Credentials changed? | Claude Code updates the item in place (creation date unchanged), so the user's Keychain decision survives; its modification date changes, so the new token is read on the next refresh. | ### Least invasive option | Option | Verdict | |---|---| -| **Read Claude Code's Keychain item at fetch time** | **Chosen.** No copy, no refresh, user-visible macOS consent, always current. | +| **Read Claude Code's Keychain item, keep the token in memory** | **Chosen.** No persisted copy, no refresh, user-visible macOS consent, current within one refresh of a renewal. Reading the item on every refresh (the first version) could show the prompt on every refresh for builds without *Always Allow*. | | Claude Code `statusLine` hook (its input JSON has `rate_limits.five_hour/seven_day`) | Zero credential access, but requires replacing the user's status line command, only updates while Claude Code is running (claude.ai usage is missed), and lacks model-specific limits. Possible future fallback. | | Ask the user to paste a `claude.ai` session cookie | Rejected: grants full account access and would have to be stored. | | Read rate-limit headers from a real API request | Rejected: costs usage. | @@ -99,7 +100,7 @@ and against the open-source Codex client ([openai/codex](https://github.com/open | Where is it stored? | By default `$CODEX_HOME/auth.json` (`~/.codex/auth.json`), mode `0600`, owned by the user. Codex can instead use the Keychain (`cli_auth_credentials_store = "keyring"` or `"auto"`: service `Codex Auth`, account `cli|`). | | What does TokenBar read? | The file only, read-only, on every refresh while the provider is enabled. Never before the user enables it. It holds JSON with `auth_mode`, an optional API key, `tokens` (`id_token`, `access_token`, `refresh_token`, `account_id`) and `last_refresh`. TokenBar decodes **only** `tokens.access_token` and `tokens.account_id`. The refresh token, ID token (email, name) and API key are never decoded. | | Do credentials enter TokenBar's memory? | Yes, the access token and account ID, for the duration of one refresh: put in two request headers to `chatgpt.com` and released. Their `description` is redacted. | -| Is anything persisted? | No. No copy in TokenBar's Keychain, `UserDefaults`, or files. Requests use the ephemeral provider session (no cache, cookies, or credential storage). | +| Is anything persisted? | No. The in-memory copy is never written anywhere: no copy in TokenBar's Keychain, `UserDefaults`, or files. Requests use the ephemeral provider session (no cache, cookies, or credential storage). | | Who grants access? | The user, by enabling the provider. Unlike Keychain items, a file in the user's home folder has no per-app macOS prompt (TokenBar is not sandboxed). An unreadable file is reported as "Access was not allowed". | | Codex logged out? | `codex logout` deletes `auth.json` → "Not connected". Signed in with an API key instead of ChatGPT (no `tokens`) → "Not connected": API-key usage has no plan limits. | | Keychain storage mode? | **Not supported.** With `keyring` (or `auto` when Codex chose the Keychain) there is no file → "Not connected". The item's format has not been verified against a live capture, so TokenBar does not read it. |