@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,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.DEFAULT_REQUEST_OPTIONS = exports.DEFAULT_CREATION_OPTIONS = exports.webAuthnAbortService = exports.WebAuthnAbortService = exports.identifyAuthenticationError = exports.identifyRegistrationError = exports.isWebAuthnError = exports.WebAuthnError = void 0;
15
+ exports.deserializeCredentialCreationOptions = deserializeCredentialCreationOptions;
16
+ exports.deserializeCredentialRequestOptions = deserializeCredentialRequestOptions;
17
+ exports.serializeCredentialCreationResponse = serializeCredentialCreationResponse;
18
+ exports.serializeCredentialRequestResponse = serializeCredentialRequestResponse;
19
+ exports.isValidDomain = isValidDomain;
20
+ exports.createCredential = createCredential;
21
+ exports.getCredential = getCredential;
22
+ exports.mergeCredentialCreationOptions = mergeCredentialCreationOptions;
23
+ exports.mergeCredentialRequestOptions = mergeCredentialRequestOptions;
24
+ const base64url_1 = require("./base64url");
25
+ const errors_1 = require("./errors");
26
+ const helpers_1 = require("./helpers");
27
+ const webauthn_errors_1 = require("./webauthn.errors");
28
+ Object.defineProperty(exports, "identifyAuthenticationError", { enumerable: true, get: function () { return webauthn_errors_1.identifyAuthenticationError; } });
29
+ Object.defineProperty(exports, "identifyRegistrationError", { enumerable: true, get: function () { return webauthn_errors_1.identifyRegistrationError; } });
30
+ Object.defineProperty(exports, "isWebAuthnError", { enumerable: true, get: function () { return webauthn_errors_1.isWebAuthnError; } });
31
+ Object.defineProperty(exports, "WebAuthnError", { enumerable: true, get: function () { return webauthn_errors_1.WebAuthnError; } });
32
+ /**
33
+ * WebAuthn abort service to manage ceremony cancellation.
34
+ * Ensures only one WebAuthn ceremony is active at a time to prevent "operation already in progress" errors.
35
+ *
36
+ * @experimental This class is experimental and may change in future releases
37
+ * @see {@link https://w3c.github.io/webauthn/#sctn-automation-webdriver-capability W3C WebAuthn Spec - Aborting Ceremonies}
38
+ */
39
+ class WebAuthnAbortService {
40
+ /**
41
+ * Create an abort signal for a new WebAuthn operation.
42
+ * Automatically cancels any existing operation.
43
+ *
44
+ * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get()
45
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal}
46
+ */
47
+ createNewAbortSignal() {
48
+ // Abort any existing calls to navigator.credentials.create() or navigator.credentials.get()
49
+ if (this.controller) {
50
+ const abortError = new Error('Cancelling existing WebAuthn API call for new one');
51
+ abortError.name = 'AbortError';
52
+ this.controller.abort(abortError);
53
+ }
54
+ const newController = new AbortController();
55
+ this.controller = newController;
56
+ return newController.signal;
57
+ }
58
+ /**
59
+ * Manually cancel the current WebAuthn operation.
60
+ * Useful for cleaning up when user cancels or navigates away.
61
+ *
62
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort}
63
+ */
64
+ cancelCeremony() {
65
+ if (this.controller) {
66
+ const abortError = new Error('Manually cancelling existing WebAuthn API call');
67
+ abortError.name = 'AbortError';
68
+ this.controller.abort(abortError);
69
+ this.controller = undefined;
70
+ }
71
+ }
72
+ }
73
+ exports.WebAuthnAbortService = WebAuthnAbortService;
74
+ /**
75
+ * Singleton instance to ensure only one WebAuthn ceremony is active at a time.
76
+ * This prevents "operation already in progress" errors when retrying WebAuthn operations.
77
+ *
78
+ * @experimental This instance is experimental and may change in future releases
79
+ */
80
+ exports.webAuthnAbortService = new WebAuthnAbortService();
81
+ /**
82
+ * Convert base64url encoded strings in WebAuthn credential creation options to ArrayBuffers
83
+ * as required by the WebAuthn browser API.
84
+ * Supports both native WebAuthn Level 3 parseCreationOptionsFromJSON and manual fallback.
85
+ *
86
+ * @param {ServerCredentialCreationOptions} options - JSON options from server with base64url encoded fields
87
+ * @returns {PublicKeyCredentialCreationOptionsFuture} Options ready for navigator.credentials.create()
88
+ * @see {@link https://w3c.github.io/webauthn/#sctn-parseCreationOptionsFromJSON W3C WebAuthn Spec - parseCreationOptionsFromJSON}
89
+ */
90
+ function deserializeCredentialCreationOptions(options) {
91
+ if (!options) {
92
+ throw new Error('Credential creation options are required');
93
+ }
94
+ // Check if the native parseCreationOptionsFromJSON method is available
95
+ if (typeof PublicKeyCredential !== 'undefined' &&
96
+ 'parseCreationOptionsFromJSON' in PublicKeyCredential &&
97
+ typeof PublicKeyCredential
98
+ .parseCreationOptionsFromJSON === 'function') {
99
+ // Use the native WebAuthn Level 3 method
100
+ return PublicKeyCredential.parseCreationOptionsFromJSON(
101
+ /** we assert the options here as typescript still doesn't know about future webauthn types */
102
+ options);
103
+ }
104
+ // Fallback to manual parsing for browsers that don't support the native method
105
+ // Destructure to separate fields that need transformation
106
+ const { challenge: challengeStr, user: userOpts, excludeCredentials } = options, restOptions = __rest(options
107
+ // Convert challenge from base64url to ArrayBuffer
108
+ , ["challenge", "user", "excludeCredentials"]);
109
+ // Convert challenge from base64url to ArrayBuffer
110
+ const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer;
111
+ // Convert user.id from base64url to ArrayBuffer
112
+ const user = Object.assign(Object.assign({}, userOpts), { id: (0, base64url_1.base64UrlToUint8Array)(userOpts.id).buffer });
113
+ // Build the result object
114
+ const result = Object.assign(Object.assign({}, restOptions), { challenge,
115
+ user });
116
+ // Only add excludeCredentials if it exists
117
+ if (excludeCredentials && excludeCredentials.length > 0) {
118
+ result.excludeCredentials = new Array(excludeCredentials.length);
119
+ for (let i = 0; i < excludeCredentials.length; i++) {
120
+ const cred = excludeCredentials[i];
121
+ result.excludeCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key',
122
+ // Cast transports to handle future transport types like "cable"
123
+ transports: cred.transports });
124
+ }
125
+ }
126
+ return result;
127
+ }
128
+ /**
129
+ * Convert base64url encoded strings in WebAuthn credential request options to ArrayBuffers
130
+ * as required by the WebAuthn browser API.
131
+ * Supports both native WebAuthn Level 3 parseRequestOptionsFromJSON and manual fallback.
132
+ *
133
+ * @param {ServerCredentialRequestOptions} options - JSON options from server with base64url encoded fields
134
+ * @returns {PublicKeyCredentialRequestOptionsFuture} Options ready for navigator.credentials.get()
135
+ * @see {@link https://w3c.github.io/webauthn/#sctn-parseRequestOptionsFromJSON W3C WebAuthn Spec - parseRequestOptionsFromJSON}
136
+ */
137
+ function deserializeCredentialRequestOptions(options) {
138
+ if (!options) {
139
+ throw new Error('Credential request options are required');
140
+ }
141
+ // Check if the native parseRequestOptionsFromJSON method is available
142
+ if (typeof PublicKeyCredential !== 'undefined' &&
143
+ 'parseRequestOptionsFromJSON' in PublicKeyCredential &&
144
+ typeof PublicKeyCredential
145
+ .parseRequestOptionsFromJSON === 'function') {
146
+ // Use the native WebAuthn Level 3 method
147
+ return PublicKeyCredential.parseRequestOptionsFromJSON(options);
148
+ }
149
+ // Fallback to manual parsing for browsers that don't support the native method
150
+ // Destructure to separate fields that need transformation
151
+ const { challenge: challengeStr, allowCredentials } = options, restOptions = __rest(options
152
+ // Convert challenge from base64url to ArrayBuffer
153
+ , ["challenge", "allowCredentials"]);
154
+ // Convert challenge from base64url to ArrayBuffer
155
+ const challenge = (0, base64url_1.base64UrlToUint8Array)(challengeStr).buffer;
156
+ // Build the result object
157
+ const result = Object.assign(Object.assign({}, restOptions), { challenge });
158
+ // Only add allowCredentials if it exists
159
+ if (allowCredentials && allowCredentials.length > 0) {
160
+ result.allowCredentials = new Array(allowCredentials.length);
161
+ for (let i = 0; i < allowCredentials.length; i++) {
162
+ const cred = allowCredentials[i];
163
+ result.allowCredentials[i] = Object.assign(Object.assign({}, cred), { id: (0, base64url_1.base64UrlToUint8Array)(cred.id).buffer, type: cred.type || 'public-key',
164
+ // Cast transports to handle future transport types like "cable"
165
+ transports: cred.transports });
166
+ }
167
+ }
168
+ return result;
169
+ }
170
+ /**
171
+ * Convert a registration/enrollment credential response to server format.
172
+ * Serializes binary fields to base64url for JSON transmission.
173
+ * Supports both native WebAuthn Level 3 toJSON and manual fallback.
174
+ *
175
+ * @param {RegistrationCredential} credential - Credential from navigator.credentials.create()
176
+ * @returns {RegistrationResponseJSON} JSON-serializable credential for server
177
+ * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}
178
+ */
179
+ function serializeCredentialCreationResponse(credential) {
180
+ var _a;
181
+ // Check if the credential instance has the toJSON method
182
+ if ('toJSON' in credential && typeof credential.toJSON === 'function') {
183
+ // Use the native WebAuthn Level 3 method
184
+ return credential.toJSON();
185
+ }
186
+ const credentialWithAttachment = credential;
187
+ return {
188
+ id: credential.id,
189
+ rawId: credential.id,
190
+ response: {
191
+ attestationObject: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.attestationObject)),
192
+ clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(credential.response.clientDataJSON)),
193
+ },
194
+ type: 'public-key',
195
+ clientExtensionResults: credential.getClientExtensionResults(),
196
+ // Convert null to undefined and cast to AuthenticatorAttachment type
197
+ authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined),
198
+ };
199
+ }
200
+ /**
201
+ * Convert an authentication/verification credential response to server format.
202
+ * Serializes binary fields to base64url for JSON transmission.
203
+ * Supports both native WebAuthn Level 3 toJSON and manual fallback.
204
+ *
205
+ * @param {AuthenticationCredential} credential - Credential from navigator.credentials.get()
206
+ * @returns {AuthenticationResponseJSON} JSON-serializable credential for server
207
+ * @see {@link https://w3c.github.io/webauthn/#dom-publickeycredential-tojson W3C WebAuthn Spec - toJSON}
208
+ */
209
+ function serializeCredentialRequestResponse(credential) {
210
+ var _a;
211
+ // Check if the credential instance has the toJSON method
212
+ if ('toJSON' in credential && typeof credential.toJSON === 'function') {
213
+ // Use the native WebAuthn Level 3 method
214
+ return credential.toJSON();
215
+ }
216
+ // Fallback to manual conversion for browsers that don't support toJSON
217
+ // Access authenticatorAttachment via type assertion to handle TypeScript version differences
218
+ // @simplewebauthn/types includes this property but base TypeScript 4.7.4 doesn't
219
+ const credentialWithAttachment = credential;
220
+ const clientExtensionResults = credential.getClientExtensionResults();
221
+ const assertionResponse = credential.response;
222
+ return {
223
+ id: credential.id,
224
+ rawId: credential.id, // W3C spec expects rawId to match id for JSON format
225
+ response: {
226
+ authenticatorData: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.authenticatorData)),
227
+ clientDataJSON: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.clientDataJSON)),
228
+ signature: (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.signature)),
229
+ userHandle: assertionResponse.userHandle
230
+ ? (0, base64url_1.bytesToBase64URL)(new Uint8Array(assertionResponse.userHandle))
231
+ : undefined,
232
+ },
233
+ type: 'public-key',
234
+ clientExtensionResults,
235
+ // Convert null to undefined and cast to AuthenticatorAttachment type
236
+ authenticatorAttachment: ((_a = credentialWithAttachment.authenticatorAttachment) !== null && _a !== void 0 ? _a : undefined),
237
+ };
238
+ }
239
+ /**
240
+ * A simple test to determine if a hostname is a properly-formatted domain name.
241
+ * Considers localhost valid for development environments.
242
+ *
243
+ * A "valid domain" is defined here: https://url.spec.whatwg.org/#valid-domain
244
+ *
245
+ * Regex sourced from here:
246
+ * https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html
247
+ *
248
+ * @param {string} hostname - The hostname to validate
249
+ * @returns {boolean} True if valid domain or localhost
250
+ * @see {@link https://url.spec.whatwg.org/#valid-domain WHATWG URL Spec - Valid Domain}
251
+ */
252
+ function isValidDomain(hostname) {
253
+ return (
254
+ // Consider localhost valid as well since it's okay wrt Secure Contexts
255
+ hostname === 'localhost' || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname));
256
+ }
257
+ /**
258
+ * Determine if the browser is capable of WebAuthn.
259
+ * Checks for necessary Web APIs: PublicKeyCredential and Credential Management.
260
+ *
261
+ * @returns {boolean} True if browser supports WebAuthn
262
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredential#browser_compatibility MDN - PublicKeyCredential Browser Compatibility}
263
+ */
264
+ function browserSupportsWebAuthn() {
265
+ var _a, _b;
266
+ return !!((0, helpers_1.isBrowser)() &&
267
+ 'PublicKeyCredential' in window &&
268
+ window.PublicKeyCredential &&
269
+ 'credentials' in navigator &&
270
+ typeof ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _a === void 0 ? void 0 : _a.create) === 'function' &&
271
+ typeof ((_b = navigator === null || navigator === void 0 ? void 0 : navigator.credentials) === null || _b === void 0 ? void 0 : _b.get) === 'function');
272
+ }
273
+ /**
274
+ * Create a WebAuthn credential using the browser's credentials API.
275
+ * Wraps navigator.credentials.create() with error handling.
276
+ *
277
+ * @param {CredentialCreationOptions} options - Options including publicKey parameters
278
+ * @returns {Promise<RequestResult<RegistrationCredential, WebAuthnError>>} Created credential or error
279
+ * @see {@link https://w3c.github.io/webauthn/#sctn-createCredential W3C WebAuthn Spec - Create Credential}
280
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/create MDN - credentials.create}
281
+ */
282
+ async function createCredential(options) {
283
+ try {
284
+ const response = await navigator.credentials.create(
285
+ /** we assert the type here until typescript types are updated */
286
+ options);
287
+ if (!response) {
288
+ return {
289
+ data: null,
290
+ error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response),
291
+ };
292
+ }
293
+ if (!(response instanceof PublicKeyCredential)) {
294
+ return {
295
+ data: null,
296
+ error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response),
297
+ };
298
+ }
299
+ return { data: response, error: null };
300
+ }
301
+ catch (err) {
302
+ return {
303
+ data: null,
304
+ error: (0, webauthn_errors_1.identifyRegistrationError)({
305
+ error: err,
306
+ options,
307
+ }),
308
+ };
309
+ }
310
+ }
311
+ /**
312
+ * Get a WebAuthn credential using the browser's credentials API.
313
+ * Wraps navigator.credentials.get() with error handling.
314
+ *
315
+ * @param {CredentialRequestOptions} options - Options including publicKey parameters
316
+ * @returns {Promise<RequestResult<AuthenticationCredential, WebAuthnError>>} Retrieved credential or error
317
+ * @see {@link https://w3c.github.io/webauthn/#sctn-getAssertion W3C WebAuthn Spec - Get Assertion}
318
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CredentialsContainer/get MDN - credentials.get}
319
+ */
320
+ async function getCredential(options) {
321
+ try {
322
+ const response = await navigator.credentials.get(
323
+ /** we assert the type here until typescript types are updated */
324
+ options);
325
+ if (!response) {
326
+ return {
327
+ data: null,
328
+ error: new webauthn_errors_1.WebAuthnUnknownError('Empty credential response', response),
329
+ };
330
+ }
331
+ if (!(response instanceof PublicKeyCredential)) {
332
+ return {
333
+ data: null,
334
+ error: new webauthn_errors_1.WebAuthnUnknownError('Browser returned unexpected credential type', response),
335
+ };
336
+ }
337
+ return { data: response, error: null };
338
+ }
339
+ catch (err) {
340
+ return {
341
+ data: null,
342
+ error: (0, webauthn_errors_1.identifyAuthenticationError)({
343
+ error: err,
344
+ options,
345
+ }),
346
+ };
347
+ }
348
+ }
349
+ exports.DEFAULT_CREATION_OPTIONS = {
350
+ hints: ['security-key'],
351
+ authenticatorSelection: {
352
+ authenticatorAttachment: 'cross-platform',
353
+ requireResidentKey: false,
354
+ /** set to preferred because older yubikeys don't have PIN/Biometric */
355
+ userVerification: 'preferred',
356
+ residentKey: 'discouraged',
357
+ },
358
+ attestation: 'none',
359
+ };
360
+ exports.DEFAULT_REQUEST_OPTIONS = {
361
+ /** set to preferred because older yubikeys don't have PIN/Biometric */
362
+ userVerification: 'preferred',
363
+ hints: ['security-key'],
364
+ };
365
+ function deepMerge(...sources) {
366
+ const isObject = (val) => val !== null && typeof val === 'object' && !Array.isArray(val);
367
+ const isArrayBufferLike = (val) => val instanceof ArrayBuffer || ArrayBuffer.isView(val);
368
+ const result = {};
369
+ for (const source of sources) {
370
+ if (!source)
371
+ continue;
372
+ for (const key in source) {
373
+ const value = source[key];
374
+ if (value === undefined)
375
+ continue;
376
+ if (Array.isArray(value)) {
377
+ // preserve array reference, including unions like AuthenticatorTransport[]
378
+ result[key] = value;
379
+ }
380
+ else if (isArrayBufferLike(value)) {
381
+ result[key] = value;
382
+ }
383
+ else if (isObject(value)) {
384
+ const existing = result[key];
385
+ if (isObject(existing)) {
386
+ result[key] = deepMerge(existing, value);
387
+ }
388
+ else {
389
+ result[key] = deepMerge(value);
390
+ }
391
+ }
392
+ else {
393
+ result[key] = value;
394
+ }
395
+ }
396
+ }
397
+ return result;
398
+ }
399
+ /**
400
+ * Merges WebAuthn credential creation options with overrides.
401
+ * Sets sensible defaults for authenticator selection and extensions.
402
+ *
403
+ * @param {PublicKeyCredentialCreationOptionsFuture} baseOptions - The base options from the server
404
+ * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Optional overrides to apply
405
+ * @param {string} friendlyName - Optional friendly name for the credential
406
+ * @returns {PublicKeyCredentialCreationOptionsFuture} Merged credential creation options
407
+ * @see {@link https://w3c.github.io/webauthn/#dictdef-authenticatorselectioncriteria W3C WebAuthn Spec - AuthenticatorSelectionCriteria}
408
+ */
409
+ function mergeCredentialCreationOptions(baseOptions, overrides) {
410
+ return deepMerge(exports.DEFAULT_CREATION_OPTIONS, baseOptions, overrides || {});
411
+ }
412
+ /**
413
+ * Merges WebAuthn credential request options with overrides.
414
+ * Sets sensible defaults for user verification and hints.
415
+ *
416
+ * @param {PublicKeyCredentialRequestOptionsFuture} baseOptions - The base options from the server
417
+ * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Optional overrides to apply
418
+ * @returns {PublicKeyCredentialRequestOptionsFuture} Merged credential request options
419
+ * @see {@link https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptions W3C WebAuthn Spec - PublicKeyCredentialRequestOptions}
420
+ */
421
+ function mergeCredentialRequestOptions(baseOptions, overrides) {
422
+ return deepMerge(exports.DEFAULT_REQUEST_OPTIONS, baseOptions, overrides || {});
423
+ }
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