UNPKG

tryaii-mcp-server

Version:

TryAII MCP Server - 15+ AI models with comparison, cost tracking, and collective intelligence

98 lines 3.21 kB
import * as crypto from 'crypto'; import { logger } from './logger.js'; // Encryption configuration const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || '6RTLRshLJx0ZzZCjo9gWr7A3hpRajr22zEiCM3eN1CQ='; const ALGORITHM = 'aes256'; // Use legacy algorithm for Node.js compatibility const IV_LENGTH = 16; // For GCM, this is always 16 const TAG_LENGTH = 16; // Authentication tag length /** * Encrypt sensitive data (like API keys) */ export function encrypt(text) { try { const key = Buffer.from(ENCRYPTION_KEY, 'base64'); const iv = crypto.randomBytes(IV_LENGTH); const cipher = crypto.createCipheriv('aes-256-cbc', key, iv); let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); return { encryptedText: encrypted, iv: iv.toString('hex'), tag: '' // Not using auth tag for simplicity }; } catch (error) { logger.error('Encryption failed', { error }); throw new Error('Failed to encrypt data'); } } /** * Decrypt sensitive data (like API keys) */ export function decrypt(encryptedData) { try { const key = Buffer.from(ENCRYPTION_KEY, 'base64'); const iv = Buffer.from(encryptedData.iv, 'hex'); const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); let decrypted = decipher.update(encryptedData.encryptedText, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } catch (error) { logger.error('Decryption failed', { error }); throw new Error('Failed to decrypt data'); } } /** * Hash API key for identification (one-way) */ export function hashApiKey(apiKey) { return crypto.createHash('sha256').update(apiKey + 'tryaii-salt').digest('hex'); } /** * Mask API key for logging (show only first/last few characters) */ export function maskApiKey(apiKey) { if (!apiKey || apiKey.length < 8) { return '***'; } return `${apiKey.substring(0, 4)}...${apiKey.substring(apiKey.length - 4)}`; } /** * Extract user identifier from request headers or params */ export function extractUserFromApiKey(apiKey) { try { // Hash the API key to create a consistent user ID const hashedKey = hashApiKey(apiKey); // Determine provider based on API key format let provider = 'unknown'; if (apiKey.startsWith('sk-')) { provider = 'openai'; } else if (apiKey.startsWith('claude-')) { provider = 'anthropic'; } else if (apiKey.startsWith('AI')) { provider = 'google'; } else if (apiKey.includes('deepseek')) { provider = 'deepseek'; } else if (apiKey.includes('xai')) { provider = 'xai'; } return { userId: `user_${hashedKey.substring(0, 16)}`, // Use first 16 chars of hash provider }; } catch (error) { logger.error('Failed to extract user from API key', { error }); return { userId: 'anonymous', provider: 'unknown' }; } } //# sourceMappingURL=encryption.js.map