BigBlocks Docs
Components/Authentication

AuthManager

Core authentication manager class for Bitcoin-based authentication and session management

Core authentication manager class that handles Bitcoin-based authentication, session management, backup operations, and user state. It provides a comprehensive API for managing Bitcoin identity authentication with support for multiple backup formats and OAuth integration.

Demo

Demo NoteThis demonstrates the AuthManager core functionality. The manager handles authentication state, backup management, and OAuth integration. Try the actions to see state changes.
Live AuthManager Instance
AuthManager State
Authenticated:No
Loading:No
Current Step:initial
Mode:signin
Has Local Backup:No
Wallet Capabilities:No
Linked Providers:0
Authentication Actions
Password:
OAuth Integration:
Configuration
API URL: https://api.bigblocks.ioOAuth Providers: google, githubStorage: BigBlocks MemoryStorageCallbacks: onSuccess, onError

API Reference

This component extends BitcoinAuthConfig for configuration and uses StorageAdapter for persistent storage.

Overview

The AuthManager is the core engine behind BigBlocks authentication. It manages the complete authentication lifecycle, from account creation and sign-in to backup management and session handling. It supports multiple backup formats (BAP Master, BAP Member, OneSat) and provides OAuth integration for cloud backup storage.

Key Features

  • Multi-format Backup Support: BAP Master, BAP Member, OneSat, WIF formats
  • Encrypted Storage: AES-256 encryption for local backup storage
  • OAuth Integration: Link Google, GitHub, and custom providers for cloud backups
  • Session Management: Secure session creation and management
  • Event System: Subscribe to authentication state changes
  • Wallet Integration: Check for and integrate with browser wallet extensions
  • Type-safe API: Full TypeScript support with comprehensive type definitions

Configuration

interface BitcoinAuthConfig {
  apiUrl?: string;                    // API base URL (default: '/api')
  oauthProviders?: OAuthProvider[];   // OAuth providers to enable
  customOAuthProviders?: CustomOAuthProvider[]; // Custom OAuth configurations
  backupTypes?: BackupTypeConfig;     // Allowed backup formats
  storage?: StorageAdapter;           // Storage implementation
  storageNamespace?: string;          // Storage key namespace
  theme?: ThemeConfig;               // UI theme configuration
  redirects?: RedirectConfig;        // OAuth redirect URLs
  onSuccess?: (user: AuthUser) => void; // Success callback
  onError?: (error: AuthError) => void; // Error callback
}

Basic Usage

Creating an AuthManager

import { AuthManager, createAuthManager } from 'bigblocks';

// Using factory function (recommended)
const authManager = createAuthManager({
  apiUrl: 'https://api.bigblocks.io',
  oauthProviders: ['google', 'github'],
  storage: customStorageAdapter, // Optional custom storage
});

// Direct instantiation
const authManager = new AuthManager({
  apiUrl: '/api',
  backupTypes: { enabled: ['bap-master', 'bap-member'] }
});

Authentication Flow

// Sign up new user
async function handleSignUp(password: string) {
  try {
    await authManager.signUp(password);
    console.log('Account created successfully');
  } catch (error) {
    console.error('Sign up failed:', error);
  }
}

// Sign in existing user
async function handleSignIn(password: string) {
  try {
    await authManager.signIn(password);
    console.log('Signed in successfully');
  } catch (error) {
    console.error('Sign in failed:', error);
  }
}

// Sign out current user
async function handleSignOut() {
  await authManager.signOut();
  console.log('Signed out');
}

Core Methods

Authentication Methods

class AuthManager {
  // Create new account with password
  async signUp(password: string): Promise<{ success: boolean; error?: AuthError }>
  
  // Sign in with existing backup
  async signIn(password: string): Promise<{ success: boolean; error?: AuthError }>
  
  // Sign out current user
  async signOut(): Promise<void>
  
  // Validate password against stored backup
  async validatePassword(password: string): Promise<boolean>
}

Backup Management

class AuthManager {
  // Generate backup for current user
  generateBackup(): BapMasterBackup
  
  // Import backup from file
  async importBackup(file: File): Promise<void>
  
  // Get current backup status
  getBackupStatus(): BackupStatus
}

OAuth Integration

class AuthManager {
  // Link OAuth provider for cloud backup
  async linkOAuth(provider: OAuthProvider): Promise<void>
  
  // Handle OAuth callback after authorization
  async handleOAuthCallback(provider: OAuthProvider, success: boolean): Promise<void>
  
  // Get linked OAuth providers
  getLinkedProviders(): OAuthProvider[]
}

State Management

class AuthManager {
  // Get current authentication state
  getState(): AuthState
  
  // Subscribe to state changes
  subscribe(listener: (event: AuthEvent) => void): () => void
  
  // Get action functions for UI integration
  getActions(): AuthActions
}

State Management

Authentication State

interface AuthState {
  user: AuthUser | null;           // Current authenticated user
  isAuthenticated: boolean;        // Authentication status
  isLoading: boolean;             // Loading state
  error: AuthError | null;        // Current error
  currentStep: AuthStep;          // Current flow step
  mode: 'signin' | 'signup';      // Current mode
  hasLocalBackup: boolean;        // Local backup exists
  backupStatus: BackupStatus;     // Detailed backup status
  isImportedBackup: boolean;      // Backup was imported
  hasWalletCapabilities: boolean; // Wallet extension available
  linkedProviders: OAuthProvider[]; // Linked OAuth providers
  pendingOAuthProvider: OAuthProvider | null; // Pending OAuth link
}

Event System

type AuthEvent = 
  | { type: 'AUTH_STARTED' }
  | { type: 'AUTH_SUCCESS'; user: AuthUser }
  | { type: 'AUTH_FAILED'; error: AuthError }
  | { type: 'OAUTH_STARTED'; provider: OAuthProvider }
  | { type: 'OAUTH_LINKED'; provider: OAuthProvider }
  | { type: 'BACKUP_IMPORTED'; backupType: string }
  | { type: 'BACKUP_EXPORTED' }
  | { type: 'SESSION_EXPIRED' };

Advanced Usage

State Subscription with React

import { createAuthManager } from 'bigblocks';
import { useEffect, useState } from 'react';

export function AuthStateManager() {
  const [authManager] = useState(() => createAuthManager({ 
    apiUrl: '/api',
    onSuccess: (user) => console.log('Auth success:', user),
    onError: (error) => console.error('Auth error:', error)
  }));
  
  const [authState, setAuthState] = useState(authManager.getState());

  useEffect(() => {
    const unsubscribe = authManager.subscribe((event) => {
      console.log('Auth event:', event);
      setAuthState(authManager.getState());
      
      // Handle specific events
      switch (event.type) {
        case 'AUTH_SUCCESS':
          // Redirect to dashboard
          window.location.href = '/dashboard';
          break;
        case 'AUTH_FAILED':
          // Show error message
          alert(event.error.message);
          break;
        case 'OAUTH_LINKED':
          // Show success message
          console.log(`${event.provider} linked successfully`);
          break;
      }
    });

    return unsubscribe;
  }, [authManager]);

  return (
    <div>
      <h3>Authentication Status</h3>
      <p>Authenticated: {authState.isAuthenticated ? 'Yes' : 'No'}</p>
      <p>User: {authState.user?.paymail || 'None'}</p>
      <p>Current Step: {authState.currentStep}</p>
      <p>Has Local Backup: {authState.hasLocalBackup ? 'Yes' : 'No'}</p>
      <p>Linked Providers: {authState.linkedProviders.join(', ') || 'None'}</p>
      
      {authState.error && (
        <div style={{ color: 'red' }}>
          Error: {authState.error.message}
        </div>
      )}
    </div>
  );
}

Backup Import with Validation

import { createAuthManager } from 'bigblocks';

export function BackupImporter() {
  const authManager = createAuthManager({ apiUrl: '/api' });
  const [importing, setImporting] = useState(false);

  const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    setImporting(true);
    try {
      await authManager.importBackup(file);
      console.log('Backup imported successfully');
      
      // Check backup status
      const state = authManager.getState();
      if (state.hasLocalBackup) {
        console.log('Local backup is now available');
      }
    } catch (error) {
      console.error('Import failed:', error);
      if (error.code === 'INVALID_BACKUP_FORMAT') {
        alert('Invalid backup file format');
      } else if (error.code === 'UNSUPPORTED_BACKUP_TYPE') {
        alert('This backup type is not supported');
      }
    } finally {
      setImporting(false);
    }
  };

  return (
    <div>
      <input 
        type="file" 
        accept=".json,.txt"
        onChange={handleFileSelect}
        disabled={importing}
      />
      {importing && <p>Importing backup...</p>}
    </div>
  );
}

OAuth Integration

import { createAuthManager } from 'bigblocks';

export function OAuthLinker() {
  const authManager = createAuthManager({
    apiUrl: '/api',
    oauthProviders: ['google', 'github'],
    redirects: {
      success: '/dashboard',
      error: '/auth/error'
    }
  });

  const handleLinkProvider = async (provider: 'google' | 'github') => {
    try {
      await authManager.linkOAuth(provider);
      // User will be redirected to OAuth provider
    } catch (error) {
      console.error('OAuth linking failed:', error);
    }
  };

  const handleOAuthCallback = async (provider: 'google' | 'github', success: boolean) => {
    await authManager.handleOAuthCallback(provider, success);
    
    const state = authManager.getState();
    if (state.linkedProviders.includes(provider)) {
      console.log(`${provider} linked successfully`);
    }
  };

  return (
    <div>
      <button onClick={() => handleLinkProvider('google')}>
        Link Google Account
      </button>
      <button onClick={() => handleLinkProvider('github')}>
        Link GitHub Account
      </button>
    </div>
  );
}

Custom Storage Adapter

import { StorageAdapter } from 'bigblocks';

// Custom storage adapter for server-side rendering
const serverStorageAdapter: StorageAdapter = {
  async get(key: string): Promise<string | null> {
    // Implement server-side storage retrieval
    return await db.get(`auth:${key}`);
  },
  
  async set(key: string, value: string): Promise<void> {
    // Implement server-side storage
    await db.set(`auth:${key}`, value);
  },
  
  async remove(key: string): Promise<void> {
    // Implement server-side storage removal
    await db.delete(`auth:${key}`);
  }
};

const authManager = createAuthManager({
  apiUrl: '/api',
  storage: serverStorageAdapter
});

Error Handling

The AuthManager provides detailed error information:

interface AuthError {
  code: 'BACKUP_NOT_FOUND' | 'INVALID_PASSWORD' | 'NETWORK_ERROR' | 
        'INVALID_BACKUP_FORMAT' | 'UNSUPPORTED_BACKUP_TYPE' | 
        'OAUTH_ERROR' | 'SESSION_EXPIRED' | 'UNKNOWN_ERROR';
  message: string;
  details?: Record<string, any>;
}

// Handle specific error types
try {
  await authManager.signIn(password);
} catch (error: AuthError) {
  switch (error.code) {
    case 'BACKUP_NOT_FOUND':
      // Show sign-up flow
      break;
    case 'INVALID_PASSWORD':
      // Show password reset option
      break;
    case 'NETWORK_ERROR':
      // Show retry option
      break;
    default:
      // Show generic error
      break;
  }
}

Supported Backup Formats

  • BAP Master: Complete identity with private keys and attestations
  • BAP Member: Member-only backup with limited capabilities
  • OneSat: Simple backup format with basic identity
  • WIF: Wallet Import Format for single private key

Security Features

  • AES-256 Encryption: All local backups are encrypted with user password
  • Secure Session Management: Sessions are managed securely with proper cleanup
  • OAuth Security: Secure OAuth flow with state verification
  • Storage Security: Sensitive data is never stored in plain text

Installation

npm install bigblocks