mirror of
https://github.com/Wei-Shaw/claude-relay-service.git
synced 2026-01-23 00:53:33 +00:00
Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b18a1226d | ||
|
|
0b2372abab | ||
|
|
8aca1f9dd1 | ||
|
|
b63f2f78fc | ||
|
|
c971d239ff | ||
|
|
01d6e30e82 | ||
|
|
5fd78b6411 | ||
|
|
9ad5c85c2c | ||
|
|
279cd72f23 | ||
|
|
81e89d2dc4 | ||
|
|
c38b3d2a78 | ||
|
|
e8e6f972b4 | ||
|
|
d3155b82ea | ||
|
|
02018e10f3 | ||
|
|
e17cd1d61b | ||
|
|
b9d53647bd | ||
|
|
a872529b2e | ||
|
|
dfee7be944 | ||
|
|
392601efd5 | ||
|
|
249e256360 | ||
|
|
876b126ce0 | ||
|
|
6ec4f4bf5b | ||
|
|
326adaaeca | ||
|
|
d89344ad87 | ||
|
|
68f003976e | ||
|
|
63a7c2514b |
6357
pnpm-lock.yaml
generated
Normal file
6357
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -22,6 +22,54 @@ const ProxyHelper = require('../utils/proxyHelper')
|
||||
// 工具函数
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 构建 Gemini API URL
|
||||
* 兼容新旧 baseUrl 格式:
|
||||
* - 新格式(以 /models 结尾): https://xxx.com/v1beta/models -> 直接拼接 /{model}:action
|
||||
* - 旧格式(不以 /models 结尾): https://xxx.com -> 拼接 /v1beta/models/{model}:action
|
||||
*
|
||||
* @param {string} baseUrl - 账户配置的基础地址
|
||||
* @param {string} model - 模型名称
|
||||
* @param {string} action - API 动作 (generateContent, streamGenerateContent, countTokens)
|
||||
* @param {string} apiKey - API Key
|
||||
* @param {object} options - 额外选项 { stream: boolean, listModels: boolean }
|
||||
* @returns {string} 完整的 API URL
|
||||
*/
|
||||
function buildGeminiApiUrl(baseUrl, model, action, apiKey, options = {}) {
|
||||
const { stream = false, listModels = false } = options
|
||||
|
||||
// 移除末尾的斜杠(如果有)
|
||||
const normalizedBaseUrl = baseUrl.replace(/\/+$/, '')
|
||||
|
||||
// 检查是否为新格式(以 /models 结尾)
|
||||
const isNewFormat = normalizedBaseUrl.endsWith('/models')
|
||||
|
||||
let url
|
||||
if (listModels) {
|
||||
// 获取模型列表
|
||||
if (isNewFormat) {
|
||||
// 新格式: baseUrl 已包含 /v1beta/models,直接添加查询参数
|
||||
url = `${normalizedBaseUrl}?key=${apiKey}`
|
||||
} else {
|
||||
// 旧格式: 需要拼接 /v1beta/models
|
||||
url = `${normalizedBaseUrl}/v1beta/models?key=${apiKey}`
|
||||
}
|
||||
} else {
|
||||
// 模型操作 (generateContent, streamGenerateContent, countTokens)
|
||||
const streamParam = stream ? '&alt=sse' : ''
|
||||
|
||||
if (isNewFormat) {
|
||||
// 新格式: baseUrl 已包含 /v1beta/models,直接拼接 /{model}:action
|
||||
url = `${normalizedBaseUrl}/${model}:${action}?key=${apiKey}${streamParam}`
|
||||
} else {
|
||||
// 旧格式: 需要拼接 /v1beta/models/{model}:action
|
||||
url = `${normalizedBaseUrl}/v1beta/models/${model}:${action}?key=${apiKey}${streamParam}`
|
||||
}
|
||||
}
|
||||
|
||||
return url
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成会话哈希
|
||||
*/
|
||||
@@ -378,9 +426,13 @@ async function handleMessages(req, res) {
|
||||
// 解析代理配置
|
||||
const proxyConfig = parseProxyConfig(account)
|
||||
|
||||
const apiUrl = stream
|
||||
? `${account.baseUrl}/v1beta/models/${model}:streamGenerateContent?key=${account.apiKey}&alt=sse`
|
||||
: `${account.baseUrl}/v1beta/models/${model}:generateContent?key=${account.apiKey}`
|
||||
const apiUrl = buildGeminiApiUrl(
|
||||
account.baseUrl,
|
||||
model,
|
||||
stream ? 'streamGenerateContent' : 'generateContent',
|
||||
account.apiKey,
|
||||
{ stream }
|
||||
)
|
||||
|
||||
const axiosConfig = {
|
||||
method: 'POST',
|
||||
@@ -630,15 +682,22 @@ async function handleModels(req, res) {
|
||||
})
|
||||
}
|
||||
|
||||
// 选择账户获取模型列表
|
||||
// 选择账户获取模型列表(允许 API 账户)
|
||||
let account = null
|
||||
let isApiAccount = false
|
||||
try {
|
||||
const accountSelection = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||
apiKeyData,
|
||||
null,
|
||||
null
|
||||
null,
|
||||
{ allowApiAccounts: true }
|
||||
)
|
||||
account = await geminiAccountService.getAccount(accountSelection.accountId)
|
||||
isApiAccount = accountSelection.accountType === 'gemini-api'
|
||||
if (isApiAccount) {
|
||||
account = await geminiApiAccountService.getAccount(accountSelection.accountId)
|
||||
} else {
|
||||
account = await geminiAccountService.getAccount(accountSelection.accountId)
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to select Gemini account for models endpoint:', error)
|
||||
}
|
||||
@@ -659,7 +718,47 @@ async function handleModels(req, res) {
|
||||
}
|
||||
|
||||
// 获取模型列表
|
||||
const models = await getAvailableModels(account.accessToken, account.proxy)
|
||||
let models
|
||||
if (isApiAccount) {
|
||||
// API Key 账户:使用 API Key 获取模型列表
|
||||
const proxyConfig = parseProxyConfig(account)
|
||||
try {
|
||||
const apiUrl = buildGeminiApiUrl(account.baseUrl, null, null, account.apiKey, {
|
||||
listModels: true
|
||||
})
|
||||
const axiosConfig = {
|
||||
method: 'GET',
|
||||
url: apiUrl,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
if (proxyConfig) {
|
||||
const proxyHelper = new ProxyHelper()
|
||||
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig)
|
||||
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
|
||||
}
|
||||
const response = await axios(axiosConfig)
|
||||
models = (response.data.models || []).map((m) => ({
|
||||
id: m.name?.replace('models/', '') || m.name,
|
||||
object: 'model',
|
||||
created: Date.now() / 1000,
|
||||
owned_by: 'google'
|
||||
}))
|
||||
} catch (error) {
|
||||
logger.warn('Failed to fetch models from Gemini API:', error.message)
|
||||
// 返回默认模型列表
|
||||
models = [
|
||||
{
|
||||
id: 'gemini-2.5-flash',
|
||||
object: 'model',
|
||||
created: Date.now() / 1000,
|
||||
owned_by: 'google'
|
||||
}
|
||||
]
|
||||
}
|
||||
} else {
|
||||
// OAuth 账户:使用 OAuth token 获取模型列表
|
||||
models = await getAvailableModels(account.accessToken, account.proxy)
|
||||
}
|
||||
|
||||
res.json({
|
||||
object: 'list',
|
||||
@@ -786,12 +885,36 @@ function handleSimpleEndpoint(apiMethod) {
|
||||
|
||||
// 从路径参数或请求体中获取模型名
|
||||
const requestedModel = req.body.model || req.params.modelName || 'gemini-2.5-flash'
|
||||
const { accountId } = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||
req.apiKey,
|
||||
sessionHash,
|
||||
requestedModel
|
||||
)
|
||||
const { accountId, accountType } = schedulerResult
|
||||
|
||||
// v1internal 路由只支持 OAuth 账户,不支持 API Key 账户
|
||||
if (accountType === 'gemini-api') {
|
||||
logger.error(
|
||||
`❌ v1internal routes do not support Gemini API accounts. Account: ${accountId}`
|
||||
)
|
||||
return res.status(400).json({
|
||||
error: {
|
||||
message:
|
||||
'This endpoint only supports Gemini OAuth accounts. Gemini API Key accounts are not compatible with v1internal format.',
|
||||
type: 'invalid_account_type'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const account = await geminiAccountService.getAccount(accountId)
|
||||
if (!account) {
|
||||
return res.status(404).json({
|
||||
error: {
|
||||
message: 'Gemini account not found',
|
||||
type: 'account_not_found'
|
||||
}
|
||||
})
|
||||
}
|
||||
const { accessToken, refreshToken } = account
|
||||
|
||||
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1internal'
|
||||
@@ -842,12 +965,34 @@ async function handleLoadCodeAssist(req, res) {
|
||||
|
||||
// 从路径参数或请求体中获取模型名
|
||||
const requestedModel = req.body.model || req.params.modelName || 'gemini-2.5-flash'
|
||||
const { accountId } = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||
req.apiKey,
|
||||
sessionHash,
|
||||
requestedModel
|
||||
)
|
||||
const { accountId, accountType } = schedulerResult
|
||||
|
||||
// v1internal 路由只支持 OAuth 账户,不支持 API Key 账户
|
||||
if (accountType === 'gemini-api') {
|
||||
logger.error(`❌ v1internal routes do not support Gemini API accounts. Account: ${accountId}`)
|
||||
return res.status(400).json({
|
||||
error: {
|
||||
message:
|
||||
'This endpoint only supports Gemini OAuth accounts. Gemini API Key accounts are not compatible with v1internal format.',
|
||||
type: 'invalid_account_type'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const account = await geminiAccountService.getAccount(accountId)
|
||||
if (!account) {
|
||||
return res.status(404).json({
|
||||
error: {
|
||||
message: 'Gemini account not found',
|
||||
type: 'account_not_found'
|
||||
}
|
||||
})
|
||||
}
|
||||
const { accessToken, refreshToken, projectId } = account
|
||||
|
||||
const { metadata, cloudaicompanionProject } = req.body
|
||||
@@ -919,12 +1064,34 @@ async function handleOnboardUser(req, res) {
|
||||
|
||||
// 从路径参数或请求体中获取模型名
|
||||
const requestedModel = req.body.model || req.params.modelName || 'gemini-2.5-flash'
|
||||
const { accountId } = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||
req.apiKey,
|
||||
sessionHash,
|
||||
requestedModel
|
||||
)
|
||||
const { accountId, accountType } = schedulerResult
|
||||
|
||||
// v1internal 路由只支持 OAuth 账户,不支持 API Key 账户
|
||||
if (accountType === 'gemini-api') {
|
||||
logger.error(`❌ v1internal routes do not support Gemini API accounts. Account: ${accountId}`)
|
||||
return res.status(400).json({
|
||||
error: {
|
||||
message:
|
||||
'This endpoint only supports Gemini OAuth accounts. Gemini API Key accounts are not compatible with v1internal format.',
|
||||
type: 'invalid_account_type'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const account = await geminiAccountService.getAccount(accountId)
|
||||
if (!account) {
|
||||
return res.status(404).json({
|
||||
error: {
|
||||
message: 'Gemini account not found',
|
||||
type: 'account_not_found'
|
||||
}
|
||||
})
|
||||
}
|
||||
const { accessToken, refreshToken, projectId } = account
|
||||
|
||||
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1internal'
|
||||
@@ -1013,31 +1180,93 @@ async function handleCountTokens(req, res) {
|
||||
})
|
||||
}
|
||||
|
||||
// 使用统一调度选择账号
|
||||
const { accountId } = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||
// 使用统一调度选择账号(允许 API 账户)
|
||||
const schedulerResult = await unifiedGeminiScheduler.selectAccountForApiKey(
|
||||
req.apiKey,
|
||||
sessionHash,
|
||||
model
|
||||
)
|
||||
const account = await geminiAccountService.getAccount(accountId)
|
||||
const { accessToken, refreshToken } = account
|
||||
|
||||
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1internal'
|
||||
logger.info(`CountTokens request (${version})`, {
|
||||
model,
|
||||
contentsLength: contents.length,
|
||||
apiKeyId: req.apiKey?.id || 'unknown'
|
||||
})
|
||||
{ allowApiAccounts: true }
|
||||
)
|
||||
const { accountId, accountType } = schedulerResult
|
||||
const isApiAccount = accountType === 'gemini-api'
|
||||
|
||||
let account
|
||||
if (isApiAccount) {
|
||||
account = await geminiApiAccountService.getAccount(accountId)
|
||||
} else {
|
||||
account = await geminiAccountService.getAccount(accountId)
|
||||
}
|
||||
|
||||
if (!account) {
|
||||
return res.status(404).json({
|
||||
error: {
|
||||
message: `${isApiAccount ? 'Gemini API' : 'Gemini'} account not found`,
|
||||
type: 'account_not_found'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1'
|
||||
logger.info(
|
||||
`CountTokens request (${version}) - ${isApiAccount ? 'API Key' : 'OAuth'} Account`,
|
||||
{
|
||||
model,
|
||||
contentsLength: contents.length,
|
||||
accountId,
|
||||
apiKeyId: req.apiKey?.id || 'unknown'
|
||||
}
|
||||
)
|
||||
|
||||
// 解析账户的代理配置
|
||||
const proxyConfig = parseProxyConfig(account)
|
||||
|
||||
const client = await geminiAccountService.getOauthClient(accessToken, refreshToken, proxyConfig)
|
||||
const response = await geminiAccountService.countTokens(client, contents, model, proxyConfig)
|
||||
let response
|
||||
if (isApiAccount) {
|
||||
// API Key 账户:直接使用 API Key 请求
|
||||
const modelName = model.startsWith('models/') ? model.replace('models/', '') : model
|
||||
const apiUrl = buildGeminiApiUrl(account.baseUrl, modelName, 'countTokens', account.apiKey)
|
||||
|
||||
const axiosConfig = {
|
||||
method: 'POST',
|
||||
url: apiUrl,
|
||||
data: { contents },
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
}
|
||||
|
||||
if (proxyConfig) {
|
||||
const proxyHelper = new ProxyHelper()
|
||||
axiosConfig.httpsAgent = proxyHelper.createProxyAgent(proxyConfig)
|
||||
axiosConfig.httpAgent = proxyHelper.createProxyAgent(proxyConfig)
|
||||
}
|
||||
|
||||
try {
|
||||
const apiResponse = await axios(axiosConfig)
|
||||
response = {
|
||||
totalTokens: apiResponse.data.totalTokens || 0,
|
||||
totalBillableCharacters: apiResponse.data.totalBillableCharacters || 0,
|
||||
...apiResponse.data
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Gemini API countTokens request failed:', {
|
||||
status: error.response?.status,
|
||||
data: error.response?.data
|
||||
})
|
||||
throw error
|
||||
}
|
||||
} else {
|
||||
// OAuth 账户
|
||||
const { accessToken, refreshToken } = account
|
||||
const client = await geminiAccountService.getOauthClient(
|
||||
accessToken,
|
||||
refreshToken,
|
||||
proxyConfig
|
||||
)
|
||||
response = await geminiAccountService.countTokens(client, contents, model, proxyConfig)
|
||||
}
|
||||
|
||||
res.json(response)
|
||||
} catch (error) {
|
||||
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1internal'
|
||||
const version = req.path.includes('v1beta') ? 'v1beta' : 'v1'
|
||||
logger.error(`Error in countTokens endpoint (${version})`, { error: error.message })
|
||||
res.status(500).json({
|
||||
error: {
|
||||
@@ -1722,7 +1951,7 @@ async function handleStandardGenerateContent(req, res) {
|
||||
|
||||
if (isApiAccount) {
|
||||
// Gemini API 账户:直接使用 API Key 请求
|
||||
const apiUrl = `${account.baseUrl}/v1beta/models/${model}:generateContent?key=${account.apiKey}`
|
||||
const apiUrl = buildGeminiApiUrl(account.baseUrl, model, 'generateContent', account.apiKey)
|
||||
|
||||
const axiosConfig = {
|
||||
method: 'POST',
|
||||
@@ -1993,7 +2222,15 @@ async function handleStandardStreamGenerateContent(req, res) {
|
||||
|
||||
if (isApiAccount) {
|
||||
// Gemini API 账户:直接使用 API Key 请求流式接口
|
||||
const apiUrl = `${account.baseUrl}/v1beta/models/${model}:streamGenerateContent?key=${account.apiKey}&alt=sse`
|
||||
const apiUrl = buildGeminiApiUrl(
|
||||
account.baseUrl,
|
||||
model,
|
||||
'streamGenerateContent',
|
||||
account.apiKey,
|
||||
{
|
||||
stream: true
|
||||
}
|
||||
)
|
||||
|
||||
const axiosConfig = {
|
||||
method: 'POST',
|
||||
|
||||
@@ -255,6 +255,108 @@ router.post('/claude-accounts/exchange-setup-token-code', authenticateAdmin, asy
|
||||
}
|
||||
})
|
||||
|
||||
// =============================================================================
|
||||
// Cookie自动授权端点 (基于sessionKey自动完成OAuth流程)
|
||||
// =============================================================================
|
||||
|
||||
// 普通OAuth的Cookie自动授权
|
||||
router.post('/claude-accounts/oauth-with-cookie', authenticateAdmin, async (req, res) => {
|
||||
try {
|
||||
const { sessionKey, proxy } = req.body
|
||||
|
||||
// 验证sessionKey参数
|
||||
if (!sessionKey || typeof sessionKey !== 'string' || sessionKey.trim().length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'sessionKey不能为空',
|
||||
message: '请提供有效的sessionKey值'
|
||||
})
|
||||
}
|
||||
|
||||
const trimmedSessionKey = sessionKey.trim()
|
||||
|
||||
logger.info('🍪 Starting Cookie-based OAuth authorization', {
|
||||
sessionKeyLength: trimmedSessionKey.length,
|
||||
sessionKeyPrefix: trimmedSessionKey.substring(0, 10) + '...',
|
||||
hasProxy: !!proxy
|
||||
})
|
||||
|
||||
// 执行Cookie自动授权流程
|
||||
const result = await oauthHelper.oauthWithCookie(trimmedSessionKey, proxy, false)
|
||||
|
||||
logger.success('🎉 Cookie-based OAuth authorization completed successfully')
|
||||
|
||||
return res.json({
|
||||
success: true,
|
||||
data: {
|
||||
claudeAiOauth: result.claudeAiOauth,
|
||||
organizationUuid: result.organizationUuid,
|
||||
capabilities: result.capabilities
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('❌ Cookie-based OAuth authorization failed:', {
|
||||
error: error.message,
|
||||
sessionKeyLength: req.body.sessionKey ? req.body.sessionKey.length : 0
|
||||
})
|
||||
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'Cookie授权失败',
|
||||
message: error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// Setup Token的Cookie自动授权
|
||||
router.post('/claude-accounts/setup-token-with-cookie', authenticateAdmin, async (req, res) => {
|
||||
try {
|
||||
const { sessionKey, proxy } = req.body
|
||||
|
||||
// 验证sessionKey参数
|
||||
if (!sessionKey || typeof sessionKey !== 'string' || sessionKey.trim().length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'sessionKey不能为空',
|
||||
message: '请提供有效的sessionKey值'
|
||||
})
|
||||
}
|
||||
|
||||
const trimmedSessionKey = sessionKey.trim()
|
||||
|
||||
logger.info('🍪 Starting Cookie-based Setup Token authorization', {
|
||||
sessionKeyLength: trimmedSessionKey.length,
|
||||
sessionKeyPrefix: trimmedSessionKey.substring(0, 10) + '...',
|
||||
hasProxy: !!proxy
|
||||
})
|
||||
|
||||
// 执行Cookie自动授权流程(Setup Token模式)
|
||||
const result = await oauthHelper.oauthWithCookie(trimmedSessionKey, proxy, true)
|
||||
|
||||
logger.success('🎉 Cookie-based Setup Token authorization completed successfully')
|
||||
|
||||
return res.json({
|
||||
success: true,
|
||||
data: {
|
||||
claudeAiOauth: result.claudeAiOauth,
|
||||
organizationUuid: result.organizationUuid,
|
||||
capabilities: result.capabilities
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('❌ Cookie-based Setup Token authorization failed:', {
|
||||
error: error.message,
|
||||
sessionKeyLength: req.body.sessionKey ? req.body.sessionKey.length : 0
|
||||
})
|
||||
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'Cookie授权失败',
|
||||
message: error.message
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// 获取所有Claude账户
|
||||
router.get('/claude-accounts', authenticateAdmin, async (req, res) => {
|
||||
try {
|
||||
|
||||
@@ -131,7 +131,8 @@ router.post('/claude-console-accounts', authenticateAdmin, async (req, res) => {
|
||||
groupId,
|
||||
dailyQuota,
|
||||
quotaResetTime,
|
||||
maxConcurrentTasks
|
||||
maxConcurrentTasks,
|
||||
disableAutoProtection
|
||||
} = req.body
|
||||
|
||||
if (!name || !apiUrl || !apiKey) {
|
||||
@@ -151,6 +152,10 @@ router.post('/claude-console-accounts', authenticateAdmin, async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 校验上游错误自动防护开关
|
||||
const normalizedDisableAutoProtection =
|
||||
disableAutoProtection === true || disableAutoProtection === 'true'
|
||||
|
||||
// 验证accountType的有效性
|
||||
if (accountType && !['shared', 'dedicated', 'group'].includes(accountType)) {
|
||||
return res
|
||||
@@ -180,7 +185,8 @@ router.post('/claude-console-accounts', authenticateAdmin, async (req, res) => {
|
||||
maxConcurrentTasks:
|
||||
maxConcurrentTasks !== undefined && maxConcurrentTasks !== null
|
||||
? Number(maxConcurrentTasks)
|
||||
: 0
|
||||
: 0,
|
||||
disableAutoProtection: normalizedDisableAutoProtection
|
||||
})
|
||||
|
||||
// 如果是分组类型,将账户添加到分组(CCR 归属 Claude 平台分组)
|
||||
@@ -250,6 +256,13 @@ router.put('/claude-console-accounts/:accountId', authenticateAdmin, async (req,
|
||||
return res.status(404).json({ error: 'Account not found' })
|
||||
}
|
||||
|
||||
// 规范化上游错误自动防护开关
|
||||
if (mappedUpdates.disableAutoProtection !== undefined) {
|
||||
mappedUpdates.disableAutoProtection =
|
||||
mappedUpdates.disableAutoProtection === true ||
|
||||
mappedUpdates.disableAutoProtection === 'true'
|
||||
}
|
||||
|
||||
// 处理分组的变更
|
||||
if (mappedUpdates.accountType !== undefined) {
|
||||
// 如果之前是分组类型,需要从所有分组中移除
|
||||
|
||||
@@ -248,16 +248,29 @@ router.post('/', authenticateAdmin, async (req, res) => {
|
||||
.json({ error: 'Invalid account type. Must be "shared", "dedicated" or "group"' })
|
||||
}
|
||||
|
||||
// 如果是分组类型,验证groupId
|
||||
if (accountData.accountType === 'group' && !accountData.groupId) {
|
||||
// 如果是分组类型,验证groupId或groupIds
|
||||
if (
|
||||
accountData.accountType === 'group' &&
|
||||
!accountData.groupId &&
|
||||
(!accountData.groupIds || accountData.groupIds.length === 0)
|
||||
) {
|
||||
return res.status(400).json({ error: 'Group ID is required for group type accounts' })
|
||||
}
|
||||
|
||||
const newAccount = await geminiAccountService.createAccount(accountData)
|
||||
|
||||
// 如果是分组类型,将账户添加到分组
|
||||
if (accountData.accountType === 'group' && accountData.groupId) {
|
||||
await accountGroupService.addAccountToGroup(newAccount.id, accountData.groupId, 'gemini')
|
||||
// 如果是分组类型,处理分组绑定
|
||||
if (accountData.accountType === 'group') {
|
||||
if (accountData.groupIds && accountData.groupIds.length > 0) {
|
||||
// 多分组模式
|
||||
await accountGroupService.setAccountGroups(newAccount.id, accountData.groupIds, 'gemini')
|
||||
logger.info(
|
||||
`🏢 Added Gemini account ${newAccount.id} to groups: ${accountData.groupIds.join(', ')}`
|
||||
)
|
||||
} else if (accountData.groupId) {
|
||||
// 单分组模式(向后兼容)
|
||||
await accountGroupService.addAccountToGroup(newAccount.id, accountData.groupId, 'gemini')
|
||||
}
|
||||
}
|
||||
|
||||
logger.success(`🏢 Admin created new Gemini account: ${accountData.name}`)
|
||||
@@ -282,8 +295,12 @@ router.put('/:accountId', authenticateAdmin, async (req, res) => {
|
||||
.json({ error: 'Invalid account type. Must be "shared", "dedicated" or "group"' })
|
||||
}
|
||||
|
||||
// 如果更新为分组类型,验证groupId
|
||||
if (updates.accountType === 'group' && !updates.groupId) {
|
||||
// 如果更新为分组类型,验证groupId或groupIds
|
||||
if (
|
||||
updates.accountType === 'group' &&
|
||||
!updates.groupId &&
|
||||
(!updates.groupIds || updates.groupIds.length === 0)
|
||||
) {
|
||||
return res.status(400).json({ error: 'Group ID is required for group type accounts' })
|
||||
}
|
||||
|
||||
|
||||
@@ -23,8 +23,9 @@ router.get('/gemini-api-accounts', authenticateAdmin, async (req, res) => {
|
||||
// 根据分组ID筛选
|
||||
if (groupId) {
|
||||
const group = await accountGroupService.getGroup(groupId)
|
||||
if (group && group.platform === 'gemini' && group.memberIds && group.memberIds.length > 0) {
|
||||
accounts = accounts.filter((account) => group.memberIds.includes(account.id))
|
||||
if (group && group.platform === 'gemini') {
|
||||
const groupMembers = await accountGroupService.getGroupMembers(groupId)
|
||||
accounts = accounts.filter((account) => groupMembers.includes(account.id))
|
||||
} else {
|
||||
accounts = []
|
||||
}
|
||||
@@ -62,8 +63,12 @@ router.get('/gemini-api-accounts', authenticateAdmin, async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 获取分组信息
|
||||
const groupInfos = await accountGroupService.getAccountGroups(account.id)
|
||||
|
||||
return {
|
||||
...account,
|
||||
groupInfos,
|
||||
usage: {
|
||||
daily: usageStats.daily,
|
||||
total: usageStats.total,
|
||||
@@ -257,13 +262,10 @@ router.delete('/gemini-api-accounts/:id', authenticateAdmin, async (req, res) =>
|
||||
// 自动解绑所有绑定的 API Keys(支持 api: 前缀)
|
||||
const unboundCount = await apiKeyService.unbindAccountFromAllKeys(id, 'gemini-api')
|
||||
|
||||
// 检查是否在分组中
|
||||
const groups = await accountGroupService.getAllGroups()
|
||||
for (const group of groups) {
|
||||
if (group.platform === 'gemini' && group.memberIds && group.memberIds.includes(id)) {
|
||||
await accountGroupService.removeMemberFromGroup(group.id, id)
|
||||
logger.info(`Removed Gemini-API account ${id} from group ${group.id}`)
|
||||
}
|
||||
// 从所有分组中移除此账户
|
||||
if (account.accountType === 'group') {
|
||||
await accountGroupService.removeAccountFromAllGroups(id)
|
||||
logger.info(`Removed Gemini-API account ${id} from all groups`)
|
||||
}
|
||||
|
||||
const result = await geminiApiAccountService.deleteAccount(id)
|
||||
|
||||
@@ -31,8 +31,9 @@ router.get('/openai-responses-accounts', authenticateAdmin, async (req, res) =>
|
||||
// 根据分组ID筛选
|
||||
if (groupId) {
|
||||
const group = await accountGroupService.getGroup(groupId)
|
||||
if (group && group.platform === 'openai' && group.memberIds && group.memberIds.length > 0) {
|
||||
accounts = accounts.filter((account) => group.memberIds.includes(account.id))
|
||||
if (group && group.platform === 'openai') {
|
||||
const groupMembers = await accountGroupService.getGroupMembers(groupId)
|
||||
accounts = accounts.filter((account) => groupMembers.includes(account.id))
|
||||
} else {
|
||||
accounts = []
|
||||
}
|
||||
@@ -94,9 +95,13 @@ router.get('/openai-responses-accounts', authenticateAdmin, async (req, res) =>
|
||||
logger.info(`OpenAI-Responses account ${account.id} has ${boundCount} bound API keys`)
|
||||
}
|
||||
|
||||
// 获取分组信息
|
||||
const groupInfos = await accountGroupService.getAccountGroups(account.id)
|
||||
|
||||
const formattedAccount = formatAccountExpiry(account)
|
||||
return {
|
||||
...formattedAccount,
|
||||
groupInfos,
|
||||
boundApiKeysCount: boundCount,
|
||||
usage: {
|
||||
daily: usageStats.daily,
|
||||
@@ -109,6 +114,7 @@ router.get('/openai-responses-accounts', authenticateAdmin, async (req, res) =>
|
||||
const formattedAccount = formatAccountExpiry(account)
|
||||
return {
|
||||
...formattedAccount,
|
||||
groupInfos: [],
|
||||
boundApiKeysCount: 0,
|
||||
usage: {
|
||||
daily: { requests: 0, tokens: 0, allTokens: 0 },
|
||||
@@ -130,7 +136,39 @@ router.get('/openai-responses-accounts', authenticateAdmin, async (req, res) =>
|
||||
// 创建 OpenAI-Responses 账户
|
||||
router.post('/openai-responses-accounts', authenticateAdmin, async (req, res) => {
|
||||
try {
|
||||
const account = await openaiResponsesAccountService.createAccount(req.body)
|
||||
const accountData = req.body
|
||||
|
||||
// 验证分组类型
|
||||
if (
|
||||
accountData.accountType === 'group' &&
|
||||
!accountData.groupId &&
|
||||
(!accountData.groupIds || accountData.groupIds.length === 0)
|
||||
) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Group ID is required for group type accounts'
|
||||
})
|
||||
}
|
||||
|
||||
const account = await openaiResponsesAccountService.createAccount(accountData)
|
||||
|
||||
// 如果是分组类型,处理分组绑定
|
||||
if (accountData.accountType === 'group') {
|
||||
if (accountData.groupIds && accountData.groupIds.length > 0) {
|
||||
// 多分组模式
|
||||
await accountGroupService.setAccountGroups(account.id, accountData.groupIds, 'openai')
|
||||
logger.info(
|
||||
`🏢 Added OpenAI-Responses account ${account.id} to groups: ${accountData.groupIds.join(', ')}`
|
||||
)
|
||||
} else if (accountData.groupId) {
|
||||
// 单分组模式(向后兼容)
|
||||
await accountGroupService.addAccountToGroup(account.id, accountData.groupId, 'openai')
|
||||
logger.info(
|
||||
`🏢 Added OpenAI-Responses account ${account.id} to group: ${accountData.groupId}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const formattedAccount = formatAccountExpiry(account)
|
||||
res.json({ success: true, data: formattedAccount })
|
||||
} catch (error) {
|
||||
@@ -148,6 +186,15 @@ router.put('/openai-responses-accounts/:id', authenticateAdmin, async (req, res)
|
||||
const { id } = req.params
|
||||
const updates = req.body
|
||||
|
||||
// 获取当前账户信息
|
||||
const currentAccount = await openaiResponsesAccountService.getAccount(id)
|
||||
if (!currentAccount) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: 'Account not found'
|
||||
})
|
||||
}
|
||||
|
||||
// ✅ 【新增】映射字段名:前端的 expiresAt -> 后端的 subscriptionExpiresAt
|
||||
const mappedUpdates = mapExpiryField(updates, 'OpenAI-Responses', id)
|
||||
|
||||
@@ -163,12 +210,48 @@ router.put('/openai-responses-accounts/:id', authenticateAdmin, async (req, res)
|
||||
mappedUpdates.priority = priority.toString()
|
||||
}
|
||||
|
||||
// 处理分组变更
|
||||
if (mappedUpdates.accountType !== undefined) {
|
||||
// 如果之前是分组类型,需要从所有分组中移除
|
||||
if (currentAccount.accountType === 'group') {
|
||||
const oldGroups = await accountGroupService.getAccountGroups(id)
|
||||
for (const oldGroup of oldGroups) {
|
||||
await accountGroupService.removeAccountFromGroup(id, oldGroup.id)
|
||||
}
|
||||
logger.info(`📤 Removed OpenAI-Responses account ${id} from all groups`)
|
||||
}
|
||||
|
||||
// 如果新类型是分组,处理多分组支持
|
||||
if (mappedUpdates.accountType === 'group') {
|
||||
if (Object.prototype.hasOwnProperty.call(mappedUpdates, 'groupIds')) {
|
||||
if (mappedUpdates.groupIds && mappedUpdates.groupIds.length > 0) {
|
||||
// 设置新的多分组
|
||||
await accountGroupService.setAccountGroups(id, mappedUpdates.groupIds, 'openai')
|
||||
logger.info(
|
||||
`📥 Added OpenAI-Responses account ${id} to groups: ${mappedUpdates.groupIds.join(', ')}`
|
||||
)
|
||||
} else {
|
||||
// groupIds 为空数组,从所有分组中移除
|
||||
await accountGroupService.removeAccountFromAllGroups(id)
|
||||
logger.info(
|
||||
`📤 Removed OpenAI-Responses account ${id} from all groups (empty groupIds)`
|
||||
)
|
||||
}
|
||||
} else if (mappedUpdates.groupId) {
|
||||
// 向后兼容:仅当没有 groupIds 但有 groupId 时使用单分组逻辑
|
||||
await accountGroupService.addAccountToGroup(id, mappedUpdates.groupId, 'openai')
|
||||
logger.info(`📥 Added OpenAI-Responses account ${id} to group: ${mappedUpdates.groupId}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = await openaiResponsesAccountService.updateAccount(id, mappedUpdates)
|
||||
|
||||
if (!result.success) {
|
||||
return res.status(400).json(result)
|
||||
}
|
||||
|
||||
logger.success(`📝 Admin updated OpenAI-Responses account: ${id}`)
|
||||
res.json({ success: true, ...result })
|
||||
} catch (error) {
|
||||
logger.error('Failed to update OpenAI-Responses account:', error)
|
||||
@@ -195,13 +278,10 @@ router.delete('/openai-responses-accounts/:id', authenticateAdmin, async (req, r
|
||||
// 自动解绑所有绑定的 API Keys
|
||||
const unboundCount = await apiKeyService.unbindAccountFromAllKeys(id, 'openai-responses')
|
||||
|
||||
// 检查是否在分组中
|
||||
const groups = await accountGroupService.getAllGroups()
|
||||
for (const group of groups) {
|
||||
if (group.platform === 'openai' && group.memberIds && group.memberIds.includes(id)) {
|
||||
await accountGroupService.removeMemberFromGroup(group.id, id)
|
||||
logger.info(`Removed OpenAI-Responses account ${id} from group ${group.id}`)
|
||||
}
|
||||
// 从所有分组中移除此账户
|
||||
if (account.accountType === 'group') {
|
||||
await accountGroupService.removeAccountFromAllGroups(id)
|
||||
logger.info(`Removed OpenAI-Responses account ${id} from all groups`)
|
||||
}
|
||||
|
||||
const result = await openaiResponsesAccountService.deleteAccount(id)
|
||||
|
||||
@@ -972,6 +972,9 @@ router.post('/v1/messages/count_tokens', authenticateApiKey, async (req, res) =>
|
||||
const maxAttempts = 2
|
||||
let attempt = 0
|
||||
|
||||
// 引入 claudeConsoleAccountService 用于检查 count_tokens 可用性
|
||||
const claudeConsoleAccountService = require('../services/claudeConsoleAccountService')
|
||||
|
||||
const processRequest = async () => {
|
||||
const { accountId, accountType } = await unifiedClaudeScheduler.selectAccountForApiKey(
|
||||
req.apiKey,
|
||||
@@ -1003,6 +1006,17 @@ router.post('/v1/messages/count_tokens', authenticateApiKey, async (req, res) =>
|
||||
})
|
||||
}
|
||||
|
||||
// 🔍 claude-console 账户特殊处理:检查 count_tokens 端点是否可用
|
||||
if (accountType === 'claude-console') {
|
||||
const isUnavailable = await claudeConsoleAccountService.isCountTokensUnavailable(accountId)
|
||||
if (isUnavailable) {
|
||||
logger.info(
|
||||
`⏭️ count_tokens unavailable for Claude Console account ${accountId}, returning fallback response`
|
||||
)
|
||||
return { fallbackResponse: true }
|
||||
}
|
||||
}
|
||||
|
||||
const relayOptions = {
|
||||
skipUsageRecord: true,
|
||||
customPath: '/v1/messages/count_tokens'
|
||||
@@ -1028,6 +1042,23 @@ router.post('/v1/messages/count_tokens', authenticateApiKey, async (req, res) =>
|
||||
relayOptions
|
||||
)
|
||||
|
||||
// 🔍 claude-console 账户:检测上游 404 响应并标记
|
||||
if (accountType === 'claude-console' && response.statusCode === 404) {
|
||||
logger.warn(
|
||||
`⚠️ count_tokens endpoint returned 404 for Claude Console account ${accountId}, marking as unavailable`
|
||||
)
|
||||
// 标记失败不应影响 fallback 响应
|
||||
try {
|
||||
await claudeConsoleAccountService.markCountTokensUnavailable(accountId)
|
||||
} catch (markError) {
|
||||
logger.error(
|
||||
`❌ Failed to mark count_tokens unavailable for account ${accountId}, but will still return fallback:`,
|
||||
markError
|
||||
)
|
||||
}
|
||||
return { fallbackResponse: true }
|
||||
}
|
||||
|
||||
res.status(response.statusCode)
|
||||
|
||||
const skipHeaders = ['content-encoding', 'transfer-encoding', 'content-length']
|
||||
@@ -1050,11 +1081,21 @@ router.post('/v1/messages/count_tokens', authenticateApiKey, async (req, res) =>
|
||||
}
|
||||
|
||||
logger.info(`✅ Token count request completed for key: ${req.apiKey.name}`)
|
||||
return { fallbackResponse: false }
|
||||
}
|
||||
|
||||
while (attempt < maxAttempts) {
|
||||
try {
|
||||
await processRequest()
|
||||
const result = await processRequest()
|
||||
|
||||
// 🔍 处理 fallback 响应(claude-console 账户 count_tokens 不可用)
|
||||
if (result && result.fallbackResponse) {
|
||||
if (!res.headersSent) {
|
||||
return res.status(200).json({ input_tokens: 0 })
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
} catch (error) {
|
||||
if (error.code === 'CONSOLE_ACCOUNT_CONCURRENCY_FULL') {
|
||||
|
||||
@@ -5,6 +5,7 @@ const apiKeyService = require('../services/apiKeyService')
|
||||
const CostCalculator = require('../utils/costCalculator')
|
||||
const claudeAccountService = require('../services/claudeAccountService')
|
||||
const openaiAccountService = require('../services/openaiAccountService')
|
||||
const { createClaudeTestPayload } = require('../utils/testPayloadHelper')
|
||||
|
||||
const router = express.Router()
|
||||
|
||||
@@ -792,8 +793,8 @@ router.post('/api/batch-model-stats', async (req, res) => {
|
||||
|
||||
// 🧪 API Key 端点测试接口 - 测试API Key是否能正常访问服务
|
||||
router.post('/api-key/test', async (req, res) => {
|
||||
const axios = require('axios')
|
||||
const config = require('../../config/config')
|
||||
const { sendStreamTestRequest } = require('../utils/testPayloadHelper')
|
||||
|
||||
try {
|
||||
const { apiKey, model = 'claude-sonnet-4-5-20250929' } = req.body
|
||||
@@ -805,7 +806,6 @@ router.post('/api-key/test', async (req, res) => {
|
||||
})
|
||||
}
|
||||
|
||||
// 基本格式验证
|
||||
if (typeof apiKey !== 'string' || apiKey.length < 10 || apiKey.length > 512) {
|
||||
return res.status(400).json({
|
||||
error: 'Invalid API key format',
|
||||
@@ -813,7 +813,6 @@ router.post('/api-key/test', async (req, res) => {
|
||||
})
|
||||
}
|
||||
|
||||
// 首先验证API Key是否有效(不触发激活)
|
||||
const validation = await apiKeyService.validateApiKeyForStats(apiKey)
|
||||
if (!validation.valid) {
|
||||
return res.status(401).json({
|
||||
@@ -824,244 +823,29 @@ router.post('/api-key/test', async (req, res) => {
|
||||
|
||||
logger.api(`🧪 API Key test started for: ${validation.keyData.name} (${validation.keyData.id})`)
|
||||
|
||||
// 设置SSE响应头
|
||||
res.setHeader('Content-Type', 'text/event-stream')
|
||||
res.setHeader('Cache-Control', 'no-cache')
|
||||
res.setHeader('Connection', 'keep-alive')
|
||||
res.setHeader('X-Accel-Buffering', 'no')
|
||||
|
||||
// 发送测试开始事件
|
||||
res.write(`data: ${JSON.stringify({ type: 'test_start', message: 'Test started' })}\n\n`)
|
||||
|
||||
// 构建测试请求,模拟 Claude CLI 客户端
|
||||
const port = config.server.port || 3000
|
||||
const baseURL = `http://127.0.0.1:${port}`
|
||||
const apiUrl = `http://127.0.0.1:${port}/api/v1/messages?beta=true`
|
||||
|
||||
const testPayload = {
|
||||
model,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: 'hi'
|
||||
}
|
||||
],
|
||||
system: [
|
||||
{
|
||||
type: 'text',
|
||||
text: "You are Claude Code, Anthropic's official CLI for Claude."
|
||||
}
|
||||
],
|
||||
max_tokens: 32000,
|
||||
temperature: 1,
|
||||
stream: true
|
||||
}
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'claude-cli/2.0.52 (external, cli)',
|
||||
'x-api-key': apiKey,
|
||||
'anthropic-version': config.claude.apiVersion || '2023-06-01'
|
||||
}
|
||||
|
||||
// 向自身服务发起测试请求
|
||||
// 使用 validateStatus 允许所有状态码通过,以便我们可以处理流式错误响应
|
||||
const response = await axios.post(`${baseURL}/api/v1/messages`, testPayload, {
|
||||
headers,
|
||||
responseType: 'stream',
|
||||
timeout: 60000, // 60秒超时
|
||||
validateStatus: () => true // 接受所有状态码,自行处理错误
|
||||
})
|
||||
|
||||
// 检查响应状态码,如果不是2xx,尝试读取错误信息
|
||||
if (response.status >= 400) {
|
||||
logger.error(
|
||||
`🧪 API Key test received error status ${response.status} for: ${validation.keyData.name}`
|
||||
)
|
||||
|
||||
// 尝试从流中读取错误信息
|
||||
let errorBody = ''
|
||||
for await (const chunk of response.data) {
|
||||
errorBody += chunk.toString()
|
||||
}
|
||||
|
||||
let errorMessage = `HTTP ${response.status}`
|
||||
try {
|
||||
// 尝试解析SSE格式的错误
|
||||
const lines = errorBody.split('\n')
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
const dataStr = line.substring(6).trim()
|
||||
if (dataStr && dataStr !== '[DONE]') {
|
||||
const data = JSON.parse(dataStr)
|
||||
if (data.error?.message) {
|
||||
errorMessage = data.error.message
|
||||
break
|
||||
} else if (data.message) {
|
||||
errorMessage = data.message
|
||||
break
|
||||
} else if (typeof data.error === 'string') {
|
||||
errorMessage = data.error
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 如果不是SSE格式,尝试直接解析JSON
|
||||
if (errorMessage === `HTTP ${response.status}`) {
|
||||
const jsonError = JSON.parse(errorBody)
|
||||
errorMessage =
|
||||
jsonError.error?.message || jsonError.message || jsonError.error || errorMessage
|
||||
}
|
||||
} catch {
|
||||
// 解析失败,使用原始错误体或默认消息
|
||||
if (errorBody && errorBody.length < 500) {
|
||||
errorMessage = errorBody
|
||||
}
|
||||
}
|
||||
|
||||
res.write(`data: ${JSON.stringify({ type: 'error', error: errorMessage })}\n\n`)
|
||||
res.write(
|
||||
`data: ${JSON.stringify({ type: 'test_complete', success: false, error: errorMessage })}\n\n`
|
||||
)
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
|
||||
let receivedContent = ''
|
||||
let testSuccess = false
|
||||
let upstreamError = null
|
||||
|
||||
// 处理流式响应
|
||||
response.data.on('data', (chunk) => {
|
||||
const lines = chunk.toString().split('\n')
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
const dataStr = line.substring(6).trim()
|
||||
if (dataStr === '[DONE]') {
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const data = JSON.parse(dataStr)
|
||||
|
||||
// 检查上游返回的错误事件
|
||||
if (data.type === 'error' || data.error) {
|
||||
let errorMsg = 'Unknown upstream error'
|
||||
|
||||
// 优先从 data.error 提取(如果是对象,获取其 message)
|
||||
if (typeof data.error === 'object' && data.error?.message) {
|
||||
errorMsg = data.error.message
|
||||
} else if (typeof data.error === 'string' && data.error !== 'Claude API error') {
|
||||
// 如果 error 是字符串且不是通用错误,直接使用
|
||||
errorMsg = data.error
|
||||
} else if (data.details) {
|
||||
// 尝试从 details 字段解析详细错误(claudeRelayService 格式)
|
||||
try {
|
||||
const details =
|
||||
typeof data.details === 'string' ? JSON.parse(data.details) : data.details
|
||||
if (details.error?.message) {
|
||||
errorMsg = details.error.message
|
||||
} else if (details.message) {
|
||||
errorMsg = details.message
|
||||
}
|
||||
} catch {
|
||||
// details 不是有效 JSON,尝试直接使用
|
||||
if (typeof data.details === 'string' && data.details.length < 500) {
|
||||
errorMsg = data.details
|
||||
}
|
||||
}
|
||||
} else if (data.message) {
|
||||
errorMsg = data.message
|
||||
}
|
||||
|
||||
// 添加状态码信息(如果有)
|
||||
if (data.status && errorMsg !== 'Unknown upstream error') {
|
||||
errorMsg = `[${data.status}] ${errorMsg}`
|
||||
}
|
||||
|
||||
upstreamError = errorMsg
|
||||
logger.error(`🧪 Upstream error in test for: ${validation.keyData.name}:`, errorMsg)
|
||||
res.write(`data: ${JSON.stringify({ type: 'error', error: errorMsg })}\n\n`)
|
||||
continue
|
||||
}
|
||||
|
||||
// 提取文本内容
|
||||
if (data.type === 'content_block_delta' && data.delta?.text) {
|
||||
receivedContent += data.delta.text
|
||||
res.write(`data: ${JSON.stringify({ type: 'content', text: data.delta.text })}\n\n`)
|
||||
}
|
||||
|
||||
// 消息结束
|
||||
if (data.type === 'message_stop') {
|
||||
testSuccess = true
|
||||
res.write(`data: ${JSON.stringify({ type: 'message_stop' })}\n\n`)
|
||||
}
|
||||
} catch {
|
||||
// 忽略解析错误
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
response.data.on('end', () => {
|
||||
// 如果有上游错误,标记为失败
|
||||
if (upstreamError) {
|
||||
testSuccess = false
|
||||
}
|
||||
|
||||
logger.api(
|
||||
`🧪 API Key test completed for: ${validation.keyData.name}, success: ${testSuccess}, content length: ${receivedContent.length}${upstreamError ? `, error: ${upstreamError}` : ''}`
|
||||
)
|
||||
res.write(
|
||||
`data: ${JSON.stringify({
|
||||
type: 'test_complete',
|
||||
success: testSuccess,
|
||||
contentLength: receivedContent.length,
|
||||
error: upstreamError || undefined
|
||||
})}\n\n`
|
||||
)
|
||||
res.end()
|
||||
})
|
||||
|
||||
response.data.on('error', (err) => {
|
||||
logger.error(`🧪 API Key test stream error for: ${validation.keyData.name}`, err)
|
||||
|
||||
// 如果已经捕获了上游错误,优先使用那个
|
||||
let errorMsg = upstreamError || err.message || 'Stream error'
|
||||
|
||||
// 如果错误消息是通用的 "Claude API error: xxx",提供更友好的提示
|
||||
if (errorMsg.startsWith('Claude API error:') && upstreamError) {
|
||||
errorMsg = upstreamError
|
||||
}
|
||||
|
||||
res.write(`data: ${JSON.stringify({ type: 'error', error: errorMsg })}\n\n`)
|
||||
res.write(
|
||||
`data: ${JSON.stringify({ type: 'test_complete', success: false, error: errorMsg })}\n\n`
|
||||
)
|
||||
res.end()
|
||||
})
|
||||
|
||||
// 处理客户端断开连接
|
||||
req.on('close', () => {
|
||||
if (!res.writableEnded) {
|
||||
response.data.destroy()
|
||||
}
|
||||
await sendStreamTestRequest({
|
||||
apiUrl,
|
||||
authorization: apiKey,
|
||||
responseStream: res,
|
||||
payload: createClaudeTestPayload(model, { stream: true }),
|
||||
timeout: 60000,
|
||||
extraHeaders: { 'x-api-key': apiKey }
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('❌ API Key test failed:', error)
|
||||
|
||||
// 如果还未发送响应头,返回JSON错误
|
||||
if (!res.headersSent) {
|
||||
return res.status(500).json({
|
||||
error: 'Test failed',
|
||||
message: error.response?.data?.error?.message || error.message || 'Internal server error'
|
||||
message: error.message || 'Internal server error'
|
||||
})
|
||||
}
|
||||
|
||||
// 如果已经是SSE流,发送错误事件
|
||||
res.write(
|
||||
`data: ${JSON.stringify({ type: 'error', error: error.response?.data?.error?.message || error.message || 'Test failed' })}\n\n`
|
||||
`data: ${JSON.stringify({ type: 'error', error: error.message || 'Test failed' })}\n\n`
|
||||
)
|
||||
res.end()
|
||||
}
|
||||
|
||||
@@ -67,7 +67,8 @@ class ClaudeConsoleAccountService {
|
||||
schedulable = true, // 是否可被调度
|
||||
dailyQuota = 0, // 每日额度限制(美元),0表示不限制
|
||||
quotaResetTime = '00:00', // 额度重置时间(HH:mm格式)
|
||||
maxConcurrentTasks = 0 // 最大并发任务数,0表示无限制
|
||||
maxConcurrentTasks = 0, // 最大并发任务数,0表示无限制
|
||||
disableAutoProtection = false // 是否关闭自动防护(429/401/400/529 不自动禁用)
|
||||
} = options
|
||||
|
||||
// 验证必填字段
|
||||
@@ -115,7 +116,8 @@ class ClaudeConsoleAccountService {
|
||||
lastResetDate: redis.getDateStringInTimezone(), // 最后重置日期(按配置时区)
|
||||
quotaResetTime, // 额度重置时间
|
||||
quotaStoppedAt: '', // 因额度停用的时间
|
||||
maxConcurrentTasks: maxConcurrentTasks.toString() // 最大并发任务数,0表示无限制
|
||||
maxConcurrentTasks: maxConcurrentTasks.toString(), // 最大并发任务数,0表示无限制
|
||||
disableAutoProtection: disableAutoProtection.toString() // 关闭自动防护
|
||||
}
|
||||
|
||||
const client = redis.getClientSafe()
|
||||
@@ -153,6 +155,7 @@ class ClaudeConsoleAccountService {
|
||||
quotaResetTime,
|
||||
quotaStoppedAt: null,
|
||||
maxConcurrentTasks, // 新增:返回并发限制配置
|
||||
disableAutoProtection, // 新增:返回自动防护开关
|
||||
activeTaskCount: 0 // 新增:新建账户当前并发数为0
|
||||
}
|
||||
}
|
||||
@@ -213,7 +216,8 @@ class ClaudeConsoleAccountService {
|
||||
|
||||
// 并发控制相关
|
||||
maxConcurrentTasks: parseInt(accountData.maxConcurrentTasks) || 0,
|
||||
activeTaskCount
|
||||
activeTaskCount,
|
||||
disableAutoProtection: accountData.disableAutoProtection === 'true'
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -259,6 +263,7 @@ class ClaudeConsoleAccountService {
|
||||
}
|
||||
accountData.isActive = accountData.isActive === 'true'
|
||||
accountData.schedulable = accountData.schedulable !== 'false' // 默认为true
|
||||
accountData.disableAutoProtection = accountData.disableAutoProtection === 'true'
|
||||
|
||||
if (accountData.proxy) {
|
||||
accountData.proxy = JSON.parse(accountData.proxy)
|
||||
@@ -367,6 +372,9 @@ class ClaudeConsoleAccountService {
|
||||
if (updates.maxConcurrentTasks !== undefined) {
|
||||
updatedData.maxConcurrentTasks = updates.maxConcurrentTasks.toString()
|
||||
}
|
||||
if (updates.disableAutoProtection !== undefined) {
|
||||
updatedData.disableAutoProtection = updates.disableAutoProtection.toString()
|
||||
}
|
||||
|
||||
// ✅ 直接保存 subscriptionExpiresAt(如果提供)
|
||||
// Claude Console 没有 token 刷新逻辑,不会覆盖此字段
|
||||
@@ -1510,6 +1518,71 @@ class ClaudeConsoleAccountService {
|
||||
const expiryDate = new Date(account.subscriptionExpiresAt)
|
||||
return expiryDate <= new Date()
|
||||
}
|
||||
|
||||
// 🚫 标记账户的 count_tokens 端点不可用
|
||||
async markCountTokensUnavailable(accountId) {
|
||||
try {
|
||||
const client = redis.getClientSafe()
|
||||
const accountKey = `${this.ACCOUNT_KEY_PREFIX}${accountId}`
|
||||
|
||||
// 检查账户是否存在
|
||||
const exists = await client.exists(accountKey)
|
||||
if (!exists) {
|
||||
logger.warn(
|
||||
`⚠️ Cannot mark count_tokens unavailable for non-existent account: ${accountId}`
|
||||
)
|
||||
return { success: false, reason: 'Account not found' }
|
||||
}
|
||||
|
||||
await client.hset(accountKey, {
|
||||
countTokensUnavailable: 'true',
|
||||
countTokensUnavailableAt: new Date().toISOString()
|
||||
})
|
||||
|
||||
logger.info(
|
||||
`🚫 Marked count_tokens endpoint as unavailable for Claude Console account: ${accountId}`
|
||||
)
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
logger.error(`❌ Failed to mark count_tokens unavailable for account ${accountId}:`, error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ 移除账户的 count_tokens 不可用标记
|
||||
async removeCountTokensUnavailable(accountId) {
|
||||
try {
|
||||
const client = redis.getClientSafe()
|
||||
const accountKey = `${this.ACCOUNT_KEY_PREFIX}${accountId}`
|
||||
|
||||
await client.hdel(accountKey, 'countTokensUnavailable', 'countTokensUnavailableAt')
|
||||
|
||||
logger.info(
|
||||
`✅ Removed count_tokens unavailable mark for Claude Console account: ${accountId}`
|
||||
)
|
||||
return { success: true }
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
`❌ Failed to remove count_tokens unavailable mark for account ${accountId}:`,
|
||||
error
|
||||
)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// 🔍 检查账户的 count_tokens 端点是否不可用
|
||||
async isCountTokensUnavailable(accountId) {
|
||||
try {
|
||||
const client = redis.getClientSafe()
|
||||
const accountKey = `${this.ACCOUNT_KEY_PREFIX}${accountId}`
|
||||
|
||||
const value = await client.hget(accountKey, 'countTokensUnavailable')
|
||||
return value === 'true'
|
||||
} catch (error) {
|
||||
logger.error(`❌ Failed to check count_tokens availability for account ${accountId}:`, error)
|
||||
return false // 出错时默认返回可用,避免误阻断
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = new ClaudeConsoleAccountService()
|
||||
|
||||
@@ -12,7 +12,7 @@ const {
|
||||
|
||||
class ClaudeConsoleRelayService {
|
||||
constructor() {
|
||||
this.defaultUserAgent = 'claude-cli/1.0.69 (external, cli)'
|
||||
this.defaultUserAgent = 'claude-cli/2.0.52 (external, cli)'
|
||||
}
|
||||
|
||||
// 🚀 转发请求到Claude Console API
|
||||
@@ -37,6 +37,8 @@ class ClaudeConsoleRelayService {
|
||||
throw new Error('Claude Console Claude account not found')
|
||||
}
|
||||
|
||||
const autoProtectionDisabled = account.disableAutoProtection === true
|
||||
|
||||
logger.info(
|
||||
`📤 Processing Claude Console API request for key: ${apiKeyData.name || apiKeyData.id}, account: ${account.name} (${accountId}), request: ${requestId}`
|
||||
)
|
||||
@@ -248,27 +250,41 @@ class ClaudeConsoleRelayService {
|
||||
|
||||
// 检查错误状态并相应处理
|
||||
if (response.status === 401) {
|
||||
logger.warn(`🚫 Unauthorized error detected for Claude Console account ${accountId}`)
|
||||
await claudeConsoleAccountService.markAccountUnauthorized(accountId)
|
||||
logger.warn(
|
||||
`🚫 Unauthorized error detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
|
||||
)
|
||||
if (!autoProtectionDisabled) {
|
||||
await claudeConsoleAccountService.markAccountUnauthorized(accountId)
|
||||
}
|
||||
} else if (accountDisabledError) {
|
||||
logger.error(
|
||||
`🚫 Account disabled error (400) detected for Claude Console account ${accountId}, marking as blocked`
|
||||
`🚫 Account disabled error (400) detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
|
||||
)
|
||||
// 传入完整的错误详情到 webhook
|
||||
const errorDetails =
|
||||
typeof response.data === 'string' ? response.data : JSON.stringify(response.data)
|
||||
await claudeConsoleAccountService.markConsoleAccountBlocked(accountId, errorDetails)
|
||||
if (!autoProtectionDisabled) {
|
||||
await claudeConsoleAccountService.markConsoleAccountBlocked(accountId, errorDetails)
|
||||
}
|
||||
} else if (response.status === 429) {
|
||||
logger.warn(`🚫 Rate limit detected for Claude Console account ${accountId}`)
|
||||
logger.warn(
|
||||
`🚫 Rate limit detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
|
||||
)
|
||||
// 收到429先检查是否因为超过了手动配置的每日额度
|
||||
await claudeConsoleAccountService.checkQuotaUsage(accountId).catch((err) => {
|
||||
logger.error('❌ Failed to check quota after 429 error:', err)
|
||||
})
|
||||
|
||||
await claudeConsoleAccountService.markAccountRateLimited(accountId)
|
||||
if (!autoProtectionDisabled) {
|
||||
await claudeConsoleAccountService.markAccountRateLimited(accountId)
|
||||
}
|
||||
} else if (response.status === 529) {
|
||||
logger.warn(`🚫 Overload error detected for Claude Console account ${accountId}`)
|
||||
await claudeConsoleAccountService.markAccountOverloaded(accountId)
|
||||
logger.warn(
|
||||
`🚫 Overload error detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
|
||||
)
|
||||
if (!autoProtectionDisabled) {
|
||||
await claudeConsoleAccountService.markAccountOverloaded(accountId)
|
||||
}
|
||||
} else if (response.status === 200 || response.status === 201) {
|
||||
// 如果请求成功,检查并移除错误状态
|
||||
const isRateLimited = await claudeConsoleAccountService.isAccountRateLimited(accountId)
|
||||
@@ -597,6 +613,7 @@ class ClaudeConsoleRelayService {
|
||||
})
|
||||
|
||||
response.data.on('end', async () => {
|
||||
const autoProtectionDisabled = account.disableAutoProtection === true
|
||||
// 记录原始错误消息到日志(方便调试,包含供应商信息)
|
||||
logger.error(
|
||||
`📝 [Stream] Upstream error response from ${account?.name || accountId}: ${errorDataForCheck.substring(0, 500)}`
|
||||
@@ -609,24 +626,41 @@ class ClaudeConsoleRelayService {
|
||||
)
|
||||
|
||||
if (response.status === 401) {
|
||||
await claudeConsoleAccountService.markAccountUnauthorized(accountId)
|
||||
logger.warn(
|
||||
`🚫 [Stream] Unauthorized error detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
|
||||
)
|
||||
if (!autoProtectionDisabled) {
|
||||
await claudeConsoleAccountService.markAccountUnauthorized(accountId)
|
||||
}
|
||||
} else if (accountDisabledError) {
|
||||
logger.error(
|
||||
`🚫 [Stream] Account disabled error (400) detected for Claude Console account ${accountId}, marking as blocked`
|
||||
`🚫 [Stream] Account disabled error (400) detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
|
||||
)
|
||||
// 传入完整的错误详情到 webhook
|
||||
await claudeConsoleAccountService.markConsoleAccountBlocked(
|
||||
accountId,
|
||||
errorDataForCheck
|
||||
)
|
||||
if (!autoProtectionDisabled) {
|
||||
await claudeConsoleAccountService.markConsoleAccountBlocked(
|
||||
accountId,
|
||||
errorDataForCheck
|
||||
)
|
||||
}
|
||||
} else if (response.status === 429) {
|
||||
await claudeConsoleAccountService.markAccountRateLimited(accountId)
|
||||
logger.warn(
|
||||
`🚫 [Stream] Rate limit detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
|
||||
)
|
||||
// 检查是否因为超过每日额度
|
||||
claudeConsoleAccountService.checkQuotaUsage(accountId).catch((err) => {
|
||||
logger.error('❌ Failed to check quota after 429 error:', err)
|
||||
})
|
||||
if (!autoProtectionDisabled) {
|
||||
await claudeConsoleAccountService.markAccountRateLimited(accountId)
|
||||
}
|
||||
} else if (response.status === 529) {
|
||||
await claudeConsoleAccountService.markAccountOverloaded(accountId)
|
||||
logger.warn(
|
||||
`🚫 [Stream] Overload error detected for Claude Console account ${accountId}${autoProtectionDisabled ? ' (auto-protection disabled, skipping status change)' : ''}`
|
||||
)
|
||||
if (!autoProtectionDisabled) {
|
||||
await claudeConsoleAccountService.markAccountOverloaded(accountId)
|
||||
}
|
||||
}
|
||||
|
||||
// 设置响应头
|
||||
@@ -1113,22 +1147,11 @@ class ClaudeConsoleRelayService {
|
||||
}
|
||||
}
|
||||
|
||||
// 🧪 测试账号连接(供Admin API使用,直接复用 _makeClaudeConsoleStreamRequest)
|
||||
// 🧪 测试账号连接(供Admin API使用)
|
||||
async testAccountConnection(accountId, responseStream) {
|
||||
const testRequestBody = {
|
||||
model: 'claude-sonnet-4-5-20250929',
|
||||
max_tokens: 100,
|
||||
stream: true,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: 'hi'
|
||||
}
|
||||
]
|
||||
}
|
||||
const { sendStreamTestRequest } = require('../utils/testPayloadHelper')
|
||||
|
||||
try {
|
||||
// 获取账户信息
|
||||
const account = await claudeConsoleAccountService.getAccount(accountId)
|
||||
if (!account) {
|
||||
throw new Error('Account not found')
|
||||
@@ -1136,48 +1159,32 @@ class ClaudeConsoleRelayService {
|
||||
|
||||
logger.info(`🧪 Testing Claude Console account connection: ${account.name} (${accountId})`)
|
||||
|
||||
// 创建代理agent
|
||||
const proxyAgent = claudeConsoleAccountService._createProxyAgent(account.proxy)
|
||||
const cleanUrl = account.apiUrl.replace(/\/$/, '')
|
||||
const apiUrl = cleanUrl.endsWith('/v1/messages')
|
||||
? cleanUrl
|
||||
: `${cleanUrl}/v1/messages?beta=true`
|
||||
|
||||
// 设置响应头
|
||||
await sendStreamTestRequest({
|
||||
apiUrl,
|
||||
authorization: `Bearer ${account.apiKey}`,
|
||||
responseStream,
|
||||
proxyAgent: claudeConsoleAccountService._createProxyAgent(account.proxy),
|
||||
extraHeaders: account.userAgent ? { 'User-Agent': account.userAgent } : {}
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error(`❌ Test account connection failed:`, error)
|
||||
if (!responseStream.headersSent) {
|
||||
responseStream.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
Connection: 'keep-alive',
|
||||
'X-Accel-Buffering': 'no'
|
||||
'Cache-Control': 'no-cache'
|
||||
})
|
||||
}
|
||||
|
||||
// 创建流转换器,将 Claude API 格式转换为前端测试页面期望的格式
|
||||
const streamTransformer = this._createTestStreamTransformer()
|
||||
|
||||
// 直接复用现有的流式请求方法
|
||||
await this._makeClaudeConsoleStreamRequest(
|
||||
testRequestBody,
|
||||
account,
|
||||
proxyAgent,
|
||||
{}, // clientHeaders - 测试不需要客户端headers
|
||||
responseStream,
|
||||
accountId,
|
||||
null, // usageCallback - 测试不需要统计
|
||||
streamTransformer, // 使用转换器将 Claude API 格式转为前端期望格式
|
||||
{} // requestOptions
|
||||
)
|
||||
|
||||
logger.info(`✅ Test request completed for account: ${account.name}`)
|
||||
} catch (error) {
|
||||
logger.error(`❌ Test account connection failed:`, error)
|
||||
// 发送错误事件给前端
|
||||
if (!responseStream.destroyed && !responseStream.writableEnded) {
|
||||
try {
|
||||
const errorMsg = error.message || '测试失败'
|
||||
responseStream.write(`data: ${JSON.stringify({ type: 'error', error: errorMsg })}\n\n`)
|
||||
} catch {
|
||||
// 忽略写入错误
|
||||
}
|
||||
responseStream.write(
|
||||
`data: ${JSON.stringify({ type: 'test_complete', success: false, error: error.message })}\n\n`
|
||||
)
|
||||
responseStream.end()
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ const zlib = require('zlib')
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const ProxyHelper = require('../utils/proxyHelper')
|
||||
const { filterForClaude } = require('../utils/headerFilter')
|
||||
const claudeAccountService = require('./claudeAccountService')
|
||||
const unifiedClaudeScheduler = require('./unifiedClaudeScheduler')
|
||||
const sessionHelper = require('../utils/sessionHelper')
|
||||
@@ -13,6 +14,7 @@ const redis = require('../models/redis')
|
||||
const ClaudeCodeValidator = require('../validators/clients/claudeCodeValidator')
|
||||
const { formatDateWithTimezone } = require('../utils/dateHelper')
|
||||
const requestIdentityService = require('./requestIdentityService')
|
||||
const { createClaudeTestPayload } = require('../utils/testPayloadHelper')
|
||||
|
||||
class ClaudeRelayService {
|
||||
constructor() {
|
||||
@@ -789,7 +791,8 @@ class ClaudeRelayService {
|
||||
return total
|
||||
}
|
||||
|
||||
const removeFromMessages = () => {
|
||||
// 只移除 cache_control 属性,保留内容本身,避免丢失用户消息
|
||||
const removeCacheControlFromMessages = () => {
|
||||
if (!Array.isArray(body.messages)) {
|
||||
return false
|
||||
}
|
||||
@@ -803,12 +806,8 @@ class ClaudeRelayService {
|
||||
for (let contentIndex = 0; contentIndex < message.content.length; contentIndex += 1) {
|
||||
const contentItem = message.content[contentIndex]
|
||||
if (contentItem && contentItem.cache_control) {
|
||||
message.content.splice(contentIndex, 1)
|
||||
|
||||
if (message.content.length === 0) {
|
||||
body.messages.splice(messageIndex, 1)
|
||||
}
|
||||
|
||||
// 只删除 cache_control 属性,保留内容
|
||||
delete contentItem.cache_control
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -817,7 +816,8 @@ class ClaudeRelayService {
|
||||
return false
|
||||
}
|
||||
|
||||
const removeFromSystem = () => {
|
||||
// 只移除 cache_control 属性,保留 system 内容
|
||||
const removeCacheControlFromSystem = () => {
|
||||
if (!Array.isArray(body.system)) {
|
||||
return false
|
||||
}
|
||||
@@ -825,12 +825,8 @@ class ClaudeRelayService {
|
||||
for (let index = 0; index < body.system.length; index += 1) {
|
||||
const systemItem = body.system[index]
|
||||
if (systemItem && systemItem.cache_control) {
|
||||
body.system.splice(index, 1)
|
||||
|
||||
if (body.system.length === 0) {
|
||||
delete body.system
|
||||
}
|
||||
|
||||
// 只删除 cache_control 属性,保留内容
|
||||
delete systemItem.cache_control
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -841,12 +837,13 @@ class ClaudeRelayService {
|
||||
let total = countCacheControlBlocks()
|
||||
|
||||
while (total > MAX_CACHE_CONTROL_BLOCKS) {
|
||||
if (removeFromMessages()) {
|
||||
// 优先从 messages 中移除 cache_control,再从 system 中移除
|
||||
if (removeCacheControlFromMessages()) {
|
||||
total -= 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (removeFromSystem()) {
|
||||
if (removeCacheControlFromSystem()) {
|
||||
total -= 1
|
||||
continue
|
||||
}
|
||||
@@ -881,62 +878,9 @@ class ClaudeRelayService {
|
||||
|
||||
// 🔧 过滤客户端请求头
|
||||
_filterClientHeaders(clientHeaders) {
|
||||
// 需要移除的敏感 headers
|
||||
const sensitiveHeaders = [
|
||||
'content-type',
|
||||
'user-agent',
|
||||
'x-api-key',
|
||||
'authorization',
|
||||
'x-authorization',
|
||||
'host',
|
||||
'content-length',
|
||||
'connection',
|
||||
'proxy-authorization',
|
||||
'content-encoding',
|
||||
'transfer-encoding'
|
||||
]
|
||||
|
||||
// 🆕 需要移除的浏览器相关 headers(避免CORS问题)
|
||||
const browserHeaders = [
|
||||
'origin',
|
||||
'referer',
|
||||
'sec-fetch-mode',
|
||||
'sec-fetch-site',
|
||||
'sec-fetch-dest',
|
||||
'sec-ch-ua',
|
||||
'sec-ch-ua-mobile',
|
||||
'sec-ch-ua-platform',
|
||||
'accept-language',
|
||||
'accept-encoding',
|
||||
'accept',
|
||||
'cache-control',
|
||||
'pragma',
|
||||
'anthropic-dangerous-direct-browser-access' // 这个头可能触发CORS检查
|
||||
]
|
||||
|
||||
// 应该保留的 headers(用于会话一致性和追踪)
|
||||
const allowedHeaders = [
|
||||
'x-request-id',
|
||||
'anthropic-version', // 保留API版本
|
||||
'anthropic-beta' // 保留beta功能
|
||||
]
|
||||
|
||||
const filteredHeaders = {}
|
||||
|
||||
// 转发客户端的非敏感 headers
|
||||
Object.keys(clientHeaders || {}).forEach((key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
// 如果在允许列表中,直接保留
|
||||
if (allowedHeaders.includes(lowerKey)) {
|
||||
filteredHeaders[key] = clientHeaders[key]
|
||||
}
|
||||
// 如果不在敏感列表和浏览器列表中,也保留
|
||||
else if (!sensitiveHeaders.includes(lowerKey) && !browserHeaders.includes(lowerKey)) {
|
||||
filteredHeaders[key] = clientHeaders[key]
|
||||
}
|
||||
})
|
||||
|
||||
return filteredHeaders
|
||||
// 使用统一的 headerFilter 工具类 - 移除 CDN、浏览器和代理相关 headers
|
||||
// 同时伪装成正常的直接客户端请求,避免触发上游 API 的安全检查
|
||||
return filterForClaude(clientHeaders)
|
||||
}
|
||||
|
||||
_applyRequestIdentityTransform(body, headers, context = {}) {
|
||||
@@ -2249,26 +2193,7 @@ class ClaudeRelayService {
|
||||
|
||||
// 🧪 测试账号连接(供Admin API使用,直接复用 _makeClaudeStreamRequestWithUsageCapture)
|
||||
async testAccountConnection(accountId, responseStream) {
|
||||
const testRequestBody = {
|
||||
model: 'claude-sonnet-4-5-20250929',
|
||||
max_tokens: 100,
|
||||
stream: true,
|
||||
system: [
|
||||
{
|
||||
type: 'text',
|
||||
text: this.claudeCodeSystemPrompt,
|
||||
cache_control: {
|
||||
type: 'ephemeral'
|
||||
}
|
||||
}
|
||||
],
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: 'hi'
|
||||
}
|
||||
]
|
||||
}
|
||||
const testRequestBody = createClaudeTestPayload('claude-sonnet-4-5-20250929', { stream: true })
|
||||
|
||||
try {
|
||||
// 获取账户信息
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const axios = require('axios')
|
||||
const ProxyHelper = require('../utils/proxyHelper')
|
||||
const logger = require('../utils/logger')
|
||||
const { filterForOpenAI } = require('../utils/headerFilter')
|
||||
const openaiResponsesAccountService = require('./openaiResponsesAccountService')
|
||||
const apiKeyService = require('./apiKeyService')
|
||||
const unifiedOpenAIScheduler = require('./unifiedOpenAIScheduler')
|
||||
@@ -73,9 +74,9 @@ class OpenAIResponsesRelayService {
|
||||
const targetUrl = `${fullAccount.baseApi}${req.path}`
|
||||
logger.info(`🎯 Forwarding to: ${targetUrl}`)
|
||||
|
||||
// 构建请求头
|
||||
// 构建请求头 - 使用统一的 headerFilter 移除 CDN headers
|
||||
const headers = {
|
||||
...this._filterRequestHeaders(req.headers),
|
||||
...filterForOpenAI(req.headers),
|
||||
Authorization: `Bearer ${fullAccount.apiKey}`,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
@@ -810,29 +811,10 @@ class OpenAIResponsesRelayService {
|
||||
return { resetsInSeconds, errorData }
|
||||
}
|
||||
|
||||
// 过滤请求头
|
||||
// 过滤请求头 - 已迁移到 headerFilter 工具类
|
||||
// 此方法保留用于向后兼容,实际使用 filterForOpenAI()
|
||||
_filterRequestHeaders(headers) {
|
||||
const filtered = {}
|
||||
const skipHeaders = [
|
||||
'host',
|
||||
'content-length',
|
||||
'authorization',
|
||||
'x-api-key',
|
||||
'x-cr-api-key',
|
||||
'connection',
|
||||
'upgrade',
|
||||
'sec-websocket-key',
|
||||
'sec-websocket-version',
|
||||
'sec-websocket-extensions'
|
||||
]
|
||||
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (!skipHeaders.includes(key.toLowerCase())) {
|
||||
filtered[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
return filtered
|
||||
return filterForOpenAI(headers)
|
||||
}
|
||||
|
||||
// 估算费用(简化版本,实际应该根据不同的定价模型)
|
||||
|
||||
@@ -19,6 +19,12 @@ class UnifiedGeminiScheduler {
|
||||
return schedulable !== false && schedulable !== 'false'
|
||||
}
|
||||
|
||||
// 🔧 辅助方法:检查账户是否激活(兼容字符串和布尔值)
|
||||
_isActive(isActive) {
|
||||
// 兼容布尔值 true 和字符串 'true'
|
||||
return isActive === true || isActive === 'true'
|
||||
}
|
||||
|
||||
// 🎯 统一调度Gemini账号
|
||||
async selectAccountForApiKey(
|
||||
apiKeyData,
|
||||
@@ -35,7 +41,11 @@ class UnifiedGeminiScheduler {
|
||||
if (apiKeyData.geminiAccountId.startsWith('api:')) {
|
||||
const accountId = apiKeyData.geminiAccountId.replace('api:', '')
|
||||
const boundAccount = await geminiApiAccountService.getAccount(accountId)
|
||||
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
|
||||
if (
|
||||
boundAccount &&
|
||||
this._isActive(boundAccount.isActive) &&
|
||||
boundAccount.status !== 'error'
|
||||
) {
|
||||
logger.info(
|
||||
`🎯 Using bound Gemini-API account: ${boundAccount.name} (${accountId}) for API key ${apiKeyData.name}`
|
||||
)
|
||||
@@ -68,7 +78,11 @@ class UnifiedGeminiScheduler {
|
||||
// 普通 Gemini OAuth 专属账户
|
||||
else {
|
||||
const boundAccount = await geminiAccountService.getAccount(apiKeyData.geminiAccountId)
|
||||
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
|
||||
if (
|
||||
boundAccount &&
|
||||
this._isActive(boundAccount.isActive) &&
|
||||
boundAccount.status !== 'error'
|
||||
) {
|
||||
logger.info(
|
||||
`🎯 Using bound dedicated Gemini account: ${boundAccount.name} (${apiKeyData.geminiAccountId}) for API key ${apiKeyData.name}`
|
||||
)
|
||||
@@ -184,7 +198,11 @@ class UnifiedGeminiScheduler {
|
||||
if (apiKeyData.geminiAccountId.startsWith('api:')) {
|
||||
const accountId = apiKeyData.geminiAccountId.replace('api:', '')
|
||||
const boundAccount = await geminiApiAccountService.getAccount(accountId)
|
||||
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
|
||||
if (
|
||||
boundAccount &&
|
||||
this._isActive(boundAccount.isActive) &&
|
||||
boundAccount.status !== 'error'
|
||||
) {
|
||||
const isRateLimited = await this.isAccountRateLimited(accountId)
|
||||
if (!isRateLimited) {
|
||||
// 检查模型支持
|
||||
@@ -231,7 +249,11 @@ class UnifiedGeminiScheduler {
|
||||
// 普通 Gemini OAuth 账户
|
||||
else if (!apiKeyData.geminiAccountId.startsWith('group:')) {
|
||||
const boundAccount = await geminiAccountService.getAccount(apiKeyData.geminiAccountId)
|
||||
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
|
||||
if (
|
||||
boundAccount &&
|
||||
this._isActive(boundAccount.isActive) &&
|
||||
boundAccount.status !== 'error'
|
||||
) {
|
||||
const isRateLimited = await this.isAccountRateLimited(boundAccount.id)
|
||||
if (!isRateLimited) {
|
||||
// 检查模型支持
|
||||
@@ -276,7 +298,7 @@ class UnifiedGeminiScheduler {
|
||||
const geminiAccounts = await geminiAccountService.getAllAccounts()
|
||||
for (const account of geminiAccounts) {
|
||||
if (
|
||||
account.isActive === 'true' &&
|
||||
this._isActive(account.isActive) &&
|
||||
account.status !== 'error' &&
|
||||
(account.accountType === 'shared' || !account.accountType) && // 兼容旧数据
|
||||
this._isSchedulable(account.schedulable)
|
||||
@@ -326,7 +348,7 @@ class UnifiedGeminiScheduler {
|
||||
const geminiApiAccounts = await geminiApiAccountService.getAllAccounts()
|
||||
for (const account of geminiApiAccounts) {
|
||||
if (
|
||||
account.isActive === 'true' &&
|
||||
this._isActive(account.isActive) &&
|
||||
account.status !== 'error' &&
|
||||
(account.accountType === 'shared' || !account.accountType) &&
|
||||
this._isSchedulable(account.schedulable)
|
||||
@@ -386,7 +408,7 @@ class UnifiedGeminiScheduler {
|
||||
try {
|
||||
if (accountType === 'gemini') {
|
||||
const account = await geminiAccountService.getAccount(accountId)
|
||||
if (!account || account.isActive !== 'true' || account.status === 'error') {
|
||||
if (!account || !this._isActive(account.isActive) || account.status === 'error') {
|
||||
return false
|
||||
}
|
||||
// 检查是否可调度
|
||||
@@ -397,7 +419,7 @@ class UnifiedGeminiScheduler {
|
||||
return !(await this.isAccountRateLimited(accountId))
|
||||
} else if (accountType === 'gemini-api') {
|
||||
const account = await geminiApiAccountService.getAccount(accountId)
|
||||
if (!account || account.isActive !== 'true' || account.status === 'error') {
|
||||
if (!account || !this._isActive(account.isActive) || account.status === 'error') {
|
||||
return false
|
||||
}
|
||||
// 检查是否可调度
|
||||
@@ -643,7 +665,7 @@ class UnifiedGeminiScheduler {
|
||||
|
||||
// 检查账户是否可用
|
||||
if (
|
||||
account.isActive === 'true' &&
|
||||
this._isActive(account.isActive) &&
|
||||
account.status !== 'error' &&
|
||||
this._isSchedulable(account.schedulable)
|
||||
) {
|
||||
|
||||
@@ -834,11 +834,24 @@ class UnifiedOpenAIScheduler {
|
||||
throw error
|
||||
}
|
||||
|
||||
// 获取可用的分组成员账户
|
||||
// 获取可用的分组成员账户(支持 OpenAI 和 OpenAI-Responses 两种类型)
|
||||
const availableAccounts = []
|
||||
for (const memberId of memberIds) {
|
||||
const account = await openaiAccountService.getAccount(memberId)
|
||||
if (account && account.isActive && account.status !== 'error') {
|
||||
// 首先尝试从 OpenAI 账户服务获取
|
||||
let account = await openaiAccountService.getAccount(memberId)
|
||||
let accountType = 'openai'
|
||||
|
||||
// 如果 OpenAI 账户不存在,尝试从 OpenAI-Responses 账户服务获取
|
||||
if (!account) {
|
||||
account = await openaiResponsesAccountService.getAccount(memberId)
|
||||
accountType = 'openai-responses'
|
||||
}
|
||||
|
||||
if (
|
||||
account &&
|
||||
(account.isActive === true || account.isActive === 'true') &&
|
||||
account.status !== 'error'
|
||||
) {
|
||||
const readiness = await this._ensureAccountReadyForScheduling(account, account.id, {
|
||||
sanitized: false
|
||||
})
|
||||
@@ -846,23 +859,25 @@ class UnifiedOpenAIScheduler {
|
||||
if (!readiness.canUse) {
|
||||
if (readiness.reason === 'rate_limited') {
|
||||
logger.debug(
|
||||
`⏭️ Skipping group member OpenAI account ${account.name} - still rate limited`
|
||||
`⏭️ Skipping group member ${accountType} account ${account.name} - still rate limited`
|
||||
)
|
||||
} else {
|
||||
logger.debug(
|
||||
`⏭️ Skipping group member OpenAI account ${account.name} - not schedulable`
|
||||
`⏭️ Skipping group member ${accountType} account ${account.name} - not schedulable`
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查token是否过期
|
||||
const isExpired = openaiAccountService.isTokenExpired(account)
|
||||
if (isExpired && !account.refreshToken) {
|
||||
logger.warn(
|
||||
`⚠️ Group member OpenAI account ${account.name} token expired and no refresh token available`
|
||||
)
|
||||
continue
|
||||
// 检查token是否过期(仅对 OpenAI OAuth 账户检查)
|
||||
if (accountType === 'openai') {
|
||||
const isExpired = openaiAccountService.isTokenExpired(account)
|
||||
if (isExpired && !account.refreshToken) {
|
||||
logger.warn(
|
||||
`⚠️ Group member OpenAI account ${account.name} token expired and no refresh token available`
|
||||
)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// 检查模型支持(仅在明确设置了supportedModels且不为空时才检查)
|
||||
@@ -871,17 +886,17 @@ class UnifiedOpenAIScheduler {
|
||||
const modelSupported = account.supportedModels.includes(requestedModel)
|
||||
if (!modelSupported) {
|
||||
logger.debug(
|
||||
`⏭️ Skipping group member OpenAI account ${account.name} - doesn't support model ${requestedModel}`
|
||||
`⏭️ Skipping group member ${accountType} account ${account.name} - doesn't support model ${requestedModel}`
|
||||
)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否被限流
|
||||
// 添加到可用账户列表
|
||||
availableAccounts.push({
|
||||
...account,
|
||||
accountId: account.id,
|
||||
accountType: 'openai',
|
||||
accountType,
|
||||
priority: parseInt(account.priority) || 50,
|
||||
lastUsedAt: account.lastUsedAt || '0'
|
||||
})
|
||||
|
||||
133
src/utils/headerFilter.js
Normal file
133
src/utils/headerFilter.js
Normal file
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* 统一的 CDN Headers 过滤列表
|
||||
*
|
||||
* 用于各服务在原有过滤逻辑基础上,额外移除 Cloudflare CDN 和代理相关的 headers
|
||||
* 避免触发上游 API(如 88code)的安全检查
|
||||
*/
|
||||
|
||||
// Cloudflare CDN headers(橙色云代理模式会添加这些)
|
||||
const cdnHeaders = [
|
||||
'x-real-ip',
|
||||
'x-forwarded-for',
|
||||
'x-forwarded-proto',
|
||||
'x-forwarded-host',
|
||||
'x-forwarded-port',
|
||||
'x-accel-buffering',
|
||||
'cf-ray',
|
||||
'cf-connecting-ip',
|
||||
'cf-ipcountry',
|
||||
'cf-visitor',
|
||||
'cf-request-id',
|
||||
'cdn-loop',
|
||||
'true-client-ip'
|
||||
]
|
||||
|
||||
/**
|
||||
* 为 OpenAI/Responses API 过滤 headers
|
||||
* 在原有 skipHeaders 基础上添加 CDN headers
|
||||
*/
|
||||
function filterForOpenAI(headers) {
|
||||
const skipHeaders = [
|
||||
'host',
|
||||
'content-length',
|
||||
'authorization',
|
||||
'x-api-key',
|
||||
'x-cr-api-key',
|
||||
'connection',
|
||||
'upgrade',
|
||||
'sec-websocket-key',
|
||||
'sec-websocket-version',
|
||||
'sec-websocket-extensions',
|
||||
...cdnHeaders // 添加 CDN headers
|
||||
]
|
||||
|
||||
const filtered = {}
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (!skipHeaders.includes(key.toLowerCase())) {
|
||||
filtered[key] = value
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
/**
|
||||
* 为 Claude/Anthropic API 过滤 headers
|
||||
* 在原有逻辑基础上添加 CDN headers 到敏感列表
|
||||
*/
|
||||
function filterForClaude(headers) {
|
||||
const sensitiveHeaders = [
|
||||
'content-type',
|
||||
'user-agent',
|
||||
'x-api-key',
|
||||
'authorization',
|
||||
'x-authorization',
|
||||
'host',
|
||||
'content-length',
|
||||
'connection',
|
||||
'proxy-authorization',
|
||||
'content-encoding',
|
||||
'transfer-encoding',
|
||||
...cdnHeaders // 添加 CDN headers
|
||||
]
|
||||
|
||||
const browserHeaders = [
|
||||
'origin',
|
||||
'referer',
|
||||
'sec-fetch-mode',
|
||||
'sec-fetch-site',
|
||||
'sec-fetch-dest',
|
||||
'sec-ch-ua',
|
||||
'sec-ch-ua-mobile',
|
||||
'sec-ch-ua-platform',
|
||||
'accept-language',
|
||||
'accept-encoding',
|
||||
'accept',
|
||||
'cache-control',
|
||||
'pragma',
|
||||
'anthropic-dangerous-direct-browser-access'
|
||||
]
|
||||
|
||||
const allowedHeaders = ['x-request-id', 'anthropic-version', 'anthropic-beta']
|
||||
|
||||
const filtered = {}
|
||||
Object.keys(headers || {}).forEach((key) => {
|
||||
const lowerKey = key.toLowerCase()
|
||||
if (allowedHeaders.includes(lowerKey)) {
|
||||
filtered[key] = headers[key]
|
||||
} else if (!sensitiveHeaders.includes(lowerKey) && !browserHeaders.includes(lowerKey)) {
|
||||
filtered[key] = headers[key]
|
||||
}
|
||||
})
|
||||
|
||||
return filtered
|
||||
}
|
||||
|
||||
/**
|
||||
* 为 Gemini API 过滤 headers(如果需要转发客户端 headers 时使用)
|
||||
* 目前 Gemini 服务不转发客户端 headers,仅提供此方法备用
|
||||
*/
|
||||
function filterForGemini(headers) {
|
||||
const skipHeaders = [
|
||||
'host',
|
||||
'content-length',
|
||||
'authorization',
|
||||
'x-api-key',
|
||||
'connection',
|
||||
...cdnHeaders // 添加 CDN headers
|
||||
]
|
||||
|
||||
const filtered = {}
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (!skipHeaders.includes(key.toLowerCase())) {
|
||||
filtered[key] = value
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
cdnHeaders,
|
||||
filterForOpenAI,
|
||||
filterForClaude,
|
||||
filterForGemini
|
||||
}
|
||||
@@ -18,6 +18,13 @@ const OAUTH_CONFIG = {
|
||||
SCOPES_SETUP: 'user:inference' // Setup Token 只需要推理权限
|
||||
}
|
||||
|
||||
// Cookie自动授权配置常量
|
||||
const COOKIE_OAUTH_CONFIG = {
|
||||
CLAUDE_AI_URL: 'https://claude.ai',
|
||||
ORGANIZATIONS_URL: 'https://claude.ai/api/organizations',
|
||||
AUTHORIZE_URL_TEMPLATE: 'https://claude.ai/v1/oauth/{organization_uuid}/authorize'
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机的 state 参数
|
||||
* @returns {string} 随机生成的 state (base64url编码)
|
||||
@@ -570,8 +577,299 @@ function extractExtInfo(data) {
|
||||
return Object.keys(ext).length > 0 ? ext : null
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Cookie自动授权相关方法 (基于Clove项目实现)
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* 构建带Cookie的请求头
|
||||
* @param {string} sessionKey - sessionKey值
|
||||
* @returns {object} 请求头对象
|
||||
*/
|
||||
function buildCookieHeaders(sessionKey) {
|
||||
return {
|
||||
Accept: 'application/json',
|
||||
'Accept-Language': 'en-US,en;q=0.9',
|
||||
'Cache-Control': 'no-cache',
|
||||
Cookie: `sessionKey=${sessionKey}`,
|
||||
Origin: COOKIE_OAUTH_CONFIG.CLAUDE_AI_URL,
|
||||
Referer: `${COOKIE_OAUTH_CONFIG.CLAUDE_AI_URL}/new`,
|
||||
'User-Agent':
|
||||
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用Cookie获取组织UUID和能力列表
|
||||
* @param {string} sessionKey - sessionKey值
|
||||
* @param {object|null} proxyConfig - 代理配置(可选)
|
||||
* @returns {Promise<{organizationUuid: string, capabilities: string[]}>}
|
||||
*/
|
||||
async function getOrganizationInfo(sessionKey, proxyConfig = null) {
|
||||
const headers = buildCookieHeaders(sessionKey)
|
||||
const agent = createProxyAgent(proxyConfig)
|
||||
|
||||
try {
|
||||
if (agent) {
|
||||
logger.info(`🌐 Using proxy for organization info: ${ProxyHelper.maskProxyInfo(proxyConfig)}`)
|
||||
}
|
||||
|
||||
logger.debug('🔄 Fetching organization info with Cookie', {
|
||||
url: COOKIE_OAUTH_CONFIG.ORGANIZATIONS_URL,
|
||||
hasProxy: !!proxyConfig
|
||||
})
|
||||
|
||||
const axiosConfig = {
|
||||
headers,
|
||||
timeout: 30000,
|
||||
maxRedirects: 0 // 禁止自动重定向,以便检测Cloudflare拦截(302)
|
||||
}
|
||||
|
||||
if (agent) {
|
||||
axiosConfig.httpAgent = agent
|
||||
axiosConfig.httpsAgent = agent
|
||||
axiosConfig.proxy = false
|
||||
}
|
||||
|
||||
const response = await axios.get(COOKIE_OAUTH_CONFIG.ORGANIZATIONS_URL, axiosConfig)
|
||||
|
||||
if (!response.data || !Array.isArray(response.data)) {
|
||||
throw new Error('获取组织信息失败:响应格式无效')
|
||||
}
|
||||
|
||||
// 找到具有chat能力且能力最多的组织
|
||||
let bestOrg = null
|
||||
let maxCapabilities = []
|
||||
|
||||
for (const org of response.data) {
|
||||
const capabilities = org.capabilities || []
|
||||
|
||||
// 必须有chat能力
|
||||
if (!capabilities.includes('chat')) {
|
||||
continue
|
||||
}
|
||||
|
||||
// 选择能力最多的组织
|
||||
if (capabilities.length > maxCapabilities.length) {
|
||||
bestOrg = org
|
||||
maxCapabilities = capabilities
|
||||
}
|
||||
}
|
||||
|
||||
if (!bestOrg || !bestOrg.uuid) {
|
||||
throw new Error('未找到具有chat能力的组织')
|
||||
}
|
||||
|
||||
logger.success('✅ Found organization', {
|
||||
uuid: bestOrg.uuid,
|
||||
capabilities: maxCapabilities
|
||||
})
|
||||
|
||||
return {
|
||||
organizationUuid: bestOrg.uuid,
|
||||
capabilities: maxCapabilities
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.response) {
|
||||
const { status } = error.response
|
||||
|
||||
if (status === 403 || status === 401) {
|
||||
throw new Error('Cookie授权失败:无效的sessionKey或已过期')
|
||||
}
|
||||
|
||||
if (status === 302) {
|
||||
throw new Error('请求被Cloudflare拦截,请稍后重试')
|
||||
}
|
||||
|
||||
throw new Error(`获取组织信息失败:HTTP ${status}`)
|
||||
} else if (error.request) {
|
||||
throw new Error('获取组织信息失败:网络错误或超时')
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用Cookie自动获取授权code
|
||||
* @param {string} sessionKey - sessionKey值
|
||||
* @param {string} organizationUuid - 组织UUID
|
||||
* @param {string} scope - 授权scope
|
||||
* @param {object|null} proxyConfig - 代理配置(可选)
|
||||
* @returns {Promise<{authorizationCode: string, codeVerifier: string, state: string}>}
|
||||
*/
|
||||
async function authorizeWithCookie(sessionKey, organizationUuid, scope, proxyConfig = null) {
|
||||
// 生成PKCE参数
|
||||
const codeVerifier = generateCodeVerifier()
|
||||
const codeChallenge = generateCodeChallenge(codeVerifier)
|
||||
const state = generateState()
|
||||
|
||||
// 构建授权URL
|
||||
const authorizeUrl = COOKIE_OAUTH_CONFIG.AUTHORIZE_URL_TEMPLATE.replace(
|
||||
'{organization_uuid}',
|
||||
organizationUuid
|
||||
)
|
||||
|
||||
// 构建请求payload
|
||||
const payload = {
|
||||
response_type: 'code',
|
||||
client_id: OAUTH_CONFIG.CLIENT_ID,
|
||||
organization_uuid: organizationUuid,
|
||||
redirect_uri: OAUTH_CONFIG.REDIRECT_URI,
|
||||
scope,
|
||||
state,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256'
|
||||
}
|
||||
|
||||
const headers = {
|
||||
...buildCookieHeaders(sessionKey),
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
const agent = createProxyAgent(proxyConfig)
|
||||
|
||||
try {
|
||||
if (agent) {
|
||||
logger.info(
|
||||
`🌐 Using proxy for Cookie authorization: ${ProxyHelper.maskProxyInfo(proxyConfig)}`
|
||||
)
|
||||
}
|
||||
|
||||
logger.debug('🔄 Requesting authorization with Cookie', {
|
||||
url: authorizeUrl,
|
||||
scope,
|
||||
hasProxy: !!proxyConfig
|
||||
})
|
||||
|
||||
const axiosConfig = {
|
||||
headers,
|
||||
timeout: 30000,
|
||||
maxRedirects: 0 // 禁止自动重定向,以便检测Cloudflare拦截(302)
|
||||
}
|
||||
|
||||
if (agent) {
|
||||
axiosConfig.httpAgent = agent
|
||||
axiosConfig.httpsAgent = agent
|
||||
axiosConfig.proxy = false
|
||||
}
|
||||
|
||||
const response = await axios.post(authorizeUrl, payload, axiosConfig)
|
||||
|
||||
// 从响应中获取redirect_uri
|
||||
const redirectUri = response.data?.redirect_uri
|
||||
|
||||
if (!redirectUri) {
|
||||
throw new Error('授权响应中未找到redirect_uri')
|
||||
}
|
||||
|
||||
logger.debug('📎 Got redirect URI', { redirectUri: `${redirectUri.substring(0, 80)}...` })
|
||||
|
||||
// 解析redirect_uri获取authorization code
|
||||
const url = new URL(redirectUri)
|
||||
const authorizationCode = url.searchParams.get('code')
|
||||
const responseState = url.searchParams.get('state')
|
||||
|
||||
if (!authorizationCode) {
|
||||
throw new Error('redirect_uri中未找到授权码')
|
||||
}
|
||||
|
||||
// 构建完整的授权码(包含state,如果有的话)
|
||||
const fullCode = responseState ? `${authorizationCode}#${responseState}` : authorizationCode
|
||||
|
||||
logger.success('✅ Got authorization code via Cookie', {
|
||||
codeLength: authorizationCode.length,
|
||||
codePrefix: `${authorizationCode.substring(0, 10)}...`
|
||||
})
|
||||
|
||||
return {
|
||||
authorizationCode: fullCode,
|
||||
codeVerifier,
|
||||
state
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.response) {
|
||||
const { status } = error.response
|
||||
|
||||
if (status === 403 || status === 401) {
|
||||
throw new Error('Cookie授权失败:无效的sessionKey或已过期')
|
||||
}
|
||||
|
||||
if (status === 302) {
|
||||
throw new Error('请求被Cloudflare拦截,请稍后重试')
|
||||
}
|
||||
|
||||
const errorData = error.response.data
|
||||
let errorMessage = `HTTP ${status}`
|
||||
|
||||
if (errorData) {
|
||||
if (typeof errorData === 'string') {
|
||||
errorMessage += `: ${errorData}`
|
||||
} else if (errorData.error) {
|
||||
errorMessage += `: ${errorData.error}`
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`授权请求失败:${errorMessage}`)
|
||||
} else if (error.request) {
|
||||
throw new Error('授权请求失败:网络错误或超时')
|
||||
}
|
||||
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整的Cookie自动授权流程
|
||||
* @param {string} sessionKey - sessionKey值
|
||||
* @param {object|null} proxyConfig - 代理配置(可选)
|
||||
* @param {boolean} isSetupToken - 是否为Setup Token模式
|
||||
* @returns {Promise<{claudeAiOauth: object, organizationUuid: string, capabilities: string[]}>}
|
||||
*/
|
||||
async function oauthWithCookie(sessionKey, proxyConfig = null, isSetupToken = false) {
|
||||
logger.info('🍪 Starting Cookie-based OAuth flow', {
|
||||
isSetupToken,
|
||||
hasProxy: !!proxyConfig
|
||||
})
|
||||
|
||||
// 步骤1:获取组织信息
|
||||
logger.debug('Step 1/3: Fetching organization info...')
|
||||
const { organizationUuid, capabilities } = await getOrganizationInfo(sessionKey, proxyConfig)
|
||||
|
||||
// 步骤2:确定scope并获取授权code
|
||||
const scope = isSetupToken ? OAUTH_CONFIG.SCOPES_SETUP : 'user:profile user:inference'
|
||||
|
||||
logger.debug('Step 2/3: Getting authorization code...', { scope })
|
||||
const { authorizationCode, codeVerifier, state } = await authorizeWithCookie(
|
||||
sessionKey,
|
||||
organizationUuid,
|
||||
scope,
|
||||
proxyConfig
|
||||
)
|
||||
|
||||
// 步骤3:交换token
|
||||
logger.debug('Step 3/3: Exchanging token...')
|
||||
const tokenData = isSetupToken
|
||||
? await exchangeSetupTokenCode(authorizationCode, codeVerifier, state, proxyConfig)
|
||||
: await exchangeCodeForTokens(authorizationCode, codeVerifier, state, proxyConfig)
|
||||
|
||||
logger.success('✅ Cookie-based OAuth flow completed', {
|
||||
isSetupToken,
|
||||
organizationUuid,
|
||||
hasAccessToken: !!tokenData.accessToken,
|
||||
hasRefreshToken: !!tokenData.refreshToken
|
||||
})
|
||||
|
||||
return {
|
||||
claudeAiOauth: tokenData,
|
||||
organizationUuid,
|
||||
capabilities
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
OAUTH_CONFIG,
|
||||
COOKIE_OAUTH_CONFIG,
|
||||
generateOAuthParams,
|
||||
generateSetupTokenParams,
|
||||
exchangeCodeForTokens,
|
||||
@@ -584,5 +882,10 @@ module.exports = {
|
||||
generateCodeChallenge,
|
||||
generateAuthUrl,
|
||||
generateSetupTokenAuthUrl,
|
||||
createProxyAgent
|
||||
createProxyAgent,
|
||||
// Cookie自动授权相关方法
|
||||
buildCookieHeaders,
|
||||
getOrganizationInfo,
|
||||
authorizeWithCookie,
|
||||
oauthWithCookie
|
||||
}
|
||||
|
||||
242
src/utils/testPayloadHelper.js
Normal file
242
src/utils/testPayloadHelper.js
Normal file
@@ -0,0 +1,242 @@
|
||||
const crypto = require('crypto')
|
||||
|
||||
/**
|
||||
* 生成随机十六进制字符串
|
||||
* @param {number} bytes - 字节数
|
||||
* @returns {string} 十六进制字符串
|
||||
*/
|
||||
function randomHex(bytes = 32) {
|
||||
return crypto.randomBytes(bytes).toString('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 Claude Code 风格的会话字符串
|
||||
* @returns {string} 会话字符串,格式: user_{64位hex}_account__session_{uuid}
|
||||
*/
|
||||
function generateSessionString() {
|
||||
const hex64 = randomHex(32) // 32 bytes => 64 hex characters
|
||||
const uuid = crypto.randomUUID()
|
||||
return `user_${hex64}_account__session_${uuid}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 Claude 测试请求体
|
||||
* @param {string} model - 模型名称
|
||||
* @param {object} options - 可选配置
|
||||
* @param {boolean} options.stream - 是否流式(默认false)
|
||||
* @returns {object} 测试请求体
|
||||
*/
|
||||
function createClaudeTestPayload(model = 'claude-sonnet-4-5-20250929', options = {}) {
|
||||
const payload = {
|
||||
model,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'hi',
|
||||
cache_control: {
|
||||
type: 'ephemeral'
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
system: [
|
||||
{
|
||||
type: 'text',
|
||||
text: "You are Claude Code, Anthropic's official CLI for Claude.",
|
||||
cache_control: {
|
||||
type: 'ephemeral'
|
||||
}
|
||||
}
|
||||
],
|
||||
metadata: {
|
||||
user_id: generateSessionString()
|
||||
},
|
||||
max_tokens: 21333,
|
||||
temperature: 1
|
||||
}
|
||||
|
||||
if (options.stream) {
|
||||
payload.stream = true
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送流式测试请求并处理SSE响应
|
||||
* @param {object} options - 配置选项
|
||||
* @param {string} options.apiUrl - API URL
|
||||
* @param {string} options.authorization - Authorization header值
|
||||
* @param {object} options.responseStream - Express响应流
|
||||
* @param {object} [options.payload] - 请求体(默认使用createClaudeTestPayload)
|
||||
* @param {object} [options.proxyAgent] - 代理agent
|
||||
* @param {number} [options.timeout] - 超时时间(默认30000)
|
||||
* @param {object} [options.extraHeaders] - 额外的请求头
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function sendStreamTestRequest(options) {
|
||||
const axios = require('axios')
|
||||
const logger = require('./logger')
|
||||
|
||||
const {
|
||||
apiUrl,
|
||||
authorization,
|
||||
responseStream,
|
||||
payload = createClaudeTestPayload('claude-sonnet-4-5-20250929', { stream: true }),
|
||||
proxyAgent = null,
|
||||
timeout = 30000,
|
||||
extraHeaders = {}
|
||||
} = options
|
||||
|
||||
const sendSSE = (type, data = {}) => {
|
||||
if (!responseStream.destroyed && !responseStream.writableEnded) {
|
||||
try {
|
||||
responseStream.write(`data: ${JSON.stringify({ type, ...data })}\n\n`)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const endTest = (success, error = null) => {
|
||||
if (!responseStream.destroyed && !responseStream.writableEnded) {
|
||||
try {
|
||||
responseStream.write(
|
||||
`data: ${JSON.stringify({ type: 'test_complete', success, error: error || undefined })}\n\n`
|
||||
)
|
||||
responseStream.end()
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 设置响应头
|
||||
if (!responseStream.headersSent) {
|
||||
responseStream.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
Connection: 'keep-alive',
|
||||
'X-Accel-Buffering': 'no'
|
||||
})
|
||||
}
|
||||
|
||||
sendSSE('test_start', { message: 'Test started' })
|
||||
|
||||
const requestConfig = {
|
||||
method: 'POST',
|
||||
url: apiUrl,
|
||||
data: payload,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'anthropic-version': '2023-06-01',
|
||||
'User-Agent': 'claude-cli/2.0.52 (external, cli)',
|
||||
authorization,
|
||||
...extraHeaders
|
||||
},
|
||||
timeout,
|
||||
responseType: 'stream',
|
||||
validateStatus: () => true
|
||||
}
|
||||
|
||||
if (proxyAgent) {
|
||||
requestConfig.httpAgent = proxyAgent
|
||||
requestConfig.httpsAgent = proxyAgent
|
||||
requestConfig.proxy = false
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await axios(requestConfig)
|
||||
logger.debug(`🌊 Test response status: ${response.status}`)
|
||||
|
||||
// 处理非200响应
|
||||
if (response.status !== 200) {
|
||||
return new Promise((resolve) => {
|
||||
const chunks = []
|
||||
response.data.on('data', (chunk) => chunks.push(chunk))
|
||||
response.data.on('end', () => {
|
||||
const errorData = Buffer.concat(chunks).toString()
|
||||
let errorMsg = `API Error: ${response.status}`
|
||||
try {
|
||||
const json = JSON.parse(errorData)
|
||||
errorMsg = json.message || json.error?.message || json.error || errorMsg
|
||||
} catch {
|
||||
if (errorData.length < 200) {
|
||||
errorMsg = errorData || errorMsg
|
||||
}
|
||||
}
|
||||
endTest(false, errorMsg)
|
||||
resolve()
|
||||
})
|
||||
response.data.on('error', (err) => {
|
||||
endTest(false, err.message)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 处理成功的流式响应
|
||||
return new Promise((resolve) => {
|
||||
let buffer = ''
|
||||
|
||||
response.data.on('data', (chunk) => {
|
||||
buffer += chunk.toString()
|
||||
const lines = buffer.split('\n')
|
||||
buffer = lines.pop() || ''
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith('data:')) {
|
||||
continue
|
||||
}
|
||||
const jsonStr = line.substring(5).trim()
|
||||
if (!jsonStr || jsonStr === '[DONE]') {
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
const data = JSON.parse(jsonStr)
|
||||
|
||||
if (data.type === 'content_block_delta' && data.delta?.text) {
|
||||
sendSSE('content', { text: data.delta.text })
|
||||
}
|
||||
if (data.type === 'message_stop') {
|
||||
sendSSE('message_stop')
|
||||
}
|
||||
if (data.type === 'error' || data.error) {
|
||||
const errMsg = data.error?.message || data.message || data.error || 'Unknown error'
|
||||
sendSSE('error', { error: errMsg })
|
||||
}
|
||||
} catch {
|
||||
// ignore parse errors
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
response.data.on('end', () => {
|
||||
if (!responseStream.destroyed && !responseStream.writableEnded) {
|
||||
endTest(true)
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
|
||||
response.data.on('error', (err) => {
|
||||
endTest(false, err.message)
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('❌ Stream test request failed:', error.message)
|
||||
endTest(false, error.message)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
randomHex,
|
||||
generateSessionString,
|
||||
createClaudeTestPayload,
|
||||
sendStreamTestRequest
|
||||
}
|
||||
17
web/admin-spa/package-lock.json
generated
17
web/admin-spa/package-lock.json
generated
@@ -1157,6 +1157,7 @@
|
||||
"resolved": "https://registry.npmmirror.com/@types/lodash-es/-/lodash-es-4.17.12.tgz",
|
||||
"integrity": "sha512-0NgftHUcV4v34VhXm8QBSftKVXtbkBG3ViCjs6+eJ5a6y6Mi/jiFGPc1sC7QK+9BFhWrURE3EOggmWaSxL9OzQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/lodash": "*"
|
||||
}
|
||||
@@ -1351,6 +1352,7 @@
|
||||
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"acorn": "bin/acorn"
|
||||
},
|
||||
@@ -1587,6 +1589,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"caniuse-lite": "^1.0.30001726",
|
||||
"electron-to-chromium": "^1.5.173",
|
||||
@@ -3060,13 +3063,15 @@
|
||||
"version": "4.17.21",
|
||||
"resolved": "https://registry.npmmirror.com/lodash/-/lodash-4.17.21.tgz",
|
||||
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/lodash-es": {
|
||||
"version": "4.17.21",
|
||||
"resolved": "https://registry.npmmirror.com/lodash-es/-/lodash-es-4.17.21.tgz",
|
||||
"integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==",
|
||||
"license": "MIT"
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/lodash-unified": {
|
||||
"version": "1.0.3",
|
||||
@@ -3618,6 +3623,7 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.11",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -3764,6 +3770,7 @@
|
||||
"integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"prettier": "bin/prettier.cjs"
|
||||
},
|
||||
@@ -3789,7 +3796,7 @@
|
||||
},
|
||||
"node_modules/prettier-plugin-tailwindcss": {
|
||||
"version": "0.6.14",
|
||||
"resolved": "https://registry.npmmirror.com/prettier-plugin-tailwindcss/-/prettier-plugin-tailwindcss-0.6.14.tgz",
|
||||
"resolved": "https://registry.npmjs.org/prettier-plugin-tailwindcss/-/prettier-plugin-tailwindcss-0.6.14.tgz",
|
||||
"integrity": "sha512-pi2e/+ZygeIqntN+vC573BcW5Cve8zUB0SSAGxqpB4f96boZF4M3phPVoOFCeypwkpRYdi7+jQ5YJJUwrkGUAg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
@@ -4028,6 +4035,7 @@
|
||||
"integrity": "sha512-33xGNBsDJAkzt0PvninskHlWnTIPgDtTwhg0U38CUoNP/7H6wI2Cz6dUeoNPbjdTdsYTGuiFFASuUOWovH0SyQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@types/estree": "1.0.8"
|
||||
},
|
||||
@@ -4525,6 +4533,7 @@
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -4915,6 +4924,7 @@
|
||||
"integrity": "sha512-qO3aKv3HoQC8QKiNSTuUM1l9o/XX3+c+VTgLHbJWHZGeTPVAg2XwazI9UWzoxjIJCGCV2zU60uqMzjeLZuULqA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"esbuild": "^0.21.3",
|
||||
"postcss": "^8.4.43",
|
||||
@@ -5115,6 +5125,7 @@
|
||||
"resolved": "https://registry.npmmirror.com/vue/-/vue-3.5.18.tgz",
|
||||
"integrity": "sha512-7W4Y4ZbMiQ3SEo+m9lnoNpV9xG7QVMLa+/0RFwwiAVkeYoyGXqWE85jabU4pllJNUzqfLShJ5YLptewhCWUgNA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@vue/compiler-dom": "3.5.18",
|
||||
"@vue/compiler-sfc": "3.5.18",
|
||||
|
||||
@@ -1451,6 +1451,26 @@
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 上游错误处理 -->
|
||||
<div v-if="form.platform === 'claude-console'">
|
||||
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||
>上游错误处理</label
|
||||
>
|
||||
<label class="inline-flex cursor-pointer items-center">
|
||||
<input
|
||||
v-model="form.disableAutoProtection"
|
||||
class="mr-2 rounded border-gray-300 text-blue-600 focus:border-blue-500 focus:ring focus:ring-blue-200 dark:border-gray-600 dark:bg-gray-700"
|
||||
type="checkbox"
|
||||
/>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300">
|
||||
上游错误不自动暂停调度
|
||||
</span>
|
||||
</label>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
勾选后遇到 401/400/429/529 等上游错误仅记录日志并透传,不自动禁用或限流
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- OpenAI-Responses 特定字段 -->
|
||||
@@ -1524,24 +1544,32 @@
|
||||
<input
|
||||
v-model="form.baseUrl"
|
||||
class="form-input w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 dark:placeholder-gray-400"
|
||||
placeholder="https://generativelanguage.googleapis.com"
|
||||
:class="{ 'border-red-500 dark:border-red-400': errors.baseUrl }"
|
||||
placeholder="https://generativelanguage.googleapis.com/v1beta/models"
|
||||
required
|
||||
type="url"
|
||||
/>
|
||||
<p v-if="errors.baseUrl" class="mt-1 text-xs text-red-500 dark:text-red-400">
|
||||
{{ errors.baseUrl }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
填写 API 基础地址(可包含路径前缀),系统会自动拼接
|
||||
填写 API 基础地址,必须以
|
||||
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600">/models</code>
|
||||
结尾。系统会自动拼接
|
||||
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||
>/v1beta/models/{model}:generateContent</code
|
||||
>/{model}:generateContent</code
|
||||
>
|
||||
</p>
|
||||
<p class="mt-0.5 text-xs text-gray-400 dark:text-gray-500">
|
||||
官方:
|
||||
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||
>https://generativelanguage.googleapis.com</code
|
||||
>https://generativelanguage.googleapis.com/v1beta/models</code
|
||||
>
|
||||
| 上游为 CRS:
|
||||
</p>
|
||||
<p class="mt-0.5 text-xs text-gray-400 dark:text-gray-500">
|
||||
上游为 CRS:
|
||||
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||
>https://your-crs.com/gemini</code
|
||||
>https://your-crs.com/gemini/v1beta/models</code
|
||||
>
|
||||
</p>
|
||||
</div>
|
||||
@@ -2021,6 +2049,7 @@
|
||||
<!-- 步骤2: OAuth授权 -->
|
||||
<OAuthFlow
|
||||
v-if="oauthStep === 2 && form.addType === 'oauth'"
|
||||
ref="oauthFlowRef"
|
||||
:platform="form.platform"
|
||||
:proxy="form.proxy"
|
||||
@back="oauthStep = 1"
|
||||
@@ -2044,11 +2073,45 @@
|
||||
<h4 class="mb-3 font-semibold text-blue-900 dark:text-blue-200">
|
||||
Claude Setup Token 授权
|
||||
</h4>
|
||||
<p class="mb-4 text-sm text-blue-800 dark:text-blue-300">
|
||||
请按照以下步骤通过 Setup Token 完成 Claude 账户的授权:
|
||||
</p>
|
||||
|
||||
<div class="space-y-4">
|
||||
<!-- 授权方式选择 -->
|
||||
<div class="mb-4">
|
||||
<p class="mb-3 text-sm font-medium text-blue-800 dark:text-blue-300">
|
||||
选择授权方式:
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-4">
|
||||
<label class="flex cursor-pointer items-center">
|
||||
<input
|
||||
v-model="authMethod"
|
||||
class="mr-2 text-blue-600 focus:ring-blue-500"
|
||||
type="radio"
|
||||
value="manual"
|
||||
@change="onAuthMethodChange"
|
||||
/>
|
||||
<span class="text-sm text-blue-800 dark:text-blue-300">
|
||||
<i class="fas fa-link mr-1" />手动授权
|
||||
</span>
|
||||
</label>
|
||||
<label class="flex cursor-pointer items-center">
|
||||
<input
|
||||
v-model="authMethod"
|
||||
class="mr-2 text-blue-600 focus:ring-blue-500"
|
||||
type="radio"
|
||||
value="cookie"
|
||||
@change="onAuthMethodChange"
|
||||
/>
|
||||
<span class="text-sm text-blue-800 dark:text-blue-300">
|
||||
<i class="fas fa-cookie mr-1" />Cookie 自动授权
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 手动授权流程 -->
|
||||
<div v-if="authMethod === 'manual'" class="space-y-4">
|
||||
<p class="mb-4 text-sm text-blue-800 dark:text-blue-300">
|
||||
请按照以下步骤通过 Setup Token 完成 Claude 账户的授权:
|
||||
</p>
|
||||
<!-- 步骤1: 生成授权链接 -->
|
||||
<div
|
||||
class="rounded-lg border border-blue-300 bg-white/80 p-4 dark:border-blue-600 dark:bg-gray-800/80"
|
||||
@@ -2174,6 +2237,113 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Cookie自动授权流程 -->
|
||||
<div v-if="authMethod === 'cookie'" class="space-y-4">
|
||||
<p class="mb-4 text-sm text-blue-800 dark:text-blue-300">
|
||||
使用 sessionKey 自动完成授权,无需手动打开链接。
|
||||
</p>
|
||||
|
||||
<div
|
||||
class="rounded-lg border border-blue-300 bg-white/80 p-4 dark:border-blue-600 dark:bg-gray-800/80"
|
||||
>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label
|
||||
class="mb-2 flex items-center gap-2 text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
<i class="fas fa-cookie text-blue-500" />sessionKey
|
||||
<span
|
||||
v-if="parsedSessionKeyCount > 1"
|
||||
class="rounded-full bg-blue-500 px-2 py-0.5 text-xs text-white"
|
||||
>
|
||||
{{ parsedSessionKeyCount }} 个
|
||||
</span>
|
||||
</label>
|
||||
<textarea
|
||||
v-model="sessionKey"
|
||||
class="form-input w-full resize-y border-gray-300 font-mono text-sm dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200 dark:placeholder-gray-400"
|
||||
:class="{ 'border-red-500': cookieAuthError }"
|
||||
placeholder="每行一个 sessionKey,例如: sk-ant-sid01-xxxxx... sk-ant-sid01-yyyyy..."
|
||||
rows="3"
|
||||
/>
|
||||
<p
|
||||
v-if="parsedSessionKeyCount > 1"
|
||||
class="mt-1 text-xs text-blue-600 dark:text-blue-400"
|
||||
>
|
||||
<i class="fas fa-info-circle mr-1" />
|
||||
将批量创建 {{ parsedSessionKeyCount }} 个账户
|
||||
</p>
|
||||
<p v-if="cookieAuthError" class="mt-1 text-xs text-red-500">
|
||||
{{ cookieAuthError }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 帮助说明 -->
|
||||
<div>
|
||||
<button
|
||||
class="flex items-center text-xs text-blue-600 hover:text-blue-700"
|
||||
type="button"
|
||||
@click="showSessionKeyHelp = !showSessionKeyHelp"
|
||||
>
|
||||
<i
|
||||
:class="
|
||||
showSessionKeyHelp
|
||||
? 'fas fa-chevron-down mr-1'
|
||||
: 'fas fa-chevron-right mr-1'
|
||||
"
|
||||
/>
|
||||
如何获取 sessionKey?
|
||||
</button>
|
||||
<div
|
||||
v-if="showSessionKeyHelp"
|
||||
class="mt-3 rounded border border-gray-200 bg-gray-50 p-3 dark:border-gray-600 dark:bg-gray-700"
|
||||
>
|
||||
<ol class="space-y-2 text-xs text-gray-600 dark:text-gray-300">
|
||||
<li>1. 在浏览器中登录 <strong>claude.ai</strong></li>
|
||||
<li>2. 按 <strong>F12</strong> 打开开发者工具</li>
|
||||
<li>3. 切换到 <strong>"Application"</strong> (应用) 标签页</li>
|
||||
<li>
|
||||
4. 在左侧选择 <strong>"Cookies"</strong> →
|
||||
<strong>"https://claude.ai"</strong>
|
||||
</li>
|
||||
<li>5. 找到键为 <strong>"sessionKey"</strong> 的那一行</li>
|
||||
<li>6. 复制其 <strong>"Value"</strong> (值) 列的内容</li>
|
||||
</ol>
|
||||
<p class="mt-2 text-xs text-gray-500 dark:text-gray-400">
|
||||
<i class="fas fa-info-circle mr-1" />
|
||||
sessionKey 通常以 "sk-ant-" 开头
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 开始授权按钮 -->
|
||||
<button
|
||||
class="btn btn-primary w-full px-4 py-3"
|
||||
:disabled="cookieAuthLoading || !sessionKey.trim()"
|
||||
type="button"
|
||||
@click="handleCookieAuth"
|
||||
>
|
||||
<div v-if="cookieAuthLoading" class="loading-spinner mr-2" />
|
||||
<i v-else class="fas fa-magic mr-2" />
|
||||
<template v-if="cookieAuthLoading && batchProgress.total > 1">
|
||||
正在授权 {{ batchProgress.current }}/{{ batchProgress.total }}...
|
||||
</template>
|
||||
<template v-else-if="cookieAuthLoading"> 授权中... </template>
|
||||
<template v-else> 开始自动授权 </template>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="rounded border border-yellow-300 bg-yellow-50 p-3 dark:border-yellow-700 dark:bg-yellow-900/30"
|
||||
>
|
||||
<p class="text-xs text-yellow-800 dark:text-yellow-300">
|
||||
<i class="fas fa-exclamation-triangle mr-1" />
|
||||
<strong>提示:</strong>如果您设置了代理,Cookie授权也会使用相同的代理配置。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -2188,6 +2358,7 @@
|
||||
上一步
|
||||
</button>
|
||||
<button
|
||||
v-if="authMethod === 'manual'"
|
||||
class="btn btn-primary flex-1 px-6 py-3 font-semibold"
|
||||
:disabled="!canExchangeSetupToken || setupTokenExchanging"
|
||||
type="button"
|
||||
@@ -2919,6 +3090,26 @@
|
||||
<p class="mt-1 text-xs text-gray-500">账号被限流后暂停调度的时间(分钟)</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 上游错误处理(编辑模式)-->
|
||||
<div v-if="form.platform === 'claude-console'">
|
||||
<label class="mb-3 block text-sm font-semibold text-gray-700 dark:text-gray-300">
|
||||
上游错误处理
|
||||
</label>
|
||||
<label class="inline-flex cursor-pointer items-center">
|
||||
<input
|
||||
v-model="form.disableAutoProtection"
|
||||
class="mr-2 rounded border-gray-300 text-blue-600 focus:border-blue-500 focus:ring focus:ring-blue-200 dark:border-gray-600 dark:bg-gray-700"
|
||||
type="checkbox"
|
||||
/>
|
||||
<span class="text-sm text-gray-700 dark:text-gray-300">
|
||||
上游错误不自动暂停调度
|
||||
</span>
|
||||
</label>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
勾选后遇到 401/400/429/529 等上游错误仅记录日志并透传,不自动禁用或限流
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- OpenAI-Responses 特定字段(编辑模式)-->
|
||||
@@ -3025,23 +3216,31 @@
|
||||
<input
|
||||
v-model="form.baseUrl"
|
||||
class="form-input w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200"
|
||||
placeholder="https://generativelanguage.googleapis.com"
|
||||
:class="{ 'border-red-500 dark:border-red-400': errors.baseUrl }"
|
||||
placeholder="https://generativelanguage.googleapis.com/v1beta/models"
|
||||
type="url"
|
||||
/>
|
||||
<p v-if="errors.baseUrl" class="mt-1 text-xs text-red-500 dark:text-red-400">
|
||||
{{ errors.baseUrl }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
填写 API 基础地址(可包含路径前缀),系统会自动拼接
|
||||
填写 API 基础地址,必须以
|
||||
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600">/models</code>
|
||||
结尾。系统会自动拼接
|
||||
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||
>/v1beta/models/{model}:generateContent</code
|
||||
>/{model}:generateContent</code
|
||||
>
|
||||
</p>
|
||||
<p class="mt-0.5 text-xs text-gray-400 dark:text-gray-500">
|
||||
官方:
|
||||
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||
>https://generativelanguage.googleapis.com</code
|
||||
>https://generativelanguage.googleapis.com/v1beta/models</code
|
||||
>
|
||||
| 上游为 CRS:
|
||||
</p>
|
||||
<p class="mt-0.5 text-xs text-gray-400 dark:text-gray-500">
|
||||
上游为 CRS:
|
||||
<code class="rounded bg-gray-100 px-1 dark:bg-gray-600"
|
||||
>https://your-crs.com/gemini</code
|
||||
>https://your-crs.com/gemini/v1beta/models</code
|
||||
>
|
||||
</p>
|
||||
</div>
|
||||
@@ -3522,6 +3721,9 @@ const { showConfirmModal, confirmOptions, showConfirm, handleConfirm, handleCanc
|
||||
const isEdit = computed(() => !!props.account)
|
||||
const show = ref(true)
|
||||
|
||||
// OAuthFlow 组件引用
|
||||
const oauthFlowRef = ref(null)
|
||||
|
||||
// OAuth步骤
|
||||
const oauthStep = ref(1)
|
||||
const loading = ref(false)
|
||||
@@ -3535,6 +3737,22 @@ const setupTokenAuthCode = ref('')
|
||||
const setupTokenCopied = ref(false)
|
||||
const setupTokenSessionId = ref('')
|
||||
|
||||
// Cookie自动授权相关状态
|
||||
const authMethod = ref('manual') // 'manual' | 'cookie'
|
||||
const sessionKey = ref('')
|
||||
const cookieAuthLoading = ref(false)
|
||||
const cookieAuthError = ref('')
|
||||
const showSessionKeyHelp = ref(false)
|
||||
const batchProgress = ref({ current: 0, total: 0 }) // 批量进度
|
||||
|
||||
// 解析后的 sessionKey 数量
|
||||
const parsedSessionKeyCount = computed(() => {
|
||||
return sessionKey.value
|
||||
.split('\n')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0).length
|
||||
})
|
||||
|
||||
// Claude Code 统一 User-Agent 信息
|
||||
const unifiedUserAgent = ref('')
|
||||
const clearingCache = ref(false)
|
||||
@@ -3716,6 +3934,8 @@ const form = ref({
|
||||
endpointType: props.account?.endpointType || 'anthropic',
|
||||
// OpenAI-Responses 特定字段
|
||||
baseApi: props.account?.baseApi || '',
|
||||
// Gemini-API 特定字段
|
||||
baseUrl: props.account?.baseUrl || 'https://generativelanguage.googleapis.com',
|
||||
rateLimitDuration: props.account?.rateLimitDuration || 60,
|
||||
supportedModels: (() => {
|
||||
const models = props.account?.supportedModels
|
||||
@@ -3732,6 +3952,7 @@ const form = ref({
|
||||
})(),
|
||||
userAgent: props.account?.userAgent || '',
|
||||
enableRateLimit: props.account ? props.account.rateLimitDuration > 0 : true,
|
||||
disableAutoProtection: props.account?.disableAutoProtection === true,
|
||||
// 额度管理字段
|
||||
dailyQuota: props.account?.dailyQuota || 0,
|
||||
dailyUsage: props.account?.dailyUsage || 0,
|
||||
@@ -4175,10 +4396,198 @@ const exchangeSetupTokenCode = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
// 处理OAuth成功
|
||||
const handleOAuthSuccess = async (tokenInfo) => {
|
||||
// =============================================================================
|
||||
// Cookie自动授权相关方法
|
||||
// =============================================================================
|
||||
|
||||
// Cookie自动授权(支持批量)
|
||||
const handleCookieAuth = async () => {
|
||||
// 解析多行输入
|
||||
const sessionKeys = sessionKey.value
|
||||
.split('\n')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0)
|
||||
|
||||
if (sessionKeys.length === 0) {
|
||||
cookieAuthError.value = '请输入至少一个 sessionKey'
|
||||
return
|
||||
}
|
||||
|
||||
cookieAuthLoading.value = true
|
||||
cookieAuthError.value = ''
|
||||
batchProgress.value = { current: 0, total: sessionKeys.length }
|
||||
|
||||
const isSetupToken = form.value.addType === 'setup-token'
|
||||
const proxyPayload = buildProxyPayload(form.value.proxy)
|
||||
|
||||
const results = []
|
||||
const errors = []
|
||||
|
||||
for (let i = 0; i < sessionKeys.length; i++) {
|
||||
batchProgress.value.current = i + 1
|
||||
try {
|
||||
const payload = {
|
||||
sessionKey: sessionKeys[i],
|
||||
...(proxyPayload && { proxy: proxyPayload })
|
||||
}
|
||||
|
||||
let result
|
||||
if (isSetupToken) {
|
||||
result = await accountsStore.oauthSetupTokenWithCookie(payload)
|
||||
} else {
|
||||
result = await accountsStore.oauthWithCookie(payload)
|
||||
}
|
||||
results.push(result)
|
||||
} catch (error) {
|
||||
errors.push({
|
||||
index: i + 1,
|
||||
key: sessionKeys[i].substring(0, 20) + '...',
|
||||
error: error.message
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
batchProgress.value = { current: 0, total: 0 }
|
||||
|
||||
if (results.length > 0) {
|
||||
try {
|
||||
// 成功后处理OAuth数据(传递数组)
|
||||
// cookieAuthLoading 保持 true,直到账号创建完成
|
||||
await handleOAuthSuccess(results)
|
||||
} finally {
|
||||
cookieAuthLoading.value = false
|
||||
}
|
||||
} else {
|
||||
cookieAuthLoading.value = false
|
||||
}
|
||||
|
||||
if (errors.length > 0 && results.length === 0) {
|
||||
cookieAuthError.value = '全部授权失败,请检查 sessionKey 是否有效'
|
||||
} else if (errors.length > 0) {
|
||||
cookieAuthError.value = `${errors.length} 个授权失败`
|
||||
}
|
||||
}
|
||||
|
||||
// 重置Cookie授权状态
|
||||
const resetCookieAuth = () => {
|
||||
sessionKey.value = ''
|
||||
cookieAuthError.value = ''
|
||||
showSessionKeyHelp.value = false
|
||||
batchProgress.value = { current: 0, total: 0 }
|
||||
}
|
||||
|
||||
// 切换授权方式时重置状态
|
||||
const onAuthMethodChange = () => {
|
||||
// 切换到手动模式时清除Cookie相关状态
|
||||
if (authMethod.value === 'manual') {
|
||||
resetCookieAuth()
|
||||
} else {
|
||||
// 切换到Cookie模式时清除手动授权状态
|
||||
setupTokenAuthUrl.value = ''
|
||||
setupTokenAuthCode.value = ''
|
||||
setupTokenSessionId.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
// 构建 Claude 账户数据(辅助函数)
|
||||
const buildClaudeAccountData = (tokenInfo, accountName, clientId) => {
|
||||
const proxyPayload = buildProxyPayload(form.value.proxy)
|
||||
const claudeOauthPayload = tokenInfo.claudeAiOauth || tokenInfo
|
||||
|
||||
const data = {
|
||||
name: accountName,
|
||||
description: form.value.description,
|
||||
accountType: form.value.accountType,
|
||||
groupId: form.value.accountType === 'group' ? form.value.groupId : undefined,
|
||||
groupIds: form.value.accountType === 'group' ? form.value.groupIds : undefined,
|
||||
expiresAt: form.value.expiresAt || undefined,
|
||||
proxy: proxyPayload,
|
||||
claudeAiOauth: claudeOauthPayload,
|
||||
priority: form.value.priority || 50,
|
||||
autoStopOnWarning: form.value.autoStopOnWarning || false,
|
||||
useUnifiedUserAgent: form.value.useUnifiedUserAgent || false,
|
||||
useUnifiedClientId: form.value.useUnifiedClientId || false,
|
||||
unifiedClientId: clientId,
|
||||
subscriptionInfo: {
|
||||
accountType: form.value.subscriptionType || 'claude_max',
|
||||
hasClaudeMax: form.value.subscriptionType === 'claude_max',
|
||||
hasClaudePro: form.value.subscriptionType === 'claude_pro',
|
||||
manuallySet: true
|
||||
}
|
||||
}
|
||||
|
||||
// 处理 extInfo
|
||||
if (claudeOauthPayload) {
|
||||
const extInfoPayload = {}
|
||||
const extSource = claudeOauthPayload.extInfo
|
||||
if (extSource?.org_uuid) extInfoPayload.org_uuid = extSource.org_uuid
|
||||
if (extSource?.account_uuid) extInfoPayload.account_uuid = extSource.account_uuid
|
||||
|
||||
if (!extSource) {
|
||||
if (claudeOauthPayload.organization?.uuid) {
|
||||
extInfoPayload.org_uuid = claudeOauthPayload.organization.uuid
|
||||
}
|
||||
if (claudeOauthPayload.account?.uuid) {
|
||||
extInfoPayload.account_uuid = claudeOauthPayload.account.uuid
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys(extInfoPayload).length > 0) {
|
||||
data.extInfo = extInfoPayload
|
||||
}
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
// 处理OAuth成功(支持批量)
|
||||
const handleOAuthSuccess = async (tokenInfoOrList) => {
|
||||
loading.value = true
|
||||
try {
|
||||
const currentPlatform = form.value.platform
|
||||
|
||||
// Claude 平台支持批量创建
|
||||
if (currentPlatform === 'claude' && Array.isArray(tokenInfoOrList)) {
|
||||
const tokenInfoList = tokenInfoOrList
|
||||
const isBatch = tokenInfoList.length > 1
|
||||
const baseName = form.value.name
|
||||
|
||||
const results = []
|
||||
const errors = []
|
||||
|
||||
for (let i = 0; i < tokenInfoList.length; i++) {
|
||||
const tokenInfo = tokenInfoList[i]
|
||||
// 批量时自动命名
|
||||
const accountName = isBatch ? `${baseName}_${i + 1}` : baseName
|
||||
// 如果启用统一客户端标识,为每个账户生成独立 ID
|
||||
const clientId = form.value.useUnifiedClientId ? generateClientId() : ''
|
||||
const data = buildClaudeAccountData(tokenInfo, accountName, clientId)
|
||||
|
||||
try {
|
||||
const result = await accountsStore.createClaudeAccount(data)
|
||||
results.push(result)
|
||||
} catch (error) {
|
||||
errors.push({ name: accountName, error: error.message })
|
||||
}
|
||||
}
|
||||
|
||||
// 处理结果
|
||||
if (results.length > 0) {
|
||||
const msg = isBatch
|
||||
? `成功创建 ${results.length}/${tokenInfoList.length} 个账户`
|
||||
: '账户创建成功'
|
||||
showToast(msg, 'success')
|
||||
emit('success', results[0]) // 兼容单个创建的返回
|
||||
}
|
||||
if (errors.length > 0) {
|
||||
showToast(`${errors.length} 个账户创建失败`, 'error')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 单个 tokenInfo 或其他平台的处理(保持原有逻辑)
|
||||
const tokenInfo = Array.isArray(tokenInfoOrList) ? tokenInfoOrList[0] : tokenInfoOrList
|
||||
|
||||
// OAuth模式也需要确保生成客户端ID
|
||||
if (
|
||||
form.value.platform === 'claude' &&
|
||||
@@ -4200,8 +4609,6 @@ const handleOAuthSuccess = async (tokenInfo) => {
|
||||
proxy: proxyPayload
|
||||
}
|
||||
|
||||
const currentPlatform = form.value.platform
|
||||
|
||||
if (currentPlatform === 'claude') {
|
||||
// Claude使用claudeAiOauth字段
|
||||
const claudeOauthPayload = tokenInfo.claudeAiOauth || tokenInfo
|
||||
@@ -4362,6 +4769,8 @@ const handleOAuthSuccess = async (tokenInfo) => {
|
||||
// 错误已通过 toast 显示给用户
|
||||
} finally {
|
||||
loading.value = false
|
||||
// 重置 OAuthFlow 组件的加载状态(如果是通过 OAuth 模式调用)
|
||||
oauthFlowRef.value?.resetCookieAuth()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4483,6 +4892,14 @@ const createAccount = async () => {
|
||||
errors.value.apiKey = '请填写 API Key'
|
||||
hasError = true
|
||||
}
|
||||
// 验证 baseUrl 必须以 /models 结尾
|
||||
if (!form.value.baseUrl || form.value.baseUrl.trim() === '') {
|
||||
errors.value.baseUrl = '请填写 API 基础地址'
|
||||
hasError = true
|
||||
} else if (!form.value.baseUrl.trim().endsWith('/models')) {
|
||||
errors.value.baseUrl = 'API 基础地址必须以 /models 结尾'
|
||||
hasError = true
|
||||
}
|
||||
} else {
|
||||
// 其他平台(如 Droid)使用多 API Key 输入
|
||||
const apiKeys = parseApiKeysInput(form.value.apiKeysInput)
|
||||
@@ -4639,6 +5056,10 @@ const createAccount = async () => {
|
||||
data.userAgent = form.value.userAgent || null
|
||||
// 如果不启用限流,传递 0 表示不限流
|
||||
data.rateLimitDuration = form.value.enableRateLimit ? form.value.rateLimitDuration || 60 : 0
|
||||
// 上游错误处理(仅 Claude Console)
|
||||
if (form.value.platform === 'claude-console') {
|
||||
data.disableAutoProtection = !!form.value.disableAutoProtection
|
||||
}
|
||||
// 额度管理字段
|
||||
data.dailyQuota = form.value.dailyQuota || 0
|
||||
data.quotaResetTime = form.value.quotaResetTime || '00:00'
|
||||
@@ -4746,6 +5167,7 @@ const updateAccount = async () => {
|
||||
// 清除之前的错误
|
||||
errors.value.name = ''
|
||||
errors.value.apiKeys = ''
|
||||
errors.value.baseUrl = ''
|
||||
|
||||
// 验证账户名称
|
||||
if (!form.value.name || form.value.name.trim() === '') {
|
||||
@@ -4753,6 +5175,19 @@ const updateAccount = async () => {
|
||||
return
|
||||
}
|
||||
|
||||
// Gemini API 的 baseUrl 验证(必须以 /models 结尾)
|
||||
if (form.value.platform === 'gemini-api') {
|
||||
const baseUrl = form.value.baseUrl?.trim() || ''
|
||||
if (!baseUrl) {
|
||||
errors.value.baseUrl = '请填写 API 基础地址'
|
||||
return
|
||||
}
|
||||
if (!baseUrl.endsWith('/models')) {
|
||||
errors.value.baseUrl = 'API 基础地址必须以 /models 结尾'
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 分组类型验证 - 更新账户流程修复
|
||||
if (
|
||||
form.value.accountType === 'group' &&
|
||||
@@ -4953,6 +5388,8 @@ const updateAccount = async () => {
|
||||
data.userAgent = form.value.userAgent || null
|
||||
// 如果不启用限流,传递 0 表示不限流
|
||||
data.rateLimitDuration = form.value.enableRateLimit ? form.value.rateLimitDuration || 60 : 0
|
||||
// 上游错误处理
|
||||
data.disableAutoProtection = !!form.value.disableAutoProtection
|
||||
// 额度管理字段
|
||||
data.dailyQuota = form.value.dailyQuota || 0
|
||||
data.quotaResetTime = form.value.quotaResetTime || '00:00'
|
||||
@@ -5567,12 +6004,16 @@ watch(
|
||||
deploymentName: newAccount.deploymentName || '',
|
||||
// OpenAI-Responses 特定字段
|
||||
baseApi: newAccount.baseApi || '',
|
||||
// Gemini-API 特定字段
|
||||
baseUrl: newAccount.baseUrl || 'https://generativelanguage.googleapis.com',
|
||||
// 额度管理字段
|
||||
dailyQuota: newAccount.dailyQuota || 0,
|
||||
dailyUsage: newAccount.dailyUsage || 0,
|
||||
quotaResetTime: newAccount.quotaResetTime || '00:00',
|
||||
// 并发控制字段
|
||||
maxConcurrentTasks: newAccount.maxConcurrentTasks || 0
|
||||
maxConcurrentTasks: newAccount.maxConcurrentTasks || 0,
|
||||
// 上游错误处理
|
||||
disableAutoProtection: newAccount.disableAutoProtection === true
|
||||
}
|
||||
|
||||
// 如果是Claude Console账户,加载实时使用情况
|
||||
@@ -5586,12 +6027,27 @@ watch(
|
||||
loadGroups().then(async () => {
|
||||
const foundGroupIds = []
|
||||
|
||||
// 如果账户有 groupInfo,直接使用它的 groupId
|
||||
if (newAccount.groupInfo && newAccount.groupInfo.id) {
|
||||
// 优先使用 groupInfos 数组(后端返回的标准格式)
|
||||
if (
|
||||
newAccount.groupInfos &&
|
||||
Array.isArray(newAccount.groupInfos) &&
|
||||
newAccount.groupInfos.length > 0
|
||||
) {
|
||||
// 从 groupInfos 数组中提取所有分组 ID
|
||||
newAccount.groupInfos.forEach((group) => {
|
||||
if (group && group.id) {
|
||||
foundGroupIds.push(group.id)
|
||||
}
|
||||
})
|
||||
if (foundGroupIds.length > 0) {
|
||||
form.value.groupId = foundGroupIds[0]
|
||||
}
|
||||
} else if (newAccount.groupInfo && newAccount.groupInfo.id) {
|
||||
// 兼容旧的 groupInfo 单对象格式
|
||||
form.value.groupId = newAccount.groupInfo.id
|
||||
foundGroupIds.push(newAccount.groupInfo.id)
|
||||
} else if (newAccount.groupId) {
|
||||
// 如果账户有 groupId 字段,直接使用(OpenAI-Responses 等账户)
|
||||
// 如果账户有 groupId 字段,直接使用
|
||||
form.value.groupId = newAccount.groupId
|
||||
foundGroupIds.push(newAccount.groupId)
|
||||
} else if (
|
||||
|
||||
@@ -13,128 +13,269 @@
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<h4 class="mb-3 font-semibold text-blue-900 dark:text-blue-200">Claude 账户授权</h4>
|
||||
<p class="mb-4 text-sm text-blue-800 dark:text-blue-300">
|
||||
请按照以下步骤完成 Claude 账户的授权:
|
||||
</p>
|
||||
|
||||
<div class="space-y-4">
|
||||
<!-- 步骤1: 生成授权链接 -->
|
||||
<!-- 授权方式选择 -->
|
||||
<div class="mb-4">
|
||||
<label class="mb-2 block text-sm font-medium text-blue-800 dark:text-blue-300">
|
||||
选择授权方式
|
||||
</label>
|
||||
<div class="flex gap-4">
|
||||
<label class="flex cursor-pointer items-center gap-2">
|
||||
<input
|
||||
v-model="authMethod"
|
||||
class="text-blue-600 focus:ring-blue-500"
|
||||
name="claude-auth-method"
|
||||
type="radio"
|
||||
value="manual"
|
||||
@change="onAuthMethodChange"
|
||||
/>
|
||||
<span class="text-sm text-blue-900 dark:text-blue-200">手动授权</span>
|
||||
</label>
|
||||
<label class="flex cursor-pointer items-center gap-2">
|
||||
<input
|
||||
v-model="authMethod"
|
||||
class="text-blue-600 focus:ring-blue-500"
|
||||
name="claude-auth-method"
|
||||
type="radio"
|
||||
value="cookie"
|
||||
@change="onAuthMethodChange"
|
||||
/>
|
||||
<span class="text-sm text-blue-900 dark:text-blue-200">Cookie自动授权</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Cookie自动授权表单 -->
|
||||
<div v-if="authMethod === 'cookie'" class="space-y-4">
|
||||
<div
|
||||
class="rounded-lg border border-blue-300 bg-white/80 p-4 dark:border-blue-600 dark:bg-gray-800/80"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-blue-600 text-xs font-bold text-white"
|
||||
<p class="mb-3 text-sm text-blue-700 dark:text-blue-300">
|
||||
使用 claude.ai 的 sessionKey 自动完成 OAuth 授权流程,无需手动打开浏览器。
|
||||
</p>
|
||||
|
||||
<!-- sessionKey输入 -->
|
||||
<div class="mb-4">
|
||||
<label
|
||||
class="mb-2 flex items-center gap-2 text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
1
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<p class="mb-2 font-medium text-blue-900 dark:text-blue-200">
|
||||
点击下方按钮生成授权链接
|
||||
</p>
|
||||
<button
|
||||
v-if="!authUrl"
|
||||
class="btn btn-primary px-4 py-2 text-sm"
|
||||
:disabled="loading"
|
||||
@click="generateAuthUrl"
|
||||
<i class="fas fa-cookie text-blue-500" />
|
||||
sessionKey
|
||||
<span
|
||||
v-if="parsedSessionKeyCount > 1"
|
||||
class="rounded-full bg-blue-500 px-2 py-0.5 text-xs text-white"
|
||||
>
|
||||
<i v-if="!loading" class="fas fa-link mr-2" />
|
||||
<div v-else class="loading-spinner mr-2" />
|
||||
{{ loading ? '生成中...' : '生成授权链接' }}
|
||||
{{ parsedSessionKeyCount }} 个
|
||||
</span>
|
||||
<button
|
||||
class="text-blue-500 hover:text-blue-600"
|
||||
type="button"
|
||||
@click="showSessionKeyHelp = !showSessionKeyHelp"
|
||||
>
|
||||
<i class="fas fa-question-circle" />
|
||||
</button>
|
||||
<div v-else class="space-y-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<input
|
||||
class="form-input flex-1 bg-gray-50 font-mono text-xs dark:bg-gray-700"
|
||||
readonly
|
||||
type="text"
|
||||
:value="authUrl"
|
||||
/>
|
||||
</label>
|
||||
<textarea
|
||||
v-model="sessionKey"
|
||||
class="form-input w-full resize-y font-mono text-sm"
|
||||
placeholder="每行一个 sessionKey,例如: sk-ant-sid01-xxxxx... sk-ant-sid01-yyyyy..."
|
||||
rows="3"
|
||||
/>
|
||||
<p
|
||||
v-if="parsedSessionKeyCount > 1"
|
||||
class="mt-1 text-xs text-blue-600 dark:text-blue-400"
|
||||
>
|
||||
<i class="fas fa-info-circle mr-1" />
|
||||
将批量创建 {{ parsedSessionKeyCount }} 个账户
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 帮助说明 -->
|
||||
<div
|
||||
v-if="showSessionKeyHelp"
|
||||
class="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3 dark:border-amber-700 dark:bg-amber-900/30"
|
||||
>
|
||||
<h5 class="mb-2 font-semibold text-amber-800 dark:text-amber-200">
|
||||
<i class="fas fa-lightbulb mr-1" />如何获取 sessionKey
|
||||
</h5>
|
||||
<ol
|
||||
class="list-inside list-decimal space-y-1 text-xs text-amber-700 dark:text-amber-300"
|
||||
>
|
||||
<li>在浏览器中登录 <strong>claude.ai</strong></li>
|
||||
<li>
|
||||
按
|
||||
<kbd class="rounded bg-gray-200 px-1 dark:bg-gray-700">F12</kbd>
|
||||
打开开发者工具
|
||||
</li>
|
||||
<li>切换到 <strong>Application</strong>(应用)标签页</li>
|
||||
<li>
|
||||
在左侧找到 <strong>Cookies</strong> → <strong>https://claude.ai</strong>
|
||||
</li>
|
||||
<li>找到键为 <strong>sessionKey</strong> 的那一行</li>
|
||||
<li>复制其 <strong>Value</strong>(值)列的内容</li>
|
||||
</ol>
|
||||
<p class="mt-2 text-xs text-amber-600 dark:text-amber-400">
|
||||
<i class="fas fa-info-circle mr-1" />
|
||||
sessionKey 通常以
|
||||
<code class="rounded bg-gray-200 px-1 dark:bg-gray-700">sk-ant-sid01-</code>
|
||||
开头
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 错误信息 -->
|
||||
<div
|
||||
v-if="cookieAuthError"
|
||||
class="mb-4 rounded-lg border border-red-200 bg-red-50 p-3 dark:border-red-700 dark:bg-red-900/30"
|
||||
>
|
||||
<p class="text-sm text-red-600 dark:text-red-400">
|
||||
<i class="fas fa-exclamation-circle mr-1" />
|
||||
{{ cookieAuthError }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- 授权按钮 -->
|
||||
<button
|
||||
class="btn btn-primary w-full px-4 py-3 text-base font-semibold"
|
||||
:disabled="cookieAuthLoading || !sessionKey.trim()"
|
||||
type="button"
|
||||
@click="handleCookieAuth"
|
||||
>
|
||||
<div v-if="cookieAuthLoading" class="loading-spinner mr-2" />
|
||||
<i v-else class="fas fa-magic mr-2" />
|
||||
<template v-if="cookieAuthLoading && batchProgress.total > 1">
|
||||
正在授权 {{ batchProgress.current }}/{{ batchProgress.total }}...
|
||||
</template>
|
||||
<template v-else-if="cookieAuthLoading"> 正在授权... </template>
|
||||
<template v-else> 开始自动授权 </template>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 手动授权流程 -->
|
||||
<div v-else>
|
||||
<p class="mb-4 text-sm text-blue-800 dark:text-blue-300">
|
||||
请按照以下步骤完成 Claude 账户的授权:
|
||||
</p>
|
||||
|
||||
<div class="space-y-4">
|
||||
<!-- 步骤1: 生成授权链接 -->
|
||||
<div
|
||||
class="rounded-lg border border-blue-300 bg-white/80 p-4 dark:border-blue-600 dark:bg-gray-800/80"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-blue-600 text-xs font-bold text-white"
|
||||
>
|
||||
1
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<p class="mb-2 font-medium text-blue-900 dark:text-blue-200">
|
||||
点击下方按钮生成授权链接
|
||||
</p>
|
||||
<button
|
||||
v-if="!authUrl"
|
||||
class="btn btn-primary px-4 py-2 text-sm"
|
||||
:disabled="loading"
|
||||
@click="generateAuthUrl"
|
||||
>
|
||||
<i v-if="!loading" class="fas fa-link mr-2" />
|
||||
<div v-else class="loading-spinner mr-2" />
|
||||
{{ loading ? '生成中...' : '生成授权链接' }}
|
||||
</button>
|
||||
<div v-else class="space-y-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<input
|
||||
class="form-input flex-1 bg-gray-50 font-mono text-xs dark:bg-gray-700"
|
||||
readonly
|
||||
type="text"
|
||||
:value="authUrl"
|
||||
/>
|
||||
<button
|
||||
class="rounded-lg bg-gray-100 px-3 py-2 transition-colors hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600"
|
||||
title="复制链接"
|
||||
@click="copyAuthUrl"
|
||||
>
|
||||
<i :class="copied ? 'fas fa-check text-green-500' : 'fas fa-copy'" />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
class="rounded-lg bg-gray-100 px-3 py-2 transition-colors hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600"
|
||||
title="复制链接"
|
||||
@click="copyAuthUrl"
|
||||
class="text-xs text-blue-600 hover:text-blue-700"
|
||||
@click="regenerateAuthUrl"
|
||||
>
|
||||
<i :class="copied ? 'fas fa-check text-green-500' : 'fas fa-copy'" />
|
||||
<i class="fas fa-sync-alt mr-1" />重新生成
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
class="text-xs text-blue-600 hover:text-blue-700"
|
||||
@click="regenerateAuthUrl"
|
||||
>
|
||||
<i class="fas fa-sync-alt mr-1" />重新生成
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 步骤2: 访问链接并授权 -->
|
||||
<div
|
||||
class="rounded-lg border border-blue-300 bg-white/80 p-4 dark:border-blue-600 dark:bg-gray-800/80"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-blue-600 text-xs font-bold text-white"
|
||||
>
|
||||
2
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<p class="mb-2 font-medium text-blue-900 dark:text-blue-200">
|
||||
在浏览器中打开链接并完成授权
|
||||
</p>
|
||||
<p class="mb-2 text-sm text-blue-700 dark:text-blue-300">
|
||||
请在新标签页中打开授权链接,登录您的 Claude 账户并授权。
|
||||
</p>
|
||||
<!-- 步骤2: 访问链接并授权 -->
|
||||
<div
|
||||
class="rounded-lg border border-blue-300 bg-white/80 p-4 dark:border-blue-600 dark:bg-gray-800/80"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="rounded border border-yellow-300 bg-yellow-50 p-3 dark:border-yellow-700 dark:bg-yellow-900/30"
|
||||
class="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-blue-600 text-xs font-bold text-white"
|
||||
>
|
||||
<p class="text-xs text-yellow-800 dark:text-yellow-300">
|
||||
<i class="fas fa-exclamation-triangle mr-1" />
|
||||
<strong>注意:</strong
|
||||
>如果您设置了代理,请确保浏览器也使用相同的代理访问授权页面。
|
||||
2
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<p class="mb-2 font-medium text-blue-900 dark:text-blue-200">
|
||||
在浏览器中打开链接并完成授权
|
||||
</p>
|
||||
<p class="mb-2 text-sm text-blue-700 dark:text-blue-300">
|
||||
请在新标签页中打开授权链接,登录您的 Claude 账户并授权。
|
||||
</p>
|
||||
<div
|
||||
class="rounded border border-yellow-300 bg-yellow-50 p-3 dark:border-yellow-700 dark:bg-yellow-900/30"
|
||||
>
|
||||
<p class="text-xs text-yellow-800 dark:text-yellow-300">
|
||||
<i class="fas fa-exclamation-triangle mr-1" />
|
||||
<strong>注意:</strong
|
||||
>如果您设置了代理,请确保浏览器也使用相同的代理访问授权页面。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 步骤3: 输入授权码 -->
|
||||
<div
|
||||
class="rounded-lg border border-blue-300 bg-white/80 p-4 dark:border-blue-600 dark:bg-gray-800/80"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-blue-600 text-xs font-bold text-white"
|
||||
>
|
||||
3
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<p class="mb-2 font-medium text-blue-900 dark:text-blue-200">
|
||||
输入 Authorization Code
|
||||
</p>
|
||||
<p class="mb-3 text-sm text-blue-700 dark:text-blue-300">
|
||||
授权完成后,页面会显示一个
|
||||
<strong>Authorization Code</strong>,请将其复制并粘贴到下方输入框:
|
||||
</p>
|
||||
<div class="space-y-3">
|
||||
<div>
|
||||
<label
|
||||
class="mb-2 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
<i class="fas fa-key mr-2 text-blue-500" />Authorization Code
|
||||
</label>
|
||||
<textarea
|
||||
v-model="authCode"
|
||||
class="form-input w-full resize-none font-mono text-sm"
|
||||
placeholder="粘贴从Claude页面获取的Authorization Code..."
|
||||
rows="3"
|
||||
/>
|
||||
</div>
|
||||
<p class="mt-2 text-xs text-gray-500 dark:text-gray-400">
|
||||
<i class="fas fa-info-circle mr-1" />
|
||||
请粘贴从Claude页面复制的Authorization Code
|
||||
<!-- 步骤3: 输入授权码 -->
|
||||
<div
|
||||
class="rounded-lg border border-blue-300 bg-white/80 p-4 dark:border-blue-600 dark:bg-gray-800/80"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div
|
||||
class="flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full bg-blue-600 text-xs font-bold text-white"
|
||||
>
|
||||
3
|
||||
</div>
|
||||
<div class="flex-1">
|
||||
<p class="mb-2 font-medium text-blue-900 dark:text-blue-200">
|
||||
输入 Authorization Code
|
||||
</p>
|
||||
<p class="mb-3 text-sm text-blue-700 dark:text-blue-300">
|
||||
授权完成后,页面会显示一个
|
||||
<strong>Authorization Code</strong>,请将其复制并粘贴到下方输入框:
|
||||
</p>
|
||||
<div class="space-y-3">
|
||||
<div>
|
||||
<label
|
||||
class="mb-2 block text-sm font-semibold text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
<i class="fas fa-key mr-2 text-blue-500" />Authorization Code
|
||||
</label>
|
||||
<textarea
|
||||
v-model="authCode"
|
||||
class="form-input w-full resize-none font-mono text-sm"
|
||||
placeholder="粘贴从Claude页面获取的Authorization Code..."
|
||||
rows="3"
|
||||
/>
|
||||
</div>
|
||||
<p class="mt-2 text-xs text-gray-500 dark:text-gray-400">
|
||||
<i class="fas fa-info-circle mr-1" />
|
||||
请粘贴从Claude页面复制的Authorization Code
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -636,7 +777,9 @@
|
||||
>
|
||||
上一步
|
||||
</button>
|
||||
<!-- Cookie自动授权模式不显示此按钮(Claude平台) -->
|
||||
<button
|
||||
v-if="!(platform === 'claude' && authMethod === 'cookie')"
|
||||
class="btn btn-primary flex-1 px-6 py-3 font-semibold"
|
||||
:disabled="!canExchange || exchanging"
|
||||
type="button"
|
||||
@@ -682,6 +825,22 @@ const verificationUriComplete = ref('')
|
||||
const remainingSeconds = ref(0)
|
||||
let countdownTimer = null
|
||||
|
||||
// Cookie自动授权相关状态
|
||||
const authMethod = ref('manual') // 'manual' | 'cookie'
|
||||
const sessionKey = ref('')
|
||||
const cookieAuthLoading = ref(false)
|
||||
const cookieAuthError = ref('')
|
||||
const showSessionKeyHelp = ref(false)
|
||||
const batchProgress = ref({ current: 0, total: 0 }) // 批量进度
|
||||
|
||||
// 解析后的 sessionKey 数量
|
||||
const parsedSessionKeyCount = computed(() => {
|
||||
return sessionKey.value
|
||||
.split('\n')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0).length
|
||||
})
|
||||
|
||||
// 计算是否可以交换code
|
||||
const canExchange = computed(() => {
|
||||
if (props.platform === 'droid') {
|
||||
@@ -984,4 +1143,93 @@ const exchangeCode = async () => {
|
||||
onBeforeUnmount(() => {
|
||||
stopCountdown()
|
||||
})
|
||||
|
||||
// Cookie自动授权处理(支持批量)
|
||||
const handleCookieAuth = async () => {
|
||||
// 解析多行输入
|
||||
const sessionKeys = sessionKey.value
|
||||
.split('\n')
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s.length > 0)
|
||||
|
||||
if (sessionKeys.length === 0) {
|
||||
cookieAuthError.value = '请输入至少一个 sessionKey'
|
||||
return
|
||||
}
|
||||
|
||||
cookieAuthLoading.value = true
|
||||
cookieAuthError.value = ''
|
||||
batchProgress.value = { current: 0, total: sessionKeys.length }
|
||||
|
||||
// 构建代理配置
|
||||
const proxyConfig = props.proxy?.enabled
|
||||
? {
|
||||
type: props.proxy.type,
|
||||
host: props.proxy.host,
|
||||
port: parseInt(props.proxy.port),
|
||||
username: props.proxy.username || null,
|
||||
password: props.proxy.password || null
|
||||
}
|
||||
: null
|
||||
|
||||
const results = []
|
||||
const errors = []
|
||||
|
||||
for (let i = 0; i < sessionKeys.length; i++) {
|
||||
batchProgress.value.current = i + 1
|
||||
try {
|
||||
const result = await accountsStore.oauthWithCookie({
|
||||
sessionKey: sessionKeys[i],
|
||||
proxy: proxyConfig
|
||||
})
|
||||
results.push(result)
|
||||
} catch (error) {
|
||||
errors.push({
|
||||
index: i + 1,
|
||||
key: sessionKeys[i].substring(0, 20) + '...',
|
||||
error: error.message
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
batchProgress.value = { current: 0, total: 0 }
|
||||
|
||||
if (results.length > 0) {
|
||||
// emit 后父组件会调用 handleOAuthSuccess 创建账号
|
||||
// cookieAuthLoading 保持 true,成功后表单会关闭,失败时父组件会处理
|
||||
emit('success', results) // 返回数组(单个时也是数组)
|
||||
// 注意:不在这里设置 cookieAuthLoading = false
|
||||
// 父组件创建账号完成后表单会关闭/重置
|
||||
} else {
|
||||
// 全部授权失败时才恢复按钮状态
|
||||
cookieAuthLoading.value = false
|
||||
}
|
||||
|
||||
if (errors.length > 0 && results.length === 0) {
|
||||
cookieAuthError.value = '全部授权失败,请检查 sessionKey 是否有效'
|
||||
} else if (errors.length > 0) {
|
||||
cookieAuthError.value = `${errors.length} 个授权失败`
|
||||
}
|
||||
}
|
||||
|
||||
// 重置Cookie授权状态
|
||||
const resetCookieAuth = () => {
|
||||
sessionKey.value = ''
|
||||
cookieAuthError.value = ''
|
||||
cookieAuthLoading.value = false
|
||||
batchProgress.value = { current: 0, total: 0 }
|
||||
}
|
||||
|
||||
// 切换授权方式时重置状态
|
||||
const onAuthMethodChange = () => {
|
||||
resetCookieAuth()
|
||||
authUrl.value = ''
|
||||
authCode.value = ''
|
||||
sessionId.value = ''
|
||||
}
|
||||
|
||||
// 暴露方法供父组件调用
|
||||
defineExpose({
|
||||
resetCookieAuth
|
||||
})
|
||||
</script>
|
||||
|
||||
174
web/admin-spa/src/components/common/ActionDropdown.vue
Normal file
174
web/admin-spa/src/components/common/ActionDropdown.vue
Normal file
@@ -0,0 +1,174 @@
|
||||
<template>
|
||||
<div class="relative">
|
||||
<!-- 触发器按钮 -->
|
||||
<button
|
||||
ref="triggerRef"
|
||||
class="flex h-8 w-8 items-center justify-center rounded-lg border border-gray-200 bg-white text-gray-600 transition-all duration-200 hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-400 dark:hover:border-gray-500 dark:hover:bg-gray-700 dark:hover:text-gray-200"
|
||||
:class="[
|
||||
isOpen &&
|
||||
'border-blue-400 bg-blue-50 text-blue-600 dark:border-blue-500 dark:bg-blue-900/30 dark:text-blue-400'
|
||||
]"
|
||||
title="更多操作"
|
||||
@click.stop="toggleDropdown"
|
||||
>
|
||||
<i class="fas fa-ellipsis-v text-sm"></i>
|
||||
</button>
|
||||
|
||||
<!-- 下拉菜单 - 使用 Teleport 避免被父容器裁剪 -->
|
||||
<Teleport to="body">
|
||||
<transition
|
||||
enter-active-class="transition duration-200 ease-out"
|
||||
enter-from-class="transform scale-95 opacity-0"
|
||||
enter-to-class="transform scale-100 opacity-100"
|
||||
leave-active-class="transition duration-150 ease-in"
|
||||
leave-from-class="transform scale-100 opacity-100"
|
||||
leave-to-class="transform scale-95 opacity-0"
|
||||
>
|
||||
<div
|
||||
v-if="isOpen"
|
||||
ref="dropdownRef"
|
||||
class="fixed z-[9999] min-w-[140px] overflow-hidden rounded-lg border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-600 dark:bg-gray-800"
|
||||
:style="dropdownStyle"
|
||||
>
|
||||
<button
|
||||
v-for="action in actions"
|
||||
:key="action.key"
|
||||
class="flex w-full items-center gap-2 whitespace-nowrap px-3 py-2 text-left text-sm transition-colors duration-150"
|
||||
:class="getActionClass(action)"
|
||||
@click.stop="handleAction(action)"
|
||||
>
|
||||
<i :class="['fas', action.icon, 'w-4 text-center text-xs']"></i>
|
||||
<span>{{ action.label }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</transition>
|
||||
</Teleport>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
|
||||
|
||||
defineProps({
|
||||
actions: {
|
||||
type: Array,
|
||||
required: true
|
||||
// 格式: [{ key: 'edit', label: '编辑', icon: 'fa-edit', color: 'blue', handler: () => {} }]
|
||||
}
|
||||
})
|
||||
|
||||
const emit = defineEmits(['action'])
|
||||
|
||||
const isOpen = ref(false)
|
||||
const triggerRef = ref(null)
|
||||
const dropdownRef = ref(null)
|
||||
const dropdownStyle = ref({})
|
||||
|
||||
const getActionClass = (action) => {
|
||||
const colorMap = {
|
||||
purple: 'text-purple-600 hover:bg-purple-50 dark:text-purple-400 dark:hover:bg-purple-900/20',
|
||||
indigo: 'text-indigo-600 hover:bg-indigo-50 dark:text-indigo-400 dark:hover:bg-indigo-900/20',
|
||||
blue: 'text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/20',
|
||||
green: 'text-green-600 hover:bg-green-50 dark:text-green-400 dark:hover:bg-green-900/20',
|
||||
orange: 'text-orange-600 hover:bg-orange-50 dark:text-orange-400 dark:hover:bg-orange-900/20',
|
||||
red: 'text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-900/20',
|
||||
gray: 'text-gray-600 hover:bg-gray-50 dark:text-gray-400 dark:hover:bg-gray-700'
|
||||
}
|
||||
return colorMap[action.color] || colorMap.gray
|
||||
}
|
||||
|
||||
const toggleDropdown = async () => {
|
||||
isOpen.value = !isOpen.value
|
||||
if (isOpen.value) {
|
||||
await nextTick()
|
||||
updateDropdownPosition()
|
||||
}
|
||||
}
|
||||
|
||||
const closeDropdown = () => {
|
||||
isOpen.value = false
|
||||
}
|
||||
|
||||
const handleAction = (action) => {
|
||||
closeDropdown()
|
||||
if (action.handler) {
|
||||
action.handler()
|
||||
}
|
||||
emit('action', action.key)
|
||||
}
|
||||
|
||||
const updateDropdownPosition = () => {
|
||||
if (!triggerRef.value || !isOpen.value) return
|
||||
|
||||
const trigger = triggerRef.value.getBoundingClientRect()
|
||||
const dropdownHeight = 200 // 预估高度
|
||||
const dropdownWidth = 160 // 预估宽度
|
||||
const spaceBelow = window.innerHeight - trigger.bottom
|
||||
const spaceAbove = trigger.top
|
||||
const spaceRight = window.innerWidth - trigger.right
|
||||
const spaceLeft = trigger.left
|
||||
|
||||
let top, left
|
||||
|
||||
// 计算垂直位置
|
||||
if (spaceBelow >= dropdownHeight || spaceBelow >= spaceAbove) {
|
||||
top = trigger.bottom + 4
|
||||
} else {
|
||||
top = trigger.top - dropdownHeight - 4
|
||||
}
|
||||
|
||||
// 计算水平位置 - 优先显示在左侧(因为按钮在右侧固定列)
|
||||
if (spaceLeft >= dropdownWidth) {
|
||||
left = trigger.left - dropdownWidth + trigger.width
|
||||
} else if (spaceRight >= dropdownWidth) {
|
||||
left = trigger.left
|
||||
} else {
|
||||
left = window.innerWidth - dropdownWidth - 10
|
||||
}
|
||||
|
||||
// 确保不超出边界
|
||||
if (left < 10) left = 10
|
||||
if (top < 10) top = 10
|
||||
|
||||
dropdownStyle.value = {
|
||||
top: `${top}px`,
|
||||
left: `${left}px`
|
||||
}
|
||||
}
|
||||
|
||||
const handleScroll = () => {
|
||||
if (isOpen.value) {
|
||||
updateDropdownPosition()
|
||||
}
|
||||
}
|
||||
|
||||
const handleResize = () => {
|
||||
if (isOpen.value) {
|
||||
closeDropdown()
|
||||
}
|
||||
}
|
||||
|
||||
const handleClickOutside = (event) => {
|
||||
if (!triggerRef.value || !isOpen.value) return
|
||||
|
||||
if (!triggerRef.value.contains(event.target)) {
|
||||
if (dropdownRef.value && !dropdownRef.value.contains(event.target)) {
|
||||
closeDropdown()
|
||||
} else if (!dropdownRef.value) {
|
||||
closeDropdown()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
window.addEventListener('scroll', handleScroll, true)
|
||||
window.addEventListener('resize', handleResize)
|
||||
document.addEventListener('click', handleClickOutside)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('scroll', handleScroll, true)
|
||||
window.removeEventListener('resize', handleResize)
|
||||
document.removeEventListener('click', handleClickOutside)
|
||||
})
|
||||
</script>
|
||||
@@ -750,6 +750,39 @@ export const useAccountsStore = defineStore('accounts', () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Cookie自动授权 - 普通OAuth
|
||||
const oauthWithCookie = async (payload) => {
|
||||
try {
|
||||
const response = await apiClient.post('/admin/claude-accounts/oauth-with-cookie', payload)
|
||||
if (response.success) {
|
||||
return response.data
|
||||
} else {
|
||||
throw new Error(response.message || 'Cookie授权失败')
|
||||
}
|
||||
} catch (err) {
|
||||
error.value = err.message
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Cookie自动授权 - Setup Token
|
||||
const oauthSetupTokenWithCookie = async (payload) => {
|
||||
try {
|
||||
const response = await apiClient.post(
|
||||
'/admin/claude-accounts/setup-token-with-cookie',
|
||||
payload
|
||||
)
|
||||
if (response.success) {
|
||||
return response.data
|
||||
} else {
|
||||
throw new Error(response.message || 'Cookie授权失败')
|
||||
}
|
||||
} catch (err) {
|
||||
error.value = err.message
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// 生成Gemini OAuth URL
|
||||
const generateGeminiAuthUrl = async (proxyConfig) => {
|
||||
try {
|
||||
@@ -914,6 +947,8 @@ export const useAccountsStore = defineStore('accounts', () => {
|
||||
exchangeClaudeCode,
|
||||
generateClaudeSetupTokenUrl,
|
||||
exchangeClaudeSetupTokenCode,
|
||||
oauthWithCookie,
|
||||
oauthSetupTokenWithCookie,
|
||||
generateGeminiAuthUrl,
|
||||
exchangeGeminiCode,
|
||||
generateOpenAIAuthUrl,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -253,12 +253,15 @@
|
||||
<!-- 桌面端表格视图 -->
|
||||
<div v-else class="table-wrapper hidden md:block">
|
||||
<div class="table-container">
|
||||
<table class="w-full table-fixed">
|
||||
<table class="w-full">
|
||||
<thead
|
||||
class="sticky top-0 z-10 bg-gradient-to-b from-gray-50 to-gray-100/90 backdrop-blur-sm dark:from-gray-700 dark:to-gray-800/90"
|
||||
>
|
||||
<tr>
|
||||
<th v-if="shouldShowCheckboxes" class="w-[50px] px-3 py-4 text-left">
|
||||
<th
|
||||
v-if="shouldShowCheckboxes"
|
||||
class="checkbox-column sticky left-0 z-20 min-w-[50px] px-3 py-4 text-left"
|
||||
>
|
||||
<div class="flex items-center">
|
||||
<input
|
||||
v-model="selectAllChecked"
|
||||
@@ -270,7 +273,8 @@
|
||||
</div>
|
||||
</th>
|
||||
<th
|
||||
class="w-[14%] min-w-[120px] cursor-pointer px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600"
|
||||
class="name-column sticky z-20 min-w-[140px] cursor-pointer px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600"
|
||||
:class="shouldShowCheckboxes ? 'left-[50px]' : 'left-0'"
|
||||
@click="sortApiKeys('name')"
|
||||
>
|
||||
名称
|
||||
@@ -285,17 +289,17 @@
|
||||
<i v-else class="fas fa-sort ml-1 text-gray-400" />
|
||||
</th>
|
||||
<th
|
||||
class="w-[15%] min-w-[120px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[140px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
所属账号
|
||||
</th>
|
||||
<th
|
||||
class="w-[10%] min-w-[80px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[100px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
标签
|
||||
</th>
|
||||
<th
|
||||
class="w-[6%] min-w-[60px] cursor-pointer px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600"
|
||||
class="min-w-[80px] cursor-pointer px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600"
|
||||
@click="sortApiKeys('status')"
|
||||
>
|
||||
状态
|
||||
@@ -310,7 +314,7 @@
|
||||
<i v-else class="fas fa-sort ml-1 text-gray-400" />
|
||||
</th>
|
||||
<th
|
||||
class="w-[4%] min-w-[40px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[70px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
:class="{
|
||||
'cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600': canSortByCost,
|
||||
'cursor-not-allowed opacity-60': !canSortByCost
|
||||
@@ -331,22 +335,22 @@
|
||||
<i v-else class="fas fa-clock ml-1 text-gray-400" title="索引更新中" />
|
||||
</th>
|
||||
<th
|
||||
class="w-[14%] min-w-[120px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[180px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
限制
|
||||
</th>
|
||||
<th
|
||||
class="w-[5%] min-w-[45px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[80px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
Token
|
||||
</th>
|
||||
<th
|
||||
class="w-[5%] min-w-[45px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[80px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
请求数
|
||||
</th>
|
||||
<th
|
||||
class="w-[8%] min-w-[70px] cursor-pointer px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600"
|
||||
class="min-w-[100px] cursor-pointer px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600"
|
||||
@click="sortApiKeys('lastUsedAt')"
|
||||
>
|
||||
最后使用
|
||||
@@ -361,7 +365,7 @@
|
||||
<i v-else class="fas fa-sort ml-1 text-gray-400" />
|
||||
</th>
|
||||
<th
|
||||
class="w-[8%] min-w-[70px] cursor-pointer px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600"
|
||||
class="min-w-[100px] cursor-pointer px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600"
|
||||
@click="sortApiKeys('createdAt')"
|
||||
>
|
||||
创建时间
|
||||
@@ -376,7 +380,7 @@
|
||||
<i v-else class="fas fa-sort ml-1 text-gray-400" />
|
||||
</th>
|
||||
<th
|
||||
class="w-[8%] min-w-[70px] cursor-pointer px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600"
|
||||
class="min-w-[100px] cursor-pointer px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-600"
|
||||
@click="sortApiKeys('expiresAt')"
|
||||
>
|
||||
过期时间
|
||||
@@ -391,7 +395,7 @@
|
||||
<i v-else class="fas fa-sort ml-1 text-gray-400" />
|
||||
</th>
|
||||
<th
|
||||
class="operations-column sticky right-0 w-[23%] min-w-[200px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="operations-column sticky right-0 min-w-[120px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
操作
|
||||
</th>
|
||||
@@ -410,7 +414,10 @@
|
||||
'hover:bg-blue-50/60 hover:shadow-sm dark:hover:bg-blue-900/20'
|
||||
]"
|
||||
>
|
||||
<td v-if="shouldShowCheckboxes" class="px-3 py-3">
|
||||
<td
|
||||
v-if="shouldShowCheckboxes"
|
||||
class="checkbox-column sticky left-0 z-10 px-3 py-3"
|
||||
>
|
||||
<div class="flex items-center">
|
||||
<input
|
||||
v-model="selectedApiKeys"
|
||||
@@ -421,7 +428,10 @@
|
||||
/>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-3 py-3">
|
||||
<td
|
||||
class="name-column sticky z-10 px-3 py-3"
|
||||
:class="shouldShowCheckboxes ? 'left-[50px]' : 'left-0'"
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<!-- 名称 -->
|
||||
<div
|
||||
@@ -854,14 +864,15 @@
|
||||
class="operations-column operations-cell whitespace-nowrap px-3 py-3"
|
||||
style="font-size: 13px"
|
||||
>
|
||||
<div class="flex gap-1">
|
||||
<!-- 大屏幕:展开所有按钮 -->
|
||||
<div class="hidden gap-1 2xl:flex">
|
||||
<button
|
||||
class="rounded px-2 py-1 text-xs font-medium text-purple-600 transition-colors hover:bg-purple-50 hover:text-purple-900 dark:hover:bg-purple-900/20"
|
||||
title="查看详细统计"
|
||||
@click="showUsageDetails(key)"
|
||||
>
|
||||
<i class="fas fa-chart-line" />
|
||||
<span class="ml-1 hidden xl:inline">详情</span>
|
||||
<span class="ml-1">详情</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="key && key.id"
|
||||
@@ -875,7 +886,7 @@
|
||||
expandedApiKeys[key.id] ? 'fa-chevron-up' : 'fa-chevron-down'
|
||||
]"
|
||||
/>
|
||||
<span class="ml-1 hidden xl:inline">模型</span>
|
||||
<span class="ml-1">模型</span>
|
||||
</button>
|
||||
<button
|
||||
class="rounded px-2 py-1 text-xs font-medium text-blue-600 transition-colors hover:bg-blue-50 hover:text-blue-900 dark:hover:bg-blue-900/20"
|
||||
@@ -883,7 +894,7 @@
|
||||
@click="openEditApiKeyModal(key)"
|
||||
>
|
||||
<i class="fas fa-edit" />
|
||||
<span class="ml-1 hidden xl:inline">编辑</span>
|
||||
<span class="ml-1">编辑</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="
|
||||
@@ -896,7 +907,7 @@
|
||||
@click="openRenewApiKeyModal(key)"
|
||||
>
|
||||
<i class="fas fa-clock" />
|
||||
<span class="ml-1 hidden xl:inline">续期</span>
|
||||
<span class="ml-1">续期</span>
|
||||
</button>
|
||||
<button
|
||||
:class="[
|
||||
@@ -909,9 +920,7 @@
|
||||
@click="toggleApiKeyStatus(key)"
|
||||
>
|
||||
<i :class="['fas', key.isActive ? 'fa-ban' : 'fa-check-circle']" />
|
||||
<span class="ml-1 hidden xl:inline">{{
|
||||
key.isActive ? '禁用' : '激活'
|
||||
}}</span>
|
||||
<span class="ml-1">{{ key.isActive ? '禁用' : '激活' }}</span>
|
||||
</button>
|
||||
<button
|
||||
class="rounded px-2 py-1 text-xs font-medium text-red-600 transition-colors hover:bg-red-50 hover:text-red-900 dark:hover:bg-red-900/20"
|
||||
@@ -919,9 +928,35 @@
|
||||
@click="deleteApiKey(key.id)"
|
||||
>
|
||||
<i class="fas fa-trash" />
|
||||
<span class="ml-1 hidden xl:inline">删除</span>
|
||||
<span class="ml-1">删除</span>
|
||||
</button>
|
||||
</div>
|
||||
<!-- 小屏幕:常用按钮 + 下拉菜单 -->
|
||||
<div class="flex items-center gap-1 2xl:hidden">
|
||||
<!-- 始终显示的快捷按钮 -->
|
||||
<button
|
||||
class="rounded px-2 py-1 text-xs font-medium text-purple-600 transition-colors hover:bg-purple-50 hover:text-purple-900 dark:hover:bg-purple-900/20"
|
||||
title="查看详细统计"
|
||||
@click="showUsageDetails(key)"
|
||||
>
|
||||
<i class="fas fa-chart-line" />
|
||||
</button>
|
||||
<button
|
||||
v-if="key && key.id"
|
||||
class="rounded px-2 py-1 text-xs font-medium text-indigo-600 transition-colors hover:bg-indigo-50 hover:text-indigo-900 dark:hover:bg-indigo-900/20"
|
||||
title="模型使用分布"
|
||||
@click="toggleApiKeyModelStats(key.id)"
|
||||
>
|
||||
<i
|
||||
:class="[
|
||||
'fas',
|
||||
expandedApiKeys[key.id] ? 'fa-chevron-up' : 'fa-chevron-down'
|
||||
]"
|
||||
/>
|
||||
</button>
|
||||
<!-- 更多操作下拉菜单 -->
|
||||
<ActionDropdown :actions="getApiKeyActions(key)" />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -1722,62 +1757,64 @@
|
||||
|
||||
<div class="table-wrapper">
|
||||
<div class="table-container">
|
||||
<table class="w-full table-fixed">
|
||||
<thead class="bg-gray-50/80 backdrop-blur-sm dark:bg-gray-700/80">
|
||||
<table class="w-full">
|
||||
<thead
|
||||
class="sticky top-0 z-10 bg-gradient-to-b from-gray-50 to-gray-100/90 backdrop-blur-sm dark:from-gray-700 dark:to-gray-800/90"
|
||||
>
|
||||
<tr>
|
||||
<th
|
||||
class="w-[14%] min-w-[120px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="name-column sticky left-0 z-20 min-w-[140px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
名称
|
||||
</th>
|
||||
<th
|
||||
class="w-[15%] min-w-[120px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[140px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
所属账号
|
||||
</th>
|
||||
<th
|
||||
v-if="isLdapEnabled"
|
||||
class="w-[15%] min-w-[120px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[120px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
创建者
|
||||
</th>
|
||||
<th
|
||||
class="w-[15%] min-w-[120px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[120px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
创建时间
|
||||
</th>
|
||||
<th
|
||||
class="w-[10%] min-w-[90px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[100px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
删除者
|
||||
</th>
|
||||
<th
|
||||
class="w-[10%] min-w-[90px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[100px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
删除时间
|
||||
</th>
|
||||
<th
|
||||
class="w-[8%] min-w-[60px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[70px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
费用
|
||||
</th>
|
||||
<th
|
||||
class="w-[8%] min-w-[60px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[80px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
Token
|
||||
</th>
|
||||
<th
|
||||
class="w-[8%] min-w-[60px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[80px] px-3 py-4 text-right text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
请求数
|
||||
</th>
|
||||
<th
|
||||
class="w-[9%] min-w-[80px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="min-w-[100px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
最后使用
|
||||
</th>
|
||||
<th
|
||||
class="operations-column sticky right-0 w-[15%] min-w-[160px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
class="operations-column sticky right-0 min-w-[140px] px-3 py-4 text-left text-xs font-bold uppercase tracking-wider text-gray-700 dark:text-gray-300"
|
||||
>
|
||||
操作
|
||||
</th>
|
||||
@@ -1785,7 +1822,7 @@
|
||||
</thead>
|
||||
<tbody class="divide-y divide-gray-200/50 dark:divide-gray-600/50">
|
||||
<tr v-for="key in deletedApiKeys" :key="key.id" class="table-row">
|
||||
<td class="px-3 py-3">
|
||||
<td class="name-column sticky left-0 z-10 px-3 py-3">
|
||||
<div class="flex items-center">
|
||||
<div
|
||||
class="mr-2 flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-red-500 to-red-600"
|
||||
@@ -2074,6 +2111,7 @@ import ExpiryEditModal from '@/components/apikeys/ExpiryEditModal.vue'
|
||||
import UsageDetailModal from '@/components/apikeys/UsageDetailModal.vue'
|
||||
import LimitProgressBar from '@/components/apikeys/LimitProgressBar.vue'
|
||||
import CustomDropdown from '@/components/common/CustomDropdown.vue'
|
||||
import ActionDropdown from '@/components/common/ActionDropdown.vue'
|
||||
|
||||
// 响应式数据
|
||||
const clientsStore = useClientsStore()
|
||||
@@ -3705,6 +3743,50 @@ const handleRenewSuccess = () => {
|
||||
loadApiKeys()
|
||||
}
|
||||
|
||||
// 获取API Key的操作菜单项(用于ActionDropdown)
|
||||
const getApiKeyActions = (key) => {
|
||||
const actions = [
|
||||
{
|
||||
key: 'edit',
|
||||
label: '编辑',
|
||||
icon: 'fa-edit',
|
||||
color: 'blue',
|
||||
handler: () => openEditApiKeyModal(key)
|
||||
}
|
||||
]
|
||||
|
||||
// 如果需要续期
|
||||
if (key.expiresAt && (isApiKeyExpired(key.expiresAt) || isApiKeyExpiringSoon(key.expiresAt))) {
|
||||
actions.push({
|
||||
key: 'renew',
|
||||
label: '续期',
|
||||
icon: 'fa-clock',
|
||||
color: 'green',
|
||||
handler: () => openRenewApiKeyModal(key)
|
||||
})
|
||||
}
|
||||
|
||||
// 激活/禁用
|
||||
actions.push({
|
||||
key: 'toggle',
|
||||
label: key.isActive ? '禁用' : '激活',
|
||||
icon: key.isActive ? 'fa-ban' : 'fa-check-circle',
|
||||
color: key.isActive ? 'orange' : 'green',
|
||||
handler: () => toggleApiKeyStatus(key)
|
||||
})
|
||||
|
||||
// 删除
|
||||
actions.push({
|
||||
key: 'delete',
|
||||
label: '删除',
|
||||
icon: 'fa-trash',
|
||||
color: 'red',
|
||||
handler: () => deleteApiKey(key.id)
|
||||
})
|
||||
|
||||
return actions
|
||||
}
|
||||
|
||||
// 切换API Key状态(激活/禁用)
|
||||
const toggleApiKeyStatus = async (key) => {
|
||||
let confirmed = true
|
||||
@@ -4689,6 +4771,10 @@ onUnmounted(() => {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.dark .table-wrapper {
|
||||
border-color: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.table-container {
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
@@ -4696,12 +4782,14 @@ onUnmounted(() => {
|
||||
padding: 0;
|
||||
max-width: 100%;
|
||||
position: relative;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
/* 防止表格内容溢出,保证横向滚动 */
|
||||
.table-container table {
|
||||
min-width: 1200px;
|
||||
min-width: 1400px;
|
||||
border-collapse: collapse;
|
||||
table-layout: auto;
|
||||
}
|
||||
|
||||
.table-container::-webkit-scrollbar {
|
||||
@@ -4722,6 +4810,18 @@ onUnmounted(() => {
|
||||
background: #9ca3af;
|
||||
}
|
||||
|
||||
.dark .table-container::-webkit-scrollbar-track {
|
||||
background: #374151;
|
||||
}
|
||||
|
||||
.dark .table-container::-webkit-scrollbar-thumb {
|
||||
background: #4b5563;
|
||||
}
|
||||
|
||||
.dark .table-container::-webkit-scrollbar-thumb:hover {
|
||||
background: #6b7280;
|
||||
}
|
||||
|
||||
.table-row {
|
||||
transition: background-color 0.2s ease;
|
||||
}
|
||||
@@ -4738,13 +4838,43 @@ onUnmounted(() => {
|
||||
.operations-column {
|
||||
position: sticky;
|
||||
right: 0;
|
||||
background: inherit;
|
||||
background-color: inherit;
|
||||
z-index: 12;
|
||||
}
|
||||
|
||||
/* 确保操作列在浅色模式下有正确的背景 - 使用纯色避免滚动时重叠 */
|
||||
.table-container thead .operations-column {
|
||||
z-index: 30;
|
||||
background: linear-gradient(to bottom, #f9fafb, #f3f4f6);
|
||||
}
|
||||
|
||||
.dark .table-container thead .operations-column {
|
||||
background: linear-gradient(to bottom, #374151, #1f2937);
|
||||
}
|
||||
|
||||
/* tbody 中的操作列背景处理 - 使用纯色避免滚动时重叠 */
|
||||
.table-container tbody tr:nth-child(odd) .operations-column {
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
.table-container tbody tr:nth-child(even) .operations-column {
|
||||
background-color: #f9fafb;
|
||||
}
|
||||
|
||||
.dark .table-container tbody tr:nth-child(odd) .operations-column {
|
||||
background-color: #1f2937;
|
||||
}
|
||||
|
||||
.dark .table-container tbody tr:nth-child(even) .operations-column {
|
||||
background-color: #374151;
|
||||
}
|
||||
|
||||
/* hover 状态下的操作列背景 */
|
||||
.table-container tbody tr:hover .operations-column {
|
||||
background-color: #eff6ff;
|
||||
}
|
||||
|
||||
.dark .table-container tbody tr:hover .operations-column {
|
||||
background-color: #1e3a5f;
|
||||
}
|
||||
|
||||
.table-container tbody .operations-column {
|
||||
@@ -4755,6 +4885,66 @@ onUnmounted(() => {
|
||||
box-shadow: -8px 0 12px -8px rgba(30, 41, 59, 0.45);
|
||||
}
|
||||
|
||||
/* 固定左侧列(复选框和名称列)*/
|
||||
.checkbox-column,
|
||||
.name-column {
|
||||
position: sticky;
|
||||
z-index: 12;
|
||||
}
|
||||
|
||||
/* 表头左侧固定列背景 - 使用纯色避免滚动时重叠 */
|
||||
.table-container thead .checkbox-column,
|
||||
.table-container thead .name-column {
|
||||
z-index: 30;
|
||||
background: linear-gradient(to bottom, #f9fafb, #f3f4f6);
|
||||
}
|
||||
|
||||
.dark .table-container thead .checkbox-column,
|
||||
.dark .table-container thead .name-column {
|
||||
background: linear-gradient(to bottom, #374151, #1f2937);
|
||||
}
|
||||
|
||||
/* tbody 中的左侧固定列背景处理 - 使用纯色避免滚动时重叠 */
|
||||
.table-container tbody tr:nth-child(odd) .checkbox-column,
|
||||
.table-container tbody tr:nth-child(odd) .name-column {
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
.table-container tbody tr:nth-child(even) .checkbox-column,
|
||||
.table-container tbody tr:nth-child(even) .name-column {
|
||||
background-color: #f9fafb;
|
||||
}
|
||||
|
||||
.dark .table-container tbody tr:nth-child(odd) .checkbox-column,
|
||||
.dark .table-container tbody tr:nth-child(odd) .name-column {
|
||||
background-color: #1f2937;
|
||||
}
|
||||
|
||||
.dark .table-container tbody tr:nth-child(even) .checkbox-column,
|
||||
.dark .table-container tbody tr:nth-child(even) .name-column {
|
||||
background-color: #374151;
|
||||
}
|
||||
|
||||
/* hover 状态下的左侧固定列背景 */
|
||||
.table-container tbody tr:hover .checkbox-column,
|
||||
.table-container tbody tr:hover .name-column {
|
||||
background-color: #eff6ff;
|
||||
}
|
||||
|
||||
.dark .table-container tbody tr:hover .checkbox-column,
|
||||
.dark .table-container tbody tr:hover .name-column {
|
||||
background-color: #1e3a5f;
|
||||
}
|
||||
|
||||
/* 名称列右侧阴影(分隔效果) */
|
||||
.table-container tbody .name-column {
|
||||
box-shadow: 8px 0 12px -8px rgba(15, 23, 42, 0.16);
|
||||
}
|
||||
|
||||
.dark .table-container tbody .name-column {
|
||||
box-shadow: 8px 0 12px -8px rgba(30, 41, 59, 0.45);
|
||||
}
|
||||
|
||||
.loading-spinner {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
|
||||
Reference in New Issue
Block a user