mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-07-26 09:52:11 +03:00
fix(github): keep Copilot access-token sessions active
GitHub Copilot device-flow accounts may have a GitHub access token and short-lived Copilot token without a refresh token. The proactive health check was treating that as terminal no_refresh_token and marking the connection expired minutes after login. Keep those sessions active, clear stale no_refresh_token state, and refresh the Copilot sub-token when needed.\n\nTests:\n- npx eslint src/lib/tokenHealthCheck.ts tests/unit/token-health-no-refresh-token-expired-5326.test.ts\n- DISABLE_SQLITE_AUTO_BACKUP=true node --import tsx/esm --test tests/unit/token-health-no-refresh-token-expired-5326.test.ts tests/unit/token-health-check.test.ts tests/unit/token-health-check-circuit-breaker.test.ts tests/unit/token-refresh-service.test.ts tests/unit/token-refresh-route-service.test.ts tests/unit/executor-github.test.ts\n- npm run typecheck:core\n- npm run build
This commit is contained in:
@@ -76,6 +76,35 @@ function getEffectiveTokenExpiryMs(conn: any): number {
|
|||||||
return Number.isFinite(expiryMs) ? expiryMs : 0;
|
return Number.isFinite(expiryMs) ? expiryMs : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const TOKEN_EXPIRY_BUFFER = 5 * 60 * 1000; // 5 minutes
|
||||||
|
|
||||||
|
function getCopilotTokenExpiryMs(expiresAt: unknown): number {
|
||||||
|
if (typeof expiresAt === "number" && Number.isFinite(expiresAt)) {
|
||||||
|
return expiresAt < 1e12 ? expiresAt * 1000 : expiresAt;
|
||||||
|
}
|
||||||
|
if (typeof expiresAt === "string" && expiresAt.trim()) {
|
||||||
|
const parsed = new Date(expiresAt).getTime();
|
||||||
|
return Number.isFinite(parsed) ? parsed : 0;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isGitHubAccessTokenOnlyConnection(conn: any): boolean {
|
||||||
|
return (
|
||||||
|
String(conn?.provider || "").toLowerCase() === "github" &&
|
||||||
|
typeof conn?.accessToken === "string" &&
|
||||||
|
conn.accessToken.trim().length > 0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function canClearGitHubNoRefreshTokenState(conn: any): boolean {
|
||||||
|
return (
|
||||||
|
!conn?.testStatus ||
|
||||||
|
conn.testStatus === "active" ||
|
||||||
|
(conn.testStatus === "expired" && conn.errorCode === "no_refresh_token")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Refresh circuit breaker ───────────────────────────────────────────────
|
// ── Refresh circuit breaker ───────────────────────────────────────────────
|
||||||
// A refresh that returns null (network blip, dead proxy, unclassified error)
|
// A refresh that returns null (network blip, dead proxy, unclassified error)
|
||||||
// leaves the connection active, so the next 60s sweep retries immediately —
|
// leaves the connection active, so the next 60s sweep retries immediately —
|
||||||
@@ -248,8 +277,7 @@ export function clearHealthCheckLogCache() {
|
|||||||
|
|
||||||
declare global {
|
declare global {
|
||||||
var __omnirouteTokenHC:
|
var __omnirouteTokenHC:
|
||||||
| { initialized: boolean; interval: ReturnType<typeof setInterval> | null }
|
{ initialized: boolean; interval: ReturnType<typeof setInterval> | null } | undefined;
|
||||||
| undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getHCState() {
|
function getHCState() {
|
||||||
@@ -342,6 +370,86 @@ export async function checkConnection(conn) {
|
|||||||
if (intervalMin <= 0) return;
|
if (intervalMin <= 0) return;
|
||||||
if (!conn.isActive) return;
|
if (!conn.isActive) return;
|
||||||
if (!conn.refreshToken || typeof conn.refreshToken !== "string") {
|
if (!conn.refreshToken || typeof conn.refreshToken !== "string") {
|
||||||
|
if (isGitHubAccessTokenOnlyConnection(conn)) {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const providerSpecificData = conn.providerSpecificData || {};
|
||||||
|
const hasCopilotToken =
|
||||||
|
typeof providerSpecificData.copilotToken === "string" &&
|
||||||
|
providerSpecificData.copilotToken.trim().length > 0;
|
||||||
|
const copilotExpiresAtMs = getCopilotTokenExpiryMs(
|
||||||
|
providerSpecificData.copilotTokenExpiresAt
|
||||||
|
);
|
||||||
|
const copilotAboutToExpire =
|
||||||
|
!hasCopilotToken ||
|
||||||
|
!copilotExpiresAtMs ||
|
||||||
|
copilotExpiresAtMs - Date.now() < TOKEN_EXPIRY_BUFFER;
|
||||||
|
|
||||||
|
let refreshedProviderSpecificData: Record<string, unknown> | null = null;
|
||||||
|
if (copilotAboutToExpire) {
|
||||||
|
const hideLogs = await shouldHideLogs();
|
||||||
|
const proxyResolution = await resolveProxyForConnection(conn.id);
|
||||||
|
const proxyConfig = extractResolvedProxyConfig(proxyResolution);
|
||||||
|
const healthCheckLog = {
|
||||||
|
info: (tag: string, msg: string) => {
|
||||||
|
if (!hideLogs) console.log(LOG_PREFIX, `[${tag}]`, msg);
|
||||||
|
},
|
||||||
|
warn: (tag: string, msg: string) => {
|
||||||
|
if (!hideLogs) console.warn(LOG_PREFIX, `[${tag}]`, msg);
|
||||||
|
},
|
||||||
|
error: (tag: string, msg: string, extra?: Record<string, unknown>) => {
|
||||||
|
if (!hideLogs) console.error(LOG_PREFIX, `[${tag}]`, msg, extra || "");
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const copilotResult = await refreshCopilotToken(
|
||||||
|
conn.accessToken,
|
||||||
|
healthCheckLog,
|
||||||
|
proxyConfig
|
||||||
|
);
|
||||||
|
if (copilotResult?.token) {
|
||||||
|
refreshedProviderSpecificData = {
|
||||||
|
...providerSpecificData,
|
||||||
|
copilotToken: copilotResult.token,
|
||||||
|
copilotTokenExpiresAt: copilotResult.expiresAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (canClearGitHubNoRefreshTokenState(conn)) {
|
||||||
|
await updateProviderConnection(conn.id, {
|
||||||
|
lastHealthCheckAt: now,
|
||||||
|
testStatus: "active",
|
||||||
|
lastError:
|
||||||
|
copilotAboutToExpire && !refreshedProviderSpecificData
|
||||||
|
? "Health check: Copilot token refresh failed"
|
||||||
|
: null,
|
||||||
|
lastErrorAt: copilotAboutToExpire && !refreshedProviderSpecificData ? now : null,
|
||||||
|
lastErrorType:
|
||||||
|
copilotAboutToExpire && !refreshedProviderSpecificData ? "token_refresh_failed" : null,
|
||||||
|
lastErrorSource: copilotAboutToExpire && !refreshedProviderSpecificData ? "oauth" : null,
|
||||||
|
errorCode:
|
||||||
|
copilotAboutToExpire && !refreshedProviderSpecificData ? "refresh_failed" : null,
|
||||||
|
expiredRetryCount: null,
|
||||||
|
expiredRetryAt: null,
|
||||||
|
...(refreshedProviderSpecificData
|
||||||
|
? { providerSpecificData: refreshedProviderSpecificData }
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await updateProviderConnection(conn.id, {
|
||||||
|
lastHealthCheckAt: now,
|
||||||
|
...(refreshedProviderSpecificData
|
||||||
|
? { providerSpecificData: refreshedProviderSpecificData }
|
||||||
|
: {}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
log(
|
||||||
|
`${LOG_PREFIX} ${conn.provider}/${getConnectionLogLabel(conn)} has no refresh token but has a GitHub access token; keeping connection active`
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// #5326: a refresh-CAPABLE provider (e.g. antigravity/gemini) with no usable
|
// #5326: a refresh-CAPABLE provider (e.g. antigravity/gemini) with no usable
|
||||||
// refresh token can never self-heal via the sweep — it genuinely needs re-auth.
|
// refresh token can never self-heal via the sweep — it genuinely needs re-auth.
|
||||||
// Silently skipping here left the row at testStatus="active" while the dashboard
|
// Silently skipping here left the row at testStatus="active" while the dashboard
|
||||||
@@ -352,8 +460,7 @@ export async function checkConnection(conn) {
|
|||||||
// - connections already in a terminal/specific state (expired/banned/credits_exhausted)
|
// - connections already in a terminal/specific state (expired/banned/credits_exhausted)
|
||||||
// - transient cooldown state (unavailable) owned by the request path
|
// - transient cooldown state (unavailable) owned by the request path
|
||||||
const refreshCapableNeedsReauth =
|
const refreshCapableNeedsReauth =
|
||||||
supportsTokenRefresh(conn.provider) &&
|
supportsTokenRefresh(conn.provider) && (!conn.testStatus || conn.testStatus === "active");
|
||||||
(!conn.testStatus || conn.testStatus === "active");
|
|
||||||
if (refreshCapableNeedsReauth) {
|
if (refreshCapableNeedsReauth) {
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
await updateProviderConnection(conn.id, {
|
await updateProviderConnection(conn.id, {
|
||||||
@@ -401,7 +508,6 @@ export async function checkConnection(conn) {
|
|||||||
// Prefer expiry-driven refresh when the provider returns a concrete expiry timestamp.
|
// Prefer expiry-driven refresh when the provider returns a concrete expiry timestamp.
|
||||||
// Rotating-token providers such as Codex should not be refreshed on a fixed hourly
|
// Rotating-token providers such as Codex should not be refreshed on a fixed hourly
|
||||||
// cadence while the access token is still valid for days.
|
// cadence while the access token is still valid for days.
|
||||||
const TOKEN_EXPIRY_BUFFER = 5 * 60 * 1000; // 5 minutes
|
|
||||||
const tokenExpiresAt = getEffectiveTokenExpiryMs(conn);
|
const tokenExpiresAt = getEffectiveTokenExpiryMs(conn);
|
||||||
const hasKnownExpiry = tokenExpiresAt > 0;
|
const hasKnownExpiry = tokenExpiresAt > 0;
|
||||||
const isAboutToExpire = hasKnownExpiry && tokenExpiresAt - Date.now() < TOKEN_EXPIRY_BUFFER;
|
const isAboutToExpire = hasKnownExpiry && tokenExpiresAt - Date.now() < TOKEN_EXPIRY_BUFFER;
|
||||||
|
|||||||
@@ -21,8 +21,12 @@ async function resetStorage() {
|
|||||||
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
} catch (error: any) {
|
} catch (error: unknown) {
|
||||||
if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) {
|
const code =
|
||||||
|
error && typeof error === "object" && "code" in error
|
||||||
|
? (error as { code?: unknown }).code
|
||||||
|
: null;
|
||||||
|
if ((code === "EBUSY" || code === "EPERM") && attempt < 9) {
|
||||||
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
|
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
|
||||||
} else {
|
} else {
|
||||||
throw error;
|
throw error;
|
||||||
@@ -32,6 +36,11 @@ async function resetStorage() {
|
|||||||
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
|
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getCreatedConnectionId(connection: { id?: unknown }): string {
|
||||||
|
assert.equal(typeof connection.id, "string");
|
||||||
|
return connection.id;
|
||||||
|
}
|
||||||
|
|
||||||
test.after(async () => {
|
test.after(async () => {
|
||||||
core.resetDbInstance();
|
core.resetDbInstance();
|
||||||
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
||||||
@@ -58,7 +67,7 @@ test("checkConnection marks refresh-capable provider with no refresh token as ex
|
|||||||
|
|
||||||
await tokenHealthCheck.checkConnection(connection);
|
await tokenHealthCheck.checkConnection(connection);
|
||||||
|
|
||||||
const updated = await providersDb.getProviderConnectionById((connection as any).id);
|
const updated = await providersDb.getProviderConnectionById(getCreatedConnectionId(connection));
|
||||||
assert.equal(updated?.testStatus, "expired");
|
assert.equal(updated?.testStatus, "expired");
|
||||||
assert.equal(updated?.errorCode, "no_refresh_token");
|
assert.equal(updated?.errorCode, "no_refresh_token");
|
||||||
assert.ok(updated?.lastHealthCheckAt);
|
assert.ok(updated?.lastHealthCheckAt);
|
||||||
@@ -85,7 +94,7 @@ test("checkConnection leaves a connection WITH a refresh token untouched (#5326)
|
|||||||
|
|
||||||
await tokenHealthCheck.checkConnection(connection);
|
await tokenHealthCheck.checkConnection(connection);
|
||||||
|
|
||||||
const updated = await providersDb.getProviderConnectionById((connection as any).id);
|
const updated = await providersDb.getProviderConnectionById(getCreatedConnectionId(connection));
|
||||||
assert.equal(updated?.testStatus, "active");
|
assert.equal(updated?.testStatus, "active");
|
||||||
assert.notEqual(updated?.errorCode, "no_refresh_token");
|
assert.notEqual(updated?.errorCode, "no_refresh_token");
|
||||||
});
|
});
|
||||||
@@ -108,7 +117,60 @@ test("checkConnection leaves a non-refresh provider with no refresh token untouc
|
|||||||
|
|
||||||
await tokenHealthCheck.checkConnection(connection);
|
await tokenHealthCheck.checkConnection(connection);
|
||||||
|
|
||||||
const updated = await providersDb.getProviderConnectionById((connection as any).id);
|
const updated = await providersDb.getProviderConnectionById(getCreatedConnectionId(connection));
|
||||||
assert.equal(updated?.testStatus, "active");
|
assert.equal(updated?.testStatus, "active");
|
||||||
assert.notEqual(updated?.errorCode, "no_refresh_token");
|
assert.notEqual(updated?.errorCode, "no_refresh_token");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("checkConnection keeps GitHub Copilot access-token-only connections active", async () => {
|
||||||
|
await resetStorage();
|
||||||
|
|
||||||
|
const connection = await providersDb.createProviderConnection({
|
||||||
|
provider: "github",
|
||||||
|
authType: "oauth",
|
||||||
|
name: "GitHub Access Token Account",
|
||||||
|
accessToken: "github-access-token",
|
||||||
|
refreshToken: null,
|
||||||
|
providerSpecificData: {
|
||||||
|
copilotToken: "copilot-token",
|
||||||
|
copilotTokenExpiresAt: Math.floor((Date.now() + 60 * 60 * 1000) / 1000),
|
||||||
|
},
|
||||||
|
testStatus: "active",
|
||||||
|
isActive: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await tokenHealthCheck.checkConnection(connection);
|
||||||
|
|
||||||
|
const updated = await providersDb.getProviderConnectionById(getCreatedConnectionId(connection));
|
||||||
|
assert.equal(updated?.testStatus, "active");
|
||||||
|
assert.notEqual(updated?.errorCode, "no_refresh_token");
|
||||||
|
assert.ok(updated?.lastHealthCheckAt);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("checkConnection clears stale no_refresh_token state for usable GitHub Copilot connections", async () => {
|
||||||
|
await resetStorage();
|
||||||
|
|
||||||
|
const connection = await providersDb.createProviderConnection({
|
||||||
|
provider: "github",
|
||||||
|
authType: "oauth",
|
||||||
|
name: "GitHub False Expired Account",
|
||||||
|
accessToken: "github-access-token",
|
||||||
|
refreshToken: null,
|
||||||
|
providerSpecificData: {
|
||||||
|
copilotToken: "copilot-token",
|
||||||
|
copilotTokenExpiresAt: Math.floor((Date.now() + 60 * 60 * 1000) / 1000),
|
||||||
|
},
|
||||||
|
testStatus: "expired",
|
||||||
|
errorCode: "no_refresh_token",
|
||||||
|
lastError: "No refresh token available — re-authenticate this account.",
|
||||||
|
isActive: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await tokenHealthCheck.checkConnection(connection);
|
||||||
|
|
||||||
|
const updated = await providersDb.getProviderConnectionById(getCreatedConnectionId(connection));
|
||||||
|
assert.equal(updated?.testStatus, "active");
|
||||||
|
assert.equal(updated?.errorCode ?? null, null);
|
||||||
|
assert.equal(updated?.lastError ?? null, null);
|
||||||
|
assert.ok(updated?.lastHealthCheckAt);
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user