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

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