0
# Helper Functions and Utilities
1
2
Feature detection functions and data conversion utilities that support WebAuthn operations. Includes browser capability checks and Base64URL encoding/decoding helpers essential for WebAuthn implementations.
3
4
## Capabilities
5
6
### WebAuthn Feature Detection
7
8
Functions to detect WebAuthn support and capabilities across different browsers and environments.
9
10
#### Browser WebAuthn Support
11
12
Determines if the browser supports WebAuthn at all.
13
14
```typescript { .api }
15
/**
16
* Determine if the browser is capable of WebAuthn
17
* @returns true if WebAuthn is supported, false otherwise
18
*/
19
function browserSupportsWebAuthn(): boolean;
20
```
21
22
**Usage Examples:**
23
24
```typescript
25
import { browserSupportsWebAuthn } from '@simplewebauthn/browser';
26
27
// Check before attempting WebAuthn operations
28
if (!browserSupportsWebAuthn()) {
29
// Show fallback UI or error message
30
document.getElementById('webauthn-ui').style.display = 'none';
31
document.getElementById('password-ui').style.display = 'block';
32
return;
33
}
34
35
// Safe to proceed with WebAuthn
36
startRegistration({ optionsJSON });
37
```
38
39
#### Platform Authenticator Availability
40
41
Checks if a platform authenticator (like Touch ID, Windows Hello, or fingerprint scanner) is available.
42
43
```typescript { .api }
44
/**
45
* Determine whether the browser can communicate with a built-in authenticator,
46
* like Touch ID, Android fingerprint scanner, or Windows Hello
47
* @returns Promise resolving to true if platform authenticator is available
48
*/
49
function platformAuthenticatorIsAvailable(): Promise<boolean>;
50
```
51
52
**Usage Examples:**
53
54
```typescript
55
import { platformAuthenticatorIsAvailable } from '@simplewebauthn/browser';
56
57
// Check platform authenticator availability
58
const hasPlatformAuth = await platformAuthenticatorIsAvailable();
59
60
if (hasPlatformAuth) {
61
// Show biometric options in UI
62
document.getElementById('biometric-button').style.display = 'block';
63
document.getElementById('biometric-hint').textContent =
64
'Use your fingerprint, face, or PIN to sign in';
65
} else {
66
// Show external authenticator options
67
document.getElementById('security-key-button').style.display = 'block';
68
document.getElementById('security-key-hint').textContent =
69
'Use your security key to sign in';
70
}
71
```
72
73
#### WebAuthn Autofill Support
74
75
Detects if the browser supports conditional UI (WebAuthn autofill) where credentials can appear in password autofill dropdowns.
76
77
```typescript { .api }
78
/**
79
* Determine if the browser supports conditional UI, so that WebAuthn credentials
80
* can be shown to the user in the browser's typical password autofill popup
81
* @returns Promise resolving to true if WebAuthn autofill is supported
82
*/
83
function browserSupportsWebAuthnAutofill(): Promise<boolean>;
84
```
85
86
**Usage Examples:**
87
88
```typescript
89
import {
90
browserSupportsWebAuthnAutofill,
91
startAuthentication
92
} from '@simplewebauthn/browser';
93
94
// Enable autofill if supported
95
const supportsAutofill = await browserSupportsWebAuthnAutofill();
96
97
if (supportsAutofill) {
98
// Enable conditional UI for seamless authentication
99
startAuthentication({
100
optionsJSON: authOptions,
101
useBrowserAutofill: true
102
});
103
104
// Update UI to indicate autofill is available
105
document.getElementById('login-hint').textContent =
106
'Start typing or use autofill to sign in with a passkey';
107
} else {
108
// Use traditional WebAuthn flow
109
startAuthentication({
110
optionsJSON: authOptions
111
});
112
}
113
```
114
115
### Data Conversion Utilities
116
117
Essential utilities for converting between ArrayBuffer and Base64URL string formats required by WebAuthn operations.
118
119
#### Base64URL to ArrayBuffer
120
121
Converts Base64URL-encoded strings to ArrayBuffer, typically used for credential IDs and challenges.
122
123
```typescript { .api }
124
/**
125
* Convert from a Base64URL-encoded string to an Array Buffer.
126
* Best used when converting a credential ID from a JSON string to an ArrayBuffer,
127
* like in allowCredentials or excludeCredentials
128
* @param base64URLString - Base64URL-encoded string to convert
129
* @returns ArrayBuffer representation of the input string
130
*/
131
function base64URLStringToBuffer(base64URLString: string): ArrayBuffer;
132
```
133
134
**Usage Examples:**
135
136
```typescript
137
import { base64URLStringToBuffer } from '@simplewebauthn/browser';
138
139
// Convert credential ID for excludeCredentials
140
const credentialId = 'dGVzdC1jcmVkZW50aWFsLWlk';
141
const buffer = base64URLStringToBuffer(credentialId);
142
143
// Use in WebAuthn options
144
const registrationOptions = {
145
// ... other options
146
excludeCredentials: [{
147
id: buffer,
148
type: 'public-key',
149
transports: ['internal']
150
}]
151
};
152
153
// Convert challenge from server
154
const serverChallenge = 'Y2hhbGxlbmdl';
155
const challengeBuffer = base64URLStringToBuffer(serverChallenge);
156
```
157
158
#### ArrayBuffer to Base64URL
159
160
Converts ArrayBuffer to Base64URL-encoded string, typically used for preparing credential responses for transmission to server.
161
162
```typescript { .api }
163
/**
164
* Convert the given array buffer into a Base64URL-encoded string.
165
* Ideal for converting various credential response ArrayBuffers to string
166
* for sending back to the server as JSON
167
* @param buffer - ArrayBuffer to convert
168
* @returns Base64URL-encoded string representation
169
*/
170
function bufferToBase64URLString(buffer: ArrayBuffer): string;
171
```
172
173
**Usage Examples:**
174
175
```typescript
176
import { bufferToBase64URLString } from '@simplewebauthn/browser';
177
178
// This is typically done internally by startRegistration/startAuthentication,
179
// but can be used for custom implementations
180
181
// Convert raw credential response data
182
const rawId = new Uint8Array([116, 101, 115, 116]); // example bytes
183
const credentialId = bufferToBase64URLString(rawId.buffer);
184
185
// Convert authenticator data
186
const authData = new Uint8Array(165); // example authenticator data
187
const authDataString = bufferToBase64URLString(authData.buffer);
188
189
// Build custom response object
190
const customResponse = {
191
id: credentialId,
192
rawId: credentialId,
193
response: {
194
clientDataJSON: bufferToBase64URLString(clientDataBuffer),
195
attestationObject: bufferToBase64URLString(attestationBuffer)
196
}
197
};
198
```
199
200
## Advanced Usage Patterns
201
202
### Feature Detection Flow
203
204
Comprehensive feature detection for optimal user experience:
205
206
```typescript
207
import {
208
browserSupportsWebAuthn,
209
platformAuthenticatorIsAvailable,
210
browserSupportsWebAuthnAutofill
211
} from '@simplewebauthn/browser';
212
213
async function setupWebAuthnUI() {
214
// Basic WebAuthn support check
215
if (!browserSupportsWebAuthn()) {
216
showPasswordOnlyUI();
217
return;
218
}
219
220
// Check platform authenticator
221
const hasPlatformAuth = await platformAuthenticatorIsAvailable();
222
223
// Check autofill support
224
const hasAutofill = await browserSupportsWebAuthnAutofill();
225
226
// Configure UI based on capabilities
227
if (hasPlatformAuth && hasAutofill) {
228
showBiometricWithAutofillUI();
229
} else if (hasPlatformAuth) {
230
showBiometricUI();
231
} else {
232
showSecurityKeyUI();
233
}
234
}
235
```
236
237
### Custom Data Processing
238
239
Using the conversion utilities for advanced scenarios:
240
241
```typescript
242
import {
243
base64URLStringToBuffer,
244
bufferToBase64URLString
245
} from '@simplewebauthn/browser';
246
247
// Process credential descriptors from server
248
function processCredentialDescriptors(serverDescriptors: any[]) {
249
return serverDescriptors.map(desc => ({
250
...desc,
251
id: base64URLStringToBuffer(desc.id)
252
}));
253
}
254
255
// Prepare custom data for server
256
function prepareForServer(arrayBufferData: ArrayBuffer) {
257
return {
258
data: bufferToBase64URLString(arrayBufferData),
259
timestamp: Date.now(),
260
userAgent: navigator.userAgent
261
};
262
}
263
```
264
265
## Error Handling
266
267
Feature detection functions are designed to be safe and never throw errors:
268
269
```typescript
270
// These functions never throw - safe to call without try/catch
271
const webauthnSupported = browserSupportsWebAuthn(); // boolean
272
const platformAuth = await platformAuthenticatorIsAvailable(); // boolean
273
const autofillSupported = await browserSupportsWebAuthnAutofill(); // boolean
274
275
// Conversion utilities can throw on invalid input
276
try {
277
const buffer = base64URLStringToBuffer(untrustedInput);
278
const encoded = bufferToBase64URLString(buffer);
279
} catch (error) {
280
console.error('Invalid Base64URL input:', error.message);
281
}
282
```
283
284
## Browser Compatibility
285
286
- **browserSupportsWebAuthn**: Works in all environments, returns `false` for unsupported browsers
287
- **platformAuthenticatorIsAvailable**: Requires WebAuthn support, safe fallback for unsupported browsers
288
- **browserSupportsWebAuthnAutofill**: Requires modern browser with conditional mediation support
289
- **Base64URL utilities**: Work in all JavaScript environments with `atob`/`btoa` support