Skip to content

Client Interfaces

Rain Zhang edited this page Nov 6, 2025 · 2 revisions

Client Interfaces

Table of Contents

  1. Introduction
  2. WebAuthn Ponyfill Library
  3. Simple Authentication Flow
  4. Advanced Authentication Flow
  5. Utility Functions
  6. Error Handling and Status Management
  7. Browser Compatibility
  8. Integration Patterns
  9. Usage Examples
  10. 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
Loading

Diagram sources

  • webauthn-json.browser-ponyfill.js

Function Signatures and Parameters

create(options)

Creates a new credential using the WebAuthn API.

Parameters:

  • options: CredentialCreationOptions object containing:
    • publicKey: Public key credential parameters
    • signal: AbortSignal for cancellation

Returns: Promise resolving to PublicKeyCredential with toJSON() method

Section sources

  • webauthn-json.browser-ponyfill.js

get(options)

Retrieves an existing credential using the WebAuthn API.

Parameters:

  • options: CredentialRequestOptions object containing:
    • publicKey: Public key assertion parameters
    • mediation: Credential mediation preference
    • signal: AbortSignal for cancellation

Returns: Promise resolving to PublicKeyCredential with toJSON() method

Section sources

  • webauthn-json.browser-ponyfill.js

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

  • webauthn-json.browser-ponyfill.js

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

  • webauthn-json.browser-ponyfill.js

supported()

Checks browser WebAuthn API availability.

Returns: boolean indicating WebAuthn support

Section sources

  • webauthn-json.browser-ponyfill.js

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"]
Loading

Diagram sources

  • webauthn-json.browser-ponyfill.js

Section sources

  • webauthn-json.browser-ponyfill.js

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
Loading

Diagram sources

  • auth-simple.js

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
Loading

Diagram sources

  • auth-simple.js

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

  • auth-simple.js

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

  • auth-simple.js

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"]
Loading

Diagram sources

  • auth-advanced.js

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"]
Loading

Diagram sources

  • auth-advanced.js

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

  • auth-advanced.js

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

  • auth-advanced.js

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

  • auth-advanced.js

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
Loading

Diagram sources

  • binary-utils.js

Validation Functions

validateHexInput(inputId, errorId, minBytes)

Validates hexadecimal input with configurable minimum byte requirements.

Parameters:

  • inputId: DOM element identifier
  • errorId: Error message element identifier
  • minBytes: Minimum required byte length

Returns: boolean indicating validation success

Section sources

  • forms.js

randomizeChallenge(type)

Generates cryptographically secure random challenges for registration/authentication.

Parameters:

  • type: 'reg' or 'auth' to indicate operation type

Section sources

  • forms.js

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"]
Loading

Diagram sources

  • hints.js

Section sources

  • hints.js

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
Loading

Diagram sources

  • status.js

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

  • status.js

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"]
Loading

Diagram sources

  • webauthn-json.browser-ponyfill.js

Supported Browsers

The platform supports modern browsers with WebAuthn capabilities:

  • Chrome: Version 67+
  • Firefox: Version 60+
  • Safari: Version 14+
  • Edge: Version 79+

Section sources

  • webauthn-json.browser-ponyfill.js

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)
Loading

Module Exports and Global Access

The main entry point exports all public functions for global access:

Section sources

  • main.js

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

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

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

Post-Quantum WebAuthn Platform

Getting Started

Architectural Foundations

Cryptography & Security

Authentication Platform

Core Protocol

Flows & Interfaces

Authenticator Capabilities

Server Platform

Frontend Platform

Architecture

Interaction & Utilities

Metadata Service (MDS)

Storage & Data Management

Data Models & Encoding

API Reference

Cross-Platform & HID

Operations & Troubleshooting

Glossary & References

Clone this wiki locally