Skip to Content
📚 MyStoryFlow Docs — Your guide to preserving family stories

Authentication System Overview

This document provides a comprehensive overview of the MyStoryFlow authentication ecosystem, covering cross-app authentication, session management, admin dashboard, and user impersonation systems.

🏗️ System Architecture

The MyStoryFlow authentication system is built on a multi-layered architecture that supports:

  • Cross-App Authentication - Seamless login across web app, admin app, and tools
  • Session Management - Secure session handling with real-time synchronization
  • Admin Dashboard - Comprehensive administrative interface with role-based access
  • User Impersonation - Secure customer support and debugging capabilities

Core Technologies

  • Supabase Auth - Primary authentication provider
  • JWT Tokens - Secure session tokens with automatic refresh
  • React Context - Application state management
  • Session Bridge - Cross-domain session transfer
  • Role-Based Access Control - Granular permission system

🔐 Authentication Flow

User Registration and Login

The AuthContext provides multiple authentication methods:

  1. Email/Password Authentication

    // Sign up await signUp(email, password, { full_name: 'John Doe' }) // Sign in await signIn(email, password)
  2. OAuth Providers

    // Google authentication await signInWithGoogle() // Redirects to: /auth/callback // Apple authentication await signInWithApple() // Redirects to: /auth/callback
  3. Magic Link (Passwordless)

    await signInWithMagicLink(email) // Sends email with link to: /auth/callback
  4. Session Storage

    • HTTP-only cookies (primary, via SSR)
    • localStorage (cross-tab sync via SessionBridge)
    • sessionStorage (session hash for validation)
    • URL parameters (cross-domain transfer)

Middleware Protection

Server-side route protection is implemented in middleware:

// apps/web-app/middleware.ts export async function middleware(request: NextRequest) { return await updateSession(request) } // apps/web-app/lib/supabase/middleware.ts export async function updateSession(request: NextRequest) { // Create SSR client with cookie management const supabase = createServerClient(/* ... */) // Validate session await supabase.auth.getUser() // Route-specific protection logic // - Dashboard requires setup_completed // - Campaign creation redirects if setup complete // - Family workspace allows gift purchasers return response }

Client-Side Protection

Client components use the ProtectedRoute wrapper:

import { ProtectedRoute } from '@mystoryflow/auth' export default function DashboardPage() { return ( <ProtectedRoute redirectTo="/login"> <DashboardContent /> </ProtectedRoute> ) }

Cross-App Authentication

The SessionBridge enables seamless authentication across applications:

const sessionBridge = new SessionBridge(supabaseUrl, supabaseKey) const currentSession = await sessionBridge.getCurrentSession() const adminUrl = sessionBridge.createCrossDomainUrl( 'http://localhost:3003', currentSession ) ``` --> ## 👥 User Roles and Permissions ### Role Hierarchy ```tsx type UserRole = | 'user' // Basic user access | 'admin' // Full administrative access | 'moderator' // Content moderation access | 'super_admin' // Super administrator | 'customer_support' // Customer support access | 'content_moderator' // Content moderation only | 'analyst' // Analytics and reporting | 'billing_admin' // Billing administration ``` --> ### Permission Matrix | Feature | User | Customer Support | Moderator | Admin | Super Admin | | ------------------ | ---- | ---------------- | --------- | ----- | ----------- | | Create Stories | ✅ | ✅ | ✅ | ✅ | ✅ | | View Dashboard | ✅ | ✅ | ✅ | ✅ | ✅ | | Admin Dashboard | ❌ | ✅ | ✅ | ✅ | ✅ | | User Management | ❌ | ✅ | ✅ | ✅ | ✅ | | User Impersonation | ❌ | ❌ | ❌ | ✅ | ✅ | | Content Moderation | ❌ | ❌ | ✅ | ✅ | ✅ | | Feature Flags | ❌ | ❌ | ❌ | ✅ | ✅ | | System Settings | ❌ | ❌ | ❌ | ✅ | ✅ | | Billing Admin | ❌ | ❌ | ❌ | ❌ | ✅ | ## 🛡️ Security Features ### Session Security - **Token Refresh** - Automatic token refresh handled by Supabase client library via `onAuthStateChange` listener - **Session Validation** - Server-side session validation in middleware using `supabase.auth.getUser()` - **Cross-Tab Sync** - Session synchronization via `window.storage` events and Supabase auth state changes - **Secure Storage** - Session tokens stored in HTTP-only cookies via SSR configuration > **Implementation Status:** Multi-Factor Authentication (MFA/2FA) is implemented and available in user settings at `/dashboard/settings/two-factor`. Users can enable TOTP-based authentication using authenticator apps. ### Audit Logging All authentication and administrative events are logged via the AuditService: ```tsx interface AuditLog { id: string userId: string userEmail?: string action: string // e.g., 'login_success', 'user_impersonation_started' resource: string resourceId?: string details: Record<string, any> ipAddress?: string userAgent?: string timestamp: string severity: 'low' | 'medium' | 'high' | 'critical' category: 'auth' | 'data' | 'system' | 'security' | 'billing' | 'content' } ``` --> ## 🎛️ Admin Dashboard Integration ### Dashboard Authentication Admin users have access to both web app and admin dashboard. Role-based routing is handled by the role-routing configuration: ```tsx // packages/auth/src/role-routing.ts export const ROLE_ROUTING_CONFIG: Record<UserRole, RoleRouting> = { user: { defaultApp: 'web', allowedApps: ['web'], redirectUrl: process.env.NEXT_PUBLIC_WEB_APP_URL || 'http://localhost:3000', }, admin: { defaultApp: 'admin', allowedApps: ['web', 'admin'], redirectUrl: process.env.NEXT_PUBLIC_ADMIN_APP_URL || 'http://localhost:3003', }, // ... other roles with admin dashboard access } ``` --> ### Admin Features - **User Management** - View, edit, and manage user accounts - **Content Moderation** - Review and moderate user-generated content - **System Monitoring** - Real-time system health and performance metrics - **Feature Flags** - A/B testing and feature rollout management - **Revenue Analytics** - Financial tracking and subscription management ## 🎭 User Impersonation System ### Security Protocols User impersonation follows strict security guidelines: 1. **Admin Authentication** - Only verified admin users can impersonate (not support) 2. **Time-Limited Sessions** - Maximum 4-hour impersonation sessions with automatic expiration 3. **Comprehensive Auditing** - All actions logged with full context via AuditService 4. **Session Token** - Unique session token generated for each impersonation 5. **Manual Termination** - Admins can end sessions at any time 6. **Database Tracking** - Impersonation sessions tracked in `impersonation_sessions` table ### Impersonation Flow ```tsx // Start impersonation (admin-app) const result = await userImpersonationService.startImpersonation( adminUserId, targetUserId, reason ) if (result.success) { // Generate impersonation URL const impersonationUrl = userImpersonationService.generateImpersonationUrl( result.sessionToken ) // URL format: http://localhost:3000/admin-impersonate?token={sessionToken} window.open(impersonationUrl, '_blank') } // End impersonation await userImpersonationService.endImpersonation(adminUserId, sessionToken) ``` --> ## 🔄 Session Management ### Session Lifecycle 1. **Initialization** - Session created on successful authentication 2. **Storage** - Session stored across multiple mechanisms 3. **Synchronization** - Real-time sync across browser tabs 4. **Refresh** - Automatic token refresh before expiry 5. **Cleanup** - Session cleared on logout or expiry ### Cross-App Session Transfer ```tsx // Create session bridge const sessionBridge = new SessionBridge(supabaseUrl, supabaseAnonKey) // Get current session const currentSession = await sessionBridge.getCurrentSession() // Create cross-domain URL with session const adminUrl = sessionBridge.createCrossDomainUrl( 'http://localhost:3003', currentSession ) // Session is transferred via URL parameter, then stored locally // and cleaned up from URL ``` --> ### Real-time Synchronization Sessions are synchronized across tabs and applications using: - **Storage Events** - Cross-tab communication via `window.storage` event listener - **Supabase Auth State** - `onAuthStateChange` listener for SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED events - **Session Bridge** - Automatic session storage and sync via `setupSessionSync()` method - **Server-Side Validation** - Middleware validates session on each request via SSR client ## 📊 Analytics and Monitoring ### Authentication Metrics The AuditService tracks comprehensive authentication and security metrics: ```tsx // Available audit statistics const stats = await AuditService.getAuditStats('7d') // '24h', '7d', or '30d' interface AuditStats { totalActions: number actionsByCategory: Record<string, number> actionsBySeverity: Record<string, number> topUsers: Array<{ userId: string; email: string; actionCount: number }> recentCriticalActions: AuditLog[] } ``` --> ### Real-time Monitoring - **Audit Logs** - All actions tracked in `audit_logs` table with full context - **Security Alerts** - `detectSuspiciousActivity()` monitors for brute force and privilege escalation - **Impersonation Tracking** - All impersonation sessions logged with high severity - **Export Capabilities** - Audit logs exportable in CSV or JSON format for compliance ## 🛠️ Development Workflow ### Local Development Setup ```bash # Start all applications npm run dev # Individual apps cd apps/web-app && npm run dev # Port 3000 cd apps/admin-app && npm run dev # Port 3003 cd apps/tools-app && npm run dev # Port 3001 ``` --> ### Environment Configuration ```env # Supabase Configuration NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key SUPABASE_SERVICE_ROLE_KEY=your-service-role-key # App URLs (used by role-routing and session bridge) NEXT_PUBLIC_WEB_APP_URL=http://localhost:3000 NEXT_PUBLIC_ADMIN_APP_URL=http://localhost:3003 NEXT_PUBLIC_TOOLS_APP_URL=http://localhost:3001 # Note: JWT secrets managed by Supabase, no additional configuration needed ``` --> ### Testing Strategy ```bash # Run authentication context tests npm test -- __tests__/auth/auth-context.test.tsx # Run auth callback tests npm test -- __tests__/auth/callback.test.tsx # Run login/signup flow tests npm test -- __tests__/auth/login.test.tsx npm test -- __tests__/auth/signup.test.tsx # Note: Tests located in __tests__/auth/ directory ``` --> ## 🚨 Troubleshooting ### Common Issues 1. **Session Not Transferring Between Apps** - Check environment variables - Verify Supabase configuration - Review browser console for errors - Test with network tab open 2. **Admin Dashboard Access Denied** - Verify user role in database - Check admin permissions - Review authentication flow - Validate session tokens 3. **Impersonation Not Working** - Verify admin role (only 'admin' and 'super_admin' can impersonate) - Check impersonation_sessions table for active sessions - Verify session token is passed correctly via URL - Review audit logs for errors (high severity events) ### Debug Tools ```tsx // Check current auth state const { user, profile, loading } = useAuth() console.log('Auth State:', { user, profile, loading }) // Check session in Supabase client const { data: { session } } = await supabase.auth.getSession() console.log('Supabase Session:', session) // View audit logs for debugging const { logs } = await AuditService.getAuditLogs({ userId: user.id, limit: 10 }) console.log('Recent Audit Logs:', logs) ``` --> ## 🔐 Security Best Practices ### Implementation Guidelines 1. **Authentication Security** - Use strong password requirements - Implement rate limiting for login attempts - Enable MFA for admin accounts - Monitor for suspicious activity 2. **Session Security** - Server-side validation in middleware via `updateSession()` - Automatic token refresh via Supabase `onAuthStateChange` - HTTP-only cookies for session storage (SSR configuration) - Monitor session patterns via AuditService 3. **Admin Security** - Require additional authentication for sensitive operations - Implement role-based access control - Log all administrative actions - Regular security audits 4. **Impersonation Security** - Strict 4-hour time limits with automatic expiration - Comprehensive audit logging via AuditService (high severity) - Role verification (admin/super_admin only) - Session tracking in impersonation_sessions table - Manual termination via `endImpersonation()` ### Security Checklist - [x] Strong authentication requirements (Supabase Auth) - [x] MFA available for all accounts (TOTP-based) - [x] Session validation implemented (middleware) - [x] Cross-app security tested (SessionBridge) - [x] Audit logging configured (AuditService) - [x] Error handling implemented - [x] Security monitoring active (detectSuspiciousActivity) - [ ] Regular security reviews scheduled ## 📈 Current Implementation Status ### ✅ Implemented Features - Supabase Auth with email/password - OAuth providers (Google, Apple) - Magic link authentication - TOTP-based MFA (2FA) - Role-based access control (8 roles) - User impersonation system - Comprehensive audit logging - Session management and sync - Cross-app authentication (SessionBridge) - Server-side middleware protection - Client-side route protection ### 🚧 Known Limitations 1. **CrossAppNavigator** - Documentation references `CrossAppNavigator` class, but implementation uses `SessionBridge` directly 2. **User Notification** - Impersonation banner for users not implemented in web-app 3. **Rate Limiting** - Login rate limiting not implemented at application level (relies on Supabase) ### Planned Enhancements 1. **Advanced Authentication** - Biometric authentication - Additional social providers (GitHub, Microsoft) - Single Sign-On (SSO) for enterprise 2. **Enhanced Security** - Zero-trust architecture - Advanced threat detection - Automated incident response - Compliance automation 3. **Improved User Experience** - Mobile authentication apps - Voice-activated controls - Progressive web app features - Offline authentication 4. **Advanced Analytics** - Machine learning insights - Predictive security analytics - User behavior analysis - Performance optimization ## 📚 Related Documentation - **[Cross-App Authentication](./cross-app-authentication.mdx)** - Detailed cross-app authentication implementation - **[Admin Dashboard System](./admin-dashboard.mdx)** - Comprehensive admin dashboard documentation - **[User Impersonation](./user-impersonation.mdx)** - Complete user impersonation system guide - **[Session Management](./session-management.mdx)** - In-depth session management documentation ## 🤝 Contributing When contributing to the authentication system: 1. Follow security best practices 2. Add comprehensive tests 3. Update documentation 4. Review security implications 5. Test cross-app functionality ### Code Review Checklist - [ ] Security implications reviewed - [ ] Tests added for new features - [ ] Documentation updated - [ ] Cross-app compatibility tested - [ ] Performance impact assessed