@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,3026 @@
1
+ import GoTrueAdminApi from './GoTrueAdminApi';
2
+ import { AUTO_REFRESH_TICK_DURATION_MS, AUTO_REFRESH_TICK_THRESHOLD, DEFAULT_HEADERS, EXPIRY_MARGIN_MS, GOTRUE_URL, JWKS_TTL, STORAGE_KEY, } from './lib/constants';
3
+ import { AuthImplicitGrantRedirectError, AuthInvalidCredentialsError, AuthInvalidJwtError, AuthInvalidTokenResponseError, AuthPKCECodeVerifierMissingError, AuthPKCEGrantCodeExchangeError, AuthSessionMissingError, AuthUnknownError, isAuthApiError, isAuthError, isAuthImplicitGrantRedirectError, isAuthRetryableFetchError, isAuthSessionMissingError, } from './lib/errors';
4
+ import { _request, _sessionResponse, _sessionResponsePassword, _ssoResponse, _userResponse, } from './lib/fetch';
5
+ import { decodeJWT, deepClone, Deferred, generateCallbackId, getAlgorithm, getCodeChallengeAndMethod, getItemAsync, insecureUserWarningProxy, isBrowser, parseParametersFromURL, removeItemAsync, resolveFetch, retryable, setItemAsync, sleep, supportsLocalStorage, userNotAvailableProxy, validateExp, } from './lib/helpers';
6
+ import { memoryLocalStorageAdapter } from './lib/local-storage';
7
+ import { LockAcquireTimeoutError, navigatorLock } from './lib/locks';
8
+ import { polyfillGlobalThis } from './lib/polyfills';
9
+ import { version } from './lib/version';
10
+ import { bytesToBase64URL, stringToUint8Array } from './lib/base64url';
11
+ import { createSiweMessage, fromHex, getAddress, toHex, } from './lib/web3/ethereum';
12
+ import { deserializeCredentialCreationOptions, deserializeCredentialRequestOptions, serializeCredentialCreationResponse, serializeCredentialRequestResponse, WebAuthnApi, } from './lib/webauthn';
13
+ polyfillGlobalThis(); // Make "globalThis" available
14
+ const DEFAULT_OPTIONS = {
15
+ url: GOTRUE_URL,
16
+ storageKey: STORAGE_KEY,
17
+ autoRefreshToken: true,
18
+ persistSession: true,
19
+ detectSessionInUrl: true,
20
+ headers: DEFAULT_HEADERS,
21
+ flowType: 'implicit',
22
+ debug: false,
23
+ hasCustomAuthorizationHeader: false,
24
+ throwOnError: false,
25
+ lockAcquireTimeout: 5000, // 5 seconds
26
+ skipAutoInitialize: false,
27
+ };
28
+ async function lockNoOp(name, acquireTimeout, fn) {
29
+ return await fn();
30
+ }
31
+ /**
32
+ * Caches JWKS values for all clients created in the same environment. This is
33
+ * especially useful for shared-memory execution environments such as Vercel's
34
+ * Fluid Compute, AWS Lambda or Supabase's Edge Functions. Regardless of how
35
+ * many clients are created, if they share the same storage key they will use
36
+ * the same JWKS cache, significantly speeding up getClaims() with asymmetric
37
+ * JWTs.
38
+ */
39
+ const GLOBAL_JWKS = {};
40
+ class GoTrueClient {
41
+ /**
42
+ * The JWKS used for verifying asymmetric JWTs
43
+ */
44
+ get jwks() {
45
+ var _a, _b;
46
+ return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.jwks) !== null && _b !== void 0 ? _b : { keys: [] };
47
+ }
48
+ set jwks(value) {
49
+ GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { jwks: value });
50
+ }
51
+ get jwks_cached_at() {
52
+ var _a, _b;
53
+ return (_b = (_a = GLOBAL_JWKS[this.storageKey]) === null || _a === void 0 ? void 0 : _a.cachedAt) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER;
54
+ }
55
+ set jwks_cached_at(value) {
56
+ GLOBAL_JWKS[this.storageKey] = Object.assign(Object.assign({}, GLOBAL_JWKS[this.storageKey]), { cachedAt: value });
57
+ }
58
+ /**
59
+ * Create a new client for use in the browser.
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * import { GoTrueClient } from '@supabase/auth-js'
64
+ *
65
+ * const auth = new GoTrueClient({
66
+ * url: 'https://xyzcompany.supabase.co/auth/v1',
67
+ * headers: { apikey: 'public-anon-key' },
68
+ * storageKey: 'supabase-auth',
69
+ * })
70
+ * ```
71
+ */
72
+ constructor(options) {
73
+ var _a, _b, _c;
74
+ /**
75
+ * @experimental
76
+ */
77
+ this.userStorage = null;
78
+ this.memoryStorage = null;
79
+ this.stateChangeEmitters = new Map();
80
+ this.autoRefreshTicker = null;
81
+ this.autoRefreshTickTimeout = null;
82
+ this.visibilityChangedCallback = null;
83
+ this.refreshingDeferred = null;
84
+ /**
85
+ * Keeps track of the async client initialization.
86
+ * When null or not yet resolved the auth state is `unknown`
87
+ * Once resolved the auth state is known and it's safe to call any further client methods.
88
+ * Keep extra care to never reject or throw uncaught errors
89
+ */
90
+ this.initializePromise = null;
91
+ this.detectSessionInUrl = true;
92
+ this.hasCustomAuthorizationHeader = false;
93
+ this.suppressGetSessionWarning = false;
94
+ this.lockAcquired = false;
95
+ this.pendingInLock = [];
96
+ /**
97
+ * Used to broadcast state change events to other tabs listening.
98
+ */
99
+ this.broadcastChannel = null;
100
+ this.logger = console.log;
101
+ const settings = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
102
+ this.storageKey = settings.storageKey;
103
+ this.instanceID = (_a = GoTrueClient.nextInstanceID[this.storageKey]) !== null && _a !== void 0 ? _a : 0;
104
+ GoTrueClient.nextInstanceID[this.storageKey] = this.instanceID + 1;
105
+ this.logDebugMessages = !!settings.debug;
106
+ if (typeof settings.debug === 'function') {
107
+ this.logger = settings.debug;
108
+ }
109
+ if (this.instanceID > 0 && isBrowser()) {
110
+ const message = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;
111
+ console.warn(message);
112
+ if (this.logDebugMessages) {
113
+ console.trace(message);
114
+ }
115
+ }
116
+ this.persistSession = settings.persistSession;
117
+ this.autoRefreshToken = settings.autoRefreshToken;
118
+ this.admin = new GoTrueAdminApi({
119
+ url: settings.url,
120
+ headers: settings.headers,
121
+ fetch: settings.fetch,
122
+ });
123
+ this.url = settings.url;
124
+ this.headers = settings.headers;
125
+ this.fetch = resolveFetch(settings.fetch);
126
+ this.lock = settings.lock || lockNoOp;
127
+ this.detectSessionInUrl = settings.detectSessionInUrl;
128
+ this.flowType = settings.flowType;
129
+ this.hasCustomAuthorizationHeader = settings.hasCustomAuthorizationHeader;
130
+ this.throwOnError = settings.throwOnError;
131
+ this.lockAcquireTimeout = settings.lockAcquireTimeout;
132
+ if (settings.lock) {
133
+ this.lock = settings.lock;
134
+ }
135
+ else if (this.persistSession && isBrowser() && ((_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.navigator) === null || _b === void 0 ? void 0 : _b.locks)) {
136
+ this.lock = navigatorLock;
137
+ }
138
+ else {
139
+ this.lock = lockNoOp;
140
+ }
141
+ if (!this.jwks) {
142
+ this.jwks = { keys: [] };
143
+ this.jwks_cached_at = Number.MIN_SAFE_INTEGER;
144
+ }
145
+ this.mfa = {
146
+ verify: this._verify.bind(this),
147
+ enroll: this._enroll.bind(this),
148
+ unenroll: this._unenroll.bind(this),
149
+ challenge: this._challenge.bind(this),
150
+ listFactors: this._listFactors.bind(this),
151
+ challengeAndVerify: this._challengeAndVerify.bind(this),
152
+ getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this),
153
+ webauthn: new WebAuthnApi(this),
154
+ };
155
+ this.oauth = {
156
+ getAuthorizationDetails: this._getAuthorizationDetails.bind(this),
157
+ approveAuthorization: this._approveAuthorization.bind(this),
158
+ denyAuthorization: this._denyAuthorization.bind(this),
159
+ listGrants: this._listOAuthGrants.bind(this),
160
+ revokeGrant: this._revokeOAuthGrant.bind(this),
161
+ };
162
+ if (this.persistSession) {
163
+ if (settings.storage) {
164
+ this.storage = settings.storage;
165
+ }
166
+ else {
167
+ if (supportsLocalStorage()) {
168
+ this.storage = globalThis.localStorage;
169
+ }
170
+ else {
171
+ this.memoryStorage = {};
172
+ this.storage = memoryLocalStorageAdapter(this.memoryStorage);
173
+ }
174
+ }
175
+ if (settings.userStorage) {
176
+ this.userStorage = settings.userStorage;
177
+ }
178
+ }
179
+ else {
180
+ this.memoryStorage = {};
181
+ this.storage = memoryLocalStorageAdapter(this.memoryStorage);
182
+ }
183
+ if (isBrowser() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) {
184
+ try {
185
+ this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey);
186
+ }
187
+ catch (e) {
188
+ console.error('Failed to create a new BroadcastChannel, multi-tab state changes will not be available', e);
189
+ }
190
+ (_c = this.broadcastChannel) === null || _c === void 0 ? void 0 : _c.addEventListener('message', async (event) => {
191
+ this._debug('received broadcast notification from other tab or client', event);
192
+ try {
193
+ await this._notifyAllSubscribers(event.data.event, event.data.session, false); // broadcast = false so we don't get an endless loop of messages
194
+ }
195
+ catch (error) {
196
+ this._debug('#broadcastChannel', 'error', error);
197
+ }
198
+ });
199
+ }
200
+ // Only auto-initialize if not explicitly disabled. Skipped in SSR contexts
201
+ // where initialization timing must be controlled. All public methods have
202
+ // lazy initialization, so the client remains fully functional.
203
+ if (!settings.skipAutoInitialize) {
204
+ this.initialize().catch((error) => {
205
+ this._debug('#initialize()', 'error', error);
206
+ });
207
+ }
208
+ }
209
+ /**
210
+ * Returns whether error throwing mode is enabled for this client.
211
+ */
212
+ isThrowOnErrorEnabled() {
213
+ return this.throwOnError;
214
+ }
215
+ /**
216
+ * Centralizes return handling with optional error throwing. When `throwOnError` is enabled
217
+ * and the provided result contains a non-nullish error, the error is thrown instead of
218
+ * being returned. This ensures consistent behavior across all public API methods.
219
+ */
220
+ _returnResult(result) {
221
+ if (this.throwOnError && result && result.error) {
222
+ throw result.error;
223
+ }
224
+ return result;
225
+ }
226
+ _logPrefix() {
227
+ return ('GoTrueClient@' +
228
+ `${this.storageKey}:${this.instanceID} (${version}) ${new Date().toISOString()}`);
229
+ }
230
+ _debug(...args) {
231
+ if (this.logDebugMessages) {
232
+ this.logger(this._logPrefix(), ...args);
233
+ }
234
+ return this;
235
+ }
236
+ /**
237
+ * Initializes the client session either from the url or from storage.
238
+ * This method is automatically called when instantiating the client, but should also be called
239
+ * manually when checking for an error from an auth redirect (oauth, magiclink, password recovery, etc).
240
+ */
241
+ async initialize() {
242
+ if (this.initializePromise) {
243
+ return await this.initializePromise;
244
+ }
245
+ this.initializePromise = (async () => {
246
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
247
+ return await this._initialize();
248
+ });
249
+ })();
250
+ return await this.initializePromise;
251
+ }
252
+ /**
253
+ * IMPORTANT:
254
+ * 1. Never throw in this method, as it is called from the constructor
255
+ * 2. Never return a session from this method as it would be cached over
256
+ * the whole lifetime of the client
257
+ */
258
+ async _initialize() {
259
+ var _a;
260
+ try {
261
+ let params = {};
262
+ let callbackUrlType = 'none';
263
+ if (isBrowser()) {
264
+ params = parseParametersFromURL(window.location.href);
265
+ if (this._isImplicitGrantCallback(params)) {
266
+ callbackUrlType = 'implicit';
267
+ }
268
+ else if (await this._isPKCECallback(params)) {
269
+ callbackUrlType = 'pkce';
270
+ }
271
+ }
272
+ /**
273
+ * Attempt to get the session from the URL only if these conditions are fulfilled
274
+ *
275
+ * Note: If the URL isn't one of the callback url types (implicit or pkce),
276
+ * then there could be an existing session so we don't want to prematurely remove it
277
+ */
278
+ if (isBrowser() && this.detectSessionInUrl && callbackUrlType !== 'none') {
279
+ const { data, error } = await this._getSessionFromURL(params, callbackUrlType);
280
+ if (error) {
281
+ this._debug('#_initialize()', 'error detecting session from URL', error);
282
+ if (isAuthImplicitGrantRedirectError(error)) {
283
+ const errorCode = (_a = error.details) === null || _a === void 0 ? void 0 : _a.code;
284
+ if (errorCode === 'identity_already_exists' ||
285
+ errorCode === 'identity_not_found' ||
286
+ errorCode === 'single_identity_not_deletable') {
287
+ return { error };
288
+ }
289
+ }
290
+ // Don't remove existing session on URL login failure.
291
+ // A failed attempt (e.g. reused magic link) shouldn't invalidate a valid session.
292
+ return { error };
293
+ }
294
+ const { session, redirectType } = data;
295
+ this._debug('#_initialize()', 'detected session in URL', session, 'redirect type', redirectType);
296
+ await this._saveSession(session);
297
+ setTimeout(async () => {
298
+ if (redirectType === 'recovery') {
299
+ await this._notifyAllSubscribers('PASSWORD_RECOVERY', session);
300
+ }
301
+ else {
302
+ await this._notifyAllSubscribers('SIGNED_IN', session);
303
+ }
304
+ }, 0);
305
+ return { error: null };
306
+ }
307
+ // no login attempt via callback url try to recover session from storage
308
+ await this._recoverAndRefresh();
309
+ return { error: null };
310
+ }
311
+ catch (error) {
312
+ if (isAuthError(error)) {
313
+ return this._returnResult({ error });
314
+ }
315
+ return this._returnResult({
316
+ error: new AuthUnknownError('Unexpected error during initialization', error),
317
+ });
318
+ }
319
+ finally {
320
+ await this._handleVisibilityChange();
321
+ this._debug('#_initialize()', 'end');
322
+ }
323
+ }
324
+ /**
325
+ * Creates a new anonymous user.
326
+ *
327
+ * @returns A session where the is_anonymous claim in the access token JWT set to true
328
+ */
329
+ async signInAnonymously(credentials) {
330
+ var _a, _b, _c;
331
+ try {
332
+ const res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
333
+ headers: this.headers,
334
+ body: {
335
+ data: (_b = (_a = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _a === void 0 ? void 0 : _a.data) !== null && _b !== void 0 ? _b : {},
336
+ gotrue_meta_security: { captcha_token: (_c = credentials === null || credentials === void 0 ? void 0 : credentials.options) === null || _c === void 0 ? void 0 : _c.captchaToken },
337
+ },
338
+ xform: _sessionResponse,
339
+ });
340
+ const { data, error } = res;
341
+ if (error || !data) {
342
+ return this._returnResult({ data: { user: null, session: null }, error: error });
343
+ }
344
+ const session = data.session;
345
+ const user = data.user;
346
+ if (data.session) {
347
+ await this._saveSession(data.session);
348
+ await this._notifyAllSubscribers('SIGNED_IN', session);
349
+ }
350
+ return this._returnResult({ data: { user, session }, error: null });
351
+ }
352
+ catch (error) {
353
+ if (isAuthError(error)) {
354
+ return this._returnResult({ data: { user: null, session: null }, error });
355
+ }
356
+ throw error;
357
+ }
358
+ }
359
+ /**
360
+ * Creates a new user.
361
+ *
362
+ * Be aware that if a user account exists in the system you may get back an
363
+ * error message that attempts to hide this information from the user.
364
+ * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled.
365
+ *
366
+ * @returns A logged-in session if the server has "autoconfirm" ON
367
+ * @returns A user if the server has "autoconfirm" OFF
368
+ *
369
+ * @category Auth
370
+ *
371
+ * @remarks
372
+ * - By default, the user needs to verify their email address before logging in. To turn this off, disable **Confirm email** in [your project](/dashboard/project/_/auth/providers).
373
+ * - **Confirm email** determines if users need to confirm their email address after signing up.
374
+ * - If **Confirm email** is enabled, a `user` is returned but `session` is null.
375
+ * - If **Confirm email** is disabled, both a `user` and a `session` are returned.
376
+ * - When the user confirms their email address, they are redirected to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) by default. You can modify your `SITE_URL` or add additional redirect URLs in [your project](/dashboard/project/_/auth/url-configuration).
377
+ * - If signUp() is called for an existing confirmed user:
378
+ * - When both **Confirm email** and **Confirm phone** (even when phone provider is disabled) are enabled in [your project](/dashboard/project/_/auth/providers), an obfuscated/fake user object is returned.
379
+ * - When either **Confirm email** or **Confirm phone** (even when phone provider is disabled) is disabled, the error message, `User already registered` is returned.
380
+ * - To fetch the currently logged-in user, refer to [`getUser()`](/docs/reference/javascript/auth-getuser).
381
+ *
382
+ * @example Sign up with an email and password
383
+ * ```js
384
+ * const { data, error } = await supabase.auth.signUp({
385
+ * email: 'example@email.com',
386
+ * password: 'example-password',
387
+ * })
388
+ * ```
389
+ *
390
+ * @exampleResponse Sign up with an email and password
391
+ * ```json
392
+ * // Some fields may be null if "confirm email" is enabled.
393
+ * {
394
+ * "data": {
395
+ * "user": {
396
+ * "id": "11111111-1111-1111-1111-111111111111",
397
+ * "aud": "authenticated",
398
+ * "role": "authenticated",
399
+ * "email": "example@email.com",
400
+ * "email_confirmed_at": "2024-01-01T00:00:00Z",
401
+ * "phone": "",
402
+ * "last_sign_in_at": "2024-01-01T00:00:00Z",
403
+ * "app_metadata": {
404
+ * "provider": "email",
405
+ * "providers": [
406
+ * "email"
407
+ * ]
408
+ * },
409
+ * "user_metadata": {},
410
+ * "identities": [
411
+ * {
412
+ * "identity_id": "22222222-2222-2222-2222-222222222222",
413
+ * "id": "11111111-1111-1111-1111-111111111111",
414
+ * "user_id": "11111111-1111-1111-1111-111111111111",
415
+ * "identity_data": {
416
+ * "email": "example@email.com",
417
+ * "email_verified": false,
418
+ * "phone_verified": false,
419
+ * "sub": "11111111-1111-1111-1111-111111111111"
420
+ * },
421
+ * "provider": "email",
422
+ * "last_sign_in_at": "2024-01-01T00:00:00Z",
423
+ * "created_at": "2024-01-01T00:00:00Z",
424
+ * "updated_at": "2024-01-01T00:00:00Z",
425
+ * "email": "example@email.com"
426
+ * }
427
+ * ],
428
+ * "created_at": "2024-01-01T00:00:00Z",
429
+ * "updated_at": "2024-01-01T00:00:00Z"
430
+ * },
431
+ * "session": {
432
+ * "access_token": "<ACCESS_TOKEN>",
433
+ * "token_type": "bearer",
434
+ * "expires_in": 3600,
435
+ * "expires_at": 1700000000,
436
+ * "refresh_token": "<REFRESH_TOKEN>",
437
+ * "user": {
438
+ * "id": "11111111-1111-1111-1111-111111111111",
439
+ * "aud": "authenticated",
440
+ * "role": "authenticated",
441
+ * "email": "example@email.com",
442
+ * "email_confirmed_at": "2024-01-01T00:00:00Z",
443
+ * "phone": "",
444
+ * "last_sign_in_at": "2024-01-01T00:00:00Z",
445
+ * "app_metadata": {
446
+ * "provider": "email",
447
+ * "providers": [
448
+ * "email"
449
+ * ]
450
+ * },
451
+ * "user_metadata": {},
452
+ * "identities": [
453
+ * {
454
+ * "identity_id": "22222222-2222-2222-2222-222222222222",
455
+ * "id": "11111111-1111-1111-1111-111111111111",
456
+ * "user_id": "11111111-1111-1111-1111-111111111111",
457
+ * "identity_data": {
458
+ * "email": "example@email.com",
459
+ * "email_verified": false,
460
+ * "phone_verified": false,
461
+ * "sub": "11111111-1111-1111-1111-111111111111"
462
+ * },
463
+ * "provider": "email",
464
+ * "last_sign_in_at": "2024-01-01T00:00:00Z",
465
+ * "created_at": "2024-01-01T00:00:00Z",
466
+ * "updated_at": "2024-01-01T00:00:00Z",
467
+ * "email": "example@email.com"
468
+ * }
469
+ * ],
470
+ * "created_at": "2024-01-01T00:00:00Z",
471
+ * "updated_at": "2024-01-01T00:00:00Z"
472
+ * }
473
+ * }
474
+ * },
475
+ * "error": null
476
+ * }
477
+ * ```
478
+ *
479
+ * @example Sign up with a phone number and password (SMS)
480
+ * ```js
481
+ * const { data, error } = await supabase.auth.signUp({
482
+ * phone: '123456789',
483
+ * password: 'example-password',
484
+ * options: {
485
+ * channel: 'sms'
486
+ * }
487
+ * })
488
+ * ```
489
+ *
490
+ * @exampleDescription Sign up with a phone number and password (whatsapp)
491
+ * The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature.
492
+ *
493
+ * @example Sign up with a phone number and password (whatsapp)
494
+ * ```js
495
+ * const { data, error } = await supabase.auth.signUp({
496
+ * phone: '123456789',
497
+ * password: 'example-password',
498
+ * options: {
499
+ * channel: 'whatsapp'
500
+ * }
501
+ * })
502
+ * ```
503
+ *
504
+ * @example Sign up with additional user metadata
505
+ * ```js
506
+ * const { data, error } = await supabase.auth.signUp(
507
+ * {
508
+ * email: 'example@email.com',
509
+ * password: 'example-password',
510
+ * options: {
511
+ * data: {
512
+ * first_name: 'John',
513
+ * age: 27,
514
+ * }
515
+ * }
516
+ * }
517
+ * )
518
+ * ```
519
+ *
520
+ * @exampleDescription Sign up with a redirect URL
521
+ * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project.
522
+ *
523
+ * @example Sign up with a redirect URL
524
+ * ```js
525
+ * const { data, error } = await supabase.auth.signUp(
526
+ * {
527
+ * email: 'example@email.com',
528
+ * password: 'example-password',
529
+ * options: {
530
+ * emailRedirectTo: 'https://example.com/welcome'
531
+ * }
532
+ * }
533
+ * )
534
+ * ```
535
+ */
536
+ async signUp(credentials) {
537
+ var _a, _b, _c;
538
+ try {
539
+ let res;
540
+ if ('email' in credentials) {
541
+ const { email, password, options } = credentials;
542
+ let codeChallenge = null;
543
+ let codeChallengeMethod = null;
544
+ if (this.flowType === 'pkce') {
545
+ ;
546
+ [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
547
+ }
548
+ res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
549
+ headers: this.headers,
550
+ redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
551
+ body: {
552
+ email,
553
+ password,
554
+ data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {},
555
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
556
+ code_challenge: codeChallenge,
557
+ code_challenge_method: codeChallengeMethod,
558
+ },
559
+ xform: _sessionResponse,
560
+ });
561
+ }
562
+ else if ('phone' in credentials) {
563
+ const { phone, password, options } = credentials;
564
+ res = await _request(this.fetch, 'POST', `${this.url}/signup`, {
565
+ headers: this.headers,
566
+ body: {
567
+ phone,
568
+ password,
569
+ data: (_b = options === null || options === void 0 ? void 0 : options.data) !== null && _b !== void 0 ? _b : {},
570
+ channel: (_c = options === null || options === void 0 ? void 0 : options.channel) !== null && _c !== void 0 ? _c : 'sms',
571
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
572
+ },
573
+ xform: _sessionResponse,
574
+ });
575
+ }
576
+ else {
577
+ throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password');
578
+ }
579
+ const { data, error } = res;
580
+ if (error || !data) {
581
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
582
+ return this._returnResult({ data: { user: null, session: null }, error: error });
583
+ }
584
+ const session = data.session;
585
+ const user = data.user;
586
+ if (data.session) {
587
+ await this._saveSession(data.session);
588
+ await this._notifyAllSubscribers('SIGNED_IN', session);
589
+ }
590
+ return this._returnResult({ data: { user, session }, error: null });
591
+ }
592
+ catch (error) {
593
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
594
+ if (isAuthError(error)) {
595
+ return this._returnResult({ data: { user: null, session: null }, error });
596
+ }
597
+ throw error;
598
+ }
599
+ }
600
+ /**
601
+ * Log in an existing user with an email and password or phone and password.
602
+ *
603
+ * Be aware that you may get back an error message that will not distinguish
604
+ * between the cases where the account does not exist or that the
605
+ * email/phone and password combination is wrong or that the account can only
606
+ * be accessed via social login.
607
+ */
608
+ async signInWithPassword(credentials) {
609
+ try {
610
+ let res;
611
+ if ('email' in credentials) {
612
+ const { email, password, options } = credentials;
613
+ res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
614
+ headers: this.headers,
615
+ body: {
616
+ email,
617
+ password,
618
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
619
+ },
620
+ xform: _sessionResponsePassword,
621
+ });
622
+ }
623
+ else if ('phone' in credentials) {
624
+ const { phone, password, options } = credentials;
625
+ res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=password`, {
626
+ headers: this.headers,
627
+ body: {
628
+ phone,
629
+ password,
630
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
631
+ },
632
+ xform: _sessionResponsePassword,
633
+ });
634
+ }
635
+ else {
636
+ throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a password');
637
+ }
638
+ const { data, error } = res;
639
+ if (error) {
640
+ return this._returnResult({ data: { user: null, session: null }, error });
641
+ }
642
+ else if (!data || !data.session || !data.user) {
643
+ const invalidTokenError = new AuthInvalidTokenResponseError();
644
+ return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError });
645
+ }
646
+ if (data.session) {
647
+ await this._saveSession(data.session);
648
+ await this._notifyAllSubscribers('SIGNED_IN', data.session);
649
+ }
650
+ return this._returnResult({
651
+ data: Object.assign({ user: data.user, session: data.session }, (data.weak_password ? { weakPassword: data.weak_password } : null)),
652
+ error,
653
+ });
654
+ }
655
+ catch (error) {
656
+ if (isAuthError(error)) {
657
+ return this._returnResult({ data: { user: null, session: null }, error });
658
+ }
659
+ throw error;
660
+ }
661
+ }
662
+ /**
663
+ * Log in an existing user via a third-party provider.
664
+ * This method supports the PKCE flow.
665
+ */
666
+ async signInWithOAuth(credentials) {
667
+ var _a, _b, _c, _d;
668
+ return await this._handleProviderSignIn(credentials.provider, {
669
+ redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo,
670
+ scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes,
671
+ queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
672
+ skipBrowserRedirect: (_d = credentials.options) === null || _d === void 0 ? void 0 : _d.skipBrowserRedirect,
673
+ });
674
+ }
675
+ /**
676
+ * Log in an existing user by exchanging an Auth Code issued during the PKCE flow.
677
+ */
678
+ async exchangeCodeForSession(authCode) {
679
+ await this.initializePromise;
680
+ return this._acquireLock(this.lockAcquireTimeout, async () => {
681
+ return this._exchangeCodeForSession(authCode);
682
+ });
683
+ }
684
+ /**
685
+ * Signs in a user by verifying a message signed by the user's private key.
686
+ * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards,
687
+ * both of which derive from the EIP-4361 standard
688
+ * With slight variation on Solana's side.
689
+ * @reference https://eips.ethereum.org/EIPS/eip-4361
690
+ */
691
+ async signInWithWeb3(credentials) {
692
+ const { chain } = credentials;
693
+ switch (chain) {
694
+ case 'ethereum':
695
+ return await this.signInWithEthereum(credentials);
696
+ case 'solana':
697
+ return await this.signInWithSolana(credentials);
698
+ default:
699
+ throw new Error(`@supabase/auth-js: Unsupported chain "${chain}"`);
700
+ }
701
+ }
702
+ async signInWithEthereum(credentials) {
703
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
704
+ // TODO: flatten type
705
+ let message;
706
+ let signature;
707
+ if ('message' in credentials) {
708
+ message = credentials.message;
709
+ signature = credentials.signature;
710
+ }
711
+ else {
712
+ const { chain, wallet, statement, options } = credentials;
713
+ let resolvedWallet;
714
+ if (!isBrowser()) {
715
+ if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) {
716
+ throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.');
717
+ }
718
+ resolvedWallet = wallet;
719
+ }
720
+ else if (typeof wallet === 'object') {
721
+ resolvedWallet = wallet;
722
+ }
723
+ else {
724
+ const windowAny = window;
725
+ if ('ethereum' in windowAny &&
726
+ typeof windowAny.ethereum === 'object' &&
727
+ 'request' in windowAny.ethereum &&
728
+ typeof windowAny.ethereum.request === 'function') {
729
+ resolvedWallet = windowAny.ethereum;
730
+ }
731
+ else {
732
+ throw new Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`);
733
+ }
734
+ }
735
+ const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href);
736
+ const accounts = await resolvedWallet
737
+ .request({
738
+ method: 'eth_requestAccounts',
739
+ })
740
+ .then((accs) => accs)
741
+ .catch(() => {
742
+ throw new Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`);
743
+ });
744
+ if (!accounts || accounts.length === 0) {
745
+ throw new Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`);
746
+ }
747
+ const address = getAddress(accounts[0]);
748
+ let chainId = (_b = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _b === void 0 ? void 0 : _b.chainId;
749
+ if (!chainId) {
750
+ const chainIdHex = await resolvedWallet.request({
751
+ method: 'eth_chainId',
752
+ });
753
+ chainId = fromHex(chainIdHex);
754
+ }
755
+ const siweMessage = {
756
+ domain: url.host,
757
+ address: address,
758
+ statement: statement,
759
+ uri: url.href,
760
+ version: '1',
761
+ chainId: chainId,
762
+ nonce: (_c = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _c === void 0 ? void 0 : _c.nonce,
763
+ issuedAt: (_e = (_d = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _d === void 0 ? void 0 : _d.issuedAt) !== null && _e !== void 0 ? _e : new Date(),
764
+ expirationTime: (_f = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _f === void 0 ? void 0 : _f.expirationTime,
765
+ notBefore: (_g = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _g === void 0 ? void 0 : _g.notBefore,
766
+ requestId: (_h = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _h === void 0 ? void 0 : _h.requestId,
767
+ resources: (_j = options === null || options === void 0 ? void 0 : options.signInWithEthereum) === null || _j === void 0 ? void 0 : _j.resources,
768
+ };
769
+ message = createSiweMessage(siweMessage);
770
+ // Sign message
771
+ signature = (await resolvedWallet.request({
772
+ method: 'personal_sign',
773
+ params: [toHex(message), address],
774
+ }));
775
+ }
776
+ try {
777
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, {
778
+ headers: this.headers,
779
+ body: Object.assign({ chain: 'ethereum', message,
780
+ signature }, (((_k = credentials.options) === null || _k === void 0 ? void 0 : _k.captchaToken)
781
+ ? { gotrue_meta_security: { captcha_token: (_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken } }
782
+ : null)),
783
+ xform: _sessionResponse,
784
+ });
785
+ if (error) {
786
+ throw error;
787
+ }
788
+ if (!data || !data.session || !data.user) {
789
+ const invalidTokenError = new AuthInvalidTokenResponseError();
790
+ return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError });
791
+ }
792
+ if (data.session) {
793
+ await this._saveSession(data.session);
794
+ await this._notifyAllSubscribers('SIGNED_IN', data.session);
795
+ }
796
+ return this._returnResult({ data: Object.assign({}, data), error });
797
+ }
798
+ catch (error) {
799
+ if (isAuthError(error)) {
800
+ return this._returnResult({ data: { user: null, session: null }, error });
801
+ }
802
+ throw error;
803
+ }
804
+ }
805
+ async signInWithSolana(credentials) {
806
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
807
+ let message;
808
+ let signature;
809
+ if ('message' in credentials) {
810
+ message = credentials.message;
811
+ signature = credentials.signature;
812
+ }
813
+ else {
814
+ const { chain, wallet, statement, options } = credentials;
815
+ let resolvedWallet;
816
+ if (!isBrowser()) {
817
+ if (typeof wallet !== 'object' || !(options === null || options === void 0 ? void 0 : options.url)) {
818
+ throw new Error('@supabase/auth-js: Both wallet and url must be specified in non-browser environments.');
819
+ }
820
+ resolvedWallet = wallet;
821
+ }
822
+ else if (typeof wallet === 'object') {
823
+ resolvedWallet = wallet;
824
+ }
825
+ else {
826
+ const windowAny = window;
827
+ if ('solana' in windowAny &&
828
+ typeof windowAny.solana === 'object' &&
829
+ (('signIn' in windowAny.solana && typeof windowAny.solana.signIn === 'function') ||
830
+ ('signMessage' in windowAny.solana &&
831
+ typeof windowAny.solana.signMessage === 'function'))) {
832
+ resolvedWallet = windowAny.solana;
833
+ }
834
+ else {
835
+ throw new Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`);
836
+ }
837
+ }
838
+ const url = new URL((_a = options === null || options === void 0 ? void 0 : options.url) !== null && _a !== void 0 ? _a : window.location.href);
839
+ if ('signIn' in resolvedWallet && resolvedWallet.signIn) {
840
+ const output = await resolvedWallet.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: new Date().toISOString() }, options === null || options === void 0 ? void 0 : options.signInWithSolana), {
841
+ // non-overridable properties
842
+ version: '1', domain: url.host, uri: url.href }), (statement ? { statement } : null)));
843
+ let outputToProcess;
844
+ if (Array.isArray(output) && output[0] && typeof output[0] === 'object') {
845
+ outputToProcess = output[0];
846
+ }
847
+ else if (output &&
848
+ typeof output === 'object' &&
849
+ 'signedMessage' in output &&
850
+ 'signature' in output) {
851
+ outputToProcess = output;
852
+ }
853
+ else {
854
+ throw new Error('@supabase/auth-js: Wallet method signIn() returned unrecognized value');
855
+ }
856
+ if ('signedMessage' in outputToProcess &&
857
+ 'signature' in outputToProcess &&
858
+ (typeof outputToProcess.signedMessage === 'string' ||
859
+ outputToProcess.signedMessage instanceof Uint8Array) &&
860
+ outputToProcess.signature instanceof Uint8Array) {
861
+ message =
862
+ typeof outputToProcess.signedMessage === 'string'
863
+ ? outputToProcess.signedMessage
864
+ : new TextDecoder().decode(outputToProcess.signedMessage);
865
+ signature = outputToProcess.signature;
866
+ }
867
+ else {
868
+ throw new Error('@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields');
869
+ }
870
+ }
871
+ else {
872
+ if (!('signMessage' in resolvedWallet) ||
873
+ typeof resolvedWallet.signMessage !== 'function' ||
874
+ !('publicKey' in resolvedWallet) ||
875
+ typeof resolvedWallet !== 'object' ||
876
+ !resolvedWallet.publicKey ||
877
+ !('toBase58' in resolvedWallet.publicKey) ||
878
+ typeof resolvedWallet.publicKey.toBase58 !== 'function') {
879
+ throw new Error('@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API');
880
+ }
881
+ message = [
882
+ `${url.host} wants you to sign in with your Solana account:`,
883
+ resolvedWallet.publicKey.toBase58(),
884
+ ...(statement ? ['', statement, ''] : ['']),
885
+ 'Version: 1',
886
+ `URI: ${url.href}`,
887
+ `Issued At: ${(_c = (_b = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _b === void 0 ? void 0 : _b.issuedAt) !== null && _c !== void 0 ? _c : new Date().toISOString()}`,
888
+ ...(((_d = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _d === void 0 ? void 0 : _d.notBefore)
889
+ ? [`Not Before: ${options.signInWithSolana.notBefore}`]
890
+ : []),
891
+ ...(((_e = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _e === void 0 ? void 0 : _e.expirationTime)
892
+ ? [`Expiration Time: ${options.signInWithSolana.expirationTime}`]
893
+ : []),
894
+ ...(((_f = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _f === void 0 ? void 0 : _f.chainId)
895
+ ? [`Chain ID: ${options.signInWithSolana.chainId}`]
896
+ : []),
897
+ ...(((_g = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _g === void 0 ? void 0 : _g.nonce) ? [`Nonce: ${options.signInWithSolana.nonce}`] : []),
898
+ ...(((_h = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _h === void 0 ? void 0 : _h.requestId)
899
+ ? [`Request ID: ${options.signInWithSolana.requestId}`]
900
+ : []),
901
+ ...(((_k = (_j = options === null || options === void 0 ? void 0 : options.signInWithSolana) === null || _j === void 0 ? void 0 : _j.resources) === null || _k === void 0 ? void 0 : _k.length)
902
+ ? [
903
+ 'Resources',
904
+ ...options.signInWithSolana.resources.map((resource) => `- ${resource}`),
905
+ ]
906
+ : []),
907
+ ].join('\n');
908
+ const maybeSignature = await resolvedWallet.signMessage(new TextEncoder().encode(message), 'utf8');
909
+ if (!maybeSignature || !(maybeSignature instanceof Uint8Array)) {
910
+ throw new Error('@supabase/auth-js: Wallet signMessage() API returned an recognized value');
911
+ }
912
+ signature = maybeSignature;
913
+ }
914
+ }
915
+ try {
916
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=web3`, {
917
+ headers: this.headers,
918
+ body: Object.assign({ chain: 'solana', message, signature: bytesToBase64URL(signature) }, (((_l = credentials.options) === null || _l === void 0 ? void 0 : _l.captchaToken)
919
+ ? { gotrue_meta_security: { captcha_token: (_m = credentials.options) === null || _m === void 0 ? void 0 : _m.captchaToken } }
920
+ : null)),
921
+ xform: _sessionResponse,
922
+ });
923
+ if (error) {
924
+ throw error;
925
+ }
926
+ if (!data || !data.session || !data.user) {
927
+ const invalidTokenError = new AuthInvalidTokenResponseError();
928
+ return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError });
929
+ }
930
+ if (data.session) {
931
+ await this._saveSession(data.session);
932
+ await this._notifyAllSubscribers('SIGNED_IN', data.session);
933
+ }
934
+ return this._returnResult({ data: Object.assign({}, data), error });
935
+ }
936
+ catch (error) {
937
+ if (isAuthError(error)) {
938
+ return this._returnResult({ data: { user: null, session: null }, error });
939
+ }
940
+ throw error;
941
+ }
942
+ }
943
+ async _exchangeCodeForSession(authCode) {
944
+ const storageItem = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`);
945
+ const [codeVerifier, redirectType] = (storageItem !== null && storageItem !== void 0 ? storageItem : '').split('/');
946
+ try {
947
+ if (!codeVerifier && this.flowType === 'pkce') {
948
+ throw new AuthPKCECodeVerifierMissingError();
949
+ }
950
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=pkce`, {
951
+ headers: this.headers,
952
+ body: {
953
+ auth_code: authCode,
954
+ code_verifier: codeVerifier,
955
+ },
956
+ xform: _sessionResponse,
957
+ });
958
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
959
+ if (error) {
960
+ throw error;
961
+ }
962
+ if (!data || !data.session || !data.user) {
963
+ const invalidTokenError = new AuthInvalidTokenResponseError();
964
+ return this._returnResult({
965
+ data: { user: null, session: null, redirectType: null },
966
+ error: invalidTokenError,
967
+ });
968
+ }
969
+ if (data.session) {
970
+ await this._saveSession(data.session);
971
+ await this._notifyAllSubscribers('SIGNED_IN', data.session);
972
+ }
973
+ return this._returnResult({ data: Object.assign(Object.assign({}, data), { redirectType: redirectType !== null && redirectType !== void 0 ? redirectType : null }), error });
974
+ }
975
+ catch (error) {
976
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
977
+ if (isAuthError(error)) {
978
+ return this._returnResult({
979
+ data: { user: null, session: null, redirectType: null },
980
+ error,
981
+ });
982
+ }
983
+ throw error;
984
+ }
985
+ }
986
+ /**
987
+ * Allows signing in with an OIDC ID token. The authentication provider used
988
+ * should be enabled and configured.
989
+ */
990
+ async signInWithIdToken(credentials) {
991
+ try {
992
+ const { options, provider, token, access_token, nonce } = credentials;
993
+ const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, {
994
+ headers: this.headers,
995
+ body: {
996
+ provider,
997
+ id_token: token,
998
+ access_token,
999
+ nonce,
1000
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
1001
+ },
1002
+ xform: _sessionResponse,
1003
+ });
1004
+ const { data, error } = res;
1005
+ if (error) {
1006
+ return this._returnResult({ data: { user: null, session: null }, error });
1007
+ }
1008
+ else if (!data || !data.session || !data.user) {
1009
+ const invalidTokenError = new AuthInvalidTokenResponseError();
1010
+ return this._returnResult({ data: { user: null, session: null }, error: invalidTokenError });
1011
+ }
1012
+ if (data.session) {
1013
+ await this._saveSession(data.session);
1014
+ await this._notifyAllSubscribers('SIGNED_IN', data.session);
1015
+ }
1016
+ return this._returnResult({ data, error });
1017
+ }
1018
+ catch (error) {
1019
+ if (isAuthError(error)) {
1020
+ return this._returnResult({ data: { user: null, session: null }, error });
1021
+ }
1022
+ throw error;
1023
+ }
1024
+ }
1025
+ /**
1026
+ * Log in a user using magiclink or a one-time password (OTP).
1027
+ *
1028
+ * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent.
1029
+ * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent.
1030
+ * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
1031
+ *
1032
+ * Be aware that you may get back an error message that will not distinguish
1033
+ * between the cases where the account does not exist or, that the account
1034
+ * can only be accessed via social login.
1035
+ *
1036
+ * Do note that you will need to configure a Whatsapp sender on Twilio
1037
+ * if you are using phone sign in with the 'whatsapp' channel. The whatsapp
1038
+ * channel is not supported on other providers
1039
+ * at this time.
1040
+ * This method supports PKCE when an email is passed.
1041
+ */
1042
+ async signInWithOtp(credentials) {
1043
+ var _a, _b, _c, _d, _e;
1044
+ try {
1045
+ if ('email' in credentials) {
1046
+ const { email, options } = credentials;
1047
+ let codeChallenge = null;
1048
+ let codeChallengeMethod = null;
1049
+ if (this.flowType === 'pkce') {
1050
+ ;
1051
+ [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
1052
+ }
1053
+ const { error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {
1054
+ headers: this.headers,
1055
+ body: {
1056
+ email,
1057
+ data: (_a = options === null || options === void 0 ? void 0 : options.data) !== null && _a !== void 0 ? _a : {},
1058
+ create_user: (_b = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _b !== void 0 ? _b : true,
1059
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
1060
+ code_challenge: codeChallenge,
1061
+ code_challenge_method: codeChallengeMethod,
1062
+ },
1063
+ redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
1064
+ });
1065
+ return this._returnResult({ data: { user: null, session: null }, error });
1066
+ }
1067
+ if ('phone' in credentials) {
1068
+ const { phone, options } = credentials;
1069
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/otp`, {
1070
+ headers: this.headers,
1071
+ body: {
1072
+ phone,
1073
+ data: (_c = options === null || options === void 0 ? void 0 : options.data) !== null && _c !== void 0 ? _c : {},
1074
+ create_user: (_d = options === null || options === void 0 ? void 0 : options.shouldCreateUser) !== null && _d !== void 0 ? _d : true,
1075
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
1076
+ channel: (_e = options === null || options === void 0 ? void 0 : options.channel) !== null && _e !== void 0 ? _e : 'sms',
1077
+ },
1078
+ });
1079
+ return this._returnResult({
1080
+ data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id },
1081
+ error,
1082
+ });
1083
+ }
1084
+ throw new AuthInvalidCredentialsError('You must provide either an email or phone number.');
1085
+ }
1086
+ catch (error) {
1087
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
1088
+ if (isAuthError(error)) {
1089
+ return this._returnResult({ data: { user: null, session: null }, error });
1090
+ }
1091
+ throw error;
1092
+ }
1093
+ }
1094
+ /**
1095
+ * Log in a user given a User supplied OTP or TokenHash received through mobile or email.
1096
+ */
1097
+ async verifyOtp(params) {
1098
+ var _a, _b;
1099
+ try {
1100
+ let redirectTo = undefined;
1101
+ let captchaToken = undefined;
1102
+ if ('options' in params) {
1103
+ redirectTo = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo;
1104
+ captchaToken = (_b = params.options) === null || _b === void 0 ? void 0 : _b.captchaToken;
1105
+ }
1106
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/verify`, {
1107
+ headers: this.headers,
1108
+ body: Object.assign(Object.assign({}, params), { gotrue_meta_security: { captcha_token: captchaToken } }),
1109
+ redirectTo,
1110
+ xform: _sessionResponse,
1111
+ });
1112
+ if (error) {
1113
+ throw error;
1114
+ }
1115
+ if (!data) {
1116
+ const tokenVerificationError = new Error('An error occurred on token verification.');
1117
+ throw tokenVerificationError;
1118
+ }
1119
+ const session = data.session;
1120
+ const user = data.user;
1121
+ if (session === null || session === void 0 ? void 0 : session.access_token) {
1122
+ await this._saveSession(session);
1123
+ await this._notifyAllSubscribers(params.type == 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN', session);
1124
+ }
1125
+ return this._returnResult({ data: { user, session }, error: null });
1126
+ }
1127
+ catch (error) {
1128
+ if (isAuthError(error)) {
1129
+ return this._returnResult({ data: { user: null, session: null }, error });
1130
+ }
1131
+ throw error;
1132
+ }
1133
+ }
1134
+ /**
1135
+ * Attempts a single-sign on using an enterprise Identity Provider. A
1136
+ * successful SSO attempt will redirect the current page to the identity
1137
+ * provider authorization page. The redirect URL is implementation and SSO
1138
+ * protocol specific.
1139
+ *
1140
+ * You can use it by providing a SSO domain. Typically you can extract this
1141
+ * domain by asking users for their email address. If this domain is
1142
+ * registered on the Auth instance the redirect will use that organization's
1143
+ * currently active SSO Identity Provider for the login.
1144
+ *
1145
+ * If you have built an organization-specific login page, you can use the
1146
+ * organization's SSO Identity Provider UUID directly instead.
1147
+ */
1148
+ async signInWithSSO(params) {
1149
+ var _a, _b, _c, _d, _e;
1150
+ try {
1151
+ let codeChallenge = null;
1152
+ let codeChallengeMethod = null;
1153
+ if (this.flowType === 'pkce') {
1154
+ ;
1155
+ [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
1156
+ }
1157
+ const result = await _request(this.fetch, 'POST', `${this.url}/sso`, {
1158
+ body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, ('providerId' in params ? { provider_id: params.providerId } : null)), ('domain' in params ? { domain: params.domain } : null)), { redirect_to: (_b = (_a = params.options) === null || _a === void 0 ? void 0 : _a.redirectTo) !== null && _b !== void 0 ? _b : undefined }), (((_c = params === null || params === void 0 ? void 0 : params.options) === null || _c === void 0 ? void 0 : _c.captchaToken)
1159
+ ? { gotrue_meta_security: { captcha_token: params.options.captchaToken } }
1160
+ : null)), { skip_http_redirect: true, code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),
1161
+ headers: this.headers,
1162
+ xform: _ssoResponse,
1163
+ });
1164
+ // Automatically redirect in browser unless skipBrowserRedirect is true
1165
+ if (((_d = result.data) === null || _d === void 0 ? void 0 : _d.url) && isBrowser() && !((_e = params.options) === null || _e === void 0 ? void 0 : _e.skipBrowserRedirect)) {
1166
+ window.location.assign(result.data.url);
1167
+ }
1168
+ return this._returnResult(result);
1169
+ }
1170
+ catch (error) {
1171
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
1172
+ if (isAuthError(error)) {
1173
+ return this._returnResult({ data: null, error });
1174
+ }
1175
+ throw error;
1176
+ }
1177
+ }
1178
+ /**
1179
+ * Sends a reauthentication OTP to the user's email or phone number.
1180
+ * Requires the user to be signed-in.
1181
+ */
1182
+ async reauthenticate() {
1183
+ await this.initializePromise;
1184
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
1185
+ return await this._reauthenticate();
1186
+ });
1187
+ }
1188
+ async _reauthenticate() {
1189
+ try {
1190
+ return await this._useSession(async (result) => {
1191
+ const { data: { session }, error: sessionError, } = result;
1192
+ if (sessionError)
1193
+ throw sessionError;
1194
+ if (!session)
1195
+ throw new AuthSessionMissingError();
1196
+ const { error } = await _request(this.fetch, 'GET', `${this.url}/reauthenticate`, {
1197
+ headers: this.headers,
1198
+ jwt: session.access_token,
1199
+ });
1200
+ return this._returnResult({ data: { user: null, session: null }, error });
1201
+ });
1202
+ }
1203
+ catch (error) {
1204
+ if (isAuthError(error)) {
1205
+ return this._returnResult({ data: { user: null, session: null }, error });
1206
+ }
1207
+ throw error;
1208
+ }
1209
+ }
1210
+ /**
1211
+ * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP.
1212
+ */
1213
+ async resend(credentials) {
1214
+ try {
1215
+ const endpoint = `${this.url}/resend`;
1216
+ if ('email' in credentials) {
1217
+ const { email, type, options } = credentials;
1218
+ const { error } = await _request(this.fetch, 'POST', endpoint, {
1219
+ headers: this.headers,
1220
+ body: {
1221
+ email,
1222
+ type,
1223
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
1224
+ },
1225
+ redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
1226
+ });
1227
+ return this._returnResult({ data: { user: null, session: null }, error });
1228
+ }
1229
+ else if ('phone' in credentials) {
1230
+ const { phone, type, options } = credentials;
1231
+ const { data, error } = await _request(this.fetch, 'POST', endpoint, {
1232
+ headers: this.headers,
1233
+ body: {
1234
+ phone,
1235
+ type,
1236
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
1237
+ },
1238
+ });
1239
+ return this._returnResult({
1240
+ data: { user: null, session: null, messageId: data === null || data === void 0 ? void 0 : data.message_id },
1241
+ error,
1242
+ });
1243
+ }
1244
+ throw new AuthInvalidCredentialsError('You must provide either an email or phone number and a type');
1245
+ }
1246
+ catch (error) {
1247
+ if (isAuthError(error)) {
1248
+ return this._returnResult({ data: { user: null, session: null }, error });
1249
+ }
1250
+ throw error;
1251
+ }
1252
+ }
1253
+ /**
1254
+ * Returns the session, refreshing it if necessary.
1255
+ *
1256
+ * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
1257
+ *
1258
+ * **IMPORTANT:** This method loads values directly from the storage attached
1259
+ * to the client. If that storage is based on request cookies for example,
1260
+ * the values in it may not be authentic and therefore it's strongly advised
1261
+ * against using this method and its results in such circumstances. A warning
1262
+ * will be emitted if this is detected. Use {@link #getUser()} instead.
1263
+ */
1264
+ async getSession() {
1265
+ await this.initializePromise;
1266
+ const result = await this._acquireLock(this.lockAcquireTimeout, async () => {
1267
+ return this._useSession(async (result) => {
1268
+ return result;
1269
+ });
1270
+ });
1271
+ return result;
1272
+ }
1273
+ /**
1274
+ * Acquires a global lock based on the storage key.
1275
+ */
1276
+ async _acquireLock(acquireTimeout, fn) {
1277
+ this._debug('#_acquireLock', 'begin', acquireTimeout);
1278
+ try {
1279
+ if (this.lockAcquired) {
1280
+ const last = this.pendingInLock.length
1281
+ ? this.pendingInLock[this.pendingInLock.length - 1]
1282
+ : Promise.resolve();
1283
+ const result = (async () => {
1284
+ await last;
1285
+ return await fn();
1286
+ })();
1287
+ this.pendingInLock.push((async () => {
1288
+ try {
1289
+ await result;
1290
+ }
1291
+ catch (e) {
1292
+ // we just care if it finished
1293
+ }
1294
+ })());
1295
+ return result;
1296
+ }
1297
+ return await this.lock(`lock:${this.storageKey}`, acquireTimeout, async () => {
1298
+ this._debug('#_acquireLock', 'lock acquired for storage key', this.storageKey);
1299
+ try {
1300
+ this.lockAcquired = true;
1301
+ const result = fn();
1302
+ this.pendingInLock.push((async () => {
1303
+ try {
1304
+ await result;
1305
+ }
1306
+ catch (e) {
1307
+ // we just care if it finished
1308
+ }
1309
+ })());
1310
+ await result;
1311
+ // keep draining the queue until there's nothing to wait on
1312
+ while (this.pendingInLock.length) {
1313
+ const waitOn = [...this.pendingInLock];
1314
+ await Promise.all(waitOn);
1315
+ this.pendingInLock.splice(0, waitOn.length);
1316
+ }
1317
+ return await result;
1318
+ }
1319
+ finally {
1320
+ this._debug('#_acquireLock', 'lock released for storage key', this.storageKey);
1321
+ this.lockAcquired = false;
1322
+ }
1323
+ });
1324
+ }
1325
+ finally {
1326
+ this._debug('#_acquireLock', 'end');
1327
+ }
1328
+ }
1329
+ /**
1330
+ * Use instead of {@link #getSession} inside the library. It is
1331
+ * semantically usually what you want, as getting a session involves some
1332
+ * processing afterwards that requires only one client operating on the
1333
+ * session at once across multiple tabs or processes.
1334
+ */
1335
+ async _useSession(fn) {
1336
+ this._debug('#_useSession', 'begin');
1337
+ try {
1338
+ // the use of __loadSession here is the only correct use of the function!
1339
+ const result = await this.__loadSession();
1340
+ return await fn(result);
1341
+ }
1342
+ finally {
1343
+ this._debug('#_useSession', 'end');
1344
+ }
1345
+ }
1346
+ /**
1347
+ * NEVER USE DIRECTLY!
1348
+ *
1349
+ * Always use {@link #_useSession}.
1350
+ */
1351
+ async __loadSession() {
1352
+ this._debug('#__loadSession()', 'begin');
1353
+ if (!this.lockAcquired) {
1354
+ this._debug('#__loadSession()', 'used outside of an acquired lock!', new Error().stack);
1355
+ }
1356
+ try {
1357
+ let currentSession = null;
1358
+ const maybeSession = await getItemAsync(this.storage, this.storageKey);
1359
+ this._debug('#getSession()', 'session from storage', maybeSession);
1360
+ if (maybeSession !== null) {
1361
+ if (this._isValidSession(maybeSession)) {
1362
+ currentSession = maybeSession;
1363
+ }
1364
+ else {
1365
+ this._debug('#getSession()', 'session from storage is not valid');
1366
+ await this._removeSession();
1367
+ }
1368
+ }
1369
+ if (!currentSession) {
1370
+ return { data: { session: null }, error: null };
1371
+ }
1372
+ // A session is considered expired before the access token _actually_
1373
+ // expires. When the autoRefreshToken option is off (or when the tab is
1374
+ // in the background), very eager users of getSession() -- like
1375
+ // realtime-js -- might send a valid JWT which will expire by the time it
1376
+ // reaches the server.
1377
+ const hasExpired = currentSession.expires_at
1378
+ ? currentSession.expires_at * 1000 - Date.now() < EXPIRY_MARGIN_MS
1379
+ : false;
1380
+ this._debug('#__loadSession()', `session has${hasExpired ? '' : ' not'} expired`, 'expires_at', currentSession.expires_at);
1381
+ if (!hasExpired) {
1382
+ if (this.userStorage) {
1383
+ const maybeUser = (await getItemAsync(this.userStorage, this.storageKey + '-user'));
1384
+ if (maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) {
1385
+ currentSession.user = maybeUser.user;
1386
+ }
1387
+ else {
1388
+ currentSession.user = userNotAvailableProxy();
1389
+ }
1390
+ }
1391
+ // Wrap the user object with a warning proxy on the server
1392
+ // This warns when properties of the user are accessed, not when session.user itself is accessed
1393
+ if (this.storage.isServer &&
1394
+ currentSession.user &&
1395
+ !currentSession.user.__isUserNotAvailableProxy) {
1396
+ const suppressWarningRef = { value: this.suppressGetSessionWarning };
1397
+ currentSession.user = insecureUserWarningProxy(currentSession.user, suppressWarningRef);
1398
+ // Update the client-level suppression flag when the proxy suppresses the warning
1399
+ if (suppressWarningRef.value) {
1400
+ this.suppressGetSessionWarning = true;
1401
+ }
1402
+ }
1403
+ return { data: { session: currentSession }, error: null };
1404
+ }
1405
+ const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token);
1406
+ if (error) {
1407
+ return this._returnResult({ data: { session: null }, error });
1408
+ }
1409
+ return this._returnResult({ data: { session }, error: null });
1410
+ }
1411
+ finally {
1412
+ this._debug('#__loadSession()', 'end');
1413
+ }
1414
+ }
1415
+ /**
1416
+ * Gets the current user details if there is an existing session. This method
1417
+ * performs a network request to the Supabase Auth server, so the returned
1418
+ * value is authentic and can be used to base authorization rules on.
1419
+ *
1420
+ * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used.
1421
+ */
1422
+ async getUser(jwt) {
1423
+ if (jwt) {
1424
+ return await this._getUser(jwt);
1425
+ }
1426
+ await this.initializePromise;
1427
+ const result = await this._acquireLock(this.lockAcquireTimeout, async () => {
1428
+ return await this._getUser();
1429
+ });
1430
+ if (result.data.user) {
1431
+ this.suppressGetSessionWarning = true;
1432
+ }
1433
+ return result;
1434
+ }
1435
+ async _getUser(jwt) {
1436
+ try {
1437
+ if (jwt) {
1438
+ return await _request(this.fetch, 'GET', `${this.url}/user`, {
1439
+ headers: this.headers,
1440
+ jwt: jwt,
1441
+ xform: _userResponse,
1442
+ });
1443
+ }
1444
+ return await this._useSession(async (result) => {
1445
+ var _a, _b, _c;
1446
+ const { data, error } = result;
1447
+ if (error) {
1448
+ throw error;
1449
+ }
1450
+ // returns an error if there is no access_token or custom authorization header
1451
+ if (!((_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) && !this.hasCustomAuthorizationHeader) {
1452
+ return { data: { user: null }, error: new AuthSessionMissingError() };
1453
+ }
1454
+ return await _request(this.fetch, 'GET', `${this.url}/user`, {
1455
+ headers: this.headers,
1456
+ jwt: (_c = (_b = data.session) === null || _b === void 0 ? void 0 : _b.access_token) !== null && _c !== void 0 ? _c : undefined,
1457
+ xform: _userResponse,
1458
+ });
1459
+ });
1460
+ }
1461
+ catch (error) {
1462
+ if (isAuthError(error)) {
1463
+ if (isAuthSessionMissingError(error)) {
1464
+ // JWT contains a `session_id` which does not correspond to an active
1465
+ // session in the database, indicating the user is signed out.
1466
+ await this._removeSession();
1467
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
1468
+ }
1469
+ return this._returnResult({ data: { user: null }, error });
1470
+ }
1471
+ throw error;
1472
+ }
1473
+ }
1474
+ /**
1475
+ * Updates user data for a logged in user.
1476
+ */
1477
+ async updateUser(attributes, options = {}) {
1478
+ await this.initializePromise;
1479
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
1480
+ return await this._updateUser(attributes, options);
1481
+ });
1482
+ }
1483
+ async _updateUser(attributes, options = {}) {
1484
+ try {
1485
+ return await this._useSession(async (result) => {
1486
+ const { data: sessionData, error: sessionError } = result;
1487
+ if (sessionError) {
1488
+ throw sessionError;
1489
+ }
1490
+ if (!sessionData.session) {
1491
+ throw new AuthSessionMissingError();
1492
+ }
1493
+ const session = sessionData.session;
1494
+ let codeChallenge = null;
1495
+ let codeChallengeMethod = null;
1496
+ if (this.flowType === 'pkce' && attributes.email != null) {
1497
+ ;
1498
+ [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
1499
+ }
1500
+ const { data, error: userError } = await _request(this.fetch, 'PUT', `${this.url}/user`, {
1501
+ headers: this.headers,
1502
+ redirectTo: options === null || options === void 0 ? void 0 : options.emailRedirectTo,
1503
+ body: Object.assign(Object.assign({}, attributes), { code_challenge: codeChallenge, code_challenge_method: codeChallengeMethod }),
1504
+ jwt: session.access_token,
1505
+ xform: _userResponse,
1506
+ });
1507
+ if (userError) {
1508
+ throw userError;
1509
+ }
1510
+ session.user = data.user;
1511
+ await this._saveSession(session);
1512
+ await this._notifyAllSubscribers('USER_UPDATED', session);
1513
+ return this._returnResult({ data: { user: session.user }, error: null });
1514
+ });
1515
+ }
1516
+ catch (error) {
1517
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
1518
+ if (isAuthError(error)) {
1519
+ return this._returnResult({ data: { user: null }, error });
1520
+ }
1521
+ throw error;
1522
+ }
1523
+ }
1524
+ /**
1525
+ * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session.
1526
+ * If the refresh token or access token in the current session is invalid, an error will be thrown.
1527
+ * @param currentSession The current session that minimally contains an access token and refresh token.
1528
+ */
1529
+ async setSession(currentSession) {
1530
+ await this.initializePromise;
1531
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
1532
+ return await this._setSession(currentSession);
1533
+ });
1534
+ }
1535
+ async _setSession(currentSession) {
1536
+ try {
1537
+ if (!currentSession.access_token || !currentSession.refresh_token) {
1538
+ throw new AuthSessionMissingError();
1539
+ }
1540
+ const timeNow = Date.now() / 1000;
1541
+ let expiresAt = timeNow;
1542
+ let hasExpired = true;
1543
+ let session = null;
1544
+ const { payload } = decodeJWT(currentSession.access_token);
1545
+ if (payload.exp) {
1546
+ expiresAt = payload.exp;
1547
+ hasExpired = expiresAt <= timeNow;
1548
+ }
1549
+ if (hasExpired) {
1550
+ const { data: refreshedSession, error } = await this._callRefreshToken(currentSession.refresh_token);
1551
+ if (error) {
1552
+ return this._returnResult({ data: { user: null, session: null }, error: error });
1553
+ }
1554
+ if (!refreshedSession) {
1555
+ return { data: { user: null, session: null }, error: null };
1556
+ }
1557
+ session = refreshedSession;
1558
+ }
1559
+ else {
1560
+ const { data, error } = await this._getUser(currentSession.access_token);
1561
+ if (error) {
1562
+ return this._returnResult({ data: { user: null, session: null }, error });
1563
+ }
1564
+ session = {
1565
+ access_token: currentSession.access_token,
1566
+ refresh_token: currentSession.refresh_token,
1567
+ user: data.user,
1568
+ token_type: 'bearer',
1569
+ expires_in: expiresAt - timeNow,
1570
+ expires_at: expiresAt,
1571
+ };
1572
+ await this._saveSession(session);
1573
+ await this._notifyAllSubscribers('SIGNED_IN', session);
1574
+ }
1575
+ return this._returnResult({ data: { user: session.user, session }, error: null });
1576
+ }
1577
+ catch (error) {
1578
+ if (isAuthError(error)) {
1579
+ return this._returnResult({ data: { session: null, user: null }, error });
1580
+ }
1581
+ throw error;
1582
+ }
1583
+ }
1584
+ /**
1585
+ * Returns a new session, regardless of expiry status.
1586
+ * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
1587
+ * If the current session's refresh token is invalid, an error will be thrown.
1588
+ * @param currentSession The current session. If passed in, it must contain a refresh token.
1589
+ */
1590
+ async refreshSession(currentSession) {
1591
+ await this.initializePromise;
1592
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
1593
+ return await this._refreshSession(currentSession);
1594
+ });
1595
+ }
1596
+ async _refreshSession(currentSession) {
1597
+ try {
1598
+ return await this._useSession(async (result) => {
1599
+ var _a;
1600
+ if (!currentSession) {
1601
+ const { data, error } = result;
1602
+ if (error) {
1603
+ throw error;
1604
+ }
1605
+ currentSession = (_a = data.session) !== null && _a !== void 0 ? _a : undefined;
1606
+ }
1607
+ if (!(currentSession === null || currentSession === void 0 ? void 0 : currentSession.refresh_token)) {
1608
+ throw new AuthSessionMissingError();
1609
+ }
1610
+ const { data: session, error } = await this._callRefreshToken(currentSession.refresh_token);
1611
+ if (error) {
1612
+ return this._returnResult({ data: { user: null, session: null }, error: error });
1613
+ }
1614
+ if (!session) {
1615
+ return this._returnResult({ data: { user: null, session: null }, error: null });
1616
+ }
1617
+ return this._returnResult({ data: { user: session.user, session }, error: null });
1618
+ });
1619
+ }
1620
+ catch (error) {
1621
+ if (isAuthError(error)) {
1622
+ return this._returnResult({ data: { user: null, session: null }, error });
1623
+ }
1624
+ throw error;
1625
+ }
1626
+ }
1627
+ /**
1628
+ * Gets the session data from a URL string
1629
+ */
1630
+ async _getSessionFromURL(params, callbackUrlType) {
1631
+ try {
1632
+ if (!isBrowser())
1633
+ throw new AuthImplicitGrantRedirectError('No browser detected.');
1634
+ // If there's an error in the URL, it doesn't matter what flow it is, we just return the error.
1635
+ if (params.error || params.error_description || params.error_code) {
1636
+ // The error class returned implies that the redirect is from an implicit grant flow
1637
+ // but it could also be from a redirect error from a PKCE flow.
1638
+ throw new AuthImplicitGrantRedirectError(params.error_description || 'Error in URL with unspecified error_description', {
1639
+ error: params.error || 'unspecified_error',
1640
+ code: params.error_code || 'unspecified_code',
1641
+ });
1642
+ }
1643
+ // Checks for mismatches between the flowType initialised in the client and the URL parameters
1644
+ switch (callbackUrlType) {
1645
+ case 'implicit':
1646
+ if (this.flowType === 'pkce') {
1647
+ throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.');
1648
+ }
1649
+ break;
1650
+ case 'pkce':
1651
+ if (this.flowType === 'implicit') {
1652
+ throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.');
1653
+ }
1654
+ break;
1655
+ default:
1656
+ // there's no mismatch so we continue
1657
+ }
1658
+ // Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange
1659
+ if (callbackUrlType === 'pkce') {
1660
+ this._debug('#_initialize()', 'begin', 'is PKCE flow', true);
1661
+ if (!params.code)
1662
+ throw new AuthPKCEGrantCodeExchangeError('No code detected.');
1663
+ const { data, error } = await this._exchangeCodeForSession(params.code);
1664
+ if (error)
1665
+ throw error;
1666
+ const url = new URL(window.location.href);
1667
+ url.searchParams.delete('code');
1668
+ window.history.replaceState(window.history.state, '', url.toString());
1669
+ return { data: { session: data.session, redirectType: null }, error: null };
1670
+ }
1671
+ const { provider_token, provider_refresh_token, access_token, refresh_token, expires_in, expires_at, token_type, } = params;
1672
+ if (!access_token || !expires_in || !refresh_token || !token_type) {
1673
+ throw new AuthImplicitGrantRedirectError('No session defined in URL');
1674
+ }
1675
+ const timeNow = Math.round(Date.now() / 1000);
1676
+ const expiresIn = parseInt(expires_in);
1677
+ let expiresAt = timeNow + expiresIn;
1678
+ if (expires_at) {
1679
+ expiresAt = parseInt(expires_at);
1680
+ }
1681
+ const actuallyExpiresIn = expiresAt - timeNow;
1682
+ if (actuallyExpiresIn * 1000 <= AUTO_REFRESH_TICK_DURATION_MS) {
1683
+ console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${actuallyExpiresIn}s, should have been closer to ${expiresIn}s`);
1684
+ }
1685
+ const issuedAt = expiresAt - expiresIn;
1686
+ if (timeNow - issuedAt >= 120) {
1687
+ console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale', issuedAt, expiresAt, timeNow);
1688
+ }
1689
+ else if (timeNow - issuedAt < 0) {
1690
+ console.warn('@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew', issuedAt, expiresAt, timeNow);
1691
+ }
1692
+ const { data, error } = await this._getUser(access_token);
1693
+ if (error)
1694
+ throw error;
1695
+ const session = {
1696
+ provider_token,
1697
+ provider_refresh_token,
1698
+ access_token,
1699
+ expires_in: expiresIn,
1700
+ expires_at: expiresAt,
1701
+ refresh_token,
1702
+ token_type: token_type,
1703
+ user: data.user,
1704
+ };
1705
+ // Remove tokens from URL
1706
+ window.location.hash = '';
1707
+ this._debug('#_getSessionFromURL()', 'clearing window.location.hash');
1708
+ return this._returnResult({ data: { session, redirectType: params.type }, error: null });
1709
+ }
1710
+ catch (error) {
1711
+ if (isAuthError(error)) {
1712
+ return this._returnResult({ data: { session: null, redirectType: null }, error });
1713
+ }
1714
+ throw error;
1715
+ }
1716
+ }
1717
+ /**
1718
+ * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)
1719
+ *
1720
+ * If `detectSessionInUrl` is a function, it will be called with the URL and params to determine
1721
+ * if the URL should be processed as a Supabase auth callback. This allows users to exclude
1722
+ * URLs from other OAuth providers (e.g., Facebook Login) that also return access_token in the fragment.
1723
+ */
1724
+ _isImplicitGrantCallback(params) {
1725
+ if (typeof this.detectSessionInUrl === 'function') {
1726
+ return this.detectSessionInUrl(new URL(window.location.href), params);
1727
+ }
1728
+ return Boolean(params.access_token || params.error_description);
1729
+ }
1730
+ /**
1731
+ * Checks if the current URL and backing storage contain parameters given by a PKCE flow
1732
+ */
1733
+ async _isPKCECallback(params) {
1734
+ const currentStorageContent = await getItemAsync(this.storage, `${this.storageKey}-code-verifier`);
1735
+ return !!(params.code && currentStorageContent);
1736
+ }
1737
+ /**
1738
+ * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event.
1739
+ *
1740
+ * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`.
1741
+ * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.
1742
+ *
1743
+ * If using `others` scope, no `SIGNED_OUT` event is fired!
1744
+ */
1745
+ async signOut(options = { scope: 'global' }) {
1746
+ await this.initializePromise;
1747
+ return await this._acquireLock(this.lockAcquireTimeout, async () => {
1748
+ return await this._signOut(options);
1749
+ });
1750
+ }
1751
+ async _signOut({ scope } = { scope: 'global' }) {
1752
+ return await this._useSession(async (result) => {
1753
+ var _a;
1754
+ const { data, error: sessionError } = result;
1755
+ if (sessionError && !isAuthSessionMissingError(sessionError)) {
1756
+ return this._returnResult({ error: sessionError });
1757
+ }
1758
+ const accessToken = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token;
1759
+ if (accessToken) {
1760
+ const { error } = await this.admin.signOut(accessToken, scope);
1761
+ if (error) {
1762
+ // ignore 404s since user might not exist anymore
1763
+ // ignore 401s since an invalid or expired JWT should sign out the current session
1764
+ if (!((isAuthApiError(error) &&
1765
+ (error.status === 404 || error.status === 401 || error.status === 403)) ||
1766
+ isAuthSessionMissingError(error))) {
1767
+ return this._returnResult({ error });
1768
+ }
1769
+ }
1770
+ }
1771
+ if (scope !== 'others') {
1772
+ await this._removeSession();
1773
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
1774
+ }
1775
+ return this._returnResult({ error: null });
1776
+ });
1777
+ }
1778
+ onAuthStateChange(callback) {
1779
+ const id = generateCallbackId();
1780
+ const subscription = {
1781
+ id,
1782
+ callback,
1783
+ unsubscribe: () => {
1784
+ this._debug('#unsubscribe()', 'state change callback with id removed', id);
1785
+ this.stateChangeEmitters.delete(id);
1786
+ },
1787
+ };
1788
+ this._debug('#onAuthStateChange()', 'registered callback with id', id);
1789
+ this.stateChangeEmitters.set(id, subscription);
1790
+ (async () => {
1791
+ await this.initializePromise;
1792
+ await this._acquireLock(this.lockAcquireTimeout, async () => {
1793
+ this._emitInitialSession(id);
1794
+ });
1795
+ })();
1796
+ return { data: { subscription } };
1797
+ }
1798
+ async _emitInitialSession(id) {
1799
+ return await this._useSession(async (result) => {
1800
+ var _a, _b;
1801
+ try {
1802
+ const { data: { session }, error, } = result;
1803
+ if (error)
1804
+ throw error;
1805
+ await ((_a = this.stateChangeEmitters.get(id)) === null || _a === void 0 ? void 0 : _a.callback('INITIAL_SESSION', session));
1806
+ this._debug('INITIAL_SESSION', 'callback id', id, 'session', session);
1807
+ }
1808
+ catch (err) {
1809
+ await ((_b = this.stateChangeEmitters.get(id)) === null || _b === void 0 ? void 0 : _b.callback('INITIAL_SESSION', null));
1810
+ this._debug('INITIAL_SESSION', 'callback id', id, 'error', err);
1811
+ console.error(err);
1812
+ }
1813
+ });
1814
+ }
1815
+ /**
1816
+ * Sends a password reset request to an email address. This method supports the PKCE flow.
1817
+ *
1818
+ * @param email The email address of the user.
1819
+ * @param options.redirectTo The URL to send the user to after they click the password reset link.
1820
+ * @param options.captchaToken Verification token received when the user completes the captcha on the site.
1821
+ */
1822
+ async resetPasswordForEmail(email, options = {}) {
1823
+ let codeChallenge = null;
1824
+ let codeChallengeMethod = null;
1825
+ if (this.flowType === 'pkce') {
1826
+ ;
1827
+ [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey, true // isPasswordRecovery
1828
+ );
1829
+ }
1830
+ try {
1831
+ return await _request(this.fetch, 'POST', `${this.url}/recover`, {
1832
+ body: {
1833
+ email,
1834
+ code_challenge: codeChallenge,
1835
+ code_challenge_method: codeChallengeMethod,
1836
+ gotrue_meta_security: { captcha_token: options.captchaToken },
1837
+ },
1838
+ headers: this.headers,
1839
+ redirectTo: options.redirectTo,
1840
+ });
1841
+ }
1842
+ catch (error) {
1843
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
1844
+ if (isAuthError(error)) {
1845
+ return this._returnResult({ data: null, error });
1846
+ }
1847
+ throw error;
1848
+ }
1849
+ }
1850
+ /**
1851
+ * Gets all the identities linked to a user.
1852
+ */
1853
+ async getUserIdentities() {
1854
+ var _a;
1855
+ try {
1856
+ const { data, error } = await this.getUser();
1857
+ if (error)
1858
+ throw error;
1859
+ return this._returnResult({ data: { identities: (_a = data.user.identities) !== null && _a !== void 0 ? _a : [] }, error: null });
1860
+ }
1861
+ catch (error) {
1862
+ if (isAuthError(error)) {
1863
+ return this._returnResult({ data: null, error });
1864
+ }
1865
+ throw error;
1866
+ }
1867
+ }
1868
+ async linkIdentity(credentials) {
1869
+ if ('token' in credentials) {
1870
+ return this.linkIdentityIdToken(credentials);
1871
+ }
1872
+ return this.linkIdentityOAuth(credentials);
1873
+ }
1874
+ async linkIdentityOAuth(credentials) {
1875
+ var _a;
1876
+ try {
1877
+ const { data, error } = await this._useSession(async (result) => {
1878
+ var _a, _b, _c, _d, _e;
1879
+ const { data, error } = result;
1880
+ if (error)
1881
+ throw error;
1882
+ const url = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, credentials.provider, {
1883
+ redirectTo: (_a = credentials.options) === null || _a === void 0 ? void 0 : _a.redirectTo,
1884
+ scopes: (_b = credentials.options) === null || _b === void 0 ? void 0 : _b.scopes,
1885
+ queryParams: (_c = credentials.options) === null || _c === void 0 ? void 0 : _c.queryParams,
1886
+ skipBrowserRedirect: true,
1887
+ });
1888
+ return await _request(this.fetch, 'GET', url, {
1889
+ headers: this.headers,
1890
+ jwt: (_e = (_d = data.session) === null || _d === void 0 ? void 0 : _d.access_token) !== null && _e !== void 0 ? _e : undefined,
1891
+ });
1892
+ });
1893
+ if (error)
1894
+ throw error;
1895
+ if (isBrowser() && !((_a = credentials.options) === null || _a === void 0 ? void 0 : _a.skipBrowserRedirect)) {
1896
+ window.location.assign(data === null || data === void 0 ? void 0 : data.url);
1897
+ }
1898
+ return this._returnResult({
1899
+ data: { provider: credentials.provider, url: data === null || data === void 0 ? void 0 : data.url },
1900
+ error: null,
1901
+ });
1902
+ }
1903
+ catch (error) {
1904
+ if (isAuthError(error)) {
1905
+ return this._returnResult({ data: { provider: credentials.provider, url: null }, error });
1906
+ }
1907
+ throw error;
1908
+ }
1909
+ }
1910
+ async linkIdentityIdToken(credentials) {
1911
+ return await this._useSession(async (result) => {
1912
+ var _a;
1913
+ try {
1914
+ const { error: sessionError, data: { session }, } = result;
1915
+ if (sessionError)
1916
+ throw sessionError;
1917
+ const { options, provider, token, access_token, nonce } = credentials;
1918
+ const res = await _request(this.fetch, 'POST', `${this.url}/token?grant_type=id_token`, {
1919
+ headers: this.headers,
1920
+ jwt: (_a = session === null || session === void 0 ? void 0 : session.access_token) !== null && _a !== void 0 ? _a : undefined,
1921
+ body: {
1922
+ provider,
1923
+ id_token: token,
1924
+ access_token,
1925
+ nonce,
1926
+ link_identity: true,
1927
+ gotrue_meta_security: { captcha_token: options === null || options === void 0 ? void 0 : options.captchaToken },
1928
+ },
1929
+ xform: _sessionResponse,
1930
+ });
1931
+ const { data, error } = res;
1932
+ if (error) {
1933
+ return this._returnResult({ data: { user: null, session: null }, error });
1934
+ }
1935
+ else if (!data || !data.session || !data.user) {
1936
+ return this._returnResult({
1937
+ data: { user: null, session: null },
1938
+ error: new AuthInvalidTokenResponseError(),
1939
+ });
1940
+ }
1941
+ if (data.session) {
1942
+ await this._saveSession(data.session);
1943
+ await this._notifyAllSubscribers('USER_UPDATED', data.session);
1944
+ }
1945
+ return this._returnResult({ data, error });
1946
+ }
1947
+ catch (error) {
1948
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
1949
+ if (isAuthError(error)) {
1950
+ return this._returnResult({ data: { user: null, session: null }, error });
1951
+ }
1952
+ throw error;
1953
+ }
1954
+ });
1955
+ }
1956
+ /**
1957
+ * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked.
1958
+ */
1959
+ async unlinkIdentity(identity) {
1960
+ try {
1961
+ return await this._useSession(async (result) => {
1962
+ var _a, _b;
1963
+ const { data, error } = result;
1964
+ if (error) {
1965
+ throw error;
1966
+ }
1967
+ return await _request(this.fetch, 'DELETE', `${this.url}/user/identities/${identity.identity_id}`, {
1968
+ headers: this.headers,
1969
+ jwt: (_b = (_a = data.session) === null || _a === void 0 ? void 0 : _a.access_token) !== null && _b !== void 0 ? _b : undefined,
1970
+ });
1971
+ });
1972
+ }
1973
+ catch (error) {
1974
+ if (isAuthError(error)) {
1975
+ return this._returnResult({ data: null, error });
1976
+ }
1977
+ throw error;
1978
+ }
1979
+ }
1980
+ /**
1981
+ * Generates a new JWT.
1982
+ * @param refreshToken A valid refresh token that was returned on login.
1983
+ */
1984
+ async _refreshAccessToken(refreshToken) {
1985
+ const debugName = `#_refreshAccessToken(${refreshToken.substring(0, 5)}...)`;
1986
+ this._debug(debugName, 'begin');
1987
+ try {
1988
+ const startedAt = Date.now();
1989
+ // will attempt to refresh the token with exponential backoff
1990
+ return await retryable(async (attempt) => {
1991
+ if (attempt > 0) {
1992
+ await sleep(200 * Math.pow(2, attempt - 1)); // 200, 400, 800, ...
1993
+ }
1994
+ this._debug(debugName, 'refreshing attempt', attempt);
1995
+ return await _request(this.fetch, 'POST', `${this.url}/token?grant_type=refresh_token`, {
1996
+ body: { refresh_token: refreshToken },
1997
+ headers: this.headers,
1998
+ xform: _sessionResponse,
1999
+ });
2000
+ }, (attempt, error) => {
2001
+ const nextBackOffInterval = 200 * Math.pow(2, attempt);
2002
+ return (error &&
2003
+ isAuthRetryableFetchError(error) &&
2004
+ // retryable only if the request can be sent before the backoff overflows the tick duration
2005
+ Date.now() + nextBackOffInterval - startedAt < AUTO_REFRESH_TICK_DURATION_MS);
2006
+ });
2007
+ }
2008
+ catch (error) {
2009
+ this._debug(debugName, 'error', error);
2010
+ if (isAuthError(error)) {
2011
+ return this._returnResult({ data: { session: null, user: null }, error });
2012
+ }
2013
+ throw error;
2014
+ }
2015
+ finally {
2016
+ this._debug(debugName, 'end');
2017
+ }
2018
+ }
2019
+ _isValidSession(maybeSession) {
2020
+ const isValidSession = typeof maybeSession === 'object' &&
2021
+ maybeSession !== null &&
2022
+ 'access_token' in maybeSession &&
2023
+ 'refresh_token' in maybeSession &&
2024
+ 'expires_at' in maybeSession;
2025
+ return isValidSession;
2026
+ }
2027
+ async _handleProviderSignIn(provider, options) {
2028
+ const url = await this._getUrlForProvider(`${this.url}/authorize`, provider, {
2029
+ redirectTo: options.redirectTo,
2030
+ scopes: options.scopes,
2031
+ queryParams: options.queryParams,
2032
+ });
2033
+ this._debug('#_handleProviderSignIn()', 'provider', provider, 'options', options, 'url', url);
2034
+ // try to open on the browser
2035
+ if (isBrowser() && !options.skipBrowserRedirect) {
2036
+ window.location.assign(url);
2037
+ }
2038
+ return { data: { provider, url }, error: null };
2039
+ }
2040
+ /**
2041
+ * Recovers the session from LocalStorage and refreshes the token
2042
+ * Note: this method is async to accommodate for AsyncStorage e.g. in React native.
2043
+ */
2044
+ async _recoverAndRefresh() {
2045
+ var _a, _b;
2046
+ const debugName = '#_recoverAndRefresh()';
2047
+ this._debug(debugName, 'begin');
2048
+ try {
2049
+ const currentSession = (await getItemAsync(this.storage, this.storageKey));
2050
+ if (currentSession && this.userStorage) {
2051
+ let maybeUser = (await getItemAsync(this.userStorage, this.storageKey + '-user'));
2052
+ if (!this.storage.isServer && Object.is(this.storage, this.userStorage) && !maybeUser) {
2053
+ // storage and userStorage are the same storage medium, for example
2054
+ // window.localStorage if userStorage does not have the user from
2055
+ // storage stored, store it first thereby migrating the user object
2056
+ // from storage -> userStorage
2057
+ maybeUser = { user: currentSession.user };
2058
+ await setItemAsync(this.userStorage, this.storageKey + '-user', maybeUser);
2059
+ }
2060
+ currentSession.user = (_a = maybeUser === null || maybeUser === void 0 ? void 0 : maybeUser.user) !== null && _a !== void 0 ? _a : userNotAvailableProxy();
2061
+ }
2062
+ else if (currentSession && !currentSession.user) {
2063
+ // user storage is not set, let's check if it was previously enabled so
2064
+ // we bring back the storage as it should be
2065
+ if (!currentSession.user) {
2066
+ // test if userStorage was previously enabled and the storage medium was the same, to move the user back under the same key
2067
+ const separateUser = (await getItemAsync(this.storage, this.storageKey + '-user'));
2068
+ if (separateUser && (separateUser === null || separateUser === void 0 ? void 0 : separateUser.user)) {
2069
+ currentSession.user = separateUser.user;
2070
+ await removeItemAsync(this.storage, this.storageKey + '-user');
2071
+ await setItemAsync(this.storage, this.storageKey, currentSession);
2072
+ }
2073
+ else {
2074
+ currentSession.user = userNotAvailableProxy();
2075
+ }
2076
+ }
2077
+ }
2078
+ this._debug(debugName, 'session from storage', currentSession);
2079
+ if (!this._isValidSession(currentSession)) {
2080
+ this._debug(debugName, 'session is not valid');
2081
+ if (currentSession !== null) {
2082
+ await this._removeSession();
2083
+ }
2084
+ return;
2085
+ }
2086
+ const expiresWithMargin = ((_b = currentSession.expires_at) !== null && _b !== void 0 ? _b : Infinity) * 1000 - Date.now() < EXPIRY_MARGIN_MS;
2087
+ this._debug(debugName, `session has${expiresWithMargin ? '' : ' not'} expired with margin of ${EXPIRY_MARGIN_MS}s`);
2088
+ if (expiresWithMargin) {
2089
+ if (this.autoRefreshToken && currentSession.refresh_token) {
2090
+ const { error } = await this._callRefreshToken(currentSession.refresh_token);
2091
+ if (error) {
2092
+ console.error(error);
2093
+ if (!isAuthRetryableFetchError(error)) {
2094
+ this._debug(debugName, 'refresh failed with a non-retryable error, removing the session', error);
2095
+ await this._removeSession();
2096
+ }
2097
+ }
2098
+ }
2099
+ }
2100
+ else if (currentSession.user &&
2101
+ currentSession.user.__isUserNotAvailableProxy === true) {
2102
+ // If we have a proxy user, try to get the real user data
2103
+ try {
2104
+ const { data, error: userError } = await this._getUser(currentSession.access_token);
2105
+ if (!userError && (data === null || data === void 0 ? void 0 : data.user)) {
2106
+ currentSession.user = data.user;
2107
+ await this._saveSession(currentSession);
2108
+ await this._notifyAllSubscribers('SIGNED_IN', currentSession);
2109
+ }
2110
+ else {
2111
+ this._debug(debugName, 'could not get user data, skipping SIGNED_IN notification');
2112
+ }
2113
+ }
2114
+ catch (getUserError) {
2115
+ console.error('Error getting user data:', getUserError);
2116
+ this._debug(debugName, 'error getting user data, skipping SIGNED_IN notification', getUserError);
2117
+ }
2118
+ }
2119
+ else {
2120
+ // no need to persist currentSession again, as we just loaded it from
2121
+ // local storage; persisting it again may overwrite a value saved by
2122
+ // another client with access to the same local storage
2123
+ await this._notifyAllSubscribers('SIGNED_IN', currentSession);
2124
+ }
2125
+ }
2126
+ catch (err) {
2127
+ this._debug(debugName, 'error', err);
2128
+ console.error(err);
2129
+ return;
2130
+ }
2131
+ finally {
2132
+ this._debug(debugName, 'end');
2133
+ }
2134
+ }
2135
+ async _callRefreshToken(refreshToken) {
2136
+ var _a, _b;
2137
+ if (!refreshToken) {
2138
+ throw new AuthSessionMissingError();
2139
+ }
2140
+ // refreshing is already in progress
2141
+ if (this.refreshingDeferred) {
2142
+ return this.refreshingDeferred.promise;
2143
+ }
2144
+ const debugName = `#_callRefreshToken(${refreshToken.substring(0, 5)}...)`;
2145
+ this._debug(debugName, 'begin');
2146
+ try {
2147
+ this.refreshingDeferred = new Deferred();
2148
+ const { data, error } = await this._refreshAccessToken(refreshToken);
2149
+ if (error)
2150
+ throw error;
2151
+ if (!data.session)
2152
+ throw new AuthSessionMissingError();
2153
+ await this._saveSession(data.session);
2154
+ await this._notifyAllSubscribers('TOKEN_REFRESHED', data.session);
2155
+ const result = { data: data.session, error: null };
2156
+ this.refreshingDeferred.resolve(result);
2157
+ return result;
2158
+ }
2159
+ catch (error) {
2160
+ this._debug(debugName, 'error', error);
2161
+ if (isAuthError(error)) {
2162
+ const result = { data: null, error };
2163
+ if (!isAuthRetryableFetchError(error)) {
2164
+ await this._removeSession();
2165
+ }
2166
+ (_a = this.refreshingDeferred) === null || _a === void 0 ? void 0 : _a.resolve(result);
2167
+ return result;
2168
+ }
2169
+ (_b = this.refreshingDeferred) === null || _b === void 0 ? void 0 : _b.reject(error);
2170
+ throw error;
2171
+ }
2172
+ finally {
2173
+ this.refreshingDeferred = null;
2174
+ this._debug(debugName, 'end');
2175
+ }
2176
+ }
2177
+ async _notifyAllSubscribers(event, session, broadcast = true) {
2178
+ const debugName = `#_notifyAllSubscribers(${event})`;
2179
+ this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`);
2180
+ try {
2181
+ if (this.broadcastChannel && broadcast) {
2182
+ this.broadcastChannel.postMessage({ event, session });
2183
+ }
2184
+ const errors = [];
2185
+ const promises = Array.from(this.stateChangeEmitters.values()).map(async (x) => {
2186
+ try {
2187
+ await x.callback(event, session);
2188
+ }
2189
+ catch (e) {
2190
+ errors.push(e);
2191
+ }
2192
+ });
2193
+ await Promise.all(promises);
2194
+ if (errors.length > 0) {
2195
+ for (let i = 0; i < errors.length; i += 1) {
2196
+ console.error(errors[i]);
2197
+ }
2198
+ throw errors[0];
2199
+ }
2200
+ }
2201
+ finally {
2202
+ this._debug(debugName, 'end');
2203
+ }
2204
+ }
2205
+ /**
2206
+ * set currentSession and currentUser
2207
+ * process to _startAutoRefreshToken if possible
2208
+ */
2209
+ async _saveSession(session) {
2210
+ this._debug('#_saveSession()', session);
2211
+ // _saveSession is always called whenever a new session has been acquired
2212
+ // so we can safely suppress the warning returned by future getSession calls
2213
+ this.suppressGetSessionWarning = true;
2214
+ await removeItemAsync(this.storage, `${this.storageKey}-code-verifier`);
2215
+ // Create a shallow copy to work with, to avoid mutating the original session object if it's used elsewhere
2216
+ const sessionToProcess = Object.assign({}, session);
2217
+ const userIsProxy = sessionToProcess.user && sessionToProcess.user.__isUserNotAvailableProxy === true;
2218
+ if (this.userStorage) {
2219
+ if (!userIsProxy && sessionToProcess.user) {
2220
+ // If it's a real user object, save it to userStorage.
2221
+ await setItemAsync(this.userStorage, this.storageKey + '-user', {
2222
+ user: sessionToProcess.user,
2223
+ });
2224
+ }
2225
+ else if (userIsProxy) {
2226
+ // If it's the proxy, it means user was not found in userStorage.
2227
+ // We should ensure no stale user data for this key exists in userStorage if we were to save null,
2228
+ // or simply not save the proxy. For now, we don't save the proxy here.
2229
+ // If there's a need to clear userStorage if user becomes proxy, that logic would go here.
2230
+ }
2231
+ // Prepare the main session data for primary storage: remove the user property before cloning
2232
+ // This is important because the original session.user might be the proxy
2233
+ const mainSessionData = Object.assign({}, sessionToProcess);
2234
+ delete mainSessionData.user; // Remove user (real or proxy) before cloning for main storage
2235
+ const clonedMainSessionData = deepClone(mainSessionData);
2236
+ await setItemAsync(this.storage, this.storageKey, clonedMainSessionData);
2237
+ }
2238
+ else {
2239
+ // No userStorage is configured.
2240
+ // In this case, session.user should ideally not be a proxy.
2241
+ // If it were, structuredClone would fail. This implies an issue elsewhere if user is a proxy here
2242
+ const clonedSession = deepClone(sessionToProcess); // sessionToProcess still has its original user property
2243
+ await setItemAsync(this.storage, this.storageKey, clonedSession);
2244
+ }
2245
+ }
2246
+ async _removeSession() {
2247
+ this._debug('#_removeSession()');
2248
+ this.suppressGetSessionWarning = false;
2249
+ await removeItemAsync(this.storage, this.storageKey);
2250
+ await removeItemAsync(this.storage, this.storageKey + '-code-verifier');
2251
+ await removeItemAsync(this.storage, this.storageKey + '-user');
2252
+ if (this.userStorage) {
2253
+ await removeItemAsync(this.userStorage, this.storageKey + '-user');
2254
+ }
2255
+ await this._notifyAllSubscribers('SIGNED_OUT', null);
2256
+ }
2257
+ /**
2258
+ * Removes any registered visibilitychange callback.
2259
+ *
2260
+ * {@see #startAutoRefresh}
2261
+ * {@see #stopAutoRefresh}
2262
+ */
2263
+ _removeVisibilityChangedCallback() {
2264
+ this._debug('#_removeVisibilityChangedCallback()');
2265
+ const callback = this.visibilityChangedCallback;
2266
+ this.visibilityChangedCallback = null;
2267
+ try {
2268
+ if (callback && isBrowser() && (window === null || window === void 0 ? void 0 : window.removeEventListener)) {
2269
+ window.removeEventListener('visibilitychange', callback);
2270
+ }
2271
+ }
2272
+ catch (e) {
2273
+ console.error('removing visibilitychange callback failed', e);
2274
+ }
2275
+ }
2276
+ /**
2277
+ * This is the private implementation of {@link #startAutoRefresh}. Use this
2278
+ * within the library.
2279
+ */
2280
+ async _startAutoRefresh() {
2281
+ await this._stopAutoRefresh();
2282
+ this._debug('#_startAutoRefresh()');
2283
+ const ticker = setInterval(() => this._autoRefreshTokenTick(), AUTO_REFRESH_TICK_DURATION_MS);
2284
+ this.autoRefreshTicker = ticker;
2285
+ if (ticker && typeof ticker === 'object' && typeof ticker.unref === 'function') {
2286
+ // ticker is a NodeJS Timeout object that has an `unref` method
2287
+ // https://nodejs.org/api/timers.html#timeoutunref
2288
+ // When auto refresh is used in NodeJS (like for testing) the
2289
+ // `setInterval` is preventing the process from being marked as
2290
+ // finished and tests run endlessly. This can be prevented by calling
2291
+ // `unref()` on the returned object.
2292
+ ticker.unref();
2293
+ // @ts-expect-error TS has no context of Deno
2294
+ }
2295
+ else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') {
2296
+ // similar like for NodeJS, but with the Deno API
2297
+ // https://deno.land/api@latest?unstable&s=Deno.unrefTimer
2298
+ // @ts-expect-error TS has no context of Deno
2299
+ Deno.unrefTimer(ticker);
2300
+ }
2301
+ // run the tick immediately, but in the next pass of the event loop so that
2302
+ // #_initialize can be allowed to complete without recursively waiting on
2303
+ // itself
2304
+ const timeout = setTimeout(async () => {
2305
+ await this.initializePromise;
2306
+ await this._autoRefreshTokenTick();
2307
+ }, 0);
2308
+ this.autoRefreshTickTimeout = timeout;
2309
+ if (timeout && typeof timeout === 'object' && typeof timeout.unref === 'function') {
2310
+ timeout.unref();
2311
+ // @ts-expect-error TS has no context of Deno
2312
+ }
2313
+ else if (typeof Deno !== 'undefined' && typeof Deno.unrefTimer === 'function') {
2314
+ // @ts-expect-error TS has no context of Deno
2315
+ Deno.unrefTimer(timeout);
2316
+ }
2317
+ }
2318
+ /**
2319
+ * This is the private implementation of {@link #stopAutoRefresh}. Use this
2320
+ * within the library.
2321
+ */
2322
+ async _stopAutoRefresh() {
2323
+ this._debug('#_stopAutoRefresh()');
2324
+ const ticker = this.autoRefreshTicker;
2325
+ this.autoRefreshTicker = null;
2326
+ if (ticker) {
2327
+ clearInterval(ticker);
2328
+ }
2329
+ const timeout = this.autoRefreshTickTimeout;
2330
+ this.autoRefreshTickTimeout = null;
2331
+ if (timeout) {
2332
+ clearTimeout(timeout);
2333
+ }
2334
+ }
2335
+ /**
2336
+ * Starts an auto-refresh process in the background. The session is checked
2337
+ * every few seconds. Close to the time of expiration a process is started to
2338
+ * refresh the session. If refreshing fails it will be retried for as long as
2339
+ * necessary.
2340
+ *
2341
+ * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need
2342
+ * to call this function, it will be called for you.
2343
+ *
2344
+ * On browsers the refresh process works only when the tab/window is in the
2345
+ * foreground to conserve resources as well as prevent race conditions and
2346
+ * flooding auth with requests. If you call this method any managed
2347
+ * visibility change callback will be removed and you must manage visibility
2348
+ * changes on your own.
2349
+ *
2350
+ * On non-browser platforms the refresh process works *continuously* in the
2351
+ * background, which may not be desirable. You should hook into your
2352
+ * platform's foreground indication mechanism and call these methods
2353
+ * appropriately to conserve resources.
2354
+ *
2355
+ * {@see #stopAutoRefresh}
2356
+ */
2357
+ async startAutoRefresh() {
2358
+ this._removeVisibilityChangedCallback();
2359
+ await this._startAutoRefresh();
2360
+ }
2361
+ /**
2362
+ * Stops an active auto refresh process running in the background (if any).
2363
+ *
2364
+ * If you call this method any managed visibility change callback will be
2365
+ * removed and you must manage visibility changes on your own.
2366
+ *
2367
+ * See {@link #startAutoRefresh} for more details.
2368
+ */
2369
+ async stopAutoRefresh() {
2370
+ this._removeVisibilityChangedCallback();
2371
+ await this._stopAutoRefresh();
2372
+ }
2373
+ /**
2374
+ * Runs the auto refresh token tick.
2375
+ */
2376
+ async _autoRefreshTokenTick() {
2377
+ this._debug('#_autoRefreshTokenTick()', 'begin');
2378
+ try {
2379
+ await this._acquireLock(0, async () => {
2380
+ try {
2381
+ const now = Date.now();
2382
+ try {
2383
+ return await this._useSession(async (result) => {
2384
+ const { data: { session }, } = result;
2385
+ if (!session || !session.refresh_token || !session.expires_at) {
2386
+ this._debug('#_autoRefreshTokenTick()', 'no session');
2387
+ return;
2388
+ }
2389
+ // session will expire in this many ticks (or has already expired if <= 0)
2390
+ const expiresInTicks = Math.floor((session.expires_at * 1000 - now) / AUTO_REFRESH_TICK_DURATION_MS);
2391
+ this._debug('#_autoRefreshTokenTick()', `access token expires in ${expiresInTicks} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`);
2392
+ if (expiresInTicks <= AUTO_REFRESH_TICK_THRESHOLD) {
2393
+ await this._callRefreshToken(session.refresh_token);
2394
+ }
2395
+ });
2396
+ }
2397
+ catch (e) {
2398
+ console.error('Auto refresh tick failed with error. This is likely a transient error.', e);
2399
+ }
2400
+ }
2401
+ finally {
2402
+ this._debug('#_autoRefreshTokenTick()', 'end');
2403
+ }
2404
+ });
2405
+ }
2406
+ catch (e) {
2407
+ if (e.isAcquireTimeout || e instanceof LockAcquireTimeoutError) {
2408
+ this._debug('auto refresh token tick lock not available');
2409
+ }
2410
+ else {
2411
+ throw e;
2412
+ }
2413
+ }
2414
+ }
2415
+ /**
2416
+ * Registers callbacks on the browser / platform, which in-turn run
2417
+ * algorithms when the browser window/tab are in foreground. On non-browser
2418
+ * platforms it assumes always foreground.
2419
+ */
2420
+ async _handleVisibilityChange() {
2421
+ this._debug('#_handleVisibilityChange()');
2422
+ if (!isBrowser() || !(window === null || window === void 0 ? void 0 : window.addEventListener)) {
2423
+ if (this.autoRefreshToken) {
2424
+ // in non-browser environments the refresh token ticker runs always
2425
+ this.startAutoRefresh();
2426
+ }
2427
+ return false;
2428
+ }
2429
+ try {
2430
+ this.visibilityChangedCallback = async () => {
2431
+ try {
2432
+ await this._onVisibilityChanged(false);
2433
+ }
2434
+ catch (error) {
2435
+ this._debug('#visibilityChangedCallback', 'error', error);
2436
+ }
2437
+ };
2438
+ window === null || window === void 0 ? void 0 : window.addEventListener('visibilitychange', this.visibilityChangedCallback);
2439
+ // now immediately call the visbility changed callback to setup with the
2440
+ // current visbility state
2441
+ await this._onVisibilityChanged(true); // initial call
2442
+ }
2443
+ catch (error) {
2444
+ console.error('_handleVisibilityChange', error);
2445
+ }
2446
+ }
2447
+ /**
2448
+ * Callback registered with `window.addEventListener('visibilitychange')`.
2449
+ */
2450
+ async _onVisibilityChanged(calledFromInitialize) {
2451
+ const methodName = `#_onVisibilityChanged(${calledFromInitialize})`;
2452
+ this._debug(methodName, 'visibilityState', document.visibilityState);
2453
+ if (document.visibilityState === 'visible') {
2454
+ if (this.autoRefreshToken) {
2455
+ // in browser environments the refresh token ticker runs only on focused tabs
2456
+ // which prevents race conditions
2457
+ this._startAutoRefresh();
2458
+ }
2459
+ if (!calledFromInitialize) {
2460
+ // called when the visibility has changed, i.e. the browser
2461
+ // transitioned from hidden -> visible so we need to see if the session
2462
+ // should be recovered immediately... but to do that we need to acquire
2463
+ // the lock first asynchronously
2464
+ await this.initializePromise;
2465
+ await this._acquireLock(this.lockAcquireTimeout, async () => {
2466
+ if (document.visibilityState !== 'visible') {
2467
+ this._debug(methodName, 'acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting');
2468
+ // visibility has changed while waiting for the lock, abort
2469
+ return;
2470
+ }
2471
+ // recover the session
2472
+ await this._recoverAndRefresh();
2473
+ });
2474
+ }
2475
+ }
2476
+ else if (document.visibilityState === 'hidden') {
2477
+ if (this.autoRefreshToken) {
2478
+ this._stopAutoRefresh();
2479
+ }
2480
+ }
2481
+ }
2482
+ /**
2483
+ * Generates the relevant login URL for a third-party provider.
2484
+ * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed.
2485
+ * @param options.scopes A space-separated list of scopes granted to the OAuth application.
2486
+ * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application.
2487
+ */
2488
+ async _getUrlForProvider(url, provider, options) {
2489
+ const urlParams = [`provider=${encodeURIComponent(provider)}`];
2490
+ if (options === null || options === void 0 ? void 0 : options.redirectTo) {
2491
+ urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`);
2492
+ }
2493
+ if (options === null || options === void 0 ? void 0 : options.scopes) {
2494
+ urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`);
2495
+ }
2496
+ if (this.flowType === 'pkce') {
2497
+ const [codeChallenge, codeChallengeMethod] = await getCodeChallengeAndMethod(this.storage, this.storageKey);
2498
+ const flowParams = new URLSearchParams({
2499
+ code_challenge: `${encodeURIComponent(codeChallenge)}`,
2500
+ code_challenge_method: `${encodeURIComponent(codeChallengeMethod)}`,
2501
+ });
2502
+ urlParams.push(flowParams.toString());
2503
+ }
2504
+ if (options === null || options === void 0 ? void 0 : options.queryParams) {
2505
+ const query = new URLSearchParams(options.queryParams);
2506
+ urlParams.push(query.toString());
2507
+ }
2508
+ if (options === null || options === void 0 ? void 0 : options.skipBrowserRedirect) {
2509
+ urlParams.push(`skip_http_redirect=${options.skipBrowserRedirect}`);
2510
+ }
2511
+ return `${url}?${urlParams.join('&')}`;
2512
+ }
2513
+ async _unenroll(params) {
2514
+ try {
2515
+ return await this._useSession(async (result) => {
2516
+ var _a;
2517
+ const { data: sessionData, error: sessionError } = result;
2518
+ if (sessionError) {
2519
+ return this._returnResult({ data: null, error: sessionError });
2520
+ }
2521
+ return await _request(this.fetch, 'DELETE', `${this.url}/factors/${params.factorId}`, {
2522
+ headers: this.headers,
2523
+ jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
2524
+ });
2525
+ });
2526
+ }
2527
+ catch (error) {
2528
+ if (isAuthError(error)) {
2529
+ return this._returnResult({ data: null, error });
2530
+ }
2531
+ throw error;
2532
+ }
2533
+ }
2534
+ async _enroll(params) {
2535
+ try {
2536
+ return await this._useSession(async (result) => {
2537
+ var _a, _b;
2538
+ const { data: sessionData, error: sessionError } = result;
2539
+ if (sessionError) {
2540
+ return this._returnResult({ data: null, error: sessionError });
2541
+ }
2542
+ const body = Object.assign({ friendly_name: params.friendlyName, factor_type: params.factorType }, (params.factorType === 'phone'
2543
+ ? { phone: params.phone }
2544
+ : params.factorType === 'totp'
2545
+ ? { issuer: params.issuer }
2546
+ : {}));
2547
+ const { data, error } = (await _request(this.fetch, 'POST', `${this.url}/factors`, {
2548
+ body,
2549
+ headers: this.headers,
2550
+ jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
2551
+ }));
2552
+ if (error) {
2553
+ return this._returnResult({ data: null, error });
2554
+ }
2555
+ if (params.factorType === 'totp' && data.type === 'totp' && ((_b = data === null || data === void 0 ? void 0 : data.totp) === null || _b === void 0 ? void 0 : _b.qr_code)) {
2556
+ data.totp.qr_code = `data:image/svg+xml;utf-8,${data.totp.qr_code}`;
2557
+ }
2558
+ return this._returnResult({ data, error: null });
2559
+ });
2560
+ }
2561
+ catch (error) {
2562
+ if (isAuthError(error)) {
2563
+ return this._returnResult({ data: null, error });
2564
+ }
2565
+ throw error;
2566
+ }
2567
+ }
2568
+ async _verify(params) {
2569
+ return this._acquireLock(this.lockAcquireTimeout, async () => {
2570
+ try {
2571
+ return await this._useSession(async (result) => {
2572
+ var _a;
2573
+ const { data: sessionData, error: sessionError } = result;
2574
+ if (sessionError) {
2575
+ return this._returnResult({ data: null, error: sessionError });
2576
+ }
2577
+ const body = Object.assign({ challenge_id: params.challengeId }, ('webauthn' in params
2578
+ ? {
2579
+ webauthn: Object.assign(Object.assign({}, params.webauthn), { credential_response: params.webauthn.type === 'create'
2580
+ ? serializeCredentialCreationResponse(params.webauthn.credential_response)
2581
+ : serializeCredentialRequestResponse(params.webauthn.credential_response) }),
2582
+ }
2583
+ : { code: params.code }));
2584
+ const { data, error } = await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/verify`, {
2585
+ body,
2586
+ headers: this.headers,
2587
+ jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
2588
+ });
2589
+ if (error) {
2590
+ return this._returnResult({ data: null, error });
2591
+ }
2592
+ await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1000) + data.expires_in }, data));
2593
+ await this._notifyAllSubscribers('MFA_CHALLENGE_VERIFIED', data);
2594
+ return this._returnResult({ data, error });
2595
+ });
2596
+ }
2597
+ catch (error) {
2598
+ if (isAuthError(error)) {
2599
+ return this._returnResult({ data: null, error });
2600
+ }
2601
+ throw error;
2602
+ }
2603
+ });
2604
+ }
2605
+ async _challenge(params) {
2606
+ return this._acquireLock(this.lockAcquireTimeout, async () => {
2607
+ try {
2608
+ return await this._useSession(async (result) => {
2609
+ var _a;
2610
+ const { data: sessionData, error: sessionError } = result;
2611
+ if (sessionError) {
2612
+ return this._returnResult({ data: null, error: sessionError });
2613
+ }
2614
+ const response = (await _request(this.fetch, 'POST', `${this.url}/factors/${params.factorId}/challenge`, {
2615
+ body: params,
2616
+ headers: this.headers,
2617
+ jwt: (_a = sessionData === null || sessionData === void 0 ? void 0 : sessionData.session) === null || _a === void 0 ? void 0 : _a.access_token,
2618
+ }));
2619
+ if (response.error) {
2620
+ return response;
2621
+ }
2622
+ const { data } = response;
2623
+ if (data.type !== 'webauthn') {
2624
+ return { data, error: null };
2625
+ }
2626
+ switch (data.webauthn.type) {
2627
+ case 'create':
2628
+ return {
2629
+ data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: deserializeCredentialCreationOptions(data.webauthn.credential_options.publicKey) }) }) }),
2630
+ error: null,
2631
+ };
2632
+ case 'request':
2633
+ return {
2634
+ data: Object.assign(Object.assign({}, data), { webauthn: Object.assign(Object.assign({}, data.webauthn), { credential_options: Object.assign(Object.assign({}, data.webauthn.credential_options), { publicKey: deserializeCredentialRequestOptions(data.webauthn.credential_options.publicKey) }) }) }),
2635
+ error: null,
2636
+ };
2637
+ }
2638
+ });
2639
+ }
2640
+ catch (error) {
2641
+ if (isAuthError(error)) {
2642
+ return this._returnResult({ data: null, error });
2643
+ }
2644
+ throw error;
2645
+ }
2646
+ });
2647
+ }
2648
+ /**
2649
+ * {@see GoTrueMFAApi#challengeAndVerify}
2650
+ */
2651
+ async _challengeAndVerify(params) {
2652
+ // both _challenge and _verify independently acquire the lock, so no need
2653
+ // to acquire it here
2654
+ const { data: challengeData, error: challengeError } = await this._challenge({
2655
+ factorId: params.factorId,
2656
+ });
2657
+ if (challengeError) {
2658
+ return this._returnResult({ data: null, error: challengeError });
2659
+ }
2660
+ return await this._verify({
2661
+ factorId: params.factorId,
2662
+ challengeId: challengeData.id,
2663
+ code: params.code,
2664
+ });
2665
+ }
2666
+ /**
2667
+ * {@see GoTrueMFAApi#listFactors}
2668
+ */
2669
+ async _listFactors() {
2670
+ var _a;
2671
+ // use #getUser instead of #_getUser as the former acquires a lock
2672
+ const { data: { user }, error: userError, } = await this.getUser();
2673
+ if (userError) {
2674
+ return { data: null, error: userError };
2675
+ }
2676
+ const data = {
2677
+ all: [],
2678
+ phone: [],
2679
+ totp: [],
2680
+ webauthn: [],
2681
+ };
2682
+ // loop over the factors ONCE
2683
+ for (const factor of (_a = user === null || user === void 0 ? void 0 : user.factors) !== null && _a !== void 0 ? _a : []) {
2684
+ data.all.push(factor);
2685
+ if (factor.status === 'verified') {
2686
+ ;
2687
+ data[factor.factor_type].push(factor);
2688
+ }
2689
+ }
2690
+ return {
2691
+ data,
2692
+ error: null,
2693
+ };
2694
+ }
2695
+ /**
2696
+ * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel}
2697
+ */
2698
+ async _getAuthenticatorAssuranceLevel(jwt) {
2699
+ var _a, _b, _c, _d;
2700
+ if (jwt) {
2701
+ try {
2702
+ const { payload } = decodeJWT(jwt);
2703
+ let currentLevel = null;
2704
+ if (payload.aal) {
2705
+ currentLevel = payload.aal;
2706
+ }
2707
+ let nextLevel = currentLevel;
2708
+ const { data: { user }, error: userError, } = await this.getUser(jwt);
2709
+ if (userError) {
2710
+ return this._returnResult({ data: null, error: userError });
2711
+ }
2712
+ const verifiedFactors = (_b = (_a = user === null || user === void 0 ? void 0 : user.factors) === null || _a === void 0 ? void 0 : _a.filter((factor) => factor.status === 'verified')) !== null && _b !== void 0 ? _b : [];
2713
+ if (verifiedFactors.length > 0) {
2714
+ nextLevel = 'aal2';
2715
+ }
2716
+ const currentAuthenticationMethods = payload.amr || [];
2717
+ return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null };
2718
+ }
2719
+ catch (error) {
2720
+ if (isAuthError(error)) {
2721
+ return this._returnResult({ data: null, error });
2722
+ }
2723
+ throw error;
2724
+ }
2725
+ }
2726
+ const { data: { session }, error: sessionError, } = await this.getSession();
2727
+ if (sessionError) {
2728
+ return this._returnResult({ data: null, error: sessionError });
2729
+ }
2730
+ if (!session) {
2731
+ return {
2732
+ data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] },
2733
+ error: null,
2734
+ };
2735
+ }
2736
+ const { payload } = decodeJWT(session.access_token);
2737
+ let currentLevel = null;
2738
+ if (payload.aal) {
2739
+ currentLevel = payload.aal;
2740
+ }
2741
+ let nextLevel = currentLevel;
2742
+ const verifiedFactors = (_d = (_c = session.user.factors) === null || _c === void 0 ? void 0 : _c.filter((factor) => factor.status === 'verified')) !== null && _d !== void 0 ? _d : [];
2743
+ if (verifiedFactors.length > 0) {
2744
+ nextLevel = 'aal2';
2745
+ }
2746
+ const currentAuthenticationMethods = payload.amr || [];
2747
+ return { data: { currentLevel, nextLevel, currentAuthenticationMethods }, error: null };
2748
+ }
2749
+ /**
2750
+ * Retrieves details about an OAuth authorization request.
2751
+ * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
2752
+ *
2753
+ * Returns authorization details including client info, scopes, and user information.
2754
+ * If the response includes only a redirect_url field, it means consent was already given - the caller
2755
+ * should handle the redirect manually if needed.
2756
+ */
2757
+ async _getAuthorizationDetails(authorizationId) {
2758
+ try {
2759
+ return await this._useSession(async (result) => {
2760
+ const { data: { session }, error: sessionError, } = result;
2761
+ if (sessionError) {
2762
+ return this._returnResult({ data: null, error: sessionError });
2763
+ }
2764
+ if (!session) {
2765
+ return this._returnResult({ data: null, error: new AuthSessionMissingError() });
2766
+ }
2767
+ return await _request(this.fetch, 'GET', `${this.url}/oauth/authorizations/${authorizationId}`, {
2768
+ headers: this.headers,
2769
+ jwt: session.access_token,
2770
+ xform: (data) => ({ data, error: null }),
2771
+ });
2772
+ });
2773
+ }
2774
+ catch (error) {
2775
+ if (isAuthError(error)) {
2776
+ return this._returnResult({ data: null, error });
2777
+ }
2778
+ throw error;
2779
+ }
2780
+ }
2781
+ /**
2782
+ * Approves an OAuth authorization request.
2783
+ * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
2784
+ */
2785
+ async _approveAuthorization(authorizationId, options) {
2786
+ try {
2787
+ return await this._useSession(async (result) => {
2788
+ const { data: { session }, error: sessionError, } = result;
2789
+ if (sessionError) {
2790
+ return this._returnResult({ data: null, error: sessionError });
2791
+ }
2792
+ if (!session) {
2793
+ return this._returnResult({ data: null, error: new AuthSessionMissingError() });
2794
+ }
2795
+ const response = await _request(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, {
2796
+ headers: this.headers,
2797
+ jwt: session.access_token,
2798
+ body: { action: 'approve' },
2799
+ xform: (data) => ({ data, error: null }),
2800
+ });
2801
+ if (response.data && response.data.redirect_url) {
2802
+ // Automatically redirect in browser unless skipBrowserRedirect is true
2803
+ if (isBrowser() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) {
2804
+ window.location.assign(response.data.redirect_url);
2805
+ }
2806
+ }
2807
+ return response;
2808
+ });
2809
+ }
2810
+ catch (error) {
2811
+ if (isAuthError(error)) {
2812
+ return this._returnResult({ data: null, error });
2813
+ }
2814
+ throw error;
2815
+ }
2816
+ }
2817
+ /**
2818
+ * Denies an OAuth authorization request.
2819
+ * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
2820
+ */
2821
+ async _denyAuthorization(authorizationId, options) {
2822
+ try {
2823
+ return await this._useSession(async (result) => {
2824
+ const { data: { session }, error: sessionError, } = result;
2825
+ if (sessionError) {
2826
+ return this._returnResult({ data: null, error: sessionError });
2827
+ }
2828
+ if (!session) {
2829
+ return this._returnResult({ data: null, error: new AuthSessionMissingError() });
2830
+ }
2831
+ const response = await _request(this.fetch, 'POST', `${this.url}/oauth/authorizations/${authorizationId}/consent`, {
2832
+ headers: this.headers,
2833
+ jwt: session.access_token,
2834
+ body: { action: 'deny' },
2835
+ xform: (data) => ({ data, error: null }),
2836
+ });
2837
+ if (response.data && response.data.redirect_url) {
2838
+ // Automatically redirect in browser unless skipBrowserRedirect is true
2839
+ if (isBrowser() && !(options === null || options === void 0 ? void 0 : options.skipBrowserRedirect)) {
2840
+ window.location.assign(response.data.redirect_url);
2841
+ }
2842
+ }
2843
+ return response;
2844
+ });
2845
+ }
2846
+ catch (error) {
2847
+ if (isAuthError(error)) {
2848
+ return this._returnResult({ data: null, error });
2849
+ }
2850
+ throw error;
2851
+ }
2852
+ }
2853
+ /**
2854
+ * Lists all OAuth grants that the authenticated user has authorized.
2855
+ * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
2856
+ */
2857
+ async _listOAuthGrants() {
2858
+ try {
2859
+ return await this._useSession(async (result) => {
2860
+ const { data: { session }, error: sessionError, } = result;
2861
+ if (sessionError) {
2862
+ return this._returnResult({ data: null, error: sessionError });
2863
+ }
2864
+ if (!session) {
2865
+ return this._returnResult({ data: null, error: new AuthSessionMissingError() });
2866
+ }
2867
+ return await _request(this.fetch, 'GET', `${this.url}/user/oauth/grants`, {
2868
+ headers: this.headers,
2869
+ jwt: session.access_token,
2870
+ xform: (data) => ({ data, error: null }),
2871
+ });
2872
+ });
2873
+ }
2874
+ catch (error) {
2875
+ if (isAuthError(error)) {
2876
+ return this._returnResult({ data: null, error });
2877
+ }
2878
+ throw error;
2879
+ }
2880
+ }
2881
+ /**
2882
+ * Revokes a user's OAuth grant for a specific client.
2883
+ * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth.
2884
+ */
2885
+ async _revokeOAuthGrant(options) {
2886
+ try {
2887
+ return await this._useSession(async (result) => {
2888
+ const { data: { session }, error: sessionError, } = result;
2889
+ if (sessionError) {
2890
+ return this._returnResult({ data: null, error: sessionError });
2891
+ }
2892
+ if (!session) {
2893
+ return this._returnResult({ data: null, error: new AuthSessionMissingError() });
2894
+ }
2895
+ await _request(this.fetch, 'DELETE', `${this.url}/user/oauth/grants`, {
2896
+ headers: this.headers,
2897
+ jwt: session.access_token,
2898
+ query: { client_id: options.clientId },
2899
+ noResolveJson: true,
2900
+ });
2901
+ return { data: {}, error: null };
2902
+ });
2903
+ }
2904
+ catch (error) {
2905
+ if (isAuthError(error)) {
2906
+ return this._returnResult({ data: null, error });
2907
+ }
2908
+ throw error;
2909
+ }
2910
+ }
2911
+ async fetchJwk(kid, jwks = { keys: [] }) {
2912
+ // try fetching from the supplied jwks
2913
+ let jwk = jwks.keys.find((key) => key.kid === kid);
2914
+ if (jwk) {
2915
+ return jwk;
2916
+ }
2917
+ const now = Date.now();
2918
+ // try fetching from cache
2919
+ jwk = this.jwks.keys.find((key) => key.kid === kid);
2920
+ // jwk exists and jwks isn't stale
2921
+ if (jwk && this.jwks_cached_at + JWKS_TTL > now) {
2922
+ return jwk;
2923
+ }
2924
+ // jwk isn't cached in memory so we need to fetch it from the well-known endpoint
2925
+ const { data, error } = await _request(this.fetch, 'GET', `${this.url}/.well-known/jwks.json`, {
2926
+ headers: this.headers,
2927
+ });
2928
+ if (error) {
2929
+ throw error;
2930
+ }
2931
+ if (!data.keys || data.keys.length === 0) {
2932
+ return null;
2933
+ }
2934
+ this.jwks = data;
2935
+ this.jwks_cached_at = now;
2936
+ // Find the signing key
2937
+ jwk = data.keys.find((key) => key.kid === kid);
2938
+ if (!jwk) {
2939
+ return null;
2940
+ }
2941
+ return jwk;
2942
+ }
2943
+ /**
2944
+ * Extracts the JWT claims present in the access token by first verifying the
2945
+ * JWT against the server's JSON Web Key Set endpoint
2946
+ * `/.well-known/jwks.json` which is often cached, resulting in significantly
2947
+ * faster responses. Prefer this method over {@link #getUser} which always
2948
+ * sends a request to the Auth server for each JWT.
2949
+ *
2950
+ * If the project is not using an asymmetric JWT signing key (like ECC or
2951
+ * RSA) it always sends a request to the Auth server (similar to {@link
2952
+ * #getUser}) to verify the JWT.
2953
+ *
2954
+ * @param jwt An optional specific JWT you wish to verify, not the one you
2955
+ * can obtain from {@link #getSession}.
2956
+ * @param options Various additional options that allow you to customize the
2957
+ * behavior of this method.
2958
+ */
2959
+ async getClaims(jwt, options = {}) {
2960
+ try {
2961
+ let token = jwt;
2962
+ if (!token) {
2963
+ const { data, error } = await this.getSession();
2964
+ if (error || !data.session) {
2965
+ return this._returnResult({ data: null, error });
2966
+ }
2967
+ token = data.session.access_token;
2968
+ }
2969
+ const { header, payload, signature, raw: { header: rawHeader, payload: rawPayload }, } = decodeJWT(token);
2970
+ if (!(options === null || options === void 0 ? void 0 : options.allowExpired)) {
2971
+ // Reject expired JWTs should only happen if jwt argument was passed
2972
+ validateExp(payload.exp);
2973
+ }
2974
+ const signingKey = !header.alg ||
2975
+ header.alg.startsWith('HS') ||
2976
+ !header.kid ||
2977
+ !('crypto' in globalThis && 'subtle' in globalThis.crypto)
2978
+ ? null
2979
+ : await this.fetchJwk(header.kid, (options === null || options === void 0 ? void 0 : options.keys) ? { keys: options.keys } : options === null || options === void 0 ? void 0 : options.jwks);
2980
+ // If symmetric algorithm or WebCrypto API is unavailable, fallback to getUser()
2981
+ if (!signingKey) {
2982
+ const { error } = await this.getUser(token);
2983
+ if (error) {
2984
+ throw error;
2985
+ }
2986
+ // getUser succeeds so the claims in the JWT can be trusted
2987
+ return {
2988
+ data: {
2989
+ claims: payload,
2990
+ header,
2991
+ signature,
2992
+ },
2993
+ error: null,
2994
+ };
2995
+ }
2996
+ const algorithm = getAlgorithm(header.alg);
2997
+ // Convert JWK to CryptoKey
2998
+ const publicKey = await crypto.subtle.importKey('jwk', signingKey, algorithm, true, [
2999
+ 'verify',
3000
+ ]);
3001
+ // Verify the signature
3002
+ const isValid = await crypto.subtle.verify(algorithm, publicKey, signature, stringToUint8Array(`${rawHeader}.${rawPayload}`));
3003
+ if (!isValid) {
3004
+ throw new AuthInvalidJwtError('Invalid JWT signature');
3005
+ }
3006
+ // If verification succeeds, decode and return claims
3007
+ return {
3008
+ data: {
3009
+ claims: payload,
3010
+ header,
3011
+ signature,
3012
+ },
3013
+ error: null,
3014
+ };
3015
+ }
3016
+ catch (error) {
3017
+ if (isAuthError(error)) {
3018
+ return this._returnResult({ data: null, error });
3019
+ }
3020
+ throw error;
3021
+ }
3022
+ }
3023
+ }
3024
+ GoTrueClient.nextInstanceID = {};
3025
+ export default GoTrueClient;
3026
+ //# sourceMappingURL=GoTrueClient.js.map