Skip to content

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

Rust

share provider auth lifecycle

Raine Virtae5345a2185f4
diff --git a/src/providers/codex/auth/manager.ts b/src/providers/codex/auth/manager.ts
index d45c19d..82c7b0f 100644
--- a/src/providers/codex/auth/manager.ts
+++ b/src/providers/codex/auth/manager.ts
@@ -1,52 +1,19 @@
import { CLIENT_ID, ISSUER, REFRESH_MARGIN_MS } from "./constants.ts";
import { extractAccountId, type TokenResponse } from "./jwt.ts";
import { loadAuth, saveAuth, type StoredAuth } from "./token-store.ts";
+import { createAuthLifecycle, validateTokenResponse } from "../../shared/auth/manager.ts";
-function validateTokenResponse(t: unknown): asserts t is TokenResponse {
- if (!t || typeof t !== "object") throw new Error("Invalid token response: not an object");
- const o = t as Record<string, unknown>;
- if (typeof o.access_token !== "string" || !o.access_token)
- throw new Error("Invalid token response: missing access_token");
- if (typeof o.refresh_token !== "string" || !o.refresh_token)
- throw new Error("Invalid token response: missing refresh_token");
- if (
- o.expires_in !== undefined &&
- (typeof o.expires_in !== "number" || !Number.isFinite(o.expires_in) || o.expires_in <= 0)
- )
- throw new Error("Invalid token response: bad expires_in");
-}
+const lifecycle = createAuthLifecycle<StoredAuth>({
+ loadAuth,
+ loginRequiredMessage: "Not authenticated. Run: claude-code-proxy codex auth login",
+ forceRefreshUnauthenticatedMessage: "Not authenticated",
+ refreshMarginMs: REFRESH_MARGIN_MS,
+ refreshNow,
+});
-let cached: StoredAuth | undefined;
-let inflight: Promise<StoredAuth> | undefined;
-
-export async function getAuth(): Promise<StoredAuth> {
- if (!cached) {
- const stored = await loadAuth();
- if (!stored) throw new Error("Not authenticated. Run: claude-code-proxy codex auth login");
- cached = stored;
- }
- if (cached.expires - REFRESH_MARGIN_MS > Date.now()) {
- return cached;
- }
- if (inflight) return inflight;
- inflight = refreshNow(cached).finally(() => {
- inflight = undefined;
- });
- return inflight;
-}
-
-export async function forceRefresh(): Promise<StoredAuth> {
- if (!cached) {
- const stored = await loadAuth();
- if (!stored) throw new Error("Not authenticated");
- cached = stored;
- }
- if (inflight) return inflight;
- inflight = refreshNow(cached).finally(() => {
- inflight = undefined;
- });
- return inflight;
-}
+export const getAuth = lifecycle.getAuth;
+export const forceRefresh = lifecycle.forceRefresh;
+export const resetCache = lifecycle.resetCache;
async function refreshNow(current: StoredAuth): Promise<StoredAuth> {
const resp = await fetch(`${ISSUER}/oauth/token`, {
@@ -69,7 +36,7 @@ async function refreshNow(current: StoredAuth): Promise<StoredAuth> {
accountId,
};
await saveAuth(next);
- cached = next;
+ lifecycle.setCached(next);
return next;
}
@@ -82,10 +49,6 @@ export async function persistInitialTokens(tokens: TokenResponse): Promise<Store
accountId: extractAccountId(tokens),
};
await saveAuth(auth);
- cached = auth;
+ lifecycle.setCached(auth);
return auth;
}
-
-export function resetCache(): void {
- cached = undefined;
-}
diff --git a/src/providers/codex/auth/token-store.ts b/src/providers/codex/auth/token-store.ts
index 71fa221..07beb26 100644
--- a/src/providers/codex/auth/token-store.ts
+++ b/src/providers/codex/auth/token-store.ts
@@ -1,7 +1,6 @@
-import { mkdir, readFile, writeFile, unlink, rename } from "node:fs/promises";
-import { dirname, join } from "node:path";
-import { keychainGet, keychainSet, keychainDelete } from "../../../keychain.ts";
+import { join } from "node:path";
import { codexAuthFile, legacyConfigDir } from "../../../paths.ts";
+import { createAuthStore } from "../../shared/auth/token-store.ts";
export interface StoredAuth {
access: string;
@@ -10,68 +9,13 @@ export interface StoredAuth {
accountId?: string;
}
-function file(): string {
- return codexAuthFile();
-}
-function legacyFile(): string {
- return join(legacyConfigDir(), "codex", "auth.json");
-}
-const KEYCHAIN_SERVICE = "claude-code-proxy.codex";
-const KEYCHAIN_ACCOUNT = "auth";
-
-export async function loadAuth(): Promise<StoredAuth | undefined> {
- if (process.platform === "darwin") {
- const raw = keychainGet(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);
- if (!raw) return undefined;
- return JSON.parse(raw) as StoredAuth;
- }
-
- const primary = file();
- try {
- const raw = await readFile(primary, "utf8");
- return JSON.parse(raw) as StoredAuth;
- } catch (err: any) {
- if (err?.code !== "ENOENT") throw err;
- }
- const legacy = legacyFile();
- if (legacy === primary) return undefined;
- try {
- const raw = await readFile(legacy, "utf8");
- return JSON.parse(raw) as StoredAuth;
- } catch (err: any) {
- if (err?.code === "ENOENT") return undefined;
- throw err;
- }
-}
-
-export async function saveAuth(auth: StoredAuth): Promise<void> {
- if (process.platform === "darwin") {
- keychainSet(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT, JSON.stringify(auth));
- return;
- }
+const store = createAuthStore<StoredAuth>({
+ file: codexAuthFile,
+ legacyFile: () => join(legacyConfigDir(), "codex", "auth.json"),
+ keychainService: "claude-code-proxy.codex",
+});
- const path = file();
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
- const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
- await writeFile(tmp, JSON.stringify(auth, null, 2), { encoding: "utf8", mode: 0o600 });
- await rename(tmp, path);
-}
-
-export async function clearAuth(): Promise<void> {
- if (process.platform === "darwin") {
- keychainDelete(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);
- return;
- }
-
- for (const path of [file(), legacyFile()]) {
- try {
- await unlink(path);
- } catch (err: any) {
- if (err?.code !== "ENOENT") throw err;
- }
- }
-}
-
-export function authPath(): string {
- return process.platform === "darwin" ? "macOS Keychain" : file();
-}
+export const loadAuth = store.loadAuth;
+export const saveAuth = store.saveAuth;
+export const clearAuth = store.clearAuth;
+export const authPath = store.authPath;
diff --git a/src/providers/kimi/auth/manager.ts b/src/providers/kimi/auth/manager.ts
index c65025f..811962f 100644
--- a/src/providers/kimi/auth/manager.ts
+++ b/src/providers/kimi/auth/manager.ts
@@ -3,6 +3,7 @@ import { commonHeaders } from "./headers.ts";
import { extractUserId } from "./jwt.ts";
import type { TokenResponse } from "./login.ts";
import { clearAuth, loadAuth, saveAuth, type StoredAuth } from "./token-store.ts";
+import { createAuthLifecycle, validateTokenResponse } from "../../shared/auth/manager.ts";
import { createLogger } from "../../../log.ts";
const log = createLogger("kimi.auth");
@@ -10,22 +11,17 @@ const log = createLogger("kimi.auth");
const RETRYABLE_STATUSES = new Set([429, 500, 502, 503, 504]);
const MAX_REFRESH_ATTEMPTS = 3;
-function validateTokenResponse(t: unknown): asserts t is TokenResponse {
- if (!t || typeof t !== "object") throw new Error("Invalid token response: not an object");
- const o = t as Record<string, unknown>;
- if (typeof o.access_token !== "string" || !o.access_token)
- throw new Error("Invalid token response: missing access_token");
- if (typeof o.refresh_token !== "string" || !o.refresh_token)
- throw new Error("Invalid token response: missing refresh_token");
- if (
- o.expires_in !== undefined &&
- (typeof o.expires_in !== "number" || !Number.isFinite(o.expires_in) || o.expires_in <= 0)
- )
- throw new Error("Invalid token response: bad expires_in");
-}
+const lifecycle = createAuthLifecycle<StoredAuth>({
+ loadAuth,
+ loginRequiredMessage: "Not authenticated. Run: claude-code-proxy kimi auth login",
+ forceRefreshUnauthenticatedMessage: "Not authenticated",
+ refreshMarginMs: REFRESH_MARGIN_MS,
+ refreshNow,
+});
-let cached: StoredAuth | undefined;
-let inflight: Promise<StoredAuth> | undefined;
+export const getAuth = lifecycle.getAuth;
+export const forceRefresh = lifecycle.forceRefresh;
+export const resetCache = lifecycle.resetCache;
export class KimiAuthUnauthorizedError extends Error {
constructor(message: string) {
@@ -34,47 +30,14 @@ export class KimiAuthUnauthorizedError extends Error {
}
}
-export async function getAuth(): Promise<StoredAuth> {
- if (!cached) {
- const stored = await loadAuth();
- if (!stored) throw new Error("Not authenticated. Run: claude-code-proxy kimi auth login");
- cached = stored;
- }
- if (cached.expires - REFRESH_MARGIN_MS > Date.now()) {
- return cached;
- }
- if (inflight) return inflight;
- inflight = refreshNow(cached).finally(() => {
- inflight = undefined;
- });
- return inflight;
-}
-
-export async function forceRefresh(): Promise<StoredAuth> {
- if (!cached) {
- const stored = await loadAuth();
- if (!stored) throw new Error("Not authenticated");
- cached = stored;
- }
- if (inflight) return inflight;
- inflight = refreshNow(cached).finally(() => {
- inflight = undefined;
- });
- return inflight;
-}
-
export async function persistInitialTokens(tokens: TokenResponse): Promise<StoredAuth> {
validateTokenResponse(tokens);
const auth = tokensToStored(tokens);
await saveAuth(auth);
- cached = auth;
+ lifecycle.setCached(auth);
return auth;
}
-export function resetCache(): void {
- cached = undefined;
-}
-
function tokensToStored(tokens: TokenResponse): StoredAuth {
return {
access: tokens.access_token,
@@ -110,21 +73,20 @@ async function refreshNow(current: StoredAuth): Promise<StoredAuth> {
}
if (resp.status === 200) {
- const tokens = await resp.json();
- validateTokenResponse(tokens);
+ const tokens: unknown = await resp.json();
+ validateTokenResponse<TokenResponse>(tokens);
const next: StoredAuth = {
...tokensToStored(tokens),
refresh: tokens.refresh_token || current.refresh,
userId: extractUserId(tokens.access_token) || current.userId,
};
await saveAuth(next);
- cached = next;
+ lifecycle.setCached(next);
return next;
}
if (resp.status === 401 || resp.status === 403) {
- // Refresh token is dead; clear local state so the next login is clean.
- cached = undefined;
+ lifecycle.setCached(undefined);
await clearAuth().catch(() => undefined);
const body = (await resp.json().catch(() => ({}))) as { error_description?: string };
throw new KimiAuthUnauthorizedError(
diff --git a/src/providers/kimi/auth/token-store.ts b/src/providers/kimi/auth/token-store.ts
index c50b098..5a41fa0 100644
--- a/src/providers/kimi/auth/token-store.ts
+++ b/src/providers/kimi/auth/token-store.ts
@@ -1,7 +1,6 @@
-import { mkdir, readFile, writeFile, unlink, rename } from "node:fs/promises";
-import { dirname, join } from "node:path";
-import { keychainGet, keychainSet, keychainDelete } from "../../../keychain.ts";
+import { join } from "node:path";
import { kimiAuthFile, legacyConfigDir } from "../../../paths.ts";
+import { createAuthStore } from "../../shared/auth/token-store.ts";
export interface StoredAuth {
access: string;
@@ -11,68 +10,13 @@ export interface StoredAuth {
userId?: string;
}
-function file(): string {
- return kimiAuthFile();
-}
-function legacyFile(): string {
- return join(legacyConfigDir(), "kimi", "auth.json");
-}
-const KEYCHAIN_SERVICE = "claude-code-proxy.kimi";
-const KEYCHAIN_ACCOUNT = "auth";
-
-export async function loadAuth(): Promise<StoredAuth | undefined> {
- if (process.platform === "darwin") {
- const raw = keychainGet(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);
- if (!raw) return undefined;
- return JSON.parse(raw) as StoredAuth;
- }
-
- const primary = file();
- try {
- const raw = await readFile(primary, "utf8");
- return JSON.parse(raw) as StoredAuth;
- } catch (err: any) {
- if (err?.code !== "ENOENT") throw err;
- }
- const legacy = legacyFile();
- if (legacy === primary) return undefined;
- try {
- const raw = await readFile(legacy, "utf8");
- return JSON.parse(raw) as StoredAuth;
- } catch (err: any) {
- if (err?.code === "ENOENT") return undefined;
- throw err;
- }
-}
-
-export async function saveAuth(auth: StoredAuth): Promise<void> {
- if (process.platform === "darwin") {
- keychainSet(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT, JSON.stringify(auth));
- return;
- }
+const store = createAuthStore<StoredAuth>({
+ file: kimiAuthFile,
+ legacyFile: () => join(legacyConfigDir(), "kimi", "auth.json"),
+ keychainService: "claude-code-proxy.kimi",
+});
- const path = file();
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
- const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
- await writeFile(tmp, JSON.stringify(auth, null, 2), { encoding: "utf8", mode: 0o600 });
- await rename(tmp, path);
-}
-
-export async function clearAuth(): Promise<void> {
- if (process.platform === "darwin") {
- keychainDelete(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT);
- return;
- }
-
- for (const path of [file(), legacyFile()]) {
- try {
- await unlink(path);
- } catch (err: any) {
- if (err?.code !== "ENOENT") throw err;
- }
- }
-}
-
-export function authPath(): string {
- return process.platform === "darwin" ? "macOS Keychain" : file();
-}
+export const loadAuth = store.loadAuth;
+export const saveAuth = store.saveAuth;
+export const clearAuth = store.clearAuth;
+export const authPath = store.authPath;
diff --git a/src/providers/shared/auth/manager.ts b/src/providers/shared/auth/manager.ts
new file mode 100644
index 0000000..8f97cd8
--- /dev/null
+++ b/src/providers/shared/auth/manager.ts
@@ -0,0 +1,76 @@
+export interface TokenResponse {
+ access_token: string;
+ refresh_token: string;
+ expires_in?: number;
+}
+
+export function validateTokenResponse<T extends TokenResponse>(t: unknown): asserts t is T {
+ if (!t || typeof t !== "object") throw new Error("Invalid token response: not an object");
+ const o = t as Record<string, unknown>;
+ if (typeof o.access_token !== "string" || !o.access_token)
+ throw new Error("Invalid token response: missing access_token");
+ if (typeof o.refresh_token !== "string" || !o.refresh_token)
+ throw new Error("Invalid token response: missing refresh_token");
+ if (
+ o.expires_in !== undefined &&
+ (typeof o.expires_in !== "number" || !Number.isFinite(o.expires_in) || o.expires_in <= 0)
+ )
+ throw new Error("Invalid token response: bad expires_in");
+}
+
+export interface AuthLifecycle<T extends { expires: number }> {
+ getAuth(): Promise<T>;
+ forceRefresh(): Promise<T>;
+ resetCache(): void;
+ setCached(auth: T | undefined): void;
+}
+
+export function createAuthLifecycle<T extends { expires: number }>(deps: {
+ loadAuth: () => Promise<T | undefined>;
+ loginRequiredMessage: string;
+ forceRefreshUnauthenticatedMessage: string;
+ refreshMarginMs: number;
+ refreshNow: (current: T) => Promise<T>;
+}): AuthLifecycle<T> {
+ let cached: T | undefined;
+ let inflight: Promise<T> | undefined;
+
+ async function getAuth(): Promise<T> {
+ if (!cached) {
+ const stored = await deps.loadAuth();
+ if (!stored) throw new Error(deps.loginRequiredMessage);
+ cached = stored;
+ }
+ if (cached.expires - deps.refreshMarginMs > Date.now()) {
+ return cached;
+ }
+ if (inflight) return inflight;
+ inflight = deps.refreshNow(cached).finally(() => {
+ inflight = undefined;
+ });
+ return inflight;
+ }
+
+ async function forceRefresh(): Promise<T> {
+ if (!cached) {
+ const stored = await deps.loadAuth();
+ if (!stored) throw new Error(deps.forceRefreshUnauthenticatedMessage);
+ cached = stored;
+ }
+ if (inflight) return inflight;
+ inflight = deps.refreshNow(cached).finally(() => {
+ inflight = undefined;
+ });
+ return inflight;
+ }
+
+ function resetCache(): void {
+ cached = undefined;
+ }
+
+ function setCached(auth: T | undefined): void {
+ cached = auth;
+ }
+
+ return { getAuth, forceRefresh, resetCache, setCached };
+}
diff --git a/src/providers/shared/auth/token-store.ts b/src/providers/shared/auth/token-store.ts
new file mode 100644
index 0000000..55238a5
--- /dev/null
+++ b/src/providers/shared/auth/token-store.ts
@@ -0,0 +1,81 @@
+import { mkdir, readFile, writeFile, unlink, rename } from "node:fs/promises";
+import { dirname } from "node:path";
+import { keychainGet, keychainSet, keychainDelete } from "../../../keychain.ts";
+
+const KEYCHAIN_ACCOUNT = "auth";
+
+export interface AuthStoreOptions {
+ file: () => string;
+ legacyFile: () => string;
+ keychainService: string;
+}
+
+export interface AuthStore<T> {
+ loadAuth(): Promise<T | undefined>;
+ saveAuth(auth: T): Promise<void>;
+ clearAuth(): Promise<void>;
+ authPath(): string;
+}
+
+export function createAuthStore<T>(options: AuthStoreOptions): AuthStore<T> {
+ const { file, legacyFile, keychainService } = options;
+
+ return {
+ async loadAuth(): Promise<T | undefined> {
+ if (process.platform === "darwin") {
+ const raw = keychainGet(keychainService, KEYCHAIN_ACCOUNT);
+ if (!raw) return undefined;
+ return JSON.parse(raw) as T;
+ }
+
+ const primary = file();
+ try {
+ const raw = await readFile(primary, "utf8");
+ return JSON.parse(raw) as T;
+ } catch (err: any) {
+ if (err?.code !== "ENOENT") throw err;
+ }
+ const legacy = legacyFile();
+ if (legacy === primary) return undefined;
+ try {
+ const raw = await readFile(legacy, "utf8");
+ return JSON.parse(raw) as T;
+ } catch (err: any) {
+ if (err?.code === "ENOENT") return undefined;
+ throw err;
+ }
+ },
+
+ async saveAuth(auth: T): Promise<void> {
+ if (process.platform === "darwin") {
+ keychainSet(keychainService, KEYCHAIN_ACCOUNT, JSON.stringify(auth));
+ return;
+ }
+
+ const path = file();
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
+ await writeFile(tmp, JSON.stringify(auth, null, 2), { encoding: "utf8", mode: 0o600 });
+ await rename(tmp, path);
+ },
+
+ async clearAuth(): Promise<void> {
+ if (process.platform === "darwin") {
+ keychainDelete(keychainService, KEYCHAIN_ACCOUNT);
+ return;
+ }
+
+ for (const path of [file(), legacyFile()]) {
+ try {
+ await unlink(path);
+ } catch (err: any) {
+ if (err?.code !== "ENOENT") throw err;
+ }
+ }
+ },
+
+ authPath(): string {
+ return process.platform === "darwin" ? "macOS Keychain" : file();
+ },
+ };
+}