Client Errors - FeitianTech/postquantum-webauthn-platform GitHub Wiki

Client-Side Error Handling in Post-Quantum WebAuthn Platform

Table of Contents

  1. Introduction
  2. Error Handling Architecture
  3. WebAuthn API Exception Types
  4. Simple Interface Error Handling
  5. Advanced Interface Error Handling
  6. Form Validation and Error Display
  7. Error Message Presentation Patterns
  8. Error Recovery Mechanisms
  9. Best Practices and Guidelines
  10. Troubleshooting Common Issues

Introduction

The Post-Quantum WebAuthn Platform frontend implements a comprehensive client-side error handling system designed to gracefully manage WebAuthn API exceptions, form validation errors, and user interface feedback. The system provides distinct error handling approaches for both simple and advanced authentication interfaces, with sophisticated mechanisms for displaying user-friendly error messages and guiding users through recovery processes.

The error handling system operates across multiple JavaScript modules, each specialized for different aspects of the authentication flow. This modular approach ensures consistent error presentation while accommodating the varying complexity requirements of simple versus advanced WebAuthn configurations.

Error Handling Architecture

The error handling system follows a layered architecture with clear separation of concerns:

graph TB
subgraph "Error Handling Layers"
A[WebAuthn API Layer] --> B[JavaScript Error Handlers]
B --> C[Form Validation Layer]
C --> D[UI Status Display Layer]
D --> E[User Feedback System]
end
subgraph "Error Types"
F[NotAllowedError]
G[InvalidStateError]
H[SecurityError]
I[NotSupportedError]
J[Validation Errors]
K[Network Errors]
end
A --> F
A --> G
A --> H
A --> I
C --> J
B --> K
Loading

Diagram sources

  • auth-simple.js
  • auth-advanced.js
  • forms.js

The architecture consists of four primary layers:

  1. WebAuthn API Layer: Direct interaction with browser WebAuthn APIs
  2. JavaScript Error Handlers: Centralized error processing and categorization
  3. Form Validation Layer: Input validation and constraint checking
  4. UI Status Display Layer: User interface feedback and message presentation

Section sources

  • auth-simple.js
  • auth-advanced.js

WebAuthn API Exception Types

The platform handles five primary WebAuthn API exception types, each requiring specific error handling strategies:

NotAllowedError

Occurs when users cancel the authentication process or when the authenticator is unavailable. This is the most common error type encountered during WebAuthn operations.

InvalidStateError

Indicates authenticator state issues, such as attempting to register an already-registered credential or encountering invalid credential states during authentication.

SecurityError

Signals security-related failures, often caused by network connectivity issues, mixed content warnings, or browser security restrictions.

NotSupportedError

Appears when the browser lacks WebAuthn support or when required features are not available in the current environment.

Network Errors

Captured during server communication failures, including timeouts, connection drops, and HTTP error responses.

Section sources

  • auth-simple.js
  • auth-advanced.js

Simple Interface Error Handling

The simple interface implements streamlined error handling focused on user accessibility and immediate feedback:

sequenceDiagram
participant User
participant UI as Simple UI
participant Handler as Error Handler
participant Status as Status Display
User->>UI : Initiate Registration/Auth
UI->>Handler : Call WebAuthn API
Handler->>Handler : Catch Exception
Handler->>Handler : Categorize Error Type
Handler->>Status : Display User-Friendly Message
Status->>User : Show Error Notification
User->>UI : Retry/Cancel Action
Loading

Diagram sources

  • auth-simple.js
  • status.js

Error Detection and Categorization

The simple interface employs a centralized error handling pattern using try-catch blocks around WebAuthn API calls:

// Example error handling pattern from auth-simple.js
try {
    // WebAuthn API call
    const credential = await create(createOptions);
} catch (error) {
    let errorMessage = error.message;
    if (error.name === 'NotAllowedError') {
        errorMessage = 'User cancelled or authenticator not available';
    } else if (error.name === 'InvalidStateError') {
        errorMessage = 'Authenticator is already registered for this account';
    } else if (error.name === 'SecurityError') {
        errorMessage = 'Security error - check your connection and try again';
    } else if (error.name === 'NotSupportedError') {
        errorMessage = 'WebAuthn is not supported in this browser';
    }
    showStatus('simple', errorMessage, 'error');
}

User Interface Integration

The simple interface utilizes a dedicated status element with ID pattern [tabId]-status for error display:

<div class="status" id="simple-status"></div>

Error messages are automatically positioned relative to the associated progress indicator and include automatic dismissal after 10 seconds.

Section sources

  • auth-simple.js
  • tab.html

Advanced Interface Error Handling

The advanced interface implements sophisticated error handling with detailed diagnostic information and feature compatibility detection:

flowchart TD
A[WebAuthn API Call] --> B{Exception Caught?}
B --> |Yes| C[Categorize Error Type]
B --> |No| D[Continue Processing]
C --> E{Error Type}
E --> |NotAllowedError| F[User Cancellation Message]
E --> |InvalidStateError| G[Authenticator State Issue]
E --> |SecurityError| H[Connection/Security Issue]
E --> |Other| I[Generic Error Message]
F --> J[Collect Feature Issues]
G --> J
H --> J
I --> J
J --> K[Generate Detailed Message]
K --> L[Display to User]
Loading

Diagram sources

  • auth-advanced.js
  • forms.js

Advanced Error Processing

The advanced interface includes feature compatibility detection to provide more informative error messages:

// Feature compatibility detection from auth-advanced.js
const potentialIssues = collectPotentialUnsupportedFeatures(
    publicKey, 
    convertedExtensions, 
    createOptions
);
const detailMessage = potentialIssues.length
    ? ` The authenticator may not support: ${potentialIssues.join(', ')}.`
    : '';

Comprehensive Error Categories

The advanced interface handles additional error scenarios:

  • Feature Compatibility Issues: Identifies unsupported authenticator features
  • Extension Support Problems: Detects missing extension capabilities
  • Algorithm Compatibility: Validates signature algorithm support
  • Configuration Conflicts: Resolves conflicting authenticator settings

Section sources

  • auth-advanced.js
  • forms.js

Form Validation and Error Display

The platform implements comprehensive form validation with real-time error detection and user-friendly error messaging:

classDiagram
class FormValidator {
+validateHexInput(inputId, errorId, minBytes)
+validateUserIdInput()
+validateChallengeInputs()
+validatePrfEvalInputs()
+validateLargeBlobWriteInput()
-formatErrorMessage(errorType, minLength)
-updateErrorDisplay(inputElement, errorElement, isValid)
}
class ErrorDisplay {
+showError(errorId, message)
+hideError(errorId)
+highlightInput(inputId, isValid)
+clearAllErrors()
}
FormValidator --> ErrorDisplay : updates
Loading

Diagram sources

  • forms.js
  • forms.js

Input Validation Patterns

The form validation system implements consistent patterns across different input types:

Hexadecimal Input Validation

Validates hexadecimal format with minimum byte length requirements:

// Pattern from forms.js
export function validateHexInput(inputId, errorId, minBytes = 0) {
    const input = document.getElementById(inputId);
    const error = document.getElementById(errorId);
    if (!input || !error) return true;
    
    const value = input.value.trim();
    if (!value) {
        error.style.display = 'none';
        input.classList.remove('error');
        return true;
    }
    
    // Format validation logic...
}

Challenge Input Validation

Requires minimum 16-byte challenge values for cryptographic security:

// Challenge validation from forms.js
export function validateChallengeInputs() {
    let valid = true;
    const challengeRegInput = document.getElementById('challenge-reg');
    const challengeAuthInput = document.getElementById('challenge-auth');
    
    if (challengeRegInput) valid &= validateHexInput('challenge-reg', 'challenge-reg-error', 16);
    if (challengeAuthInput) valid &= validateHexInput('challenge-auth', 'challenge-auth-error', 16);
    
    return Boolean(valid);
}

Error Message Formatting

Error messages follow a consistent format pattern with specific guidance for each input type:

  • Hex Value Errors: "Invalid hex value (minimum X bytes required)"
  • Challenge Errors: "Invalid hex value (minimum 16 bytes required)"
  • PRF Evaluation Errors: "Invalid hex value (exactly 32 bytes required)"

Section sources

  • forms.js
  • forms.js

Error Message Presentation Patterns

The platform implements sophisticated error message presentation with multiple visual and behavioral patterns:

Status Element Management

The status.js module provides centralized status management with automatic positioning and timing:

// Status display pattern from status.js
export function showStatus(tabId, message, type) {
    const statusEl = resolveStatusElement(tabId);
    if (!statusEl) return;
    
    hideAllStatuses();
    clearStatusTimeout(statusEl);
    
    statusEl.className = `status ${type}`;
    statusEl.textContent = message;
    
    adjustStatusPosition(statusEl, tabId);
    
    requestAnimationFrame(() => {
        statusEl.classList.add('status--visible');
    });
    
    const timeoutId = window.setTimeout(() => {
        hideStatus(statusEl);
    }, STATUS_TIMEOUT_MS);
    statusEl.dataset.statusTimeoutId = String(timeoutId);
}

Visual Error States

Error messages utilize CSS classes for consistent visual presentation:

  • Success Messages: Green highlighting with positive feedback
  • Warning Messages: Orange/yellow highlighting for cautionary information
  • Error Messages: Red highlighting with corrective guidance
  • Information Messages: Blue highlighting for informational content

Dynamic Positioning

Status messages automatically position themselves relative to associated progress indicators:

// Position adjustment from status.js
function adjustStatusPosition(statusEl, tabIdOrElement) {
    let progressEl = null;
    // Resolve progress element...
    
    if (!progressEl || !progressEl.classList.contains('show')) {
        statusEl.style.removeProperty('bottom');
        return;
    }
    
    const progressHeight = Math.ceil(progressEl.getBoundingClientRect().height);
    const spacer = 12;
    statusEl.style.bottom = `calc(var(--global-toast-offset) + ${progressHeight + spacer}px)`;
}

Section sources

  • status.js
  • status.js

Error Recovery Mechanisms

The platform implements several error recovery mechanisms to enhance user experience:

Automatic Error Dismissal

All status messages automatically dismiss after 10 seconds to prevent interface clutter:

const STATUS_TIMEOUT_MS = 10000;

Progress Indicator Coordination

Error messages automatically reposition when progress indicators become visible or hidden:

// Progress coordination from status.js
export function hideProgress(tabIdOrElement) {
    const { progressEl } = resolveProgressElements(tabIdOrElement);
    if (progressEl) {
        progressEl.classList.remove('show');
        
        const statusId = progressEl.id?.endsWith('-progress')
            ? `${progressEl.id.slice(0, -'-progress'.length)}-status`
            : null;
        const statusEl = statusId ? document.getElementById(statusId) : null;
        if (statusEl?.classList.contains('status--visible')) {
            adjustStatusPosition(statusEl, tabIdOrElement);
        }
    }
}

Form Reset Capabilities

Both simple and advanced interfaces provide form reset functionality to recover from invalid states:

  • Simple Interface: Resets username field and clears credentials
  • Advanced Interface: Resets all form fields to default values
  • JSON Editor: Provides reset functionality for complex configurations

Section sources

  • status.js
  • status.js

Best Practices and Guidelines

Error Message Design Principles

  1. Clarity: Use plain language that non-technical users can understand
  2. Actionability: Provide specific guidance on how to resolve issues
  3. Consistency: Maintain uniform error message formats across interfaces
  4. Context: Include relevant technical context when appropriate

Implementation Guidelines

  1. Centralized Error Handling: Use consistent try-catch patterns across modules
  2. User-Friendly Messages: Translate technical error codes into human-readable text
  3. Visual Consistency: Maintain uniform styling for error states
  4. Accessibility: Ensure error messages are accessible to screen readers

Performance Considerations

  1. Minimal DOM Manipulation: Batch DOM updates for better performance
  2. Efficient Timing: Use requestAnimationFrame for smooth animations
  3. Memory Management: Clean up event listeners and timeouts appropriately

Section sources

  • auth-simple.js
  • auth-advanced.js

Troubleshooting Common Issues

Authentication Failures

Issue: Users encounter "User cancelled or authenticator not available" errors Solution: Verify authenticator availability and browser permissions

Issue: "Authenticator is already registered for this account" during registration Solution: Clear existing credentials or use a different account

Form Validation Problems

Issue: Challenge input validation fails Solution: Ensure challenge values meet minimum 16-byte requirement

Issue: PRF evaluation inputs rejected Solution: Verify inputs are exactly 32 bytes in hexadecimal format

Browser Compatibility

Issue: "WebAuthn is not supported in this browser" Solution: Use supported browsers (Edge, Chrome, Safari, Firefox)

Issue: Mixed content warnings causing security errors Solution: Ensure site uses HTTPS protocol

Network Connectivity

Issue: Server communication failures Solution: Check network connectivity and firewall settings

Section sources

  • auth-simple.js
  • forms.js
⚠️ **GitHub.com Fallback** ⚠️