export type ApiKeyValidationResult = | { valid: true; userId: string; apiKeyId: string; } | { valid: false; error: string; }; export interface ApiKeyValidator { validate(apiKey: string): Promise; } export class EdgeFunctionApiKeyValidator implements ApiKeyValidator { private supabaseUrl: string; private supabaseAnonKey: string; constructor(supabaseUrl: string, supabaseAnonKey: string) { this.supabaseUrl = supabaseUrl; this.supabaseAnonKey = supabaseAnonKey; } async validate(apiKey: string): Promise { try { const response = await fetch( `${this.supabaseUrl}/functions/v1/validate-api-key`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.supabaseAnonKey}`, }, body: JSON.stringify({ apiKey }), }, ); if (!response.ok) { const errorData = (await response.json()) as { error?: string }; return { valid: false, error: errorData.error ?? "Validation failed" }; } const data = (await response.json()) as { userId: string; apiKeyId: string; }; return { valid: true, userId: data.userId, apiKeyId: data.apiKeyId, }; } catch { return { valid: false, error: "Failed to validate API key" }; } } }