Initial commit
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
import { getProviderConnections, validateApiKey, updateProviderConnection } from "@/lib/localDb";
|
||||
import { isAccountUnavailable, getUnavailableUntil } from "open-sse/services/accountFallback.js";
|
||||
import * as log from "../utils/logger.js";
|
||||
|
||||
/**
|
||||
* Get provider credentials from localDb
|
||||
* Filters out unavailable accounts and returns the highest priority available account
|
||||
* @param {string} provider - Provider name
|
||||
* @param {string|null} excludeConnectionId - Connection ID to exclude (for retry with next account)
|
||||
*/
|
||||
export async function getProviderCredentials(provider, excludeConnectionId = null) {
|
||||
const connections = await getProviderConnections({ provider, isActive: true });
|
||||
|
||||
if (connections.length === 0) {
|
||||
log.warn("AUTH", `No credentials for ${provider}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Filter out unavailable accounts and excluded connection
|
||||
const availableConnections = connections.filter(c => {
|
||||
if (excludeConnectionId && c.id === excludeConnectionId) return false;
|
||||
if (isAccountUnavailable(c.rateLimitedUntil)) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
if (availableConnections.length === 0) {
|
||||
log.warn("AUTH", `All ${connections.length} accounts for ${provider} unavailable`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const connection = availableConnections[0];
|
||||
|
||||
return {
|
||||
apiKey: connection.apiKey,
|
||||
accessToken: connection.accessToken,
|
||||
refreshToken: connection.refreshToken,
|
||||
projectId: connection.projectId,
|
||||
copilotToken: connection.providerSpecificData?.copilotToken,
|
||||
providerSpecificData: connection.providerSpecificData,
|
||||
connectionId: connection.id,
|
||||
// Include current status for optimization check
|
||||
testStatus: connection.testStatus,
|
||||
lastError: connection.lastError,
|
||||
rateLimitedUntil: connection.rateLimitedUntil
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark account as unavailable with cooldown
|
||||
*/
|
||||
export async function markAccountUnavailable(connectionId, cooldownMs, reason = "Provider error", errorCode = null, provider = null) {
|
||||
const rateLimitedUntil = getUnavailableUntil(cooldownMs);
|
||||
await updateProviderConnection(connectionId, {
|
||||
rateLimitedUntil,
|
||||
testStatus: "unavailable",
|
||||
lastError: reason,
|
||||
errorCode,
|
||||
lastErrorAt: new Date().toISOString()
|
||||
});
|
||||
// log.warn("AUTH", `Account ${connectionId.slice(0,8)} unavailable until ${rateLimitedUntil}`);
|
||||
|
||||
// Log to stderr for CLI to display
|
||||
if (provider && errorCode && reason) {
|
||||
console.error(`❌ ${provider} [${errorCode}]: ${reason}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear account error status (only if currently has error)
|
||||
* Optimized to avoid unnecessary DB updates
|
||||
*/
|
||||
export async function clearAccountError(connectionId, currentConnection) {
|
||||
// Only update if currently has error status
|
||||
const hasError = currentConnection.testStatus === "unavailable" ||
|
||||
currentConnection.lastError ||
|
||||
currentConnection.rateLimitedUntil;
|
||||
|
||||
if (!hasError) return; // Skip if already clean
|
||||
|
||||
await updateProviderConnection(connectionId, {
|
||||
testStatus: "active",
|
||||
lastError: null,
|
||||
lastErrorAt: null,
|
||||
rateLimitedUntil: null
|
||||
});
|
||||
log.info("AUTH", `Account ${connectionId.slice(0,8)} error cleared`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract API key from request headers
|
||||
*/
|
||||
export function extractApiKey(request) {
|
||||
const authHeader = request.headers.get("Authorization");
|
||||
if (authHeader?.startsWith("Bearer ")) {
|
||||
return authHeader.slice(7);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate API key (optional - for local use can skip)
|
||||
*/
|
||||
export async function isValidApiKey(apiKey) {
|
||||
if (!apiKey) return false;
|
||||
return await validateApiKey(apiKey);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Re-export from open-sse with localDb integration
|
||||
import { getModelAliases, getComboByName } from "@/lib/localDb";
|
||||
import { parseModel, resolveModelAliasFromMap, getModelInfoCore } from "open-sse/services/model.js";
|
||||
|
||||
export { parseModel };
|
||||
|
||||
/**
|
||||
* Resolve model alias from localDb
|
||||
*/
|
||||
export async function resolveModelAlias(alias) {
|
||||
const aliases = await getModelAliases();
|
||||
return resolveModelAliasFromMap(alias, aliases);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get full model info (parse or resolve)
|
||||
*/
|
||||
export async function getModelInfo(modelStr) {
|
||||
return getModelInfoCore(modelStr, getModelAliases);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if model is a combo and get models list
|
||||
* @returns {Promise<string[]|null>} Array of models or null if not a combo
|
||||
*/
|
||||
export async function getComboModels(modelStr) {
|
||||
// Only check if it's not in provider/model format
|
||||
if (modelStr.includes("/")) return null;
|
||||
|
||||
const combo = await getComboByName(modelStr);
|
||||
if (combo && combo.models && combo.models.length > 0) {
|
||||
return combo.models;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// Re-export from open-sse with local logger
|
||||
import * as log from "../utils/logger.js";
|
||||
import { updateProviderConnection } from "../../lib/localDb.js";
|
||||
import {
|
||||
TOKEN_EXPIRY_BUFFER_MS as BUFFER_MS,
|
||||
refreshAccessToken as _refreshAccessToken,
|
||||
refreshClaudeOAuthToken as _refreshClaudeOAuthToken,
|
||||
refreshGoogleToken as _refreshGoogleToken,
|
||||
refreshQwenToken as _refreshQwenToken,
|
||||
refreshCodexToken as _refreshCodexToken,
|
||||
refreshIflowToken as _refreshIflowToken,
|
||||
refreshGitHubToken as _refreshGitHubToken,
|
||||
refreshCopilotToken as _refreshCopilotToken,
|
||||
getAccessToken as _getAccessToken,
|
||||
refreshTokenByProvider as _refreshTokenByProvider,
|
||||
formatProviderCredentials as _formatProviderCredentials,
|
||||
getAllAccessTokens as _getAllAccessTokens
|
||||
} from "open-sse/services/tokenRefresh.js";
|
||||
|
||||
export const TOKEN_EXPIRY_BUFFER_MS = BUFFER_MS;
|
||||
|
||||
// Wrap functions with local logger
|
||||
export const refreshAccessToken = (provider, refreshToken, credentials) =>
|
||||
_refreshAccessToken(provider, refreshToken, credentials, log);
|
||||
|
||||
export const refreshClaudeOAuthToken = (refreshToken) =>
|
||||
_refreshClaudeOAuthToken(refreshToken, log);
|
||||
|
||||
export const refreshGoogleToken = (refreshToken, clientId, clientSecret) =>
|
||||
_refreshGoogleToken(refreshToken, clientId, clientSecret, log);
|
||||
|
||||
export const refreshQwenToken = (refreshToken) =>
|
||||
_refreshQwenToken(refreshToken, log);
|
||||
|
||||
export const refreshCodexToken = (refreshToken) =>
|
||||
_refreshCodexToken(refreshToken, log);
|
||||
|
||||
export const refreshIflowToken = (refreshToken) =>
|
||||
_refreshIflowToken(refreshToken, log);
|
||||
|
||||
export const refreshGitHubToken = (refreshToken) =>
|
||||
_refreshGitHubToken(refreshToken, log);
|
||||
|
||||
export const refreshCopilotToken = (githubAccessToken) =>
|
||||
_refreshCopilotToken(githubAccessToken, log);
|
||||
|
||||
export const getAccessToken = (provider, credentials) =>
|
||||
_getAccessToken(provider, credentials, log);
|
||||
|
||||
export const refreshTokenByProvider = (provider, credentials) =>
|
||||
_refreshTokenByProvider(provider, credentials, log);
|
||||
|
||||
export const formatProviderCredentials = (provider, credentials) =>
|
||||
_formatProviderCredentials(provider, credentials, log);
|
||||
|
||||
export const getAllAccessTokens = (userInfo) =>
|
||||
_getAllAccessTokens(userInfo, log);
|
||||
|
||||
// Local-specific: Update credentials in localDb
|
||||
export async function updateProviderCredentials(connectionId, newCredentials) {
|
||||
try {
|
||||
const updates = {};
|
||||
|
||||
if (newCredentials.accessToken) {
|
||||
updates.accessToken = newCredentials.accessToken;
|
||||
}
|
||||
if (newCredentials.refreshToken) {
|
||||
updates.refreshToken = newCredentials.refreshToken;
|
||||
}
|
||||
if (newCredentials.expiresIn) {
|
||||
updates.expiresAt = new Date(Date.now() + newCredentials.expiresIn * 1000).toISOString();
|
||||
updates.expiresIn = newCredentials.expiresIn;
|
||||
}
|
||||
if (newCredentials.providerSpecificData) {
|
||||
updates.providerSpecificData = newCredentials.providerSpecificData;
|
||||
}
|
||||
|
||||
const result = await updateProviderConnection(connectionId, updates);
|
||||
log.info("TOKEN_REFRESH", "Credentials updated in localDb", {
|
||||
connectionId,
|
||||
success: !!result
|
||||
});
|
||||
return !!result;
|
||||
} catch (error) {
|
||||
log.error("TOKEN_REFRESH", "Error updating credentials in localDb", {
|
||||
connectionId,
|
||||
error: error.message,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Local-specific: Check and refresh token proactively
|
||||
export async function checkAndRefreshToken(provider, credentials) {
|
||||
let updatedCredentials = { ...credentials };
|
||||
|
||||
// Check regular token expiry
|
||||
if (updatedCredentials.expiresAt) {
|
||||
const expiresAt = new Date(updatedCredentials.expiresAt).getTime();
|
||||
const now = Date.now();
|
||||
|
||||
if (expiresAt - now < TOKEN_EXPIRY_BUFFER_MS) {
|
||||
log.info("TOKEN_REFRESH", "Token expiring soon, refreshing proactively", {
|
||||
provider,
|
||||
expiresIn: Math.round((expiresAt - now) / 1000)
|
||||
});
|
||||
|
||||
const newCredentials = await getAccessToken(provider, updatedCredentials);
|
||||
if (newCredentials && newCredentials.accessToken) {
|
||||
await updateProviderCredentials(updatedCredentials.connectionId, newCredentials);
|
||||
|
||||
updatedCredentials = {
|
||||
...updatedCredentials,
|
||||
accessToken: newCredentials.accessToken,
|
||||
refreshToken: newCredentials.refreshToken || updatedCredentials.refreshToken,
|
||||
expiresAt: newCredentials.expiresIn
|
||||
? new Date(Date.now() + newCredentials.expiresIn * 1000).toISOString()
|
||||
: updatedCredentials.expiresAt
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check GitHub copilot token expiry
|
||||
if (provider === "github" && updatedCredentials.providerSpecificData?.copilotTokenExpiresAt) {
|
||||
const copilotExpiresAt = updatedCredentials.providerSpecificData.copilotTokenExpiresAt * 1000;
|
||||
const now = Date.now();
|
||||
|
||||
if (copilotExpiresAt - now < TOKEN_EXPIRY_BUFFER_MS) {
|
||||
log.info("TOKEN_REFRESH", "Copilot token expiring soon, refreshing proactively", {
|
||||
provider,
|
||||
expiresIn: Math.round((copilotExpiresAt - now) / 1000)
|
||||
});
|
||||
|
||||
const copilotToken = await refreshCopilotToken(updatedCredentials.accessToken);
|
||||
if (copilotToken) {
|
||||
await updateProviderCredentials(updatedCredentials.connectionId, {
|
||||
providerSpecificData: {
|
||||
...updatedCredentials.providerSpecificData,
|
||||
copilotToken: copilotToken.token,
|
||||
copilotTokenExpiresAt: copilotToken.expiresAt
|
||||
}
|
||||
});
|
||||
|
||||
updatedCredentials.providerSpecificData = {
|
||||
...updatedCredentials.providerSpecificData,
|
||||
copilotToken: copilotToken.token,
|
||||
copilotTokenExpiresAt: copilotToken.expiresAt
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return updatedCredentials;
|
||||
}
|
||||
|
||||
// Local-specific: Refresh GitHub and Copilot tokens together
|
||||
export async function refreshGitHubAndCopilotTokens(credentials) {
|
||||
const newGitHubCredentials = await refreshGitHubToken(credentials.refreshToken);
|
||||
if (newGitHubCredentials?.accessToken) {
|
||||
const copilotToken = await refreshCopilotToken(newGitHubCredentials.accessToken);
|
||||
if (copilotToken) {
|
||||
return {
|
||||
...newGitHubCredentials,
|
||||
providerSpecificData: {
|
||||
copilotToken: copilotToken.token,
|
||||
copilotTokenExpiresAt: copilotToken.expiresAt
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
return newGitHubCredentials;
|
||||
}
|
||||
Reference in New Issue
Block a user