/** * Secure API Key Management System * * This module provides secure management of Tavus API keys across environments * and supports multi-customer scenarios. */ import { getEnvironmentConfig } from './environment'; export interface Customer { id: string; apiKey: string; permissions: string[]; limits: { dailyRequests: number; monthlyCredits: number; }; environment: string; } export interface ValidationResult { valid: boolean; reason?: string; customer?: Customer; } export interface ApiKeyConfig { development: string; staging: string; production: string; customers: Record; } /** * Secure API Key Manager */ export class ApiKeyManager { private static instance: ApiKeyManager; private config: ApiKeyConfig; private constructor() { this.config = this.loadConfiguration(); } static getInstance(): ApiKeyManager { if (!ApiKeyManager.instance) { ApiKeyManager.instance = new ApiKeyManager(); } return ApiKeyManager.instance; } /** * Load API key configuration from environment variables */ private loadConfiguration(): ApiKeyConfig { return { development: process.env.TAVUS_API_KEY_DEV || '', staging: process.env.TAVUS_API_KEY_STAGING || '', production: process.env.TAVUS_API_KEY_PROD || '', customers: this.loadCustomerKeys() }; } /** * Load customer API keys from environment variables */ private loadCustomerKeys(): Record { const customers: Record = {}; // Load customer keys from environment variables // Format: CUSTOMER__API_KEY, CUSTOMER__PERMISSIONS, etc. const envVars = Object.keys(process.env); const customerKeys = envVars.filter(key => key.startsWith('CUSTOMER_') && key.endsWith('_API_KEY')); for (const key of customerKeys) { const customerId = key.replace('CUSTOMER_', '').replace('_API_KEY', '').toLowerCase(); const apiKey = process.env[key] || ''; if (apiKey) { customers[customerId] = { id: customerId, apiKey, permissions: this.parseCustomerPermissions(customerId), limits: this.parseCustomerLimits(customerId), environment: process.env[`CUSTOMER_${customerId.toUpperCase()}_ENVIRONMENT`] || 'production' }; } } return customers; } /** * Parse customer permissions from environment variables */ private parseCustomerPermissions(customerId: string): string[] { const permissionsKey = `CUSTOMER_${customerId.toUpperCase()}_PERMISSIONS`; const permissions = process.env[permissionsKey]; if (permissions) { return permissions.split(',').map(p => p.trim()); } // Default permissions return ['read', 'write']; } /** * Parse customer limits from environment variables */ private parseCustomerLimits(customerId: string): { dailyRequests: number; monthlyCredits: number } { const dailyRequests = parseInt(process.env[`CUSTOMER_${customerId.toUpperCase()}_DAILY_REQUESTS`] || '1000'); const monthlyCredits = parseInt(process.env[`CUSTOMER_${customerId.toUpperCase()}_MONTHLY_CREDITS`] || '100'); return { dailyRequests, monthlyCredits }; } /** * Get API key for the current environment */ getApiKey(): string { const environment = getEnvironmentConfig().environment; switch (environment) { case 'development': return this.config.development; case 'staging': return this.config.staging; case 'production': return this.config.production; default: return this.config.development; } } /** * Get API key for a specific customer */ getCustomerApiKey(customerId: string): string | null { const customer = this.config.customers[customerId]; return customer?.apiKey || null; } /** * Validate an API key */ async validateKey(apiKey: string, environment: string): Promise { // Check if it's a customer key const customer = this.findCustomerByKey(apiKey); if (customer) { return this.validateCustomerKey(customer, environment); } // Check if it's an environment key return this.validateEnvironmentKey(apiKey, environment); } /** * Find customer by API key */ private findCustomerByKey(apiKey: string): Customer | null { for (const customer of Object.values(this.config.customers)) { if (customer.apiKey === apiKey) { return customer; } } return null; } /** * Validate customer API key */ private async validateCustomerKey(customer: Customer, environment: string): Promise { // Check environment access if (customer.environment !== environment && customer.environment !== 'all') { return { valid: false, reason: `Customer ${customer.id} does not have access to ${environment} environment` }; } // TODO: Add rate limiting and usage tracking // For now, just return valid return { valid: true, customer }; } /** * Validate environment API key */ private async validateEnvironmentKey(apiKey: string, environment: string): Promise { let expectedKey: string; switch (environment) { case 'development': expectedKey = this.config.development; break; case 'staging': expectedKey = this.config.staging; break; case 'production': expectedKey = this.config.production; break; default: return { valid: false, reason: 'Invalid environment' }; } if (apiKey === expectedKey) { return { valid: true }; } return { valid: false, reason: 'Invalid API key for environment' }; } /** * Check if API key has specific permission */ hasPermission(apiKey: string, permission: string): boolean { const customer = this.findCustomerByKey(apiKey); if (customer) { return customer.permissions.includes(permission); } // Environment keys have all permissions return true; } /** * Get customer information by API key */ getCustomerByKey(apiKey: string): Customer | null { return this.findCustomerByKey(apiKey); } /** * List all customers */ listCustomers(): Customer[] { return Object.values(this.config.customers); } /** * Add a new customer */ addCustomer(customer: Customer): void { this.config.customers[customer.id] = customer; } /** * Remove a customer */ removeCustomer(customerId: string): boolean { if (this.config.customers[customerId]) { delete this.config.customers[customerId]; return true; } return false; } /** * Reload configuration from environment variables */ reloadConfiguration(): void { this.config = this.loadConfiguration(); } } /** * Get the API key manager instance */ export function getApiKeyManager(): ApiKeyManager { return ApiKeyManager.getInstance(); } /** * Get API key for current environment (backward compatibility) */ export function getTavusApiKey(): string { return getApiKeyManager().getApiKey(); } /** * Set API key for current environment (backward compatibility) */ export function setTavusApiKey(key: string): void { const environment = getEnvironmentConfig().environment; const envKey = `TAVUS_API_KEY_${environment.toUpperCase()}`; process.env[envKey] = key; // Reload configuration const manager = getApiKeyManager(); manager.reloadConfiguration(); }