resolve: 解决与upstream/dev的合并冲突

- 合并admin.js中的groupIds和autoStopOnWarning参数
- 统一AccountForm.vue中的错误提示文案和平台判断逻辑
- 保留AccountsView.vue中的分组过滤和ungrouped功能
- 确保Azure OpenAI账户创建和更新逻辑完整性

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
sczheng189
2025-09-02 20:32:42 +08:00
66 changed files with 11527 additions and 1581 deletions

View File

@@ -14,7 +14,7 @@ class ApiKeyService {
const {
name = 'Unnamed Key',
description = '',
tokenLimit = config.limits.defaultTokenLimit,
tokenLimit = 0, // 默认为0不再使用token限制
expiresAt = null,
claudeAccountId = null,
claudeConsoleAccountId = null,
@@ -27,11 +27,13 @@ class ApiKeyService {
concurrencyLimit = 0,
rateLimitWindow = null,
rateLimitRequests = null,
rateLimitCost = null, // 新增:速率限制费用字段
enableModelRestriction = false,
restrictedModels = [],
enableClientRestriction = false,
allowedClients = [],
dailyCostLimit = 0,
weeklyOpusCostLimit = 0,
tags = []
} = options
@@ -49,6 +51,7 @@ class ApiKeyService {
concurrencyLimit: String(concurrencyLimit ?? 0),
rateLimitWindow: String(rateLimitWindow ?? 0),
rateLimitRequests: String(rateLimitRequests ?? 0),
rateLimitCost: String(rateLimitCost ?? 0), // 新增:速率限制费用字段
isActive: String(isActive),
claudeAccountId: claudeAccountId || '',
claudeConsoleAccountId: claudeConsoleAccountId || '',
@@ -62,11 +65,14 @@ class ApiKeyService {
enableClientRestriction: String(enableClientRestriction || false),
allowedClients: JSON.stringify(allowedClients || []),
dailyCostLimit: String(dailyCostLimit || 0),
weeklyOpusCostLimit: String(weeklyOpusCostLimit || 0),
tags: JSON.stringify(tags || []),
createdAt: new Date().toISOString(),
lastUsedAt: '',
expiresAt: expiresAt || '',
createdBy: 'admin' // 可以根据需要扩展用户系统
createdBy: options.createdBy || 'admin',
userId: options.userId || '',
userUsername: options.userUsername || ''
}
// 保存API Key数据并建立哈希映射
@@ -83,6 +89,7 @@ class ApiKeyService {
concurrencyLimit: parseInt(keyData.concurrencyLimit),
rateLimitWindow: parseInt(keyData.rateLimitWindow || 0),
rateLimitRequests: parseInt(keyData.rateLimitRequests || 0),
rateLimitCost: parseFloat(keyData.rateLimitCost || 0), // 新增:速率限制费用字段
isActive: keyData.isActive === 'true',
claudeAccountId: keyData.claudeAccountId,
claudeConsoleAccountId: keyData.claudeConsoleAccountId,
@@ -96,6 +103,7 @@ class ApiKeyService {
enableClientRestriction: keyData.enableClientRestriction === 'true',
allowedClients: JSON.parse(keyData.allowedClients || '[]'),
dailyCostLimit: parseFloat(keyData.dailyCostLimit || 0),
weeklyOpusCostLimit: parseFloat(keyData.weeklyOpusCostLimit || 0),
tags: JSON.parse(keyData.tags || '[]'),
createdAt: keyData.createdAt,
expiresAt: keyData.expiresAt,
@@ -130,6 +138,20 @@ class ApiKeyService {
return { valid: false, error: 'API key has expired' }
}
// 如果API Key属于某个用户检查用户是否被禁用
if (keyData.userId) {
try {
const userService = require('./userService')
const user = await userService.getUserById(keyData.userId, false)
if (!user || !user.isActive) {
return { valid: false, error: 'User account is disabled' }
}
} catch (error) {
logger.error('❌ Error checking user status during API key validation:', error)
return { valid: false, error: 'Unable to validate user status' }
}
}
// 获取使用统计(供返回数据使用)
const usage = await redis.getUsageStats(keyData.id)
@@ -184,12 +206,15 @@ class ApiKeyService {
concurrencyLimit: parseInt(keyData.concurrencyLimit || 0),
rateLimitWindow: parseInt(keyData.rateLimitWindow || 0),
rateLimitRequests: parseInt(keyData.rateLimitRequests || 0),
rateLimitCost: parseFloat(keyData.rateLimitCost || 0), // 新增:速率限制费用字段
enableModelRestriction: keyData.enableModelRestriction === 'true',
restrictedModels,
enableClientRestriction: keyData.enableClientRestriction === 'true',
allowedClients,
dailyCostLimit: parseFloat(keyData.dailyCostLimit || 0),
weeklyOpusCostLimit: parseFloat(keyData.weeklyOpusCostLimit || 0),
dailyCost: dailyCost || 0,
weeklyOpusCost: (await redis.getWeeklyOpusCost(keyData.id)) || 0,
tags,
usage
}
@@ -201,34 +226,52 @@ class ApiKeyService {
}
// 📋 获取所有API Keys
async getAllApiKeys() {
async getAllApiKeys(includeDeleted = false) {
try {
const apiKeys = await redis.getAllApiKeys()
let apiKeys = await redis.getAllApiKeys()
const client = redis.getClientSafe()
// 默认过滤掉已删除的API Keys
if (!includeDeleted) {
apiKeys = apiKeys.filter((key) => key.isDeleted !== 'true')
}
// 为每个key添加使用统计和当前并发数
for (const key of apiKeys) {
key.usage = await redis.getUsageStats(key.id)
const costStats = await redis.getCostStats(key.id)
// Add cost information to usage object for frontend compatibility
if (key.usage && costStats) {
key.usage.total = key.usage.total || {}
key.usage.total.cost = costStats.total
key.usage.totalCost = costStats.total
}
key.totalCost = costStats ? costStats.total : 0
key.tokenLimit = parseInt(key.tokenLimit)
key.concurrencyLimit = parseInt(key.concurrencyLimit || 0)
key.rateLimitWindow = parseInt(key.rateLimitWindow || 0)
key.rateLimitRequests = parseInt(key.rateLimitRequests || 0)
key.rateLimitCost = parseFloat(key.rateLimitCost || 0) // 新增:速率限制费用字段
key.currentConcurrency = await redis.getConcurrency(key.id)
key.isActive = key.isActive === 'true'
key.enableModelRestriction = key.enableModelRestriction === 'true'
key.enableClientRestriction = key.enableClientRestriction === 'true'
key.permissions = key.permissions || 'all' // 兼容旧数据
key.dailyCostLimit = parseFloat(key.dailyCostLimit || 0)
key.weeklyOpusCostLimit = parseFloat(key.weeklyOpusCostLimit || 0)
key.dailyCost = (await redis.getDailyCost(key.id)) || 0
key.weeklyOpusCost = (await redis.getWeeklyOpusCost(key.id)) || 0
// 获取当前时间窗口的请求次数Token使用量
// 获取当前时间窗口的请求次数Token使用量和费用
if (key.rateLimitWindow > 0) {
const requestCountKey = `rate_limit:requests:${key.id}`
const tokenCountKey = `rate_limit:tokens:${key.id}`
const costCountKey = `rate_limit:cost:${key.id}` // 新增:费用计数器
const windowStartKey = `rate_limit:window_start:${key.id}`
key.currentWindowRequests = parseInt((await client.get(requestCountKey)) || '0')
key.currentWindowTokens = parseInt((await client.get(tokenCountKey)) || '0')
key.currentWindowCost = parseFloat((await client.get(costCountKey)) || '0') // 新增:当前窗口费用
// 获取窗口开始时间和计算剩余时间
const windowStart = await client.get(windowStartKey)
@@ -251,6 +294,7 @@ class ApiKeyService {
// 重置计数为0因为窗口已过期
key.currentWindowRequests = 0
key.currentWindowTokens = 0
key.currentWindowCost = 0 // 新增:重置费用
}
} else {
// 窗口还未开始(没有任何请求)
@@ -261,6 +305,7 @@ class ApiKeyService {
} else {
key.currentWindowRequests = 0
key.currentWindowTokens = 0
key.currentWindowCost = 0 // 新增:重置费用
key.windowStartTime = null
key.windowEndTime = null
key.windowRemainingSeconds = null
@@ -307,6 +352,7 @@ class ApiKeyService {
'concurrencyLimit',
'rateLimitWindow',
'rateLimitRequests',
'rateLimitCost', // 新增:速率限制费用字段
'isActive',
'claudeAccountId',
'claudeConsoleAccountId',
@@ -321,6 +367,7 @@ class ApiKeyService {
'enableClientRestriction',
'allowedClients',
'dailyCostLimit',
'weeklyOpusCostLimit',
'tags'
]
const updatedData = { ...keyData }
@@ -353,16 +400,32 @@ class ApiKeyService {
}
}
// 🗑️ 删除API Key
async deleteApiKey(keyId) {
// 🗑️ 删除API Key (保留使用统计)
async deleteApiKey(keyId, deletedBy = 'system', deletedByType = 'system') {
try {
const result = await redis.deleteApiKey(keyId)
if (result === 0) {
const keyData = await redis.getApiKey(keyId)
if (!keyData || Object.keys(keyData).length === 0) {
throw new Error('API key not found')
}
logger.success(`🗑️ Deleted API key: ${keyId}`)
// 标记为已删除,保留所有数据和统计信息
const updatedData = {
...keyData,
isDeleted: 'true',
deletedAt: new Date().toISOString(),
deletedBy,
deletedByType, // 'user', 'admin', 'system'
isActive: 'false' // 同时禁用
}
await redis.setApiKey(keyId, updatedData)
// 从哈希映射中移除这样就不能再使用这个key进行API调用
if (keyData.apiKey) {
await redis.deleteApiKeyHash(keyData.apiKey)
}
logger.success(`🗑️ Soft deleted API key: ${keyId} by ${deletedBy} (${deletedByType})`)
return { success: true }
} catch (error) {
@@ -396,6 +459,13 @@ class ApiKeyService {
model
)
// 检查是否为 1M 上下文请求
let isLongContextRequest = false
if (model && model.includes('[1m]')) {
const totalInputTokens = inputTokens + cacheCreateTokens + cacheReadTokens
isLongContextRequest = totalInputTokens > 200000
}
// 记录API Key级别的使用统计
await redis.incrementTokenUsage(
keyId,
@@ -404,7 +474,10 @@ class ApiKeyService {
outputTokens,
cacheCreateTokens,
cacheReadTokens,
model
model,
0, // ephemeral5mTokens - 暂时为0后续处理
0, // ephemeral1hTokens - 暂时为0后续处理
isLongContextRequest
)
// 记录费用统计
@@ -433,7 +506,8 @@ class ApiKeyService {
outputTokens,
cacheCreateTokens,
cacheReadTokens,
model
model,
isLongContextRequest
)
logger.database(
`📊 Recorded account usage: ${accountId} - ${totalTokens} tokens (API Key: ${keyId})`
@@ -460,8 +534,38 @@ class ApiKeyService {
}
}
// 📊 记录 Opus 模型费用(仅限 claude 和 claude-console 账户)
async recordOpusCost(keyId, cost, model, accountType) {
try {
// 判断是否为 Opus 模型
if (!model || !model.toLowerCase().includes('claude-opus')) {
return // 不是 Opus 模型,直接返回
}
// 判断是否为 claude 或 claude-console 账户
if (!accountType || (accountType !== 'claude' && accountType !== 'claude-console')) {
logger.debug(`⚠️ Skipping Opus cost recording for non-Claude account type: ${accountType}`)
return // 不是 claude 账户,直接返回
}
// 记录 Opus 周费用
await redis.incrementWeeklyOpusCost(keyId, cost)
logger.database(
`💰 Recorded Opus weekly cost for ${keyId}: $${cost.toFixed(6)}, model: ${model}, account type: ${accountType}`
)
} catch (error) {
logger.error('❌ Failed to record Opus cost:', error)
}
}
// 📊 记录使用情况(新版本,支持详细的缓存类型)
async recordUsageWithDetails(keyId, usageObject, model = 'unknown', accountId = null) {
async recordUsageWithDetails(
keyId,
usageObject,
model = 'unknown',
accountId = null,
accountType = null
) {
try {
// 提取 token 数量
const inputTokens = usageObject.input_tokens || 0
@@ -505,7 +609,8 @@ class ApiKeyService {
cacheReadTokens,
model,
ephemeral5mTokens, // 传递5分钟缓存 tokens
ephemeral1hTokens // 传递1小时缓存 tokens
ephemeral1hTokens, // 传递1小时缓存 tokens
costInfo.isLongContextRequest || false // 传递 1M 上下文请求标记
)
// 记录费用统计
@@ -515,6 +620,9 @@ class ApiKeyService {
`💰 Recorded cost for ${keyId}: $${costInfo.totalCost.toFixed(6)}, model: ${model}`
)
// 记录 Opus 周费用(如果适用)
await this.recordOpusCost(keyId, costInfo.totalCost, model, accountType)
// 记录详细的缓存费用(如果有)
if (costInfo.ephemeral5mCost > 0 || costInfo.ephemeral1hCost > 0) {
logger.database(
@@ -541,7 +649,8 @@ class ApiKeyService {
outputTokens,
cacheCreateTokens,
cacheReadTokens,
model
model,
costInfo.isLongContextRequest || false
)
logger.database(
`📊 Recorded account usage: ${accountId} - ${totalTokens} tokens (API Key: ${keyId})`
@@ -608,6 +717,225 @@ class ApiKeyService {
return await redis.getAllAccountsUsageStats()
}
// === 用户相关方法 ===
// 🔑 创建API Key支持用户
async createApiKey(options = {}) {
return await this.generateApiKey(options)
}
// 👤 获取用户的API Keys
async getUserApiKeys(userId, includeDeleted = false) {
try {
const allKeys = await redis.getAllApiKeys()
let userKeys = allKeys.filter((key) => key.userId === userId)
// 默认过滤掉已删除的API Keys
if (!includeDeleted) {
userKeys = userKeys.filter((key) => key.isDeleted !== 'true')
}
// Populate usage stats for each user's API key (same as getAllApiKeys does)
const userKeysWithUsage = []
for (const key of userKeys) {
const usage = await redis.getUsageStats(key.id)
const dailyCost = (await redis.getDailyCost(key.id)) || 0
const costStats = await redis.getCostStats(key.id)
userKeysWithUsage.push({
id: key.id,
name: key.name,
description: key.description,
key: key.apiKey ? `${this.prefix}****${key.apiKey.slice(-4)}` : null, // 只显示前缀和后4位
tokenLimit: parseInt(key.tokenLimit || 0),
isActive: key.isActive === 'true',
createdAt: key.createdAt,
lastUsedAt: key.lastUsedAt,
expiresAt: key.expiresAt,
usage,
dailyCost,
totalCost: costStats.total,
dailyCostLimit: parseFloat(key.dailyCostLimit || 0),
userId: key.userId,
userUsername: key.userUsername,
createdBy: key.createdBy,
// Include deletion fields for deleted keys
isDeleted: key.isDeleted,
deletedAt: key.deletedAt,
deletedBy: key.deletedBy,
deletedByType: key.deletedByType
})
}
return userKeysWithUsage
} catch (error) {
logger.error('❌ Failed to get user API keys:', error)
return []
}
}
// 🔍 通过ID获取API Key检查权限
async getApiKeyById(keyId, userId = null) {
try {
const keyData = await redis.getApiKey(keyId)
if (!keyData) {
return null
}
// 如果指定了用户ID检查权限
if (userId && keyData.userId !== userId) {
return null
}
return {
id: keyData.id,
name: keyData.name,
description: keyData.description,
key: keyData.apiKey,
tokenLimit: parseInt(keyData.tokenLimit || 0),
isActive: keyData.isActive === 'true',
createdAt: keyData.createdAt,
lastUsedAt: keyData.lastUsedAt,
expiresAt: keyData.expiresAt,
userId: keyData.userId,
userUsername: keyData.userUsername,
createdBy: keyData.createdBy,
permissions: keyData.permissions,
dailyCostLimit: parseFloat(keyData.dailyCostLimit || 0)
}
} catch (error) {
logger.error('❌ Failed to get API key by ID:', error)
return null
}
}
// 🔄 重新生成API Key
async regenerateApiKey(keyId) {
try {
const existingKey = await redis.getApiKey(keyId)
if (!existingKey) {
throw new Error('API key not found')
}
// 生成新的key
const newApiKey = `${this.prefix}${this._generateSecretKey()}`
const newHashedKey = this._hashApiKey(newApiKey)
// 删除旧的哈希映射
const oldHashedKey = existingKey.apiKey
await redis.deleteApiKeyHash(oldHashedKey)
// 更新key数据
const updatedKeyData = {
...existingKey,
apiKey: newHashedKey,
updatedAt: new Date().toISOString()
}
// 保存新数据并建立新的哈希映射
await redis.setApiKey(keyId, updatedKeyData, newHashedKey)
logger.info(`🔄 Regenerated API key: ${existingKey.name} (${keyId})`)
return {
id: keyId,
name: existingKey.name,
key: newApiKey, // 返回完整的新key
updatedAt: updatedKeyData.updatedAt
}
} catch (error) {
logger.error('❌ Failed to regenerate API key:', error)
throw error
}
}
// 🗑️ 硬删除API Key (完全移除)
async hardDeleteApiKey(keyId) {
try {
const keyData = await redis.getApiKey(keyId)
if (!keyData) {
throw new Error('API key not found')
}
// 删除key数据和哈希映射
await redis.deleteApiKey(keyId)
await redis.deleteApiKeyHash(keyData.apiKey)
logger.info(`🗑️ Deleted API key: ${keyData.name} (${keyId})`)
return true
} catch (error) {
logger.error('❌ Failed to delete API key:', error)
throw error
}
}
// 🚫 禁用用户的所有API Keys
async disableUserApiKeys(userId) {
try {
const userKeys = await this.getUserApiKeys(userId)
let disabledCount = 0
for (const key of userKeys) {
if (key.isActive) {
await this.updateApiKey(key.id, { isActive: false })
disabledCount++
}
}
logger.info(`🚫 Disabled ${disabledCount} API keys for user: ${userId}`)
return { count: disabledCount }
} catch (error) {
logger.error('❌ Failed to disable user API keys:', error)
throw error
}
}
// 📊 获取聚合使用统计支持多个API Key
async getAggregatedUsageStats(keyIds, options = {}) {
try {
if (!Array.isArray(keyIds)) {
keyIds = [keyIds]
}
const { period: _period = 'week', model: _model } = options
const stats = {
totalRequests: 0,
totalInputTokens: 0,
totalOutputTokens: 0,
totalCost: 0,
dailyStats: [],
modelStats: []
}
// 汇总所有API Key的统计数据
for (const keyId of keyIds) {
const keyStats = await redis.getUsageStats(keyId)
const costStats = await redis.getCostStats(keyId)
if (keyStats && keyStats.total) {
stats.totalRequests += keyStats.total.requests || 0
stats.totalInputTokens += keyStats.total.inputTokens || 0
stats.totalOutputTokens += keyStats.total.outputTokens || 0
stats.totalCost += costStats?.total || 0
}
}
// TODO: 实现日期范围和模型统计
// 这里可以根据需要添加更详细的统计逻辑
return stats
} catch (error) {
logger.error('❌ Failed to get usage stats:', error)
return {
totalRequests: 0,
totalInputTokens: 0,
totalOutputTokens: 0,
totalCost: 0,
dailyStats: [],
modelStats: []
}
}
}
// 🧹 清理过期的API Keys
async cleanupExpiredKeys() {
try {

View File

@@ -300,7 +300,11 @@ async function getAllAccounts() {
}
}
accounts.push(accountData)
accounts.push({
...accountData,
isActive: accountData.isActive === 'true',
schedulable: accountData.schedulable !== 'false'
})
}
}

View File

@@ -273,6 +273,11 @@ function handleStreamResponse(upstreamResponse, clientResponse, options = {}) {
let eventCount = 0
const maxEvents = 10000 // 最大事件数量限制
// 专门用于保存最后几个chunks以提取usage数据
let finalChunksBuffer = ''
const FINAL_CHUNKS_SIZE = 32 * 1024 // 32KB保留最终chunks
const allParsedEvents = [] // 存储所有解析的事件用于最终usage提取
// 设置响应头
clientResponse.setHeader('Content-Type', 'text/event-stream')
clientResponse.setHeader('Cache-Control', 'no-cache')
@@ -297,8 +302,8 @@ function handleStreamResponse(upstreamResponse, clientResponse, options = {}) {
clientResponse.flushHeaders()
}
// 解析 SSE 事件以捕获 usage 数据
const parseSSEForUsage = (data) => {
// 强化的SSE事件解析,保存所有事件用于最终处理
const parseSSEForUsage = (data, isFromFinalBuffer = false) => {
const lines = data.split('\n')
for (const line of lines) {
@@ -310,34 +315,54 @@ function handleStreamResponse(upstreamResponse, clientResponse, options = {}) {
}
const eventData = JSON.parse(jsonStr)
// 保存所有成功解析的事件
allParsedEvents.push(eventData)
// 获取模型信息
if (eventData.model) {
actualModel = eventData.model
}
// 获取使用统计Responses API: response.completed -> response.usage
if (eventData.type === 'response.completed' && eventData.response) {
if (eventData.response.model) {
actualModel = eventData.response.model
}
if (eventData.response.usage) {
usageData = eventData.response.usage
logger.debug('Captured Azure OpenAI nested usage (response.usage):', usageData)
// 使用强化的usage提取函数
const { usageData: extractedUsage, actualModel: extractedModel } =
extractUsageDataRobust(
eventData,
`stream-event-${isFromFinalBuffer ? 'final' : 'normal'}`
)
if (extractedUsage && !usageData) {
usageData = extractedUsage
if (extractedModel) {
actualModel = extractedModel
}
logger.debug(`🎯 Stream usage captured via robust extraction`, {
isFromFinalBuffer,
usageData,
actualModel
})
}
// 兼容 Chat Completions 风格(顶层 usage
if (!usageData && eventData.usage) {
usageData = eventData.usage
logger.debug('Captured Azure OpenAI usage (top-level):', usageData)
}
// 原有的简单提取作为备用
if (!usageData) {
// 获取使用统计Responses API: response.completed -> response.usage
if (eventData.type === 'response.completed' && eventData.response) {
if (eventData.response.model) {
actualModel = eventData.response.model
}
if (eventData.response.usage) {
usageData = eventData.response.usage
logger.debug('🎯 Stream usage (backup method - response.usage):', usageData)
}
}
// 检查是否是完成事件
if (eventData.choices && eventData.choices[0] && eventData.choices[0].finish_reason) {
// 这是最后一个 chunk
// 兼容 Chat Completions 风格(顶层 usage
if (!usageData && eventData.usage) {
usageData = eventData.usage
logger.debug('🎯 Stream usage (backup method - top-level):', usageData)
}
}
} catch (e) {
// 忽略解析错误
logger.debug('SSE parsing error (expected for incomplete chunks):', e.message)
}
}
}
@@ -387,10 +412,19 @@ function handleStreamResponse(upstreamResponse, clientResponse, options = {}) {
// 同时解析数据以捕获 usage 信息,带缓冲区大小限制
buffer += chunkStr
// 防止缓冲区过大
// 保留最后的chunks用于最终usage提取不被truncate影响
finalChunksBuffer += chunkStr
if (finalChunksBuffer.length > FINAL_CHUNKS_SIZE) {
finalChunksBuffer = finalChunksBuffer.slice(-FINAL_CHUNKS_SIZE)
}
// 防止主缓冲区过大 - 但保持最后部分用于usage解析
if (buffer.length > MAX_BUFFER_SIZE) {
logger.warn(`Stream ${streamId} buffer exceeded limit, truncating`)
buffer = buffer.slice(-MAX_BUFFER_SIZE / 2) // 保留后一半
logger.warn(
`Stream ${streamId} buffer exceeded limit, truncating main buffer but preserving final chunks`
)
// 保留最后1/4而不是1/2为usage数据留更多空间
buffer = buffer.slice(-MAX_BUFFER_SIZE / 4)
}
// 处理完整的 SSE 事件
@@ -426,9 +460,91 @@ function handleStreamResponse(upstreamResponse, clientResponse, options = {}) {
hasEnded = true
try {
// 处理剩余的 buffer
if (buffer.trim() && buffer.length <= MAX_EVENT_SIZE) {
parseSSEForUsage(buffer)
logger.debug(`🔚 Stream ended, performing comprehensive usage extraction for ${streamId}`, {
mainBufferSize: buffer.length,
finalChunksBufferSize: finalChunksBuffer.length,
parsedEventsCount: allParsedEvents.length,
hasUsageData: !!usageData
})
// 多层次的最终usage提取策略
if (!usageData) {
logger.debug('🔍 No usage found during stream, trying final extraction methods...')
// 方法1: 解析剩余的主buffer
if (buffer.trim() && buffer.length <= MAX_EVENT_SIZE) {
parseSSEForUsage(buffer, false)
}
// 方法2: 解析保留的final chunks buffer
if (!usageData && finalChunksBuffer.trim()) {
logger.debug('🔍 Trying final chunks buffer for usage extraction...')
parseSSEForUsage(finalChunksBuffer, true)
}
// 方法3: 从所有解析的事件中重新搜索usage
if (!usageData && allParsedEvents.length > 0) {
logger.debug('🔍 Searching through all parsed events for usage...')
// 倒序查找因为usage通常在最后
for (let i = allParsedEvents.length - 1; i >= 0; i--) {
const { usageData: foundUsage, actualModel: foundModel } = extractUsageDataRobust(
allParsedEvents[i],
`final-event-scan-${i}`
)
if (foundUsage) {
usageData = foundUsage
if (foundModel) {
actualModel = foundModel
}
logger.debug(`🎯 Usage found in event ${i} during final scan!`)
break
}
}
}
// 方法4: 尝试合并所有事件并搜索
if (!usageData && allParsedEvents.length > 0) {
logger.debug('🔍 Trying combined events analysis...')
const combinedData = {
events: allParsedEvents,
lastEvent: allParsedEvents[allParsedEvents.length - 1],
eventCount: allParsedEvents.length
}
const { usageData: combinedUsage } = extractUsageDataRobust(
combinedData,
'combined-events'
)
if (combinedUsage) {
usageData = combinedUsage
logger.debug('🎯 Usage found via combined events analysis!')
}
}
}
// 最终usage状态报告
if (usageData) {
logger.debug('✅ Final stream usage extraction SUCCESS', {
streamId,
usageData,
actualModel,
totalEvents: allParsedEvents.length,
finalBufferSize: finalChunksBuffer.length
})
} else {
logger.warn('❌ Final stream usage extraction FAILED', {
streamId,
totalEvents: allParsedEvents.length,
finalBufferSize: finalChunksBuffer.length,
mainBufferSize: buffer.length,
lastFewEvents: allParsedEvents.slice(-3).map((e) => ({
type: e.type,
hasUsage: !!e.usage,
hasResponse: !!e.response,
keys: Object.keys(e)
}))
})
}
if (onEnd) {
@@ -484,6 +600,120 @@ function handleStreamResponse(upstreamResponse, clientResponse, options = {}) {
})
}
// 强化的用量数据提取函数
function extractUsageDataRobust(responseData, context = 'unknown') {
logger.debug(`🔍 Attempting usage extraction for ${context}`, {
responseDataKeys: Object.keys(responseData || {}),
responseDataType: typeof responseData,
hasUsage: !!responseData?.usage,
hasResponse: !!responseData?.response
})
let usageData = null
let actualModel = null
try {
// 策略 1: 顶层 usage (标准 Chat Completions)
if (responseData?.usage) {
usageData = responseData.usage
actualModel = responseData.model
logger.debug('✅ Usage extracted via Strategy 1 (top-level)', { usageData, actualModel })
}
// 策略 2: response.usage (Responses API)
else if (responseData?.response?.usage) {
usageData = responseData.response.usage
actualModel = responseData.response.model || responseData.model
logger.debug('✅ Usage extracted via Strategy 2 (response.usage)', { usageData, actualModel })
}
// 策略 3: 嵌套搜索 - 深度查找 usage 字段
else {
const findUsageRecursive = (obj, path = '') => {
if (!obj || typeof obj !== 'object') {
return null
}
for (const [key, value] of Object.entries(obj)) {
const currentPath = path ? `${path}.${key}` : key
if (key === 'usage' && value && typeof value === 'object') {
logger.debug(`✅ Usage found at path: ${currentPath}`, value)
return { usage: value, path: currentPath }
}
if (typeof value === 'object' && value !== null) {
const nested = findUsageRecursive(value, currentPath)
if (nested) {
return nested
}
}
}
return null
}
const found = findUsageRecursive(responseData)
if (found) {
usageData = found.usage
// Try to find model in the same parent object
const pathParts = found.path.split('.')
pathParts.pop() // remove 'usage'
let modelParent = responseData
for (const part of pathParts) {
modelParent = modelParent?.[part]
}
actualModel = modelParent?.model || responseData?.model
logger.debug('✅ Usage extracted via Strategy 3 (recursive)', {
usageData,
actualModel,
foundPath: found.path
})
}
}
// 策略 4: 特殊响应格式处理
if (!usageData) {
// 检查是否有 choices 数组usage 可能在最后一个 choice 中
if (responseData?.choices?.length > 0) {
const lastChoice = responseData.choices[responseData.choices.length - 1]
if (lastChoice?.usage) {
usageData = lastChoice.usage
actualModel = responseData.model || lastChoice.model
logger.debug('✅ Usage extracted via Strategy 4 (choices)', { usageData, actualModel })
}
}
}
// 最终验证和记录
if (usageData) {
logger.debug('🎯 Final usage extraction result', {
context,
usageData,
actualModel,
inputTokens: usageData.prompt_tokens || usageData.input_tokens || 0,
outputTokens: usageData.completion_tokens || usageData.output_tokens || 0,
totalTokens: usageData.total_tokens || 0
})
} else {
logger.warn('❌ Failed to extract usage data', {
context,
responseDataStructure: `${JSON.stringify(responseData, null, 2).substring(0, 1000)}...`,
availableKeys: Object.keys(responseData || {}),
responseSize: JSON.stringify(responseData || {}).length
})
}
} catch (extractionError) {
logger.error('🚨 Error during usage extraction', {
context,
error: extractionError.message,
stack: extractionError.stack,
responseDataType: typeof responseData
})
}
return { usageData, actualModel }
}
// 处理非流式响应
function handleNonStreamResponse(upstreamResponse, clientResponse) {
try {
@@ -510,9 +740,8 @@ function handleNonStreamResponse(upstreamResponse, clientResponse) {
const responseData = upstreamResponse.data
clientResponse.json(responseData)
// 提取 usage 数据
const usageData = responseData.usage
const actualModel = responseData.model
// 使用强化的用量提取
const { usageData, actualModel } = extractUsageDataRobust(responseData, 'non-stream')
return { usageData, actualModel, responseData }
} catch (error) {

View File

@@ -15,6 +15,7 @@ const {
} = require('../utils/tokenRefreshLogger')
const tokenRefreshService = require('./tokenRefreshService')
const LRUCache = require('../utils/lruCache')
const { formatDateWithTimezone, getISOStringWithTimezone } = require('../utils/dateHelper')
class ClaudeAccountService {
constructor() {
@@ -57,7 +58,8 @@ class ClaudeAccountService {
platform = 'claude',
priority = 50, // 调度优先级 (1-100数字越小优先级越高)
schedulable = true, // 是否可被调度
subscriptionInfo = null // 手动设置的订阅信息
subscriptionInfo = null, // 手动设置的订阅信息
autoStopOnWarning = false // 5小时使用量接近限制时自动停止调度
} = options
const accountId = uuidv4()
@@ -88,6 +90,7 @@ class ClaudeAccountService {
status: 'active', // 有OAuth数据的账户直接设为active
errorMessage: '',
schedulable: schedulable.toString(), // 是否可被调度
autoStopOnWarning: autoStopOnWarning.toString(), // 5小时使用量接近限制时自动停止调度
// 优先使用手动设置的订阅信息否则使用OAuth数据中的否则默认为空
subscriptionInfo: subscriptionInfo
? JSON.stringify(subscriptionInfo)
@@ -118,6 +121,7 @@ class ClaudeAccountService {
status: 'created', // created, active, expired, error
errorMessage: '',
schedulable: schedulable.toString(), // 是否可被调度
autoStopOnWarning: autoStopOnWarning.toString(), // 5小时使用量接近限制时自动停止调度
// 手动设置的订阅信息
subscriptionInfo: subscriptionInfo ? JSON.stringify(subscriptionInfo) : ''
}
@@ -158,7 +162,8 @@ class ClaudeAccountService {
status: accountData.status,
createdAt: accountData.createdAt,
expiresAt: accountData.expiresAt,
scopes: claudeAiOauth ? claudeAiOauth.scopes : []
scopes: claudeAiOauth ? claudeAiOauth.scopes : [],
autoStopOnWarning
}
}
@@ -479,7 +484,11 @@ class ClaudeAccountService {
lastRequestTime: null
},
// 添加调度状态
schedulable: account.schedulable !== 'false' // 默认为true兼容历史数据
schedulable: account.schedulable !== 'false', // 默认为true兼容历史数据
// 添加自动停止调度设置
autoStopOnWarning: account.autoStopOnWarning === 'true', // 默认为false
// 添加停止原因
stoppedReason: account.stoppedReason || null
}
})
)
@@ -512,7 +521,8 @@ class ClaudeAccountService {
'accountType',
'priority',
'schedulable',
'subscriptionInfo'
'subscriptionInfo',
'autoStopOnWarning'
]
const updatedData = { ...accountData }
@@ -634,7 +644,10 @@ class ClaudeAccountService {
const accounts = await redis.getAllClaudeAccounts()
let activeAccounts = accounts.filter(
(account) => account.isActive === 'true' && account.status !== 'error'
(account) =>
account.isActive === 'true' &&
account.status !== 'error' &&
account.schedulable !== 'false'
)
// 如果请求的是 Opus 模型,过滤掉 Pro 和 Free 账号
@@ -721,7 +734,12 @@ class ClaudeAccountService {
// 如果API Key绑定了专属账户优先使用
if (apiKeyData.claudeAccountId) {
const boundAccount = await redis.getClaudeAccount(apiKeyData.claudeAccountId)
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
if (
boundAccount &&
boundAccount.isActive === 'true' &&
boundAccount.status !== 'error' &&
boundAccount.schedulable !== 'false'
) {
logger.info(
`🎯 Using bound dedicated account: ${boundAccount.name} (${apiKeyData.claudeAccountId}) for API key ${apiKeyData.name}`
)
@@ -740,6 +758,7 @@ class ClaudeAccountService {
(account) =>
account.isActive === 'true' &&
account.status !== 'error' &&
account.schedulable !== 'false' &&
(account.accountType === 'shared' || !account.accountType) // 兼容旧数据
)
@@ -1100,8 +1119,8 @@ class ClaudeAccountService {
platform: 'claude-oauth',
status: 'error',
errorCode: 'CLAUDE_OAUTH_RATE_LIMITED',
reason: `Account rate limited (429 error). ${rateLimitResetTimestamp ? `Reset at: ${new Date(rateLimitResetTimestamp * 1000).toISOString()}` : 'Estimated reset in 1-5 hours'}`,
timestamp: new Date().toISOString()
reason: `Account rate limited (429 error). ${rateLimitResetTimestamp ? `Reset at: ${formatDateWithTimezone(rateLimitResetTimestamp)}` : 'Estimated reset in 1-5 hours'}`,
timestamp: getISOStringWithTimezone(new Date())
})
} catch (webhookError) {
logger.error('Failed to send rate limit webhook notification:', webhookError)
@@ -1272,6 +1291,42 @@ class ClaudeAccountService {
accountData.sessionWindowEnd = windowEnd.toISOString()
accountData.lastRequestTime = now.toISOString()
// 清除会话窗口状态,因为进入了新窗口
if (accountData.sessionWindowStatus) {
delete accountData.sessionWindowStatus
delete accountData.sessionWindowStatusUpdatedAt
}
// 如果账户因为5小时限制被自动停止现在恢复调度
if (
accountData.autoStoppedAt &&
accountData.schedulable === 'false' &&
accountData.stoppedReason === '5小时使用量接近限制自动停止调度'
) {
logger.info(
`✅ Auto-resuming scheduling for account ${accountData.name} (${accountId}) - new session window started`
)
accountData.schedulable = 'true'
delete accountData.stoppedReason
delete accountData.autoStoppedAt
// 发送Webhook通知
try {
const webhookNotifier = require('../utils/webhookNotifier')
await webhookNotifier.sendAccountAnomalyNotification({
accountId,
accountName: accountData.name || 'Claude Account',
platform: 'claude',
status: 'resumed',
errorCode: 'CLAUDE_5H_LIMIT_RESUMED',
reason: '进入新的5小时窗口已自动恢复调度',
timestamp: getISOStringWithTimezone(new Date())
})
} catch (webhookError) {
logger.error('Failed to send webhook notification:', webhookError)
}
}
logger.info(
`🕐 Created new session window for account ${accountData.name} (${accountId}): ${windowStart.toISOString()} - ${windowEnd.toISOString()} (from current time)`
)
@@ -1317,7 +1372,8 @@ class ClaudeAccountService {
windowEnd: null,
progress: 0,
remainingTime: null,
lastRequestTime: accountData.lastRequestTime || null
lastRequestTime: accountData.lastRequestTime || null,
sessionWindowStatus: accountData.sessionWindowStatus || null
}
}
@@ -1334,7 +1390,8 @@ class ClaudeAccountService {
windowEnd: accountData.sessionWindowEnd,
progress: 100,
remainingTime: 0,
lastRequestTime: accountData.lastRequestTime || null
lastRequestTime: accountData.lastRequestTime || null,
sessionWindowStatus: accountData.sessionWindowStatus || null
}
}
@@ -1352,7 +1409,8 @@ class ClaudeAccountService {
windowEnd: accountData.sessionWindowEnd,
progress,
remainingTime,
lastRequestTime: accountData.lastRequestTime || null
lastRequestTime: accountData.lastRequestTime || null,
sessionWindowStatus: accountData.sessionWindowStatus || null
}
} catch (error) {
logger.error(`❌ Failed to get session window info for account ${accountId}:`, error)
@@ -1708,6 +1766,9 @@ class ClaudeAccountService {
delete updatedAccountData.rateLimitedAt
delete updatedAccountData.rateLimitStatus
delete updatedAccountData.rateLimitEndAt
delete updatedAccountData.tempErrorAt
delete updatedAccountData.sessionWindowStart
delete updatedAccountData.sessionWindowEnd
// 保存更新后的账户数据
await redis.setClaudeAccount(accountId, updatedAccountData)
@@ -1720,6 +1781,10 @@ class ClaudeAccountService {
const rateLimitKey = `ratelimit:${accountId}`
await redis.client.del(rateLimitKey)
// 清除5xx错误计数
const serverErrorKey = `claude_account:${accountId}:5xx_errors`
await redis.client.del(serverErrorKey)
logger.info(
`✅ Successfully reset all error states for account ${accountData.name} (${accountId})`
)
@@ -1738,6 +1803,209 @@ class ClaudeAccountService {
throw error
}
}
// 🧹 清理临时错误账户
async cleanupTempErrorAccounts() {
try {
const accounts = await redis.getAllClaudeAccounts()
let cleanedCount = 0
const TEMP_ERROR_RECOVERY_MINUTES = 5 // 临时错误状态恢复时间(分钟)
for (const account of accounts) {
if (account.status === 'temp_error' && account.tempErrorAt) {
const tempErrorAt = new Date(account.tempErrorAt)
const now = new Date()
const minutesSinceTempError = (now - tempErrorAt) / (1000 * 60)
// 如果临时错误状态超过指定时间,尝试重新激活
if (minutesSinceTempError > TEMP_ERROR_RECOVERY_MINUTES) {
account.status = 'active' // 恢复为 active 状态
account.schedulable = 'true' // 恢复为可调度
delete account.errorMessage
delete account.tempErrorAt
await redis.setClaudeAccount(account.id, account)
// 同时清除500错误计数
await this.clearInternalErrors(account.id)
cleanedCount++
logger.success(`🧹 Reset temp_error status for account ${account.name} (${account.id})`)
}
}
}
if (cleanedCount > 0) {
logger.success(`🧹 Reset ${cleanedCount} temp_error accounts`)
}
return cleanedCount
} catch (error) {
logger.error('❌ Failed to cleanup temp_error accounts:', error)
return 0
}
}
// 记录5xx服务器错误
async recordServerError(accountId, statusCode) {
try {
const key = `claude_account:${accountId}:5xx_errors`
// 增加错误计数设置5分钟过期时间
await redis.client.incr(key)
await redis.client.expire(key, 300) // 5分钟
logger.info(`📝 Recorded ${statusCode} error for account ${accountId}`)
} catch (error) {
logger.error(`❌ Failed to record ${statusCode} error for account ${accountId}:`, error)
}
}
// 记录500内部错误(保留以便向后兼容)
async recordInternalError(accountId) {
return this.recordServerError(accountId, 500)
}
// 获取5xx错误计数
async getServerErrorCount(accountId) {
try {
const key = `claude_account:${accountId}:5xx_errors`
const count = await redis.client.get(key)
return parseInt(count) || 0
} catch (error) {
logger.error(`❌ Failed to get 5xx error count for account ${accountId}:`, error)
return 0
}
}
// 获取500错误计数(保留以便向后兼容)
async getInternalErrorCount(accountId) {
return this.getServerErrorCount(accountId)
}
// 清除500错误计数
async clearInternalErrors(accountId) {
try {
const key = `claude_account:${accountId}:5xx_errors`
await redis.client.del(key)
logger.info(`✅ Cleared 5xx error count for account ${accountId}`)
} catch (error) {
logger.error(`❌ Failed to clear 5xx errors for account ${accountId}:`, error)
}
}
// 标记账号为临时错误状态
async markAccountTempError(accountId, sessionHash = null) {
try {
const accountData = await redis.getClaudeAccount(accountId)
if (!accountData || Object.keys(accountData).length === 0) {
throw new Error('Account not found')
}
// 更新账户状态
const updatedAccountData = { ...accountData }
updatedAccountData.status = 'temp_error' // 新增的临时错误状态
updatedAccountData.schedulable = 'false' // 设置为不可调度
updatedAccountData.errorMessage = 'Account temporarily disabled due to consecutive 500 errors'
updatedAccountData.tempErrorAt = new Date().toISOString()
// 保存更新后的账户数据
await redis.setClaudeAccount(accountId, updatedAccountData)
// 如果有sessionHash删除粘性会话映射
if (sessionHash) {
await redis.client.del(`sticky_session:${sessionHash}`)
logger.info(`🗑️ Deleted sticky session mapping for hash: ${sessionHash}`)
}
logger.warn(
`⚠️ Account ${accountData.name} (${accountId}) marked as temp_error and disabled for scheduling`
)
// 发送Webhook通知
try {
const webhookNotifier = require('../utils/webhookNotifier')
await webhookNotifier.sendAccountAnomalyNotification({
accountId,
accountName: accountData.name,
platform: 'claude-oauth',
status: 'temp_error',
errorCode: 'CLAUDE_OAUTH_TEMP_ERROR',
reason: 'Account temporarily disabled due to consecutive 500 errors'
})
} catch (webhookError) {
logger.error('Failed to send webhook notification:', webhookError)
}
return { success: true }
} catch (error) {
logger.error(`❌ Failed to mark account ${accountId} as temp_error:`, error)
throw error
}
}
// 更新会话窗口状态allowed, allowed_warning, rejected
async updateSessionWindowStatus(accountId, status) {
try {
// 参数验证
if (!accountId || !status) {
logger.warn(
`Invalid parameters for updateSessionWindowStatus: accountId=${accountId}, status=${status}`
)
return
}
const accountData = await redis.getClaudeAccount(accountId)
if (!accountData || Object.keys(accountData).length === 0) {
logger.warn(`Account not found: ${accountId}`)
return
}
// 验证状态值是否有效
const validStatuses = ['allowed', 'allowed_warning', 'rejected']
if (!validStatuses.includes(status)) {
logger.warn(`Invalid session window status: ${status} for account ${accountId}`)
return
}
// 更新会话窗口状态
accountData.sessionWindowStatus = status
accountData.sessionWindowStatusUpdatedAt = new Date().toISOString()
// 如果状态是 allowed_warning 且账户设置了自动停止调度
if (status === 'allowed_warning' && accountData.autoStopOnWarning === 'true') {
logger.warn(
`⚠️ Account ${accountData.name} (${accountId}) approaching 5h limit, auto-stopping scheduling`
)
accountData.schedulable = 'false'
accountData.stoppedReason = '5小时使用量接近限制自动停止调度'
accountData.autoStoppedAt = new Date().toISOString()
// 发送Webhook通知
try {
const webhookNotifier = require('../utils/webhookNotifier')
await webhookNotifier.sendAccountAnomalyNotification({
accountId,
accountName: accountData.name || 'Claude Account',
platform: 'claude',
status: 'warning',
errorCode: 'CLAUDE_5H_LIMIT_WARNING',
reason: '5小时使用量接近限制已自动停止调度',
timestamp: getISOStringWithTimezone(new Date())
})
} catch (webhookError) {
logger.error('Failed to send webhook notification:', webhookError)
}
}
await redis.setClaudeAccount(accountId, accountData)
logger.info(
`📊 Updated session window status for account ${accountData.name} (${accountId}): ${status}`
)
} catch (error) {
logger.error(`❌ Failed to update session window status for account ${accountId}:`, error)
}
}
}
module.exports = new ClaudeAccountService()

View File

@@ -369,6 +369,7 @@ class ClaudeConsoleAccountService {
// 发送Webhook通知
try {
const webhookNotifier = require('../utils/webhookNotifier')
const { getISOStringWithTimezone } = require('../utils/dateHelper')
await webhookNotifier.sendAccountAnomalyNotification({
accountId,
accountName: account.name || 'Claude Console Account',
@@ -376,7 +377,7 @@ class ClaudeConsoleAccountService {
status: 'error',
errorCode: 'CLAUDE_CONSOLE_RATE_LIMITED',
reason: `Account rate limited (429 error). ${account.rateLimitDuration ? `Will be blocked for ${account.rateLimitDuration} hours` : 'Temporary rate limit'}`,
timestamp: new Date().toISOString()
timestamp: getISOStringWithTimezone(new Date())
})
} catch (webhookError) {
logger.error('Failed to send rate limit webhook notification:', webhookError)
@@ -453,6 +454,144 @@ class ClaudeConsoleAccountService {
}
}
// 🚫 标记账号为未授权状态401错误
async markAccountUnauthorized(accountId) {
try {
const client = redis.getClientSafe()
const account = await this.getAccount(accountId)
if (!account) {
throw new Error('Account not found')
}
const updates = {
schedulable: 'false',
status: 'unauthorized',
errorMessage: 'API Key无效或已过期401错误',
unauthorizedAt: new Date().toISOString(),
unauthorizedCount: String((parseInt(account.unauthorizedCount || '0') || 0) + 1)
}
await client.hset(`${this.ACCOUNT_KEY_PREFIX}${accountId}`, updates)
// 发送Webhook通知
try {
const webhookNotifier = require('../utils/webhookNotifier')
await webhookNotifier.sendAccountAnomalyNotification({
accountId,
accountName: account.name || 'Claude Console Account',
platform: 'claude-console',
status: 'error',
errorCode: 'CLAUDE_CONSOLE_UNAUTHORIZED',
reason: 'API Key无效或已过期401错误账户已停止调度',
timestamp: new Date().toISOString()
})
} catch (webhookError) {
logger.error('Failed to send unauthorized webhook notification:', webhookError)
}
logger.warn(
`🚫 Claude Console account marked as unauthorized: ${account.name} (${accountId})`
)
return { success: true }
} catch (error) {
logger.error(`❌ Failed to mark Claude Console account as unauthorized: ${accountId}`, error)
throw error
}
}
// 🚫 标记账号为过载状态529错误
async markAccountOverloaded(accountId) {
try {
const client = redis.getClientSafe()
const account = await this.getAccount(accountId)
if (!account) {
throw new Error('Account not found')
}
const updates = {
overloadedAt: new Date().toISOString(),
overloadStatus: 'overloaded',
errorMessage: '服务过载529错误'
}
await client.hset(`${this.ACCOUNT_KEY_PREFIX}${accountId}`, updates)
// 发送Webhook通知
try {
const webhookNotifier = require('../utils/webhookNotifier')
await webhookNotifier.sendAccountAnomalyNotification({
accountId,
accountName: account.name || 'Claude Console Account',
platform: 'claude-console',
status: 'error',
errorCode: 'CLAUDE_CONSOLE_OVERLOADED',
reason: '服务过载529错误。账户将暂时停止调度',
timestamp: new Date().toISOString()
})
} catch (webhookError) {
logger.error('Failed to send overload webhook notification:', webhookError)
}
logger.warn(`🚫 Claude Console account marked as overloaded: ${account.name} (${accountId})`)
return { success: true }
} catch (error) {
logger.error(`❌ Failed to mark Claude Console account as overloaded: ${accountId}`, error)
throw error
}
}
// ✅ 移除账号的过载状态
async removeAccountOverload(accountId) {
try {
const client = redis.getClientSafe()
await client.hdel(`${this.ACCOUNT_KEY_PREFIX}${accountId}`, 'overloadedAt', 'overloadStatus')
logger.success(`✅ Overload status removed for Claude Console account: ${accountId}`)
return { success: true }
} catch (error) {
logger.error(
`❌ Failed to remove overload status for Claude Console account: ${accountId}`,
error
)
throw error
}
}
// 🔍 检查账号是否处于过载状态
async isAccountOverloaded(accountId) {
try {
const account = await this.getAccount(accountId)
if (!account) {
return false
}
if (account.overloadStatus === 'overloaded' && account.overloadedAt) {
const overloadedAt = new Date(account.overloadedAt)
const now = new Date()
const minutesSinceOverload = (now - overloadedAt) / (1000 * 60)
// 过载状态持续10分钟后自动恢复
if (minutesSinceOverload >= 10) {
await this.removeAccountOverload(accountId)
return false
}
return true
}
return false
} catch (error) {
logger.error(
`❌ Failed to check overload status for Claude Console account: ${accountId}`,
error
)
return false
}
}
// 🚫 标记账号为封锁状态(模型不支持等原因)
async blockAccount(accountId, reason) {
try {

View File

@@ -175,16 +175,26 @@ class ClaudeConsoleRelayService {
`[DEBUG] Response data preview: ${typeof response.data === 'string' ? response.data.substring(0, 200) : JSON.stringify(response.data).substring(0, 200)}`
)
// 检查是否为限流错误
if (response.status === 429) {
// 检查错误状态并相应处理
if (response.status === 401) {
logger.warn(`🚫 Unauthorized error detected for Claude Console account ${accountId}`)
await claudeConsoleAccountService.markAccountUnauthorized(accountId)
} else if (response.status === 429) {
logger.warn(`🚫 Rate limit detected for Claude Console account ${accountId}`)
await claudeConsoleAccountService.markAccountRateLimited(accountId)
} else if (response.status === 529) {
logger.warn(`🚫 Overload error detected for Claude Console account ${accountId}`)
await claudeConsoleAccountService.markAccountOverloaded(accountId)
} else if (response.status === 200 || response.status === 201) {
// 如果请求成功,检查并移除限流状态
// 如果请求成功,检查并移除错误状态
const isRateLimited = await claudeConsoleAccountService.isAccountRateLimited(accountId)
if (isRateLimited) {
await claudeConsoleAccountService.removeAccountRateLimit(accountId)
}
const isOverloaded = await claudeConsoleAccountService.isAccountOverloaded(accountId)
if (isOverloaded) {
await claudeConsoleAccountService.removeAccountOverload(accountId)
}
}
// 更新最后使用时间
@@ -363,8 +373,12 @@ class ClaudeConsoleRelayService {
if (response.status !== 200) {
logger.error(`❌ Claude Console API returned error status: ${response.status}`)
if (response.status === 429) {
if (response.status === 401) {
claudeConsoleAccountService.markAccountUnauthorized(accountId)
} else if (response.status === 429) {
claudeConsoleAccountService.markAccountRateLimited(accountId)
} else if (response.status === 529) {
claudeConsoleAccountService.markAccountOverloaded(accountId)
}
// 设置错误响应的状态码和响应头
@@ -396,12 +410,17 @@ class ClaudeConsoleRelayService {
return
}
// 成功响应,检查并移除限流状态
// 成功响应,检查并移除错误状态
claudeConsoleAccountService.isAccountRateLimited(accountId).then((isRateLimited) => {
if (isRateLimited) {
claudeConsoleAccountService.removeAccountRateLimit(accountId)
}
})
claudeConsoleAccountService.isAccountOverloaded(accountId).then((isOverloaded) => {
if (isOverloaded) {
claudeConsoleAccountService.removeAccountOverload(accountId)
}
})
// 设置响应头
if (!responseStream.headersSent) {
@@ -564,9 +583,15 @@ class ClaudeConsoleRelayService {
logger.error('❌ Claude Console Claude stream request error:', error.message)
// 检查是否是429错误
if (error.response && error.response.status === 429) {
claudeConsoleAccountService.markAccountRateLimited(accountId)
// 检查错误状态
if (error.response) {
if (error.response.status === 401) {
claudeConsoleAccountService.markAccountUnauthorized(accountId)
} else if (error.response.status === 429) {
claudeConsoleAccountService.markAccountRateLimited(accountId)
} else if (error.response.status === 529) {
claudeConsoleAccountService.markAccountOverloaded(accountId)
}
}
// 发送错误响应

View File

@@ -180,15 +180,15 @@ class ClaudeRelayService {
// 记录401错误
await this.recordUnauthorizedError(accountId)
// 检查是否需要标记为异常(连续3次401
// 检查是否需要标记为异常(遇到1次401就停止调度
const errorCount = await this.getUnauthorizedErrorCount(accountId)
logger.info(
`🔐 Account ${accountId} has ${errorCount} consecutive 401 errors in the last 5 minutes`
)
if (errorCount >= 3) {
if (errorCount >= 1) {
logger.error(
`❌ Account ${accountId} exceeded 401 error threshold (${errorCount} errors), marking as unauthorized`
`❌ Account ${accountId} encountered 401 error (${errorCount} errors), marking as unauthorized`
)
await unifiedClaudeScheduler.markAccountUnauthorized(
accountId,
@@ -197,6 +197,23 @@ class ClaudeRelayService {
)
}
}
// 检查是否为5xx状态码
else if (response.statusCode >= 500 && response.statusCode < 600) {
logger.warn(`🔥 Server error (${response.statusCode}) detected for account ${accountId}`)
// 记录5xx错误
await claudeAccountService.recordServerError(accountId, response.statusCode)
// 检查是否需要标记为临时错误状态连续3次500
const errorCount = await claudeAccountService.getServerErrorCount(accountId)
logger.info(
`🔥 Account ${accountId} has ${errorCount} consecutive 5xx errors in the last 5 minutes`
)
if (errorCount > 10) {
logger.error(
`❌ Account ${accountId} exceeded 5xx error threshold (${errorCount} errors), marking as temp_error`
)
await claudeAccountService.markAccountTempError(accountId, sessionHash)
}
}
// 检查是否为429状态码
else if (response.statusCode === 429) {
isRateLimited = true
@@ -247,8 +264,30 @@ class ClaudeRelayService {
)
}
} else if (response.statusCode === 200 || response.statusCode === 201) {
// 请求成功清除401错误计数
// 提取5小时会话窗口状态
// 使用大小写不敏感的方式获取响应头
const get5hStatus = (headers) => {
if (!headers) {
return null
}
// HTTP头部名称不区分大小写需要处理不同情况
return (
headers['anthropic-ratelimit-unified-5h-status'] ||
headers['Anthropic-Ratelimit-Unified-5h-Status'] ||
headers['ANTHROPIC-RATELIMIT-UNIFIED-5H-STATUS']
)
}
const sessionWindowStatus = get5hStatus(response.headers)
if (sessionWindowStatus) {
logger.info(`📊 Session window status for account ${accountId}: ${sessionWindowStatus}`)
// 保存会话窗口状态到账户数据
await claudeAccountService.updateSessionWindowStatus(accountId, sessionWindowStatus)
}
// 请求成功清除401和500错误计数
await this.clearUnauthorizedErrors(accountId)
await claudeAccountService.clearInternalErrors(accountId)
// 如果请求成功,检查并移除限流状态
const isRateLimited = await unifiedClaudeScheduler.isAccountRateLimited(
accountId,
@@ -436,7 +475,10 @@ class ClaudeRelayService {
const modelConfig = pricingData[model]
if (!modelConfig) {
logger.debug(`🔍 Model ${model} not found in pricing file, skipping max_tokens validation`)
// 如果找不到模型配置,直接透传客户端参数,不进行任何干预
logger.info(
`📝 Model ${model} not found in pricing file, passing through client parameters without modification`
)
return
}
@@ -883,6 +925,34 @@ class ClaudeRelayService {
// 错误响应处理
if (res.statusCode !== 200) {
// 将错误处理逻辑封装在一个异步函数中
const handleErrorResponse = async () => {
// 增加对5xx错误的处理
if (res.statusCode >= 500 && res.statusCode < 600) {
logger.warn(
`🔥 [Stream] Server error (${res.statusCode}) detected for account ${accountId}`
)
// 记录5xx错误
await claudeAccountService.recordServerError(accountId, res.statusCode)
// 检查是否需要标记为临时错误状态连续3次500
const errorCount = await claudeAccountService.getServerErrorCount(accountId)
logger.info(
`🔥 [Stream] Account ${accountId} has ${errorCount} consecutive 5xx errors in the last 5 minutes`
)
if (errorCount > 10) {
logger.error(
`❌ [Stream] Account ${accountId} exceeded 5xx error threshold (${errorCount} errors), marking as temp_error`
)
await claudeAccountService.markAccountTempError(accountId, sessionHash)
}
}
}
// 调用异步错误处理函数
handleErrorResponse().catch((err) => {
logger.error('❌ Error in stream error handler:', err)
})
logger.error(`❌ Claude API returned error status: ${res.statusCode}`)
let errorData = ''
@@ -1143,6 +1213,27 @@ class ClaudeRelayService {
usageCallback(finalUsage)
}
// 提取5小时会话窗口状态
// 使用大小写不敏感的方式获取响应头
const get5hStatus = (headers) => {
if (!headers) {
return null
}
// HTTP头部名称不区分大小写需要处理不同情况
return (
headers['anthropic-ratelimit-unified-5h-status'] ||
headers['Anthropic-Ratelimit-Unified-5h-Status'] ||
headers['ANTHROPIC-RATELIMIT-UNIFIED-5H-STATUS']
)
}
const sessionWindowStatus = get5hStatus(res.headers)
if (sessionWindowStatus) {
logger.info(`📊 Session window status for account ${accountId}: ${sessionWindowStatus}`)
// 保存会话窗口状态到账户数据
await claudeAccountService.updateSessionWindowStatus(accountId, sessionWindowStatus)
}
// 处理限流状态
if (rateLimitDetected || res.statusCode === 429) {
// 提取限流重置时间戳
@@ -1162,6 +1253,9 @@ class ClaudeRelayService {
rateLimitResetTimestamp
)
} else if (res.statusCode === 200) {
// 请求成功清除401和500错误计数
await this.clearUnauthorizedErrors(accountId)
await claudeAccountService.clearInternalErrors(accountId)
// 如果请求成功,检查并移除限流状态
const isRateLimited = await unifiedClaudeScheduler.isAccountRateLimited(
accountId,

View File

@@ -138,11 +138,19 @@ function createOAuth2Client(redirectUri = null, proxyConfig = null) {
return new OAuth2Client(clientOptions)
}
// 生成授权 URL (支持 PKCE)
async function generateAuthUrl(state = null, redirectUri = null) {
// 生成授权 URL (支持 PKCE 和代理)
async function generateAuthUrl(state = null, redirectUri = null, proxyConfig = null) {
// 使用新的 redirect URI
const finalRedirectUri = redirectUri || 'https://codeassist.google.com/authcode'
const oAuth2Client = createOAuth2Client(finalRedirectUri)
const oAuth2Client = createOAuth2Client(finalRedirectUri, proxyConfig)
if (proxyConfig) {
logger.info(
`🌐 Using proxy for Gemini auth URL generation: ${ProxyHelper.getProxyDescription(proxyConfig)}`
)
} else {
logger.debug('🌐 No proxy configured for Gemini auth URL generation')
}
// 生成 PKCE code verifier
const codeVerifier = await oAuth2Client.generateCodeVerifierAsync()
@@ -965,12 +973,10 @@ async function getAccountRateLimitInfo(accountId) {
}
}
// 获取配置的OAuth客户端 - 参考GeminiCliSimulator的getOauthClient方法
async function getOauthClient(accessToken, refreshToken) {
const client = new OAuth2Client({
clientId: OAUTH_CLIENT_ID,
clientSecret: OAUTH_CLIENT_SECRET
})
// 获取配置的OAuth客户端 - 参考GeminiCliSimulator的getOauthClient方法(支持代理)
async function getOauthClient(accessToken, refreshToken, proxyConfig = null) {
const client = createOAuth2Client(null, proxyConfig)
const creds = {
access_token: accessToken,
refresh_token: refreshToken,
@@ -980,6 +986,14 @@ async function getOauthClient(accessToken, refreshToken) {
expiry_date: 1754269905646
}
if (proxyConfig) {
logger.info(
`🌐 Using proxy for Gemini OAuth client: ${ProxyHelper.getProxyDescription(proxyConfig)}`
)
} else {
logger.debug('🌐 No proxy configured for Gemini OAuth client')
}
// 设置凭据
client.setCredentials(creds)
@@ -996,8 +1010,8 @@ async function getOauthClient(accessToken, refreshToken) {
return client
}
// 调用 Google Code Assist API 的 loadCodeAssist 方法
async function loadCodeAssist(client, projectId = null) {
// 调用 Google Code Assist API 的 loadCodeAssist 方法(支持代理)
async function loadCodeAssist(client, projectId = null, proxyConfig = null) {
const axios = require('axios')
const CODE_ASSIST_ENDPOINT = 'https://cloudcode-pa.googleapis.com'
const CODE_ASSIST_API_VERSION = 'v1internal'
@@ -1017,7 +1031,7 @@ async function loadCodeAssist(client, projectId = null) {
metadata: clientMetadata
}
const response = await axios({
const axiosConfig = {
url: `${CODE_ASSIST_ENDPOINT}/${CODE_ASSIST_API_VERSION}:loadCodeAssist`,
method: 'POST',
headers: {
@@ -1026,7 +1040,20 @@ async function loadCodeAssist(client, projectId = null) {
},
data: request,
timeout: 30000
})
}
// 添加代理配置
const proxyAgent = ProxyHelper.createProxyAgent(proxyConfig)
if (proxyAgent) {
axiosConfig.httpsAgent = proxyAgent
logger.info(
`🌐 Using proxy for Gemini loadCodeAssist: ${ProxyHelper.getProxyDescription(proxyConfig)}`
)
} else {
logger.debug('🌐 No proxy configured for Gemini loadCodeAssist')
}
const response = await axios(axiosConfig)
logger.info('📋 loadCodeAssist API调用成功')
return response.data
@@ -1059,8 +1086,8 @@ function getOnboardTier(loadRes) {
}
}
// 调用 Google Code Assist API 的 onboardUser 方法(包含轮询逻辑)
async function onboardUser(client, tierId, projectId, clientMetadata) {
// 调用 Google Code Assist API 的 onboardUser 方法(包含轮询逻辑,支持代理
async function onboardUser(client, tierId, projectId, clientMetadata, proxyConfig = null) {
const axios = require('axios')
const CODE_ASSIST_ENDPOINT = 'https://cloudcode-pa.googleapis.com'
const CODE_ASSIST_API_VERSION = 'v1internal'
@@ -1073,15 +1100,8 @@ async function onboardUser(client, tierId, projectId, clientMetadata) {
metadata: clientMetadata
}
logger.info('📋 开始onboardUser API调用', {
tierId,
projectId,
hasProjectId: !!projectId,
isFreeTier: tierId === 'free-tier' || tierId === 'FREE'
})
// 轮询onboardUser直到长运行操作完成
let lroRes = await axios({
// 创建基础axios配置
const baseAxiosConfig = {
url: `${CODE_ASSIST_ENDPOINT}/${CODE_ASSIST_API_VERSION}:onboardUser`,
method: 'POST',
headers: {
@@ -1090,8 +1110,29 @@ async function onboardUser(client, tierId, projectId, clientMetadata) {
},
data: onboardReq,
timeout: 30000
}
// 添加代理配置
const proxyAgent = ProxyHelper.createProxyAgent(proxyConfig)
if (proxyAgent) {
baseAxiosConfig.httpsAgent = proxyAgent
logger.info(
`🌐 Using proxy for Gemini onboardUser: ${ProxyHelper.getProxyDescription(proxyConfig)}`
)
} else {
logger.debug('🌐 No proxy configured for Gemini onboardUser')
}
logger.info('📋 开始onboardUser API调用', {
tierId,
projectId,
hasProjectId: !!projectId,
isFreeTier: tierId === 'free-tier' || tierId === 'FREE'
})
// 轮询onboardUser直到长运行操作完成
let lroRes = await axios(baseAxiosConfig)
let attempts = 0
const maxAttempts = 12 // 最多等待1分钟5秒 * 12次
@@ -1099,17 +1140,7 @@ async function onboardUser(client, tierId, projectId, clientMetadata) {
logger.info(`⏳ 等待onboardUser完成... (${attempts + 1}/${maxAttempts})`)
await new Promise((resolve) => setTimeout(resolve, 5000))
lroRes = await axios({
url: `${CODE_ASSIST_ENDPOINT}/${CODE_ASSIST_API_VERSION}:onboardUser`,
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
},
data: onboardReq,
timeout: 30000
})
lroRes = await axios(baseAxiosConfig)
attempts++
}
@@ -1121,8 +1152,13 @@ async function onboardUser(client, tierId, projectId, clientMetadata) {
return lroRes.data
}
// 完整的用户设置流程 - 参考setup.ts的逻辑
async function setupUser(client, initialProjectId = null, clientMetadata = null) {
// 完整的用户设置流程 - 参考setup.ts的逻辑(支持代理)
async function setupUser(
client,
initialProjectId = null,
clientMetadata = null,
proxyConfig = null
) {
logger.info('🚀 setupUser 开始', { initialProjectId, hasClientMetadata: !!clientMetadata })
let projectId = initialProjectId || process.env.GOOGLE_CLOUD_PROJECT || null
@@ -1141,7 +1177,7 @@ async function setupUser(client, initialProjectId = null, clientMetadata = null)
// 调用loadCodeAssist
logger.info('📞 调用 loadCodeAssist...')
const loadRes = await loadCodeAssist(client, projectId)
const loadRes = await loadCodeAssist(client, projectId, proxyConfig)
logger.info('✅ loadCodeAssist 完成', {
hasCloudaicompanionProject: !!loadRes.cloudaicompanionProject
})
@@ -1164,7 +1200,7 @@ async function setupUser(client, initialProjectId = null, clientMetadata = null)
// 调用onboardUser
logger.info('📞 调用 onboardUser...', { tierId: tier.id, projectId })
const lroRes = await onboardUser(client, tier.id, projectId, clientMetadata)
const lroRes = await onboardUser(client, tier.id, projectId, clientMetadata, proxyConfig)
logger.info('✅ onboardUser 完成', { hasDone: !!lroRes.done, hasResponse: !!lroRes.response })
const result = {
@@ -1178,8 +1214,8 @@ async function setupUser(client, initialProjectId = null, clientMetadata = null)
return result
}
// 调用 Code Assist API 计算 token 数量
async function countTokens(client, contents, model = 'gemini-2.0-flash-exp') {
// 调用 Code Assist API 计算 token 数量(支持代理)
async function countTokens(client, contents, model = 'gemini-2.0-flash-exp', proxyConfig = null) {
const axios = require('axios')
const CODE_ASSIST_ENDPOINT = 'https://cloudcode-pa.googleapis.com'
const CODE_ASSIST_API_VERSION = 'v1internal'
@@ -1196,7 +1232,7 @@ async function countTokens(client, contents, model = 'gemini-2.0-flash-exp') {
logger.info('📊 countTokens API调用开始', { model, contentsLength: contents.length })
const response = await axios({
const axiosConfig = {
url: `${CODE_ASSIST_ENDPOINT}/${CODE_ASSIST_API_VERSION}:countTokens`,
method: 'POST',
headers: {
@@ -1205,7 +1241,20 @@ async function countTokens(client, contents, model = 'gemini-2.0-flash-exp') {
},
data: request,
timeout: 30000
})
}
// 添加代理配置
const proxyAgent = ProxyHelper.createProxyAgent(proxyConfig)
if (proxyAgent) {
axiosConfig.httpsAgent = proxyAgent
logger.info(
`🌐 Using proxy for Gemini countTokens: ${ProxyHelper.getProxyDescription(proxyConfig)}`
)
} else {
logger.debug('🌐 No proxy configured for Gemini countTokens')
}
const response = await axios(axiosConfig)
logger.info('✅ countTokens API调用成功', { totalTokens: response.data.totalTokens })
return response.data

626
src/services/ldapService.js Normal file
View File

@@ -0,0 +1,626 @@
const ldap = require('ldapjs')
const logger = require('../utils/logger')
const config = require('../../config/config')
const userService = require('./userService')
class LdapService {
constructor() {
this.config = config.ldap || {}
this.client = null
// 验证配置 - 只有在 LDAP 配置存在且启用时才验证
if (this.config && this.config.enabled) {
this.validateConfiguration()
}
}
// 🔍 验证LDAP配置
validateConfiguration() {
const errors = []
if (!this.config.server) {
errors.push('LDAP server configuration is missing')
} else {
if (!this.config.server.url || typeof this.config.server.url !== 'string') {
errors.push('LDAP server URL is not configured or invalid')
}
if (!this.config.server.bindDN || typeof this.config.server.bindDN !== 'string') {
errors.push('LDAP bind DN is not configured or invalid')
}
if (
!this.config.server.bindCredentials ||
typeof this.config.server.bindCredentials !== 'string'
) {
errors.push('LDAP bind credentials are not configured or invalid')
}
if (!this.config.server.searchBase || typeof this.config.server.searchBase !== 'string') {
errors.push('LDAP search base is not configured or invalid')
}
if (!this.config.server.searchFilter || typeof this.config.server.searchFilter !== 'string') {
errors.push('LDAP search filter is not configured or invalid')
}
}
if (errors.length > 0) {
logger.error('❌ LDAP configuration validation failed:', errors)
// Don't throw error during initialization, just log warnings
logger.warn('⚠️ LDAP authentication may not work properly due to configuration errors')
} else {
logger.info('✅ LDAP configuration validation passed')
}
}
// 🔍 提取LDAP条目的DN
extractDN(ldapEntry) {
if (!ldapEntry) {
return null
}
// Try different ways to get the DN
let dn = null
// Method 1: Direct dn property
if (ldapEntry.dn) {
;({ dn } = ldapEntry)
}
// Method 2: objectName property (common in some LDAP implementations)
else if (ldapEntry.objectName) {
dn = ldapEntry.objectName
}
// Method 3: distinguishedName property
else if (ldapEntry.distinguishedName) {
dn = ldapEntry.distinguishedName
}
// Method 4: Check if the entry itself is a DN string
else if (typeof ldapEntry === 'string' && ldapEntry.includes('=')) {
dn = ldapEntry
}
// Convert DN to string if it's an object
if (dn && typeof dn === 'object') {
if (dn.toString && typeof dn.toString === 'function') {
dn = dn.toString()
} else if (dn.dn && typeof dn.dn === 'string') {
;({ dn } = dn)
}
}
// Validate the DN format
if (typeof dn === 'string' && dn.trim() !== '' && dn.includes('=')) {
return dn.trim()
}
return null
}
// 🔗 创建LDAP客户端连接
createClient() {
try {
const clientOptions = {
url: this.config.server.url,
timeout: this.config.server.timeout,
connectTimeout: this.config.server.connectTimeout,
reconnect: true
}
// 如果使用 LDAPS (SSL/TLS),添加 TLS 选项
if (this.config.server.url.toLowerCase().startsWith('ldaps://')) {
const tlsOptions = {}
// 证书验证设置
if (this.config.server.tls) {
if (typeof this.config.server.tls.rejectUnauthorized === 'boolean') {
tlsOptions.rejectUnauthorized = this.config.server.tls.rejectUnauthorized
}
// CA 证书
if (this.config.server.tls.ca) {
tlsOptions.ca = this.config.server.tls.ca
}
// 客户端证书和私钥 (双向认证)
if (this.config.server.tls.cert) {
tlsOptions.cert = this.config.server.tls.cert
}
if (this.config.server.tls.key) {
tlsOptions.key = this.config.server.tls.key
}
// 服务器名称 (SNI)
if (this.config.server.tls.servername) {
tlsOptions.servername = this.config.server.tls.servername
}
}
clientOptions.tlsOptions = tlsOptions
logger.debug('🔒 Creating LDAPS client with TLS options:', {
url: this.config.server.url,
rejectUnauthorized: tlsOptions.rejectUnauthorized,
hasCA: !!tlsOptions.ca,
hasCert: !!tlsOptions.cert,
hasKey: !!tlsOptions.key,
servername: tlsOptions.servername
})
}
const client = ldap.createClient(clientOptions)
// 设置错误处理
client.on('error', (err) => {
if (err.code === 'CERT_HAS_EXPIRED' || err.code === 'UNABLE_TO_VERIFY_LEAF_SIGNATURE') {
logger.error('🔒 LDAP TLS certificate error:', {
code: err.code,
message: err.message,
hint: 'Consider setting LDAP_TLS_REJECT_UNAUTHORIZED=false for self-signed certificates'
})
} else {
logger.error('🔌 LDAP client error:', err)
}
})
client.on('connect', () => {
if (this.config.server.url.toLowerCase().startsWith('ldaps://')) {
logger.info('🔒 LDAPS client connected successfully')
} else {
logger.info('🔗 LDAP client connected successfully')
}
})
client.on('connectTimeout', () => {
logger.warn('⏱️ LDAP connection timeout')
})
return client
} catch (error) {
logger.error('❌ Failed to create LDAP client:', error)
throw error
}
}
// 🔒 绑定LDAP连接管理员认证
async bindClient(client) {
return new Promise((resolve, reject) => {
// 验证绑定凭据
const { bindDN } = this.config.server
const { bindCredentials } = this.config.server
if (!bindDN || typeof bindDN !== 'string') {
const error = new Error('LDAP bind DN is not configured or invalid')
logger.error('❌ LDAP configuration error:', error.message)
reject(error)
return
}
if (!bindCredentials || typeof bindCredentials !== 'string') {
const error = new Error('LDAP bind credentials are not configured or invalid')
logger.error('❌ LDAP configuration error:', error.message)
reject(error)
return
}
client.bind(bindDN, bindCredentials, (err) => {
if (err) {
logger.error('❌ LDAP bind failed:', err)
reject(err)
} else {
logger.debug('🔑 LDAP bind successful')
resolve()
}
})
})
}
// 🔍 搜索用户
async searchUser(client, username) {
return new Promise((resolve, reject) => {
// 防止LDAP注入转义特殊字符
// 根据RFC 4515需要转义的特殊字符* ( ) \ NUL
const escapedUsername = username
.replace(/\\/g, '\\5c') // 反斜杠必须先转义
.replace(/\*/g, '\\2a') // 星号
.replace(/\(/g, '\\28') // 左括号
.replace(/\)/g, '\\29') // 右括号
.replace(/\0/g, '\\00') // NUL字符
.replace(/\//g, '\\2f') // 斜杠
const searchFilter = this.config.server.searchFilter.replace('{{username}}', escapedUsername)
const searchOptions = {
scope: 'sub',
filter: searchFilter,
attributes: this.config.server.searchAttributes
}
logger.debug(`🔍 Searching for user: ${username} with filter: ${searchFilter}`)
const entries = []
client.search(this.config.server.searchBase, searchOptions, (err, res) => {
if (err) {
logger.error('❌ LDAP search error:', err)
reject(err)
return
}
res.on('searchEntry', (entry) => {
logger.debug('🔍 LDAP search entry received:', {
dn: entry.dn,
objectName: entry.objectName,
type: typeof entry.dn,
entryType: typeof entry,
hasAttributes: !!entry.attributes,
attributeCount: entry.attributes ? entry.attributes.length : 0
})
entries.push(entry)
})
res.on('searchReference', (referral) => {
logger.debug('🔗 LDAP search referral:', referral.uris)
})
res.on('error', (error) => {
logger.error('❌ LDAP search result error:', error)
reject(error)
})
res.on('end', (result) => {
logger.debug(
`✅ LDAP search completed. Status: ${result.status}, Found ${entries.length} entries`
)
if (entries.length === 0) {
resolve(null)
} else {
// Log the structure of the first entry for debugging
if (entries[0]) {
logger.debug('🔍 Full LDAP entry structure:', {
entryType: typeof entries[0],
entryConstructor: entries[0].constructor?.name,
entryKeys: Object.keys(entries[0]),
entryStringified: JSON.stringify(entries[0], null, 2).substring(0, 500)
})
}
if (entries.length === 1) {
resolve(entries[0])
} else {
logger.warn(`⚠️ Multiple LDAP entries found for username: ${username}`)
resolve(entries[0]) // 使用第一个结果
}
}
})
})
})
}
// 🔐 验证用户密码
async authenticateUser(userDN, password) {
return new Promise((resolve, reject) => {
// 验证输入参数
if (!userDN || typeof userDN !== 'string') {
const error = new Error('User DN is not provided or invalid')
logger.error('❌ LDAP authentication error:', error.message)
reject(error)
return
}
if (!password || typeof password !== 'string') {
logger.debug(`🚫 Invalid or empty password for DN: ${userDN}`)
resolve(false)
return
}
const authClient = this.createClient()
authClient.bind(userDN, password, (err) => {
authClient.unbind() // 立即关闭认证客户端
if (err) {
if (err.name === 'InvalidCredentialsError') {
logger.debug(`🚫 Invalid credentials for DN: ${userDN}`)
resolve(false)
} else {
logger.error('❌ LDAP authentication error:', err)
reject(err)
}
} else {
logger.debug(`✅ Authentication successful for DN: ${userDN}`)
resolve(true)
}
})
})
}
// 📝 提取用户信息
extractUserInfo(ldapEntry, username) {
try {
const attributes = ldapEntry.attributes || []
const userInfo = { username }
// 创建属性映射
const attrMap = {}
attributes.forEach((attr) => {
const name = attr.type || attr.name
const values = Array.isArray(attr.values) ? attr.values : [attr.values]
attrMap[name] = values.length === 1 ? values[0] : values
})
// 根据配置映射用户属性
const mapping = this.config.userMapping
userInfo.displayName = attrMap[mapping.displayName] || username
userInfo.email = attrMap[mapping.email] || ''
userInfo.firstName = attrMap[mapping.firstName] || ''
userInfo.lastName = attrMap[mapping.lastName] || ''
// 如果没有displayName尝试组合firstName和lastName
if (!userInfo.displayName || userInfo.displayName === username) {
if (userInfo.firstName || userInfo.lastName) {
userInfo.displayName = `${userInfo.firstName || ''} ${userInfo.lastName || ''}`.trim()
}
}
logger.debug('📋 Extracted user info:', {
username: userInfo.username,
displayName: userInfo.displayName,
email: userInfo.email
})
return userInfo
} catch (error) {
logger.error('❌ Error extracting user info:', error)
return { username }
}
}
// 🔍 验证和清理用户名
validateAndSanitizeUsername(username) {
if (!username || typeof username !== 'string' || username.trim() === '') {
throw new Error('Username is required and must be a non-empty string')
}
const trimmedUsername = username.trim()
// 用户名只能包含字母、数字、下划线和连字符
const usernameRegex = /^[a-zA-Z0-9_-]+$/
if (!usernameRegex.test(trimmedUsername)) {
throw new Error('Username can only contain letters, numbers, underscores, and hyphens')
}
// 长度限制 (防止过长的输入)
if (trimmedUsername.length > 64) {
throw new Error('Username cannot exceed 64 characters')
}
// 不能以连字符开头或结尾
if (trimmedUsername.startsWith('-') || trimmedUsername.endsWith('-')) {
throw new Error('Username cannot start or end with a hyphen')
}
return trimmedUsername
}
// 🔐 主要的登录验证方法
async authenticateUserCredentials(username, password) {
if (!this.config.enabled) {
throw new Error('LDAP authentication is not enabled')
}
// 验证和清理用户名 (防止LDAP注入)
const sanitizedUsername = this.validateAndSanitizeUsername(username)
if (!password || typeof password !== 'string' || password.trim() === '') {
throw new Error('Password is required and must be a non-empty string')
}
// 验证LDAP服务器配置
if (!this.config.server || !this.config.server.url) {
throw new Error('LDAP server URL is not configured')
}
if (!this.config.server.bindDN || typeof this.config.server.bindDN !== 'string') {
throw new Error('LDAP bind DN is not configured')
}
if (
!this.config.server.bindCredentials ||
typeof this.config.server.bindCredentials !== 'string'
) {
throw new Error('LDAP bind credentials are not configured')
}
if (!this.config.server.searchBase || typeof this.config.server.searchBase !== 'string') {
throw new Error('LDAP search base is not configured')
}
const client = this.createClient()
try {
// 1. 使用管理员凭据绑定
await this.bindClient(client)
// 2. 搜索用户 (使用已验证的用户名)
const ldapEntry = await this.searchUser(client, sanitizedUsername)
if (!ldapEntry) {
logger.info(`🚫 User not found in LDAP: ${sanitizedUsername}`)
return { success: false, message: 'Invalid username or password' }
}
// 3. 获取用户DN
logger.debug('🔍 LDAP entry details for DN extraction:', {
hasEntry: !!ldapEntry,
entryType: typeof ldapEntry,
entryKeys: Object.keys(ldapEntry || {}),
dn: ldapEntry.dn,
objectName: ldapEntry.objectName,
dnType: typeof ldapEntry.dn,
objectNameType: typeof ldapEntry.objectName
})
// Use the helper method to extract DN
const userDN = this.extractDN(ldapEntry)
logger.debug(`👤 Extracted user DN: ${userDN} (type: ${typeof userDN})`)
// 验证用户DN
if (!userDN) {
logger.error(`❌ Invalid or missing DN for user: ${sanitizedUsername}`, {
ldapEntryDn: ldapEntry.dn,
ldapEntryObjectName: ldapEntry.objectName,
ldapEntryType: typeof ldapEntry,
extractedDN: userDN
})
return { success: false, message: 'Authentication service error' }
}
// 4. 验证用户密码
const isPasswordValid = await this.authenticateUser(userDN, password)
if (!isPasswordValid) {
logger.info(`🚫 Invalid password for user: ${sanitizedUsername}`)
return { success: false, message: 'Invalid username or password' }
}
// 5. 提取用户信息
const userInfo = this.extractUserInfo(ldapEntry, sanitizedUsername)
// 6. 创建或更新本地用户
const user = await userService.createOrUpdateUser(userInfo)
// 7. 检查用户是否被禁用
if (!user.isActive) {
logger.security(
`🔒 Disabled user LDAP login attempt: ${sanitizedUsername} from LDAP authentication`
)
return {
success: false,
message: 'Your account has been disabled. Please contact administrator.'
}
}
// 8. 记录登录
await userService.recordUserLogin(user.id)
// 9. 创建用户会话
const sessionToken = await userService.createUserSession(user.id)
logger.info(`✅ LDAP authentication successful for user: ${sanitizedUsername}`)
return {
success: true,
user,
sessionToken,
message: 'Authentication successful'
}
} catch (error) {
// 记录详细错误供调试,但不向用户暴露
logger.error('❌ LDAP authentication error:', {
username: sanitizedUsername,
error: error.message,
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
})
// 返回通用错误消息,避免信息泄露
// 不要尝试解析具体的错误信息因为不同LDAP服务器返回的格式不同
return {
success: false,
message: 'Authentication service unavailable'
}
} finally {
// 确保客户端连接被关闭
if (client) {
client.unbind((err) => {
if (err) {
logger.debug('Error unbinding LDAP client:', err)
}
})
}
}
}
// 🔍 测试LDAP连接
async testConnection() {
if (!this.config.enabled) {
return { success: false, message: 'LDAP is not enabled' }
}
const client = this.createClient()
try {
await this.bindClient(client)
return {
success: true,
message: 'LDAP connection successful',
server: this.config.server.url,
searchBase: this.config.server.searchBase
}
} catch (error) {
logger.error('❌ LDAP connection test failed:', {
error: error.message,
server: this.config.server.url,
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
})
// 提供通用错误消息,避免泄露系统细节
let userMessage = 'LDAP connection failed'
// 对于某些已知错误类型,提供有用但不泄露细节的信息
if (error.code === 'ECONNREFUSED') {
userMessage = 'Unable to connect to LDAP server'
} else if (error.code === 'ETIMEDOUT') {
userMessage = 'LDAP server connection timeout'
} else if (error.name === 'InvalidCredentialsError') {
userMessage = 'LDAP bind credentials are invalid'
}
return {
success: false,
message: userMessage,
server: this.config.server.url.replace(/:[^:]*@/, ':***@') // 隐藏密码部分
}
} finally {
if (client) {
client.unbind((err) => {
if (err) {
logger.debug('Error unbinding test LDAP client:', err)
}
})
}
}
}
// 📊 获取LDAP配置信息不包含敏感信息
getConfigInfo() {
const configInfo = {
enabled: this.config.enabled,
server: {
url: this.config.server.url,
searchBase: this.config.server.searchBase,
searchFilter: this.config.server.searchFilter,
timeout: this.config.server.timeout,
connectTimeout: this.config.server.connectTimeout
},
userMapping: this.config.userMapping
}
// 添加 TLS 配置信息(不包含敏感数据)
if (this.config.server.url.toLowerCase().startsWith('ldaps://') && this.config.server.tls) {
configInfo.server.tls = {
rejectUnauthorized: this.config.server.tls.rejectUnauthorized,
hasCA: !!this.config.server.tls.ca,
hasCert: !!this.config.server.tls.cert,
hasKey: !!this.config.server.tls.key,
servername: this.config.server.tls.servername
}
}
return configInfo
}
}
module.exports = new LdapService()

View File

@@ -502,6 +502,8 @@ async function getAllAccounts() {
// 不解密敏感字段,只返回基本信息
accounts.push({
...accountData,
isActive: accountData.isActive === 'true',
schedulable: accountData.schedulable !== 'false',
openaiOauth: accountData.openaiOauth ? '[ENCRYPTED]' : '',
accessToken: accountData.accessToken ? '[ENCRYPTED]' : '',
refreshToken: accountData.refreshToken ? '[ENCRYPTED]' : '',

View File

@@ -45,6 +45,7 @@ class PricingService {
'claude-sonnet-3-5': 0.000006,
'claude-sonnet-3-7': 0.000006,
'claude-sonnet-4': 0.000006,
'claude-sonnet-4-20250514': 0.000006,
// Haiku 系列: $1.6/MTok
'claude-3-5-haiku': 0.0000016,
@@ -55,6 +56,17 @@ class PricingService {
'claude-haiku-3': 0.0000016,
'claude-haiku-3-5': 0.0000016
}
// 硬编码的 1M 上下文模型价格(美元/token
// 当总输入 tokens 超过 200k 时使用这些价格
this.longContextPricing = {
// claude-sonnet-4-20250514[1m] 模型的 1M 上下文价格
'claude-sonnet-4-20250514[1m]': {
input: 0.000006, // $6/MTok
output: 0.0000225 // $22.50/MTok
}
// 未来可以添加更多 1M 模型的价格
}
}
// 初始化价格服务
@@ -249,6 +261,7 @@ class PricingService {
// 尝试直接匹配
if (this.pricingData[modelName]) {
logger.debug(`💰 Found exact pricing match for ${modelName}`)
return this.pricingData[modelName]
}
@@ -293,6 +306,22 @@ class PricingService {
return null
}
// 确保价格对象包含缓存价格
ensureCachePricing(pricing) {
if (!pricing) {
return pricing
}
// 如果缺少缓存价格根据输入价格计算缓存创建价格通常是输入价格的1.25倍缓存读取是0.1倍)
if (!pricing.cache_creation_input_token_cost && pricing.input_cost_per_token) {
pricing.cache_creation_input_token_cost = pricing.input_cost_per_token * 1.25
}
if (!pricing.cache_read_input_token_cost && pricing.input_cost_per_token) {
pricing.cache_read_input_token_cost = pricing.input_cost_per_token * 0.1
}
return pricing
}
// 获取 1 小时缓存价格
getEphemeral1hPricing(modelName) {
if (!modelName) {
@@ -329,9 +358,40 @@ class PricingService {
// 计算使用费用
calculateCost(usage, modelName) {
// 检查是否为 1M 上下文模型
const isLongContextModel = modelName && modelName.includes('[1m]')
let isLongContextRequest = false
let useLongContextPricing = false
if (isLongContextModel) {
// 计算总输入 tokens
const inputTokens = usage.input_tokens || 0
const cacheCreationTokens = usage.cache_creation_input_tokens || 0
const cacheReadTokens = usage.cache_read_input_tokens || 0
const totalInputTokens = inputTokens + cacheCreationTokens + cacheReadTokens
// 如果总输入超过 200k使用 1M 上下文价格
if (totalInputTokens > 200000) {
isLongContextRequest = true
// 检查是否有硬编码的 1M 价格
if (this.longContextPricing[modelName]) {
useLongContextPricing = true
} else {
// 如果没有找到硬编码价格,使用第一个 1M 模型的价格作为默认
const defaultLongContextModel = Object.keys(this.longContextPricing)[0]
if (defaultLongContextModel) {
useLongContextPricing = true
logger.warn(
`⚠️ No specific 1M pricing for ${modelName}, using default from ${defaultLongContextModel}`
)
}
}
}
}
const pricing = this.getModelPricing(modelName)
if (!pricing) {
if (!pricing && !useLongContextPricing) {
return {
inputCost: 0,
outputCost: 0,
@@ -340,14 +400,35 @@ class PricingService {
ephemeral5mCost: 0,
ephemeral1hCost: 0,
totalCost: 0,
hasPricing: false
hasPricing: false,
isLongContextRequest: false
}
}
const inputCost = (usage.input_tokens || 0) * (pricing.input_cost_per_token || 0)
const outputCost = (usage.output_tokens || 0) * (pricing.output_cost_per_token || 0)
let inputCost = 0
let outputCost = 0
if (useLongContextPricing) {
// 使用 1M 上下文特殊价格(仅输入和输出价格改变)
const longContextPrices =
this.longContextPricing[modelName] ||
this.longContextPricing[Object.keys(this.longContextPricing)[0]]
inputCost = (usage.input_tokens || 0) * longContextPrices.input
outputCost = (usage.output_tokens || 0) * longContextPrices.output
logger.info(
`💰 Using 1M context pricing for ${modelName}: input=$${longContextPrices.input}/token, output=$${longContextPrices.output}/token`
)
} else {
// 使用正常价格
inputCost = (usage.input_tokens || 0) * (pricing?.input_cost_per_token || 0)
outputCost = (usage.output_tokens || 0) * (pricing?.output_cost_per_token || 0)
}
// 缓存价格保持不变(即使对于 1M 模型)
const cacheReadCost =
(usage.cache_read_input_tokens || 0) * (pricing.cache_read_input_token_cost || 0)
(usage.cache_read_input_tokens || 0) * (pricing?.cache_read_input_token_cost || 0)
// 处理缓存创建费用:
// 1. 如果有详细的 cache_creation 对象,使用它
@@ -362,7 +443,7 @@ class PricingService {
const ephemeral1hTokens = usage.cache_creation.ephemeral_1h_input_tokens || 0
// 5分钟缓存使用标准的 cache_creation_input_token_cost
ephemeral5mCost = ephemeral5mTokens * (pricing.cache_creation_input_token_cost || 0)
ephemeral5mCost = ephemeral5mTokens * (pricing?.cache_creation_input_token_cost || 0)
// 1小时缓存使用硬编码的价格
const ephemeral1hPrice = this.getEphemeral1hPricing(modelName)
@@ -373,7 +454,7 @@ class PricingService {
} else if (usage.cache_creation_input_tokens) {
// 旧格式,所有缓存创建 tokens 都按 5 分钟价格计算(向后兼容)
cacheCreateCost =
(usage.cache_creation_input_tokens || 0) * (pricing.cache_creation_input_token_cost || 0)
(usage.cache_creation_input_tokens || 0) * (pricing?.cache_creation_input_token_cost || 0)
ephemeral5mCost = cacheCreateCost
}
@@ -386,11 +467,22 @@ class PricingService {
ephemeral1hCost,
totalCost: inputCost + outputCost + cacheCreateCost + cacheReadCost,
hasPricing: true,
isLongContextRequest,
pricing: {
input: pricing.input_cost_per_token || 0,
output: pricing.output_cost_per_token || 0,
cacheCreate: pricing.cache_creation_input_token_cost || 0,
cacheRead: pricing.cache_read_input_token_cost || 0,
input: useLongContextPricing
? (
this.longContextPricing[modelName] ||
this.longContextPricing[Object.keys(this.longContextPricing)[0]]
)?.input || 0
: pricing?.input_cost_per_token || 0,
output: useLongContextPricing
? (
this.longContextPricing[modelName] ||
this.longContextPricing[Object.keys(this.longContextPricing)[0]]
)?.output || 0
: pricing?.output_cost_per_token || 0,
cacheCreate: pricing?.cache_creation_input_token_cost || 0,
cacheRead: pricing?.cache_read_input_token_cost || 0,
ephemeral1h: this.getEphemeral1hPricing(modelName)
}
}

View File

@@ -176,7 +176,8 @@ class UnifiedClaudeScheduler {
boundAccount &&
boundAccount.isActive === 'true' &&
boundAccount.status !== 'error' &&
boundAccount.status !== 'blocked'
boundAccount.status !== 'blocked' &&
boundAccount.status !== 'temp_error'
) {
const isRateLimited = await claudeAccountService.isAccountRateLimited(boundAccount.id)
if (!isRateLimited) {
@@ -262,6 +263,7 @@ class UnifiedClaudeScheduler {
account.isActive === 'true' &&
account.status !== 'error' &&
account.status !== 'blocked' &&
account.status !== 'temp_error' &&
(account.accountType === 'shared' || !account.accountType) && // 兼容旧数据
this._isSchedulable(account.schedulable)
) {
@@ -441,7 +443,12 @@ class UnifiedClaudeScheduler {
try {
if (accountType === 'claude-official') {
const account = await redis.getClaudeAccount(accountId)
if (!account || account.isActive !== 'true' || account.status === 'error') {
if (
!account ||
account.isActive !== 'true' ||
account.status === 'error' ||
account.status === 'temp_error'
) {
return false
}
// 检查是否可调度
@@ -452,7 +459,15 @@ class UnifiedClaudeScheduler {
return !(await claudeAccountService.isAccountRateLimited(accountId))
} else if (accountType === 'claude-console') {
const account = await claudeConsoleAccountService.getAccount(accountId)
if (!account || !account.isActive || account.status !== 'active') {
if (!account || !account.isActive) {
return false
}
// 检查账户状态
if (
account.status !== 'active' &&
account.status !== 'unauthorized' &&
account.status !== 'overloaded'
) {
return false
}
// 检查是否可调度
@@ -460,7 +475,19 @@ class UnifiedClaudeScheduler {
logger.info(`🚫 Claude Console account ${accountId} is not schedulable`)
return false
}
return !(await claudeConsoleAccountService.isAccountRateLimited(accountId))
// 检查是否被限流
if (await claudeConsoleAccountService.isAccountRateLimited(accountId)) {
return false
}
// 检查是否未授权401错误
if (account.status === 'unauthorized') {
return false
}
// 检查是否过载529错误
if (await claudeConsoleAccountService.isAccountOverloaded(accountId)) {
return false
}
return true
} else if (accountType === 'bedrock') {
const accountResult = await bedrockAccountService.getAccount(accountId)
if (!accountResult.success || !accountResult.data.isActive) {

View File

@@ -34,7 +34,11 @@ class UnifiedOpenAIScheduler {
// 普通专属账户
const boundAccount = await openaiAccountService.getAccount(apiKeyData.openaiAccountId)
if (boundAccount && boundAccount.isActive === 'true' && boundAccount.status !== 'error') {
if (
boundAccount &&
(boundAccount.isActive === true || boundAccount.isActive === 'true') &&
boundAccount.status !== 'error'
) {
// 检查是否被限流
const isRateLimited = await this.isAccountRateLimited(boundAccount.id)
if (isRateLimited) {
@@ -165,7 +169,7 @@ class UnifiedOpenAIScheduler {
const openaiAccounts = await openaiAccountService.getAllAccounts()
for (const account of openaiAccounts) {
if (
account.isActive === 'true' &&
account.isActive &&
account.status !== 'error' &&
(account.accountType === 'shared' || !account.accountType) && // 兼容旧数据
this._isSchedulable(account.schedulable)
@@ -233,7 +237,7 @@ class UnifiedOpenAIScheduler {
try {
if (accountType === 'openai') {
const account = await openaiAccountService.getAccount(accountId)
if (!account || account.isActive !== 'true' || account.status === 'error') {
if (!account || !account.isActive || account.status === 'error') {
return false
}
// 检查是否可调度
@@ -395,7 +399,7 @@ class UnifiedOpenAIScheduler {
const account = await openaiAccountService.getAccount(memberId)
if (
account &&
account.isActive === 'true' &&
account.isActive &&
account.status !== 'error' &&
this._isSchedulable(account.schedulable)
) {

514
src/services/userService.js Normal file
View File

@@ -0,0 +1,514 @@
const redis = require('../models/redis')
const crypto = require('crypto')
const logger = require('../utils/logger')
const config = require('../../config/config')
class UserService {
constructor() {
this.userPrefix = 'user:'
this.usernamePrefix = 'username:'
this.userSessionPrefix = 'user_session:'
}
// 🔑 生成用户ID
generateUserId() {
return crypto.randomBytes(16).toString('hex')
}
// 🔑 生成会话Token
generateSessionToken() {
return crypto.randomBytes(32).toString('hex')
}
// 👤 创建或更新用户
async createOrUpdateUser(userData) {
try {
const {
username,
email,
displayName,
firstName,
lastName,
role = config.userManagement.defaultUserRole,
isActive = true
} = userData
// 检查用户是否已存在
let user = await this.getUserByUsername(username)
const isNewUser = !user
if (isNewUser) {
const userId = this.generateUserId()
user = {
id: userId,
username,
email,
displayName,
firstName,
lastName,
role,
isActive,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
lastLoginAt: null,
apiKeyCount: 0,
totalUsage: {
requests: 0,
inputTokens: 0,
outputTokens: 0,
totalCost: 0
}
}
} else {
// 更新现有用户信息
user = {
...user,
email,
displayName,
firstName,
lastName,
updatedAt: new Date().toISOString()
}
}
// 保存用户信息
await redis.set(`${this.userPrefix}${user.id}`, JSON.stringify(user))
await redis.set(`${this.usernamePrefix}${username}`, user.id)
logger.info(`📝 ${isNewUser ? 'Created' : 'Updated'} user: ${username} (${user.id})`)
return user
} catch (error) {
logger.error('❌ Error creating/updating user:', error)
throw error
}
}
// 👤 通过用户名获取用户
async getUserByUsername(username) {
try {
const userId = await redis.get(`${this.usernamePrefix}${username}`)
if (!userId) {
return null
}
const userData = await redis.get(`${this.userPrefix}${userId}`)
return userData ? JSON.parse(userData) : null
} catch (error) {
logger.error('❌ Error getting user by username:', error)
throw error
}
}
// 👤 通过ID获取用户
async getUserById(userId, calculateUsage = true) {
try {
const userData = await redis.get(`${this.userPrefix}${userId}`)
if (!userData) {
return null
}
const user = JSON.parse(userData)
// Calculate totalUsage by aggregating user's API keys usage (if requested)
if (calculateUsage) {
try {
const usageStats = await this.calculateUserUsageStats(userId)
user.totalUsage = usageStats.totalUsage
user.apiKeyCount = usageStats.apiKeyCount
} catch (error) {
logger.error('❌ Error calculating user usage stats:', error)
// Fallback to stored values if calculation fails
user.totalUsage = user.totalUsage || {
requests: 0,
inputTokens: 0,
outputTokens: 0,
totalCost: 0
}
user.apiKeyCount = user.apiKeyCount || 0
}
}
return user
} catch (error) {
logger.error('❌ Error getting user by ID:', error)
throw error
}
}
// 📊 计算用户使用统计通过聚合API Keys
async calculateUserUsageStats(userId) {
try {
// Use the existing apiKeyService method which already includes usage stats
const apiKeyService = require('./apiKeyService')
const userApiKeys = await apiKeyService.getUserApiKeys(userId, true) // Include deleted keys for stats
const totalUsage = {
requests: 0,
inputTokens: 0,
outputTokens: 0,
totalCost: 0
}
for (const apiKey of userApiKeys) {
if (apiKey.usage && apiKey.usage.total) {
totalUsage.requests += apiKey.usage.total.requests || 0
totalUsage.inputTokens += apiKey.usage.total.inputTokens || 0
totalUsage.outputTokens += apiKey.usage.total.outputTokens || 0
totalUsage.totalCost += apiKey.totalCost || 0
}
}
logger.debug(
`📊 Calculated user ${userId} usage: ${totalUsage.requests} requests, ${totalUsage.inputTokens} input tokens, $${totalUsage.totalCost.toFixed(4)} total cost from ${userApiKeys.length} API keys`
)
// Count only non-deleted API keys for the user's active count
const activeApiKeyCount = userApiKeys.filter((key) => key.isDeleted !== 'true').length
return {
totalUsage,
apiKeyCount: activeApiKeyCount
}
} catch (error) {
logger.error('❌ Error calculating user usage stats:', error)
return {
totalUsage: {
requests: 0,
inputTokens: 0,
outputTokens: 0,
totalCost: 0
},
apiKeyCount: 0
}
}
}
// 📋 获取所有用户列表(管理员功能)
async getAllUsers(options = {}) {
try {
const client = redis.getClientSafe()
const { page = 1, limit = 20, role, isActive } = options
const pattern = `${this.userPrefix}*`
const keys = await client.keys(pattern)
const users = []
for (const key of keys) {
const userData = await client.get(key)
if (userData) {
const user = JSON.parse(userData)
// 应用过滤条件
if (role && user.role !== role) {
continue
}
if (typeof isActive === 'boolean' && user.isActive !== isActive) {
continue
}
// Calculate dynamic usage stats for each user
try {
const usageStats = await this.calculateUserUsageStats(user.id)
user.totalUsage = usageStats.totalUsage
user.apiKeyCount = usageStats.apiKeyCount
} catch (error) {
logger.error(`❌ Error calculating usage for user ${user.id}:`, error)
// Fallback to stored values
user.totalUsage = user.totalUsage || {
requests: 0,
inputTokens: 0,
outputTokens: 0,
totalCost: 0
}
user.apiKeyCount = user.apiKeyCount || 0
}
users.push(user)
}
}
// 排序和分页
users.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
const startIndex = (page - 1) * limit
const endIndex = startIndex + limit
const paginatedUsers = users.slice(startIndex, endIndex)
return {
users: paginatedUsers,
total: users.length,
page,
limit,
totalPages: Math.ceil(users.length / limit)
}
} catch (error) {
logger.error('❌ Error getting all users:', error)
throw error
}
}
// 🔄 更新用户状态
async updateUserStatus(userId, isActive) {
try {
const user = await this.getUserById(userId, false) // Skip usage calculation
if (!user) {
throw new Error('User not found')
}
user.isActive = isActive
user.updatedAt = new Date().toISOString()
await redis.set(`${this.userPrefix}${userId}`, JSON.stringify(user))
logger.info(`🔄 Updated user status: ${user.username} -> ${isActive ? 'active' : 'disabled'}`)
// 如果禁用用户删除所有会话并禁用其所有API Keys
if (!isActive) {
await this.invalidateUserSessions(userId)
// Disable all user's API keys when user is disabled
try {
const apiKeyService = require('./apiKeyService')
const result = await apiKeyService.disableUserApiKeys(userId)
logger.info(`🔑 Disabled ${result.count} API keys for disabled user: ${user.username}`)
} catch (error) {
logger.error('❌ Error disabling user API keys during user disable:', error)
}
}
return user
} catch (error) {
logger.error('❌ Error updating user status:', error)
throw error
}
}
// 🔄 更新用户角色
async updateUserRole(userId, role) {
try {
const user = await this.getUserById(userId, false) // Skip usage calculation
if (!user) {
throw new Error('User not found')
}
user.role = role
user.updatedAt = new Date().toISOString()
await redis.set(`${this.userPrefix}${userId}`, JSON.stringify(user))
logger.info(`🔄 Updated user role: ${user.username} -> ${role}`)
return user
} catch (error) {
logger.error('❌ Error updating user role:', error)
throw error
}
}
// 📊 更新用户API Key数量 (已废弃,现在通过聚合计算)
async updateUserApiKeyCount(userId, _count) {
// This method is deprecated since apiKeyCount is now calculated dynamically
// in getUserById by aggregating the user's API keys
logger.debug(
`📊 updateUserApiKeyCount called for ${userId} but is now deprecated (count auto-calculated)`
)
}
// 📝 记录用户登录
async recordUserLogin(userId) {
try {
const user = await this.getUserById(userId, false) // Skip usage calculation
if (!user) {
return
}
user.lastLoginAt = new Date().toISOString()
await redis.set(`${this.userPrefix}${userId}`, JSON.stringify(user))
} catch (error) {
logger.error('❌ Error recording user login:', error)
}
}
// 🎫 创建用户会话
async createUserSession(userId, sessionData = {}) {
try {
const sessionToken = this.generateSessionToken()
const session = {
token: sessionToken,
userId,
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + config.userManagement.userSessionTimeout).toISOString(),
...sessionData
}
const ttl = Math.floor(config.userManagement.userSessionTimeout / 1000)
await redis.setex(`${this.userSessionPrefix}${sessionToken}`, ttl, JSON.stringify(session))
logger.info(`🎫 Created session for user: ${userId}`)
return sessionToken
} catch (error) {
logger.error('❌ Error creating user session:', error)
throw error
}
}
// 🎫 验证用户会话
async validateUserSession(sessionToken) {
try {
const sessionData = await redis.get(`${this.userSessionPrefix}${sessionToken}`)
if (!sessionData) {
return null
}
const session = JSON.parse(sessionData)
// 检查会话是否过期
if (new Date() > new Date(session.expiresAt)) {
await this.invalidateUserSession(sessionToken)
return null
}
// 获取用户信息
const user = await this.getUserById(session.userId, false) // Skip usage calculation for validation
if (!user || !user.isActive) {
await this.invalidateUserSession(sessionToken)
return null
}
return { session, user }
} catch (error) {
logger.error('❌ Error validating user session:', error)
return null
}
}
// 🚫 使用户会话失效
async invalidateUserSession(sessionToken) {
try {
await redis.del(`${this.userSessionPrefix}${sessionToken}`)
logger.info(`🚫 Invalidated session: ${sessionToken}`)
} catch (error) {
logger.error('❌ Error invalidating user session:', error)
}
}
// 🚫 使用户所有会话失效
async invalidateUserSessions(userId) {
try {
const client = redis.getClientSafe()
const pattern = `${this.userSessionPrefix}*`
const keys = await client.keys(pattern)
for (const key of keys) {
const sessionData = await client.get(key)
if (sessionData) {
const session = JSON.parse(sessionData)
if (session.userId === userId) {
await client.del(key)
}
}
}
logger.info(`🚫 Invalidated all sessions for user: ${userId}`)
} catch (error) {
logger.error('❌ Error invalidating user sessions:', error)
}
}
// 🗑️ 删除用户(软删除,标记为不活跃)
async deleteUser(userId) {
try {
const user = await this.getUserById(userId, false) // Skip usage calculation
if (!user) {
throw new Error('User not found')
}
// 软删除:标记为不活跃并添加删除时间戳
user.isActive = false
user.deletedAt = new Date().toISOString()
user.updatedAt = new Date().toISOString()
await redis.set(`${this.userPrefix}${userId}`, JSON.stringify(user))
// 删除所有会话
await this.invalidateUserSessions(userId)
// Disable all user's API keys when user is deleted
try {
const apiKeyService = require('./apiKeyService')
const result = await apiKeyService.disableUserApiKeys(userId)
logger.info(`🔑 Disabled ${result.count} API keys for deleted user: ${user.username}`)
} catch (error) {
logger.error('❌ Error disabling user API keys during user deletion:', error)
}
logger.info(`🗑️ Soft deleted user: ${user.username} (${userId})`)
return user
} catch (error) {
logger.error('❌ Error deleting user:', error)
throw error
}
}
// 📊 获取用户统计信息
async getUserStats() {
try {
const client = redis.getClientSafe()
const pattern = `${this.userPrefix}*`
const keys = await client.keys(pattern)
const stats = {
totalUsers: 0,
activeUsers: 0,
adminUsers: 0,
regularUsers: 0,
totalApiKeys: 0,
totalUsage: {
requests: 0,
inputTokens: 0,
outputTokens: 0,
totalCost: 0
}
}
for (const key of keys) {
const userData = await client.get(key)
if (userData) {
const user = JSON.parse(userData)
stats.totalUsers++
if (user.isActive) {
stats.activeUsers++
}
if (user.role === 'admin') {
stats.adminUsers++
} else {
stats.regularUsers++
}
// Calculate dynamic usage stats for each user
try {
const usageStats = await this.calculateUserUsageStats(user.id)
stats.totalApiKeys += usageStats.apiKeyCount
stats.totalUsage.requests += usageStats.totalUsage.requests
stats.totalUsage.inputTokens += usageStats.totalUsage.inputTokens
stats.totalUsage.outputTokens += usageStats.totalUsage.outputTokens
stats.totalUsage.totalCost += usageStats.totalUsage.totalCost
} catch (error) {
logger.error(`❌ Error calculating usage for user ${user.id} in stats:`, error)
// Fallback to stored values if calculation fails
stats.totalApiKeys += user.apiKeyCount || 0
stats.totalUsage.requests += user.totalUsage?.requests || 0
stats.totalUsage.inputTokens += user.totalUsage?.inputTokens || 0
stats.totalUsage.outputTokens += user.totalUsage?.outputTokens || 0
stats.totalUsage.totalCost += user.totalUsage?.totalCost || 0
}
}
}
return stats
} catch (error) {
logger.error('❌ Error getting user stats:', error)
throw error
}
}
}
module.exports = new UserService()

View File

@@ -56,15 +56,26 @@ class WebhookConfigService {
// 验证平台配置
if (config.platforms) {
const validPlatforms = ['wechat_work', 'dingtalk', 'feishu', 'slack', 'discord', 'custom']
const validPlatforms = [
'wechat_work',
'dingtalk',
'feishu',
'slack',
'discord',
'custom',
'bark'
]
for (const platform of config.platforms) {
if (!validPlatforms.includes(platform.type)) {
throw new Error(`不支持的平台类型: ${platform.type}`)
}
if (!platform.url || !this.isValidUrl(platform.url)) {
throw new Error(`无效的webhook URL: ${platform.url}`)
// Bark平台使用deviceKey而不是url
if (platform.type !== 'bark') {
if (!platform.url || !this.isValidUrl(platform.url)) {
throw new Error(`无效的webhook URL: ${platform.url}`)
}
}
// 验证平台特定的配置
@@ -108,6 +119,88 @@ class WebhookConfigService {
case 'custom':
// 自定义webhook用户自行负责格式
break
case 'bark':
// 验证设备密钥
if (!platform.deviceKey) {
throw new Error('Bark平台必须提供设备密钥')
}
// 验证设备密钥格式通常是22-24位字符
if (platform.deviceKey.length < 20 || platform.deviceKey.length > 30) {
logger.warn('⚠️ Bark设备密钥长度可能不正确请检查是否完整复制')
}
// 验证服务器URL如果提供
if (platform.serverUrl) {
if (!this.isValidUrl(platform.serverUrl)) {
throw new Error('Bark服务器URL格式无效')
}
if (!platform.serverUrl.includes('/push')) {
logger.warn('⚠️ Bark服务器URL应该以/push结尾')
}
}
// 验证声音参数(如果提供)
if (platform.sound) {
const validSounds = [
'default',
'alarm',
'anticipate',
'bell',
'birdsong',
'bloom',
'calypso',
'chime',
'choo',
'descent',
'electronic',
'fanfare',
'glass',
'gotosleep',
'healthnotification',
'horn',
'ladder',
'mailsent',
'minuet',
'multiwayinvitation',
'newmail',
'newsflash',
'noir',
'paymentsuccess',
'shake',
'sherwoodforest',
'silence',
'spell',
'suspense',
'telegraph',
'tiptoes',
'typewriters',
'update',
'alert'
]
if (!validSounds.includes(platform.sound)) {
logger.warn(`⚠️ 未知的Bark声音: ${platform.sound}`)
}
}
// 验证级别参数
if (platform.level) {
const validLevels = ['active', 'timeSensitive', 'passive', 'critical']
if (!validLevels.includes(platform.level)) {
throw new Error(`无效的Bark通知级别: ${platform.level}`)
}
}
// 验证图标URL如果提供
if (platform.icon && !this.isValidUrl(platform.icon)) {
logger.warn('⚠️ Bark图标URL格式可能不正确')
}
// 验证点击跳转URL如果提供
if (platform.clickUrl && !this.isValidUrl(platform.clickUrl)) {
logger.warn('⚠️ Bark点击跳转URL格式可能不正确')
}
break
}
}

View File

@@ -2,6 +2,7 @@ const axios = require('axios')
const crypto = require('crypto')
const logger = require('../utils/logger')
const webhookConfigService = require('./webhookConfigService')
const { getISOStringWithTimezone } = require('../utils/dateHelper')
class WebhookService {
constructor() {
@@ -11,7 +12,8 @@ class WebhookService {
feishu: this.sendToFeishu.bind(this),
slack: this.sendToSlack.bind(this),
discord: this.sendToDiscord.bind(this),
custom: this.sendToCustom.bind(this)
custom: this.sendToCustom.bind(this),
bark: this.sendToBark.bind(this)
}
}
@@ -205,13 +207,40 @@ class WebhookService {
const payload = {
type,
service: 'claude-relay-service',
timestamp: new Date().toISOString(),
timestamp: getISOStringWithTimezone(new Date()),
data
}
await this.sendHttpRequest(platform.url, payload, platform.timeout || 10000)
}
/**
* Bark webhook
*/
async sendToBark(platform, type, data) {
const payload = {
device_key: platform.deviceKey,
title: this.getNotificationTitle(type),
body: this.formatMessageForBark(type, data),
level: platform.level || this.getBarkLevel(type),
sound: platform.sound || this.getBarkSound(type),
group: platform.group || 'claude-relay',
badge: 1
}
// 添加可选参数
if (platform.icon) {
payload.icon = platform.icon
}
if (platform.clickUrl) {
payload.url = platform.clickUrl
}
const url = platform.serverUrl || 'https://api.day.app/push'
await this.sendHttpRequest(url, payload, platform.timeout || 10000)
}
/**
* 发送HTTP请求
*/
@@ -329,7 +358,7 @@ class WebhookService {
title,
color,
fields,
timestamp: new Date().toISOString(),
timestamp: getISOStringWithTimezone(new Date()),
footer: {
text: 'Claude Relay Service'
}
@@ -351,6 +380,81 @@ class WebhookService {
return titles[type] || '📢 系统通知'
}
/**
* 获取Bark通知级别
*/
getBarkLevel(type) {
const levels = {
accountAnomaly: 'timeSensitive',
quotaWarning: 'active',
systemError: 'critical',
securityAlert: 'critical',
test: 'passive'
}
return levels[type] || 'active'
}
/**
* 获取Bark声音
*/
getBarkSound(type) {
const sounds = {
accountAnomaly: 'alarm',
quotaWarning: 'bell',
systemError: 'alert',
securityAlert: 'alarm',
test: 'default'
}
return sounds[type] || 'default'
}
/**
* 格式化Bark消息
*/
formatMessageForBark(type, data) {
const lines = []
if (data.accountName) {
lines.push(`账号: ${data.accountName}`)
}
if (data.platform) {
lines.push(`平台: ${data.platform}`)
}
if (data.status) {
lines.push(`状态: ${data.status}`)
}
if (data.errorCode) {
lines.push(`错误: ${data.errorCode}`)
}
if (data.reason) {
lines.push(`原因: ${data.reason}`)
}
if (data.message) {
lines.push(`消息: ${data.message}`)
}
if (data.quota) {
lines.push(`剩余配额: ${data.quota.remaining}/${data.quota.total}`)
}
if (data.usage) {
lines.push(`使用率: ${data.usage}%`)
}
// 添加服务标识和时间戳
lines.push(`\n服务: Claude Relay Service`)
lines.push(`时间: ${new Date().toLocaleString('zh-CN')}`)
return lines.join('\n')
}
/**
* 格式化通知详情
*/
@@ -477,7 +581,7 @@ class WebhookService {
try {
const testData = {
message: 'Claude Relay Service webhook测试',
timestamp: new Date().toISOString()
timestamp: getISOStringWithTimezone(new Date())
}
await this.sendToPlatform(platform, 'test', testData, { maxRetries: 1, retryDelay: 1000 })