UNPKG

route-claudecode

Version:

Advanced routing and transformation system for Claude Code outputs to multiple AI providers

257 lines 9.87 kB
"use strict"; /** * CodeWhisperer 多源凭据管理器 * 基于 AIClient-2-API 的灵活凭据加载策略 * 项目所有者: Jason Zhang */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.CredentialManager = void 0; const fs = __importStar(require("fs")); const path = __importStar(require("path")); const os = __importStar(require("os")); const fs_1 = require("fs"); const enhanced_auth_config_1 = require("./enhanced-auth-config"); class CredentialManager { config; logger; constructor(config = {}, logger) { this.config = { ...enhanced_auth_config_1.DEFAULT_CREDENTIAL_CONFIG, ...config }; this.logger = logger; } /** * 按优先级加载凭据 */ async loadCredentials() { const mergedCredentials = {}; for (const source of this.config.priorityOrder || []) { try { const credentials = await this.loadFromSource(source); if (credentials) { Object.assign(mergedCredentials, credentials); this.log('info', `Successfully loaded credentials from ${source}`); } } catch (error) { this.log('warn', `Failed to load credentials from ${source}: ${error instanceof Error ? error.message : String(error)}`); continue; } } // 验证必需字段 if (!mergedCredentials.accessToken && !mergedCredentials.refreshToken) { this.log('error', 'No valid credentials found from any source'); return null; } return mergedCredentials; } /** * 从指定源加载凭据 */ async loadFromSource(source) { switch (source) { case enhanced_auth_config_1.CredentialSource.BASE64: return this.loadFromBase64(); case enhanced_auth_config_1.CredentialSource.FILE_PATH: return this.loadFromFilePath(); case enhanced_auth_config_1.CredentialSource.DIRECTORY_SCAN: return this.loadFromDirectoryScan(); case enhanced_auth_config_1.CredentialSource.ENVIRONMENT: return this.loadFromEnvironment(); case enhanced_auth_config_1.CredentialSource.DEFAULT_PATH: return this.loadFromDefaultPath(); default: return null; } } /** * 从 Base64 编码字符串加载凭据 */ loadFromBase64() { if (!this.config.base64Creds) { return null; } try { const decodedCreds = Buffer.from(this.config.base64Creds, 'base64').toString('utf8'); const parsedCreds = JSON.parse(decodedCreds); this.log('debug', 'Successfully decoded Base64 credentials'); return parsedCreds; } catch (error) { this.log('error', `Failed to parse Base64 credentials: ${error instanceof Error ? error.message : String(error)}`); return null; } } /** * 从指定文件路径加载凭据 */ async loadFromFilePath() { if (!this.config.credsFilePath) { return null; } return this.loadCredentialsFromFile(this.config.credsFilePath); } /** * 从目录扫描加载凭据 */ async loadFromDirectoryScan() { const dirPath = this.config.credsDirPath || path.join(os.homedir(), '.aws', 'sso', 'cache'); if (!fs.existsSync(dirPath)) { this.log('debug', `Credentials directory not found: ${dirPath}`); return null; } try { const files = await fs_1.promises.readdir(dirPath); const mergedCredentials = {}; for (const file of files) { if (file.endsWith('.json') && file !== enhanced_auth_config_1.KIRO_AUTH_TOKEN_FILE) { const filePath = path.join(dirPath, file); const credentials = await this.loadCredentialsFromFile(filePath); if (credentials) { Object.assign(mergedCredentials, credentials); this.log('debug', `Loaded credentials from ${file}`); } } } return Object.keys(mergedCredentials).length > 0 ? mergedCredentials : null; } catch (error) { this.log('warn', `Could not scan credentials directory ${dirPath}: ${error instanceof Error ? error.message : String(error)}`); return null; } } /** * 从环境变量加载凭据 */ loadFromEnvironment() { const prefix = this.config.envPrefix || 'KIRO_'; const envCredentials = {}; const envMappings = { [`${prefix}ACCESS_TOKEN`]: 'accessToken', [`${prefix}REFRESH_TOKEN`]: 'refreshToken', [`${prefix}CLIENT_ID`]: 'clientId', [`${prefix}CLIENT_SECRET`]: 'clientSecret', [`${prefix}EXPIRES_AT`]: 'expiresAt', [`${prefix}PROFILE_ARN`]: 'profileArn', [`${prefix}REGION`]: 'region', [`${prefix}AUTH_METHOD`]: 'authMethod' }; for (const [envKey, credKey] of Object.entries(envMappings)) { const envValue = process.env[envKey]; if (envValue) { envCredentials[credKey] = envValue; } } if (Object.keys(envCredentials).length === 0) { return null; } this.log('debug', `Loaded ${Object.keys(envCredentials).length} credentials from environment variables`); return envCredentials; } /** * 从默认路径加载凭据 */ async loadFromDefaultPath() { const defaultPath = path.join(os.homedir(), '.aws', 'sso', 'cache', enhanced_auth_config_1.KIRO_AUTH_TOKEN_FILE); return this.loadCredentialsFromFile(defaultPath); } /** * 从文件加载凭据的通用方法 */ async loadCredentialsFromFile(filePath) { try { if (!fs.existsSync(filePath)) { this.log('debug', `Credential file not found: ${filePath}`); return null; } const fileContent = await fs_1.promises.readFile(filePath, 'utf8'); const credentials = JSON.parse(fileContent); return credentials; } catch (error) { if (error?.code === 'ENOENT') { this.log('debug', `Credential file not found: ${filePath}`); } else if (error instanceof SyntaxError) { this.log('warn', `Failed to parse JSON from ${filePath}: ${error.message}`); } else { this.log('warn', `Failed to read credential file ${filePath}: ${error instanceof Error ? error.message : String(error)}`); } return null; } } /** * 保存凭据到文件 */ async saveCredentialsToFile(filePath, newData) { try { let existingData = {}; // 尝试读取现有数据 try { if (fs.existsSync(filePath)) { const fileContent = await fs_1.promises.readFile(filePath, 'utf8'); existingData = JSON.parse(fileContent); } } catch (readError) { this.log('debug', `Could not read existing file ${filePath}, creating new one`); } // 合并数据 const mergedData = { ...existingData, ...newData }; // 确保目录存在 await fs_1.promises.mkdir(path.dirname(filePath), { recursive: true }); // 保存文件 await fs_1.promises.writeFile(filePath, JSON.stringify(mergedData, null, 2), 'utf8'); this.log('info', `Updated credential file: ${filePath}`); } catch (error) { this.log('error', `Failed to save credentials to file ${filePath}: ${error instanceof Error ? error.message : String(error)}`); throw error; } } /** * 日志输出方法 */ log(level, message) { if (this.logger) { this.logger[level]?.(message); } else { console.log(`[CredentialManager] ${level.toUpperCase()}: ${message}`); } } } exports.CredentialManager = CredentialManager; //# sourceMappingURL=credential-manager.js.map