@supabase/auth-js 2.73.0-rc.3 → 2.73.0-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +28 -1
  2. package/dist/main/GoTrueClient.d.ts +1 -1
  3. package/dist/main/GoTrueClient.d.ts.map +1 -1
  4. package/dist/main/GoTrueClient.js +43 -15
  5. package/dist/main/GoTrueClient.js.map +1 -1
  6. package/dist/main/lib/base64url.d.ts +3 -2
  7. package/dist/main/lib/base64url.d.ts.map +1 -1
  8. package/dist/main/lib/base64url.js.map +1 -1
  9. package/dist/main/lib/helpers.d.ts +2 -1
  10. package/dist/main/lib/helpers.d.ts.map +1 -1
  11. package/dist/main/lib/helpers.js.map +1 -1
  12. package/dist/main/lib/types.d.ts +140 -19
  13. package/dist/main/lib/types.d.ts.map +1 -1
  14. package/dist/main/lib/types.js +3 -2
  15. package/dist/main/lib/types.js.map +1 -1
  16. package/dist/main/lib/version.d.ts +1 -1
  17. package/dist/main/lib/version.js +1 -1
  18. package/dist/main/lib/webauthn.d.ts +274 -0
  19. package/dist/main/lib/webauthn.d.ts.map +1 -0
  20. package/dist/main/lib/webauthn.dom.d.ts +583 -0
  21. package/dist/main/lib/webauthn.dom.d.ts.map +1 -0
  22. package/dist/main/lib/webauthn.dom.js +4 -0
  23. package/dist/main/lib/webauthn.dom.js.map +1 -0
  24. package/dist/main/lib/webauthn.errors.d.ts +80 -0
  25. package/dist/main/lib/webauthn.errors.d.ts.map +1 -0
  26. package/dist/main/lib/webauthn.errors.js +265 -0
  27. package/dist/main/lib/webauthn.errors.js.map +1 -0
  28. package/dist/main/lib/webauthn.js +702 -0
  29. package/dist/main/lib/webauthn.js.map +1 -0
  30. package/dist/module/GoTrueClient.d.ts +1 -1
  31. package/dist/module/GoTrueClient.d.ts.map +1 -1
  32. package/dist/module/GoTrueClient.js +49 -21
  33. package/dist/module/GoTrueClient.js.map +1 -1
  34. package/dist/module/lib/base64url.d.ts +3 -2
  35. package/dist/module/lib/base64url.d.ts.map +1 -1
  36. package/dist/module/lib/base64url.js.map +1 -1
  37. package/dist/module/lib/helpers.d.ts +2 -1
  38. package/dist/module/lib/helpers.d.ts.map +1 -1
  39. package/dist/module/lib/helpers.js.map +1 -1
  40. package/dist/module/lib/types.d.ts +140 -19
  41. package/dist/module/lib/types.d.ts.map +1 -1
  42. package/dist/module/lib/types.js +2 -1
  43. package/dist/module/lib/types.js.map +1 -1
  44. package/dist/module/lib/version.d.ts +1 -1
  45. package/dist/module/lib/version.js +1 -1
  46. package/dist/module/lib/webauthn.d.ts +274 -0
  47. package/dist/module/lib/webauthn.d.ts.map +1 -0
  48. package/dist/module/lib/webauthn.dom.d.ts +583 -0
  49. package/dist/module/lib/webauthn.dom.d.ts.map +1 -0
  50. package/dist/module/lib/webauthn.dom.js +3 -0
  51. package/dist/module/lib/webauthn.dom.js.map +1 -0
  52. package/dist/module/lib/webauthn.errors.d.ts +80 -0
  53. package/dist/module/lib/webauthn.errors.d.ts.map +1 -0
  54. package/dist/module/lib/webauthn.errors.js +257 -0
  55. package/dist/module/lib/webauthn.errors.js.map +1 -0
  56. package/dist/module/lib/webauthn.js +685 -0
  57. package/dist/module/lib/webauthn.js.map +1 -0
  58. package/package.json +1 -1
  59. package/src/GoTrueClient.ts +198 -68
  60. package/src/lib/base64url.ts +4 -2
  61. package/src/lib/helpers.ts +2 -1
  62. package/src/lib/types.ts +205 -26
  63. package/src/lib/version.ts +1 -1
  64. package/src/lib/webauthn.dom.ts +636 -0
  65. package/src/lib/webauthn.errors.ts +317 -0
  66. package/src/lib/webauthn.ts +929 -0
@@ -0,0 +1,929 @@
1
+ import GoTrueClient from '../GoTrueClient'
2
+ import { base64UrlToUint8Array, bytesToBase64URL } from './base64url'
3
+ import { AuthError, AuthUnknownError, isAuthError } from './errors'
4
+ import {
5
+ AuthMFAEnrollWebauthnResponse,
6
+ AuthMFAVerifyResponse,
7
+ AuthMFAVerifyResponseData,
8
+ MFAChallengeWebauthnParams,
9
+ MFAEnrollWebauthnParams,
10
+ MFAVerifyWebauthnParamFields,
11
+ MFAVerifyWebauthnParams,
12
+ RequestResult,
13
+ StrictOmit,
14
+ } from './types'
15
+ import { isBrowser } from './helpers'
16
+ import type {
17
+ AuthenticationCredential,
18
+ AuthenticationResponseJSON,
19
+ AuthenticatorAttachment,
20
+ PublicKeyCredentialCreationOptionsFuture,
21
+ PublicKeyCredentialCreationOptionsJSON,
22
+ PublicKeyCredentialFuture,
23
+ PublicKeyCredentialRequestOptionsFuture,
24
+ PublicKeyCredentialRequestOptionsJSON,
25
+ RegistrationCredential,
26
+ RegistrationResponseJSON,
27
+ } from './webauthn.dom'
28
+
29
+ import {
30
+ identifyAuthenticationError,
31
+ identifyRegistrationError,
32
+ isWebAuthnError,
33
+ WebAuthnError,
34
+ WebAuthnUnknownError,
35
+ } from './webauthn.errors'
36
+
37
+ export { WebAuthnError, isWebAuthnError, identifyRegistrationError, identifyAuthenticationError }
38
+ // Re-export the JSON types for use in other files
39
+ export type { RegistrationResponseJSON, AuthenticationResponseJSON }
40
+
41
+ /**
42
+ * WebAuthn abort service to manage ceremony cancellation.
43
+ * Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors.
44
+ *
45
+ * @experimental This class is experimental and may change in future releases
46
+ * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies}
47
+ */
48
+ export class WebAuthnAbortService {
49
+ private controller: AbortController | undefined
50
+
51
+ /**
52
+ * Create an abort signal for a new WebAuthn operation.
53
+ * Automatically cancels any existing operation.
54
+ *
55
+ * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get()
56
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal}
57
+ */
58
+ createNewAbortSignal(): AbortSignal {
59
+ // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get()
60
+ if (this.controller) {
61
+ const abortError = new Error('Cancelling existing WebAuthn API call for new one')
62
+ abortError.name = 'AbortError'
63
+ this.controller.abort(abortError)
64
+ }
65
+
66
+ const newController = new AbortController()
67
+ this.controller = newController
68
+ return newController.signal
69
+ }
70
+
71
+ /**
72
+ * Manually cancel the current WebAuthn operation.
73
+ * Useful for cleaning up when user cancels or navigates away.
74
+ *
75
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort}
76
+ */
77
+ cancelCeremony(): void {
78
+ if (this.controller) {
79
+ const abortError = new Error('Manually cancelling existing WebAuthn API call')
80
+ abortError.name = 'AbortError'
81
+ this.controller.abort(abortError)
82
+ this.controller = undefined
83
+ }
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Singleton instance to ensure only one WebAuthn ceremony is active at a time.
89
+ * This prevents "operation already in progress" errors when retrying WebAuthn operations.
90
+ *
91
+ * @experimental This instance is experimental and may change in future releases
92
+ */
93
+ export const webAuthnAbortService = new WebAuthnAbortService()
94
+
95
+ /**
96
+ * Server response format for WebAuthn credential creation options.
97
+ * Uses W3C standard JSON format with base64url-encoded binary fields.
98
+ */
99
+ export type ServerCredentialCreationOptions = PublicKeyCredentialCreationOptionsJSON
100
+
101
+ /**
102
+ * Server response format for WebAuthn credential request options.
103
+ * Uses W3C standard JSON format with base64url-encoded binary fields.
104
+ */
105
+ export type ServerCredentialRequestOptions = PublicKeyCredentialRequestOptionsJSON
106
+
107
+ /**
108
+ * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers
109
+ * as required by the WebAuthn browser API.
110
+ * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback.
111
+ *
112
+ * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields
113
+ * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create()
114
+ * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON}
115
+ */
116
+ export function deserializeCredentialCreationOptions(
117
+ options: ServerCredentialCreationOptions
118
+ ): PublicKeyCredentialCreationOptionsFuture {
119
+ if (!options) {
120
+ throw new Error('Credential creation options are required')
121
+ }
122
+
123
+ // Check if the native parseCreationOptionsFromJSON method is available
124
+ if (
125
+ typeof PublicKeyCredential !== 'undefined' &&
126
+ 'parseCreationOptionsFromJSON' in PublicKeyCredential &&
127
+ typeof (PublicKeyCredential as unknown as PublicKeyCredentialFuture)
128
+ .parseCreationOptionsFromJSON === 'function'
129
+ ) {
130
+ // Use the native WebAuthn Level 3 method
131
+ return (
132
+ PublicKeyCredential as unknown as PublicKeyCredentialFuture
133
+ ).parseCreationOptionsFromJSON(
134
+ /** we assert the options here as typescript still doesn't know about future webauthn types */
135
+ options as any
136
+ ) as PublicKeyCredentialCreationOptionsFuture
137
+ }
138
+
139
+ // Fallback to manual parsing for browsers that don't support the native method
140
+ // Destructure to separate fields that need transformation
141
+ const { challenge: challengeStr, user: userOpts, excludeCredentials, ...restOptions } = options
142
+
143
+ // Convert challenge from base64url to ArrayBuffer
144
+ const challenge = base64UrlToUint8Array(challengeStr).buffer as ArrayBuffer
145
+
146
+ // Convert user.id from base64url to ArrayBuffer
147
+ const user: PublicKeyCredentialUserEntity = {
148
+ ...userOpts,
149
+ id: base64UrlToUint8Array(userOpts.id).buffer as ArrayBuffer,
150
+ }
151
+
152
+ // Build the result object
153
+ const result: PublicKeyCredentialCreationOptionsFuture = {
154
+ ...restOptions,
155
+ challenge,
156
+ user,
157
+ }
158
+
159
+ // Only add excludeCredentials if it exists
160
+ if (excludeCredentials && excludeCredentials.length > 0) {
161
+ result.excludeCredentials = new Array(excludeCredentials.length)
162
+
163
+ for (let i = 0; i < excludeCredentials.length; i++) {
164
+ const cred = excludeCredentials[i]
165
+ result.excludeCredentials[i] = {
166
+ ...cred,
167
+ id: base64UrlToUint8Array(cred.id).buffer,
168
+ type: cred.type || 'public-key',
169
+ // Cast transports to handle future transport types like "cable"
170
+ transports: cred.transports,
171
+ }
172
+ }
173
+ }
174
+
175
+ return result
176
+ }
177
+
178
+ /**
179
+ * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers
180
+ * as required by the WebAuthn browser API.
181
+ * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback.
182
+ *
183
+ * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields
184
+ * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get()
185
+ * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON}
186
+ */
187
+ export function deserializeCredentialRequestOptions(
188
+ options: ServerCredentialRequestOptions
189
+ ): PublicKeyCredentialRequestOptionsFuture {
190
+ if (!options) {
191
+ throw new Error('Credential request options are required')
192
+ }
193
+
194
+ // Check if the native parseRequestOptionsFromJSON method is available
195
+ if (
196
+ typeof PublicKeyCredential !== 'undefined' &&
197
+ 'parseRequestOptionsFromJSON' in PublicKeyCredential &&
198
+ typeof (PublicKeyCredential as unknown as PublicKeyCredentialFuture)
199
+ .parseRequestOptionsFromJSON === 'function'
200
+ ) {
201
+ // Use the native WebAuthn Level 3 method
202
+ return (
203
+ PublicKeyCredential as unknown as PublicKeyCredentialFuture
204
+ ).parseRequestOptionsFromJSON(options) as PublicKeyCredentialRequestOptionsFuture
205
+ }
206
+
207
+ // Fallback to manual parsing for browsers that don't support the native method
208
+ // Destructure to separate fields that need transformation
209
+ const { challenge: challengeStr, allowCredentials, ...restOptions } = options
210
+
211
+ // Convert challenge from base64url to ArrayBuffer
212
+ const challenge = base64UrlToUint8Array(challengeStr).buffer as ArrayBuffer
213
+
214
+ // Build the result object
215
+ const result: PublicKeyCredentialRequestOptionsFuture = {
216
+ ...restOptions,
217
+ challenge,
218
+ }
219
+
220
+ // Only add allowCredentials if it exists
221
+ if (allowCredentials && allowCredentials.length > 0) {
222
+ result.allowCredentials = new Array(allowCredentials.length)
223
+
224
+ for (let i = 0; i < allowCredentials.length; i++) {
225
+ const cred = allowCredentials[i]
226
+ result.allowCredentials[i] = {
227
+ ...cred,
228
+ id: base64UrlToUint8Array(cred.id).buffer,
229
+ type: cred.type || 'public-key',
230
+ // Cast transports to handle future transport types like "cable"
231
+ transports: cred.transports,
232
+ }
233
+ }
234
+ }
235
+
236
+ return result
237
+ }
238
+
239
+ /**
240
+ * Server format for credential response with base64url-encoded binary fields
241
+ * Can be either a registration or authentication response
242
+ */
243
+ export type ServerCredentialResponse = RegistrationResponseJSON | AuthenticationResponseJSON
244
+
245
+ /**
246
+ * Convert a registration/enrollment credential response to server format.
247
+ * Serializes binary fields to base64url for JSON transmission.
248
+ * Supports both native WebAuthn Level 3 toJSON and manual fallback.
249
+ *
250
+ * @param {RegistrationCredential} credential - Credential from navigator.credentials.create()
251
+ * @returns {RegistrationResponseJSON} JSON-serializable credential for server
252
+ * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}
253
+ */
254
+ export function serializeCredentialCreationResponse(
255
+ credential: RegistrationCredential
256
+ ): RegistrationResponseJSON {
257
+ // Check if the credential instance has the toJSON method
258
+ if ('toJSON' in credential && typeof credential.toJSON === 'function') {
259
+ // Use the native WebAuthn Level 3 method
260
+ return (credential as RegistrationCredential).toJSON()
261
+ }
262
+ const credentialWithAttachment = credential as PublicKeyCredential & {
263
+ response: AuthenticatorAttestationResponse
264
+ authenticatorAttachment?: string | null
265
+ }
266
+
267
+ return {
268
+ id: credential.id,
269
+ rawId: credential.id,
270
+ response: {
271
+ attestationObject: bytesToBase64URL(new Uint8Array(credential.response.attestationObject)),
272
+ clientDataJSON: bytesToBase64URL(new Uint8Array(credential.response.clientDataJSON)),
273
+ },
274
+ type: 'public-key',
275
+ clientExtensionResults: credential.getClientExtensionResults(),
276
+ // Convert null to undefined and cast to AuthenticatorAttachment type
277
+ authenticatorAttachment: (credentialWithAttachment.authenticatorAttachment ?? undefined) as
278
+ | AuthenticatorAttachment
279
+ | undefined,
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Convert an authentication/verification credential response to server format.
285
+ * Serializes binary fields to base64url for JSON transmission.
286
+ * Supports both native WebAuthn Level 3 toJSON and manual fallback.
287
+ *
288
+ * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get()
289
+ * @returns {AuthenticationResponseJSON} JSON-serializable credential for server
290
+ * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}
291
+ */
292
+ export function serializeCredentialRequestResponse(
293
+ credential: AuthenticationCredential
294
+ ): AuthenticationResponseJSON {
295
+ // Check if the credential instance has the toJSON method
296
+ if ('toJSON' in credential && typeof credential.toJSON === 'function') {
297
+ // Use the native WebAuthn Level 3 method
298
+ return (credential as AuthenticationCredential).toJSON()
299
+ }
300
+
301
+ // Fallback to manual conversion for browsers that don't support toJSON
302
+ // Access authenticatorAttachment via type assertion to handle TypeScript version differences
303
+ // @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't
304
+ const credentialWithAttachment = credential as PublicKeyCredential & {
305
+ response: AuthenticatorAssertionResponse
306
+ authenticatorAttachment?: string | null
307
+ }
308
+
309
+ const clientExtensionResults = credential.getClientExtensionResults()
310
+ const assertionResponse = credential.response
311
+
312
+ return {
313
+ id: credential.id,
314
+ rawId: credential.id, // W3C spec expects rawId to match id for JSON format
315
+ response: {
316
+ authenticatorData: bytesToBase64URL(new Uint8Array(assertionResponse.authenticatorData)),
317
+ clientDataJSON: bytesToBase64URL(new Uint8Array(assertionResponse.clientDataJSON)),
318
+ signature: bytesToBase64URL(new Uint8Array(assertionResponse.signature)),
319
+ userHandle: assertionResponse.userHandle
320
+ ? bytesToBase64URL(new Uint8Array(assertionResponse.userHandle))
321
+ : undefined,
322
+ },
323
+ type: 'public-key',
324
+ clientExtensionResults,
325
+ // Convert null to undefined and cast to AuthenticatorAttachment type
326
+ authenticatorAttachment: (credentialWithAttachment.authenticatorAttachment ?? undefined) as
327
+ | AuthenticatorAttachment
328
+ | undefined,
329
+ }
330
+ }
331
+
332
+ /**
333
+ * A simple test to determine if a hostname is a properly-formatted domain name.
334
+ * Considers localhost valid for development environments.
335
+ *
336
+ * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain
337
+ *
338
+ * Regex sourced from here:
339
+ * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html
340
+ *
341
+ * @param {string} hostname - The hostname to validate
342
+ * @returns {boolean} True if valid domain or localhost
343
+ * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain}
344
+ */
345
+ export function isValidDomain(hostname: string): boolean {
346
+ return (
347
+ // Consider localhost valid as well since it's okay wrt Secure Contexts
348
+ hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname)
349
+ )
350
+ }
351
+
352
+ /**
353
+ * Determine if the browser is capable of WebAuthn.
354
+ * Checks for necessary Web APIs: PublicKeyCredential and Credential Management.
355
+ *
356
+ * @returns {boolean} True if browser supports WebAuthn
357
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility}
358
+ */
359
+ function browserSupportsWebAuthn(): boolean {
360
+ return !!(
361
+ isBrowser() &&
362
+ 'PublicKeyCredential' in window &&
363
+ window.PublicKeyCredential &&
364
+ 'credentials' in navigator &&
365
+ typeof navigator?.credentials?.create === 'function' &&
366
+ typeof navigator?.credentials?.get === 'function'
367
+ )
368
+ }
369
+
370
+ /**
371
+ * Create a WebAuthn credential using the browser's credentials API.
372
+ * Wraps navigator.credentials.create() with error handling.
373
+ *
374
+ * @param {CredentialCreationOptions} options - Options including publicKey parameters
375
+ * @returns {Promise<RequestResult<RegistrationCredential, WebAuthnError>>} Created credential or error
376
+ * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}
377
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create}
378
+ */
379
+ export async function createCredential(
380
+ options: StrictOmit<CredentialCreationOptions, 'publicKey'> & {
381
+ publicKey: PublicKeyCredentialCreationOptionsFuture
382
+ }
383
+ ): Promise<RequestResult<RegistrationCredential, WebAuthnError>> {
384
+ try {
385
+ const response = await navigator.credentials.create(
386
+ /** we assert the type here until typescript types are updated */
387
+ options as Parameters<typeof navigator.credentials.create>[0]
388
+ )
389
+ if (!response) {
390
+ return {
391
+ data: null,
392
+ error: new WebAuthnUnknownError('Empty credential response', response),
393
+ }
394
+ }
395
+ if (!(response instanceof PublicKeyCredential)) {
396
+ return {
397
+ data: null,
398
+ error: new WebAuthnUnknownError('Browser returned unexpected credential type', response),
399
+ }
400
+ }
401
+ return { data: response as RegistrationCredential, error: null }
402
+ } catch (err) {
403
+ return {
404
+ data: null,
405
+ error: identifyRegistrationError({
406
+ error: err as Error,
407
+ options,
408
+ }),
409
+ }
410
+ }
411
+ }
412
+
413
+ /**
414
+ * Get a WebAuthn credential using the browser's credentials API.
415
+ * Wraps navigator.credentials.get() with error handling.
416
+ *
417
+ * @param {CredentialRequestOptions} options - Options including publicKey parameters
418
+ * @returns {Promise<RequestResult<AuthenticationCredential, WebAuthnError>>} Retrieved credential or error
419
+ * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}
420
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get}
421
+ */
422
+ export async function getCredential(
423
+ options: StrictOmit<CredentialRequestOptions, 'publicKey'> & {
424
+ publicKey: PublicKeyCredentialRequestOptionsFuture
425
+ }
426
+ ): Promise<RequestResult<AuthenticationCredential, WebAuthnError>> {
427
+ try {
428
+ const response = await navigator.credentials.get(
429
+ /** we assert the type here until typescript types are updated */
430
+ options as Parameters<typeof navigator.credentials.get>[0]
431
+ )
432
+ if (!response) {
433
+ return {
434
+ data: null,
435
+ error: new WebAuthnUnknownError('Empty credential response', response),
436
+ }
437
+ }
438
+ if (!(response instanceof PublicKeyCredential)) {
439
+ return {
440
+ data: null,
441
+ error: new WebAuthnUnknownError('Browser returned unexpected credential type', response),
442
+ }
443
+ }
444
+ return { data: response as AuthenticationCredential, error: null }
445
+ } catch (err) {
446
+ return {
447
+ data: null,
448
+ error: identifyAuthenticationError({
449
+ error: err as Error,
450
+ options,
451
+ }),
452
+ }
453
+ }
454
+ }
455
+
456
+ export const DEFAULT_CREATION_OPTIONS: Partial<PublicKeyCredentialCreationOptionsFuture> = {
457
+ hints: ['security-key'],
458
+ authenticatorSelection: {
459
+ authenticatorAttachment: 'cross-platform',
460
+ requireResidentKey: false,
461
+ /** set to preferred because older yubikeys don't have PIN/Biometric */
462
+ userVerification: 'preferred',
463
+ residentKey: 'discouraged',
464
+ },
465
+ attestation: 'none',
466
+ }
467
+
468
+ export const DEFAULT_REQUEST_OPTIONS: Partial<PublicKeyCredentialRequestOptionsFuture> = {
469
+ /** set to preferred because older yubikeys don't have PIN/Biometric */
470
+ userVerification: 'preferred',
471
+ hints: ['security-key'],
472
+ }
473
+
474
+ function deepMerge<T>(...sources: Partial<T>[]): T {
475
+ const isObject = (val: unknown): val is Record<string, unknown> =>
476
+ val !== null && typeof val === 'object' && !Array.isArray(val)
477
+
478
+ const isArrayBufferLike = (val: unknown): val is ArrayBuffer | ArrayBufferView =>
479
+ val instanceof ArrayBuffer || ArrayBuffer.isView(val)
480
+
481
+ const result: Partial<T> = {}
482
+
483
+ for (const source of sources) {
484
+ if (!source) continue
485
+
486
+ for (const key in source) {
487
+ const value = source[key]
488
+ if (value === undefined) continue
489
+
490
+ if (Array.isArray(value)) {
491
+ // preserve array reference, including unions like AuthenticatorTransport[]
492
+ result[key] = value as T[typeof key]
493
+ } else if (isArrayBufferLike(value)) {
494
+ result[key] = value as T[typeof key]
495
+ } else if (isObject(value)) {
496
+ const existing = result[key]
497
+ if (isObject(existing)) {
498
+ result[key] = deepMerge(existing, value) as unknown as T[typeof key]
499
+ } else {
500
+ result[key] = deepMerge(value) as unknown as T[typeof key]
501
+ }
502
+ } else {
503
+ result[key] = value as T[typeof key]
504
+ }
505
+ }
506
+ }
507
+
508
+ return result as T
509
+ }
510
+
511
+ /**
512
+ * Merges WebAuthn credential creation options with overrides.
513
+ * Sets sensible defaults for authenticator selection and extensions.
514
+ *
515
+ * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server
516
+ * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply
517
+ * @param {string} friendlyName - Optional friendly name for the credential
518
+ * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options
519
+ * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria}
520
+ */
521
+ export function mergeCredentialCreationOptions(
522
+ baseOptions: PublicKeyCredentialCreationOptionsFuture,
523
+ overrides?: Partial<PublicKeyCredentialCreationOptionsFuture>
524
+ ): PublicKeyCredentialCreationOptionsFuture {
525
+ return deepMerge(DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {})
526
+ }
527
+
528
+ /**
529
+ * Merges WebAuthn credential request options with overrides.
530
+ * Sets sensible defaults for user verification and hints.
531
+ *
532
+ * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server
533
+ * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply
534
+ * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options
535
+ * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions}
536
+ */
537
+ export function mergeCredentialRequestOptions(
538
+ baseOptions: PublicKeyCredentialRequestOptionsFuture,
539
+ overrides?: Partial<PublicKeyCredentialRequestOptionsFuture>
540
+ ): PublicKeyCredentialRequestOptionsFuture {
541
+ return deepMerge(DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {})
542
+ }
543
+
544
+ /**
545
+ * WebAuthn API wrapper for Supabase Auth.
546
+ * Provides methods for enrolling, challenging, verifying, authenticating, and registering WebAuthn credentials.
547
+ *
548
+ * @experimental This API is experimental and may change in future releases
549
+ * @see {@link https://w3c.github.io/webauthn/ W3C WebAuthn Specification}
550
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API MDN - Web Authentication API}
551
+ */
552
+ export class WebAuthnApi {
553
+ public enroll: typeof WebAuthnApi.prototype._enroll
554
+ public challenge: typeof WebAuthnApi.prototype._challenge
555
+ public verify: typeof WebAuthnApi.prototype._verify
556
+ public authenticate: typeof WebAuthnApi.prototype._authenticate
557
+ public register: typeof WebAuthnApi.prototype._register
558
+
559
+ constructor(private client: GoTrueClient) {
560
+ // Bind all methods so they can be destructured
561
+ this.enroll = this._enroll.bind(this)
562
+ this.challenge = this._challenge.bind(this)
563
+ this.verify = this._verify.bind(this)
564
+ this.authenticate = this._authenticate.bind(this)
565
+ this.register = this._register.bind(this)
566
+ }
567
+
568
+ /**
569
+ * Enroll a new WebAuthn factor.
570
+ * Creates an unverified WebAuthn factor that must be verified with a credential.
571
+ *
572
+ * @experimental This method is experimental and may change in future releases
573
+ * @param {Omit<MFAEnrollWebauthnParams, 'factorType'>} params - Enrollment parameters (friendlyName required)
574
+ * @returns {Promise<AuthMFAEnrollWebauthnResponse>} Enrolled factor details or error
575
+ * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential}
576
+ */
577
+ public async _enroll(
578
+ params: Omit<MFAEnrollWebauthnParams, 'factorType'>
579
+ ): Promise<AuthMFAEnrollWebauthnResponse> {
580
+ return this.client.mfa.enroll({ ...params, factorType: 'webauthn' })
581
+ }
582
+
583
+ /**
584
+ * Challenge for WebAuthn credential creation or authentication.
585
+ * Combines server challenge with browser credential operations.
586
+ * Handles both registration (create) and authentication (request) flows.
587
+ *
588
+ * @experimental This method is experimental and may change in future releases
589
+ * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId
590
+ * @param {Object} overrides - Allows you to override the parameters passed to navigator.credentials
591
+ * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation
592
+ * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request
593
+ * @returns {Promise<RequestResult>} Challenge response with credential or error
594
+ * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation}
595
+ * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion}
596
+ */
597
+ public async _challenge(
598
+ {
599
+ factorId,
600
+ webauthn,
601
+ friendlyName,
602
+ signal,
603
+ }: MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal },
604
+ overrides?:
605
+ | {
606
+ create?: Partial<PublicKeyCredentialCreationOptionsFuture>
607
+ request?: never
608
+ }
609
+ | {
610
+ create?: never
611
+ request?: Partial<PublicKeyCredentialRequestOptionsFuture>
612
+ }
613
+ ): Promise<
614
+ RequestResult<
615
+ { factorId: string; challengeId: string } & {
616
+ webauthn: StrictOmit<
617
+ MFAVerifyWebauthnParamFields<'create' | 'request'>['webauthn'],
618
+ 'rpId' | 'rpOrigins'
619
+ >
620
+ },
621
+ WebAuthnError | AuthError
622
+ >
623
+ > {
624
+ try {
625
+ // Get challenge from server using the client's MFA methods
626
+ const { data: challengeResponse, error: challengeError } = await this.client.mfa.challenge({
627
+ factorId,
628
+ webauthn,
629
+ })
630
+
631
+ if (!challengeResponse) {
632
+ return { data: null, error: challengeError }
633
+ }
634
+
635
+ const abortSignal = signal ?? webAuthnAbortService.createNewAbortSignal()
636
+
637
+ /** webauthn will fail if either of the name/displayname are blank */
638
+ if (challengeResponse.webauthn.type === 'create') {
639
+ const { user } = challengeResponse.webauthn.credential_options.publicKey
640
+ if (!user.name) {
641
+ user.name = `${user.id}:${friendlyName}`
642
+ }
643
+ if (!user.displayName) {
644
+ user.displayName = user.name
645
+ }
646
+ }
647
+
648
+ switch (challengeResponse.webauthn.type) {
649
+ case 'create': {
650
+ const options = mergeCredentialCreationOptions(
651
+ challengeResponse.webauthn.credential_options.publicKey,
652
+ overrides?.create
653
+ )
654
+
655
+ const { data, error } = await createCredential({
656
+ publicKey: options,
657
+ signal: abortSignal,
658
+ })
659
+
660
+ if (data) {
661
+ return {
662
+ data: {
663
+ factorId,
664
+ challengeId: challengeResponse.id,
665
+ webauthn: {
666
+ type: challengeResponse.webauthn.type,
667
+ credential_response: data,
668
+ },
669
+ },
670
+ error: null,
671
+ }
672
+ }
673
+ return { data: null, error }
674
+ }
675
+
676
+ case 'request': {
677
+ const options = mergeCredentialRequestOptions(
678
+ challengeResponse.webauthn.credential_options.publicKey,
679
+ overrides?.request
680
+ )
681
+
682
+ const { data, error } = await getCredential({
683
+ ...challengeResponse.webauthn.credential_options,
684
+ publicKey: options,
685
+ signal: abortSignal,
686
+ })
687
+
688
+ if (data) {
689
+ return {
690
+ data: {
691
+ factorId,
692
+ challengeId: challengeResponse.id,
693
+ webauthn: {
694
+ type: challengeResponse.webauthn.type,
695
+ credential_response: data,
696
+ },
697
+ },
698
+ error: null,
699
+ }
700
+ }
701
+ return { data: null, error }
702
+ }
703
+ }
704
+ } catch (error) {
705
+ if (isAuthError(error)) {
706
+ return { data: null, error }
707
+ }
708
+ return {
709
+ data: null,
710
+ error: new AuthUnknownError('Unexpected error in challenge', error),
711
+ }
712
+ }
713
+ }
714
+
715
+ /**
716
+ * Verify a WebAuthn credential with the server.
717
+ * Completes the WebAuthn ceremony by sending the credential to the server for verification.
718
+ *
719
+ * @experimental This method is experimental and may change in future releases
720
+ * @param {Object} params - Verification parameters
721
+ * @param {string} params.challengeId - ID of the challenge being verified
722
+ * @param {string} params.factorId - ID of the WebAuthn factor
723
+ * @param {MFAVerifyWebauthnParams<T>['webauthn']} params.webauthn - WebAuthn credential response
724
+ * @returns {Promise<AuthMFAVerifyResponse>} Verification result with session or error
725
+ * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion}
726
+ * */
727
+ public async _verify<T extends 'create' | 'request'>({
728
+ challengeId,
729
+ factorId,
730
+ webauthn,
731
+ }: {
732
+ challengeId: string
733
+ factorId: string
734
+ webauthn: MFAVerifyWebauthnParams<T>['webauthn']
735
+ }): Promise<AuthMFAVerifyResponse> {
736
+ return this.client.mfa.verify({
737
+ factorId,
738
+ challengeId,
739
+ webauthn: webauthn,
740
+ })
741
+ }
742
+
743
+ /**
744
+ * Complete WebAuthn authentication flow.
745
+ * Performs challenge and verification in a single operation for existing credentials.
746
+ *
747
+ * @experimental This method is experimental and may change in future releases
748
+ * @param {Object} params - Authentication parameters
749
+ * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with
750
+ * @param {Object} params.webauthn - WebAuthn configuration
751
+ * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname)
752
+ * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin)
753
+ * @param {AbortSignal} params.webauthn.signal - Optional abort signal
754
+ * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get
755
+ * @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Authentication result
756
+ * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony}
757
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions}
758
+ */
759
+ public async _authenticate(
760
+ {
761
+ factorId,
762
+ webauthn: {
763
+ rpId = typeof window !== 'undefined' ? window.location.hostname : undefined,
764
+ rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined,
765
+ signal,
766
+ },
767
+ }: {
768
+ factorId: string
769
+ webauthn: {
770
+ rpId?: string
771
+ rpOrigins?: string[]
772
+ signal?: AbortSignal
773
+ }
774
+ },
775
+ overrides?: PublicKeyCredentialRequestOptionsFuture
776
+ ): Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>> {
777
+ if (!rpId) {
778
+ return {
779
+ data: null,
780
+ error: new AuthError('rpId is required for WebAuthn authentication'),
781
+ }
782
+ }
783
+ try {
784
+ if (!browserSupportsWebAuthn()) {
785
+ return {
786
+ data: null,
787
+ error: new AuthUnknownError('Browser does not support WebAuthn', null),
788
+ }
789
+ }
790
+
791
+ // Get challenge and credential
792
+ const { data: challengeResponse, error: challengeError } = await this.challenge(
793
+ {
794
+ factorId,
795
+ webauthn: { rpId, rpOrigins },
796
+ signal,
797
+ },
798
+ { request: overrides }
799
+ )
800
+
801
+ if (!challengeResponse) {
802
+ return { data: null, error: challengeError }
803
+ }
804
+
805
+ const { webauthn } = challengeResponse
806
+
807
+ // Verify credential
808
+ return this._verify({
809
+ factorId,
810
+ challengeId: challengeResponse.challengeId,
811
+ webauthn: {
812
+ type: webauthn.type,
813
+ rpId,
814
+ rpOrigins,
815
+ credential_response: webauthn.credential_response,
816
+ },
817
+ })
818
+ } catch (error) {
819
+ if (isAuthError(error)) {
820
+ return { data: null, error }
821
+ }
822
+ return {
823
+ data: null,
824
+ error: new AuthUnknownError('Unexpected error in authenticate', error),
825
+ }
826
+ }
827
+ }
828
+
829
+ /**
830
+ * Complete WebAuthn registration flow.
831
+ * Performs enrollment, challenge, and verification in a single operation for new credentials.
832
+ *
833
+ * @experimental This method is experimental and may change in future releases
834
+ * @param {Object} params - Registration parameters
835
+ * @param {string} params.friendlyName - User-friendly name for the credential
836
+ * @param {string} params.rpId - Relying Party ID (defaults to current hostname)
837
+ * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin)
838
+ * @param {AbortSignal} params.signal - Optional abort signal
839
+ * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create
840
+ * @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Registration result
841
+ * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony}
842
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions}
843
+ */
844
+ public async _register(
845
+ {
846
+ friendlyName,
847
+ rpId = typeof window !== 'undefined' ? window.location.hostname : undefined,
848
+ rpOrigins = typeof window !== 'undefined' ? [window.location.origin] : undefined,
849
+ signal,
850
+ }: {
851
+ friendlyName: string
852
+ rpId?: string
853
+ rpOrigins?: string[]
854
+ signal?: AbortSignal
855
+ },
856
+ overrides?: Partial<PublicKeyCredentialCreationOptionsFuture>
857
+ ): Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>> {
858
+ if (!rpId) {
859
+ return {
860
+ data: null,
861
+ error: new AuthError('rpId is required for WebAuthn registration'),
862
+ }
863
+ }
864
+ try {
865
+ if (!browserSupportsWebAuthn()) {
866
+ return {
867
+ data: null,
868
+ error: new AuthUnknownError('Browser does not support WebAuthn', null),
869
+ }
870
+ }
871
+
872
+ // Enroll factor
873
+ const { data: factor, error: enrollError } = await this._enroll({
874
+ friendlyName,
875
+ })
876
+
877
+ if (!factor) {
878
+ await this.client.mfa
879
+ .listFactors()
880
+ .then((factors) =>
881
+ factors.data?.all.find(
882
+ (v) =>
883
+ v.factor_type === 'webauthn' &&
884
+ v.friendly_name === friendlyName &&
885
+ v.status !== 'unverified'
886
+ )
887
+ )
888
+ .then((factor) => (factor ? this.client.mfa.unenroll({ factorId: factor?.id }) : void 0))
889
+ return { data: null, error: enrollError }
890
+ }
891
+
892
+ // Get challenge and create credential
893
+ const { data: challengeResponse, error: challengeError } = await this._challenge(
894
+ {
895
+ factorId: factor.id,
896
+ friendlyName: factor.friendly_name,
897
+ webauthn: { rpId, rpOrigins },
898
+ signal,
899
+ },
900
+ {
901
+ create: overrides,
902
+ }
903
+ )
904
+
905
+ if (!challengeResponse) {
906
+ return { data: null, error: challengeError }
907
+ }
908
+
909
+ return this._verify({
910
+ factorId: factor.id,
911
+ challengeId: challengeResponse.challengeId,
912
+ webauthn: {
913
+ rpId,
914
+ rpOrigins,
915
+ type: challengeResponse.webauthn.type,
916
+ credential_response: challengeResponse.webauthn.credential_response,
917
+ },
918
+ })
919
+ } catch (error) {
920
+ if (isAuthError(error)) {
921
+ return { data: null, error }
922
+ }
923
+ return {
924
+ data: null,
925
+ error: new AuthUnknownError('Unexpected error in register', error),
926
+ }
927
+ }
928
+ }
929
+ }