Client Interfaces - FeitianTech/postquantum-webauthn-platform GitHub Wiki
Client Interfaces
Table of Contents
- Introduction
- WebAuthn Ponyfill Library
- Simple Authentication Flow
- Advanced Authentication Flow
- Utility Functions
- Error Handling and Status Management
- Browser Compatibility
- Integration Patterns
- Usage Examples
- Troubleshooting
Introduction
The Post-Quantum WebAuthn Platform provides comprehensive client-side JavaScript interfaces for interacting with WebAuthn APIs. The platform offers two distinct authentication flows: a simple streamlined interface for basic use cases and an advanced interface with extensive customization options for developers and testing scenarios.
The client-side architecture consists of several key components:
- WebAuthn Ponyfill: A cross-browser compatibility layer that normalizes WebAuthn API differences
- Authentication Flows: Two distinct pathways for credential registration and authentication
- Utility Libraries: Helper functions for data conversion, validation, and UI management
- Status Management: Comprehensive feedback and progress indication systems
WebAuthn Ponyfill Library
The webauthn-json.browser-ponyfill.js library serves as the foundational interface for WebAuthn operations, providing essential functions for converting between JSON and binary WebAuthn data formats using base64url encoding.
Core Exported Functions
classDiagram
class WebAuthnPonyfill {
+create(options) Promise~PublicKeyCredential~
+get(options) Promise~PublicKeyCredential~
+parseCreationOptionsFromJSON(requestJSON) CredentialCreationOptions
+parseRequestOptionsFromJSON(requestJSON) CredentialRequestOptions
+supported() boolean
}
class Base64Utils {
+base64urlToBuffer(base64url) ArrayBuffer
+bufferToBase64url(buffer) string
+convert(conversionFn, schema, input) any
}
class SchemaValidation {
+credentialCreationOptions object
+credentialRequestOptions object
+publicKeyCredentialWithAttestation object
+publicKeyCredentialWithAssertion object
}
WebAuthnPonyfill --> Base64Utils : uses
WebAuthnPonyfill --> SchemaValidation : validates
Diagram sources
Function Signatures and Parameters
create(options)
Creates a new credential using the WebAuthn API.
Parameters:
options: CredentialCreationOptions object containing:publicKey: Public key credential parameterssignal: AbortSignal for cancellation
Returns: Promise resolving to PublicKeyCredential with toJSON() method
Section sources
get(options)
Retrieves an existing credential using the WebAuthn API.
Parameters:
options: CredentialRequestOptions object containing:publicKey: Public key assertion parametersmediation: Credential mediation preferencesignal: AbortSignal for cancellation
Returns: Promise resolving to PublicKeyCredential with toJSON() method
Section sources
parseCreationOptionsFromJSON(requestJSON)
Converts JSON-formatted creation options to native WebAuthn format.
Parameters:
requestJSON: JSON object with base64url-encoded binary data
Returns: Native CredentialCreationOptions object with converted binary data
Section sources
parseRequestOptionsFromJSON(requestJSON)
Converts JSON-formatted request options to native WebAuthn format.
Parameters:
requestJSON: JSON object with base64url-encoded binary data
Returns: Native CredentialRequestOptions object with converted binary data
Section sources
supported()
Checks browser WebAuthn API availability.
Returns: boolean indicating WebAuthn support
Section sources
Base64url Encoding Implementation
The ponyfill implements robust base64url encoding/decoding for seamless data conversion:
flowchart TD
A["Base64url String"] --> B["Replace '-' with '+'"]
B --> C["Replace '_' with '/'"]
C --> D["Add Padding '='"]
D --> E["atob() Decode"]
E --> F["Uint8Array Buffer"]
G["Uint8Array Buffer"] --> H["btoa() Encode"]
H --> I["Replace '+' with '-'"]
I --> J["Replace '/' with '_'"]
J --> K["Remove '=' Padding"]
K --> L["Base64url String"]
Diagram sources
Section sources
Simple Authentication Flow
The simple authentication flow provides an intuitive interface for basic WebAuthn operations, ideal for production applications requiring straightforward registration and authentication experiences.
Simple Registration Process
sequenceDiagram
participant User as User
participant UI as Simple UI
participant Backend as Server Backend
participant Authenticator as Authenticator Device
User->>UI : Enter email & click Register
UI->>Backend : POST /api/register/begin
Backend-->>UI : Registration options
UI->>UI : Parse JSON options
UI->>Authenticator : navigator.credentials.create()
Authenticator-->>UI : Credential response
UI->>Backend : POST /api/register/complete
Backend-->>UI : Registration result
UI->>User : Show success/error message
Diagram sources
Simple Authentication Process
sequenceDiagram
participant User as User
participant UI as Simple UI
participant Backend as Server Backend
participant Authenticator as Authenticator Device
User->>UI : Enter email & click Authenticate
UI->>UI : Load stored credentials
UI->>Backend : POST /api/authenticate/begin
Backend-->>UI : Authentication options
UI->>UI : Parse JSON options
UI->>Authenticator : navigator.credentials.get()
Authenticator-->>UI : Assertion response
UI->>Backend : POST /api/authenticate/complete
Backend-->>UI : Authentication result
UI->>User : Show success/error message
Diagram sources
Simple Flow Functions
simpleRegister()
Handles the complete registration process for a user.
Key Features:
- Email validation and input sanitization
- Automatic credential option parsing
- Extension handling for advanced features
- Session state management
- Progress indication and error handling
Error Handling:
- NotAllowedError: User cancellation or unavailable authenticator
- InvalidStateError: Authenticator already registered
- SecurityError: Connection/security issues
- NotSupportedError: Browser lacks WebAuthn support
Section sources
simpleAuthenticate()
Manages the authentication process for existing users.
Key Features:
- Stored credential retrieval from local storage
- Credential preparation for server submission
- Sign count validation and updates
- User feedback and progress tracking
Error Handling:
- NotAllowedError: User cancellation or no authenticator
- InvalidStateError: Authenticator error or invalid credential
- SecurityError: Connection/security issues
- NotSupportedError: Browser lacks WebAuthn support
Section sources
Advanced Authentication Flow
The advanced authentication flow provides comprehensive control over WebAuthn operations, enabling detailed customization of credential options and extensive debugging capabilities.
Advanced Registration Process
flowchart TD
A["Parse JSON Editor"] --> B["Validate Structure"]
B --> C["Apply Extensions"]
C --> D["Enforce Hints"]
D --> E["Generate Options"]
E --> F["Call navigator.credentials.create()"]
F --> G["Process Response"]
G --> H["Send to Server"]
H --> I["Store Credentials"]
I --> J["Show Results"]
Diagram sources
Advanced Authentication Process
flowchart TD
A["Parse JSON Editor"] --> B["Validate Structure"]
B --> C["Load Stored Credentials"]
C --> D["Prepare Request Payload"]
D --> E["Call navigator.credentials.get()"]
E --> F["Process Assertion"]
F --> G["Send to Server"]
G --> H["Update Sign Count"]
H --> I["Refresh UI"]
Diagram sources
Advanced Flow Functions
advancedRegister()
Provides comprehensive registration with extensive customization options.
Advanced Features:
- JSON editor integration for custom credential options
- Extension support (PRF, largeBlob, credential protection)
- Authenticator attachment preferences
- Fake credential generation
- Warning detection and reporting
Error Detection Capabilities:
- Unsupported authenticator features identification
- Configuration validation
- Feature compatibility checking
Section sources
advancedAuthenticate()
Offers detailed authentication with credential filtering and extension support.
Advanced Features:
- Stored credential management
- Allow credential filtering
- Extension evaluation
- Large blob support
- PRF extension support
Section sources
Extension Support
The advanced flow supports various WebAuthn extensions:
| Extension | Purpose | Support Level |
|---|---|---|
| PRF | Private Key Protection | Full support with evaluation |
| Large Blob | Persistent storage | Full support with read/write |
| Credential Protection | Enhanced security | Full support with policies |
| Min PIN Length | Authentication requirements | Basic support |
Section sources
Utility Functions
The platform provides extensive utility functions for data manipulation, validation, and format conversion.
Binary Data Utilities
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
+normalizeClientExtensionResults(results) object
+jsonValueToUint8Array(jsonValue) Uint8Array
}
class FormatConversion {
+convertFormat(value, fromFormat, toFormat) string
+currentFormatToJsonFormat(value) object
+getCurrentBinaryFormat() string
+normalizeToHex(value) string
}
BinaryUtils --> FormatConversion : uses
Diagram sources
Validation Functions
validateHexInput(inputId, errorId, minBytes)
Validates hexadecimal input with configurable minimum byte requirements.
Parameters:
inputId: DOM element identifiererrorId: Error message element identifierminBytes: Minimum required byte length
Returns: boolean indicating validation success
Section sources
randomizeChallenge(type)
Generates cryptographically secure random challenges for registration/authentication.
Parameters:
type: 'reg' or 'auth' to indicate operation type
Section sources
Hint System
The hint system enables intelligent authenticator selection based on user preferences:
flowchart TD
A["User Selection"] --> B["Normalize Hints"]
B --> C["Derive Attachments"]
C --> D["Filter Credentials"]
D --> E["Update UI"]
F["Stored Credentials"] --> G["Check Capabilities"]
G --> H["Enable/Disable Options"]
Diagram sources
Section sources
Error Handling and Status Management
The platform implements comprehensive error handling and user feedback mechanisms.
Status Management System
classDiagram
class StatusManager {
+showStatus(tabId, message, type) void
+hideStatus(tabIdOrElement) void
+showProgress(tabId, message) void
+hideProgress(tabIdOrElement) void
+dismissAllTransientMessages() void
}
class StatusTypes {
<<enumeration>>
SUCCESS
ERROR
WARNING
INFO
}
StatusManager --> StatusTypes : uses
Diagram sources
Error Categories and Handling
| Error Type | Description | Handling Strategy |
|---|---|---|
| NotAllowedError | User cancellation or unavailable authenticator | Informative user message |
| InvalidStateError | Authenticator state issues | Retry suggestion |
| SecurityError | Connection or security violations | Connection check recommendation |
| NotSupportedError | Browser lacks WebAuthn support | Browser compatibility notice |
| ValidationError | Invalid input or configuration | Form validation feedback |
Section sources
Browser Compatibility
The WebAuthn ponyfill ensures broad browser compatibility through feature detection and graceful degradation.
Feature Detection
flowchart TD
A["Browser Support Check"] --> B["navigator.credentials"]
B --> C["navigator.credentials.create"]
C --> D["navigator.credentials.get"]
D --> E["window.PublicKeyCredential"]
E --> F["All Features Available?"]
F --> |Yes| G["Full WebAuthn Support"]
F --> |No| H["Limited Support"]
Diagram sources
Supported Browsers
The platform supports modern browsers with WebAuthn capabilities:
- Chrome: Version 67+
- Firefox: Version 60+
- Safari: Version 14+
- Edge: Version 79+
Section sources
Integration Patterns
Frontend-Backend Communication
The client-side interfaces communicate with backend APIs through standardized JSON-RPC patterns:
sequenceDiagram
participant Client as Client Script
participant Backend as Server API
participant Authenticator as WebAuthn API
Client->>Backend : Begin Request (JSON)
Backend-->>Client : Options Response (JSON)
Client->>Authenticator : WebAuthn Operation
Authenticator-->>Client : Binary Response
Client->>Client : Convert to JSON
Client->>Backend : Complete Request (JSON)
Backend-->>Client : Result Response (JSON)
Module Exports and Global Access
The main entry point exports all public functions for global access:
Section sources
Usage Examples
Basic Registration Example
// Simple registration flow
async function registerUser(email) {
try {
// Call simple registration function
await simpleRegister();
// Check registration status
const status = document.getElementById('simple-status');
if (status.classList.contains('success')) {
console.log('Registration successful!');
}
} catch (error) {
console.error('Registration failed:', error.message);
}
}
Advanced Registration Example
// Advanced registration with custom options
async function registerAdvanced() {
try {
// Set up custom credential options
const options = {
publicKey: {
rp: { name: 'My Application', id: 'example.com' },
user: {
id: 'user123',
name: 'John Doe',
displayName: 'John'
},
challenge: 'random-challenge-string',
pubKeyCredParams: [{ alg: -7, type: 'public-key' }],
authenticatorSelection: {
authenticatorAttachment: 'platform',
requireResidentKey: false,
userVerification: 'preferred'
},
extensions: {
credProps: true,
largeBlob: { support: true }
}
}
};
// Call advanced registration
await advancedRegister();
} catch (error) {
console.error('Advanced registration failed:', error.message);
}
}
Authentication Example
// Simple authentication flow
async function authenticateUser(email) {
try {
// Set email and trigger authentication
document.getElementById('simple-email').value = email;
await simpleAuthenticate();
// Handle success
const status = document.getElementById('simple-status');
if (status.classList.contains('success')) {
console.log('Authentication successful!');
}
} catch (error) {
console.error('Authentication failed:', error.message);
}
}
Troubleshooting
Common Issues and Solutions
WebAuthn Not Supported
Symptoms: "WebAuthn is not supported in this browser" error Solution: Ensure browser meets minimum requirements (Chrome 67+, Firefox 60+, Safari 14+, Edge 79+)
Authenticator Not Found
Symptoms: "User cancelled or authenticator not available" error Solutions:
- Verify authenticator hardware is connected and powered
- Check authenticator compatibility with browser
- Try different authentication method (PIN vs biometric)
Challenge Validation Failures
Symptoms: "Invalid challenge" errors Solutions:
- Ensure challenge is properly encoded in required format
- Verify challenge meets minimum length requirements (16+ bytes)
- Check for encoding/decoding issues in custom implementations
Extension Compatibility
Symptoms: "Extension not supported" errors Solutions:
- Verify authenticator supports requested extensions
- Check extension configuration syntax
- Review authenticator capability documentation
Debug Information
The platform provides comprehensive debug information through the debug utilities:
- Registration Debug: Shows credential creation details and algorithm information
- Authentication Debug: Displays assertion details and verification results
- Extension Debug: Provides extension evaluation and capability information
Section sources
Performance Considerations
- Network Latency: WebAuthn operations depend on server response times
- Authentication Speed: Biometric authentication typically faster than PIN-based
- Storage Efficiency: Local credential storage optimized for minimal footprint
Security Best Practices
- Challenge Generation: Use cryptographically secure random generators
- Timeout Configuration: Set appropriate timeouts for user experience balance
- Error Handling: Provide meaningful error messages without exposing sensitive information
- HTTPS Requirement: Ensure all WebAuthn operations occur over secure connections