|
| 1 | +/** |
| 2 | + * Authentication manager with API key validation and fallback logic |
| 3 | + */ |
| 4 | + |
| 5 | +import { AuthConfig, ValidationResult, AuthenticationResult } from "./types.js"; |
| 6 | +import { KeyValidationCache } from "./KeyValidationCache.js"; |
| 7 | +import { RateLimiter } from "./RateLimiter.js"; |
| 8 | +import { SecureKeyHandler } from "./SecureKeyHandler.js"; |
| 9 | + |
| 10 | +export class AuthManager { |
| 11 | + private config: AuthConfig; |
| 12 | + private cache: KeyValidationCache; |
| 13 | + private rateLimiter: RateLimiter; |
| 14 | + |
| 15 | + constructor(config: AuthConfig) { |
| 16 | + this.config = config; |
| 17 | + this.cache = new KeyValidationCache(config.keyValidationCache); |
| 18 | + this.rateLimiter = new RateLimiter(config.rateLimiting); |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Validate an API key |
| 23 | + */ |
| 24 | + async validateApiKey(apiKey: string): Promise<ValidationResult> { |
| 25 | + const startTime = Date.now(); |
| 26 | + |
| 27 | + // Validate format first |
| 28 | + if (!SecureKeyHandler.isValidFormat(apiKey)) { |
| 29 | + return { |
| 30 | + isValid: false, |
| 31 | + keyHash: SecureKeyHandler.hashKey(apiKey || "invalid"), |
| 32 | + errorMessage: "Invalid API key format", |
| 33 | + }; |
| 34 | + } |
| 35 | + |
| 36 | + const keyHash = SecureKeyHandler.hashKey(apiKey); |
| 37 | + |
| 38 | + // Check cache first |
| 39 | + const cached = this.cache.get(keyHash); |
| 40 | + if (cached) { |
| 41 | + return cached; |
| 42 | + } |
| 43 | + |
| 44 | + // Check rate limiting |
| 45 | + const rateLimitResult = this.rateLimiter.isAllowed(keyHash); |
| 46 | + if (!rateLimitResult.allowed) { |
| 47 | + const result: ValidationResult = { |
| 48 | + isValid: false, |
| 49 | + keyHash, |
| 50 | + errorMessage: "Rate limit exceeded", |
| 51 | + rateLimitInfo: { |
| 52 | + remaining: rateLimitResult.remaining, |
| 53 | + resetTime: rateLimitResult.resetTime, |
| 54 | + limit: this.config.rateLimiting.requestsPerMinute, |
| 55 | + }, |
| 56 | + }; |
| 57 | + return result; |
| 58 | + } |
| 59 | + |
| 60 | + // Perform actual validation |
| 61 | + // In a real implementation, this would call the Lighthouse API to validate the key |
| 62 | + // For now, we'll do basic validation and assume the key is valid if it has the right format |
| 63 | + const isValid = await this.performKeyValidation(apiKey); |
| 64 | + |
| 65 | + const result: ValidationResult = { |
| 66 | + isValid, |
| 67 | + keyHash, |
| 68 | + errorMessage: isValid ? undefined : "API key validation failed", |
| 69 | + rateLimitInfo: { |
| 70 | + remaining: rateLimitResult.remaining, |
| 71 | + resetTime: rateLimitResult.resetTime, |
| 72 | + limit: this.config.rateLimiting.requestsPerMinute, |
| 73 | + }, |
| 74 | + }; |
| 75 | + |
| 76 | + // Cache the result if valid |
| 77 | + if (isValid) { |
| 78 | + this.cache.set(keyHash, result); |
| 79 | + } |
| 80 | + |
| 81 | + return result; |
| 82 | + } |
| 83 | + |
| 84 | + /** |
| 85 | + * Get effective API key (request key or fallback) |
| 86 | + */ |
| 87 | + async getEffectiveApiKey(requestKey?: string): Promise<string> { |
| 88 | + // If request key is provided, use it |
| 89 | + if (requestKey) { |
| 90 | + return requestKey; |
| 91 | + } |
| 92 | + |
| 93 | + // Fall back to default key if configured |
| 94 | + if (this.config.defaultApiKey) { |
| 95 | + return this.config.defaultApiKey; |
| 96 | + } |
| 97 | + |
| 98 | + // If authentication is required and no key is available, throw error |
| 99 | + if (this.config.requireAuthentication) { |
| 100 | + throw new Error("API key is required. Provide apiKey parameter or configure server default."); |
| 101 | + } |
| 102 | + |
| 103 | + throw new Error("No API key available"); |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Authenticate a request and return result |
| 108 | + */ |
| 109 | + async authenticate(requestKey?: string): Promise<AuthenticationResult> { |
| 110 | + const startTime = Date.now(); |
| 111 | + |
| 112 | + try { |
| 113 | + const effectiveKey = await this.getEffectiveApiKey(requestKey); |
| 114 | + const usedFallback = !requestKey && !!this.config.defaultApiKey; |
| 115 | + |
| 116 | + const validation = await this.validateApiKey(effectiveKey); |
| 117 | + |
| 118 | + return { |
| 119 | + success: validation.isValid, |
| 120 | + keyHash: validation.keyHash, |
| 121 | + usedFallback, |
| 122 | + rateLimited: validation.rateLimitInfo?.remaining === 0 || false, |
| 123 | + authTime: Date.now() - startTime, |
| 124 | + errorMessage: validation.errorMessage, |
| 125 | + }; |
| 126 | + } catch (error) { |
| 127 | + return { |
| 128 | + success: false, |
| 129 | + keyHash: "unknown", |
| 130 | + usedFallback: false, |
| 131 | + rateLimited: false, |
| 132 | + authTime: Date.now() - startTime, |
| 133 | + errorMessage: error instanceof Error ? error.message : "Authentication failed", |
| 134 | + }; |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + /** |
| 139 | + * Sanitize API key for logging |
| 140 | + */ |
| 141 | + sanitizeApiKey(apiKey: string): string { |
| 142 | + return SecureKeyHandler.sanitizeForLogs(apiKey); |
| 143 | + } |
| 144 | + |
| 145 | + /** |
| 146 | + * Check if a key is rate limited |
| 147 | + */ |
| 148 | + isRateLimited(apiKey: string): boolean { |
| 149 | + const keyHash = SecureKeyHandler.hashKey(apiKey); |
| 150 | + const result = this.rateLimiter.getStatus(keyHash); |
| 151 | + return !result.allowed; |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Invalidate cached validation for a key |
| 156 | + */ |
| 157 | + invalidateKey(apiKey: string): void { |
| 158 | + const keyHash = SecureKeyHandler.hashKey(apiKey); |
| 159 | + this.cache.invalidate(keyHash); |
| 160 | + } |
| 161 | + |
| 162 | + /** |
| 163 | + * Get cache statistics |
| 164 | + */ |
| 165 | + getCacheStats() { |
| 166 | + return this.cache.getStats(); |
| 167 | + } |
| 168 | + |
| 169 | + /** |
| 170 | + * Get rate limiter status for a key |
| 171 | + */ |
| 172 | + getRateLimitStatus(apiKey: string) { |
| 173 | + const keyHash = SecureKeyHandler.hashKey(apiKey); |
| 174 | + return this.rateLimiter.getStatus(keyHash); |
| 175 | + } |
| 176 | + |
| 177 | + /** |
| 178 | + * Perform actual key validation |
| 179 | + * In production, this would call the Lighthouse API |
| 180 | + */ |
| 181 | + private async performKeyValidation(apiKey: string): Promise<boolean> { |
| 182 | + // Basic validation: key should be non-empty and have reasonable length |
| 183 | + // In production, this would make an API call to Lighthouse to validate the key |
| 184 | + return SecureKeyHandler.isValidFormat(apiKey); |
| 185 | + } |
| 186 | + |
| 187 | + /** |
| 188 | + * Destroy the auth manager and cleanup resources |
| 189 | + */ |
| 190 | + destroy(): void { |
| 191 | + this.cache.destroy(); |
| 192 | + this.rateLimiter.destroy(); |
| 193 | + } |
| 194 | +} |
0 commit comments