How CodexBar Imports Browser Cookies for Authentication

CodexBar automatically extracts authentication cookies from Chrome, Chromium, Edge, or Safari's SQLite databases and stores them in the macOS keychain to authenticate LLM provider requests without requiring manual cookie input.

CodexBar is a macOS application that interfaces with various LLM providers including OpenAI and Claude. Instead of asking users to paste raw cookie strings, the app implements an automated browser cookie import system that reads session tokens directly from the user's web browsers when authentication errors occur.

The Three-Component Architecture

CodexBar's cookie import system relies on three coordinated components that handle detection, storage, and orchestration.

BrowserDetection

The BrowserDetection class scans the file system to locate installed browsers and determine the path to each browser's cookie SQLite database. It maintains a preference order of Chrome first, followed by Chromium-based browsers, Edge, and finally Safari. The detector caches results for the lifetime of the process using the BrowserDetection(cacheTTL:) initializer.

In Sources/CodexBar/BrowserDetection.swift, the implementation reads standard macOS directories such as ~/Library/Application Support/Google/Chrome/Default/Cookies to build an ordered list of available browsers.

CookieHeaderCache and KeychainCookieHeaderStore

The KeychainCookieHeaderStore class persists the final Cookie: header string in the macOS keychain so credentials survive application restarts, while CookieHeaderCache provides an in-memory layer to avoid repeated keychain hits.

According to Sources/CodexBar/CookieHeaderStore.swift, the store offers loadCookieHeader() to read a generic-password entry identified by the provider name, and storeCookieHeader(_:) to write the header after normalization by CookieHeaderNormalizer.

UsageStore Extensions

Provider-specific extensions such as UsageStore+OpenAIWeb orchestrate the import workflow. When a fetcher receives a login-required or account-mismatch error, the extension triggers the browser detection and cookie extraction logic, then retries the request once with the new credentials.

The source file Sources/CodexBar/UsageStore+OpenAIWeb.swift contains the trigger logic: "On login-required … import cookies from the configured browser order and retry once."

Step-by-Step Import Process

When CodexBar needs to authenticate a web endpoint request, it executes the following sequence:

  1. Detect browsers – BrowserDetection scans the file system and builds an ordered array [Browser] of viable cookie sources.

  2. Select the first viable profile – The system iterates through the list sequentially, attempting to open each browser's cookie database until it finds an accessible SQLite file.

  3. Open the SQLite cookie store – A read-only connection is established to the Cookies database file. macOS encrypts Safari's cookies, but Chrome and Chromium use a format readable by the system SQLite driver.

  4. Query the cookie table – The app executes SQL similar to the following query found in Sources/CodexBarCore/BrowserCookieImporter.swift:

    SELECT name, value FROM cookies
    WHERE host_key LIKE '%openai.com%' AND (name = 'session' OR name = 'auth')
    ORDER BY expires_utc DESC LIMIT 1;
  5. Build the header – The retrieved name=value pair is formatted into a header string and passed through CookieHeaderNormalizer for validation:

    let header = "Cookie: \(name)=\(value)"
  6. Persist credentials – The normalized header is saved via KeychainCookieHeaderStore.storeCookieHeader(header) and cached in CookieHeaderCache.

  7. Retry the request – The original network fetcher (such as OpenAIChatFetcher or ClaudeUsageFetcher) re-executes the HTTP request with the freshly imported Cookie: header.

If no browser contains a matching cookie, the import silently fails and the UI displays the message "Sign in to chatgpt.com, then refresh OpenAI cookies" as referenced in Tests/CodexBarTests/StatusMenuNativeSectionSpacingTests.swift.

Implementation Code Examples

Detecting Available Browsers

The following pattern appears throughout the test suite, such as in Tests/CodexBarTests/WindsurfWebFetcherTests.swift:

let detection = BrowserDetection(cacheTTL: 0)          // cache disabled for tests
let browsers = detection.availableBrowsers()          // → [.chrome, .chromium, .edge, .safari]

Importing and Storing OpenAI Cookies

This simplified implementation demonstrates the core extraction logic:

func importOpenAICookie() throws -> String? {
    for browser in detection.availableBrowsers() {
        guard let db = try? browser.openCookieDatabase() else { continue }
        if let (name, value) = try db.fetchOpenAICookie() {
            let header = "Cookie: \(name)=\(value)"
            try KeychainCookieHeaderStore(account: "openai", promptKind: .openAI).storeCookieHeader(header)
            return header
        }
    }
    return nil      // no matching cookie found
}

Retrieving Stored Headers for Requests

Fetchers load the stored header before making authenticated requests:

let store = KeychainCookieHeaderStore(account: "openai", promptKind: .openAI)
let header = try store.loadCookieHeader()

var request = URLRequest(url: endpoint)
if let h = header { 
    request.addValue(h, forHTTPHeaderField: "Cookie") 
}

Key Source Files

The cookie import functionality spans the following files in the steipete/CodexBar repository:

Summary

  • BrowserDetection locates Chrome, Chromium, Edge, and Safari profiles by scanning macOS Library directories.
  • KeychainCookieHeaderStore persists the Cookie: header in the macOS keychain with an in-memory cache for performance.
  • UsageStore extensions trigger automatic imports when network requests return authentication errors, retrying once with the new credentials.
  • The system queries browser SQLite databases using provider-specific SQL to extract session tokens like session or auth.
  • All cookie handling operates automatically without manual user input, falling back to UI prompts only when no valid cookies are found.

Frequently Asked Questions

CodexBar supports Chrome, Chromium-based browsers, Microsoft Edge, and Safari. The BrowserDetection class prioritizes Chrome first, then falls back through Chromium variants, Edge, and finally Safari if earlier options fail or lack valid cookies.

While Safari encrypts its cookie storage on macOS, CodexBar primarily targets Chrome and Chromium browsers which use unencrypted SQLite formats readable by the system SQLite driver. The BrowserDetection class includes Safari in its fallback chain, but the implementation focuses on the accessible Chrome/Chromium format for reliable automation.

Where does CodexBar store imported cookies between app restarts?

Imported cookie headers are stored in the macOS keychain using KeychainCookieHeaderStore, identified by the provider name (e.g., "openai"). An in-memory CookieHeaderCache prevents redundant keychain queries during active sessions, while the keychain ensures persistence across application restarts.

The automatic import triggers when fetchers receive login-required or account-mismatch errors. If automatic import fails, the UI displays "Sign in to chatgpt.com, then refresh OpenAI cookies" as implemented in the status menu tests, prompting users to authenticate via browser before the next automatic import attempt.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →