/** * Supabase Authentication Configuration * * Provides comprehensive multi-tenant authentication configuration for the slide-show platform. * This module handles Supabase client setup, JWT token management, and tenant-specific * authentication settings with enterprise-grade security features. * * Features: * - Multi-tenant client isolation * - Custom JWT claims management * - Environment-specific configurations * - Token validation with tenant context * - Secure client initialization * - Comprehensive error handling and logging */ import { createClient, type SupabaseClient, type Session, type User } from '@supabase/supabase-js'; import { z } from 'zod'; // ============================================================================ // CONFIGURATION SCHEMAS AND TYPES // ============================================================================ /** * Environment configuration schema for validation */ export const SupabaseConfigSchema = z.object({ url: z.string().url('Invalid Supabase URL'), anonKey: z.string().min(1, 'Supabase anon key is required'), serviceRoleKey: z.string().min(1, 'Supabase service role key is required').optional(), jwtSecret: z.string().min(32, 'JWT secret must be at least 32 characters'), redirectTo: z.string().url('Invalid redirect URL').optional(), detectSessionInUrl: z.boolean().default(true), autoRefreshToken: z.boolean().default(true), persistSession: z.boolean().default(true), debug: z.boolean().default(false), }); export type SupabaseConfig = z.infer; /** * Tenant-specific authentication configuration */ export interface TenantAuthConfig { tenantId: string; sessionTimeoutMinutes: number; maxConcurrentSessions: number; requireMFA: boolean; enforcePasswordPolicy: boolean; passwordPolicy: { minLength: number; requireUppercase: boolean; requireLowercase: boolean; requireNumbers: boolean; requireSymbols: boolean; maxAgeDays: number; preventReuseCount: number; }; maxFailedAttempts: number; lockoutDurationMinutes: number; progressiveLockoutEnabled: boolean; allowedDomains: string[]; autoProvisionUsers: boolean; autoAssignRoles: string[]; jwtClaimMapping: Record; customClaims: Record; logAllAuthEvents: boolean; logFailedAttempts: boolean; logSessionChanges: boolean; isActive: boolean; } /** * Custom JWT claims for tenant isolation and authorization */ export interface CustomJWTClaims { sub: string; // User ID email: string; tenant_id: string; session_id?: string; roles: string[]; permissions: string[]; is_admin: boolean; display_name?: string; presentation_context?: { presentation_id?: string; role?: 'presenter' | 'viewer' | 'guest'; voice_enabled?: boolean; }; device_context?: { device_id?: string; device_type?: string; trusted?: boolean; }; iat: number; exp: number; } /** * Authentication provider types */ export type AuthProvider = 'supabase' | 'google' | 'github' | 'microsoft' | 'discord' | 'buzztrail'; /** * Client configuration options */ export interface ClientOptions { tenantId?: string; sessionToken?: string; userAgent?: string; ipAddress?: string; deviceId?: string; enableLogging?: boolean; } // ============================================================================ // CONFIGURATION MANAGER // ============================================================================ /** * Manages Supabase authentication configuration with multi-tenant support */ export class SupabaseAuthConfig { private static instance: SupabaseAuthConfig; private config: SupabaseConfig; private tenantConfigs: Map = new Map(); private clients: Map = new Map(); private constructor() { this.config = this.loadAndValidateConfig(); } /** * Get singleton instance */ public static getInstance(): SupabaseAuthConfig { if (!SupabaseAuthConfig.instance) { SupabaseAuthConfig.instance = new SupabaseAuthConfig(); } return SupabaseAuthConfig.instance; } /** * Load and validate configuration from environment */ private loadAndValidateConfig(): SupabaseConfig { const rawConfig = { url: process.env.SUPABASE_URL || process.env.VITE_SUPABASE_URL, anonKey: process.env.SUPABASE_ANON_KEY || process.env.VITE_SUPABASE_ANON_KEY, serviceRoleKey: process.env.SUPABASE_SERVICE_ROLE_KEY, jwtSecret: process.env.SUPABASE_JWT_SECRET, redirectTo: process.env.SUPABASE_REDIRECT_TO, detectSessionInUrl: process.env.SUPABASE_DETECT_SESSION_IN_URL !== 'false', autoRefreshToken: process.env.SUPABASE_AUTO_REFRESH_TOKEN !== 'false', persistSession: process.env.SUPABASE_PERSIST_SESSION !== 'false', debug: process.env.NODE_ENV === 'development' || process.env.SUPABASE_DEBUG === 'true', }; try { return SupabaseConfigSchema.parse(rawConfig); } catch (error) { if (error instanceof z.ZodError) { const issues = error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join(', '); throw new Error(`Supabase configuration validation failed: ${issues}`); } throw new Error(`Failed to load Supabase configuration: ${error}`); } } /** * Get validated configuration */ public getConfig(): SupabaseConfig { return this.config; } /** * Create tenant-isolated Supabase client */ public createClient(options: ClientOptions = {}): SupabaseClient { const clientKey = this.generateClientKey(options); // Return existing client if available const existingClient = this.clients.get(clientKey); if (existingClient) { return existingClient; } try { const client = createClient( this.config.url, this.config.anonKey, { auth: { detectSessionInUrl: this.config.detectSessionInUrl, autoRefreshToken: this.config.autoRefreshToken, persistSession: this.config.persistSession, flowType: 'pkce', // Custom headers for tenant isolation ...(options.tenantId && { headers: { 'X-Tenant-ID': options.tenantId, 'X-Device-ID': options.deviceId || 'unknown', 'User-Agent': options.userAgent || 'SlideShow-Platform/1.0', }, }), }, global: { headers: { 'X-Client-Info': 'slide-show-platform', 'X-Client-Version': '1.0.0', ...(options.tenantId && { 'X-Tenant-ID': options.tenantId }), }, }, // Enable realtime if needed for presentation features realtime: { params: { eventsPerSecond: 10, }, }, } ); // Store client for reuse this.clients.set(clientKey, client); // Set up event listeners for security monitoring this.setupClientEventListeners(client, options); if (this.config.debug) { console.log(`[SupabaseAuthConfig] Created client for tenant: ${options.tenantId || 'default'}`); } return client; } catch (error) { console.error('[SupabaseAuthConfig] Failed to create Supabase client:', error); throw new Error(`Failed to create Supabase client: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Generate unique client key for caching */ private generateClientKey(options: ClientOptions): string { return `${options.tenantId || 'default'}_${options.sessionToken || 'anon'}`; } /** * Set up client event listeners for security monitoring */ private setupClientEventListeners(client: SupabaseClient, options: ClientOptions): void { // Monitor authentication state changes client.auth.onAuthStateChange((event, session) => { if (this.config.debug || options.enableLogging) { console.log(`[SupabaseAuthConfig] Auth state changed: ${event}`, { tenantId: options.tenantId, userId: session?.user?.id, timestamp: new Date().toISOString(), }); } // Handle specific auth events switch (event) { case 'SIGNED_IN': this.handleSignIn(session, options); break; case 'SIGNED_OUT': this.handleSignOut(options); break; case 'TOKEN_REFRESHED': this.handleTokenRefresh(session, options); break; case 'USER_UPDATED': this.handleUserUpdate(session, options); break; } }); } /** * Handle user sign-in event */ private handleSignIn(session: Session | null, options: ClientOptions): void { try { if (session?.user && options.tenantId) { // Validate tenant access this.validateTenantAccess(session.user, options.tenantId); // Log successful sign-in this.logAuthEvent('user_signed_in', session.user.id, options.tenantId, { timestamp: new Date().toISOString(), deviceId: options.deviceId, ipAddress: options.ipAddress, }); } } catch (error) { console.error('[SupabaseAuthConfig] Error handling sign-in:', error); } } /** * Handle user sign-out event */ private handleSignOut(options: ClientOptions): void { try { // Clean up client cache const clientKey = this.generateClientKey(options); this.clients.delete(clientKey); // Log sign-out this.logAuthEvent('user_signed_out', 'unknown', options.tenantId, { timestamp: new Date().toISOString(), deviceId: options.deviceId, }); } catch (error) { console.error('[SupabaseAuthConfig] Error handling sign-out:', error); } } /** * Handle token refresh event */ private handleTokenRefresh(session: Session | null, options: ClientOptions): void { try { if (this.config.debug) { console.log('[SupabaseAuthConfig] Token refreshed for user:', session?.user?.id); } // Validate refreshed token if (session?.access_token) { this.validateJWTClaims(session.access_token, options.tenantId); } } catch (error) { console.error('[SupabaseAuthConfig] Error handling token refresh:', error); } } /** * Handle user update event */ private handleUserUpdate(session: Session | null, options: ClientOptions): void { try { // Log user profile update this.logAuthEvent('user_updated', session?.user?.id, options.tenantId, { timestamp: new Date().toISOString(), changes: 'profile_updated', }); } catch (error) { console.error('[SupabaseAuthConfig] Error handling user update:', error); } } /** * Validate tenant access for user */ private validateTenantAccess(user: User, tenantId: string): void { // Extract tenant information from user metadata or JWT claims const userTenantId = user.user_metadata?.tenant_id || user.app_metadata?.tenant_id; if (userTenantId && userTenantId !== tenantId) { throw new Error(`User does not have access to tenant: ${tenantId}`); } } /** * Validate JWT claims for tenant isolation */ public validateJWTClaims(token: string, expectedTenantId?: string): CustomJWTClaims { try { // Decode JWT token (simplified - in production use proper JWT library) const payload = this.decodeJWT(token); // Validate required claims if (!payload.sub || !payload.tenant_id) { throw new Error('Invalid JWT claims: missing required fields'); } // Validate tenant isolation if (expectedTenantId && payload.tenant_id !== expectedTenantId) { throw new Error(`Tenant isolation violation: expected ${expectedTenantId}, got ${payload.tenant_id}`); } // Validate expiration if (payload.exp < Math.floor(Date.now() / 1000)) { throw new Error('JWT token has expired'); } return payload as CustomJWTClaims; } catch (error) { console.error('[SupabaseAuthConfig] JWT validation failed:', error); throw error; } } /** * Decode JWT token (simplified implementation) */ private decodeJWT(token: string): Record { try { const [, payload] = token.split('.'); return JSON.parse(atob(payload)) as Record; } catch (_error) { throw new Error('Failed to decode JWT token'); } } /** * Set tenant-specific configuration */ public setTenantConfig(tenantId: string, config: TenantAuthConfig): void { this.tenantConfigs.set(tenantId, config); } /** * Get tenant-specific configuration */ public getTenantConfig(tenantId: string): TenantAuthConfig | null { return this.tenantConfigs.get(tenantId) || null; } /** * Get default tenant configuration */ public getDefaultTenantConfig(): TenantAuthConfig { return { tenantId: 'default', sessionTimeoutMinutes: 480, // 8 hours maxConcurrentSessions: 5, requireMFA: false, enforcePasswordPolicy: true, passwordPolicy: { minLength: 8, requireUppercase: true, requireLowercase: true, requireNumbers: true, requireSymbols: false, maxAgeDays: 90, preventReuseCount: 5, }, maxFailedAttempts: 5, lockoutDurationMinutes: 30, progressiveLockoutEnabled: true, allowedDomains: [], autoProvisionUsers: false, autoAssignRoles: [], jwtClaimMapping: {}, customClaims: {}, logAllAuthEvents: true, logFailedAttempts: true, logSessionChanges: true, isActive: true, }; } /** * Log authentication events */ private logAuthEvent(event: string, userId: string, tenantId?: string, metadata?: Record): void { const logEntry = { event, userId, tenantId, timestamp: new Date().toISOString(), metadata, }; if (this.config.debug) { console.log('[SupabaseAuthConfig] Auth Event:', logEntry); } // In production, send to logging service // await this.sendToLoggingService(logEntry); } /** * Clean up resources */ public cleanup(): void { this.clients.clear(); this.tenantConfigs.clear(); } /** * Health check for configuration */ public async healthCheck(): Promise<{ status: 'healthy' | 'unhealthy'; details: Record }> { try { // Test basic client creation const testClient = this.createClient(); // Test connection (simplified) const { data: _data, error } = await testClient.auth.getSession(); return { status: 'healthy', details: { configValid: true, clientCreated: true, connectionTest: !error, totalClients: this.clients.size, totalTenantConfigs: this.tenantConfigs.size, timestamp: new Date().toISOString(), }, }; } catch (error) { return { status: 'unhealthy', details: { error: error instanceof Error ? error.message : 'Unknown error', timestamp: new Date().toISOString(), }, }; } } } // ============================================================================ // CONVENIENCE EXPORTS // ============================================================================ /** * Get singleton instance of SupabaseAuthConfig */ export const supabaseAuthConfig = SupabaseAuthConfig.getInstance(); /** * Create a new Supabase client with tenant isolation */ export function createSupabaseClient(options: ClientOptions = {}): SupabaseClient { return supabaseAuthConfig.createClient(options); } /** * Validate JWT token with tenant context */ export function validateJWTToken(token: string, tenantId?: string): CustomJWTClaims { return supabaseAuthConfig.validateJWTClaims(token, tenantId); } /** * Get tenant configuration */ export function getTenantAuthConfig(tenantId: string): TenantAuthConfig | null { return supabaseAuthConfig.getTenantConfig(tenantId); } export default SupabaseAuthConfig;