mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-05 14:52:09 +03:00
* docs(changelog): record PR #1748 for next release * fix(models): apply blocked providers filter to non-chat catalog models (#1752) * chore(release): v3.7.5 — integrate ngrok tunnel and fix models filter (#1753, #1752) * chore(release): update changelog format for v3.7.5 * Speed up endpoint initial render * Address endpoint review feedback * Add endpoint loading model translations * fix: resolve build issues and implement memory UPSERT logic (#1763) * fix: resolve build issues for v3.7.5 and apply memory/translation fixes 1. antigravityHeaders.ts: restore ANTIGRAVITY_LOAD_CODE_ASSIST_* exports for oauth.ts compatibility 2. next.config.mjs: add @ngrok/ngrok to serverExternalPackages and webpack externals to handle native .node modules 3. Memory system: UPSERT logic to prevent duplicate entries with same apiKeyId + key 4. Chinese translations: complete CLI tools and memory dashboard localizations 5. Test fixes: unique keys for pagination tests to comply with unique constraint Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: address Gemini Code Assist review feedback 1. store.ts: add expires_at to UPDATE statement in UPSERT logic - Previously, expires_at was not being persisted to database on update - This caused state mismatch between returned Memory object and actual DB row 2. package-lock.json: revert react-markdown registry to official npmjs.org - Mirror-specific registry URL (npmmirror.com) should not be in lockfile Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> * fix(antigravity): normalize Gemini bridge payloads (#1769) * fix(antigravity): normalize Gemini bridge payloads Clamp Claude bridge output tokens, use Gemini-valid system roles and tool names, and serialize antigravity requests from a cloned body so Cloud Code payload shaping stays valid. * fix(cli): stop fallback after unsafe known paths Preserve known-path security checks by stopping command discovery when a configured CLI path is suspicious or non-executable, instead of falling through to PATH discovery. * test(memory): make query result assertion deterministic Avoid relying on database result ordering when checking filtered memory keys so the unit suite remains stable across runs. * fix(review): preserve safe cloning and CLI reasons Handle non-cloneable antigravity request bodies without throwing and preserve specific CLI known-path failure reasons instead of masking them as not_found. * fix(sse): propagate AbortSignal to pre-fetch semaphore and rate-limit awaits (#1771) When a combo target takes too long, the request-level deadline fires and calls abortController.abort() on the stream controller, but the abort signal never reaches pending awaits in acquireAccountSemaphore() or withRateLimit(). These awaits sit between stream controller creation and executor.execute(), causing requests to hang indefinitely past the 600s deadline. Pass streamController.signal to both functions so they can respond to abort events and terminate early when the request deadline expires. Signed-off-by: wucm667 <stevenwucongmin@gmail.com> * Fix model sync import handling (#1755) * Fix model sync import handling * Align model import storage semantics * Address model review feedback * fix(codex): stabilize copilot responses reasoning and tool replay (#1750) * chore(xiaomi): Update Xiaomi provider model list (#1759) * Move DB health to management API (#1757) * Move DB health to management API * Address DB health review feedback * fix(kiro): support organization IDC OAuth with regional endpoints and refresh (#1754) * fix(kiro): support organization IDC OAuth with regional endpoints and refresh * fix(kiro): refresh IDC tokens with stored region --------- Co-authored-by: ngocdb <ngocdb@ngocdb.local> * chore(workflows): add strict PR contributor credit policy - Add ABSOLUTE PROHIBITION section to review-prs.md - Add PR PROHIBITION rule to resolve-issues.md - Add contributor credit rule to AGENTS.md Review Focus - Based on audit finding: 37 PRs had code absorbed without merge credit * chore(release): acknowledge 29 community contributors with retroactive credit This commit formally recognizes 29 contributors whose code was manually integrated across releases v3.4.0 through v3.7.4 without proper GitHub merge credit. Their PRs were resolved locally due to merge conflicts but closed instead of merged, preventing them from appearing in the Contributors graph. We have updated our workflows to ensure this never happens again. Co-authored-by: Randi <55005611+rdself@users.noreply.github.com> Co-authored-by: Benson K B <4044180+benzntech@users.noreply.github.com> Co-authored-by: clousky2020 <33016567+clousky2020@users.noreply.github.com> Co-authored-by: Raxxoor <7317522+dhaern@users.noreply.github.com> Co-authored-by: Jason Landbridge <15127381+JasonLandbridge@users.noreply.github.com> Co-authored-by: slewis3600 <35925982+slewis3600@users.noreply.github.com> Co-authored-by: Markus Hartung <12826053+hartmark@users.noreply.github.com> Co-authored-by: Hernan Javier Ardila Sanchez <204746071+herjarsa@users.noreply.github.com> Co-authored-by: 3_1_3_u <5846351+andruwa13@users.noreply.github.com> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com> Co-authored-by: i1hwan <35260883+i1hwan@users.noreply.github.com> Co-authored-by: xandr0s <1709302+xandr0s@users.noreply.github.com> Co-authored-by: backryun <24198422+backryun@users.noreply.github.com> Co-authored-by: Owen <36758131+kang-heewon@users.noreply.github.com> Co-authored-by: Ravi Tharuma <25951435+RaviTharuma@users.noreply.github.com> Co-authored-by: Chris <3751981+christopher-s@users.noreply.github.com> Co-authored-by: Wellington Fonseca <5421548+wlfonseca@users.noreply.github.com> Co-authored-by: Ethan Hunt <136065060+only4copilot@users.noreply.github.com> Co-authored-by: tombii <6607822+tombii@users.noreply.github.com> Co-authored-by: AndrewDragonIV <7906124+AndrewDragonIV@users.noreply.github.com> Co-authored-by: Danh Thanh <50534210+dt418@users.noreply.github.com> Co-authored-by: Will F <30637450+willbnu@users.noreply.github.com> Co-authored-by: defhouse <232128212+defhouse@users.noreply.github.com> Co-authored-by: Skydwest <186351198+mercs2910@users.noreply.github.com> Co-authored-by: zenobit <6384793+zen0bit@users.noreply.github.com> Co-authored-by: Ivan <16905671+razllivan@users.noreply.github.com> Co-authored-by: foxy1402 <45601526+foxy1402@users.noreply.github.com> Co-authored-by: Luan Dias <65574834+luandiasrj@users.noreply.github.com> Co-authored-by: Sergei Korolev <891832+knopki@users.noreply.github.com> Co-authored-by: dail45 <69967573+dail45@users.noreply.github.com> * fix(combo): include 429 in provider circuit breaker to stop infinite retry on exhausted quotas (#1767) Previously, PROVIDER_FAILURE_ERROR_CODES only included {408, 500, 502, 503, 504}, meaning 429 responses never counted toward the circuit breaker threshold. This caused exhausted accounts to be retried every 3-5 seconds indefinitely instead of being blocked by the provider breaker. Adding 429 ensures persistent rate limiting triggers the circuit breaker after the configured failure threshold, giving the provider time to recover. * fix(claude): respect client thinking/effort params to prevent forced quota drain (#1761) Previously, OmniRoute unconditionally injected thinking: {type: 'adaptive'} and output_config: {effort: 'high'} for Claude Opus 4.7 in Claude Code client requests. This caused Claude Max 5h quota to drain in ~15 minutes. Now checks the original client body: if thinking or output_config are explicitly set (even to null or a different value), the injection is skipped. Users can opt-out by sending thinking: null or output_config: {effort: 'low'}. * Add MseeP.ai badge to README.md (#1727) Integrated into release/v3.7.5 * chore(docs): update CHANGELOG for PR #1727 * fix(tests): update stream-utils assertion for responses api compliance * feat: Fix support for claude-cli using Gemini provider (#1779) Integrated into release/v3.7.5 * fix(codex): align client identity metadata (#1778) Integrated into release/v3.7.5 * fix(blackbox-web): correct cookie name and populate session/subscription fields (#1776) Integrated into release/v3.7.5 * Fix Codex /responses/compact passthrough (#1777) Integrated into release/v3.7.5 * test(reasoning-cache): isolate DB state using mkdtempSync to prevent 401 middleware errors * chore(release): v3.7.5 — integrate remaining PRs and finalize stability * chore(config): remove local patch artifacts and trim workspace config Delete temporary patch scripts and local OMC session files that should not ship with the repository. Also remove the Next.js config file and expand editor and TypeScript exclusions to ignore large local workspace directories and reduce unnecessary indexing. * fix(antigravity): cap Claude bridge output tokens (#1785) Integrated into release/v3.7.5 * fix(codex): stabilize Copilot responses replay state (#1791) Integrated into release/v3.7.5 * fix(chatgpt-web): restore validator + expand model catalog to ChatGPT Plus tier (#1792) Integrated into release/v3.7.5 * fix(antigravity): scrub internal OmniRoute headers (#1794) Integrated into release/v3.7.5 * fix(grok-web): fix Grok validator and cookie parsing (#1793) Integrated into release/v3.7.5 * chore(release): v3.7.5 — finalize changelog for LTS patch * feat(api-keys): add rename support in permissions modal Add an editable key name field at the top of the permissions modal, allowing users to rename API keys alongside existing permission settings. The backend already supported name updates via PATCH /api/keys/:id — this wires the UI to send the name field and refreshes the key list on success. Changes: - Add keyName state and text input to PermissionsModal - Update handleUpdatePermissions to validate and send name in PATCH body - Add integration test for rename via PATCH (valid, empty, too-long names) - Update E2E mock to handle PATCH requests * chore(release): finalize v3.7.5 LTS release with schema and db initialization fixes * test: fix json escaping in stream-utilities test * fix(build): restore next.config.mjs that was accidentally deleted * fix(sse): decrement pending requests on passthrough mode failure (#1798) Integrated into release/v3.7.5 * fix(grok-web): repair validator probe + accept full cookie blobs (#1793) Integrated into release/v3.7.5 * docs(i18n): sync documentation updates to 40 languages --------- Signed-off-by: wucm667 <stevenwucongmin@gmail.com> Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com> Co-authored-by: R.D. <rogerproself@gmail.com> Co-authored-by: clousky2020 <33016567+clousky2020@users.noreply.github.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: cloudy <37777261+uwuclxdy@users.noreply.github.com> Co-authored-by: wucm667 <109257021+wucm667@users.noreply.github.com> Co-authored-by: Randi <55005611+rdself@users.noreply.github.com> Co-authored-by: ivan-mezentsev <ivan@mezentsev.me> Co-authored-by: backryun <bakryun0718@proton.me> Co-authored-by: Dao Bao Ngoc <42265865+daongoc315@users.noreply.github.com> Co-authored-by: ngocdb <ngocdb@ngocdb.local> Co-authored-by: Benson K B <4044180+benzntech@users.noreply.github.com> Co-authored-by: Raxxoor <7317522+dhaern@users.noreply.github.com> Co-authored-by: Jason Landbridge <15127381+JasonLandbridge@users.noreply.github.com> Co-authored-by: slewis3600 <35925982+slewis3600@users.noreply.github.com> Co-authored-by: Markus Hartung <12826053+hartmark@users.noreply.github.com> Co-authored-by: Hernan Javier Ardila Sanchez <204746071+herjarsa@users.noreply.github.com> Co-authored-by: 3_1_3_u <5846351+andruwa13@users.noreply.github.com> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com> Co-authored-by: i1hwan <35260883+i1hwan@users.noreply.github.com> Co-authored-by: xandr0s <1709302+xandr0s@users.noreply.github.com> Co-authored-by: backryun <24198422+backryun@users.noreply.github.com> Co-authored-by: Owen <36758131+kang-heewon@users.noreply.github.com> Co-authored-by: Ravi Tharuma <25951435+RaviTharuma@users.noreply.github.com> Co-authored-by: Chris <3751981+christopher-s@users.noreply.github.com> Co-authored-by: Wellington Fonseca <5421548+wlfonseca@users.noreply.github.com> Co-authored-by: Ethan Hunt <136065060+only4copilot@users.noreply.github.com> Co-authored-by: tombii <6607822+tombii@users.noreply.github.com> Co-authored-by: AndrewDragonIV <7906124+AndrewDragonIV@users.noreply.github.com> Co-authored-by: Danh Thanh <50534210+dt418@users.noreply.github.com> Co-authored-by: Will F <30637450+willbnu@users.noreply.github.com> Co-authored-by: defhouse <232128212+defhouse@users.noreply.github.com> Co-authored-by: Skydwest <186351198+mercs2910@users.noreply.github.com> Co-authored-by: zenobit <6384793+zen0bit@users.noreply.github.com> Co-authored-by: Ivan <16905671+razllivan@users.noreply.github.com> Co-authored-by: foxy1402 <45601526+foxy1402@users.noreply.github.com> Co-authored-by: Luan Dias <65574834+luandiasrj@users.noreply.github.com> Co-authored-by: Sergei Korolev <891832+knopki@users.noreply.github.com> Co-authored-by: dail45 <69967573+dail45@users.noreply.github.com> Co-authored-by: MseeP.ai <mseep@skydeck.ai> Co-authored-by: Markus Hartung <mail@hartmark.se> Co-authored-by: Raxxoor <manker_lol@hotmail.com> Co-authored-by: Jack <5443152+hijak@users.noreply.github.com> Co-authored-by: Sergey Morozov <tr0st@bk.ru> Co-authored-by: payne <baboialex95@gmail.com> Co-authored-by: Antigravity Assistant <bot@antigravity.local> Co-authored-by: Andrew Munsell <andrew@wizardapps.net>
1097 lines
32 KiB
TypeScript
Executable File
1097 lines
32 KiB
TypeScript
Executable File
// @ts-nocheck
|
|
import { PROVIDERS, OAUTH_ENDPOINTS } from "../config/constants.ts";
|
|
import { getGitHubCopilotRefreshHeaders } from "../config/providerHeaderProfiles.ts";
|
|
import { pbkdf2Sync } from "node:crypto";
|
|
import { runWithProxyContext } from "../utils/proxyFetch.ts";
|
|
|
|
// Token expiry buffer (refresh if expires within 5 minutes)
|
|
export const TOKEN_EXPIRY_BUFFER_MS = 5 * 60 * 1000;
|
|
|
|
const CACHE_SECRET = "omniroute-token-cache";
|
|
|
|
// In-flight refresh promise cache to prevent race conditions
|
|
// Key: "provider:sha256(refreshToken)" → Value: Promise<result>
|
|
const refreshPromiseCache = new Map();
|
|
|
|
type RefreshLogger = {
|
|
info?: (tag: string, message: string, data?: Record<string, unknown>) => void;
|
|
warn?: (tag: string, message: string, data?: Record<string, unknown>) => void;
|
|
error?: (tag: string, message: string, data?: Record<string, unknown>) => void;
|
|
debug?: (tag: string, message: string, data?: Record<string, unknown>) => void;
|
|
} | null;
|
|
|
|
function buildFormParams(entries: Record<string, unknown>): URLSearchParams {
|
|
const params = new URLSearchParams();
|
|
for (const [key, value] of Object.entries(entries)) {
|
|
if (typeof value === "string" && value.length > 0) {
|
|
params.set(key, value);
|
|
}
|
|
}
|
|
return params;
|
|
}
|
|
|
|
function getRefreshCacheKey(provider, refreshToken) {
|
|
const tokenHash = pbkdf2Sync(refreshToken, CACHE_SECRET, 1000, 32, "sha256").toString("hex");
|
|
return `${provider}:${tokenHash}`;
|
|
}
|
|
|
|
/**
|
|
* Refresh OAuth access token using refresh token
|
|
*/
|
|
export async function refreshAccessToken(
|
|
provider,
|
|
refreshToken,
|
|
credentials,
|
|
log,
|
|
proxyConfig: unknown = null
|
|
) {
|
|
const config = PROVIDERS[provider];
|
|
|
|
const refreshEndpoint = config?.refreshUrl || config?.tokenUrl;
|
|
if (!config || !refreshEndpoint) {
|
|
log?.warn?.("TOKEN_REFRESH", `No refresh endpoint configured for provider: ${provider}`);
|
|
return null;
|
|
}
|
|
|
|
if (!refreshToken) {
|
|
log?.warn?.("TOKEN_REFRESH", `No refresh token available for provider: ${provider}`);
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
const params = new URLSearchParams({
|
|
grant_type: "refresh_token",
|
|
refresh_token: refreshToken,
|
|
});
|
|
if (config.clientId) params.set("client_id", config.clientId);
|
|
if (config.clientSecret) params.set("client_secret", config.clientSecret);
|
|
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch(refreshEndpoint, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
Accept: "application/json",
|
|
},
|
|
body: params,
|
|
})
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
log?.error?.("TOKEN_REFRESH", `Failed to refresh token for ${provider}`, {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const tokens = await response.json();
|
|
|
|
log?.info?.("TOKEN_REFRESH", `Successfully refreshed token for ${provider}`, {
|
|
hasNewAccessToken: !!tokens.access_token,
|
|
hasNewRefreshToken: !!tokens.refresh_token,
|
|
expiresIn: tokens.expires_in,
|
|
});
|
|
|
|
return {
|
|
accessToken: tokens.access_token,
|
|
refreshToken: tokens.refresh_token || refreshToken,
|
|
expiresIn: tokens.expires_in,
|
|
};
|
|
} catch (error) {
|
|
log?.error?.("TOKEN_REFRESH", `Error refreshing token for ${provider}`, {
|
|
error: error.message,
|
|
});
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Specialized refresh for Cline OAuth tokens.
|
|
* Cline refresh endpoint expects JSON body and returns camelCase fields.
|
|
*/
|
|
export async function refreshClineToken(refreshToken, log, proxyConfig: unknown = null) {
|
|
const endpoint = PROVIDERS.cline?.refreshUrl;
|
|
if (!endpoint) {
|
|
log?.warn?.("TOKEN_REFRESH", "No refresh URL configured for Cline");
|
|
return null;
|
|
}
|
|
|
|
try {
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch(endpoint, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Accept: "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
refreshToken,
|
|
grantType: "refresh_token",
|
|
clientType: "extension",
|
|
}),
|
|
})
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
log?.error?.("TOKEN_REFRESH", "Failed to refresh Cline token", {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const payload = await response.json();
|
|
const data = payload?.data || payload;
|
|
const expiresAtIso = data?.expiresAt;
|
|
const expiresIn = expiresAtIso
|
|
? Math.max(1, Math.floor((new Date(expiresAtIso).getTime() - Date.now()) / 1000))
|
|
: undefined;
|
|
|
|
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Cline token", {
|
|
hasNewAccessToken: !!data?.accessToken,
|
|
hasNewRefreshToken: !!data?.refreshToken,
|
|
expiresIn,
|
|
});
|
|
|
|
return {
|
|
accessToken: data?.accessToken,
|
|
refreshToken: data?.refreshToken || refreshToken,
|
|
expiresIn,
|
|
};
|
|
} catch (error) {
|
|
log?.error?.("TOKEN_REFRESH", `Network error refreshing Cline token: ${error.message}`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Specialized refresh for Kimi Coding OAuth tokens.
|
|
* Uses custom X-Msh-* headers required by Kimi OAuth API.
|
|
*/
|
|
export async function refreshKimiCodingToken(refreshToken, log, proxyConfig: unknown = null) {
|
|
const endpoint = PROVIDERS["kimi-coding"]?.refreshUrl || PROVIDERS["kimi-coding"]?.tokenUrl;
|
|
if (!endpoint) {
|
|
log?.warn?.("TOKEN_REFRESH", "No refresh URL configured for Kimi Coding");
|
|
return null;
|
|
}
|
|
|
|
// Generate device info for headers (same as OAuth flow)
|
|
const deviceId = "kimi-refresh-" + Date.now();
|
|
const platform = "omniroute";
|
|
const version = "2.1.2";
|
|
const deviceModel =
|
|
typeof process !== "undefined" ? `${process.platform} ${process.arch}` : "unknown";
|
|
|
|
try {
|
|
const params = new URLSearchParams({
|
|
grant_type: "refresh_token",
|
|
refresh_token: refreshToken,
|
|
client_id: PROVIDERS["kimi-coding"]?.clientId || "",
|
|
});
|
|
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch(endpoint, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
Accept: "application/json",
|
|
"X-Msh-Platform": platform,
|
|
"X-Msh-Version": version,
|
|
"X-Msh-Device-Model": deviceModel,
|
|
"X-Msh-Device-Id": deviceId,
|
|
},
|
|
body: params,
|
|
})
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
log?.error?.("TOKEN_REFRESH", "Failed to refresh Kimi Coding token", {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const tokens = await response.json();
|
|
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Kimi Coding token", {
|
|
hasNewAccessToken: !!tokens.access_token,
|
|
hasNewRefreshToken: !!tokens.refresh_token,
|
|
expiresIn: tokens.expires_in,
|
|
});
|
|
|
|
return {
|
|
accessToken: tokens.access_token,
|
|
refreshToken: tokens.refresh_token || refreshToken,
|
|
expiresIn: tokens.expires_in,
|
|
tokenType: tokens.token_type,
|
|
scope: tokens.scope,
|
|
};
|
|
} catch (error) {
|
|
log?.error?.("TOKEN_REFRESH", `Network error refreshing Kimi Coding token: ${error.message}`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Specialized refresh for Claude OAuth tokens
|
|
*/
|
|
export async function refreshClaudeOAuthToken(refreshToken, log, proxyConfig: unknown = null) {
|
|
try {
|
|
// Standard OAuth2 token refresh uses form-urlencoded (not JSON)
|
|
const params = buildFormParams({
|
|
grant_type: "refresh_token",
|
|
refresh_token: refreshToken,
|
|
client_id: PROVIDERS.claude.clientId,
|
|
});
|
|
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch(OAUTH_ENDPOINTS.anthropic.token, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
Accept: "application/json",
|
|
"anthropic-beta": "oauth-2025-04-20",
|
|
},
|
|
body: params.toString(),
|
|
})
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
log?.error?.("TOKEN_REFRESH", "Failed to refresh Claude OAuth token", {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const tokens = await response.json();
|
|
|
|
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Claude OAuth token", {
|
|
hasNewAccessToken: !!tokens.access_token,
|
|
hasNewRefreshToken: !!tokens.refresh_token,
|
|
expiresIn: tokens.expires_in,
|
|
});
|
|
|
|
return {
|
|
accessToken: tokens.access_token,
|
|
refreshToken: tokens.refresh_token || refreshToken,
|
|
expiresIn: tokens.expires_in,
|
|
};
|
|
} catch (error) {
|
|
log?.error?.("TOKEN_REFRESH", `Network error refreshing Claude token: ${error.message}`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Specialized refresh for Google providers (Gemini, Antigravity)
|
|
*/
|
|
export async function refreshGoogleToken(
|
|
refreshToken,
|
|
clientId,
|
|
clientSecret,
|
|
log,
|
|
proxyConfig: unknown = null
|
|
) {
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch(OAUTH_ENDPOINTS.google.token, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
Accept: "application/json",
|
|
},
|
|
body: buildFormParams({
|
|
grant_type: "refresh_token",
|
|
refresh_token: refreshToken,
|
|
client_id: clientId,
|
|
client_secret: clientSecret,
|
|
}),
|
|
})
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
log?.error?.("TOKEN_REFRESH", "Failed to refresh Google token", {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const tokens = await response.json();
|
|
|
|
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Google token", {
|
|
hasNewAccessToken: !!tokens.access_token,
|
|
hasNewRefreshToken: !!tokens.refresh_token,
|
|
expiresIn: tokens.expires_in,
|
|
});
|
|
|
|
return {
|
|
accessToken: tokens.access_token,
|
|
refreshToken: tokens.refresh_token || refreshToken,
|
|
expiresIn: tokens.expires_in,
|
|
};
|
|
}
|
|
|
|
export async function refreshQwenToken(refreshToken, log, proxyConfig: unknown = null) {
|
|
const endpoint = OAUTH_ENDPOINTS.qwen.token;
|
|
|
|
try {
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch(endpoint, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
Accept: "application/json",
|
|
},
|
|
body: buildFormParams({
|
|
grant_type: "refresh_token",
|
|
refresh_token: refreshToken,
|
|
client_id: PROVIDERS.qwen.clientId,
|
|
}),
|
|
})
|
|
);
|
|
|
|
if (response.status === 200) {
|
|
const tokens = await response.json();
|
|
|
|
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Qwen token", {
|
|
hasNewAccessToken: !!tokens.access_token,
|
|
hasNewRefreshToken: !!tokens.refresh_token,
|
|
expiresIn: tokens.expires_in,
|
|
});
|
|
|
|
return {
|
|
accessToken: tokens.access_token,
|
|
refreshToken: tokens.refresh_token || refreshToken,
|
|
expiresIn: tokens.expires_in,
|
|
providerSpecificData: tokens.resource_url
|
|
? { resourceUrl: tokens.resource_url }
|
|
: undefined,
|
|
};
|
|
} else {
|
|
const errorText = await response.text().catch(() => "");
|
|
|
|
// Detect unrecoverable invalid_request (expired/revoked refresh token or bad client_id)
|
|
let errorCode = null;
|
|
try {
|
|
const parsed = JSON.parse(errorText);
|
|
errorCode = parsed?.error;
|
|
} catch {
|
|
// not JSON, ignore
|
|
}
|
|
|
|
if (errorCode === "invalid_request") {
|
|
log?.error?.(
|
|
"TOKEN_REFRESH",
|
|
"Qwen refresh token is invalid or expired. Re-authentication required.",
|
|
{
|
|
status: response.status,
|
|
}
|
|
);
|
|
return { error: "invalid_request" };
|
|
}
|
|
|
|
log?.warn?.("TOKEN_REFRESH", `Error with Qwen endpoint`, {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
}
|
|
} catch (error) {
|
|
log?.warn?.("TOKEN_REFRESH", `Network error trying Qwen endpoint`, {
|
|
error: error.message,
|
|
});
|
|
}
|
|
|
|
log?.error?.("TOKEN_REFRESH", "Failed to refresh Qwen token");
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Specialized refresh for Codex (OpenAI) OAuth tokens.
|
|
* OpenAI uses rotating (one-time-use) refresh tokens.
|
|
* Returns { error: 'refresh_token_reused' } when the token has already been consumed,
|
|
* so callers can stop retrying and request re-authentication.
|
|
*/
|
|
export async function refreshCodexToken(refreshToken, log, proxyConfig: unknown = null) {
|
|
try {
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch(OAUTH_ENDPOINTS.openai.token, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
Accept: "application/json",
|
|
},
|
|
body: buildFormParams({
|
|
grant_type: "refresh_token",
|
|
refresh_token: refreshToken,
|
|
client_id: PROVIDERS.codex.clientId,
|
|
scope: "openid profile email offline_access",
|
|
}),
|
|
})
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
|
|
// Detect unrecoverable "refresh_token_reused" or "invalid_grant" error from OpenAI
|
|
// This means the token was already consumed or has expired.
|
|
// Retrying with the same token will never succeed.
|
|
let errorCode = null;
|
|
try {
|
|
const parsed = JSON.parse(errorText);
|
|
errorCode =
|
|
parsed?.error?.code || (typeof parsed?.error === "string" ? parsed.error : null);
|
|
} catch {
|
|
// not JSON, ignore
|
|
}
|
|
|
|
if (
|
|
errorCode === "refresh_token_reused" ||
|
|
errorCode === "invalid_grant" ||
|
|
errorCode === "token_expired" ||
|
|
errorCode === "invalid_token"
|
|
) {
|
|
log?.error?.(
|
|
"TOKEN_REFRESH",
|
|
"Codex refresh token already used or invalid. Re-authentication required.",
|
|
{
|
|
status: response.status,
|
|
errorCode,
|
|
}
|
|
);
|
|
return { error: "unrecoverable_refresh_error", code: errorCode };
|
|
}
|
|
|
|
log?.error?.("TOKEN_REFRESH", "Failed to refresh Codex token", {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const tokens = await response.json();
|
|
|
|
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Codex token", {
|
|
hasNewAccessToken: !!tokens.access_token,
|
|
hasNewRefreshToken: !!tokens.refresh_token,
|
|
expiresIn: tokens.expires_in,
|
|
});
|
|
|
|
return {
|
|
accessToken: tokens.access_token,
|
|
refreshToken: tokens.refresh_token || refreshToken,
|
|
expiresIn: tokens.expires_in,
|
|
};
|
|
} catch (error) {
|
|
log?.error?.("TOKEN_REFRESH", `Network error refreshing Codex token: ${error.message}`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Specialized refresh for Kiro (AWS CodeWhisperer) tokens
|
|
* Supports both AWS SSO OIDC (Builder ID/IDC) and Social Auth (Google/GitHub)
|
|
*/
|
|
export async function refreshKiroToken(
|
|
refreshToken,
|
|
providerSpecificData,
|
|
log,
|
|
proxyConfig: unknown = null
|
|
) {
|
|
try {
|
|
const authMethod = providerSpecificData?.authMethod;
|
|
const clientId = providerSpecificData?.clientId;
|
|
const clientSecret = providerSpecificData?.clientSecret;
|
|
const region = providerSpecificData?.region;
|
|
|
|
// AWS SSO OIDC (Builder ID or IDC)
|
|
// If clientId and clientSecret exist, assume AWS SSO OIDC (default to builder-id if authMethod not specified)
|
|
if (clientId && clientSecret) {
|
|
const endpoint = `https://oidc.${region || "us-east-1"}.amazonaws.com/token`;
|
|
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch(endpoint, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Accept: "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
clientId: clientId,
|
|
clientSecret: clientSecret,
|
|
refreshToken: refreshToken,
|
|
grantType: "refresh_token",
|
|
}),
|
|
})
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
log?.error?.("TOKEN_REFRESH", "Failed to refresh Kiro AWS token", {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const tokens = await response.json();
|
|
|
|
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Kiro AWS token", {
|
|
hasNewAccessToken: !!tokens.accessToken,
|
|
expiresIn: tokens.expiresIn,
|
|
});
|
|
|
|
return {
|
|
accessToken: tokens.accessToken,
|
|
refreshToken: tokens.refreshToken || refreshToken,
|
|
expiresIn: tokens.expiresIn,
|
|
};
|
|
}
|
|
|
|
// Social Auth (Google/GitHub) - use Kiro's refresh endpoint
|
|
const tokenUrl = PROVIDERS.kiro.tokenUrl;
|
|
if (!tokenUrl) {
|
|
log?.error?.("TOKEN_REFRESH", "Missing Kiro token endpoint");
|
|
return null;
|
|
}
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch(tokenUrl, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Accept: "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
refreshToken: refreshToken,
|
|
}),
|
|
})
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
log?.error?.("TOKEN_REFRESH", "Failed to refresh Kiro social token", {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const tokens = await response.json();
|
|
|
|
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Kiro social token", {
|
|
hasNewAccessToken: !!tokens.accessToken,
|
|
expiresIn: tokens.expiresIn,
|
|
});
|
|
|
|
return {
|
|
accessToken: tokens.accessToken,
|
|
refreshToken: tokens.refreshToken || refreshToken,
|
|
expiresIn: tokens.expiresIn,
|
|
};
|
|
} catch (error) {
|
|
log?.error?.("TOKEN_REFRESH", `Network error refreshing Kiro token: ${error.message}`);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Specialized refresh for Qoder OAuth tokens
|
|
*/
|
|
export async function refreshQoderToken(refreshToken, log, proxyConfig: unknown = null) {
|
|
if (!OAUTH_ENDPOINTS.qoder.token || !PROVIDERS.qoder.clientId || !PROVIDERS.qoder.clientSecret) {
|
|
log?.warn?.(
|
|
"TOKEN_REFRESH",
|
|
"Qoder OAuth refresh skipped: browser OAuth is not configured in this environment"
|
|
);
|
|
return null;
|
|
}
|
|
|
|
const basicAuth = btoa(`${PROVIDERS.qoder.clientId}:${PROVIDERS.qoder.clientSecret}`);
|
|
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch(OAUTH_ENDPOINTS.qoder.token, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
Accept: "application/json",
|
|
Authorization: `Basic ${basicAuth}`,
|
|
},
|
|
body: buildFormParams({
|
|
grant_type: "refresh_token",
|
|
refresh_token: refreshToken,
|
|
client_id: PROVIDERS.qoder.clientId,
|
|
client_secret: PROVIDERS.qoder.clientSecret,
|
|
}),
|
|
})
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
log?.error?.("TOKEN_REFRESH", "Failed to refresh Qoder token", {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const tokens = await response.json();
|
|
|
|
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Qoder token", {
|
|
hasNewAccessToken: !!tokens.access_token,
|
|
hasNewRefreshToken: !!tokens.refresh_token,
|
|
expiresIn: tokens.expires_in,
|
|
});
|
|
|
|
return {
|
|
accessToken: tokens.access_token,
|
|
refreshToken: tokens.refresh_token || refreshToken,
|
|
expiresIn: tokens.expires_in,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Specialized refresh for GitHub Copilot OAuth tokens
|
|
*/
|
|
export async function refreshGitHubToken(refreshToken, log, proxyConfig: unknown = null) {
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch(OAUTH_ENDPOINTS.github.token, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
Accept: "application/json",
|
|
},
|
|
body: buildFormParams({
|
|
grant_type: "refresh_token",
|
|
refresh_token: refreshToken,
|
|
client_id: PROVIDERS.github.clientId,
|
|
client_secret: PROVIDERS.github.clientSecret,
|
|
}),
|
|
})
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
log?.error?.("TOKEN_REFRESH", "Failed to refresh GitHub token", {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const tokens = await response.json();
|
|
|
|
log?.info?.("TOKEN_REFRESH", "Successfully refreshed GitHub token", {
|
|
hasNewAccessToken: !!tokens.access_token,
|
|
hasNewRefreshToken: !!tokens.refresh_token,
|
|
expiresIn: tokens.expires_in,
|
|
});
|
|
|
|
return {
|
|
accessToken: tokens.access_token,
|
|
refreshToken: tokens.refresh_token || refreshToken,
|
|
expiresIn: tokens.expires_in,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Refresh GitHub Copilot token using GitHub access token
|
|
*/
|
|
export async function refreshCopilotToken(githubAccessToken, log, proxyConfig: unknown = null) {
|
|
try {
|
|
const response = await runWithProxyContext(proxyConfig, () =>
|
|
fetch("https://api.github.com/copilot_internal/v2/token", {
|
|
headers: getGitHubCopilotRefreshHeaders(`token ${githubAccessToken}`),
|
|
})
|
|
);
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
log?.error?.("TOKEN_REFRESH", "Failed to refresh Copilot token", {
|
|
status: response.status,
|
|
error: errorText,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
const data = await response.json();
|
|
|
|
log?.info?.("TOKEN_REFRESH", "Successfully refreshed Copilot token", {
|
|
hasToken: !!data.token,
|
|
expiresAt: data.expires_at,
|
|
});
|
|
|
|
return {
|
|
token: data.token,
|
|
expiresAt: data.expires_at,
|
|
};
|
|
} catch (error) {
|
|
log?.error?.("TOKEN_REFRESH", "Error refreshing Copilot token", {
|
|
error: error.message,
|
|
});
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get access token for a specific provider (internal, does the actual work)
|
|
*/
|
|
async function _getAccessTokenInternal(provider, credentials, log, proxyConfig: unknown = null) {
|
|
switch (provider) {
|
|
case "gemini":
|
|
case "gemini-cli":
|
|
case "antigravity":
|
|
return await refreshGoogleToken(
|
|
credentials.refreshToken,
|
|
PROVIDERS[provider].clientId,
|
|
PROVIDERS[provider].clientSecret,
|
|
log,
|
|
proxyConfig
|
|
);
|
|
|
|
case "claude":
|
|
return await refreshClaudeOAuthToken(credentials.refreshToken, log, proxyConfig);
|
|
|
|
case "codex":
|
|
return await refreshCodexToken(credentials.refreshToken, log, proxyConfig);
|
|
|
|
case "qwen":
|
|
return await refreshQwenToken(credentials.refreshToken, log, proxyConfig);
|
|
|
|
case "qoder":
|
|
return await refreshQoderToken(credentials.refreshToken, log, proxyConfig);
|
|
|
|
case "github":
|
|
return await refreshGitHubToken(credentials.refreshToken, log, proxyConfig);
|
|
|
|
case "kiro":
|
|
case "amazon-q":
|
|
return await refreshKiroToken(
|
|
credentials.refreshToken,
|
|
credentials.providerSpecificData,
|
|
log,
|
|
proxyConfig
|
|
);
|
|
|
|
case "cline":
|
|
return await refreshClineToken(credentials.refreshToken, log, proxyConfig);
|
|
|
|
case "kimi-coding":
|
|
return await refreshKimiCodingToken(credentials.refreshToken, log, proxyConfig);
|
|
|
|
default:
|
|
// Fallback to generic OAuth refresh for unknown providers
|
|
return refreshAccessToken(provider, credentials.refreshToken, credentials, log, proxyConfig);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Whether a provider has a supported refresh path in this service.
|
|
*/
|
|
export function supportsTokenRefresh(provider) {
|
|
const explicitlySupported = new Set([
|
|
"gemini",
|
|
"gemini-cli",
|
|
"antigravity",
|
|
"claude",
|
|
"codex",
|
|
"qwen",
|
|
"qoder",
|
|
"github",
|
|
"kiro",
|
|
"amazon-q",
|
|
"cline",
|
|
"kimi-coding",
|
|
]);
|
|
if (explicitlySupported.has(provider)) return true;
|
|
const config = PROVIDERS[provider];
|
|
return !!(config?.refreshUrl || config?.tokenUrl);
|
|
}
|
|
|
|
/**
|
|
* Check if a refresh result indicates an unrecoverable error
|
|
* (e.g. the refresh token was already consumed and cannot be reused).
|
|
* Callers should stop retrying and request re-authentication.
|
|
*/
|
|
export function isUnrecoverableRefreshError(result) {
|
|
return (
|
|
result &&
|
|
typeof result === "object" &&
|
|
(result.error === "unrecoverable_refresh_error" ||
|
|
result.error === "refresh_token_reused" ||
|
|
result.error === "invalid_request" ||
|
|
result.error === "invalid_grant")
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Get access token for a specific provider (with deduplication).
|
|
* If a refresh is already in-flight for the same provider+token,
|
|
* subsequent calls share the existing promise instead of making
|
|
* parallel OAuth requests.
|
|
*/
|
|
export async function getAccessToken(provider, credentials, log, proxyConfig: unknown = null) {
|
|
if (!credentials || !credentials.refreshToken || typeof credentials.refreshToken !== "string") {
|
|
log?.warn?.("TOKEN_REFRESH", `No valid refresh token available for provider: ${provider}`);
|
|
return null;
|
|
}
|
|
|
|
const cacheKey = getRefreshCacheKey(provider, credentials.refreshToken);
|
|
|
|
// If a refresh is already in-flight, reuse it
|
|
if (refreshPromiseCache.has(cacheKey)) {
|
|
log?.info?.("TOKEN_REFRESH", `Reusing in-flight refresh for ${provider}`);
|
|
return refreshPromiseCache.get(cacheKey);
|
|
}
|
|
|
|
// Start a new refresh and cache the promise
|
|
const refreshPromise = _getAccessTokenInternal(provider, credentials, log, proxyConfig).finally(
|
|
() => {
|
|
refreshPromiseCache.delete(cacheKey);
|
|
}
|
|
);
|
|
|
|
refreshPromiseCache.set(cacheKey, refreshPromise);
|
|
return refreshPromise;
|
|
}
|
|
|
|
/**
|
|
* Refresh token by provider type (alias for getAccessToken)
|
|
* @deprecated Since v0.2.70 — use getAccessToken() directly.
|
|
* Still exported because open-sse/index.js and src/sse wrapper use it.
|
|
* Will be removed in a future major version.
|
|
*/
|
|
export const refreshTokenByProvider = getAccessToken;
|
|
|
|
/**
|
|
* Format credentials for provider
|
|
*/
|
|
export function formatProviderCredentials(provider, credentials, log) {
|
|
const config = PROVIDERS[provider];
|
|
if (!config) {
|
|
log?.warn?.("TOKEN_REFRESH", `No configuration found for provider: ${provider}`);
|
|
return null;
|
|
}
|
|
|
|
switch (provider) {
|
|
case "gemini":
|
|
return {
|
|
apiKey: credentials.apiKey,
|
|
accessToken: credentials.accessToken,
|
|
projectId: credentials.projectId,
|
|
};
|
|
|
|
case "claude":
|
|
return {
|
|
apiKey: credentials.apiKey,
|
|
accessToken: credentials.accessToken,
|
|
};
|
|
|
|
case "codex":
|
|
case "qwen":
|
|
case "qoder":
|
|
case "openai":
|
|
case "openrouter":
|
|
return {
|
|
apiKey: credentials.apiKey,
|
|
accessToken: credentials.accessToken,
|
|
};
|
|
|
|
case "antigravity":
|
|
case "gemini-cli":
|
|
return {
|
|
accessToken: credentials.accessToken,
|
|
refreshToken: credentials.refreshToken,
|
|
};
|
|
|
|
default:
|
|
return {
|
|
apiKey: credentials.apiKey,
|
|
accessToken: credentials.accessToken,
|
|
refreshToken: credentials.refreshToken,
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get all access tokens for a user
|
|
*/
|
|
export async function getAllAccessTokens(userInfo, log) {
|
|
const results = {};
|
|
|
|
if (userInfo.connections && Array.isArray(userInfo.connections)) {
|
|
for (const connection of userInfo.connections) {
|
|
if (connection.isActive && connection.provider) {
|
|
const token = await getAccessToken(
|
|
connection.provider,
|
|
{
|
|
refreshToken: connection.refreshToken,
|
|
},
|
|
log
|
|
);
|
|
|
|
if (token) {
|
|
results[connection.provider] = token;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return results;
|
|
}
|
|
|
|
/**
|
|
* Refresh token with retry and exponential backoff
|
|
* Retries on failure with increasing delay: 1s, 2s, 3s...
|
|
*
|
|
* Includes:
|
|
* - Per-provider circuit breaker (5 consecutive failures → 30min pause)
|
|
* - 30s timeout per refresh attempt to prevent hanging connections
|
|
*
|
|
* @param {function} refreshFn - Async function that returns token or null
|
|
* @param {number} maxRetries - Max retry attempts (default 3)
|
|
* @param {object} log - Logger instance (optional)
|
|
* @param {string} provider - Provider ID for circuit breaker tracking (optional)
|
|
* @returns {Promise<object|null>} Token result or null if all retries fail
|
|
*/
|
|
|
|
// ─── Circuit Breaker State ──────────────────────────────────────────────────
|
|
const _circuitBreaker: Record<string, { failures: number; blockedUntil: number }> = {};
|
|
const CIRCUIT_BREAKER_THRESHOLD = 5; // consecutive failures before tripping
|
|
const CIRCUIT_BREAKER_COOLDOWN = 30 * 60 * 1000; // 30 minutes
|
|
const REFRESH_TIMEOUT_MS = 30_000; // 30s max per refresh attempt
|
|
|
|
interface CircuitBreakerStatusEntry {
|
|
failures: number;
|
|
blocked: boolean;
|
|
blockedUntil: string | null;
|
|
remainingMs: number;
|
|
}
|
|
|
|
interface RefreshLoggerLike {
|
|
error?: (scope: string, message: string) => void;
|
|
warn?: (scope: string, message: string) => void;
|
|
}
|
|
|
|
/**
|
|
* Check if a provider is circuit-breaker blocked.
|
|
*/
|
|
export function isProviderBlocked(provider: string): boolean {
|
|
const state = _circuitBreaker[provider];
|
|
if (!state) return false;
|
|
if (!state.blockedUntil) return false;
|
|
if (state.blockedUntil > Date.now()) return true;
|
|
// Cooldown expired — reset
|
|
delete _circuitBreaker[provider];
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Get circuit breaker status for all providers (for diagnostics).
|
|
*/
|
|
export function getCircuitBreakerStatus(): Record<string, CircuitBreakerStatusEntry> {
|
|
const result: Record<string, CircuitBreakerStatusEntry> = {};
|
|
for (const [provider, state] of Object.entries(_circuitBreaker)) {
|
|
result[provider] = {
|
|
failures: state.failures,
|
|
blocked: state.blockedUntil > Date.now(),
|
|
blockedUntil:
|
|
state.blockedUntil > Date.now() ? new Date(state.blockedUntil).toISOString() : null,
|
|
remainingMs: Math.max(0, state.blockedUntil - Date.now()),
|
|
};
|
|
}
|
|
return result;
|
|
}
|
|
|
|
/**
|
|
* Record a successful refresh — resets circuit breaker for provider.
|
|
*/
|
|
function recordSuccess(provider: string) {
|
|
if (_circuitBreaker[provider]) {
|
|
delete _circuitBreaker[provider];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Record a failed refresh — increments circuit breaker counter.
|
|
*/
|
|
function recordFailure(provider: string, log: RefreshLoggerLike | null = null) {
|
|
if (!_circuitBreaker[provider]) {
|
|
_circuitBreaker[provider] = { failures: 0, blockedUntil: 0 };
|
|
}
|
|
_circuitBreaker[provider].failures++;
|
|
|
|
if (_circuitBreaker[provider].failures >= CIRCUIT_BREAKER_THRESHOLD) {
|
|
_circuitBreaker[provider].blockedUntil = Date.now() + CIRCUIT_BREAKER_COOLDOWN;
|
|
log?.error?.(
|
|
"TOKEN_REFRESH",
|
|
`🔴 Circuit breaker tripped for ${provider}: ${CIRCUIT_BREAKER_THRESHOLD} consecutive failures. ` +
|
|
`Blocked for ${CIRCUIT_BREAKER_COOLDOWN / 60000}min. Provider needs re-authentication.`
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Execute a function with a timeout.
|
|
*/
|
|
async function withTimeout<T>(fn: () => Promise<T>, timeoutMs: number): Promise<T | null> {
|
|
return await new Promise<T | null>((resolve, reject) => {
|
|
const timer = setTimeout(() => resolve(null), timeoutMs);
|
|
if (typeof timer === "object" && "unref" in timer) {
|
|
(timer as { unref?: () => void }).unref?.();
|
|
}
|
|
|
|
fn().then(
|
|
(result) => {
|
|
clearTimeout(timer);
|
|
resolve(result);
|
|
},
|
|
(error) => {
|
|
clearTimeout(timer);
|
|
reject(error);
|
|
}
|
|
);
|
|
});
|
|
}
|
|
|
|
export async function refreshWithRetry(
|
|
refreshFn,
|
|
maxRetries = 3,
|
|
log: RefreshLogger = null,
|
|
provider = "unknown"
|
|
) {
|
|
// Circuit breaker check
|
|
if (isProviderBlocked(provider)) {
|
|
log?.warn?.("TOKEN_REFRESH", `⚡ Circuit breaker active for ${provider}, skipping refresh`);
|
|
return null;
|
|
}
|
|
|
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
if (attempt > 0) {
|
|
const delay = attempt * 1000;
|
|
log?.debug?.("TOKEN_REFRESH", `Retry ${attempt}/${maxRetries} after ${delay}ms`);
|
|
await new Promise((r) => setTimeout(r, delay));
|
|
}
|
|
|
|
try {
|
|
const result = await withTimeout(refreshFn, REFRESH_TIMEOUT_MS);
|
|
if (result) {
|
|
recordSuccess(provider);
|
|
return result;
|
|
}
|
|
} catch (error) {
|
|
log?.warn?.("TOKEN_REFRESH", `Attempt ${attempt + 1}/${maxRetries} failed: ${error.message}`);
|
|
}
|
|
}
|
|
|
|
// All retries exhausted — record failure for circuit breaker
|
|
recordFailure(provider, log);
|
|
log?.error?.("TOKEN_REFRESH", `All ${maxRetries} retry attempts failed for ${provider}`);
|
|
return null;
|
|
}
|