UNPKG

magically-sdk

Version:

Official SDK for Magically - Build mobile apps with AI

207 lines (206 loc) 6.65 kB
import { AuthState, User, SDKConfig, AccountDeletionResponse } from './types'; export declare class MagicallyAuth { private config; private logger; private apiClient; private authState; private listeners; private refreshTimer; private tokenKey; private allowedOrigins; constructor(config: SDKConfig); /** * Simple helper - is user authenticated? */ get isAuthenticated(): boolean; /** * Initialize authentication - check for stored tokens */ private initializeAuth; /** * Sign up with email and password */ signUpWithEmail(params: { email: string; password: string; name: string; verificationCode?: string; }): Promise<{ accessToken: string; user: User; }>; /** * Sign in with email and password */ signInWithEmail(params: { email: string; password: string; }): Promise<{ accessToken: string; user: User; }>; /** * Send email verification code * @param email - User's email address * @param type - Must be 'signup' for new users or 'password_reset' for existing users. Defaults to 'signup' * @throws Error if type is invalid or API request fails */ sendVerificationCode(email: string, type?: 'signup' | 'password_reset'): Promise<void>; /** * Verify email with code */ verifyCode(email: string, code: string): Promise<void>; /** * Reset password with verification code * Single call that handles verification and password update internally */ resetPassword(params: { email: string; code: string; newPassword: string; }): Promise<void>; /** * Internal method that handles Google, Apple, and email authentication flows * Contains the core authentication logic shared by all methods */ private _performAuthenticationFlow; /** * Sign in with Google OAuth * Handles ALL complexity internally - just returns user or throws error */ signInWithGoogle(): Promise<User>; /** * Sign in with Apple OAuth * Handles ALL complexity internally - just returns user or throws error */ signInWithApple(): Promise<User>; /** * Trigger authentication flow for specified provider * Supports Google OAuth, Apple OAuth, and email/password authentication */ triggerAuthenticationFlow(provider: 'google' | 'apple' | 'email'): Promise<User>; /** * Sign out user * Handles ALL complexity internally - just clears everything */ signOut(): Promise<void>; /** * Delete user account from the app (Apple App Store compliance requirement) * * This method permanently deletes the user's account and all associated data from the app. * Depending on the app's deletion policy settings, deletion may be: * - INSTANT: Account and all data deleted immediately * - SCHEDULED: Account marked for deletion after a grace period (1-30 days) * * @returns {Promise<AccountDeletionResponse>} Response with deletion details * @throws {Error} If user is not authenticated or deletion fails * * @example * ```typescript * try { * const result = await magically.auth.deleteAccount(); * * if (result.action === 'deleted') { * console.log('Account deleted immediately'); * } else if (result.action === 'scheduled') { * console.log(`Account will be deleted on ${result.deletionDate}`); * console.log(`${result.daysRemaining} days remaining to cancel`); * } * } catch (error) { * console.error('Failed to delete account:', error); * } * ``` */ deleteAccount(): Promise<AccountDeletionResponse>; /** * Get current user - simple getter (returns cached JWT user) */ get currentUser(): User | null; /** * Get current user - LLM friendly method as LLM keeps looking for this for some reason */ getCurrentUser(): User | null; /** * Fetch fresh user data from the database (includes user_profiles) * Unlike currentUser which returns cached JWT data, this fetches fresh data from the database * * @returns Fresh user data merged with user profile, or null if not authenticated */ fetchCurrentUser(): Promise<User | null>; /** * Refresh current user data (alias for fetchCurrentUser) * Fetches fresh data from database and updates the cache */ refreshCurrentUser(): Promise<User | null>; /** * Parse user from JWT token (Supabase-like pattern for edge functions) * Automatically sets the user in auth state for subsequent operations * @param authHeaderOrToken - Either full "Bearer xxx" header or just the JWT token * @returns User object or null if invalid/expired */ getUser(authHeaderOrToken?: string | Request | null): Promise<{ user: User | null; }>; /** * Get current auth state - for debugging/UI */ get state(): AuthState; /** * Get a valid access token for API calls * Automatically refreshes if needed */ getValidToken(): Promise<string>; /** * Subscribe to auth state changes */ onAuthStateChanged(callback: (state: AuthState) => void): () => void; /** * Refresh access token */ refreshToken(): Promise<string>; /** * Check if token needs refresh and refresh if necessary */ ensureValidToken(): Promise<string>; private setAuthState; private setLoading; private setError; private notifyListeners; private getApiUrl; private getRedirectUri; private getClientId; private getOAuthClient; /** * Determine platform for OAuth redirect URI */ private getPlatform; private buildOAuthUrl; private generateState; private extractCodeFromUrl; /** * Parse authentication data from URL (supports both hash fragments and query params) */ private parseAuthDataFromUrl; private getUserFromToken; private decodeJWT; private validateToken; private storeTokens; private getStoredTokens; private clearStoredTokens; /** * Set up postMessage listener for OAuth callback (web only) */ private setupPostMessageListener; /** * Start background token refresh */ private startBackgroundRefresh; /** * Stop background token refresh */ private stopBackgroundRefresh; /** * Ensure user exists in project database */ private ensureUserInDatabase; }