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