/** * Supabase Authentication Client * * Provides comprehensive authentication client functionality with multi-tenant isolation * and enterprise-grade security features for the slide-show platform. * * Features: * - Multi-tenant user authentication * - Session management with device tracking * - Social authentication providers * - Multi-factor authentication support * - Presentation-specific authentication flows * - Real-time user state management * - Comprehensive error handling and logging * - Integration with existing BuzzTrail authentication */ import type { SupabaseClient, Session, User, AuthError } from '@supabase/supabase-js'; import { supabaseAuthConfig, type CustomJWTClaims, type TenantAuthConfig, type ClientOptions } from './auth-config'; // ============================================================================ // AUTHENTICATION INTERFACES AND TYPES // ============================================================================ export interface AuthCredentials { email: string; password: string; tenantId?: string; deviceInfo?: DeviceInfo; } export interface DeviceInfo { deviceId?: string; deviceType?: 'desktop' | 'mobile' | 'tablet'; userAgent?: string; browser?: string; operatingSystem?: string; country?: string; region?: string; city?: string; isMobile?: boolean; isTrusted?: boolean; } export interface SignUpData extends AuthCredentials { firstName?: string; lastName?: string; displayName?: string; inviteToken?: string; autoAssignRoles?: string[]; } export interface AuthResult { user: User; session: Session; claims: CustomJWTClaims; tenantConfig: TenantAuthConfig; } export interface SocialAuthProvider { provider: 'google' | 'github' | 'microsoft' | 'discord'; scopes?: string; redirectTo?: string; queryParams?: Record; } export interface MFAChallenge { challengeId: string; method: 'totp' | 'sms' | 'email'; maskedTarget?: string; expiresAt: string; } export interface MFAResponse { challengeId: string; code: string; } export interface PresentationAuthRequest { presentationId: string; role: 'presenter' | 'viewer' | 'guest'; accessCode?: string; guestName?: string; voiceEnabled?: boolean; } export interface BuzzTrailSSORequest { authorizationCode: string; state?: string; redirectUri?: string; } export interface SessionInfo { sessionId: string; userId: string; tenantId: string; deviceId?: string; ipAddress?: string; userAgent?: string; createdAt: string; lastActivityAt: string; expiresAt: string; isActive: boolean; presentationContext?: { presentationId?: string; role?: string; voiceEnabled?: boolean; }; } // ============================================================================ // AUTHENTICATION CLIENT CLASS // ============================================================================ /** * Comprehensive authentication client with multi-tenant support */ export class SupabaseAuthClient { private client: SupabaseClient; private tenantId?: string; private deviceInfo?: DeviceInfo; private currentSession?: Session; private currentClaims?: CustomJWTClaims; constructor(options: ClientOptions = {}) { this.tenantId = options.tenantId; this.deviceInfo = this.extractDeviceInfo(options); this.client = supabaseAuthConfig.createClient(options); this.setupEventListeners(); } // ============================================================================ // CORE AUTHENTICATION METHODS // ============================================================================ /** * Sign in with email and password */ async signIn(credentials: AuthCredentials): Promise { try { const { email, password, tenantId, deviceInfo } = credentials; // Update tenant context if provided if (tenantId) { this.tenantId = tenantId; } // Update device info if provided if (deviceInfo) { this.deviceInfo = { ...this.deviceInfo, ...deviceInfo }; } // Perform authentication const { data, error } = await this.client.auth.signInWithPassword({ email, password, options: { data: { tenant_id: this.tenantId, device_info: this.deviceInfo, }, }, }); if (error) { await this.handleAuthError(error, 'sign_in_failed'); throw new Error(`Authentication failed: ${error.message}`); } if (!data.user || !data.session) { throw new Error('Authentication failed: No user or session returned'); } // Validate and extract JWT claims const claims = supabaseAuthConfig.validateJWTClaims( data.session.access_token, this.tenantId ); // Get tenant configuration const tenantConfig = this.getTenantConfig(claims.tenant_id); // Create user session record await this.createUserSession(data.user.id, data.session, this.deviceInfo); // Update internal state this.currentSession = data.session; this.currentClaims = claims; // Log successful sign-in await this.logAuthEvent('user_signed_in', data.user.id, { tenantId: claims.tenant_id, deviceInfo: this.deviceInfo, timestamp: new Date().toISOString(), }); return { user: data.user, session: data.session, claims, tenantConfig, }; } catch (error) { console.error('[SupabaseAuthClient] Sign-in failed:', error); throw error; } } /** * Sign up new user */ async signUp(signUpData: SignUpData): Promise { try { const { email, password, tenantId, firstName, lastName, displayName, inviteToken, autoAssignRoles } = signUpData; // Update tenant context if (tenantId) { this.tenantId = tenantId; } const { data, error } = await this.client.auth.signUp({ email, password, options: { data: { tenant_id: this.tenantId, first_name: firstName, last_name: lastName, display_name: displayName || `${firstName} ${lastName}`.trim() || email, invite_token: inviteToken, auto_assign_roles: autoAssignRoles, device_info: this.deviceInfo, }, }, }); if (error) { await this.handleAuthError(error, 'sign_up_failed'); throw new Error(`Sign-up failed: ${error.message}`); } if (!data.user) { throw new Error('Sign-up failed: No user returned'); } // If session is available (email confirmed), proceed with full auth result if (data.session) { const claims = supabaseAuthConfig.validateJWTClaims( data.session.access_token, this.tenantId ); const tenantConfig = this.getTenantConfig(claims.tenant_id); await this.createUserSession(data.user.id, data.session, this.deviceInfo); this.currentSession = data.session; this.currentClaims = claims; await this.logAuthEvent('user_signed_up', data.user.id, { tenantId: claims.tenant_id, emailConfirmed: true, timestamp: new Date().toISOString(), }); return { user: data.user, session: data.session, claims, tenantConfig, }; } // Email confirmation required await this.logAuthEvent('user_registered_pending_confirmation', data.user.id, { tenantId: this.tenantId, email: data.user.email, timestamp: new Date().toISOString(), }); throw new Error('Please check your email to confirm your account before signing in.'); } catch (error) { console.error('[SupabaseAuthClient] Sign-up failed:', error); throw error; } } /** * Sign out current user */ async signOut(): Promise { try { const userId = this.currentClaims?.sub; const tenantId = this.currentClaims?.tenant_id; // Sign out from Supabase const { error } = await this.client.auth.signOut(); if (error) { console.error('[SupabaseAuthClient] Sign-out error:', error); } // Clean up session record if (this.currentClaims?.session_id) { await this.endUserSession(this.currentClaims.session_id); } // Clear internal state this.currentSession = undefined; this.currentClaims = undefined; // Log sign-out if (userId) { await this.logAuthEvent('user_signed_out', userId, { tenantId, timestamp: new Date().toISOString(), }); } } catch (error) { console.error('[SupabaseAuthClient] Sign-out failed:', error); throw error; } } // ============================================================================ // SOCIAL AUTHENTICATION // ============================================================================ /** * Sign in with social provider */ async signInWithProvider(providerConfig: SocialAuthProvider): Promise { try { const { provider, scopes, redirectTo, queryParams } = providerConfig; const { data: _data, error } = await this.client.auth.signInWithOAuth({ provider, options: { scopes, redirectTo, queryParams: { ...queryParams, tenant_id: this.tenantId, device_info: JSON.stringify(this.deviceInfo), }, }, }); if (error) { await this.handleAuthError(error, 'social_auth_failed'); throw new Error(`Social authentication failed: ${error.message}`); } // Log social auth attempt await this.logAuthEvent('social_auth_initiated', 'unknown', { provider, tenantId: this.tenantId, timestamp: new Date().toISOString(), }); } catch (error) { console.error('[SupabaseAuthClient] Social authentication failed:', error); throw error; } } // ============================================================================ // MULTI-FACTOR AUTHENTICATION // ============================================================================ /** * Initiate MFA challenge */ async initiateMFAChallenge(method: 'totp' | 'sms' | 'email'): Promise { try { if (!this.currentSession) { throw new Error('No active session for MFA challenge'); } // Call Supabase function to initiate MFA challenge const { data, error } = await this.client.rpc('initiate_mfa_challenge', { user_id: this.currentClaims?.sub, method, tenant_id: this.tenantId, }); if (error) { throw new Error(`MFA challenge initiation failed: ${error.message}`); } await this.logAuthEvent('mfa_challenge_initiated', this.currentClaims?.sub || 'unknown', { method, challengeId: data.challenge_id, timestamp: new Date().toISOString(), }); return { challengeId: data.challenge_id, method, maskedTarget: data.masked_target, expiresAt: data.expires_at, }; } catch (error) { console.error('[SupabaseAuthClient] MFA challenge initiation failed:', error); throw error; } } /** * Verify MFA challenge */ async verifyMFAChallenge(response: MFAResponse): Promise { try { const { challengeId, code } = response; const { data, error } = await this.client.rpc('verify_mfa_challenge', { challenge_id: challengeId, code, user_id: this.currentClaims?.sub, tenant_id: this.tenantId, }); if (error) { await this.logAuthEvent('mfa_verification_failed', this.currentClaims?.sub || 'unknown', { challengeId, error: error.message, timestamp: new Date().toISOString(), }); throw new Error(`MFA verification failed: ${error.message}`); } const verified = data.verified; await this.logAuthEvent( verified ? 'mfa_verification_success' : 'mfa_verification_failed', this.currentClaims?.sub || 'unknown', { challengeId, timestamp: new Date().toISOString(), } ); return verified; } catch (error) { console.error('[SupabaseAuthClient] MFA verification failed:', error); throw error; } } // ============================================================================ // PRESENTATION-SPECIFIC AUTHENTICATION // ============================================================================ /** * Authenticate for presentation access */ async authenticateForPresentation(request: PresentationAuthRequest): Promise { try { const { presentationId, role, accessCode, guestName, voiceEnabled } = request; let authResult: AuthResult; if (role === 'guest') { // Create temporary guest user authResult = await this.createGuestUser(presentationId, guestName, voiceEnabled); } else { // Validate current session and permissions if (!this.currentSession || !this.currentClaims) { throw new Error('Authentication required for presentation access'); } // Verify access permissions const hasAccess = await this.verifyPresentationAccess( presentationId, this.currentClaims.sub, role, accessCode ); if (!hasAccess) { throw new Error('Access denied to presentation'); } // Update session with presentation context const sessionId = this.currentClaims.session_id; if (!sessionId) { throw new Error('Session ID not found in claims'); } await this.updateSessionPresentationContext( sessionId, presentationId, role, voiceEnabled ); // Refresh claims with presentation context const refreshedClaims = { ...this.currentClaims }; refreshedClaims.presentation_context = { presentation_id: presentationId, role, voice_enabled: voiceEnabled, }; this.currentClaims = refreshedClaims; authResult = { user: { id: this.currentClaims.sub } as User, session: this.currentSession, claims: refreshedClaims, tenantConfig: this.getTenantConfig(this.currentClaims.tenant_id), }; } await this.logAuthEvent('presentation_access_granted', authResult.claims.sub, { presentationId, role, voiceEnabled, timestamp: new Date().toISOString(), }); return authResult; } catch (error) { console.error('[SupabaseAuthClient] Presentation authentication failed:', error); throw error; } } /** * Create temporary guest user for presentation */ private async createGuestUser( presentationId: string, guestName?: string, voiceEnabled?: boolean ): Promise { const { data, error } = await this.client.rpc('create_guest_user', { presentation_id: presentationId, guest_name: guestName || `Guest_${Date.now()}`, voice_enabled: voiceEnabled || false, tenant_id: this.tenantId, device_info: this.deviceInfo, }); if (error) { throw new Error(`Failed to create guest user: ${error.message}`); } return data as AuthResult; } // ============================================================================ // BUZZTRAIL SSO INTEGRATION // ============================================================================ /** * Complete BuzzTrail SSO authentication */ async completeBuzzTrailSSO(ssoRequest: BuzzTrailSSORequest): Promise { try { const { authorizationCode, state, redirectUri } = ssoRequest; const { data, error } = await this.client.rpc('complete_buzztrail_sso', { authorization_code: authorizationCode, state, redirect_uri: redirectUri, tenant_id: this.tenantId, device_info: this.deviceInfo, }); if (error) { await this.handleAuthError(error, 'buzztrail_sso_failed'); throw new Error(`BuzzTrail SSO failed: ${error.message}`); } const { user, session, claims } = data; this.currentSession = session; this.currentClaims = claims; await this.logAuthEvent('buzztrail_sso_success', claims.sub, { tenantId: claims.tenant_id, timestamp: new Date().toISOString(), }); return { user, session, claims, tenantConfig: this.getTenantConfig(claims.tenant_id), }; } catch (error) { console.error('[SupabaseAuthClient] BuzzTrail SSO failed:', error); throw error; } } // ============================================================================ // SESSION MANAGEMENT // ============================================================================ /** * Get current session information */ async getCurrentSession(): Promise { try { if (!this.currentSession || !this.currentClaims?.session_id) { return null; } const { data, error } = await this.client .from('user_sessions') .select('*') .eq('id', this.currentClaims.session_id) .single(); if (error || !data) { return null; } return { sessionId: data.id, userId: data.user_id, tenantId: data.tenant_id, deviceId: data.device_id, ipAddress: data.ip_address, userAgent: data.user_agent, createdAt: data.created_at, lastActivityAt: data.last_activity_at, expiresAt: data.expires_at, isActive: data.is_active, presentationContext: data.presentation_context, }; } catch (error) { console.error('[SupabaseAuthClient] Failed to get session info:', error); return null; } } /** * Refresh current session */ async refreshSession(): Promise { try { const { data, error } = await this.client.auth.refreshSession(); if (error || !data.session) { return null; } const claims = supabaseAuthConfig.validateJWTClaims( data.session.access_token, this.tenantId ); this.currentSession = data.session; this.currentClaims = claims; if (!data.user) { throw new Error('User data missing from authentication response'); } return { user: data.user, session: data.session, claims, tenantConfig: this.getTenantConfig(claims.tenant_id), }; } catch (error) { console.error('[SupabaseAuthClient] Session refresh failed:', error); return null; } } // ============================================================================ // UTILITY METHODS // ============================================================================ /** * Get current user */ getCurrentUser(): User | null { return this.currentSession?.user || null; } /** * Get current JWT claims */ getCurrentClaims(): CustomJWTClaims | null { return this.currentClaims || null; } /** * Check if user is authenticated */ isAuthenticated(): boolean { return !!(this.currentSession && this.currentClaims); } /** * Check if user has specific role */ hasRole(roleName: string): boolean { return this.currentClaims?.roles.includes(roleName) || false; } /** * Check if user has specific permission */ hasPermission(permissionName: string): boolean { return this.currentClaims?.permissions.includes(permissionName) || false; } /** * Get Supabase client instance */ getClient(): SupabaseClient { return this.client; } // ============================================================================ // PRIVATE HELPER METHODS // ============================================================================ private extractDeviceInfo(options: ClientOptions): DeviceInfo { return { deviceId: options.deviceId, userAgent: options.userAgent || (typeof navigator !== 'undefined' ? navigator.userAgent : undefined), // Add more device detection logic as needed }; } private setupEventListeners(): void { this.client.auth.onAuthStateChange((event, _session) => { if (event === 'SIGNED_OUT') { this.currentSession = undefined; this.currentClaims = undefined; } }); } private getTenantConfig(tenantId: string): TenantAuthConfig { return supabaseAuthConfig.getTenantConfig(tenantId) || supabaseAuthConfig.getDefaultTenantConfig(); } private async createUserSession(userId: string, session: Session, deviceInfo?: DeviceInfo): Promise { try { await this.client.rpc('create_user_session', { user_uuid: userId, device_info: deviceInfo || {}, ip_address: null, // Will be set by server }); } catch (error) { console.error('[SupabaseAuthClient] Failed to create user session:', error); } } private async endUserSession(sessionId: string): Promise { try { await this.client .from('user_sessions') .update({ is_active: false, ended_at: new Date().toISOString() }) .eq('id', sessionId); } catch (error) { console.error('[SupabaseAuthClient] Failed to end user session:', error); } } private async verifyPresentationAccess( presentationId: string, userId: string, role: string, accessCode?: string ): Promise { try { const { data, error } = await this.client.rpc('verify_presentation_access', { presentation_id: presentationId, user_id: userId, requested_role: role, access_code: accessCode, }); return !error && data?.has_access; } catch (error) { console.error('[SupabaseAuthClient] Presentation access verification failed:', error); return false; } } private async updateSessionPresentationContext( sessionId: string, presentationId: string, role: string, voiceEnabled?: boolean ): Promise { try { await this.client .from('user_sessions') .update({ presentation_context: { presentation_id: presentationId, role, voice_enabled: voiceEnabled, }, }) .eq('id', sessionId); } catch (error) { console.error('[SupabaseAuthClient] Failed to update session presentation context:', error); } } private async handleAuthError(error: AuthError, eventType: string): Promise { const errorInfo = { type: eventType, code: error.status || 'unknown', message: error.message, timestamp: new Date().toISOString(), tenantId: this.tenantId, deviceInfo: this.deviceInfo, }; console.error(`[SupabaseAuthClient] Auth error (${eventType}):`, errorInfo); // Log to audit system await this.logAuthEvent(eventType, 'unknown', errorInfo); } private async logAuthEvent(event: string, userId: string, metadata?: Record): Promise { try { // In production, this would send to a logging service const logEntry = { event, userId, tenantId: this.tenantId, timestamp: new Date().toISOString(), metadata, }; console.log('[SupabaseAuthClient] Auth Event:', logEntry); // Send to database audit log await this.client.rpc('log_auth_event', { event_type: event, user_id: userId, tenant_id: this.tenantId, metadata: metadata || {}, }); } catch (error) { console.error('[SupabaseAuthClient] Failed to log auth event:', error); } } } export default SupabaseAuthClient;