Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.

Expand Down
7 changes: 4 additions & 3 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
}
}
Original file line number Diff line number Diff line change
@@ -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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -28,17 +29,18 @@ 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
)
)

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")
Expand All @@ -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
}
Expand All @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
@@ -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.";
Loading
Loading