Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

use keychain on mac and file storage elsewhere

Raine Virtab5dde60fda50
diff --git a/README.md b/README.md
index b726642..cb6e1b0 100644
--- a/README.md
+++ b/README.md
@@ -62,9 +62,10 @@ Or, on a headless machine (device code flow):
claude-codex-proxy auth device
```
-Either command prints a URL. Sign in with your **ChatGPT Plus/Pro account**. The
-access and refresh tokens are stored in the system credential store (macOS
-Keychain or Linux Secret Service).
+Either command prints a URL. Sign in with your **ChatGPT Plus/Pro account**. On
+macOS, access and refresh tokens are stored in Keychain. On other platforms,
+they are stored at `~/.config/claude-codex-proxy/auth.json` with 0600
+permissions.
Verify it stuck:
@@ -122,7 +123,7 @@ sequenceDiagram
participant AUTH as auth.openai.com
participant CGX as chatgpt.com/<br/>backend-api/codex
- Note over P,AUTH: One-time: PKCE or device OAuth<br/>tokens cached at<br/>~/.config/claude-codex-proxy/auth.json
+ Note over P,AUTH: One-time: PKCE or device OAuth<br/>tokens cached in Keychain on macOS<br/>or at ~/.config/claude-codex-proxy/auth.json elsewhere
CC->>P: POST /v1/messages (Anthropic shape, stream: true)
@@ -166,7 +167,7 @@ Key decisions:
| [`auth login`](#auth-login) | Browser OAuth (PKCE) |
| [`auth device`](#auth-device) | Device-code OAuth (headless) |
| [`auth status`](#auth-status) | Show account ID and token expiry |
-| [`auth logout`](#auth-logout) | Delete the stored auth file |
+| [`auth logout`](#auth-logout) | Delete stored auth credentials |
---
@@ -193,8 +194,8 @@ stored a token.
Runs the PKCE browser flow against `auth.openai.com` using the Codex CLI's
client ID. Prints a URL, opens a local callback listener on port 1455, waits for
the browser to redirect back, and stores the resulting access / refresh tokens
-at `~/.config/claude-codex-proxy/auth.json` (mode 0600). The process exits
-automatically once the tokens are saved.
+in Keychain on macOS or at `~/.config/claude-codex-proxy/auth.json` (mode 0600)
+on other platforms. The process exits automatically once the tokens are saved.
```sh
claude-codex-proxy auth login
@@ -234,9 +235,11 @@ Example output:
```
Account: 79342a5e-57b7-44ea-bfdc-a83ba070dad6
Expires: 2026-04-28T16:46:04.827Z (in 863946s)
-File: /Users/you/.config/claude-codex-proxy/auth.json
+Storage: macOS Keychain
```
+On non-macOS platforms, the storage line shows the auth file path instead.
+
The proxy refreshes the access token 5 minutes before expiry with a
single-flight guard, so concurrent requests never trigger stampedes of refresh
calls.
@@ -245,8 +248,9 @@ calls.
### `auth logout`
-Removes `~/.config/claude-codex-proxy/auth.json`. No server call is needed; the
-refresh token just becomes dead.
+Removes stored auth credentials. On macOS this deletes the Keychain entry; on
+other platforms it removes `~/.config/claude-codex-proxy/auth.json`. No server
+call is needed; the refresh token just becomes dead.
```sh
claude-codex-proxy auth logout
@@ -279,7 +283,10 @@ Settings are environment variables on the proxy process, not a config file.
### Files
-- `~/.config/claude-codex-proxy/auth.json` — OAuth tokens, 0600
+- `~/.config/claude-codex-proxy/auth.json` — OAuth tokens on non-macOS platforms,
+ 0600
+- macOS Keychain entry `claude-codex-proxy` / account `auth` — OAuth tokens on
+ macOS
- `$XDG_STATE_HOME/claude-codex-proxy/proxy.log` — JSON-lines log, rotated at 20
MiB. Secrets (`authorization`, `access`, `refresh`, `id_token`,
`ChatGPT-Account-Id`, …) are redacted before write.
diff --git a/src/auth/token-store.ts b/src/auth/token-store.ts
index 4c04035..b3b6ed7 100644
--- a/src/auth/token-store.ts
+++ b/src/auth/token-store.ts
@@ -1,3 +1,7 @@
+import { mkdir, readFile, writeFile, chmod, unlink, rename } from "node:fs/promises"
+import { dirname, join } from "node:path"
+import { homedir } from "node:os"
+
export interface StoredAuth {
access: string
refresh: string
@@ -5,50 +9,33 @@ export interface StoredAuth {
accountId?: string
}
+const DIR = join(homedir(), ".config", "claude-codex-proxy")
+const FILE = join(DIR, "auth.json")
const KEYCHAIN_SERVICE = "claude-codex-proxy"
const KEYCHAIN_ACCOUNT = "auth"
-const SECRET_TOOL_LABEL = "claude-codex-proxy auth"
-const SECRET_TOOL_ATTRIBUTES = ["service", KEYCHAIN_SERVICE, "account", KEYCHAIN_ACCOUNT] as const
export async function loadAuth(): Promise<StoredAuth | undefined> {
- const raw = await loadStoredValue()
- if (!raw) return undefined
- return JSON.parse(raw) as StoredAuth
-}
-
-export async function saveAuth(auth: StoredAuth): Promise<void> {
- await saveStoredValue(JSON.stringify(auth))
-}
-
-export async function clearAuth(): Promise<void> {
- await clearStoredValue()
-}
-
-export function authPath(): string {
- if (process.platform === "darwin") return "macOS Keychain"
- if (process.platform === "linux") return "Linux Secret Service"
- return "unsupported auth storage"
-}
-
-async function loadStoredValue(): Promise<string | undefined> {
if (process.platform === "darwin") {
- return readKeychain().catch((err: Error & { code?: number }) => {
+ const raw = await readKeychain().catch((err: Error & { code?: number }) => {
if (err.code === 44) return undefined
throw err
})
+ if (!raw) return undefined
+ return JSON.parse(raw) as StoredAuth
}
- if (process.platform === "linux") {
- return readSecret().catch((err: Error & { code?: number }) => {
- if (err.code === 1) return undefined
- throw err
- })
+
+ try {
+ const raw = await readFile(FILE, "utf8")
+ return JSON.parse(raw) as StoredAuth
+ } catch (err: any) {
+ if (err?.code === "ENOENT") return undefined
+ throw err
}
- throw new Error("Auth storage is only supported on macOS and Linux")
}
-async function saveStoredValue(value: string): Promise<void> {
+export async function saveAuth(auth: StoredAuth): Promise<void> {
if (process.platform === "darwin") {
- await runCommand("security", [
+ await runSecurity([
"add-generic-password",
"-U",
"-a",
@@ -56,63 +43,60 @@ async function saveStoredValue(value: string): Promise<void> {
"-s",
KEYCHAIN_SERVICE,
"-w",
- value,
+ JSON.stringify(auth),
])
return
}
- if (process.platform === "linux") {
- await runCommand("secret-tool", ["store", "--label", SECRET_TOOL_LABEL, ...SECRET_TOOL_ATTRIBUTES], value)
- return
+
+ await mkdir(dirname(FILE), { recursive: true })
+ const tmp = `${FILE}.${process.pid}.${Date.now()}.tmp`
+ await writeFile(tmp, JSON.stringify(auth, null, 2), { encoding: "utf8", mode: 0o600 })
+ try {
+ await chmod(tmp, 0o600)
+ } catch {
+ // best-effort; mode in writeFile options usually suffices
}
- throw new Error("Auth storage is only supported on macOS and Linux")
+ await rename(tmp, FILE)
}
-async function clearStoredValue(): Promise<void> {
+export async function clearAuth(): Promise<void> {
if (process.platform === "darwin") {
- await runCommand("security", ["delete-generic-password", "-a", KEYCHAIN_ACCOUNT, "-s", KEYCHAIN_SERVICE]).catch(
+ await runSecurity(["delete-generic-password", "-a", KEYCHAIN_ACCOUNT, "-s", KEYCHAIN_SERVICE]).catch(
(err: Error & { code?: number }) => {
if (err.code !== 44) throw err
},
)
return
}
- if (process.platform === "linux") {
- await runCommand("secret-tool", ["clear", ...SECRET_TOOL_ATTRIBUTES]).catch((err: Error & { code?: number }) => {
- if (err.code !== 1) throw err
- })
- return
+
+ try {
+ await unlink(FILE)
+ } catch (err: any) {
+ if (err?.code !== "ENOENT") throw err
}
- throw new Error("Auth storage is only supported on macOS and Linux")
}
-async function readKeychain(): Promise<string> {
- const { stdout } = await runCommand("security", ["find-generic-password", "-w", "-a", KEYCHAIN_ACCOUNT, "-s", KEYCHAIN_SERVICE])
- return stdout.trim()
+export function authPath(): string {
+ return process.platform === "darwin" ? "macOS Keychain" : FILE
}
-async function readSecret(): Promise<string> {
- const { stdout } = await runCommand("secret-tool", ["lookup", ...SECRET_TOOL_ATTRIBUTES])
+async function readKeychain(): Promise<string> {
+ const { stdout } = await runSecurity(["find-generic-password", "-w", "-a", KEYCHAIN_ACCOUNT, "-s", KEYCHAIN_SERVICE])
return stdout.trim()
}
-async function runCommand(command: string, args: string[], stdin?: string): Promise<{ stdout: string; stderr: string }> {
- const proc = Bun.spawn([command, ...args], {
- stdin: stdin === undefined ? "ignore" : "pipe",
+async function runSecurity(args: string[]): Promise<{ stdout: string; stderr: string }> {
+ const proc = Bun.spawn(["security", ...args], {
stdout: "pipe",
stderr: "pipe",
})
- if (stdin !== undefined && proc.stdin) {
- proc.stdin.write(stdin)
- proc.stdin.end()
- }
const [stdout, stderr, exitCode] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
])
if (exitCode !== 0) {
- const message = stderr.trim() || stdout.trim() || `${command} exited with ${exitCode}`
- const err = new Error(message) as Error & { code?: number }
+ const err = new Error(stderr.trim() || `security exited with ${exitCode}`) as Error & { code?: number }
err.code = exitCode
throw err
}