Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
import fs from "fs/promises";
import path from "path";
import { getCachedProviderConnectionById } from "@/lib/db/readCache";
import { createBackup } from "@/shared/services/backupService";
import { getCliConfigPaths } from "@/shared/services/cliRuntime";
import {
TOKEN_EXPIRY_BUFFER_MS,
getAccessToken,
updateProviderCredentials,
} from "@/sse/services/tokenRefresh";
import { isUnrecoverableRefreshError } from "@omniroute/open-sse/services/tokenRefresh.ts";
type JsonRecord = Record<string, unknown>;
interface CodexConnectionLike {
id?: string;
provider?: string;
authType?: string;
name?: string;
email?: string;
displayName?: string;
accessToken?: string | null;
refreshToken?: string | null;
idToken?: string | null;
expiresAt?: string | null;
expiresIn?: number | null;
providerSpecificData?: JsonRecord | null;
}
export interface CodexAuthFilePayload {
auth_mode: "chatgpt";
OPENAI_API_KEY: null;
tokens: {
id_token: string;
access_token: string;
refresh_token: string;
account_id: string;
};
last_refresh: string;
}
export interface BuiltCodexAuthFile {
connectionId: string;
connectionLabel: string;
fileName: string;
payload: CodexAuthFilePayload;
content: string;
}
export class CodexAuthFileError extends Error {
status: number;
code: string;
constructor(message: string, status = 400, code = "invalid_request") {
super(message);
this.name = "CodexAuthFileError";
this.status = status;
this.code = code;
}
}
const CODEX_REFRESH_BUFFER_MS = Math.max(TOKEN_EXPIRY_BUFFER_MS, 5 * 60 * 1000);
function toRecord(value: unknown): JsonRecord {
return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
}
function toNonEmptyString(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed ? trimmed : null;
}
function decodeJwtPayload(jwt: string): JsonRecord | null {
try {
const parts = jwt.split(".");
if (parts.length !== 3) return null;
const payload = Buffer.from(parts[1], "base64url").toString("utf8");
return toRecord(JSON.parse(payload));
} catch {
return null;
}
}
function extractCodexAccountId(idToken: string, providerSpecificData: unknown): string | null {
const payload = decodeJwtPayload(idToken);
const authInfo = payload ? toRecord(payload["https://api.openai.com/auth"]) : {};
return (
toNonEmptyString(authInfo.chatgpt_account_id) ||
toNonEmptyString(authInfo.account_id) ||
toNonEmptyString(toRecord(providerSpecificData).workspaceId)
);
}
function extractCodexEmail(connection: CodexConnectionLike): string | null {
const idToken = toNonEmptyString(connection.idToken);
if (idToken) {
const payload = decodeJwtPayload(idToken);
if (payload) {
const fromClaim = toNonEmptyString(payload.email);
if (fromClaim) return fromClaim;
}
}
return toNonEmptyString(connection.email);
}
function shouldRefreshCodexConnection(connection: CodexConnectionLike): boolean {
if (!toNonEmptyString(connection.accessToken)) {
return true;
}
const expiresAt = toNonEmptyString(connection.expiresAt);
if (!expiresAt) {
return false;
}
const expiresAtMs = new Date(expiresAt).getTime();
if (Number.isNaN(expiresAtMs)) {
return false;
}
return expiresAtMs - Date.now() <= CODEX_REFRESH_BUFFER_MS;
}
function getConnectionLabel(connection: CodexConnectionLike): string {
return (
toNonEmptyString(connection.name) ||
toNonEmptyString(connection.email) ||
toNonEmptyString(connection.displayName) ||
toNonEmptyString(connection.id) ||
"codex-account"
);
}
function sanitizeFileNamePart(value: string): string {
// Keep alphanumerics, dot, underscore, hyphen and @ so email addresses survive
// intact in the exported filename (e.g. `[email protected]`).
const normalized = value
.trim()
.toLowerCase()
.replace(/[^a-z0-9._@-]+/g, "-")
.replace(/^-+|-+$/g, "");
return normalized || "account";
}
function buildCodexAuthPayload(connection: CodexConnectionLike): CodexAuthFilePayload {
const idToken = toNonEmptyString(connection.idToken);
const accessToken = toNonEmptyString(connection.accessToken);
const refreshToken = toNonEmptyString(connection.refreshToken);
if (!idToken) {
throw new CodexAuthFileError(
"Codex connection is missing id_token. Re-authenticate this account before exporting.",
409,
"reauth_required"
);
}
if (!accessToken) {
throw new CodexAuthFileError(
"Codex connection is missing access_token. Refresh or re-authenticate this account first.",
409,
"access_token_missing"
);
}
if (!refreshToken) {
throw new CodexAuthFileError(
"Codex connection is missing refresh_token. Re-authenticate this account before exporting.",
409,
"reauth_required"
);
}
const accountId = extractCodexAccountId(idToken, connection.providerSpecificData);
if (!accountId) {
throw new CodexAuthFileError(
"Unable to derive Codex account_id from the stored session. Re-authenticate this account.",
409,
"account_id_missing"
);
}
return {
auth_mode: "chatgpt",
OPENAI_API_KEY: null,
tokens: {
id_token: idToken,
access_token: accessToken,
refresh_token: refreshToken,
account_id: accountId,
},
last_refresh: new Date().toISOString(),
};
}
async function resolveFreshCodexConnection(connectionId: string): Promise<CodexConnectionLike> {
const connection = (await getCachedProviderConnectionById(
connectionId
)) as CodexConnectionLike | null;
if (!connection) {
throw new CodexAuthFileError("Connection not found", 404, "not_found");
}
if (connection.provider !== "codex") {
throw new CodexAuthFileError("Only Codex provider connections can export Codex auth files");
}
if (connection.authType !== "oauth") {
throw new CodexAuthFileError("Only OAuth Codex connections support auth.json export");
}
if (!shouldRefreshCodexConnection(connection)) {
return connection;
}
const refreshToken = toNonEmptyString(connection.refreshToken);
if (!refreshToken) {
throw new CodexAuthFileError(
"Codex connection requires refresh but no refresh_token is available. Re-authenticate first.",
409,
"reauth_required"
);
}
// Pass onPersist so the DB write is atomic with the network call inside the mutex.
let persistedRefresh: any = null;
const refreshed = await getAccessToken(
"codex",
{
connectionId,
accessToken: connection.accessToken,
refreshToken,
expiresAt: connection.expiresAt,
expiresIn: connection.expiresIn,
idToken: connection.idToken,
providerSpecificData: connection.providerSpecificData,
},
async (result) => {
await updateProviderCredentials(connectionId, result);
persistedRefresh = result;
}
);
if (isUnrecoverableRefreshError(refreshed)) {
throw new CodexAuthFileError(
"Codex refresh token is no longer valid. Re-authenticate this account before exporting.",
409,
"reauth_required"
);
}
if (!refreshed?.accessToken) {
throw new CodexAuthFileError(
"Failed to refresh the Codex session before exporting the auth file. Re-authenticate this account if the session is stale.",
502,
"refresh_failed"
);
}
// If onPersist was not triggered (no accessToken path), fall back to explicit persist.
if (!persistedRefresh) {
await updateProviderCredentials(connectionId, refreshed);
}
const effectiveExpiresAt = refreshed.expiresAt
? refreshed.expiresAt
: typeof refreshed.expiresIn === "number"
? new Date(Date.now() + refreshed.expiresIn * 1000).toISOString()
: connection.expiresAt || null;
return {
...connection,
accessToken: refreshed.accessToken,
refreshToken: toNonEmptyString(refreshed.refreshToken) || refreshToken,
expiresIn:
typeof refreshed.expiresIn === "number" ? refreshed.expiresIn : connection.expiresIn || null,
expiresAt: effectiveExpiresAt,
providerSpecificData: refreshed.providerSpecificData
? {
...toRecord(connection.providerSpecificData),
...toRecord(refreshed.providerSpecificData),
}
: connection.providerSpecificData,
};
}
export async function buildCodexAuthFile(connectionId: string): Promise<BuiltCodexAuthFile> {
const connection = await resolveFreshCodexConnection(connectionId);
const payload = buildCodexAuthPayload(connection);
const connectionLabel = getConnectionLabel(connection);
const fileNameIdentifier = extractCodexEmail(connection) || connectionLabel;
const fileName = `auth-${sanitizeFileNamePart(fileNameIdentifier)}.json`;
const content = JSON.stringify(payload, null, 2) + "\n";
return {
connectionId,
connectionLabel,
fileName,
payload,
content,
};
}
export async function writeCodexAuthFileToLocalCli(connectionId: string) {
const built = await buildCodexAuthFile(connectionId);
const paths = getCliConfigPaths("codex");
// authPath is sourced exclusively from the static CLI_TOOLS table in
// src/shared/services/cliRuntime.ts (joined against os.homedir() inside
// that helper). No external/user input ever reaches the path APIs below.
const authPath = paths?.auth;
if (!authPath) {
throw new CodexAuthFileError("Codex auth path could not be resolved", 500, "path_unavailable");
}
const authDir = path.dirname(authPath);
await fs.mkdir(authDir, { recursive: true });
// Side-by-side .bak inside the .codex directory for one-click manual
// rollback. Both halves are server-controlled (authDir from the static
// CLI_TOOLS table; basename from a server-generated ISO timestamp), so
// string concatenation here is safe — and avoids the false-positive
// taint on path.join when Semgrep cannot follow the trust chain.
let savedBakPath: string | null = null;
try {
await fs.access(authPath);
const ts = new Date().toISOString().replace(/[:.]/g, "-");
savedBakPath = `${authDir}${path.sep}auth-${ts}.bak`;
await fs.copyFile(authPath, savedBakPath);
} catch {
// No existing file; nothing to back up side-by-side.
}
// Centralized history (audit trail across all CLI tools).
const centralizedBackupPath = await createBackup("codex", authPath);
await fs.writeFile(authPath, built.content, { encoding: "utf8", mode: 0o600 });
try {
await fs.chmod(authPath, 0o600);
} catch {
// Best effort on platforms that ignore chmod semantics.
}
return {
...built,
authPath,
savedBakPath,
centralizedBackupPath,
};
}
/**
* Decision for the guarded write (see writeCodexAuthFileToLocalCliIfNeeded).
*/
export type CodexAuthWriteDecision =
| "written" // wrote a fresh auth.json (was absent, stale, or force)
| "skipped_present_fresh"; // an existing, non-stale auth.json was left untouched
/**
* Guarded variant of writeCodexAuthFileToLocalCli for the codex-app-server
* "Sign in with ChatGPT" flow. Per the design decision (William, Q2):
*
* - Write ONLY when ~/.codex/auth.json is ABSENT, or STALE (its token is at/
* past the refresh buffer), or when `force` is set.
* - NEVER clobber an existing, healthy (non-stale) auth.json — a user may be
* managing the CLI session themselves. (The underlying writer always makes a
* backup regardless, so even a forced overwrite is recoverable.)
*
* Staleness is read from the existing file's `last_refresh` + the token's own
* expiry claim (JWT `exp` on the access_token) when present; if neither is
* readable we treat the file as fresh (do not clobber).
*
* Returns the write decision plus (when written) the underlying write result.
*/
export async function writeCodexAuthFileToLocalCliIfNeeded(
connectionId: string,
options: { force?: boolean } = {}
): Promise<{
decision: CodexAuthWriteDecision;
authPath: string | null;
result?: Awaited<ReturnType<typeof writeCodexAuthFileToLocalCli>>;
}> {
const paths = getCliConfigPaths("codex");
const authPath = paths?.auth ?? null;
if (!options.force && authPath) {
const existing = await readExistingCodexAuth(authPath);
if (existing && !isCodexAuthStale(existing)) {
// Present and healthy — do not clobber a session we didn't (or don't need
// to) manage. The connection can still authenticate turns via this file.
return { decision: "skipped_present_fresh", authPath };
}
}
const result = await writeCodexAuthFileToLocalCli(connectionId);
return { decision: "written", authPath: result.authPath, result };
}
/** Read + parse an existing ~/.codex/auth.json; null when absent/unreadable. */
async function readExistingCodexAuth(authPath: string): Promise<CodexAuthFilePayload | null> {
try {
const raw = await fs.readFile(authPath, "utf8");
const parsed = JSON.parse(raw) as unknown;
const rec = toRecord(parsed);
const tokens = toRecord(rec.tokens);
if (!toNonEmptyString(tokens.access_token)) return null;
return parsed as CodexAuthFilePayload;
} catch {
return null;
}
}
/**
* A stored auth.json is "stale" when its access_token is at/past the refresh
* buffer. Prefer the JWT `exp` claim on the access_token; fall back to
* `last_refresh` + a conservative validity window; if neither is parseable,
* treat as NOT stale (never clobber on ambiguity).
*/
function isCodexAuthStale(payload: CodexAuthFilePayload): boolean {
const accessToken = toNonEmptyString(payload?.tokens?.access_token);
if (accessToken) {
const claims = decodeJwtPayload(accessToken);
const exp = claims && typeof claims.exp === "number" ? claims.exp : null;
if (exp) {
const expiresAtMs = exp * 1000;
return expiresAtMs - Date.now() <= CODEX_REFRESH_BUFFER_MS;
}
}
// No usable exp claim — fall back to last_refresh age. Codex access tokens are
// short-lived (~hours); if the file hasn't refreshed in > 6h, consider it stale.
const lastRefresh = toNonEmptyString(payload?.last_refresh);
if (lastRefresh) {
const refreshedMs = new Date(lastRefresh).getTime();
if (!Number.isNaN(refreshedMs)) {
const SIX_HOURS_MS = 6 * 60 * 60 * 1000;
return Date.now() - refreshedMs >= SIX_HOURS_MS;
}
}
return false;
}