/** * Authentication Types and Interfaces * * Comprehensive TypeScript type definitions for the authentication system * supporting multi-tenant slide-show platform functionality. * * Features: * - Complete type safety for authentication flows * - Multi-tenant user and session types * - Presentation-specific authentication types * - Social authentication provider types * - Multi-factor authentication types * - Permission and role-based types * - Error handling and response types * - Integration with Supabase Auth types */ import type { User as SupabaseUser, Session as SupabaseSession } from '@supabase/supabase-js'; // ============================================================================ // CORE AUTHENTICATION TYPES // ============================================================================ /** * Authentication provider enumeration */ export type AuthProvider = | 'supabase' | 'google' | 'github' | 'microsoft' | 'discord' | 'buzztrail' | 'apple' | 'facebook' | 'twitter'; /** * User status enumeration */ export type UserStatus = | 'active' | 'pending_verification' | 'suspended' | 'inactive' | 'banned'; /** * Authentication event types */ export type AuthEventType = | 'user_signed_in' | 'user_signed_out' | 'user_signed_up' | 'user_updated' | 'password_reset_requested' | 'password_reset_completed' | 'email_confirmed' | 'mfa_enabled' | 'mfa_disabled' | 'mfa_challenge_initiated' | 'mfa_verification_success' | 'mfa_verification_failed' | 'social_auth_linked' | 'social_auth_unlinked' | 'session_created' | 'session_expired' | 'session_terminated' | 'presentation_access_granted' | 'presentation_access_denied' | 'buzztrail_sso_success' | 'buzztrail_sso_failed' | 'cross_tenant_access_blocked' | 'security_violation' | 'account_locked' | 'account_unlocked'; /** * Session status enumeration */ export type SessionStatus = | 'active' | 'expired' | 'terminated' | 'suspicious'; /** * Device type enumeration */ export type DeviceType = | 'desktop' | 'mobile' | 'tablet' | 'smart_tv' | 'unknown'; // ============================================================================ // USER AND PROFILE TYPES // ============================================================================ /** * Extended user profile with multi-tenant support */ export interface User extends Omit { // Core identity id: string; email: string; emailVerified: boolean; phone?: string; phoneVerified?: boolean; // Profile information firstName?: string; lastName?: string; displayName: string; avatarUrl?: string; timezone?: string; locale?: string; // Multi-tenant context tenantId: string; tenantRole: string; // Authentication authProvider: AuthProvider; externalAuthId?: string; lastSignInAt?: string; lastActivityAt?: string; // Status and permissions status: UserStatus; roles: string[]; permissions: string[]; isAdmin: boolean; // Preferences preferences: UserPreferences; // Audit fields createdAt: string; updatedAt: string; } /** * User preferences and settings */ export interface UserPreferences { // Notification settings emailNotifications: boolean; pushNotifications: boolean; smsNotifications: boolean; // Theme and UI theme: 'light' | 'dark' | 'auto'; language: string; dateFormat: string; timeFormat: '12h' | '24h'; // Privacy settings profileVisibility: 'public' | 'tenant' | 'private'; allowAnalytics: boolean; // Presentation defaults defaultPresentationTheme?: string; autoJoinVoice: boolean; preferredVideoQuality: 'auto' | 'high' | 'medium' | 'low'; // Security preferences requireMFAForSensitiveActions: boolean; sessionTimeout?: number; // in minutes trustedDevices: string[]; } /** * User creation data */ export interface CreateUserData { email: string; password?: string; firstName?: string; lastName?: string; displayName?: string; phone?: string; tenantId?: string; authProvider?: AuthProvider; externalAuthId?: string; inviteToken?: string; autoAssignRoles?: string[]; preferences?: Partial; metadata?: Record; } /** * User update data */ export interface UpdateUserData { firstName?: string; lastName?: string; displayName?: string; avatarUrl?: string; phone?: string; timezone?: string; locale?: string; preferences?: Partial; status?: UserStatus; metadata?: Record; } // ============================================================================ // SESSION AND TOKEN TYPES // ============================================================================ /** * Extended session with tenant context */ export interface Session extends SupabaseSession { // Core session data from Supabase access_token: string; refresh_token: string; expires_in: number; expires_at?: number; token_type: string; user: User; // Extended session information sessionId: string; tenantId: string; deviceInfo: DeviceInfo; ipAddress?: string; userAgent?: string; // Session lifecycle createdAt: string; lastActivityAt: string; expiresAt: string; status: SessionStatus; // Presentation context presentationContext?: PresentationContext; // Security information isSecure: boolean; isTrustedDevice: boolean; riskScore?: number; } /** * Device information */ export interface DeviceInfo { deviceId: string; deviceType: DeviceType; deviceName?: string; userAgent?: string; browser?: string; browserVersion?: string; operatingSystem?: string; osVersion?: string; screenResolution?: string; isMobile: boolean; isTablet: boolean; isTrusted: boolean; // Location information (if available) country?: string; region?: string; city?: string; ipAddress?: string; // Security features hasWebRTC: boolean; hasCamera: boolean; hasMicrophone: boolean; hasNotifications: boolean; } /** * Presentation context within session */ export interface PresentationContext { presentationId: string; role: PresentationRole; permissions: PresentationPermission[]; voiceEnabled: boolean; videoEnabled: boolean; canControl: boolean; canAnnotate: boolean; canChat: boolean; joinedAt: string; lastInteractionAt?: string; } /** * JWT token claims with custom fields */ export interface JWTClaims { // Standard JWT claims iss: string; // issuer sub: string; // subject (user ID) aud: string; // audience exp: number; // expiration time iat: number; // issued at nbf?: number; // not before // Custom claims email: string; tenantId: string; sessionId: string; roles: string[]; permissions: string[]; isAdmin: boolean; displayName?: string; // Device context deviceId?: string; deviceType?: DeviceType; isTrustedDevice?: boolean; // Presentation context presentationContext?: PresentationContext; // Security context riskScore?: number; requiresMFA?: boolean; lastPasswordChange?: string; } // ============================================================================ // AUTHENTICATION FLOW TYPES // ============================================================================ /** * Sign in credentials */ export interface SignInCredentials { email: string; password: string; tenantId?: string; deviceInfo?: Partial; rememberMe?: boolean; mfaCode?: string; } /** * Sign up data */ export interface SignUpData extends CreateUserData { password: string; confirmPassword: string; acceptTerms: boolean; acceptPrivacy: boolean; subscribeToNewsletter?: boolean; } /** * Password reset request */ export interface PasswordResetRequest { email: string; tenantId?: string; redirectTo?: string; } /** * Password reset completion */ export interface PasswordResetCompletion { token: string; newPassword: string; confirmPassword: string; } /** * Email verification request */ export interface EmailVerificationRequest { email: string; tenantId?: string; redirectTo?: string; } /** * Phone verification request */ export interface PhoneVerificationRequest { phone: string; tenantId?: string; } /** * Phone verification completion */ export interface PhoneVerificationCompletion { phone: string; code: string; } // ============================================================================ // SOCIAL AUTHENTICATION TYPES // ============================================================================ /** * Social authentication provider configuration */ export interface SocialAuthProvider { provider: AuthProvider; clientId: string; clientSecret?: string; scopes: string[]; redirectUri: string; authorizeUrl: string; tokenUrl: string; userInfoUrl: string; isEnabled: boolean; tenantSpecific: boolean; } /** * Social authentication request */ export interface SocialAuthRequest { provider: AuthProvider; scopes?: string[]; redirectTo?: string; state?: string; tenantId?: string; linkToExisting?: boolean; } /** * Social authentication callback */ export interface SocialAuthCallback { provider: AuthProvider; code: string; state?: string; error?: string; errorDescription?: string; } /** * External account linking */ export interface ExternalAccountLink { id: string; userId: string; provider: AuthProvider; externalUserId: string; externalEmail?: string; externalUsername?: string; accessToken?: string; // encrypted refreshToken?: string; // encrypted tokenExpiresAt?: string; profileData: Record; isVerified: boolean; linkedAt: string; lastSyncAt?: string; } // ============================================================================ // MULTI-FACTOR AUTHENTICATION TYPES // ============================================================================ /** * MFA method types */ export type MFAMethod = | 'totp' | 'sms' | 'email' | 'backup_codes' | 'hardware_key' | 'biometric' | 'push_notification'; /** * MFA setup configuration */ export interface MFASetup { method: MFAMethod; isEnabled: boolean; isVerified: boolean; setupData?: { // For TOTP secret?: string; qrCodeUrl?: string; backupCodes?: string[]; // For SMS/Email target?: string; // For hardware keys credentialId?: string; publicKey?: string; }; createdAt: string; verifiedAt?: string; } /** * MFA challenge */ export interface MFAChallenge { challengeId: string; method: MFAMethod; target?: string; // masked phone/email expiresAt: string; attemptsRemaining: number; } /** * MFA verification */ export interface MFAVerification { challengeId: string; code: string; method: MFAMethod; deviceInfo?: Partial; } /** * MFA status */ export interface MFAStatus { isEnabled: boolean; isRequired: boolean; availableMethods: MFAMethod[]; enabledMethods: MFAMethod[]; preferredMethod?: MFAMethod; backupCodesRemaining?: number; lastVerifiedAt?: string; } // ============================================================================ // PRESENTATION AUTHENTICATION TYPES // ============================================================================ /** * Presentation role types */ export type PresentationRole = | 'owner' | 'presenter' | 'co_presenter' | 'moderator' | 'viewer' | 'guest'; /** * Presentation permission types */ export type PresentationPermission = | 'view' | 'present' | 'control' | 'annotate' | 'chat' | 'voice' | 'video' | 'screen_share' | 'recording' | 'invite_users' | 'manage_settings' | 'end_presentation'; /** * Presentation access request */ export interface PresentationAccessRequest { presentationId: string; requestedRole: PresentationRole; accessCode?: string; guestName?: string; guestEmail?: string; voiceEnabled?: boolean; videoEnabled?: boolean; deviceInfo?: Partial; } /** * Presentation access grant */ export interface PresentationAccessGrant { presentationId: string; userId: string; role: PresentationRole; permissions: PresentationPermission[]; grantedBy: string; grantedAt: string; expiresAt?: string; accessCode?: string; isActive: boolean; } /** * Guest user creation */ export interface GuestUserCreation { presentationId: string; guestName: string; guestEmail?: string; tempUserId: string; tempToken: string; expiresAt: string; permissions: PresentationPermission[]; } // ============================================================================ // TENANT AND ORGANIZATION TYPES // ============================================================================ /** * Tenant information */ export interface Tenant { id: string; name: string; domain?: string; slug: string; status: 'active' | 'suspended' | 'inactive'; plan: 'free' | 'professional' | 'enterprise' | 'custom'; // Limits and quotas maxUsers: number; maxPresentations: number; maxStorageGB: number; maxMonthlySessions: number; // Features features: string[]; settings: TenantSettings; // Branding logoUrl?: string; primaryColor?: string; customDomain?: string; // Billing billingEmail?: string; subscriptionId?: string; subscriptionStatus?: string; currentPeriodEnd?: string; // Audit createdAt: string; updatedAt: string; createdBy: string; } /** * Tenant settings */ export interface TenantSettings { // Authentication settings authConfig: { allowedDomains: string[]; requireEmailVerification: boolean; requireMFA: boolean; passwordPolicy: PasswordPolicy; sessionTimeoutMinutes: number; maxConcurrentSessions: number; enableSocialAuth: boolean; enabledSocialProviders: AuthProvider[]; }; // Presentation settings presentationConfig: { defaultTheme: string; allowGuestAccess: boolean; maxGuestsPerPresentation: number; defaultPresentationTimeout: number; enableRecording: boolean; enableVoice: boolean; enableVideo: boolean; enableScreenShare: boolean; enableAnnotations: boolean; enableChat: boolean; }; // Security settings securityConfig: { enableAuditLogging: boolean; enableSecurityAlerts: boolean; ipWhitelist: string[]; enableDeviceTracking: boolean; requireSecureConnections: boolean; }; // Integration settings integrationConfig: { enableBuzzTrailSSO: boolean; enableWebhooks: boolean; webhookUrls: string[]; apiRateLimit: number; }; } /** * Password policy configuration */ export interface PasswordPolicy { minLength: number; maxLength: number; requireUppercase: boolean; requireLowercase: boolean; requireNumbers: boolean; requireSymbols: boolean; preventCommonPasswords: boolean; preventUserInfoInPassword: boolean; maxAgeDays: number; preventReuseCount: number; minTimeBetweenChangesHours: number; } // ============================================================================ // ROLE AND PERMISSION TYPES // ============================================================================ /** * Role definition */ export interface Role { id: string; name: string; displayName: string; description: string; tenantId: string; permissions: Permission[]; isSystemRole: boolean; isDefaultRole: boolean; isAssignable: boolean; createdAt: string; updatedAt: string; } /** * Permission definition */ export interface Permission { id: string; name: string; displayName: string; description: string; category: string; resource: string; actions: string[]; conditions?: PermissionCondition[]; isSystemPermission: boolean; } /** * Permission condition */ export interface PermissionCondition { field: string; operator: 'equals' | 'not_equals' | 'in' | 'not_in' | 'greater_than' | 'less_than' | 'contains'; value: unknown; } /** * User role assignment */ export interface UserRoleAssignment { id: string; userId: string; roleId: string; tenantId: string; grantedBy: string; grantedAt: string; expiresAt?: string; isActive: boolean; conditions?: PermissionCondition[]; } // ============================================================================ // API RESPONSE TYPES // ============================================================================ /** * Authentication result */ export interface AuthResult { success: boolean; user?: User; session?: Session; claims?: JWTClaims; tenant?: Tenant; mfaRequired?: boolean; mfaChallenge?: MFAChallenge; error?: AuthError; } /** * Authentication error */ export interface AuthError { code: string; message: string; details?: Record; timestamp: string; requestId?: string; } /** * Validation result */ export interface ValidationResult { isValid: boolean; errors: ValidationError[]; warnings: ValidationWarning[]; } /** * Validation error */ export interface ValidationError { field: string; code: string; message: string; value?: unknown; } /** * Validation warning */ export interface ValidationWarning { field: string; code: string; message: string; value?: unknown; } /** * API response wrapper */ export interface ApiResponse { success: boolean; data?: T; error?: AuthError; metadata?: { requestId: string; timestamp: string; version: string; pagination?: { page: number; limit: number; total: number; hasMore: boolean; }; }; } // ============================================================================ // EVENT AND AUDIT TYPES // ============================================================================ /** * Authentication event */ export interface AuthEvent { id: string; type: AuthEventType; userId?: string; tenantId?: string; sessionId?: string; deviceId?: string; ipAddress?: string; userAgent?: string; success: boolean; error?: string; metadata: Record; timestamp: string; } /** * Security event */ export interface SecurityEvent { id: string; type: 'suspicious_login' | 'multiple_failed_attempts' | 'unusual_location' | 'device_change' | 'privilege_escalation'; severity: 'low' | 'medium' | 'high' | 'critical'; userId?: string; tenantId?: string; description: string; details: Record; resolved: boolean; resolvedBy?: string; resolvedAt?: string; timestamp: string; } /** * Audit log entry */ export interface AuditLogEntry { id: string; tenantId: string; userId: string; action: string; resource: string; resourceId?: string; oldValues?: Record; newValues?: Record; ipAddress?: string; userAgent?: string; success: boolean; error?: string; timestamp: string; } // ============================================================================ // UTILITY TYPES // ============================================================================ /** * Optional fields utility type */ export type Optional = Omit & Partial>; /** * Required fields utility type */ export type Required = T & { [P in K]-?: T[P] }; /** * Deep partial utility type */ export type DeepPartial = { [P in keyof T]?: T[P] extends object ? DeepPartial : T[P]; }; /** * Timestamp fields utility type */ export type WithTimestamps = T & { createdAt: string; updatedAt: string; }; /** * Tenant scoped entity utility type */ export type TenantScoped = T & { tenantId: string; };