@supabase/auth-js 2.72.0-rc.8 → 2.72.1-canary.0

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