fix(codex): durable OAuth refresh lifecycle

Add shared OAuth credential lifecycle manager with provider-aware refresh
decisions. Implement CodexExecutor.refreshCredentials so 401/403 retry
refresh works for Codex, track lastRefreshAt and refresh before the
upstream stale-token window, preserve omitted idToken, and add
per-connection single-flight refresh to avoid refresh-token rotation races.

Merged from PR #1664.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Kevin Le
2026-06-06 11:04:36 +07:00
committed by decolua
co-authored by Cursor
parent 38b73bfc6b
commit c233c7c8fc
15 changed files with 484 additions and 140 deletions
+19 -19
View File
@@ -5,10 +5,13 @@ import { isOpenAICompatibleProvider, isAnthropicCompatibleProvider } from "@/sha
import { PROVIDER_ENDPOINTS } from "@/shared/constants/config";
import { getDefaultModel } from "open-sse/config/providerModels.js";
import { resolveOllamaLocalHost } from "open-sse/config/providers.js";
import {
refreshProviderCredentials,
shouldRefreshCredentials,
} from "open-sse/services/oauthCredentialManager.js";
import {
GEMINI_CONFIG,
ANTIGRAVITY_CONFIG,
CODEX_CONFIG,
KIRO_CONFIG,
QWEN_CONFIG,
CLAUDE_CONFIG,
@@ -126,18 +129,7 @@ async function refreshOAuthToken(connection) {
}
if (provider === "codex") {
const response = await fetch(CODEX_CONFIG.tokenUrl, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "refresh_token",
client_id: CODEX_CONFIG.clientId,
refresh_token: refreshToken,
}),
});
if (!response.ok) return null;
const data = await response.json();
return { accessToken: data.access_token, expiresIn: data.expires_in, refreshToken: data.refresh_token || refreshToken };
return await refreshProviderCredentials(provider, connection, console);
}
if (provider === "claude") {
@@ -227,10 +219,7 @@ async function refreshOAuthToken(connection) {
}
function isTokenExpired(connection) {
if (!connection.expiresAt) return false;
const expiresAt = new Date(connection.expiresAt).getTime();
const buffer = 5 * 60 * 1000;
return expiresAt <= Date.now() + buffer;
return shouldRefreshCredentials(connection.provider, connection);
}
async function testOAuthConnection(connection, effectiveProxy = null) {
@@ -673,14 +662,25 @@ export async function testSingleConnection(id) {
};
if (result.refreshed && result.newTokens) {
updateData.accessToken = result.newTokens.accessToken;
if (result.newTokens.accessToken) updateData.accessToken = result.newTokens.accessToken;
if (result.newTokens.refreshToken) updateData.refreshToken = result.newTokens.refreshToken;
if (result.newTokens.idToken) updateData.idToken = result.newTokens.idToken;
if (result.newTokens.lastRefreshAt) updateData.lastRefreshAt = result.newTokens.lastRefreshAt;
if (result.newTokens.expiresIn) updateData.expiresIn = result.newTokens.expiresIn;
if (result.newTokens.expiresIn) {
updateData.expiresAt = new Date(Date.now() + result.newTokens.expiresIn * 1000).toISOString();
} else if (result.newTokens.expiresAt) {
updateData.expiresAt = result.newTokens.expiresAt;
}
if (result.newTokens.providerSpecificData) {
updateData.providerSpecificData = {
...(connection.providerSpecificData || {}),
...result.newTokens.providerSpecificData,
};
}
}
await updateProviderConnection(id, updateData);
return { valid: result.valid, error: result.error, latencyMs, testedAt: new Date().toISOString() };
return { valid: result.valid, error: result.error, refreshed: !!result.refreshed, latencyMs, testedAt: new Date().toISOString() };
}
+40 -4
View File
@@ -1,5 +1,36 @@
import { getProviderConnections } from "@/lib/localDb.js";
import { getExecutor, refreshTokenByProvider } from "open-sse/index.js";
import { getProviderConnections, updateProviderConnection } from "@/lib/localDb.js";
import { getExecutor } from "open-sse/index.js";
async function persistRefreshedCredentials(connection, newCredentials) {
const updateData = {};
if (newCredentials.accessToken) updateData.accessToken = newCredentials.accessToken;
if (newCredentials.refreshToken) updateData.refreshToken = newCredentials.refreshToken;
if (newCredentials.idToken) updateData.idToken = newCredentials.idToken;
if (newCredentials.lastRefreshAt) updateData.lastRefreshAt = newCredentials.lastRefreshAt;
if (newCredentials.expiresIn) {
updateData.expiresIn = newCredentials.expiresIn;
updateData.expiresAt = new Date(Date.now() + newCredentials.expiresIn * 1000).toISOString();
} else if (newCredentials.expiresAt) {
updateData.expiresAt = newCredentials.expiresAt;
}
const providerSpecificUpdates = {
...(newCredentials.providerSpecificData || {}),
...(newCredentials.copilotToken ? { copilotToken: newCredentials.copilotToken } : {}),
...(newCredentials.copilotTokenExpiresAt ? { copilotTokenExpiresAt: newCredentials.copilotTokenExpiresAt } : {}),
};
if (Object.keys(providerSpecificUpdates).length > 0) {
updateData.providerSpecificData = {
...(connection.providerSpecificData || {}),
...providerSpecificUpdates,
};
}
if (Object.keys(updateData).length > 0) {
await updateProviderConnection(connection.id, updateData);
}
}
export async function POST(request) {
try {
@@ -19,7 +50,11 @@ export async function POST(request) {
apiKey: connection.apiKey,
accessToken: connection.accessToken,
refreshToken: connection.refreshToken,
copilotToken: connection.copilotToken,
idToken: connection.idToken,
lastRefreshAt: connection.lastRefreshAt,
connectionId: connection.id,
copilotToken: connection.providerSpecificData?.copilotToken,
copilotTokenExpiresAt: connection.providerSpecificData?.copilotTokenExpiresAt,
projectId: connection.projectId,
providerSpecificData: connection.providerSpecificData
};
@@ -31,9 +66,10 @@ export async function POST(request) {
// Auto-refresh token on 401/403 and retry (same as chatCore.js)
if (response.status === 401 || response.status === 403) {
const newCredentials = await refreshTokenByProvider(provider, credentials);
const newCredentials = await executor.refreshCredentials(credentials, console);
if (newCredentials?.accessToken || newCredentials?.copilotToken) {
Object.assign(credentials, newCredentials);
await persistRefreshedCredentials(connection, newCredentials);
({ response } = await executor.execute({ model, body, stream, credentials }));
}
}
+21 -4
View File
@@ -27,7 +27,10 @@ async function refreshAndUpdateCredentials(connection, force = false, proxyOptio
const credentials = {
accessToken: connection.accessToken,
refreshToken: connection.refreshToken,
idToken: connection.idToken,
expiresAt: connection.expiresAt || connection.tokenExpiresAt,
lastRefreshAt: connection.lastRefreshAt,
connectionId: connection.id,
providerSpecificData: connection.providerSpecificData,
// For GitHub
copilotToken: connection.providerSpecificData?.copilotToken,
@@ -68,19 +71,32 @@ async function refreshAndUpdateCredentials(connection, force = false, proxyOptio
updateData.refreshToken = refreshResult.refreshToken;
}
if (refreshResult.idToken) {
updateData.idToken = refreshResult.idToken;
}
if (refreshResult.lastRefreshAt) {
updateData.lastRefreshAt = refreshResult.lastRefreshAt;
}
// Update token expiry
if (refreshResult.expiresIn) {
updateData.expiresAt = new Date(Date.now() + refreshResult.expiresIn * 1000).toISOString();
updateData.expiresIn = refreshResult.expiresIn;
} else if (refreshResult.expiresAt) {
updateData.expiresAt = refreshResult.expiresAt;
}
// Handle provider-specific data (copilotToken for GitHub, etc.)
if (refreshResult.copilotToken || refreshResult.copilotTokenExpiresAt) {
const providerSpecificUpdates = {
...(refreshResult.providerSpecificData || {}),
...(refreshResult.copilotToken ? { copilotToken: refreshResult.copilotToken } : {}),
...(refreshResult.copilotTokenExpiresAt ? { copilotTokenExpiresAt: refreshResult.copilotTokenExpiresAt } : {}),
};
if (Object.keys(providerSpecificUpdates).length > 0) {
updateData.providerSpecificData = {
...connection.providerSpecificData,
copilotToken: refreshResult.copilotToken,
copilotTokenExpiresAt: refreshResult.copilotTokenExpiresAt,
...(connection.providerSpecificData || {}),
...providerSpecificUpdates,
};
}
@@ -91,6 +107,7 @@ async function refreshAndUpdateCredentials(connection, force = false, proxyOptio
const updatedConnection = {
...connection,
...updateData,
providerSpecificData: updateData.providerSpecificData || connection.providerSpecificData,
};
return {
+4 -1
View File
@@ -225,9 +225,12 @@ const PROVIDERS = {
const mapped = {
accessToken: tokens.access_token,
refreshToken: tokens.refresh_token,
idToken: tokens.id_token,
expiresIn: tokens.expires_in,
lastRefreshAt: new Date().toISOString(),
};
if (info.email) mapped.email = info.email;
const email = info.email || extractEmailFromAccessToken(tokens.access_token);
if (email) mapped.email = email;
if (info.chatgptAccountId || info.chatgptPlanType) {
mapped.providerSpecificData = {
chatgptAccountId: info.chatgptAccountId,
+1 -1
View File
@@ -54,6 +54,7 @@ export class CodexService extends OAuthService {
accessToken: tokens.access_token,
refreshToken: tokens.refresh_token,
expiresIn: tokens.expires_in,
lastRefreshAt: new Date().toISOString(),
}),
});
@@ -141,4 +142,3 @@ export class CodexService extends OAuthService {
}
}
}
+2 -3
View File
@@ -218,9 +218,8 @@ async function handleSingleModelChat(body, modelStr, clientRawRequest = null, re
sourceFormatOverride: request?.url ? detectFormatByEndpoint(new URL(request.url).pathname, body) : null,
onCredentialsRefreshed: async (newCreds) => {
await updateProviderCredentials(credentials.connectionId, {
accessToken: newCreds.accessToken,
refreshToken: newCreds.refreshToken,
providerSpecificData: newCreds.providerSpecificData,
...newCreds,
existingProviderSpecificData: credentials.providerSpecificData,
testStatus: "active"
});
},
+2 -3
View File
@@ -114,9 +114,8 @@ export async function handleEmbeddings(request) {
log,
onCredentialsRefreshed: async (newCreds) => {
await updateProviderCredentials(credentials.connectionId, {
accessToken: newCreds.accessToken,
refreshToken: newCreds.refreshToken,
providerSpecificData: newCreds.providerSpecificData,
...newCreds,
existingProviderSpecificData: credentials.providerSpecificData,
testStatus: "active"
});
},
+4
View File
@@ -163,6 +163,10 @@ export async function getProviderCredentials(provider, excludeConnectionIds = nu
apiKey: connection.apiKey,
accessToken: connection.accessToken,
refreshToken: connection.refreshToken,
idToken: connection.idToken,
expiresAt: connection.expiresAt,
expiresIn: connection.expiresIn,
lastRefreshAt: connection.lastRefreshAt,
projectId: connection.projectId,
connectionName: connection.displayName || connection.name || connection.email || connection.id,
copilotToken: connection.providerSpecificData?.copilotToken,
+47 -33
View File
@@ -23,6 +23,10 @@ import {
refreshKiroToken as _refreshKiroToken,
getRefreshLeadMs as _getRefreshLeadMs
} from "open-sse/services/tokenRefresh.js";
import {
refreshProviderCredentials as _refreshProviderCredentials,
shouldRefreshCredentials as _shouldRefreshCredentials,
} from "open-sse/services/oauthCredentialManager.js";
export const TOKEN_EXPIRY_BUFFER_MS = BUFFER_MS;
@@ -67,6 +71,9 @@ export const formatProviderCredentials = (provider, credentials) =>
export const getAllAccessTokens = (userInfo) =>
_getAllAccessTokens(userInfo, log);
export const shouldRefreshCredentials = (provider, credentials) =>
_shouldRefreshCredentials(provider, credentials);
// ─── Lifecycle hook ───────────────────────────────────────────────────────────
/**
@@ -158,6 +165,9 @@ export async function updateProviderCredentials(connectionId, newCredentials) {
if (newCredentials.accessToken) updates.accessToken = newCredentials.accessToken;
if (newCredentials.refreshToken) updates.refreshToken = newCredentials.refreshToken;
if (newCredentials.idToken) updates.idToken = newCredentials.idToken;
if (newCredentials.lastRefreshAt) updates.lastRefreshAt = newCredentials.lastRefreshAt;
if (newCredentials.expiresAt) updates.expiresAt = newCredentials.expiresAt;
if (newCredentials.expiresIn) {
updates.expiresAt = toExpiresAt(newCredentials.expiresIn);
updates.expiresIn = newCredentials.expiresIn;
@@ -174,6 +184,13 @@ export async function updateProviderCredentials(connectionId, newCredentials) {
...newCredentials.providerSpecificData,
};
}
if (newCredentials.copilotToken || newCredentials.copilotTokenExpiresAt) {
updates.providerSpecificData = {
...(updates.providerSpecificData || newCredentials.existingProviderSpecificData || {}),
...(newCredentials.copilotToken ? { copilotToken: newCredentials.copilotToken } : {}),
...(newCredentials.copilotTokenExpiresAt ? { copilotTokenExpiresAt: newCredentials.copilotTokenExpiresAt } : {}),
};
}
if (newCredentials.projectId) updates.projectId = newCredentials.projectId;
const result = await updateProviderConnection(connectionId, updates);
@@ -205,44 +222,41 @@ export async function checkAndRefreshToken(provider, credentials) {
let creds = { ...credentials };
// ── 1. Regular access-token expiry ────────────────────────────────────────
if (creds.expiresAt) {
const expiresAt = new Date(creds.expiresAt).getTime();
const now = Date.now();
const remaining = expiresAt - now;
if (_shouldRefreshCredentials(provider, creds)) {
const expiresAt = creds.expiresAt ? new Date(creds.expiresAt).getTime() : null;
const remaining = expiresAt ? expiresAt - Date.now() : null;
const refreshLead = _getRefreshLeadMs(provider);
if (remaining < refreshLead) {
log.info("TOKEN_REFRESH", "Token expiring soon, refreshing proactively", {
provider,
expiresIn: Math.round(remaining / 1000),
refreshLeadMs: refreshLead,
});
const newCreds = await getAccessToken(provider, creds);
if (newCreds?.accessToken) {
const mergedCreds = {
...newCreds,
existingProviderSpecificData: creds.providerSpecificData,
};
log.info("TOKEN_REFRESH", "Refreshing provider credentials proactively", {
provider,
expiresIn: remaining === null ? null : Math.round(remaining / 1000),
refreshLeadMs: refreshLead,
lastRefreshAt: creds.lastRefreshAt || null,
});
// Persist to DB (non-blocking path continues below)
await updateProviderCredentials(creds.connectionId, mergedCreds);
const newCreds = await _refreshProviderCredentials(provider, creds, log);
if (newCreds?.accessToken || newCreds?.apiKey || newCreds?.copilotToken) {
const mergedCreds = {
...newCreds,
existingProviderSpecificData: creds.providerSpecificData,
};
creds = {
...creds,
accessToken: newCreds.accessToken,
refreshToken: newCreds.refreshToken ?? creds.refreshToken,
providerSpecificData: newCreds.providerSpecificData
? { ...creds.providerSpecificData, ...newCreds.providerSpecificData }
: creds.providerSpecificData,
expiresAt: newCreds.expiresIn
? toExpiresAt(newCreds.expiresIn)
: normalizeExpiresAt(newCreds.expiresAt) || creds.expiresAt,
};
// Persist to DB (non-blocking path continues below)
await updateProviderCredentials(creds.connectionId, mergedCreds);
// Non-blocking: refresh projectId with the new access token
_refreshProjectId(provider, creds.connectionId, creds.accessToken);
}
creds = {
...creds,
...newCreds,
expiresAt: newCreds.expiresIn
? toExpiresAt(newCreds.expiresIn)
: normalizeExpiresAt(newCreds.expiresAt) || newCreds.expiresAt || creds.expiresAt,
providerSpecificData: newCreds.providerSpecificData
? { ...creds.providerSpecificData, ...newCreds.providerSpecificData }
: creds.providerSpecificData,
};
// Non-blocking: refresh projectId with the new access token
_refreshProjectId(provider, creds.connectionId, creds.accessToken);
}
}