Shared Client Utilities - FeitianTech/postquantum-webauthn-platform GitHub Wiki
Shared Client Utilities
Table of Contents
- Introduction
- WebAuthn JSON Browser Ponyfill
- Binary Utilities
- State Management System
- UI Utilities
- Status and Loading Management
- Navigation System
- Local Storage Management
- Integration Examples
- Error Handling and Browser Compatibility
Introduction
The PostQuantum WebAuthn Platform provides a comprehensive suite of shared JavaScript utilities designed to bridge the gap between the native WebAuthn API and JSON-based frontend logic. These utilities handle the complex transformations required for authenticator data, client data, and attestation statements, while also providing robust state management, UI enhancements, and cross-browser compatibility solutions.
The shared utilities are organized into several key modules that work together to provide a seamless WebAuthn experience across different browsers and authentication scenarios. The architecture emphasizes modularity, reusability, and maintainability while ensuring optimal performance and user experience.
WebAuthn JSON Browser Ponyfill
The webauthn-json.browser-ponyfill.js serves as a critical bridge between the native WebAuthn API and JSON-based frontend applications. It provides essential encoding and decoding capabilities for CBOR data via base64url transformation, enabling seamless communication between the browser's WebAuthn implementation and the platform's backend systems.
Core Encoding/Decoding Functions
The ponyfill implements fundamental base64url conversion utilities that handle the transformation between string representations and binary data:
flowchart TD
A["Base64URL String"] --> B["base64urlToBuffer()"]
B --> C["ArrayBuffer"]
C --> D["Uint8Array View"]
E["ArrayBuffer"] --> F["bufferToBase64url()"]
F --> G["Base64URL String"]
H["JSON Request"] --> I["parseCreationOptionsFromJSON()"]
I --> J["Convert Challenge & Credentials"]
J --> K["Native WebAuthn Options"]
L["WebAuthn Response"] --> M["createResponseToJSON()"]
M --> N["JSON Response"]
Diagram sources
Schema-Based Transformation System
The ponyfill employs a sophisticated schema-based transformation system that ensures data integrity and type safety during the conversion process. The system supports various data types and provides flexible conversion options:
| Schema Type | Purpose | Usage Pattern |
|---|---|---|
copyValue |
Direct copying without transformation | Simple data preservation |
convertValue |
Apply conversion function | Base64url encoding/decoding |
| Array Schema | Process collections | Credential descriptors |
| Object Schema | Transform complex structures | Public key credentials |
Authentication Flow Integration
The ponyfill integrates seamlessly with the WebAuthn authentication flow, providing automatic JSON serialization for both registration and authentication operations:
sequenceDiagram
participant Client as "Client Application"
participant Ponyfill as "WebAuthn Ponyfill"
participant Browser as "Browser WebAuthn"
participant Server as "Backend Server"
Client->>Ponyfill : parseCreationOptionsFromJSON()
Ponyfill->>Ponyfill : convert(base64urlToBuffer, schema, options)
Ponyfill-->>Client : Native WebAuthn Options
Client->>Browser : navigator.credentials.create()
Browser-->>Client : PublicKeyCredential
Client->>Ponyfill : createResponseToJSON()
Ponyfill->>Ponyfill : convert(bufferToBase64url, schema, credential)
Ponyfill-->>Client : JSON Registration Response
Client->>Server : Submit JSON Response
Diagram sources
Section sources
Binary Utilities
The binary-utils.js module provides comprehensive tools for array buffer manipulation, hex/base64 conversions, and data format transformations. This utility library serves as the foundation for handling binary data throughout the WebAuthn authentication process.
Core Conversion Functions
The binary utilities offer bidirectional conversion capabilities between various data formats commonly encountered in WebAuthn operations:
classDiagram
class BinaryUtils {
+hexToBase64Url(hexString) string
+base64UrlToHex(base64url) string
+base64ToBase64Url(base64) string
+hexToBase64(hexString) string
+base64ToHex(base64) string
+bytesToHex(bytes) string
+hexToUint8Array(hex) Uint8Array
+base64ToUint8Array(base64) Uint8Array
+base64UrlToUint8Array(base64url) Uint8Array
+arrayBufferToHex(buffer) string
+jsonValueToUint8Array(jsonValue) Uint8Array
+normalizeClientExtensionResults(results) object
}
class FormatConverter {
+convertFormat(value, fromFormat, toFormat) string
+currentFormatToJsonFormat(value) object
+currentFormatToBase64Url(value) string
+normalizeToHex(value) string
}
BinaryUtils --> FormatConverter : "uses"
Diagram sources
Advanced Extension Processing
The binary utilities include specialized functions for handling WebAuthn extensions, particularly for PRF (Private Key Reduction Function) and Large Blob extensions:
| Extension Type | Processing Function | Key Features |
|---|---|---|
| PRF | convertPrfExtension() |
Evaluation, credential-specific processing |
| Large Blob | convertLargeBlobExtension() |
Write operations, support detection |
| Credential Protection | convertCredProtectValue() |
Policy normalization, validation |
Data Validation and Sanitization
The binary utilities implement comprehensive validation and sanitization mechanisms to ensure data integrity:
flowchart TD
A["Input Data"] --> B{"Valid Hex?"}
B --> |Yes| C["Normalize Hex"]
B --> |No| D{"Valid Base64?"}
D --> |Yes| E["Convert to Hex"]
D --> |No| F["Return Empty"]
C --> G["Validate Length"]
E --> G
G --> H{"Even Length?"}
H --> |Yes| I["Return Normalized"]
H --> |No| F
J["JSON Value"] --> K["Detect Format"]
K --> L{"Format Type"}
L --> |"hex"| M["Direct Conversion"]
L --> |"b64"| N["Base64 to Hex"]
L --> |"b64u"| O["Base64Url to Hex"]
L --> |"js"| P["JavaScript to Hex"]
Diagram sources
Section sources
State Management System
The state management system (state.js) provides centralized control over user session context and credential artifacts. This system maintains application state across different authentication flows and user interactions.
State Architecture
The state system follows a singleton pattern with carefully structured properties for different aspects of the authentication process:
classDiagram
class AppState {
+string currentSubTab
+Array storedCredentials
+string currentJsonMode
+object currentJsonData
+number lastFakeCredLength
+Array generatedExcludeCredentials
+Array generatedAllowCredentials
+TextDecoder utf8Decoder
}
class SubTabManager {
+switchSubTab(subTab) void
+getCurrentSubTab() string
}
class CredentialManager {
+addCredential(credential) void
+removeCredential(id) void
+getStoredCredentials() Array
}
AppState --> SubTabManager : "manages"
AppState --> CredentialManager : "tracks"
Diagram sources
Session Context Management
The state system maintains session context through several key mechanisms:
| State Property | Purpose | Scope |
|---|---|---|
currentSubTab |
Active sub-navigation tab | UI state |
storedCredentials |
Local credential cache | Persistence |
utf8Decoder |
Text decoding capability | Browser compatibility |
Section sources
UI Utilities
The UI utilities (ui.js) provide comprehensive functionality for managing modal dialogs, status messages, loading states, and responsive navigation. These utilities ensure consistent user experience across different screen sizes and interaction patterns.
Modal Management System
The modal system implements a sophisticated z-index management and stacking mechanism:
flowchart TD
A["Open Modal Request"] --> B["Ensure Base Z-Index"]
B --> C["Calculate Highest Z-Index"]
C --> D["Apply Stack Increment"]
D --> E["Set Modal Position"]
E --> F["Add Open Class"]
F --> G["Update Global Scroll Lock"]
H["Close Modal Request"] --> I["Remove Open Class"]
I --> J["Reset Z-Index"]
J --> K["Finalize Close"]
K --> G
Diagram sources
Sticky Header Implementation
The sticky header system provides dynamic header behavior with smooth transitions and responsive design:
classDiagram
class StickyHeaderController {
+HTMLElement header
+HTMLElement miniHeader
+HTMLElement miniInner
+refreshGeometry() void
+evaluate() void
+reset() void
+destroy() void
}
class GeometryCalculator {
+measureHeaderBottom() number
+measureMiniHeader() void
+calculateRevealRange() number
}
class ProgressEvaluator {
+getScrollPosition() number
+evaluateProgress() void
+applyProgress(value) void
}
StickyHeaderController --> GeometryCalculator : "uses"
StickyHeaderController --> ProgressEvaluator : "uses"
Diagram sources
Responsive Design Features
The UI utilities implement comprehensive responsive design patterns:
| Feature | Implementation | Purpose |
|---|---|---|
| Mobile Breakpoint | HEADER_MOBILE_BREAKPOINT = 900px |
Responsive navigation |
| Touch Interaction | Gesture recognition | Mobile usability |
| Accessibility | ARIA attributes | Screen reader support |
| Animation | CSS transitions | Smooth user experience |
Section sources
Status and Loading Management
The status and loading management system provides unified control over user feedback mechanisms, including status messages, progress indicators, and loading animations.
Status Message System
The status system implements a sophisticated message queue with automatic timing and positioning:
sequenceDiagram
participant User as "User Action"
participant Status as "Status Manager"
participant UI as "UI Element"
participant Timer as "Timeout Handler"
User->>Status : showStatus(tabId, message, type)
Status->>Status : hideAllStatuses()
Status->>UI : Set message content
Status->>UI : Add status class
Status->>UI : Show with animation
Status->>Timer : Schedule auto-hide
Timer->>Status : hideStatus()
Status->>UI : Remove animation class
Status->>UI : Clear message
Diagram sources
Progress Tracking System
The progress system provides real-time feedback for long-running operations:
flowchart TD
A["Start Operation"] --> B["Initialize Progress"]
B --> C["Update Progress Value"]
C --> D{"Progress Complete?"}
D --> |No| E["Animate Step Forward"]
E --> F["Render Progress"]
F --> C
D --> |Yes| G["Stop Animation"]
G --> H["Complete Operation"]
I["Show Progress"] --> J["Adjust Position"]
J --> K["Add Show Class"]
L["Hide Progress"] --> M["Remove Show Class"]
M --> N["Adjust Status Position"]
Diagram sources
Loader Implementation
The loader system provides comprehensive application loading feedback:
| Component | Purpose | Features |
|---|---|---|
| Progress Bar | Visual progress indication | Animated, customizable |
| Status Messages | Operation feedback | Dynamic content updates |
| Percentage Display | Numeric progress | Real-time calculations |
| Hidden State | Clean completion | Graceful fade-out |
Section sources
Navigation System
The navigation system (navigation.js) manages tab switching, sub-tab navigation, and mobile-responsive menu behavior. It provides seamless transitions between different sections of the application.
Tab Management Architecture
The navigation system implements a modular tab management system:
classDiagram
class NavigationManager {
+switchTab(tab, options) void
+switchSubTab(subTab) void
+initializeNavigationMenu() object
+toggleSection(sectionId, event) void
}
class MenuController {
+open() void
+close(options) void
+toggle() void
-updateExpanded(state) void
}
class StateManager {
+currentSubTab string
+preserveScroll boolean
+preserveMessages boolean
}
NavigationManager --> MenuController : "uses"
NavigationManager --> StateManager : "manages"
Diagram sources
Mobile Responsiveness
The navigation system adapts to different screen sizes with intelligent breakpoint detection:
flowchart TD
A["Viewport Change"] --> B{"Width ≤ 900px?"}
B --> |Yes| C["Enable Mobile Mode"]
B --> |No| D["Enable Desktop Mode"]
C --> E["Show Hamburger Menu"]
C --> F["Collapse Navigation"]
C --> G["Touch Gestures"]
D --> H["Full Navigation Bar"]
D --> I["Hover Effects"]
D --> J["Keyboard Navigation"]
K["User Interaction"] --> L{"Mobile Mode?"}
L --> |Yes| M["Touch Handlers"]
L --> |No| N["Mouse Handlers"]
Diagram sources
Event Handling System
The navigation system implements comprehensive event handling for different interaction patterns:
| Event Type | Handler | Purpose |
|---|---|---|
| Click | handleToggleClick() |
Menu toggle activation |
| Resize | handleResize() |
Responsive adaptation |
| Keyboard | handleKeyDown() |
Accessibility support |
| Overlay | handleOverlayClick() |
Outside click dismissal |
Section sources
Local Storage Management
The local storage management system (local-storage.js) provides sophisticated credential storage, synchronization, and data persistence capabilities. It handles both simple and advanced credential types with intelligent data compression and server synchronization.
Credential Storage Architecture
The storage system implements a unified approach to credential management:
classDiagram
class StorageManager {
+getAllStoredCredentialsInOrder() Array
+saveAdvancedCredential(credential) boolean
+ensureAdvancedCredentialArtifactsSynced() Promise
-persistUnifiedCredentialRecords(records) boolean
-partitionRecords(records) object
}
class ArtifactSynchronizer {
+synchroniseAdvancedCredentialArtifacts() Promise
-uploadCredentialArtifact(id, data) Promise
-fetchCredentialArtifact(id) Promise
}
class DataSanitizer {
+sanitiseRegistrationDetailSnapshot(snapshot) object
+sanitiseAttestationObjectForSnapshot(obj) object
+truncateString(value, maxLength) string
}
StorageManager --> ArtifactSynchronizer : "uses"
StorageManager --> DataSanitizer : "uses"
Diagram sources
Data Synchronization Strategy
The system implements intelligent synchronization between local storage and server artifacts:
flowchart TD
A["Credential Record"] --> B{"Has Heavy Data?"}
B --> |Yes| C["Check Server Artifact"]
B --> |No| D["Store Locally"]
C --> E{"Needs Upload?"}
E --> |Yes| F["Upload to Server"]
E --> |No| G["Use Local Summary"]
F --> H["Update HasServerArtifact"]
H --> I["Store Summary Locally"]
J["Server Sync Request"] --> K["Fetch All Records"]
K --> L["Compare Versions"]
L --> M["Upload Changed Records"]
M --> N["Update Local Records"]
O["Legacy Migration"] --> P["Read Legacy Storage"]
P --> Q["Convert Formats"]
Q --> R["Write Unified Storage"]
Diagram sources
Data Sanitization and Compression
The storage system implements comprehensive data sanitization to optimize storage and transmission:
| Sanitization Level | Purpose | Applied To |
|---|---|---|
| Aggressive | Remove sensitive data | Attestation objects |
| Heavy | Reduce size impact | Certificate chains |
| Moderate | Preserve functionality | Extension data |
| Light | Minimal processing | Basic metadata |
Section sources
Integration Examples
Challenge Encoding Example
Here's how to encode a challenge object into a buffer using the binary utilities:
// Example challenge encoding process
const challengeHex = "4a8c5e7f1b3d9e6a2c8f0d5b7e9a1c3f";
const challengeBuffer = hexToUint8Array(challengeHex);
const challengeBase64Url = bufferToBase64url(challengeBuffer);
Registration Response Decoding Example
Example of decoding a registration response using the webauthn-json ponyfill:
// Example registration response processing
const registrationResponse = await navigator.credentials.create({
publicKey: creationOptions
});
// Automatic JSON serialization
const jsonResponse = registrationResponse.toJSON();
Error Handling Patterns
The utilities implement comprehensive error handling patterns:
// Example error handling in authentication flow
try {
const response = await get(options);
const jsonResult = response.toJSON();
// Process successful response
} catch (error) {
// Handle WebAuthn errors
showStatus('advanced', `Authentication failed: ${error.message}`, 'error');
}
Error Handling and Browser Compatibility
Browser Support Detection
The webauthn-json ponyfill includes comprehensive browser compatibility checking:
// Browser support validation
function supported() {
return !!(navigator.credentials &&
navigator.credentials.create &&
navigator.credentials.get &&
window.PublicKeyCredential);
}
Fallback Mechanisms
The system implements graceful degradation for unsupported browsers:
flowchart TD
A["WebAuthn Request"] --> B{"Browser Supports WebAuthn?"}
B --> |Yes| C["Use Native API"]
B --> |No| D["Show Compatibility Warning"]
C --> E{"Operation Successful?"}
E --> |Yes| F["Return Results"]
E --> |No| G["Handle Error"]
D --> H["Provide Alternative Method"]
H --> I["Manual Form Submission"]
Error Recovery Strategies
The utilities implement multiple error recovery strategies:
| Error Type | Recovery Strategy | Implementation |
|---|---|---|
| Network Errors | Retry with exponential backoff | Promise-based retry logic |
| Data Corruption | Fallback to cached data | Local storage validation |
| Browser Incompatibility | Polyfill detection | Feature detection patterns |
| User Interruption | State restoration | Session persistence |
Section sources